hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
0b9eefd450416d7fbd226a21f513e742c6e6cf8a
4,466
cpp
C++
tc 160+/CubeRoll.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/CubeRoll.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/CubeRoll.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <string> #include <vector> #include <set> #include <queue> using namespace std; bool done[100001]; int solve(int a, int b, int x, int y) { memset(done, 0, sizeof done); queue<int> Q; Q.push(a); int dist = 0; int sz = 0; done[a] = true; while (!Q.empty()) { if (sz == 0) { ++dist; sz = Q.size(); } a = Q.front(); Q.pop(); --sz; for (int i=1; i<1000; ++i) { int move = i*i; if (a-move>x && !done[a-move]) { if (a-move == b) { return dist; } done[a-move] = true; Q.push(a-move); } if (a+move<y && !done[a+move]) { if (a+move == b) { return dist; } done[a+move] = true; Q.push(a+move); } } } return -1; } int solve(int a, int b) { set<long long> squares; for (long long i=1; i<50001; ++i) { squares.insert(i*i); } int d = abs(a-b); if (squares.count(d)) { return 1; } for (set<long long>::const_iterator it=squares.begin(); it!=squares.end(); ++it) { if (*it<d && squares.count(d-*it)) { return 2; } else if (*it>d && squares.count(*it-d)) { return 2; } } return 3; } class CubeRoll { public: int getMinimumSteps(int a, int b, vector <int> P) { sort(P.begin(), P.end()); if (a < P[0]) { if (b < P[0]) { return solve(a, b); } else { return -1; } } else if (a > P.back()) { if (b > P.back()) { return solve(a, b); } else { return -1; } } else { int p = lower_bound(P.begin(), P.end(), a) - P.begin(); if (P[p-1]<b && b<P[p]) { return solve(a, b, P[p-1], P[p]); } else { return -1; } } } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 5; int Arg1 = 1; int Arr2[] = {3}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = -1; verify_case(0, Arg3, getMinimumSteps(Arg0, Arg1, Arg2)); } void test_case_1() { int Arg0 = 36; int Arg1 = 72; int Arr2[] = {300, 100, 200, 400}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 1; verify_case(1, Arg3, getMinimumSteps(Arg0, Arg1, Arg2)); } void test_case_2() { int Arg0 = 10; int Arg1 = 21; int Arr2[] = {38,45}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; verify_case(2, Arg3, getMinimumSteps(Arg0, Arg1, Arg2)); } void test_case_3() { int Arg0 = 98765; int Arg1 = 4963; int Arr2[] = {10,20,40,30}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; verify_case(3, Arg3, getMinimumSteps(Arg0, Arg1, Arg2)); } void test_case_4() { int Arg0 = 68332; int Arg1 = 825; int Arr2[] = {99726,371,67,89210}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; verify_case(4, Arg3, getMinimumSteps(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CubeRoll ___test; ___test.run_test(-1); } // END CUT HERE
34.890625
309
0.478728
ibudiselic
0ba3c2151d33f9fbad0dfa431a211587439e66c4
1,246
cpp
C++
CSCI 301/Project 8 - Queuing Simulation/implement.cpp
pradhulstha/Prashul-Shrestha-CSCI-2
903ffbe8001577890d2336a6cd706d5a17458f62
[ "Apache-2.0" ]
null
null
null
CSCI 301/Project 8 - Queuing Simulation/implement.cpp
pradhulstha/Prashul-Shrestha-CSCI-2
903ffbe8001577890d2336a6cd706d5a17458f62
[ "Apache-2.0" ]
null
null
null
CSCI 301/Project 8 - Queuing Simulation/implement.cpp
pradhulstha/Prashul-Shrestha-CSCI-2
903ffbe8001577890d2336a6cd706d5a17458f62
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "header.h" using namespace std; void Store_Queue::enqueue(int Time) { Node* temp; temp = new Node; temp -> data = Time; temp -> next = NULL; if(first == NULL) first = temp; if(rear == NULL) rear = temp; ++count; } Store_Queue::Item Store_Queue::dequeue() { Item popped; Node* temp; temp = new Node; popped = first -> data; temp = first; first = first -> next; --count; delete temp; if(first == NULL) rear = NULL; return popped; } int Store_Queue::Shortest_queue(Store_Queue q[], int queuecount) { int short_line = 0; for(int i = 0; i < queuecount; ++i) { if(q[i].length() < q[short_line].length()) { short_line = i; } } return short_line; } ostream& operator << (ostream& out_s, Store_Queue Line) { Store_Queue::Node* cursor; Store_Queue::Item print; for ( cursor = Line.first; cursor != NULL && cursor -> next != NULL ; cursor = cursor -> next) { print = Line.dequeue(); out_s<< print <<" "; Line.enqueue(print); } if(cursor != NULL) { print = Line.dequeue(); out_s << print << " "; Line.enqueue(print); } return out_s; } /*Store_Queue::size_t Store_Queue::next_index(size_t index) { return (i + 1) % CAPACITY; }*/
15.974359
95
0.610754
pradhulstha
0ba43aeceb5658d59f6183f177c35b23db44dd80
2,455
cpp
C++
tests/AllegroFlare/RandomTest.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
25
2015-03-30T02:02:43.000Z
2019-03-04T22:29:12.000Z
tests/AllegroFlare/RandomTest.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
122
2015-04-01T08:15:26.000Z
2019-10-16T20:31:22.000Z
tests/AllegroFlare/RandomTest.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
4
2016-09-02T12:14:09.000Z
2018-11-23T20:38:49.000Z
#include <gtest/gtest.h> #include <AllegroFlare/Random.hpp> TEST(AllegroFlare_RandomTest, gets_the_current_seed) { AllegroFlare::Random number_generator = AllegroFlare::Random(123); ASSERT_EQ(123, number_generator.get_seed()); } TEST(AllegroFlare_RandomTest, sets_the_current_seed) { AllegroFlare::Random number_generator = AllegroFlare::Random(123); number_generator.set_seed(456); ASSERT_EQ(456, number_generator.get_seed()); } TEST(AllegroFlare_RandomTest, only_returns_integers_within_the_bounds_inclusive) { AllegroFlare::Random number_generator = AllegroFlare::Random(123); const int min_random_num = 1; const int max_random_num = 3; for (int i=0; i<1000; i++) { int val = number_generator.get_random_int(min_random_num, max_random_num); ASSERT_TRUE(val <= max_random_num); ASSERT_TRUE(val >= min_random_num); } } TEST(AllegroFlare_RandomTest, only_returns_doubles_within_the_bounds_inclusive) { AllegroFlare::Random number_generator = AllegroFlare::Random(123); const double min_random_num = 1.0; const double max_random_num = 3.0; for (int i=0; i<1000; i++) { double val = number_generator.get_random_double(min_random_num, max_random_num); ASSERT_TRUE(val <= max_random_num); ASSERT_TRUE(val >= min_random_num); } } TEST(AllegroFlare_RandomTest, only_returns_floats_within_the_bounds_inclusive) { AllegroFlare::Random number_generator = AllegroFlare::Random(123); const float min_random_num = 1.0; const float max_random_num = 3.0; for (int i=0; i<1000; i++) { float val = number_generator.get_random_float(min_random_num, max_random_num); ASSERT_TRUE(val <= max_random_num); ASSERT_TRUE(val >= min_random_num); } } TEST(RandomTest, DISABLED_returns_an_expected_sequence_of_random_numbers_given_a_seed) { // TODO, these results are different, depending on platform (MacOS, Win). // It's *possible* the results could be different on different devices of the // same OS, too, (but this has not been tested) AllegroFlare::Random number_generator = AllegroFlare::Random(123456); const int min_random_num = 0; const int max_random_num = 10; std::vector<int> expected_numbers = {1, 10, 2, 1, 8}; for (int i=0; i<expected_numbers.size(); i++) { int val = number_generator.get_random_int(min_random_num, max_random_num); ASSERT_EQ(expected_numbers[i], val); } }
26.684783
86
0.731568
MarkOates
0ba44d8c21d841694a05a6d0ce438d8f6ceff019
1,403
cpp
C++
psx/_dump_/18/_dump_c_src_/diabpsx/psxsrc/pads.cpp
maoa3/scalpel
2e7381b516cded28996d290438acc618d00b2aa7
[ "Unlicense" ]
15
2018-06-28T01:11:25.000Z
2021-09-27T15:57:18.000Z
psx/_dump_/18/_dump_c_src_/diabpsx/psxsrc/pads.cpp
maoa3/scalpel
2e7381b516cded28996d290438acc618d00b2aa7
[ "Unlicense" ]
7
2018-06-29T04:08:23.000Z
2019-10-17T13:57:22.000Z
psx/_dump_/18/_dump_c_src_/diabpsx/psxsrc/pads.cpp
maoa3/scalpel
2e7381b516cded28996d290438acc618d00b2aa7
[ "Unlicense" ]
7
2018-06-28T01:11:34.000Z
2020-05-23T09:21:48.000Z
// C:\diabpsx\PSXSRC\PADS.CPP #include "types.h" // address: 0x8009FBFC // line start: 98 // line end: 105 void PAD_Open__Fv() { } // address: 0x800831AC // line start: 111 // line end: 141 unsigned long ReadPadStream__Fv() { // register: 19 register unsigned char *p0; // register: 18 register unsigned char *p1; // register: 16 register unsigned long rval; } // address: 0x800832C4 // line start: 152 // line end: 203 void PAD_Handler__Fv() { // register: 16 register unsigned long JVal; // register: 3 register unsigned long v; // register: 17 register unsigned char fin; } // address: 0x8008347C // size: 0x6C // line start: 217 // line end: 228 struct CPad *PAD_GetPad__FiUc(int PadNum, unsigned char both) { } // address: 0x80083518 // line start: 240 // line end: 271 void NewVal__4CPadUs(struct CPad *this, unsigned short New) { { // register: 7 register int i; { } } } // address: 0x80083650 // line start: 275 // line end: 307 void BothNewVal__4CPadUsUs(struct CPad *this, unsigned short New, unsigned short New2) { { // register: 7 register int i; { } } } // address: 0x800837AC // line start: 317 // line end: 341 unsigned short Trans__4CPadUs(struct CPad *this, unsigned short PadVal) { // register: 2 register unsigned short RetVal; } // address: 0x800838D0 // line start: 345 // line end: 345 void _GLOBAL__I_Pad0() { }
15.943182
88
0.670706
maoa3
24392ec5778dc52e78bd8d93517094c6e0a92d22
18,609
cc
C++
wrappers/7.0.0/vtkCylinderSourceWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/7.0.0/vtkCylinderSourceWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/7.0.0/vtkCylinderSourceWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkPolyDataAlgorithmWrap.h" #include "vtkCylinderSourceWrap.h" #include "vtkObjectWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkCylinderSourceWrap::ptpl; VtkCylinderSourceWrap::VtkCylinderSourceWrap() { } VtkCylinderSourceWrap::VtkCylinderSourceWrap(vtkSmartPointer<vtkCylinderSource> _native) { native = _native; } VtkCylinderSourceWrap::~VtkCylinderSourceWrap() { } void VtkCylinderSourceWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkCylinderSource").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("CylinderSource").ToLocalChecked(), ConstructorGetter); } void VtkCylinderSourceWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkCylinderSourceWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkPolyDataAlgorithmWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkPolyDataAlgorithmWrap::ptpl)); tpl->SetClassName(Nan::New("VtkCylinderSourceWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "CappingOff", CappingOff); Nan::SetPrototypeMethod(tpl, "cappingOff", CappingOff); Nan::SetPrototypeMethod(tpl, "CappingOn", CappingOn); Nan::SetPrototypeMethod(tpl, "cappingOn", CappingOn); Nan::SetPrototypeMethod(tpl, "GetCapping", GetCapping); Nan::SetPrototypeMethod(tpl, "getCapping", GetCapping); Nan::SetPrototypeMethod(tpl, "GetCenter", GetCenter); Nan::SetPrototypeMethod(tpl, "getCenter", GetCenter); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "GetHeight", GetHeight); Nan::SetPrototypeMethod(tpl, "getHeight", GetHeight); Nan::SetPrototypeMethod(tpl, "GetHeightMaxValue", GetHeightMaxValue); Nan::SetPrototypeMethod(tpl, "getHeightMaxValue", GetHeightMaxValue); Nan::SetPrototypeMethod(tpl, "GetHeightMinValue", GetHeightMinValue); Nan::SetPrototypeMethod(tpl, "getHeightMinValue", GetHeightMinValue); Nan::SetPrototypeMethod(tpl, "GetOutputPointsPrecision", GetOutputPointsPrecision); Nan::SetPrototypeMethod(tpl, "getOutputPointsPrecision", GetOutputPointsPrecision); Nan::SetPrototypeMethod(tpl, "GetRadius", GetRadius); Nan::SetPrototypeMethod(tpl, "getRadius", GetRadius); Nan::SetPrototypeMethod(tpl, "GetRadiusMaxValue", GetRadiusMaxValue); Nan::SetPrototypeMethod(tpl, "getRadiusMaxValue", GetRadiusMaxValue); Nan::SetPrototypeMethod(tpl, "GetRadiusMinValue", GetRadiusMinValue); Nan::SetPrototypeMethod(tpl, "getRadiusMinValue", GetRadiusMinValue); Nan::SetPrototypeMethod(tpl, "GetResolution", GetResolution); Nan::SetPrototypeMethod(tpl, "getResolution", GetResolution); Nan::SetPrototypeMethod(tpl, "GetResolutionMaxValue", GetResolutionMaxValue); Nan::SetPrototypeMethod(tpl, "getResolutionMaxValue", GetResolutionMaxValue); Nan::SetPrototypeMethod(tpl, "GetResolutionMinValue", GetResolutionMinValue); Nan::SetPrototypeMethod(tpl, "getResolutionMinValue", GetResolutionMinValue); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetCapping", SetCapping); Nan::SetPrototypeMethod(tpl, "setCapping", SetCapping); Nan::SetPrototypeMethod(tpl, "SetCenter", SetCenter); Nan::SetPrototypeMethod(tpl, "setCenter", SetCenter); Nan::SetPrototypeMethod(tpl, "SetHeight", SetHeight); Nan::SetPrototypeMethod(tpl, "setHeight", SetHeight); Nan::SetPrototypeMethod(tpl, "SetOutputPointsPrecision", SetOutputPointsPrecision); Nan::SetPrototypeMethod(tpl, "setOutputPointsPrecision", SetOutputPointsPrecision); Nan::SetPrototypeMethod(tpl, "SetRadius", SetRadius); Nan::SetPrototypeMethod(tpl, "setRadius", SetRadius); Nan::SetPrototypeMethod(tpl, "SetResolution", SetResolution); Nan::SetPrototypeMethod(tpl, "setResolution", SetResolution); #ifdef VTK_NODE_PLUS_VTKCYLINDERSOURCEWRAP_INITPTPL VTK_NODE_PLUS_VTKCYLINDERSOURCEWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkCylinderSourceWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkCylinderSource> native = vtkSmartPointer<vtkCylinderSource>::New(); VtkCylinderSourceWrap* obj = new VtkCylinderSourceWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkCylinderSourceWrap::CappingOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->CappingOff(); } void VtkCylinderSourceWrap::CappingOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->CappingOn(); } void VtkCylinderSourceWrap::GetCapping(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCapping(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::GetCenter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); double const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCenter(); Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 3 * sizeof(double)); Local<v8::Float64Array> at = v8::Float64Array::New(ab, 0, 3); memcpy(ab->GetContents().Data(), r, 3 * sizeof(double)); info.GetReturnValue().Set(at); } void VtkCylinderSourceWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkCylinderSourceWrap::GetHeight(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetHeight(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::GetHeightMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetHeightMaxValue(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::GetHeightMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetHeightMinValue(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::GetOutputPointsPrecision(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOutputPointsPrecision(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::GetRadius(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetRadius(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::GetRadiusMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetRadiusMaxValue(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::GetRadiusMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetRadiusMinValue(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::GetResolution(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetResolution(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::GetResolutionMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetResolutionMaxValue(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::GetResolutionMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetResolutionMinValue(); info.GetReturnValue().Set(Nan::New(r)); } void VtkCylinderSourceWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkCylinderSourceWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); vtkCylinderSource * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkCylinderSourceWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkCylinderSourceWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkCylinderSourceWrap *w = new VtkCylinderSourceWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkCylinderSourceWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject()); vtkCylinderSource * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkCylinderSourceWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkCylinderSourceWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkCylinderSourceWrap *w = new VtkCylinderSourceWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkCylinderSourceWrap::SetCapping(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCapping( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkCylinderSourceWrap::SetCenter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCenter( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCenter( b0 ); return; } else if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() > 1 && info[1]->IsNumber()) { if(info.Length() > 2 && info[2]->IsNumber()) { if(info.Length() != 3) { Nan::ThrowError("Too many parameters."); return; } native->SetCenter( info[0]->NumberValue(), info[1]->NumberValue(), info[2]->NumberValue() ); return; } } } Nan::ThrowError("Parameter mismatch"); } void VtkCylinderSourceWrap::SetHeight(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetHeight( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkCylinderSourceWrap::SetOutputPointsPrecision(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetOutputPointsPrecision( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkCylinderSourceWrap::SetRadius(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetRadius( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkCylinderSourceWrap::SetResolution(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkCylinderSourceWrap *wrapper = ObjectWrap::Unwrap<VtkCylinderSourceWrap>(info.Holder()); vtkCylinderSource *native = (vtkCylinderSource *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetResolution( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); }
30.506557
102
0.723037
axkibe
243a4125ec0e4aff0607b782bb2619c443a15db1
993
cpp
C++
class/app/juego/rompible.cpp
TheMarlboroMan/winter-fgj5
28cd4bd4ae37230e51c1a9963bcd293e674cdc3c
[ "Beerware" ]
null
null
null
class/app/juego/rompible.cpp
TheMarlboroMan/winter-fgj5
28cd4bd4ae37230e51c1a9963bcd293e674cdc3c
[ "Beerware" ]
null
null
null
class/app/juego/rompible.cpp
TheMarlboroMan/winter-fgj5
28cd4bd4ae37230e51c1a9963bcd293e674cdc3c
[ "Beerware" ]
null
null
null
#include "rompible.h" using namespace App_Juego; Rompible::Rompible(float x, float y) :Actor(x, y, W, H) { } unsigned int Rompible::obtener_ciclos_representable()const { return 1; } unsigned short int Rompible::obtener_profundidad_ordenacion() const { return 30; } void Rompible::transformar_bloque(App_Graficos::Bloque_transformacion_representable &b) const { const auto& a=b.obtener_animacion(App_Definiciones::animaciones::sprites, App_Definiciones::animaciones_sprites::rompible); const auto& f=a.obtener_para_tiempo_animacion(App_Graficos::Animaciones::obtener_tiempo(), a.acc_duracion_total()).frame; b.establecer_tipo(App_Graficos::Bloque_transformacion_representable::tipos::tr_bitmap); b.establecer_alpha(255); b.establecer_recurso(App::Recursos_graficos::rt_sprites); b.establecer_recorte(f.x, f.y, f.w, f.h); b.establecer_posicion(acc_espaciable_x()+f.desp_x, acc_espaciable_y()+f.desp_y, f.w, f.h); } void Rompible::recibir_disparo(int v) { mut_borrar(true); }
26.131579
124
0.784491
TheMarlboroMan
243a74c9cddaf02dcd3bbf7236ab3f142daebafd
31,866
cpp
C++
src/core/runtime/src/level_zero_runtime.cpp
intel/cassian
8e9594f053f9b9464066c8002297346580e4aa2a
[ "MIT" ]
1
2021-10-05T14:15:34.000Z
2021-10-05T14:15:34.000Z
src/core/runtime/src/level_zero_runtime.cpp
intel/cassian
8e9594f053f9b9464066c8002297346580e4aa2a
[ "MIT" ]
null
null
null
src/core/runtime/src/level_zero_runtime.cpp
intel/cassian
8e9594f053f9b9464066c8002297346580e4aa2a
[ "MIT" ]
null
null
null
/* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include <algorithm> #include <cstddef> #include <cstdint> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <ze_api.h> #include <cassian/logging/logging.hpp> #include <cassian/offline_compiler/offline_compiler.hpp> #include <cassian/runtime/access_qualifier.hpp> #include <cassian/runtime/device_properties.hpp> #include <cassian/runtime/feature.hpp> #include <cassian/runtime/image_properties.hpp> #include <cassian/runtime/level_zero_utils.hpp> #include <cassian/runtime/program_descriptor.hpp> #include <cassian/runtime/runtime.hpp> #include <cassian/utility/utility.hpp> #include "level_zero_runtime.hpp" #include "level_zero_wrapper.hpp" namespace cassian { LevelZeroRuntime::~LevelZeroRuntime() { if (queue_ != nullptr) { wrapper_.zeCommandQueueDestroy(queue_); } if (context_ != nullptr) { wrapper_.zeContextDestroy(context_); } } void LevelZeroRuntime::initialize() { logging::info() << "Runtime: " << name() << '\n'; ze_result_t result = ZE_RESULT_SUCCESS; result = wrapper_.zeInit(0); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to initialize Level Zero"); } uint32_t num_driver_handles = 1; result = wrapper_.zeDriverGet(&num_driver_handles, &driver_); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to get Level Zero driver"); } uint32_t num_devices = 1; result = wrapper_.zeDeviceGet(driver_, &num_devices, &device_); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to get Level Zero device"); } ze_context_desc_t context_description = {}; context_description.stype = ZE_STRUCTURE_TYPE_CONTEXT_DESC; context_description.pNext = nullptr; context_description.flags = 0; result = wrapper_.zeContextCreate(driver_, &context_description, &context_); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to create Level Zero context"); } ze_command_queue_desc_t command_queue_description = {}; command_queue_description.stype = ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC; command_queue_description.pNext = nullptr; command_queue_description.ordinal = 0; command_queue_description.index = 0; command_queue_description.flags = 0; command_queue_description.mode = ZE_COMMAND_QUEUE_MODE_ASYNCHRONOUS; command_queue_description.priority = ZE_COMMAND_QUEUE_PRIORITY_NORMAL; result = wrapper_.zeCommandQueueCreate(context_, device_, &command_queue_description, &queue_); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to create Level Zero command queue"); } } Buffer LevelZeroRuntime::create_buffer(const size_t size, AccessQualifier /*access*/) { ze_device_mem_alloc_desc_t device_memory_allocation_description = {}; device_memory_allocation_description.stype = ZE_STRUCTURE_TYPE_DEVICE_MEM_ALLOC_DESC; device_memory_allocation_description.pNext = nullptr; device_memory_allocation_description.flags = 0; device_memory_allocation_description.ordinal = 0; ze_host_mem_alloc_desc_t host_memory_allocation_description = {}; host_memory_allocation_description.stype = ZE_STRUCTURE_TYPE_HOST_MEM_ALLOC_DESC; host_memory_allocation_description.pNext = nullptr; host_memory_allocation_description.flags = 0; void *buffer = nullptr; ze_result_t result = wrapper_.zeMemAllocShared( context_, &device_memory_allocation_description, &host_memory_allocation_description, size, 1, device_, &buffer); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to allocate Level Zero memory"); } auto id = reinterpret_cast<std::uintptr_t>(buffer); buffers_[id] = buffer; return {id, size}; } Image LevelZeroRuntime::create_image(const ImageDimensions dim, const ImageType type, const ImageFormat format, const ImageChannelOrder order, AccessQualifier /*access*/) { ze_image_desc_t image_description = {}; image_description.stype = ZE_STRUCTURE_TYPE_IMAGE_DESC; image_description.pNext = nullptr; image_description.arraylevels = 0; image_description.width = dim.width; image_description.height = dim.height; image_description.depth = dim.depth; image_description.miplevels = 0; image_description.type = ze_get_image_type(type); image_description.flags = 0; image_description.format = ze_create_image_format(format, order); ze_image_handle_t image = nullptr; ze_result_t result = wrapper_.zeImageCreate(context_, device_, &image_description, &image); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to allocate Level Zero memory"); } auto id = reinterpret_cast<std::uintptr_t>(image); images_[id] = image; return {id, dim}; } Sampler LevelZeroRuntime::create_sampler(SamplerCoordinates coordinates, SamplerAddressingMode address_mode, SamplerFilterMode filter_mode) { ze_sampler_desc_t sampler_description = {}; sampler_description.stype = ZE_STRUCTURE_TYPE_SAMPLER_DESC; sampler_description.pNext = nullptr; switch (coordinates) { case SamplerCoordinates::unnormalized: sampler_description.isNormalized = 0U; break; case SamplerCoordinates::normalized: sampler_description.isNormalized = 1U; break; } switch (address_mode) { case SamplerAddressingMode::none: sampler_description.addressMode = ZE_SAMPLER_ADDRESS_MODE_NONE; break; case SamplerAddressingMode::clamp_to_edge: sampler_description.addressMode = ZE_SAMPLER_ADDRESS_MODE_CLAMP; break; case SamplerAddressingMode::clamp: sampler_description.addressMode = ZE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; break; case SamplerAddressingMode::repeat: sampler_description.addressMode = ZE_SAMPLER_ADDRESS_MODE_REPEAT; break; case SamplerAddressingMode::mirror: sampler_description.addressMode = ZE_SAMPLER_ADDRESS_MODE_MIRROR; break; } switch (filter_mode) { case SamplerFilterMode::nearest: sampler_description.filterMode = ZE_SAMPLER_FILTER_MODE_NEAREST; break; case SamplerFilterMode::linear: sampler_description.filterMode = ZE_SAMPLER_FILTER_MODE_LINEAR; break; } ze_sampler_handle_t sampler = nullptr; ze_result_t result = wrapper_.zeSamplerCreate(context_, device_, &sampler_description, &sampler); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to create Level Zero sampler"); } auto id = reinterpret_cast<std::uintptr_t>(sampler); samplers_[id] = sampler; return {id}; } void LevelZeroRuntime::read_buffer(const Buffer &buffer, void *data) { void *b = buffers_.at(buffer.id); ze_command_list_desc_t command_list_description = {}; command_list_description.stype = ZE_STRUCTURE_TYPE_COMMAND_LIST_DESC; command_list_description.pNext = nullptr; command_list_description.commandQueueGroupOrdinal = 0; command_list_description.flags = 0; ze_command_list_handle_t command_list = nullptr; ze_result_t result = wrapper_.zeCommandListCreate( context_, device_, &command_list_description, &command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to create Level Zero command list"); } result = wrapper_.zeCommandListAppendMemoryCopy( command_list, data, b, buffer.size, nullptr, 0, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException( "Failed to append memory copy to Level Zero command list"); } result = wrapper_.zeCommandListClose(command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to close Level Zero command list"); } result = wrapper_.zeCommandQueueExecuteCommandLists(queue_, 1, &command_list, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to execute Level Zero command list"); } result = wrapper_.zeCommandQueueSynchronize(queue_, UINT64_MAX); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to synchronize Level Zero command queue"); } result = wrapper_.zeCommandListDestroy(command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to destroy Level Zero command list"); } } void LevelZeroRuntime::read_image(const Image &image, void *data) { ze_image_handle_t src_image = images_.at(image.id); ze_command_list_desc_t command_list_description = {}; command_list_description.stype = ZE_STRUCTURE_TYPE_COMMAND_LIST_DESC; command_list_description.pNext = nullptr; command_list_description.commandQueueGroupOrdinal = 0; command_list_description.flags = 0; ze_command_list_handle_t command_list = nullptr; ze_result_t result = wrapper_.zeCommandListCreate( context_, device_, &command_list_description, &command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to create Level Zero command list"); } ze_image_region_t region = {}; region.width = image.dim.width; region.height = image.dim.height; region.depth = image.dim.depth; region.originX = 0; region.originY = 0; region.originZ = 0; result = wrapper_.zeCommandListAppendImageCopyToMemory( command_list, data, src_image, &region, nullptr, 0, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException( "Failed to append image copy to Level Zero command list"); } result = wrapper_.zeCommandListClose(command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to close Level Zero command list"); } result = wrapper_.zeCommandQueueExecuteCommandLists(queue_, 1, &command_list, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to execute Level Zero command list"); } result = wrapper_.zeCommandQueueSynchronize(queue_, UINT64_MAX); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to synchronize Level Zero command queue"); } result = wrapper_.zeCommandListDestroy(command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to destroy Level Zero command list"); } } void LevelZeroRuntime::write_buffer(const Buffer &buffer, const void *data) { void *b = buffers_.at(buffer.id); ze_command_list_desc_t command_list_description = {}; command_list_description.stype = ZE_STRUCTURE_TYPE_COMMAND_LIST_DESC; command_list_description.pNext = nullptr; command_list_description.commandQueueGroupOrdinal = 0; command_list_description.flags = 0; ze_command_list_handle_t command_list = nullptr; ze_result_t result = wrapper_.zeCommandListCreate( context_, device_, &command_list_description, &command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to create Level Zero command list"); } result = wrapper_.zeCommandListAppendMemoryCopy( command_list, b, data, buffer.size, nullptr, 0, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException( "Failed to append memory copy to Level Zero command list"); } result = wrapper_.zeCommandListClose(command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to close Level Zero command list"); } result = wrapper_.zeCommandQueueExecuteCommandLists(queue_, 1, &command_list, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to execute Level Zero command list"); } result = wrapper_.zeCommandQueueSynchronize(queue_, UINT64_MAX); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to synchronize Level Zero command queue"); } result = wrapper_.zeCommandListDestroy(command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to destroy Level Zero command list"); } } void LevelZeroRuntime::write_image(const Image &image, const void *data) { ze_image_handle_t dst_image = images_.at(image.id); ze_command_list_desc_t command_list_description = {}; command_list_description.stype = ZE_STRUCTURE_TYPE_COMMAND_LIST_DESC; command_list_description.pNext = nullptr; command_list_description.commandQueueGroupOrdinal = 0; command_list_description.flags = 0; ze_command_list_handle_t command_list = nullptr; ze_result_t result = wrapper_.zeCommandListCreate( context_, device_, &command_list_description, &command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to create Level Zero command list"); } ze_image_region_t region = {}; region.width = image.dim.width; region.height = image.dim.height; region.depth = image.dim.depth; region.originX = 0; region.originY = 0; region.originZ = 0; result = wrapper_.zeCommandListAppendImageCopyFromMemory( command_list, dst_image, data, &region, nullptr, 0, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException( "Failed to append image copy to Level Zero command list"); } result = wrapper_.zeCommandListClose(command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to close Level Zero command list"); } result = wrapper_.zeCommandQueueExecuteCommandLists(queue_, 1, &command_list, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to execute Level Zero command list"); } result = wrapper_.zeCommandQueueSynchronize(queue_, UINT64_MAX); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to synchronize Level Zero command queue"); } result = wrapper_.zeCommandListDestroy(command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to destroy Level Zero command list"); } } void LevelZeroRuntime::release_buffer(const Buffer &buffer) { void *b = buffers_.at(buffer.id); buffers_.erase(buffer.id); ze_result_t result = wrapper_.zeMemFree(context_, b); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to free Level Zero memory"); } } void LevelZeroRuntime::release_image(const Image &image) { ze_image_handle_t i = images_.at(image.id); images_.erase(image.id); ze_result_t result = wrapper_.zeImageDestroy(i); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to destroy Level Zero image"); } } void LevelZeroRuntime::release_sampler(const Sampler &sampler) { ze_sampler_handle_t s = samplers_.at(sampler.id); samplers_.erase(sampler.id); ze_result_t result = wrapper_.zeSamplerDestroy(s); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to destroy Level Zero sampler"); } } ze_module_handle_t LevelZeroRuntime::ze_create_module( const std::string &source, const std::string &build_options, const std::string &program_type, const std::optional<std::string> &spirv_options) { ze_result_t result = ZE_RESULT_SUCCESS; ze_module_handle_t module = nullptr; ze_module_build_log_handle_t build_log_handle = nullptr; auto f = finally([&]() mutable { if (build_log_handle != nullptr) { wrapper_.zeModuleBuildLogDestroy(build_log_handle); } }); if (program_type == "source") { throw RuntimeException( "Compilation from source is not supported by Level Zero"); } if (program_type == "spirv") { auto device_id = get_device_property(DeviceProperty::device_id); const std::vector<uint8_t> spv = generate_spirv_from_source(device_id, source, build_options); ze_module_desc_t module_description = {}; module_description.stype = ZE_STRUCTURE_TYPE_MODULE_DESC; module_description.pNext = nullptr; module_description.format = ZE_MODULE_FORMAT_IL_SPIRV; module_description.inputSize = static_cast<uint32_t>(spv.size()); module_description.pInputModule = spv.data(); if (spirv_options.has_value()) { module_description.pBuildFlags = spirv_options->c_str(); } else if (build_options.find("-cmc") == 0) { module_description.pBuildFlags = "-vc-codegen"; } else { module_description.pBuildFlags = build_options.c_str(); } module_description.pConstants = nullptr; result = wrapper_.zeModuleCreate(context_, device_, &module_description, &module, &build_log_handle); if (result != ZE_RESULT_SUCCESS) { const auto build_log = ze_get_module_build_log(build_log_handle); logging::error() << "Build log:\n" << build_log << '\n'; throw RuntimeException("Failed to create Level Zero module"); } } else { throw RuntimeException("Invalid program type: " + program_type); } return module; } Kernel LevelZeroRuntime::create_kernel( const std::string &kernel_name, const std::string &source, const std::string &build_options, const std::string &program_type, const std::optional<std::string> &spirv_options) { ze_result_t result = ZE_RESULT_SUCCESS; ze_module_handle_t module = ze_create_module(source, build_options, program_type, spirv_options); ze_kernel_desc_t kernel_description = {}; kernel_description.stype = ZE_STRUCTURE_TYPE_KERNEL_DESC; kernel_description.pNext = nullptr; kernel_description.pKernelName = kernel_name.c_str(); kernel_description.flags = 0; ze_kernel_handle_t kernel = nullptr; result = wrapper_.zeKernelCreate(module, &kernel_description, &kernel); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to create Level Zero kernel"); } auto id = reinterpret_cast<std::uintptr_t>(kernel); kernels_[id] = kernel; modules_.emplace(id, module); return Kernel(id); } Kernel LevelZeroRuntime::create_kernel_from_multiple_programs( const std::string &kernel_name, const std::vector<ProgramDescriptor> &program_descriptors, const std::string & /*linker_options*/) { ze_result_t result = ZE_RESULT_SUCCESS; ze_module_build_log_handle_t link_log_handle = nullptr; std::vector<ze_module_handle_t> modules; auto f = finally([&]() mutable { if (link_log_handle != nullptr) { wrapper_.zeModuleBuildLogDestroy(link_log_handle); } for (auto *m : modules) { wrapper_.zeModuleDestroy(m); } }); std::transform(std::begin(program_descriptors), std::end(program_descriptors), std::back_inserter(modules), [this](const auto &desc) { return ze_create_module(desc.source, desc.compiler_options, desc.program_type, desc.spirv_options); }); result = wrapper_.zeModuleDynamicLink(modules.size(), modules.data(), &link_log_handle); if (result != ZE_RESULT_SUCCESS) { const auto link_log = ze_get_module_build_log(link_log_handle); logging::error() << "Link log:\n" << link_log << '\n'; throw RuntimeException("Failed to link Level Zero modules"); } ze_kernel_desc_t kernel_description = {}; kernel_description.stype = ZE_STRUCTURE_TYPE_KERNEL_DESC; kernel_description.pNext = nullptr; kernel_description.pKernelName = kernel_name.c_str(); kernel_description.flags = 0; ze_kernel_handle_t kernel = nullptr; auto it = std::find_if(std::begin(modules), std::end(modules), [&](auto module) { kernel = nullptr; auto status = wrapper_.zeKernelCreate(module, &kernel_description, &kernel); if (status == ZE_RESULT_SUCCESS) { return true; } if (status == ZE_RESULT_ERROR_INVALID_KERNEL_NAME) { return false; } throw RuntimeException("Failed to create Level Zero modules"); }); if (it == std::end(modules)) { throw RuntimeException("Failed to create Level Zero modules"); } auto id = reinterpret_cast<std::uintptr_t>(kernel); kernels_[id] = kernel; for (auto *m : modules) { modules_.emplace(id, m); } modules.clear(); return Kernel(id); } void LevelZeroRuntime::set_kernel_argument(const Kernel &kernel, const int argument_index, const Buffer &buffer) { void *b = buffers_.at(buffer.id); set_kernel_argument(kernel, argument_index, sizeof(b), &b); } void LevelZeroRuntime::set_kernel_argument(const Kernel &kernel, const int argument_index, const Image &image) { ze_image_handle_t i = images_.at(image.id); set_kernel_argument(kernel, argument_index, sizeof(i), &i); } void LevelZeroRuntime::set_kernel_argument(const Kernel &kernel, const int argument_index, const Sampler &sampler) { ze_sampler_handle_t s = samplers_.at(sampler.id); set_kernel_argument(kernel, argument_index, sizeof(s), &s); } void LevelZeroRuntime::set_kernel_argument(const Kernel &kernel, const int argument_index, const size_t argument_size, const void *argument) { ze_kernel_handle_t k = kernels_.at(kernel.id); ze_result_t result = wrapper_.zeKernelSetArgumentValue( k, argument_index, argument_size, argument); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to set Level Zero kernel argument"); } } void LevelZeroRuntime::run_kernel_common( const Kernel &kernel, const std::array<size_t, 3> global_work_size, const std::array<size_t, 3> *local_work_size) { ze_kernel_handle_t k = kernels_.at(kernel.id); ze_command_list_desc_t command_list_description = {}; command_list_description.stype = ZE_STRUCTURE_TYPE_COMMAND_LIST_DESC; command_list_description.pNext = nullptr; command_list_description.commandQueueGroupOrdinal = 0; command_list_description.flags = 0; ze_command_list_handle_t command_list = nullptr; ze_result_t result = wrapper_.zeCommandListCreate( context_, device_, &command_list_description, &command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to create Level Zero command list"); } if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to get suggested Level Zero gropu size"); } ze_group_count_t thread_group_dimensions = {}; std::array<uint32_t, 3> local_ws = {1, 1, 1}; if (local_work_size == nullptr) { result = wrapper_.zeKernelSuggestGroupSize( k, global_work_size[0], global_work_size[1], global_work_size[2], &local_ws[0], &local_ws[1], &local_ws[2]); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to get Level Zero suggested group size"); } result = wrapper_.zeKernelSetGroupSize(k, local_ws[0], local_ws[1], local_ws[2]); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to set Level Zero group size"); } thread_group_dimensions.groupCountX = std::max(global_work_size[0] / local_ws[0], static_cast<size_t>(1)); thread_group_dimensions.groupCountY = std::max(global_work_size[1] / local_ws[1], static_cast<size_t>(1)); thread_group_dimensions.groupCountZ = std::max(global_work_size[2] / local_ws[2], static_cast<size_t>(1)); } else { result = wrapper_.zeKernelSetGroupSize(k, local_work_size->at(0), local_work_size->at(1), local_work_size->at(2)); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to set Level Zero group size"); } thread_group_dimensions.groupCountX = std::max( global_work_size[0] / local_work_size->at(0), static_cast<size_t>(1)); thread_group_dimensions.groupCountY = std::max( global_work_size[1] / local_work_size->at(1), static_cast<size_t>(1)); thread_group_dimensions.groupCountZ = std::max( global_work_size[2] / local_work_size->at(2), static_cast<size_t>(1)); } logging::debug() << "Running kernel with global_work_size = " << to_string(global_work_size) << " and local_work_size = " << (local_work_size != nullptr ? to_string(*local_work_size) : to_string(local_ws)) << '\n'; result = wrapper_.zeCommandListAppendLaunchKernel( command_list, k, &thread_group_dimensions, nullptr, 0, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException( "Failed to append kernel to Level Zero command list"); } result = wrapper_.zeCommandListClose(command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to close Level Zero command list"); } result = wrapper_.zeCommandQueueExecuteCommandLists(queue_, 1, &command_list, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to execute Level Zero command list"); } result = wrapper_.zeCommandQueueSynchronize(queue_, UINT64_MAX); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to synchronize Level Zero command queue"); } result = wrapper_.zeCommandListDestroy(command_list); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to destroy Level Zero command list"); } } void LevelZeroRuntime::release_kernel(const Kernel &kernel) { ze_kernel_handle_t k = kernels_.at(kernel.id); kernels_.erase(kernel.id); ze_result_t result = wrapper_.zeKernelDestroy(k); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to release Level Zero kernel"); } auto modules_for_kernel = modules_.equal_range(kernel.id); std::vector<std::pair<std::uintptr_t, ze_module_handle_t>> modules_to_destroy; auto is_module_in_use = [&](auto p) { return std::find_if(std::begin(modules_), std::end(modules_), [id = p.first, m = p.second](auto p) { return p.first != id && p.second == m; }) != std::end(modules_); }; std::copy_if(modules_for_kernel.first, modules_for_kernel.second, std::back_inserter(modules_to_destroy), is_module_in_use); modules_.erase(kernel.id); for (auto m : modules_to_destroy) { result = wrapper_.zeModuleDestroy(m.second); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to release Level Zero module"); } } } bool LevelZeroRuntime::is_feature_supported(const Feature feature) const { ze_device_module_properties_t device_module_properties = {}; device_module_properties.stype = ZE_STRUCTURE_TYPE_DEVICE_MODULE_PROPERTIES; device_module_properties.pNext = nullptr; ze_result_t result = wrapper_.zeDeviceGetModuleProperties(device_, &device_module_properties); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to get Level Zero kernel properties"); } ze_device_image_properties_t device_image_properties = {}; result = wrapper_.zeDeviceGetImageProperties(device_, &device_image_properties); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to get Level Zero image properties"); } switch (feature) { case Feature::fp16: return (device_module_properties.flags & ZE_DEVICE_MODULE_FLAG_FP16) != 0; case Feature::fp64: return (device_module_properties.flags & ZE_DEVICE_MODULE_FLAG_FP64) != 0; case Feature::read_write_images: return (device_image_properties.maxReadImageArgs != 0U) && (device_image_properties.maxWriteImageArgs != 0U); case Feature::image: case Feature::image2d: return get_device_property(DeviceProperty::image2d) != 0; case Feature::sampling: return get_device_property(DeviceProperty::max_num_samplers) != 0; case Feature::int64_atomics: return (device_module_properties.flags & ZE_DEVICE_MODULE_FLAG_INT64_ATOMICS) != 0; default: return false; } } int LevelZeroRuntime::get_device_property(const DeviceProperty property) const { ze_device_properties_t device_properties = {}; device_properties.stype = ZE_STRUCTURE_TYPE_DEVICE_PROPERTIES; device_properties.pNext = nullptr; ze_result_t result = wrapper_.zeDeviceGetProperties(device_, &device_properties); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to get Level Zero device properties"); } ze_device_compute_properties_t device_compute_properties = {}; device_compute_properties.stype = ZE_STRUCTURE_TYPE_DEVICE_COMPUTE_PROPERTIES; device_compute_properties.pNext = nullptr; result = wrapper_.zeDeviceGetComputeProperties(device_, &device_compute_properties); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException( "Failed to get Level Zero device compute properties"); } ze_device_image_properties_t device_image_properties = {}; device_image_properties.stype = ZE_STRUCTURE_TYPE_DEVICE_IMAGE_PROPERTIES; device_image_properties.pNext = nullptr; result = wrapper_.zeDeviceGetImageProperties(device_, &device_image_properties); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to get Level Zero device image properties"); } switch (property) { case DeviceProperty::max_group_size_x: return static_cast<int>(device_compute_properties.maxGroupSizeX); case DeviceProperty::max_group_size_y: return static_cast<int>(device_compute_properties.maxGroupSizeY); case DeviceProperty::max_group_size_z: return static_cast<int>(device_compute_properties.maxGroupSizeZ); case DeviceProperty::max_total_group_size: return static_cast<int>(device_compute_properties.maxTotalGroupSize); case DeviceProperty::max_num_samplers: return static_cast<int>(device_image_properties.maxSamplers); case DeviceProperty::image: return static_cast<int>(device_image_properties.maxImageDims1D != 0U && device_image_properties.maxImageDims2D != 0U && device_image_properties.maxImageDims3D != 0U); case DeviceProperty::image2d: return static_cast<int>(device_image_properties.maxImageDims2D); case DeviceProperty::max_local_memory_size: return static_cast<int>(device_compute_properties.maxSharedLocalMemory); case DeviceProperty::device_id: return static_cast<int>(device_properties.deviceId); case DeviceProperty::simd_width: return static_cast<int>(device_properties.physicalEUSimdWidth); default: throw RuntimeException("Failed to find device property"); } } std::string LevelZeroRuntime::name() const { return "L0"; } std::string LevelZeroRuntime::ze_get_module_build_log( const ze_module_build_log_handle_t &build_log_handle) const { size_t log_size = 0; ze_result_t result = wrapper_.zeModuleBuildLogGetString(build_log_handle, &log_size, nullptr); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to get Level Zero build log size"); } std::vector<char> log_vector(log_size); result = wrapper_.zeModuleBuildLogGetString(build_log_handle, &log_size, log_vector.data()); if (result != ZE_RESULT_SUCCESS) { throw RuntimeException("Failed to get Level Zero build log"); } std::string log(log_vector.begin(), log_vector.end()); return log; } } // namespace cassian
37.622196
80
0.711009
intel
243adbb232eafea79221ffa8f9fd869b0a1c9014
16,115
cpp
C++
PhantomEngine/PhantomFont.cpp
DexianZhao/PhantomGameEngine
cf8e341d21e3973856d9f23ad0b1af9db831bac7
[ "MIT" ]
4
2019-11-08T00:15:13.000Z
2021-03-26T13:34:50.000Z
PhantomEngine/PhantomFont.cpp
DexianZhao/PhantomGameEngine
cf8e341d21e3973856d9f23ad0b1af9db831bac7
[ "MIT" ]
4
2021-03-13T10:26:09.000Z
2021-03-13T10:45:35.000Z
PhantomEngine/PhantomFont.cpp
DexianZhao/PhantomGameEngine
cf8e341d21e3973856d9f23ad0b1af9db831bac7
[ "MIT" ]
3
2020-06-01T01:53:05.000Z
2021-03-21T03:51:33.000Z
////////////////////////////////////////////////////////////////////////////////////////////////////// /* 幻影游戏引擎, 2009-2016, Phantom Game Engine, http://www.aixspace.com Design Writer : 赵德贤 Dexian Zhao Email: yuzhou_995@hotmail.com */ ////////////////////////////////////////////////////////////////////////////////////////////////////// #include "PhantomFont.h" #include "PhantomManager.h" namespace Phantom{ Font::Font() { m_fPixelSize = 16.0f; m_fFontSize = 16.0f; m_fFontItalic = 0; m_bFullRGB = false; m_textColor = color4(1,1,1,1); m_fFontScale = 1.0f; m_fontSpaceW = 0; } Font::~Font() { } BOOL Font::LoadFont(const char* szFigFile) {CPUTime(Font); CFileHelperR r; if(!r.open(szFigFile)) { LogInfo("error:load font %s failure\n", szFigFile); return false; } char head[4]; r.read(head, 4); if(stricmp(head, "fig") != 0) { LogInfo("error:load font %s failure, not fig file\n", szFigFile); return false; } int pixelSize = 12; int version = 1; r >> version; r >> pixelSize; r >> m_bFullRGB; m_fPixelSize = (float)pixelSize; int nCount = 0; r >> nCount; if(nCount > 65536)//不超过65536个 { LogInfo("error:load font %s failure, data error\n", szFigFile); return false; } unsigned short maxcode = 0; r >> maxcode; unsigned short other = 0; r >> other; r.seek(other, StreamBase::Seek_Cur); // this->m_texts.SetArrayCount(nCount); r.read(m_texts.GetPtr(), sizeof(FontTextInfo) * nCount); // LFileName fig = szFigFile; fig.setIsFile(); // LFileName dir, file; fig.splitpath(&dir, &file, 0); dir += file; for(int i=0;i<MAX_FONT_IMAGES;i++) { LFileName path; path = dir; if(i == 0) path += ".png"; else { char buf[128]; sprintf(buf, "%d.png", i); path += buf; } //如果找到了就载入 if(!fexist(path)) break; TexturePtr ret; if(g_manager.LoadTexture(ret, path, 0, Phantom::TextureFilter_Point|0x00030000)) { m_fontImgs[i] = ret.GetPtr(); } } m_charsetMap.SetArrayCount(maxcode + 1); for(int i=0;i<m_charsetMap.size();i++) m_charsetMap[i] = -1; for(int i=0;i<nCount;i++) { assert(m_texts[i].unicode <= maxcode); m_charsetMap[m_texts[i].unicode] = (unsigned short)i; } this->m_fontName = file; return true; } BOOL Font::DrawTexts(const char* szUTF8, Rect& destRect, unsigned int len, unsigned dtFormat, const matrix4x4* world) {CPUTime(Font); if(len == 0) len = strlen(szUTF8); if(len <= 0)return false; m_tempBuffer.SetArrayCount(len * 2, false); if(g_manager.GetIsUtf8()) { int index = 0; for(int i=0;i<len;i++) { int n = 0; m_tempBuffer[index++] = utf8ToUnicode((const unsigned char*)szUTF8 + i, &n); i += (n - 1); } m_tempBuffer.SetArrayCount(index); } else { int l = Utf8ToW(szUTF8, m_tempBuffer.GetPtr(), len * 2); m_tempBuffer.SetArrayCount(l); } DrawTexts(m_tempBuffer.GetPtr(), destRect, m_tempBuffer.size(), dtFormat, world); return true; } BOOL Font::DrawTextClip(const short_t* szU, Rect& destRect, unsigned int len, unsigned dtFormat, const matrix4x4* world, const Rect* clip, BOOL bIsUI) {CPUTime(Font); if(!InitDrawText(destRect, &m_textColor, world, 0)) return false; if(len == 0) len = u_strlen(szU); // rect_f destIO((float)destRect.left, (float)destRect.top, (float)destRect.right, (float)destRect.bottom); rect_f rc = destIO; float maxLineHeight = 0; float2 topSpace(destIO.bottom, 0); { unsigned int nLength = len; const short_t* szUnicode = szU; float maxHeight = 0; while(*szUnicode && nLength > 0) { nLength--; if(!DrawUnicode(*szUnicode, rc, maxHeight, destRect, false, maxLineHeight, &topSpace, bIsUI, clip)) break; szUnicode++; } if(dtFormat & DrawTextAlign_RIGHT) destIO.left = destIO.right - (rc.right - destIO.left); else if(dtFormat & DrawTextAlign_CENTER) destIO.left += (destIO.GetWidth() - (rc.right - destIO.left)) / 2.0f; if(dtFormat & DrawTextAlign_BOTTOM) destIO.top = destIO.bottom - maxLineHeight;//(rc.bottom - destIO.top); else if(dtFormat & DrawTextAlign_VCENTER) destIO.top += (destIO.GetHeight() - maxLineHeight) / 2.0f;//(rc.bottom - destIO.top)) / 2.0f; if(dtFormat & DrawTextAlign_CALCRECT) return true; } { unsigned int nLength = len; const short_t* szUnicode = szU; float maxHeight = 0; while(*szUnicode && nLength > 0) { nLength--; if(!DrawUnicode(*szUnicode, destIO, maxHeight, destRect, true, maxLineHeight, &topSpace, bIsUI, clip)) break; szUnicode++; } } return true; } BOOL Font::DrawTexts(const short_t* szU, Rect& destRect, unsigned int len, unsigned dtFormat, const matrix4x4* world, const rect_f* scale, BOOL bIsUI) {CPUTime(Font); if(!InitDrawText(destRect, &m_textColor, world, scale)) return false; if(len == 0) len = -1; // rect_f destIO((float)destRect.left, (float)destRect.top, (float)destRect.right, (float)destRect.bottom); rect_f rc = destIO; float maxLineHeight = 0; float2 topSpace(destIO.bottom, 0); //if(dtFormat > 0) { unsigned int nLength = len; const short_t* szUnicode = szU; float maxHeight = 0; while(*szUnicode && nLength > 0) { nLength--; if(!DrawUnicode(*szUnicode, rc, maxHeight, destRect, false, maxLineHeight, &topSpace, bIsUI)) break; szUnicode++; } //maxLineHeight = topSpace.y - topSpace.x; if(dtFormat & DrawTextAlign_RIGHT) destIO.left = destIO.right - (rc.right - destIO.left); else if(dtFormat & DrawTextAlign_CENTER) destIO.left += (destIO.GetWidth() - (rc.right - destIO.left)) / 2.0f; if(dtFormat & DrawTextAlign_BOTTOM) destIO.top = destIO.bottom - maxLineHeight;//(rc.bottom - destIO.top); else if(dtFormat & DrawTextAlign_VCENTER) destIO.top += (destIO.GetHeight() - maxLineHeight) / 2.0f;//(rc.bottom - destIO.top)) / 2.0f; if(dtFormat & DrawTextAlign_CALCRECT) return true; } { unsigned int nLength = len; const short_t* szUnicode = szU; float maxHeight = 0; while(*szUnicode && nLength > 0) { nLength--; if(!DrawUnicode(*szUnicode, destIO, maxHeight, destRect, true, maxLineHeight, &topSpace, bIsUI)) break; szUnicode++; } } return true; } Font::FontTextInfo* Font::GetTextInfo(unsigned short u) {CPUTime(Font); if(u >= m_charsetMap.size() || m_charsetMap[u] == 65535) return 0; FontTextInfo* info = &m_texts[m_charsetMap[u]]; if(info->unicode != u) return 0; return info; } int Font::GetTextDrawCount(const short_t* szUnicode, int textCount, unsigned int nPixelWidth) {CPUTime(Font); Rect destRect(0, 0, g_manager.GetBufferWidth(), g_manager.GetBufferHeight()); rect_f destIO(0, 0, g_manager.GetBufferWidth(), g_manager.GetBufferHeight()); unsigned int nLength = textCount; float maxHeight = 0; int nCount = 0; float maxLineHeight = 0; while(*szUnicode && nLength > 0) { nLength--; if(!DrawUnicode(*szUnicode, destIO, maxHeight, destRect, false, maxLineHeight)) break; if(destIO.right >= nPixelWidth) return nCount; nCount++; szUnicode++; } return nCount; } VOID Font::SetFontSize(float f) {CPUTime(Font); m_fFontSize = f; if(m_fFontSize < 0) m_fFontSize = -m_fFontSize; m_fFontScale = m_fFontSize / m_fPixelSize; int nScale = (int)(m_fFontScale * 10); if((nScale%2) > 0) nScale = (nScale / 2 + 1) * 2; else nScale = (nScale / 2) * 2; m_fFontScale = (float)nScale / 10.0f; } Size Font::GetTextDrawSize(const short_t* szUnicode, int textCount) {CPUTime(Font); Rect destRect(0, 0, g_manager.GetBufferWidth(), g_manager.GetBufferHeight()); rect_f destIO(0, 0, m_fFontSize, m_fFontSize); unsigned int nLength = textCount; float maxHeight = 0; float maxLineHeight = 0; float2 topSpace(1000, 0); while(*szUnicode && nLength > 0) { nLength--; if(!DrawUnicode(*szUnicode, destIO, maxHeight, destRect, false, maxLineHeight, &topSpace)) { maxLineHeight = m_fFontSize; destIO.right = maxLineHeight; break; } szUnicode++; } return Size(destIO.right, maxLineHeight); } BOOL ClipRect(Rect& dest, Rect& tex, const Rect& clip) { if(dest.bottom < clip.top || dest.top > clip.bottom || dest.left > clip.right || dest.right < clip.left) return false; int dh = dest.GetHeight(); int dw = dest.GetWidth(); int th = tex.GetHeight(); int tw = tex.GetWidth(); if(dest.top < clip.top) { int ch = clip.top - dest.top; dest.top = clip.top; tex.top += ch * th / dh; } if(dest.bottom > clip.bottom) { int ch = dest.bottom - clip.bottom; dest.bottom = clip.bottom; tex.bottom -= ch * th / dh; } if(dest.left < clip.left) { int cw = clip.left - dest.left; dest.left = clip.left; tex.left += cw * tw / dw; } if(dest.right > clip.right) { int cw = dest.right - clip.right; dest.right = clip.right; tex.right -= cw * tw / dw; } return true; } BOOL Font::DrawUnicode(short_t u, rect_f& dio, float& maxHeight, const Rect& destRc, BOOL bDraw, float& maxLineHeight, float2* topSpace, BOOL bIsUI, const Rect* clip) {CPUTime(Font); if(u == ' ') { u = '_'; bDraw = false; } Font* font = this; FontTextInfo* info = GetTextInfo(u); if(!info || u < 128) { font = g_manager.GetDefaultENFont(); if(!font) return false; info = font->GetTextInfo(u); } if(!info) { for(int i=0;i<g_manager.m_fonts.size();i++) { if(g_manager.m_fonts[i] == font) continue; font = g_manager.m_fonts[i]; info = g_manager.m_fonts[i]->GetTextInfo(u); if(info) break; } } float screenWidth = (float)g_manager.GetBufferWidth(); float screenHeight = (float)g_manager.GetBufferHeight(); float scale = 1;//(float)m_fFontSize / (float)info->rh;//m_fFontScale; if(bDraw) scale *= ((float)maxLineHeight / (float)font->m_fPixelSize); float width,height; float offX = 0; float offY = 0; float realW = 0; float realH = 0; if(info) { //scale *= (float)m_fFontSize / (float)info->h;// width = (float)info->w * scale; height = (float)info->h * scale; realW = (float)info->rw * scale; realH = (float)info->rh * scale; offX = (float)info->offX * scale; offY = (float)info->offY * scale; } else { realW = m_fFontSize; realH = m_fFontSize; width = m_fFontSize; height = m_fFontSize; } dio.right = dio.left + width; if(dio.right > destRc.right) { dio.left = destRc.left; dio.right = dio.left + width; dio.top += maxLineHeight;//maxHeight; maxHeight = 0; } float top = dio.top + offY;// + realH; dio.bottom = top + height;//realH; if(!bDraw) { maxLineHeight = getmax(maxLineHeight, height); } else { float fSaveB = dio.bottom - dio.top; } rect_f rc(dio.left, top , dio.right, dio.bottom); //dio.bottom += height * 0.5f; if(dio.bottom > maxHeight) maxHeight = dio.bottom; // if((int)dio.top > destRc.bottom) return false; if(info) { Texture* t = font->m_fontImgs[info->imageIndex].t; float fTexWidth = (float)t->GetWidth(); float fTexHeight = (float)t->GetHeight(); if(bDraw) { if(clip){ Rect rcd(rc.left, rc.top, rc.right, rc.bottom); Rect rct(info->x, info->y, info->x + info->w, info->y + info->h); if(ClipRect(rcd, rct, *clip)) DrawUnicode(font->m_fontImgs[info->imageIndex].t, info->channel, rect_f(rcd.left, rcd.top, rcd.right, rcd.bottom), rect_f((float)rct.left / fTexWidth, (float)rct.top / fTexHeight, (float)rct.right / fTexWidth, (float)rct.bottom / fTexHeight), bIsUI); } else { rect_f texr((float)(info->x) / fTexWidth, (float)(info->y) / fTexHeight, (float)(info->x + info->w) / fTexWidth, (float)(info->y + info->h) / fTexHeight); rc.right = rc.left + (float)info->w; rc.bottom = rc.top + (float)info->h; DrawUnicode(font->m_fontImgs[info->imageIndex].t, info->channel, rc, texr, bIsUI); } } } if(info && u > 256) { if((info->w + 2) == info->rw) { width += width * 0.2f; } } dio.left += (width-m_fontSpaceW); return true; } BOOL Font::InitDrawText(const Rect& rc, const color4* c, const matrix4x4* world, const rect_f* scale) {CPUTime(Font); //if(rc.right <= rc.left || rc.bottom <= rc.top) // return false; //if(m_bFullRGB) //{ // if(!g_manager.SetRenderMode(RenderMode_TextFull)) // return false; //} //else if(!g_manager.SetRenderMode(RenderMode_TextChannel)) // return false; //m_screenRect.set(rc.left, rc.top, rc.right, rc.bottom); //float fov = tanf(g_manager.Get2DProjectionFov() / 2.0f) * 2.0f; //float fovY = fov; //float fovX = fovY * (float)g_manager.GetBufferWidth() / (float)g_manager.GetBufferHeight(); //// //m_drawPos[0].setxyz(m_screenRect.left, m_screenRect.top, 0); //m_drawPos[1].setxyz(m_screenRect.right, m_screenRect.top, 0); //m_drawPos[2].setxyz(m_screenRect.right, m_screenRect.bottom, 0); //m_drawPos[3].setxyz(m_screenRect.left, m_screenRect.bottom, 0); //for(int i=0;i<4;i++) //{ // float3& p = m_drawPos[i]; // if(world) // p.transform(p, *world); // else if(scale) // { // p.x = p.x * scale->left + scale->right; // p.y = p.y * scale->top + scale->bottom; // } //} //m_drawPosBegin = m_drawPos[0]; //m_drawPosDirL = m_drawPos[1] - m_drawPos[0]; //m_drawPosDirT = m_drawPos[3] - m_drawPos[0]; //m_drawPosDirL.normalize(); //m_drawPosDirT.normalize(); //// //g_manager.SetWorldMatrix2D(0); //unsigned int temp = 0xffffffff; //if(c) // temp = *c; //for(int i=0;i<4;i++) // m_drawColor[i] = temp; //g_manager->SetCullVisible(CullMode_CW); //g_manager->SetAlphaMode(AlphaMode_Blend); return true; } VOID Font::DrawUnicode(Texture* tex, int channel, const rect_f& screen, const rect_f& texRc, BOOL bIsUI) //渲染2D图片 {CPUTime(Font); assert(channel < 3); static float3 texChannel[3] = {float3(1,0,0), float3(0,1,0), float3(0,0,1)}; float fWidth = m_screenRect.GetWidth(); float fHeight = m_screenRect.GetHeight(); float left = screen.left - m_screenRect.left; float top = screen.top - m_screenRect.top; float right = screen.right - m_screenRect.left; float bottom = screen.bottom - m_screenRect.top; float l2 = left + m_fFontItalic * this->m_fFontSize; float r2 = right + m_fFontItalic * this->m_fFontSize; m_drawPos[0] = m_drawPosBegin + m_drawPosDirL * l2 + m_drawPosDirT * top; m_drawPos[1] = m_drawPosBegin + m_drawPosDirL * r2 + m_drawPosDirT * top; m_drawPos[2] = m_drawPosBegin + m_drawPosDirL * right + m_drawPosDirT * bottom; m_drawPos[3] = m_drawPosBegin + m_drawPosDirL * left + m_drawPosDirT * bottom; float fov = tanf(g_manager.Get2DProjectionFov() / 2.0f) * 2.0f; float fovY = fov; float fovX = fovY * (float)g_manager.GetBufferWidth() / (float)g_manager.GetBufferHeight(); for(int i=0;i<4;i++) { if(bIsUI) { m_drawPos[i].x *= g_manager.GetUIScale().x; m_drawPos[i].y *= g_manager.GetUIScale().y; m_drawPos[i].x += g_manager.GetUIOffset().x; m_drawPos[i].y += g_manager.GetUIOffset().y; } m_drawPos[i].x = ((m_drawPos[i].x / (float)g_manager.GetBufferWidth()) - 0.5f) * fovX; m_drawPos[i].y = (0.5f - (m_drawPos[i].y / (float)g_manager.GetBufferHeight())) * fovY; m_drawPos[i].z = 0; } // m_drawUV[0] = float2(texRc.left, texRc.top); m_drawUV[1] = float2(texRc.right, texRc.top); m_drawUV[2] = float2(texRc.right, texRc.bottom); m_drawUV[3] = float2(texRc.left, texRc.bottom); g_manager.GetCurrProgram()->SetTexture(TextureIndex_0, tex); if(!m_bFullRGB) { if(this->m_varTextChannel.is_findFail()) this->m_varTextChannel.reset_handle(); g_manager.GetCurrProgram()->SetFloat3(this->m_varTextChannel, texChannel[channel], "textChannel"); } static unsigned short indexBuffer[] ={3,1,0,3,2,1, 0,1,3,1,2,3}; int numIndices = 6; g_manager->DrawIndexed(g_manager.GetCurrProgram(), DrawVInfos(4, m_drawPos, m_drawColor, m_drawUV), indexBuffer, numIndices, DrawMode_Triangles); } };
30.348399
173
0.634998
DexianZhao
243c884e7bac4f400e8f268fe9e546622882ffe6
944
cpp
C++
test/tests/memcached/regression/lp_000-583-031.cpp
topilski/libmemcached
7a10166fbc4e718a3392ff744eb5bc499defd952
[ "BSD-3-Clause" ]
18
2021-06-23T15:20:25.000Z
2022-03-25T22:51:09.000Z
test/tests/memcached/regression/lp_000-583-031.cpp
topilski/libmemcached
7a10166fbc4e718a3392ff744eb5bc499defd952
[ "BSD-3-Clause" ]
108
2020-01-20T09:25:47.000Z
2021-05-18T06:45:30.000Z
test/tests/memcached/regression/lp_000-583-031.cpp
topilski/libmemcached
7a10166fbc4e718a3392ff744eb5bc499defd952
[ "BSD-3-Clause" ]
4
2021-06-25T07:49:31.000Z
2022-02-07T21:30:45.000Z
#include "test/lib/common.hpp" #include "test/lib/ReturnMatcher.hpp" TEST_CASE("memcached_regression_lp583031") { MemcachedPtr memc; LoneReturnMatcher test{*memc}; REQUIRE_SUCCESS(memcached_server_add(*memc, "192.0.2.1", 11211)); REQUIRE_SUCCESS(memcached_behavior_set(*memc, MEMCACHED_BEHAVIOR_CONNECT_TIMEOUT, 3000)); REQUIRE_SUCCESS(memcached_behavior_set(*memc, MEMCACHED_BEHAVIOR_RETRY_TIMEOUT, 1000)); REQUIRE_SUCCESS(memcached_behavior_set(*memc, MEMCACHED_BEHAVIOR_SND_TIMEOUT, 1000)); REQUIRE_SUCCESS(memcached_behavior_set(*memc, MEMCACHED_BEHAVIOR_RCV_TIMEOUT, 1000)); REQUIRE_SUCCESS(memcached_behavior_set(*memc, MEMCACHED_BEHAVIOR_POLL_TIMEOUT, 1000)); REQUIRE_SUCCESS(memcached_behavior_set(*memc, MEMCACHED_BEHAVIOR_SERVER_FAILURE_LIMIT, 3)); memcached_return_t rc; Malloced val(memcached_get(*memc, S("not-found"), nullptr, nullptr, &rc)); REQUIRE_RC(MEMCACHED_TIMEOUT, rc); REQUIRE_FALSE(*val); }
44.952381
93
0.808263
topilski
2441f77a6976761118737787ae981b45238b81e3
3,260
cpp
C++
tests/integral.cpp
steven-varga/h5cpp11
9b322fe381608cb277817a993999d03753d356be
[ "MIT" ]
6
2019-03-07T23:40:16.000Z
2021-09-22T17:31:32.000Z
tests/integral.cpp
steven-varga/h5cpp11
9b322fe381608cb277817a993999d03753d356be
[ "MIT" ]
null
null
null
tests/integral.cpp
steven-varga/h5cpp11
9b322fe381608cb277817a993999d03753d356be
[ "MIT" ]
1
2021-03-18T04:34:47.000Z
2021-03-18T04:34:47.000Z
/* * Copyright (c) 2017 vargaconsulting, Toronto,ON Canada * Author: Varga, Steven <steven@vargaconsulting.ca> * * 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 <gtest/gtest.h> #include <armadillo> #include <h5cpp/core> #include <h5cpp/mock.hpp> #include <h5cpp/create.hpp> #include <h5cpp/read.hpp> #include <h5cpp/write.hpp> #include "event_listener.hpp" #include "abstract.h" template <typename T> class IntegralTest : public AbstractTest<T>{}; typedef ::testing::Types<H5CPP_TEST_PRIMITIVE_TYPES> PrimitiveTypes; TYPED_TEST_CASE(IntegralTest, PrimitiveTypes); TYPED_TEST(IntegralTest,IntegralCreate) { // PLAIN if( h5::create<TypeParam>(this->fd,this->name + " 1d",{3}) < 0 ) ADD_FAILURE(); if( h5::create<TypeParam>(this->fd,this->name + " 2d",{2,3} ) < 0 ) ADD_FAILURE(); if( h5::create<TypeParam>(this->fd,this->name + " 3d",{1,2,3}) < 0 ) ADD_FAILURE(); // CHUNKED if( h5::create<TypeParam>(this->fd,this->name + " 1d chunk",{3000},{100} ) < 0 ) ADD_FAILURE(); if( h5::create<TypeParam>(this->fd,this->name + " 2d chunk",{2000,3},{100,1} ) < 0 ) ADD_FAILURE(); if( h5::create<TypeParam>(this->fd,this->name + " 3d chunk",{1000,2,3},{100,1,1} ) < 0 ) ADD_FAILURE(); // CHUNKED COMPRESSION: GZIP 9 if( h5::create<TypeParam>(this->fd,this->name + " 1d chunk gzip",{3000},{100},9 ) < 0 ) ADD_FAILURE(); if( h5::create<TypeParam>(this->fd,this->name + " 2d chunk gzip",{2000,3},{100,1},9 ) < 0 ) ADD_FAILURE(); if( h5::create<TypeParam>(this->fd,this->name + " 3d chunk gzip",{1000,2,3},{100,1,1},9 ) < 0 ) ADD_FAILURE(); } TYPED_TEST(IntegralTest,IntegralPointerWrite) { TypeParam data[100]={0}; hid_t ds = h5::create<TypeParam>(this->fd, this->name+".ptr",{100},{} ); h5::write(ds, data,{0},{100} ); H5Dclose(ds); } TYPED_TEST(IntegralTest,IntegralPointerRead) { TypeParam data[100]={0}; hid_t ds = h5::create<TypeParam>(this->fd, this->name+".ptr",{100},{} ); h5::write(ds, data,{0},{100} ); h5::read<TypeParam>(ds,data,{5},{20} ); H5Dclose(ds); h5::read<TypeParam>(this->fd,this->name+".ptr",data,{5},{20} ); } /*----------- BEGIN TEST RUNNER ---------------*/ H5CPP_TEST_RUNNER( int argc, char** argv ); /*----------------- END -----------------------*/
44.657534
111
0.675767
steven-varga
24426d11f8ebb6badf340fe65008b120b3fdc2fb
1,912
cpp
C++
pcommon/unittests/benchmark_bin128hash.cpp
mmalyutin/libpcomn
22e315e1de5f47254e1080a37ec87759e2fbed55
[ "Zlib" ]
6
2015-02-18T17:10:15.000Z
2019-01-01T13:48:05.000Z
pcommon/unittests/benchmark_bin128hash.cpp
mmalyutin/libpcomn
22e315e1de5f47254e1080a37ec87759e2fbed55
[ "Zlib" ]
null
null
null
pcommon/unittests/benchmark_bin128hash.cpp
mmalyutin/libpcomn
22e315e1de5f47254e1080a37ec87759e2fbed55
[ "Zlib" ]
3
2018-06-24T15:59:12.000Z
2021-02-15T09:21:39.000Z
/*-*- tab-width:4;indent-tabs-mode:nil;c-file-style:"ellemtel";c-basic-offset:4;c-file-offsets:((innamespace . 0)(inlambda . 0)) -*-*/ #include <pcomn_stopwatch.h> #include <pcomn_hash.h> #include <iostream> #include <algorithm> using namespace pcomn ; static constexpr size_t SIDE = 2048 ; static binary128_t v1[SIDE] ; static binary128_t v2[SIDE] ; __noinline binary128_t clock_hashing(size_t rounds) { if (!rounds) return {} ; const size_t itemcount = SIDE*rounds ; std::cout << "Running " << rounds << " rounds (" << itemcount << " items)" << std::endl ; PCpuStopwatch cpu_stopwatch ; PRealStopwatch wall_stopwatch ; binary128_t *from = v1 ; binary128_t *to = v2 ; wall_stopwatch.start() ; cpu_stopwatch.start() ; for (size_t n = 0 ; ++n < rounds ; std::swap(from, to)) { std::transform(from, from + SIDE, to, [](const binary128_t &v) { const uint64_t h = v.hash() ; return binary128_t(h, h) ; }) ; } cpu_stopwatch.stop() ; wall_stopwatch.stop() ; std::cout << cpu_stopwatch.elapsed() << "s CPU time, " << cpu_stopwatch.elapsed()/itemcount << "s per item, " << wall_stopwatch.elapsed() << "s real time, " << wall_stopwatch.elapsed()/itemcount << "s per item" << std::endl ; return *std::min_element(from, from + SIDE) ; } int main(int argc, char *argv[]) { if (argc != 2) return 1 ; int rounds = atoi(argv[1]) ; if (rounds <= 0) return 1 ; std::generate(std::begin(v1), std::end(v1), [init=0]() mutable { ++init ; return binary128_t(init, init) ; }) ; std::transform(std::begin(v1), std::end(v1), std::begin(v2), [](const binary128_t &v) { const uint64_t h = v.hash() ; return binary128_t(h, h) ; }) ; const binary128_t minval = clock_hashing(rounds) ; std::cout << minval << std::endl ; return 0 ; }
29.415385
134
0.598849
mmalyutin
2444c57303f6608b70cdf975eade38640a782801
9,352
cpp
C++
Dev/unitTest_cpp_gtest/Graphics/LowLayer/asd.Graphics_CubemapTexture_Test.cpp
akitsu-sanae/Altseed
03ac9ed2bc9d05c713f415177d796cb81914bb9a
[ "FTL" ]
null
null
null
Dev/unitTest_cpp_gtest/Graphics/LowLayer/asd.Graphics_CubemapTexture_Test.cpp
akitsu-sanae/Altseed
03ac9ed2bc9d05c713f415177d796cb81914bb9a
[ "FTL" ]
null
null
null
Dev/unitTest_cpp_gtest/Graphics/LowLayer/asd.Graphics_CubemapTexture_Test.cpp
akitsu-sanae/Altseed
03ac9ed2bc9d05c713f415177d796cb81914bb9a
[ "FTL" ]
null
null
null
 #include "../asd.Graphics_Test_Utls.h" static const char* dx_vs = R"( struct VS_Input { float3 Pos : Pos0; float2 UV : UV0; }; struct VS_Output { float4 Pos : SV_POSITION; float2 UV : TEXCOORD0; }; VS_Output main( const VS_Input Input ) { VS_Output Output = (VS_Output)0; Output.Pos = float4( Input.Pos.x, Input.Pos.y, Input.Pos.z, 1.0 ); Output.UV = Input.UV; return Output; } )"; static const char* dx_ps = R"( TextureCube g_texture : register( t0 ); SamplerState g_sampler : register( s0 ); struct PS_Input { float4 Pos : SV_POSITION; float2 UV : TEXCOORD0; }; float4 main( const PS_Input Input ) : SV_Target { float3 uv = float3(Input.UV.x, Input.UV.y, 1.0 - dot(Input.UV,Input.UV)); uv = normalize(uv); float4 Output = g_texture.SampleLevel(g_sampler, uv, 0.5); if(Output.a == 0.0f) discard; return Output; } )"; static const char* gl_vs = R"( //#version 150 in vec3 Pos; in vec2 UV; out vec4 vaTexCoord; void main() { gl_Position = vec4(Pos.x,Pos.y,Pos.z,1.0); vaTexCoord = vec4(UV.x,UV.y,0.0,0.0); } )"; static const char* gl_ps = R"( //#version 150 in vec4 vaTexCoord; uniform samplerCube g_texture; out vec4 fragColor; void main() { vec2 uv_ = vaTexCoord.xy; //uv_.y = 1.0 - uv_.y; vec3 uv = vec3(uv_.x, -uv_.y, 1.0 - dot(uv_,uv_)); uv = normalize(uv); fragColor = textureLod(g_texture, uv.xyz, 0.5); } )"; static const char* dx_writemip_vs = R"( struct VS_Input { float3 Pos : Pos0; float2 UV : UV0; }; struct VS_Output { float4 Pos : SV_POSITION; float2 UV : TEXCOORD0; }; VS_Output main( const VS_Input Input ) { VS_Output Output = (VS_Output)0; Output.Pos = float4( Input.Pos.x, Input.Pos.y, Input.Pos.z, 1.0 ); Output.UV = Input.UV; return Output; } )"; static const char* dx_writemip_ps = R"( Texture2D g_texture : register( t0 ); SamplerState g_sampler : register( s0 ); struct PS_Input { float4 Pos : SV_POSITION; float2 UV : TEXCOORD0; }; float4 main( const PS_Input Input ) : SV_Target { float2 uv = float2(Input.UV.x, Input.UV.y); float4 Output = g_texture.Sample(g_sampler, uv); if(Output.a == 0.0f) discard; return Output; } )"; static const char* gl_writemip_vs = R"( //#version 150 in vec3 Pos; in vec2 UV; out vec4 vaTexCoord; void main() { gl_Position = vec4(Pos.x,Pos.y,Pos.z,1.0); vaTexCoord = vec4(UV.x,UV.y,0.0,0.0); } )"; static const char* gl_writemip_ps = R"( //#version 150 in vec4 vaTexCoord; uniform sampler2D g_texture; out vec4 fragColor; void main() { vec2 uv = vaTexCoord.xy; uv.y = 1.0 - uv.y; fragColor = texture(g_texture, uv); } )"; struct Vertex { asd::Vector3DF Pos; asd::Vector2DF UV; Vertex() {} Vertex(asd::Vector3DF pos, asd::Vector2DF uv) { Pos = pos; UV = uv; } }; void Graphics_CubemapTexture(bool isOpenGLMode) { StartGraphicsTest(); SetGLEnable(isOpenGLMode); asd::Log* log = asd::Log_Imp::Create(u"graphics.html", u"描画"); auto window = asd::Window_Imp::Create(640, 480, asd::ToAString(u"CubemapTexture").c_str(), log, false, asd::WindowPositionType::Default, isOpenGLMode ? asd::GraphicsDeviceType::OpenGL : asd::GraphicsDeviceType::DirectX11, asd::ColorSpaceType::LinearSpace, false); ASSERT_TRUE(window != nullptr); auto synchronizer = std::make_shared<asd::Synchronizer>(); auto file = asd::File_Imp::Create(synchronizer); ASSERT_TRUE(file != nullptr); asd::GraphicsOption go; go.IsFullScreen = false; go.IsReloadingEnabled = false; go.ColorSpace = asd::ColorSpaceType::LinearSpace; go.GraphicsDevice = isOpenGLMode ? asd::GraphicsDeviceType::OpenGL : asd::GraphicsDeviceType::DirectX11; auto graphics = asd::Graphics_Imp::Create(window, isOpenGLMode ? asd::GraphicsDeviceType::OpenGL : asd::GraphicsDeviceType::DirectX11, log, file, go); ASSERT_TRUE(graphics != nullptr); auto cubemap = graphics->CreateCubemapTextureFrom6ImageFiles_( asd::ToAString("Data/Cubemap/Sky1/Front.png").c_str(), asd::ToAString("Data/Cubemap/Sky1/Left.png").c_str(), asd::ToAString("Data/Cubemap/Sky1/Back.png").c_str(), asd::ToAString("Data/Cubemap/Sky1/Right.png").c_str(), asd::ToAString("Data/Cubemap/Sky1/Top.png").c_str(), asd::ToAString("Data/Cubemap/Sky1/Bottom.png").c_str() ); auto front = graphics->CreateTexture2D(asd::ToAString("Data/Cubemap/Sky1/Front.png").c_str()); auto back = graphics->CreateTexture2D(asd::ToAString("Data/Cubemap/Sky1/Back.png").c_str()); auto left = graphics->CreateTexture2D(asd::ToAString("Data/Cubemap/Sky1/Left.png").c_str()); auto right = graphics->CreateTexture2D(asd::ToAString("Data/Cubemap/Sky1/Right.png").c_str()); auto top = graphics->CreateTexture2D(asd::ToAString("Data/Cubemap/Sky1/Top.png").c_str()); auto bottom = graphics->CreateTexture2D(asd::ToAString("Data/Cubemap/Sky1/Bottom.png").c_str()); auto vertexBuffer = graphics->CreateVertexBuffer_Imp(sizeof(Vertex), 4, false); ASSERT_TRUE(vertexBuffer != nullptr); auto vertexBufferMip = graphics->CreateVertexBuffer_Imp(sizeof(Vertex), 4, false); ASSERT_TRUE(vertexBufferMip != nullptr); auto indexBuffer = graphics->CreateIndexBuffer_Imp(6, false, false); ASSERT_TRUE(indexBuffer != nullptr); std::vector<asd::VertexLayout> vl; vl.push_back(asd::VertexLayout("Pos", asd::VertexLayoutFormat::R32G32B32_FLOAT)); vl.push_back(asd::VertexLayout("UV", asd::VertexLayoutFormat::R32G32_FLOAT)); std::shared_ptr<asd::NativeShader_Imp> shader; std::shared_ptr<asd::NativeShader_Imp> shaderMip; bool const is32bit = false; std::vector<asd::Macro> macro; if (isOpenGLMode) { shader = graphics->CreateShader_Imp( gl_vs, "vs", gl_ps, "ps", vl, is32bit, macro); shaderMip = graphics->CreateShader_Imp( gl_writemip_vs, "vs", gl_writemip_ps, "ps", vl, is32bit, macro); } else { shader = graphics->CreateShader_Imp( dx_vs, "vs", dx_ps, "ps", vl, is32bit, macro); shaderMip = graphics->CreateShader_Imp( dx_writemip_vs, "vs", dx_writemip_ps, "ps", vl, is32bit, macro); } ASSERT_TRUE(shader != nullptr); ASSERT_TRUE(shaderMip != nullptr); { vertexBuffer->Lock(); auto vb = vertexBuffer->GetBuffer<Vertex>(4); vb[0] = Vertex(asd::Vector3DF(-1.0f, 1.0f, 0.5f), asd::Vector2DF(0.0f, 0.0f)); vb[1] = Vertex(asd::Vector3DF(0.5f, 1.0f, 0.5f), asd::Vector2DF(1.0f, 0.0f)); vb[2] = Vertex(asd::Vector3DF(0.5f, -1.0f, 0.5f), asd::Vector2DF(1.0f, 1.0f)); vb[3] = Vertex(asd::Vector3DF(-1.0f, -1.0f, 0.5f), asd::Vector2DF(0.0f, 1.0f)); vertexBuffer->Unlock(); } { vertexBufferMip->Lock(); auto vb = vertexBufferMip->GetBuffer<Vertex>(4); vb[0] = Vertex(asd::Vector3DF(-1.0f, 1.0f, 0.5f), asd::Vector2DF(0.0f, 0.0f)); vb[1] = Vertex(asd::Vector3DF(1.0f, 1.0f, 0.5f), asd::Vector2DF(1.0f, 0.0f)); vb[2] = Vertex(asd::Vector3DF(1.0f, -1.0f, 0.5f), asd::Vector2DF(1.0f, 1.0f)); vb[3] = Vertex(asd::Vector3DF(-1.0f, -1.0f, 0.5f), asd::Vector2DF(0.0f, 1.0f)); vertexBufferMip->Unlock(); } { indexBuffer->Lock(); auto ib = indexBuffer->GetBuffer<uint16_t>(6); ib[0] = 0; ib[1] = 1; ib[2] = 2; ib[3] = 0; ib[4] = 2; ib[5] = 3; indexBuffer->Unlock(); } shader->SetTexture("g_texture", cubemap, asd::TextureFilterType::Linear, asd::TextureWrapType::Clamp, 0); int32_t time = 0; while (window->DoEvent()) { graphics->Begin(); for (int i = 0; i < 6; i++) { if (i == 0) shaderMip->SetTexture("g_texture", right.get(), asd::TextureFilterType::Linear, asd::TextureWrapType::Clamp, 0); if (i == 1) shaderMip->SetTexture("g_texture", left.get(), asd::TextureFilterType::Linear, asd::TextureWrapType::Clamp, 0); if (i == 2) shaderMip->SetTexture("g_texture", top.get(), asd::TextureFilterType::Linear, asd::TextureWrapType::Clamp, 0); if (i == 3) shaderMip->SetTexture("g_texture", bottom.get(), asd::TextureFilterType::Linear, asd::TextureWrapType::Clamp, 0); if (i == 4) shaderMip->SetTexture("g_texture", front.get(), asd::TextureFilterType::Linear, asd::TextureWrapType::Clamp, 0); if (i == 5) shaderMip->SetTexture("g_texture", back.get(), asd::TextureFilterType::Linear, asd::TextureWrapType::Clamp, 0); graphics->SetRenderTarget((asd::CubemapTexture_Imp*)cubemap, i, 1, nullptr); graphics->SetVertexBuffer(vertexBufferMip.get()); graphics->SetIndexBuffer(indexBuffer.get()); graphics->SetShader(shaderMip.get()); asd::RenderState state; state.DepthTest = false; state.DepthWrite = false; graphics->SetRenderState(state); graphics->DrawPolygon(2); } graphics->SetRenderTarget(nullptr, nullptr); graphics->Clear(true, false, asd::Color(64, 32, 16, 255)); graphics->SetVertexBuffer(vertexBuffer.get()); graphics->SetIndexBuffer(indexBuffer.get()); graphics->SetShader(shader.get()); asd::RenderState state; state.DepthTest = false; state.DepthWrite = false; graphics->SetRenderState(state); graphics->DrawPolygon(2); graphics->Present(); graphics->End(); if (time == 10) { SAVE_SCREEN_SHOT(graphics, 0); } if (time == 11) { window->Close(); } time++; } front.reset(); cubemap->Release(); graphics->Release(); file->Release(); vertexBuffer.reset(); indexBuffer.reset(); shader.reset(); window->Release(); delete log; } #ifdef _WIN32 TEST(Graphics, CubemapTexture_DX) { Graphics_CubemapTexture(false); } #endif TEST(Graphics, CubemapTexture_GL) { Graphics_CubemapTexture(true); }
23.736041
264
0.682849
akitsu-sanae
24456748eb83551545415f08cac844482106b8f2
2,215
cpp
C++
tests/dist/mpi/examples/mpi_send.cpp
Shillaker/faabric
40da290179c650d9e285475a1992572dfe1c0b10
[ "Apache-2.0" ]
1
2020-09-01T13:37:54.000Z
2020-09-01T13:37:54.000Z
tests/dist/mpi/examples/mpi_send.cpp
Shillaker/faabric
40da290179c650d9e285475a1992572dfe1c0b10
[ "Apache-2.0" ]
null
null
null
tests/dist/mpi/examples/mpi_send.cpp
Shillaker/faabric
40da290179c650d9e285475a1992572dfe1c0b10
[ "Apache-2.0" ]
1
2020-09-13T15:21:16.000Z
2020-09-13T15:21:16.000Z
#include <faabric/mpi/mpi.h> #include <stdio.h> namespace tests::mpi { int send() { int res = MPI_Init(NULL, NULL); if (res != MPI_SUCCESS) { printf("Failed on MPI init\n"); return 1; } int rank; int worldSize; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); if (rank < 0) { printf("Rank must be positive integer or zero (is %i)\n", rank); return 1; } if (worldSize <= 1) { printf("World size must be greater than 1 (is %i)\n", worldSize); return 1; } if (rank == 0) { // Send message to the rest of the world for (int dest = 1; dest < worldSize; dest++) { int sentNumber = 100 + dest; MPI_Send(&sentNumber, 1, MPI_INT, dest, 0, MPI_COMM_WORLD); } // Wait for all responses int receivedNumber = 0; int expectedNumber; for (int r = 1; r < worldSize; r++) { expectedNumber = 100 - r; MPI_Recv(&receivedNumber, 1, MPI_INT, r, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); if (receivedNumber != expectedNumber) { printf( "Got unexpected number from rank %i (got %i, expected %i)\n", r, receivedNumber, expectedNumber); return 1; } } } else { int expectedNumber = 100 + rank; int sentNumber = 100 - rank; int receivedNumber = 0; // Receive message from master MPI_Recv( &receivedNumber, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); if (receivedNumber != expectedNumber) { printf("Got unexpected number from master (got %i, expected %i)\n", receivedNumber, expectedNumber); return 1; } // Send response back MPI_Send(&sentNumber, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); } MPI_Finalize(); printf("MPI Send example finished succesfully.\n"); return 0; } }
27.012195
80
0.504289
Shillaker
24457fd301b53435389d8c4e4ca692145557a1f1
416
cpp
C++
source/pso/function/Easom.cpp
Nothrax/pso_visualisation
96f9453643c49f0b94b5d9f0462274f74a29388f
[ "MIT" ]
null
null
null
source/pso/function/Easom.cpp
Nothrax/pso_visualisation
96f9453643c49f0b94b5d9f0462274f74a29388f
[ "MIT" ]
null
null
null
source/pso/function/Easom.cpp
Nothrax/pso_visualisation
96f9453643c49f0b94b5d9f0462274f74a29388f
[ "MIT" ]
null
null
null
#include <pso/function/Easom.h> double Easom::calculateFitness(Point point) { return -cos(point.x) * cos(point.y) * exp(-(point.x - _pi) * (point.x - _pi) - (point.y - _pi) * (point.y - _pi)); } double Easom::getMinFitness() { return -1.0; } Point Easom::getBoundary() { Point point = {80.0, 80.0}; return point; } std::string Easom::getMinPoint() { return "[3.14159,\n3.14159]"; }
21.894737
87
0.596154
Nothrax
244761738fccc8a11616eb2eccb6938685186722
7,679
cpp
C++
test/test_complex.cpp
pruthvistony/rocThrust
c986b97395d4a6cbacc7a4600d11bdf389de639a
[ "Apache-2.0" ]
null
null
null
test/test_complex.cpp
pruthvistony/rocThrust
c986b97395d4a6cbacc7a4600d11bdf389de639a
[ "Apache-2.0" ]
null
null
null
test/test_complex.cpp
pruthvistony/rocThrust
c986b97395d4a6cbacc7a4600d11bdf389de639a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008-2013 NVIDIA Corporation * Modifications Copyright© 2019 Advanced Micro Devices, Inc. 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 <thrust/complex.h> #include "test_header.hpp" TESTS_DEFINE(ComplexTests, FloatTestsParams); TYPED_TEST(ComplexTests, TestComplexConstructors) { using T = typename TestFixture::input_type; thrust::host_vector<T> data = get_random_data<T>(2, T(-1000), T(1000)); thrust::complex<T> a(data[0], data[1]); thrust::complex<T> b(a); thrust::complex<float> float_b(a); a = thrust::complex<T>(data[0], data[1]); ASSERT_NEAR_COMPLEX(a, b); a = thrust::complex<T>(data[0]); ASSERT_EQ(data[0], a.real()); ASSERT_EQ(T(0), a.imag()); a = thrust::complex<T>(); ASSERT_NEAR_COMPLEX(a, std::complex<T>(0)); a = thrust::complex<T>( thrust::complex<float>(static_cast<float>(data[0]), static_cast<float>(data[1]))); ASSERT_NEAR_COMPLEX(a, float_b); a = thrust::complex<T>( thrust::complex<double>(static_cast<double>(data[0]), static_cast<double>(data[1]))); ASSERT_NEAR_COMPLEX(a, b); a = thrust::complex<T>( std::complex<float>(static_cast<float>(data[0]), static_cast<float>(data[1]))); ASSERT_NEAR_COMPLEX(a, float_b); a = thrust::complex<T>( std::complex<double>(static_cast<double>(data[0]), static_cast<double>(data[1]))); ASSERT_NEAR_COMPLEX(a, b); } TYPED_TEST(ComplexTests, TestComplexGetters) { using T = typename TestFixture::input_type; thrust::host_vector<T> data = get_random_data<T>(2, std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); thrust::complex<T> z(data[0], data[1]); ASSERT_EQ(data[0], z.real()); ASSERT_EQ(data[1], z.imag()); z.real(data[1]); z.imag(data[0]); ASSERT_EQ(data[1], z.real()); ASSERT_EQ(data[0], z.imag()); volatile thrust::complex<T> v(data[0], data[1]); ASSERT_EQ(data[0], v.real()); ASSERT_EQ(data[1], v.imag()); v.real(data[1]); v.imag(data[0]); ASSERT_EQ(data[1], v.real()); ASSERT_EQ(data[0], v.imag()); } TYPED_TEST(ComplexTests, TestComplexMemberOperators) { using T = typename TestFixture::input_type; thrust::host_vector<T> data_a = get_random_data<T>(2, 10000, 10000); thrust::host_vector<T> data_b = get_random_data<T>(2, 10000, 10000); thrust::complex<T> a(data_a[0], data_a[1]); thrust::complex<T> b(data_b[0], data_b[1]); std::complex<T> c(a); std::complex<T> d(b); a += b; c += d; ASSERT_NEAR_COMPLEX(a, c); a -= b; c -= d; ASSERT_NEAR_COMPLEX(a, c); a *= b; c *= d; ASSERT_NEAR_COMPLEX(a, c); a /= b; c /= d; ASSERT_NEAR_COMPLEX(a, c); // casting operator c = (std::complex<T>)a; } TYPED_TEST(ComplexTests, TestComplexBasicArithmetic) { using T = typename TestFixture::input_type; thrust::host_vector<T> data = get_random_data<T>(2, T(-100), T(100)); thrust::complex<T> a(data[0], data[1]); std::complex<T> b(a); // Test the basic arithmetic functions against std ASSERT_NEAR(abs(a), abs(b), T(0.01)); ASSERT_NEAR(arg(a), arg(b), T(0.01)); ASSERT_NEAR(norm(a), norm(b), T(0.01)); ASSERT_EQ(conj(a), conj(b)); ASSERT_NEAR_COMPLEX(thrust::polar(data[0], data[1]), std::polar(data[0], data[1])); // random_samples does not seem to produce infinities so proj(z) == z ASSERT_EQ(proj(a), a); } TYPED_TEST(ComplexTests, TestComplexBinaryArithmetic) { using T = typename TestFixture::input_type; thrust::host_vector<T> data_a = get_random_data<T>(2, -10000, 10000); thrust::host_vector<T> data_b = get_random_data<T>(2, -10000, 10000); thrust::complex<T> a(data_a[0], data_a[1]); thrust::complex<T> b(data_b[0], data_b[1]); ASSERT_NEAR_COMPLEX(a * b, std::complex<T>(a) * std::complex<T>(b)); ASSERT_NEAR_COMPLEX(a * data_b[0], std::complex<T>(a) * data_b[0]); ASSERT_NEAR_COMPLEX(data_a[0] * b, data_a[0] * std::complex<T>(b)); ASSERT_NEAR_COMPLEX(a / b, std::complex<T>(a) / std::complex<T>(b)); ASSERT_NEAR_COMPLEX(a / data_b[0], std::complex<T>(a) / data_b[0]); ASSERT_NEAR_COMPLEX(data_a[0] / b, data_a[0] / std::complex<T>(b)); ASSERT_EQ(a + b, std::complex<T>(a) + std::complex<T>(b)); ASSERT_EQ(a + data_b[0], std::complex<T>(a) + data_b[0]); ASSERT_EQ(data_a[0] + b, data_a[0] + std::complex<T>(b)); ASSERT_EQ(a - b, std::complex<T>(a) - std::complex<T>(b)); ASSERT_EQ(a - data_b[0], std::complex<T>(a) - data_b[0]); ASSERT_EQ(data_a[0] - b, data_a[0] - std::complex<T>(b)); } TYPED_TEST(ComplexTests, TestComplexUnaryArithmetic) { using T = typename TestFixture::input_type; thrust::host_vector<T> data_a = get_random_data<T>(2, std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); thrust::complex<T> a(data_a[0], data_a[1]); ASSERT_EQ(+a, +std::complex<T>(a)); ASSERT_EQ(-a, -std::complex<T>(a)); } TYPED_TEST(ComplexTests, TestComplexExponentialFunctions) { using T = typename TestFixture::input_type; thrust::host_vector<T> data_a = get_random_data<T>(2, -100, 100); thrust::complex<T> a(data_a[0], data_a[1]); std::complex<T> b(a); ASSERT_NEAR_COMPLEX(exp(a), exp(b)); ASSERT_NEAR_COMPLEX(log(a), log(b)); ASSERT_NEAR_COMPLEX(log10(a), log10(b)); } TYPED_TEST(ComplexTests, TestComplexPowerFunctions) { using T = typename TestFixture::input_type; thrust::host_vector<T> data_a = get_random_data<T>(2, -100, 100); thrust::host_vector<T> data_b = get_random_data<T>(2, -100, 100); thrust::complex<T> a(data_a[0], data_a[1]); thrust::complex<T> b(data_b[0], data_b[1]); std::complex<T> c(a); std::complex<T> d(b); ASSERT_NEAR_COMPLEX(pow(a, b), pow(c, d)); ASSERT_NEAR_COMPLEX(pow(a, b.real()), pow(c, d.real())); ASSERT_NEAR_COMPLEX(pow(a.real(), b), pow(c.real(), d)); ASSERT_NEAR_COMPLEX(sqrt(a), sqrt(c)); } TYPED_TEST(ComplexTests, TestComplexTrigonometricFunctions) { using T = typename TestFixture::input_type; thrust::host_vector<T> data_a = get_random_data<T>(2, T(-1), T(1)); thrust::complex<T> a(data_a[0], data_a[1]); std::complex<T> c(a); ASSERT_NEAR_COMPLEX(cos(a), cos(c)); ASSERT_NEAR_COMPLEX(sin(a), sin(c)); ASSERT_NEAR_COMPLEX(tan(a), tan(c)); ASSERT_NEAR_COMPLEX(cosh(a), cosh(c)); ASSERT_NEAR_COMPLEX(sinh(a), sinh(c)); ASSERT_NEAR_COMPLEX(tanh(a), tanh(c)); ASSERT_NEAR_COMPLEX(acos(a), acos(c)); ASSERT_NEAR_COMPLEX(asin(a), asin(c)); ASSERT_NEAR_COMPLEX(atan(a), atan(c)); ASSERT_NEAR_COMPLEX(acosh(a), acosh(c)); ASSERT_NEAR_COMPLEX(asinh(a), asinh(c)); ASSERT_NEAR_COMPLEX(atanh(a), atanh(c)); } TYPED_TEST(ComplexTests, TestComplexStreamOperators) { using T = typename TestFixture::input_type; thrust::host_vector<T> data_a = get_random_data<T>(2, T(-1000), T(1000)); thrust::complex<T> a(data_a[0], data_a[1]); std::stringstream out; out << a; thrust::complex<T> b; out >> b; ASSERT_NEAR_COMPLEX(a, b); }
29.648649
94
0.643313
pruthvistony
2449425f1b7bfb17634c4118ae5ffb5b55724615
38,179
cc
C++
pcall/src/main/cpp/slicer/dex_bytecode.cc
johnlee175/PCallDemo
1940e2ecac85d37505e66524fb46ff801c3d4de3
[ "Apache-2.0" ]
4
2019-01-03T04:16:37.000Z
2019-08-04T17:54:18.000Z
pcall/src/main/cpp/slicer/dex_bytecode.cc
johnlee175/PCallDemo
1940e2ecac85d37505e66524fb46ff801c3d4de3
[ "Apache-2.0" ]
null
null
null
pcall/src/main/cpp/slicer/dex_bytecode.cc
johnlee175/PCallDemo
1940e2ecac85d37505e66524fb46ff801c3d4de3
[ "Apache-2.0" ]
2
2019-08-04T17:54:34.000Z
2021-05-07T05:40:27.000Z
/* * Copyright (C) 2017 The Android Open Source Project * * 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 "dex_bytecode.h" #include "common.h" #include <assert.h> #include <array> namespace dex { Opcode OpcodeFromBytecode(u2 bytecode) { Opcode opcode = Opcode(bytecode & 0xff); CHECK(opcode != OP_UNUSED_FF); return opcode; } // Table that maps each opcode to the index type implied by that opcode static constexpr std::array<InstructionIndexType, kNumPackedOpcodes> gInstructionIndexTypeTable = { kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexStringRef, kIndexStringRef, kIndexTypeRef, kIndexNone, kIndexNone, kIndexTypeRef, kIndexTypeRef, kIndexNone, kIndexTypeRef, kIndexTypeRef, kIndexTypeRef, kIndexTypeRef, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexUnknown, kIndexUnknown, kIndexUnknown, kIndexUnknown, kIndexUnknown, kIndexUnknown, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexMethodRef, kIndexMethodRef, kIndexMethodRef, kIndexMethodRef, kIndexMethodRef, kIndexUnknown, kIndexMethodRef, kIndexMethodRef, kIndexMethodRef, kIndexMethodRef, kIndexMethodRef, kIndexUnknown, kIndexUnknown, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexNone, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexUnknown, kIndexVaries, kIndexInlineMethod, kIndexInlineMethod, kIndexMethodRef, kIndexNone, kIndexFieldOffset, kIndexFieldOffset, kIndexFieldOffset, kIndexFieldOffset, kIndexFieldOffset, kIndexFieldOffset, kIndexVtableOffset, kIndexVtableOffset, kIndexVtableOffset, kIndexVtableOffset, kIndexFieldRef, kIndexFieldRef, kIndexFieldRef, kIndexUnknown, }; InstructionIndexType GetIndexTypeFromOpcode(Opcode opcode) { return gInstructionIndexTypeTable[opcode]; } // Table that maps each opcode to the full width of instructions that // use that opcode, in (16-bit) code units. Unimplemented opcodes as // well as the "breakpoint" opcode have a width of zero. static constexpr std::array<u1, kNumPackedOpcodes> gInstructionWidthTable = { 1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 2, 2, 3, 5, 2, 2, 3, 2, 1, 1, 2, 2, 1, 2, 2, 3, 3, 3, 1, 1, 2, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 0, 3, 3, 3, 3, 3, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 3, 3, 3, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 2, 2, 2, 0, }; size_t GetWidthFromOpcode(Opcode opcode) { return gInstructionWidthTable[opcode]; } size_t GetWidthFromBytecode(const u2* bytecode) { size_t width = 0; if (*bytecode == kPackedSwitchSignature) { width = 4 + bytecode[1] * 2; } else if (*bytecode == kSparseSwitchSignature) { width = 2 + bytecode[1] * 4; } else if (*bytecode == kArrayDataSignature) { u2 elemWidth = bytecode[1]; u4 len = bytecode[2] | (((u4)bytecode[3]) << 16); // The plus 1 is to round up for odd size and width. width = 4 + (elemWidth * len + 1) / 2; } else { width = GetWidthFromOpcode(OpcodeFromBytecode(bytecode[0])); } return width; } // Table that maps each opcode to the instruction flags static constexpr std::array<OpcodeFlags, kNumPackedOpcodes> gOpcodeFlagsTable = { /* NOP */ kInstrCanContinue, /* MOVE */ kInstrCanContinue, /* MOVE_FROM16 */ kInstrCanContinue, /* MOVE_16 */ kInstrCanContinue, /* MOVE_WIDE */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* MOVE_WIDE_FROM16 */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* MOVE_WIDE_16 */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* MOVE_OBJECT */ kInstrCanContinue, /* MOVE_OBJECT_FROM16 */ kInstrCanContinue, /* MOVE_OBJECT_16 */ kInstrCanContinue, /* MOVE_RESULT */ kInstrCanContinue, /* MOVE_RESULT_WIDE */ kInstrCanContinue|kInstrWideRegA, /* MOVE_RESULT_OBJECT */ kInstrCanContinue, /* MOVE_EXCEPTION */ kInstrCanContinue, /* RETURN_VOID */ kInstrCanReturn, /* RETURN */ kInstrCanReturn, /* RETURN_WIDE */ kInstrCanReturn|kInstrWideRegA, /* RETURN_OBJECT */ kInstrCanReturn, /* CONST_4 */ kInstrCanContinue, /* CONST_16 */ kInstrCanContinue, /* CONST */ kInstrCanContinue, /* CONST_HIGH16 */ kInstrCanContinue, /* CONST_WIDE_16 */ kInstrCanContinue|kInstrWideRegA, /* CONST_WIDE_32 */ kInstrCanContinue|kInstrWideRegA, /* CONST_WIDE */ kInstrCanContinue|kInstrWideRegA, /* CONST_WIDE_HIGH16 */ kInstrCanContinue|kInstrWideRegA, /* CONST_STRING */ kInstrCanContinue|kInstrCanThrow, /* CONST_STRING_JUMBO */ kInstrCanContinue|kInstrCanThrow, /* CONST_CLASS */ kInstrCanContinue|kInstrCanThrow, /* MONITOR_ENTER */ kInstrCanContinue|kInstrCanThrow, /* MONITOR_EXIT */ kInstrCanContinue|kInstrCanThrow, /* CHECK_CAST */ kInstrCanContinue|kInstrCanThrow, /* INSTANCE_OF */ kInstrCanContinue|kInstrCanThrow, /* ARRAY_LENGTH */ kInstrCanContinue|kInstrCanThrow, /* NEW_INSTANCE */ kInstrCanContinue|kInstrCanThrow, /* NEW_ARRAY */ kInstrCanContinue|kInstrCanThrow, /* FILLED_NEW_ARRAY */ kInstrCanContinue|kInstrCanThrow, /* FILLED_NEW_ARRAY_RANGE */ kInstrCanContinue|kInstrCanThrow, /* FILL_ARRAY_DATA */ kInstrCanContinue, /* THROW */ kInstrCanThrow, /* GOTO */ kInstrCanBranch, /* GOTO_16 */ kInstrCanBranch, /* GOTO_32 */ kInstrCanBranch, /* PACKED_SWITCH */ kInstrCanContinue|kInstrCanSwitch, /* SPARSE_SWITCH */ kInstrCanContinue|kInstrCanSwitch, /* CMPL_FLOAT */ kInstrCanContinue, /* CMPG_FLOAT */ kInstrCanContinue, /* CMPL_DOUBLE */ kInstrCanContinue|kInstrWideRegB|kInstrWideRegC, /* CMPG_DOUBLE */ kInstrCanContinue|kInstrWideRegB|kInstrWideRegC, /* CMP_LONG */ kInstrCanContinue|kInstrWideRegB|kInstrWideRegC, /* IF_EQ */ kInstrCanContinue|kInstrCanBranch, /* IF_NE */ kInstrCanContinue|kInstrCanBranch, /* IF_LT */ kInstrCanContinue|kInstrCanBranch, /* IF_GE */ kInstrCanContinue|kInstrCanBranch, /* IF_GT */ kInstrCanContinue|kInstrCanBranch, /* IF_LE */ kInstrCanContinue|kInstrCanBranch, /* IF_EQZ */ kInstrCanContinue|kInstrCanBranch, /* IF_NEZ */ kInstrCanContinue|kInstrCanBranch, /* IF_LTZ */ kInstrCanContinue|kInstrCanBranch, /* IF_GEZ */ kInstrCanContinue|kInstrCanBranch, /* IF_GTZ */ kInstrCanContinue|kInstrCanBranch, /* IF_LEZ */ kInstrCanContinue|kInstrCanBranch, /* UNUSED_3E */ 0, /* UNUSED_3F */ 0, /* UNUSED_40 */ 0, /* UNUSED_41 */ 0, /* UNUSED_42 */ 0, /* UNUSED_43 */ 0, /* AGET */ kInstrCanContinue|kInstrCanThrow, /* AGET_WIDE */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* AGET_OBJECT */ kInstrCanContinue|kInstrCanThrow, /* AGET_BOOLEAN */ kInstrCanContinue|kInstrCanThrow, /* AGET_BYTE */ kInstrCanContinue|kInstrCanThrow, /* AGET_CHAR */ kInstrCanContinue|kInstrCanThrow, /* AGET_SHORT */ kInstrCanContinue|kInstrCanThrow, /* APUT */ kInstrCanContinue|kInstrCanThrow, /* APUT_WIDE */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* APUT_OBJECT */ kInstrCanContinue|kInstrCanThrow, /* APUT_BOOLEAN */ kInstrCanContinue|kInstrCanThrow, /* APUT_BYTE */ kInstrCanContinue|kInstrCanThrow, /* APUT_CHAR */ kInstrCanContinue|kInstrCanThrow, /* APUT_SHORT */ kInstrCanContinue|kInstrCanThrow, /* IGET */ kInstrCanContinue|kInstrCanThrow, /* IGET_WIDE */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* IGET_OBJECT */ kInstrCanContinue|kInstrCanThrow, /* IGET_BOOLEAN */ kInstrCanContinue|kInstrCanThrow, /* IGET_BYTE */ kInstrCanContinue|kInstrCanThrow, /* IGET_CHAR */ kInstrCanContinue|kInstrCanThrow, /* IGET_SHORT */ kInstrCanContinue|kInstrCanThrow, /* IPUT */ kInstrCanContinue|kInstrCanThrow, /* IPUT_WIDE */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* IPUT_OBJECT */ kInstrCanContinue|kInstrCanThrow, /* IPUT_BOOLEAN */ kInstrCanContinue|kInstrCanThrow, /* IPUT_BYTE */ kInstrCanContinue|kInstrCanThrow, /* IPUT_CHAR */ kInstrCanContinue|kInstrCanThrow, /* IPUT_SHORT */ kInstrCanContinue|kInstrCanThrow, /* SGET */ kInstrCanContinue|kInstrCanThrow, /* SGET_WIDE */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* SGET_OBJECT */ kInstrCanContinue|kInstrCanThrow, /* SGET_BOOLEAN */ kInstrCanContinue|kInstrCanThrow, /* SGET_BYTE */ kInstrCanContinue|kInstrCanThrow, /* SGET_CHAR */ kInstrCanContinue|kInstrCanThrow, /* SGET_SHORT */ kInstrCanContinue|kInstrCanThrow, /* SPUT */ kInstrCanContinue|kInstrCanThrow, /* SPUT_WIDE */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* SPUT_OBJECT */ kInstrCanContinue|kInstrCanThrow, /* SPUT_BOOLEAN */ kInstrCanContinue|kInstrCanThrow, /* SPUT_BYTE */ kInstrCanContinue|kInstrCanThrow, /* SPUT_CHAR */ kInstrCanContinue|kInstrCanThrow, /* SPUT_SHORT */ kInstrCanContinue|kInstrCanThrow, /* INVOKE_VIRTUAL */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_SUPER */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_DIRECT */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_STATIC */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_INTERFACE */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* UNUSED_73 */ 0, /* INVOKE_VIRTUAL_RANGE */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_SUPER_RANGE */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_DIRECT_RANGE */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_STATIC_RANGE */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_INTERFACE_RANGE */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* UNUSED_79 */ 0, /* UNUSED_7A */ 0, /* NEG_INT */ kInstrCanContinue, /* NOT_INT */ kInstrCanContinue, /* NEG_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* NOT_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* NEG_FLOAT */ kInstrCanContinue, /* NEG_DOUBLE */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* INT_TO_LONG */ kInstrCanContinue|kInstrWideRegA, /* INT_TO_FLOAT */ kInstrCanContinue, /* INT_TO_DOUBLE */ kInstrCanContinue|kInstrWideRegA, /* LONG_TO_INT */ kInstrCanContinue|kInstrWideRegB, /* LONG_TO_FLOAT */ kInstrCanContinue|kInstrWideRegB, /* LONG_TO_DOUBLE */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* FLOAT_TO_INT */ kInstrCanContinue, /* FLOAT_TO_LONG */ kInstrCanContinue|kInstrWideRegA, /* FLOAT_TO_DOUBLE */ kInstrCanContinue|kInstrWideRegA, /* DOUBLE_TO_INT */ kInstrCanContinue|kInstrWideRegB, /* DOUBLE_TO_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* DOUBLE_TO_FLOAT */ kInstrCanContinue|kInstrWideRegB, /* INT_TO_BYTE */ kInstrCanContinue, /* INT_TO_CHAR */ kInstrCanContinue, /* INT_TO_SHORT */ kInstrCanContinue, /* ADD_INT */ kInstrCanContinue, /* SUB_INT */ kInstrCanContinue, /* MUL_INT */ kInstrCanContinue, /* DIV_INT */ kInstrCanContinue|kInstrCanThrow, /* REM_INT */ kInstrCanContinue|kInstrCanThrow, /* AND_INT */ kInstrCanContinue, /* OR_INT */ kInstrCanContinue, /* XOR_INT */ kInstrCanContinue, /* SHL_INT */ kInstrCanContinue, /* SHR_INT */ kInstrCanContinue, /* USHR_INT */ kInstrCanContinue, /* ADD_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* SUB_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* MUL_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* DIV_LONG */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* REM_LONG */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* AND_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* OR_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* XOR_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* SHL_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* SHR_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* USHR_LONG */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* ADD_FLOAT */ kInstrCanContinue, /* SUB_FLOAT */ kInstrCanContinue, /* MUL_FLOAT */ kInstrCanContinue, /* DIV_FLOAT */ kInstrCanContinue, /* REM_FLOAT */ kInstrCanContinue, /* ADD_DOUBLE */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* SUB_DOUBLE */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* MUL_DOUBLE */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* DIV_DOUBLE */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* REM_DOUBLE */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB|kInstrWideRegC, /* ADD_INT_2ADDR */ kInstrCanContinue, /* SUB_INT_2ADDR */ kInstrCanContinue, /* MUL_INT_2ADDR */ kInstrCanContinue, /* DIV_INT_2ADDR */ kInstrCanContinue|kInstrCanThrow, /* REM_INT_2ADDR */ kInstrCanContinue|kInstrCanThrow, /* AND_INT_2ADDR */ kInstrCanContinue, /* OR_INT_2ADDR */ kInstrCanContinue, /* XOR_INT_2ADDR */ kInstrCanContinue, /* SHL_INT_2ADDR */ kInstrCanContinue, /* SHR_INT_2ADDR */ kInstrCanContinue, /* USHR_INT_2ADDR */ kInstrCanContinue, /* ADD_LONG_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* SUB_LONG_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* MUL_LONG_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* DIV_LONG_2ADDR */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA|kInstrWideRegB, /* REM_LONG_2ADDR */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA|kInstrWideRegB, /* AND_LONG_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* OR_LONG_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* XOR_LONG_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* SHL_LONG_2ADDR */ kInstrCanContinue|kInstrWideRegA, /* SHR_LONG_2ADDR */ kInstrCanContinue|kInstrWideRegA, /* USHR_LONG_2ADDR */ kInstrCanContinue|kInstrWideRegA, /* ADD_FLOAT_2ADDR */ kInstrCanContinue, /* SUB_FLOAT_2ADDR */ kInstrCanContinue, /* MUL_FLOAT_2ADDR */ kInstrCanContinue, /* DIV_FLOAT_2ADDR */ kInstrCanContinue, /* REM_FLOAT_2ADDR */ kInstrCanContinue, /* ADD_DOUBLE_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* SUB_DOUBLE_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* MUL_DOUBLE_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* DIV_DOUBLE_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* REM_DOUBLE_2ADDR */ kInstrCanContinue|kInstrWideRegA|kInstrWideRegB, /* ADD_INT_LIT16 */ kInstrCanContinue, /* RSUB_INT */ kInstrCanContinue, /* MUL_INT_LIT16 */ kInstrCanContinue, /* DIV_INT_LIT16 */ kInstrCanContinue|kInstrCanThrow, /* REM_INT_LIT16 */ kInstrCanContinue|kInstrCanThrow, /* AND_INT_LIT16 */ kInstrCanContinue, /* OR_INT_LIT16 */ kInstrCanContinue, /* XOR_INT_LIT16 */ kInstrCanContinue, /* ADD_INT_LIT8 */ kInstrCanContinue, /* RSUB_INT_LIT8 */ kInstrCanContinue, /* MUL_INT_LIT8 */ kInstrCanContinue, /* DIV_INT_LIT8 */ kInstrCanContinue|kInstrCanThrow, /* REM_INT_LIT8 */ kInstrCanContinue|kInstrCanThrow, /* AND_INT_LIT8 */ kInstrCanContinue, /* OR_INT_LIT8 */ kInstrCanContinue, /* XOR_INT_LIT8 */ kInstrCanContinue, /* SHL_INT_LIT8 */ kInstrCanContinue, /* SHR_INT_LIT8 */ kInstrCanContinue, /* USHR_INT_LIT8 */ kInstrCanContinue, /* IGET_VOLATILE */ kInstrCanContinue|kInstrCanThrow, /* IPUT_VOLATILE */ kInstrCanContinue|kInstrCanThrow, /* SGET_VOLATILE */ kInstrCanContinue|kInstrCanThrow, /* SPUT_VOLATILE */ kInstrCanContinue|kInstrCanThrow, /* IGET_OBJECT_VOLATILE */ kInstrCanContinue|kInstrCanThrow, /* IGET_WIDE_VOLATILE */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* IPUT_WIDE_VOLATILE */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* SGET_WIDE_VOLATILE */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* SPUT_WIDE_VOLATILE */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* BREAKPOINT */ 0, /* THROW_VERIFICATION_ERROR */ kInstrCanThrow, /* EXECUTE_INLINE */ kInstrCanContinue|kInstrCanThrow, /* EXECUTE_INLINE_RANGE */ kInstrCanContinue|kInstrCanThrow, /* INVOKE_OBJECT_INIT_RANGE */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* RETURN_VOID_BARRIER */ kInstrCanReturn, /* IGET_QUICK */ kInstrCanContinue|kInstrCanThrow, /* IGET_WIDE_QUICK */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* IGET_OBJECT_QUICK */ kInstrCanContinue|kInstrCanThrow, /* IPUT_QUICK */ kInstrCanContinue|kInstrCanThrow, /* IPUT_WIDE_QUICK */ kInstrCanContinue|kInstrCanThrow|kInstrWideRegA, /* IPUT_OBJECT_QUICK */ kInstrCanContinue|kInstrCanThrow, /* INVOKE_VIRTUAL_QUICK */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_VIRTUAL_QUICK_RANGE */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_SUPER_QUICK */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* INVOKE_SUPER_QUICK_RANGE */ kInstrCanContinue|kInstrCanThrow|kInstrInvoke, /* IPUT_OBJECT_VOLATILE */ kInstrCanContinue|kInstrCanThrow, /* SGET_OBJECT_VOLATILE */ kInstrCanContinue|kInstrCanThrow, /* SPUT_OBJECT_VOLATILE */ kInstrCanContinue|kInstrCanThrow, /* UNUSED_FF */ 0, }; // Table that maps each opcode to the instruction format static constexpr std::array<InstructionFormat, kNumPackedOpcodes> gInstructionFormatTable = { kFmt10x, kFmt12x, kFmt22x, kFmt32x, kFmt12x, kFmt22x, kFmt32x, kFmt12x, kFmt22x, kFmt32x, kFmt11x, kFmt11x, kFmt11x, kFmt11x, kFmt10x, kFmt11x, kFmt11x, kFmt11x, kFmt11n, kFmt21s, kFmt31i, kFmt21h, kFmt21s, kFmt31i, kFmt51l, kFmt21h, kFmt21c, kFmt31c, kFmt21c, kFmt11x, kFmt11x, kFmt21c, kFmt22c, kFmt12x, kFmt21c, kFmt22c, kFmt35c, kFmt3rc, kFmt31t, kFmt11x, kFmt10t, kFmt20t, kFmt30t, kFmt31t, kFmt31t, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt22t, kFmt22t, kFmt22t, kFmt22t, kFmt22t, kFmt22t, kFmt21t, kFmt21t, kFmt21t, kFmt21t, kFmt21t, kFmt21t, kFmt00x, kFmt00x, kFmt00x, kFmt00x, kFmt00x, kFmt00x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt22c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt21c, kFmt35c, kFmt35c, kFmt35c, kFmt35c, kFmt35c, kFmt00x, kFmt3rc, kFmt3rc, kFmt3rc, kFmt3rc, kFmt3rc, kFmt00x, kFmt00x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt23x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt12x, kFmt22s, kFmt22s, kFmt22s, kFmt22s, kFmt22s, kFmt22s, kFmt22s, kFmt22s, kFmt22b, kFmt22b, kFmt22b, kFmt22b, kFmt22b, kFmt22b, kFmt22b, kFmt22b, kFmt22b, kFmt22b, kFmt22b, kFmt22c, kFmt22c, kFmt21c, kFmt21c, kFmt22c, kFmt22c, kFmt22c, kFmt21c, kFmt21c, kFmt00x, kFmt20bc, kFmt35mi, kFmt3rmi, kFmt35c, kFmt10x, kFmt22cs, kFmt22cs, kFmt22cs, kFmt22cs, kFmt22cs, kFmt22cs, kFmt35ms, kFmt3rms, kFmt35ms, kFmt3rms, kFmt22c, kFmt21c, kFmt21c, kFmt00x, }; InstructionFormat GetFormatFromOpcode(Opcode opcode) { return gInstructionFormatTable[opcode]; } OpcodeFlags GetFlagsFromOpcode(Opcode opcode) { return gOpcodeFlagsTable[opcode]; } // Dalvik opcode names. static constexpr std::array<const char*, kNumPackedOpcodes> gOpcodeNames = { "nop", "move", "move/from16", "move/16", "move-wide", "move-wide/from16", "move-wide/16", "move-object", "move-object/from16", "move-object/16", "move-result", "move-result-wide", "move-result-object", "move-exception", "return-void", "return", "return-wide", "return-object", "const/4", "const/16", "const", "const/high16", "const-wide/16", "const-wide/32", "const-wide", "const-wide/high16", "const-string", "const-string/jumbo", "const-class", "monitor-enter", "monitor-exit", "check-cast", "instance-of", "array-length", "new-instance", "new-array", "filled-new-array", "filled-new-array/range", "fill-array-data", "throw", "goto", "goto/16", "goto/32", "packed-switch", "sparse-switch", "cmpl-float", "cmpg-float", "cmpl-double", "cmpg-double", "cmp-long", "if-eq", "if-ne", "if-lt", "if-ge", "if-gt", "if-le", "if-eqz", "if-nez", "if-ltz", "if-gez", "if-gtz", "if-lez", "unused-3e", "unused-3f", "unused-40", "unused-41", "unused-42", "unused-43", "aget", "aget-wide", "aget-object", "aget-boolean", "aget-byte", "aget-char", "aget-short", "aput", "aput-wide", "aput-object", "aput-boolean", "aput-byte", "aput-char", "aput-short", "iget", "iget-wide", "iget-object", "iget-boolean", "iget-byte", "iget-char", "iget-short", "iput", "iput-wide", "iput-object", "iput-boolean", "iput-byte", "iput-char", "iput-short", "sget", "sget-wide", "sget-object", "sget-boolean", "sget-byte", "sget-char", "sget-short", "sput", "sput-wide", "sput-object", "sput-boolean", "sput-byte", "sput-char", "sput-short", "invoke-virtual", "invoke-super", "invoke-direct", "invoke-static", "invoke-interface", "unused-73", "invoke-virtual/range", "invoke-super/range", "invoke-direct/range", "invoke-static/range", "invoke-interface/range", "unused-79", "unused-7a", "neg-int", "not-int", "neg-long", "not-long", "neg-float", "neg-double", "int-to-long", "int-to-float", "int-to-double", "long-to-int", "long-to-float", "long-to-double", "float-to-int", "float-to-long", "float-to-double", "double-to-int", "double-to-long", "double-to-float", "int-to-byte", "int-to-char", "int-to-short", "add-int", "sub-int", "mul-int", "div-int", "rem-int", "and-int", "or-int", "xor-int", "shl-int", "shr-int", "ushr-int", "add-long", "sub-long", "mul-long", "div-long", "rem-long", "and-long", "or-long", "xor-long", "shl-long", "shr-long", "ushr-long", "add-float", "sub-float", "mul-float", "div-float", "rem-float", "add-double", "sub-double", "mul-double", "div-double", "rem-double", "add-int/2addr", "sub-int/2addr", "mul-int/2addr", "div-int/2addr", "rem-int/2addr", "and-int/2addr", "or-int/2addr", "xor-int/2addr", "shl-int/2addr", "shr-int/2addr", "ushr-int/2addr", "add-long/2addr", "sub-long/2addr", "mul-long/2addr", "div-long/2addr", "rem-long/2addr", "and-long/2addr", "or-long/2addr", "xor-long/2addr", "shl-long/2addr", "shr-long/2addr", "ushr-long/2addr", "add-float/2addr", "sub-float/2addr", "mul-float/2addr", "div-float/2addr", "rem-float/2addr", "add-double/2addr", "sub-double/2addr", "mul-double/2addr", "div-double/2addr", "rem-double/2addr", "add-int/lit16", "rsub-int", "mul-int/lit16", "div-int/lit16", "rem-int/lit16", "and-int/lit16", "or-int/lit16", "xor-int/lit16", "add-int/lit8", "rsub-int/lit8", "mul-int/lit8", "div-int/lit8", "rem-int/lit8", "and-int/lit8", "or-int/lit8", "xor-int/lit8", "shl-int/lit8", "shr-int/lit8", "ushr-int/lit8", "+iget-volatile", "+iput-volatile", "+sget-volatile", "+sput-volatile", "+iget-object-volatile", "+iget-wide-volatile", "+iput-wide-volatile", "+sget-wide-volatile", "+sput-wide-volatile", "^breakpoint", "^throw-verification-error", "+execute-inline", "+execute-inline/range", "+invoke-object-init/range", "+return-void-barrier", "+iget-quick", "+iget-wide-quick", "+iget-object-quick", "+iput-quick", "+iput-wide-quick", "+iput-object-quick", "+invoke-virtual-quick", "+invoke-virtual-quick/range", "+invoke-super-quick", "+invoke-super-quick/range", "+iput-object-volatile", "+sget-object-volatile", "+sput-object-volatile", "unused-ff", }; const char* GetOpcodeName(Opcode opcode) { return gOpcodeNames[opcode]; } // Helpers for DecodeInstruction() static u4 InstA(u2 inst) { return (inst >> 8) & 0x0f; } static u4 InstB(u2 inst) { return inst >> 12; } static u4 InstAA(u2 inst) { return inst >> 8; } // Helper for DecodeInstruction() static u4 FetchU4(const u2* ptr) { return ptr[0] | (u4(ptr[1]) << 16); } // Helper for DecodeInstruction() static u8 FetchU8(const u2* ptr) { return FetchU4(ptr) | (u8(FetchU4(ptr + 2)) << 32); } // Decode a Dalvik bytecode and extract the individual fields Instruction DecodeInstruction(const u2* bytecode) { u2 inst = bytecode[0]; Opcode opcode = OpcodeFromBytecode(inst); InstructionFormat format = GetFormatFromOpcode(opcode); Instruction dec = {}; dec.opcode = opcode; switch (format) { case kFmt10x: // op break; case kFmt12x: // op vA, vB dec.vA = InstA(inst); dec.vB = InstB(inst); break; case kFmt11n: // op vA, #+B dec.vA = InstA(inst); dec.vB = s4(InstB(inst) << 28) >> 28; // sign extend 4-bit value break; case kFmt11x: // op vAA dec.vA = InstAA(inst); break; case kFmt10t: // op +AA dec.vA = s1(InstAA(inst)); // sign-extend 8-bit value break; case kFmt20t: // op +AAAA dec.vA = s2(bytecode[1]); // sign-extend 16-bit value break; case kFmt20bc: // [opt] op AA, thing@BBBB case kFmt21c: // op vAA, thing@BBBB case kFmt22x: // op vAA, vBBBB dec.vA = InstAA(inst); dec.vB = bytecode[1]; break; case kFmt21s: // op vAA, #+BBBB case kFmt21t: // op vAA, +BBBB dec.vA = InstAA(inst); dec.vB = s2(bytecode[1]); // sign-extend 16-bit value break; case kFmt21h: // op vAA, #+BBBB0000[00000000] dec.vA = InstAA(inst); // The value should be treated as right-zero-extended, but we don't // actually do that here. Among other things, we don't know if it's // the top bits of a 32- or 64-bit value. dec.vB = bytecode[1]; break; case kFmt23x: // op vAA, vBB, vCC dec.vA = InstAA(inst); dec.vB = bytecode[1] & 0xff; dec.vC = bytecode[1] >> 8; break; case kFmt22b: // op vAA, vBB, #+CC dec.vA = InstAA(inst); dec.vB = bytecode[1] & 0xff; dec.vC = s1(bytecode[1] >> 8); // sign-extend 8-bit value break; case kFmt22s: // op vA, vB, #+CCCC case kFmt22t: // op vA, vB, +CCCC dec.vA = InstA(inst); dec.vB = InstB(inst); dec.vC = s2(bytecode[1]); // sign-extend 16-bit value break; case kFmt22c: // op vA, vB, thing@CCCC case kFmt22cs: // [opt] op vA, vB, field offset CCCC dec.vA = InstA(inst); dec.vB = InstB(inst); dec.vC = bytecode[1]; break; case kFmt30t: // op +AAAAAAAA dec.vA = FetchU4(bytecode + 1); break; case kFmt31t: // op vAA, +BBBBBBBB case kFmt31c: // op vAA, string@BBBBBBBB dec.vA = InstAA(inst); dec.vB = FetchU4(bytecode + 1); break; case kFmt32x: // op vAAAA, vBBBB dec.vA = bytecode[1]; dec.vB = bytecode[2]; break; case kFmt31i: // op vAA, #+BBBBBBBB dec.vA = InstAA(inst); dec.vB = FetchU4(bytecode + 1); break; case kFmt35c: // op {vC, vD, vE, vF, vG}, thing@BBBB case kFmt35ms: // [opt] invoke-virtual+super case kFmt35mi: // [opt] inline invoke { dec.vA = InstB(inst); // This is labeled A in the spec. dec.vB = bytecode[1]; u2 regList = bytecode[2]; // Copy the argument registers into the arg[] array, and // also copy the first argument (if any) into vC. (The // Instruction structure doesn't have separate // fields for {vD, vE, vF, vG}, so there's no need to make // copies of those.) Note that cases 5..2 fall through. switch (dec.vA) { case 5: // A fifth arg is verboten for inline invokes CHECK(format != kFmt35mi); // Per note at the top of this format decoder, the // fifth argument comes from the A field in the // instruction, but it's labeled G in the spec. dec.arg[4] = InstA(inst); // fallthrough case 4: dec.arg[3] = (regList >> 12) & 0x0f; // fallthrough case 3: dec.arg[2] = (regList >> 8) & 0x0f; // fallthrough case 2: dec.arg[1] = (regList >> 4) & 0x0f; // fallthrough case 1: dec.vC = dec.arg[0] = regList & 0x0f; // fallthrough case 0: // Valid, but no need to do anything break; default: CHECK(!"Invalid arg count in 35c/35ms/35mi"); break; } } break; case kFmt3rc: // op {vCCCC .. v(CCCC+AA-1)}, meth@BBBB case kFmt3rms: // [opt] invoke-virtual+super/range case kFmt3rmi: // [opt] execute-inline/range dec.vA = InstAA(inst); dec.vB = bytecode[1]; dec.vC = bytecode[2]; break; case kFmt51l: // op vAA, #+BBBBBBBBBBBBBBBB dec.vA = InstAA(inst); dec.vB_wide = FetchU8(bytecode + 1); break; default: FATAL("Can't decode unexpected format 0x%02x", format); } return dec; } } // namespace dex
42.51559
113
0.606197
johnlee175
2449ed2b00ba32f672b59471cecc210d30d65993
5,335
cpp
C++
src/WINNT/afsrdr/tools/settrace/settrace.cpp
jakllsch/openafs
e739eaa650ee30dcce54d05908b062839eafbf73
[ "BSD-3-Clause" ]
54
2015-01-26T02:12:37.000Z
2022-02-09T07:00:34.000Z
src/WINNT/afsrdr/tools/settrace/settrace.cpp
jakllsch/openafs
e739eaa650ee30dcce54d05908b062839eafbf73
[ "BSD-3-Clause" ]
5
2016-08-12T04:37:29.000Z
2020-12-10T16:46:06.000Z
src/WINNT/afsrdr/tools/settrace/settrace.cpp
jakllsch/openafs
e739eaa650ee30dcce54d05908b062839eafbf73
[ "BSD-3-Clause" ]
38
2015-07-30T13:27:25.000Z
2022-01-27T06:45:13.000Z
/* * Copyright (c) 2008, 2009, 2010, 2011 Kernel Drivers, LLC. * Copyright (c) 2009, 2010, 2011 Your File System, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, * this list of conditions and the following disclaimer in the * documentation * and/or other materials provided with the distribution. * - Neither the names of Kernel Drivers, LLC and Your File System, Inc. * nor the names of their contributors may be used to endorse or promote * products derived from this software without specific prior written * permission from Kernel Drivers, LLC and Your File System, Inc. * * 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. */ #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0500 #endif #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <shlwapi.h> #include <devioctl.h> #include "AFSUserDefines.h" #include "AFSUserIoctl.h" #include "AFSUserStructs.h" void usage( void) { printf("SetTrace /l <Logging level> | /s <Subsystem> | /b <Buffer size in KB> | /f <debug Flags>\n"); } int main(int argc, char* argv[]) { ULONG rc = 0; DWORD bytesReturned = 0; HANDLE hControlDevice = NULL; DWORD dwError = 0; AFSTraceConfigCB stConfig; int dwLevel = -1, dwSystem = -1, dwBufferLen = -1, dwFlags = -1; int dwIndex; if( argc < 3) { usage(); return 1; } hControlDevice = CreateFile( AFS_SYMLINK, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); if( hControlDevice == INVALID_HANDLE_VALUE) { printf( "SetTrace: Failed to open control device error: %d\n", GetLastError()); return 2; } dwIndex = 1; while( dwIndex < argc) { if( _strcmpi(argv[ dwIndex], "/l") == 0) { if ( !StrToIntExA( argv[ ++dwIndex], STIF_SUPPORT_HEX, &dwLevel)) { printf("SetTrace Failed to parse parameter %s\n", argv[ dwIndex]); dwError = 1; break; } } else if( _strcmpi(argv[ dwIndex], "/s") == 0) { if ( !StrToIntExA( argv[ ++dwIndex], STIF_SUPPORT_HEX, &dwSystem)) { printf("SetTrace Failed to parse parameter %s\n", argv[ dwIndex]); dwError = 1; break; } } else if( _strcmpi(argv[ dwIndex], "/b") == 0) { if ( !StrToIntExA( argv[ ++dwIndex], STIF_SUPPORT_HEX, &dwBufferLen)) { printf("SetTrace Failed to parse parameter %s\n", argv[ dwIndex]); dwError = 1; break; } } else if( _strcmpi(argv[ dwIndex], "/d") == 0 || _strcmpi(argv[ dwIndex], "/f") == 0) { if ( !StrToIntExA( argv[ ++dwIndex], STIF_SUPPORT_HEX, &dwFlags)) { printf("SetTrace Failed to parse parameter %s\n", argv[ dwIndex]); dwError = 1; break; } } else { usage(); dwError = 1; break; } dwIndex++; } if ( dwError) { rc = 4; goto cleanup; } stConfig.Subsystem = dwSystem; stConfig.TraceLevel = dwLevel; stConfig.TraceBufferLength = dwBufferLen; stConfig.DebugFlags = dwFlags; dwError = DeviceIoControl( hControlDevice, IOCTL_AFS_CONFIGURE_DEBUG_TRACE, &stConfig, sizeof( AFSTraceConfigCB), NULL, 0, &bytesReturned, NULL); if( !dwError) { printf( "SetTrace Failed to set attributes %d\n", GetLastError()); rc = 3; } else { printf( "SetTrace: Successfully set parameters\n"); } cleanup: CloseHandle( hControlDevice); return rc; }
26.280788
105
0.561575
jakllsch
244d67f3a543162ec8841d0659c81427b0abcf37
10,823
cc
C++
runtime/vm/resolver.cc
annagrin/sdk
dfce72bbf9bf359ecd810964259978e24c55e237
[ "BSD-3-Clause" ]
2
2020-03-09T11:45:05.000Z
2021-06-08T12:06:05.000Z
runtime/vm/resolver.cc
annagrin/sdk
dfce72bbf9bf359ecd810964259978e24c55e237
[ "BSD-3-Clause" ]
null
null
null
runtime/vm/resolver.cc
annagrin/sdk
dfce72bbf9bf359ecd810964259978e24c55e237
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/resolver.h" #include "vm/dart_entry.h" #include "vm/flags.h" #include "vm/isolate.h" #include "vm/log.h" #include "vm/object.h" #include "vm/object_store.h" #include "vm/symbols.h" namespace dart { DEFINE_FLAG(bool, trace_resolving, false, "Trace resolving."); // The actual names of named arguments are not checked by the dynamic resolver, // but by the method entry code. It is important that the dynamic resolver // checks that no named arguments are passed to a method that does not accept // them, since the entry code of such a method does not check for named // arguments. The dynamic resolver actually checks that a valid number of named // arguments is passed in. RawFunction* Resolver::ResolveDynamic(const Instance& receiver, const String& function_name, const ArgumentsDescriptor& args_desc) { // Figure out type of receiver first. const Class& cls = Class::Handle(receiver.clazz()); return ResolveDynamicForReceiverClass(cls, function_name, args_desc); } RawFunction* Resolver::ResolveDynamicForReceiverClass( const Class& receiver_class, const String& function_name, const ArgumentsDescriptor& args_desc, bool allow_add) { Thread* thread = Thread::Current(); Zone* zone = thread->zone(); Function& function = Function::Handle( zone, ResolveDynamicAnyArgs(zone, receiver_class, function_name, allow_add)); if (function.IsNull() || !function.AreValidArguments(NNBDMode::kLegacyLib, args_desc, NULL)) { // Return a null function to signal to the upper levels to dispatch to // "noSuchMethod" function. if (FLAG_trace_resolving) { String& error_message = String::Handle(zone, Symbols::New(thread, "function not found")); if (!function.IsNull()) { // Obtain more detailed error message. function.AreValidArguments(NNBDMode::kLegacyLib, args_desc, &error_message); } THR_Print("ResolveDynamic error '%s': %s.\n", function_name.ToCString(), error_message.ToCString()); } return Function::null(); } return function.raw(); } RawFunction* Resolver::ResolveDynamicAnyArgs(Zone* zone, const Class& receiver_class, const String& function_name, bool allow_add) { Class& cls = Class::Handle(zone, receiver_class.raw()); if (FLAG_trace_resolving) { THR_Print("ResolveDynamic '%s' for class %s\n", function_name.ToCString(), String::Handle(zone, cls.Name()).ToCString()); } Function& function = Function::Handle(zone); String& demangled = String::Handle(zone); const bool is_getter = Field::IsGetterName(function_name); if (is_getter) { demangled = Field::NameFromGetter(function_name); } if (Function::IsDynamicInvocationForwarderName(function_name)) { demangled = Function::DemangleDynamicInvocationForwarderName(function_name); #ifdef DART_PRECOMPILED_RUNTIME // In precompiled mode, the non-dynamic version of the function may be // tree-shaken away, so can't necessarily resolve the demanged name. while (!cls.IsNull()) { function = cls.GetInvocationDispatcher( function_name, Array::null_array(), RawFunction::kDynamicInvocationForwarder, /*create_if_absent=*/false); if (!function.IsNull()) break; cls = cls.SuperClass(); } // Some functions don't require dynamic invocation forwarders, for example // if there are no parameters or all the parameters are marked // `generic-covariant` (meaning there's no work for the dynamic invocation // forwarder to do, see `kernel::DynamicInvocationForwarder`). For these // functions, we won't have built a `dyn:` version, but it's safe to just // return the original version directly. return !function.IsNull() ? function.raw() : ResolveDynamicAnyArgs(zone, receiver_class, demangled, allow_add); #else function = ResolveDynamicAnyArgs(zone, receiver_class, demangled, allow_add); return function.IsNull() ? function.raw() : function.GetDynamicInvocationForwarder( function_name, allow_add); #endif } // Now look for an instance function whose name matches function_name // in the class. while (!cls.IsNull()) { function = cls.LookupDynamicFunction(function_name); if (!function.IsNull()) { return function.raw(); } // Getter invocation might actually be a method extraction. if (is_getter && function.IsNull()) { function = cls.LookupDynamicFunction(demangled); if (!function.IsNull()) { if (allow_add && FLAG_lazy_dispatchers) { // We were looking for the getter but found a method with the same // name. Create a method extractor and return it. // The extractor does not exist yet, so using GetMethodExtractor is // not necessary here. function = function.CreateMethodExtractor(function_name); return function.raw(); } else { return Function::null(); } } } cls = cls.SuperClass(); } return function.raw(); } RawFunction* Resolver::ResolveStatic(const Library& library, const String& class_name, const String& function_name, intptr_t type_args_len, intptr_t num_arguments, const Array& argument_names) { ASSERT(!library.IsNull()); Function& function = Function::Handle(); if (class_name.IsNull() || (class_name.Length() == 0)) { // Check if we are referring to a top level function. const Object& object = Object::Handle(library.ResolveName(function_name)); if (!object.IsNull() && object.IsFunction()) { function ^= object.raw(); if (!function.AreValidArguments(NNBDMode::kLegacyLib, type_args_len, num_arguments, argument_names, NULL)) { if (FLAG_trace_resolving) { String& error_message = String::Handle(); // Obtain more detailed error message. function.AreValidArguments(NNBDMode::kLegacyLib, type_args_len, num_arguments, argument_names, &error_message); THR_Print("ResolveStatic error '%s': %s.\n", function_name.ToCString(), error_message.ToCString()); } function = Function::null(); } } else { if (FLAG_trace_resolving) { THR_Print("ResolveStatic error: function '%s' not found.\n", function_name.ToCString()); } } } else { // Lookup class_name in the library's class dictionary to get at // the dart class object. If class_name is not found in the dictionary // ResolveStatic will return a NULL function object. const Class& cls = Class::Handle(library.LookupClass(class_name)); if (!cls.IsNull()) { function = ResolveStatic(cls, function_name, type_args_len, num_arguments, argument_names); } if (FLAG_trace_resolving && function.IsNull()) { THR_Print("ResolveStatic error: function '%s.%s' not found.\n", class_name.ToCString(), function_name.ToCString()); } } return function.raw(); } RawFunction* Resolver::ResolveStatic(const Class& cls, const String& function_name, intptr_t type_args_len, intptr_t num_arguments, const Array& argument_names) { ASSERT(!cls.IsNull()); if (FLAG_trace_resolving) { THR_Print("ResolveStatic '%s'\n", function_name.ToCString()); } const Function& function = Function::Handle(cls.LookupStaticFunction(function_name)); if (function.IsNull() || !function.AreValidArguments(NNBDMode::kLegacyLib, type_args_len, num_arguments, argument_names, NULL)) { // Return a null function to signal to the upper levels to throw a // resolution error or maybe throw the error right here. if (FLAG_trace_resolving) { String& error_message = String::Handle(String::New("function not found")); if (!function.IsNull()) { // Obtain more detailed error message. function.AreValidArguments(NNBDMode::kLegacyLib, type_args_len, num_arguments, argument_names, &error_message); } THR_Print("ResolveStatic error '%s': %s.\n", function_name.ToCString(), error_message.ToCString()); } return Function::null(); } return function.raw(); } RawFunction* Resolver::ResolveStaticAllowPrivate(const Class& cls, const String& function_name, intptr_t type_args_len, intptr_t num_arguments, const Array& argument_names) { ASSERT(!cls.IsNull()); if (FLAG_trace_resolving) { THR_Print("ResolveStaticAllowPrivate '%s'\n", function_name.ToCString()); } const Function& function = Function::Handle(cls.LookupStaticFunctionAllowPrivate(function_name)); if (function.IsNull() || !function.AreValidArguments(NNBDMode::kLegacyLib, type_args_len, num_arguments, argument_names, NULL)) { // Return a null function to signal to the upper levels to throw a // resolution error or maybe throw the error right here. if (FLAG_trace_resolving) { String& error_message = String::Handle(String::New("function not found")); if (!function.IsNull()) { // Obtain more detailed error message. function.AreValidArguments(NNBDMode::kLegacyLib, type_args_len, num_arguments, argument_names, &error_message); } THR_Print("ResolveStaticAllowPrivate error '%s': %s.\n", function_name.ToCString(), error_message.ToCString()); } return Function::null(); } return function.raw(); } } // namespace dart
42.443137
80
0.61397
annagrin
244da09164ff9cfabb3cb29e67832566c39f0107
1,039
cpp
C++
src/3D/Face3D.cpp
FloydATC/Deep
856914d7e99778df094541361e8d98b9f3ce8a06
[ "CC0-1.0" ]
null
null
null
src/3D/Face3D.cpp
FloydATC/Deep
856914d7e99778df094541361e8d98b9f3ce8a06
[ "CC0-1.0" ]
null
null
null
src/3D/Face3D.cpp
FloydATC/Deep
856914d7e99778df094541361e8d98b9f3ce8a06
[ "CC0-1.0" ]
null
null
null
#include "Face3D.h" Face3D::Face3D(Vertex3D* v1, Vertex3D* v2, Vertex3D* v3) { //ctor vertices.push_back(v1); vertices.push_back(v2); vertices.push_back(v3); calc_normal(); calc_center(); adjacent = { -1, -1, -1 }; } Face3D::~Face3D() { //dtor } Vector3 Face3D::calc_normal() { // Compute vertex normals for a flat surface //For each triangle ABC // n := normalize(cross(B-A, C-A)) // A.n := n // B.n := n // C.n := n Vector3 ba = vertices[1]->v - vertices[0]->v; Vector3 ca = vertices[2]->v - vertices[0]->v; this->normal = ba.cross(ca).normalize(); return this->normal; } Vector3 Face3D::calc_center() { // Compute average position of the three vertices this->center = (vertices[0]->v + vertices[1]->v + vertices[2]->v) / 3.0; return this->center; } Edge3D Face3D::getEdge(uint8_t edge_no) { return Edge3D(this->vertices[edge_no]->v, this->vertices[(edge_no+1)%3]->v); } void Face3D::setAdjacentFace(uint8_t edge_no, uint32_t face_id) { this->adjacent[edge_no] = face_id; }
18.553571
78
0.637151
FloydATC
244da2fbf3de12c406a0160c5777f5c9f7a87d27
879
cpp
C++
src/engine/Demo.cpp
wsmind/leaf
2a421515ef667a77c36fd852e59aedb677ab734c
[ "MIT" ]
18
2017-01-11T22:09:07.000Z
2022-02-02T03:20:23.000Z
src/engine/Demo.cpp
wsmind/leaf
2a421515ef667a77c36fd852e59aedb677ab734c
[ "MIT" ]
13
2016-08-04T18:29:14.000Z
2018-11-21T19:08:11.000Z
src/engine/Demo.cpp
wsmind/leaf
2a421515ef667a77c36fd852e59aedb677ab734c
[ "MIT" ]
1
2018-11-20T15:24:53.000Z
2018-11-20T15:24:53.000Z
#include <engine/Demo.h> #include <cassert> #include <engine/resource/ResourceManager.h> #include <engine/scene/Scene.h> #include <cJSON/cJSON.h> const std::string Demo::resourceClassName = "Demo"; const std::string Demo::defaultResourceData = "{\"scenes\": []}"; void Demo::load(const unsigned char *buffer, size_t size) { cJSON *json = cJSON_Parse((const char *)buffer); cJSON *scenesJson = cJSON_GetObjectItem(json, "scenes"); cJSON *sceneJson = scenesJson->child; while (sceneJson) { Scene *scene = ResourceManager::getInstance()->requestResource<Scene>(sceneJson->valuestring); this->scenes.push_back(scene); sceneJson = sceneJson->next; } cJSON_Delete(json); } void Demo::unload() { for (auto scene : this->scenes) ResourceManager::getInstance()->releaseResource(scene); this->scenes.clear(); }
23.756757
102
0.676906
wsmind
245322917e3c4ac189437cfcc7ebda7edc618771
2,165
cpp
C++
logdevice/common/SlowStorageTasksTracer.cpp
SimonKinds/LogDevice
fc9ac2fccb6faa3292b2b0a610a9eb77fd445824
[ "BSD-3-Clause" ]
1
2018-10-17T06:49:04.000Z
2018-10-17T06:49:04.000Z
logdevice/common/SlowStorageTasksTracer.cpp
msdgwzhy6/LogDevice
bc2491b7dfcd129e25490c7d5321d3d701f53ac4
[ "BSD-3-Clause" ]
null
null
null
logdevice/common/SlowStorageTasksTracer.cpp
msdgwzhy6/LogDevice
bc2491b7dfcd129e25490c7d5321d3d701f53ac4
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/common/SlowStorageTasksTracer.h" #include "logdevice/common/configuration/Log.h" #include <algorithm> namespace facebook { namespace logdevice { SlowStorageTasksTracer::SlowStorageTasksTracer( std::shared_ptr<TraceLogger> logger) : SampledTracer(std::move(logger)) {} void SlowStorageTasksTracer::traceStorageTask( const StorageTaskDebugInfo& info) { auto sample_builder = [&]() { auto sample = std::make_unique<TraceSample>(); sample->addIntValue("shard_id", info.shard_id); sample->addNormalValue("task_priority", info.priority); sample->addNormalValue("thread_type", info.thread_type); sample->addNormalValue("task_type", info.task_type); sample->addIntValue("enqueue_time", info.enqueue_time.count()); sample->addNormalValue("durability", info.durability); if (info.log_id) { sample->addNormalValue( "log_id", folly::to<std::string>(info.log_id.value().val())); } if (info.lsn) { sample->addNormalValue("lsn", folly::to<std::string>(info.lsn.value())); } if (info.client_address) { sample->addNormalValue( "client_address", info.client_address.value().toStringNoPort()); } if (info.execution_start_time) { sample->addIntValue( "execution_start_time", info.execution_start_time.value().count()); } if (info.execution_end_time) { sample->addIntValue( "execution_end_time", info.execution_end_time.value().count()); } if (info.client_id) { sample->addNormalValue("client_id", info.client_id.value().toString()); } if (info.node_id) { sample->addNormalValue("node_id", info.node_id.value().toString()); } if (info.extra_info) { sample->addNormalValue("extra_info", info.extra_info.value()); } return sample; }; publish(SLOW_STORAGE_TASKS_TRACER, sample_builder); } }} // namespace facebook::logdevice
32.313433
78
0.68545
SimonKinds
24594fbb7ff3fa127391fb572484b90cf630ff2c
3,207
cc
C++
components/metrics/metrics_upload_scheduler.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/metrics/metrics_upload_scheduler.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/metrics/metrics_upload_scheduler.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/metrics/metrics_upload_scheduler.h" #include <stdint.h> #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "build/build_config.h" #include "components/metrics/metrics_scheduler.h" namespace metrics { namespace { // When uploading metrics to the server fails, we progressively wait longer and // longer before sending the next log. This backoff process helps reduce load // on a server that is having issues. // The following is the multiplier we use to expand that inter-log duration. const double kBackoffMultiplier = 2; // The maximum backoff interval in hours. const int kMaxBackoffIntervalHours = 24; // Minutes to wait if we are unable to upload due to data usage cap. const int kOverDataUsageIntervalMinutes = 5; // Increases the upload interval each time it's called, to handle the case // where the server is having issues. base::TimeDelta BackOffUploadInterval(base::TimeDelta interval) { DCHECK_GT(kBackoffMultiplier, 1.0); interval = base::TimeDelta::FromMicroseconds(static_cast<int64_t>( kBackoffMultiplier * interval.InMicroseconds())); base::TimeDelta max_interval = base::TimeDelta::FromHours(kMaxBackoffIntervalHours); if (interval > max_interval || interval.InSeconds() < 0) { interval = max_interval; } return interval; } // Time delay after a log is uploaded successfully before attempting another. // On mobile, keeping the radio on is very expensive, so prefer to keep this // short and send in bursts. base::TimeDelta GetUnsentLogsInterval() { return base::TimeDelta::FromSeconds(3); } // Initial time delay after a log uploaded fails before retrying it. base::TimeDelta GetInitialBackoffInterval() { return base::TimeDelta::FromMinutes(5); } } // namespace MetricsUploadScheduler::MetricsUploadScheduler( const base::RepeatingClosure& upload_callback, bool fast_startup_for_testing) : MetricsScheduler(upload_callback, fast_startup_for_testing), unsent_logs_interval_(GetUnsentLogsInterval()), initial_backoff_interval_(GetInitialBackoffInterval()), backoff_interval_(initial_backoff_interval_) {} MetricsUploadScheduler::~MetricsUploadScheduler() {} void MetricsUploadScheduler::UploadFinished(bool server_is_healthy) { // If the server is having issues, back off. Otherwise, reset to default // (unless there are more logs to send, in which case the next upload should // happen sooner). if (!server_is_healthy) { TaskDone(backoff_interval_); backoff_interval_ = BackOffUploadInterval(backoff_interval_); } else { backoff_interval_ = initial_backoff_interval_; TaskDone(unsent_logs_interval_); } } void MetricsUploadScheduler::StopAndUploadCancelled() { Stop(); TaskDone(unsent_logs_interval_); } void MetricsUploadScheduler::UploadOverDataUsageCap() { TaskDone(base::TimeDelta::FromMinutes(kOverDataUsageIntervalMinutes)); } } // namespace metrics
34.117021
79
0.772373
sarang-apps
245a974abe43b18a78fbf27cbd469476071daf5f
304
hpp
C++
include/mod/sequences.hpp
rationalis-petra/modulus
194e4029b3085e89b7e35bb925fcba079905ef80
[ "MIT" ]
1
2021-09-24T19:45:18.000Z
2021-09-24T19:45:18.000Z
include/mod/sequences.hpp
rationalis-petra/modulus
194e4029b3085e89b7e35bb925fcba079905ef80
[ "MIT" ]
null
null
null
include/mod/sequences.hpp
rationalis-petra/modulus
194e4029b3085e89b7e35bb925fcba079905ef80
[ "MIT" ]
null
null
null
#ifndef __MODULUS_MOD_OPTIONAL_HPP #define __MODULUS_MOD_OPTIONAL_HPP #include <functional> namespace mod { template <typename Seq, typename B> B fold(Seq s, std::function<B(B, B)> func, B val) { for (auto it = s.begin(); it < s.end(); it++) { val = func(*it, val); } return val; } } #endif
17.882353
51
0.661184
rationalis-petra
245aa294f35055b88d677f25841334f7b7067bfa
2,000
cpp
C++
src/Xen/XenCtrl.cpp
nccgroup/xendbg
74ce0c1ad6398b14e5702d0f58832d40088cea23
[ "MIT" ]
67
2019-01-27T01:49:40.000Z
2022-02-18T16:01:09.000Z
src/Xen/XenCtrl.cpp
SpencerMichaels/xendbg
e0290847eb0c345a9db681514c1adcf9269396c8
[ "MIT" ]
3
2019-06-30T14:51:56.000Z
2020-02-14T19:17:23.000Z
src/Xen/XenCtrl.cpp
SpencerMichaels/xendbg
e0290847eb0c345a9db681514c1adcf9269396c8
[ "MIT" ]
14
2019-01-28T07:11:23.000Z
2021-06-14T13:33:12.000Z
// // Copyright (C) 2018-2019 NCC Group // // 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 <Xen/XenCtrl.hpp> #include <Xen/XenException.hpp> using xd::xen::DomInfo ; using xd::xen::XenCtrl; using xd::xen::XenException; xd::xen::XenCtrl::XenCtrl() : _xenctrl(xc_interface_open(nullptr, nullptr, 0), &xc_interface_close), xencall(_xenctrl) { if (!_xenctrl) throw XenException("Failed to open Xenctrl handle!", errno); } XenCtrl::XenVersion XenCtrl::get_xen_version() const { int version = xc_version(_xenctrl.get(), XENVER_version, NULL); return XenVersion { version >> 16, version & ((1 << 16) - 1) }; } DomInfo XenCtrl::get_domain_info(DomID domid) const { xc_dominfo_t dominfo; int ret = xc_domain_getinfo(_xenctrl.get(), domid, 1, &dominfo); // TODO: Why do these get out of sync?! Can I ignore it? if (ret != 1) // || dominfo.domid != domid) throw XenException("Failed to get domain info!", errno); return dominfo; }
36.363636
83
0.729
nccgroup
245f3dce222614e9e4f091a4afb52e5525ae3296
291
cpp
C++
PROVAS/prova_1_2019_2/q4/q4.cpp
EduFreit4s/Tecnicas-de-Program
360a2addabe8226b4abc78b26fd6ece0297892f4
[ "MIT" ]
5
2019-10-03T22:14:13.000Z
2020-02-18T00:23:55.000Z
PROVAS/prova_1_2019_2/q4/q4.cpp
EduFreit4s/Tecnicas-de-Program
360a2addabe8226b4abc78b26fd6ece0297892f4
[ "MIT" ]
null
null
null
PROVAS/prova_1_2019_2/q4/q4.cpp
EduFreit4s/Tecnicas-de-Program
360a2addabe8226b4abc78b26fd6ece0297892f4
[ "MIT" ]
2
2019-10-24T21:32:53.000Z
2019-12-05T18:36:56.000Z
#include "triangulo.h" #include "quadrado.h" using namespace std; int main(){ Triangulo triangulo(5, 2); Quadrado quadrado(15, 10); cout << "Area do triangulo: " << triangulo.getArea() << endl; cout << "Area do quadrado: " << quadrado.getArea() << endl; return 0; }
19.4
65
0.618557
EduFreit4s
246011e5d6908b4bbd4919d5f4b5a558ad96daa5
31,996
cpp
C++
unit-tests/hdr/test-hdr.cpp
rocket-kaya/librealsense
4663fe85b5177b5ac19834f115400fb1d5368e14
[ "Apache-2.0" ]
1
2021-05-05T17:46:11.000Z
2021-05-05T17:46:11.000Z
unit-tests/hdr/test-hdr.cpp
rocket-kaya/librealsense
4663fe85b5177b5ac19834f115400fb1d5368e14
[ "Apache-2.0" ]
null
null
null
unit-tests/hdr/test-hdr.cpp
rocket-kaya/librealsense
4663fe85b5177b5ac19834f115400fb1d5368e14
[ "Apache-2.0" ]
2
2021-01-25T01:18:47.000Z
2021-03-18T06:44:07.000Z
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2021 Intel Corporation. All Rights Reserved. ///////////////////////////////////////////////////////////////////////////// // This set of tests is valid for any device that supports the HDR feature // ///////////////////////////////////////////////////////////////////////////// //#cmake:add-file ../unit-tests-common.h //#cmake:add-file ../approx.h #define CATCH_CONFIG_MAIN #include "../catch.h" #include "../unit-tests-common.h" #include <easylogging++.h> #ifdef BUILD_SHARED_LIBS // With static linkage, ELPP is initialized by librealsense, so doing it here will // create errors. When we're using the shared .so/.dll, the two are separate and we have // to initialize ours if we want to use the APIs! INITIALIZE_EASYLOGGINGPP #endif using namespace rs2; // HDR CONFIGURATION TESTS TEST_CASE("HDR Config - default config", "[hdr][live]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { auto exposure_range = depth_sensor.get_option_range(RS2_OPTION_EXPOSURE); auto gain_range = depth_sensor.get_option_range(RS2_OPTION_GAIN); depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); depth_sensor.set_option(RS2_OPTION_SEQUENCE_ID, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_SEQUENCE_ID) == 1.f); auto exp = depth_sensor.get_option(RS2_OPTION_EXPOSURE); REQUIRE(depth_sensor.get_option(RS2_OPTION_EXPOSURE) == exposure_range.def - 1000); //w/a REQUIRE(depth_sensor.get_option(RS2_OPTION_GAIN) == gain_range.def); depth_sensor.set_option(RS2_OPTION_SEQUENCE_ID, 2); REQUIRE(depth_sensor.get_option(RS2_OPTION_SEQUENCE_ID) == 2.f); REQUIRE(depth_sensor.get_option(RS2_OPTION_EXPOSURE) == exposure_range.min); REQUIRE(depth_sensor.get_option(RS2_OPTION_GAIN) == gain_range.min); depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 0); auto enabled = depth_sensor.get_option(RS2_OPTION_HDR_ENABLED); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 0.f); } } else { std::cout << "No device was found - skipping test" << std::endl; } } } TEST_CASE("HDR Config - custom config", "[hdr][live]") { // Require at least one device to be plugged in rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { depth_sensor.set_option(RS2_OPTION_SEQUENCE_SIZE, 2); REQUIRE(depth_sensor.get_option(RS2_OPTION_SEQUENCE_SIZE) == 2.f); depth_sensor.set_option(RS2_OPTION_SEQUENCE_ID, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_SEQUENCE_ID) == 1.f); depth_sensor.set_option(RS2_OPTION_EXPOSURE, 120.f); REQUIRE(depth_sensor.get_option(RS2_OPTION_EXPOSURE) == 120.f); depth_sensor.set_option(RS2_OPTION_GAIN, 90.f); REQUIRE(depth_sensor.get_option(RS2_OPTION_GAIN) == 90.f); depth_sensor.set_option(RS2_OPTION_SEQUENCE_ID, 2); REQUIRE(depth_sensor.get_option(RS2_OPTION_SEQUENCE_ID) == 2.f); depth_sensor.set_option(RS2_OPTION_EXPOSURE, 1200.f); REQUIRE(depth_sensor.get_option(RS2_OPTION_EXPOSURE) == 1200.f); depth_sensor.set_option(RS2_OPTION_GAIN, 20.f); REQUIRE(depth_sensor.get_option(RS2_OPTION_GAIN) == 20.f); depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 0); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 0.f); } } else { std::cout << "No device was found - skipping test" << std::endl; } } } // HDR STREAMING TESTS TEST_CASE("HDR Streaming - default config", "[hdr][live][using_pipeline]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { auto exposure_range = depth_sensor.get_option_range(RS2_OPTION_EXPOSURE); auto gain_range = depth_sensor.get_option_range(RS2_OPTION_GAIN); depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); rs2::config cfg; cfg.enable_stream(RS2_STREAM_DEPTH); cfg.enable_stream(RS2_STREAM_INFRARED, 1); rs2::pipeline pipe; pipe.start(cfg); int iteration = 0; while (++iteration < 100) { rs2::frameset data; REQUIRE_NOTHROW(data = pipe.wait_for_frames()); rs2::depth_frame out_depth_frame = data.get_depth_frame(); if (iteration < 3) continue; if (out_depth_frame.supports_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID)) { long long frame_exposure = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_ACTUAL_EXPOSURE); long long frame_gain = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_GAIN_LEVEL); auto seq_id = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID); if (seq_id == 0) { REQUIRE(frame_exposure == exposure_range.def - 1000.f); // w/a REQUIRE(frame_gain == gain_range.def); } else { REQUIRE(frame_exposure == exposure_range.min); REQUIRE(frame_gain == gain_range.min); } } } } } else { std::cout << "No device was found - skipping test" << std::endl; } } } TEST_CASE("HDR Streaming - custom config", "[hdr][live][using_pipeline]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { depth_sensor.set_option(RS2_OPTION_SEQUENCE_SIZE, 2); REQUIRE(depth_sensor.get_option(RS2_OPTION_SEQUENCE_SIZE) == 2.f); auto first_exposure = 120.f; auto first_gain = 90.f; depth_sensor.set_option(RS2_OPTION_SEQUENCE_ID, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_SEQUENCE_ID) == 1.f); depth_sensor.set_option(RS2_OPTION_EXPOSURE, first_exposure); REQUIRE(depth_sensor.get_option(RS2_OPTION_EXPOSURE) == first_exposure); depth_sensor.set_option(RS2_OPTION_GAIN, first_gain); REQUIRE(depth_sensor.get_option(RS2_OPTION_GAIN) == first_gain); auto second_exposure = 1200.f; auto second_gain = 20.f; depth_sensor.set_option(RS2_OPTION_SEQUENCE_ID, 2); REQUIRE(depth_sensor.get_option(RS2_OPTION_SEQUENCE_ID) == 2.f); depth_sensor.set_option(RS2_OPTION_EXPOSURE, second_exposure); REQUIRE(depth_sensor.get_option(RS2_OPTION_EXPOSURE) == second_exposure); depth_sensor.set_option(RS2_OPTION_GAIN, second_gain); REQUIRE(depth_sensor.get_option(RS2_OPTION_GAIN) == second_gain); depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); rs2::config cfg; cfg.enable_stream(RS2_STREAM_DEPTH); cfg.enable_stream(RS2_STREAM_INFRARED, 1); rs2::pipeline pipe; pipe.start(cfg); int iteration = 0; while (++iteration < 100) { rs2::frameset data; REQUIRE_NOTHROW(data = pipe.wait_for_frames()); rs2::depth_frame out_depth_frame = data.get_depth_frame(); if (iteration < 3) continue; if (out_depth_frame.supports_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID)) { long long frame_exposure = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_ACTUAL_EXPOSURE); long long frame_gain = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_GAIN_LEVEL); auto seq_id = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID); if (seq_id == 0) { REQUIRE(frame_exposure == first_exposure); REQUIRE(frame_gain == first_gain); } else { REQUIRE(frame_exposure == second_exposure); REQUIRE(frame_gain == second_gain); } } } } } else { std::cout << "No device was found - skipping test" << std::endl; } } } // HDR CHANGING CONFIG WHILE STREAMING TESTS TEST_CASE("HDR Config while Streaming", "[hdr][live][using_pipeline]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { auto exposure_range = depth_sensor.get_option_range(RS2_OPTION_EXPOSURE); auto gain_range = depth_sensor.get_option_range(RS2_OPTION_GAIN); depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); rs2::config cfg; cfg.enable_stream(RS2_STREAM_DEPTH); cfg.enable_stream(RS2_STREAM_INFRARED, 1); rs2::pipeline pipe; pipe.start(cfg); auto required_exposure = exposure_range.def - 1000; // w/a auto required_gain = gain_range.def; auto changed_exposure = 33000.f; auto changed_gain = 150.f; int iteration = 0; while (++iteration < 100) { rs2::frameset data; REQUIRE_NOTHROW(data = pipe.wait_for_frames()); rs2::depth_frame out_depth_frame = data.get_depth_frame(); if (iteration < 3 || (iteration > 30 && iteration < 36)) continue; if (iteration == 30) { depth_sensor.set_option(RS2_OPTION_SEQUENCE_ID, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_SEQUENCE_ID) == 1.f); depth_sensor.set_option(RS2_OPTION_EXPOSURE, changed_exposure); REQUIRE(depth_sensor.get_option(RS2_OPTION_EXPOSURE) == changed_exposure); depth_sensor.set_option(RS2_OPTION_GAIN, changed_gain); REQUIRE(depth_sensor.get_option(RS2_OPTION_GAIN) == changed_gain); required_exposure = changed_exposure; required_gain = changed_gain; continue; } if (out_depth_frame.supports_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID)) { long long frame_exposure = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_ACTUAL_EXPOSURE); long long frame_gain = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_GAIN_LEVEL); auto seq_id = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID); if (seq_id == 0) { REQUIRE(frame_exposure == required_exposure); REQUIRE(frame_gain == required_gain); } else { REQUIRE(frame_exposure == exposure_range.min); REQUIRE(frame_gain == gain_range.min); } } } } } else { std::cout << "No device was found - skipping test" << std::endl; } } } // CHECKING HDR AFTER PIPE RESTART TEST_CASE("HDR Running - restart hdr at restream", "[hdr][live][using_pipeline]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { rs2::config cfg; cfg.enable_stream(RS2_STREAM_DEPTH); rs2::pipeline pipe; pipe.start(cfg); depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); for (int i = 0; i < 10; ++i) { rs2::frameset data; REQUIRE_NOTHROW(data = pipe.wait_for_frames()); } REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); pipe.stop(); pipe.start(cfg); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); pipe.stop(); } } else { std::cout << "No device was found - skipping test" << std::endl; } } } // CHECKING SEQUENCE ID WHILE STREAMING TEST_CASE("HDR Streaming - checking sequence id", "[hdr][live][using_pipeline]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { rs2::config cfg; cfg.enable_stream(RS2_STREAM_DEPTH); cfg.enable_stream(RS2_STREAM_INFRARED, 1); rs2::pipeline pipe; pipe.start(cfg); depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1.f); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); int iteration = 0; int sequence_id = -1; int iterations_for_preparation = 6; while (++iteration < 50) // Application still alive? { rs2::frameset data; REQUIRE_NOTHROW(data = pipe.wait_for_frames()); if (iteration < iterations_for_preparation) continue; auto depth_frame = data.get_depth_frame(); if (depth_frame.supports_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID)) { auto depth_seq_id = depth_frame.get_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID); auto ir_frame = data.get_infrared_frame(1); auto ir_seq_id = ir_frame.get_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID); if (iteration == iterations_for_preparation) { REQUIRE(depth_seq_id == ir_seq_id); sequence_id = depth_seq_id; } else { sequence_id = (sequence_id == 0) ? 1 : 0; REQUIRE(sequence_id == depth_seq_id); REQUIRE(sequence_id == ir_seq_id); } } } pipe.stop(); } } else { std::cout << "No device was found - skipping test" << std::endl; } } } TEST_CASE("Emitter on/off - checking sequence id", "[hdr][live][using_pipeline]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { rs2::config cfg; cfg.enable_stream(RS2_STREAM_DEPTH); cfg.enable_stream(RS2_STREAM_INFRARED, 1); rs2::pipeline pipe; pipe.start(cfg); depth_sensor.set_option(RS2_OPTION_EMITTER_ON_OFF, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_EMITTER_ON_OFF) == 1.f); int iteration = 0; int sequence_id = -1; int iterations_for_preparation = 6; while (++iteration < 50) // Application still alive? { rs2::frameset data; REQUIRE_NOTHROW(data = pipe.wait_for_frames()); if (iteration < iterations_for_preparation) continue; auto depth_frame = data.get_depth_frame(); if (depth_frame.supports_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID)) { auto depth_seq_id = depth_frame.get_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID); auto ir_frame = data.get_infrared_frame(1); auto ir_seq_id = ir_frame.get_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID); if (iteration == iterations_for_preparation) { REQUIRE(depth_seq_id == ir_seq_id); sequence_id = depth_seq_id; } else { sequence_id = (sequence_id == 0) ? 1 : 0; REQUIRE(sequence_id == depth_seq_id); REQUIRE(sequence_id == ir_seq_id); } } } pipe.stop(); } } else { std::cout << "No device was found - skipping test" << std::endl; } } } //This tests checks that the previously saved merged frame is discarded after a pipe restart TEST_CASE("HDR Merge - discard merged frame", "[hdr][live][using_pipeline]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); rs2::config cfg; cfg.enable_stream(RS2_STREAM_DEPTH); rs2::pipeline pipe; pipe.start(cfg); // initializing the merging filter rs2::hdr_merge merging_filter; int num_of_iterations_in_serie = 10; int first_series_last_merged_ts = -1; for (int i = 0; i < num_of_iterations_in_serie; ++i) { rs2::frameset data; REQUIRE_NOTHROW(data = pipe.wait_for_frames()); rs2::depth_frame out_depth_frame = data.get_depth_frame(); if (out_depth_frame.supports_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID)) { // merging the frames from the different HDR sequence IDs auto merged_frameset = merging_filter.process(data); auto merged_depth_frame = merged_frameset.as<rs2::frameset>().get_depth_frame(); long long frame_ts = merged_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP); if (i == (num_of_iterations_in_serie - 1)) first_series_last_merged_ts = frame_ts; } } REQUIRE(first_series_last_merged_ts != -1); pipe.stop(); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); pipe.start(cfg); for (int i = 0; i < 10; ++i) { rs2::frameset data; REQUIRE_NOTHROW(data = pipe.wait_for_frames()); rs2::depth_frame out_depth_frame = data.get_depth_frame(); if (out_depth_frame.supports_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID)) { // merging the frames from the different HDR sequence IDs auto merged_frameset = merging_filter.process(data); auto merged_depth_frame = merged_frameset.as<rs2::frameset>().get_depth_frame(); long long frame_ts = merged_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP); REQUIRE(frame_ts > first_series_last_merged_ts); } } pipe.stop(); } } else { std::cout << "No device was found - skipping test" << std::endl; } } } TEST_CASE("HDR Start Stop - recover manual exposure and gain", "[HDR]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { float gain_before_hdr = 50.f; depth_sensor.set_option(RS2_OPTION_GAIN, gain_before_hdr); REQUIRE(depth_sensor.get_option(RS2_OPTION_GAIN) == gain_before_hdr); float exposure_before_hdr = 5000.f; depth_sensor.set_option(RS2_OPTION_EXPOSURE, exposure_before_hdr); REQUIRE(depth_sensor.get_option(RS2_OPTION_EXPOSURE) == exposure_before_hdr); depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); rs2::config cfg; cfg.enable_stream(RS2_STREAM_DEPTH); rs2::pipeline pipe; pipe.start(cfg); int iteration = 0; int iteration_for_disable = 50; int iteration_to_check_after_disable = iteration_for_disable + 2; while (++iteration < 70) { rs2::frameset data; REQUIRE_NOTHROW(data = pipe.wait_for_frames()); rs2::depth_frame out_depth_frame = data.get_depth_frame(); if (out_depth_frame.supports_frame_metadata(RS2_FRAME_METADATA_SEQUENCE_ID)) { long long frame_gain = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_GAIN_LEVEL); long long frame_exposure = out_depth_frame.get_frame_metadata(RS2_FRAME_METADATA_ACTUAL_EXPOSURE); if (iteration > iteration_for_disable && iteration < iteration_to_check_after_disable) continue; if (iteration == iteration_for_disable) { depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 0); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 0.f); } else if (iteration >= iteration_to_check_after_disable) { REQUIRE(frame_gain == gain_before_hdr); REQUIRE(frame_exposure == exposure_before_hdr); } } } } } else { std::cout << "No device was found - skipping test" << std::endl; } } } // CONTROLS STABILITY WHILE HDR ACTIVE TEST_CASE("HDR Active - set locked options", "[hdr][live]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { //setting laser ON REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_EMITTER_ENABLED, 1.f)); auto laser_power_before_hdr = depth_sensor.get_option(RS2_OPTION_LASER_POWER); std::this_thread::sleep_for((std::chrono::milliseconds)(1500)); REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1.f)); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); // the following calls should not be performed and should send a LOG_WARNING REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE, 1.f)); REQUIRE(depth_sensor.get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE) == 0.f); REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_EMITTER_ENABLED, 0.f)); REQUIRE(depth_sensor.get_option(RS2_OPTION_EMITTER_ENABLED) == 1.f); REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_EMITTER_ON_OFF, 1.f)); REQUIRE(depth_sensor.get_option(RS2_OPTION_EMITTER_ON_OFF) == 0.f); REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_LASER_POWER, laser_power_before_hdr - 30.f)); REQUIRE(depth_sensor.get_option(RS2_OPTION_LASER_POWER) == laser_power_before_hdr); } } else { std::cout << "No device was found - skipping test" << std::endl; } } } TEST_CASE("HDR Streaming - set locked options", "[hdr][live][using_pipeline]") { rs2::context ctx; if (make_context(SECTION_FROM_TEST_NAME, &ctx, "2.39.0")) { rs2::device_list devices_list = ctx.query_devices(); size_t device_count = devices_list.size(); if (devices_list.size() != 0) { rs2::depth_sensor depth_sensor = restart_first_device_and_return_depth_sensor(ctx, devices_list); if (depth_sensor && depth_sensor.supports(RS2_OPTION_HDR_ENABLED)) { //setting laser ON REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_EMITTER_ENABLED, 1.f)); auto laser_power_before_hdr = depth_sensor.get_option(RS2_OPTION_LASER_POWER); std::this_thread::sleep_for((std::chrono::milliseconds)(1500)); REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_HDR_ENABLED, 1.f)); REQUIRE(depth_sensor.get_option(RS2_OPTION_HDR_ENABLED) == 1.f); rs2::config cfg; cfg.enable_stream(RS2_STREAM_DEPTH); rs2::pipeline pipe; pipe.start(cfg); int iteration = 0; while (++iteration < 50) { rs2::frameset data; REQUIRE_NOTHROW(data = pipe.wait_for_frames()); if (iteration == 20) { // the following calls should not be performed and should send a LOG_WARNING REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE, 1.f)); REQUIRE(depth_sensor.get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE) == 0.f); REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_EMITTER_ENABLED, 0.f)); REQUIRE(depth_sensor.get_option(RS2_OPTION_EMITTER_ENABLED) == 1.f); REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_EMITTER_ON_OFF, 1.f)); REQUIRE(depth_sensor.get_option(RS2_OPTION_EMITTER_ON_OFF) == 0.f); REQUIRE_NOTHROW(depth_sensor.set_option(RS2_OPTION_LASER_POWER, laser_power_before_hdr - 30.f)); REQUIRE(depth_sensor.get_option(RS2_OPTION_LASER_POWER) == laser_power_before_hdr); } } } } else { std::cout << "No device was found - skipping test" << std::endl; } } }
42.322751
122
0.561039
rocket-kaya
2463b1d1f84cb6068161203df82beb4d4fd58407
3,272
cc
C++
test/static_test/test_strings.cc
vvchernov/onnxruntime-extensions
cc858e831b719d31e4f34ee9adb391105b4ce26b
[ "MIT" ]
59
2021-04-29T07:39:42.000Z
2022-03-29T21:12:05.000Z
test/static_test/test_strings.cc
vvchernov/onnxruntime-extensions
cc858e831b719d31e4f34ee9adb391105b4ce26b
[ "MIT" ]
45
2021-05-12T08:32:58.000Z
2022-03-29T21:11:59.000Z
test/static_test/test_strings.cc
vvchernov/onnxruntime-extensions
cc858e831b719d31e4f34ee9adb391105b4ce26b
[ "MIT" ]
18
2021-05-10T10:15:46.000Z
2022-03-22T10:46:36.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "gtest/gtest.h" #include "string_utils.h" #include "text/re2_strings/string_regex_split_re.hpp" #include "text/string_ecmaregex_split.hpp" TEST(strings, std_regex_test) { std::regex regex("[\u2700-\u27bf\U0001f650-\U0001f67f\U0001f600-\U0001f64f\u2600-\u26ff" "\U0001f300-\U0001f5ff\U0001f900-\U0001f9ff\U0001fa70-\U0001faff" "\U0001f680-\U0001f6ff]"); std::string test =u8"abcde😀🔍🦑😁🔍🎉😂🤣"; auto result = std::regex_replace(test, regex, ""); std::cout << test << std::endl; std::cout << result << std::endl; } TEST(strings, regex_split) { std::string input = "hello world"; re2::RE2 reg("(\\s)"); re2::RE2 keep_reg("\\s"); std::vector<std::string_view> tokens; std::vector<int64_t> begin_offsets; std::vector<int64_t> end_offsets; RegexSplitImpl(input, reg, true, keep_reg, tokens, begin_offsets, end_offsets); std::vector<std::string_view> expected_tokens{"hello", " ", " ", "world"}; std::vector<int64_t> expected_begin_offsets{0, 5, 6, 7}; std::vector<int64_t> expected_end_offsets{5, 6, 7, 12}; EXPECT_EQ(expected_tokens, tokens); EXPECT_EQ(expected_begin_offsets, begin_offsets); EXPECT_EQ(expected_end_offsets, end_offsets); } TEST(strings, regex_split_skip) { std::string input = "hello world"; re2::RE2 reg("(\\s)"); re2::RE2 keep_reg(""); std::vector<std::string_view> tokens; std::vector<int64_t> begin_offsets; std::vector<int64_t> end_offsets; RegexSplitImpl(input, reg, true, keep_reg, tokens, begin_offsets, end_offsets); std::vector<std::string_view> expected_tokens{"hello", "world"}; std::vector<int64_t> expected_begin_offsets{0, 6}; std::vector<int64_t> expected_end_offsets{5, 11}; EXPECT_EQ(expected_tokens, tokens); EXPECT_EQ(expected_begin_offsets, begin_offsets); EXPECT_EQ(expected_end_offsets, end_offsets); } TEST(strings, regex_split_no_matched) { std::string input = "helloworld"; std::regex reg("(\\s)"); std::regex keep_reg(""); std::vector<std::string_view> tokens; std::vector<int64_t> begin_offsets; std::vector<int64_t> end_offsets; ECMARegexSplitImpl(input, reg, true, keep_reg, tokens, begin_offsets, end_offsets); std::vector<std::string_view> expected_tokens{"helloworld"}; std::vector<int64_t> expected_begin_offsets{0}; std::vector<int64_t> expected_end_offsets{10}; EXPECT_EQ(expected_tokens, tokens); EXPECT_EQ(expected_begin_offsets, begin_offsets); EXPECT_EQ(expected_end_offsets, end_offsets); } TEST(strings, regex_split_begin_end_delim) { std::string input = " hello world "; std::regex reg("(\\s)"); std::regex keep_reg("\\s"); std::vector<std::string_view> tokens; std::vector<int64_t> begin_offsets; std::vector<int64_t> end_offsets; ECMARegexSplitImpl(input, reg, true, keep_reg, tokens, begin_offsets, end_offsets); std::vector<std::string_view> expected_tokens{" ", "hello"," ", "world", " "}; std::vector<int64_t> expected_begin_offsets{0, 1, 6, 7, 12}; std::vector<int64_t> expected_end_offsets{1, 6, 7, 12, 13}; EXPECT_EQ(expected_tokens, tokens); EXPECT_EQ(expected_begin_offsets, begin_offsets); EXPECT_EQ(expected_end_offsets, end_offsets); }
38.494118
90
0.718826
vvchernov
2463d4d986c95bf2155c21f51c379c6e05df10ea
2,512
cpp
C++
src/modules/m_setagent.cpp
BerilBBJ/beryldb
6569b568796e4cea64fe7f42785b0319541a0284
[ "BSD-3-Clause" ]
206
2021-04-27T21:44:24.000Z
2022-02-23T12:01:20.000Z
src/modules/m_setagent.cpp
BerilBBJ/beryldb
6569b568796e4cea64fe7f42785b0319541a0284
[ "BSD-3-Clause" ]
10
2021-05-04T19:46:59.000Z
2021-10-01T23:43:07.000Z
src/modules/m_setagent.cpp
berylcorp/beryl
6569b568796e4cea64fe7f42785b0319541a0284
[ "BSD-3-Clause" ]
7
2021-04-28T16:17:56.000Z
2021-12-10T01:14:42.000Z
/* * BerylDB - A lightweight database. * http://www.beryldb.com * * Copyright (C) 2021 - Carlos F. Ferry <cferry@beryldb.com> * * This file is part of BerylDB. BerylDB is free software: you can * redistribute it and/or modify it under the terms of the BSD License * version 3. * * More information about our licensing can be found at https://docs.beryl.dev */ #include "beryl.h" #include "engine.h" class CommandSetAgent : public Command { public: CommandSetAgent(Module* Creator) : Command(Creator, "SETAGENT", 2) { last_empty_ok = false; flags = 'e'; syntax = "[<instance>] <channel>[,<channel>]+"; INTERPRET2(TR_INSTANCE, TR_TEXT); } COMMAND_RESULT Handle(User* user, const Params& parameters) { const std::string& instance = parameters[0]; const std::string& agent = parameters[1]; User* target = Kernel->Clients->FindInstance(instance); if ((!target) || (target->registered != REG_OK)) { user->SendProtocol(Protocols::NoInstance(instance)); return FAILED; } if (agent.empty() || agent.length() < 3 || agent.length() > 15) { user->SendProtocol(ERR_INPUT2, ERR_BAD_FORMAT, VALID_AGENT); return FAILED; } if (!Kernel->Engine->IsAgent(agent)) { user->SendProtocol(ERR_INPUT2, ERR_BAD_FORMAT, WRONG_AGENT); return FAILED; } if (IS_LOCAL(target)) { target->SetAgent(parameters[1]); user->SendProtocol(BRLD_OK, PROCESS_OK); } return SUCCESS; } RouteParams GetRouting(User* user, const Params& parameters) { return ROUTE_OPT_UCAST(parameters[0]); } }; class ModuleSetAgent : public Module { private: CommandSetAgent cmd; public: ModuleSetAgent() : cmd(this) { } Version GetDescription() { return Version("Adds SETAGENT command.", VF_BERYLDB|VF_OPTCOMMON); } }; MODULE_LOAD(ModuleSetAgent)
27.911111
84
0.492834
BerilBBJ
2465240e76a1b711bf73c99d1ae72091b9b828a4
440
cpp
C++
Algorithms/DynamicProgramming/Fibonacci Numbers/fibonacci_recursion.cpp
Nidita/Data-Structures-Algorithms
7b5198c8d37e9a70dd0885c6eef6dddd9d85d74a
[ "MIT" ]
26
2019-07-17T11:05:43.000Z
2022-02-06T08:31:40.000Z
Algorithms/DynamicProgramming/Fibonacci Numbers/fibonacci_recursion.cpp
Nidita/Data-Structures-Algorithms
7b5198c8d37e9a70dd0885c6eef6dddd9d85d74a
[ "MIT" ]
7
2019-07-16T19:52:25.000Z
2022-01-08T08:03:44.000Z
Algorithms/DynamicProgramming/Fibonacci Numbers/fibonacci_recursion.cpp
Nidita/Data-Structures-Algorithms
7b5198c8d37e9a70dd0885c6eef6dddd9d85d74a
[ "MIT" ]
19
2020-01-14T02:44:28.000Z
2021-12-27T17:31:59.000Z
#include<iostream> #include<ctime> using namespace std; int fib(int); int main() { int n; cin >> n; time_t start = time(NULL); for (int i = 1; i <= n; ++i) { cout << fib(i) << " "; } time_t end = time(NULL); cout << endl << "Time: " << (end - start) << " s"; } int fib(int n) { if (n==1 || n==2) { return 1; } else { return fib(n - 1) + fib(n - 2); } }
12.571429
54
0.425
Nidita
2465d6c0361247ffb55a93d70af22c11b4255a73
10,826
cpp
C++
src/Chinese/relations/ch_PotentialRelationInstance.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/Chinese/relations/ch_PotentialRelationInstance.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/Chinese/relations/ch_PotentialRelationInstance.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright 2008 by BBN Technologies Corp. // All Rights Reserved. #include "Generic/common/leak_detection.h" #include "Chinese/relations/ch_PotentialRelationInstance.h" #include "Generic/relations/RelationTypeSet.h" #include "Chinese/relations/ch_RelationUtilities.h" #include "Generic/common/InternalInconsistencyException.h" #include "Generic/common/Symbol.h" #include "Generic/theories/Argument.h" #include "Generic/theories/MentionSet.h" #include "Generic/theories/Mention.h" #include "Generic/theories/Proposition.h" #include "Generic/theories/RelationConstants.h" #include "Generic/theories/SynNode.h" #include "Generic/common/SessionLogger.h" // 0 last hanzi of predicate // 1 left mention type // 2 right mention type // 3 left metonymy // 4 right metonymy ChinesePotentialRelationInstance::ChinesePotentialRelationInstance() { for (int i = 0; i < CH_POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE; i++) { _ngram[i] = NULL_SYM; } } void ChinesePotentialRelationInstance::setFromTrainingNgram(Symbol *training_instance) { // call base class version PotentialRelationInstance::setFromTrainingNgram(training_instance); setLastHanziOfPredicate(training_instance[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE]); setLeftMentionType(training_instance[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+1]); setRightMentionType(training_instance[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+2]); setLeftMetonymy(training_instance[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+3]); setRightMetonymy(training_instance[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+4]); } Symbol* ChinesePotentialRelationInstance::getTrainingNgram() { for (int i = 0; i < POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE; i++) { _ngram[i] = PotentialRelationInstance::_ngram[i]; } return _ngram; } void ChinesePotentialRelationInstance::setStandardInstance( Argument *first, Argument *second, const Proposition *prop, const MentionSet *mentionSet) { // First, set the members of the generic PotentialRelationInstance // set relation type to default (NONE) setRelationType(RelationConstants::NONE); // set mention indicies _leftMention = first->getMention(mentionSet)->getUID(); _rightMention = second->getMention(mentionSet)->getUID(); // set predicate if (prop->getPredType() == Proposition::NOUN_PRED || prop->getPredType() == Proposition::VERB_PRED || prop->getPredType() == Proposition::COPULA_PRED || prop->getPredType() == Proposition::MODIFIER_PRED || prop->getPredType() == Proposition::POSS_PRED || prop->getPredType() == Proposition::NAME_PRED) { setPredicate(prop->getPredSymbol()); } else if (prop->getPredType() == Proposition::SET_PRED) setPredicate(SET_SYM); else if (prop->getPredType() == Proposition::COMP_PRED) setPredicate(COMP_SYM); else { SessionLogger::warn("potential_relation_instance") << "unknown predicate type in " << "ChinesePotentialRelationInstance::setStandardInstance(): " << prop->getPredTypeString(prop->getPredType()); setPredicate(CONFUSED_SYM); } // set stemmed predicate -- language specific setStemmedPredicate(RelationUtilities::get()->stemPredicate(prop->getPredSymbol(), prop->getPredType())); // set head words - make an exception for APPO - we want the head word to be the head word of the DESC if (first->getMention(mentionSet)->getMentionType() == Mention::APPO) setLeftHeadword(first->getMention(mentionSet)->getChild()->getNode()->getHeadWord()); else setLeftHeadword(first->getMention(mentionSet)->getNode()->getHeadWord()); if (second->getMention(mentionSet)->getMentionType() == Mention::APPO) setRightHeadword(second->getMention(mentionSet)->getChild()->getNode()->getHeadWord()); else setRightHeadword(second->getMention(mentionSet)->getNode()->getHeadWord()); // set everything else setNestedWord(NULL_SYM); setLeftEntityType(first->getMention(mentionSet)->getEntityType().getName()); setRightEntityType(second->getMention(mentionSet)->getEntityType().getName()); setLeftRole(first->getRoleSym()); setRightRole(second->getRoleSym()); setNestedRole(NULL_SYM); setReverse(NULL_SYM); if (first->getRoleSym() == Argument::REF_ROLE) setPredicationType(ONE_PLACE); else setPredicationType(MULTI_PLACE); // Now set the Chinese specific members const wchar_t *pred = getPredicate().to_string(); // unless the predicate is ':SET' or ':COMP' if (pred[0] != ':') { wchar_t str[2]; size_t len = wcslen(pred); wcsncpy(str, pred + len - 1, 2); setLastHanziOfPredicate(Symbol(str)); } else setLastHanziOfPredicate(getPredicate()); setLeftMentionType(first->getMention(mentionSet)->getMentionType()); setRightMentionType(second->getMention(mentionSet)->getMentionType()); if (first->getMention(mentionSet)->hasIntendedType()) setLeftMetonymy(first->getMention(mentionSet)->getIntendedType().getName()); else if (first->getMention(mentionSet)->hasRoleType()) setLeftMetonymy(first->getMention(mentionSet)->getRoleType().getName()); if (second->getMention(mentionSet)->hasIntendedType()) setRightMetonymy(second->getMention(mentionSet)->getIntendedType().getName()); else if (second->getMention(mentionSet)->hasRoleType()) setRightMetonymy(second->getMention(mentionSet)->getRoleType().getName()); } void ChinesePotentialRelationInstance::setStandardNestedInstance( Argument *first, Argument *intermediate, Argument *second, const Proposition *outer_prop, const Proposition *inner_prop, const MentionSet *mentionSet) { // set all the basics in regular function setStandardInstance(first, second, outer_prop, mentionSet); // get nested word from inner_prop Symbol nested_word = inner_prop->getPredSymbol(); // get nested word from inner_prop if (inner_prop->getPredType() == Proposition::NOUN_PRED || inner_prop->getPredType() == Proposition::MODIFIER_PRED || inner_prop->getPredType() == Proposition::VERB_PRED || inner_prop->getPredType() == Proposition::COPULA_PRED) { setNestedWord(RelationUtilities::get()->stemPredicate(nested_word, inner_prop->getPredType())); } else if (inner_prop->getPredType() == Proposition::SET_PRED) setNestedWord(SET_SYM); else if (inner_prop->getPredType() == Proposition::COMP_PRED) setNestedWord(COMP_SYM); else { SessionLogger::warn("potential_relation_instance") << "unknown predicate type in " << "ChinesePotentialRelationInstance::setStandardNestedInstance(): " << inner_prop->getPredTypeString(inner_prop->getPredType()); setNestedWord(CONFUSED_SYM); } setNestedRole(intermediate->getRoleSym()); } void ChinesePotentialRelationInstance::setStandardListInstance(Argument *first, Argument *second, bool listIsFirst, const Mention *member, const Proposition *prop, const MentionSet *mentionSet) { setStandardInstance(first, second, prop, mentionSet); if (listIsFirst) { _leftMention = member->getUID(); if (member->getMentionType() == Mention::APPO) setLeftHeadword(member->getChild()->getNode()->getHeadWord()); else setLeftHeadword(member->getNode()->getHeadWord()); setLeftEntityType(member->getEntityType().getName()); setLeftMentionType(member->getMentionType()); if (member->hasIntendedType()) setLeftMetonymy(member->getIntendedType().getName()); else if (member->hasRoleType()) setLeftMetonymy(member->getRoleType().getName()); } else { _rightMention = member->getUID(); if (member->getMentionType() == Mention::APPO) setRightHeadword(member->getChild()->getNode()->getHeadWord()); else setRightHeadword(member->getNode()->getHeadWord()); setRightEntityType(member->getEntityType().getName()); setRightMentionType(member->getMentionType()); setRightMetonymy(member->getIntendedType().getName()); if (member->hasIntendedType()) setRightMetonymy(member->getIntendedType().getName()); else if (member->hasRoleType()) setRightMetonymy(member->getRoleType().getName()); } } Symbol ChinesePotentialRelationInstance::getLastHanziOfPredicate() { return _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE]; } Symbol ChinesePotentialRelationInstance::getLeftMentionType() { return _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+1]; } Symbol ChinesePotentialRelationInstance::getRightMentionType() { return _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+2]; } Symbol ChinesePotentialRelationInstance::getLeftMetonymy() { return _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+3]; } Symbol ChinesePotentialRelationInstance::getRightMetonymy() { return _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+4]; } void ChinesePotentialRelationInstance::setLastHanziOfPredicate(Symbol sym) { _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE] = sym; } void ChinesePotentialRelationInstance::setLeftMentionType(Symbol sym) { _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+1] = sym; } void ChinesePotentialRelationInstance::setRightMentionType(Symbol sym) { _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+2] = sym; } void ChinesePotentialRelationInstance::setLeftMetonymy(Symbol sym) { _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+3] = sym; } void ChinesePotentialRelationInstance::setRightMetonymy(Symbol sym) { _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+4] = sym; } void ChinesePotentialRelationInstance::setLeftMentionType(Mention::Type type) { _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+1] = convertMentionType(type); } void ChinesePotentialRelationInstance::setRightMentionType(Mention::Type type) { _ngram[POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE+2] = convertMentionType(type); } std::wstring ChinesePotentialRelationInstance::toString() { std::wstring result = PotentialRelationInstance::toString(); for (int i = POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE; i < CH_POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE; i++) { result += _ngram[i].to_string(); result += L" "; } return result; } std::string ChinesePotentialRelationInstance::toDebugString() { std::string result = PotentialRelationInstance::toDebugString(); for (int i = POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE; i < CH_POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE; i++) { result += _ngram[i].to_debug_string(); result += " "; } return result; } Symbol ChinesePotentialRelationInstance::convertMentionType(Mention::Type type) { if (type == Mention::NONE) return Symbol(L"NONE"); else if (type == Mention::NAME) return Symbol(L"NAME"); else if (type == Mention::PRON) return Symbol(L"PRON"); else if (type == Mention::DESC) return Symbol(L"DESC"); else if (type == Mention::PART) return Symbol(L"PART"); else if (type == Mention::APPO) return Symbol(L"APPO"); else if (type == Mention::LIST) return Symbol(L"LIST"); return Symbol(); }
42.124514
160
0.752448
BBN-E
24665bf25fac621878f6a60c15a824be490ca97b
2,755
cpp
C++
src/apps/gxyviewer-worker.cpp
BruceCherniak/Galaxy
239cdd6ae060916ea8c1ba225e386095b785a702
[ "Apache-2.0" ]
null
null
null
src/apps/gxyviewer-worker.cpp
BruceCherniak/Galaxy
239cdd6ae060916ea8c1ba225e386095b785a702
[ "Apache-2.0" ]
null
null
null
src/apps/gxyviewer-worker.cpp
BruceCherniak/Galaxy
239cdd6ae060916ea8c1ba225e386095b785a702
[ "Apache-2.0" ]
null
null
null
// ========================================================================== // // Copyright (c) 2014-2019 The University of Texas at Austin. // // All rights reserved. // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // A copy of the License is included with this software in the file LICENSE. // // If your copy does not contain the License, you may obtain a copy of the // // License at: // // // // https://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // // // ========================================================================== // #include <iostream> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <string.h> #include "Application.h" #include "Renderer.h" #include "AsyncRendering.h" #include <ospray/ospray.h> using namespace gxy; using namespace std; int mpiRank, mpiSize; #include "Debug.h" void syntax(char *a) { cerr << "syntax: " << a << " [options]" << endl; cerr << "options:" << endl; cerr << " -D run debugger" << endl; cerr << " -A wait for attachment" << endl; exit(1); } int main(int argc, char *argv[]) { bool dbg = false, atch = false; char *dbgarg; ospInit(&argc, (const char **)argv); Application theApplication(&argc, &argv); theApplication.Start(); AsyncRendering::RegisterClass(); for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-A")) { dbg = true, atch = true; } else if (!strcmp(argv[i], "-D")) { dbg = true, dbgarg = argv[i] + 2; break; } else { syntax(argv[0]); } } Renderer::Initialize(); GetTheApplication()->Run(); mpiRank = theApplication.GetRank(); mpiSize = theApplication.GetSize(); Debug *d = dbg ? new Debug(argv[0], atch, dbgarg) : NULL; GetTheApplication()->Wait(); return 0; }
32.797619
81
0.477677
BruceCherniak
246a4824d5f3ccfbe303f34dda510baeb45d4adf
3,407
cpp
C++
PETBWUAMF/src/Application.cpp
piotrfutymski/PETBWUAMF
05953179a8649b8e55abcdb98b50f91a46e2da53
[ "Apache-2.0" ]
null
null
null
PETBWUAMF/src/Application.cpp
piotrfutymski/PETBWUAMF
05953179a8649b8e55abcdb98b50f91a46e2da53
[ "Apache-2.0" ]
null
null
null
PETBWUAMF/src/Application.cpp
piotrfutymski/PETBWUAMF
05953179a8649b8e55abcdb98b50f91a46e2da53
[ "Apache-2.0" ]
null
null
null
#include "Application.h" Application::Application() { } void Application::init(std::string settingFilePath) { srand(time(NULL)); std::ifstream stream(settingFilePath); if(stream.is_open()) { stream >> _settings; Logger::log("Setting loaded succesfully"); } else { Logger::log("Unable to load settings"); return; } stream.close(); Didax::AssetMeneger::loadAllAssets(_settings); _game.init({}); _game.initOrderFunctions(); _engine.init(_settings, &_game); } int Application::run() { _engine.run(); while (!_game.isGameEnded()) { auto gamedata = _game.playTurn(this->getMoveFromConsole()); _reporter.SaveTurn(gamedata); } return 0; } Move Application::getMoveFromConsole() { bool reset = true; //petla cala while (reset) { Move res; _consoleUI.clear(); _consoleUI.logState(_game, _reporter); _consoleUI.makeMove(_game); Order * order = nullptr; int oID, x, y, id, rest=0; //petla wyboru rozkazu while (1) { Logger::log("----------------------Pick order id----------------------"); std::cin >> oID; if (oID == -1) { rest = 1; break; } order = _game.getObject<Order>(oID); if (order == nullptr) { Logger::log("-------------------Order doesn't exist-------------------"); } else { auto poss = _game.getPossibleOrders(_game.getActivePlayer()); if (std::find(poss.begin(), poss.end(), order->getID()) != poss.end()) break; } } if (rest) continue; //do tad bylo fajnie, ale chce dac mozliwosc wycofania sie z rozkazu res.orderID = oID; Logger::log("---------------------------------------------------------"); for (size_t i = 0; i < order->getTargetsCount(); i++) { if (order->getPrototype()->_target == OrderPrototype::TargetType::MoveT) { _consoleUI.MoveMap(_game, order); Logger::log("----------------------Choose Position (int) (int)--------"); std::cin >> x; if (x == -1) { rest = 1; break; } std::cin >> y; if (y == -1) { rest = 1; break; } res.positions.push_back({ x,y }); Logger::log("---------------------------------------------------------"); } else if(order->getPrototype()->_target == OrderPrototype::TargetType::AttackT) { Logger::log("------------------Choose Target ID (int)-----------------"); _consoleUI.AttackMap(_game, order); std::cin >> id; if (id == -1) { rest = 1; break; } res.units.push_back(id); Logger::log("---------------------------------------------------------"); } else if (order->getPrototype()->_target == OrderPrototype::TargetType::ChargeT) { _consoleUI.MoveMap(_game, order); Logger::log("----------------------Choose Position (int) (int)--------"); std::cin >> x; if (x == -1) { rest = 1; break; } std::cin >> y; if (y == -1) { rest = 1; break; } res.positions.push_back({ x,y }); Logger::log("---------------------------------------------------------"); Logger::log("------------------Choose Target ID (int)-----------------"); _consoleUI.ChargeMap(_game, order, res); std::cin >> id; if (id == -1) { rest = 1; break; } res.units.push_back(id); Logger::log("---------------------------------------------------------"); } } if (rest) continue; return res; } }
20.279762
82
0.491048
piotrfutymski
246d1122b2586189924fae88f550ba68460df271
4,061
hpp
C++
include/common_robotics_utilities/simple_dtw.hpp
EricCousineau-TRI/common_robotics_utilities
df2f0c68d92d93c919bb7401abe5e12bd5ca2345
[ "BSD-3-Clause" ]
null
null
null
include/common_robotics_utilities/simple_dtw.hpp
EricCousineau-TRI/common_robotics_utilities
df2f0c68d92d93c919bb7401abe5e12bd5ca2345
[ "BSD-3-Clause" ]
null
null
null
include/common_robotics_utilities/simple_dtw.hpp
EricCousineau-TRI/common_robotics_utilities
df2f0c68d92d93c919bb7401abe5e12bd5ca2345
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <cstdint> #include <functional> #include <limits> #include <stdexcept> #include <vector> #include <Eigen/Geometry> namespace common_robotics_utilities { namespace simple_dtw { template<typename FirstDatatype, typename SecondDatatype, typename FirstContainer=std::vector<FirstDatatype>, typename SecondContainer=std::vector<SecondDatatype>> class SimpleDTW { protected: void InitializeMatrix(const ssize_t first_sequence_size, const ssize_t second_sequence_size) { const ssize_t rows = first_sequence_size + 1; const ssize_t cols = second_sequence_size + 1; if (dtw_matrix_.rows() < rows || dtw_matrix_.cols() < cols) { dtw_matrix_ = Eigen::MatrixXd::Zero(rows, cols); if (rows > 1 && cols > 1) { for (ssize_t row = 1; row < rows; row++) { dtw_matrix_(row, 0) = std::numeric_limits<double>::infinity(); } for (ssize_t col = 1; col < cols; col++) { dtw_matrix_(0, col) = std::numeric_limits<double>::infinity(); } } } } Eigen::MatrixXd dtw_matrix_; public: SimpleDTW() { InitializeMatrix(0, 0); } SimpleDTW(const ssize_t first_sequence_size, const ssize_t second_sequence_size) { InitializeMatrix(first_sequence_size, second_sequence_size); } double EvaluateWarpingCost( const FirstContainer& first_sequence, const SecondContainer& second_sequence, const std::function<double(const FirstDatatype&, const SecondDatatype&)>& distance_fn) { if (first_sequence.empty()) { throw std::invalid_argument("first_sequence is empty"); } if (second_sequence.empty()) { throw std::invalid_argument("second_sequence is empty"); } const ssize_t first_sequence_size = static_cast<ssize_t>(first_sequence.size()); const ssize_t second_sequence_size = static_cast<ssize_t>(second_sequence.size()); InitializeMatrix(first_sequence_size, second_sequence_size); //Compute DTW cost for the two sequences for (ssize_t i = 1; i <= first_sequence_size; i++) { const FirstDatatype& first_item = first_sequence[static_cast<size_t>(i) - 1]; for (ssize_t j = 1; j <= second_sequence_size; j++) { const SecondDatatype& second_item = second_sequence[static_cast<size_t>(j) - 1]; const double index_cost = distance_fn(first_item, second_item); double prev_cost = 0.0; // Get the next neighboring values from the matrix to use for the update double im1j = dtw_matrix_(i - 1, j); double im1jm1 = dtw_matrix_(i - 1, j - 1); double ijm1 = dtw_matrix_(i, j - 1); // Start the update step if (im1j < im1jm1 && im1j < ijm1) { prev_cost = im1j; } else if (ijm1 < im1j && ijm1 < im1jm1) { prev_cost = ijm1; } else { prev_cost = im1jm1; } // Update the value in the matrix const double new_cost = index_cost + prev_cost; dtw_matrix_(i, j) = new_cost; } } //Return total path cost const double warping_cost = dtw_matrix_(first_sequence_size, second_sequence_size); return warping_cost; } }; template<typename FirstDatatype, typename SecondDatatype, typename FirstContainer=std::vector<FirstDatatype>, typename SecondContainer=std::vector<SecondDatatype>> inline double EvaluateWarpingCost( const FirstContainer& first_sequence, const SecondContainer& second_sequence, const std::function<double(const FirstDatatype&, const SecondDatatype&)>& distance_fn) { SimpleDTW<FirstDatatype, SecondDatatype, FirstContainer, SecondContainer> dtw_evaluator; return dtw_evaluator.EvaluateWarpingCost( first_sequence, second_sequence, distance_fn); } } // namespace simple_dtw } // namespace common_robotics_utilities
30.765152
80
0.645654
EricCousineau-TRI
246d5610bfb128a44e51d3a4ff61c77c00376058
199
cpp
C++
ModelChecker/unitary_tests/Model_checker/unused_var.cpp
jxw1102/projet_merou
886c6774c5d2dbd91556ec5592a2296703da0132
[ "Apache-2.0" ]
3
2015-02-11T20:10:38.000Z
2015-12-26T07:30:37.000Z
ModelChecker/unitary_tests/Model_checker/unused_var.cpp
jxw1102/projet_merou
886c6774c5d2dbd91556ec5592a2296703da0132
[ "Apache-2.0" ]
7
2015-02-06T23:34:58.000Z
2015-02-26T21:53:20.000Z
ModelChecker/unitary_tests/Model_checker/unused_var.cpp
jxw1102/projet_merou
886c6774c5d2dbd91556ec5592a2296703da0132
[ "Apache-2.0" ]
1
2015-04-24T07:54:22.000Z
2015-04-24T07:54:22.000Z
int f() { return 2; } int main(int argc, char** argv) { int x; int y; int z; x + y + 2 + f(); if (x > 2) { int r = 3; } else { int r = 2; r++; } return 0; }
9.47619
34
0.376884
jxw1102
246e58a926a20d920d3c54a118e320fac5bee7e3
1,984
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/animation/PointFEvaluator.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/animation/PointFEvaluator.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/animation/PointFEvaluator.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "elastos/droid/animation/PointFEvaluator.h" #include "elastos/droid/graphics/CPointF.h" using Elastos::Droid::Graphics::CPointF; namespace Elastos { namespace Droid { namespace Animation { CAR_INTERFACE_IMPL(PointFEvaluator, Object, ITypeEvaluator); PointFEvaluator::PointFEvaluator() { } PointFEvaluator::PointFEvaluator( /* [in] */ IPointF* reuse) : mPoint(reuse) { } ECode PointFEvaluator::Evaluate( /* [in] */ Float fraction, /* [in] */ IInterface* startValue, /* [in] */ IInterface* endValue, /* [out] */ IInterface** pf) { VALIDATE_NOT_NULL(pf); Float v1 = 0.f, v2 = 0.f; IPointF::Probe(startValue)->GetX(&v1); IPointF::Probe(endValue)->GetX(&v2); Float x = v1 + (fraction * (v2 - v1)); IPointF::Probe(startValue)->GetY(&v1); IPointF::Probe(endValue)->GetY(&v2); Float y = v1 + (fraction * (v2 - v1)); if (mPoint != NULL) { mPoint->Set(x, y); *pf = mPoint; REFCOUNT_ADD(*pf); return NOERROR; } AutoPtr<IPointF> obj; CPointF::New(x, y, (IPointF**)&obj); *pf = obj.Get(); REFCOUNT_ADD(*pf) return NOERROR; } } //namespace Animation } //namespace Droid } //namespace Elastos
28.342857
75
0.611895
jingcao80
246e7c5a830df24ef92625e448e2d17a770c243a
7,270
hpp
C++
Engine/Core/Headers/Molten/Gui/CanvasRenderer.hpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
2
2019-11-11T21:17:14.000Z
2019-11-11T22:07:26.000Z
Engine/Core/Headers/Molten/Gui/CanvasRenderer.hpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
null
null
null
Engine/Core/Headers/Molten/Gui/CanvasRenderer.hpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
1
2020-04-05T03:50:57.000Z
2020-04-05T03:50:57.000Z
/* * MIT License * * Copyright (c) 2022 Jimmie Bergmann * * 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 MOLTEN_CORE_GUI_CANVASRENDERER_HPP #define MOLTEN_CORE_GUI_CANVASRENDERER_HPP #include "Molten/Gui/GuiTypes.hpp" #include "Molten/Gui/Font.hpp" #include "Molten/Math/Vector.hpp" #include "Molten/Math/Matrix.hpp" #include "Molten/Math/Bounds.hpp" #include "Molten/Math/AABB.hpp" #include "Molten/Renderer/RenderResource.hpp" #include "Molten/Renderer/Sampler.hpp" #include "Molten/Renderer/ShaderProgram.hpp" #include "Molten/Renderer/Texture.hpp" #include "Molten/Renderer/VertexBuffer.hpp" namespace Molten { class Renderer; class CommandBuffer; class Pipeline; class VertexBuffer; class IndexBuffer; class DescriptorSet; class FramedDescriptorSet; class Logger; } namespace Molten::Shader::Visual { class VertexScript; class FragmentScript; } namespace Molten::Gui { class CanvasRenderer; struct MOLTEN_API CanvasRendererTexture { CanvasRendererTexture() = default; CanvasRendererTexture(const CanvasRendererTexture&) = delete; CanvasRendererTexture(CanvasRendererTexture&&) noexcept = default; CanvasRendererTexture& operator =(const CanvasRendererTexture&) = delete; CanvasRendererTexture& operator =(CanvasRendererTexture&&) noexcept = default; SharedRenderResource<Texture2D> texture; Vector2ui32 dimensions; RenderResource<DescriptorSet> descriptorSet; }; struct MOLTEN_API CanvasRendererFramedTexture { CanvasRendererFramedTexture() = default; ~CanvasRendererFramedTexture() = default; CanvasRendererFramedTexture(const CanvasRendererTexture&) = delete; CanvasRendererFramedTexture(CanvasRendererFramedTexture&&) noexcept = default; CanvasRendererFramedTexture& operator =(const CanvasRendererFramedTexture&) = delete; CanvasRendererFramedTexture& operator =(CanvasRendererFramedTexture&&) noexcept = default; SharedRenderResource<FramedTexture2D> framedTexture; RenderResource<FramedDescriptorSet> framedDescriptorSet; }; struct MOLTEN_API CanvasRendererFontSequence { struct Group { Group() = default; Group(const Group&) = delete; Group(Group&&) noexcept = default; Group& operator =(const Group&) = delete; Group& operator =(Group&&) noexcept = default; CanvasRendererTexture* texture; RenderResource<VertexBuffer> vertexBuffer; }; CanvasRendererFontSequence() = default; CanvasRendererFontSequence(const CanvasRendererFontSequence&) = delete; CanvasRendererFontSequence(CanvasRendererFontSequence&&) noexcept = default; CanvasRendererFontSequence& operator =(const CanvasRendererFontSequence&) = delete; CanvasRendererFontSequence& operator =(CanvasRendererFontSequence&&) noexcept = default; std::vector<Group> groups; }; class MOLTEN_API CanvasRenderer { public: static CanvasRendererPointer Create(Renderer& renderer, Logger * logger = nullptr, const Vector2f32& size = { 0.0f, 0.0f }); CanvasRenderer(Renderer& renderer, Logger* logger = nullptr, const Vector2f32& size = {0.0f, 0.0f}); ~CanvasRenderer(); CanvasRenderer(const CanvasRenderer&) = delete; CanvasRenderer(CanvasRenderer&&) = delete; CanvasRenderer& operator =(const CanvasRenderer&) = delete; CanvasRenderer& operator =(CanvasRenderer&&) = delete; void Close(); void Resize(const Vector2f32& size); CanvasRendererTexture CreateTexture(const TextureDescriptor2D& textureDescriptor); bool UpdateTexture(CanvasRendererTexture& texture, const TextureUpdateDescriptor2D& textureUpdateDescriptor); CanvasRendererFramedTexture CreateFramedTexture(SharedRenderResource<FramedTexture2D> framedTexture); CanvasRendererFontSequence CreateFontSequence(FontGroupedSequence& fontGroupedSequence); void SetCommandBuffer(CommandBuffer& commandBuffer); void DrawRect(const AABB2f32& bounds, const Vector4f32& color); void DrawRect(const AABB2f32& bounds, CanvasRendererTexture& texture); void DrawRect(const AABB2f32& bounds, const Bounds2f32& textureCoords, CanvasRendererTexture& texture); void DrawRect(const AABB2f32& bounds, const Bounds2f32& textureCoords, CanvasRendererFramedTexture& framedtexture); void DrawFontSequence(const Vector2f32& position, CanvasRendererFontSequence& fontSequence); private: struct ColoredRectData { ColoredRectData(); RenderResource<Pipeline> pipeline; RenderResource<VertexBuffer> vertexBuffer; RenderResource<IndexBuffer> indexBuffer; uint32_t projectionLocation; uint32_t positionLocation; uint32_t sizeLocation; uint32_t colorLocation; }; struct TexturedRectData { TexturedRectData(); RenderResource<Pipeline> pipeline; RenderResource<VertexBuffer> vertexBuffer; RenderResource<IndexBuffer> indexBuffer; uint32_t projectionLocation; uint32_t positionLocation; uint32_t sizeLocation; uint32_t uvPositionLocation; uint32_t uvSizeLocation; }; struct FontRenderData { FontRenderData(); RenderResource<Pipeline> pipeline; uint32_t projectionLocation; uint32_t positionLocation; }; static void DestroyColoredRect(ColoredRectData& data); static void DestroyTexturedRect(TexturedRectData& data); void LoadColoredRect(); void LoadTexturedRect(); void LoadFontRenderData(); //Logger* m_logger; Renderer& m_backendRenderer; CommandBuffer* m_commandBuffer; Matrix4x4f32 m_projection; SharedRenderResource<Sampler2D> m_sampler2D; ColoredRectData m_coloredRect; TexturedRectData m_texturedRect; FontRenderData m_fontRenderData; }; } #endif
33.657407
132
0.708391
jimmiebergmann
2471b6f6fb0b17ef35074b28a2af07d8eac4d4a9
1,203
cpp
C++
QSidePanel/QSidePanel/PanelLeftSide.cpp
inobelar/QSidePanel
4554e1bcd3f0942df66ed1357cdac7afdd08597d
[ "MIT" ]
16
2019-10-11T12:08:05.000Z
2022-01-02T05:59:16.000Z
QSidePanel/QSidePanel/PanelLeftSide.cpp
inobelar/QSidePanel
4554e1bcd3f0942df66ed1357cdac7afdd08597d
[ "MIT" ]
null
null
null
QSidePanel/QSidePanel/PanelLeftSide.cpp
inobelar/QSidePanel
4554e1bcd3f0942df66ed1357cdac7afdd08597d
[ "MIT" ]
9
2019-11-17T20:09:55.000Z
2021-10-31T14:54:02.000Z
#include "PanelLeftSide.hpp" #include "side_panel_helpers.hpp" PanelLeftSide::PanelLeftSide(QWidget *parent) : SidePanel(parent) { this->getOpenedRect = [this](const QRect& parent_rect) -> QRect { return q_sp::rect_opened_left(this->getPanelSize(), parent_rect); }; this->getClosedRect = [this](const QRect& parent_rect) -> QRect { return q_sp::rect_closed_left(this->getPanelSize(), parent_rect); }; this->alignedHandlerRect = [](const QRect& panel_geom, const QSize& handler_size, qreal) -> QRect { return q_sp::rect_aligned_right_center(panel_geom, handler_size); }; this->initialHandlerSize = []() -> QSize { return {60, 120}; }; this->updateHandler = [](const SidePanelState state, HandlerWidgetT* handler) { switch (state) { case SidePanelState::Opening: { handler->setText("<"); } break; case SidePanelState::Opened: { handler->setText("<"); } break; case SidePanelState::Closing: { handler->setText(">"); } break; case SidePanelState::Closed: { handler->setText(">"); } break; default: break; } }; } PanelLeftSide::~PanelLeftSide() { }
27.340909
101
0.630923
inobelar
2472363c01386672c2bd64fd807a58795b005fbe
2,092
cc
C++
L1TriggerConfig/GMTConfigProducers/src/L1MuGMTChannelMaskOnlineProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
L1TriggerConfig/GMTConfigProducers/src/L1MuGMTChannelMaskOnlineProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
L1TriggerConfig/GMTConfigProducers/src/L1MuGMTChannelMaskOnlineProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "CondTools/L1Trigger/interface/L1ConfigOnlineProdBase.h" #include "CondFormats/L1TObjects/interface/L1MuGMTChannelMask.h" #include "CondFormats/DataRecord/interface/L1MuGMTChannelMaskRcd.h" class L1MuGMTChannelMaskOnlineProducer : public L1ConfigOnlineProdBase<L1MuGMTChannelMaskRcd, L1MuGMTChannelMask> { public: L1MuGMTChannelMaskOnlineProducer(const edm::ParameterSet& iConfig) : L1ConfigOnlineProdBase<L1MuGMTChannelMaskRcd, L1MuGMTChannelMask>(iConfig) {} ~L1MuGMTChannelMaskOnlineProducer() override {} std::unique_ptr<L1MuGMTChannelMask> newObject(const std::string& objectKey) override; private: }; std::unique_ptr<L1MuGMTChannelMask> L1MuGMTChannelMaskOnlineProducer::newObject(const std::string& objectKey) { std::vector<std::string> columns; columns.push_back("ENABLE_RPCB"); columns.push_back("ENABLE_CSC"); columns.push_back("ENABLE_DT"); columns.push_back("ENABLE_RPCF"); // Execute SQL queries to get data from OMDS (using key) and make C++ object // Example: SELECT A_PARAMETER FROM CMS_XXX.XXX_CONF WHERE XXX_CONF.XXX_KEY = objectKey l1t::OMDSReader::QueryResults results = m_omdsReader.basicQuery( columns, "CMS_GMT", "GMT_RUN_SETTINGS", "GMT_RUN_SETTINGS.ID", m_omdsReader.singleAttribute(objectKey)); if (results.queryFailed()) // check if query was successful { edm::LogError("L1-O2O") << "L1MuGMTChannelMaskOnlineProducer: Problem getting " << objectKey << " key from GMT_RUN_SETTING."; return std::unique_ptr<L1MuGMTChannelMask>(); } unsigned mask = 0; bool maskaux; results.fillVariable("ENABLE_RPCB", maskaux); if (!maskaux) mask |= 2; results.fillVariable("ENABLE_CSC", maskaux); if (!maskaux) mask |= 4; results.fillVariable("ENABLE_DT", maskaux); if (!maskaux) mask |= 1; results.fillVariable("ENABLE_RPCF", maskaux); if (!maskaux) mask |= 8; auto gmtchanmask = std::make_unique<L1MuGMTChannelMask>(); gmtchanmask->setSubsystemMask(mask); return gmtchanmask; } DEFINE_FWK_EVENTSETUP_MODULE(L1MuGMTChannelMaskOnlineProducer);
36.068966
115
0.751912
ckamtsikis
2473bab8beb9489d52016119d08a8b903ff7dcf8
5,800
cc
C++
src/developer/debug/zxdb/console/verbs_shared.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
src/developer/debug/zxdb/console/verbs_shared.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
src/developer/debug/zxdb/console/verbs_shared.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/debug/zxdb/client/filter.h" #include "src/developer/debug/zxdb/client/session.h" #include "src/developer/debug/zxdb/console/command_utils.h" #include "src/developer/debug/zxdb/console/console.h" #include "src/developer/debug/zxdb/console/console_context.h" #include "src/developer/debug/zxdb/console/format_job.h" #include "src/developer/debug/zxdb/console/format_target.h" #include "src/developer/debug/zxdb/console/verbs.h" namespace zxdb { namespace { // new --------------------------------------------------------------------------------------------- const char kNewShortHelp[] = "new: Create a new debugger object."; const char kNewHelp[] = R"(<object-type> [ <reference-object-id> ] new Creates a new object of type <object-type>. The settings from the current object will be cloned. If an explicit object index is specified ("process 2 new"), the new one will clone the given one. The new object will be the active one of that type. filter new A filter looks for process launches matching a pattern and automatically attaches to them. Most often, filters are created with the "attach <filter>" command. See "help filter" and "help attach" for more. [zxdb] filter new Filter 2 FIXME job new A job context holds settings (filters, etc.) and possibly a running job. The new context will have no associated job and can then be run or attached. Attach a job context with a job on the target system with "attach-job <koid>". [zxdb] job new Job 2 [Not attached] [zxdb] job 2 attach-job 1960 Job 2 [Attached] koid=1960 process new A process context holds settings (binary name, command line arguments, etc.) and possibly a running process. The new context will have no associated process and can then be run or attached. [zxdb] process new Process 2 [Not running] [zxdb] attach 22860 Attached Process 2 [Running] koid=22860 foobar.cmx )"; Err DoNew(ConsoleContext* context, const Command& cmd) { // Require exactly one noun to be specified for the type of object. if (cmd.nouns().size() != 1u || !cmd.args().empty()) { return Err( "Use \"<object-type> new\" to create a new object of <object-type>.\n" "For example, \"process new\"."); } Console* console = Console::get(); switch (cmd.nouns().begin()->first) { case Noun::kFilter: { Filter* new_filter = context->session()->system().CreateNewFilter(); if (cmd.filter()) { // Clone existing filter's settings. new_filter->SetJob(cmd.filter()->job()); new_filter->SetPattern(cmd.filter()->pattern()); } context->SetActiveFilter(new_filter); console->Output(FormatFilter(context, new_filter)); break; } case Noun::kJob: { JobContext* new_job_context = context->session()->system().CreateNewJobContext(); context->SetActiveJobContext(new_job_context); console->Output(FormatJobContext(context, new_job_context)); break; } case Noun::kProcess: { Target* new_target = context->session()->system().CreateNewTarget(cmd.target()); context->SetActiveTarget(new_target); console->Output(FormatTarget(context, new_target)); break; } default: { std::string noun_name = GetNouns().find(cmd.nouns().begin()->first)->second.aliases[0]; return Err("The \"new\" command is not supported for \"%s\" objects.", noun_name.c_str()); } } return Err(); } // rm -------------------------------------------------------------------------- const char kRmShortHelp[] = "rm: Remove a debugger object."; const char kRmHelp[] = R"(<object-type> [ <object-id> ] rm Removes the given object. Specify an explicit object id ("filter 2 rm") to remove that object, or omit it ("filter rm") to remove the current one (if there is one). To see a list of available objects and their IDs, use the object type by itself ("filter"). filter rm Removes the filter. job rm Removes the job. Any filters tied to this job will also be deleted. )"; Err DoRm(ConsoleContext* context, const Command& cmd) { // Require exactly one noun to be specified for the type of object. if (cmd.nouns().size() != 1u || !cmd.args().empty()) { return Err( "Use \"<object-type> <index> rm\" to delete an object.\n" "For example, \"filter 2 rm\"."); } OutputBuffer description; switch (cmd.nouns().begin()->first) { case Noun::kFilter: { if (cmd.filter()) { description = FormatFilter(context, cmd.filter()); context->session()->system().DeleteFilter(cmd.filter()); } else { return Err("No filter to remove."); } break; } case Noun::kJob: { if (cmd.job_context()) { description = FormatJobContext(context, cmd.job_context()); context->session()->system().DeleteJobContext(cmd.job_context()); } else { return Err("No job to remove."); } break; } default: { std::string noun_name = GetNouns().find(cmd.nouns().begin()->first)->second.aliases[0]; return Err("The \"rm\" command is not supported for \"%s\" objects.", noun_name.c_str()); } } OutputBuffer out("Removed "); out.Append(std::move(description)); Console::get()->Output(out); return Err(); } } // namespace void AppendSharedVerbs(std::map<Verb, VerbRecord>* verbs) { (*verbs)[Verb::kNew] = VerbRecord(&DoNew, {"new"}, kNewShortHelp, kNewHelp, CommandGroup::kGeneral); (*verbs)[Verb::kRm] = VerbRecord(&DoRm, {"rm"}, kRmShortHelp, kRmHelp, CommandGroup::kGeneral); } } // namespace zxdb
33.526012
100
0.647414
casey
24740f8c87f13649a18bb0264ec9969e7e44e74c
1,521
cpp
C++
src/application/ui/rental/view_all_rental_history_ui.cpp
luist18/feup-aeda-proj1
c9d500f3fbc24d36fed85a706926872094c2bf0b
[ "MIT" ]
null
null
null
src/application/ui/rental/view_all_rental_history_ui.cpp
luist18/feup-aeda-proj1
c9d500f3fbc24d36fed85a706926872094c2bf0b
[ "MIT" ]
null
null
null
src/application/ui/rental/view_all_rental_history_ui.cpp
luist18/feup-aeda-proj1
c9d500f3fbc24d36fed85a706926872094c2bf0b
[ "MIT" ]
1
2020-04-03T17:10:34.000Z
2020-04-03T17:10:34.000Z
#include <list> #include "../../../model/rental/rental.h" #include "view_all_rental_history_ui.h" #include "../../../util/io_util.h" ViewAllRentalHistoryUI::ViewAllRentalHistoryUI(UIManager &ui_manager) : controller(ui_manager.getCompany().getRentalManager()) {} void ViewAllRentalHistoryUI::run() { const size_t qt_to_show = 5; const std::list<Rental> &rentals = controller.getAllRentals(); showRentals(rentals, 0, qt_to_show); } void ViewAllRentalHistoryUI::showRentals(const std::list<Rental> &rentals, const int first, const int qt) const { if (rentals.empty()) { cout << "There are no rentals yet." << endl; return; } cout << endl; cout << "Showing rentals ..." << endl; cout << endl; auto it = rentals.begin(); advance(it, first); int i = 0; for (; it != rentals.end() && i < qt; ++it) { cout << (*it).toOneLineDescription() << endl; ++i; } cout << endl; cout << "Previous (a) / Next (d)" << endl; cout << "0 - Main menu" << endl; cout << "Option: "; string option; getline(cin, option); option = option[0]; if (option == "d") { int new_first = first + qt; if (new_first + qt >= rentals.size()) new_first = rentals.size() - qt - 1; if (new_first < 0) new_first = 0; showRentals(rentals, new_first, qt); } else if (option == "a") { int new_first = first - qt; if (new_first < 0) new_first = 0; showRentals(rentals, new_first, qt); } else if (option == "0") return; else { cout << "Invalid input." << endl; showRentals(rentals, first, qt); } }
24.532258
113
0.634451
luist18
247823b2fcf93eeb139a63caf4829f6b3aa21578
2,273
cc
C++
google/cloud/spanner/testing/pick_random_instance.cc
antfitch/google-cloud-cpp-spanner
05a2e3ad3ee0ac96164013ce4d9cfce251059569
[ "Apache-2.0" ]
null
null
null
google/cloud/spanner/testing/pick_random_instance.cc
antfitch/google-cloud-cpp-spanner
05a2e3ad3ee0ac96164013ce4d9cfce251059569
[ "Apache-2.0" ]
null
null
null
google/cloud/spanner/testing/pick_random_instance.cc
antfitch/google-cloud-cpp-spanner
05a2e3ad3ee0ac96164013ce4d9cfce251059569
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "google/cloud/spanner/testing/pick_random_instance.h" #include "google/cloud/spanner/instance_admin_client.h" namespace google { namespace cloud { namespace spanner_testing { inline namespace SPANNER_CLIENT_NS { StatusOr<std::string> PickRandomInstance( google::cloud::internal::DefaultPRNG& generator, std::string const& project_id) { spanner::InstanceAdminClient client(spanner::MakeInstanceAdminConnection()); /** * We started to have integration tests for InstanceAdminClient which creates * and deletes temporary instances. If we pick one of those instances here, * the following tests will fail after the deletion. * InstanceAdminClient's integration tests are using instances prefixed with * "temporary-instances-", so we only pick instances prefixed with * "test-instance-" here for isolation. */ std::vector<std::string> instance_ids; for (auto& instance : client.ListInstances(project_id, "")) { if (!instance) return std::move(instance).status(); auto name = instance->name(); std::string const sep = "/instances/"; std::string const valid_instance_name = sep + "test-instance-"; auto pos = name.rfind(valid_instance_name); if (pos != std::string::npos) { instance_ids.push_back(name.substr(pos + sep.size())); } } if (instance_ids.empty()) { return Status(StatusCode::kInternal, "No available instances for test"); } auto random_index = std::uniform_int_distribution<std::size_t>(0, instance_ids.size() - 1); return instance_ids[random_index(generator)]; } } // namespace SPANNER_CLIENT_NS } // namespace spanner_testing } // namespace cloud } // namespace google
37.883333
79
0.730312
antfitch
247bd112688fb21ced0ac93ae15fb723c9e2e421
3,105
cc
C++
Algorithms/RawPRI/RawPRITest.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
Algorithms/RawPRI/RawPRITest.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
Algorithms/RawPRI/RawPRITest.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
#include <iostream> #include "ace/FILE_Connector.h" #include "ace/Reactor.h" #include "ace/Stream.h" #include "IO/FileWriterTask.h" #include "IO/MessageManager.h" #include "IO/Module.h" #include "IO/Readers.h" #include "Logger/Log.h" #include "Messages/RawVideo.h" #include "Messages/Video.h" #include "UnitTest/UnitTest.h" #include "Utils/FilePath.h" #include "RawPRI.h" using namespace SideCar::Algorithms; using namespace SideCar::IO; using namespace SideCar::Messages; struct Test : public UnitTest::TestObj { Test() : UnitTest::TestObj("RawPRI") {} void test(); }; void Test::test() { Logger::Log::Root().setPriorityLimit(Logger::Priority::kDebug); Utils::TemporaryFilePath testOutputPath("RawPRITestOutput"); { ACE_Stream<ACE_MT_SYNCH> stream; Module<FileWriterTask>* writer = new Module<FileWriterTask>("Writer"); assertEqual(0, stream.push(writer)); assertTrue(writer->getTask()->openAndInit("Video", testOutputPath)); Module<Controller>* controller = new Module<Controller>("RawPRI"); assertEqual(0, stream.push(controller)); assertTrue(controller->getTask()->openAndInit("RawPRI")); controller->getTask()->enterRunState(); RawPRI* rawPRI = dynamic_cast<RawPRI*>(controller->getTask()->getAlgorithm()); assertTrue(rawPRI); int16_t init[] = {0x0000, 0x0003, 0x00FC, 0x00FF, 0xFFFC, 0xFFFF, 0x7FFF}; RawVideo::Ref msg(RawVideo::Make("test", 0.0015339808, 0, 4096, 0, 0.0, 300.0, 7, init, init + 7)); std::cerr << *msg.get() << std::endl; assertEqual(size_t(7), msg->size()); RawVideo::const_iterator pos = msg->begin(); assertEqual(0, *pos++); assertEqual(0x0003, *pos++); assertEqual(0x00FC, *pos++); assertEqual(0x00FF, *pos++); assertEqual(int16_t(0xFFFC), *pos++); assertEqual(int16_t(0xFFFF), *pos++); assertEqual(int16_t(0x7FFF), *pos++); assertTrue(pos == msg->end()); MessageManager mgr(msg); stream.put(mgr.getMessage(), 0); assertFalse(mgr.hasEncoded()); } FileReader::Ref reader(new FileReader); ACE_FILE_Addr inputAddr(testOutputPath.c_str()); ACE_FILE_Connector inputConnector(reader->getDevice(), inputAddr); assertTrue(reader->fetchInput()); assertTrue(reader->isMessageAvailable()); Decoder decoder(reader->getMessage()); { Video::Ref msg(decoder.decode<Video>()); assertEqual(size_t(7), msg->size()); Video::const_iterator pos = msg->begin(); std::cerr << *msg.get() << std::endl; assertEqual(0, *pos++); assertEqual(0x0003, *pos++); assertEqual(0x00FC, *pos++); assertEqual(0x00FF, *pos++); assertEqual(int16_t(0xFFFC), *pos++); assertEqual(int16_t(0xFFFF), *pos++); assertEqual(int16_t(0x7FFF), *pos++); assertTrue(pos == msg->end()); } // Uncomment the following to fail the test and see the log results. assertTrue(false); } int main(int argc, const char* argv[]) { return Test().mainRun(); }
31.683673
107
0.637359
jwillemsen
247bdad5a035d5882800b6810a7ec53368ce88b1
894
hpp
C++
stan/math/prim/fun/as_value_column_array_or_scalar.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/fun/as_value_column_array_or_scalar.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/fun/as_value_column_array_or_scalar.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_FUN_AS_VALUE_COLUMN_ARRAY_OR_SCALAR #define STAN_MATH_PRIM_FUN_AS_VALUE_COLUMN_ARRAY_OR_SCALAR #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/prim/fun/as_column_vector_or_scalar.hpp> #include <stan/math/prim/fun/as_array_or_scalar.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <vector> namespace stan { namespace math { /** * Extract the value from an object and for eigen vectors and `std::vectors` * convert to an eigen column array and for scalars return a scalar. * @tparam T A stan scalar, eigen vector, or `std::vector`. * @param a Specified scalar. * @return the scalar. */ template <typename T> inline auto as_value_column_array_or_scalar(T&& a) { return value_of( as_array_or_scalar(as_column_vector_or_scalar(std::forward<T>(a)))); } } // namespace math } // namespace stan #endif
28.83871
76
0.762864
LaudateCorpus1
247e37797dd0ee0a881cf103d22af936faf33b19
9,735
cpp
C++
TERefiner/HardClipReads.cpp
simoncchu/REPdenovo
708f2f8efc40f6df0a64c1e4049f16e79f65f471
[ "MIT" ]
6
2019-11-11T19:33:21.000Z
2020-03-26T23:41:22.000Z
TERefiner/HardClipReads.cpp
simoncchu/REPdenovo
708f2f8efc40f6df0a64c1e4049f16e79f65f471
[ "MIT" ]
3
2019-08-19T14:14:55.000Z
2020-05-10T23:47:23.000Z
TERefiner/HardClipReads.cpp
simoncchu/REPdenovo
708f2f8efc40f6df0a64c1e4049f16e79f65f471
[ "MIT" ]
1
2020-02-13T15:18:53.000Z
2020-02-13T15:18:53.000Z
/* The MIT License Copyright (c) 20082-2012 by Heng Li <lh3@me.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 "public_parameters.h" #include "HardClipReads.h" #include <fstream> #include <map> using namespace std; #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include <zlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <math.h> #include "kseq.h" KSEQ_INIT(gzFile, gzread) typedef struct { int n, m; uint64_t *a; } reglist_t; #include "khash.h" KHASH_MAP_INIT_STR(reg, reglist_t) typedef kh_reg_t reghash_t; reghash_t *stk_reg_read(const char *fn) { reghash_t *h = kh_init(reg); gzFile fp; kstream_t *ks; int dret; kstring_t *str; // read the list str = (kstring_t *)calloc(1, sizeof(kstring_t)); fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); ks = ks_init(fp); while (ks_getuntil(ks, 0, str, &dret) >= 0) { int beg = -1, end = -1; reglist_t *p; khint_t k = kh_get(reg, h, str->s); if (k == kh_end(h)) { int ret; char *s = strdup(str->s); k = kh_put(reg, h, s, &ret); memset(&kh_val(h, k), 0, sizeof(reglist_t)); } p = &kh_val(h, k); if (dret != '\n') { if (ks_getuntil(ks, 0, str, &dret) > 0 && isdigit(str->s[0])) { beg = atoi(str->s); if (dret != '\n') { if (ks_getuntil(ks, 0, str, &dret) > 0 && isdigit(str->s[0])) { end = atoi(str->s); if (end < 0) end = -1; } } } } // skip the rest of the line if (dret != '\n') while ((dret = ks_getc(ks)) > 0 && dret != '\n'); if (end < 0 && beg > 0) end = beg, beg = beg - 1; // if there is only one column if (beg < 0) beg = 0, end = INT_MAX; if (p->n == p->m) { p->m = p->m? p->m<<1 : 4; p->a = (uint64_t*)realloc(p->a, p->m * 8); } p->a[p->n++] = (uint64_t)beg<<32 | end; } ks_destroy(ks); gzclose(fp); free(str->s); free(str); return h; } void stk_reg_destroy(reghash_t *h) { khint_t k; if (h == 0) return; for (k = 0; k < kh_end(h); ++k) { if (kh_exist(h, k)) { free(kh_val(h, k).a); free((char*)kh_key(h, k)); } } kh_destroy(reg, h); } /* constant table */ unsigned char seq_nt16_table[256] = { 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15 /*'-'*/,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15, 15,15, 5, 6, 8,15, 7, 9, 0,10,15,15, 15,15,15,15, 15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15, 15,15, 5, 6, 8,15, 7, 9, 0,10,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15 }; char *seq_nt16_rev_table = "XACMGRSVTWYHKDBN"; unsigned char seq_nt16to4_table[] = { 4, 0, 1, 4, 2, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4 }; unsigned char seq_nt16comp_table[] = { 0, 8, 4, 12, 2, 10, 9, 14, 1, 6, 5, 13, 3, 11, 7, 15 }; int bitcnt_table[] = { 4, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; char comp_tab[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 'T', 'V', 'G', 'H', 'E', 'F', 'C', 'D', 'I', 'J', 'M', 'L', 'K', 'N', 'O', 'P', 'Q', 'Y', 'S', 'A', 'A', 'B', 'W', 'X', 'R', 'Z', 91, 92, 93, 94, 95, 64, 't', 'v', 'g', 'h', 'e', 'f', 'c', 'd', 'i', 'j', 'm', 'l', 'k', 'n', 'o', 'p', 'q', 'y', 's', 'a', 'a', 'b', 'w', 'x', 'r', 'z', 123, 124, 125, 126, 127 }; static void stk_printstr(const kstring_t *s, unsigned line_len) { if (line_len != UINT_MAX && line_len != 0) { int i, rest = s->l; for (i = 0; i < s->l; i += line_len, rest -= line_len) { putchar('\n'); if (rest > line_len) fwrite(s->s + i, 1, line_len, stdout); else fwrite(s->s + i, 1, rest, stdout); } putchar('\n'); } else { putchar('\n'); puts(s->s); } } void stk_printseq(const kseq_t *s, int line_len) { putchar(s->qual.l? '@' : '>'); fputs(s->name.s, stdout); if (s->comment.l) { putchar(' '); fputs(s->comment.s, stdout); } stk_printstr(&s->seq, line_len); if (s->qual.l) { putchar('+'); stk_printstr(&s->qual, line_len); } } /* 64-bit Mersenne Twister pseudorandom number generator. Adapted from: http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/C-LANG/mt19937-64.c which was written by Takuji Nishimura and Makoto Matsumoto and released under the 3-clause BSD license. */ typedef uint64_t krint64_t; struct _krand_t; typedef struct _krand_t krand_t; #define KR_NN 312 #define KR_MM 156 #define KR_UM 0xFFFFFFFF80000000ULL /* Most significant 33 bits */ #define KR_LM 0x7FFFFFFFULL /* Least significant 31 bits */ struct _krand_t { int mti; krint64_t mt[KR_NN]; }; static void kr_srand0(krint64_t seed, krand_t *kr) { kr->mt[0] = seed; for (kr->mti = 1; kr->mti < KR_NN; ++kr->mti) kr->mt[kr->mti] = 6364136223846793005ULL * (kr->mt[kr->mti - 1] ^ (kr->mt[kr->mti - 1] >> 62)) + kr->mti; } krand_t *kr_srand(krint64_t seed) { krand_t *kr; kr = (krand_t *)malloc(sizeof(krand_t)); kr_srand0(seed, kr); return kr; } krint64_t kr_rand(krand_t *kr) { krint64_t x; static const krint64_t mag01[2] = { 0, 0xB5026F5AA96619E9ULL }; if (kr->mti >= KR_NN) { int i; if (kr->mti == KR_NN + 1) kr_srand0(5489ULL, kr); for (i = 0; i < KR_NN - KR_MM; ++i) { x = (kr->mt[i] & KR_UM) | (kr->mt[i+1] & KR_LM); kr->mt[i] = kr->mt[i + KR_MM] ^ (x>>1) ^ mag01[(int)(x&1)]; } for (; i < KR_NN - 1; ++i) { x = (kr->mt[i] & KR_UM) | (kr->mt[i+1] & KR_LM); kr->mt[i] = kr->mt[i + (KR_MM - KR_NN)] ^ (x>>1) ^ mag01[(int)(x&1)]; } x = (kr->mt[KR_NN - 1] & KR_UM) | (kr->mt[0] & KR_LM); kr->mt[KR_NN - 1] = kr->mt[KR_MM - 1] ^ (x>>1) ^ mag01[(int)(x&1)]; kr->mti = 0; } x = kr->mt[kr->mti++]; x ^= (x >> 29) & 0x5555555555555555ULL; x ^= (x << 17) & 0x71D67FFFEDA60000ULL; x ^= (x << 37) & 0xFFF7EEE000000000ULL; x ^= (x >> 43); return x; } #define kr_drand(_kr) ((kr_rand(_kr) >> 11) * (1.0/9007199254740992.0)) /* subseq */ int stk_subseq(const char* freads, const char* fid, const char* fout_raw) { khash_t(reg) *h = kh_init(reg); gzFile fp; kseq_t *seq; int l, i, j, is_tab = 0, line = 0; khint_t k; h = stk_reg_read(fid); FILE * pFile; pFile = fopen (fout_raw,"w"); // subseq fp=gzopen(freads, "r"); seq = kseq_init(fp); while ((l = kseq_read(seq)) >= 0) { reglist_t *p; k = kh_get(reg, h, seq->name.s); if (k == kh_end(h)) continue; p = &kh_val(h, k); for (i = 0; i < p->n; ++i) { int beg = p->a[i]>>32, end = p->a[i]; if (beg >= seq->seq.l) { fprintf(stderr, "[subseq] %s: %d >= %ld\n", seq->name.s, beg, seq->seq.l); continue; } if (end > seq->seq.l) end = seq->seq.l; if (is_tab == 0) { //printf("%c%s", seq->qual.l == seq->seq.l? '@' : '>', seq->name.s); fprintf(pFile, "%s", seq->name.s); if (beg > 0 || (int)p->a[i] != INT_MAX) { if (end == INT_MAX) { if (beg) fprintf(pFile,":%d", beg+1); } else fprintf(pFile,":%d-%d", beg+1, end); } } else fprintf(pFile,"%s\t%d\t", seq->name.s, beg + 1); if (end > seq->seq.l) end = seq->seq.l; for (j = 0; j < end - beg; ++j) { if (is_tab == 0 && (j == 0 || (line > 0 && j % line == 0))) fprintf(pFile,"%c",'\t');//putchar('\t'); /*putchar('\n');*/ //putchar(seq->seq.s[j + beg]); fprintf(pFile,"%c",seq->seq.s[j + beg]); } //putchar('\n'); if (seq->qual.l != seq->seq.l || is_tab) continue; //printf("+"); for (j = 0; j < end - beg; ++j) { if (j == 0 || (line > 0 && j % line == 0)) {/*putchar('\n');*/} //putchar(seq->qual.s[j + beg]); } fprintf(pFile,"%c",'\n');//putchar('\n'); } } fclose(pFile); // free kseq_destroy(seq); gzclose(fp); stk_reg_destroy(h); return 0; } void HardClipReads::traceRawReadById(string fleft_fastq, string fright_fastq) { //trace left hard-clip reads stk_subseq(fleft_fastq.c_str(), fname_left_hclip.c_str(), fname_lhclip_raw.c_str()); //trace right hard-clip reads stk_subseq(fright_fastq.c_str(), fname_right_hclip.c_str(), fname_rhclip_raw.c_str()); }
30.139319
124
0.571443
simoncchu
247e76eb1c02396e67955e75d55929d252af6e8c
9,124
cc
C++
src/so/so.cc
emer/pdpp
ccce243ae356dc5908cdd667419a7afd74cf22ad
[ "BSD-3-Clause" ]
null
null
null
src/so/so.cc
emer/pdpp
ccce243ae356dc5908cdd667419a7afd74cf22ad
[ "BSD-3-Clause" ]
null
null
null
src/so/so.cc
emer/pdpp
ccce243ae356dc5908cdd667419a7afd74cf22ad
[ "BSD-3-Clause" ]
null
null
null
/* -*- C++ -*- */ /*============================================================================= // // // This file is part of the PDP++ software package. // // // // Copyright (C) 1995 Randall C. O'Reilly, Chadley K. Dawson, // // James L. McClelland, and Carnegie Mellon University // // // // Permission to use, copy, and modify this software and its documentation // // for any purpose other than distribution-for-profit is hereby granted // // without fee, provided that the above copyright notice and this permission // // notice appear in all copies of the software and related documentation. // // // // Permission to distribute the software or modified or extended versions // // thereof on a not-for-profit basis is explicitly granted, under the above // // conditions. HOWEVER, THE RIGHT TO DISTRIBUTE THE SOFTWARE OR MODIFIED OR // // EXTENDED VERSIONS THEREOF FOR PROFIT IS *NOT* GRANTED EXCEPT BY PRIOR // // ARRANGEMENT AND WRITTEN CONSENT OF THE COPYRIGHT HOLDERS. // // // // Note that the taString class, which is derived from the GNU String class, // // is Copyright (C) 1988 Free Software Foundation, written by Doug Lea, and // // is covered by the GNU General Public License, see ta_string.h. // // The iv_graphic library and some iv_misc classes were derived from the // // InterViews morpher example and other InterViews code, which is // // Copyright (C) 1987, 1988, 1989, 1990, 1991 Stanford University // // Copyright (C) 1991 Silicon Graphics, Inc. // // // // THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, // // EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY // // WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. // // // // IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE FOR ANY SPECIAL, // // INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES // // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT // // ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, // // ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS // // SOFTWARE. // ==============================================================================*/ // so.cc #include "so.h" ////////////////////////// // Con,Spec // ////////////////////////// void SoConSpec::Initialize() { min_obj_type = &TA_SoCon_Group; lrate = 0.1f; wt_limits.min = 0.0f; wt_limits.max = 1.0f; wt_limits.type = WeightLimits::MIN_MAX; avg_act_source = LAYER_AVG_ACT; rnd.mean = .5; } void SoConSpec::InitLinks() { ConSpec::InitLinks(); } void SoCon_Group::Initialize() { spec.SetBaseType(&TA_SoConSpec); avg_in_act = 0.0f; } void HebbConSpec::Initialize() { wt_limits.min = -1.0f; wt_limits.max = 1.0f; } ////////////////////////// // Unit,Spec // ////////////////////////// void SoUnitSpec::Initialize() { min_obj_type = &TA_SoUnit; } void SoUnitSpec::InitState(Unit* u) { UnitSpec::InitState(u); ((SoUnit*)u)->act_i = 0.0f; } void SoUnitSpec::Compute_Act(Unit* u) { // simple linear function if(u->ext_flag & Unit::EXT) u->act = u->ext; else u->act = u->net; } void SoUnitSpec::Compute_AvgInAct(Unit* u) { SoCon_Group* recv_gp; int g; FOR_ITR_GP(SoCon_Group, recv_gp, u->recv., g) { if(!recv_gp->prjn->from->lesion) recv_gp->Compute_AvgInAct(u); } } void SoUnitSpec::GraphActFun(GraphLog* graph_log, float min, float max) { if(graph_log == NULL) { graph_log = (GraphLog*) pdpMisc::GetNewLog(GET_MY_OWNER(Project), &TA_GraphLog); if(graph_log == NULL) return; } graph_log->name = name + ": Act Fun"; DataTable* dt = &(graph_log->data); dt->Reset(); dt->NewColFloat("netin"); dt->NewColFloat("act"); SoUnit un; float x; for(x = min; x <= max; x += .01f) { un.net = x; Compute_Act(&un); dt->AddBlankRow(); dt->SetLastFloatVal(x, 0); dt->SetLastFloatVal(un.act, 1); } dt->UpdateAllRanges(); graph_log->ViewAllData(); } void ThreshLinSoUnitSpec::Initialize() { threshold = 0.0f; } void ThreshLinSoUnitSpec::Compute_Act(Unit* u) { if(u->ext_flag & Unit::EXT) u->act = u->ext; else u->act = (u->net > threshold) ? (u->net - threshold) : 0.0f; } void SoUnit::Initialize() { spec.SetBaseType(&TA_SoUnitSpec); act_i = 0.0f; } ////////////////////////// // Layer,Spec // ////////////////////////// void SoLayerSpec::Initialize() { min_obj_type = &TA_SoLayer; netin_type = MAX_NETIN_WINS; // competitive learning style } SoUnit* SoLayerSpec::FindMaxNetIn(SoLayer* lay) { SoUnitSpec* uspec = (SoUnitSpec*)lay->unit_spec.spec; float max_val = -1.0e20; SoUnit* max_val_u = NULL; SoUnit* u; taLeafItr i; FOR_ITR_EL(SoUnit, u, lay->units., i) { u->act = uspec->act_range.min; u->act_i = uspec->act_range.min; if(u->net > max_val) { max_val_u = u; max_val = u->net; } } return max_val_u; } SoUnit* SoLayerSpec::FindMinNetIn(SoLayer* lay) { SoUnitSpec* uspec = (SoUnitSpec*)lay->unit_spec.spec; float min_val = 1.0e20; SoUnit* min_val_u = NULL; SoUnit* u; taLeafItr i; FOR_ITR_EL(SoUnit, u, lay->units., i) { u->act = uspec->act_range.min; u->act_i = uspec->act_range.min; if(u->net < min_val) { min_val_u = u; min_val = u->net; } } return min_val_u; } SoUnit* SoLayerSpec::FindWinner(SoLayer* lay) { if(netin_type == MAX_NETIN_WINS) return FindMaxNetIn(lay); return FindMinNetIn(lay); } // default layerspec just iterates over units void SoLayerSpec::Compute_Net(SoLayer* lay) { Unit* u; taLeafItr i; FOR_ITR_EL(Unit, u, lay->units., i) u->Compute_Net(); } void SoLayerSpec::Compute_Act(SoLayer* lay) { Unit* u; taLeafItr i; FOR_ITR_EL(Unit, u, lay->units., i) u->Compute_Act(); Compute_AvgAct(lay); // always compute average layer act.. } void SoLayerSpec::Compute_dWt(SoLayer* lay) { Unit* u; taLeafItr i; FOR_ITR_EL(Unit, u, lay->units., i) u->Compute_dWt(); } void SoLayerSpec::UpdateWeights(SoLayer* lay) { Unit* u; taLeafItr i; FOR_ITR_EL(Unit, u, lay->units., i) u->UpdateWeights(); } void SoLayerSpec::Compute_AvgAct(SoLayer* lay) { lay->sum_act = 0.0f; if(lay->units.leaves == 0) return; Unit* u; taLeafItr i; FOR_ITR_EL(Unit, u, lay->units., i) lay->sum_act += u->act; lay->avg_act = lay->sum_act / (float)lay->units.leaves; } void SoLayer::Copy_(const SoLayer& cp) { spec = cp.spec; avg_act = cp.avg_act; sum_act = cp.sum_act; } void SoLayer::Initialize() { spec.SetBaseType(&TA_SoLayerSpec); units.SetBaseType(&TA_SoUnit); unit_spec.SetBaseType(&TA_SoUnitSpec); avg_act = 0.0f; sum_act = 0.0f; winner = NULL; } void SoLayer::InitLinks() { Layer::InitLinks(); spec.SetDefaultSpec(this); } void SoLayer::CutLinks() { spec.CutLinks(); Layer::CutLinks(); winner = NULL; } bool SoLayer::SetLayerSpec(LayerSpec* sp) { if(sp == NULL) return false; if(sp->CheckObjectType(this)) spec.SetSpec((SoLayerSpec*)sp); else return false; return true; } ////////////////////////// // Processes // ////////////////////////// void SoTrial::Initialize() { min_unit = &TA_SoUnit; min_con_group = &TA_SoCon_Group; min_con = &TA_SoCon; min_layer = &TA_SoLayer; } void SoTrial::Compute_Act() { // compute activations in feed-forward fashion Layer* lay; taLeafItr l; FOR_ITR_EL(Layer, lay, network->layers., l) { lay->Compute_Net(); #ifdef DMEM_COMPILE lay->DMem_SyncNet(); #endif lay->Compute_Act(); } } void SoTrial::Compute_dWt() { network->Compute_dWt(); } void SoTrial::Loop() { network->InitExterns(); if(cur_event) { cur_event->ApplyPatterns(network); } Compute_Act(); // compute the delta - weight (only if not testing...) if((epoch_proc != NULL) && (epoch_proc->wt_update != EpochProcess::TEST)) Compute_dWt(); // weight update taken care of by the process } bool SoTrial::CheckNetwork() { if(network && (network->dmem_sync_level != Network::DMEM_SYNC_LAYER)) { network->dmem_sync_level = Network::DMEM_SYNC_LAYER; } return TrialProcess::CheckNetwork(); } ////////////////////////////////// // Simple SoftMax // ////////////////////////////////// void SoftMaxLayerSpec::Initialize() { softmax_gain = 1.0f; } void SoftMaxLayerSpec::Compute_Act(SoLayer* lay) { if(lay->ext_flag & Unit::EXT) { // input layer SoLayerSpec::Compute_Act(lay); return; } SoUnitSpec* uspec = (SoUnitSpec*)lay->unit_spec.spec; float sum = 0.0f; Unit* u; taLeafItr i; FOR_ITR_EL(Unit, u, lay->units., i) { u->Compute_Act(); u->act = expf(softmax_gain * u->net); // e to the net sum += u->act; } FOR_ITR_EL(Unit, u, lay->units., i) { u->act = uspec->act_range.Project(u->act / sum); // normalize by sum, rescale to act range range } Compute_AvgAct(lay); }
25.994302
84
0.612231
emer
247fe0aaaccabce6151516dcb6e2b2bd5f98a08c
375
cpp
C++
codeforces/contests/round/452-div2/a.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
codeforces/contests/round/452-div2/a.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
codeforces/contests/round/452-div2/a.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <cpplib/stdinc.hpp> int32_t main(){ desync(); int n; cin >> n; int a = 0, b = 0; for(int i=0; i<n; ++i){ int x; cin >> x; if(x == 1) a++; else b++; } int ans = a/3; for(int i=1; i<=min(a, b); ++i) ans = max(ans, i + (a - i)/3); cout << ans << endl; return 0; }
17.045455
38
0.365333
tysm
248549609861a709e59c17a09dd585989e60102b
3,703
cc
C++
tensorflow/cc/ops/control_flow_ops.cc
shishaochen/TensorFlow-0.8-Win
63221dfc4f1a1d064308e632ba12e6a54afe1fd8
[ "Apache-2.0" ]
1
2017-09-14T23:59:05.000Z
2017-09-14T23:59:05.000Z
tensorflow/cc/ops/control_flow_ops.cc
shishaochen/TensorFlow-0.8-Win
63221dfc4f1a1d064308e632ba12e6a54afe1fd8
[ "Apache-2.0" ]
1
2016-10-19T02:43:04.000Z
2016-10-31T14:53:06.000Z
tensorflow/cc/ops/control_flow_ops.cc
shishaochen/TensorFlow-0.8-Win
63221dfc4f1a1d064308e632ba12e6a54afe1fd8
[ "Apache-2.0" ]
8
2016-10-23T00:50:02.000Z
2019-04-21T11:11:57.000Z
// This file is MACHINE GENERATED! Do not edit. #include "tensorflow/cc/ops/control_flow_ops.h" #include "tensorflow/core/graph/node_builder.h" namespace tensorflow { namespace ops { Node* Abort(const GraphDefBuilder::Options& opts) { static const string kOpName = "Abort"; return SourceOp(kOpName, opts); } Node* ControlTrigger(const GraphDefBuilder::Options& opts) { static const string kOpName = "ControlTrigger"; return SourceOp(kOpName, opts); } Node* Enter(NodeOut data, StringPiece frame_name, const GraphDefBuilder::Options& opts) { if (opts.HaveError()) return nullptr; static const string kOpName = "Enter"; NodeBuilder node_builder(opts.GetNameForOp(kOpName), kOpName, opts.op_registry()); node_builder.Input(data); node_builder.Attr("frame_name", frame_name); return opts.FinalizeBuilder(&node_builder); } Node* Exit(NodeOut data, const GraphDefBuilder::Options& opts) { static const string kOpName = "Exit"; return UnaryOp(kOpName, data, opts); } Node* LoopCond(NodeOut input, const GraphDefBuilder::Options& opts) { static const string kOpName = "LoopCond"; return UnaryOp(kOpName, input, opts); } Node* Merge(gtl::ArraySlice<NodeOut> inputs, const GraphDefBuilder::Options& opts) { if (opts.HaveError()) return nullptr; static const string kOpName = "Merge"; NodeBuilder node_builder(opts.GetNameForOp(kOpName), kOpName, opts.op_registry()); node_builder.Input(inputs); return opts.FinalizeBuilder(&node_builder); } Node* NextIteration(NodeOut data, const GraphDefBuilder::Options& opts) { static const string kOpName = "NextIteration"; return UnaryOp(kOpName, data, opts); } Node* RefEnter(NodeOut data, StringPiece frame_name, const GraphDefBuilder::Options& opts) { if (opts.HaveError()) return nullptr; static const string kOpName = "RefEnter"; NodeBuilder node_builder(opts.GetNameForOp(kOpName), kOpName, opts.op_registry()); node_builder.Input(data); node_builder.Attr("frame_name", frame_name); return opts.FinalizeBuilder(&node_builder); } Node* RefExit(NodeOut data, const GraphDefBuilder::Options& opts) { static const string kOpName = "RefExit"; return UnaryOp(kOpName, data, opts); } Node* RefMerge(gtl::ArraySlice<NodeOut> inputs, const GraphDefBuilder::Options& opts) { if (opts.HaveError()) return nullptr; static const string kOpName = "RefMerge"; NodeBuilder node_builder(opts.GetNameForOp(kOpName), kOpName, opts.op_registry()); node_builder.Input(inputs); return opts.FinalizeBuilder(&node_builder); } Node* RefNextIteration(NodeOut data, const GraphDefBuilder::Options& opts) { static const string kOpName = "RefNextIteration"; return UnaryOp(kOpName, data, opts); } Node* RefSelect(NodeOut index, gtl::ArraySlice<NodeOut> inputs, const GraphDefBuilder::Options& opts) { if (opts.HaveError()) return nullptr; static const string kOpName = "RefSelect"; NodeBuilder node_builder(opts.GetNameForOp(kOpName), kOpName, opts.op_registry()); node_builder.Input(index); node_builder.Input(inputs); return opts.FinalizeBuilder(&node_builder); } Node* RefSwitch(NodeOut data, NodeOut pred, const GraphDefBuilder::Options& opts) { static const string kOpName = "RefSwitch"; return BinaryOp(kOpName, data, pred, opts); } Node* Switch(NodeOut data, NodeOut pred, const GraphDefBuilder::Options& opts) { static const string kOpName = "Switch"; return BinaryOp(kOpName, data, pred, opts); } } // namespace ops } // namespace tensorflow
33.0625
79
0.706454
shishaochen
2486d4b4ca6ead6c8a6b3b0be35db8628c79d0c2
1,998
cpp
C++
odetest02.cpp
yoggy/odetest
9fd121098b436092509b098db38519d8fc2e8526
[ "MIT" ]
null
null
null
odetest02.cpp
yoggy/odetest
9fd121098b436092509b098db38519d8fc2e8526
[ "MIT" ]
null
null
null
odetest02.cpp
yoggy/odetest
9fd121098b436092509b098db38519d8fc2e8526
[ "MIT" ]
null
null
null
// // odetest02.cpp - simple free fall & bound test // #include <ode/ode.h> #include <ncurses.h> #include <unistd.h> dWorldID world; dJointGroupID contactgroup; static void nearCallback(void *data, dGeomID o1, dGeomID o2) { const int N = 10; dContact contact[N]; int n = dCollide(o1, o2, N, &contact[0].geom, sizeof(dContact)); for (int i = 0; i < n; i++) { contact[i].surface.mode = dContactBounce; contact[i].surface.mu = 0.0; contact[i].surface.bounce = 0.7; contact[i].surface.bounce_vel = 0.01; dJointID c = dJointCreateContact(world, contactgroup, &contact[i]); dJointAttach(c, dGeomGetBody(contact[i].geom.g1), dGeomGetBody(contact[i].geom.g2)); } } int main (int argc, char **argv) { initscr(); dInitODE(); // setup world world = dWorldCreate(); dWorldSetGravity(world, 0, 0, -9.8); dSpaceID space = dHashSpaceCreate(0); contactgroup = dJointGroupCreate(0); // grand plane (for collision) dGeomID ground = dCreatePlane(space, 0, 0, 1, 0); // body dBodyID ball = dBodyCreate(world); // mass dMass m; dMassSetZero(&m); const dReal radius = 0.2; // 20cm const dReal mass = 1.0; // 1kg dMassSetSphereTotal(&m, mass, radius); dBodySetMass(ball, &m); dBodySetPosition(ball, 0.0, 0.0, 10); // x=0m, y=0m, z=10m dGeomID geom = dCreateSphere(space, radius); dGeomSetBody(geom, ball); // simulation loop (1000 step) dReal stepsize = 0.01; // 0.01ms for (int i = 0; i < 1000; ++i) { dSpaceCollide(space, 0, &nearCallback); dWorldStep(world, 0.01); dJointGroupEmpty(contactgroup); // draw erase(); const dReal *pos = dBodyGetPosition(ball); const dReal *R = dBodyGetRotation(ball); mvprintw((int)(12-pos[2]), 5, "*"); // ball mvprintw(12, 0, "============================"); // ground // draw move(0, 0); printw("t=%f, pos=(%f, %f, %f) \n", stepsize * i, pos[0], pos[1], pos[2]); refresh(); usleep(10 * 1000); } // cleanup dWorldDestroy(world); dCloseODE(); endwin(); return 0; }
21.031579
86
0.631632
yoggy
248777dae7d01164b3d2928d2aed3fe2a25f6e7e
2,650
hpp
C++
src/ibeo_8l_sdk/src/ibeosdk/datablocks/PointCloudPlane7510.hpp
tomcamp0228/ibeo_ros2
ff56c88d6e82440ae3ce4de08f2745707c354604
[ "MIT" ]
1
2020-06-19T11:01:49.000Z
2020-06-19T11:01:49.000Z
include/ibeosdk/datablocks/PointCloudPlane7510.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
null
null
null
include/ibeosdk/datablocks/PointCloudPlane7510.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
2
2020-06-19T11:01:48.000Z
2020-10-29T03:07:14.000Z
//====================================================================== /*! \file PointCloudPlane7510.hpp *\verbatim * ------------------------------------------ * (C) 2016 Ibeo Automotive Systems GmbH, Hamburg, Germany * ------------------------------------------ * * Created on: Mar 15, 2016 * by: Kristian Bischoff *\endverbatim *///------------------------------------------------------------------- //====================================================================== #ifndef POINTCLOUDPLANE7510_HPP_SEEN #define POINTCLOUDPLANE7510_HPP_SEEN //====================================================================== #include <ibeosdk/misc/WinCompatibility.hpp> #include <ibeosdk/datablocks/RegisteredDataBlock.hpp> #include <ibeosdk/datablocks/snippets/PlanePoint.hpp> #include <ibeosdk/datablocks/snippets/PointCloudBase.hpp> #include <vector> //====================================================================== namespace ibeosdk { //====================================================================== class PointCloudPlane7510 : public RegisteredDataBlock<PointCloudPlane7510>, public PointCloudBase { public: PointCloudPlane7510() : PointCloudBase() {} virtual ~PointCloudPlane7510() {} public: virtual std::streamsize getSerializedSize() const; virtual DataTypeId getDataType() const; virtual bool deserialize(std::istream& is, const IbeoDataHeader& dh); virtual bool serialize(std::ostream& os) const; public: virtual bool empty() const { return m_points.empty(); } public: typedef CustomIterator<PlanePoint, std::vector<PlanePoint>::iterator, PlanePointProxy, PlanePointProxy, PointCloudPlane7510, PointCloudPlane7510> iterator; typedef CustomIterator<PlanePoint , std::vector<PlanePoint>::const_iterator, PlanePointProxy const, PlanePointProxy, PointCloudPlane7510 const, PointCloudPlane7510> const_iterator; virtual iterator begin() { return iterator(m_points.begin(), this); } virtual iterator end() { return iterator(m_points.end(), this); } virtual const_iterator begin() const { return const_iterator(m_points.begin(), this); } virtual const_iterator end() const { return const_iterator(m_points.end(), this); } void push_back(const PlanePoint& point) { m_points.push_back(point); } private: std::vector<PlanePoint> m_points; }; // PointCloudPlane7510 //====================================================================== } // namespace ibeosdk //====================================================================== #endif // POINTCLOUDPLANE7510_HPP_SEEN //======================================================================
35.333333
181
0.548679
tomcamp0228
24894c0176346f59b7ff2438ae254a9da1dfd571
486
cpp
C++
gmsh-4.2.2/demos/api/onelab_data.cpp
Poofee/fastFEM
14eb626df973e2123604041451912c867ab7188c
[ "MIT" ]
4
2019-05-06T09:35:08.000Z
2021-05-14T16:26:45.000Z
onelab/share/doc/gmsh/demos/api/onelab_data.cpp
Christophe-Foyer/pyFEA
344996d6b075ee4b2214283f0af8159d86d154fd
[ "MIT" ]
null
null
null
onelab/share/doc/gmsh/demos/api/onelab_data.cpp
Christophe-Foyer/pyFEA
344996d6b075ee4b2214283f0af8159d86d154fd
[ "MIT" ]
1
2020-12-15T13:47:23.000Z
2020-12-15T13:47:23.000Z
#include <iostream> #include <gmsh.h> int main(int argc, char **argv) { if(argc < 2){ std::cout << "Usage: " << argv[0] << " file [options]" << std::endl; return 0; } gmsh::initialize(); gmsh::option::setNumber("General.Terminal", 1); gmsh::open(argv[1]); // attempts to run a client selected when opening the file (e.g. a .pro file) gmsh::onelab::run(); std::string json; gmsh::onelab::get(json); std::cout << json; gmsh::finalize(); return 0; }
18
79
0.59465
Poofee
248feb2e5cba068ec2e626244553d2d7f758bbba
3,475
hh
C++
include/ignition/physics/Geometry.hh
jspricke/ign-physics
abd7c4562e96eb2adcf0dea9b8c8ca3dcccd4790
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/ignition/physics/Geometry.hh
jspricke/ign-physics
abd7c4562e96eb2adcf0dea9b8c8ca3dcccd4790
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/ignition/physics/Geometry.hh
jspricke/ign-physics
abd7c4562e96eb2adcf0dea9b8c8ca3dcccd4790
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef IGNITION_PHYSICS_GEOMETRY_HH_ #define IGNITION_PHYSICS_GEOMETRY_HH_ #include <Eigen/Geometry> #define DETAIL_IGN_PHYSICS_MAKE_BOTH_PRECISIONS(Type, Dim) \ using Type ## Dim ## d = Type<double, Dim>; \ using Type ## Dim ## f = Type<float, Dim>; /// \brief This macro defines the following types: /// Type2d // 2-dimensional version of Type with double precision /// Type2f // 2-dimensional version of Type with float precision /// Type3d // 3-dimensional version of Type with double precision /// Type3f // 3-dimensional version of Type with float precision #define IGN_PHYSICS_MAKE_ALL_TYPE_COMBOS(Type) \ DETAIL_IGN_PHYSICS_MAKE_BOTH_PRECISIONS(Type, 2) \ DETAIL_IGN_PHYSICS_MAKE_BOTH_PRECISIONS(Type, 3) namespace ignition { namespace physics { /// \brief This is used by ignition-physics to represent rigid body /// transforms in 2D or 3D simulations. The precision can be chosen as /// float or scalar. template <typename Scalar, std::size_t Dim> using Pose = Eigen::Transform<Scalar, Dim, Eigen::Isometry>; IGN_PHYSICS_MAKE_ALL_TYPE_COMBOS(Pose) template <typename Scalar, std::size_t Dim> using Vector = Eigen::Matrix<Scalar, Dim, 1>; IGN_PHYSICS_MAKE_ALL_TYPE_COMBOS(Vector) template <typename Scalar, std::size_t Dim> using LinearVector = Vector<Scalar, Dim>; IGN_PHYSICS_MAKE_ALL_TYPE_COMBOS(LinearVector) template <typename Scalar, std::size_t Dim> using AngularVector = Vector<Scalar, (Dim*(Dim-1))/2>; IGN_PHYSICS_MAKE_ALL_TYPE_COMBOS(AngularVector) template <typename Scalar, std::size_t Dim> struct Wrench { AngularVector<Scalar, Dim> torque; LinearVector<Scalar, Dim> force; }; IGN_PHYSICS_MAKE_ALL_TYPE_COMBOS(Wrench) template <typename Scalar, std::size_t Dim> using AlignedBox = Eigen::AlignedBox<Scalar, Dim>; IGN_PHYSICS_MAKE_ALL_TYPE_COMBOS(AlignedBox) ///////////////////////////////////////////////// /// \brief This struct is used to conveniently convert from a policy to a /// geometric type. Example usage: /// /// using AngularVector = FromPolicy<FeaturePolicy3d>::To<AngularVector>; template <typename PolicyT> struct FromPolicy { using Scalar = typename PolicyT::Scalar; enum { Dim = PolicyT::Dim }; template<template <typename, std::size_t> class Type> using Use = Type<Scalar, Dim>; }; template<typename Scalar> Eigen::Rotation2D<Scalar> Rotate( const Scalar &_angle, const AngularVector<Scalar, 2> &_axis) { return Eigen::Rotation2D<Scalar>(_angle*_axis[0]); } template <typename Scalar> Eigen::AngleAxis<Scalar> Rotate( const Scalar &_angle, const AngularVector<Scalar, 3> &_axis) { return Eigen::AngleAxis<Scalar>(_angle, _axis); } } } #endif
33.095238
77
0.699281
jspricke
2490d796d308211a5a203296e845088c5207edd0
15,105
cpp
C++
c/wikipedia/wikipedia_tuple_map_impl.cpp
mmonto7/small-world-graph
8ea1015c24065cb71875620b28c66ffb8348dcae
[ "MIT" ]
3
2016-05-31T07:23:27.000Z
2018-02-16T00:06:04.000Z
c/wikipedia/wikipedia_tuple_map_impl.cpp
mmonto7/small-world-graph
8ea1015c24065cb71875620b28c66ffb8348dcae
[ "MIT" ]
2
2020-08-31T20:51:20.000Z
2021-03-30T18:05:25.000Z
c/wikipedia/wikipedia_tuple_map_impl.cpp
mmonto7/small-world-graph
8ea1015c24065cb71875620b28c66ffb8348dcae
[ "MIT" ]
4
2015-01-17T07:31:25.000Z
2020-08-31T20:49:41.000Z
#include "wikipedia_tuple_map_impl.h" #include "benchmark.h" #include <sys/stat.h> #include "wikipedia_stopword_list.h" #include "string_utils.h" #include <valgrind/callgrind.h> WikipediaTupleMapImpl::WikipediaTupleMapImpl() { id_tuple_table_ = NULL; tuples_.set_deleted_key(NULL); } void WikipediaTupleMapImpl::load(const char* index_root) { stop_words_ = new WordList(__wikipedia_stopwords); cout << sizeof(canonical_tuple_t) << endl; load_pages(index_root); load_redirects(index_root); load_images(index_root); load_redirect_overrides(index_root); delete stop_words_; stop_words_ = NULL; } /* This method returns false if no existence, true on existence, and the * image_link pointer will point to the image_link if it exists */ canonical_tuple_t* WikipediaTupleMapImpl::tuple_exists(const char* tuple) const { TupleImageHash::const_iterator res; res = tuples_.find(tuple); if (res != tuples_.end()) { return res->second; } else { return NULL; } } /* * This method looks up a word in the tuple map and appends it to the list if * it exists. It assumes that the word start points to a null terminated * string. If you passt the canonical ngram check, then it will ensure that * the canonical is at least a bigram (this helps prevent against too many stop * word unigrams) */ inline bool WikipediaTupleMapImpl::append_tuple_if_exists(start_finish_str* word, TupleImageList& list, bool do_canonical_ngram_check) { TupleImageHash::const_iterator res; res = tuples_.find(word->start); //cout << "Searching for '" << word->start << "'" << endl; if (res != tuples_.end()) { word->found = true; canonical_tuple_t* result = res->second; alias_canonical_pair_t pair; pair.canonical = result; pair.alias = res->first; //cout << "Found:'" << result->tuple << "'" << endl; if (do_canonical_ngram_check) { bool more_than_one_word = false; int j = 0; while(result->tuple[j] != '\0') { if (result->tuple[j] == ' ') { more_than_one_word = true; break; } j++; } if (more_than_one_word) { //cout << "MATCH: '" << word->start << "' --> '" << result->tuple << "' Ambiguous:" << (bool) result->ambiguous << endl; list.push_back(pair); } } else { //cout << "MATCH: '" << word->start << "' --> '" << result->tuple << "' Ambiguous:" << (bool) result->ambiguous << endl; list.push_back(pair); } return true; } else { return false; } } /* * Some crazy NLP that can do a sliding window on a snippet looking for tuples * * Step 1. Convert sentence in start_finish_str* of words (this is for * performance reasons, so we don't need to create multiple strings) * * Step 2. Do sliding ngram windows (starting with 3 down to 2 down to 1), and * keep track of words that are part of ngrams that hit in the tuples_ hash * * Step 3. On the unigram window, only take a unigram if it is an alias of a * canonical URL that is longer than one word */ void WikipediaTupleMapImpl::tuples_from_snippet(const char* snippet, TupleImageList& list, bool want_full_if_multiple_capitalized) /* variable want_full_if_multiple_capitalized now actually just means want_exact_match_unless_starts_with_"anything"_etc. */ { int len = strlen(snippet); char* dup = (char*) malloc(sizeof(char) * len + 1); memcpy(dup,snippet,len + 1); cout << "Snippet: " << snippet << endl; char* front = dup; char* cur = dup; int word_count = 0; //int capitalized_word_count = 0; start_finish_str* words = 0; int i=0; // leading whitespace while(dup[i] == ' ') { i++; } cur += i; while(i <= len) { if (dup[i] == ' ' || dup[i] == '-' || dup[i] == ',' || dup[i] == ';' || dup[i] == '"') { words = (start_finish_str*) realloc(words,(word_count + 1) * sizeof(start_finish_str)); words[word_count].start = cur; /* if (*cur >= 65 && *cur <= 90) capitalized_word_count++; */ words[word_count].finish = front + i; words[word_count].found = false; word_count++; i++; while(dup[i] == ' ' || dup[i] == '-' || dup[i] == ',' || dup[i] == ';' || dup[i] == '"') { i++; } cur = front + i; } else if (dup[i] == '\0') { words = (start_finish_str*) realloc(words,(word_count + 1) * sizeof(start_finish_str)); words[word_count].start = cur; /* if (*cur >= 65 && *cur <= 90) capitalized_word_count++; */ words[word_count].finish = front + i; words[word_count].found = false; word_count++; } i++; } if (word_count < 9) { *words[word_count-1].finish = '\0'; if (append_tuple_if_exists(&words[0],list)) { free(words); free(dup); return; } } //if (want_full_if_multiple_capitalized && capitalized_word_count > 1) { if (want_full_if_multiple_capitalized && (strcmp("i like",snippet) && strcmp("I like",snippet) && strcmp("everything",snippet) && strcmp("Everything",snippet) && strcmp("anything",snippet) && strcmp("Anything",snippet))) { free(words); free(dup); return; } /* don't need this anymore because of above block if (word_count == 1) { *words[0].finish = '\0'; append_tuple_if_exists(&words[0],list); free(words); free(dup); return; } */ if (word_count == 2) { /* don't need this anymore either because of above block *words[1].finish = '\0'; bool bigram_found = append_tuple_if_exists(&words[0],list); if (!bigram_found) { */ *words[0].finish = '\0'; append_tuple_if_exists(&words[0],list,true); append_tuple_if_exists(&words[1],list,true); //} free(words); free(dup); return; } // Do quadgram sliding window for(int i=0; i < word_count - 3; i++) { char orig = *(words[i+3].finish); *(words[i+3].finish) = '\0'; bool quadgram_found = append_tuple_if_exists(&words[i],list); *(words[i+3].finish) = orig; if (quadgram_found) { words[i].found = true; words[i+1].found = true; words[i+2].found = true; words[i+3].found = true; i += 3; } } // Do trigram sliding window for(int i=0; i < word_count - 2; i++) { char orig = *(words[i+2].finish); *(words[i+2].finish) = '\0'; bool trigram_found = append_tuple_if_exists(&words[i],list); *(words[i+2].finish) = orig; if (trigram_found) { words[i].found = true; words[i+1].found = true; words[i+2].found = true; i += 2; } } // Do Bigram sliding window of pairs of unfound words in trigram window for(int i=0; i < word_count - 1; i++) { if (!words[i].found && !words[i+1].found) { char orig = *(words[i+1].finish); *(words[i+1].finish) = '\0'; bool bigram_found = append_tuple_if_exists(&words[i],list); *(words[i+1].finish) = orig; if (bigram_found) { words[i].found = true; words[i+1].found = true; i++; } } } // Do unigram window. Only take a unigram in this case if it maps to a // canonical tuple with more than one word. This is to prevent an overflow // of possible stop words for(int i=0; i < word_count; i++) { if (!words[i].found && (words[i].start[0]>=65 && words[i].start[0]<=90)) { char orig = *(words[i].finish); *(words[i].finish) = '\0'; append_tuple_if_exists(&words[i],list,true); *(words[i].finish) = orig; } } free(words); free(dup); } size_t WikipediaTupleMapImpl::size() { return tuples_.size(); } void WikipediaTupleMapImpl::clear() { for(TupleImageHash::iterator ii = tuples_.begin(), end = tuples_.end(); ii != end; ii++) { char* tuple = (char*) ii->first; canonical_tuple_t* canonical = (canonical_tuple_t*) ii->second; if (strcmp(tuple,canonical->tuple)) { tuples_.erase(ii); free(tuple); } } // Only canonicals should be left for(TupleImageHash::iterator ii = tuples_.begin(), end = tuples_.end(); ii != end; ii++) { char* tuple = (char*) ii->first; canonical_tuple_t* canonical = (canonical_tuple_t*) ii->second; free((char*) canonical->image_link); free(canonical); free(tuple); } } void WikipediaTupleMapImpl::map(void(* fn_ptr)(const char*, const canonical_tuple_t*)) { TupleImageHash::const_iterator end = tuples_.end(); for(TupleImageHash::const_iterator ii = tuples_.begin(); ii != end; ii++) { fn_ptr(ii->first,ii->second); } } /* Entry Point into the Library */ WikipediaTupleMap* WikipediaTupleMap::instance_ = NULL; WikipediaTupleMap* WikipediaTupleMap::instance() { if (!instance_) { instance_ = new WikipediaTupleMapImpl(); } return instance_; } /* Static Implementation */ void WikipediaTupleMapImpl::load_pages(const char* index_root) { bench_start("Load Pages"); FILE* file = NULL; char buffer[4096]; tuples_.resize(10000000); // optimization id_tuple_table_ = NULL; size_t biggest_id_so_far = 0; string index_filename = string(index_root) + ".pages"; int page_count = 0; if ((file = fopen((char*)index_filename.c_str(),"r"))) { while (fgets(buffer,4096,file)) { char* first = NULL; char* second = NULL; char* third = NULL; int length = strlen(buffer); for(int i = 0; i < length; i++) { if (buffer[i] == '|') { buffer[i] = '\0'; first = buffer; second = buffer + i + 1; for(int j=i; j < length; j++) { if (buffer[j] == '|') { buffer[j] = '\0'; third = buffer + j + 1; buffer[length-1] = '\0'; break; } } if (!first || !second || !third) break; int id = atoi(first); int ambiguous = atoi(third); char* key = strdup(second); downcase(second); if (id > (int) biggest_id_so_far) { id_tuple_table_ = (canonical_tuple_t**) realloc(id_tuple_table_,sizeof(canonical_tuple_t*) * (id + 1)); for(int k = biggest_id_so_far + 1; k < id + 1; k++) { id_tuple_table_[k] = NULL; } biggest_id_so_far = id; } if (!stop_words_->match(second)) { canonical_tuple_t* pair = (canonical_tuple_t*) malloc(sizeof(canonical_tuple_t)); pair->tuple = key; pair->image_link = NULL; pair->ambiguous = (ambiguous == 1); tuples_[key] = pair; page_count++; id_tuple_table_[id] = pair; } else { //cout << "Skipping " << key << endl; free(key); } break; } } } fclose(file); } else { cout << "Page File Open Error" << endl; } bench_finish("Load Pages"); cout << "Loaded:" << page_count << " pages." << endl; } void WikipediaTupleMapImpl::load_redirects(const char* index_root) { CALLGRIND_START_INSTRUMENTATION; bench_start("Load Redirects"); string redirects_filename = string(index_root) + ".redirects"; char buffer[4096]; FILE* redirects_file = NULL; if ((redirects_file = fopen((char*)redirects_filename.c_str(),"r"))) { while (fgets(buffer,4096,redirects_file)) { char* first = NULL; char* second = NULL; int length = strlen(buffer); for(int i = 0; i < length; i++) { if (buffer[i] == '>') { buffer[i] = '\0'; first = buffer; buffer[length-1] = '\0'; second = buffer + i + 1; if (!first || !second) break; int id = atoi(second); canonical_tuple_t* pair = id_tuple_table_[id]; if (pair) { char* key = strdup(first); downcase(first); if (!stop_words_->match(first)) { tuples_[key] = pair; } else { free(key); } } break; } } } fclose(redirects_file); } else { cout << "Redirects File Open Error" << endl; } bench_finish("Load Redirects"); CALLGRIND_STOP_INSTRUMENTATION; } void WikipediaTupleMapImpl::load_redirect_overrides(const char* index_root) { bench_start("Load Redirect Overrides"); string redirects_filename = string(index_root) + ".overrides"; char buffer[4096]; FILE* redirects_file = NULL; if ((redirects_file = fopen((char*)redirects_filename.c_str(),"r"))) { while (fgets(buffer,4096,redirects_file)) { char* first = NULL; char* second = NULL; int length = strlen(buffer); for(int i = 0; i < length; i++) { if (buffer[i] == '>') { buffer[i] = '\0'; first = buffer; buffer[length-1] = '\0'; second = buffer + i + 1; if (!first || !second) break; TupleImageHash::const_iterator canonical_it = tuples_.find(second); if (canonical_it != tuples_.end()) { canonical_tuple_t* canon = canonical_it->second; // Now look for the redirect TupleImageHash::const_iterator redirect_it = tuples_.find(first); if (redirect_it != tuples_.end()) { const char* key = redirect_it->first; cout << "Redirecting Existing: " << key << " to " << canon->tuple << endl; tuples_[key] = canon; } else { char* new_key = strdup(first); cout << "Redirecting New: " << new_key << " to " << canon->tuple << endl; tuples_[new_key] = canon; } } break; } } } fclose(redirects_file); } else { cout << "Overrides File Open Error" << endl; } bench_finish("Load Redirect Overrides"); } void WikipediaTupleMapImpl::load_images(const char* index_root) { bench_start("Load Images"); FILE* file = NULL; char buffer[4096]; string raw_images_filename = string(index_root) + ".images"; string validated_images_filename = string(index_root) + ".images.validated"; string images_filename = ""; struct stat stats; if (!stat(validated_images_filename.c_str(),&stats)) { images_filename = validated_images_filename; } else { images_filename = raw_images_filename; } cout << "Loading: " << images_filename << endl; if ((file = fopen((char*)images_filename.c_str(),"r"))) { while (fgets(buffer,4096,file)) { char* first = NULL; char* second = NULL; int length = strlen(buffer); for(int i = 0; i < length; i++) { if (buffer[i] == '|') { buffer[i] = '\0'; first = buffer; second = buffer + i + 1; buffer[length-1] = '\0'; TupleImageHash::const_iterator res; res = tuples_.find(first); if (res != tuples_.end()) { char* image = strdup(second); canonical_tuple_t* canonical = res->second; canonical->image_link = image; } break; } } } } else { cout << "File Open Error" << endl; } bench_finish("Load Images"); }
29.792899
250
0.583052
mmonto7
24911b4f7decb852ac130f4a734da024f44f63a3
2,282
hpp
C++
src/hotspot/share/gc/z/zThreadLocalData.hpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
null
null
null
src/hotspot/share/gc/z/zThreadLocalData.hpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
null
null
null
src/hotspot/share/gc/z/zThreadLocalData.hpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #ifndef SHARE_GC_Z_ZTHREADLOCALDATA_HPP #define SHARE_GC_Z_ZTHREADLOCALDATA_HPP #include "gc/z/zMarkStack.hpp" #include "gc/z/zGlobals.hpp" #include "runtime/thread.hpp" #include "utilities/debug.hpp" #include "utilities/sizes.hpp" class ZThreadLocalData { private: uintptr_t _address_bad_mask; ZMarkThreadLocalStacks _stacks; ZThreadLocalData() : _address_bad_mask(0), _stacks() {} static ZThreadLocalData* data(Thread* thread) { return thread->gc_data<ZThreadLocalData>(); } public: static void create(Thread* thread) { new (data(thread)) ZThreadLocalData(); } static void destroy(Thread* thread) { data(thread)->~ZThreadLocalData(); } static void set_address_bad_mask(Thread* thread, uintptr_t mask) { data(thread)->_address_bad_mask = mask; } static ZMarkThreadLocalStacks* stacks(Thread* thread) { return &data(thread)->_stacks; } static ByteSize address_bad_mask_offset() { return Thread::gc_data_offset() + byte_offset_of(ZThreadLocalData, _address_bad_mask); } static ByteSize nmethod_disarmed_offset() { return address_bad_mask_offset() + in_ByteSize(ZNMethodDisarmedOffset); } }; #endif // SHARE_GC_Z_ZTHREADLOCALDATA_HPP
31.260274
90
0.741017
siweilxy
24922cc39bb9c95ecb2e31239adbbb1ae3876c47
6,327
cpp
C++
tests/main.cpp
8infy/XILoader
7e82d917cddb3c66be76c614637cdb05dde4dddf
[ "Apache-2.0" ]
null
null
null
tests/main.cpp
8infy/XILoader
7e82d917cddb3c66be76c614637cdb05dde4dddf
[ "Apache-2.0" ]
null
null
null
tests/main.cpp
8infy/XILoader
7e82d917cddb3c66be76c614637cdb05dde4dddf
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <fstream> #include <XILoader/XILoader.h> // variables for stbi to write // image size data to static int x, y, z; static uint16_t passed = 0; static uint16_t failed = 0; #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #define PATH_TO(image) XIL_TEST_PATH image #define AS_INT(x) static_cast<int32_t>(x) #define CONCAT_(x, y) x##y #define CONCAT(x, y) CONCAT_(x, y) #define UNIQUE_VAR(x) CONCAT(x, __LINE__) #define PRINT_TITLE(str) \ std::cout << "================================= " \ << str \ << " =================================" \ << std::endl #define PRINT_END(str) PRINT_TITLE(str) << std::endl #define ASSERT_LOADED(image) \ if (!image) \ std::cout << "Failed! --> Couldn't load the image" << std::endl #define LOAD_AND_COMPARE_EACH(subject, path_to_image) \ std::cout << subject "... "; \ auto UNIQUE_VAR(xil_image) = XILoader::load(path_to_image); \ auto UNIQUE_VAR(stbi_image) = stbi_load(path_to_image, &x, &y, &z, 0); \ ASSERT_LOADED(UNIQUE_VAR(xil_image)); \ compare_each(UNIQUE_VAR(xil_image).data(), UNIQUE_VAR(stbi_image), static_cast<size_t>(x)* y* z) #define LOAD_AND_COMPARE_EACH_FLIPPED(subject, path_to_image) \ std::cout << subject "... "; \ auto UNIQUE_VAR(xil_image) = XILoader::load(path_to_image, true); \ stbi_set_flip_vertically_on_load(true); \ auto UNIQUE_VAR(stbi_image) = stbi_load(path_to_image, &x, &y, &z, 0); \ stbi_set_flip_vertically_on_load(false); \ ASSERT_LOADED(UNIQUE_VAR(xil_image)); \ compare_each(UNIQUE_VAR(xil_image).data(), UNIQUE_VAR(stbi_image), static_cast<size_t>(x)* y* z) #define PRINT_TEST_RESULTS(passed_count, failed_count) \ std::cout << "\n\nTEST RESULTS: " \ << "passed: " << passed_count \ << " / failed: " \ << failed_count \ << " (" << passed_count \ << "/" << passed_count + failed_count \ << ")" << std::endl; void compare_each(uint8_t* l, uint8_t* r, size_t size) { if (size == 0) { failed++; return; } if (!l) { failed++; return; } for (size_t i = 0; i < size; i++) { if (!(l[i] == r[i])) { std::cout << "FAILED " << "At pixel[" << i << "]" << " --> "; std::cout << "left was == " << AS_INT(l[i]) << ", right was == " << AS_INT(r[i]) << std::endl; failed++; return; } } passed++; std::cout << "PASSED" << std::endl; } void TEST_BMP() { PRINT_TITLE("BMP LOADING TEST STARTS"); LOAD_AND_COMPARE_EACH("1bpp 8x8", PATH_TO("1bpp_8x8.bmp")); LOAD_AND_COMPARE_EACH("1bpp 9x9", PATH_TO("1bpp_9x9.bmp")); LOAD_AND_COMPARE_EACH("1bpp 260x401", PATH_TO("1bpp_260x401.bmp")); LOAD_AND_COMPARE_EACH("1bpp 1419x1001", PATH_TO("1bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("flipped 1bpp 260x401", PATH_TO("1bpp_260x401_flipped.bmp")); LOAD_AND_COMPARE_EACH_FLIPPED("forced flip 1bpp 260x401", PATH_TO("1bpp_260x401_flipped.bmp")); LOAD_AND_COMPARE_EACH("4bpp 1419x1001", PATH_TO("4bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("8bpp 1419x1001", PATH_TO("8bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("16bpp 1419x1001", PATH_TO("16bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("24bpp 1419x1001", PATH_TO("24bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("flipped 24bpp 1419x1001", PATH_TO("24bpp_1419x1001_flipped.bmp")); LOAD_AND_COMPARE_EACH_FLIPPED("forced flip 24bpp 1419x1001", PATH_TO("24bpp_1419x1001_flipped.bmp")); LOAD_AND_COMPARE_EACH("32bpp 1419x1001", PATH_TO("32bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("nomask 32bpp 1419x1001", PATH_TO("32bpp_1419x1001_nomask.bmp")); PRINT_END("BMP LOADING TEST DONE"); // Cannot currently run this due to a bug in stb_image // https://github.com/nothings/stb/issues/870 // LOAD_AND_COMPARE_EACH("16bpp 4x4", PATH_TO("16bpp_4x4.bmp")); } void TEST_PNG() { PRINT_TITLE("PNG LOADING TEST STARTS"); LOAD_AND_COMPARE_EACH("8bpc RGB 400x268", PATH_TO("8pbc_rgb_400x268.png")); LOAD_AND_COMPARE_EACH("8bpc RGB 1419x1001", PATH_TO("8bpc_rgb_1419x1001.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA 4x4", PATH_TO("8bpc_rgba_4x4.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA 1473x1854", PATH_TO("8bpc_rgba_1473x1854.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA 2816x3088", PATH_TO("8pbc_rgba_2816x3088.png")); LOAD_AND_COMPARE_EACH("8bpc RGB 1419x1001 UNCOMPRESSED", PATH_TO("8bpc_rgb_uncompressed_1419x1001.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA 2816x3088 UNCOMPRESSED", PATH_TO("8bpc_rgba_uncompressed_2816x3088.png")); LOAD_AND_COMPARE_EACH_FLIPPED("8bpc RGBA 2816x3088 FLIPPED", PATH_TO("8pbc_rgba_2816x3088.png")); LOAD_AND_COMPARE_EACH_FLIPPED("8bpc RGB 1419x1001 FLIPPED", PATH_TO("8bpc_rgb_1419x1001.png")); LOAD_AND_COMPARE_EACH("16bpc RGB 1419x1001", PATH_TO("16bpc_rgb_1419x1001.png")); LOAD_AND_COMPARE_EACH("16bpc RGBA 1473x1854", PATH_TO("16bpc_rgba_1473x1854.png")); LOAD_AND_COMPARE_EACH("1bpc RGBA PALETTED 1473x1854", PATH_TO("1bpp_rgba_paletted_1473x1854.png")); LOAD_AND_COMPARE_EACH("1bpc RGB PALETTED 1473x1854", PATH_TO("1bpp_rgb_paletted_1473x1854.png")); LOAD_AND_COMPARE_EACH("4bpc RGBA PALETTED 1419x1001", PATH_TO("4bpp_rgba_paletted_1419x1001.png")); LOAD_AND_COMPARE_EACH("4bpc RGB PALETTED 1419x1001", PATH_TO("4bpp_rgb_paletted_1419x1001.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA GRAYSCALE 1473x1854", PATH_TO("8bpc_rgba_grayscale_1473x1854.png")); LOAD_AND_COMPARE_EACH("16bpc RGBA GRAYSCALE 1473x1854", PATH_TO("16bpc_rgba_grayscale_1473x1854.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA PALETTED 1473x1854", PATH_TO("8bpc_rgba_paletted_1473x1854.png")); LOAD_AND_COMPARE_EACH("8bpc RGB PALETTED 1473x1854", PATH_TO("8bpc_rgb_paletted_1473x1854.png")); LOAD_AND_COMPARE_EACH("8bpc RGB GRAYSCALE 1473x1854", PATH_TO("8bpc_rgb_grayscale_1419x1001.png")); LOAD_AND_COMPARE_EACH("16bpc RGB GRAYSCALE 1473x1854", PATH_TO("16bpc_rgb_grayscale_1419x1001.png")); PRINT_END("PNG LOADING TEST DONE"); } int main(int argc, char** argv) { TEST_BMP(); TEST_PNG(); PRINT_TEST_RESULTS(passed, failed); return 0; }
41.900662
111
0.684369
8infy
2492eca9ffd00a5653d65c9c4069f1959fb829a5
761
cpp
C++
src/Maths.cpp
elvisoric/hmi
4e80f0bb0e4ac459bef2ddbc439faf895e1b60cb
[ "MIT" ]
17
2019-03-02T14:59:32.000Z
2022-03-10T15:08:36.000Z
src/Maths.cpp
elvisoric/hmi
4e80f0bb0e4ac459bef2ddbc439faf895e1b60cb
[ "MIT" ]
1
2019-07-02T06:01:35.000Z
2019-07-02T08:25:22.000Z
src/Maths.cpp
elvisoric/hmi
4e80f0bb0e4ac459bef2ddbc439faf895e1b60cb
[ "MIT" ]
2
2019-05-15T21:05:32.000Z
2021-04-26T03:09:24.000Z
#include <Maths.h> namespace nrg { glm::mat4 createTransformation(const glm::vec3& translation, float rx, float ry, float rz, float scale) { glm::mat4 transformation{1.0f}; transformation = glm::translate(transformation, translation); transformation = glm::rotate(transformation, glm::radians(rx), glm::vec3(1.0f, 0.0f, 0.0f)); transformation = glm::rotate(transformation, glm::radians(ry), glm::vec3(0.0f, 1.0f, 0.0f)); transformation = glm::rotate(transformation, glm::radians(rz), glm::vec3(0.0f, 0.0f, 1.0f)); transformation = glm::scale(transformation, glm::vec3{scale}); return transformation; } } // namespace nrg
42.277778
80
0.599212
elvisoric
24940cf3fc62959bcbdcce907c6a46ac52bdefd2
842
hpp
C++
engine/graphics/renderer/Camera.hpp
taida957789/ouzel
a8c1cc74e6151a0f7d7d2c534f8747cba46a36af
[ "Unlicense" ]
1
2021-03-01T13:17:49.000Z
2021-03-01T13:17:49.000Z
engine/graphics/renderer/Camera.hpp
taida957789/ouzel
a8c1cc74e6151a0f7d7d2c534f8747cba46a36af
[ "Unlicense" ]
null
null
null
engine/graphics/renderer/Camera.hpp
taida957789/ouzel
a8c1cc74e6151a0f7d7d2c534f8747cba46a36af
[ "Unlicense" ]
null
null
null
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_GRAPHICS_RENDERER_CAMERA_HPP #define OUZEL_GRAPHICS_RENDERER_CAMERA_HPP #include "Renderer.hpp" #include "../../math/Matrix.hpp" namespace ouzel::graphics::renderer { class Camera final { public: enum class ProjectionMode { custom, orthographic, perspective }; enum class ScaleMode { noScale, exactFit, noBorder, showAll }; Camera(Renderer& initRenderer): renderer{initRenderer}, resource{initRenderer} { } private: Renderer& renderer; Renderer::Resource resource; Matrix4F transform; }; } #endif // OUZEL_GRAPHICS_RENDERER_CAMERA_HPP
19.581395
61
0.579572
taida957789
24983831d385f0eadab472fa5d34e904d7e2c7d4
1,045
cc
C++
fuzzers/tint_spv_reader_fuzzer.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
fuzzers/tint_spv_reader_fuzzer.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
fuzzers/tint_spv_reader_fuzzer.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Tint Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <vector> #include "src/reader/spirv/parser.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { size_t sizeInU32 = size / sizeof(uint32_t); const uint32_t* u32Data = reinterpret_cast<const uint32_t*>(data); std::vector<uint32_t> input(u32Data, u32Data + sizeInU32); if (input.size() != 0) { tint::Context ctx; tint::reader::spirv::Parser parser(&ctx, input); parser.Parse(); } return 0; }
32.65625
75
0.719617
dorba
2498f10a871dbe916e582f9a6f96d443a526416f
3,000
cpp
C++
Base/PLCore/src/System/ConsoleAndroid.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLCore/src/System/ConsoleAndroid.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLCore/src/System/ConsoleAndroid.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: ConsoleAndroid.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <android/log.h> #include "PLCore/String/String.h" #include "PLCore/System/ConsoleAndroid.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace PLCore { //[-------------------------------------------------------] //[ Public virtual Console functions ] //[-------------------------------------------------------] void ConsoleAndroid::Print(const String &sString) const { // Write into the Android in-kernel log buffer (use Androids "logcat" utility to access this system log) const String sLogMessage = "[Console] " + sString; __android_log_write(ANDROID_LOG_INFO, "PixelLight", (sLogMessage.GetFormat() == String::ASCII) ? sLogMessage.GetASCII() : sLogMessage.GetUTF8()); // Do also do the normal console output ConsoleLinux::Print(sString); } //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ ConsoleAndroid::ConsoleAndroid() { } /** * @brief * Destructor */ ConsoleAndroid::~ConsoleAndroid() { } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLCore
38.961039
146
0.505
ktotheoz
249c6d2bbc55a5154b01e724367e83c8ad6e0912
359
cpp
C++
cpp_playground/ex110/numbers.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
14
2019-04-23T13:45:10.000Z
2022-03-12T18:26:47.000Z
cpp_playground/ex110/numbers.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
null
null
null
cpp_playground/ex110/numbers.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
9
2019-09-01T15:17:45.000Z
2020-11-13T20:31:36.000Z
#include "numbers.hpp" int gcd(int x, int y) { int a, b, r; if (x > y) { a = x; b = y; } else { a = y; b = x; } while (b != 0) { r = a % b; a = b; b = r; } return a; } // x * y = LCM(x, y) * GCD (x, y) int lcm(int x, int y) { return x * y / gcd(x, y); }
12.37931
33
0.314763
chgogos
249fcbd55bd3e42b3bec6ae9ff6af3281666d15c
2,659
cpp
C++
drlvm/vm/port/src/signals/linux/signals_ia32.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
8
2015-11-04T06:06:35.000Z
2021-07-04T13:47:36.000Z
drlvm/vm/port/src/signals/linux/signals_ia32.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
1
2021-10-17T13:07:28.000Z
2021-10-17T13:07:28.000Z
drlvm/vm/port/src/signals/linux/signals_ia32.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
13
2015-11-27T03:14:50.000Z
2022-02-26T15:12:20.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdarg.h> #include "signals_internal.h" extern "C" void port_longjump_stub(void); #define DIR_FLAG ((U_32)0x00000400) void port_set_longjump_regs(void* fn, Registers* regs, int num, ...) { void** sp; va_list ap; int i; size_t rcount = (sizeof(Registers) + sizeof(void*) - 1) / sizeof(void*); if (!regs) return; sp = (void**)regs->esp - 1; *sp = (void*)regs->eip; sp = sp - rcount - 1; *((Registers*)(sp + 1)) = *regs; *sp = (void*)(sp + 1); regs->ebp = (U_32)sp; sp = sp - num - 1; va_start(ap, num); for (i = 1; i <= num; i = i + 1) { void* arg = va_arg(ap, void*); if (i == 1 && arg == regs) sp[i] = *((void**)regs->ebp); /* Replace 1st arg */ else sp[i] = arg; } *sp = (void*)&port_longjump_stub; regs->esp = (U_32)sp; regs->eip = (U_32)fn; regs->eflags = regs->eflags & ~DIR_FLAG; } void port_transfer_to_function(void* fn, Registers* pregs, int num, ...) { void** sp; va_list ap; int i; size_t rcount = (sizeof(Registers) + sizeof(void*) - 1) / sizeof(void*); Registers regs; if (!pregs) return; regs = *pregs; sp = (void**)regs.esp - 1; *sp = (void*)regs.eip; sp = sp - rcount - 1; *((Registers*)(sp + 1)) = regs; *sp = (void*)(sp + 1); regs.ebp = (U_32)sp; sp = sp - num - 1; va_start(ap, num); for (i = 1; i <= num; i = i + 1) { void* arg = va_arg(ap, void*); if (i == 1 && arg == pregs) sp[i] = *((void**)regs.ebp); /* Replace 1st arg */ else sp[i] = arg; } *sp = (void*)&port_longjump_stub; regs.esp = (U_32)sp; regs.eip = (U_32)fn; regs.eflags = regs.eflags & ~DIR_FLAG; port_transfer_to_regs(&regs); }
25.084906
76
0.574276
sirinath
24a6f4ca879d1e340a083669874c78ed923e19a7
3,888
hpp
C++
utils.hpp
Instand/algorithms
079ac867932e65e0936eab08b3176dc2d68bf684
[ "MIT" ]
2
2019-10-29T03:25:21.000Z
2019-10-30T12:03:50.000Z
utils.hpp
Instand/Algorithms
079ac867932e65e0936eab08b3176dc2d68bf684
[ "MIT" ]
null
null
null
utils.hpp
Instand/Algorithms
079ac867932e65e0936eab08b3176dc2d68bf684
[ "MIT" ]
null
null
null
#ifndef UTILS_HPP #define UTILS_HPP #include <iostream> #include <utility> #include <random> #include <string> #include <chrono> #include <memory> #define forever for(;;) #define unused(x) (void)(x) namespace cs { struct Initializer { Initializer() { std::srand(seed); } inline static unsigned seed = static_cast<unsigned>(std::chrono::steady_clock::now().time_since_epoch().count()); }; struct Generator { inline static Initializer initializer; static int generateRandomValue(int min, int max) { static std::default_random_engine engine(Initializer::seed); std::uniform_int_distribution<int> distribution(min, max); return distribution(engine); } template<typename T> static T generateRandomValue(T min, T max) { static std::default_random_engine engine(Initializer::seed); if constexpr (std::is_floating_point_v<T>) { std::uniform_real_distribution<T> distribution(min, max); return static_cast<T>(distribution(engine)); } std::uniform_int_distribution<T> distribution(min, max); return static_cast<T>(distribution(engine)); } template<typename T> static std::vector<T> generateCollection(T min, T max, size_t count) { std::vector<T> container; for (size_t i = 0; i < count; ++i) { container.push_back(Generator::generateRandomValue<T>(min, max)); } return container; } template<typename T> static std::pair<std::unique_ptr<T[]>, size_t> generateArray(T min, T max, size_t count) { std::unique_ptr<T[]> array(new T[count]); for (size_t i = 0; i < count; ++i) { array[i] = Generator::generateRandomValue<T>(min, max); } return std::make_pair(std::move(array), count); } }; namespace helper { template <typename T> struct is_pair : public std::false_type {}; template <typename T, typename K> struct is_pair<std::pair<T, K>> : public std::true_type {}; template <typename T> void print(const T& container, std::false_type) { for (const auto& element : container) { std::cout << element << " "; } std::cout << "[end]" << std::endl; } template <typename T> void print(const T& container, std::true_type) { for (const auto& [key, value] : container) { std::cout << "Key " << key << ", value " << value << std::endl; } std::cout << std::endl; } } class Console { public: template <typename... Args> static void writeLine(Args&&... args) { (std::cout << ... << args) << std::endl; } template <typename T> static void print(const T& container) { helper::print(container, helper::is_pair<typename T::value_type>()); } template <typename T> static void print(const std::string& message, const T& container) { std::cout << message << ", size: " << container.size() << ", values "; print(container); } template<typename T> static void print(std::shared_ptr<T> container) { cs::Console::print(*container.get()); } template <typename T> static void size(const T& container) { writeLine(typeid (T).name(), " size ", std::size(container)); } template <typename Iter> static void print(Iter begin, Iter end) { using ValueType = typename Iter::value_type; print(std::vector<ValueType>{begin, end}); } }; } #endif // UTILS_HPP
29.233083
121
0.551698
Instand
24a92d1969bfe14239b7da65421c720798b39331
2,813
cpp
C++
source/SoloFeature_redistributeReadsByCB.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
1,315
2015-01-07T02:03:15.000Z
2022-03-30T09:48:17.000Z
source/SoloFeature_redistributeReadsByCB.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
1,429
2015-01-08T00:09:17.000Z
2022-03-31T08:12:14.000Z
source/SoloFeature_redistributeReadsByCB.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
495
2015-01-23T20:00:45.000Z
2022-03-31T13:24:50.000Z
#include "SoloFeature.h" #include "streamFuns.h" //#include "TimeFunctions.h" //#include "SequenceFuns.h" //#include "Stats.h" //#include "GlobalVariables.h" void SoloFeature::redistributeReadsByCB() {//redistribute reads in files by CB - each file with the approximately the same number of reads, each CB is on one file only /* SoloFeature vars that have to be setup: * nCB * readFeatSum->cbReadCount[] */ //find boundaries for cells uint64 nReadRec=std::accumulate(readFeatSum->cbReadCount.begin(), readFeatSum->cbReadCount.end(), 0LLU); //for ( auto &cbrc : readFeatSum->cbReadCount ) // nReadRec += cbrc; uint64 nReadRecBin=nReadRec/pSolo.redistrReadsNfiles; P.inOut->logMain << " Redistributing reads into "<< pSolo.redistrReadsNfiles <<"files; nReadRec="<< nReadRec <<"; nReadRecBin="<< nReadRecBin <<endl; redistrFilesCBfirst.push_back(0); redistrFilesCBindex.resize(nCB); uint64 nreads=0; uint32 ind=0; for (uint32 icb=0; icb<nCB; icb++){ redistrFilesCBindex[icb]=ind; nreads += readFeatSum->cbReadCount[indCB[icb]]; if (nreads>=nReadRecBin) { ind++; redistrFilesCBfirst.push_back(icb+1); redistrFilesNreads.push_back(nreads); nreads=0; }; }; if (nreads>0) { redistrFilesCBfirst.push_back(nCB); redistrFilesNreads.push_back(nreads); }; //open output files redistrFilesStreams.resize(redistrFilesNreads.size()); for (uint32 ii=0; ii<redistrFilesNreads.size(); ii++) { //open file with flagDelete=true redistrFilesStreams[ii] = &fstrOpen(P.outFileTmp + "solo"+SoloFeatureTypes::Names[featureType]+"_redistr_"+std::to_string(ii), ERROR_OUT, P, true); }; //main cycle for (int ii=0; ii<P.runThreadN; ii++) { readFeatAll[ii]->streamReads->clear();//this is needed if eof was reached before readFeatAll[ii]->streamReads->seekg(0,ios::beg); while ( true ) { string line1; getline(*readFeatAll[ii]->streamReads,line1); if (line1.empty()) { break; }; istringstream line1stream(line1); uint64 cb1, umi; line1stream >> umi >> cb1 >> cb1; if (featureType==SoloFeatureTypes::SJ) line1stream >> cb1; line1stream >> cb1; *redistrFilesStreams[redistrFilesCBindex[indCBwl[cb1]]] << line1 <<'\n'; }; //TODO: delete streamReads files one by one to save disk space }; //close files //for (uint32 ii=0; ii<pSolo.redistrReadsNfiles; ii++) // redistrFilesStreams[ii]->flush(); };
34.728395
163
0.596872
Gavin-Lijy
24b0a21e49006b8ffb15dfad251cda8793b24d33
715
cpp
C++
Quanta/Source/Graphics/Buffer/VertexLayout.cpp
thedoctorquantum/Quanta
c952c8ca0832f978ea1fc1aa9e9a840c500977a3
[ "MIT" ]
null
null
null
Quanta/Source/Graphics/Buffer/VertexLayout.cpp
thedoctorquantum/Quanta
c952c8ca0832f978ea1fc1aa9e9a840c500977a3
[ "MIT" ]
null
null
null
Quanta/Source/Graphics/Buffer/VertexLayout.cpp
thedoctorquantum/Quanta
c952c8ca0832f978ea1fc1aa9e9a840c500977a3
[ "MIT" ]
null
null
null
#include <Quanta/Graphics/Buffer/VertexLayout.h> #include "../../Debugging/Validation.h" namespace Quanta { const VertexElement& VertexLayout::operator[](const USize index) const { DEBUG_ASSERT(index < elements.size()); return elements[index]; } void VertexLayout::Add(const VertexElement& element) { DEBUG_ASSERT(element.count != 0); DEBUG_ASSERT(element.size != 0); elements.push_back(element); stride += element.count * element.size; } USize VertexLayout::GetCount() const { return elements.size(); } USize VertexLayout::GetStride() const { return stride; } }
21.666667
74
0.594406
thedoctorquantum
24b888b8ea47372594f86e4489eaa80d64b20a52
1,511
cpp
C++
src/worker/common.cpp
abudnik/prun
643a6bf49249e220f08317b8a4739570faf7b2ae
[ "Apache-2.0" ]
20
2015-05-14T19:44:01.000Z
2018-04-14T15:25:08.000Z
src/worker/common.cpp
abudnik/prun
643a6bf49249e220f08317b8a4739570faf7b2ae
[ "Apache-2.0" ]
11
2015-04-15T19:51:06.000Z
2017-01-03T14:57:49.000Z
src/worker/common.cpp
abudnik/prun
643a6bf49249e220f08317b8a4739570faf7b2ae
[ "Apache-2.0" ]
7
2015-05-08T12:44:38.000Z
2021-12-10T18:00:01.000Z
/* =========================================================================== This software is licensed under the Apache 2 license, quoted below. Copyright (C) 2013 Andrey Budnik <budnik27@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================== */ #include "common.h" namespace worker { unsigned int SHMEM_BLOCK_SIZE = 512 * 1024; unsigned int MAX_SCRIPT_SIZE = SHMEM_BLOCK_SIZE - 1; unsigned short DEFAULT_PORT = 5555; unsigned short DEFAULT_UDP_PORT = DEFAULT_PORT - 1; unsigned short DEFAULT_MASTER_UDP_PORT = DEFAULT_PORT - 2; char const SHMEM_NAME[] = "prexec_shmem"; char const FIFO_NAME[] = "/tmp/.prexec"; char const UDS_NAME[] = "/tmp/.prexec_uds"; char const NODE_SCRIPT_NAME_PY[] = "node/node.py"; char const NODE_SCRIPT_NAME_JAVA[] = "node/node.java"; char const NODE_SCRIPT_NAME_SHELL[] = "node/node.sh"; char const NODE_SCRIPT_NAME_RUBY[] = "node/node.rb"; char const NODE_SCRIPT_NAME_JS[] = "node/node.js"; } // namespace worker
33.577778
77
0.688948
abudnik
24bc7245b30b67d814caea99b2ef86dd1fa1371c
2,231
cc
C++
src/space/libmin/mindefs.cc
yrrapt/cacd
696f5a22cb71b83eabbb9de199f1972d458fa9e9
[ "ISC" ]
11
2019-10-16T11:03:49.000Z
2021-09-28T19:46:12.000Z
src/space/libmin/mindefs.cc
yrrapt/cacd
696f5a22cb71b83eabbb9de199f1972d458fa9e9
[ "ISC" ]
null
null
null
src/space/libmin/mindefs.cc
yrrapt/cacd
696f5a22cb71b83eabbb9de199f1972d458fa9e9
[ "ISC" ]
1
2021-09-29T18:15:17.000Z
2021-09-29T18:15:17.000Z
/* * ISC License * * Copyright (C) 1997-2018 by * Arjan van Genderen * Kees-Jan van der Kolk * Simon de Graaf * Nick van der Meijs * Delft University of Technology * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #include <string.h> #include <exception> #include "src/space/libmin/mindefs.h" static void my_terminate() { fprintf(stderr, "\ninternal: *** Exception found\n"); die(); } void min_init_library(void) { static bool is_initialized = false; if(is_initialized) return; is_initialized = true; std::set_terminate (my_terminate); } //============================================================================== // // Assertion handling. // //============================================================================== void __std_assert_failed__(const char *file_name, int lineno, const char* condition) { char *s; if ((s = strrchr ((char*)file_name+1, '/'))) { /* don't use absolute path (SdeG) */ while (--s > file_name && *s != '/'); if (s > file_name) file_name = ++s; } fprintf(stderr, "\ninternal: *** Assertion `%s' failed at %s:%d\n", condition, file_name, lineno); die(); } void __std_out_of_memory__(const char *file_name, int lineno, const char* expression) { char *s; if ((s = strrchr ((char*)file_name+1, '/'))) { /* don't use absolute path (SdeG) */ while (--s > file_name && *s != '/'); if (s > file_name) file_name = ++s; } fprintf(stderr, "\ninternal: *** Out of memory at %s:%d\n", file_name, lineno); die(); }
30.148649
102
0.629314
yrrapt
24bd02b74e123c16ba3fc1576c9820cf2c74ab79
379
hpp
C++
include/aikido/planner/ompl/detail/CRRTConnect-impl.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
181
2016-04-22T15:11:23.000Z
2022-03-26T12:51:08.000Z
include/aikido/planner/ompl/detail/CRRTConnect-impl.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
514
2016-04-20T04:29:51.000Z
2022-02-10T19:46:21.000Z
include/aikido/planner/ompl/detail/CRRTConnect-impl.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
31
2017-03-17T09:53:02.000Z
2022-03-23T10:35:05.000Z
namespace aikido { namespace planner { namespace ompl { //============================================================================== template <template <typename T> class NN> void CRRTConnect::setNearestNeighbors() { mStartTree.reset(new NN<CRRT::Motion*>()); mGoalTree.reset(new NN<CRRT::Motion*>()); } } // namespace ompl } // namespace planner } // namespace aikido
23.6875
80
0.562005
personalrobotics
24beaeeb0a15535525308aced1c0e098200695b3
5,394
cpp
C++
applications/PoromechanicsApplication/custom_constitutive/custom_yield_criteria/modified_mises_yield_criterion.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
applications/PoromechanicsApplication/custom_constitutive/custom_yield_criteria/modified_mises_yield_criterion.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
applications/PoromechanicsApplication/custom_constitutive/custom_yield_criteria/modified_mises_yield_criterion.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// // Project Name: KratosPoromechanicsApplication $ // Created by: $Author: IPouplana $ // Last modified by: $Co-Author: $ // Date: $Date: July 2015 $ // Revision: $Revision: 0.0 $ // // // System includes // External includes // Project includes #include "custom_constitutive/custom_yield_criteria/modified_mises_yield_criterion.hpp" #include "poromechanics_application_variables.h" namespace Kratos { //*******************************CONSTRUCTOR****************************************** //************************************************************************************ ModifiedMisesYieldCriterion::ModifiedMisesYieldCriterion() :YieldCriterion() { } //*****************************INITIALIZATION CONSTRUCTOR***************************** //************************************************************************************ ModifiedMisesYieldCriterion::ModifiedMisesYieldCriterion(HardeningLawPointer pHardeningLaw) :YieldCriterion(pHardeningLaw) { } //*******************************ASSIGMENT OPERATOR*********************************** //************************************************************************************ ModifiedMisesYieldCriterion& ModifiedMisesYieldCriterion::operator=(ModifiedMisesYieldCriterion const& rOther) { YieldCriterion::operator=(rOther); return *this; } //*******************************COPY CONSTRUCTOR************************************* //************************************************************************************ ModifiedMisesYieldCriterion::ModifiedMisesYieldCriterion(ModifiedMisesYieldCriterion const& rOther) :YieldCriterion(rOther) { } //********************************CLONE*********************************************** //************************************************************************************ YieldCriterion::Pointer ModifiedMisesYieldCriterion::Clone() const { return Kratos::make_shared<ModifiedMisesYieldCriterion>(*this); } //********************************DESTRUCTOR****************************************** //************************************************************************************ ModifiedMisesYieldCriterion::~ModifiedMisesYieldCriterion() { } /// Operations. //************************** CALCULATE EQUIVALENT STRAIN ***************************** //************************************************************************************ double& ModifiedMisesYieldCriterion::CalculateYieldCondition(double& rStateFunction, const Parameters& rVariables) { // Compute I1 const Matrix& StrainMatrix = rVariables.GetStrainMatrix(); const unsigned int Dim = StrainMatrix.size1(); double I1 = 0.0; for(unsigned int i = 0; i < Dim; i++) { I1 += StrainMatrix(i,i); } // Compute J2 Matrix DeviatoricStrain(Dim,Dim); noalias(DeviatoricStrain) = StrainMatrix; for(unsigned int i = 0; i < Dim; i++) { DeviatoricStrain(i,i) -= I1/Dim; } Matrix Auxiliar(Dim,Dim); noalias(Auxiliar) = prod(DeviatoricStrain,DeviatoricStrain); double J2 = 0.0; for(unsigned int i = 0; i < Dim; i++) { J2 += Auxiliar(i,i); } J2 *= 0.5; // Compute Equivalent Strain (rStateFunction) const Properties& MaterialProperties = mpHardeningLaw->GetProperties(); const double& StrengthRatio = MaterialProperties[STRENGTH_RATIO]; const double& PoissonRatio = MaterialProperties[POISSON_RATIO]; rStateFunction = I1*(StrengthRatio-1.0)/(2.0*StrengthRatio*(1.0-2.0*PoissonRatio)) + sqrt( I1*I1*(StrengthRatio-1.0)*(StrengthRatio-1.0)/((1.0-2.0*PoissonRatio)*(1.0-2.0*PoissonRatio)) + J2*12.0*StrengthRatio/((1.0+PoissonRatio)*(1.0+PoissonRatio)) )/(2.0*StrengthRatio); return rStateFunction; } //***************************CALCULATE DAMAGE PARAMETER ****************************** //************************************************************************************ double& ModifiedMisesYieldCriterion::CalculateStateFunction(double& rStateFunction, const Parameters& rVariables) { const HardeningLaw::Parameters& HardeningLawParameters = rVariables.GetHardeningParameters(); mpHardeningLaw->CalculateHardening(rStateFunction, HardeningLawParameters); return rStateFunction; } //***************************CALCULATE DAMAGE DERIVATIVE ***************************** //************************************************************************************ double& ModifiedMisesYieldCriterion::CalculateDeltaStateFunction(double& rDeltaStateFunction, const Parameters& rVariables) { const HardeningLaw::Parameters& HardeningLawParameters = rVariables.GetHardeningParameters(); mpHardeningLaw->CalculateDeltaHardening(rDeltaStateFunction, HardeningLawParameters); return rDeltaStateFunction; } //************************************************************************************ //************************************************************************************ void ModifiedMisesYieldCriterion::save( Serializer& rSerializer ) const { KRATOS_SERIALIZE_SAVE_BASE_CLASS( rSerializer, YieldCriterion ) } void ModifiedMisesYieldCriterion::load( Serializer& rSerializer ) { KRATOS_SERIALIZE_LOAD_BASE_CLASS( rSerializer, YieldCriterion ) } } // namespace Kratos.
32.493976
123
0.513904
lkusch
24c330f2e3f866747cee4264ff09b664462b5de9
16,214
cpp
C++
platforms/android/modules/alexa/src/main/cpp/src/Alexa/AlexaConfigurationBinder.cpp
krishnaprasad/alexa-auto-sdk
2fb8d28a9c4138111f9b19c2527478562acc4643
[ "Apache-2.0" ]
null
null
null
platforms/android/modules/alexa/src/main/cpp/src/Alexa/AlexaConfigurationBinder.cpp
krishnaprasad/alexa-auto-sdk
2fb8d28a9c4138111f9b19c2527478562acc4643
[ "Apache-2.0" ]
null
null
null
platforms/android/modules/alexa/src/main/cpp/src/Alexa/AlexaConfigurationBinder.cpp
krishnaprasad/alexa-auto-sdk
2fb8d28a9c4138111f9b19c2527478562acc4643
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <AACE/JNI/Core/EngineConfigurationBinder.h> #include <AACE/JNI/Alexa/AlexaConfigurationBinder.h> // String to identify log entries originating from this file. static const char TAG[] = "aace.jni.alexa.config.AlexaConfigurationBinder"; // type aliases using TemplateRuntimeTimeout = aace::alexa::config::AlexaConfiguration::TemplateRuntimeTimeout; using TemplateRuntimeTimeoutType = aace::alexa::config::AlexaConfiguration::TemplateRuntimeTimeoutType; using EqualizerBand = aace::jni::alexa::EqualizerControllerHandler::EqualizerBand; namespace aace { namespace jni { namespace alexa { // // JTemplateRuntimeTimeout // TemplateRuntimeTimeout JTemplateRuntimeTimeout::getTemplateRuntimeTimeout() { try_with_context { jobject timeoutTypeObj; ThrowIfNot( invoke( "getType", "()Lcom/amazon/aace/alexa/config/AlexaConfiguration$TemplateRuntimeTimeoutType;", &timeoutTypeObj), "getType:invokeMethodFailed"); TemplateRuntimeTimeoutType checkedTimeoutTypeObj; ThrowIfNot( JTemplateRuntimeTimeoutType::checkType(timeoutTypeObj, &checkedTimeoutTypeObj), "invalidTimeoutType"); jint checkedInt; ThrowIfNot(invoke("getValue", "()I", &checkedInt), "getValue:invokeMethodFailed"); return {checkedTimeoutTypeObj, std::chrono::milliseconds(checkedInt)}; } catch_with_ex { AACE_JNI_ERROR(TAG, "getTemplateRuntimeTimeout", ex.what()); return {}; } } std::vector<TemplateRuntimeTimeout> JTemplateRuntimeTimeout::convert(jobjectArray timeoutArrObj) { try_with_context { std::vector<TemplateRuntimeTimeout> runtimeTimeouts; JObjectArray arr(timeoutArrObj); jobject next; for (int j = 0; j < arr.size(); j++) { ThrowIfNot(arr.getAt(j, &next), "getArrayValueFailed"); runtimeTimeouts.push_back(aace::jni::alexa::JTemplateRuntimeTimeout(next).getTemplateRuntimeTimeout()); } return runtimeTimeouts; } catch_with_ex { AACE_JNI_ERROR(TAG, "convert", ex.what()); return {}; } } } // namespace alexa } // namespace jni } // namespace aace // JNI extern "C" { JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createDeviceInfoConfigBinder( JNIEnv* env, jobject obj, jstring deviceSerialNumber, jstring clientId, jstring productId, jstring manufacturerName, jstring description) { try { auto config = aace::alexa::config::AlexaConfiguration::createDeviceInfoConfig( JString(deviceSerialNumber).toStdStr(), JString(clientId).toStdStr(), JString(productId).toStdStr(), JString(manufacturerName).toStdStr(), JString(description).toStdStr()); ThrowIfNull(config, "createDeviceInfoConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfigurationBinder_createDeviceInfoConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createAlertsConfigBinder( JNIEnv* env, jobject obj, jstring databaseFilePath) { try { auto config = aace::alexa::config::AlexaConfiguration::createAlertsConfig(JString(databaseFilePath).toStdStr()); ThrowIfNull(config, "createAlertsConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR(TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createAlertsConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createNotificationsConfigBinder( JNIEnv* env, jobject obj, jstring databaseFilePath) { try { auto config = aace::alexa::config::AlexaConfiguration::createNotificationsConfig(JString(databaseFilePath).toStdStr()); ThrowIfNull(config, "createNotificationsConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createNotificationsConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createCertifiedSenderConfigBinder( JNIEnv* env, jobject obj, jstring databaseFilePath) { try { auto config = aace::alexa::config::AlexaConfiguration::createCertifiedSenderConfig(JString(databaseFilePath).toStdStr()); ThrowIfNull(config, "createCertifiedSenderConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createCertifiedSenderConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createCapabilitiesDelegateConfigBinder( JNIEnv* env, jobject obj, jstring databaseFilePath) { try { auto config = aace::alexa::config::AlexaConfiguration::createCapabilitiesDelegateConfig( JString(databaseFilePath).toStdStr()); ThrowIfNull(config, "createCapabilitiesDelegateConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createCapabilitiesDelegateConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createCurlConfigBinder( JNIEnv* env, jobject obj, jstring certsPath, jstring iface) { try { auto config = iface != nullptr ? aace::alexa::config::AlexaConfiguration::createCurlConfig( JString(certsPath).toStdStr(), JString(iface).toStdStr()) : aace::alexa::config::AlexaConfiguration::createCurlConfig(JString(certsPath).toStdStr()); ThrowIfNull(config, "createCurlConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR(TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createCurlConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createMiscStorageConfigBinder( JNIEnv* env, jobject obj, jstring databaseFilePath) { try { auto config = aace::alexa::config::AlexaConfiguration::createMiscStorageConfig(JString(databaseFilePath).toStdStr()); ThrowIfNull(config, "createMiscStorageConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createMiscStorageConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createDeviceSettingsConfigBinder( JNIEnv* env, jobject obj, jstring databaseFilePath, jobjectArray locales, jstring defaultLocale, jstring defaultTimezone, jobjectArray localeCombinations = {}) { try { std::vector<std::string> localesVector; std::vector<std::vector<std::string>> localeCombinationsVector; int localesSize = env->GetArrayLength(locales); int localeCombinationsSize = env->GetArrayLength(localeCombinations); jstring locale; for (int j = 0; j < localesSize; j++) { locale = (jstring)env->GetObjectArrayElement(locales, j); localesVector.push_back(JString(locale).toStdStr()); } for (int i = 0; i < localeCombinationsSize; i++) { int localeCombinationSize = env->GetArrayLength((jobjectArray)env->GetObjectArrayElement(localeCombinations, i)); std::vector<std::string> localeCombinationVector; for (int j = 0; j < localeCombinationSize; j++) { locale = (jstring)env->GetObjectArrayElement( (jobjectArray)env->GetObjectArrayElement(localeCombinations, i), j); localeCombinationVector.push_back(JString(locale).toStdStr()); } localeCombinationsVector.push_back(localeCombinationVector); } auto config = aace::alexa::config::AlexaConfiguration::createDeviceSettingsConfig( JString(databaseFilePath).toStdStr(), localesVector, JString(defaultLocale).toStdStr(), JString(defaultTimezone).toStdStr(), localeCombinationsVector); ThrowIfNull(config, "createDeviceSettingsConfigConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createDeviceSettingsConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createSpeakerManagerConfigBinder( JNIEnv* env, jobject obj, jboolean enabled) { try { auto config = aace::alexa::config::AlexaConfiguration::createSpeakerManagerConfig(enabled); ThrowIfNull(config, "createSpeakerManagerConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createSpeakerManagerConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createSystemConfigBinder( JNIEnv* env, jobject obj, jint firmwareVersion) { try { auto config = aace::alexa::config::AlexaConfiguration::createSystemConfig(firmwareVersion); ThrowIfNull(config, "createSystemConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR(TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createSystemConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createSpeechRecognizerConfigBinder( JNIEnv* env, jobject obj, jstring encoderName) { try { auto config = aace::alexa::config::AlexaConfiguration::createSpeechRecognizerConfig(JString(encoderName).toStdStr()); ThrowIfNull(config, "createSpeechRecognizerConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createSpeechRecognizerConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createTemplateRuntimeTimeoutConfigBinder( JNIEnv* env, jobject obj, jobjectArray timeoutList) { try { auto config = aace::alexa::config::AlexaConfiguration::createTemplateRuntimeTimeoutConfig( aace::jni::alexa::JTemplateRuntimeTimeout::convert(timeoutList)); ThrowIfNull(config, "createTemplateRuntimeConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createTemplateRuntimeTimeoutConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createEqualizerControllerConfigBinder( JNIEnv* env, jobject obj, jobjectArray supportedBands, jint minLevel, jint maxLevel, jobjectArray defaultBandLevels) { try { std::vector<EqualizerBand> equalizerBands; JObjectArray bandsObjArr(supportedBands); jobject bandObj; EqualizerBand band; for (int j = 0; j < bandsObjArr.size(); j++) { ThrowIfNot(bandsObjArr.getAt(j, &bandObj), "getArrayValueFailed"); ThrowIfNot(aace::jni::alexa::JEqualizerBand::checkType(bandObj, &band), "invalidEqualizerBandType"); equalizerBands.push_back(band); } auto config = aace::alexa::config::AlexaConfiguration::createEqualizerControllerConfig( equalizerBands, minLevel, maxLevel, aace::jni::alexa::JEqualizeBandLevel::convert(defaultBandLevels)); ThrowIfNull(config, "createEqualizerControllerConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createEqualizerControllerConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createExternalMediaPlayerConfigBinder( JNIEnv* env, jobject obj, jstring agent) { try { auto config = aace::alexa::config::AlexaConfiguration::createExternalMediaPlayerConfig(JString(agent).toStdStr()); ThrowIfNull(config, "createExternalMediaPlayerConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createExternalMediaPlayerConfigBinder", ex.what()); return 0; } } JNIEXPORT jlong JNICALL Java_com_amazon_aace_alexa_config_AlexaConfiguration_createAuthProviderConfigBinder( JNIEnv* env, jobject obj, jobjectArray providerNames) { try { std::vector<std::string> providerNamesVector; int providerNamesSize = env->GetArrayLength(providerNames); jstring providerName; for (int j = 0; j < providerNamesSize; j++) { providerName = (jstring)env->GetObjectArrayElement(providerNames, j); providerNamesVector.push_back(JString(providerName).toStdStr()); } auto config = aace::alexa::config::AlexaConfiguration::createAuthProviderConfig(providerNamesVector); ThrowIfNull(config, "createAuthProviderConfigFailed"); return reinterpret_cast<long>(new aace::jni::core::config::EngineConfigurationBinder(config)); } catch (const std::exception& ex) { AACE_JNI_ERROR( TAG, "Java_com_amazon_aace_alexa_config_AlexaConfiguration_createAuthProviderConfigBinder", ex.what()); return 0; } } }
39.837838
120
0.704946
krishnaprasad
24c33c40653321a4e4db478187c783c22e089f39
10,897
cpp
C++
src/comm.cpp
ckrisgarrett/C3D-2015
76b751e8c33aa048e0e19c5aec53780735fd2144
[ "MIT" ]
null
null
null
src/comm.cpp
ckrisgarrett/C3D-2015
76b751e8c33aa048e0e19c5aec53780735fd2144
[ "MIT" ]
null
null
null
src/comm.cpp
ckrisgarrett/C3D-2015
76b751e8c33aa048e0e19c5aec53780735fd2144
[ "MIT" ]
null
null
null
/* File: comm.cpp Author: Kris Garrett Date: September 6, 2013 */ #include "global.h" #include "utils.h" #include <string.h> #include <stdlib.h> #ifdef USE_MPI #include <mpi.h> /* Returns MPI communication sizes in bytes. */ static double getBoundarySizeX() { return (g_gY[3] - g_gY[0] + 1) * (g_gZ[3] - g_gZ[0] + 1) * NUM_GHOST_CELLS * g_numMoments * sizeof(double); } static double getBoundarySizeY() { return (g_gX[3] - g_gX[0] + 1) * (g_gZ[3] - g_gZ[0] + 1) * NUM_GHOST_CELLS * g_numMoments * sizeof(double); } static double getBoundarySizeZ() { return (g_gX[3] - g_gX[0] + 1) * (g_gY[3] - g_gY[0] + 1) * NUM_GHOST_CELLS * g_numMoments * sizeof(double); } /* Returns the boundaries inside the domain (ie not the ghost cells). */ static void getInnerBoundaries(char *xPos, char *xNeg, char *yPos, char *yNeg, char *zPos, char *zNeg) { int x1 = g_gX[1]; int x2 = g_gX[2] + 1 - NUM_GHOST_CELLS; int y1 = g_gY[1]; int y2 = g_gY[2] + 1 - NUM_GHOST_CELLS; int z1 = g_gZ[1]; int z2 = g_gZ[2] + 1 - NUM_GHOST_CELLS; int index; // x for(int i = 0; i < NUM_GHOST_CELLS; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { index = k + (g_gZ[2] - g_gZ[1] + 1) * (j + i * (g_gY[2] - g_gY[1] + 1)); memcpy(&xPos[index * g_numMoments * sizeof(double)], &g_u[IU(x2+i,j,k,0)], g_numMoments * sizeof(double)); memcpy(&xNeg[index * g_numMoments * sizeof(double)], &g_u[IU(x1+i,j,k,0)], g_numMoments * sizeof(double)); }}} // y for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = 0; j < NUM_GHOST_CELLS; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { index = k + (g_gZ[2] - g_gZ[1] + 1) * (j + i * NUM_GHOST_CELLS); memcpy(&yPos[index * g_numMoments * sizeof(double)], &g_u[IU(i,y2+j,k,0)], g_numMoments * sizeof(double)); memcpy(&yNeg[index * g_numMoments * sizeof(double)], &g_u[IU(i,y1+j,k,0)], g_numMoments * sizeof(double)); }}} // z for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = 0; k < NUM_GHOST_CELLS; k++) { index = k + NUM_GHOST_CELLS * (j + i * (g_gY[2] - g_gY[1] + 1)); memcpy(&zPos[index * g_numMoments * sizeof(double)], &g_u[IU(i,j,z2+k,0)], g_numMoments * sizeof(double)); memcpy(&zNeg[index * g_numMoments * sizeof(double)], &g_u[IU(i,j,z1+k,0)], g_numMoments * sizeof(double)); }}} } /* Puts the input data into the ghost cells. */ static void setOuterBoundaries(char *xPos, char *xNeg, char *yPos, char *yNeg, char *zPos, char *zNeg) { int x1 = g_gX[0]; int x2 = g_gX[3] + 1 - NUM_GHOST_CELLS; int y1 = g_gY[0]; int y2 = g_gY[3] + 1 - NUM_GHOST_CELLS; int z1 = g_gZ[0]; int z2 = g_gZ[3] + 1 - NUM_GHOST_CELLS; int index; // x for(int i = 0; i < NUM_GHOST_CELLS; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { index = k + (g_gZ[2] - g_gZ[1] + 1) * (j + i * (g_gY[2] - g_gY[1] + 1)); memcpy(&g_u[IU(x2+i,j,k,0)], &xPos[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); memcpy(&g_u[IU(x1+i,j,k,0)], &xNeg[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); }}} // y for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = 0; j < NUM_GHOST_CELLS; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { index = k + (g_gZ[2] - g_gZ[1] + 1) * (j + i * NUM_GHOST_CELLS); memcpy(&g_u[IU(i,y2+j,k,0)], &yPos[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); memcpy(&g_u[IU(i,y1+j,k,0)], &yNeg[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); }}} // z for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = 0; k < NUM_GHOST_CELLS; k++) { index = k + NUM_GHOST_CELLS * (j + i * (g_gY[2] - g_gY[1] + 1)); memcpy(&g_u[IU(i,j,z2+k,0)], &zPos[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); memcpy(&g_u[IU(i,j,z1+k,0)], &zNeg[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); }}} } /* Given the node for the x,y,z direction, returns the 1D index for the node. */ static int mpiIndex(char direction, int node) { int nodeX = g_nodeX; int nodeY = g_nodeY; int nodeZ = g_nodeZ; if(direction == 'x') nodeX = (node + g_mpix) % g_mpix; else if(direction == 'y') nodeY = (node + g_mpiy) % g_mpiy; else if(direction == 'z') nodeZ = (node + g_mpiz) % g_mpiz; else { printf("Direction MPI Error.\n"); utils_abort(); } return nodeZ + g_mpiz * (nodeY + g_mpiy * nodeX); } /* MPI version of communicateBoundaries. It implements periodic boundary conditions. */ void communicateBoundaries() { // Variables. int boundarySizeX = getBoundarySizeX(); int boundarySizeY = getBoundarySizeY(); int boundarySizeZ = getBoundarySizeZ(); int sendXPosTag = 1; int recvXNegTag = 1; int sendXNegTag = 2; int recvXPosTag = 2; int sendYPosTag = 3; int recvYNegTag = 3; int sendYNegTag = 4; int recvYPosTag = 4; int sendZPosTag = 5; int recvZNegTag = 5; int sendZNegTag = 6; int recvZPosTag = 6; MPI_Request mpiRequest[12]; int mpiError; // Variables to allocate only once. static bool firstTime = true; static char *sendXPos = NULL; static char *sendXNeg = NULL; static char *recvXPos = NULL; static char *recvXNeg = NULL; static char *sendYPos = NULL; static char *sendYNeg = NULL; static char *recvYPos = NULL; static char *recvYNeg = NULL; static char *sendZPos = NULL; static char *sendZNeg = NULL; static char *recvZPos = NULL; static char *recvZNeg = NULL; // First time initialization. if(firstTime) { firstTime = false; sendXPos = (char*)malloc(boundarySizeX); sendXNeg = (char*)malloc(boundarySizeX); recvXPos = (char*)malloc(boundarySizeX); recvXNeg = (char*)malloc(boundarySizeX); sendYPos = (char*)malloc(boundarySizeY); sendYNeg = (char*)malloc(boundarySizeY); recvYPos = (char*)malloc(boundarySizeY); recvYNeg = (char*)malloc(boundarySizeY); sendZPos = (char*)malloc(boundarySizeZ); sendZNeg = (char*)malloc(boundarySizeZ); recvZPos = (char*)malloc(boundarySizeZ); recvZNeg = (char*)malloc(boundarySizeZ); if(sendXPos == NULL || sendXNeg == NULL || recvXPos == NULL || recvXNeg == NULL || sendYPos == NULL || sendYNeg == NULL || recvYPos == NULL || recvYNeg == NULL || sendZPos == NULL || sendZNeg == NULL || recvZPos == NULL || recvZNeg == NULL) { printf("comm.cpp: Memory allocation failed.\n"); utils_abort(); } } // Get boundaries to send. getInnerBoundaries(sendXPos, sendXNeg, sendYPos, sendYNeg, sendZPos, sendZNeg); // Send MPI_Isend(sendXPos, boundarySizeX, MPI_CHAR, mpiIndex('x', g_nodeX + 1), sendXPosTag, MPI_COMM_WORLD, &mpiRequest[0]); MPI_Isend(sendXNeg, boundarySizeX, MPI_CHAR, mpiIndex('x', g_nodeX - 1), sendXNegTag, MPI_COMM_WORLD, &mpiRequest[1]); MPI_Isend(sendYPos, boundarySizeY, MPI_CHAR, mpiIndex('y', g_nodeY + 1), sendYPosTag, MPI_COMM_WORLD, &mpiRequest[2]); MPI_Isend(sendYNeg, boundarySizeY, MPI_CHAR, mpiIndex('y', g_nodeY - 1), sendYNegTag, MPI_COMM_WORLD, &mpiRequest[3]); MPI_Isend(sendZPos, boundarySizeZ, MPI_CHAR, mpiIndex('z', g_nodeZ + 1), sendZPosTag, MPI_COMM_WORLD, &mpiRequest[4]); MPI_Isend(sendZNeg, boundarySizeZ, MPI_CHAR, mpiIndex('z', g_nodeZ - 1), sendZNegTag, MPI_COMM_WORLD, &mpiRequest[5]); // Recv MPI_Irecv(recvXPos, boundarySizeX, MPI_CHAR, mpiIndex('x', g_nodeX + 1), recvXPosTag, MPI_COMM_WORLD, &mpiRequest[6]); MPI_Irecv(recvXNeg, boundarySizeX, MPI_CHAR, mpiIndex('x', g_nodeX - 1), recvXNegTag, MPI_COMM_WORLD, &mpiRequest[7]); MPI_Irecv(recvYPos, boundarySizeY, MPI_CHAR, mpiIndex('y', g_nodeY + 1), recvYPosTag, MPI_COMM_WORLD, &mpiRequest[8]); MPI_Irecv(recvYNeg, boundarySizeY, MPI_CHAR, mpiIndex('y', g_nodeY - 1), recvYNegTag, MPI_COMM_WORLD, &mpiRequest[9]); MPI_Irecv(recvZPos, boundarySizeZ, MPI_CHAR, mpiIndex('z', g_nodeZ + 1), recvZPosTag, MPI_COMM_WORLD, &mpiRequest[10]); MPI_Irecv(recvZNeg, boundarySizeZ, MPI_CHAR, mpiIndex('z', g_nodeZ - 1), recvZNegTag, MPI_COMM_WORLD, &mpiRequest[11]); // Wait for Send/Recv mpiError = MPI_Waitall(12, mpiRequest, MPI_STATUSES_IGNORE); if(mpiError != MPI_SUCCESS) { printf("comm.cpp: MPI Error %d.\n", mpiError); utils_abort(); } // Set ghost boundaries. setOuterBoundaries(recvXPos, recvXNeg, recvYPos, recvYNeg, recvZPos, recvZNeg); } #else /* Serial version of communicateBoundaries. It implements periodic boundary conditions. */ void communicateBoundaries() { int x0 = g_gX[0]; int x1 = g_gX[1]; int x2 = g_gX[2] + 1 - NUM_GHOST_CELLS; int x3 = g_gX[3] + 1 - NUM_GHOST_CELLS; int y0 = g_gY[0]; int y1 = g_gY[1]; int y2 = g_gY[2] + 1 - NUM_GHOST_CELLS; int y3 = g_gY[3] + 1 - NUM_GHOST_CELLS; int z0 = g_gZ[0]; int z1 = g_gZ[1]; int z2 = g_gZ[2] + 1 - NUM_GHOST_CELLS; int z3 = g_gZ[3] + 1 - NUM_GHOST_CELLS; // x for(int i = 0; i < NUM_GHOST_CELLS; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { for(int m = 0; m < g_numMoments; m++) { g_u[IU(x0+i,j,k,m)] = g_u[IU(x2+i,j,k,m)]; g_u[IU(x3+i,j,k,m)] = g_u[IU(x1+i,j,k,m)]; }}}} // y for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = 0; j < NUM_GHOST_CELLS; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { for(int m = 0; m < g_numMoments; m++) { g_u[IU(i,y0+j,k,m)] = g_u[IU(i,y2+j,k,m)]; g_u[IU(i,y3+j,k,m)] = g_u[IU(i,y1+j,k,m)]; }}}} // z for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = 0; k < NUM_GHOST_CELLS; k++) { for(int m = 0; m < g_numMoments; m++) { g_u[IU(i,j,z0+k,m)] = g_u[IU(i,j,z2+k,m)]; g_u[IU(i,j,z3+k,m)] = g_u[IU(i,j,z1+k,m)]; }}}} } #endif
33.42638
95
0.564834
ckrisgarrett
24c40051257477239e4aefb7b39bbed8838c2052
507
cpp
C++
leetcode/153_Find-Minimum-in-Rotated-Sorted-Array/FindMin.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
1
2017-10-13T10:34:46.000Z
2017-10-13T10:34:46.000Z
leetcode/153_Find-Minimum-in-Rotated-Sorted-Array/FindMin.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
null
null
null
leetcode/153_Find-Minimum-in-Rotated-Sorted-Array/FindMin.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int findMin(vector<int>& nums) { int n = nums.size(); if (n <= 0) return 0; if (n == 1) return nums[0]; int left = 0; int right = n - 1; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] > nums[right]) left = mid + 1; else if (nums[mid] < nums[right]) right = mid; } return nums[left]; } };
25.35
58
0.487179
chasingegg
24c43e8624709e2201d2e79d6f1f08627e8678a3
439
cpp
C++
Kattis-Solutions/Backspace.cpp
SurgicalSteel/Competitive-Programming
3662b676de94796f717b25dc8d1b93c6851fb274
[ "MIT" ]
14
2016-02-11T09:26:13.000Z
2022-03-27T01:14:29.000Z
Kattis-Solutions/Backspace.cpp
SurgicalSteel/Competitive-Programming
3662b676de94796f717b25dc8d1b93c6851fb274
[ "MIT" ]
null
null
null
Kattis-Solutions/Backspace.cpp
SurgicalSteel/Competitive-Programming
3662b676de94796f717b25dc8d1b93c6851fb274
[ "MIT" ]
7
2016-10-25T19:29:35.000Z
2021-12-05T18:31:39.000Z
#include <bits/stdc++.h> using namespace std; #define psb push_back int main() { string s; cin>>s; if(s.length()==1){cout<<s<<"\n";} else { stack<string> ss; for(int i=0;i<s.length();++i) { if(s.substr(i,1)!="<"){ss.push(s.substr(i,1));} else{ss.pop();} } vector<string> vs; while(!ss.empty()) { vs.psb(ss.top()); ss.pop(); } for(int i=vs.size()-1;i>=0;--i){cout<<vs[i];} printf("\n"); } return 0; }
16.259259
50
0.530752
SurgicalSteel
24c45235ff20b5f80136dc02bf808429808375b4
5,663
cc
C++
tensorflow/core/grappler/costs/virtual_placer.cc
tianhm/tensorflow
e55574f28257bdacd744dcdba86c839e661b1b2a
[ "Apache-2.0" ]
47
2017-03-08T20:58:54.000Z
2021-06-24T07:07:49.000Z
tensorflow/core/grappler/costs/virtual_placer.cc
genSud/tensorflow
ec8216568d8cd9810004067558041c11a8356685
[ "Apache-2.0" ]
1
2019-07-11T16:29:54.000Z
2019-07-11T16:29:54.000Z
tensorflow/core/grappler/costs/virtual_placer.cc
genSud/tensorflow
ec8216568d8cd9810004067558041c11a8356685
[ "Apache-2.0" ]
19
2017-04-17T01:28:40.000Z
2020-08-15T13:01:33.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/grappler/costs/virtual_placer.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/grappler/clusters/cluster.h" #include "tensorflow/core/grappler/devices.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { namespace grappler { VirtualPlacer::VirtualPlacer(const Cluster* cluster) { CHECK(cluster); devices_ = cluster->GetDevices(); if (devices_.empty()) { // If there are no devices in the cluster, add a single device, "UNKNOWN" to // the cluster. default_device_ = "UNKNOWN"; DeviceProperties& prop = devices_["UNKNOWN"]; prop.set_type("UNKNOWN"); } else if (devices_.size() == 1) { // If there is only one device in the cluster, use it as default device, // whatever it is. default_device_ = devices_.begin()->first; } else { // Default device is set from the devices in the cluster in the following // priority: /gpu:0, /cpu:0, or any device. // TODO(dyoon): This logic assumes single machine with CPU and GPU devices. // Make it more general to support multiple machines, job types, and devices // other than CPU and GPU. std::map<int, string> cpu_devices; // CPU device map: id -> device name. std::map<int, string> gpu_devices; // GPU device map: id -> device name. for (const auto& device : devices_) { DeviceNameUtils::ParsedName parsed_name; bool parsed = DeviceNameUtils::ParseFullName(device.first, &parsed_name); if (parsed) { // Parsed devices are stored to cpu_devices or gpu_devices map, // addressed (and orderd) by device id. if (str_util::Lowercase(parsed_name.type) == "gpu") { gpu_devices[parsed_name.id] = device.first; } else if (str_util::Lowercase(parsed_name.type) == "cpu") { cpu_devices[parsed_name.id] = device.first; } } } if (!gpu_devices.empty()) { // GPU:0 (or GPU with smallest device id). default_device_ = gpu_devices.begin()->second; } else if (!cpu_devices.empty()) { // CPU:0 (or CPU with smallest device id). default_device_ = cpu_devices.begin()->second; } else { default_device_ = devices_.begin()->first; // Any device. } } // Default job name for canonical device name. default_job_name_ = "localhost"; // Scan the device names from the cluster, and if there is one job name used, // use it for canonical device name. std::unordered_set<string> job_names_from_cluster; for (const auto& device : devices_) { const auto& device_name = device.first; DeviceNameUtils::ParsedName parsed_name; bool parsed = DeviceNameUtils::ParseFullName(device_name, &parsed_name); if (parsed && !parsed_name.job.empty()) { job_names_from_cluster.insert(parsed_name.job); } } // If there is only type of job name in all the devices in the cluster, use // that one as default job name; otherwise, use localhost. // TODO(dyoon): this should be improved, especially when the cluster is // composed of multiple worker, PS, and other types of jobs. if (job_names_from_cluster.size() == 1) { auto it = job_names_from_cluster.begin(); default_job_name_ = *it; } } const DeviceProperties& VirtualPlacer::get_device(const NodeDef& node) const { string device = get_canonical_device_name(node); VLOG(3) << "Device name: " << device; auto it = devices_.find(device); DCHECK(it != devices_.end()); return it->second; } string VirtualPlacer::get_canonical_device_name(const NodeDef& node) const { string device; if (!node.device().empty()) { if (devices_.find(node.device()) != devices_.end()) { return node.device(); } DeviceNameUtils::ParsedName parsed_name; bool parsed = DeviceNameUtils::ParseFullName(node.device(), &parsed_name); if (!parsed) { parsed = DeviceNameUtils::ParseLocalName(node.device(), &parsed_name); parsed_name.job = "localhost"; } if (!parsed) { if (node.device() == "GPU" || node.device() == "CPU" || node.device() == "gpu" || node.device() == "cpu") { parsed_name.job = "localhost"; parsed_name.type = node.device(); parsed = true; } } if (!parsed) { return get_default_device_name(); } else { if (parsed_name.job.empty()) { parsed_name.job = default_job_name_; } device = strings::StrCat( "/job:", parsed_name.job, "/replica:", parsed_name.replica, "/task:", parsed_name.task, "/", str_util::Lowercase(parsed_name.type), ":", parsed_name.id); } } else { return get_default_device_name(); } if (devices_.find(device) == devices_.end()) { return get_default_device_name(); } return device; } const string& VirtualPlacer::get_default_device_name() const { return default_device_; } } // end namespace grappler } // end namespace tensorflow
37.753333
80
0.666961
tianhm
24c45595e93abef055dbd268558dec5fb6858ce6
4,251
cpp
C++
Editor/src/windows/assets_create/SceneCreator.cpp
ThakeeNathees/PixelEngine
4df8d8b209497ffae881d65da9eebaa054279b41
[ "Apache-2.0" ]
11
2020-08-23T17:36:40.000Z
2021-08-24T09:42:50.000Z
Editor/src/windows/assets_create/SceneCreator.cpp
ThakeeNathees/PixelEngine
4df8d8b209497ffae881d65da9eebaa054279b41
[ "Apache-2.0" ]
1
2020-08-24T06:56:46.000Z
2020-08-24T13:56:14.000Z
Editor/src/windows/assets_create/SceneCreator.cpp
ThakeeNathees/Pixel-Engine
4df8d8b209497ffae881d65da9eebaa054279b41
[ "Apache-2.0" ]
3
2019-12-09T13:03:22.000Z
2020-04-08T06:00:53.000Z
#include "pch.h" #include "SceneCreator.h" // cpp include #include "windows/file_tree/FileTree.h" SceneCreator* SceneCreator::s_instance = nullptr; void SceneCreator::render() { if (m_open) { ImGui::Begin("Create New Script", &m_open); ImGui::SetWindowSize(ImVec2(400, 220), ImGuiCond_Once); static float witdh_frac = .6f; // title ImGui::Text("Create a new Scene Here"); ImGui::Text(""); // scene name ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * witdh_frac); ImGui::InputText("scene name", m_scene_name, sizeof(m_scene_name)); // script path select ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * witdh_frac); ImGui::InputText("scene path ", m_scene_path, sizeof(m_scene_path)); ImGui::SameLine(); static auto obj_path_button = Resources::getFileFormatIcon("dir_open"); if (ImGui::ImageButton(obj_path_button)) { ExplorerPopup::getInstance()->setPath("."); ImGui::OpenPopup("Explorer"); ExplorerPopup::getInstance()->setParentWindow(2); } /************************ end of input fields ********************/ // create button ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 20); if (ImGui::Button("Create", ImVec2(-1, 20))) { std::string str_scene_path = std::string(m_scene_path); // char array to string if (m_scene_name[0] == '\0' || m_scene_name[0] == '\0') ImGui::OpenPopup("Error!"); else if (!PyUtils::getInstance()->getStrUtil().attr("isValidName")(std::string(m_scene_name)).cast<bool>()) ImGui::OpenPopup("Invalid Scene Name!"); else if (!PyUtils::getInstance()->getOs().attr("path").attr("isdir")(std::string(m_scene_path)).cast<bool>()) ImGui::OpenPopup("Invalid Scene Path!"); else { int scn_id = CLI::getInstance()->getPeproj().next_scn_id++; //std::string scn_file_path = std::string(m_scene_path).append("/").append(std::string(m_scene_name)).append(".scn.xml"); // TODO: check path exists, also for object creator auto obj_tag = m_py_scn_maker.attr("newScene")(std::string(m_scene_name), scn_id); m_py_scn_maker.attr("writeScene")(obj_tag, std::string(m_scene_path)); int error = CLI::getInstance()->projFileUpdate(false); if (error) { CLI::log("Error: in CLI::projFileUpdate(false) -> project file may damaged", Console::LOGLEVEL_ERROR); } m_open = false; m_is_scene_created = true; FileTree::getInstance()->reload(); } } // render popups ExplorerPopup::getInstance()->render(); if (ImGui::BeginPopupModal("Error!")) { ImGui::SetWindowSize(ImVec2(300, 120), ImGuiCond_Once); ImGui::Image(Resources::getOtherIcon("error")); ImGui::SameLine(); if (m_scene_name[0] == '\0') ImGui::TextWrapped("Error! enter a Scene Name!"); else ImGui::TextWrapped("Error! enter the Scene Path!"); if (ImGui::Button("OK", ImVec2(280, 20))) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } if (ImGui::BeginPopupModal("Invalid Scene Path!")) { ImGui::SetWindowSize(ImVec2(300, 120), ImGuiCond_Once); ImGui::Image(Resources::getOtherIcon("error")); ImGui::SameLine(); ImGui::TextWrapped("Error! scene path is invalid"); if (ImGui::Button("OK", ImVec2(280, 20))) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } if (ImGui::BeginPopupModal("Invalid Scene Name!")) { ImGui::SetWindowSize(ImVec2(300, 140), ImGuiCond_Once); ImGui::Image(Resources::getOtherIcon("error")); ImGui::SameLine(); ImGui::TextWrapped("Error! scene name is invalid. (scene name must start with alphabatic character and doesn't contain any of the following \\ / : * ? \" < > | spacebar)"); if (ImGui::Button("OK", ImVec2(280, 20))) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } // capture selected path to inputs if (ExplorerPopup::getInstance()->isPathSelected() && ExplorerPopup::getInstance()->getParentWindow() == 2) { ExplorerPopup::getInstance()->setParentWindow(-1); auto rel_path = PyUtils::getInstance()->getFileUtil().attr("relPath")(ExplorerPopup::getInstance()->getSelectedPath()).cast<std::string>(); const char* c = rel_path.c_str(); int i = 0; // to copy string while (c[i]) m_scene_path[i] = c[i++]; m_scene_path[i] = 0; ExplorerPopup::getInstance()->setPathSelectedFalse(); } ImGui::End(); } }
39
175
0.669725
ThakeeNathees
24c72f6b20c435a4c35c6da2ddfdddbaeb5fc1a1
34,826
cpp
C++
cpp/nvgraph/cpp/tests/nvgraph_capi_tests_clustering.cpp
seunghwak/cugraph
f2f6f9147ce8c2f46b7b6dbc335f885c11b69004
[ "Apache-2.0" ]
16
2019-09-13T11:43:26.000Z
2022-03-02T10:11:59.000Z
cpp/nvgraph/cpp/tests/nvgraph_capi_tests_clustering.cpp
seunghwak/cugraph
f2f6f9147ce8c2f46b7b6dbc335f885c11b69004
[ "Apache-2.0" ]
5
2020-02-12T14:55:25.000Z
2021-12-06T17:55:12.000Z
cpp/nvgraph/cpp/tests/nvgraph_capi_tests_clustering.cpp
seunghwak/cugraph
f2f6f9147ce8c2f46b7b6dbc335f885c11b69004
[ "Apache-2.0" ]
6
2020-04-06T01:34:45.000Z
2021-01-21T17:13:24.000Z
#include <utility> #include "gtest/gtest.h" #include "nvgraph_test_common.h" #include "valued_csr_graph.hxx" #include "readMatrix.hxx" #include "nvgraphP.h" #include "nvgraph.h" #include "nvgraph_experimental.h" #include "stdlib.h" #include <algorithm> extern "C" { #include "mmio.h" } #include "mm.hxx" // do the perf measurements, enabled by command line parameter '--perf' static int PERF = 0; // minimum vertices in the graph to perform perf measurements #define PERF_ROWS_LIMIT 1000 // number of repeats = multiplier/num_vertices #define PARTITIONER_ITER_MULTIPLIER 1 #define SELECTOR_ITER_MULTIPLIER 1 // iterations for stress tests = this multiplier * iterations for perf tests static int STRESS_MULTIPLIER = 10; static std::string ref_data_prefix = ""; static std::string graph_data_prefix = ""; // utility template <typename T> struct nvgraph_Const; template <> struct nvgraph_Const<double> { static const cudaDataType_t Type = CUDA_R_64F; static const double inf; static const double tol; typedef union fpint { double f; unsigned long u; } fpint_st; }; const double nvgraph_Const<double>::inf = DBL_MAX; const double nvgraph_Const<double>::tol = 1e-6; // this is what we use as a tolerance in the algorithms, more precision than this is useless for CPU reference comparison template <> struct nvgraph_Const<float> { static const cudaDataType_t Type = CUDA_R_32F; static const float inf; static const float tol; typedef union fpint { float f; unsigned u; } fpint_st; }; const float nvgraph_Const<float>::inf = FLT_MAX; const float nvgraph_Const<float>::tol = 1e-4; template <typename T> bool enough_device_memory(int n, int nnz, size_t add) { size_t mtotal, mfree; cudaMemGetInfo(&mfree, &mtotal); if (mfree > add + sizeof(T)*3*(n + nnz)) return true; return false; } std::string convert_to_local_path(const std::string& in_file) { std::string wstr = in_file; if ((wstr != "dummy") & (wstr != "")) { std::string prefix; if (graph_data_prefix.length() > 0) { prefix = graph_data_prefix; } else { #ifdef _WIN32 //prefix = "C:\\mnt\\eris\\test\\matrices_collection\\"; prefix = "Z:\\matrices_collection\\"; std::replace(wstr.begin(), wstr.end(), '/', '\\'); #else prefix = "/mnt/nvgraph_test_data/"; #endif } wstr = prefix + wstr; } return wstr; } std::string convert_to_local_path_refdata(const std::string& in_file) { std::string wstr = in_file; if ((wstr != "dummy") & (wstr != "")) { std::string prefix; if (ref_data_prefix.length() > 0) { prefix = ref_data_prefix; } else { #ifdef _WIN32 //prefix = "C:\\mnt\\eris\\test\\ref_data\\"; prefix = "Z:\\ref_data\\"; std::replace(wstr.begin(), wstr.end(), '/', '\\'); #else prefix = "/mnt/nvgraph_test_data/ref_data/"; #endif } wstr = prefix + wstr; } return wstr; } /**************************** * SPECTRAL CLUSTERING *****************************/ typedef struct SpectralClustering_Usecase_t { std::string graph_file; int clusters; int eigenvalues; nvgraphSpectralClusteringType_t algorithm; nvgraphClusteringMetric_t metric; SpectralClustering_Usecase_t(const std::string& a, int b, int c, nvgraphSpectralClusteringType_t d, nvgraphClusteringMetric_t e) : clusters(b), eigenvalues(c), algorithm(d), metric(e){ graph_file = convert_to_local_path(a);}; SpectralClustering_Usecase_t& operator=(const SpectralClustering_Usecase_t& rhs) { graph_file = rhs.graph_file; clusters = rhs.clusters; eigenvalues = rhs.eigenvalues; algorithm = rhs.algorithm; metric = rhs.metric; return *this; } } SpectralClustering_Usecase; class NVGraphCAPITests_SpectralClustering : public ::testing::TestWithParam<SpectralClustering_Usecase> { public: NVGraphCAPITests_SpectralClustering() : handle(NULL) {} static void SetupTestCase() {} static void TearDownTestCase() {} virtual void SetUp() { if (handle == NULL) { status = nvgraphCreate(&handle); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); } } virtual void TearDown() { if (handle != NULL) { status = nvgraphDestroy(handle); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); handle = NULL; } } nvgraphStatus_t status; nvgraphHandle_t handle; template <typename T> void run_current_test(const SpectralClustering_Usecase& param) { const ::testing::TestInfo* const test_info =::testing::UnitTest::GetInstance()->current_test_info(); std::stringstream ss; ss << param.clusters; ss << param.eigenvalues; ss << param.algorithm; ss << param.metric; std::string test_id = std::string(test_info->test_case_name()) + std::string(".") + std::string(test_info->name()) + std::string("_") + getFileName(param.graph_file) + std::string("_") + ss.str().c_str(); nvgraphStatus_t status; int m, n, nnz; MM_typecode mc; FILE* fpin = fopen(param.graph_file.c_str(),"r"); ASSERT_TRUE(fpin != NULL) << "Cannot read input graph file: " << param.graph_file << std::endl; ASSERT_EQ(mm_properties<int>(fpin, 1, &mc, &m, &n, &nnz),0) << "could not read Matrix Market file properties"<< "\n"; ASSERT_TRUE(mm_is_matrix(mc)); ASSERT_TRUE(mm_is_coordinate(mc)); ASSERT_TRUE(m==n); ASSERT_FALSE(mm_is_complex(mc)); ASSERT_FALSE(mm_is_skew(mc)); // Allocate memory on host std::vector<int> cooRowIndA(nnz); std::vector<int> csrColIndA(nnz); std::vector<int> csrRowPtrA(n+1); std::vector<T> csrValA(nnz); ASSERT_EQ( (mm_to_coo<int,T>(fpin, 1, nnz, &cooRowIndA[0], &csrColIndA[0], &csrValA[0], NULL)) , 0)<< "could not read matrix data"<< "\n"; ASSERT_EQ( (coo_to_csr<int,T> (n, n, nnz, &cooRowIndA[0], &csrColIndA[0], &csrValA[0], NULL, &csrRowPtrA[0], NULL, NULL, NULL)), 0) << "could not covert COO to CSR "<< "\n"; ASSERT_EQ(fclose(fpin),0); //ASSERT_TRUE(fpin != NULL) << "Cannot read input graph file: " << param.graph_file << std::endl; int *clustering_d; if (!enough_device_memory<T>(n, nnz, sizeof(int)*(csrRowPtrA.size() + csrColIndA.size()))) { std::cout << "[ WAIVED ] " << test_info->test_case_name() << "." << test_info->name() << std::endl; return; } cudaMalloc((void**)&clustering_d , n*sizeof(int)); nvgraphGraphDescr_t g1 = NULL; status = nvgraphCreateGraphDescr(handle, &g1); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); // set up graph nvgraphCSRTopology32I_st topology = {n, nnz, &csrRowPtrA[0], &csrColIndA[0]}; status = nvgraphSetGraphStructure(handle, g1, (void*)&topology, NVGRAPH_CSR_32); // set up graph data size_t numsets = 1; void* edgeptr[1] = {(void*)&csrValA[0]}; cudaDataType_t type_e[1] = {nvgraph_Const<T>::Type}; status = nvgraphAllocateEdgeData(handle, g1, numsets, type_e ); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); status = nvgraphSetEdgeData(handle, g1, (void *)edgeptr[0], 0 ); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); int weight_index = 0; struct SpectralClusteringParameter clustering_params; clustering_params.n_clusters = param.clusters; clustering_params.n_eig_vects = param.eigenvalues; clustering_params.algorithm = param.algorithm; clustering_params.evs_tolerance = 0.0f ; clustering_params.evs_max_iter = 0; clustering_params.kmean_tolerance = 0.0f; clustering_params.kmean_max_iter = 0; std::vector<int> random_assignments_h(n); std::vector<T> eigVals_h(param.eigenvalues); std::vector<T> eigVecs_h(n*param.eigenvalues); float score = 0.0, random_score = 0.0; if (PERF && n > PERF_ROWS_LIMIT) { double start, stop; start = second(); int repeat = std::max((int)((float)(PARTITIONER_ITER_MULTIPLIER)/n), 1); for (int i = 0; i < repeat; i++) status =nvgraphSpectralClustering(handle, g1, weight_index, &clustering_params, clustering_d, &eigVals_h[0], &eigVecs_h[0]); stop = second(); printf("&&&& PERF Time_%s %10.8f -ms\n", test_id.c_str(), 1000.0*(stop-start)/repeat); } else status =nvgraphSpectralClustering(handle, g1, weight_index, &clustering_params, clustering_d, &eigVals_h[0], &eigVecs_h[0]); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); // Analyse quality status = nvgraphAnalyzeClustering(handle, g1, weight_index, param.clusters, clustering_d, param.metric, &score); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); //printf("Score = %f\n", score); // === // Synthetic random for (int i=0; i<n; i++) { random_assignments_h[i] = rand() % param.clusters; //printf("%d ", random_assignments_h[i]); } status = nvgraphAnalyzeClustering(handle, g1, weight_index, param.clusters, &random_assignments_h[0], param.metric, &random_score); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); //printf("Random modularity = %f\n", modularity2); if (param.metric == NVGRAPH_MODULARITY) EXPECT_GE(score, random_score); // we want higher modularity else EXPECT_GE(random_score, score); //we want less edge cut cudaFree(clustering_d); status = nvgraphDestroyGraphDescr(handle, g1); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); } }; TEST_P(NVGraphCAPITests_SpectralClustering, CheckResultDouble) { run_current_test<double>(GetParam()); } TEST_P(NVGraphCAPITests_SpectralClustering, CheckResultFloat) { run_current_test<float>(GetParam()); } // --gtest_filter=*ModularityCorrectness* INSTANTIATE_TEST_CASE_P(SpectralModularityCorrectnessCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 2, 2, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 3, 3, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/uk.mtx", 2, 2, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/uk.mtx", 3, 3, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/data.mtx", 3, 3, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/data.mtx", 5, 5, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/data.mtx", 7, 7, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/cti.mtx", 3, 3,NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/cti.mtx", 5, 5,NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 7,NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY) ///// more instances ) ); // --gtest_filter=*ModularityCorner* INSTANTIATE_TEST_CASE_P(SpectralModularityCornerCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/uk.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/delaunay_n12.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/data.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 4,NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 4, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 17, 7, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY) // tests cases on coAuthorsDBLP may diverge on some cards (likely due to different normalization operation) //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 4,NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 17, 7,NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY) ///// more instances ) ); // --gtest_filter=*LanczosBlancedCutCorrectness* INSTANTIATE_TEST_CASE_P(SpectralLanczosBlancedCutCorrectnessCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 2, 2,NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 4, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/uk.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n12.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/data.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT) ///// more instances ) ); // --gtest_filter=*LanczosBlancedCutCorner* INSTANTIATE_TEST_CASE_P(SpectralLanczosBlancedCutCornerCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/uk.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n12.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/data.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 4,NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 17, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT) // tests cases on coAuthorsDBLP may diverge on some cards (likely due to different normalization operation) //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 4,NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 17, 7,NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT) ) ); // --gtest_filter=*LobpcgBlancedCutCorrectness* INSTANTIATE_TEST_CASE_P(SpectralLobpcgBlancedCutCorrectnessCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 2, 2,NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 4, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/uk.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n12.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT) ///// more instances ) ); // --gtest_filter=*LobpcgBlancedCutCorner* INSTANTIATE_TEST_CASE_P(SpectralLobpcgBlancedCutCornerCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/uk.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n12.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/data.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 4,NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 17, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT) // tests cases on coAuthorsDBLP may diverge on some cards (likely due to different normalization operation) //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 4,NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 17, 7,NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT) ///// more instances ) ); //Followinf tests were commented becasue they are a bit redundent and quite long to run // previous tests already contain dataset with 1 million edges //// --gtest_filter=*ModularityLargeCorrectness* //INSTANTIATE_TEST_CASE_P(SpectralModularityLargeCorrectnessCheck, // NVGraphCAPITests_SpectralClustering, // // graph FILE number of clusters # number of eigenvalues # // ::testing::Values( // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 2, 2, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 3, 3, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 5, 5, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 7, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 2, 2, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 3, 3, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 5, 5, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 7, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY) // ///// more instances // ) // ); // //// --gtest_filter=*LanczosBlancedCutLargeCorrectness* //INSTANTIATE_TEST_CASE_P(SpectralLanczosBlancedCutLargeCorrectnessCheck, // NVGraphCAPITests_SpectralClustering, // // graph FILE number of clusters # number of eigenvalues # // ::testing::Values( // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 2, 2, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 5, 5, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 2, 2, NVGRAPH_BALANCED_CUT_LANCZOS,NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LANCZOS,NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 5, 5, NVGRAPH_BALANCED_CUT_LANCZOS,NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS,NVGRAPH_RATIO_CUT) // ) // ); //// --gtest_filter=*LobpcgBlancedCutLargeCorrectness* //INSTANTIATE_TEST_CASE_P(SpectralLobpcgBlancedCutLargeCorrectnessCheck, // NVGraphCAPITests_SpectralClustering, // // graph FILE number of clusters # number of eigenvalues # // ::testing::Values( // //SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 2, 2, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 5, 5, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 2, 2, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 5, 5, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT) // ) // ); /**************************** * SELECTOR *****************************/ typedef struct Selector_Usecase_t { std::string graph_file; nvgraphEdgeWeightMatching_t metric; Selector_Usecase_t(const std::string& a, nvgraphEdgeWeightMatching_t b) : metric(b){ graph_file = convert_to_local_path(a);}; Selector_Usecase_t& operator=(const Selector_Usecase_t& rhs) { graph_file = rhs.graph_file; metric = rhs.metric; return *this; } }Selector_Usecase; class NVGraphCAPITests_Selector : public ::testing::TestWithParam<Selector_Usecase> { public: NVGraphCAPITests_Selector() : handle(NULL) {} static void SetupTestCase() {} static void TearDownTestCase() {} virtual void SetUp() { if (handle == NULL) { status = nvgraphCreate(&handle); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); } } virtual void TearDown() { if (handle != NULL) { status = nvgraphDestroy(handle); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); handle = NULL; } } nvgraphStatus_t status; nvgraphHandle_t handle; template <typename T> void run_current_test(const Selector_Usecase& param) { const ::testing::TestInfo* const test_info =::testing::UnitTest::GetInstance()->current_test_info(); std::stringstream ss; ss << param.metric; std::string test_id = std::string(test_info->test_case_name()) + std::string(".") + std::string(test_info->name()) + std::string("_") + getFileName(param.graph_file)+ std::string("_") + ss.str().c_str(); nvgraphStatus_t status; int m, n, nnz; MM_typecode mc; FILE* fpin = fopen(param.graph_file.c_str(),"r"); ASSERT_TRUE(fpin != NULL) << "Cannot read input graph file: " << param.graph_file << std::endl; ASSERT_EQ(mm_properties<int>(fpin, 1, &mc, &m, &n, &nnz),0) << "could not read Matrix Market file properties"<< "\n"; ASSERT_TRUE(mm_is_matrix(mc)); ASSERT_TRUE(mm_is_coordinate(mc)); ASSERT_TRUE(m==n); ASSERT_FALSE(mm_is_complex(mc)); ASSERT_FALSE(mm_is_skew(mc)); // Allocate memory on host std::vector<int> cooRowIndA(nnz); std::vector<int> csrColIndA(nnz); std::vector<int> csrRowPtrA(n+1); std::vector<T> csrValA(nnz); ASSERT_EQ( (mm_to_coo<int,T>(fpin, 1, nnz, &cooRowIndA[0], &csrColIndA[0], &csrValA[0], NULL)) , 0)<< "could not read matrix data"<< "\n"; ASSERT_EQ( (coo_to_csr<int,T> (n, n, nnz, &cooRowIndA[0], &csrColIndA[0], &csrValA[0], NULL, &csrRowPtrA[0], NULL, NULL, NULL)), 0) << "could not covert COO to CSR "<< "\n"; ASSERT_EQ(fclose(fpin),0); //ASSERT_TRUE(fpin != NULL) << "Cannot read input graph file: " << param.graph_file << std::endl; if (!enough_device_memory<T>(n, nnz, sizeof(int)*(csrRowPtrA.size() + csrColIndA.size()))) { std::cout << "[ WAIVED ] " << test_info->test_case_name() << "." << test_info->name() << std::endl; return; } //int *aggregates_d; //cudaMalloc((void**)&aggregates_d , n*sizeof(int)); nvgraphGraphDescr_t g1 = NULL; status = nvgraphCreateGraphDescr(handle, &g1); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); // set up graph nvgraphCSRTopology32I_st topology = {n, nnz, &csrRowPtrA[0], &csrColIndA[0]}; status = nvgraphSetGraphStructure(handle, g1, (void*)&topology, NVGRAPH_CSR_32); // set up graph data size_t numsets = 1; //void* vertexptr[1] = {(void*)&calculated_res[0]}; //cudaDataType_t type_v[1] = {nvgraph_Const<T>::Type}; void* edgeptr[1] = {(void*)&csrValA[0]}; cudaDataType_t type_e[1] = {nvgraph_Const<T>::Type}; //status = nvgraphAllocateVertexData(handle, g1, numsets, type_v); //ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); //status = nvgraphSetVertexData(handle, g1, vertexptr[0], 0, NVGRAPH_CSR_32 ); //ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); status = nvgraphAllocateEdgeData(handle, g1, numsets, type_e ); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); status = nvgraphSetEdgeData(handle, g1, (void *)edgeptr[0], 0 ); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); int weight_index = 0; std::vector<int> aggregates_h(n); //std::vector<int> aggregates_global_h(n); size_t num_aggregates; size_t *num_aggregates_ptr = &num_aggregates; status = nvgraphHeavyEdgeMatching(handle, g1, weight_index, param.metric, &aggregates_h[0], num_aggregates_ptr); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); std::cout << "n = " << n << ", num aggregates = " << num_aggregates << std::endl; if (param.metric == NVGRAPH_SCALED_BY_DIAGONAL) EXPECT_EQ(num_aggregates, static_cast<size_t>(166)); // comparing against amgx result on poisson2D.mtx else EXPECT_LE(num_aggregates, static_cast<size_t>(n)); // just make sure the output make sense //for (int i=0; i<n; i++) //{ // printf("%d\n", aggregates_h[i]); //} status = nvgraphDestroyGraphDescr(handle, g1); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); } }; TEST_P(NVGraphCAPITests_Selector, CheckResultDouble) { run_current_test<double>(GetParam()); } TEST_P(NVGraphCAPITests_Selector, CheckResultFloat) { run_current_test<float>(GetParam()); } // --gtest_filter=*Correctness* INSTANTIATE_TEST_CASE_P(SmallCorrectnessCheck, NVGraphCAPITests_Selector, // graph FILE SIMILARITY_METRIC ::testing::Values( Selector_Usecase("Florida/poisson2D.mtx", NVGRAPH_SCALED_BY_DIAGONAL), Selector_Usecase("dimacs10/delaunay_n10.mtx", NVGRAPH_SCALED_BY_ROW_SUM), Selector_Usecase("dimacs10/delaunay_n10.mtx", NVGRAPH_UNSCALED), Selector_Usecase("dimacs10/uk.mtx", NVGRAPH_SCALED_BY_ROW_SUM), Selector_Usecase("dimacs10/uk.mtx", NVGRAPH_UNSCALED), Selector_Usecase("dimacs10/data.mtx", NVGRAPH_SCALED_BY_ROW_SUM), Selector_Usecase("dimacs10/data.mtx", NVGRAPH_UNSCALED), Selector_Usecase("dimacs10/cti.mtx", NVGRAPH_SCALED_BY_ROW_SUM), Selector_Usecase("dimacs10/cti.mtx", NVGRAPH_UNSCALED) ///// more instances ) ); int main(int argc, char **argv) { srand(42); ::testing::InitGoogleTest(&argc, argv); for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "--perf") == 0) PERF = 1; if (strcmp(argv[i], "--stress-iters") == 0) STRESS_MULTIPLIER = atoi(argv[i+1]); if (strcmp(argv[i], "--ref-data-dir") == 0) ref_data_prefix = std::string(argv[i+1]); if (strcmp(argv[i], "--graph-data-dir") == 0) graph_data_prefix = std::string(argv[i+1]); } return RUN_ALL_TESTS(); return 0; }
53.088415
229
0.584822
seunghwak
24c796b8ef924857dae0df21aaede888ebbeb2c0
6,388
cpp
C++
src/rdx/rdx_containers.cpp
elasota/rdx2
e08ca09a07d3ac8675f7f950a7bdf838a9f5f907
[ "MIT" ]
null
null
null
src/rdx/rdx_containers.cpp
elasota/rdx2
e08ca09a07d3ac8675f7f950a7bdf838a9f5f907
[ "MIT" ]
null
null
null
src/rdx/rdx_containers.cpp
elasota/rdx2
e08ca09a07d3ac8675f7f950a7bdf838a9f5f907
[ "MIT" ]
null
null
null
#include "rdx_reftypedefs.hpp" #include "rdx_builtins.hpp" void rdxCStructContainer::VisitReferences(rdxIObjectManager *objm, rdxIObjectReferenceVisitor *visitor, bool visitNonSerializable) { rdxDebugBreak(rdxBREAKCAUSE_Unimplemented); } void rdxCStructContainer::InitializeContents(rdxIObjectManager *objm, rdxWeakRTRef(rdxCStructuredType) st) { // TODO MUSTFIX } class rdxXAPI_ArrayContainer_Shim { public: RDX_FORCEINLINE static void VisitReferences(rdxCArrayContainer *v, rdxIObjectManager *objm, rdxIObjectReferenceVisitor *visitor, bool visitNonSerializable) { v->VisitReferences_Local(objm, visitor, visitNonSerializable); } RDX_FORCEINLINE static void ComputeContainerSize(rdxSOperationContext *ctx, rdxLargeUInt elementSize, rdxLargeUInt numElements, rdxLargeUInt numDimensions, rdxLargeUInt *outDimensionsOffset, rdxLargeUInt *outSize) { rdxCArrayContainer::ComputeContainerSize_Local(ctx, elementSize, numElements, numDimensions, outDimensionsOffset, outSize); } }; RDX_DYNLIB_API void rdxXAPI_ArrayContainer_VisitReferences(rdxCArrayContainer *v, rdxIObjectManager *objm, rdxIObjectReferenceVisitor *visitor, bool visitNonSerializable) { rdxXAPI_ArrayContainer_Shim::VisitReferences(v, objm, visitor, visitNonSerializable); } RDX_DYNLIB_API void rdxXAPI_ArrayContainer_ComputeContainerSize(rdxSOperationContext *ctx, rdxLargeUInt elementSize, rdxLargeUInt numElements, rdxLargeUInt numDimensions, rdxLargeUInt *outDimensionsOffset, rdxLargeUInt *outSize) { rdxXAPI_ArrayContainer_Shim::ComputeContainerSize(ctx, elementSize, numElements, numDimensions, outDimensionsOffset, outSize); } void rdxCArrayContainer::VisitReferences_Local(rdxIObjectManager *objm, rdxIObjectReferenceVisitor *visitor, bool visitNonSerializable) { rdxUInt8 *byteBase = reinterpret_cast<rdxUInt8*>(ModifyRawData()); rdxLargeUInt stride = m_stride; rdxLargeUInt numElements = m_numElements; rdxIfcTypeInfo typeInfo = m_contentsTypeInfo; rdxWeakRTRef(rdxCStructuredType) structureST; rdxWeakRTRef(rdxCArrayOfType) arrayContainerType = this->ObjectInfo()->containerType.ToWeakRTRef().StaticCast<rdxCArrayOfType>(); bool isCRefArray = false; bool isIRefArray = false; bool isStructArray = false; bool isPODArray = false; bool isUnknownTypeArray = true; if(arrayContainerType.IsNotNull()) { rdxWeakRTRef(rdxCType) subscriptType = arrayContainerType->type.ToWeakRTRef(); if(subscriptType.IsNotNull()) { isUnknownTypeArray = false; rdxWeakRTRef(rdxCType) subscriptTypeType = subscriptType->ObjectInfo()->containerType.ToWeakRTRef(); if(subscriptTypeType == objm->GetBuiltIns()->st_StructuredType) { rdxWeakRTRef(rdxCStructuredType) subscriptST = subscriptType.StaticCast<rdxCStructuredType>(); if(subscriptST->storageSpecifier == rdxSS_RefStruct || subscriptST->storageSpecifier == rdxSS_ValStruct) { structureST = subscriptST; isStructArray = true; } else if(subscriptST->storageSpecifier == rdxSS_Class) isCRefArray = true; else if(subscriptST->storageSpecifier == rdxSS_Interface) isIRefArray = true; else if(subscriptST->storageSpecifier == rdxSS_Enum) isPODArray = true; } else if(subscriptTypeType == objm->GetBuiltIns()->st_ArrayOfType) isCRefArray = true; else if(subscriptTypeType == objm->GetBuiltIns()->st_DelegateType) isCRefArray = true; } } if(isCRefArray) { while(numElements--) { rdxTracedRTRef(rdxCObject) *refP = reinterpret_cast<rdxTracedRTRef(rdxCObject)*>(byteBase); visitor->VisitReference(objm, *refP); byteBase += sizeof(rdxTracedRTRef(rdxCObject)); } } else if(isIRefArray) { while(numElements--) { rdxTracedTypelessIRef *refP = reinterpret_cast<rdxTracedTypelessIRef*>(byteBase); visitor->VisitReference(objm, *refP); byteBase += sizeof(rdxTracedTypelessIRef); } } else if(isStructArray) { objm->VisitStructureReferences(byteBase, visitor, visitNonSerializable, typeInfo, structureST, stride, numElements); } else if(isPODArray) { } else if(isUnknownTypeArray) { rdxIfcTypeFuncs typeFuncs = m_contentsTypeInfo.TypeFuncs(); if(typeFuncs.IsNotNull()) { rdxIfcTypeFuncs::VisitReferencesFunc vrf = m_contentsTypeInfo.TypeFuncs().GetVisitReferencesFunc(); if(vrf != RDX_CNULL) { while(numElements--) { vrf(objm, byteBase, visitor, visitNonSerializable); byteBase += stride; } } } } } void rdxCArrayContainer::InitializeContents(rdxIObjectManager *objm, bool zeroFill, rdxWeakRTRef(rdxCType) contentsType) { // TODO MUSTFIX - Need defaults int todo = 0; } void rdxCArrayContainer::InitializeArray(rdxLargeUInt numElements, rdxLargeUInt overflow, rdxLargeUInt stride, rdxLargeUInt dimensionsOffset, rdxIfcTypeInfo contentsTypeInfo) { m_numElements = numElements; m_overflow = overflow; m_stride = stride; m_dimensionsOffset = dimensionsOffset; m_contentsTypeInfo = contentsTypeInfo; } void rdxCArrayContainer::ComputeContainerSize_Local(rdxSOperationContext *ctx, rdxLargeUInt elementSize, rdxLargeUInt numElements, rdxLargeUInt numDimensions, rdxLargeUInt *outDimensionsOffset, rdxLargeUInt *outSize) { rdxLargeUInt sz = rdxPaddedSize(sizeof(rdxCArrayContainer), RDX_MAX_ALIGNMENT); if(!rdxCheckMulOverflowU(elementSize, numElements)) RDX_LTHROW(ctx, RDX_ERROR_INTEGER_OVERFLOW); rdxLargeUInt arrayContentsSize = elementSize * numElements; rdxLargeUInt dimSize = 0; if(numDimensions > 0) { if(!rdxCheckAddOverflowU(numDimensions, 1)) RDX_LTHROW(ctx, RDX_ERROR_INTEGER_OVERFLOW); if(!rdxCheckMulOverflowU(numDimensions + 1, sizeof(rdxLargeUInt))) RDX_LTHROW(ctx, RDX_ERROR_INTEGER_OVERFLOW); dimSize = (numDimensions + 1) * sizeof(rdxLargeUInt); } if(!rdxCheckAddOverflowU(dimSize, RDX_MAX_ALIGNMENT - 1)) RDX_LTHROW(ctx, RDX_ERROR_INTEGER_OVERFLOW); dimSize += RDX_MAX_ALIGNMENT - 1; dimSize -= dimSize % RDX_MAX_ALIGNMENT; if(!rdxCheckAddOverflowU(sz, arrayContentsSize)) RDX_LTHROW(ctx, RDX_ERROR_INTEGER_OVERFLOW); sz += arrayContentsSize; if(!rdxCheckAddOverflowU(sz, dimSize)) RDX_LTHROW(ctx, RDX_ERROR_INTEGER_OVERFLOW); if(outDimensionsOffset != RDX_CNULL) *outDimensionsOffset = sz; sz += dimSize; if(outSize != RDX_CNULL) *outSize = sz; }
37.139535
229
0.766594
elasota
24c8cc7529379dee87d921eb4741ee34c6bdb2bc
4,607
hpp
C++
srcs/list/list_iterator.hpp
paozer/ft_containers
ec6db7fa47b31abae3d6a997b344315c884f4b45
[ "Unlicense" ]
1
2021-02-16T23:16:05.000Z
2021-02-16T23:16:05.000Z
srcs/list/list_iterator.hpp
paozer/ft_containers
ec6db7fa47b31abae3d6a997b344315c884f4b45
[ "Unlicense" ]
null
null
null
srcs/list/list_iterator.hpp
paozer/ft_containers
ec6db7fa47b31abae3d6a997b344315c884f4b45
[ "Unlicense" ]
null
null
null
#pragma once #include "list_node.hpp" #include "../utils/utils.hpp" #include <cstddef> // NULL, std::ptrdiff_t #include <iterator> // std::bidirectional_iterator_tag namespace ft { template <class T, bool is_const> class list_iterator { public: typedef T value_type; typedef std::ptrdiff_t difference_type; typedef typename choose<is_const, const T*, T*>::type pointer; typedef typename choose<is_const, const T&, T&>::type reference; typedef std::bidirectional_iterator_tag iterator_category; private: typedef list_iterator<value_type, is_const> self_type; typedef typename choose<is_const, const list_node<value_type>*, list_node<value_type>*>::type node_pointer; public: /* CONSTRUCTORS */ list_iterator (node_pointer node = NULL) : _node(node) { } list_iterator (const list_iterator<value_type, false>& other) : _node(other.get_node()) { } /* OPERATORS */ list_iterator& operator= (const self_type& other) { if (this != &other) _node = other._node; return *this; } friend bool operator== (const self_type& rhs, const self_type& lhs) { return rhs._node == lhs._node; } friend bool operator!= (const self_type& rhs, const self_type& lhs) { return rhs._node != lhs._node; } reference operator* (void) { return _node->content; } pointer operator-> (void) { return &_node->content; } self_type& operator++ (void) { _node = _node->next; return *this; } self_type operator++ (int) { self_type tmp = *this; _node = _node->next; return tmp; } self_type& operator-- (void) { _node = _node->prev; return *this; } self_type operator-- (int) { self_type tmp = *this; _node = _node->prev; return tmp; } /* GETTERS */ node_pointer get_prev (void) const { return _node->prev; } node_pointer get_next (void) const { return _node->next; } node_pointer get_node (void) const { return _node; } private: node_pointer _node; }; // CLASS LIST_ITERATOR template <class T, bool is_const> class reverse_list_iterator { public: typedef T value_type; typedef std::ptrdiff_t difference_type; typedef typename choose<is_const, const T*, T*>::type pointer; typedef typename choose<is_const, const T&, T&>::type reference; typedef std::bidirectional_iterator_tag iterator_category; private: typedef reverse_list_iterator<value_type, is_const> self_type; typedef typename choose<is_const, const list_node<value_type>*, list_node<value_type>*>::type node_pointer; public: /* CONSTRUCTORS */ reverse_list_iterator (node_pointer node = NULL) : _node(node) { } reverse_list_iterator (const reverse_list_iterator<value_type, false>& other) : _node(other.get_node()) { } /* OPERATORS */ reverse_list_iterator& operator= (const self_type& other) { if (this != &other) _node = other._node; return *this; } friend bool operator== (const self_type& rhs, const self_type& lhs) { return rhs._node == lhs._node; } friend bool operator!= (const self_type& rhs, const self_type& lhs) { return !(rhs == lhs); } reference operator* (void) { return _node->content; } pointer operator-> (void) { return &_node->content; } self_type& operator++ (void) { _node = _node->prev; return *this; } self_type operator++ (int) { self_type tmp = *this; _node = _node->prev; return tmp; } self_type& operator-- (void) { _node = _node->next; return *this; } self_type operator-- (int) { self_type tmp = *this; _node = _node->next; return tmp; } /* GETTERS */ node_pointer get_prev (void) const { return _node->prev; } node_pointer get_next (void) const { return _node->next; } node_pointer get_node (void) const { return _node; } private: node_pointer _node; }; // CLASS REVERSE_LIST_ITERATOR } // NAMESPACE FT
27.921212
115
0.569351
paozer
24c934f081d9ad0d56c6c5ee51ae4f9c7033400e
1,596
hpp
C++
Sources/Audio/SoundBuffer.hpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
Sources/Audio/SoundBuffer.hpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
Sources/Audio/SoundBuffer.hpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
#pragma once #include "Maths/Vector3.hpp" #include "Resources/Resource.hpp" #include "Audio.hpp" namespace acid { /** * @brief Resource that represents a sound buffer. */ class ACID_EXPORT SoundBuffer : public Resource { public: /** * Creates a new sound buffer, or finds one with the same values. * @param metadata The metadata to decode values from. * @return The sound buffer with the requested values. */ static std::shared_ptr<SoundBuffer> Create(const Metadata &metadata); /** * Creates a new sound buffer, or finds one with the same values. * @param filename The file to load the sound buffer from. * @return The sound buffer with the requested values. */ static std::shared_ptr<SoundBuffer> Create(const std::string &filename); /** * Creates a new sound buffer. * @param filename The file to load the sound buffer from. * @param load If this resource will be loaded immediately, otherwise {@link SoundBuffer#Load} can be called later. */ explicit SoundBuffer(std::string filename, const bool &load = true); ~SoundBuffer(); void Load() override; const std::string &GetFilename() const { return m_filename; }; const uint32_t &GetBuffer() const { return m_buffer; } ACID_EXPORT friend const Metadata &operator>>(const Metadata &metadata, SoundBuffer &soundBuffer); ACID_EXPORT friend Metadata &operator<<(Metadata &metadata, const SoundBuffer &soundBuffer); private: static uint32_t LoadBufferWav(const std::string &filename); static uint32_t LoadBufferOgg(const std::string &filename); std::string m_filename; uint32_t m_buffer; }; }
27.517241
116
0.736842
liuping1997
24cb85e54cd50c9746b27788c67e923e9747c047
1,079
cpp
C++
Excelenta/Problema1.cpp
NegreanV/MyAlgorithms
7dd16d677d537d34280c3858ccf4cbea4b3ddf26
[ "Apache-2.0" ]
1
2015-10-24T10:02:06.000Z
2015-10-24T10:02:06.000Z
Excelenta/Problema1.cpp
NegreanV/MyAlgorithms
7dd16d677d537d34280c3858ccf4cbea4b3ddf26
[ "Apache-2.0" ]
null
null
null
Excelenta/Problema1.cpp
NegreanV/MyAlgorithms
7dd16d677d537d34280c3858ccf4cbea4b3ddf26
[ "Apache-2.0" ]
null
null
null
/*Se considera fisierul BAC.TXT ce contine un sir crescator cu cel mult un milion de numere naturale de cel mult noua cifre fiecare, separate prin câte un spatiu. Sa se scrie un program C/C++ care, folosind un algoritm eficient din punct de vedere al memoriei utilizate si al timpului de executare, citeste din fisier toti termenii sirului si afiseaza pe ecran, pe o singura linie, fiecare termen distinct al sirului urmat de numarul de aparitii ale acestuia în sir. Valorile afisate sunt separate prin câte un spatiu. Exemplu: daca fisierul BAC.TXT are urmatorul continut: 1 1 1 5 5 5 5 9 9 11 20 20 20 programul va afisa: 1 3 5 4 9 2 11 1 20 3 deoarece 1 apare de 3 ori, 5 apare de 4 ori,etc */ #include <fstream> using namespace std; int main() { ifstream f("input.in"); long x, y, n; f >> x; n = 1; while(f >> y) { if(x == y) { n++; } else { cout << x << " " << n << " "; n = 1; } x = y; } cout << x << " " << n; return 0; }
25.690476
86
0.599629
NegreanV
24d0626c3a47f6d399935c90b5edbf5dd7428df0
1,492
cc
C++
src/kernel.cc
klantz81/feature-detection
1ed289711128a30648e198b085534fe9a9610984
[ "MIT" ]
null
null
null
src/kernel.cc
klantz81/feature-detection
1ed289711128a30648e198b085534fe9a9610984
[ "MIT" ]
null
null
null
src/kernel.cc
klantz81/feature-detection
1ed289711128a30648e198b085534fe9a9610984
[ "MIT" ]
null
null
null
#include "kernel.h" cKernel::cKernel(int kernel_radius, double mu, double sigma) : kernel_radius(kernel_radius), mu(mu), sigma(sigma) { this->kernel = new double[this->kernel_radius * 2 + 1]; this->kernel_derivative = new double[this->kernel_radius * 2 + 1]; for (int _i = -this->kernel_radius; _i <= this->kernel_radius; _i++) { this->kernel[_i + this->kernel_radius] = 1.0 / (this->sigma * sqrt(2.0 * M_PI)) * exp(-0.5 * pow((_i - this->mu) / this->sigma, 2.0)); this->kernel_derivative[_i + this->kernel_radius] = - (_i - mu) / (pow(this->sigma, 2.0) * sqrt(2.0 * M_PI)) * exp(-0.5 * pow((_i - this->mu) / this->sigma, 2.0)); } double sum0 = 0.0, sum1 = 0.0; for (int _i = -this->kernel_radius; _i <= this->kernel_radius; _i++) { sum0 += this->kernel[_i + this->kernel_radius]; sum1 -= _i * this->kernel_derivative[_i + this->kernel_radius]; } for (int _i = -this->kernel_radius; _i <= this->kernel_radius; _i++) { this->kernel[_i + this->kernel_radius] /= sum0; this->kernel_derivative[_i + this->kernel_radius] /= sum1; } sum0 = 0.0; sum1 = 0.0; for (int _i = -this->kernel_radius; _i <= this->kernel_radius; _i++) { sum0 += this->kernel[_i + this->kernel_radius]; sum1 -= _i * this->kernel_derivative[_i + this->kernel_radius]; } std::cout << "kernel summation: " << sum0 << std::endl; std::cout << "kernel derivative summation: " << sum1 << std::endl; } cKernel::~cKernel() { delete [] this->kernel; delete [] this->kernel_derivative; }
42.628571
165
0.632708
klantz81
24d4f10e103130563f1b3b21732b8fac57d35c50
8,027
cpp
C++
MIPS/mipsr3000/pi_control.cpp
lovisXII/RISC-V-project
8131f8b2cb2d476ebf80c71d727b1b3831fd6811
[ "MIT" ]
3
2022-02-07T02:15:14.000Z
2022-02-14T09:43:28.000Z
MIPS/mipsr3000/pi_control.cpp
lovisXII/RISC-V-project
8131f8b2cb2d476ebf80c71d727b1b3831fd6811
[ "MIT" ]
null
null
null
MIPS/mipsr3000/pi_control.cpp
lovisXII/RISC-V-project
8131f8b2cb2d476ebf80c71d727b1b3831fd6811
[ "MIT" ]
null
null
null
#include "pi_control.h" void pi_control::processPI_IREQ() { sc_uint<8> pi_ireq; pi_ireq[0]=PI_IREQ0.read(); pi_ireq[1]=PI_IREQ1.read(); pi_ireq[2]=PI_IREQ2.read(); pi_ireq[3]=PI_IREQ3.read(); pi_ireq[4]=PI_IREQ4.read(); pi_ireq[5]=PI_IREQ5.read(); pi_ireq[6]=PI_IREQ6.read(); pi_ireq[7]=PI_IREQ7.read(); PI_IREQ.write(pi_ireq); } void pi_control::processCK_SX() { CK_SX.write(CK.read()); } void pi_control::processREQUEST_SX() { REQUEST_SX.write(PI_IREQ.read()); } void pi_control::processCURPRIO_SX7() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX7.write(prior_rx[7] & (CURPRIO_SX6.read() | request_sx[7])); } void pi_control::processCURPRIO_SX6() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX6.write(prior_rx[6] & (CURPRIO_SX5.read() | request_sx[6])); } void pi_control::processCURPRIO_SX5() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX5.write(prior_rx[5] & (CURPRIO_SX4.read() | request_sx[5])); } void pi_control::processCURPRIO_SX4() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX4.write(prior_rx[4] & (CURPRIO_SX3.read() | request_sx[4])); } void pi_control::processCURPRIO_SX3() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX3.write(prior_rx[3] & (CURPRIO_SX2.read() | request_sx[3])); } void pi_control::processCURPRIO_SX2() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX2.write(prior_rx[2] & (CURPRIO_SX1.read() | request_sx[2])); } void pi_control::processCURPRIO_SX1() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX1.write(prior_rx[1] & (CURPRIO_SX0.read() | request_sx[1])); } void pi_control::processCURPRIO_SX0() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX0.write(prior_rx[0] & (CURPRIO_SX7.read() | request_sx[0])); } void pi_control::processCURPRIO_SX() { sc_uint<8> curprio_sx=0x0; curprio_sx[0]=CURPRIO_SX0.read(); curprio_sx[1]=CURPRIO_SX1.read(); curprio_sx[2]=CURPRIO_SX2.read(); curprio_sx[3]=CURPRIO_SX3.read(); curprio_sx[4]=CURPRIO_SX4.read(); curprio_sx[5]=CURPRIO_SX5.read(); curprio_sx[6]=CURPRIO_SX6.read(); curprio_sx[7]=CURPRIO_SX7.read(); CURPRIO_SX.write(curprio_sx); } void pi_control::processGRANT_SX() { sc_uint<8> grant_sx; sc_uint<8> request_sx=REQUEST_SX.read(); sc_uint<8> curprio_sx=CURPRIO_SX.read(); grant_sx[7]=(request_sx[7] & (!curprio_sx[6])); grant_sx[6]=(request_sx[6] & (!curprio_sx[5])); grant_sx[5]=(request_sx[5] & (!curprio_sx[4])); grant_sx[4]=(request_sx[4] & (!curprio_sx[3])); grant_sx[3]=(request_sx[3] & (!curprio_sx[2])); grant_sx[2]=(request_sx[2] & (!curprio_sx[1])); grant_sx[1]=(request_sx[1] & (!curprio_sx[0])); grant_sx[0]=(request_sx[0] & (!curprio_sx[7])); GRANT_SX.write(grant_sx); } void pi_control::processDFLMSTR_SX() { sc_uint<8> dflmstr_sx=0x0; sc_uint<8> prior_rx=PRIOR_RX.read(); dflmstr_sx.range(7,1)=prior_rx.range(7,1) & (~prior_rx.range(6,0)); dflmstr_sx[0]=prior_rx[0] & (!prior_rx[7]); DFLMSTR_SX.write(dflmstr_sx); } void pi_control::processGLBRQST_SX() { GLBRQST_SX.write((REQUEST_SX.read()==0x0)?0:1); } void pi_control::processCMPDFLT_SX() { CMPDFLT_SX.write(DFLMSTR_SX.read() & REQUEST_SX.read()); } void pi_control::processDFLTRQS_SX() { DFLTRQS_SX.write((CMPDFLT_SX.read()==0x0)?0:1); } void pi_control::processSELECT_SX() { sc_uint<32> pi_a=PI_A.read(); sc_uint<32> pi_a_shft=pi_a << 2; if (pi_a_shft.range(31,12)==0x0) SELECT_SX.write(0x1); else if (pi_a_shft.range(31,12)==0x00400) SELECT_SX.write(0x2); else if (pi_a_shft.range(31,12)==0x80000) SELECT_SX.write(0x4); else if (pi_a_shft.range(31,12)==0xBFC00) SELECT_SX.write(0x8); else if (pi_a_shft.range(31,12)==0xC0000) SELECT_SX.write(0x10); else SELECT_SX.write(0x0); } void pi_control::processC_NXTS_SX() { if (RESET_RX.read()==1) C_NXTS_SX.write(c_idle); else if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==0)) C_NXTS_SX.write(c_idle); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read() ==1) && (GLBRQST_SX.read() ==0)) C_NXTS_SX.write(c_idle); else if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==1) && (DFLTRQS_SX.read() ==0)) C_NXTS_SX.write(c_fadr); else if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==1) && (DFLTRQS_SX.read() ==1)&& (PI_LOCK.read() ==1)) C_NXTS_SX.write(c_fadr); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read() ==1) && (GLBRQST_SX.read() ==1)) C_NXTS_SX.write(c_fadr); else if ((C_STAT_RX.read() == c_fadr) && (PI_LOCK.read() ==1)) C_NXTS_SX.write(c_nadr); else if ((C_STAT_RX.read() == c_nadr) && (PI_LOCK.read() ==1)) C_NXTS_SX.write(c_nadr); else if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==1) && (DFLTRQS_SX.read() ==1)&& (PI_LOCK.read() ==0)) C_NXTS_SX.write(c_ldat); else if ((C_STAT_RX.read() == c_fadr) && (PI_LOCK.read() ==0)) C_NXTS_SX.write(c_ldat); else if ((C_STAT_RX.read() == c_nadr) && (PI_LOCK.read() ==0)) C_NXTS_SX.write(c_ldat); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read() ==0)) C_NXTS_SX.write(c_ldat); else C_NXTS_SX.write(c_idle); } void pi_control::processWRTPRIO_SX() { if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==1 )) WRTPRIO_SX.write(1); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read() ==1 )&& (GLBRQST_SX.read() ==1 )) WRTPRIO_SX.write(1); else WRTPRIO_SX.write(0); } void pi_control::processPI_TOUT() { PI_TOUT <= '0'; } void pi_control::processTRANRQS_SX() { if ((PI_OPC.read()==0x0) || (PI_OPC.read()==0x1)) TRANRQS_SX.write(0); else TRANRQS_SX.write(1); } void pi_control::processDATARDY_SX() { if ((PI_ACK.read() == ack_rdy) || (PI_ACK.read() == ack_rdm) | (PI_ACK.read() == ack_spl)) DATARDY_SX.write(1); else DATARDY_SX.write(0); } void pi_control::processPI_SEL() { if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==1) && (DFLTRQS_SX.read() ==1)) PI_SEL.write(SELECT_SX.read()); else if ((C_STAT_RX.read() == c_fadr) && (TRANRQS_SX.read() ==1)) PI_SEL.write(SELECT_SX.read()); else if ((C_STAT_RX.read() == c_nadr) && (TRANRQS_SX.read() ==1) && (DATARDY_SX.read() ==1)) PI_SEL.write(SELECT_SX.read()); else PI_SEL.write(0x0); } void pi_control::processPI_GNT() { if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read()==0)) PI_GNT.write(DFLMSTR_SX.read()); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read()==1)&& (GLBRQST_SX.read()==0)) PI_GNT.write(DFLMSTR_SX.read()); else if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read()==1)&& (DFLTRQS_SX.read()==0)) PI_GNT.write(GRANT_SX.read()); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read()==1)&& (GLBRQST_SX.read()==1)) PI_GNT.write(GRANT_SX.read()); else PI_GNT.write(0x0); } void pi_control::processC_STAT_RX() { C_STAT_RX.write(C_NXTS_SX.read()); } void pi_control::processPRIOR_RX() { if (RESET_RX.read()==1) PRIOR_RX.write(0x7F); else if (WRTPRIO_SX.read()==1) PRIOR_RX.write(~GRANT_SX.read()); } void pi_control::processRESET_RX() { RESET_RX.write(!RESET_N.read()); } void pi_control::processGNTS() { sc_uint<8> pi_gnt=PI_GNT.read(); PI_GNT0.write(pi_gnt[0]); PI_GNT1.write(pi_gnt[1]); PI_GNT2.write(pi_gnt[2]); PI_GNT3.write(pi_gnt[3]); PI_GNT4.write(pi_gnt[4]); PI_GNT5.write(pi_gnt[5]); PI_GNT6.write(pi_gnt[6]); PI_GNT7.write(pi_gnt[7]); } void pi_control::processSELS() { sc_uint<8> pi_sel=PI_SEL.read(); PI_SEL0.write(pi_sel[0]); PI_SEL1.write(pi_sel[1]); PI_SEL2.write(pi_sel[2]); PI_SEL3.write(pi_sel[3]); PI_SEL4.write(pi_sel[4]); PI_SEL5.write(pi_sel[5]); PI_SEL6.write(pi_sel[6]); PI_SEL7.write(pi_sel[7]); }
26.57947
117
0.665753
lovisXII
24d7ec97e429ddae0ff31e23caff4c73292b190e
5,952
cc
C++
tensorflow/lite/core/api/flatbuffer_conversions_test.cc
where-is-brett/tensorflow
5da8599b2cf9edfb9fac4431c705501bf7ceccd8
[ "Apache-2.0" ]
57
2017-09-03T07:08:31.000Z
2022-02-28T04:33:42.000Z
tensorflow/lite/core/api/flatbuffer_conversions_test.cc
sagol/tensorflow
04f2870814d2773e09dcfa00cbe76a66a2c4de88
[ "Apache-2.0" ]
58
2021-11-22T05:41:28.000Z
2022-01-19T01:33:40.000Z
tensorflow/lite/core/api/flatbuffer_conversions_test.cc
sagol/tensorflow
04f2870814d2773e09dcfa00cbe76a66a2c4de88
[ "Apache-2.0" ]
66
2020-05-15T10:05:12.000Z
2022-02-14T07:28:18.000Z
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/core/api/flatbuffer_conversions.h" #include <cstring> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/string_type.h" namespace tflite { namespace { class MockErrorReporter : public ErrorReporter { public: MockErrorReporter() : buffer_size_(0) {} int Report(const char* format, va_list args) override { buffer_size_ = vsnprintf(buffer_, kBufferSize, format, args); return buffer_size_; } char* GetBuffer() { return buffer_; } int GetBufferSize() { return buffer_size_; } string GetAsString() const { return string(buffer_, buffer_size_); } private: static constexpr int kBufferSize = 256; char buffer_[kBufferSize]; int buffer_size_; }; // Used to determine how the op data parsing function creates its working space. class MockDataAllocator : public BuiltinDataAllocator { public: MockDataAllocator() : is_allocated_(false) {} void* Allocate(size_t size) override { EXPECT_FALSE(is_allocated_); const int max_size = kBufferSize; EXPECT_LE(size, max_size); is_allocated_ = true; return buffer_; } void Deallocate(void* data) override { is_allocated_ = false; } private: static constexpr int kBufferSize = 1024; char buffer_[kBufferSize]; bool is_allocated_; }; } // namespace class FlatbufferConversionsTest : public ::testing::Test { public: const Operator* BuildTestOperator(BuiltinOptions op_type, flatbuffers::Offset<void> options) { flatbuffers::Offset<Operator> offset = CreateOperatorDirect(builder_, 0, nullptr, nullptr, op_type, options, nullptr, CustomOptionsFormat_FLEXBUFFERS, nullptr); builder_.Finish(offset); void* pointer = builder_.GetBufferPointer(); return flatbuffers::GetRoot<Operator>(pointer); } protected: MockErrorReporter mock_reporter_; MockDataAllocator mock_allocator_; flatbuffers::FlatBufferBuilder builder_; }; TEST_F(FlatbufferConversionsTest, ParseBadSqueeze) { const Operator* op = BuildTestOperator( BuiltinOptions_SqueezeOptions, CreateSqueezeOptions(builder_).Union()); void* output_data = nullptr; EXPECT_NE(kTfLiteOk, ParseOpData(op, BuiltinOperator_SQUEEZE, &mock_reporter_, &mock_allocator_, &output_data)); EXPECT_THAT(mock_reporter_.GetAsString(), ::testing::ContainsRegex( "Input array not provided for operation 'squeeze'")); } TEST_F(FlatbufferConversionsTest, ParseDynamicReshape) { const Operator* op = BuildTestOperator( BuiltinOptions_ReshapeOptions, CreateReshapeOptions(builder_).Union()); void* output_data = nullptr; EXPECT_EQ(kTfLiteOk, ParseOpData(op, BuiltinOperator_RESHAPE, &mock_reporter_, &mock_allocator_, &output_data)); } TEST_F(FlatbufferConversionsTest, TestParseOpDataConv) { const Operator* conv_op = BuildTestOperator(BuiltinOptions_Conv2DOptions, CreateConv2DOptions(builder_, Padding_SAME, 1, 2, ActivationFunctionType_RELU, 3, 4) .Union()); void* output_data = nullptr; EXPECT_EQ(kTfLiteOk, ParseOpData(conv_op, BuiltinOperator_CONV_2D, &mock_reporter_, &mock_allocator_, &output_data)); EXPECT_NE(nullptr, output_data); TfLiteConvParams* params = reinterpret_cast<TfLiteConvParams*>(output_data); EXPECT_EQ(kTfLitePaddingSame, params->padding); EXPECT_EQ(1, params->stride_width); EXPECT_EQ(2, params->stride_height); EXPECT_EQ(kTfLiteActRelu, params->activation); EXPECT_EQ(3, params->dilation_width_factor); EXPECT_EQ(4, params->dilation_height_factor); } TEST_F(FlatbufferConversionsTest, ParseBadFullyConnected) { const Operator* conv_op = BuildTestOperator( BuiltinOptions_FullyConnectedOptions, CreateFullyConnectedOptions( builder_, ActivationFunctionType_RELU, static_cast<FullyConnectedOptionsWeightsFormat>(-1), true) .Union()); void* output_data = nullptr; EXPECT_EQ(kTfLiteError, ParseOpData(conv_op, BuiltinOperator_FULLY_CONNECTED, &mock_reporter_, &mock_allocator_, &output_data)); } TEST_F(FlatbufferConversionsTest, TestParseOpDataCustom) { const Operator* custom_op = BuildTestOperator(BuiltinOptions_NONE, flatbuffers::Offset<void>()); void* output_data = nullptr; EXPECT_EQ(kTfLiteOk, ParseOpData(custom_op, BuiltinOperator_CUSTOM, &mock_reporter_, &mock_allocator_, &output_data)); EXPECT_EQ(nullptr, output_data); } TEST_F(FlatbufferConversionsTest, TestConvertTensorType) { TfLiteType type; EXPECT_EQ(kTfLiteOk, ConvertTensorType(TensorType_FLOAT32, &type, &mock_reporter_)); EXPECT_EQ(kTfLiteFloat32, type); } TEST_F(FlatbufferConversionsTest, TestConvertTensorTypeFloat16) { TfLiteType type; EXPECT_EQ(kTfLiteOk, ConvertTensorType(TensorType_FLOAT16, &type, &mock_reporter_)); EXPECT_EQ(kTfLiteFloat16, type); } } // namespace tflite int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
35.640719
80
0.710349
where-is-brett
24d7ef2cbedf3c0ca8bdb5bac2609f7477a868fc
13,032
cc
C++
ragel/flat.cc
podsvirov/colm-suite
9d45f0d47982d83141763a9728a4f97d6a06bacd
[ "MIT" ]
3
2018-08-18T16:37:49.000Z
2019-04-30T20:21:50.000Z
ragel/flat.cc
podsvirov/colm-suite
9d45f0d47982d83141763a9728a4f97d6a06bacd
[ "MIT" ]
null
null
null
ragel/flat.cc
podsvirov/colm-suite
9d45f0d47982d83141763a9728a4f97d6a06bacd
[ "MIT" ]
1
2017-08-31T05:45:14.000Z
2017-08-31T05:45:14.000Z
/* * Copyright 2004-2018 Adrian Thurston <thurston@colm.net> * * 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 "ragel.h" #include "flat.h" #include "redfsm.h" #include "gendata.h" void Flat::genAnalysis() { redFsm->sortByStateId(); /* Choose default transitions and the single transition. */ redFsm->chooseDefaultSpan(); /* Do flat expand. */ redFsm->makeFlatClass(); /* If any errors have occured in the input file then don't write anything. */ if ( red->id->errorCount > 0 ) return; /* Anlayze Machine will find the final action reference counts, among other * things. We will use these in reporting the usage of fsm directives in * action code. */ red->analyzeMachine(); setKeyType(); /* Run the analysis pass over the table data. */ setTableState( TableArray::AnalyzePass ); tableDataPass(); /* Switch the tables over to the code gen mode. */ setTableState( TableArray::GeneratePass ); } void Flat::tableDataPass() { if ( type == Flat::Loop ) { if ( redFsm->anyActions() ) taActions(); } taKeys(); taCharClass(); taFlatIndexOffset(); taIndicies(); taIndexDefaults(); taTransCondSpaces(); if ( red->condSpaceList.length() > 0 ) taTransOffsets(); taCondTargs(); taCondActions(); taToStateActions(); taFromStateActions(); taEofConds(); taEofActions(); taEofTrans(); taNfaTargs(); taNfaOffsets(); taNfaPushActions(); taNfaPopTrans(); } void Flat::writeData() { if ( type == Flat::Loop ) { /* If there are any transtion functions then output the array. If there * are none, don't bother emitting an empty array that won't be used. */ if ( redFsm->anyActions() ) taActions(); } taKeys(); taCharClass(); taFlatIndexOffset(); taIndicies(); taIndexDefaults(); taTransCondSpaces(); if ( red->condSpaceList.length() > 0 ) taTransOffsets(); taCondTargs(); taCondActions(); if ( redFsm->anyToStateActions() ) taToStateActions(); if ( redFsm->anyFromStateActions() ) taFromStateActions(); taEofConds(); if ( redFsm->anyEofActions() ) taEofActions(); if ( redFsm->anyEofTrans() ) taEofTrans(); taNfaTargs(); taNfaOffsets(); taNfaPushActions(); taNfaPopTrans(); STATE_IDS(); } void Flat::setKeyType() { transKeys.setType( ALPH_TYPE(), alphType->size, alphType->isChar ); transKeys.isSigned = keyOps->isSigned; } void Flat::setTableState( TableArray::State state ) { for ( ArrayVector::Iter i = arrayVector; i.lte(); i++ ) { TableArray *tableArray = *i; tableArray->setState( state ); } } void Flat::taFlatIndexOffset() { flatIndexOffset.start(); int curIndOffset = 0; for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { /* Write the index offset. */ flatIndexOffset.value( curIndOffset ); /* Move the index offset ahead. */ if ( st->transList != 0 ) curIndOffset += ( st->high - st->low + 1 ); } flatIndexOffset.finish(); } void Flat::taCharClass() { charClass.start(); if ( redFsm->classMap != 0 ) { long long maxSpan = keyOps->span( redFsm->lowKey, redFsm->highKey ); for ( long long pos = 0; pos < maxSpan; pos++ ) charClass.value( redFsm->classMap[pos] ); } charClass.finish(); } void Flat::taToStateActions() { toStateActions.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { /* Write any eof action. */ TO_STATE_ACTION(st); } toStateActions.finish(); } void Flat::taFromStateActions() { fromStateActions.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { /* Write any eof action. */ FROM_STATE_ACTION( st ); } fromStateActions.finish(); } void Flat::taEofActions() { eofActions.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { /* Write any eof action. */ EOF_ACTION( st ); } eofActions.finish(); } void Flat::taEofConds() { /* * EOF Cond Spaces */ eofCondSpaces.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->outCondSpace != 0 ) eofCondSpaces.value( st->outCondSpace->condSpaceId ); else eofCondSpaces.value( -1 ); } eofCondSpaces.finish(); /* * EOF Cond Key Indixes */ eofCondKeyOffs.start(); int curOffset = 0; for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { long off = 0; if ( st->outCondSpace != 0 ) { off = curOffset; curOffset += st->outCondKeys.length(); } eofCondKeyOffs.value( off ); } eofCondKeyOffs.finish(); /* * EOF Cond Key Lengths. */ eofCondKeyLens.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { long len = 0; if ( st->outCondSpace != 0 ) len = st->outCondKeys.length(); eofCondKeyLens.value( len ); } eofCondKeyLens.finish(); /* * EOF Cond Keys */ eofCondKeys.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->outCondSpace != 0 ) { for ( int c = 0; c < st->outCondKeys.length(); c++ ) { CondKey key = st->outCondKeys[c]; eofCondKeys.value( key.getVal() ); } } } eofCondKeys.finish(); } void Flat::taEofTrans() { /* Transitions must be written ordered by their id. */ RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()]; for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ ) transPtrs[trans->id] = trans; long *transPos = new long[redFsm->transSet.length()]; for ( int t = 0; t < redFsm->transSet.length(); t++ ) { /* Save the position. Needed for eofTargs. */ RedTransAp *trans = transPtrs[t]; transPos[trans->id] = t; } eofTrans.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { long trans = 0; if ( st->eofTrans != 0 ) trans = transPos[st->eofTrans->id] + 1; eofTrans.value( trans ); } eofTrans.finish(); delete[] transPtrs; delete[] transPos; } void Flat::taKeys() { transKeys.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->transList ) { /* Emit just low key and high key. */ transKeys.value( st->low ); transKeys.value( st->high ); } else { /* Emit an impossible range so the driver fails the lookup. */ transKeys.value( 1 ); transKeys.value( 0 ); } } transKeys.finish(); } void Flat::taIndicies() { indicies.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->transList != 0 ) { long long span = st->high - st->low + 1; for ( long long pos = 0; pos < span; pos++ ) indicies.value( st->transList[pos]->id ); } } indicies.finish(); } void Flat::taIndexDefaults() { indexDefaults.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { /* The state's default index goes next. */ if ( st->defTrans != 0 ) indexDefaults.value( st->defTrans->id ); else indexDefaults.value( 0 ); } indexDefaults.finish(); } void Flat::taTransCondSpaces() { transCondSpaces.start(); /* Transitions must be written ordered by their id. */ RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()]; for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ ) { transPtrs[trans->id] = trans; } /* Keep a count of the num of items in the array written. */ for ( int t = 0; t < redFsm->transSet.length(); t++ ) { /* Save the position. Needed for eofTargs. */ RedTransAp *trans = transPtrs[t]; if ( trans->condSpace != 0 ) transCondSpaces.value( trans->condSpace->condSpaceId ); else transCondSpaces.value( -1 ); } delete[] transPtrs; transCondSpaces.finish(); } void Flat::taTransOffsets() { transOffsets.start(); /* Transitions must be written ordered by their id. */ RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()]; for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ ) transPtrs[trans->id] = trans; /* Keep a count of the num of items in the array written. */ int curOffset = 0; for ( int t = 0; t < redFsm->transSet.length(); t++ ) { /* Save the position. Needed for eofTargs. */ RedTransAp *trans = transPtrs[t]; transOffsets.value( curOffset ); curOffset += trans->condFullSize(); } delete[] transPtrs; transOffsets.finish(); } void Flat::taCondTargs() { condTargs.start(); /* Transitions must be written ordered by their id. */ RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()]; for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ ) transPtrs[trans->id] = trans; /* Keep a count of the num of items in the array written. */ for ( int t = 0; t < redFsm->transSet.length(); t++ ) { /* Save the position. Needed for eofTargs. */ RedTransAp *trans = transPtrs[t]; long fullSize = trans->condFullSize(); RedCondPair **fullPairs = new RedCondPair*[fullSize]; for ( long k = 0; k < fullSize; k++ ) fullPairs[k] = trans->errCond(); for ( int c = 0; c < trans->numConds(); c++ ) fullPairs[trans->outCondKey( c ).getVal()] = trans->outCond( c ); for ( int k = 0; k < fullSize; k++ ) { RedCondPair *cond = fullPairs[k]; condTargs.value( cond->targ->id ); } delete[] fullPairs; } delete[] transPtrs; condTargs.finish(); } void Flat::taCondActions() { condActions.start(); /* Transitions must be written ordered by their id. */ RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()]; for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ ) transPtrs[trans->id] = trans; /* Keep a count of the num of items in the array written. */ for ( int t = 0; t < redFsm->transSet.length(); t++ ) { /* Save the position. Needed for eofTargs. */ RedTransAp *trans = transPtrs[t]; long fullSize = trans->condFullSize(); RedCondPair **fullPairs = new RedCondPair*[fullSize]; for ( long k = 0; k < fullSize; k++ ) fullPairs[k] = trans->errCond(); for ( int c = 0; c < trans->numConds(); c++ ) fullPairs[trans->outCondKey( c ).getVal()] = trans->outCond( c ); for ( int k = 0; k < fullSize; k++ ) { RedCondPair *cond = fullPairs[k]; COND_ACTION( cond ); } delete[] fullPairs; } delete[] transPtrs; condActions.finish(); } /* Write out the array of actions. */ void Flat::taActions() { actions.start(); /* Add in the the empty actions array. */ actions.value( 0 ); for ( GenActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) { /* Length first. */ actions.value( act->key.length() ); for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) actions.value( item->value->actionId ); } actions.finish(); } void Flat::taNfaTargs() { nfaTargs.start(); /* Offset of zero means no NFA targs, put a filler there. */ nfaTargs.value( 0 ); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->nfaTargs != 0 ) { nfaTargs.value( st->nfaTargs->length() ); for ( RedNfaTargs::Iter targ = *st->nfaTargs; targ.lte(); targ++ ) nfaTargs.value( targ->state->id ); } } nfaTargs.finish(); } /* These need to mirror nfa targs. */ void Flat::taNfaPushActions() { nfaPushActions.start(); nfaPushActions.value( 0 ); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->nfaTargs != 0 ) { nfaPushActions.value( 0 ); for ( RedNfaTargs::Iter targ = *st->nfaTargs; targ.lte(); targ++ ) NFA_PUSH_ACTION( targ ); } } nfaPushActions.finish(); } void Flat::taNfaPopTrans() { nfaPopTrans.start(); nfaPopTrans.value( 0 ); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->nfaTargs != 0 ) { nfaPopTrans.value( 0 ); for ( RedNfaTargs::Iter targ = *st->nfaTargs; targ.lte(); targ++ ) NFA_POP_TEST( targ ); } } nfaPopTrans.finish(); } void Flat::taNfaOffsets() { nfaOffsets.start(); /* Offset of zero means no NFA targs, real targs start at 1. */ long offset = 1; for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->nfaTargs == 0 ) { nfaOffsets.value( 0 ); } else { nfaOffsets.value( offset ); offset += 1 + st->nfaTargs->length(); } } nfaOffsets.finish(); }
22.585789
81
0.651473
podsvirov
24dd44fbc951d9b8039b54dedd592133ae1e0dfc
1,221
hpp
C++
src/libs/asn1/include/keto/asn1/TimeHelper.hpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:00.000Z
2020-03-04T10:38:00.000Z
src/libs/asn1/include/keto/asn1/TimeHelper.hpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
null
null
null
src/libs/asn1/include/keto/asn1/TimeHelper.hpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:01.000Z
2020-03-04T10:38:01.000Z
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: TimeHelper.hpp * Author: ubuntu * * Created on January 31, 2018, 8:12 AM */ #ifndef TIMEHELPER_HPP #define TIMEHELPER_HPP #include "UTCTime.h" #include <chrono> namespace keto { namespace asn1 { class TimeHelper { public: TimeHelper(); TimeHelper(const UTCTime_t& time); TimeHelper(const TimeHelper& orig) = default; virtual ~TimeHelper(); TimeHelper& operator =(const UTCTime_t& time); TimeHelper& operator =(const UTCTime_t* time); /** * The internal memory is assumed to be owned by the last person in the row * and thus must be freed by that code. * * @return A utc time copy. */ operator UTCTime_t() const; TimeHelper& operator =(const std::time_t& time); operator std::time_t() const; TimeHelper& operator =(const std::chrono::system_clock::time_point& time); operator std::chrono::system_clock::time_point() const; private: std::chrono::system_clock::time_point time_point; }; } } #endif /* TIMEHELPER_HPP */
22.611111
79
0.674857
burntjam
24e02d8b23ecbbcb76f21271ea3e5fea3b61e872
94
cc
C++
DataFormats/L1TMuon/src/EMTFDaqOut.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
DataFormats/L1TMuon/src/EMTFDaqOut.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
DataFormats/L1TMuon/src/EMTFDaqOut.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "DataFormats/L1TMuon/interface/EMTFDaqOut.h" namespace l1t {} // End namespace l1t
23.5
53
0.765957
ckamtsikis
24e7a91e3bd72cc1198516040aae5562d61e71e6
3,096
hpp
C++
include/more_concepts/base_concepts.hpp
MiSo1289/more_concepts
ee7949691e8d0024b818bc10f3157dcdeb4ed8af
[ "MIT" ]
45
2021-02-01T01:28:27.000Z
2022-03-29T23:48:46.000Z
include/more_concepts/base_concepts.hpp
MiSo1289/more_concepts
ee7949691e8d0024b818bc10f3157dcdeb4ed8af
[ "MIT" ]
1
2021-02-11T12:33:25.000Z
2021-02-11T16:33:05.000Z
include/more_concepts/base_concepts.hpp
MiSo1289/more_concepts
ee7949691e8d0024b818bc10f3157dcdeb4ed8af
[ "MIT" ]
3
2021-02-11T07:25:47.000Z
2021-08-15T16:55:11.000Z
#pragma once #include <concepts> #include <cstddef> #include <system_error> #include <type_traits> #include "more_concepts/detail/type_traits.hpp" namespace more_concepts { /// Types that are non-reference, non-c-array, non-function or function reference, /// non-const and non-volatile. /// /// Assigning an object of this type to an auto variable preserves the type. template <typename T> concept decayed = std::same_as<T, std::decay_t<T>>; /// Types that support aggregate initialization: /// https://en.cppreference.com/w/cpp/language/aggregate_initialization template <typename T> concept aggregate = std::is_aggregate_v<T>; /// Types which can be trivially constructed and destructed (as in without performing /// any (de)initialization at all), and can be trivially copied (as in copying is equivalent /// to calling memcpy). template <typename T> concept trivial = std::is_trivial_v<T>; /// Type is a scoped or unscoped enumeration (enum / enum class). template <typename T> concept enum_type = std::is_enum_v<T>; /// An enum type that represents an error, and can be used to construct a std::error_code /// object. template <typename T> concept error_code_enum = enum_type<T> and std::is_error_code_enum_v<T>; /// An enum type that represents an error, and can be used to construct a std::error_condition /// object. template <typename T> concept error_condition_enum = enum_type<T> and std::is_error_condition_enum_v<T>; /// Types that can be called with std::invoke using one or more function signatures. /// The return type of each signature is only checked for convertibility. template <typename Fn, typename... Signatures> concept invocable_as = requires(Signatures& ... signatures) { ([] <typename Ret, typename... Args>(auto(&)(Args...) -> Ret) requires std::is_invocable_r_v<Ret, Fn, Args> {}(signatures), ...); }; /// Types that can be called with the function call operator using one or more function /// signatures. The return type of each signature must match exactly. template <typename Fn, typename... Signatures> concept callable_as = requires(Signatures& ... signatures) { // Call operator checking is deferred to a type trait; // doing it inline breaks the compiler (GCC 10.2) ([] <typename Ret, typename... Args>(auto(&)(Args...) -> Ret) requires detail::is_callable_r_v<Ret, Fn, Args...> {}(signatures), ...); }; /// From https://en.cppreference.com/w/cpp/named_req/Hash: /// A Hash is a function object for which the output depends only on the input /// and has a very low probability of yielding the same output given different input values. /// /// Used to define the unordered_associative_container concept. template <typename Fn, typename KeyType> concept hash_function = callable_as< Fn const, auto(KeyType&) -> std::size_t, auto(KeyType const&) -> std::size_t>; }
38.7
98
0.674419
MiSo1289
24e811f79451435abe222df6e663d9e41fce8351
232
hpp
C++
book/cpp_templates/tmplbook/meta/pow3const.hpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
book/cpp_templates/tmplbook/meta/pow3const.hpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
book/cpp_templates/tmplbook/meta/pow3const.hpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
// primary template to compute 3 to the Nth template<int N> struct Pow3 { static int const value = 3 * Pow3<N-1>::value; }; // full specialization to end the recursion template<> struct Pow3<0> { static int const value = 1; };
19.333333
48
0.689655
houruixiang
00878d1828f82cbcc4f844db2ec01e3607c21e02
1,216
cpp
C++
plugins/mmstd_moldyn/src/io/MMSPDFrameData.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
2
2020-10-16T10:15:37.000Z
2021-01-21T13:06:00.000Z
plugins/mmstd_moldyn/src/io/MMSPDFrameData.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
null
null
null
plugins/mmstd_moldyn/src/io/MMSPDFrameData.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
1
2021-01-28T01:19:54.000Z
2021-01-28T01:19:54.000Z
/* * MMSPDFrameData.cpp * * Copyright (C) 2011 by VISUS (Universitaet Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "io/MMSPDFrameData.h" using namespace megamol::stdplugin::moldyn::io; /****************************************************************************/ /* * MMSPDFrameData::Particles::Particles */ MMSPDFrameData::Particles::Particles(void) : count(0), data(), fieldMap(NULL) { // Intentionally empty } /* * MMSPDFrameData::Particles::~Particles */ MMSPDFrameData::Particles::~Particles(void) { delete[] this->fieldMap; this->fieldMap = NULL; } /* * MMSPDFrameData::Particles::operator== */ bool MMSPDFrameData::Particles::operator==(const MMSPDFrameData::Particles& rhs) { return (this->count == rhs.count) && (&this->data == &rhs.data) // sufficient && (this->fieldMap == rhs.fieldMap); // sufficient } /****************************************************************************/ /* * MMSPDFrameData::MMSPDFrameData */ MMSPDFrameData::MMSPDFrameData(void) : data(), idxRec() { // Intentionally empty } /* * MMSPDFrameData::~MMSPDFrameData */ MMSPDFrameData::~MMSPDFrameData(void) { // Intentionally empty }
20.610169
82
0.583882
azuki-monster
008a4345df697e2ff35f98f5123b8a3f56d9f7f2
417
hpp
C++
include/netuit/assign/AssignAvailableProcs.hpp
mmore500/pipe-profile
861babd819909d1bda5e933269e7bc64018272d6
[ "MIT" ]
15
2020-07-31T23:06:09.000Z
2022-01-13T18:05:33.000Z
include/netuit/assign/AssignAvailableProcs.hpp
mmore500/pipe-profile
861babd819909d1bda5e933269e7bc64018272d6
[ "MIT" ]
137
2020-08-13T23:32:17.000Z
2021-10-16T04:00:40.000Z
include/netuit/assign/AssignAvailableProcs.hpp
mmore500/pipe-profile
861babd819909d1bda5e933269e7bc64018272d6
[ "MIT" ]
3
2020-08-09T01:52:03.000Z
2020-10-02T02:13:47.000Z
#pragma once #ifndef NETUIT_ASSIGN_ASSIGNAVAILABLEPROCS_HPP_INCLUDE #define NETUIT_ASSIGN_ASSIGNAVAILABLEPROCS_HPP_INCLUDE #include "../../uitsl/mpi/mpi_init_utils.hpp" namespace netuit { struct AssignAvailableProcs { uitsl::proc_id_t operator()(const size_t & node_id) { return node_id % uitsl::get_nprocs(); } }; } // namespace netuit #endif // #ifndef NETUIT_ASSIGN_ASSIGNAVAILABLEPROCS_HPP_INCLUDE
20.85
64
0.784173
mmore500
008a4c950ad08521c91437bc9c7c9915522d39f9
5,090
cpp
C++
src/Parsers.cpp
markwinter/tmxjson
926a6effcf0f0fc2a4ff0350d0c33b843e827d4b
[ "MIT" ]
1
2018-06-23T06:42:44.000Z
2018-06-23T06:42:44.000Z
src/Parsers.cpp
markwinter/tmxjson
926a6effcf0f0fc2a4ff0350d0c33b843e827d4b
[ "MIT" ]
null
null
null
src/Parsers.cpp
markwinter/tmxjson
926a6effcf0f0fc2a4ff0350d0c33b843e827d4b
[ "MIT" ]
null
null
null
/* MIT License. Copyright Mark Winter */ #include <string> #include <iostream> #include "thirdparty/base64.hpp" #include "Utils.hpp" #include "Parsers.hpp" #include "TypedProperty.hpp" namespace tmxjson { void from_json(const json& object_json, Object& object) { object.SetId(object_json["id"]); if (check_json_var(object_json, "gid")) object.SetGid(object_json["gid"]); object.SetObjectType(ObjectType::kRectangle); if (check_json_var(object_json, "ellipse")) object.SetObjectType(ObjectType::kEllipse); if (check_json_var(object_json, "point")) object.SetObjectType(ObjectType::kPoint); if (check_json_var(object_json, "polygon")) { object.SetObjectType(ObjectType::kPolygon); std::vector<std::pair<float, float>> data; for (auto& pair : object_json["polygon"]) data.emplace_back(pair["x"], pair["y"]); object.SetDataPoints(data); } if (check_json_var(object_json, "polyline")) { object.SetObjectType(ObjectType::kPolyline); std::vector<std::pair<float, float>> data; for (auto& pair : object_json["polyline"]) data.emplace_back(pair["x"], pair["y"]); object.SetDataPoints(data); } if (check_json_var(object_json, "text")) { object.SetObjectType(ObjectType::kText); object.SetTextObject(object_json["text"]["text"], object_json["text"]["wrap"]); } if (check_json_var(object_json, "properties")) parse_properties(object.GetProperties(), object_json["properties"]); object.SetName(object_json["name"]); object.SetType(object_json["type"]); object.SetRotation(object_json["rotation"]); object.SetVisible(object_json["visible"]); object.SetX(object_json["x"]); object.SetY(object_json["y"]); object.SetHeight(object_json["height"]); object.SetWidth(object_json["width"]); } void from_json(const json& layer_json, Layer& layer) { layer.SetType(layer_json["type"].get<std::string>()); if (layer.GetType() == LayerType::kGroup) { layer.SetLayers(layer_json["layers"]); } else if (layer.GetType() == LayerType::kTileLayer) { layer.SetHeight(layer_json["height"]); layer.SetWidth(layer_json["width"]); try { std::string raw_data = layer_json["data"]; if (layer_json.at("encoding") == "base64") raw_data = base64_decode(raw_data); std::vector<unsigned char> uncompressed_data; if (check_json_var(layer_json, "compression")) zlib_inflate(raw_data.c_str(), raw_data.length() * sizeof(unsigned char), uncompressed_data, raw_data.length() * 5); else uncompressed_data.insert(uncompressed_data.end(), raw_data.begin(), raw_data.end()); layer.SetData(parse_tile_data(uncompressed_data)); } catch (json::out_of_range& e) { // If no 'encoding' key then data is just plain int array layer.SetData(parse_tile_data(layer_json["data"])); } } else if (layer.GetType() == LayerType::kObjectGroup) { layer.SetObjects(layer_json["objects"]); if (layer_json["draworder"] == "topdown") layer.SetDrawOrder(DrawOrder::kTopDown); else if (layer_json["draworder"] == "index") layer.SetDrawOrder(DrawOrder::kIndex); } else if (layer.GetType() == LayerType::kImageLayer) { layer.SetImage(layer_json["image"]); } // All layers can optionally have offsets. Only appear in json if they are non-0 if (check_json_var(layer_json, "offsetx")) layer.SetOffsetX(layer_json["offsetx"]); if (check_json_var(layer_json, "offsety")) layer.SetOffsetY(layer_json["offsety"]); if (check_json_var(layer_json, "properties")) parse_properties(layer.GetProperties(), layer_json["properties"]); layer.SetX(layer_json["x"]); layer.SetY(layer_json["y"]); layer.SetName(layer_json["name"]); layer.SetOpacity(layer_json["opacity"]); layer.SetVisible(layer_json["visible"]); } void from_json(const json& tileset_json, TileSet& tileset) { tileset.SetColumns(tileset_json["columns"]); tileset.SetFirstGid(tileset_json["firstgid"]); tileset.SetName(tileset_json["name"]); tileset.SetType(TileSetType::kTileSet); tileset.SetImage(tileset_json["image"]); tileset.SetImageWidth(tileset_json["imagewidth"]); tileset.SetImageHeight(tileset_json["imageheight"]); tileset.SetTileCount(tileset_json["tilecount"]); tileset.SetTileHeight(tileset_json["tileheight"]); tileset.SetTileWidth(tileset_json["tilewidth"]); tileset.SetSpacing(tileset_json["spacing"]); tileset.SetMargin(tileset_json["margin"]); if (check_json_var(tileset_json, "tileoffset")) tileset.SetOffset(tileset_json["tileoffset"]["x"], tileset_json["tileoffset"]["y"]); if (check_json_var(tileset_json, "grid")) { GridOrientation grid_orientation = GridOrientation::kOrthogonal; if (tileset_json["grid"]["orientation"] == "isometric") grid_orientation = GridOrientation::kIsometric; tileset.SetGrid(grid_orientation, tileset_json["grid"]["width"], tileset_json["grid"]["height"]); } if (check_json_var(tileset_json, "properties")) parse_properties(tileset.GetProperties(), tileset_json["properties"]); } } // namespace tmxjson
34.161074
124
0.70609
markwinter
008c68739342faedec38079069043a21980ac6c4
527
hpp
C++
src/font.hpp
ceilors/fb-tetris
5496898443e35e37e374de2e97505a6027d38c30
[ "BSD-3-Clause" ]
null
null
null
src/font.hpp
ceilors/fb-tetris
5496898443e35e37e374de2e97505a6027d38c30
[ "BSD-3-Clause" ]
null
null
null
src/font.hpp
ceilors/fb-tetris
5496898443e35e37e374de2e97505a6027d38c30
[ "BSD-3-Clause" ]
null
null
null
#ifndef __FONT_HPP__ #define __FONT_HPP__ #include <sstream> #include <cstdint> #include <ft2build.h> #include FT_FREETYPE_H #include "framebuffer.hpp" #include "structs.hpp" class Font { FT_Library library; FT_Face face; FT_GlyphSlot slot; const uint16_t font_dpi = 100; uint16_t font_size = 0; public: Font(const char * filename, uint16_t size); ~Font(); void render(FrameBuffer & fb, Point pos, const char * text); void render(FrameBuffer & fb, Point pos, uint32_t value); }; #endif
19.518519
64
0.70019
ceilors
008c7403ea5ba46d564973fae113c0166ba45d05
1,103
cpp
C++
xpcc/examples/lpc2368/display/hd44780/main.cpp
jrahlf/3D-Non-Contact-Laser-Profilometer
912eb8890442f897c951594c79a8a594096bc119
[ "MIT" ]
5
2016-02-06T14:57:35.000Z
2018-01-02T23:34:18.000Z
xpcc/examples/lpc2368/display/hd44780/main.cpp
jrahlf/3D-Non-Contact-Laser-Profilometer
912eb8890442f897c951594c79a8a594096bc119
[ "MIT" ]
null
null
null
xpcc/examples/lpc2368/display/hd44780/main.cpp
jrahlf/3D-Non-Contact-Laser-Profilometer
912eb8890442f897c951594c79a8a594096bc119
[ "MIT" ]
1
2020-04-19T13:16:31.000Z
2020-04-19T13:16:31.000Z
/** * Test for LPC2368 processor on * Development board * "CP-JR ARM7 LPC2368" * from www.etteam.com * * A HD44780 compatible display should be connected to the ET-CLCD connector. * * Status as of 2012-06-10: works in hardware. * */ #include <xpcc/architecture.hpp> #include <xpcc/driver/ui/display.hpp> // define the pins used by the LCD namespace lcd { GPIO__OUTPUT(E, 1, 31); GPIO__OUTPUT(Rw, 1, 29); GPIO__OUTPUT(Rs, 1, 28); GPIO__IO(D4, 1, 24); GPIO__IO(D5, 1, 25); GPIO__IO(D6, 1, 26); GPIO__IO(D7, 1, 27); typedef xpcc::gpio::Nibble<D7, D6, D5, D4> Data; } // create an LCD object xpcc::Hd44780< lcd::E, lcd::Rw, lcd::Rs, lcd::Data > display(20, 4); int main(void) { xpcc::lpc::Clock::initialize(); display.initialize(); display.setCursor(0, 0); // write the standard welcome message ;-) display << "Hello World!\n"; uint8_t counter = 0; while (1) { // Go to the beginning of the second line of the display and // write the value of 'counter' display.setCursor(0, 1); display << counter << " "; counter++; xpcc::delay_ms(200); } return 0; }
18.383333
77
0.651859
jrahlf
0092de019f5e7bd61c3475801f384247613a6b7a
421
cpp
C++
books/C++_Prime_Plus/Chapter6/or.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
5
2019-09-17T09:12:15.000Z
2021-05-29T10:54:39.000Z
books/C++_Prime_Plus/Chapter6/or.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
null
null
null
books/C++_Prime_Plus/Chapter6/or.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
2
2021-07-26T06:36:12.000Z
2022-01-23T15:20:30.000Z
#include"iostream" using namespace std; int main() { cout<<"This program may reformat your hard disk\n" "and destroy all your data\n" "Do you wish to continue?<y/n> "; char ch; cin>>ch; if(ch=='y'||ch=='Y') cout<<"You were warned!\a\a\a\n"; else if(ch=='n'||ch=='N') cout<<"A wise choice... bye\n"; else cout<<"That wasn't a y or an n. so I guess I'll" "trash your disk anyway.\a\a\a\n"; return 0; }
22.157895
51
0.610451
liangjisheng
009a69572ae19d08e1621db09756870bd9d81657
2,617
cpp
C++
source/models.cpp
KJ002/Tetris
bf02931628c7b7bd78b4aa46fefca4d219786a65
[ "MIT" ]
null
null
null
source/models.cpp
KJ002/Tetris
bf02931628c7b7bd78b4aa46fefca4d219786a65
[ "MIT" ]
null
null
null
source/models.cpp
KJ002/Tetris
bf02931628c7b7bd78b4aa46fefca4d219786a65
[ "MIT" ]
null
null
null
#include "models.hpp" #include <array> #include <raylib.h> TetrisMeta::TetrisMeta(int x, int y, int shape){ shape = shape % 7; origin = (Vec2){(float)x, (float)y}; if (!shape){ map = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, }; rotationalOrigin = (Vec2){2.5, 1.5}; colour = BLUE; } if (shape == 1){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, }; rotationalOrigin = (Vec2){1, 1}; colour = DARKBLUE; } if (shape == 2){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, }; rotationalOrigin = (Vec2){1, 1}; colour = GOLD; } if (shape == 3){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, }; rotationalOrigin = (Vec2){1.5, 1.5}; colour = YELLOW; } if (shape == 4){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, }; rotationalOrigin = (Vec2){1, 1}; colour = LIME; } if (shape == 5){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, }; rotationalOrigin = (Vec2){1, 1}; colour = MAGENTA; } if (shape == 6){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, }; rotationalOrigin = (Vec2){1, 1}; colour = RED; } } TetrisMeta::TetrisMeta(){ TetrisMeta(0, 0, 0); } int TetrisMeta::getX() const{ return origin.x; } int TetrisMeta::getY() const{ return origin.y; } Vec2 TetrisMeta::get() const{ return origin; } Rectangle TetrisMeta::getRec() const{ return (Rectangle){origin.x, origin.y, 10., 10.}; } void TetrisMeta::setX(const int x){ origin.x = (float)x; } void TetrisMeta::setY(const int y){ origin.y = (float)y; } void TetrisMeta::setX(const float x){ origin.x = x; } void TetrisMeta::setY(const float y){ origin.y = y; } void TetrisMeta::set(const Vec2 v){ origin = v; } int TetrisMeta::appendX(const int x){ origin.x += x; return origin.x; } int TetrisMeta::appendY(const int y){ origin.y += y; return origin.y; } float TetrisMeta::appendX(const float x){ origin.x += x; return origin.x; } float TetrisMeta::appendY(const float y){ origin.y += y; return origin.y; } Vec2 TetrisMeta::append(const Vec2 v){ origin = origin + v; return origin; }
15.485207
51
0.477264
KJ002
009e8864b6f1ccab1f2eca3b93d2aae451b25ed1
2,863
cc
C++
chromium/content/browser/background_sync/background_sync_context_impl.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/content/browser/background_sync/background_sync_context_impl.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/content/browser/background_sync/background_sync_context_impl.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/background_sync/background_sync_context_impl.h" #include <utility> #include "base/bind.h" #include "base/stl_util.h" #include "content/browser/background_sync/background_sync_manager.h" #include "content/browser/background_sync/background_sync_service_impl.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/public/browser/browser_thread.h" namespace content { BackgroundSyncContextImpl::BackgroundSyncContextImpl() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } BackgroundSyncContextImpl::~BackgroundSyncContextImpl() { DCHECK(!background_sync_manager_); DCHECK(services_.empty()); } void BackgroundSyncContextImpl::Init( const scoped_refptr<ServiceWorkerContextWrapper>& context) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&BackgroundSyncContextImpl::CreateBackgroundSyncManager, this, context)); } void BackgroundSyncContextImpl::Shutdown() { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&BackgroundSyncContextImpl::ShutdownOnIO, this)); } void BackgroundSyncContextImpl::CreateService( mojo::InterfaceRequest<BackgroundSyncService> request) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&BackgroundSyncContextImpl::CreateServiceOnIOThread, this, base::Passed(&request))); } void BackgroundSyncContextImpl::ServiceHadConnectionError( BackgroundSyncServiceImpl* service) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(ContainsValue(services_, service)); services_.erase(service); delete service; } BackgroundSyncManager* BackgroundSyncContextImpl::background_sync_manager() const { DCHECK_CURRENTLY_ON(BrowserThread::IO); return background_sync_manager_.get(); } void BackgroundSyncContextImpl::CreateBackgroundSyncManager( const scoped_refptr<ServiceWorkerContextWrapper>& context) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!background_sync_manager_); background_sync_manager_ = BackgroundSyncManager::Create(context); } void BackgroundSyncContextImpl::CreateServiceOnIOThread( mojo::InterfaceRequest<BackgroundSyncService> request) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(background_sync_manager_); services_.insert(new BackgroundSyncServiceImpl(this, std::move(request))); } void BackgroundSyncContextImpl::ShutdownOnIO() { DCHECK_CURRENTLY_ON(BrowserThread::IO); STLDeleteElements(&services_); background_sync_manager_.reset(); } } // namespace content
30.457447
79
0.785889
wedataintelligence
009fe56b1bf529a6710d1c8311e3e9668e6662b1
2,197
cpp
C++
samples/CoreAPI_SpriteRendering/SpriteRendering.cpp
odayibasi/swengine
ef07b7c9125d01596837a423a9f3dcbced1f5aa7
[ "Zlib", "MIT" ]
3
2021-03-01T20:41:13.000Z
2021-07-10T13:45:47.000Z
samples/CoreAPI_SpriteRendering/SpriteRendering.cpp
odayibasi/swengine
ef07b7c9125d01596837a423a9f3dcbced1f5aa7
[ "Zlib", "MIT" ]
null
null
null
samples/CoreAPI_SpriteRendering/SpriteRendering.cpp
odayibasi/swengine
ef07b7c9125d01596837a423a9f3dcbced1f5aa7
[ "Zlib", "MIT" ]
null
null
null
#include "../../include/SWEngine.h" #pragma comment (lib,"../../lib/SWUtil.lib") #pragma comment (lib,"../../lib/SWTypes.lib") #pragma comment (lib,"../../lib/SWCore.lib") #pragma comment (lib,"../../lib/SWGame.lib") #pragma comment (lib,"../../lib/SWGui.lib") #pragma comment (lib,"../../lib/SWEngine.lib") swApplication spriteRenderingApp; int spriteID; int spriteID2; int animatorID=-1; int animatorID2=-1; //Img1 Setting swRect target1={200,200,125,150}; swRect target2={400,200,125,150}; //------------------------------------------------------------------------------------------- void GameLoop(){ swGraphicsBeginScene(); //Background swGraphicsSetBgColor0(0.0f,0.0f,0.6f); //BlendingMode swGraphicsSetBlendingMode(SW_BLENDING_MODE_SOLID); //Draw Image int index=swAnimatorGetIndex(animatorID); swGraphicsSetColor0(1,1,1,1); swGraphicsRenderSprite0(spriteID,index,&target1); index=swAnimatorGetIndex(animatorID2); swGraphicsSetColor0(1,1,1,1); swGraphicsRenderSprite0(spriteID2,index,&target2); swGraphicsEndScene(); } //------------------------------------------------------------------------------------------- int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd) { //Application Settings spriteRenderingApp.hInstance=hInstance; spriteRenderingApp.fullScreen=false; spriteRenderingApp.cursor=true; spriteRenderingApp.width=800; spriteRenderingApp.height=600; spriteRenderingApp.title="Sprite Rendering"; spriteRenderingApp.path="\\rsc\\SprRendering\\"; spriteRenderingApp.appRun=GameLoop; //Application Execution swEngineInit(&spriteRenderingApp); //Init My Application //spriteID=swGraphicsCreateSprite("XenRunning\\"); spriteID=swGraphicsCreateSprite("Smurfs\\"); animatorID=swAnimatorCreate(swGraphicsGetCountOfImgInSprite(spriteID),0.1); swAnimatorSetExecutionMode(animatorID, SW_ANIMATOR_EXEC_FORWARD_LOOP); spriteID2=swGraphicsCreateSprite("XenRunning\\"); animatorID2=swAnimatorCreate(swGraphicsGetCountOfImgInSprite(spriteID2),0.1); swAnimatorSetExecutionMode(animatorID2, SW_ANIMATOR_EXEC_FORWARD_LOOP); swEngineRun(); swEngineExit(); return 0; }
24.142857
93
0.699135
odayibasi
00a03f1b75847a8934df7a07051cddbc3a8427e8
7,303
hpp
C++
libraries/app/include/graphene/app/api_objects.hpp
dls-cipher/bitshares-core
feba0cf93f0e442ef5e39f58b469112033cd74d8
[ "MIT" ]
null
null
null
libraries/app/include/graphene/app/api_objects.hpp
dls-cipher/bitshares-core
feba0cf93f0e442ef5e39f58b469112033cd74d8
[ "MIT" ]
null
null
null
libraries/app/include/graphene/app/api_objects.hpp
dls-cipher/bitshares-core
feba0cf93f0e442ef5e39f58b469112033cd74d8
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/chain/account_object.hpp> #include <graphene/chain/asset_object.hpp> #include <graphene/chain/vesting_balance_object.hpp> #include <graphene/chain/market_object.hpp> #include <graphene/chain/proposal_object.hpp> #include <graphene/chain/withdraw_permission_object.hpp> #include <graphene/chain/htlc_object.hpp> #include <graphene/api_helper_indexes/api_helper_indexes.hpp> #include <graphene/market_history/market_history_plugin.hpp> #include <fc/optional.hpp> namespace graphene { namespace app { using namespace graphene::chain; using namespace graphene::market_history; struct more_data { bool balances = false; bool vesting_balances = false; bool limit_orders = false; bool call_orders = false; bool settle_orders = false; bool proposals = false; bool assets = false; bool withdraws_from = false; bool withdraws_to = false; bool htlcs_from = false; bool htlcs_to = false; }; struct full_account { account_object account; account_statistics_object statistics; string registrar_name; string referrer_name; string lifetime_referrer_name; vector<variant> votes; optional<vesting_balance_object> cashback_balance; vector<account_balance_object> balances; vector<vesting_balance_object> vesting_balances; vector<limit_order_object> limit_orders; vector<call_order_object> call_orders; vector<force_settlement_object> settle_orders; vector<proposal_object> proposals; vector<asset_id_type> assets; vector<withdraw_permission_object> withdraws_from; vector<withdraw_permission_object> withdraws_to; vector<htlc_object> htlcs_from; vector<htlc_object> htlcs_to; more_data more_data_available; }; struct order { string price; string quote; string base; }; struct order_book { string base; string quote; vector< order > bids; vector< order > asks; }; struct market_ticker { time_point_sec time; string base; string quote; string latest; string lowest_ask; string lowest_ask_base_size; string lowest_ask_quote_size; string highest_bid; string highest_bid_base_size; string highest_bid_quote_size; string percent_change; string base_volume; string quote_volume; optional<object_id_type> mto_id; market_ticker() {} market_ticker(const market_ticker_object& mto, const fc::time_point_sec& now, const asset_object& asset_base, const asset_object& asset_quote, const order_book& orders); market_ticker(const fc::time_point_sec& now, const asset_object& asset_base, const asset_object& asset_quote); }; struct market_volume { time_point_sec time; string base; string quote; string base_volume; string quote_volume; }; struct market_trade { int64_t sequence = 0; fc::time_point_sec date; string price; string amount; string value; string type; account_id_type side1_account_id = GRAPHENE_NULL_ACCOUNT; account_id_type side2_account_id = GRAPHENE_NULL_ACCOUNT; }; struct extended_asset_object : asset_object { extended_asset_object() {} explicit extended_asset_object( const asset_object& a ) : asset_object( a ) {} explicit extended_asset_object( asset_object&& a ) : asset_object( std::move(a) ) {} optional<share_type> total_in_collateral; optional<share_type> total_backing_collateral; }; } } FC_REFLECT( graphene::app::more_data, (balances) (vesting_balances) (limit_orders) (call_orders) (settle_orders) (proposals) (assets) (withdraws_from) (withdraws_to) (htlcs_from) (htlcs_to) ) FC_REFLECT( graphene::app::full_account, (account) (statistics) (registrar_name) (referrer_name) (lifetime_referrer_name) (votes) (cashback_balance) (balances) (vesting_balances) (limit_orders) (call_orders) (settle_orders) (proposals) (assets) (withdraws_from) (withdraws_to) (htlcs_from) (htlcs_to) (more_data_available) ) FC_REFLECT( graphene::app::order, (price)(quote)(base) ); FC_REFLECT( graphene::app::order_book, (base)(quote)(bids)(asks) ); FC_REFLECT( graphene::app::market_ticker, (time)(base)(quote)(latest)(lowest_ask)(lowest_ask_base_size)(lowest_ask_quote_size) (highest_bid)(highest_bid_base_size)(highest_bid_quote_size)(percent_change)(base_volume)(quote_volume)(mto_id) ); FC_REFLECT( graphene::app::market_volume, (time)(base)(quote)(base_volume)(quote_volume) ); FC_REFLECT( graphene::app::market_trade, (sequence)(date)(price)(amount)(value)(type) (side1_account_id)(side2_account_id)); FC_REFLECT_DERIVED( graphene::app::extended_asset_object, (graphene::chain::asset_object), (total_in_collateral)(total_backing_collateral) );
37.071066
126
0.606189
dls-cipher
00a13c40be88a9e7bc31cc03d6355162f9d7a23e
3,175
cpp
C++
src/base/tkernel_utils.cpp
Unionfab/mayo
881b81b2b6febe6fb88967e4eef6ef22882e1734
[ "BSD-2-Clause" ]
382
2018-02-24T23:46:02.000Z
2022-03-31T16:08:24.000Z
src/base/tkernel_utils.cpp
Unionfab/mayo
881b81b2b6febe6fb88967e4eef6ef22882e1734
[ "BSD-2-Clause" ]
102
2017-05-18T09:36:26.000Z
2022-03-24T15:24:28.000Z
src/base/tkernel_utils.cpp
Unionfab/mayo
881b81b2b6febe6fb88967e4eef6ef22882e1734
[ "BSD-2-Clause" ]
124
2017-10-22T23:40:13.000Z
2022-03-28T08:57:23.000Z
/**************************************************************************** ** Copyright (c) 2021, Fougue Ltd. <http://www.fougue.pro> ** All rights reserved. ** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt ****************************************************************************/ #include "tkernel_utils.h" #include <Message_ProgressIndicator.hxx> #include <cmath> namespace Mayo { TKernelUtils::ReturnType_StartProgressIndicator TKernelUtils::start(const opencascade::handle<Message_ProgressIndicator>& progress) { #if OCC_VERSION_HEX >= OCC_VERSION_CHECK(7, 5, 0) return Message_ProgressIndicator::Start(progress); #else return progress; #endif } std::string TKernelUtils::colorToHex(const Quantity_Color& color) { //#if OCC_VERSION_HEX >= 0x070400 // constexpr bool hashPrefix = true; // return to_QString(Quantity_Color::ColorToHex(this->value(), hashPrefix)); //#endif // Converts a decimal digit to hexadecimal character auto fnHexDigit = [](uint8_t v) { if (v < 10) return '0' + v; else return 'A' + (v - 10); }; // Adds to 'str' the hexadecimal representation of 'v' belonging to [0, 255] auto fnAddHexColorComponent = [&](std::string& str, double v) { double iv = 0.; // Integral part of 'v' const double fv = std::modf(v / 16., &iv); // Fractional part of 'v' const auto a1 = uint8_t(iv); const auto a0 = uint8_t(fv * 16); str += fnHexDigit(a1); str += fnHexDigit(a0); }; std::string strHex; strHex += '#'; fnAddHexColorComponent(strHex, color.Red() * 255); fnAddHexColorComponent(strHex, color.Green() * 255); fnAddHexColorComponent(strHex, color.Blue() * 255); return strHex; } bool TKernelUtils::colorFromHex(std::string_view strHex, Quantity_Color* color) { //#if OCC_VERSION_HEX >= 0x070400 // Quantity_Color color; // return Quantity_Color::ColorFromHex(strHexHex.c_str(), color); //#else if (!color) return true; if (strHex.empty()) return false; if (strHex.at(0) != '#') return false; if (strHex.size() != 7) return false; // Converts an hexadecimal digit to decimal digit auto fnFromHex = [](char c) { if (c >= '0' && c <= '9') return int(c - '0'); else if (c >= 'A' && c <= 'F') return int(c - 'A' + 10); else if (c >= 'a' && c <= 'f') return int(c - 'a' + 10); else return -1; }; // Decodes a string containing an hexadecimal number to a decimal number auto fnHex2Int = [&](std::string_view str) { int result = 0; for (char c : str) { result = result * 16; const int h = fnFromHex(c); if (h < 0) return -1; result += h; } return result; }; const int r = fnHex2Int(strHex.substr(1, 2)); const int g = fnHex2Int(strHex.substr(3, 2)); const int b = fnHex2Int(strHex.substr(5, 2)); color->SetValues(r / 255., g / 255., b / 255., Quantity_TOC_RGB); return true; } } // namespace Mayo
28.603604
83
0.562835
Unionfab
00a2800fbe8a64fd882eba54a45718b91645985b
827
cpp
C++
Smooth_Game/Source/Component.cpp
Glitch0011/DirectX11-Demo
02b2ff51f4c936696ab25fb34da77cb4997980a9
[ "MIT" ]
null
null
null
Smooth_Game/Source/Component.cpp
Glitch0011/DirectX11-Demo
02b2ff51f4c936696ab25fb34da77cb4997980a9
[ "MIT" ]
null
null
null
Smooth_Game/Source/Component.cpp
Glitch0011/DirectX11-Demo
02b2ff51f4c936696ab25fb34da77cb4997980a9
[ "MIT" ]
null
null
null
#include <Component.h> #include <GameObject.h> using namespace std; using namespace SmoothGame; HRESULT Component::Send(MessageName name, Params param) { return this->GameObject->Send(name, param); } HRESULT Component::RecieveMessage(MessageName functionName, Params parameters) { if (this->functions.size() > 0) { for (auto functionDeclaration : this->functions) { if (functionDeclaration.first == functionName) { return functionDeclaration.second(parameters); } } } return E_NOTIMPL; } HRESULT Component::DelayedSend(MessageName funtionName, Params parameters) { return this->GameObject->DelayedSend(funtionName, parameters); } HRESULT Component::SendAsync(MessageName name, Params param, function<void(HRESULT, Params)> callback) { return this->GameObject->SendAsync(name, param, callback); }
22.972222
102
0.754534
Glitch0011
00a4b6e7228139c55153d0688a42e282e3a86328
1,641
cpp
C++
Source/CoreExtensions/Private/Math/Triangle2D.cpp
TheEmidee/UECoreExtensions
3068a8655509b7ff3d8f3e2fedf345618fdb37a2
[ "MIT" ]
2
2021-08-13T17:45:45.000Z
2021-10-06T14:42:52.000Z
Source/CoreExtensions/Private/Math/Triangle2D.cpp
TheEmidee/UE4CoreExtensions
e904c600d125d2fff737f8e54ea93145c964484d
[ "MIT" ]
1
2022-03-04T13:20:29.000Z
2022-03-04T13:20:29.000Z
Source/CoreExtensions/Private/Math/Triangle2D.cpp
TheEmidee/UECoreExtensions
3068a8655509b7ff3d8f3e2fedf345618fdb37a2
[ "MIT" ]
null
null
null
#include "Math/Triangle2D.h" FTriangle2D::FTriangle2D( const FVector2D & v1, const FVector2D & v2, const FVector2D & v3 ) : PointA( v1 ), PointB( v2 ), PointC( v3 ) {} bool FTriangle2D::ContainsVertex( const FVector2D & v ) const { return PointA.Equals( v ) || PointB.Equals( v ) || PointC.Equals( v ); } // From: https://githuPointB.com/Bl4ckb0ne/delaunay-triangulation bool FTriangle2D::CircumCircleContains( const FVector2D & v ) const { const auto ab = PointA.SizeSquared(); const auto cd = PointB.SizeSquared(); const auto ef = PointC.SizeSquared(); const auto ax = PointA.X; const auto ay = PointA.Y; const auto bx = PointB.X; const auto by = PointB.Y; const auto cx = PointC.X; const auto cy = PointC.Y; const auto circum_x = ( ab * ( cy - by ) + cd * ( ay - cy ) + ef * ( by - ay ) ) / ( ax * ( cy - by ) + bx * ( ay - cy ) + cx * ( by - ay ) ); const auto circum_y = ( ab * ( cx - bx ) + cd * ( ax - cx ) + ef * ( bx - ax ) ) / ( ay * ( cx - bx ) + by * ( ax - cx ) + cy * ( bx - ax ) ); const FVector2D circum( 0.5f * circum_x, 0.5f * circum_y ); const auto circum_radius = FVector2D::DistSquared( PointA, circum ); const auto dist = FVector2D::DistSquared( v, circum ); return dist <= circum_radius; } bool FTriangle2D::operator==( const FTriangle2D & t ) const { return ( PointA == t.PointA || PointA == t.PointB || PointA == t.PointC ) && ( PointB == t.PointA || PointB == t.PointB || PointB == t.PointC ) && ( PointC == t.PointA || PointC == t.PointB || PointC == t.PointC ); }
39.071429
147
0.57465
TheEmidee
00a4f998bf537d09a9fa7d120e7b6d1ff70c23c6
2,635
hpp
C++
lib/util/bitmask.hpp
sparkml/mastermind-strategy
22763672c413c6a73e2c036a9f522b65a0025b68
[ "MIT" ]
null
null
null
lib/util/bitmask.hpp
sparkml/mastermind-strategy
22763672c413c6a73e2c036a9f522b65a0025b68
[ "MIT" ]
null
null
null
lib/util/bitmask.hpp
sparkml/mastermind-strategy
22763672c413c6a73e2c036a9f522b65a0025b68
[ "MIT" ]
null
null
null
/// @defgroup BitMask Bit-Mask of fixed size /// @ingroup util #ifndef UTILITIES_BITMASK_HPP #define UTILITIES_BITMASK_HPP #include <cassert> #include "intrinsic.hpp" namespace util { /** * Represents a bitmask of fixed size. * This class serves as a simpler and faster alternative to * <code>std::bitset<N></code>. * @ingroup BitMask */ template <class T, size_t Bits> class bitmask { public: static_assert(Bits <= sizeof(T)*8, "The storage type does not have enough bits."); typedef T value_type; private: value_type _value; public: /// Creates an empty bitmask. bitmask() : _value(0) { } /// Creates a bitmask using the supplied mask. explicit bitmask(value_type value) : _value(value) { } /// Gets the internal value of the mask. value_type value() const { return _value; } /// Tests a given bit. bool operator [] (size_t bit) const { assert(bit <= Bits); return (_value & ((value_type)1 << bit)) != 0; } /// Resets a given bit to zero. void reset(int bit) { assert(bit >= 0 && bit <= (int)Bits); _value &= ~((value_type)1 << bit); } /// Resets the bits corresponding to the set bits in the given mask. void reset(const bitmask<T,Bits> &m) { _value &= ~ m.value(); } /// Resets all bits to zero. void reset() { _value = 0; } /// Returns @c true if all bits are reset. bool empty() const { return _value == 0; } /// Tests whether the bitmask is empty. bool operator ! () const { return _value == 0; } /// Returns @c true if there is exactly one bit set. bool unique() const { return _value && (_value & (_value - 1)) == 0; } /// Returns @c true if there are no more than one bit set. bool empty_or_unique() const { return (_value & (_value - 1)) == T(0); } /// Returns the index of the least significant bit set. /// If no bit is set, returns @c -1. int smallest() const { return _value == 0 ? -1 : util::intrinsic::bit_scan_forward(_value); } #if 0 int count() const { int n = 0; for (int i = 0; i < MM_MAX_COLORS; ++i) { if (value & (1 << i)) ++n; } return n; } void set_count(int count) { assert(count >= 0 && count <= MM_MAX_COLORS); value = (1 << count) - 1; } #endif /// Returns a bitmask with the least significant @c count bits set. static bitmask<T,Bits> fill(size_t count) { assert(count >= 0 && count <= Bits); return bitmask<T,Bits>(((value_type)1 << count) - 1); } }; template <class T, size_t Bits> inline bitmask<T,Bits> operator & ( const bitmask<T,Bits> &x, const bitmask<T,Bits> &y) { return bitmask<T,Bits>(x.value() & y.value()); } } // namespace util #endif // UTILITIES_BITMASK_HPP
20.585938
83
0.639848
sparkml