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
3db11026f8a1ee573b6de54f080be4cc6a948a9f
5,028
hpp
C++
src/Input.hpp
mechanicsfoundry/raytracinginoneweekend-glsl
515905135456fe263be9bc13b708222c28827a4d
[ "MIT" ]
4
2021-03-01T13:33:30.000Z
2021-03-14T20:05:00.000Z
src/Input.hpp
mechanicsfoundry/raytracinginoneweekend-glsl
515905135456fe263be9bc13b708222c28827a4d
[ "MIT" ]
null
null
null
src/Input.hpp
mechanicsfoundry/raytracinginoneweekend-glsl
515905135456fe263be9bc13b708222c28827a4d
[ "MIT" ]
null
null
null
#pragma once enum class DPadDirection { UP, DOWN, LEFT, RIGHT }; // these are matched to SDL key map scancodes enum class Scancode { S_UNKNOWN = 0, S_A = 4, S_B = 5, S_C = 6, S_D = 7, S_E = 8, S_F = 9, S_G = 10, S_H = 11, S_I = 12, S_J = 13, S_K = 14, S_L = 15, S_M = 16, S_N = 17, S_O = 18, S_P = 19, S_Q = 20, S_R = 21, S_S = 22, S_T = 23, S_U = 24, S_V = 25, S_W = 26, S_X = 27, S_Y = 28, S_Z = 29, S_1 = 30, S_2 = 31, S_3 = 32, S_4 = 33, S_5 = 34, S_6 = 35, S_7 = 36, S_8 = 37, S_9 = 38, S_0 = 39, S_RETURN = 40, S_ESCAPE = 41, S_BACKSPACE = 42, S_TAB = 43, S_SPACE = 44, S_MINUS = 45, S_EQUALS = 46, S_LEFTBRACKET = 47, S_RIGHTBRACKET = 48, S_BACKSLASH = 49, S_NONUSHASH = 50, S_SEMICOLON = 51, S_APOSTROPHE = 52, S_GRAVE = 53, S_COMMA = 54, S_PERIOD = 55, S_SLASH = 56, S_CAPSLOCK = 57, S_F1 = 58, S_F2 = 59, S_F3 = 60, S_F4 = 61, S_F5 = 62, S_F6 = 63, S_F7 = 64, S_F8 = 65, S_F9 = 66, S_F10 = 67, S_F11 = 68, S_F12 = 69, S_PRINTSCREEN = 70, S_SCROLLLOCK = 71, S_PAUSE = 72, S_INSERT = 73, S_HOME = 74, S_PAGEUP = 75, S_DELETE = 76, S_END = 77, S_PAGEDOWN = 78, S_RIGHT = 79, S_LEFT = 80, S_DOWN = 81, S_UP = 82, S_NUMLOCKCLEAR = 83, S_KP_DIVIDE = 84, S_KP_MULTIPLY = 85, S_KP_MINUS = 86, S_KP_PLUS = 87, S_KP_ENTER = 88, S_KP_1 = 89, S_KP_2 = 90, S_KP_3 = 91, S_KP_4 = 92, S_KP_5 = 93, S_KP_6 = 94, S_KP_7 = 95, S_KP_8 = 96, S_KP_9 = 97, S_KP_0 = 98, S_KP_PERIOD = 99, S_NONUSBACKSLASH = 100, S_APPLICATION = 101, S_POWER = 102, S_KP_EQUALS = 103, S_F13 = 104, S_F14 = 105, S_F15 = 106, S_F16 = 107, S_F17 = 108, S_F18 = 109, S_F19 = 110, S_F20 = 111, S_F21 = 112, S_F22 = 113, S_F23 = 114, S_F24 = 115, S_EXECUTE = 116, S_HELP = 117, S_MENU = 118, S_SELECT = 119, S_STOP = 120, S_AGAIN = 121, S_UNDO = 122, S_CUT = 123, S_COPY = 124, S_PASTE = 125, S_FIND = 126, S_MUTE = 127, S_VOLUMEUP = 128, S_VOLUMEDOWN = 129, S_KP_COMMA = 133, S_KP_EQUALSAS400 = 134, S_INTERNATIONAL1 = 135, S_INTERNATIONAL2 = 136, S_INTERNATIONAL3 = 137, S_INTERNATIONAL4 = 138, S_INTERNATIONAL5 = 139, S_INTERNATIONAL6 = 140, S_INTERNATIONAL7 = 141, S_INTERNATIONAL8 = 142, S_INTERNATIONAL9 = 143, S_LANG1 = 144, S_LANG2 = 145, S_LANG3 = 146, S_LANG4 = 147, S_LANG5 = 148, S_LANG6 = 149, S_LANG7 = 150, S_LANG8 = 151, S_LANG9 = 152, S_ALTERASE = 153, S_SYSREQ = 154, S_CANCEL = 155, S_CLEAR = 156, S_PRIOR = 157, S_RETURN2 = 158, S_SEPARATOR = 159, S_OUT = 160, S_OPER = 161, S_CLEARAGAIN = 162, S_CRSEL = 163, S_EXSEL = 164, S_KP_00 = 176, S_KP_000 = 177, S_THOUSANDSSEPARATOR = 178, S_DECIMALSEPARATOR = 179, S_CURRENCYUNIT = 180, S_CURRENCYSUBUNIT = 181, S_KP_LEFTPAREN = 182, S_KP_RIGHTPAREN = 183, S_KP_LEFTBRACE = 184, S_KP_RIGHTBRACE = 185, S_KP_TAB = 186, S_KP_BACKSPACE = 187, S_KP_A = 188, S_KP_B = 189, S_KP_C = 190, S_KP_D = 191, S_KP_E = 192, S_KP_F = 193, S_KP_XOR = 194, S_KP_POWER = 195, S_KP_PERCENT = 196, S_KP_LESS = 197, S_KP_GREATER = 198, S_KP_AMPERSAND = 199, S_KP_DBLAMPERSAND = 200, S_KP_VERTICALBAR = 201, S_KP_DBLVERTICALBAR = 202, S_KP_COLON = 203, S_KP_HASH = 204, S_KP_SPACE = 205, S_KP_AT = 206, S_KP_EXCLAM = 207, S_KP_MEMSTORE = 208, S_KP_MEMRECALL = 209, S_KP_MEMCLEAR = 210, S_KP_MEMADD = 211, S_KP_MEMSUBTRACT = 212, S_KP_MEMMULTIPLY = 213, S_KP_MEMDIVIDE = 214, S_KP_PLUSMINUS = 215, S_KP_CLEAR = 216, S_KP_CLEARENTRY = 217, S_KP_BINARY = 218, S_KP_OCTAL = 219, S_KP_DECIMAL = 220, S_KP_HEXADECIMAL = 221, S_LCTRL = 224, S_LSHIFT = 225, S_LALT = 226, S_LGUI = 227, S_RCTRL = 228, S_RSHIFT = 229, S_RALT = 230, S_RGUI = 231, S_MODE = 257, S_AUDIONEXT = 258, S_AUDIOPREV = 259, S_AUDIOSTOP = 260, S_AUDIOPLAY = 261, S_AUDIOMUTE = 262, S_MEDIASELECT = 263, S_WWW = 264, S_MAIL = 265, S_CALCULATOR = 266, S_COMPUTER = 267, S_AC_SEARCH = 268, S_AC_HOME = 269, S_AC_BACK = 270, S_AC_FORWARD = 271, S_AC_STOP = 272, S_AC_REFRESH = 273, S_AC_BOOKMARKS = 274, S_BRIGHTNESSDOWN = 275, S_BRIGHTNESSUP = 276, S_DISPLAYSWITCH = 277, S_KBDILLUMTOGGLE = 278, S_KBDILLUMDOWN = 279, S_KBDILLUMUP = 280, S_EJECT = 281, S_SLEEP = 282, S_APP1 = 283, S_APP2 = 284, S_AUDIOREWIND = 285, S_AUDIOFASTFORWARD = 286, NUM_SCANCODES = 512 };
19.413127
45
0.552506
mechanicsfoundry
3db1981084b1813f6fd4be3eb695e9820fb1ef9e
507
cpp
C++
utils/src/drawing/Point.cpp
AleksievAleksandar/Chess
4dd9e27ddf3302aa959d3a8854d3bc5fcb970dde
[ "MIT" ]
null
null
null
utils/src/drawing/Point.cpp
AleksievAleksandar/Chess
4dd9e27ddf3302aa959d3a8854d3bc5fcb970dde
[ "MIT" ]
null
null
null
utils/src/drawing/Point.cpp
AleksievAleksandar/Chess
4dd9e27ddf3302aa959d3a8854d3bc5fcb970dde
[ "MIT" ]
null
null
null
//Coresponding header #include "utils/drawing/Point.h" //C system includes //C++ system includes //Thitrd-party includes //Own includes //Forward Declarations const Point Point::ZERO(0, 0); const Point Point::UNDEFINED(1000, 1000); Point::Point(int32_t inputX, int32_t inputY) : x(inputX), y(inputY) {} bool Point::operator==(const Point & other) const { return ((this->x == other.x) && (this->y == other.y)); } bool Point::operator!=(const Point& other) const { return !(*this == other); }
15.363636
55
0.674556
AleksievAleksandar
3db1ea476c051e3c77f16173d80f015e29e591c8
4,549
cpp
C++
src/lib/logic/triple_to_fact.cpp
ethz-asl/libowlcpp
42d342bd901c19cfe090d20c6481d061a76f0fec
[ "BSL-1.0" ]
10
2017-12-21T05:20:40.000Z
2021-09-18T05:14:01.000Z
src/lib/logic/triple_to_fact.cpp
ethz-asl/libowlcpp
42d342bd901c19cfe090d20c6481d061a76f0fec
[ "BSL-1.0" ]
2
2017-12-21T07:31:54.000Z
2021-06-23T08:52:35.000Z
src/lib/logic/triple_to_fact.cpp
ethz-asl/libowlcpp
42d342bd901c19cfe090d20c6481d061a76f0fec
[ "BSL-1.0" ]
7
2016-02-17T13:20:31.000Z
2021-11-08T09:30:43.000Z
/** @file "/owlcpp/lib/logic/triple_to_fact.cpp" part of owlcpp project. @n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt. @n Copyright Mikhail K Levin 2013 *******************************************************************************/ #ifndef OWLCPP_LOGIC_SOURCE #define OWLCPP_LOGIC_SOURCE #endif #include "owlcpp/logic/triple_to_fact.hpp" #include "boost/foreach.hpp" #include "fact++/Kernel.h" #include "owlcpp/logic/detail/triple_to_fact_adaptor.hpp" #include "owlcpp/rdf/triple_store.hpp" #include "owlcpp/rdf/print_triple.hpp" namespace owlcpp { /* *******************************************************************************/ TDLAxiom* submit( Triple const& t, Triple_store const& ts, ReasoningKernel& kernel, const bool strict ) { logic::factpp::Adaptor_triple at(ts, kernel, strict); try{ return at.submit(t); } catch(Logic_err const&) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("error submitting triple") << Logic_err::str1_t(to_string(t, ts)) << Logic_err::str2_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } } /* *******************************************************************************/ TDLAxiom* submit_check( Triple const& t, Triple_store const& ts, ReasoningKernel& kernel, const bool strict ) { logic::factpp::Adaptor_triple at(ts, kernel, strict); TDLAxiom* a = 0; try{ a = at.submit(t); } catch(Logic_err const&) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("error submitting triple") << Logic_err::str1_t(to_string(t, ts)) << Logic_err::str2_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } if( a ) try{ kernel.isKBConsistent(); }catch(EFaCTPlusPlus const& e) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("reasoning error after submitting triple") << Logic_err::str1_t(e.what()) << Logic_err::str2_t(to_string(t, ts)) << Logic_err::str3_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } return a; } /* *******************************************************************************/ std::size_t submit( Triple_store const& ts, ReasoningKernel& kernel, const bool strict, const bool diagnose ) { if( diagnose ) return submit_check(ts, kernel, strict); std::size_t n = 0; logic::factpp::Adaptor_triple at(ts, kernel, strict); BOOST_FOREACH(Triple const& t, ts.map_triple()) { try{ if( at.submit(t) ) ++n; } catch(Logic_err const&) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("error submitting triple") << Logic_err::str1_t(to_string(t, ts)) << Logic_err::str2_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } } return n; } /* *******************************************************************************/ std::size_t submit_check( Triple_store const& ts, ReasoningKernel& kernel, const bool strict ) { std::size_t n = 0; logic::factpp::Adaptor_triple at(ts, kernel, strict); BOOST_FOREACH(Triple const& t, ts.map_triple()) { TDLAxiom* a = 0; try{ a = at.submit(t); } catch(Logic_err const&) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("error submitting triple") << Logic_err::str1_t(to_string(t, ts)) << Logic_err::str2_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } if( a ) try{ ++n; kernel.isKBConsistent(); }catch(EFaCTPlusPlus const& e) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("reasoning error after submitting triple") << Logic_err::str1_t(e.what()) << Logic_err::str2_t(to_string(t, ts)) << Logic_err::str3_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } } return n; } }//namespace owlcpp
31.811189
85
0.513959
ethz-asl
3db374f94ab913c1d8f1e0148d5847f4bf406d94
1,961
cpp
C++
NatureUserInterfaceApp/GUI/NuiPangoPolygonMeshShader.cpp
hustztz/NatureUserInterfaceStudio
3cdac6b6ee850c5c8470fa5f1554c7447be0d8af
[ "MIT" ]
3
2016-07-14T13:04:35.000Z
2017-04-01T09:58:27.000Z
NatureUserInterfaceApp/GUI/NuiPangoPolygonMeshShader.cpp
hustztz/NatureUserInterfaceStudio
3cdac6b6ee850c5c8470fa5f1554c7447be0d8af
[ "MIT" ]
null
null
null
NatureUserInterfaceApp/GUI/NuiPangoPolygonMeshShader.cpp
hustztz/NatureUserInterfaceStudio
3cdac6b6ee850c5c8470fa5f1554c7447be0d8af
[ "MIT" ]
1
2021-11-21T15:33:35.000Z
2021-11-21T15:33:35.000Z
#include "NuiPangoPolygonMeshShader.h" #include "Shape\NuiPolygonMesh.h" NuiPangoPolygonMeshShader::NuiPangoPolygonMeshShader() : m_numTriangles(0) { glGenBuffers(1, &m_vbo); glGenBuffers(1, &m_ibo); } NuiPangoPolygonMeshShader::~NuiPangoPolygonMeshShader() { uninitializeBuffers(); } bool NuiPangoPolygonMeshShader::initializeBuffers(NuiPolygonMesh* pMesh) { if(!pMesh) return false; int currentNumTriangles = pMesh->getTrianglesNum(); if (abs(currentNumTriangles - m_numTriangles) > 100) { pMesh->evaluateMesh(); m_numTriangles = currentNumTriangles; } if (0 == m_numTriangles) return false; glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glBufferData(GL_ARRAY_BUFFER, pMesh->getVerticesBufferSize(), pMesh->getVerticesBuffer(), GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, pMesh->getIndicesBufferSize(), pMesh->getIndicesBuffer(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); return true; } void NuiPangoPolygonMeshShader::drawMesh(const pangolin::OpenGlMatrix& mvp, bool bNormals) { glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glVertexPointer(3, GL_FLOAT, sizeof(pcl::PointXYZRGBNormal), 0); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); if (bNormals) { glColorPointer(3, GL_FLOAT, sizeof(pcl::PointXYZRGBNormal), (void *)(sizeof(float) * 4)); } else { glColorPointer(3, GL_UNSIGNED_BYTE, sizeof(pcl::PointXYZRGBNormal), (void *)(sizeof(float) * 8)); } glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo); glDrawElements(GL_TRIANGLES, m_numTriangles * 3, GL_UNSIGNED_INT, 0); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } void NuiPangoPolygonMeshShader::uninitializeBuffers() { glDeleteBuffers(1, &m_vbo); glDeleteBuffers(1, &m_ibo); }
26.146667
113
0.782764
hustztz
3db437c0abe19da4bb1dadb1d6c2e45b4ee1a2bc
3,235
cpp
C++
src/bindings.cpp
joshuarrrrr/wand
b53bb4880714bf39ce9c6e3f903d0f1edcaf8047
[ "MIT" ]
null
null
null
src/bindings.cpp
joshuarrrrr/wand
b53bb4880714bf39ce9c6e3f903d0f1edcaf8047
[ "MIT" ]
null
null
null
src/bindings.cpp
joshuarrrrr/wand
b53bb4880714bf39ce9c6e3f903d0f1edcaf8047
[ "MIT" ]
null
null
null
#include <pybind11/pybind11.h> #include <pybind11/chrono.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <string> #include <multitouch_device.hpp> #include <touch_point.hpp> namespace py = pybind11; using namespace wand; PYBIND11_MODULE(wand, m) { m.doc() = ""; py::class_<TouchPoint, std::shared_ptr<TouchPoint>>{m, "TouchPoint"} .def(py::init<int>(), py::arg("id")) .def("__repr__", [](const TouchPoint& touch) { return "<wand.TouchPoint " + std::to_string(touch.id()) + ">"; }) .def_property_readonly("id", &TouchPoint::id) .def_property_readonly("active", &TouchPoint::active) .def_property_readonly("start_time", &TouchPoint::start_time) .def_property_readonly("update_time", &TouchPoint::update_time) .def_property_readonly("end_time", &TouchPoint::end_time) .def_property_readonly("duration", &TouchPoint::duration) .def_property_readonly("start_x", &TouchPoint::start_x) .def_property_readonly("start_y", &TouchPoint::start_y) .def_property_readonly("start_pos", [](const TouchPoint& touch) { std::array<double, 2> pos = {touch.start_x(), touch.start_y()}; return py::array_t<double>(2, pos.data()); }) .def_property_readonly("x", &TouchPoint::x) .def_property_readonly("y", &TouchPoint::y) .def_property_readonly("pos", [](const TouchPoint& touch) { std::array<double, 2> pos = {touch.x(), touch.y()}; return py::array_t<double>(2, pos.data()); }) .def_property_readonly( "direction", [](const TouchPoint& touch) { std::array<double, 2> direction = {touch.x() - touch.start_x(), touch.y() - touch.start_y()}; return py::array_t<double>(2, direction.data()); }) .def_property_readonly("timestamps", &TouchPoint::timestamps) .def_property_readonly("x_positions", &TouchPoint::x_positions) .def_property_readonly("y_positions", &TouchPoint::y_positions); py::class_<MultitouchDevice, std::shared_ptr<MultitouchDevice>>{m, "MultitouchDevice"} .def(py::init<std::string>(), py::arg("path")) .def("__repr__", [](const MultitouchDevice& device) { return "<wand.MultitouchDevice \"" + device.name() + "\">"; }) .def_property_readonly("name", &MultitouchDevice::name) .def_property_readonly("num_slots", &MultitouchDevice::num_slots) .def_property_readonly("touch_points", &MultitouchDevice::touch_points) .def_property_readonly("running", &MultitouchDevice::running) .def("start", &MultitouchDevice::start) .def("stop", &MultitouchDevice::stop) .def("poll_events", [](MultitouchDevice& dev) { TouchPtrSet new_touch_points, updated_touch_points, finished_touch_points; dev.poll_events(new_touch_points, updated_touch_points, finished_touch_points); return std::make_tuple(std::move(new_touch_points), std::move(updated_touch_points), std::move(finished_touch_points)); }); }
46.884058
118
0.622875
joshuarrrrr
3db522672c3dbbd2ca95b86041fb79a5c4bc9c59
2,480
cpp
C++
BashuOJ-Code/5187.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/5187.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/5187.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<iomanip> #include<algorithm> #include<vector> #include<queue> #include<stack> #define ri register int #define ll long long using namespace std; const int MAXN=50005; const int MAXM=100005; int c[MAXN],dep[MAXN]; int n,m,sill=320,p[MAXN][16],g[MAXN][330]; vector<int>a[MAXN]; inline int GetInt() { int num=0,bj=1; char c=getchar(); while(!isdigit(c))bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(isdigit(c))num=num*10+c-'0',c=getchar(); return num*bj; } inline int Climb(int u,int k) { for(ri dk=0;k;k>>=1,++dk)if(k&1)u=p[u][dk]; return u; } void DFS(int u,int fa,int depth) { dep[u]=depth; vector<int>::iterator it; for(it=a[u].begin();it!=a[u].end();++it) { if(*it==fa)continue; p[*it][0]=u; DFS(*it,u,depth+1); } } void Tree_DP(int u) { for(ri i=1;i<=sill;i++) { int anc=Climb(u,i); g[u][i]=g[anc][i]+c[u]; } vector<int>::iterator it; for(it=a[u].begin();it!=a[u].end();++it) { if(*it==p[u][0])continue; Tree_DP(*it); } } inline void ST() { int k=log2(n); for(ri j=1;j<=k;j++) for(ri i=1;i<=n;i++) p[i][j]=p[p[i][j-1]][j-1]; } int len; inline int LCA(int a,int b) { if(dep[a]<dep[b])swap(a,b); int k=log2(dep[a]); for(ri i=k;i>=0;i--) if(dep[a]-(1<<i)>=dep[b])a=p[a][i],len+=(1<<i); if(a==b)return a; for(ri i=k;i>=0;i--) if(p[a][i]!=-1&&p[a][i]!=p[b][i])a=p[a][i],b=p[b][i],len+=(1<<(i+1)); len+=2; return p[a][0]; } inline int Query(int s,int t,int k) { int lca=LCA(s,t),ret=0,len=dep[s]+dep[t]-2*dep[lca],u=s; if(s==t)return c[s]; if(k<=sill) { int step=int(ceil(double(dep[s]-dep[lca])/(double)k)); int aim=Climb(s,step*k); ret+=g[s][k]-g[aim][k]; if(len%k)ret+=c[t],t=Climb(t,len%k); step=int(ceil(double(dep[t]-dep[lca])/(double)k)); aim=Climb(t,step*k); ret+=g[t][k]-g[aim][k]; if(!((dep[u]-dep[lca])%k))ret+=c[lca]; return ret; } else { int lca=LCA(s,t),ret=0,u=s; if(s==t)return c[s]; while(dep[s]>=dep[lca])ret+=c[s],s=Climb(s,k); if(len%k)ret+=c[t],t=Climb(t,len%k); while(dep[t]>=dep[lca])ret+=c[t],t=Climb(t,k); if(!((dep[u]-dep[lca])%k))ret-=c[lca]; return ret; } } int main() { n=GetInt(),m=GetInt(); for(ri i=1;i<=n;i++)c[i]=GetInt(); for(ri i=1;i<n;i++) { int u=GetInt(),v=GetInt(); a[u].push_back(v); a[v].push_back(u); } DFS(1,0,1),ST(),Tree_DP(1); for(ri i=1;i<=m;i++) { int s=GetInt(),t=GetInt(),k=GetInt(); printf("%d\n",Query(s,t,k)); } return 0; }
20.495868
71
0.568548
magicgh
3db59b7cf39b7d2b23adf4cccdd86667cbe9e717
303
cc
C++
cpp_gui_wt/itp.cc
hpepper/idea-to-product
64b72a2dff0fd1edc0ef6886f49a095e72febbcb
[ "Apache-2.0" ]
null
null
null
cpp_gui_wt/itp.cc
hpepper/idea-to-product
64b72a2dff0fd1edc0ef6886f49a095e72febbcb
[ "Apache-2.0" ]
null
null
null
cpp_gui_wt/itp.cc
hpepper/idea-to-product
64b72a2dff0fd1edc0ef6886f49a095e72febbcb
[ "Apache-2.0" ]
null
null
null
/* * itp.cc * * Created on: Nov 13, 2015 */ #include <Wt/WApplication> #include "IdeaToProduct.h" Wt::WApplication *createApplication(const Wt::WEnvironment& env) { return new IdeaToProduct(env); } int main(int argc, char **argv) { return Wt::WRun(argc, argv, &createApplication); }
13.173913
64
0.666667
hpepper
3db73ec1c3b65834ef9d175708b430a03d76ff31
12,569
cpp
C++
ThirdParty/JSBSim/include/math/FGLocation.cpp
Lynnvon/FlightSimulator
2dca6f8364b7f4972a248de3dbc3a711740f5ed4
[ "MIT" ]
1
2022-02-03T08:29:35.000Z
2022-02-03T08:29:35.000Z
ThirdParty/JSBSim/include/math/FGLocation.cpp
Lynnvon/FlightSimulator
2dca6f8364b7f4972a248de3dbc3a711740f5ed4
[ "MIT" ]
null
null
null
ThirdParty/JSBSim/include/math/FGLocation.cpp
Lynnvon/FlightSimulator
2dca6f8364b7f4972a248de3dbc3a711740f5ed4
[ "MIT" ]
null
null
null
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGLocation.cpp Author: Jon S. Berndt Date started: 04/04/2004 Purpose: Store an arbitrary location on the globe ------- Copyright (C) 1999 Jon S. Berndt (jon@jsbsim.org) ------------------ ------- (C) 2004 Mathias Froehlich (Mathias.Froehlich@web.de) ---- ------- (C) 2011 Ola Røer Thorsen (ola@silentwings.no) ----------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION ------------------------------------------------------------------------------ This class encapsulates an arbitrary position in the globe with its accessors. It has vector properties, so you can add multiply .... HISTORY ------------------------------------------------------------------------------ 04/04/2004 MF Created 11/01/2011 ORT Encapsulated ground callback code in FGLocation and removed it from FGFDMExec. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include <cmath> #include "FGLocation.h" namespace JSBSim { /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGLocation::FGLocation(void) : mECLoc(1.0, 0.0, 0.0), mCacheValid(false) { e2 = c = 0.0; a = ec = ec2 = 1.0; mLon = mLat = mRadius = 0.0; mGeodLat = GeodeticAltitude = 0.0; mTl2ec.InitMatrix(); mTec2l.InitMatrix(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGLocation::FGLocation(double lon, double lat, double radius) : mCacheValid(false) { e2 = c = 0.0; a = ec = ec2 = 1.0; mLon = mLat = mRadius = 0.0; mGeodLat = GeodeticAltitude = 0.0; mTl2ec.InitMatrix(); mTec2l.InitMatrix(); double sinLat = sin(lat); double cosLat = cos(lat); double sinLon = sin(lon); double cosLon = cos(lon); mECLoc = { radius*cosLat*cosLon, radius*cosLat*sinLon, radius*sinLat }; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGLocation::FGLocation(const FGColumnVector3& lv) : mECLoc(lv), mCacheValid(false) { e2 = c = 0.0; a = ec = ec2 = 1.0; mLon = mLat = mRadius = 0.0; mGeodLat = GeodeticAltitude = 0.0; mTl2ec.InitMatrix(); mTec2l.InitMatrix(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGLocation::FGLocation(const FGLocation& l) : mECLoc(l.mECLoc), mCacheValid(l.mCacheValid) { a = l.a; e2 = l.e2; c = l.c; ec = l.ec; ec2 = l.ec2; mEllipseSet = l.mEllipseSet; /*ag * if the cache is not valid, all of the following values are unset. * They will be calculated once ComputeDerivedUnconditional is called. * If unset, they may possibly contain NaN and could thus trigger floating * point exceptions. */ if (!mCacheValid) return; mLon = l.mLon; mLat = l.mLat; mRadius = l.mRadius; mTl2ec = l.mTl2ec; mTec2l = l.mTec2l; mGeodLat = l.mGeodLat; GeodeticAltitude = l.GeodeticAltitude; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGLocation& FGLocation::operator=(const FGLocation& l) { mECLoc = l.mECLoc; mCacheValid = l.mCacheValid; mEllipseSet = l.mEllipseSet; a = l.a; e2 = l.e2; c = l.c; ec = l.ec; ec2 = l.ec2; //ag See comment in constructor above if (!mCacheValid) return *this; mLon = l.mLon; mLat = l.mLat; mRadius = l.mRadius; mTl2ec = l.mTl2ec; mTec2l = l.mTec2l; mGeodLat = l.mGeodLat; GeodeticAltitude = l.GeodeticAltitude; return *this; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetLongitude(double longitude) { double rtmp = mECLoc.Magnitude(eX, eY); // Check if we have zero radius. // If so set it to 1, so that we can set a position if (0.0 == mECLoc.Magnitude()) rtmp = 1.0; // Fast return if we are on the north or south pole ... if (rtmp == 0.0) return; mCacheValid = false; mECLoc(eX) = rtmp*cos(longitude); mECLoc(eY) = rtmp*sin(longitude); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetLatitude(double latitude) { mCacheValid = false; double r = mECLoc.Magnitude(); if (r == 0.0) { mECLoc(eX) = 1.0; r = 1.0; } double rtmp = mECLoc.Magnitude(eX, eY); if (rtmp != 0.0) { double fac = r/rtmp*cos(latitude); mECLoc(eX) *= fac; mECLoc(eY) *= fac; } else { mECLoc(eX) = r*cos(latitude); mECLoc(eY) = 0.0; } mECLoc(eZ) = r*sin(latitude); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetRadius(double radius) { mCacheValid = false; double rold = mECLoc.Magnitude(); if (rold == 0.0) mECLoc(eX) = radius; else mECLoc *= radius/rold; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetPosition(double lon, double lat, double radius) { mCacheValid = false; double sinLat = sin(lat); double cosLat = cos(lat); double sinLon = sin(lon); double cosLon = cos(lon); mECLoc = { radius*cosLat*cosLon, radius*cosLat*sinLon, radius*sinLat }; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetPositionGeodetic(double lon, double lat, double height) { assert(mEllipseSet); mCacheValid = false; double slat = sin(lat); double clat = cos(lat); double RN = a / sqrt(1.0 - e2*slat*slat); mECLoc(eX) = (RN + height)*clat*cos(lon); mECLoc(eY) = (RN + height)*clat*sin(lon); mECLoc(eZ) = ((1 - e2)*RN + height)*slat; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetEllipse(double semimajor, double semiminor) { mCacheValid = false; mEllipseSet = true; a = semimajor; ec = semiminor/a; ec2 = ec * ec; e2 = 1.0 - ec2; c = a * e2; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGLocation::GetSeaLevelRadius(void) const { assert(mEllipseSet); ComputeDerived(); double cosLat = cos(mLat); return a*ec/sqrt(1.0-e2*cosLat*cosLat); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::ComputeDerivedUnconditional(void) const { // The radius is just the Euclidean norm of the vector. mRadius = mECLoc.Magnitude(); // The distance of the location to the Z-axis, which is the axis // through the poles. double rxy = mECLoc.Magnitude(eX, eY); // Compute the longitude and its sin/cos values. double sinLon, cosLon; if (rxy == 0.0) { sinLon = 0.0; cosLon = 1.0; mLon = 0.0; } else { sinLon = mECLoc(eY)/rxy; cosLon = mECLoc(eX)/rxy; mLon = atan2(mECLoc(eY), mECLoc(eX)); } // Compute the geocentric & geodetic latitudes. double sinLat, cosLat; if (mRadius == 0.0) { mLat = 0.0; sinLat = 0.0; cosLat = 1.0; if (mEllipseSet) { mGeodLat = 0.0; GeodeticAltitude = -a; } } else { mLat = atan2( mECLoc(eZ), rxy ); // Calculate the geodetic latitude based on "Transformation from Cartesian to // geodetic coordinates accelerated by Halley's method", Fukushima T. (2006) // Journal of Geodesy, Vol. 79, pp. 689-693 // Unlike I. Sofair's method which uses a closed form solution, Fukushima's // method is an iterative method whose convergence is so fast that only one // iteration suffices. In addition, Fukushima's method has a much better // numerical stability over Sofair's method at the North and South poles and // it also gives the correct result for a spherical Earth. if (mEllipseSet) { double s0 = fabs(mECLoc(eZ)); double zc = ec * s0; double c0 = ec * rxy; double c02 = c0 * c0; double s02 = s0 * s0; double a02 = c02 + s02; double a0 = sqrt(a02); double a03 = a02 * a0; double s1 = zc*a03 + c*s02*s0; double c1 = rxy*a03 - c*c02*c0; double cs0c0 = c*c0*s0; double b0 = 1.5*cs0c0*((rxy*s0-zc*c0)*a0-cs0c0); s1 = s1*a03-b0*s0; double cc = ec*(c1*a03-b0*c0); mGeodLat = sign(mECLoc(eZ))*atan(s1 / cc); double s12 = s1 * s1; double cc2 = cc * cc; double norm = sqrt(s12 + cc2); cosLat = cc / norm; sinLat = sign(mECLoc(eZ)) * s1 / norm; GeodeticAltitude = (rxy*cc + s0*s1 - a*sqrt(ec2*s12 + cc2)) / norm; } else { sinLat = mECLoc(eZ)/mRadius; cosLat = rxy/mRadius; } } // Compute the transform matrices from and to the earth centered frame. // See Stevens and Lewis, "Aircraft Control and Simulation", Second Edition, // Eqn. 1.4-13, page 40. In Stevens and Lewis notation, this is C_n/e - the // orientation of the navigation (local) frame relative to the ECEF frame, // and a transformation from ECEF to nav (local) frame. mTec2l = { -cosLon*sinLat, -sinLon*sinLat, cosLat, -sinLon , cosLon , 0.0 , -cosLon*cosLat, -sinLon*cosLat, -sinLat }; // In Stevens and Lewis notation, this is C_e/n - the // orientation of the ECEF frame relative to the nav (local) frame, // and a transformation from nav (local) to ECEF frame. mTl2ec = mTec2l.Transposed(); // Mark the cached values as valid mCacheValid = true; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The calculations, below, implement the Haversine formulas to calculate // heading and distance to a set of lat/long coordinates from the current // position. // // The basic equations are (lat1, long1 are source positions; lat2 // long2 are target positions): // // R = earth’s radius // Δlat = lat2 − lat1 // Δlong = long2 − long1 // // For the waypoint distance calculation: // // a = sin²(Δlat/2) + cos(lat1)∙cos(lat2)∙sin²(Δlong/2) // c = 2∙atan2(√a, √(1−a)) // d = R∙c double FGLocation::GetDistanceTo(double target_longitude, double target_latitude) const { ComputeDerived(); double delta_lat_rad = target_latitude - mLat; double delta_lon_rad = target_longitude - mLon; double distance_a = pow(sin(0.5*delta_lat_rad), 2.0) + (cos(mLat) * cos(target_latitude) * (pow(sin(0.5*delta_lon_rad), 2.0))); return 2.0 * GetRadius() * atan2(sqrt(distance_a), sqrt(1.0 - distance_a)); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The calculations, below, implement the Haversine formulas to calculate // heading and distance to a set of lat/long coordinates from the current // position. // // The basic equations are (lat1, long1 are source positions; lat2 // long2 are target positions): // // R = earth’s radius // Δlat = lat2 − lat1 // Δlong = long2 − long1 // // For the heading angle calculation: // // θ = atan2(sin(Δlong)∙cos(lat2), cos(lat1)∙sin(lat2) − sin(lat1)∙cos(lat2)∙cos(Δlong)) double FGLocation::GetHeadingTo(double target_longitude, double target_latitude) const { ComputeDerived(); double delta_lon_rad = target_longitude - mLon; double Y = sin(delta_lon_rad) * cos(target_latitude); double X = cos(mLat) * sin(target_latitude) - sin(mLat) * cos(target_latitude) * cos(delta_lon_rad); double heading_to_waypoint_rad = atan2(Y, X); if (heading_to_waypoint_rad < 0) heading_to_waypoint_rad += 2.0*M_PI; return heading_to_waypoint_rad; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% } // namespace JSBSim
28.565909
89
0.557403
Lynnvon
3db9b42621692c39fcbfa859c884a09e9241a09b
2,140
cpp
C++
src/planner/logical_operator.cpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
1
2022-03-09T03:05:00.000Z
2022-03-09T03:05:00.000Z
src/planner/logical_operator.cpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
null
null
null
src/planner/logical_operator.cpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
1
2022-01-18T09:38:19.000Z
2022-01-18T09:38:19.000Z
#include "duckdb/planner/logical_operator.hpp" #include "duckdb/common/printer.hpp" #include "duckdb/common/string_util.hpp" using namespace duckdb; using namespace std; string LogicalOperator::ParamsToString() const { string result = ""; if (expressions.size() > 0) { result += "["; result += StringUtil::Join(expressions, expressions.size(), ", ", [](const unique_ptr<Expression> &expression) { return expression->GetName(); }); result += "]"; } return result; } void LogicalOperator::ResolveOperatorTypes() { // if (types.size() > 0) { // // types already resolved for this node // return; // } types.clear(); // first resolve child types for (auto &child : children) { child->ResolveOperatorTypes(); } // now resolve the types for this operator ResolveTypes(); } vector<ColumnBinding> LogicalOperator::GenerateColumnBindings(idx_t table_idx, idx_t column_count) { vector<ColumnBinding> result; for (idx_t i = 0; i < column_count; i++) { result.push_back(ColumnBinding(table_idx, i)); } return result; } vector<TypeId> LogicalOperator::MapTypes(vector<TypeId> types, vector<idx_t> projection_map) { if (projection_map.size() == 0) { return types; } else { vector<TypeId> result_types; for (auto index : projection_map) { result_types.push_back(types[index]); } return result_types; } } vector<ColumnBinding> LogicalOperator::MapBindings(vector<ColumnBinding> bindings, vector<idx_t> projection_map) { if (projection_map.size() == 0) { return bindings; } else { vector<ColumnBinding> result_bindings; for (auto index : projection_map) { result_bindings.push_back(bindings[index]); } return result_bindings; } } string LogicalOperator::ToString(idx_t depth) const { string result = LogicalOperatorToString(type); result += ParamsToString(); if (children.size() > 0) { for (idx_t i = 0; i < children.size(); i++) { result += "\n" + string(depth * 4, ' '); auto &child = children[i]; result += child->ToString(depth + 1); } result += ""; } return result; } void LogicalOperator::Print() { Printer::Print(ToString()); }
25.47619
114
0.684112
rainmaple
3dbc6b4a4e76a80b1006d2832fe4f8eb1fc8cd74
667
cpp
C++
tests/all.cpp
robclu/wrench
8fff96c35b4d2ff351edd8ec2b7ce0d03343bda7
[ "MIT" ]
null
null
null
tests/all.cpp
robclu/wrench
8fff96c35b4d2ff351edd8ec2b7ce0d03343bda7
[ "MIT" ]
null
null
null
tests/all.cpp
robclu/wrench
8fff96c35b4d2ff351edd8ec2b7ce0d03343bda7
[ "MIT" ]
null
null
null
//==--- wrench/tests/all.cpp ------------------------------- -*- C++ -*- ---==// // // Wrench // // Copyright (c) 2020 Rob Clucas. // // This file is distributed under the MIT License. See LICENSE for details. // //==------------------------------------------------------------------------==// // /// \file all.cpp /// \brief This file implements all tests. // //==------------------------------------------------------------------------==// #include "algorithm/algorithm.hpp" #include "memory/memory.hpp" int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
30.318182
80
0.4003
robclu
3dbd2980368ebc42b00ccbf542aa0777d2c7b032
2,137
cc
C++
fides/mock_settings_document.cc
cschuet/fides
c31ad020f213f859ddeb7a7be558e7769a501044
[ "FSFAP" ]
2
2018-07-27T00:29:35.000Z
2018-07-29T14:44:59.000Z
fides/mock_settings_document.cc
cschuet/fides
c31ad020f213f859ddeb7a7be558e7769a501044
[ "FSFAP" ]
null
null
null
fides/mock_settings_document.cc
cschuet/fides
c31ad020f213f859ddeb7a7be558e7769a501044
[ "FSFAP" ]
null
null
null
// Copyright 2015 The Chromium OS 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 "fides/mock_settings_document.h" #include "fides/identifier_utils.h" namespace fides { MockSettingsDocument::MockSettingsDocument(const VersionStamp& version_stamp) : version_stamp_(version_stamp) {} MockSettingsDocument::~MockSettingsDocument() {} std::unique_ptr<MockSettingsDocument> MockSettingsDocument::Clone() const { std::unique_ptr<MockSettingsDocument> copy( new MockSettingsDocument(version_stamp_)); copy->deletions_ = deletions_; copy->key_value_map_ = key_value_map_; return copy; } BlobRef MockSettingsDocument::GetValue(const Key& key) const { auto entry = key_value_map_.find(key); return entry != key_value_map_.end() ? BlobRef(&entry->second) : BlobRef(); } std::set<Key> MockSettingsDocument::GetKeys(const Key& prefix) const { std::set<Key> result; for (const auto& entry : utils::GetRange(prefix, key_value_map_)) result.insert(entry.first); return result; } std::set<Key> MockSettingsDocument::GetDeletions(const Key& prefix) const { std::set<Key> result; for (const auto& entry : utils::GetRange(prefix, deletions_)) result.insert(entry); return result; } VersionStamp MockSettingsDocument::GetVersionStamp() const { return version_stamp_; } bool MockSettingsDocument::HasKeysOrDeletions(const Key& prefix) const { return utils::HasKeys(prefix, key_value_map_) || utils::HasKeys(prefix, deletions_); } void MockSettingsDocument::SetKey(const Key& key, const std::string& value) { key_value_map_.insert(std::make_pair(key, std::move(value))); } void MockSettingsDocument::ClearKey(const Key& key) { key_value_map_.erase(key); } void MockSettingsDocument::ClearKeys() { key_value_map_.clear(); } void MockSettingsDocument::SetDeletion(const Key& key) { deletions_.insert(key); } void MockSettingsDocument::ClearDeletion(const Key& key) { deletions_.erase(key); } void MockSettingsDocument::ClearDeletions() { deletions_.clear(); } } // namespace fides
27.753247
77
0.750585
cschuet
3dbdc45ea055ecc6fc7cf67d92f3a5c3fad796cc
3,509
cpp
C++
EngCode/SOHTA engine/Graphics.cpp
AthosMatos/ATHOS-Engine
24b09042cd8d661ac70d0f6b302a8b129a843fbd
[ "MIT" ]
null
null
null
EngCode/SOHTA engine/Graphics.cpp
AthosMatos/ATHOS-Engine
24b09042cd8d661ac70d0f6b302a8b129a843fbd
[ "MIT" ]
null
null
null
EngCode/SOHTA engine/Graphics.cpp
AthosMatos/ATHOS-Engine
24b09042cd8d661ac70d0f6b302a8b129a843fbd
[ "MIT" ]
null
null
null
#include "Graphics.h" #include <string.h> void Graphics::init(HWND hwnd) { cout << "GRAPHICS STARTED\n"; d3d = new D3D; d2d = new D2D; RQ2D = new RenderQueue_2D; fistscene = new StdScene; d3d->InitD3D(hwnd); InitSharedScreen(d3d->Adapter); d2d->InitD2D(sharedSurface10); d2d->UpdateClassResources(keyedMutex11, keyedMutex10); d3d->Adapter->Release(); sharedSurface10->Release(); keyedMutex11->Release(); keyedMutex10->Release(); cout << "GRAPHICS LOADED\n"; } void Graphics::startScene() { fistscene->LoadScene(); d2d->SetRenderArea(sharedTex11, 0, 0, 0, 0); sharedTex11->Release(); } void Graphics::Update(double FrameTime, double FPS) { fistscene->SceneInput(FrameTime); fistscene->UpdateScene(FrameTime,FPS); } void Graphics::Render() { //bckground color float bgColor[4] = { 0.0f,0.05f,0.1f,1.0f }; //Clear our backbuffer d3d->d3dDevCon->ClearRenderTargetView(d3d->renderTargetView, bgColor); d3d->d3dDevCon->ClearDepthStencilView(d3d->depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); fistscene->Renderscene(); RQ2D->Render(); d3d->SwapChain->Present(0, 0); } void Graphics::Release() { if (d2d)d2d->Release(); if (d3d)d3d->Release(); if (fistscene)fistscene->Release(); if (RQ2D)RQ2D->Release(); } void Graphics::InitSharedScreen(IDXGIAdapter1* Adapter) { //Create our Direc3D 10.1 Device/////////////////////////////////////////////////////////////////////////////////////// HRESULT hr = D3D10CreateDevice1(Adapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, D3D10_CREATE_DEVICE_BGRA_SUPPORT, D3D10_FEATURE_LEVEL_9_3, D3D10_1_SDK_VERSION, &d3d101Device); //Create Shared Texture that Direct3D 10.1 will render on////////////////////////////////////////////////////////////// D3D11_TEXTURE2D_DESC sharedTexDesc; ZeroMemory(&sharedTexDesc, sizeof(sharedTexDesc)); sharedTexDesc.Width = H_res; sharedTexDesc.Height = V_res; sharedTexDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; sharedTexDesc.MipLevels = 1; sharedTexDesc.ArraySize = 1; sharedTexDesc.SampleDesc.Count = 1; sharedTexDesc.Usage = D3D11_USAGE_DEFAULT; sharedTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; sharedTexDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; hr = d3d->d3dDevice->CreateTexture2D(&sharedTexDesc, NULL, &sharedTex11); // Get the keyed mutex for the shared texture (for D3D11)/////////////////////////////////////////////////////////////// hr = sharedTex11->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex11); // Get the shared handle needed to open the shared texture in D3D10.1/////////////////////////////////////////////////// IDXGIResource* sharedResource10; HANDLE sharedHandle10; hr = sharedTex11->QueryInterface(__uuidof(IDXGIResource), (void**)&sharedResource10); hr = sharedResource10->GetSharedHandle(&sharedHandle10); sharedResource10->Release(); // Open the surface for the shared texture in D3D10.1/////////////////////////////////////////////////////////////////// hr = d3d101Device->OpenSharedResource(sharedHandle10, __uuidof(IDXGISurface1), (void**)(&sharedSurface10)); hr = sharedSurface10->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex10); d3d101Device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST); d3d101Device->Release(); }
30.513043
124
0.647763
AthosMatos
3dc027a80e734cfd2994279d3c7f8335c3b04428
2,661
hpp
C++
query_optimizer/strategy/Strategy.hpp
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
31
2016-01-20T05:43:46.000Z
2022-02-07T09:14:06.000Z
query_optimizer/strategy/Strategy.hpp
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
221
2016-01-20T18:25:10.000Z
2016-06-26T02:58:12.000Z
query_optimizer/strategy/Strategy.hpp
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
17
2016-01-20T04:00:21.000Z
2019-03-12T02:41:25.000Z
/** * Copyright 2011-2015 Quickstep Technologies LLC. * Copyright 2015 Pivotal Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #ifndef QUICKSTEP_QUERY_OPTIMIZER_STRATEGY_STRATEGY_HPP_ #define QUICKSTEP_QUERY_OPTIMIZER_STRATEGY_STRATEGY_HPP_ #include <string> #include <vector> #include "query_optimizer/logical/Logical.hpp" #include "query_optimizer/physical/Physical.hpp" #include "utility/Macros.hpp" namespace quickstep { namespace optimizer { class OptimizerContext; class LogicalToPhysicalMapper; namespace strategy { /** \addtogroup OptimizerStrategy * @{ */ /** * @brief Base class for strategies that implement how to convert a logical * plan to a physical plan for a type of operators. */ class Strategy { public: /** * @brief Destructor. */ virtual ~Strategy() {} /** * @brief Converts \p logical_input to \p physical_output if the strategy * can be applied to the input; otherwise, set physical_output to NULL. * * @param logical_input The logical plan to be converted * @param physical_output The physical plan output. NULL if the strategy * cannot be applied to the input. * @return True if the strategy has been applied to the input logical. */ virtual bool generatePlan(const logical::LogicalPtr &logical_input, physical::PhysicalPtr *physical_output) = 0; /** * @return The name of the strategy. */ virtual std::string getName() const = 0; protected: /** * @brief Constructor. * * @param physical_mapper The physical plan generator. A strategy can * interact with other strategies via the plan * generator to create a complete plan. */ explicit Strategy(LogicalToPhysicalMapper *physical_mapper) : physical_mapper_(physical_mapper) {} LogicalToPhysicalMapper *physical_mapper_; private: DISALLOW_COPY_AND_ASSIGN(Strategy); }; /** @} */ } // namespace strategy } // namespace optimizer } // namespace quickstep #endif /* QUICKSTEP_QUERY_OPTIMIZER_STRATEGY_STRATEGY_HPP_ */
28.923913
80
0.699361
spring-operator
3dc6dd6bd96bf2220ffed2970168c76685ac3ccd
1,263
cpp
C++
c11httpd/worker_pool.cpp
toalexjin/c11httpd
6774d96c72d60ad8c371a6d846744a9ccc98d7ee
[ "MIT" ]
null
null
null
c11httpd/worker_pool.cpp
toalexjin/c11httpd
6774d96c72d60ad8c371a6d846744a9ccc98d7ee
[ "MIT" ]
null
null
null
c11httpd/worker_pool.cpp
toalexjin/c11httpd
6774d96c72d60ad8c371a6d846744a9ccc98d7ee
[ "MIT" ]
null
null
null
/** * Process worker pool. * * Copyright (c) 2015 Alex Jin (toalexjin@hotmail.com) */ #include "c11httpd/worker_pool.h" #include <signal.h> namespace c11httpd { err_t worker_pool_t::create(int number) { if (!this->m_main_process) { return err_t(); } for (int i = 0; i < number; ++i) { const auto pid = fork(); if (pid == -1) { return err_t::current(); } if (pid == 0) { this->m_self_pid = getpid(); this->m_main_process = false; break; } else { assert(this->m_main_process); this->m_workers.insert(pid); } } return err_t(); } err_t worker_pool_t::kill(pid_t pid) { err_t ret; if (!this->m_main_process) { return ret; } auto pos = this->m_workers.find(pid); if (pos == this->m_workers.end()) { return ret; } if (::kill(pid, SIGTERM) == -1) { ret = err_t::current(); } this->m_workers.erase(pos); return ret; } void worker_pool_t::kill_all() { if (!this->m_main_process) { return; } for (auto it = this->m_workers.cbegin(); it != this->m_workers.cend(); ++it) { ::kill((*it), SIGTERM); } this->m_workers.clear(); } bool worker_pool_t::on_terminated(pid_t pid) { if (!this->m_main_process) { return false; } return this->m_workers.erase(pid) > 0; } } // namespace c11httpd.
15.592593
79
0.618369
toalexjin
3dc96b363b476cb806b23b85e70a33eedc144b2d
1,643
hpp
C++
libff/algebra/curves/mcl_bn128/mcl_bn128_gt.hpp
CortexFoundation/libff
5e87e58d6636125052030ad8a2fb93677e327bcd
[ "MIT" ]
null
null
null
libff/algebra/curves/mcl_bn128/mcl_bn128_gt.hpp
CortexFoundation/libff
5e87e58d6636125052030ad8a2fb93677e327bcd
[ "MIT" ]
null
null
null
libff/algebra/curves/mcl_bn128/mcl_bn128_gt.hpp
CortexFoundation/libff
5e87e58d6636125052030ad8a2fb93677e327bcd
[ "MIT" ]
1
2019-07-10T09:31:25.000Z
2019-07-10T09:31:25.000Z
/** @file ***************************************************************************** * @author This file is part of libsnark, developed by SCIPR Lab * and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #ifndef MCL_BN128_GT_HPP_ #define MCL_BN128_GT_HPP_ #include <iostream> #include "depends/mcl/include/mcl/bn256.hpp" #include <libff/algebra/fields/field_utils.hpp> #include <libff/algebra/fields/fp.hpp> namespace libff { class mcl_bn128_GT; std::ostream& operator<<(std::ostream &, const mcl_bn128_GT&); std::istream& operator>>(std::istream &, mcl_bn128_GT&); class mcl_bn128_GT { public: static mcl_bn128_GT &GT_one(); mcl::bn256::Fp12 elem; mcl_bn128_GT(); bool operator==(const mcl_bn128_GT &other) const; bool operator!=(const mcl_bn128_GT &other) const; mcl_bn128_GT operator*(const mcl_bn128_GT &other) const; mcl_bn128_GT unitary_inverse() const; static mcl_bn128_GT one(); void print() { std::cout << this->elem << "\n"; }; friend std::ostream& operator<<(std::ostream &out, const mcl_bn128_GT &g); friend std::istream& operator>>(std::istream &in, mcl_bn128_GT &g); }; template<mp_size_t m> mcl_bn128_GT operator^(const mcl_bn128_GT &rhs, const bigint<m> &lhs) { return power<mcl_bn128_GT, m>(rhs, lhs); } template<mp_size_t m, const bigint<m>& modulus_p> mcl_bn128_GT operator^(const mcl_bn128_GT &rhs, const Fp_model<m,modulus_p> &lhs) { return power<mcl_bn128_GT, m>(rhs, lhs.as_bigint()); } } // libff #endif // MCL_BN128_GT_HPP_
28.327586
81
0.637858
CortexFoundation
3dc9b780ad76b91d41cd5cfa6d53f48ee32f9807
1,595
cpp
C++
Gems/LandscapeCanvas/Code/Tests/LandscapeCanvasTest.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/LandscapeCanvas/Code/Tests/LandscapeCanvasTest.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/LandscapeCanvas/Code/Tests/LandscapeCanvasTest.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzTest/AzTest.h> #include <AzCore/Component/ComponentApplication.h> #include <AzCore/Component/Entity.h> #include <AzCore/Memory/MemoryComponent.h> #include <Source/LandscapeCanvasSystemComponent.h> class LandscapeCanvasTest : public ::testing::Test { protected: void SetUp() override { // Setup a system allocator AZ::ComponentApplication::Descriptor appDesc; m_application.Create(appDesc); m_application.RegisterComponentDescriptor(LandscapeCanvas::LandscapeCanvasSystemComponent::CreateDescriptor()); } void TearDown() override { m_application.Destroy(); } AZ::ComponentApplication m_application; }; TEST_F(LandscapeCanvasTest, LandscapeCanvasSystemComponentCreatesAndDestroysSuccessfully) { LandscapeCanvas::LandscapeCanvasSystemComponent test; } TEST_F(LandscapeCanvasTest, LandscapeCanvasSystemComponentActivatesAndDeactivatesSuccessfully) { auto entity = AZStd::make_unique<AZ::Entity>(); entity->CreateComponent<LandscapeCanvas::LandscapeCanvasSystemComponent>(); entity->Init(); EXPECT_EQ(AZ::Entity::State::Init, entity->GetState()); entity->Activate(); EXPECT_EQ(AZ::Entity::State::Active, entity->GetState()); entity->Deactivate(); EXPECT_EQ(AZ::Entity::State::Init, entity->GetState()); } AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV);
27.5
119
0.742947
cypherdotXd
3dcc020c864f9a41ba0be26926ad485193f0f698
2,958
hpp
C++
include/CppML/Functional/Bind.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
48
2019-05-14T10:07:08.000Z
2021-04-08T08:26:20.000Z
include/CppML/Functional/Bind.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
null
null
null
include/CppML/Functional/Bind.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
4
2019-11-18T15:35:32.000Z
2021-12-02T05:23:04.000Z
/** * Copyright Žiga Sajovic, XLAB 2019 * Distributed under the MIT License * * https://github.com/ZigaSajovic/CppML **/ #ifndef CPPML_BIND_HPP #define CPPML_BIND_HPP #include "../Pack/Insert.hpp" #include "./Compose.hpp" #include "./Partial.hpp" namespace ml { /* * # Par: * Is a parameter holder for ml::Bind. */ template <int I, typename T> struct Par { template <typename Pipe> using f = ml::Insert<I, T, Pipe>; }; /* * # Bind: * Binds arguments, creating a partially evaluated metafunction * **NOTE** that Is must be in sorted order */ template <typename F, typename... Ts> struct Bind; template <typename F, int... Is, typename... Args> struct Bind<F, Par<Is, Args>...> : ml::Invoke<ml::Compose<Par<Is, Args>...>, F> {}; /* * Below are a few optimizations to avoid work. When we are binding * successive parameters, from the first forward, it is the same as * if we used ml::Partial, which is more efficient. */ template <typename F, typename T0> struct Bind<F, Par<0, T0>> : ml::Partial<F, T0> {}; template <typename F, typename T0, typename T1> struct Bind<F, Par<0, T0>, Par<1, T1>> : ml::Partial<F, T0, T1> {}; template <typename F, typename T0, typename T1, typename T2> struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>> : ml::Partial<F, T0, T1, T2> {}; template <typename F, typename T0, typename T1, typename T2, typename T3> struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>, Par<3, T3>> : ml::Partial<F, T0, T1, T2, T3> {}; template <typename F, typename T0, typename T1, typename T2, typename T3, typename T4> struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>, Par<3, T3>, Par<4, T4>> : ml::Partial<F, T0, T1, T2, T3, T4> {}; template <typename F, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5> struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>, Par<3, T3>, Par<4, T4>, Par<5, T5>> : ml::Partial<F, T0, T1, T2, T3, T4, T5> {}; /* * # _pi: */ template <typename T> using _p0 = Par<0, T>; template <typename T> using _p1 = Par<1, T>; template <typename T> using _p2 = Par<2, T>; template <typename T> using _p3 = Par<3, T>; template <typename T> using _p4 = Par<4, T>; template <typename T> using _p5 = Par<5, T>; template <typename T> using _p6 = Par<6, T>; template <typename T> using _p7 = Par<7, T>; template <typename T> using _p8 = Par<8, T>; template <typename T> using _p9 = Par<9, T>; template <typename T> using _p10 = Par<10, T>; template <typename T> using _p11 = Par<11, T>; template <typename T> using _p12 = Par<12, T>; template <typename T> using _p13 = Par<13, T>; template <typename T> using _p14 = Par<14, T>; template <typename T> using _p15 = Par<15, T>; template <typename T> using _p16 = Par<16, T>; template <typename T> using _p17 = Par<17, T>; template <typename T> using _p18 = Par<18, T>; template <typename T> using _p19 = Par<19, T>; template <typename T> using _p20 = Par<20, T>; } // namespace ml #endif
34.395349
74
0.647059
changjurhee
3dd1088d19894069d000f8e7b0e2e9eaeaad9467
1,857
cpp
C++
src/python/compiled_analysis_plugins/box_parallel.cpp
confitarlaburra/pteros2.0
25de81f39bc8948a37e10e3b389d58ca71195d8d
[ "BSL-1.0", "BSD-3-Clause" ]
1
2019-02-19T14:36:10.000Z
2019-02-19T14:36:10.000Z
src/python/compiled_analysis_plugins/box_parallel.cpp
confitarlaburra/pteros2.0
25de81f39bc8948a37e10e3b389d58ca71195d8d
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/python/compiled_analysis_plugins/box_parallel.cpp
confitarlaburra/pteros2.0
25de81f39bc8948a37e10e3b389d58ca71195d8d
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* * This file is a part of * * ============================================ * ### Pteros molecular modeling library ### * ============================================ * * (C) 2009-2018, Semen Yesylevskyy * * All works, which use Pteros, should cite the following papers: * * 1. Semen O. Yesylevskyy, "Pteros 2.0: Evolution of the fast parallel * molecular analysis library for C++ and python", * Journal of Computational Chemistry, 2015, 36(19), 1480–1488. * doi: 10.1002/jcc.23943. * * 2. Semen O. Yesylevskyy, "Pteros: Fast and easy to use open-source C++ * library for molecular analysis", * Journal of Computational Chemistry, 2012, 33(19), 1632–1636. * doi: 10.1002/jcc.22989. * * This is free software distributed under Artistic License: * http://www.opensource.org/licenses/artistic-license-2.0.php * */ #include "pteros/python/compiled_plugin.h" #include <fstream> #include "spdlog/fmt/fmt.h" using namespace std; using namespace pteros; struct frame_results: public Result_base { Eigen::Vector3f extents; float volume; }; PLUGIN_PARALLEL(box_parallel,frame_results) public: string help(){ return "Purpose:\n" "\tComputes box vectors and box volume for each frame\n" "Output:\n" "\tFile <label>.dat containing the following columns:\n" "\ttime box_a box_b box_c box_volume\n" "Options:\n" "\tNone"; } protected: void pre_process() override { //data.clear(); } void process_frame(const Frame_info &info) override { //data[info.valid_frame] = frame_results{system.Box(0).extents(),system.Box(0).volume()}; } void post_process(const Frame_info &info) override { } }; CREATE_COMPILED_PLUGIN(box_parallel)
26.913043
97
0.6042
confitarlaburra
3dd3c37f0f0095ce5a16fc2bbd023478f50d6855
14,921
hpp
C++
kaluun/parser.hpp
dimitarm/kaluun
1fd73fafcc2853f9cd2cebbc08dafef93e17ea28
[ "MIT" ]
2
2016-09-09T10:36:20.000Z
2017-08-14T02:41:43.000Z
kaluun/parser.hpp
dimitarm/kaluun
1fd73fafcc2853f9cd2cebbc08dafef93e17ea28
[ "MIT" ]
null
null
null
kaluun/parser.hpp
dimitarm/kaluun
1fd73fafcc2853f9cd2cebbc08dafef93e17ea28
[ "MIT" ]
null
null
null
/* * parser.hpp * * Created on: Jun 23, 2015 * Author: dimitar */ #include "template.hpp" #include <ostream> #include <sstream> #include <utility> #include <tuple> #include <typeinfo> #include <vector> #include <algorithm> #include <boost/range.hpp> #include <boost/range/algorithm/find.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/trim.hpp> #include <boost/algorithm/cxx11/all_of.hpp> #include <cctype> #ifndef PARSER_HPP_ #define PARSER_HPP_ namespace kaluun { template<class Template> struct parser { typedef Template templ_type; typedef typename Template::context_type context_type; typedef typename Template::out_type out_type; typedef typename Template::in_type in_type; typedef typename Template::holder_type holder_type; typedef typename templ_type::in_type::const_iterator const_iterator_type; typedef typename Template::expression_type expression_type; typedef typename Template::condition_type condition_type; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct exception: public std::exception { std::string msg_; exception(const in_type& in, const_iterator_type pos, std::string msg) { std::stringstream buf; auto begin = in.begin(); for (int count = 10; pos != begin && count; pos--, count--) { } buf << msg << std::string(": "); for (int count = 20; pos != in.end() && count; pos++, count--) buf << *pos; buf << std::endl; msg_ = buf.str(); } const char* what() const noexcept (true) { return msg_.c_str(); } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// const char OPEN_BRACKET = '{'; const char CLOSE_BRACKET = '}'; const char PERCENT = '%'; const char DIEZ = '#'; const char QUOTE1 = '\x27'; const char QUOTE2 = '\"'; const char WHITE_CHAR = ' '; //tokens const char TOKEN_FOR[3] = { 'f', 'o', 'r' }; const char TOKEN_IN[2] = { 'i', 'n' }; const char TOKEN_ENDFOR[6] = { 'e', 'n', 'd', 'f', 'o', 'r' }; const char TOKEN_IF[2] = { 'i', 'f' }; const char TOKEN_ELIF[4] = { 'e', 'l', 'i', 'f' }; const char TOKEN_ELSE[4] = { 'e', 'l', 's', 'e' }; const char TOKEN_ENDIF[5] = { 'e', 'n', 'd', 'i', 'f' }; const char TOKEN_SET[3] = { 's', 'e', 't' }; in_type& in_; templ_type& tree_; parser(in_type& in, templ_type& template_tree) : in_(in), tree_(template_tree) { } const_iterator_type create_text_node(const_iterator_type pos, node_with_children<context_type, out_type>* cur_level_node) { text_node<context_type, out_type, holder_type>* tx_node = new text_node<context_type, out_type, holder_type>; const_iterator_type begin = pos; bool open_bracket = false; while (pos != in_.end()) { if ((*pos == OPEN_BRACKET || *pos == PERCENT || *pos == DIEZ) && open_bracket) { break; } else if (*pos == OPEN_BRACKET) open_bracket = true; else open_bracket = false; pos++; } if (pos == in_.end()) { holder_type pure_text(begin, pos); tx_node->text_ = std::move(pure_text); } else { holder_type pure_text(begin, pos - 1); tx_node->text_ = std::move(pure_text); } if (tx_node->text_.size() > 0) cur_level_node->add_child(tx_node); else delete tx_node; return pos; } /** * Parse an expression. Returns true if expression has quotation and false otherwise. * If the expression has quotation quoted_str holds the unquoted string * If not expr_str holds the expression */ template<class Holder> bool parse_expression(const_iterator_type& pos, Holder& expr_str, std::string& quoted_str) { bool res = false; while (*pos == WHITE_CHAR and pos != in_.end()) pos++; //skip all white chars if (pos == in_.end()) throw exception(in_, pos, "unexpected end of template"); auto begin = pos; //start of expression auto end = pos; //end of expression //extract variable name int quote = 0; int num_white_chars = 0; for (; pos != in_.end() && (*pos != CLOSE_BRACKET || quote != 0); pos++) { if (quote != 0) { //inside quote if (*pos == quote) quote = 0; else quoted_str += *pos; num_white_chars = 0; //white characters in the tail } else { if (*pos == QUOTE1 || *pos == QUOTE2) { res = true; quoted_str.append(begin, end); //append all unquoted string so far end = begin; //make sure nothing will be added anymore quote = *pos; //will check for corresponding same type of quote } else { if (res) quoted_str += *pos; else end++; if (*pos == WHITE_CHAR) num_white_chars++; else num_white_chars = 0; } } } if (pos == in_.end()) throw exception(in_, pos, "unexpected end of template"); pos++; if (*pos != CLOSE_BRACKET) throw exception(in_, pos, "unexpected symbol"); pos++; if (res) quoted_str.erase(quoted_str.end() - num_white_chars, quoted_str.end()); else expr_str = Holder(begin, end - num_white_chars); return res; } bool parse_expression(const_iterator_type& pos, std::string& expr_str, std::string& quoted_str) { bool res = false; while (*pos == WHITE_CHAR and pos != in_.end()) pos++; //skip all white chars if (pos == in_.end()) throw exception(in_, pos, "unexpected end of template"); //extract variable name int quote = 0; int num_white_chars = 0; for (; pos != in_.end() && (*pos != CLOSE_BRACKET || quote != 0); pos++) { if (quote != 0) { //inside quote if (*pos == quote) quote = 0; else quoted_str += *pos; num_white_chars = 0; //white characters in the tail } else { if (*pos == QUOTE1 || *pos == QUOTE2) { res = true; quoted_str.append(expr_str); //append all unquoted string so far expr_str.clear(); //make sure nothing will be added anymore quote = *pos; //will check for corresponding same type of quote } else { if (res) quoted_str += *pos; else expr_str += *pos; if (*pos == WHITE_CHAR) num_white_chars++; else num_white_chars = 0; } } } if (pos == in_.end()) throw exception(in_, pos, "unexpected end of template"); pos++; if (*pos != CLOSE_BRACKET) throw exception(in_, pos, "unexpected symbol"); pos++; if (res) quoted_str.erase(quoted_str.end() - num_white_chars, quoted_str.end()); else expr_str.erase(expr_str.end() - num_white_chars, expr_str.end()); return res; } const_iterator_type create_variable_node(const_iterator_type pos, node_with_children<context_type, out_type>* cur_level_node) { holder_type expr_text; std::string unquoted_expr_text; node<context_type, out_type>* v_node; if (parse_expression(pos, expr_text, unquoted_expr_text)) { text_node<context_type, out_type, std::string>* node = new text_node<context_type, out_type, std::string>; v_node = node; node->text_ = unquoted_expr_text; } else { if (std::all_of(std::begin(expr_text), std::end(expr_text), [](char ch){ return isalnum(ch) || ch == '.'; })) { //todo use better algorithm to check if variable or not variable_node<context_type, out_type, holder_type>* node = new variable_node<context_type, out_type, holder_type>; v_node = node; node->name_ = expr_text; } else { expression_node<context_type, out_type, expression_type>* ex_node = new expression_node<context_type, out_type, expression_type>; expression_type::parse(expr_text, ex_node->expression_); v_node = ex_node; } } cur_level_node->add_child(v_node); return pos; } const_iterator_type create_comment_node(const_iterator_type pos) { do { while (pos != in_.end() && *pos != DIEZ) pos++; pos++; } while (pos != in_.end() && *pos != CLOSE_BRACKET); pos++; return pos; } node<context_type, out_type>* create_loop_node(boost::iterator_range<const_iterator_type>& var, boost::iterator_range<const_iterator_type>& local_var, node_with_children<context_type, out_type>* cur_level_node) { //for row in rows for_loop_node<context_type, out_type, holder_type>* loop_node = new for_loop_node<context_type, out_type, holder_type>; loop_node->loop_variable_ = holder_type(var.begin(), var.end()); loop_node->local_loop_variable_ = holder_type(local_var.begin(), local_var.end()); cur_level_node->add_child(loop_node); return loop_node; } node_with_children<context_type, out_type>* create_if_condition_node(const_iterator_type expr_begin, const_iterator_type expr_end, bool ifnode, node_with_children<context_type, out_type>* cur_level_node) { //for row in rows holder_type expression_string(expr_begin, expr_end); if_node<context_type, out_type, condition_type>* c_node; if (ifnode) c_node = new if_node<context_type, out_type, condition_type>; else { if_node<context_type, out_type, condition_type>* ifnode = dynamic_cast<if_node<context_type, out_type, condition_type>*>(cur_level_node); if(!ifnode) throw exception(in_, expr_begin, std::string("template error: expected node was if or elif, got: ") + typeid(*cur_level_node).name()); c_node = new elif_node<context_type, out_type, condition_type>; ifnode->else_node_ = c_node; } condition_type::parse(expression_string, c_node->condition_); cur_level_node->add_child(c_node); return c_node; } set_node<context_type, out_type, expression_type, holder_type>* create_set_node(const_iterator_type begin, const_iterator_type end, node_with_children<context_type, out_type>* cur_level_node) { const_iterator_type eq_pos = boost::range::find(boost::make_iterator_range(begin, end), '='); if (eq_pos != end) { auto variable = boost::trim_copy_if(boost::make_iterator_range(begin, eq_pos), boost::is_any_of(" \t")); //variable name auto expression_string = boost::trim_copy_if(boost::make_iterator_range(eq_pos + 1, end), boost::is_any_of(" \t")); //expression string set_node<context_type, out_type, expression_type, holder_type> * node_ptr = new set_node<context_type, out_type, expression_type, holder_type>; node_ptr->variable_name_ = holder_type(variable.begin(), variable.end()); expression_type::parse(holder_type(expression_string.begin(), expression_string.end()), node_ptr->expression_); cur_level_node->add_child(node_ptr); return node_ptr; } else throw exception(in_, begin, "cannot parse set node"); } std::pair<node<context_type, out_type>*, int> create_statement_node(const_iterator_type begin, const_iterator_type end, node_with_children<context_type, out_type>* cur_level_node) { boost::iterator_range<const_iterator_type> node_text(begin, end); std::vector<boost::iterator_range<const_iterator_type> > tokens(5); // Search for tokens boost::split(tokens, node_text, boost::is_any_of(" \t"), boost::token_compress_on); //remove spaces at the beginning and at the end if any if (tokens.back().size() == 0) tokens.erase(tokens.end() - 1); if (tokens.front().size() == 0) tokens.erase(tokens.begin()); //for in if (tokens[0] == TOKEN_FOR && tokens[2] == TOKEN_IN && tokens.size() == 4) return std::make_pair(create_loop_node(tokens[3], tokens[1], cur_level_node), 1); //endfor else if (tokens[0] == TOKEN_ENDFOR && tokens.size() == 1) return std::make_pair(nullptr, -1); //if, elif else if (tokens[0] == TOKEN_IF && tokens.size() > 1) return std::make_pair(create_if_condition_node(tokens[1].begin(), tokens.back().end(), true, cur_level_node), 1); else if (tokens[0] == TOKEN_ELIF && tokens.size() > 1) return std::make_pair(create_if_condition_node(tokens[1].begin(), tokens.back().end(), false, cur_level_node), 1); //else else if (tokens[0] == TOKEN_ELSE && tokens.size() == 1) { if_node<context_type, out_type, condition_type>* ifnode = dynamic_cast<if_node<context_type, out_type, condition_type>*>(cur_level_node); if (ifnode) { node_with_children<context_type, out_type> * else_node = new node_with_children<context_type, out_type>; ifnode->else_node_ = else_node; cur_level_node->add_child(else_node); return std::make_pair(else_node, 1); } else throw exception(in_, begin, std::string("template error: expected node was if or elif, got: ") + typeid(*cur_level_node).name()); } //endif else if (tokens[0] == TOKEN_ENDIF && tokens.size() == 1) { int count = -1; node_with_children<context_type, out_type>* n = cur_level_node; while (typeid(*n) != typeid(if_node<context_type, out_type, condition_type> )) { if (n->parent_ == NULL) throw exception(in_, begin, std::string("not valid template")); n = n->parent_; count--; } return std::make_pair(nullptr, count); } //set else if (tokens[0] == TOKEN_SET) { return std::make_pair(create_set_node(tokens[1].begin(), tokens.back().end(), cur_level_node), 0); } else throw exception(in_, begin, "unknown node"); } static void parse_template(in_type& in, templ_type& template_tree) { parser p(in, template_tree); p.internal_parse(); } void internal_parse() { const_iterator_type pos = in_.begin(); node_with_children<context_type, out_type>* cur_level_node = &tree_.root_; while (pos != in_.end()) { pos = create_text_node(pos, cur_level_node); //text node if (pos == in_.end()) break; if (*pos == OPEN_BRACKET) { //variable node pos++; pos = create_variable_node(pos, cur_level_node); } else if (*pos == PERCENT) { //statement node pos++; const_iterator_type begin = pos; for (; *pos != PERCENT; pos++) { } if (pos == in_.end()) throw exception(in_, pos, std::string("cannot find second open bracket")); node<context_type, out_type> * st_node; int level; std::tie(st_node, level) = create_statement_node(begin, pos, cur_level_node); //if (level == 0) //just add child node - stay on that level //nothing to do. node was added to cur_level_node if (level < 0) { //go as many levels up as necessary while (level < 0) { if (cur_level_node == NULL) throw exception(in_, pos, std::string("not valid template")); cur_level_node = cur_level_node->parent_; level++; } } else if (level == 1) { //add 1 more level if (!dynamic_cast<node_with_children<context_type, out_type>*>(st_node)) throw exception(in_, pos, std::string("node_with_children_expected, got: ") + typeid(*(st_node)).name()); cur_level_node = static_cast<node_with_children<context_type, out_type>*>(st_node); } pos++; if (*pos != CLOSE_BRACKET) throw exception(in_, pos, std::string("cannot find second open bracket")); pos++; } else if (*pos == DIEZ) { //comment node pos++; pos = create_comment_node(pos); } else throw exception(in_, pos, std::string("unexpected symbol")); } if (cur_level_node != &tree_.root_) throw exception(in_, pos, std::string("not valid template")); } private: //utilities }; } #endif /* PARSER_HPP_ */
36.392683
170
0.66765
dimitarm
3dd4ca477e3afdbe065a75f914787087cabd4fcd
5,036
hpp
C++
engine/src/main_check.hpp
Sidharth-S-S/cloe
974ef649e7dc6ec4e6869e4cf690c5b021e5091e
[ "Apache-2.0" ]
20
2020-07-07T18:28:35.000Z
2022-03-21T04:35:28.000Z
engine/src/main_check.hpp
Sidharth-S-S/cloe
974ef649e7dc6ec4e6869e4cf690c5b021e5091e
[ "Apache-2.0" ]
46
2021-01-20T10:13:09.000Z
2022-03-29T12:27:19.000Z
engine/src/main_check.hpp
Sidharth-S-S/cloe
974ef649e7dc6ec4e6869e4cf690c5b021e5091e
[ "Apache-2.0" ]
12
2021-01-25T08:01:24.000Z
2021-07-27T10:09:53.000Z
/* * Copyright 2020 Robert Bosch GmbH * * 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. * * SPDX-License-Identifier: Apache-2.0 */ /** * \file main_check.hpp * \see main.cpp * * This file contains the "check" options and command. */ #pragma once #include <iostream> // for ostream, cout #include <string> // for string #include <vector> // for vector<> #include "main_stack.hpp" // for Stack, StackOptions, new_stack namespace engine { struct CheckOptions { cloe::StackOptions stack_options; std::ostream& output = std::cout; std::string delimiter = ","; // Flags: bool distinct = false; bool summarize = false; bool output_json = false; int json_indent = 2; }; /** * Output nothing in the case that a file is valid, and an error message if * there is a problem. * * This mirrors most closely the standard unix command-line philosophy. */ inline void check_stack(const cloe::StackOptions& opt, const std::vector<std::string>& files, bool* ok = nullptr) { if (ok) { *ok = false; } cloe::Stack s = cloe::new_stack(opt, files); s.check_completeness(); if (ok) { *ok = true; } } /** * Output a summary of its state, ranging from OK to FATAL. * * This is useful for those who want a definitive answer for the input. */ inline std::string check_summary(const CheckOptions& opt, const std::vector<std::string>& files, bool* ok = nullptr) { cloe::StackOptions stack_opt = opt.stack_options; stack_opt.error = boost::none; try { check_stack(stack_opt, files, ok); return "OK"; } catch (cloe::StackIncompleteError& e) { return "INCOMPLETE (" + std::string(e.what()) + ")"; } catch (cloe::ConfError& e) { return "INVALID (" + std::string(e.what()) + ")"; } catch (std::exception& e) { return "ERROR (" + std::string(e.what()) + ")"; } } /** * Output a JSON value of its state, with null returned for ok, and an * error object for each error. */ inline cloe::Json check_json(const CheckOptions& opt, const std::vector<std::string>& files, bool* ok = nullptr) { cloe::StackOptions stack_opt = opt.stack_options; stack_opt.error = boost::none; if (opt.summarize) { return check_summary(opt, files, ok); } else { try { check_stack(stack_opt, files, ok); return nullptr; } catch (cloe::SchemaError& e) { return e; } catch (cloe::ConfError& e) { return e; } catch (std::exception& e) { return cloe::Json{ {"error", e.what()}, }; } } } inline int check_merged(const CheckOptions& opt, const std::vector<std::string>& filepaths) { bool ok = false; if (opt.output_json) { opt.output << check_json(opt, filepaths, &ok).dump(opt.json_indent) << std::endl; } else if (opt.summarize) { opt.output << check_summary(opt, filepaths, &ok) << std::endl; } else { try { check_stack(opt.stack_options, filepaths, &ok); } catch (cloe::ConcludedError&) { } catch (std::exception& e) { opt.output << e.what() << std::endl; } } return ok ? EXIT_SUCCESS : EXIT_FAILURE; } inline int check_distinct(const CheckOptions& opt, const std::vector<std::string>& filepaths) { int exit_code = EXIT_SUCCESS; auto check_each = [&](std::function<void(const std::string&, bool*)> func) { for (const auto& x : filepaths) { bool ok = true; func(x, &ok); if (!ok) { exit_code = EXIT_FAILURE; } } }; if (opt.output_json) { // Output for each file a summary cloe::Json output; check_each([&](const auto& f, bool* ok) { output[f] = check_json(opt, std::vector<std::string>{f}, ok); }); opt.output << output.dump(opt.json_indent) << std::endl; } else if (opt.summarize) { check_each([&](const auto& f, bool* ok) { opt.output << f << ": " << check_summary(opt, std::vector<std::string>{f}, ok) << std::endl; }); } else { check_each([&](const auto& f, bool* ok) { try { check_stack(opt.stack_options, std::vector<std::string>{f}, ok); } catch (cloe::ConcludedError&) { } catch (std::exception& e) { opt.output << f << ": " << e.what() << std::endl; } }); } return exit_code; } inline int check(const CheckOptions& opt, const std::vector<std::string>& filepaths) { if (opt.distinct) { return check_distinct(opt, filepaths); } else { return check_merged(opt, filepaths); } } } // namespace engine
28.292135
98
0.623114
Sidharth-S-S
3dd4d9409d3676ff423e59449739cdc779baf087
2,198
cpp
C++
contact/contact.cpp
anantja-in/usaco
1b680b40cfba18fa4dadf031c39dff3f0f2b7c30
[ "MIT" ]
null
null
null
contact/contact.cpp
anantja-in/usaco
1b680b40cfba18fa4dadf031c39dff3f0f2b7c30
[ "MIT" ]
null
null
null
contact/contact.cpp
anantja-in/usaco
1b680b40cfba18fa4dadf031c39dff3f0f2b7c30
[ "MIT" ]
null
null
null
/* ID: anant901 PROG: contact LANG: C++ */ #include <iostream> #include <fstream> #include <string> #include <map> #include <utility> #include <vector> #include <algorithm> using namespace std; int compare(pair<int, string>& a, pair<int,string>& b){ return a.first > b.first; } int val(string a){ int res = 0; int pow = 1; for(int x=a.length()-1; x>=0; x--){ if(a[x]=='1') res += pow; pow *= 2; } return res; } bool compare_strings(string &a, string &b) { if(a.length() == b.length()) return val(a)<val(b); else return a.length()<b.length(); } string format(string s) { vector <string> strings; string temp=""; for(int x=0; x<s.length(); x++) { if(s[x] == ' ') { strings.push_back(temp); temp = ""; } else { temp += s[x]; } } strings.push_back(temp); sort(strings.begin(), strings.end(), compare_strings); string f=""; for(int x=0; x<strings.size(); x++) { if(x>0){ if(x%6==0){ f+='\n'; } else { f+=' '; } } f+=strings[x]; } return f; } int main() { ofstream fout ("contact.out"); ifstream fin ("contact.in"); int A,B,N; fin>>A>>B>>N; string stream="", line; while(getline(fin, line)) stream += line; map <string,int> freq; for(long x=A-1; x<stream.length(); x++) { for(int y=x-B+1; y<=x-A+1; y++) { if(y<0) continue; // look at stream[y] to stream[x] string temp = stream.substr(y, x-y+1); if(freq.find(temp) != freq.end()) { freq[temp] += 1; } else { freq[temp] = 1; } } } map <int, string> reverse_freq; for(map<string,int>::iterator it=freq.begin(); it!=freq.end(); ++it) { if(reverse_freq.find(it->second) != reverse_freq.end()) { reverse_freq[it->second] += " "; reverse_freq[it->second] += it->first; } else { reverse_freq[it->second] = it->first; } } vector< pair<int,string> > pairs; for(map<int,string>::iterator itr = reverse_freq.begin(); itr!=reverse_freq.end(); ++itr) pairs.push_back(*itr); sort(pairs.begin(), pairs.end(), compare); if(pairs.size()<N) N=pairs.size(); for(int x=0; x<N; x++) { fout<<pairs[x].first<<endl<<format(pairs[x].second)<<endl; } fout.close(); return 0; }
19.113043
91
0.568699
anantja-in
3dda02f59f4eced11592b7858f2f8b49aed73d4f
8,021
cc
C++
art/runtime/base/unix_file/mapped_file_test.cc
CanPisces/DexHunter
b8f46563c7f3aeb79cf40db09e1d231649f1a29a
[ "Apache-2.0" ]
1,306
2015-09-01T05:06:16.000Z
2022-03-10T07:13:10.000Z
art/runtime/base/unix_file/mapped_file_test.cc
cnrat/DexHunter
b8f46563c7f3aeb79cf40db09e1d231649f1a29a
[ "Apache-2.0" ]
11
2015-09-02T09:06:42.000Z
2020-12-26T04:59:34.000Z
art/runtime/base/unix_file/mapped_file_test.cc
cnrat/DexHunter
b8f46563c7f3aeb79cf40db09e1d231649f1a29a
[ "Apache-2.0" ]
598
2015-09-01T05:06:18.000Z
2022-03-27T07:59:49.000Z
/* * Copyright (C) 2008 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 "base/unix_file/mapped_file.h" #include "base/logging.h" #include "base/unix_file/fd_file.h" #include "base/unix_file/random_access_file_test.h" #include "base/unix_file/random_access_file_utils.h" #include "base/unix_file/string_file.h" #include "gtest/gtest.h" namespace unix_file { class MappedFileTest : public RandomAccessFileTest { protected: MappedFileTest() : kContent("some content") { } void SetUp() { art::CommonTest::SetEnvironmentVariables(android_data_); good_path_ = GetTmpPath("some-file.txt"); int fd = TEMP_FAILURE_RETRY(open(good_path_.c_str(), O_CREAT|O_RDWR, 0666)); FdFile dst(fd); StringFile src; src.Assign(kContent); ASSERT_TRUE(CopyFile(src, &dst)); } virtual RandomAccessFile* MakeTestFile() { TEMP_FAILURE_RETRY(truncate(good_path_.c_str(), 0)); MappedFile* f = new MappedFile; CHECK(f->Open(good_path_, MappedFile::kReadWriteMode)); return f; } const std::string kContent; std::string good_path_; }; TEST_F(MappedFileTest, OkayToNotUse) { MappedFile file; EXPECT_EQ(-1, file.Fd()); EXPECT_FALSE(file.IsOpened()); EXPECT_FALSE(file.IsMapped()); } TEST_F(MappedFileTest, OpenClose) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode)); EXPECT_GE(file.Fd(), 0); EXPECT_TRUE(file.IsOpened()); EXPECT_EQ(kContent.size(), file.size()); EXPECT_EQ(0, file.Close()); EXPECT_EQ(-1, file.Fd()); EXPECT_FALSE(file.IsOpened()); } TEST_F(MappedFileTest, OpenFdClose) { FILE* f = tmpfile(); ASSERT_TRUE(f != NULL); MappedFile file(fileno(f)); EXPECT_GE(file.Fd(), 0); EXPECT_TRUE(file.IsOpened()); EXPECT_EQ(0, file.Close()); } TEST_F(MappedFileTest, CanUseAfterMapReadOnly) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode)); EXPECT_FALSE(file.IsMapped()); EXPECT_TRUE(file.MapReadOnly()); EXPECT_TRUE(file.IsMapped()); EXPECT_EQ(kContent.size(), file.size()); ASSERT_TRUE(file.data()); EXPECT_EQ(0, memcmp(kContent.c_str(), file.data(), file.size())); EXPECT_EQ(0, file.Flush()); } TEST_F(MappedFileTest, CanUseAfterMapReadWrite) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode)); EXPECT_FALSE(file.IsMapped()); EXPECT_TRUE(file.MapReadWrite(1)); EXPECT_TRUE(file.IsMapped()); EXPECT_EQ(1, file.size()); ASSERT_TRUE(file.data()); EXPECT_EQ(kContent[0], *file.data()); EXPECT_EQ(0, file.Flush()); } TEST_F(MappedFileTest, CanWriteNewData) { const std::string new_path(GetTmpPath("new-file.txt")); ASSERT_EQ(-1, unlink(new_path.c_str())); ASSERT_EQ(ENOENT, errno); MappedFile file; ASSERT_TRUE(file.Open(new_path, MappedFile::kReadWriteMode)); EXPECT_TRUE(file.MapReadWrite(kContent.size())); EXPECT_TRUE(file.IsMapped()); EXPECT_EQ(kContent.size(), file.size()); ASSERT_TRUE(file.data()); memcpy(file.data(), kContent.c_str(), kContent.size()); EXPECT_EQ(0, file.Close()); EXPECT_FALSE(file.IsMapped()); FdFile new_file(TEMP_FAILURE_RETRY(open(new_path.c_str(), O_RDONLY))); StringFile buffer; ASSERT_TRUE(CopyFile(new_file, &buffer)); EXPECT_EQ(kContent, buffer.ToStringPiece()); EXPECT_EQ(0, unlink(new_path.c_str())); } TEST_F(MappedFileTest, FileMustExist) { const std::string bad_path(GetTmpPath("does-not-exist.txt")); MappedFile file; EXPECT_FALSE(file.Open(bad_path, MappedFile::kReadOnlyMode)); EXPECT_EQ(-1, file.Fd()); } TEST_F(MappedFileTest, FileMustBeWritable) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode)); EXPECT_FALSE(file.MapReadWrite(10)); } TEST_F(MappedFileTest, RemappingAllowedUntilSuccess) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode)); EXPECT_FALSE(file.MapReadWrite(10)); EXPECT_FALSE(file.MapReadWrite(10)); } TEST_F(MappedFileTest, ResizeMappedFile) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode)); ASSERT_TRUE(file.MapReadWrite(10)); EXPECT_EQ(10, file.GetLength()); EXPECT_TRUE(file.Unmap()); EXPECT_TRUE(file.MapReadWrite(20)); EXPECT_EQ(20, file.GetLength()); EXPECT_EQ(0, file.Flush()); EXPECT_TRUE(file.Unmap()); EXPECT_EQ(0, file.Flush()); EXPECT_EQ(0, file.SetLength(5)); EXPECT_TRUE(file.MapReadOnly()); EXPECT_EQ(5, file.GetLength()); } TEST_F(MappedFileTest, ReadNotMapped) { TestRead(); } TEST_F(MappedFileTest, SetLengthNotMapped) { TestSetLength(); } TEST_F(MappedFileTest, WriteNotMapped) { TestWrite(); } TEST_F(MappedFileTest, ReadMappedReadOnly) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode)); ASSERT_TRUE(file.MapReadOnly()); TestReadContent(kContent, &file); } TEST_F(MappedFileTest, ReadMappedReadWrite) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode)); ASSERT_TRUE(file.MapReadWrite(kContent.size())); TestReadContent(kContent, &file); } TEST_F(MappedFileTest, WriteMappedReadWrite) { TEMP_FAILURE_RETRY(unlink(good_path_.c_str())); MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode)); ASSERT_TRUE(file.MapReadWrite(kContent.size())); // Can't write to a negative offset. EXPECT_EQ(-EINVAL, file.Write(kContent.c_str(), 0, -123)); // A zero-length write is a no-op. EXPECT_EQ(0, file.Write(kContent.c_str(), 0, 0)); // But the file size is as given when mapped. EXPECT_EQ(kContent.size(), file.GetLength()); // Data written past the end are discarded. EXPECT_EQ(kContent.size() - 1, file.Write(kContent.c_str(), kContent.size(), 1)); EXPECT_EQ(0, memcmp(kContent.c_str(), file.data() + 1, kContent.size() - 1)); // Data can be overwritten. EXPECT_EQ(kContent.size(), file.Write(kContent.c_str(), kContent.size(), 0)); EXPECT_EQ(0, memcmp(kContent.c_str(), file.data(), kContent.size())); } #if 0 // death tests don't work on android yet class MappedFileDeathTest : public MappedFileTest {}; TEST_F(MappedFileDeathTest, MustMapBeforeUse) { MappedFile file; EXPECT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode)); EXPECT_DEATH(file.data(), "mapped_"); } TEST_F(MappedFileDeathTest, RemappingNotAllowedReadOnly) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode)); ASSERT_TRUE(file.MapReadOnly()); EXPECT_DEATH(file.MapReadOnly(), "mapped_"); } TEST_F(MappedFileDeathTest, RemappingNotAllowedReadWrite) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode)); ASSERT_TRUE(file.MapReadWrite(10)); EXPECT_DEATH(file.MapReadWrite(10), "mapped_"); } TEST_F(MappedFileDeathTest, SetLengthMappedReadWrite) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode)); ASSERT_TRUE(file.MapReadWrite(10)); EXPECT_EQ(10, file.GetLength()); EXPECT_DEATH(file.SetLength(0), ".*"); } TEST_F(MappedFileDeathTest, SetLengthMappedReadOnly) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode)); ASSERT_TRUE(file.MapReadOnly()); EXPECT_EQ(kContent.size(), file.GetLength()); EXPECT_DEATH(file.SetLength(0), ".*"); } TEST_F(MappedFileDeathTest, WriteMappedReadOnly) { MappedFile file; ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode)); ASSERT_TRUE(file.MapReadOnly()); char buf[10]; EXPECT_DEATH(file.Write(buf, 0, 0), ".*"); } #endif } // namespace unix_file
30.154135
80
0.731829
CanPisces
3ddac18b8dea1f584d40151ca4efb8bad8b28d0b
5,812
hpp
C++
src/gui/logind_session_lnx.hpp
CoSoSys/cppdevtk
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/gui/logind_session_lnx.hpp
CoSoSys/cppdevtk
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/gui/logind_session_lnx.hpp
CoSoSys/cppdevtk
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// \file /// /// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <info@cososys.com>\n /// Licensed under the Apache License, Version 2.0 (the "License");\n /// you may not use this file except in compliance with the License.\n /// You may obtain a copy of the License at\n /// http://www.apache.org/licenses/LICENSE-2.0\n /// Unless required by applicable law or agreed to in writing, software\n /// distributed under the License is distributed on an "AS IS" BASIS,\n /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n /// See the License for the specific language governing permissions and\n /// limitations under the License.\n /// Please see the file COPYING. /// /// \authors Cristian ANITA <cristian.anita@cososys.com>, <cristian_anita@yahoo.com> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef CPPDEVTK_GUI_LOGIND_SESSION_LNX_HPP_INCLUDED_ #define CPPDEVTK_GUI_LOGIND_SESSION_LNX_HPP_INCLUDED_ #include <cppdevtk/gui/config.hpp> #if (!CPPDEVTK_PLATFORM_LINUX) # error "This file is Linux specific!!!" #endif #if (CPPDEVTK_PLATFORM_ANDROID) # error "This file is not for Android!!!" #endif #include "session_impl_lnx.hpp" #include <cppdevtk/util/dbus_utils.hpp> #include <QtCore/QStringList> #include <QtCore/QVariant> #include <QtCore/QVariantMap> #include <QtDBus/QDBusObjectPath> #include <QtDBus/QDBusInterface> namespace cppdevtk { namespace gui { namespace detail { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// \sa <a href=https://www.freedesktop.org/wiki/Software/systemd/logind">logind Session</a> /// \note All functions, except slots and destructor, may throw DBusException /// \attention Tested and Locked()/Unlocked() signals: /// - are not emitted when Lock/Unlock from DE (tested with KDE); screensaver signals are emitted. /// - are emitted when Lock()/Unlock() method are called /// - verify: dbus-monitor --monitor --system "type='signal',sender='org.freedesktop.login1',interface='org.freedesktop.login1.Session',path='/org/freedesktop/login1/session/_32'" class LogindSession: public Session::Impl { friend class ::cppdevtk::gui::Session; friend class LogindManager; Q_OBJECT public: virtual ~LogindSession(); virtual bool Activate(); // On Ubuntu 14.04 fails with org.freedesktop.DBus.Error.AccessDenied // TODO: report bug virtual bool Lock(); virtual bool Unlock(); virtual QString GetId() const; virtual bool GetIdleHint() const; virtual Session::IdleTime GetIdleSinceHint() const; virtual QString GetType() const; virtual uint GetUser() const; virtual QString GetRemoteHost() const; virtual bool IsActive() const; virtual bool IsRemote() const; bool operator==(const LogindSession& other) const; bool operator!=(const LogindSession& other) const; static bool IsLogindServiceRegistered(); private Q_SLOTS: void OnDBusPropertiesChanged(const QString& interfaceName, const QVariantMap& changedProperties, const QStringList& invalidatedProperties); private: Q_DISABLE_COPY(LogindSession) explicit LogindSession(const QDBusObjectPath& logindSessionPath); qulonglong DoGetIdleSinceHint() const; mutable QDBusInterface logindSessionPropertiesInterface_; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Inline functions inline QString LogindSession::GetId() const { const QDBusInterface& kDBusInterface = DBusInterfaceRef(); return util::GetDBusStringProperty(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()), kDBusInterface.interface(), kDBusInterface.connection(), "Id"); } inline QString LogindSession::GetType() const { const QDBusInterface& kDBusInterface = DBusInterfaceRef(); return util::GetDBusStringProperty(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()), kDBusInterface.interface(), kDBusInterface.connection(), "Type"); } inline uint LogindSession::GetUser() const { const QDBusInterface& kDBusInterface = DBusInterfaceRef(); return util::GetDBusUInt32Property(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()), kDBusInterface.interface(), kDBusInterface.connection(), "User"); } inline QString LogindSession::GetRemoteHost() const { const QDBusInterface& kDBusInterface = DBusInterfaceRef(); return util::GetDBusStringProperty(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()), kDBusInterface.interface(), kDBusInterface.connection(), "RemoteHost"); } inline bool LogindSession::IsActive() const { const QDBusInterface& kDBusInterface = DBusInterfaceRef(); return util::GetDBusBooleanProperty(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()), kDBusInterface.interface(), kDBusInterface.connection(), "Active"); } inline bool LogindSession::IsRemote() const { const QDBusInterface& kDBusInterface = DBusInterfaceRef(); return util::GetDBusBooleanProperty(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()), kDBusInterface.interface(), kDBusInterface.connection(), "Remote"); } inline bool LogindSession::operator==(const LogindSession& other) const { return GetId() == other.GetId(); } inline bool LogindSession::operator!=(const LogindSession& other) const { return GetId() != other.GetId(); } } // namespace detail } // namespace gui } // namespace cppdevtk #endif // CPPDEVTK_GUI_LOGIND_SESSION_LNX_HPP_INCLUDED_
37.986928
180
0.682725
CoSoSys
3ddbaa2d7749a946d533e6e07fa4456bdf001396
234
cpp
C++
Engine/Source/Color.cpp
Denisdrk6/ProjectIII
89634bcf4a3520ba78158dff50aee568089968cb
[ "MIT" ]
7
2022-02-16T12:09:19.000Z
2022-03-14T15:59:48.000Z
Engine/Source/Color.cpp
Denisdrk6/Dune-Fremen-s-Rising
89634bcf4a3520ba78158dff50aee568089968cb
[ "MIT" ]
1
2022-03-18T19:46:23.000Z
2022-03-18T19:46:23.000Z
Engine/Source/Color.cpp
Denisdrk6/Dune-Fremen-s-Rising
89634bcf4a3520ba78158dff50aee568089968cb
[ "MIT" ]
1
2022-02-20T19:49:09.000Z
2022-02-20T19:49:09.000Z
#include "Color.h" #include "Profiling.h" Color red = Color(1.0f, 0.0f, 0.0f); Color green = Color(0.0f, 1.0f, 0.0f); Color blue = Color(0.0f, 0.0f, 1.0f); Color black = Color(0.0f, 0.0f, 0.0f); Color white = Color(1.0f, 1.0f, 1.0f);
29.25
38
0.628205
Denisdrk6
3de170da2c63cee6ebe2b839d9a4196efaa7e167
1,336
hpp
C++
include/blokus/ai/logic.hpp
sunfl0w/CPP_HokusBlokus
aedb8d42143cce9fe2b7107ce4f6d15ef76dc58c
[ "MIT" ]
1
2020-09-04T16:35:38.000Z
2020-09-04T16:35:38.000Z
include/blokus/ai/logic.hpp
sunfl0w/CPP_HokusBlokus
aedb8d42143cce9fe2b7107ce4f6d15ef76dc58c
[ "MIT" ]
null
null
null
include/blokus/ai/logic.hpp
sunfl0w/CPP_HokusBlokus
aedb8d42143cce9fe2b7107ce4f6d15ef76dc58c
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <random> #include <iostream> #include "gameState.hpp" #include "move.hpp" #include "player.hpp" #include "color.hpp" #include "logger.hpp" namespace HokusBlokus::Blokus::AI { /** * @brief This class defines some virtual methods for creating AIs for the game of Blokus. * One can inherit from this class to create a new logic. * */ class Logic { public: /** * @brief Constructs a new Logic. * */ Logic(); /** * @brief Destroys a Logic. * */ virtual ~Logic(); /** * @brief Gets the next Move to play. In this method the AI hast to be implemented. * * @param currentGameState The GameState to get the next Move for. * @param ownPlayerID The ID of the Player that is played by the AI. * @return The next move that should be played. */ virtual HokusBlokus::Blokus::Move GetNextMove(HokusBlokus::Blokus::GameState currentGameState, int ownPlayerID); /** * @brief Will be executed when a game of Blokus ends. * * @param winningPlayerID The ID of the Player that won. */ virtual void OnGameEnd(int winningPlayerID); }; } // namespace Piranhas::Logic
27.265306
120
0.589072
sunfl0w
3de36dc5c4b8cba188c1f118d9c6432d64853f12
3,070
cc
C++
onnxruntime/test/optimizer/rule_based_graph_transformer_test.cc
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
5
2021-02-20T04:53:48.000Z
2021-03-09T19:29:27.000Z
onnxruntime/test/optimizer/rule_based_graph_transformer_test.cc
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
17
2020-07-21T11:13:27.000Z
2022-03-27T02:37:05.000Z
onnxruntime/test/optimizer/rule_based_graph_transformer_test.cc
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
2
2020-05-21T20:08:25.000Z
2021-04-19T10:39:13.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/graph/graph_viewer.h" #include "core/graph/model.h" #include "core/optimizer/graph_transformer.h" #include "core/optimizer/graph_transformer_mgr.h" #include "test/framework/test_utils.h" #include "test/test_environment.h" #include "gtest/gtest.h" #include "core/optimizer/rule_based_graph_transformer.h" #include "dummy_graph_transformer.h" using namespace std; using namespace ONNX_NAMESPACE; namespace onnxruntime { namespace test { TEST(RuleBasedGraphTransformerTest, TestCompatibleProviders) { auto model_uri = ORT_TSTR("testdata/transform/fusion/fuse-conv-bn-mul-add-unsqueeze.onnx"); std::shared_ptr<Model> model; ASSERT_TRUE(Model::Load(model_uri, model, nullptr, DefaultLoggingManager().DefaultLogger()) .IsOK()); Graph& graph = model->MainGraph(); // Create rule based transformer with a dummy rewrite rule and register it with Cuda as compatible provider std::unordered_set<std::string> compatible_provider{onnxruntime::kCudaExecutionProvider}; auto dummy_rule = onnxruntime::make_unique<DummyRewriteRule>("DummyRule"); const auto* dummy_rule_ptr = dummy_rule.get(); auto graph_transformer = onnxruntime::make_unique<RuleBasedGraphTransformer>("CUDATopDownTransformer", compatible_provider); graph_transformer->Register(std::move(dummy_rule)); // Create rule based transformer with a dummy rewrite rule and register it with CPU as compatible provider auto dummy_rule1 = onnxruntime::make_unique<DummyRewriteRule>("DummyRule1"); const auto* dummy_rule1_ptr = dummy_rule1.get(); auto graph_transformer1 = onnxruntime::make_unique<RuleBasedGraphTransformer>("CPUTopDownTransformer"); graph_transformer1->Register(std::move(dummy_rule1)); onnxruntime::GraphTransformerManager graph_transformation_mgr{5}; graph_transformation_mgr.Register(std::move(graph_transformer), TransformerLevel::Level2); graph_transformation_mgr.Register(std::move(graph_transformer1), TransformerLevel::Level2); graph_transformation_mgr.ApplyTransformers(graph, TransformerLevel::Level2, DefaultLoggingManager().DefaultLogger()); // Validate transformer registered with CUDA as compatible provider is not called. ASSERT_FALSE(dummy_rule_ptr->IsRewriteRuleInvoked()); // Validate transformer registered as global is called. ASSERT_TRUE(dummy_rule1_ptr->IsRewriteRuleInvoked()); } TEST(RuleBasedGraphTransformerTest, TestSettingStepsInGraphTransformerManager) { // steps provided at object construction time onnxruntime::GraphTransformerManager graph_transformation_mgr{5}; unsigned steps_queried; graph_transformation_mgr.GetSteps(steps_queried); ASSERT_EQ(steps_queried, static_cast<unsigned>(5)); // steps upadted graph_transformation_mgr.SetSteps(10); graph_transformation_mgr.GetSteps(steps_queried); ASSERT_EQ(steps_queried, static_cast<unsigned> (10)); } } // namespace test } // namespace onnxruntime
42.638889
126
0.780782
dennyac
3de3f318da6b1e6d8388c4dfd36caed2720b60e0
2,950
cpp
C++
breakpad_wrapper.cpp
lgirdk/breakpad-wrapper
5df474a3be17ca3f7289829b48a6da78e915554d
[ "Apache-2.0" ]
null
null
null
breakpad_wrapper.cpp
lgirdk/breakpad-wrapper
5df474a3be17ca3f7289829b48a6da78e915554d
[ "Apache-2.0" ]
null
null
null
breakpad_wrapper.cpp
lgirdk/breakpad-wrapper
5df474a3be17ca3f7289829b48a6da78e915554d
[ "Apache-2.0" ]
2
2018-08-16T20:50:29.000Z
2020-08-19T00:15:32.000Z
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2017 RDK Management * * 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 "breakpad_wrapper.h" #include "client/linux/handler/exception_handler.h" #include <stdio.h> static bool breakpadDumpCallback(const google_breakpad::MinidumpDescriptor& descriptor, void* context, bool succeeded) { /* Do the desired exit process here*/ #ifdef _DEBUG_ printf("breakpad Call back .................................................."); printf("Print descriptor path: %s\n", descriptor.path()); #endif return succeeded; } void breakpad_ExceptionHandler() { #ifdef _DEBUG_ printf("\t\t\t\t ********ENTER breakpad_ExceptionHandler****************** \n"); #endif static google_breakpad::ExceptionHandler* excHandler = NULL; #ifdef MINIDUMP_RDKV const char *minidump_path = "/opt/secure/minidumps"; FILE *fp; if(( fp = fopen("/tmp/.SecureDumpDisable", "r")) != NULL) { // "RFC Settings for SecureDump is : false minidump_path = "/opt/minidumps"; fclose(fp); } #endif if (excHandler) { #ifdef _DEBUG_ printf("Handler exist \n"); #endif return ; } #ifdef MINIDUMP_RDKV const char* breakpadFd = getenv("BREAKPAD_FD"); if (breakpadFd) { google_breakpad::MinidumpDescriptor descriptor(atoi(breakpadFd)); excHandler = new google_breakpad::ExceptionHandler(descriptor, NULL, breakpadDumpCallback, NULL, true, -1); } else { google_breakpad::MinidumpDescriptor descriptor(minidump_path); excHandler = new google_breakpad::ExceptionHandler(descriptor, NULL, breakpadDumpCallback, NULL, true, -1); } #else excHandler = new google_breakpad::ExceptionHandler(google_breakpad::MinidumpDescriptor("/minidumps"), NULL, breakpadDumpCallback, NULL, true, -1); #endif #ifdef _DEBUG_ printf("\t\t\t\t ******** breakpad_ExceptionHandler EXIT****************** \n"); #endif } #ifdef MINIDUMP_RDKV void __attribute__ ((constructor)) breakpad_autoconstruct(void) { breakpad_ExceptionHandler(); } #endif
32.777778
147
0.626102
lgirdk
3de67ac7a4b63b7c9d67d2d2ac6d85223f0a8b12
53,170
cpp
C++
src/core/blocks/chains.cpp
fragcolor-xyz/chainblocks
bf83f8dc8f46637bc42713d1fa77e81228ddfccf
[ "BSD-3-Clause" ]
12
2021-07-11T11:14:14.000Z
2022-03-28T11:37:29.000Z
src/core/blocks/chains.cpp
fragcolor-xyz/chainblocks
bf83f8dc8f46637bc42713d1fa77e81228ddfccf
[ "BSD-3-Clause" ]
103
2021-06-26T17:09:43.000Z
2022-03-30T12:05:18.000Z
src/core/blocks/chains.cpp
fragcolor-xyz/chainblocks
bf83f8dc8f46637bc42713d1fa77e81228ddfccf
[ "BSD-3-Clause" ]
8
2021-07-27T14:45:26.000Z
2022-03-01T08:07:18.000Z
/* SPDX-License-Identifier: BSD-3-Clause */ /* Copyright © 2019 Fragcolor Pte. Ltd. */ #include "foundation.hpp" #include "shared.hpp" #include <chrono> #include <memory> #include <set> #if !defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__) #include <taskflow/taskflow.hpp> #endif namespace chainblocks { enum RunChainMode { Inline, Detached, Stepped }; struct ChainBase { typedef EnumInfo<RunChainMode> RunChainModeInfo; static inline RunChainModeInfo runChainModeInfo{"RunChainMode", CoreCC, 'runC'}; static inline Type ModeType{ {CBType::Enum, {.enumeration = {.vendorId = CoreCC, .typeId = 'runC'}}}}; static inline Types ChainTypes{ {CoreInfo::ChainType, CoreInfo::StringType, CoreInfo::NoneType}}; static inline Types ChainVarTypes{ChainTypes, {CoreInfo::ChainVarType}}; static inline Parameters waitParamsInfo{ {"Chain", CBCCSTR("The chain to wait."), {ChainVarTypes}}, {"Passthrough", CBCCSTR("The output of this block will be its input."), {CoreInfo::BoolType}}}; static inline Parameters stopChainParamsInfo{ {"Chain", CBCCSTR("The chain to stop."), {ChainVarTypes}}, {"Passthrough", CBCCSTR("The output of this block will be its input."), {CoreInfo::BoolType}}}; static inline Parameters runChainParamsInfo{ {"Chain", CBCCSTR("The chain to run."), {ChainTypes}}}; ParamVar chainref{}; std::shared_ptr<CBChain> chain; bool passthrough{false}; RunChainMode mode{RunChainMode::Inline}; CBComposeResult chainValidation{}; IterableExposedInfo exposedInfo{}; void destroy() { chainblocks::arrayFree(chainValidation.requiredInfo); chainblocks::arrayFree(chainValidation.exposedInfo); } static CBTypesInfo inputTypes() { return CoreInfo::AnyType; } static CBTypesInfo outputTypes() { return CoreInfo::AnyType; } std::unordered_set<const CBChain *> &gatheringChains() { #ifdef WIN32 // we have to leak.. or windows tls emulation will crash at process end thread_local std::unordered_set<const CBChain *> *chains = new std::unordered_set<const CBChain *>(); return *chains; #else thread_local std::unordered_set<const CBChain *> chains; return chains; #endif } CBTypeInfo compose(const CBInstanceData &data) { // Free any previous result! arrayFree(chainValidation.requiredInfo); arrayFree(chainValidation.exposedInfo); // Actualize the chain here, if we are deserialized // chain might already be populated! if (!chain) { if (chainref->valueType == CBType::Chain) { chain = CBChain::sharedFromRef(chainref->payload.chainValue); } else if (chainref->valueType == String) { chain = GetGlobals().GlobalChains[chainref->payload.stringValue]; } else { chain = nullptr; CBLOG_DEBUG("ChainBase::compose on a null chain"); } } // Easy case, no chain... if (!chain) return data.inputType; assert(data.chain); if (chain.get() == data.chain) { CBLOG_DEBUG( "ChainBase::compose early return, data.chain == chain, name: {}", chain->name); return data.inputType; // we don't know yet... } chain->node = data.chain->node; auto node = data.chain->node.lock(); assert(node); // TODO FIXME, chainloader/chain runner might access this from threads if (node->visitedChains.count(chain.get())) { // TODO FIXME, we need to verify input and shared here... // but visited does not mean composed... return node->visitedChains[chain.get()]; } // avoid stackoverflow if (chain->isRoot || gatheringChains().count(chain.get())) { CBLOG_DEBUG( "ChainBase::compose early return, chain is being visited, name: {}", chain->name); return data.inputType; // we don't know yet... } CBLOG_TRACE("ChainBase::compose, source: {} composing: {} inputType: {}", data.chain->name, chain->name, data.inputType); // we can add early in this case! // useful for Resume/Start if (passthrough) { auto [_, done] = node->visitedChains.emplace(chain.get(), data.inputType); if (done) { CBLOG_TRACE("Pre-Marking as composed: {} ptr: {}", chain->name, (void *)chain.get()); } } else if (mode == Stepped) { auto [_, done] = node->visitedChains.emplace(chain.get(), CoreInfo::AnyType); if (done) { CBLOG_TRACE("Pre-Marking as composed: {} ptr: {}", chain->name, (void *)chain.get()); } } // and the subject here gatheringChains().insert(chain.get()); DEFER(gatheringChains().erase(chain.get())); auto dataCopy = data; dataCopy.chain = chain.get(); IterableExposedInfo shared(data.shared); IterableExposedInfo sharedCopy; if (mode == RunChainMode::Detached) { // keep only globals auto end = std::remove_if(shared.begin(), shared.end(), [](const CBExposedTypeInfo &x) { return !x.global; }); sharedCopy = IterableExposedInfo(shared.begin(), end); } else { // we allow Detached but they need to be referenced during warmup sharedCopy = shared; } dataCopy.shared = sharedCopy; CBTypeInfo chainOutput; // make sure to compose only once... if (chain->composedHash.valueType == None) { CBLOG_TRACE("Running {} compose", chain->name); chainValidation = composeChain( chain.get(), [](const CBlock *errorBlock, const char *errorTxt, bool nonfatalWarning, void *userData) { if (!nonfatalWarning) { CBLOG_ERROR("RunChain: failed inner chain validation, error: {}", errorTxt); throw ComposeError("RunChain: failed inner chain validation"); } else { CBLOG_INFO("RunChain: warning during inner chain validation: {}", errorTxt); } }, this, dataCopy); chain->composedHash = Var(1, 1); // no need to hash properly here chainOutput = chainValidation.outputType; IterableExposedInfo exposing(chainValidation.exposedInfo); // keep only globals exposedInfo = IterableExposedInfo( exposing.begin(), std::remove_if(exposing.begin(), exposing.end(), [](CBExposedTypeInfo &x) { return !x.global; })); CBLOG_TRACE("Chain {} composed", chain->name); } else { CBLOG_TRACE("Skipping {} compose", chain->name); // verify input type if (!passthrough && mode != Stepped && data.inputType != chain->inputType) { CBLOG_ERROR("Previous chain composed type {} requested call type {}", *chain->inputType, data.inputType); throw ComposeError("Attempted to call an already composed chain with a " "different input type! chain: " + chain->name); } // write output type chainOutput = chain->outputType; // ensure requirements match our input data for (auto req : chain->requiredVariables) { // find each in shared auto res = std::find_if(shared.begin(), shared.end(), [&](CBExposedTypeInfo &x) { std::string_view vx(x.name); return req == vx; }); if (res == shared.end()) { throw ComposeError("Attempted to call an already composed chain (" + chain->name + ") with " "a missing required variable: " + req); } } } auto outputType = data.inputType; if (!passthrough) { if (mode == Inline) outputType = chainOutput; else if (mode == Stepped) outputType = CoreInfo::AnyType; // unpredictable else outputType = data.inputType; } if (!passthrough && mode != Stepped) { auto [_, done] = node->visitedChains.emplace(chain.get(), outputType); if (done) { CBLOG_TRACE( "Marking as composed: {} ptr: {} inputType: {} outputType: {}", chain->name, (void *)chain.get(), *chain->inputType, chain->outputType); } } return outputType; } void cleanup() { chainref.cleanup(); } void warmup(CBContext *ctx) { chainref.warmup(ctx); } // Use state to mark the dependency for serialization as well! CBVar getState() { if (chain) { return Var(chain); } else { CBLOG_TRACE("getState no chain was avail"); return Var::Empty; } } void setState(CBVar state) { if (state.valueType == CBType::Chain) { chain = CBChain::sharedFromRef(state.payload.chainValue); } } }; struct Wait : public ChainBase { CBOptionalString help() { return CBCCSTR("Waits for another chain to complete before resuming " "execution of the current chain."); } // we don't need OwnedVar here // we keep the chain referenced! CBVar _output{}; CBExposedTypeInfo _requiredChain{}; void cleanup() { if (chainref.isVariable()) chain = nullptr; ChainBase::cleanup(); } static CBParametersInfo parameters() { return waitParamsInfo; } void setParam(int index, const CBVar &value) { switch (index) { case 0: chainref = value; break; case 1: passthrough = value.payload.boolValue; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return chainref; case 1: return Var(passthrough); default: return Var::Empty; } } CBExposedTypesInfo requiredVariables() { if (chainref.isVariable()) { _requiredChain = CBExposedTypeInfo{chainref.variableName(), CBCCSTR("The chain to run."), CoreInfo::ChainType}; return {&_requiredChain, 1, 0}; } else { return {}; } } CBVar activate(CBContext *context, const CBVar &input) { if (unlikely(!chain && chainref.isVariable())) { auto vchain = chainref.get(); if (vchain.valueType == CBType::Chain) { chain = CBChain::sharedFromRef(vchain.payload.chainValue); } else if (vchain.valueType == String) { chain = GetGlobals().GlobalChains[vchain.payload.stringValue]; } else { chain = nullptr; } } if (unlikely(!chain)) { CBLOG_WARNING("Wait's chain is void"); return input; } else { while (isRunning(chain.get())) { CB_SUSPEND(context, 0); } if (chain->finishedError.size() > 0) { // if the chain has errors we need to propagate them // we can avoid interruption using Maybe blocks throw ActivationError(chain->finishedError); } if (passthrough) { return input; } else { // no clone _output = chain->finishedOutput; return _output; } } } }; struct StopChain : public ChainBase { CBOptionalString help() { return CBCCSTR( "Stops another chain. If no chain is given, stops the current chain."); } void setup() { passthrough = true; } OwnedVar _output{}; CBExposedTypeInfo _requiredChain{}; CBTypeInfo _inputType{}; CBTypeInfo compose(const CBInstanceData &data) { _inputType = data.inputType; ChainBase::compose(data); return data.inputType; } void composed(const CBChain *chain, const CBComposeResult *result) { if (!chain && chainref->valueType == None && _inputType != result->outputType) { CBLOG_ERROR("Stop input and chain output type mismatch, Stop input must " "be the same type of the chain's output (regular flow), " "chain: {} expected: {}", chain->name, chain->outputType); throw ComposeError("Stop input and chain output type mismatch"); } } void cleanup() { if (chainref.isVariable()) chain = nullptr; ChainBase::cleanup(); } static CBParametersInfo parameters() { return stopChainParamsInfo; } void setParam(int index, const CBVar &value) { switch (index) { case 0: chainref = value; break; case 1: passthrough = value.payload.boolValue; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return chainref; case 1: return Var(passthrough); default: return Var::Empty; } } CBExposedTypesInfo requiredVariables() { if (chainref.isVariable()) { _requiredChain = CBExposedTypeInfo{chainref.variableName(), CBCCSTR("The chain to run."), CoreInfo::ChainType}; return {&_requiredChain, 1, 0}; } else { return {}; } } CBVar activate(CBContext *context, const CBVar &input) { if (unlikely(!chain && chainref.isVariable())) { auto vchain = chainref.get(); if (vchain.valueType == CBType::Chain) { chain = CBChain::sharedFromRef(vchain.payload.chainValue); } else if (vchain.valueType == String) { chain = GetGlobals().GlobalChains[vchain.payload.stringValue]; } else { chain = nullptr; } } if (unlikely(!chain)) { // in this case we stop the current chain context->stopFlow(input); return input; } else { chainblocks::stop(chain.get()); if (passthrough) { return input; } else { _output = chain->finishedOutput; return _output; } } } }; struct Resume : public ChainBase { static CBOptionalString help() { return CBCCSTR("Resumes a given chain and suspends the current one. In " "other words, switches flow execution to another chain."); } void setup() { // we use those during ChainBase::compose passthrough = true; mode = Detached; } static inline Parameters params{ {"Chain", CBCCSTR("The name of the chain to switch to."), {ChainTypes}}}; static CBParametersInfo parameters() { return params; } static CBTypesInfo inputTypes() { return CoreInfo::AnyType; } static CBTypesInfo outputTypes() { return CoreInfo::AnyType; } CBTypeInfo compose(const CBInstanceData &data) { ChainBase::compose(data); return data.inputType; } void setParam(int index, const CBVar &value) { chainref = value; } CBVar getParam(int index) { return chainref; } // NO cleanup, other chains reference this chain but should not stop it // An arbitrary chain should be able to resume it! // Cleanup mechanics still to figure, for now ref count of the actual chain // symbol, TODO maybe use CBVar refcount! CBVar activate(CBContext *context, const CBVar &input) { auto current = context->chainStack.back(); auto pchain = [&] { if (!chain) { if (current->resumer) { return current->resumer; } else { throw ActivationError("Resume, chain not found."); } } else { return chain.get(); } }(); // assign the new chain as current chain on the flow context->flow->chain = pchain; // Allow to re run chains if (chainblocks::hasEnded(pchain)) { chainblocks::stop(pchain); } // Prepare if no callc was called if (!pchain->coro) { pchain->node = context->main->node; chainblocks::prepare(pchain, context->flow); } // we should be valid as this block should be dependent on current // do this here as stop/prepare might overwrite pchain->resumer = current; // Start it if not started if (!chainblocks::isRunning(pchain)) { chainblocks::start(pchain, input); } // And normally we just delegate the CBNode + CBFlow // the following will suspend this current chain // and in node tick when re-evaluated tick will // resume with the chain we just set above! chainblocks::suspend(context, 0); return input; } }; struct Start : public Resume { static CBOptionalString help() { return CBCCSTR("Starts a given chain and suspends the current one. In " "other words, switches flow execution to another chain."); } CBVar activate(CBContext *context, const CBVar &input) { auto current = context->chainStack.back(); auto pchain = [&] { if (!chain) { if (current->resumer) { return current->resumer; } else { throw ActivationError("Resume, chain not found."); } } else { return chain.get(); } }(); // assign the new chain as current chain on the flow context->flow->chain = pchain; // ensure chain is not running, we start from top chainblocks::stop(pchain); // Prepare pchain->node = context->main->node; chainblocks::prepare(pchain, context->flow); // we should be valid as this block should be dependent on current // do this here as stop/prepare might overwrite pchain->resumer = current; // Start chainblocks::start(pchain, input); // And normally we just delegate the CBNode + CBFlow // the following will suspend this current chain // and in node tick when re-evaluated tick will // resume with the chain we just set above! chainblocks::suspend(context, 0); return input; } }; struct Recur : public ChainBase { static CBTypesInfo inputTypes() { return CoreInfo::AnyType; } static CBTypesInfo outputTypes() { return CoreInfo::AnyType; } CBTypeInfo compose(const CBInstanceData &data) { // set current chain as `chain` _wchain = data.chain->shared_from_this(); // find all variables to store in current chain // use vector in the end.. cos slightly faster for (auto &shared : data.shared) { if (shared.scope == data.chain) { CBVar ctxVar{}; ctxVar.valueType = ContextVar; ctxVar.payload.stringValue = shared.name; auto &p = _vars.emplace_back(); p = ctxVar; } } _len = _vars.size(); return ChainBase::compose(data); } void warmup(CBContext *ctx) { _storage.resize(_len); for (auto &v : _vars) { v.warmup(ctx); } auto schain = _wchain.lock(); assert(schain); _chain = schain.get(); } void cleanup() { for (auto &v : _vars) { v.cleanup(); } // force releasing resources for (size_t i = 0; i < _len; i++) { // must release on capacity for (uint32_t j = 0; j < _storage[i].cap; j++) { destroyVar(_storage[i].elements[j]); } arrayFree(_storage[i]); } _storage.resize(0); } CBVar activate(CBContext *context, const CBVar &input) { // store _vars for (size_t i = 0; i < _len; i++) { const auto len = _storage[i].len; arrayResize(_storage[i], len + 1); cloneVar(_storage[i].elements[len], _vars[i].get()); } // (Do self) // Run within the root flow auto runRes = runSubChain(_chain, context, input); if (unlikely(runRes.state == Failed)) { // meaning there was an exception while // running the sub chain, stop the parent too context->stopFlow(runRes.output); } // restore _vars for (size_t i = 0; i < _len; i++) { auto pops = arrayPop<CBSeq, CBVar>(_storage[i]); cloneVar(_vars[i].get(), pops); } return runRes.output; } std::weak_ptr<CBChain> _wchain; CBChain *_chain; std::deque<ParamVar> _vars; size_t _len; // cache it to have nothing on stack from us std::vector<CBSeq> _storage; }; struct BaseRunner : public ChainBase { // Only chain runners should expose varaibles to the context CBExposedTypesInfo exposedVariables() { // Only inline mode ensures that variables will be really avail // step and detach will run at different timing CBExposedTypesInfo empty{}; return mode == RunChainMode::Inline ? CBExposedTypesInfo(exposedInfo) : empty; } void cleanup() { if (chain) { if (mode == RunChainMode::Inline && chain->chainUsers.count(this) != 0) { chain->chainUsers.erase(this); chain->cleanup(); } else { chainblocks::stop(chain.get()); } } ChainBase::cleanup(); } void doWarmup(CBContext *context) { if (mode == RunChainMode::Inline && chain && chain->chainUsers.count(this) == 0) { chain->chainUsers.emplace(this); chain->warmup(context); } } void activateDetached(CBContext *context, const CBVar &input) { if (!chainblocks::isRunning(chain.get())) { // validated during infer not here! (false) auto node = context->main->node.lock(); if (node) node->schedule(chain, input, false); } } void activateStepMode(CBContext *context, const CBVar &input) { // Allow to re run chains if (chainblocks::hasEnded(chain.get())) { // stop the root if (!chainblocks::stop(chain.get())) { throw ActivationError("Stepped sub-chain did not end normally."); } } // Prepare if no callc was called if (!chain->coro) { chain->node = context->main->node; // pre-set chain context with our context // this is used to copy chainStack over to the new one chain->context = context; // Notice we don't share our flow! // let the chain create one by passing null chainblocks::prepare(chain.get(), nullptr); } // Starting if (!chainblocks::isRunning(chain.get())) { chainblocks::start(chain.get(), input); } // Tick the chain on the flow that this Step chain created CBDuration now = CBClock::now().time_since_epoch(); chainblocks::tick(chain->context->flow->chain, now, input); } }; template <bool INPUT_PASSTHROUGH, RunChainMode CHAIN_MODE> struct RunChain : public BaseRunner { void setup() { passthrough = INPUT_PASSTHROUGH; mode = CHAIN_MODE; } static CBParametersInfo parameters() { return runChainParamsInfo; } void setParam(int index, const CBVar &value) { switch (index) { case 0: chainref = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return chainref; default: break; } return Var::Empty; } void warmup(CBContext *context) { ChainBase::warmup(context); doWarmup(context); } CBVar activate(CBContext *context, const CBVar &input) { if (unlikely(!chain)) return input; if constexpr (CHAIN_MODE == RunChainMode::Detached) { activateDetached(context, input); return input; } else if constexpr (CHAIN_MODE == RunChainMode::Stepped) { activateStepMode(context, input); if constexpr (INPUT_PASSTHROUGH) { return input; } else { return chain->previousOutput; } } else { // Run within the root flow auto runRes = runSubChain(chain.get(), context, input); if (unlikely(runRes.state == Failed)) { // meaning there was an exception while // running the sub chain, stop the parent too context->stopFlow(runRes.output); return runRes.output; } else { if constexpr (INPUT_PASSTHROUGH) { return input; } else { return runRes.output; } } } } }; struct ChainNotFound : public ActivationError { ChainNotFound() : ActivationError("Could not find a chain to run") {} }; template <class T> struct BaseLoader : public BaseRunner { CBTypeInfo _inputTypeCopy{}; IterableExposedInfo _sharedCopy; CBTypeInfo compose(const CBInstanceData &data) { _inputTypeCopy = data.inputType; const IterableExposedInfo sharedStb(data.shared); // copy shared _sharedCopy = sharedStb; if (mode == RunChainMode::Inline || mode == RunChainMode::Stepped) { // If inline allow chains to receive a result return CoreInfo::AnyType; } else { return data.inputType; } } void setParam(int index, const CBVar &value) { switch (index) { case 1: mode = RunChainMode(value.payload.enumValue); break; default: break; } } CBVar getParam(int index) { switch (index) { case 1: return Var::Enum(mode, CoreCC, 'runC'); default: break; } return Var::Empty; } void cleanup() { BaseRunner::cleanup(); } CBVar activateChain(CBContext *context, const CBVar &input) { if (unlikely(!chain)) throw ChainNotFound(); if (mode == RunChainMode::Detached) { activateDetached(context, input); } else if (mode == RunChainMode::Stepped) { activateStepMode(context, input); return chain->previousOutput; } else { // Run within the root flow const auto runRes = runSubChain(chain.get(), context, input); if (likely(runRes.state != Failed)) { return runRes.output; } } return input; } }; struct ChainLoader : public BaseLoader<ChainLoader> { BlocksVar _onReloadBlocks{}; BlocksVar _onErrorBlocks{}; static inline Parameters params{ {"Provider", CBCCSTR("The chainblocks chain provider."), {ChainProvider::ProviderOrNone}}, {"Mode", CBCCSTR("The way to run the chain. Inline: will run the sub chain " "inline within the root chain, a pause in the child chain will " "pause the root too; Detached: will run the chain separately in " "the same node, a pause in this chain will not pause the root; " "Stepped: the chain will run as a child, the root will tick the " "chain every activation of this block and so a child pause " "won't pause the root."), {ModeType}}, {"OnReload", CBCCSTR("Blocks to execute when the chain is reloaded, the input of " "this flow will be the reloaded chain."), {CoreInfo::BlocksOrNone}}, {"OnError", CBCCSTR("Blocks to execute when a chain reload failed, the input of " "this flow will be the error message."), {CoreInfo::BlocksOrNone}}}; static CBParametersInfo parameters() { return params; } CBChainProvider *_provider; void setParam(int index, const CBVar &value) { switch (index) { case 0: { cleanup(); // stop current if (value.valueType == Object) { _provider = (CBChainProvider *)value.payload.objectValue; } else { _provider = nullptr; } } break; case 1: { BaseLoader<ChainLoader>::setParam(index, value); } break; case 2: { _onReloadBlocks = value; } break; case 3: { _onErrorBlocks = value; } break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: if (_provider) { return Var::Object(_provider, CoreCC, 'chnp'); } else { return Var(); } case 1: return BaseLoader<ChainLoader>::getParam(index); case 2: return _onReloadBlocks; case 3: return _onErrorBlocks; default: { return Var::Empty; } } } CBTypeInfo compose(const CBInstanceData &data) { CBInstanceData data2 = data; data2.inputType = CoreInfo::ChainType; _onReloadBlocks.compose(data2); _onErrorBlocks.compose(data); return BaseLoader<ChainLoader>::compose(data); } void cleanup() { BaseLoader<ChainLoader>::cleanup(); _onReloadBlocks.cleanup(); _onErrorBlocks.cleanup(); if (_provider) _provider->reset(_provider); } void warmup(CBContext *context) { BaseLoader<ChainLoader>::warmup(context); _onReloadBlocks.warmup(context); _onErrorBlocks.warmup(context); } CBVar activate(CBContext *context, const CBVar &input) { if (unlikely(!_provider)) return input; if (unlikely(!_provider->ready(_provider))) { CBInstanceData data{}; data.inputType = _inputTypeCopy; data.shared = _sharedCopy; data.chain = context->chainStack.back(); assert(data.chain->node.lock()); _provider->setup(_provider, GetGlobals().RootPath.c_str(), data); } if (unlikely(_provider->updated(_provider))) { auto update = _provider->acquire(_provider); if (unlikely(update.error != nullptr)) { CBLOG_ERROR("Failed to reload a chain via ChainLoader, reason: {}", update.error); CBVar output{}; _onErrorBlocks.activate(context, Var(update.error), output); } else { if (chain) { // stop and release previous version chainblocks::stop(chain.get()); } // but let the provider release the pointer! chain.reset(update.chain, [&](CBChain *x) { _provider->release(_provider, x); }); doWarmup(context); CBLOG_INFO("Chain {} has been reloaded", update.chain->name); CBVar output{}; _onReloadBlocks.activate(context, Var(chain), output); } } try { return BaseLoader<ChainLoader>::activateChain(context, input); } catch (const ChainNotFound &ex) { // let's ignore chain not found in this case return input; } } }; struct ChainRunner : public BaseLoader<ChainRunner> { static inline Parameters params{ {"Chain", CBCCSTR("The chain variable to compose and run."), {CoreInfo::ChainVarType}}, {"Mode", CBCCSTR("The way to run the chain. Inline: will run the sub chain " "inline within the root chain, a pause in the child chain will " "pause the root too; Detached: will run the chain separately in " "the same node, a pause in this chain will not pause the root; " "Stepped: the chain will run as a child, the root will tick the " "chain every activation of this block and so a child pause " "won't pause the root."), {ModeType}}}; static CBParametersInfo parameters() { return params; } ParamVar _chain{}; CBVar _chainHash{}; CBChain *_chainPtr = nullptr; CBExposedTypeInfo _requiredChain{}; void setParam(int index, const CBVar &value) { if (index == 0) { _chain = value; } else { BaseLoader<ChainRunner>::setParam(index, value); } } CBVar getParam(int index) { if (index == 0) { return _chain; } else { return BaseLoader<ChainRunner>::getParam(index); } } void cleanup() { BaseLoader<ChainRunner>::cleanup(); _chain.cleanup(); _chainPtr = nullptr; } void warmup(CBContext *context) { BaseLoader<ChainRunner>::warmup(context); _chain.warmup(context); } CBExposedTypesInfo requiredVariables() { if (_chain.isVariable()) { _requiredChain = CBExposedTypeInfo{_chain.variableName(), CBCCSTR("The chain to run."), CoreInfo::ChainType}; return {&_requiredChain, 1, 0}; } else { return {}; } } void doCompose(CBContext *context) { CBInstanceData data{}; data.inputType = _inputTypeCopy; data.shared = _sharedCopy; data.chain = context->chainStack.back(); chain->node = context->main->node; // avoid stackoverflow if (gatheringChains().count(chain.get())) return; // we don't know yet... gatheringChains().insert(chain.get()); DEFER(gatheringChains().erase(chain.get())); // We need to validate the sub chain to figure it out! auto res = composeChain( chain.get(), [](const CBlock *errorBlock, const char *errorTxt, bool nonfatalWarning, void *userData) { if (!nonfatalWarning) { CBLOG_ERROR("RunChain: failed inner chain validation, error: {}", errorTxt); throw CBException("RunChain: failed inner chain validation"); } else { CBLOG_INFO("RunChain: warning during inner chain validation: {}", errorTxt); } }, this, data); chainblocks::arrayFree(res.exposedInfo); chainblocks::arrayFree(res.requiredInfo); } CBVar activate(CBContext *context, const CBVar &input) { auto chainVar = _chain.get(); chain = CBChain::sharedFromRef(chainVar.payload.chainValue); if (unlikely(!chain)) return input; if (_chainHash.valueType == None || _chainHash != chain->composedHash || _chainPtr != chain.get()) { // Compose and hash in a thread await( context, [this, context, chainVar]() { doCompose(context); chain->composedHash = chainblocks::hash(chainVar); }, [] {}); _chainHash = chain->composedHash; _chainPtr = chain.get(); doWarmup(context); } return BaseLoader<ChainRunner>::activateChain(context, input); } }; enum class WaitUntil { FirstSuccess, // will wait until the first success and stop any other // pending operation AllSuccess, // will wait until all complete, will stop and fail on any // failure SomeSuccess // will wait until all complete but won't fail if some of the // chains failed }; struct ManyChain : public std::enable_shared_from_this<ManyChain> { uint32_t index; std::shared_ptr<CBChain> chain; std::shared_ptr<CBNode> node; // used only if MT bool done; }; struct ParallelBase : public ChainBase { typedef EnumInfo<WaitUntil> WaitUntilInfo; static inline WaitUntilInfo waitUntilInfo{"WaitUntil", CoreCC, 'tryM'}; static inline Type WaitUntilType{ {CBType::Enum, {.enumeration = {.vendorId = CoreCC, .typeId = 'tryM'}}}}; static inline Parameters _params{ {"Chain", CBCCSTR("The chain to spawn and try to run many times concurrently."), ChainBase::ChainVarTypes}, {"Policy", CBCCSTR("The execution policy in terms of chains success."), {WaitUntilType}}, {"Threads", CBCCSTR("The number of cpu threads to use."), {CoreInfo::IntType}}, {"Coroutines", CBCCSTR("The number of coroutines to run on each thread."), {CoreInfo::IntType}}}; static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: chainref = value; break; case 1: _policy = WaitUntil(value.payload.enumValue); break; case 2: _threads = std::max(int64_t(1), value.payload.intValue); break; case 3: _coros = std::max(int64_t(1), value.payload.intValue); break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return chainref; case 1: return Var::Enum(_policy, CoreCC, 'tryM'); case 2: return Var(_threads); case 3: return Var(_coros); default: return Var::Empty; } } CBTypeInfo compose(const CBInstanceData &data) { if (_threads > 1) { mode = RunChainMode::Detached; } else { mode = RunChainMode::Inline; } ChainBase::compose(data); // discard the result, we do our thing here _pool.reset(new ChainDoppelgangerPool<ManyChain>(CBChain::weakRef(chain))); const IterableExposedInfo shared(data.shared); // copy shared _sharedCopy = shared; return CoreInfo::NoneType; // not complete } struct Composer { ParallelBase &server; CBContext *context; void compose(CBChain *chain) { CBInstanceData data{}; data.inputType = server._inputType; data.shared = server._sharedCopy; data.chain = context->chainStack.back(); chain->node = context->main->node; auto res = composeChain( chain, [](const struct CBlock *errorBlock, const char *errorTxt, CBBool nonfatalWarning, void *userData) { if (!nonfatalWarning) { CBLOG_ERROR(errorTxt); throw ActivationError("Http.Server handler chain compose failed"); } else { CBLOG_WARNING(errorTxt); } }, nullptr, data); arrayFree(res.exposedInfo); arrayFree(res.requiredInfo); } } _composer{*this}; void warmup(CBContext *context) { #if !defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__) if (_threads > 1) { const auto threads = std::min(_threads, int64_t(std::thread::hardware_concurrency())); if (!_exec || _exec->num_workers() != (size_t(threads))) { _exec.reset(new tf::Executor(size_t(threads))); } } #endif _composer.context = context; } void cleanup() { for (auto &v : _outputs) { destroyVar(v); } _outputs.clear(); for (auto &cref : _chains) { if (cref->node) { cref->node->terminate(); } stop(cref->chain.get()); _pool->release(cref); } _chains.clear(); } virtual CBVar getInput(const std::shared_ptr<ManyChain> &mc, const CBVar &input) = 0; virtual size_t getLength(const CBVar &input) = 0; CBVar activate(CBContext *context, const CBVar &input) { auto node = context->main->node.lock(); auto len = getLength(input); _outputs.resize(len); _chains.resize(len); Defer cleanups([this]() { for (auto &cref : _chains) { if (cref) { if (cref->node) { cref->node->terminate(); } stop(cref->chain.get()); _pool->release(cref); } } _chains.clear(); }); for (uint32_t i = 0; i < len; i++) { _chains[i] = _pool->acquire(_composer); _chains[i]->index = i; _chains[i]->done = false; } size_t succeeded = 0; size_t failed = 0; // wait according to policy while (true) { const auto _suspend_state = chainblocks::suspend(context, 0); if (unlikely(_suspend_state != CBChainState::Continue)) { return Var::Empty; } else { #if defined(__EMSCRIPTEN__) && !defined(__EMSCRIPTEN_PTHREADS__) { #else if (_threads == 1) { #endif // advance our chains and check for (auto it = _chains.begin(); it != _chains.end(); ++it) { auto &cref = *it; if (cref->done) continue; // Prepare and start if no callc was called if (!cref->chain->coro) { cref->chain->node = context->main->node; // pre-set chain context with our context // this is used to copy chainStack over to the new one cref->chain->context = context; // Notice we don't share our flow! // let the chain create one by passing null chainblocks::prepare(cref->chain.get(), nullptr); chainblocks::start(cref->chain.get(), getInput(cref, input)); } // Tick the chain on the flow that this chain created CBDuration now = CBClock::now().time_since_epoch(); chainblocks::tick(cref->chain->context->flow->chain, now, getInput(cref, input)); if (!isRunning(cref->chain.get())) { if (cref->chain->state == CBChain::State::Ended) { if (_policy == WaitUntil::FirstSuccess) { // success, next call clones, make sure to destroy stop(cref->chain.get(), &_outputs[0]); return _outputs[0]; } else { stop(cref->chain.get(), &_outputs[succeeded]); succeeded++; } } else { stop(cref->chain.get()); failed++; } cref->done = true; } } } #if !defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__) else { // multithreaded tf::Taskflow flow; flow.for_each_dynamic( _chains.begin(), _chains.end(), [this, input](auto &cref) { // skip if failed or ended if (cref->done) return; // Prepare and start if no callc was called if (!cref->chain->coro) { if (!cref->node) { cref->node = CBNode::make(); } cref->chain->node = cref->node; // Notice we don't share our flow! // let the chain create one by passing null chainblocks::prepare(cref->chain.get(), nullptr); chainblocks::start(cref->chain.get(), getInput(cref, input)); } // Tick the chain on the flow that this chain created CBDuration now = CBClock::now().time_since_epoch(); chainblocks::tick(cref->chain->context->flow->chain, now, getInput(cref, input)); // also tick the node cref->node->tick(); }, _coros); _exec->run(flow).get(); for (auto it = _chains.begin(); it != _chains.end(); ++it) { auto &cref = *it; if (!cref->done && !isRunning(cref->chain.get())) { if (cref->chain->state == CBChain::State::Ended) { if (_policy == WaitUntil::FirstSuccess) { // success, next call clones, make sure to destroy stop(cref->chain.get(), &_outputs[0]); return _outputs[0]; } else { stop(cref->chain.get(), &_outputs[succeeded]); succeeded++; } } else { stop(cref->chain.get()); failed++; } cref->done = true; } } } #endif if ((succeeded + failed) == len) { if (unlikely(succeeded == 0)) { throw ActivationError("TryMany, failed all chains!"); } else { // all ended let's apply policy here if (_policy == WaitUntil::SomeSuccess) { return Var(_outputs.data(), succeeded); } else { assert(_policy == WaitUntil::AllSuccess); if (len == succeeded) { return Var(_outputs.data(), succeeded); } else { throw ActivationError("TryMany, failed some chains!"); } } } } } } } protected: WaitUntil _policy{WaitUntil::AllSuccess}; std::unique_ptr<ChainDoppelgangerPool<ManyChain>> _pool; IterableExposedInfo _sharedCopy; Type _outputSeqType; Types _outputTypes; CBTypeInfo _inputType{}; std::vector<CBVar> _outputs; std::vector<std::shared_ptr<ManyChain>> _chains; int64_t _threads{1}; int64_t _coros{1}; #if !defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__) std::unique_ptr<tf::Executor> _exec; #endif }; struct TryMany : public ParallelBase { static CBTypesInfo inputTypes() { return CoreInfo::AnySeqType; } static CBTypesInfo outputTypes() { return CoreInfo::AnySeqType; } CBTypeInfo compose(const CBInstanceData &data) { ParallelBase::compose(data); if (data.inputType.seqTypes.len == 1) { // copy single input type _inputType = data.inputType.seqTypes.elements[0]; } else { // else just mark as generic any _inputType = CoreInfo::AnyType; } if (_policy == WaitUntil::FirstSuccess) { // single result return chain->outputType; } else { // seq result _outputTypes = Types({chain->outputType}); _outputSeqType = Type::SeqOf(_outputTypes); return _outputSeqType; } } CBVar getInput(const std::shared_ptr<ManyChain> &mc, const CBVar &input) override { return input.payload.seqValue.elements[mc->index]; } size_t getLength(const CBVar &input) override { return size_t(input.payload.seqValue.len); } }; struct Expand : public ParallelBase { int64_t _width{10}; static CBTypesInfo inputTypes() { return CoreInfo::AnyType; } static CBTypesInfo outputTypes() { return CoreInfo::AnySeqType; } static inline Parameters _params{ {{"Size", CBCCSTR("The maximum expansion size."), {CoreInfo::IntType}}}, ParallelBase::_params}; static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { if (index == 0) { _width = std::max(int64_t(1), value.payload.intValue); } else { ParallelBase::setParam(index - 1, value); } } CBVar getParam(int index) { if (index == 0) { return Var(_width); } else { return ParallelBase::getParam(index - 1); } } CBTypeInfo compose(const CBInstanceData &data) { ParallelBase::compose(data); // input _inputType = data.inputType; // output _outputTypes = Types({chain->outputType}); _outputSeqType = Type::SeqOf(_outputTypes); return _outputSeqType; } CBVar getInput(const std::shared_ptr<ManyChain> &mc, const CBVar &input) override { return input; } size_t getLength(const CBVar &input) override { return size_t(_width); } }; struct Spawn : public ChainBase { Spawn() { mode = RunChainMode::Detached; } static CBTypesInfo inputTypes() { return CoreInfo::AnyType; } static CBTypesInfo outputTypes() { return CoreInfo::ChainType; } static inline Parameters _params{ {"Chain", CBCCSTR("The chain to spawn and try to run many times concurrently."), ChainBase::ChainVarTypes}}; static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: chainref = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return chainref; default: return Var::Empty; } } CBTypeInfo compose(const CBInstanceData &data) { ChainBase::compose(data); // discard the result, we do our thing here // chain should be populated now and such _pool.reset(new ChainDoppelgangerPool<ManyChain>(CBChain::weakRef(chain))); const IterableExposedInfo shared(data.shared); // copy shared _sharedCopy = shared; _inputType = data.inputType; return CoreInfo::ChainType; } struct Composer { Spawn &server; CBContext *context; void compose(CBChain *chain) { CBInstanceData data{}; data.inputType = server._inputType; data.shared = server._sharedCopy; data.chain = context->chainStack.back(); chain->node = context->main->node; auto res = composeChain( chain, [](const struct CBlock *errorBlock, const char *errorTxt, CBBool nonfatalWarning, void *userData) { if (!nonfatalWarning) { CBLOG_ERROR(errorTxt); throw ActivationError("Http.Server handler chain compose failed"); } else { CBLOG_WARNING(errorTxt); } }, nullptr, data); arrayFree(res.exposedInfo); arrayFree(res.requiredInfo); } } _composer{*this}; void warmup(CBContext *context) { _composer.context = context; } CBVar activate(CBContext *context, const CBVar &input) { auto node = context->main->node.lock(); auto c = _pool->acquire(_composer); c->chain->onStop.clear(); // we have a fresh recycled chain here std::weak_ptr<ManyChain> wc(c); c->chain->onStop.emplace_back([this, wc]() { if (auto c = wc.lock()) _pool->release(c); }); node->schedule(c->chain, input, false); return Var(c->chain); // notice this is "weak" } std::unique_ptr<ChainDoppelgangerPool<ManyChain>> _pool; IterableExposedInfo _sharedCopy; CBTypeInfo _inputType{}; }; struct Branch { static CBTypesInfo inputTypes() { return CoreInfo::AnyType; } static CBTypesInfo outputTypes() { return CoreInfo::AnyType; } static CBParametersInfo parameters() { static Parameters params{ {"Chains", CBCCSTR("The chains to schedule and run on this branch."), {CoreInfo::ChainType, CoreInfo::ChainSeqType, CoreInfo::NoneType}}}; return params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _chains = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _chains; default: return Var::Empty; } } CBOptionalString help() { return CBCCSTR( "A branch is a child node that runs and is ticked when this block is " "activated, chains on this node will inherit all of the available " "exposed variables in the activator chain."); } void composeSubChain(const CBInstanceData &data, CBChainRef &chainref) { auto chain = CBChain::sharedFromRef(chainref); auto dataCopy = data; dataCopy.chain = chain.get(); dataCopy.inputType = data.inputType; auto cr = composeChain( chain.get(), [](const CBlock *errorBlock, const char *errorTxt, bool nonfatalWarning, void *userData) { if (!nonfatalWarning) { CBLOG_ERROR("Branch: failed inner chain validation, error: {}", errorTxt); throw ComposeError("RunChain: failed inner chain validation"); } else { CBLOG_INFO("Branch: warning during inner chain validation: {}", errorTxt); } }, this, dataCopy); _composes.emplace_back(cr); _runChains.emplace_back(chain); // add to merged requirements for (auto &req : cr.requiredInfo) { arrayPush(_mergedReqs, req); } } void destroy() { // release any old compose for (auto &cr : _composes) { arrayFree(cr.requiredInfo); arrayFree(cr.exposedInfo); } _composes.clear(); arrayFree(_mergedReqs); } CBTypeInfo compose(const CBInstanceData &data) { // release any old info destroy(); _runChains.clear(); if (_chains.valueType == CBType::Seq) { for (auto &chain : _chains) { composeSubChain(data, chain.payload.chainValue); } } else if (_chains.valueType == CBType::Chain) { composeSubChain(data, _chains.payload.chainValue); } const IterableExposedInfo shared(data.shared); // copy shared _sharedCopy = shared; _node->instanceData.shared = _sharedCopy; return data.inputType; } CBExposedTypesInfo requiredVariables() { return _mergedReqs; } void warmup(CBContext *context) { // grab all the variables we need and reference them for (const auto &cr : _composes) { for (const auto &req : cr.requiredInfo) { if (_node->refs.count(req.name) == 0) { auto vp = referenceVariable(context, req.name); _node->refs[req.name] = vp; } } } for (const auto &chain : _runChains) { _node->schedule(chain, Var::Empty, false); } } void cleanup() { for (auto &[_, vp] : _node->refs) { releaseVariable(vp); } // this will also clear refs _node->terminate(); } CBVar activate(CBContext *context, const CBVar &input) { if (!_node->tick(input)) { // the node had errors in this case throw ActivationError("Branched node had errors"); } return input; } private: OwnedVar _chains{Var::Empty}; std::shared_ptr<CBNode> _node = CBNode::make(); IterableExposedInfo _sharedCopy; std::vector<CBComposeResult> _composes; CBExposedTypesInfo _mergedReqs; std::vector<std::shared_ptr<CBChain>> _runChains; }; void registerChainsBlocks() { using RunChainDo = RunChain<false, RunChainMode::Inline>; using RunChainDispatch = RunChain<true, RunChainMode::Inline>; using RunChainDetach = RunChain<true, RunChainMode::Detached>; using RunChainStep = RunChain<false, RunChainMode::Stepped>; REGISTER_CBLOCK("Resume", Resume); REGISTER_CBLOCK("Start", Start); REGISTER_CBLOCK("Wait", Wait); REGISTER_CBLOCK("Stop", StopChain); REGISTER_CBLOCK("Do", RunChainDo); REGISTER_CBLOCK("Dispatch", RunChainDispatch); REGISTER_CBLOCK("Detach", RunChainDetach); REGISTER_CBLOCK("Step", RunChainStep); REGISTER_CBLOCK("ChainLoader", ChainLoader); REGISTER_CBLOCK("ChainRunner", ChainRunner); REGISTER_CBLOCK("Recur", Recur); REGISTER_CBLOCK("TryMany", TryMany); REGISTER_CBLOCK("Spawn", Spawn); REGISTER_CBLOCK("Expand", Expand); REGISTER_CBLOCK("Branch", Branch); } }; // namespace chainblocks #ifndef __EMSCRIPTEN__ // this is a hack to fix a linker issue with taskflow... /* duplicate symbol 'thread-local initialization routine for tf::Executor::_per_thread' in: libcb_static.a(chains.cpp.o) libcb_static.a(genetic.cpp.o) */ #include "genetic.hpp" #endif
29.391929
80
0.602276
fragcolor-xyz
3de6fdd38554b4043a8a064ba5229b2c48b65f20
3,549
hpp
C++
Source/Common/Context.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/Common/Context.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/Common/Context.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
#pragma once #include "Precompiled.hpp" // // Context // // Conveniently holds pointers to instances of different types. // Use when you have to pass a non trivial number of references as a single argument. // class Context { public: // Type declarations. typedef std::pair<std::type_index, void*> InstancePtr; typedef std::vector<InstancePtr> InstanceList; typedef std::vector<Context> ContextList; // Search function definition. template<typename Type> static bool SearchInstance(const InstancePtr& instance) { return instance.first == typeid(Type*); } public: Context() { } ~Context() { } // Restores instance to it's original state. void Cleanup() { *this = Context(); } // Sets an unique instance. template<typename Type> bool Set(Type* instance) { // Free instance handle if nullptr. if(instance == nullptr) { this->Clear<Type>(); } // Find instance by type. auto it = std::find_if(m_instances.begin(), m_instances.end(), SearchInstance<Type>); // Set the instance value. if(it != m_instances.end()) { // Replace value at existing handle. it->second = instance; return false; } else { // Add a new instance handle. m_instances.emplace_back(typeid(Type*), instance); return true; } } // Gets an unique instance. template<typename Type> Type* Get() const { // Find instance by type. auto it = std::find_if(m_instances.begin(), m_instances.end(), SearchInstance<Type>); // Return instance reference. if(it != m_instances.end()) { return reinterpret_cast<Type*>(it->second); } else { return nullptr; } } // Checks if has an instance of a given type. template<typename Type> bool Has() const { // Find instance by type. auto it = std::find_if(m_instances.begin(), m_instances.end(), SearchInstance<Type>); return it != m_instances.end(); } // Clears the uniqe instance handle. template<typename Type> void Clear() { // Find and erase an instance. m_instances.erase(std::find_if(m_instances.begin(), m_instances.end(), SearchInstance<Type>)); } // Gets a subcontext. Context& operator[](int index) { assert(index >= 0); // Return self at zero index. if(index == 0) { return *this; } // Resize context list if needed. // Useful indices start from 1 here. if(m_contexts.size() < size_t(index)) { m_contexts.resize(index); } // Return a subcontext. return m_contexts[index - 1]; } const Context& operator[](int index) const { assert(index >= 0); // Return self at zero index. if(index == 0) { return *this; } // Return an empty context. // Useful indices start from 1 here. if(m_contexts.size() < size_t(index)) { static const Context Invalid; return Invalid; } // Return a subcontext. return m_contexts[index - 1]; } private: // List of unique instances. InstanceList m_instances; // List of subcontextes. ContextList m_contexts; };
22.75
102
0.554804
gunstarpl
3de704a700d839d5f6b20357eda6a3740fc4021e
4,675
cpp
C++
Libraries/graphics/Tests/test_PixelFormat.cpp
djgalloway/xcbuild
936df10e59e5f5d531efca8bd48e445d88e78e0c
[ "BSD-2-Clause-NetBSD" ]
9
2018-04-30T23:18:27.000Z
2021-06-20T15:13:38.000Z
Libraries/graphics/Tests/test_PixelFormat.cpp
djgalloway/xcbuild
936df10e59e5f5d531efca8bd48e445d88e78e0c
[ "BSD-2-Clause-NetBSD" ]
null
null
null
Libraries/graphics/Tests/test_PixelFormat.cpp
djgalloway/xcbuild
936df10e59e5f5d531efca8bd48e445d88e78e0c
[ "BSD-2-Clause-NetBSD" ]
4
2018-10-10T19:44:17.000Z
2020-01-12T11:56:31.000Z
/** Copyright (c) 2015-present, Facebook, Inc. 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. An additional grant of patent rights can be found in the PATENTS file in the same directory. */ #include <gtest/gtest.h> #include <graphics/PixelFormat.h> using graphics::PixelFormat; TEST(PixelFormat, Properties) { /* Grayscale is one-byte. */ PixelFormat f0 = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::None); EXPECT_EQ(f0.channels(), 1); EXPECT_EQ(f0.bytesPerPixel(), 1); EXPECT_EQ(f0.bitsPerPixel(), 8); /* Ignored alpha is a byte but not a channel. */ PixelFormat f1 = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::IgnoredFirst); EXPECT_EQ(f1.channels(), 1); EXPECT_EQ(f1.bytesPerPixel(), 2); EXPECT_EQ(f1.bitsPerPixel(), 16); /* Real alpha is a channel too. */ PixelFormat f2 = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::First); EXPECT_EQ(f2.channels(), 2); EXPECT_EQ(f2.bytesPerPixel(), 2); EXPECT_EQ(f2.bitsPerPixel(), 16); /* RGB has three channels. */ PixelFormat f3 = PixelFormat(PixelFormat::Color::RGB, PixelFormat::Order::Forward, PixelFormat::Alpha::None); EXPECT_EQ(f3.channels(), 3); EXPECT_EQ(f3.bytesPerPixel(), 3); EXPECT_EQ(f3.bitsPerPixel(), 24); /* RGB can also have alpha. */ PixelFormat f4 = PixelFormat(PixelFormat::Color::RGB, PixelFormat::Order::Forward, PixelFormat::Alpha::PremultipliedLast); EXPECT_EQ(f4.channels(), 4); EXPECT_EQ(f4.bytesPerPixel(), 4); EXPECT_EQ(f4.bitsPerPixel(), 32); } static std::vector<uint8_t> Expected(std::vector<uint8_t> const &value) { return value; } TEST(PixelFormat, ConvertAlpha) { PixelFormat none = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::None); PixelFormat last = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::Last); /* Should add alpha as 0xFF (solid). */ EXPECT_EQ(PixelFormat::Convert({ 0x6A, 0x6B }, none, last), Expected({ 0x6A, 0xFF, 0x6B, 0xFF })); /* Should strip out alpha, compositing against black. */ EXPECT_EQ(PixelFormat::Convert({ 0x60, 0x7F, 0x6B, 0xFF }, last, none), Expected({ 0x30, 0x6B })); PixelFormat normal = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::Last); PixelFormat premult = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::PremultipliedLast); /* Should multiply in alpha. */ EXPECT_EQ(PixelFormat::Convert({ 0x60, 0x7F, 0x80, 0x40 }, normal, premult), Expected({ 0x30, 0x7F, 0x20, 0x40 })); /* Should remove premultiplication. */ EXPECT_EQ(PixelFormat::Convert({ 0x30, 0x7F, 0x20, 0x40 }, premult, normal), Expected({ 0x60, 0x7F, 0x80, 0x40 })); } TEST(PixelFormat, ConvertGrayscale) { PixelFormat gray = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::None); PixelFormat color = PixelFormat(PixelFormat::Color::RGB, PixelFormat::Order::Forward, PixelFormat::Alpha::None); /* Should repeat the gray across the channels. */ EXPECT_EQ(PixelFormat::Convert({ 0x6A, 0x6B }, gray, color), Expected({ 0x6A, 0x6A, 0x6A, 0x6B, 0x6B, 0x6B })); /* Should average the channels to grayscale. */ EXPECT_EQ(PixelFormat::Convert({ 0x1A, 0x3A, 0x5A, 0x10, 0x40, 0xA0 }, color, gray), Expected({ 0x3A, 0x50 })); } TEST(PixelFormat, ConvertRearrange) { /* Should flip alpha position. */ PixelFormat first = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::First); PixelFormat last = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::Last); EXPECT_EQ(PixelFormat::Convert({ 0x6A, 0x7F }, last, first), Expected({ 0x7F, 0x6A })); EXPECT_EQ(PixelFormat::Convert({ 0x7F, 0x6A }, first, last), Expected({ 0x6A, 0x7F })); /* Should flip color channels. */ PixelFormat forward = PixelFormat(PixelFormat::Color::RGB, PixelFormat::Order::Forward, PixelFormat::Alpha::None); PixelFormat reversed = PixelFormat(PixelFormat::Color::RGB, PixelFormat::Order::Reversed, PixelFormat::Alpha::None); EXPECT_EQ(PixelFormat::Convert({ 0x6A, 0x6C, 0x6E }, forward, reversed), Expected({ 0x6E, 0x6C, 0x6A })); EXPECT_EQ(PixelFormat::Convert({ 0x6E, 0x6C, 0x6A }, reversed, forward), Expected({ 0x6A, 0x6C, 0x6E })); }
46.287129
137
0.706952
djgalloway
3de76419cd60453f8a99d7b4a59f72ef8da81325
3,597
cpp
C++
chapter6/Base.cpp
zzq1996/OJ
359d0ad532732092a5afe5995312b12e8da74953
[ "Apache-2.0" ]
null
null
null
chapter6/Base.cpp
zzq1996/OJ
359d0ad532732092a5afe5995312b12e8da74953
[ "Apache-2.0" ]
null
null
null
chapter6/Base.cpp
zzq1996/OJ
359d0ad532732092a5afe5995312b12e8da74953
[ "Apache-2.0" ]
null
null
null
/** * @Author : zhang * @create 2022/3/1 19:56 */ #include "Base.h" #include "iostream" #include "vector" using namespace std; /* * @Description 十进制整数转二进制 * 方法:除2取余,逆序排序 */ void Base::f6_1() { unsigned int n=0; while (cin>>n){ if(n==0){ break; }else{ vector<int> binary; while (n!=0){ binary.push_back(n%2); n=n/2; } //注意:这里是逆序输出 for (int i = binary.size()-1; i >= 0; --i) { cout<<binary[i]; } cout<<endl; } } } /* * @Description 30位的非负十进制数转二进制 * 用字符串模拟数字,对字符串模拟的数字进行对2取模和对2整除运算 * ——取余:直接用最低位对2取模 * ——整除:定义函数完成 * char转int:char-‘0’ int转char:int+‘0’ * */ /* * @Description 重写一个函数完成字符串的除法 * 对字符串str进行除2运算 * * 返回的字符串:pos位置后的str字串即整除后的整数部分 * * string字符串从0开始 * * 输入: cout<<divide("12345",2); * 输出:current:1,str[0]:0,reminder:1 current:12,str[1]:6,reminder:0 current:3,str[2]:1,reminder:1 current:14,str[3]:7,reminder:0 current:5,str[4]:2,reminder:1 str:06172 pos:1 6172 * */ string divide(string str,int x){ int reminder=0;//保留余数 //把字符串从高位到低位逐位除以2 for (int i = 0; i < str.size(); ++i) { int current=reminder*10+str[i]-'0'; // cout<<"current:"<<current; str[i]=current / x+'0';//str[i]保存的是整除2后的数 // cout<<",str["<<i<<"]:"<<str[i]; reminder = current % x;//若不能整除,则保留余数 // cout<<",reminder:"<<reminder<<endl; } int pos=0; // cout<<"str:"<<str<<endl; while(str[pos]=='0'){//寻找首个非0下标 pos++; } // cout<<"pos:"<<pos<<endl; return str.substr(pos);//删除前置多余0 } /* * @Description 字符串转2进制 */ void Base::f6_2() { string str; while (cin>>str){ vector<int> binary; while(str.size()!=0){ int last=str[str.size()-1]-'0';//获取最低位的值 binary.push_back(last%2);//将最低位对2取模的结果存入向量 str= divide(str,2);//对2整除,更新字符串 } //逆序输出向量 for (int i = binary.size()-1; i >=0; --i) { cout<<binary[i]; } cout<<endl; } } /* * @Description 输出二进制逆序数 */ void Base::f6_3() { string str; while (cin>>str){ vector<int> binary; while(str.size()!=0){ int last=str[str.size()-1]-'0';//获取最低位的值 binary.push_back(last%2);//将最低位对2取模的结果存入向量 str= divide(str,2);//对2整除,更新字符串 } int sum=0,base=1; for (int i = binary.size()-1; i >= 0; --i) { sum=sum+binary[i]*base; base=base*2; } cout<<sum<<endl; } } /* * @Description M进制转N进制 * 先转为10进制,再转为N进制 * 注意:1、进制大于10时,需实现字符与数字之间的转换 * 2、将十进制数转为N进制数的方法 */ //数字转字符 char intToChar(int x){ if (x<10){ return x+'0'; }else{ return x-10+'a'; } } void Base::f6_4() { int M=0,N=0; string str; while (cin>>M>>N>>str){ string str1; int base=1;//转换的基数 long long num=0;//定义long long类型保存转换的十进制数 //将M进制的str转为10进制的num for (int i = 0; i < str.size(); ++i) { num=num+(str[i]-'0')*base; base=base*M; } // cout<<"十进制数为:"<<num<<endl; //将num转为N进制 //不断对N求余,求商,即可得到从低位到高位上的数 vector<char> answer; while (num!=0){ answer.push_back(intToChar(num % N)); num=num/N; } //逆序输出向量数组 for (int i = answer.size()-1; i >= 0 ; --i) { cout<<answer[i]; } cout<<endl; } }
17.632353
56
0.48179
zzq1996
3de7fde1b18eda98ac3b0ca94181b6a68699e670
2,916
cpp
C++
p4c_bm/templates/src/pd_counters.cpp
krambn/p4c-bm
e6be2c76f4568d5e01f62a8955ce2839d2fa0b36
[ "Apache-2.0" ]
null
null
null
p4c_bm/templates/src/pd_counters.cpp
krambn/p4c-bm
e6be2c76f4568d5e01f62a8955ce2839d2fa0b36
[ "Apache-2.0" ]
null
null
null
p4c_bm/templates/src/pd_counters.cpp
krambn/p4c-bm
e6be2c76f4568d5e01f62a8955ce2839d2fa0b36
[ "Apache-2.0" ]
6
2019-09-17T13:52:51.000Z
2022-03-03T06:51:31.000Z
/* Copyright 2013-present Barefoot Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Antonin Bas (antonin@barefootnetworks.com) * */ #include <bm/pdfixed/pd_common.h> #include <thread> #include "pd_client.h" extern int *my_devices; extern "C" { //:: for ca_name, ca in counter_arrays.items(): //:: params = ["p4_pd_sess_hdl_t sess_hdl", //:: "p4_pd_dev_target_t dev_tgt"] //:: if ca.is_direct: //:: params += ["p4_pd_entry_hdl_t entry_hdl"] //:: else: //:: params += ["int index"] //:: #endif //:: params += ["int flags"] //:: param_str = ",\n ".join(params) //:: name = pd_prefix + "counter_read_" + ca_name p4_pd_counter_value_t ${name} ( ${param_str} ) { assert(my_devices[dev_tgt.device_id]); (void) flags; p4_pd_counter_value_t counter_value; BmCounterValue value; // TODO: try / catch block //:: if ca.is_direct: pd_client(dev_tgt.device_id).c->bm_mt_read_counter( value, 0, "${ca.table}", entry_hdl); //:: else: pd_client(dev_tgt.device_id).c->bm_counter_read( value, 0, "${ca_name}", index); //:: #endif counter_value.bytes = (uint64_t) value.bytes; counter_value.packets = (uint64_t) value.packets; return counter_value; } //:: params = ["p4_pd_sess_hdl_t sess_hdl", //:: "p4_pd_dev_target_t dev_tgt"] //:: if ca.is_direct: //:: params += ["p4_pd_entry_hdl_t entry_hdl"] //:: else: //:: params += ["int index"] //:: #endif //:: params += ["p4_pd_counter_value_t counter_value"] //:: param_str = ",\n ".join(params) //:: name = pd_prefix + "counter_write_" + ca_name p4_pd_status_t ${name} ( ${param_str} ) { assert(my_devices[dev_tgt.device_id]); BmCounterValue value; value.bytes = (int64_t) counter_value.bytes; value.packets = (int64_t) counter_value.packets; // TODO: try / catch block //:: if ca.is_direct: pd_client(dev_tgt.device_id).c->bm_mt_write_counter( 0, "${ca.table}", entry_hdl, value); //:: else: pd_client(dev_tgt.device_id).c->bm_counter_write( 0, "${ca_name}", index, value); //:: #endif return 0; } //:: name = pd_prefix + "counter_hw_sync_" + ca_name p4_pd_status_t ${name} ( p4_pd_sess_hdl_t sess_hdl, p4_pd_dev_target_t dev_tgt, p4_pd_stat_sync_cb cb_fn, void *cb_cookie ) { std::thread cb_thread(cb_fn, dev_tgt.device_id, cb_cookie); cb_thread.detach(); return 0; } //:: #endfor }
25.356522
75
0.665295
krambn
3de8cc79512d5f92f99f5ac061e38ead93af1ea8
1,126
hpp
C++
applications/CoSimulationApplication/custom_external_libraries/co_sim_io/impl/define.hpp
ma6yu/Kratos
02380412f8a833a2cdda6791e1c7f9c32e088530
[ "BSD-4-Clause" ]
null
null
null
applications/CoSimulationApplication/custom_external_libraries/co_sim_io/impl/define.hpp
ma6yu/Kratos
02380412f8a833a2cdda6791e1c7f9c32e088530
[ "BSD-4-Clause" ]
null
null
null
applications/CoSimulationApplication/custom_external_libraries/co_sim_io/impl/define.hpp
ma6yu/Kratos
02380412f8a833a2cdda6791e1c7f9c32e088530
[ "BSD-4-Clause" ]
null
null
null
// ______ _____ _ ________ // / ____/___ / ___/(_)___ ___ / _/ __ | // / / / __ \\__ \/ / __ `__ \ / // / / / // / /___/ /_/ /__/ / / / / / / // // /_/ / // \____/\____/____/_/_/ /_/ /_/___/\____/ // Kratos CoSimulationApplication // // License: BSD License, see license.txt // // Main authors: Philipp Bucher (https://github.com/philbucher) // #ifndef CO_SIM_IO_DEFINE_H_INCLUDED #define CO_SIM_IO_DEFINE_H_INCLUDED // System includes #include <string> #include <unordered_map> namespace CoSimIO { typedef std::unordered_map<std::string, std::string> SettingsType; enum class ControlSignal { Dummy, BreakSolutionLoop, ConvergenceAchieved, AdvanceInTime, InitializeSolutionStep, Predict, SolveSolutionStep, FinalizeSolutionStep, OutputSolutionStep, ImportGeometry, ExportGeometry, ImportMesh, ExportMesh, ImportData, ExportData, }; enum ConnectionStatus { NotConnected, Connected, Disconnected, ConnectionError, DisconnectionError }; } //namespace CoSimIO #endif // CO_SIM_IO_DEFINE_H_INCLUDED
20.107143
67
0.647425
ma6yu
3dee4a30782c12cfb5950567fb9c4ccce426e50f
369
cpp
C++
UESTC/2352.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
UESTC/2352.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
UESTC/2352.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <cstdio> using namespace std; double p, k, a, r = 1.0, b, m, f; int n; int main() { scanf("%lf %lf %lf %d", &p, &k, &a, &n); b = 1 - p; k /= 100.0; a /= 100.0; for (int i = 0; i < n; i++) { f = p * r; m += f * (k + i * a) * p + f * (1 - p); r *= b; } m += r * (k + n * a) * p + r * (1 - p); printf("%.3lf\n", m / (p * k + 1 - p)); return 0; }
16.772727
41
0.382114
HeRaNO
3df1534cd72d4c9bd9a355c602e7d34e307a79fb
8,097
inl
C++
SoftRP/ArrayAllocatorImpl.inl
loreStefani/SoftRP
2676145f74c734b272268820b1e1c503aa8ff765
[ "MIT" ]
null
null
null
SoftRP/ArrayAllocatorImpl.inl
loreStefani/SoftRP
2676145f74c734b272268820b1e1c503aa8ff765
[ "MIT" ]
null
null
null
SoftRP/ArrayAllocatorImpl.inl
loreStefani/SoftRP
2676145f74c734b272268820b1e1c503aa8ff765
[ "MIT" ]
null
null
null
#ifndef SOFTRP_ARRAY_ALLOCATOR_IMPL_INL_ #define SOFTRP_ARRAY_ALLOCATOR_IMPL_INL_ #include "ArrayAllocator.h" #include <utility> #include <cassert> namespace SoftRP { /* ArrayAllocator implementation */ template<typename T, typename AllocationDesc, typename ArrayAllocationDesc> inline ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>:: ArrayAllocator(size_t allocStride, size_t allocAlignment) : m_allocStride{ allocStride }, m_allocAlignment{ allocAlignment } { } template<typename T, typename AllocationDesc, typename ArrayAllocationDesc> inline ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>:: ArrayAllocator(ArrayAllocator&& va) { #ifdef SOFTRP_MULTI_THREAD std::lock_guard<std::mutex> vaLock{ va.m_mutex }; #endif m_allocStride = va.m_allocStride; m_allocAlignment = va.m_allocAlignment; m_allocations = std::move(va.m_allocations); m_arrayAllocations = std::move(va.m_arrayAllocations); } template<typename T, typename AllocationDesc, typename ArrayAllocationDesc> inline ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::~ArrayAllocator() { #ifdef _DEBUG for (auto& allocDesc : m_allocations) assert(!allocDesc.hasAllocations()); for (auto& p : m_arrayAllocations) assert(!p.second.hasAllocations()); #endif } template<typename T, typename AllocationDesc, typename ArrayAllocationDesc> inline ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>& ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::operator=(ArrayAllocator&& va) { if (&va == this) return *this; #ifdef SOFTRP_MULTI_THREAD std::unique_lock<std::mutex> thisLock{ m_mutex, std::defer_lock }; std::unique_lock<std::mutex> vaLock{ va.m_mutex, std::defer_lock }; std::lock(thisLock, vaLock); #endif m_allocStride = va.m_allocStride; m_allocAlignment = va.m_allocAlignment; m_allocations = std::move(va.m_allocations); m_arrayAllocations = std::move(va.m_arrayAllocations); return *this; } template<typename T, typename AllocationDesc, typename ArrayAllocationDesc> inline T* ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::allocate() { #ifdef SOFTRP_MULTI_THREAD std::lock_guard<std::mutex> lock{ m_mutex }; #endif for (auto& allocDesc : m_allocations) { if (allocDesc.canAllocate()) { return allocDesc.allocate(); } } m_allocations.push_back(AllocationDesc{ m_allocStride, m_allocAlignment }); return m_allocations.back().allocate(); } template<typename T, typename AllocationDesc, typename ArrayAllocationDesc> inline void ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::deallocate(T* data) { #ifdef SOFTRP_MULTI_THREAD std::lock_guard<std::mutex> lock{ m_mutex }; #endif for (auto& allocDesc : m_allocations) { if (allocDesc.deallocate(data)) return; } throw std::runtime_error{ "Deallocation requested to the wrong allocator" }; } template<typename T, typename AllocationDesc, typename ArrayAllocationDesc> inline T* ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::allocateArray(size_t count) { #ifdef SOFTRP_MULTI_THREAD std::lock_guard<std::mutex> lock{ m_mutex }; #endif auto it = m_arrayAllocations.find(count); if (it != m_arrayAllocations.end()) { return it->second.allocate(); } else { ArrayAllocationDesc arrayAllocDesc{ m_allocStride, count, m_allocAlignment }; T* ptr = arrayAllocDesc.allocate(); m_arrayAllocations.emplace(count, std::move(arrayAllocDesc)); return ptr; } } template<typename T, typename AllocationDesc, typename ArrayAllocationDesc> inline void ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::deallocateArray(T* dataArray) { #ifdef SOFTRP_MULTI_THREAD std::lock_guard<std::mutex> lock{ m_mutex }; #endif for (auto& pair : m_arrayAllocations) { auto& arrayAllocDesc = pair.second; if (arrayAllocDesc.deallocate(dataArray)) return; } throw std::runtime_error{ "Deallocation requested to the wrong allocator" }; } /* PoolAllocDescBase implementation */ template<typename T, typename Allocator> inline PoolAllocDescBase<T, Allocator>::PoolAllocDescBase(size_t allocStride, size_t allocAlignment) { const size_t elementSize = allocStride*sizeof(T); const size_t allocSize = BLOCK_SIZE*elementSize; m_data = static_cast<T*>(m_allocator.allocate(allocSize, allocAlignment)); m_end = m_data + allocStride*BLOCK_SIZE; m_allocStride = allocStride; } template<typename T, typename Allocator> inline PoolAllocDescBase<T, Allocator>::~PoolAllocDescBase() { if (m_data) { m_allocator.deallocate(m_data); m_data = nullptr; } } template<typename T, typename Allocator> inline PoolAllocDescBase<T, Allocator>::PoolAllocDescBase(PoolAllocDescBase&& aad) :m_allocationState{ aad.m_allocationState }, m_allocStride{ aad.m_allocStride }, m_data{ aad.m_data }, m_end{ aad.m_end } { aad.m_data = nullptr; } template<typename T, typename Allocator> inline PoolAllocDescBase<T, Allocator>& PoolAllocDescBase<T, Allocator>::operator=(PoolAllocDescBase&& aad) { m_allocationState = aad.m_allocationState; m_allocStride = aad.m_allocStride; m_data = aad.m_data; m_end = aad.m_end; aad.m_data = nullptr; } template<typename T, typename Allocator> inline T* PoolAllocDescBase<T, Allocator>::allocate() { size_t index = m_nextIndex; uint64_t currAlloc = static_cast<uint64_t>(1) << index; for (size_t i = index; i < BLOCK_SIZE; i++) { if ((m_allocationState & currAlloc) == 0) { m_allocationState |= currAlloc; m_nextIndex = i + 1; return m_data + i*m_allocStride; } currAlloc <<= 1; } currAlloc = 1; for (size_t i = 0; i < index; i++) { if ((m_allocationState & currAlloc) == 0) { m_allocationState |= currAlloc; m_nextIndex = i + 1; return m_data + i*m_allocStride; } currAlloc <<= 1; } return nullptr; } template<typename T, typename Allocator> inline bool PoolAllocDescBase<T, Allocator>::canAllocate() const { return m_allocationState != 0xFFFFFFFFFFFFFFFF; } template<typename T, typename Allocator> inline bool PoolAllocDescBase<T, Allocator>::hasAllocations() const { return m_allocationState != 0x0; } template<typename T, typename Allocator> inline bool PoolAllocDescBase<T, Allocator>::deallocate(T* ptr) { if (ptr < m_data || ptr >= m_end) return false; size_t index = (ptr - m_data) / m_allocStride; #ifdef _DEBUG if ((ptr - m_data) != index*m_allocStride) throw std::runtime_error{ "Deallocating from the wrong address!" }; if ((m_allocationState & (static_cast<uint64_t>(1) << index)) == 0) throw std::runtime_error{ "Deallocating from the wrong allocator!" }; #endif m_allocationState &= ~(static_cast<uint64_t>(1) << index); m_nextIndex = index; return true; } /* PoolArrayAllocDescBase implementation */ template<typename T, typename Allocator> inline PoolArrayAllocDescBase<T, Allocator>::PoolArrayAllocDescBase(size_t allocStride, size_t count, size_t allocAlignment) : m_elementSize{ allocStride*sizeof(T) }, m_allocSize{ count*m_elementSize }, m_allocAlignment{ allocAlignment } { } template<typename T, typename Allocator> inline PoolArrayAllocDescBase<T, Allocator>::~PoolArrayAllocDescBase() { for (const auto& p : m_allocated) m_allocator.deallocate(p); for (const auto& p : m_free) m_allocator.deallocate(p); } template<typename T, typename Allocator> inline T* PoolArrayAllocDescBase<T, Allocator>::allocate() { T* ptr{ nullptr }; if (m_free.size() == 0) ptr = static_cast<T*>(m_allocator.allocate(m_allocSize, m_allocAlignment)); else { ptr = m_free.front(); m_free.pop_front(); } m_allocated.emplace(ptr); return ptr; } template<typename T, typename Allocator> inline bool PoolArrayAllocDescBase<T, Allocator>::hasAllocations()const { return m_allocated.size() != 0; } template<typename T, typename Allocator> inline bool PoolArrayAllocDescBase<T, Allocator>::deallocate(T* ptr) { auto it = m_allocated.find(ptr); if (it == m_allocated.end()) return false; m_allocated.erase(it); m_free.emplace_back(ptr); return true; } } #endif
31.628906
152
0.742003
loreStefani
3df481b716a20386bdfc817ae6f34ebc9ba138e1
731
cpp
C++
mahbubul-hassan/0-Programming_Contest_DS_Algorithms/bigmod.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
3
2019-07-20T07:26:31.000Z
2020-08-06T09:31:09.000Z
mahbubul-hassan/0-Programming_Contest_DS_Algorithms/bigmod.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
null
null
null
mahbubul-hassan/0-Programming_Contest_DS_Algorithms/bigmod.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
4
2019-06-20T18:43:32.000Z
2020-10-07T16:45:23.000Z
#include <bits/stdc++.h> using namespace std; /* (ab) mod M = (a mod M)(b mod M) mod M (a^b) mod M = ? x1 = b/2, x2 = b-x1 so, ? = (a^x1 mod M)(a^x2 mod M) mod M */ class BigMod{ public: BigMod(){} ~BigMod(){} int bigMod(int a, int M){ if(a<M) return a%M; int x1 = a/2; int x2 = a-x1; return (bigMod(x1,M)*bigMod(x2,M))%M; } int bigMod(int a, int pow, int M){ if(pow==0) return 1%M; if(pow==1) return a%M; int x1 = pow/2; int x2 = pow-x1; return (bigMod(a,x1,M)*bigMod(a,x2,M))%M; } }; int main() { BigMod b; cout<<b.bigMod(1000,97)<<endl; cout<<b.bigMod(91,1000,97)<<endl; return 0; }
18.275
49
0.47606
fahimfarhan
3df4e145efc231fe90839d5fcdb465909749575f
6,676
cc
C++
SgtCore/YamlSupport.cc
dexterurbane/SmartGridToolbox
ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7
[ "Apache-2.0" ]
null
null
null
SgtCore/YamlSupport.cc
dexterurbane/SmartGridToolbox
ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7
[ "Apache-2.0" ]
null
null
null
SgtCore/YamlSupport.cc
dexterurbane/SmartGridToolbox
ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7
[ "Apache-2.0" ]
null
null
null
// Copyright 2015 National ICT Australia Limited (NICTA) // // 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 "YamlSupport.h" namespace YAML { using namespace arma; using namespace boost::posix_time; using namespace Sgt; using namespace std; Node convert<nullptr_t>::encode(const nullptr_t& from) { return Node(); } bool convert<nullptr_t>::decode(const Node& nd, nullptr_t& to) { bool result = false; if (nd.Type() == YAML::NodeType::Null) { to = nullptr; result = true; } return result; } Node convert<json>::encode(const json& from) { YAML::Node nd = YAML::Load(from.dump()); return nd; } bool convert<json>::decode(const Node& nd, json& to) { // TODO: actually try to reconstruct json from YAML. to = nd.as<string>(); return true; } Node convert<Complex>::encode(const Complex& from) { Node nd(to_string(from)); return nd; } bool convert<Complex>::decode(const Node& nd, Complex& to) { to = from_string<Complex>(nd.as<string>()); return true; } Node convert<Phase>::encode(const Phase& from) { Node nd(to_string(from)); return nd; } bool convert<Phase>::decode(const Node& nd, Phase& to) { to = from_string<Phase>(nd.as<string>()); return true; } Node convert<Phases>::encode(const Phases& from) { Node nd; for (const auto& phase: from) { nd.push_back(to_string(phase)); } return nd; } bool convert<Phases>::decode(const Node& nd, Phases& to) { if(!nd.IsSequence()) { return false; } else { vector<Phase> pVec; for (size_t i = 0; i < nd.size(); ++i) { pVec.push_back(nd[i].as<Phase>()); } to = Phases(pVec); } return true; } Node convert<BusType>::encode(const BusType& from) { Node nd(to_string(from)); return nd; } bool convert<BusType>::decode(const Node& nd, BusType& to) { to = from_string<BusType>(nd.as<string>()); return true; } Node convert<Time>::encode(const Time& from) { Node nd(boost::posix_time::to_simple_string(from)); return nd; } bool convert<Time>::decode(const Node& nd, Time& to) { to = boost::posix_time::duration_from_string(nd.as<string>()); return true; } Node convert<ptime>::encode(const ptime& from) { Node nd(boost::posix_time::to_simple_string(from)); return nd; } bool convert<ptime>::decode(const Node& nd, ptime& to) { to = boost::posix_time::time_from_string(nd.as<string>()); return true; } template<typename T> Node convert<Col<T>>::encode(const Col<T>& from) { Node nd; for (const T& val : from) nd.push_back(val); return nd; } template Node convert<Col<double>>::encode(const Col<double>& from); template Node convert<Col<Complex>>::encode(const Col<Complex>& from); template Node convert<Col<int>>::encode(const Col<int>& from); template Node convert<Col<uword>>::encode(const Col<uword>& from); template<typename T> bool convert<Col<T>>::decode(const Node& nd, Col<T>& to) { if(!nd.IsSequence()) { return false; } else { to = Col<T>(nd.size()); for (uword i = 0; i < nd.size(); ++i) { to(i) = nd[i].as<T>(); } } return true; } template bool convert<Col<double>>::decode(const Node& nd, Col<double>& to); template bool convert<Col<Complex>>::decode(const Node& nd, Col<Complex>& to); template bool convert<Col<int>>::decode(const Node& nd, Col<int>& to); template bool convert<Col<uword>>::decode(const Node& nd, Col<uword>& to); template<typename T> Node convert<Mat<T>>::encode(const Mat<T>& from) { Node nd; for (uword i = 0; i < from.n_rows; ++i) { Node nd1; for (uword k = 0; k < from.n_cols; ++k) { nd1.push_back(from(i, k)); } nd.push_back(nd1); } return nd; } template Node convert<Mat<double>>::encode(const Mat<double>& from); template Node convert<Mat<Complex>>::encode(const Mat<Complex>& from); template Node convert<Mat<int>>::encode(const Mat<int>& from); template Node convert<Mat<uword>>::encode(const Mat<uword>& from); template<typename T> bool convert<Mat<T>>::decode(const Node& nd, Mat<T>& to) { if(!nd.IsSequence()) { return false; } else { auto nrows = nd.size(); if (nrows == 0) { cerr << "Matrix has no rows in yaml." << endl; return false; } auto ncols = nd[0].size(); if (ncols == 0) { cerr << "Matrix has no columns in yaml." << endl; return false; } for (size_t i = 1; i < nrows; ++i) { if (nd[i].size() != ncols) { cerr << "Ill-formed matrix in yaml." << endl; return false; } } to = Mat<T>(nrows, ncols); for (uword i = 0; i < nrows; ++i) { for (uword k = 0; k < ncols; ++k) { to(i, k) = nd[i][k].as<T>(); } } } return true; } template bool convert<Mat<double>>::decode(const Node& nd, Mat<double>& to); template bool convert<Mat<Complex>>::decode(const Node& nd, Mat<Complex>& to); template bool convert<Mat<int>>::decode(const Node& nd, Mat<int>& to); template bool convert<Mat<uword>>::decode(const Node& nd, Mat<uword>& to); }
28.288136
82
0.529359
dexterurbane
3df7f6d89615362870ec054b8e351555f944c33a
8,488
cc
C++
DPGAnalysis/SiStripTools/plugins/APVCyclePhaseDebuggerFromL1TS.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
DPGAnalysis/SiStripTools/plugins/APVCyclePhaseDebuggerFromL1TS.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
DPGAnalysis/SiStripTools/plugins/APVCyclePhaseDebuggerFromL1TS.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
// -*- C++ -*- // // Package: SiStripTools // Class: APVCyclePhaseDebuggerFromL1TS // /**\class APVCyclePhaseDebuggerFromL1TS APVCyclePhaseDebuggerFromL1TS.cc DPGAnalysis/SiStripTools/plugins/APVCyclePhaseDebuggerFromL1TS.cc Description: EDproducer for APVCyclePhaseCollection which uses the configuration file to assign a phase to the run Implementation: <Notes on implementation> */ // // Original Author: Andrea Venturi // Created: Mon Jan 12 09:05:45 CET 2009 // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/Run.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/InputTag.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "FWCore/Utilities/interface/Exception.h" #include <map> #include <vector> #include <utility> #include <string> #include <iostream> #include "TH1F.h" #include "TProfile.h" #include "DataFormats/Scalers/interface/Level1TriggerScalers.h" #include "DPGAnalysis/SiStripTools/interface/RunHistogramManager.h" // // class decleration // class APVCyclePhaseDebuggerFromL1TS : public edm::EDAnalyzer { public: explicit APVCyclePhaseDebuggerFromL1TS(const edm::ParameterSet&); ~APVCyclePhaseDebuggerFromL1TS() override; static void fillDescriptions( edm::ConfigurationDescriptions & descriptions ); private: void beginRun(const edm::Run&, const edm::EventSetup&) override; void analyze(const edm::Event&, const edm::EventSetup&) override; // ----------member data --------------------------- edm::EDGetTokenT<Level1TriggerScalersCollection> _l1tscollectionToken; const unsigned int m_maxLS; const unsigned int m_LSfrac; RunHistogramManager m_rhm; TH1F** _hsize; TH1F** _hlresync; TH1F** _hlOC0; TH1F** _hlTE; TH1F** _hlstart; TH1F** _hlEC0; TH1F** _hlHR; TH1F** _hdlec0lresync; TH1F** _hdlresynclHR; long long _lastResync; long long _lastHardReset; long long _lastStart; long long _lastEventCounter0; long long _lastOrbitCounter0; long long _lastTestEnable; }; // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // APVCyclePhaseDebuggerFromL1TS::APVCyclePhaseDebuggerFromL1TS(const edm::ParameterSet& iConfig): _l1tscollectionToken(consumes<Level1TriggerScalersCollection>(iConfig.getParameter<edm::InputTag>("l1TSCollection"))), m_maxLS(iConfig.getUntrackedParameter<unsigned int>("maxLSBeforeRebin",250)), m_LSfrac(iConfig.getUntrackedParameter<unsigned int>("startingLSFraction",16)), m_rhm(consumesCollector()), _hsize(nullptr),_hlresync(nullptr),_hlOC0(nullptr),_hlTE(nullptr),_hlstart(nullptr),_hlEC0(nullptr),_hlHR(nullptr),_hdlec0lresync(nullptr),_hdlresynclHR(nullptr), _lastResync(-1),_lastHardReset(-1),_lastStart(-1), _lastEventCounter0(-1),_lastOrbitCounter0(-1),_lastTestEnable(-1) { //now do what ever other initialization is needed _hsize = m_rhm.makeTH1F("size","Level1TriggerScalers Collection size",20,-0.5,19.5); _hlresync = m_rhm.makeTH1F("lresync","Orbit of last resync",m_LSfrac*m_maxLS,0,m_maxLS*262144); _hlOC0 = m_rhm.makeTH1F("lOC0","Orbit of last OC0",m_LSfrac*m_maxLS,0,m_maxLS*262144); _hlTE = m_rhm.makeTH1F("lTE","Orbit of last TestEnable",m_LSfrac*m_maxLS,0,m_maxLS*262144); _hlstart = m_rhm.makeTH1F("lstart","Orbit of last Start",m_LSfrac*m_maxLS,0,m_maxLS*262144); _hlEC0 = m_rhm.makeTH1F("lEC0","Orbit of last EC0",m_LSfrac*m_maxLS,0,m_maxLS*262144); _hlHR = m_rhm.makeTH1F("lHR","Orbit of last HardReset",m_LSfrac*m_maxLS,0,m_maxLS*262144); _hdlec0lresync = m_rhm.makeTH1F("dlec0lresync","Orbit difference EC0-Resync",4000,-1999.5,2000.5); _hdlresynclHR = m_rhm.makeTH1F("dlresynclHR","Orbit difference Resync-HR",4000,-1999.5,2000.5); } APVCyclePhaseDebuggerFromL1TS::~APVCyclePhaseDebuggerFromL1TS() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) } // // member functions // // ------------ method called to produce the data ------------ void APVCyclePhaseDebuggerFromL1TS::beginRun(const edm::Run& iRun, const edm::EventSetup& iSetup) { // update the parameters from DB m_rhm.beginRun(iRun); if(_hlresync && *_hlresync) { (*_hlresync)->GetXaxis()->SetTitle("Orbit"); (*_hlresync)->GetYaxis()->SetTitle("Events"); (*_hlresync)->SetCanExtend(TH1::kXaxis); } if(_hlOC0 && *_hlOC0) { (*_hlOC0)->GetXaxis()->SetTitle("Orbit"); (*_hlOC0)->GetYaxis()->SetTitle("Events"); (*_hlOC0)->SetCanExtend(TH1::kXaxis); } if(_hlTE && *_hlTE) { (*_hlTE)->GetXaxis()->SetTitle("Orbit"); (*_hlTE)->GetYaxis()->SetTitle("Events"); (*_hlTE)->SetCanExtend(TH1::kXaxis); } if(_hlstart && *_hlstart) { (*_hlstart)->GetXaxis()->SetTitle("Orbit"); (*_hlstart)->GetYaxis()->SetTitle("Events"); (*_hlstart)->SetCanExtend(TH1::kXaxis); } if(_hlEC0 && *_hlEC0) { (*_hlEC0)->GetXaxis()->SetTitle("Orbit"); (*_hlEC0)->GetYaxis()->SetTitle("Events"); (*_hlEC0)->SetCanExtend(TH1::kXaxis); } if(_hlHR && *_hlHR) { (*_hlHR)->GetXaxis()->SetTitle("Orbit"); (*_hlHR)->GetYaxis()->SetTitle("Events"); (*_hlHR)->SetCanExtend(TH1::kXaxis); } if(_hdlec0lresync && *_hdlec0lresync) { (*_hdlec0lresync)->GetXaxis()->SetTitle("lastEC0-lastResync"); } if(_hdlresynclHR && *_hdlresynclHR) { (*_hdlresynclHR)->GetXaxis()->SetTitle("lastEC0-lastResync"); } } void APVCyclePhaseDebuggerFromL1TS::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; Handle<Level1TriggerScalersCollection> l1ts; iEvent.getByToken(_l1tscollectionToken,l1ts); if(_hsize && *_hsize) (*_hsize)->Fill(l1ts->size()); // offset computation if(!l1ts->empty()) { if(_hlresync && *_hlresync) (*_hlresync)->Fill((*l1ts)[0].lastResync()); if(_hlOC0 && *_hlOC0) (*_hlOC0)->Fill((*l1ts)[0].lastOrbitCounter0()); if(_hlTE && *_hlTE) (*_hlTE)->Fill((*l1ts)[0].lastTestEnable()); if(_hlstart && *_hlstart) (*_hlstart)->Fill((*l1ts)[0].lastStart()); if(_hlEC0 && *_hlEC0) (*_hlEC0)->Fill((*l1ts)[0].lastEventCounter0()); if(_hlHR && *_hlHR) (*_hlHR)->Fill((*l1ts)[0].lastHardReset()); if(_lastResync != (*l1ts)[0].lastResync()) { _lastResync = (*l1ts)[0].lastResync(); if(_hdlec0lresync && *_hdlec0lresync) (*_hdlec0lresync)->Fill((*l1ts)[0].lastEventCounter0()-(*l1ts)[0].lastResync()); LogDebug("TTCSignalReceived") << "New Resync at orbit " << _lastResync ; } if(_lastHardReset != (*l1ts)[0].lastHardReset()) { _lastHardReset = (*l1ts)[0].lastHardReset(); if(_hdlresynclHR && *_hdlresynclHR) (*_hdlresynclHR)->Fill((*l1ts)[0].lastResync()-(*l1ts)[0].lastHardReset()); LogDebug("TTCSignalReceived") << "New HardReset at orbit " << _lastHardReset ; } if(_lastTestEnable != (*l1ts)[0].lastTestEnable()) { _lastTestEnable = (*l1ts)[0].lastTestEnable(); // LogDebug("TTCSignalReceived") << "New TestEnable at orbit " << _lastTestEnable ; } if(_lastOrbitCounter0 != (*l1ts)[0].lastOrbitCounter0()) { _lastOrbitCounter0 = (*l1ts)[0].lastOrbitCounter0(); LogDebug("TTCSignalReceived") << "New OrbitCounter0 at orbit " << _lastOrbitCounter0 ; } if(_lastEventCounter0 != (*l1ts)[0].lastEventCounter0()) { _lastEventCounter0 = (*l1ts)[0].lastEventCounter0(); LogDebug("TTCSignalReceived") << "New EventCounter0 at orbit " << _lastEventCounter0 ; } if(_lastStart != (*l1ts)[0].lastStart()) { _lastStart = (*l1ts)[0].lastStart(); LogDebug("TTCSignalReceived") << "New Start at orbit " << _lastStart ; } } } void APVCyclePhaseDebuggerFromL1TS::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>("l1TSCollection",edm::InputTag("scalersRawToDigi")); descriptions.add("l1TSDebugger",desc); } //define this as a plug-in DEFINE_FWK_MODULE(APVCyclePhaseDebuggerFromL1TS);
31.909774
164
0.701225
nistefan
3dfa677e09fb7c346df47ca3ec87038ad93c7094
446
cpp
C++
data_structures/Range_query_cpp/C++/Update_array.cpp
CarbonDDR/al-go-rithms
8e65affbe812931b7dde0e2933eb06c0f44b4130
[ "CC0-1.0" ]
1,253
2017-06-06T07:19:25.000Z
2022-03-30T17:07:58.000Z
data_structures/Range_query_cpp/C++/Update_array.cpp
rishabh99-rc/al-go-rithms
4df20d7ef7598fda4bc89101f9a99aac94cdd794
[ "CC0-1.0" ]
554
2017-09-29T18:56:01.000Z
2022-02-21T15:48:13.000Z
data_structures/Range_query_cpp/C++/Update_array.cpp
rishabh99-rc/al-go-rithms
4df20d7ef7598fda4bc89101f9a99aac94cdd794
[ "CC0-1.0" ]
2,226
2017-09-29T19:59:59.000Z
2022-03-25T08:59:55.000Z
#include<bits/stdc++.h> using namespace std; int main(){ int n,q; long long int arr[n],upd[n+1]; cin>>n>>q; for(int i=0;i<n;i++){ cin>>arr[i]; upd[i]=0; } upd[n]=0; long long int start,end,val; for(int i=0;i<q;i++){ cin>>start>>end>>val; upd[start]+=val; upd[end+1]-=val; } long long int kk=0; cout<<"Updated array is : "; for(int i=0;i<n;i++){ kk+=upd[i]; arr[i]+=kk; cout<<arr[i]<<" "; } cout<<endl; return 0; }
15.37931
31
0.547085
CarbonDDR
ad00e2cc97e83b0ef6f2e972fd07520e98889fdc
7,398
cc
C++
mysql-dst/mysql-cluster/ndb/memcache/src/ndb_configuration.cc
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
9
2020-12-17T01:59:13.000Z
2022-03-30T16:25:08.000Z
mysql-dst/mysql-cluster/ndb/memcache/src/ndb_configuration.cc
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
1
2021-07-30T12:06:33.000Z
2021-07-31T10:16:09.000Z
mysql-dst/mysql-cluster/storage/ndb/memcache/src/ndb_configuration.cc
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
1
2021-08-01T13:47:07.000Z
2021-08-01T13:47:07.000Z
/* Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <my_config.h> #include <stdio.h> #include <pthread.h> #include <memcached/extension_loggers.h> #include <NdbApi.hpp> #include "Configuration.h" #include "ndb_configuration.h" #include "debug.h" #include "workitem.h" #include "NdbInstance.h" #include "ndb_pipeline.h" #include "thread_identifier.h" #include "Scheduler.h" #include "ExternalValue.h" /* A static global variable */ extern EXTENSION_LOGGER_DESCRIPTOR *logger; /* From ndb_pipeline */ extern int workitem_class_id; extern int workitem_actual_inline_buffer_size; /* An external Function */ extern "C" { void cache_set_initial_cas_id(uint64_t cas); /* In cache-src/items.c */ } Configuration * active_config = 0; Configuration * next_config = 0; Configuration * stale_config = 0; /* This function has C++ linkage */ Configuration & get_Configuration() { return *active_config; }; /* This function has C linkage */ bool connect_to_primary_cluster(const char *connectstring, const char *server_role) { DEBUG_ENTER(); active_config = new Configuration; active_config->setPrimaryConnectString(connectstring); active_config->setServerRole(server_role); return active_config->connectToPrimary(); } bool read_configuration(Configuration *cf) { const char *method[4] = { "is ignored", "uses NDB only", "uses local cache only", "uses NDB with local cache" }; int npref; int log_msg_sz = 0; const int log_buf_sz = 2048; char logmsg[log_buf_sz]; if(cf->readConfiguration()) { const KeyPrefix *p = cf->getDefaultPrefix(); npref = cf->nprefixes; unsigned pGET = (p->info.do_mc_read * 2) + p->info.do_db_read; unsigned pSET = (p->info.do_mc_write * 2) + p->info.do_db_write; unsigned pDEL = (p->info.do_mc_delete * 2) + p->info.do_db_delete; logger->log(LOG_WARNING, NULL, "Retrieved %d key prefix%s for server role \"%s\".\n" "The default behavior is that: \n" " GET %s\n SET %s\n DELETE %s.\n", cf->nprefixes, cf->nprefixes == 1 ? "" : "es", cf->getServerRole(), method[pGET], method[pSET], method[pDEL]); if(npref > 1) { /* List all non-default prefixes */ log_msg_sz = snprintf(logmsg, log_buf_sz - log_msg_sz, "The %d explicitly defined key prefix%s ", npref - 1, npref == 2 ? " is" : "es are"); for(int i = 1 ; i < npref ; i ++) { log_msg_sz += snprintf(logmsg + log_msg_sz, log_buf_sz - log_msg_sz, "%s\"%s\" (%s)", i > 1 ? (i == npref - 1 ? " and " : ", ") : "", cf->getPrefix(i)->prefix, cf->getPrefix(i)->table ? cf->getPrefix(i)->table->table_name : ""); } snprintf(logmsg + log_msg_sz, log_buf_sz - log_msg_sz, "\n"); logger->log(LOG_WARNING, NULL, logmsg); } return true; } return false; } /* This function has C linkage */ bool get_config() { return read_configuration(active_config); } /* This function has C linkage */ bool open_connections_to_all_clusters() { return active_config->openAllConnections(); } /* This function has C linkage */ bool prefetch_dictionary_objects() { return active_config->prefetchDictionary(); } /* This function has C linkage */ void set_initial_cas_ids(unsigned int *hi, atomic_int32_t *lo) { /* Set the initial CAS for the default engine: */ /* XXXXX disabled. Because we're linking with the actual default engine, we don't have the opportunity to coordinate CAS IDs between the two engines. */ // cache_set_initial_cas_id(active_config->initial_cas.for_default_engine); /* Set the initial CAS for the NDB engine: */ *hi = active_config->initial_cas.for_ndb_engine >> 32; *lo = active_config->initial_cas.for_ndb_engine & 0xFFFFFFFF; } /* This function has C linkage */ prefix_info_t get_prefix_info_for_key(int nkey, const char *key) { const KeyPrefix *prefix = active_config->getPrefixForKey(key, nkey); return prefix->info; } /* This function has C linkage */ void disconnect_all() { /* Run only at shutdown time. Disabled to silence a warning about "Deleting Ndb_cluster_connection with Ndb-object not deleted" */ // active_config->disconnectAll(); } /* This function has C linkage */ void print_debug_startup_info() { #ifdef DEBUG_OUTPUT size_t wi1 = 1 << workitem_class_id; size_t wi2 = sizeof(workitem) - WORKITEM_MIN_INLINE_BUF; size_t wi3 = workitem_actual_inline_buffer_size; DEBUG_PRINT(" sizeof Ndb : %lu", sizeof(Ndb)); DEBUG_PRINT(" sizeof NdbInstance : %lu", sizeof(NdbInstance)); DEBUG_PRINT(" sizeof workitem : %lu (%lu + buffer: %lu)", wi1, wi2, wi3); DEBUG_PRINT(" sizeof ExternalValue : %lu", sizeof(ExternalValue)); #endif } void reconfigure(Scheduler *s) { DEBUG_ENTER(); next_config = new Configuration(active_config); if(! read_configuration(next_config)) { logger->log(LOG_WARNING, 0, "Online reconfiguration failed."); } else if(! s->global_reconfigure(next_config)) { logger->log(LOG_WARNING, 0, "Online configuration aborted -- not supported by scheduler."); } else { /* There is no garbage collection here, but there could be if Configuration had a carefully-written destructor. */ stale_config = active_config; active_config = next_config; next_config = 0; logger->log(LOG_WARNING, 0, "ONLINE RECONFIGURATION COMPLETE"); } } extern "C" { void * run_reconfig_listener_thread(void *); } // TODO: This could take a GlobalConfigManager rather than a Scheduler void * run_reconfig_listener_thread(void *p) { thread_identifier tid; tid.pipeline = 0; strcpy(tid.name,"config_listener"); set_thread_id(&tid); DEBUG_ENTER(); ndb_pipeline * pipeline = (ndb_pipeline *) p; while(1) { int i = active_config->waitForReconfSignal(); if(i == 0) { DEBUG_PRINT("will listen again."); } else if(i == 1) { DEBUG_PRINT("reconfiguring"); reconfigure(pipeline->scheduler); } else { DEBUG_PRINT("error (%d); exiting.", i); break; } } return 0; } /* This function has C linkage */ void start_reconfig_listener(void *pipeline) { DEBUG_ENTER(); if(active_config->canReloadOnline()) { pthread_t thd_id; DEBUG_PRINT("Starting thread."); pthread_create(& thd_id, NULL, run_reconfig_listener_thread, pipeline); } else { DEBUG_PRINT("Not supported."); } }
29.710843
81
0.659232
SJTU-IPADS
ad0573882fe9cb2c61661fd4dfc0449f6af0996c
1,486
cpp
C++
src/dll/Handler.cpp
Mathieu-Lala/unamed00
e9a7bc3f2c0c791d719c1f3f68f23c2734f70f10
[ "MIT" ]
5
2020-02-23T13:48:42.000Z
2020-04-12T17:43:12.000Z
src/dll/Handler.cpp
Mathieu-Lala/unamed00
e9a7bc3f2c0c791d719c1f3f68f23c2734f70f10
[ "MIT" ]
null
null
null
src/dll/Handler.cpp
Mathieu-Lala/unamed00
e9a7bc3f2c0c791d719c1f3f68f23c2734f70f10
[ "MIT" ]
null
null
null
/** * @file src/dll/Handler.cpp * */ #include <utility> #include "dll/Handler.hpp" dll::Handler::Handler() noexcept : m_handler (EMPTY) { } dll::Handler::Handler(Handler &&o) noexcept : m_handler (std::exchange(o.m_handler, EMPTY)), m_libpath (std::move(o.m_libpath)) { } dll::Handler &dll::Handler::operator=(dll::Handler &&o) noexcept { this->m_handler = std::exchange(o.m_handler, EMPTY); this->m_libpath = std::move(o.m_libpath); return *this; } dll::Handler::Handler(Path libpath) : m_handler (EMPTY) { this->open(std::move(libpath)); } dll::Handler::~Handler() { this->close(); } bool dll::Handler::is_valid() const noexcept { return this->m_handler != EMPTY; } void dll::Handler::open(Path libpath) { this->close(); this->m_libpath = std::move(libpath); # if defined(OS_LINUX) this->m_handler = ::dlopen(this->m_libpath.c_str(), RTLD_LAZY); # elif defined(OS_WINDOWS) this->m_handler = ::LoadLibrary(this->m_libpath.c_str()); # endif if (!this->is_valid()) throw error{ }; } void dll::Handler::close() { if (!this->is_valid()) return; # if defined(OS_LINUX) auto ok = !::dlclose(this->m_handler); # elif defined(OS_WINDOWS) auto ok = ::FreeLibrary(this->m_handler); # endif this->m_handler = EMPTY; this->m_libpath = ""; if (!ok) throw error{ }; } const dll::Handler::Path &dll::Handler::getPath() const noexcept { return this->m_libpath; }
19.051282
67
0.62786
Mathieu-Lala
ad0b8fdc4c44bab64898742b0fceedd610732829
1,549
hpp
C++
include/SSVUtils/Range/Internal/Base/Range.hpp
SuperV1234/SSVUtils
a0e801b180bf65d7b3be4ea1e15b840c52e92efc
[ "AFL-3.0" ]
55
2015-01-27T09:45:01.000Z
2020-05-18T18:26:44.000Z
include/SSVUtils/Range/Internal/Base/Range.hpp
vittorioromeo/SSVUtils
dafa2499bcd350c3bfdbfb84d522e022c3513a93
[ "AFL-3.0" ]
10
2015-01-12T20:08:59.000Z
2020-08-29T23:40:59.000Z
include/SSVUtils/Range/Internal/Base/Range.hpp
vittorioromeo/SSVUtils
dafa2499bcd350c3bfdbfb84d522e022c3513a93
[ "AFL-3.0" ]
8
2015-02-24T04:30:50.000Z
2021-02-04T04:37:58.000Z
// Copyright (c) 2013-2015 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef SSVU_RANGE_INTERNAL_BASE_RANGE #define SSVU_RANGE_INTERNAL_BASE_RANGE #include "SSVUtils/Range/Internal/Base/Adaptor.hpp" namespace ssvu { /// @brief Simple range class that stores a begin and end iterator. /// @details Can be iterated upon with C++11-style for loops. template <typename TItr> class Range { private: TItr itrBegin, itrEnd; public: inline constexpr Range(const TItr& mItrBegin, const TItr& mItrEnd) noexcept : itrBegin{mItrBegin}, itrEnd{mItrEnd} { } inline constexpr auto begin() const noexcept { return itrBegin; } inline constexpr auto end() const noexcept { return itrEnd; } }; /// @brief Returns a range made from two iterators. template <typename TItr> inline constexpr auto makeRange(const TItr& mBegin, const TItr& mEnd) noexcept { return Range<TItr>(mBegin, mEnd); } /// @brief Returns a range made by `std::begin(mContainer)` and /// `std::end(mContainer)`. template <typename TC> inline constexpr auto asRange(TC& mContainer) noexcept { return makeRange(std::begin(mContainer), std::end(mContainer)); } /// @brief Returns a range made by `std::cbegin(mContainer)` and /// `std::cend(mContainer)`. template <typename TC> inline constexpr auto asRange(const TC& mContainer) noexcept { return makeRange(std::cbegin(mContainer), std::cend(mContainer)); } } // namespace ssvu #endif
25.393443
79
0.711427
SuperV1234
ad105cce07ac486786a156bf00bdcebbe804aa66
1,610
cpp
C++
LeetCode/ThousandOne/0394-decode_string.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0394-decode_string.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0394-decode_string.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 394. 字符串解码 给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。 注意 k 保证为正整数。 你可以认为输入字符串总是有效的; 输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k。 例如不会出现像 3a 或 2[4] 的输入。 示例: s = "3[a]2[bc]", 返回 "aaabcbc". s = "3[a2[c]]", 返回 "accaccacc". s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef". */ string decodeString(string const& E) { size_t len = E.length(); string D; vector<int> cnt; vector<string> rep; for (size_t i = 0; i < len;) { if (isdigit(E[i])) { int n = E[i] - '0'; size_t k = i + 1; // 保证符合要求,不用检查越界 for (; isdigit(E[k]); ++k) n = n * 10 + (E[k] - '0'); cnt.push_back(n); i = k; } else if (E[i] == '[') { string cur; size_t k = i + 1; for (; !isdigit(E[k]) && E[k] != ']'; ++k) cur.push_back(E[k]); rep.push_back(cur); i = k; } else if (E[i] == ']') { string cur; int n = cnt.back(); cur.reserve(rep.back().size() * n); while (n--) cur += rep.back(); rep.pop_back(); cnt.pop_back(); if (rep.empty()) D += cur; else rep.back() += cur; ++i; } // 又没说不能出现 **&*&¥@!%%&*&(* 这种 else // if (isalpha(E[i])) { bool out = rep.empty(); for (; i < len && !isdigit(E[i]) && E[i] != ']'; ++i) { if (out) D.push_back(E[i]); else rep.back().push_back(E[i]); } } } return D; } int main() { OutExpr(decodeString("2[b4[F]c]").c_str(), "%s"); OutExpr(decodeString("3[a]2[bc]").c_str(), "%s"); OutExpr(decodeString("3[a2[c]]").c_str(), "%s"); OutExpr(decodeString("2[abc]3[cd]ef").c_str(), "%s"); }
18.089888
60
0.526087
Ginkgo-Biloba
ad10652207b6a8e6dbe40723e9792d48315ad841
5,141
hpp
C++
mcdc/Include/parser.hpp
yadaniel/MCDC
6ca4475d813ddd19741f38f8f91c9dd477ebe4dd
[ "BSD-3-Clause" ]
16
2020-04-23T09:18:07.000Z
2022-02-06T11:14:22.000Z
mcdc/Include/parser.hpp
yadaniel/MCDC
6ca4475d813ddd19741f38f8f91c9dd477ebe4dd
[ "BSD-3-Clause" ]
1
2021-12-01T15:42:30.000Z
2021-12-01T15:42:30.000Z
mcdc/Include/parser.hpp
yadaniel/MCDC
6ca4475d813ddd19741f38f8f91c9dd477ebe4dd
[ "BSD-3-Clause" ]
10
2019-11-15T22:14:05.000Z
2021-08-02T09:04:28.000Z
// -------------------------------------------------------------------------------------------------------------------------------- // License: BSD-3-Clause // -------------------------------------------------------------------------------------------------------------------------------- // // Copyright 2019 Armin Montigny // // -------------------------------------------------------------------------------------------------------------------------------- // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met : // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the // following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and /or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or // promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -------------------------------------------------------------------------------------------------------------------------------- #pragma once #ifndef PARSER_HPP #define PARSER_HPP // // Implementation of a Shift Reduce Parser for boolean expressions // // This Software takes a string with a boolean expression as an input // and transorms it to other representations, to be able to vealuate it // // The Parser, defined in this module, analyzes the given source (boolean expression) // and generates code for a virtual machine or for an Abstract Syntax Tree AST // or whatever, using a codegenerator. // // First the source is tokenized via a scanner, then the Parser analyzes the Tokens // and tries to match it wit the productions in the grammar. If a match is found, // then the code generator is called. // // So, the algorithm is a classical shift match reduce parser. // // The whole chain consist of: // // Scanner --> Parser --> Code Generator --> Virtual Machine // // The parser tkaes a source string as input and generates an object file and a symbol table // // Operation: // // The Parser calls the scanner to get the next token. The token will be shifted on the parse stack. // Then, the top elements (one or more) of the parse stack will be compared to handles and // the look ahead symnol in the grammar. If there is no match, the next token will be read // and pushed on the stack. If there is a match, then the gode generator is called and the parse stack // will be reduced. All matching elements on the parse stack (without the look ahead symbol) will be // removed/replace by the non-terminal, the left hand side for/of this production. // This will be done until the end of the source string has been detected or a syntax error has been found. // // Tokens have attributes, specifically the input terminal symbols #include "scanner.hpp" #include "codegenerator.hpp" #include "grammar.hpp" #include <utility> // The parse stack is a vector of Tokens (with attributes). Since we want o work on more elements as // the stack top, a std::vector is used and not a std::stack using ParseStack = std::vector<TokenWithAttribute>; class Parser { public: // The parser needs to know about the scanner and the code geenrator // The Grammar is a runtime constant explicit Parser(Scanner& scannerForParser, CodeGeneratorBase* codeGeneratorForParser) noexcept : grammar(grammarForBooleanExpressions), scanner(scannerForParser), codeGeneratorForVM(codeGeneratorForParser), parseStack() {} Parser() = delete; Parser& operator =(const Parser&) = delete; // Main interface. Do the parse. Returns false on error bool parse(); protected: // Yes I know. These are references const Grammar& grammar; Scanner& scanner; CodeGeneratorBase* codeGeneratorForVM; // Match function compares top of parse stack with handles of the grammar std::pair<bool, uint> match(); // Calls Code generator and reduces the parse stack, be erasing/replacing handle elements with a none terminal void reduce(uint positionOfProduction); ParseStack parseStack; // For debugging or learning purposes void printParseStack(std::string title); }; #endif
43.940171
223
0.682163
yadaniel
ad119d5094d271a992db1bcfec3d54870b927abb
32,968
cpp
C++
serializer/tengine/v2/tm2_op_load.cpp
ArmstrongYang/Tengine
69c610b7a38e3022e69ccaf9119901f3402af567
[ "Apache-2.0" ]
1
2019-06-20T04:35:17.000Z
2019-06-20T04:35:17.000Z
serializer/tengine/v2/tm2_op_load.cpp
ArmstrongYang/Tengine
69c610b7a38e3022e69ccaf9119901f3402af567
[ "Apache-2.0" ]
null
null
null
serializer/tengine/v2/tm2_op_load.cpp
ArmstrongYang/Tengine
69c610b7a38e3022e69ccaf9119901f3402af567
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2019, Open AI Lab * Author: jingyou@openailab.com */ #include <string.h> #include "tm2_format.h" #include "tm2_op_serializer.hpp" namespace TEngine { namespace TMSerializer2 { bool LoadTmAccuracyOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_ACCURACY); SetNodeOp(node, op); return true; } bool LoadTmBatchNormOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_BATCHNORMALIZATION; BatchNormParam param = any_cast<BatchNormParam>(OpManager::GetOpDefParam(op_str)); const TM2_BatchNormParam* tm_param = GetTmPtr<TM2_BatchNormParam>(start_ptr, tm_op->offset_t_param); param.rescale_factor = tm_param->rescale_factor; param.eps = tm_param->eps; param.caffe_flavor = tm_param->caffe_flavor; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmResizeOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_BILINEARRESIZE; ResizeParam param = any_cast<ResizeParam>(OpManager::GetOpDefParam(op_str)); const TM2_ResizeParam* tm_param = GetTmPtr<TM2_ResizeParam>(start_ptr, tm_op->offset_t_param); param.scale_w = tm_param->scale_x; param.scale_h = tm_param->scale_y; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmConcatOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_CONCAT; ConcatParam param = any_cast<ConcatParam>(OpManager::GetOpDefParam(op_str)); const TM2_ConcatParam* tm_param = GetTmPtr<TM2_ConcatParam>(start_ptr, tm_op->offset_t_param); param.axis = tm_param->axis; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmConstOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_CONST); SetNodeOp(node, op); return true; } bool LoadTmConvOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_CONVOLUTION; ConvParam param = any_cast<ConvParam>(OpManager::GetOpDefParam(op_str)); const TM2_ConvParam* tm_param = GetTmPtr<TM2_ConvParam>(start_ptr, tm_op->offset_t_param); param.kernel_h = tm_param->kernel_h; param.kernel_w = tm_param->kernel_w; param.stride_h = tm_param->stride_h; param.stride_w = tm_param->stride_w; param.dilation_h = tm_param->dilation_h; param.dilation_w = tm_param->dilation_w; param.input_channel = tm_param->input_channel; param.output_channel = tm_param->output_channel; param.group = tm_param->group; param.activation = tm_param->activation; param.pad_h0 = tm_param->pad_h0; param.pad_h1 = tm_param->pad_h1; param.pad_w0 = tm_param->pad_w0; param.pad_w1 = tm_param->pad_w1; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmDeconvOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_DECONVOLUTION; DeconvParam param = any_cast<DeconvParam>(OpManager::GetOpDefParam(op_str)); const TM2_DeconvParam* tm_param = GetTmPtr<TM2_DeconvParam>(start_ptr, tm_op->offset_t_param); param.kernel_h = tm_param->kernel_h; param.kernel_w = tm_param->kernel_w; param.stride_h = tm_param->stride_h; param.stride_w = tm_param->stride_w; param.pad_w0 = tm_param->pad_w0; param.pad_w1 = tm_param->pad_w1; param.pad_h0 = tm_param->pad_h0; param.pad_h1 = tm_param->pad_h1; param.num_output = tm_param->num_output; param.dilation_h = tm_param->dilation_h; param.dilation_w = tm_param->dilation_w; param.group = tm_param->group; param.activation = tm_param->activation; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmDetectionOutputOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_DETECTIONOUTPUT; DetectionOutputParam param = any_cast<DetectionOutputParam>(OpManager::GetOpDefParam(op_str)); const TM2_DetectionOutputParam* tm_param = GetTmPtr<TM2_DetectionOutputParam>(start_ptr, tm_op->offset_t_param); param.num_classes = tm_param->num_classes; param.keep_top_k = tm_param->keep_top_k; param.nms_top_k = tm_param->nms_top_k; param.confidence_threshold = tm_param->confidence_threshold; param.nms_threshold = tm_param->nms_threshold; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmDropoutOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_DROPOUT); SetNodeOp(node, op); return true; } bool LoadTmEltwiseOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_ELTWISE; EltwiseParam param = any_cast<EltwiseParam>(OpManager::GetOpDefParam(op_str)); const TM2_EltwiseParam* tm_param = GetTmPtr<TM2_EltwiseParam>(start_ptr, tm_op->offset_t_param); param.type = static_cast<EltType>(tm_param->type); param.caffe_flavor = tm_param->caffe_flavor; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmFlattenOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_FLATTEN; FlattenParam param = any_cast<FlattenParam>(OpManager::GetOpDefParam(op_str)); const TM2_FlattenParam* tm_param = GetTmPtr<TM2_FlattenParam>(start_ptr, tm_op->offset_t_param); param.axis = tm_param->axis; param.end_axis = tm_param->end_axis; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmFCOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_FULLYCONNECTED; FCParam param = any_cast<FCParam>(OpManager::GetOpDefParam(op_str)); const TM2_FCParam* tm_param = GetTmPtr<TM2_FCParam>(start_ptr, tm_op->offset_t_param); param.num_output = tm_param->num_output; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmInputOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_INPUTOP); SetNodeOp(node, op); return true; } bool LoadTmLRNOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_LRN; LRNParam param = any_cast<LRNParam>(OpManager::GetOpDefParam(op_str)); const TM2_LRNParam* tm_param = GetTmPtr<TM2_LRNParam>(start_ptr, tm_op->offset_t_param); param.local_size = tm_param->local_size; param.alpha = tm_param->alpha; param.beta = tm_param->beta; param.norm_region = tm_param->norm_region; param.k = tm_param->k; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmNormalizeOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_NORMALIZE; NormalizeParam param = any_cast<NormalizeParam>(OpManager::GetOpDefParam(op_str)); const TM2_NormalizeParam* tm_param = GetTmPtr<TM2_NormalizeParam>(start_ptr, tm_op->offset_t_param); param.across_spatial = tm_param->across_spatial; param.channel_shared = tm_param->channel_shared; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmPermuteOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_PERMUTE; PermuteParam param = any_cast<PermuteParam>(OpManager::GetOpDefParam(op_str)); const TM2_PermuteParam* tm_param = GetTmPtr<TM2_PermuteParam>(start_ptr, tm_op->offset_t_param); param.flag = tm_param->flag; param.order0 = tm_param->order0; param.order1 = tm_param->order1; param.order2 = tm_param->order2; param.order3 = tm_param->order3; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmPoolingOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_POOLING; PoolParam param = any_cast<PoolParam>(OpManager::GetOpDefParam(op_str)); const TM2_PoolParam* tm_param = GetTmPtr<TM2_PoolParam>(start_ptr, tm_op->offset_t_param); param.alg = static_cast<PoolArg>(tm_param->alg); param.kernel_h = tm_param->kernel_h; param.kernel_w = tm_param->kernel_w; param.stride_h = tm_param->stride_h; param.stride_w = tm_param->stride_w; param.global = tm_param->global; param.caffe_flavor = tm_param->caffe_flavor; param.pad_h0 = tm_param->pad_h0; param.pad_w0 = tm_param->pad_w0; param.pad_h1 = tm_param->pad_h1; param.pad_w1 = tm_param->pad_w1; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmPreluOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_PRELU); SetNodeOp(node, op); return true; } bool LoadTmPriorBoxOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_PRIORBOX; PriorBoxParam param = any_cast<PriorBoxParam>(OpManager::GetOpDefParam(op_str)); const TM2_PriorBoxParam* tm_param = GetTmPtr<TM2_PriorBoxParam>(start_ptr, tm_op->offset_t_param); const TM2_Vector_floats* v_minsizes = GetTmPtr<TM2_Vector_floats>(start_ptr, tm_param->offset_vf_min_size); const TM2_Vector_floats* v_maxsizes = GetTmPtr<TM2_Vector_floats>(start_ptr, tm_param->offset_vf_max_size); const TM2_Vector_floats* v_variances = GetTmPtr<TM2_Vector_floats>(start_ptr, tm_param->offset_vf_variance); const TM2_Vector_floats* v_ratios = GetTmPtr<TM2_Vector_floats>(start_ptr, tm_param->offset_vf_aspect_ratio); for(unsigned int i = 0; i < v_minsizes->v_num; i++) param.min_size.push_back(v_minsizes->data[i]); for(unsigned int i = 0; i < v_maxsizes->v_num; i++) param.max_size.push_back(v_maxsizes->data[i]); for(unsigned int i = 0; i < v_variances->v_num; i++) param.variance.push_back(v_variances->data[i]); for(unsigned int i = 0; i < v_ratios->v_num; i++) param.aspect_ratio.push_back(v_ratios->data[i]); param.flip = tm_param->flip; param.clip = tm_param->clip; param.img_size = tm_param->img_size; param.img_h = tm_param->img_h; param.img_w = tm_param->img_w; param.step_w = tm_param->step_w; param.step_h = tm_param->step_h; param.offset = tm_param->offset; param.num_priors_ = tm_param->num_priors; param.out_dim_ = tm_param->out_dim; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmRegionOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_REGION; RegionParam param = any_cast<RegionParam>(OpManager::GetOpDefParam(op_str)); const TM2_RegionParam* tm_param = GetTmPtr<TM2_RegionParam>(start_ptr, tm_op->offset_t_param); const TM2_Vector_floats* v_biases = GetTmPtr<TM2_Vector_floats>(start_ptr, tm_param->offset_vf_biases); for(unsigned int i = 0; i < v_biases->v_num; i++) param.biases.push_back(v_biases->data[i]); param.num_classes = tm_param->num_classes; param.side = tm_param->side; param.num_box = tm_param->num_box; param.coords = tm_param->coords; param.confidence_threshold = tm_param->confidence_threshold; param.nms_threshold = tm_param->nms_threshold; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmReLuOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_RELU; ReLuParam param = any_cast<ReLuParam>(OpManager::GetOpDefParam(op_str)); const TM2_ReLuParam* tm_param = GetTmPtr<TM2_ReLuParam>(start_ptr, tm_op->offset_t_param); param.negative_slope = tm_param->negative_slope; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmRelu6Op(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_RELU6); SetNodeOp(node, op); return true; } bool LoadTmReorgOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_REORG; ReorgParam param = any_cast<ReorgParam>(OpManager::GetOpDefParam(op_str)); const TM2_ReorgParam* tm_param = GetTmPtr<TM2_ReorgParam>(start_ptr, tm_op->offset_t_param); param.stride = tm_param->stride; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmReshapeOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_RESHAPE; ReshapeParam param = any_cast<ReshapeParam>(OpManager::GetOpDefParam(op_str)); const TM2_ReshapeParam* tm_param = GetTmPtr<TM2_ReshapeParam>(start_ptr, tm_op->offset_t_param); param.dim_0 = tm_param->dim_0; param.dim_1 = tm_param->dim_1; param.dim_2 = tm_param->dim_2; param.dim_3 = tm_param->dim_3; param.dim_size = tm_param->dim_size; param.axis = tm_param->axis; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmROIPoolingOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_ROIPOOLING; ROIPoolingParam param = any_cast<ROIPoolingParam>(OpManager::GetOpDefParam(op_str)); const TM2_ROIPoolingParam* tm_param = GetTmPtr<TM2_ROIPoolingParam>(start_ptr, tm_op->offset_t_param); param.pooled_h = tm_param->pooled_h; param.pooled_w = tm_param->pooled_w; param.spatial_scale = tm_param->spatial_scale; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmRPNOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_RPN; RPNParam param = any_cast<RPNParam>(OpManager::GetOpDefParam(op_str)); const TM2_RPNParam* tm_param = GetTmPtr<TM2_RPNParam>(start_ptr, tm_op->offset_t_param); const TM2_Vector_floats* v_ratios = GetTmPtr<TM2_Vector_floats>(start_ptr, tm_param->offset_vf_ratios); const TM2_Vector_floats* v_scales = GetTmPtr<TM2_Vector_floats>(start_ptr, tm_param->offset_vf_anchor_scales); for(unsigned int i = 0; i < v_ratios->v_num; i++) param.ratios.push_back(v_ratios->data[i]); for(unsigned int i = 0; i < v_scales->v_num; i++) param.anchor_scales.push_back(v_scales->data[i]); param.feat_stride = tm_param->feat_stride; param.basesize = tm_param->basesize; param.min_size = tm_param->min_size; param.per_nms_topn = tm_param->per_nms_topn; param.post_nms_topn = tm_param->post_nms_topn; param.nms_thresh = tm_param->nms_thresh; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmScaleOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_SCALE; ScaleParam param = any_cast<ScaleParam>(OpManager::GetOpDefParam(op_str)); const TM2_ScaleParam* tm_param = GetTmPtr<TM2_ScaleParam>(start_ptr, tm_op->offset_t_param); param.axis = tm_param->axis; param.num_axes = tm_param->num_axes; param.bias_term = tm_param->bias_term; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmSliceOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_SLICE; SliceParam param = any_cast<SliceParam>(OpManager::GetOpDefParam(op_str)); const TM2_SliceParam* tm_param = GetTmPtr<TM2_SliceParam>(start_ptr, tm_op->offset_t_param); if(tm_param->offset_vi_slice_points != TM2_NOT_SET) { const TM2_Vector_dims* v_slice_points = GetTmPtr<TM2_Vector_dims>(start_ptr, tm_param->offset_vi_slice_points); for(unsigned int i = 0; i < v_slice_points->v_num; i++) param.slice_point_.push_back(v_slice_points->dims[i]); } if(tm_param->offset_vi_begins != TM2_NOT_SET) { const TM2_Vector_dims* v_begins = GetTmPtr<TM2_Vector_dims>(start_ptr, tm_param->offset_vi_begins); for(unsigned int i = 0; i < v_begins->v_num; i++) param.begin_.push_back(v_begins->dims[i]); } if(tm_param->offset_vi_sizes != TM2_NOT_SET) { const TM2_Vector_dims* v_sizes = GetTmPtr<TM2_Vector_dims>(start_ptr, tm_param->offset_vi_sizes); for(unsigned int i = 0; i < v_sizes->v_num; i++) param.size_.push_back(v_sizes->dims[i]); } param.axis = tm_param->axis; param.iscaffe = tm_param->iscaffe; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmSoftmaxOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_SOFTMAX; SoftmaxParam param = any_cast<SoftmaxParam>(OpManager::GetOpDefParam(op_str)); const TM2_SoftmaxParam* tm_param = GetTmPtr<TM2_SoftmaxParam>(start_ptr, tm_op->offset_t_param); param.axis = tm_param->axis; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmSplitOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_SPLIT); SetNodeOp(node, op); return true; } bool LoadTmDetectionPostProcessOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_DETECTIONPOSTPROCESS; DetectionPostProcessParam param = any_cast<DetectionPostProcessParam>(OpManager::GetOpDefParam(op_str)); const TM2_DetectionPostProcessParam* tm_param = GetTmPtr<TM2_DetectionPostProcessParam>(start_ptr, tm_op->offset_t_param); param.max_detections = tm_param->max_detections; param.max_classes_per_detection = tm_param->max_classes_per_detection; param.nms_score_threshold = tm_param->nms_score_threshold; param.nms_iou_threshold = tm_param->nms_iou_threshold; param.num_classes = tm_param->num_classes; const TM2_Vector_floats* v_scales = GetTmPtr<TM2_Vector_floats>(start_ptr, tm_param->offset_vf_scales); for(unsigned int i = 0; i < v_scales->v_num; i++) param.scales.push_back(v_scales->data[i]); StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmGemmOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_GEMM; GemmParam param = any_cast<GemmParam>(OpManager::GetOpDefParam(op_str)); const TM2_GemmParam* tm_param = GetTmPtr<TM2_GemmParam>(start_ptr, tm_op->offset_t_param); param.alpha = tm_param->alpha; param.beta = tm_param->beta; param.transA = tm_param->transA; param.transB = tm_param->transB; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmGenericOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_GENERIC; GenericParam param = any_cast<GenericParam>(OpManager::GetOpDefParam(op_str)); const TM2_GenericParam* tm_param = GetTmPtr<TM2_GenericParam>(start_ptr, tm_op->offset_t_param); param.max_input_num = tm_param->max_input_num; param.max_output_num = tm_param->max_output_num; const TM2_String* tm_string = GetTmPtr<TM2_String>(start_ptr, tm_param->offset_s_opname); char *op_name = (char *)malloc(tm_string->size); memcpy(op_name, GetTmPtr<char>(start_ptr, tm_string->offset_data), tm_string->size); param.op_name = op_name; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmLogisticOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_LOGISTIC); SetNodeOp(node, op); return true; } bool LoadTmLstmOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_LSTM; LSTMParam param = any_cast<LSTMParam>(OpManager::GetOpDefParam(op_str)); const TM2_LstmParam* tm_param = GetTmPtr<TM2_LstmParam>(start_ptr, tm_op->offset_t_param); param.forget_bias = tm_param->forget_bias; param.clip = tm_param->clip; param.output_len = tm_param->output_len; param.sequence_len = tm_param->sequence_len; param.input_size = tm_param->input_size; param.hidden_size = tm_param->hidden_size; param.cell_size = tm_param->cell_size; param.has_peephole = tm_param->has_peephole; param.has_projection = tm_param->has_projection; param.has_clip = tm_param->has_clip; param.has_bias = tm_param->has_bias; param.has_init_state = tm_param->has_init_state; param.forget_act = tm_param->forget_act; param.input_act = tm_param->input_act; param.output_act = tm_param->output_act; param.cellin_act = tm_param->cellin_act; param.cellout_act = tm_param->cellout_act; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmRnnOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_RNN; RNNParam param = any_cast<RNNParam>(OpManager::GetOpDefParam(op_str)); const TM2_RnnParam* tm_param = GetTmPtr<TM2_RnnParam>(start_ptr, tm_op->offset_t_param); param.clip = tm_param->clip; param.output_len = tm_param->output_len; param.sequence_len = tm_param->sequence_len; param.input_size = tm_param->input_size; param.hidden_size = tm_param->hidden_size; param.has_clip = tm_param->has_clip; param.has_bias = tm_param->has_bias; param.has_init_state = tm_param->has_init_state; param.activation = tm_param->activation; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmTanhOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_TANH); SetNodeOp(node, op); return true; } bool LoadTmSigmoidOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_SIGMOID); SetNodeOp(node, op); return true; } bool LoadTmSqueezeOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { const std::string& op_str = TM2_OPSTR_SQUEEZE; SqueezeParam param = any_cast<SqueezeParam>(OpManager::GetOpDefParam(op_str)); const TM2_SqueezeParam* tm_param = GetTmPtr<TM2_SqueezeParam>(start_ptr, tm_op->offset_t_param); param.dim_0 = tm_param->dim_0; param.dim_1 = tm_param->dim_1; param.dim_2 = tm_param->dim_2; param.dim_3 = tm_param->dim_3; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmFusedbnscalereluOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM2_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, TM2_OPSTR_FUSEDBNSCALERELU); SetNodeOp(node, op); return true; } op_load_t LoadTmOpFunc(uint32_t op_type) { switch(op_type) { case TM2_OPTYPE_ACCURACY: return LoadTmAccuracyOp; case TM2_OPTYPE_BATCHNORMALIZATION: return LoadTmBatchNormOp; case TM2_OPTYPE_BILINEARRESIZE: return LoadTmResizeOp; case TM2_OPTYPE_CONCAT: return LoadTmConcatOp; case TM2_OPTYPE_CONST: return LoadTmConstOp; case TM2_OPTYPE_CONVOLUTION: return LoadTmConvOp; case TM2_OPTYPE_DECONVOLUTION: return LoadTmDeconvOp; case TM2_OPTYPE_DETECTIONOUTPUT: return LoadTmDetectionOutputOp; case TM2_OPTYPE_DROPOUT: return LoadTmDropoutOp; case TM2_OPTYPE_ELTWISE: return LoadTmEltwiseOp; case TM2_OPTYPE_FLATTEN: return LoadTmFlattenOp; case TM2_OPTYPE_FULLYCONNECTED: return LoadTmFCOp; case TM2_OPTYPE_INPUTOP: return LoadTmInputOp; case TM2_OPTYPE_LRN: return LoadTmLRNOp; case TM2_OPTYPE_NORMALIZE: return LoadTmNormalizeOp; case TM2_OPTYPE_PERMUTE: return LoadTmPermuteOp; case TM2_OPTYPE_POOLING: return LoadTmPoolingOp; case TM2_OPTYPE_PRELU: return LoadTmPreluOp; case TM2_OPTYPE_PRIORBOX: return LoadTmPriorBoxOp; case TM2_OPTYPE_REGION: return LoadTmRegionOp; case TM2_OPTYPE_RELU: return LoadTmReLuOp; case TM2_OPTYPE_RELU6: return LoadTmRelu6Op; case TM2_OPTYPE_REORG: return LoadTmReorgOp; case TM2_OPTYPE_RESHAPE: return LoadTmReshapeOp; case TM2_OPTYPE_ROIPOOLING: return LoadTmROIPoolingOp; case TM2_OPTYPE_RPN: return LoadTmRPNOp; case TM2_OPTYPE_SCALE: return LoadTmScaleOp; case TM2_OPTYPE_SLICE: return LoadTmSliceOp; case TM2_OPTYPE_SOFTMAX: return LoadTmSoftmaxOp; case TM2_OPTYPE_SPLIT: return LoadTmSplitOp; case TM2_OPTYPE_DETECTIONPOSTPROCESS: return LoadTmDetectionPostProcessOp; case TM2_OPTYPE_GEMM: return LoadTmGemmOp; case TM2_OPTYPE_GENERIC: return LoadTmGenericOp; case TM2_OPTYPE_LOGISTIC: return LoadTmLogisticOp; case TM2_OPTYPE_LSTM: return LoadTmLstmOp; case TM2_OPTYPE_RNN: return LoadTmRnnOp; case TM2_OPTYPE_TANH: return LoadTmTanhOp; case TM2_OPTYPE_SIGMOID: return LoadTmSigmoidOp; case TM2_OPTYPE_SQUEEZE: return LoadTmSqueezeOp; case TM2_OPTYPE_FUSEDBNSCALERELU: return LoadTmFusedbnscalereluOp; default: LOG_ERROR() << "Operator #" << op_type << " not supported in tengine model yet\n"; return nullptr; } } std::string GetOpStr(uint32_t op_type) { switch(op_type) { case TM2_OPTYPE_ACCURACY: return std::string(TM2_OPSTR_ACCURACY); case TM2_OPTYPE_BATCHNORMALIZATION: return std::string(TM2_OPSTR_BATCHNORMALIZATION); case TM2_OPTYPE_BILINEARRESIZE: return std::string(TM2_OPSTR_BILINEARRESIZE); case TM2_OPTYPE_CONCAT: return std::string(TM2_OPSTR_CONCAT); case TM2_OPTYPE_CONST: return std::string(TM2_OPSTR_CONST); case TM2_OPTYPE_CONVOLUTION: return std::string(TM2_OPSTR_CONVOLUTION); case TM2_OPTYPE_DECONVOLUTION: return std::string(TM2_OPSTR_DECONVOLUTION); case TM2_OPTYPE_DETECTIONOUTPUT: return std::string(TM2_OPSTR_DETECTIONOUTPUT); case TM2_OPTYPE_DROPOUT: return std::string(TM2_OPSTR_DROPOUT); case TM2_OPTYPE_ELTWISE: return std::string(TM2_OPSTR_ELTWISE); case TM2_OPTYPE_FLATTEN: return std::string(TM2_OPSTR_FLATTEN); case TM2_OPTYPE_FULLYCONNECTED: return std::string(TM2_OPSTR_FULLYCONNECTED); case TM2_OPTYPE_INPUTOP: return std::string(TM2_OPSTR_INPUTOP); case TM2_OPTYPE_LRN: return std::string(TM2_OPSTR_LRN); case TM2_OPTYPE_NORMALIZE: return std::string(TM2_OPSTR_NORMALIZE); case TM2_OPTYPE_PERMUTE: return std::string(TM2_OPSTR_PERMUTE); case TM2_OPTYPE_POOLING: return std::string(TM2_OPSTR_POOLING); case TM2_OPTYPE_PRELU: return std::string(TM2_OPSTR_PRELU); case TM2_OPTYPE_PRIORBOX: return std::string(TM2_OPSTR_PRIORBOX); case TM2_OPTYPE_REGION: return std::string(TM2_OPSTR_REGION); case TM2_OPTYPE_RELU: return std::string(TM2_OPSTR_RELU); case TM2_OPTYPE_RELU6: return std::string(TM2_OPSTR_RELU6); case TM2_OPTYPE_REORG: return std::string(TM2_OPSTR_REORG); case TM2_OPTYPE_RESHAPE: return std::string(TM2_OPSTR_RESHAPE); case TM2_OPTYPE_ROIPOOLING: return std::string(TM2_OPSTR_ROIPOOLING); case TM2_OPTYPE_RPN: return std::string(TM2_OPSTR_RPN); case TM2_OPTYPE_SCALE: return std::string(TM2_OPSTR_SCALE); case TM2_OPTYPE_SLICE: return std::string(TM2_OPSTR_SLICE); case TM2_OPTYPE_SOFTMAX: return std::string(TM2_OPSTR_SOFTMAX); case TM2_OPTYPE_SPLIT: return std::string(TM2_OPSTR_SPLIT); case TM2_OPTYPE_DETECTIONPOSTPROCESS: return std::string(TM2_OPSTR_DETECTIONPOSTPROCESS); case TM2_OPTYPE_GEMM: return std::string(TM2_OPSTR_GEMM); case TM2_OPTYPE_GENERIC: return std::string(TM2_OPSTR_GENERIC); case TM2_OPTYPE_LOGISTIC: return std::string(TM2_OPSTR_LOGISTIC); case TM2_OPTYPE_LSTM: return std::string(TM2_OPSTR_LSTM); case TM2_OPTYPE_RNN: return std::string(TM2_OPSTR_RNN); case TM2_OPTYPE_TANH: return std::string(TM2_OPSTR_TANH); case TM2_OPTYPE_SIGMOID: return std::string(TM2_OPSTR_SIGMOID); case TM2_OPTYPE_SQUEEZE: return std::string(TM2_OPSTR_SQUEEZE); case TM2_OPTYPE_FUSEDBNSCALERELU: return std::string(TM2_OPSTR_FUSEDBNSCALERELU); default: LOG_ERROR() << "Get operator string failed\n"; return std::string(""); } } } // namespace TMSerializer2 } // namespace TEngine
36.794643
126
0.712388
ArmstrongYang
ad11dd5be153140c3c4eaa023dc8c6a12e2bd6e7
3,367
cpp
C++
Engine/src/shader.cpp
scilus/dmri-explorer
f23a9bf1af0ec41ef1f7b126bec237b6add542fb
[ "MIT" ]
1
2021-10-01T16:28:38.000Z
2021-10-01T16:28:38.000Z
Engine/src/shader.cpp
scilus/dmri-explorer
f23a9bf1af0ec41ef1f7b126bec237b6add542fb
[ "MIT" ]
12
2021-09-16T20:01:24.000Z
2022-03-24T00:24:17.000Z
Engine/src/shader.cpp
scilus/dmri-explorer
f23a9bf1af0ec41ef1f7b126bec237b6add542fb
[ "MIT" ]
3
2021-09-16T19:06:18.000Z
2022-02-17T19:49:05.000Z
#include "shader.h" #include "utils.hpp" #include <algorithm> #include <cstring> namespace { const int NUM_SHADER_INCLUDES = 3; const char* SHADER_INCLUDE_PATHS[NUM_SHADER_INCLUDES] = { "/include/camera_util.glsl", "/include/orthogrid_util.glsl", "/include/shfield_util.glsl" }; } namespace Slicer { namespace GPU { ShaderProgram::ShaderProgram(const std::string& filePath, const GLenum shaderType) :mShaderType(shaderType) { const std::string strShader = readFile(filePath); GLint lenShader[1] = { static_cast<GLint>(strShader.length()) }; const GLchar* strShaderC_str = strShader.c_str(); GLuint shaderID = glCreateShader(shaderType); glShaderSource(shaderID, 1, &strShaderC_str, lenShader); glCompileShaderIncludeARB(shaderID, mShaderIncludePaths.size(), mShaderIncludePaths.data(), mShaderIncludeLengths.data()); assertShaderCompilationSuccess(shaderID, filePath); this->mProgramID = glCreateProgram(); glProgramParameteri(this->mProgramID, GL_PROGRAM_SEPARABLE, GL_TRUE); glAttachShader(this->mProgramID, shaderID); glLinkProgram(this->mProgramID); assertProgramLinkingSuccess(this->mProgramID); } void ShaderProgram::CreateFilesystemForInclude() { for(int i = 0; i < NUM_SHADER_INCLUDES; ++i) { const auto pathName = SHADER_INCLUDE_PATHS[i]; const auto pathNameLen = std::strlen(pathName); const std::string strInclude = readFile( DMRI_EXPLORER_BINARY_DIR + std::string("/shaders") + pathName); // Add to virtual filesystem. glNamedStringARB(GL_SHADER_INCLUDE_ARB, pathNameLen, pathName, strInclude.length(), strInclude.c_str()); mShaderIncludePaths.push_back(pathName); mShaderIncludeLengths.push_back(static_cast<int>(pathNameLen)); } } ProgramPipeline::ProgramPipeline(const std::vector<ShaderProgram>& shaderPrograms) { glGenProgramPipelines(1, &this->mPipelineID); for(const ShaderProgram& p : shaderPrograms) { GLbitfield programStage = ProgramPipeline::convertShaderTypeToGLbitfield(p.Type()); glUseProgramStages(this->mPipelineID, programStage, p.ID()); } } ProgramPipeline::ProgramPipeline(const ShaderProgram& shaderProgram) { glGenProgramPipelines(1, &this->mPipelineID); GLbitfield programStage = ProgramPipeline::convertShaderTypeToGLbitfield(shaderProgram.Type()); glUseProgramStages(this->mPipelineID, programStage, shaderProgram.ID()); } const GLbitfield ProgramPipeline::convertShaderTypeToGLbitfield(const GLenum shaderType) const { switch(shaderType) { case GL_VERTEX_SHADER: return GL_VERTEX_SHADER_BIT; case GL_FRAGMENT_SHADER: return GL_FRAGMENT_SHADER_BIT; case GL_COMPUTE_SHADER: return GL_COMPUTE_SHADER_BIT; case GL_TESS_CONTROL_SHADER: return GL_TESS_CONTROL_SHADER_BIT; case GL_TESS_EVALUATION_SHADER: return GL_TESS_EVALUATION_SHADER_BIT; case GL_GEOMETRY_SHADER: return GL_GEOMETRY_SHADER_BIT; default: throw std::runtime_error("Invalid shader type."); } } void ProgramPipeline::Bind() const { glBindProgramPipeline(this->mPipelineID); } } // namespace GPU } // namespace Slicer
31.46729
99
0.702703
scilus
ad12b5d0153251ff19e9a2d64e2af07605ceb6be
1,408
hpp
C++
icarus/tcpserver.hpp
Jusot/icarus
1b908b0d7ff03d6ee088c94730acfef36101ef32
[ "MIT" ]
4
2019-04-01T10:49:54.000Z
2020-12-24T11:46:45.000Z
icarus/tcpserver.hpp
Jusot/Icarus
1b908b0d7ff03d6ee088c94730acfef36101ef32
[ "MIT" ]
null
null
null
icarus/tcpserver.hpp
Jusot/Icarus
1b908b0d7ff03d6ee088c94730acfef36101ef32
[ "MIT" ]
1
2019-04-04T02:36:29.000Z
2019-04-04T02:36:29.000Z
#ifndef ICARUS_TCPSERVER_HPP #define ICARUS_TCPSERVER_HPP #include <unordered_map> #include <string> #include <memory> #include "noncopyable.hpp" #include "inetaddress.hpp" #include "callbacks.hpp" namespace icarus { class InetAddress; class EventLoop; class Acceptor; class EventLoopThreadPool; class TcpServer : noncopyable { public: TcpServer(EventLoop* loop, const InetAddress& listen_addr, std::string name); ~TcpServer(); void set_thread_num(int num_threads); void start(); void set_connection_callback(ConnectionCallback cb); void set_message_callback(MessageCallback cb); void set_write_complete_callback(WriteCompleteCallback cb); private: void new_connection(int sockfd, const InetAddress& peer_addr); void remove_connection(const TcpConnectionPtr& conn); void remove_connection_in_loop(const TcpConnectionPtr& conn); using ConnectionMap = std::unordered_map<std::string, TcpConnectionPtr>; EventLoop* loop_; const std::string host_port_; const std::string name_; std::unique_ptr<Acceptor> acceptor_; std::unique_ptr<EventLoopThreadPool> thread_pool_; ConnectionCallback connection_callback_; MessageCallback message_callback_; WriteCompleteCallback write_complete_callback_; bool started_; int next_conn_id_; ConnectionMap connections_; }; } // namespace icarus #endif //ICARUS_TCPSERVER_HPP
25.142857
81
0.769176
Jusot
ad15ead714a8b3aa17abbd0a86b611b5e9148c17
743
cpp
C++
Recursive Algorithms/josephus.cpp
iabhimanyu/Algorithms
adefcd165e591d2338be8fc8a62629ff072620dd
[ "MIT" ]
715
2018-10-01T21:30:10.000Z
2022-03-23T09:14:10.000Z
Recursive Algorithms/josephus.cpp
iabhimanyu/Algorithms
adefcd165e591d2338be8fc8a62629ff072620dd
[ "MIT" ]
157
2018-10-01T20:53:11.000Z
2021-08-03T07:00:58.000Z
Recursive Algorithms/josephus.cpp
iabhimanyu/Algorithms
adefcd165e591d2338be8fc8a62629ff072620dd
[ "MIT" ]
1,225
2018-10-01T20:56:22.000Z
2022-02-22T04:00:27.000Z
#include <stdio.h> #include <iostream> using namespace std; /** * Algoritmo recursivo de Flavious Josephus * @author: Mateus Tranquilino * */ /** * Calcula o sobrevivente no problema de Flavious Josephus * em um circulo de N pessoas e de salto K. * */ int josephus(int n, int k){ if(n==1) return 1; return ( ( ( josephus(n-1, k) + k-1) % n ) + 1); } int main(){ unsigned int n, k; int x; printf("Quantos casos de Testes? "); scanf("%d", &x); for (int i=0; i < x; i++){ printf("O número de pessoas no circulo "); scanf("%d", &n); printf("O tamanho do salto "); scanf("%d", &k); printf("No caso %d a pessoa na posição %d termina viva\n", i+1, josephus(n,k)); cout << endl; } }
21.228571
83
0.577389
iabhimanyu
ad1b2e863fddd09f85e37a396ef59dc41467dbf0
957
cpp
C++
runnable/getaudioinforunnable.cpp
ilaotan/xmly-downloader-qt5
c263f0688f46d282f095ece6772f5e17d7d20478
[ "MIT" ]
null
null
null
runnable/getaudioinforunnable.cpp
ilaotan/xmly-downloader-qt5
c263f0688f46d282f095ece6772f5e17d7d20478
[ "MIT" ]
null
null
null
runnable/getaudioinforunnable.cpp
ilaotan/xmly-downloader-qt5
c263f0688f46d282f095ece6772f5e17d7d20478
[ "MIT" ]
null
null
null
#include "getaudioinforunnable.h" #include <QDebug> GetAudioInfoRunnable::GetAudioInfoRunnable(int trackID, int page, int pageSize) : audioId_(trackID), page_(page), pageSize_(pageSize) {} void GetAudioInfoRunnable::run() { auto dataError = CgoGetAudioInfo(audioId_, page_, pageSize_); if (dataError->error) { qWarning() << "get audio info fail: " << dataError->error; emit Error(QString(dataError->error), audioId_, page_, pageSize_); } else { QList<AudioItem *> list; auto array = static_cast<CArray *>(dataError->data); for (int i = 0; i < array->length; i++) { auto cgoAi = static_cast<CgoAudioItem *>(static_cast<void **>(array->pointer)[i]); AudioItem *ai = new AudioItem(); ai->id = cgoAi->id; ai->url = cgoAi->url; ai->title = cgoAi->title; ai->number = cgoAi->number; list.append(ai); delete cgoAi; } emit Finished(list); } delete dataError; }
29.90625
79
0.639498
ilaotan
ad1baaeb48291a3c19560b3429294248ab62682a
2,737
cpp
C++
dialog_search.cpp
farkoo/Real-Estate-Agency
9a30ea6bcaae836a6ec2ae09960e57636d8787fe
[ "MIT" ]
null
null
null
dialog_search.cpp
farkoo/Real-Estate-Agency
9a30ea6bcaae836a6ec2ae09960e57636d8787fe
[ "MIT" ]
null
null
null
dialog_search.cpp
farkoo/Real-Estate-Agency
9a30ea6bcaae836a6ec2ae09960e57636d8787fe
[ "MIT" ]
1
2021-02-20T15:55:26.000Z
2021-02-20T15:55:26.000Z
#include "dialog_search.h" #include<QDesktopWidget> Dialog_search::Dialog_search(QWidget *parent,int x) : QDialog(parent) { QDesktopWidget dw; int xx=dw.width()*0.2; int y=dw.height()*0.2; setFixedSize(xx,y); s=x; hint=new QLabel; label1=new QLabel; label2=new QLabel; lineedit1=new QLineEdit; lineedit2=new QLineEdit; layout1=new QVBoxLayout; layout2=new QVBoxLayout; layout3=new QHBoxLayout; pushbuttons=new QHBoxLayout; ok=new QPushButton("Ok"); cancel=new QPushButton("Cancel"); all=new QVBoxLayout; layout1->addWidget(label1); layout1->addWidget(label2); layout2->addWidget(lineedit1); layout2->addWidget(lineedit2); layout3->addLayout(layout1); layout3->addLayout(layout2); pushbuttons->addWidget(ok); pushbuttons->addWidget(cancel); all->addWidget(hint); all->addLayout(layout3); all->addLayout(pushbuttons); setLayout(all); if(s==1){ label1->setText("X"); label2->setText("Y"); hint->setText("Finding a painkiller with a base price of less than X\n and a building area of ​​more than Y."); } else if(s==2){ label1->setText("Z"); label2->hide(); lineedit2->hide(); hint->setText("See Housing in the vicinity of Z Street."); } else if(s==3){ label1->setText("N"); label2->hide(); lineedit2->hide(); hint->setText("View apartments that have more than 𝑁 houses."); } else if(s==4){ label1->setText("X"); label2->hide(); lineedit2->hide(); hint->setText("View apartments with at least a vacant house with an area of ​​𝑋."); } else if(s==5){ label1->setText("R"); label2->hide(); lineedit2->hide(); hint->setText("View apartments with at least an empty house\nwith room."); } connect(ok,SIGNAL(clicked()),this,SLOT(ok_slot())); connect(cancel,SIGNAL(clicked()),this,SLOT(cancel_slot())); } Dialog_search::~Dialog_search() { } void Dialog_search::ok_slot() { if(s==1){ if(lineedit1->text()==""||lineedit2->text()==""){ QMessageBox::information(this,"ERROR","You should fill all fields!!!"); return; } emit search_signal(lineedit1->text(),lineedit2->text()); } else { if(lineedit1->text()==""){ QMessageBox::information(this,"ERROR","You should fill this field!!!"); return; } emit search_signal(lineedit1->text()); } this->close(); } void Dialog_search::cancel_slot() { this->close(); }
27.09901
120
0.575082
farkoo
ad1c520897b33c1ff46e05cfb8905dd4051d53ba
361
hpp
C++
Helios/src/Input.hpp
rgracari/helio_test
2d516d16da4252c8f92f5c265b6151c6e87bc907
[ "Apache-2.0" ]
null
null
null
Helios/src/Input.hpp
rgracari/helio_test
2d516d16da4252c8f92f5c265b6151c6e87bc907
[ "Apache-2.0" ]
null
null
null
Helios/src/Input.hpp
rgracari/helio_test
2d516d16da4252c8f92f5c265b6151c6e87bc907
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Bitmask.hpp" namespace Helio { class Input { private: Bitmask thisFrameKeys; Bitmask lastFrameKeys; public: enum class Key { None = 0, ArrowLeft, ArrowRight, ArrowUp, ArrowDown, Esc }; void Update(); bool IsKeyPressed(Key keycode); bool IsKeyDown(Key keycode); bool IsKeyUp(Key keycode); }; }
12.033333
33
0.66205
rgracari
ad1d0040093879727d9f4956bb9fa75b2636b318
6,640
cpp
C++
quadrotor_motion_with_pid_control/subpackages/thrust_controller/src/source/thrust_controller.cpp
lesmesrafa/Multi-drone-behaviors
1d35e4f1df6d9dd8e158b01ec7577aa21ce0b9a3
[ "CC0-1.0" ]
null
null
null
quadrotor_motion_with_pid_control/subpackages/thrust_controller/src/source/thrust_controller.cpp
lesmesrafa/Multi-drone-behaviors
1d35e4f1df6d9dd8e158b01ec7577aa21ce0b9a3
[ "CC0-1.0" ]
null
null
null
quadrotor_motion_with_pid_control/subpackages/thrust_controller/src/source/thrust_controller.cpp
lesmesrafa/Multi-drone-behaviors
1d35e4f1df6d9dd8e158b01ec7577aa21ce0b9a3
[ "CC0-1.0" ]
null
null
null
#include "thrust_controller.hpp" void ThrustController::ownSetUp() { static ros::NodeHandle nh; std::string n_space ; std::string estimated_speed_topic; std::string estimated_pose_topic; std::string altitude_rate_yaw_rate_topic; std::string thrust_topic; std::string flight_action_topic; std::string robot_config_path; std::string yaml_config_file; ros_utils_lib::getPrivateParam<double> ("~uav_mass" , mass_ ,1); ros_utils_lib::getPrivateParam<std::string>("~namespace" , n_space ,"drone1"); ros_utils_lib::getPrivateParam<std::string>("~estimated_speed_topic" , estimated_speed_topic ,"self_localization/speed"); ros_utils_lib::getPrivateParam<std::string>("~estimated_pose_topic" , estimated_pose_topic ,"self_localization/pose"); ros_utils_lib::getPrivateParam<std::string>("~altitude_rate_yaw_rate_topic" , altitude_rate_yaw_rate_topic ,"actuator_command/altitude_rate_yaw_rate"); ros_utils_lib::getPrivateParam<std::string>("~thrust_topic" , thrust_topic ,"actuator_command/thrust"); ros_utils_lib::getPrivateParam<std::string>("~flight_action_topic" , flight_action_topic ,"actuator_command/flight_action"); ros_utils_lib::getPrivateParam<std::string>("~robot_config_path" , robot_config_path ,"configs/"+n_space); ros_utils_lib::getPrivateParam<std::string>("~yaml_config_file" , yaml_config_file ,"quadrotor_pid_controller_config.yaml"); std::cout << "uav_mass = " << mass_ << std::endl; altitude_rate_yaw_rate_sub_ = nh.subscribe("/" + n_space + "/" + altitude_rate_yaw_rate_topic,1,&ThrustController::altitudeRateYawRateCallback,this); pose_sub_ = nh.subscribe("/" + n_space + "/" + estimated_pose_topic ,1,&ThrustController::poseCallback,this); speeds_sub_ = nh.subscribe("/" + n_space + "/" + estimated_speed_topic,1,&ThrustController::speedsCallback,this); flight_action_sub = nh.subscribe("/" + n_space + "/" + flight_action_topic,1,&ThrustController::flightActionCallback,this); thrust_pub_ = nh.advertise<mavros_msgs::Thrust>("/" + n_space + "/" + thrust_topic,1); thrust_msg_.thrust = 0; // Load file YAML::Node yamlconf; try { yamlconf = YAML::LoadFile(robot_config_path+"/"+yaml_config_file); } catch (std::exception& e) { std::cout<<"Yaml config file does not exist in path: "<<robot_config_path<<"/"<<yaml_config_file<<" . Taking default values"<<std::endl; } if(yamlconf["thrust_controller"]){ Kp_ = yamlconf["thrust_controller"]["kp"].as<float>(); Ki = yamlconf["thrust_controller"]["ki"].as<float>(); Kd_ = yamlconf["thrust_controller"]["kd"].as<float>(); } //Code for publishing thrust value in a way that can be compared using rqt_plot tool (Only for debugging purposes #if DEBUG == 1 thrust_debugger_pub_ = nh.advertise<std_msgs::Float32MultiArray>("/"+n_space+"/"+"debug/thrust_controller",1); thrust_debugger_values_msg_.data = std::vector<float>(2); std_msgs::MultiArrayDimension dim; dim.label = "ThrustSignal"; dim.size = 2; dim.stride = 1; thrust_debugger_values_msg_.layout.dim.emplace_back(dim); roll_pitch_yaw_rate_thrust_sub_ = nh.subscribe("/"+n_space+"/"+"actuator_command/roll_pitch_yaw_rate_thrust_test",1, &ThrustController::rollPitchYawRateThrustCallback,this); roll_pitch_yaw_rate_thrust_pub_ = nh.advertise<mav_msgs::RollPitchYawrateThrust>("/"+n_space+"/"+"actuator_command/roll_pitch_yaw_rate_thrust",1); #endif } void ThrustController::computeThrust(double dz_reference){ // Initialize static variables static ros::Time prev_time = ros::Time::now(); static float accum_error = 0.0f; static float last_dz_error = 0.0f; static float last_reference = 0.0f; static ros_utils_lib::MovingAverageFilter dz_derivative_filtering(0.85); float& thrust = thrust_msg_.thrust; double dtime = (ros::Time::now()-prev_time).toSec(); prev_time = ros::Time::now(); double feed_forward = 0.0f; // double feed_forward = dz_reference_ - last_reference; float dz_error = (dz_reference- dz_measure_); float dz_derivative_error = (dz_error-last_dz_error)/(dtime+1e-9); // dz_derivative_error = dz_derivative_filtering.filterValue(dz_derivative_error); last_reference = dz_reference; last_dz_error = dz_error; accum_error += dz_error; accum_error = (accum_error > antiwindup_limit_)? antiwindup_limit_ : accum_error; accum_error = (accum_error < - antiwindup_limit_)? - antiwindup_limit_ : accum_error; thrust = mass_ * (GRAVITY_CONSTANT + feed_forward +Kp_ *dz_error + Ki*accum_error + Kd_*dz_derivative_error); thrust = thrust /(cos(pitch_)*cos(roll_)); // project Thrust in z axis thrust = (thrust < MIN_THRUST_)? MIN_THRUST_ : thrust; // LOW LIMIT THRUST IN [0, MAX_THRUST] thrust = (thrust > MAX_THRUST_)? MAX_THRUST_ : thrust; // HIGH LIMIT THRUST IN [0, MAX_THRUST] //std::cout << "dz_reference = " << dz_reference << std::endl; //std::cout << "dz_error = " << dz_error << std::endl; //std::cout << "thrust = " << thrust << std::endl; } void ThrustController::ownRun(){ computeThrust(dz_reference_); publishThrust(); } void ThrustController::publishThrust(){ thrust_pub_.publish(thrust_msg_); } // __________________________________CALLBACKS_________________________________________ void ThrustController::altitudeRateYawRateCallback(const geometry_msgs::TwistStamped& _msg){ thrust_msg_.header = _msg.header; dz_reference_ = _msg.twist.linear.z; } void ThrustController::speedsCallback(const geometry_msgs::TwistStamped& _msg){ dz_measure_ = _msg.twist.linear.z; } void ThrustController::poseCallback(const geometry_msgs::PoseStamped& _msg){ position_=_msg.pose.position; tf::Quaternion q; tf::quaternionMsgToTF(_msg.pose.orientation,q); tf::Matrix3x3 m(q); double roll,pitch,yaw; m.getRPY(roll, pitch, yaw); roll_ = roll; pitch_ = pitch; } /*------------------------ DEBUGGING FUNCTIONS --------------------------*/ #if DEBUG == 1 void ThrustController::rollPitchYawRateThrustCallback(const mav_msgs::RollPitchYawrateThrust& _msg){ std::cout << "dz_measure :"<< dz_measure_<< std::endl ; std::cout << "dz_reference :"<< dz_reference_<< std::endl ; thrust_debugger_values_msg_.data[0] = _msg.thrust.z; thrust_debugger_values_msg_.data[1] = thrust_msg_.thrust; thrust_debugger_pub_.publish(thrust_debugger_values_msg_); static mav_msgs::RollPitchYawrateThrust msg; msg = _msg; msg.thrust.z = thrust_msg_.thrust; std::cout << "prev_thrust :"<< _msg.thrust.z<< std::endl ; std::cout << "new_thrust :"<< msg.thrust.z<< std::endl ; roll_pitch_yaw_rate_thrust_pub_.publish(msg); } #endif
40.487805
152
0.72997
lesmesrafa
ad1d17efdba15af877522e3cd424bd40c8b47693
22,069
cpp
C++
modules/tracktion_engine/plugins/ARA/tracktion_MelodyneFileReader.cpp
adamnemecek/tracktion_engine
6770c21dd44b78dae4ae5da823a8e5094660c1de
[ "MIT", "Unlicense" ]
734
2018-11-16T09:39:40.000Z
2022-03-30T16:56:14.000Z
modules/tracktion_engine/plugins/ARA/tracktion_MelodyneFileReader.cpp
adamnemecek/tracktion_engine
6770c21dd44b78dae4ae5da823a8e5094660c1de
[ "MIT", "Unlicense" ]
100
2018-11-16T18:04:08.000Z
2022-03-31T17:47:53.000Z
modules/tracktion_engine/plugins/ARA/tracktion_MelodyneFileReader.cpp
adamnemecek/tracktion_engine
6770c21dd44b78dae4ae5da823a8e5094660c1de
[ "MIT", "Unlicense" ]
123
2018-11-16T15:51:50.000Z
2022-03-29T12:21:27.000Z
/* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ #if TRACKTION_ENABLE_ARA //============================================================================== #if JUCE_MSVC #pragma warning (push, 0) #elif JUCE_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wnon-virtual-dtor" #pragma clang diagnostic ignored "-Wreorder" #pragma clang diagnostic ignored "-Wunsequenced" #pragma clang diagnostic ignored "-Wint-to-pointer-cast" #pragma clang diagnostic ignored "-Wunused-parameter" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Woverloaded-virtual" #pragma clang diagnostic ignored "-Wshadow" #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" #if __clang_major__ >= 10 #pragma clang diagnostic ignored "-Wpragma-pack" #endif #endif #undef PRAGMA_ALIGN_SUPPORTED #undef VST_FORCE_DEPRECATED #define VST_FORCE_DEPRECATED 0 #ifndef JUCE_MSVC #define __cdecl #endif // If you get an error here, in order to build with ARA support you'll need // to include the SDK in your header search paths! #include "ARA_API/ARAVST3.h" #include "ARA_Library/Dispatch/ARAHostDispatch.h" #include "pluginterfaces/vst/ivstcomponent.h" #include "pluginterfaces/vst/ivstaudioprocessor.h" namespace ARA { DEF_CLASS_IID (IMainFactory) DEF_CLASS_IID (IPlugInEntryPoint) DEF_CLASS_IID (IPlugInEntryPoint2) } #if JUCE_MSVC #pragma warning (pop) #elif JUCE_CLANG #pragma clang diagnostic pop #endif namespace tracktion_engine { using namespace ARA; struct ARAClipPlayer : private SelectableListener { #include "tracktion_MelodyneInstanceFactory.h" #include "tracktion_ARAWrapperFunctions.h" #include "tracktion_ARAWrapperInterfaces.h" //============================================================================== ARAClipPlayer (Edit& ed, MelodyneFileReader& o, AudioClipBase& c) : owner (o), clip (c), file (c.getAudioFile()), edit (ed) { TRACKTION_ASSERT_MESSAGE_THREAD jassert (file.getFile().existsAsFile()); edit.tempoSequence.addSelectableListener (this); } ~ARAClipPlayer() { CRASH_TRACER TRACKTION_ASSERT_MESSAGE_THREAD edit.tempoSequence.removeSelectableListener (this); contentAnalyserChecker = nullptr; modelUpdater = nullptr; contentUpdater = nullptr; // Needs to happen before killing off ARA stuff if (auto p = getPlugin()) { p->hideWindowForShutdown(); if (auto pi = p->getAudioPluginInstance()) pi->releaseResources(); } if (auto doc = getDocument()) { if (doc->dci != nullptr) { { const ScopedDocumentEditor sde (*this, false); playbackRegionAndSource = nullptr; } melodyneInstance = nullptr; } } } //============================================================================== Edit& getEdit() { return edit; } AudioClipBase& getClip() { return clip; } ExternalPlugin* getPlugin() { return melodyneInstance != nullptr ? melodyneInstance->plugin.get() : nullptr; } const ARAFactory* getARAFactory() const { return melodyneInstance != nullptr ? melodyneInstance->factory : nullptr; } //============================================================================== bool initialise (ARAClipPlayer* clipToClone) { TRACKTION_ASSERT_MESSAGE_THREAD CRASH_TRACER if (auto doc = getDocument()) { ExternalPlugin::Ptr p = MelodyneInstanceFactory::getInstance (edit.engine).createPlugin (edit); if (p == nullptr || getDocument() == nullptr) return false; melodyneInstance.reset (MelodyneInstanceFactory::getInstance (edit.engine).createInstance (*p, doc->dcRef)); if (melodyneInstance == nullptr) return false; updateContent (clipToClone); return playbackRegionAndSource != nullptr && playbackRegionAndSource->playbackRegion != nullptr; } return false; } void contentHasChanged() { CRASH_TRACER updateContent (nullptr); owner.sendChangeMessage(); } void selectableObjectChanged (Selectable*) override { if (auto doc = getDocument()) { if (doc->musicalContext != nullptr) { doc->beginEditing (true); doc->musicalContext->update(); doc->endEditing (true); } } } void selectableObjectAboutToBeDeleted (Selectable*) override {} //============================================================================== void updateContent (ARAClipPlayer* clipToClone) { CRASH_TRACER TRACKTION_ASSERT_MESSAGE_THREAD if (MessageManager::getInstance()->isThisTheMessageThread() && getEdit().getTransport().isAllowedToReallocate()) { contentUpdater = nullptr; internalUpdateContent (clipToClone); } else { if (contentUpdater == nullptr) { contentUpdater = std::make_unique<ContentUpdater> (*this); } else { if (! contentUpdater->isTimerRunning()) //To avoid resetting it contentUpdater->startTimer (100); } } } //============================================================================== MidiMessageSequence getAnalysedMIDISequence() { CRASH_TRACER const int midiChannel = 1; MidiMessageSequence result; if (auto doc = getDocument()) { const ARADocumentControllerInterface* dci = doc->dci; ARADocumentControllerRef dcRef = doc->dcRef; ARAAudioSourceRef audioSourceRef = playbackRegionAndSource->audioSource->audioSourceRef; if (dci->isAudioSourceContentAvailable (dcRef, audioSourceRef, kARAContentTypeNotes)) { ARAContentReaderRef contentReaderRef = dci->createAudioSourceContentReader (dcRef, audioSourceRef, kARAContentTypeNotes, nullptr); int numEvents = (int) dci->getContentReaderEventCount (dcRef, contentReaderRef); for (int i = 0; i < numEvents; ++i) { if (auto note = static_cast<const ARAContentNote*> (dci->getContentReaderDataForEvent (dcRef, contentReaderRef, i))) { if (note->pitchNumber != kARAInvalidPitchNumber) { result.addEvent (MidiMessage::noteOn (midiChannel, note->pitchNumber, static_cast<float> (note->volume)), note->startPosition); result.addEvent (MidiMessage::noteOff (midiChannel, note->pitchNumber), note->startPosition + note->noteDuration); } } } dci->destroyContentReader (dcRef, contentReaderRef); } result.updateMatchedPairs(); } return result; } //============================================================================== void setViewSelection() { if (playbackRegionAndSource != nullptr) playbackRegionAndSource->setViewSelection(); } //============================================================================== void startProcessing() { TRACKTION_ASSERT_MESSAGE_THREAD if (playbackRegionAndSource != nullptr) playbackRegionAndSource->enable(); } void stopProcessing() { TRACKTION_ASSERT_MESSAGE_THREAD if (playbackRegionAndSource != nullptr) playbackRegionAndSource->disable(); } class ContentAnalyser { public: ContentAnalyser (const ARAClipPlayer& p) : pimpl (p) { } bool isAnalysing() { callBlocking ([this] { updateAnalysingContent(); }); return analysingContent; } void updateAnalysingContent() { CRASH_TRACER auto doc = pimpl.getDocument(); if (doc == nullptr) { analysingContent = false; return; } const ARADocumentControllerInterface* dci = doc->dci; ARADocumentControllerRef dcRef = doc->dcRef; ARAAudioSourceRef audioSourceRef = nullptr; if (pimpl.playbackRegionAndSource != nullptr) if (pimpl.playbackRegionAndSource->audioSource != nullptr) audioSourceRef = pimpl.playbackRegionAndSource->audioSource->audioSourceRef; if (dci != nullptr && dcRef != nullptr && audioSourceRef != nullptr) { if (firstCall) { auto araFactory = pimpl.getARAFactory(); for (ARAContentType contentType : { kARAContentTypeBarSignatures, kARAContentTypeTempoEntries }) { for (int i = 0; i < (int) araFactory->analyzeableContentTypesCount; i++) { if (araFactory->analyzeableContentTypes[i] == contentType) { typesBeingAnalyzed.push_back (contentType); break; } } } if (!typesBeingAnalyzed.empty()) dci->requestAudioSourceContentAnalysis (dcRef, audioSourceRef, (ARASize)typesBeingAnalyzed.size(), typesBeingAnalyzed.data()); firstCall = false; } analysingContent = false; for (ARAContentType contentType : typesBeingAnalyzed) { analysingContent = (dci->isAudioSourceContentAnalysisIncomplete (dcRef, audioSourceRef, contentType) != kARAFalse); if (analysingContent) break; } } else { analysingContent = false; } } private: const ARAClipPlayer& pimpl; std::vector<ARAContentType> typesBeingAnalyzed; volatile bool analysingContent = false; bool firstCall = true; ContentAnalyser() = delete; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentAnalyser) }; friend class ContentAnalyser; std::unique_ptr<ContentAnalyser> contentAnalyserChecker; bool isAnalysingContent() const { return contentAnalyserChecker->isAnalysing(); } ARADocument* getDocument() const; private: //============================================================================== MelodyneFileReader& owner; AudioClipBase& clip; const AudioFile file; Edit& edit; std::unique_ptr<MelodyneInstance> melodyneInstance; std::unique_ptr<PlaybackRegionAndSource> playbackRegionAndSource; int64 currentHashCode = 0; //============================================================================== struct ScopedDocumentEditor { ScopedDocumentEditor (ARAClipPlayer& o, bool restartModelUpdaterLater) : owner (o), restartTimerLater (restartModelUpdaterLater) { if (restartTimerLater) owner.modelUpdater = nullptr; owner.getDocument()->beginEditing (false); } ~ScopedDocumentEditor() { if (auto doc = owner.getDocument()) { doc->endEditing (false); if (restartTimerLater) owner.modelUpdater = std::make_unique<ModelUpdater> (*doc); } } private: ARAClipPlayer& owner; const bool restartTimerLater; JUCE_DECLARE_NON_COPYABLE (ScopedDocumentEditor) }; //============================================================================== /** NB: Must delete the old objects *after* creating the new ones, because Melodyne crashes if you deselect a play region and then try to select a different one. But doing it in the opposite order seems to work ok. */ void recreateTrack (ARAClipPlayer* clipToClone) { CRASH_TRACER TRACKTION_ASSERT_MESSAGE_THREAD jassert (melodyneInstance != nullptr); jassert (melodyneInstance->factory != nullptr); jassert (melodyneInstance->extensionInstance != nullptr); auto oldTrack = std::move (playbackRegionAndSource); playbackRegionAndSource = std::make_unique<PlaybackRegionAndSource> (*getDocument(), clip, *melodyneInstance->factory, *melodyneInstance->extensionInstance, String::toHexString (currentHashCode), clipToClone != nullptr ? clipToClone->playbackRegionAndSource.get() : nullptr); if (oldTrack != nullptr) { const ScopedDocumentEditor sde (*this, false); oldTrack = nullptr; } } void internalUpdateContent (ARAClipPlayer* clipToClone) { CRASH_TRACER TRACKTION_ASSERT_MESSAGE_THREAD if (auto doc = getDocument()) { jassert (doc->dci != nullptr); contentAnalyserChecker = nullptr; modelUpdater = nullptr; // Can't be editing the document in any way while restoring juce::int64 newHashCode = file.getHash() ^ file.getFile().getLastModificationTime().toMilliseconds() ^ (juce::int64) clip.itemID.getRawID(); if (currentHashCode != newHashCode) { currentHashCode = newHashCode; const ScopedDocumentEditor sde (*this, true); recreateTrack (clipToClone); } else { if (playbackRegionAndSource != nullptr && playbackRegionAndSource->playbackRegion != nullptr) { const ScopedDocumentEditor sde (*this, true); playbackRegionAndSource->playbackRegion->updateRange(); } } modelUpdater = std::make_unique<ModelUpdater> (*doc); if (contentAnalyserChecker == nullptr) contentAnalyserChecker = std::make_unique<ContentAnalyser> (*this); } } //============================================================================== struct ContentUpdater : public Timer { ContentUpdater (ARAClipPlayer& p) : owner (p) { startTimer (100); } ARAClipPlayer& owner; void timerCallback() override { CRASH_TRACER if (owner.getEdit().getTransport().isAllowedToReallocate()) { owner.internalUpdateContent (nullptr); stopTimer(); } } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentUpdater) }; std::unique_ptr<ContentUpdater> contentUpdater; //============================================================================== struct ModelUpdater : private Timer { ModelUpdater (ARADocument& d) : document (d) { startTimer (3000); } ARADocument& document; void timerCallback() override { CRASH_TRACER if (document.dci != nullptr && document.dcRef != nullptr) document.dci->notifyModelUpdates (document.dcRef); } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModelUpdater) }; std::unique_ptr<ModelUpdater> modelUpdater; //============================================================================== ARAClipPlayer() = delete; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ARAClipPlayer) }; //============================================================================== MelodyneFileReader::MelodyneFileReader (Edit& ed, AudioClipBase& clip) { TRACKTION_ASSERT_MESSAGE_THREAD CRASH_TRACER player.reset (new ARAClipPlayer (ed, *this, clip)); if (! player->initialise (nullptr)) player = nullptr; } MelodyneFileReader::MelodyneFileReader (Edit& ed, AudioClipBase& clip, MelodyneFileReader& other) { TRACKTION_ASSERT_MESSAGE_THREAD CRASH_TRACER if (other.player != nullptr) { player.reset (new ARAClipPlayer (ed, *this, clip)); if (! player->initialise (other.player.get())) player = nullptr; } jassert (player != nullptr); } MelodyneFileReader::~MelodyneFileReader() { TRACKTION_ASSERT_MESSAGE_THREAD CRASH_TRACER if (player != nullptr) if (auto plugin = player->getPlugin()) if (auto pi = plugin->getAudioPluginInstance()) pi->setPlayHead (nullptr); auto toDestroy = std::move (player); } //============================================================================== void MelodyneFileReader::showPluginWindow() { if (player != nullptr) player->setViewSelection(); if (auto p = getPlugin()) p->showWindowExplicitly(); } void MelodyneFileReader::hidePluginWindow() { if (auto p = getPlugin()) p->hideWindowForShutdown(); } ExternalPlugin* MelodyneFileReader::getPlugin() { if (isValid()) return player->getPlugin(); return {}; } //============================================================================== bool MelodyneFileReader::isAnalysingContent() { return player != nullptr && player->isAnalysingContent(); } void MelodyneFileReader::sourceClipChanged() { if (player != nullptr) player->updateContent (nullptr); } //============================================================================== MidiMessageSequence MelodyneFileReader::getAnalysedMIDISequence() { if (player != nullptr) return player->getAnalysedMIDISequence(); return {}; } void MelodyneFileReader::cleanUpOnShutdown() { ARAClipPlayer::MelodyneInstanceFactory::shutdown(); } //============================================================================== struct ARADocumentHolder::Pimpl { Pimpl (Edit& e) : edit (e) {} void initialise() { TRACKTION_ASSERT_MESSAGE_THREAD araDocument.reset (ARAClipPlayer::createDocument (edit)); if (araDocument != nullptr) { araDocument->beginRestoringState (edit.araDocument->lastState); visitAllTrackItems (edit, [] (TrackItem& i) { if (auto c = dynamic_cast<AudioClipBase*> (&i)) c->loadMelodyneState(); return true; }); araDocument->endRestoringState(); } } Edit& edit; std::unique_ptr<ARAClipPlayer::ARADocument> araDocument; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl) }; ARADocumentHolder::ARADocumentHolder (Edit& e, const juce::ValueTree& v) : edit (e), lastState (v) { } ARADocumentHolder::~ARADocumentHolder() { TRACKTION_ASSERT_MESSAGE_THREAD CRASH_TRACER pimpl = nullptr; } ARADocumentHolder::Pimpl* ARADocumentHolder::getPimpl() { if (pimpl == nullptr) { CRASH_TRACER pimpl.reset (new Pimpl (edit)); callBlocking ([this]() { pimpl->initialise(); }); } return pimpl.get(); } void ARADocumentHolder::flushStateToValueTree() { TRACKTION_ASSERT_MESSAGE_THREAD if (pimpl != nullptr) if (pimpl->araDocument != nullptr) pimpl->araDocument->flushStateToValueTree (lastState); } ARAClipPlayer::ARADocument* ARAClipPlayer::getDocument() const { if (auto l = edit.araDocument.get()) if (auto p = l->getPimpl()) return p->araDocument.get(); return {}; } } // namespace tracktion_engine #else //============================================================================== namespace tracktion_engine { struct ARADocumentHolder::Pimpl {}; struct ARAClipPlayer {}; MelodyneFileReader::MelodyneFileReader (Edit&, AudioClipBase&) {} MelodyneFileReader::MelodyneFileReader (Edit&, AudioClipBase&, MelodyneFileReader&) {} MelodyneFileReader::~MelodyneFileReader() {} void MelodyneFileReader::cleanUpOnShutdown() {} ExternalPlugin* MelodyneFileReader::getPlugin() { return {}; } void MelodyneFileReader::showPluginWindow() {} void MelodyneFileReader::hidePluginWindow() {} bool MelodyneFileReader::isAnalysingContent() { return false; } MidiMessageSequence MelodyneFileReader::getAnalysedMIDISequence() { return {}; } void MelodyneFileReader::sourceClipChanged() {} ARADocumentHolder::ARADocumentHolder (Edit& e, const juce::ValueTree&) : edit (e) { juce::ignoreUnused (edit); } ARADocumentHolder::~ARADocumentHolder() {} ARADocumentHolder::Pimpl* ARADocumentHolder::getPimpl() { return {}; } void ARADocumentHolder::flushStateToValueTree() {} } // namespace tracktion_engine #endif
31.662841
156
0.544338
adamnemecek
ad1da01581127b3687354f7b2d6dc194de671b41
696
cpp
C++
test_gendata.cpp
campfireai/lavastone
5c15a922172c1aa567a582ae6625d150b7a154ab
[ "Unlicense" ]
9
2021-09-14T23:10:26.000Z
2021-11-28T12:02:02.000Z
test_gendata.cpp
campfireai/lavastone
5c15a922172c1aa567a582ae6625d150b7a154ab
[ "Unlicense" ]
null
null
null
test_gendata.cpp
campfireai/lavastone
5c15a922172c1aa567a582ae6625d150b7a154ab
[ "Unlicense" ]
1
2021-09-16T04:54:31.000Z
2021-09-16T04:54:31.000Z
#include "gendata.hpp" #include <fstream> #include <iostream> int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "usage:\n" << "./test_gendata NUM_RECORDS\n"; exit(1); } size_t num_records = std::stoi(argv[1]); std::string fname = "data.csv"; std::cout << "writing " << num_records << " records to " << fname << "\n"; std::ofstream outfile; outfile.open(fname); outfile << "title,author,author_location,num_likes" << "\n"; for (auto r : random_recipes(num_records)) { outfile << "\"" << r.title << "\",\"" << r.author << "\",\"" << r.author_location << "\",\"" << r.num_likes << "\"\n"; } outfile.close(); }
25.777778
76
0.54023
campfireai
ad1ddad5142a021dc6e1cc083c4914ea6cea0fce
494
cpp
C++
src/render/idle_recognizer.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
3
2015-02-22T20:34:28.000Z
2020-03-04T08:55:25.000Z
src/render/idle_recognizer.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
22
2015-12-13T16:29:40.000Z
2017-03-04T15:45:44.000Z
src/render/idle_recognizer.cpp
Reaping2/Reaping2
0d4c988c99413e50cc474f6206cf64176eeec95d
[ "MIT" ]
14
2015-11-23T21:25:09.000Z
2020-07-17T17:03:23.000Z
#include "render/idle_recognizer.h" #include "core/i_move_component.h" namespace render { IdleRecognizer::IdleRecognizer( int32_t Id ) : Recognizer( Id ) { } bool IdleRecognizer::Recognize( Actor const& actor ) const { Opt<IMoveComponent> moveC = actor.Get<IMoveComponent>(); if ( !moveC.IsValid() ) { return true; } if ( !moveC->IsMoving() ) { //L1( " Idle RECOGNIZED! \n" ); return true; } return false; } } // namespace render
18.296296
60
0.615385
MrPepperoni
ad1e47e3e76af6fb97e3579a685fa52edbe3ea85
368
cpp
C++
bucket_6C/gnucash/ctemplate-patches/patch-libgnucash_engine_qofevent.cpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
17
2017-04-22T21:53:52.000Z
2021-01-21T16:57:55.000Z
bucket_6C/gnucash/ctemplate-patches/patch-libgnucash_engine_qofevent.cpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
186
2017-09-12T20:46:52.000Z
2021-11-27T18:15:14.000Z
bucket_6C/gnucash/ctemplate-patches/patch-libgnucash_engine_qofevent.cpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
74
2017-09-06T14:48:01.000Z
2021-08-28T02:48:27.000Z
--- libgnucash/engine/qofevent.cpp.orig 2020-06-07 16:56:25 UTC +++ libgnucash/engine/qofevent.cpp @@ -22,12 +22,8 @@ * * ********************************************************************/ -extern "C" -{ #include <config.h> #include <glib.h> -} - #include "qof.h" #include "qofevent-p.h"
23
71
0.388587
jrmarino
ad20873ab7d37247c6e6e99af3c83c82b6db1521
409
cpp
C++
cmake/test/main.cpp
blagodarin/seir
fec45228d161dabb8bb4aaa23c64ea218b84e8fd
[ "Apache-2.0" ]
null
null
null
cmake/test/main.cpp
blagodarin/seir
fec45228d161dabb8bb4aaa23c64ea218b84e8fd
[ "Apache-2.0" ]
null
null
null
cmake/test/main.cpp
blagodarin/seir
fec45228d161dabb8bb4aaa23c64ea218b84e8fd
[ "Apache-2.0" ]
null
null
null
// This file is part of Seir. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include <seir_base/string_utils.hpp> #include <seir_u8main/u8main.hpp> #include <iostream> #include <plf_colony.h> int u8main(int, char**) { std::string helloWorld = "Hello world!"; seir::normalizeWhitespace(helloWorld, seir::TrailingSpace::Remove); std::cerr << helloWorld << '\n'; return 0; }
21.526316
68
0.713936
blagodarin
ad22235ea03fb2f5c75be30d908be9762dad4ebe
745
cpp
C++
countFrequency.cpp
harshallgarg/CPP
4d15c5e5d426bb00d192368d21924ec9f017445f
[ "MIT" ]
2
2020-08-09T02:09:50.000Z
2020-08-09T07:07:47.000Z
countFrequency.cpp
harshallgarg/CPP
4d15c5e5d426bb00d192368d21924ec9f017445f
[ "MIT" ]
null
null
null
countFrequency.cpp
harshallgarg/CPP
4d15c5e5d426bb00d192368d21924ec9f017445f
[ "MIT" ]
4
2020-05-25T10:24:14.000Z
2021-05-03T07:52:35.000Z
// // CountFrequency.cpp // AnishC++ // // Created by Anish Mookherjee on 20/10/19. // Copyright © 2019 Anish Mookherjee. All rights reserved. // #include <iostream> using namespace std; int main() { int i,n; cout<<"Enter no. of elements you want to enter."<<endl; cin>>n; int a[n]; int b[9]; cout<<"Enter elements."<<endl; for(i=0;i<n;i++) { cin>>a[i]; b[a[i]]++; } int max=0,pos=0; for(i=0;i<9;i++) { for(int j=0;j<9;j++) { if(max<b[j]) { max=b[j]; pos=j; b[j]=0; } } if(max!=0) for(int k=0;k<max;k++) cout<<max<<endl; } return 0; }
17.325581
59
0.42953
harshallgarg
ad235f037bda26e9d8c38565b992726f81e290b0
2,078
cpp
C++
src/corners_cpp/main.cpp
satvik007/Scanner_OP
c146f67e3851cd537d62989842abfee7d34de2c0
[ "MIT" ]
null
null
null
src/corners_cpp/main.cpp
satvik007/Scanner_OP
c146f67e3851cd537d62989842abfee7d34de2c0
[ "MIT" ]
null
null
null
src/corners_cpp/main.cpp
satvik007/Scanner_OP
c146f67e3851cd537d62989842abfee7d34de2c0
[ "MIT" ]
1
2021-05-10T10:14:27.000Z
2021-05-10T10:14:27.000Z
/** * g++ main.cpp corners.cpp -o main.o `pkg-config --cflags --libs opencv4` -DDEBUG && ./main.o ../../data/img_23.jpg * * This document is part of the project ScanIN. See License for more details. * This is alternative implementation of corner detection algorithm. * Author : Satvik Choudhary * Created on : 12 July 2020 */ #include <bits/stdc++.h> #include <opencv/cv.hpp> #include <opencv2/core/core.hpp> #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "opencv2/calib3d.hpp" #include "corners.hpp" #include "dirent.h" #include <string> int main(int argc, char *argv[]) { #ifdef DEBUG // cv::namedWindow ("out", cv::WINDOW_AUTOSIZE); #endif if (argc == 1) { DIR *dir; struct dirent *ent; std::string dirName = "/home/satvik/codes/Scanner_OP/dataset"; if ((dir = opendir (dirName.c_str())) != NULL) { while ((ent = readdir (dir)) != NULL) { std::string fileName = ent->d_name; if (fileName.find(".jpg") != std::string::npos) { std::cout << fileName << std::endl; cv::Mat input = cv::imread(dirName + fileName, cv::IMREAD_COLOR); resize_image_if_bigger (input, input, 1500); #ifdef DEBUG // cv::imshow ("out", input); // cv::waitKey(0); #endif std::vector <cv::Point> rect; int ret = find_best_corners (input, rect); } } closedir (dir); } else { perror (""); return EXIT_FAILURE; } } else { std::string fileName = std::string (argv[1]); cv::Mat input = cv::imread(fileName, cv::IMREAD_COLOR); resize_image_if_bigger (input, input, 1500); std::vector <cv::Point> rect; int ret = find_best_corners (input, rect); } #ifdef DEBUG cv::destroyAllWindows(); #endif // cv::imwrite (outName, dst); return 0; }
29.267606
116
0.550529
satvik007
ad266f076a48f37607ab583853ff65d659e79f8a
5,190
hh
C++
src/transport/CMR.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/transport/CMR.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/transport/CMR.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
/* * CMR.hh * * Created on: May 17, 2012 * Author: robertsj */ #ifndef CMR_HH_ #define CMR_HH_ // Detran #include "WithinGroupAcceleration.hh" // System namespace detran { /*! * \class CMR * \brief Coarse Mesh Rebalance * * Consider the one group problem * \f[ * \Big ( \mu \frac{\partial}{\partial x} * + \eta \frac{\partial}{\partial y} * + \xi \frac{\partial}{\partial z} * \Big ) \psi + \Sigma_t(\vec{r}) \psi(\vec{r}, \hat{\Omega}) = * \Sigma_s(\vec{r}) \phi(\vec{r}) + q(\vec{r}, \hat{\Omega}) \, . * \f] * where we have explicitly separated the within-group scatter * from the external source. * * Suppose we integrate this over a coarse cell of volume * \f$ V = \Delta_x \Delta_y \Delta_z \f$ and over the * angular space, \f$ 4\pi \f$. The * streaming terms give rise to terms like * * \f[ * \begin{split} * & \int_{4\pi} \mu \int^{\Delta_y}_{0} \int^{\Delta_z}_{0} dy dz * \Bigg ( \frac{\partial \psi}{\partial x} \Big |_{x=\Delta_x} * -\frac{\partial \psi}{\partial x} \Big |_{x=0} \Bigg ) = * \int^{\Delta_y}_{0} \int^{\Delta_z}_{0} dy dz * \Big ( J_x(\Delta_x, y, z) - J_x(0, y, z) \Big ) \, , * \end{split} * \f] * * where \f$ J_x \f$ is the \f$x\f$-directed partial current. Similar * terms can be found for the other directions. * * We can write the integrated transport equation as * * \f[ * \Delta_y \Delta_z \Big ( \bar{J}_x(\Delta_x) - \bar{J}_x(0) \Big ) + * \Delta_x \Delta_z \Big ( \bar{J}_y(\Delta_y) - \bar{J}_y(0) \Big ) + * \Delta_x \Delta_y \Big ( \bar{J}_z(\Delta_z) - \bar{J}_z(0) \Big ) + * \Delta_x \Delta_y \Delta_z \bar{\Sigma_r} \bar{\phi}(\vec{r}) = * \Delta_x \Delta_y \Delta_z \bar{q}(\vec{r}) * \f] * * where we have defined the average current across a face of the box as * * \f[ * \bar{J}_x(x) = * \frac{\int^{\Delta_y}_{0} \int^{\Delta_z}_{0} dy dz J_x(x, y, z)} * {\int^{\Delta_y}_{0} \int^{\Delta_z}_{0} dy dz} \, . * \f] * * and similar averages for the removal rate and source. Note, it is * the \e removal rate of interest on the left. This requires a coarse * mesh averaged removal cross section and scalar flux. The removal * cross section is simply the total cross section minus the * within-group scattering cross section. As a consequence, the * source \f$ q \f$ does \e not include the within-group scatter source. * * We simplify notation by writing * * \f[ * \sum_{p \in (x,y,z)} \frac{1}{\Delta_{p}} * \Big ( \bar{J}_{p}(\Delta_{p}) - \bar{J}_{p}(0) \Big ) + * \bar{\Sigma_r} \bar{\phi}(\vec{r}) = * \bar{q}(\vec{r}) * \f] * * This neutron balance equation is not satisfied when the flux * in not converged. However, if we can somehow force the flux * to satisfy balance at the coarse level, then we can apply * any correction to the fine level. Let us define rebalance * factors \f$ f_i \f$ such that * * \f[ * \sum_{p \in (x,y,z)} \frac{1}{\Delta_{p}} * \Big ( \bar{J}_{p}(\Delta_{p}) - \bar{J}_{p}(0) \Big ) + * f_i \bar{\Sigma_r} \bar{\phi}_i = * \bar{q}(\vec{r}) * \f] * */ template <class D> class CMR : public WithinGroupAcceleration<D> { public: /// \name Useful Typedefs // \{ typedef SP<CMR> SP_acceleration; typedef WithingroupAcceleration<D> Base; typedef typename Base::SP_acceleration SP_base; typedef Base::SP_input SP_input; typedef Base::SP_material SP_material; typedef Base::SP_coarsemesh SP_coarsemesh; typedef Base::SP_currenttally SP_currenttally; typedef typename Base::SP_sweepsource SP_sweepsource; // \} /*! * \brief Constructor * * @param input Input database * @param material Material database * @param coarsemesh Coarse mesh * @param currenttally Current tally */ CMR(SP_input input, SP_material material, SP_coarsemesh coarsemesh, SP_currenttally currenttally); /// \name Public Interface /// \{ /*! * \brief Solve the low order equation to update the scalar flux moments * * @param group Energy group for this solve * @param phi Reference to the group flux to be updated. * @param source Smart pointer to up-to-date sweep source. * */ void accelerate(u_int group, State::moments_type &phi, SP_sweepsource source); /// \} private: /// \name Private Data /// \{ /// Cell-integrated removal rate vec_dbl d_R; /// Cell-integrated source vec_dbl d_Q; /// Rebalance factors. vec2_int d_f; /// \} /// \name Implementation /// \{ /*! * \brief Compute the coarse mesh integrated removal rate and source * @param phi Reference to fine mesh flux * @param source Smart pointer to sweep source */ void integrate(u_int group, State::moments_type &phi, SP_sweepsource source); /// \} }; } // end namespace detran #include "CMR.i.hh" #endif /* CMR_HH_ */
27.172775
75
0.584971
RLReed
ad270fc135aa168a8214ef24fd5419b8cad51509
11,906
cpp
C++
src/CoreGenPortal/PortalCore/CoreRegInfoWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
1
2019-06-25T13:06:14.000Z
2019-06-25T13:06:14.000Z
src/CoreGenPortal/PortalCore/CoreRegInfoWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
128
2018-10-23T12:45:15.000Z
2021-12-28T13:09:39.000Z
src/CoreGenPortal/PortalCore/CoreRegInfoWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
1
2021-01-20T23:17:34.000Z
2021-01-20T23:17:34.000Z
// // _COREREGINFOWIN_CPP_ // // Copyright (C) 2017-2020 Tactical Computing Laboratories, LLC // All Rights Reserved // contact@tactcomplabs.com // // See LICENSE in the top level directory for licensing details // #include "CoreGenPortal/PortalCore/CoreRegInfoWin.h" // Event Table wxBEGIN_EVENT_TABLE(CoreRegInfoWin, wxDialog) EVT_BUTTON(wxID_OK, CoreRegInfoWin::OnPressOk) EVT_BUTTON(wxID_SAVE, CoreRegInfoWin::OnSave) wxEND_EVENT_TABLE() CoreRegInfoWin::CoreRegInfoWin( wxWindow* parent, wxWindowID id, const wxString& title, CoreGenReg *Reg ) : wxDialog( parent, id, title, wxDefaultPosition, wxSize(500,500), wxDEFAULT_DIALOG_STYLE|wxVSCROLL ){ RegNode = (CoreGenReg*)Reg; // init the internals this->SetLayoutAdaptationMode(wxDIALOG_ADAPTATION_MODE_ENABLED); this->SetSizeHints( wxDefaultSize, wxDefaultSize ); // create the outer box sizer OuterSizer = new wxBoxSizer( wxVERTICAL ); // create the scrolled window Wnd = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, wxT("Scroll")); // create the inner sizer InnerSizer = new wxBoxSizer( wxVERTICAL ); // add all the interior data // -- reg name RegNameSizer = new wxBoxSizer( wxHORIZONTAL ); RegNameText = new wxStaticText( Wnd, 4, wxT("Register Name"), wxDefaultPosition, wxSize(160,-1), 0 ); RegNameText->Wrap(-1); RegNameSizer->Add( RegNameText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); RegNameCtrl = new wxTextCtrl( Wnd, 0, Reg ? wxString(Reg->GetName()) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Reg Name") ); RegNameSizer->Add( RegNameCtrl, 0, wxALL, 0 ); InnerSizer->Add(RegNameSizer, 0, wxALIGN_CENTER|wxALL, 5 ); //-- reg idx RegIdxSizer = new wxBoxSizer( wxHORIZONTAL ); RegIdxText = new wxStaticText( Wnd, 5, wxT("Register Index"), wxDefaultPosition, wxSize(160, -1), 0 ); RegIdxText->Wrap(-1); RegIdxSizer->Add( RegIdxText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); RegIdxCtrl = new wxTextCtrl( Wnd, 1, Reg ? wxString::Format(wxT("%i"),Reg->GetIndex()) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Register Index") ); RegIdxSizer->Add( RegIdxCtrl, 0, wxALL, 0 ); InnerSizer->Add(RegIdxSizer, 0, wxALIGN_CENTER|wxALL, 5); //-- width WidthSizer = new wxBoxSizer( wxHORIZONTAL ); WidthText = new wxStaticText( Wnd, 6, wxT("Register Width (in bits)"), wxDefaultPosition, wxSize(160, -1), 0 ); WidthText->Wrap(-1); WidthSizer->Add( WidthText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); WidthCtrl = new wxTextCtrl( Wnd, 2, Reg ? wxString::Format(wxT("%i"),Reg->GetWidth()): "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Register Width") ); WidthSizer->Add( WidthCtrl, 0, wxALL, 0 ); InnerSizer->Add( WidthSizer, 0, wxALIGN_CENTER|wxALL, 5 ); //-- simd SIMDSizer = new wxBoxSizer( wxHORIZONTAL ); SIMDText = new wxStaticText( Wnd, 8, wxT("SIMD Width (in bits)"), wxDefaultPosition, wxSize(160, -1), 0 ); SIMDText->Wrap(-1); SIMDSizer->Add( SIMDText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); SIMDCtrl = new wxTextCtrl( Wnd, 16, Reg ? std::to_string(Reg->GetSIMDWidth()) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Register Width") ); SIMDSizer->Add( SIMDCtrl, 0, wxALL, 0 ); InnerSizer->Add( SIMDSizer, 0, wxALIGN_CENTER|wxALL, 5 ); //-- subregs SubRegSizer = new wxBoxSizer( wxHORIZONTAL ); SubRegText = new wxStaticText( Wnd, 7, wxT("Subregister Fields"), wxDefaultPosition, wxSize(160, -1), 0 ); WidthText->Wrap(-1); SubRegSizer->Add( SubRegText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); SubRegCtrl = new wxTextCtrl( Wnd, 3, wxEmptyString, wxDefaultPosition, wxSize(320,100), wxTE_MULTILINE|wxHSCROLL, wxDefaultValidator, wxT("Subregisters ") ); SubRegCtrl->AppendText(wxT("NAME:START_BIT:END_BIT\n")); std::string SRName; unsigned SRStart; unsigned SREnd; if(Reg){ for( unsigned i=0; i<Reg->GetNumSubRegs(); i++ ){ Reg->GetSubReg(i,SRName,SRStart,SREnd); SubRegCtrl->AppendText(wxString(SRName) + wxT(":") + wxString::Format(wxT("%i"),SRStart) + wxT(":") + wxString::Format(wxT("%i"),SREnd) + wxT("\n") ); } } SubRegSizer->Add( SubRegCtrl, 0, wxALL, 0 ); InnerSizer->Add( SubRegSizer, 0, wxALIGN_CENTER|wxALL, 5 ); HCheckSizer1 = new wxBoxSizer( wxHORIZONTAL ); /* if( Reg && Reg->IsSIMD() ) SIMDCheck->SetValue(true); else SIMDCheck->SetValue(false); HCheckSizer1->Add(SIMDCheck, 0, wxALL, 0); */ //-- rw check box RWCheck = new wxCheckBox( Wnd, 9, wxT("Read/Write Register"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT, wxDefaultValidator, wxT("RWREGISTER") ); if( Reg && Reg->IsRWAttr() ) RWCheck->SetValue(true); else RWCheck->SetValue(false); HCheckSizer1->Add(RWCheck, 0, wxALL, 0); //-- ro check box ROCheck = new wxCheckBox( Wnd, 10, wxT("Read-Only Register"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT, wxDefaultValidator, wxT("ROREGISTER") ); if( Reg && Reg->IsROAttr() ) ROCheck->SetValue(true); else ROCheck->SetValue(false); HCheckSizer1->Add(ROCheck, 0, wxALL, 0 ); InnerSizer->Add(HCheckSizer1, 0, wxALIGN_CENTER|wxALL, 5 ); HCheckSizer2 = new wxBoxSizer( wxHORIZONTAL ); //-- csr check box CSRCheck = new wxCheckBox( Wnd, 11, wxT("Config Status Register"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT, wxDefaultValidator, wxT("CSRREGISTER") ); if( Reg && Reg->IsCSRAttr() ) CSRCheck->SetValue(true); else CSRCheck->SetValue(false); HCheckSizer2->Add(CSRCheck, 0, wxALL, 0); //-- ams check box AMSCheck = new wxCheckBox( Wnd, 12, wxT("Arithmetic Machine State Register"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT, wxDefaultValidator, wxT("AMSREGISTER") ); if( Reg && Reg->IsAMSAttr() ) AMSCheck->SetValue(true); else AMSCheck->SetValue(false); HCheckSizer2->Add(AMSCheck, 0, wxALL, 0); InnerSizer->Add( HCheckSizer2, 0, wxALIGN_CENTER|wxALL, 5 ); HCheckSizer3 = new wxBoxSizer( wxHORIZONTAL ); //-- tus check box TUSCheck = new wxCheckBox( Wnd, 13, wxT("Thread Unit Shared Register"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT, wxDefaultValidator, wxT("TUSREGISTER") ); if( Reg && Reg->IsTUSAttr() ) TUSCheck->SetValue(true); else TUSCheck->SetValue(false); HCheckSizer3->Add(TUSCheck, 0, wxALL, 0); //-- pc check box PCCheck = new wxCheckBox( Wnd, 14, wxT("PC Register"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT, wxDefaultValidator, wxT("PCREGISTER") ); if( Reg && Reg->IsPCAttr() ) PCCheck->SetValue(true); else PCCheck->SetValue(false); HCheckSizer3->Add(PCCheck, 0, wxALL, 0); //-- shared check box SharedCheck = new wxCheckBox( Wnd, 15, wxT("Shared Register"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT, wxDefaultValidator, wxT("SHAREDREGISTER") ); if( Reg && Reg->IsShared() ) SharedCheck->SetValue(true); else SharedCheck->SetValue(false); HCheckSizer3->Add(SharedCheck, 0, wxALL, 0); InnerSizer->Add( HCheckSizer3, 0, wxALIGN_CENTER|wxALL, 5 ); // add the static line FinalStaticLine = new wxStaticLine( Wnd, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); InnerSizer->Add( FinalStaticLine, 1, wxEXPAND | wxALL, 5 ); // setup all the buttons m_socbuttonsizer = new wxStdDialogButtonSizer(); m_userOK = new wxButton( Wnd, wxID_CANCEL ); m_userSAVE = new wxButton( Wnd, wxID_SAVE); m_socbuttonsizer->SetAffirmativeButton( m_userOK ); m_socbuttonsizer->SetCancelButton( m_userSAVE ); m_socbuttonsizer->Realize(); InnerSizer->Add( m_socbuttonsizer, 0, wxALL, 5 ); Wnd->SetScrollbars(20,20,50,50); Wnd->SetSizer( InnerSizer ); Wnd->SetAutoLayout(true); Wnd->Layout(); // draw the dialog box until we get more info OuterSizer->Add(Wnd, 1, wxEXPAND | wxALL, 5 ); this->SetSizer( OuterSizer ); this->SetAutoLayout( true ); this->Layout(); } void CoreRegInfoWin::OnPressOk(wxCommandEvent& ok){ this->EndModal(wxID_OK); } void CoreRegInfoWin::OnSave(wxCommandEvent& save){ PortalMainFrame *PMF = (PortalMainFrame*)this->GetParent(); if(PMF->OnSave(this, this->RegNode, CGReg)) this->EndModal(wxID_SAVE); } CoreRegInfoWin::~CoreRegInfoWin(){ } // EOF
34.914956
83
0.484378
opensocsysarch
ad275d65ce1a69ad14aa13f5123e9981e71c79e0
3,886
cc
C++
FWCore/Utilities/src/EDMException.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
FWCore/Utilities/src/EDMException.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
null
null
null
FWCore/Utilities/src/EDMException.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
1
2019-04-03T19:23:27.000Z
2019-04-03T19:23:27.000Z
#include "FWCore/Utilities/interface/EDMException.h" #define FILLENTRY( name ) {name, #name } namespace edm { namespace errors { static const std::map<ErrorCodes, std::string> codeMap = { FILLENTRY(CommandLineProcessing), FILLENTRY(ConfigFileNotFound), FILLENTRY(ConfigFileReadError), FILLENTRY(OtherCMS), FILLENTRY(StdException), FILLENTRY(Unknown), FILLENTRY(BadAlloc), FILLENTRY(BadExceptionType), FILLENTRY(ProductNotFound), FILLENTRY(DictionaryNotFound), FILLENTRY(NoProductSpecified), FILLENTRY(InsertFailure), FILLENTRY(Configuration), FILLENTRY(LogicError), FILLENTRY(UnimplementedFeature), FILLENTRY(InvalidReference), FILLENTRY(NullPointerError), FILLENTRY(EventTimeout), FILLENTRY(EventCorruption), FILLENTRY(ScheduleExecutionFailure), FILLENTRY(EventProcessorFailure), FILLENTRY(FileInPathError), FILLENTRY(FileOpenError), FILLENTRY(FileReadError), FILLENTRY(FatalRootError), FILLENTRY(MismatchedInputFiles), FILLENTRY(ProductDoesNotSupportViews), FILLENTRY(ProductDoesNotSupportPtr), FILLENTRY(NotFound), FILLENTRY(FormatIncompatibility), FILLENTRY(FallbackFileOpenError), FILLENTRY(NoSecondaryFiles), FILLENTRY(ExceededResourceVSize), FILLENTRY(ExceededResourceRSS), FILLENTRY(ExceededResourceTime), FILLENTRY(FileWriteError), FILLENTRY(EventGenerationFailure), FILLENTRY(CaughtSignal) }; static const std::string kUnknownCode("unknownCode"); } /// -------------- implementation details ------------------ const std::string& Exception::codeToString(errors::ErrorCodes c) { auto i(errors::codeMap.find(c)); return i!=errors::codeMap.end() ? i->second : errors::kUnknownCode; } Exception::Exception(errors::ErrorCodes aCategory): cms::Exception(codeToString(aCategory)), category_(aCategory) { } Exception::Exception(errors::ErrorCodes aCategory, std::string const& message): cms::Exception(codeToString(aCategory),message), category_(aCategory) { } Exception::Exception(errors::ErrorCodes aCategory, char const* message): cms::Exception(codeToString(aCategory), std::string(message)), category_(aCategory) { } Exception::Exception(errors::ErrorCodes aCategory, std::string const& message, cms::Exception const& another): cms::Exception(codeToString(aCategory),message,another), category_(aCategory) { } Exception::Exception(errors::ErrorCodes aCategory, char const* message, cms::Exception const& another): cms::Exception(codeToString(aCategory), std::string(message), another), category_(aCategory) { } Exception::Exception(Exception const& other): cms::Exception(other), category_(other.category_) { } Exception::~Exception() noexcept { } Exception& Exception::operator=(Exception const& other) { Exception temp(other); this->swap(temp); return *this; } int Exception::returnCode_() const { return static_cast<int>(category_); } void Exception::throwThis(errors::ErrorCodes aCategory, char const* message0, char const* message1, char const* message2, char const* message3, char const* message4) { Exception e(aCategory, std::string(message0)); e << message1 << message2 << message3 << message4; throw e; } void Exception::throwThis(errors::ErrorCodes aCategory, char const* message0, int intVal, char const* message1) { Exception e(aCategory, std::string(message0)); e << intVal << message1; throw e; } Exception* Exception::clone() const { return new Exception(*this); } void Exception::rethrow() { throw *this; } }
29.664122
112
0.673958
bisnupriyasahu
ad2c6f33cff15e436e69dd2540314cc2cc8144ad
4,895
cpp
C++
src/XliPlatform/sdl2/SDL2GLContext.cpp
mortend/uno-base
53bf65ca269f89e3b6ac01845a1de498963c5cca
[ "MIT" ]
4
2018-05-14T07:49:34.000Z
2018-05-21T06:40:17.000Z
src/XliPlatform/sdl2/SDL2GLContext.cpp
mortend/uno-base
53bf65ca269f89e3b6ac01845a1de498963c5cca
[ "MIT" ]
2
2018-10-21T12:40:49.000Z
2020-04-16T17:55:55.000Z
src/XliPlatform/sdl2/SDL2GLContext.cpp
mortend/uno-base
53bf65ca269f89e3b6ac01845a1de498963c5cca
[ "MIT" ]
4
2018-05-14T17:03:51.000Z
2018-12-01T08:05:02.000Z
#include <XliPlatform/GLContext.h> #include <XliPlatform/GL.h> #include <XliPlatform/PlatformSpecific/SDL2.h> #include <uBase/Memory.h> namespace Xli { namespace PlatformSpecific { class SDL2GLContext: public GLContext { SDL_Window* window; SDL_GLContext context; public: SDL2GLContext(Window* wnd, const GLContextAttributes& attribs) { SDL_GL_SetAttribute(SDL_GL_RED_SIZE, attribs.ColorBits.R); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, attribs.ColorBits.G); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, attribs.ColorBits.B); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, attribs.ColorBits.A); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, attribs.DepthBits); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, attribs.StencilBits); #ifndef IOS SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, attribs.Samples > 1 ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, attribs.Samples); #endif SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, attribs.AccumBits.R); SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, attribs.AccumBits.G); SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, attribs.AccumBits.B); SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, attribs.AccumBits.A); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, attribs.Buffers <= 1 ? 0 : 1); SDL_GL_SetAttribute(SDL_GL_STEREO, attribs.Stereo ? 1 : 0); #ifdef U_GL_ES2 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); #endif window = SDL2::GetWindowHandle(wnd); context = SDL_GL_CreateContext(window); if (!context) throw Exception("Failed to create OpenGL context"); Vector2i vp = wnd->GetClientSize(); glViewport(0, 0, vp.X, vp.Y); #ifdef U_GL_DESKTOP glewInit(); #endif } virtual ~SDL2GLContext() { SDL_GL_DeleteContext(context); } virtual GLContext* CreateSharedContext() { throw NotSupportedException(U_FUNCTION); } virtual void MakeCurrent(Window* wnd) { if (wnd) window = SDL2::GetWindowHandle(wnd); SDL_GL_MakeCurrent(wnd ? window : 0, wnd ? context : 0); } virtual bool IsCurrent() { return SDL_GL_GetCurrentContext() == context; } virtual void SwapBuffers() { SDL_GL_SwapWindow(window); } virtual void SetSwapInterval(int value) { SDL_GL_SetSwapInterval(value); } virtual int GetSwapInterval() { return SDL_GL_GetSwapInterval(); } virtual Vector2i GetDrawableSize() { Vector2i size; #ifdef LINUX SDL_GetWindowSize(window, &size.X, &size.Y); #else SDL_GL_GetDrawableSize(window, &size.X, &size.Y); #endif return size; } virtual void GetAttributes(GLContextAttributes& result) { memset(&result, 0, sizeof(GLContextAttributes)); SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &result.ColorBits.R); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &result.ColorBits.G); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &result.ColorBits.B); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &result.ColorBits.A); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &result.DepthBits); SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &result.StencilBits); SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &result.Samples); SDL_GL_GetAttribute(SDL_GL_ACCUM_RED_SIZE, &result.AccumBits.R); SDL_GL_GetAttribute(SDL_GL_ACCUM_GREEN_SIZE, &result.AccumBits.G); SDL_GL_GetAttribute(SDL_GL_ACCUM_BLUE_SIZE, &result.AccumBits.B); SDL_GL_GetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, &result.AccumBits.A); int doubleBuffer, stereo; SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &doubleBuffer); SDL_GL_GetAttribute(SDL_GL_STEREO, &stereo); result.Buffers = doubleBuffer ? 2 : 1; result.Stereo = stereo ? true : false; } }; } GLContext* GLContext::Create(Window* wnd, const GLContextAttributes& attribs) { return new PlatformSpecific::SDL2GLContext(wnd, attribs); } }
36.804511
92
0.595914
mortend
ad2fca2be272ebdf99a91378118a5b9f0eb02e6a
1,263
cc
C++
PhysicsTools/JetCharge/plugins/JetChargeProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
PhysicsTools/JetCharge/plugins/JetChargeProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
PhysicsTools/JetCharge/plugins/JetChargeProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "PhysicsTools/JetCharge/plugins/JetChargeProducer.h" JetChargeProducer::JetChargeProducer(const edm::ParameterSet &cfg) : srcToken_(consumes<reco::JetTracksAssociationCollection>(cfg.getParameter<edm::InputTag>("src"))), algo_(cfg) { produces<JetChargeCollection>(); } void JetChargeProducer::produce(edm::StreamID, edm::Event &iEvent, const edm::EventSetup &iSetup) const { edm::Handle<reco::JetTracksAssociationCollection> hJTAs; iEvent.getByToken(srcToken_, hJTAs); typedef reco::JetTracksAssociationCollection::const_iterator IT; typedef edm::RefToBase<reco::Jet> JetRef; if (hJTAs->keyProduct().isNull()) { // need to work around this bug someway, altough it's not stricly my fault iEvent.put(std::make_unique<JetChargeCollection>()); return; } auto ret = std::make_unique<JetChargeCollection>(hJTAs->keyProduct()); for (IT it = hJTAs->begin(), ed = hJTAs->end(); it != ed; ++it) { const JetRef &jet = it->first; const reco::TrackRefVector &tracks = it->second; float val = static_cast<float>( algo_.charge(jet->p4(), tracks) ); reco::JetFloatAssociation::setValue(*ret, jet, val); } iEvent.put(std::move(ret)); }
42.1
106
0.675376
nistefan
ad31f62e3f5313fa323f59cdd539a1bc6d62e9d6
14,715
cpp
C++
patch/game/clawmute.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
3
2021-10-10T11:12:03.000Z
2021-11-04T16:46:57.000Z
patch/game/clawmute.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
null
null
null
patch/game/clawmute.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
null
null
null
#include "objects.h" #include "lara.h" #include "control.h" #include "effect2.h" #include "sphere.h" #include "people.h" #include "traps.h" #include <specific/standard.h> #include <specific/fn_stubs.h> #define CLAW_PLASMA_DAMAGE 200 #define CLAW_BITE_DAMAGE 100 #define CLAW_TOUCH (0x90) #define CLAW_DIE_ANIM 20 #define CLAW_WALK_TURN (3*ONE_DEGREE) #define CLAW_RUN_TURN (4*ONE_DEGREE) #define CLAW_ATTACK1_RANGE SQUARE(WALL_L) #define CLAW_ATTACK2_RANGE SQUARE(WALL_L*2) #define CLAW_ATTACK3_RANGE SQUARE(WALL_L*4/3) #define CLAW_FIRE_RANGE SQUARE(WALL_L*3) #define CLAW_ROAR_CHANCE 0x60 #define CLAW_WALK_CHANCE (CLAW_ROAR_CHANCE + 0x400) #define CLAW_AWARE_DISTANCE SQUARE(WALL_L) enum claw_anims { CLAW_STOP, CLAW_WALK, CLAW_RUN, CLAW_RUN_ATAK, CLAW_WALK_ATAK1, CLAW_WALK_ATAK2, CLAW_SLASH_LEFT, CLAW_SLASH_RIGHT, CLAW_DEATH, CLAW_CLAW_ATAK, CLAW_FIRE_ATAK }; void TriggerPlasma(int16_t item_number); void TriggerPlasmaBallFlame(int16_t fx_number, long type, long xv, long yv, long zv); void TriggerPlasmaBall(ITEM_INFO* item, long type, PHD_VECTOR* pos1, int16_t room_number, int16_t angle); BITE_INFO claw_bite_left = { 19, -13, 3, 7 }, claw_bite_right = { 19, -13, 3, 4 }; void ClawmuteControl(int16_t item_number) { if (!CreatureActive(item_number)) return; auto item = &items[item_number]; auto claw = (CREATURE_INFO*)item->data; if (!claw) return; int16_t head = 0, torso_y = 0, torso_x = 0, angle = 0, tilt = 0; if (item->hit_points <= 0) { if (item->current_anim_state != CLAW_DEATH) { item->anim_number = objects[item->object_number].anim_index + CLAW_DIE_ANIM; item->frame_number = anims[item->anim_number].frame_base; item->current_anim_state = CLAW_DEATH; } if (item->frame_number == anims[item->anim_number].frame_end - 1) { CreatureDie(item_number, true); TriggerExplosionSparks(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 3, -2, 2, 0); for (int i = 0; i < 2; ++i) TriggerExplosionSparks(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 3, -1, 2, 0); g_audio->play_sound(106, { item->pos.x_pos, item->pos.y_pos, item->pos.z_pos }); return; } } else { AI_INFO info, lara_info; if (item->ai_bits) GetAITarget(claw); CreatureAIInfo(item, &info); if (claw->enemy == lara_item) { lara_info.angle = info.angle; lara_info.distance = info.distance; } else { int lara_dz = lara_item->pos.z_pos - item->pos.z_pos, lara_dx = lara_item->pos.x_pos - item->pos.x_pos; lara_info.angle = phd_atan(lara_dz, lara_dx) - item->pos.y_rot; lara_info.distance = lara_dz * lara_dz + lara_dx * lara_dx; } if (info.zone_number == info.enemy_zone) { GetCreatureMood(item, &info, VIOLENT); CreatureMood(item, &info, VIOLENT); } else { GetCreatureMood(item, &info, TIMID); CreatureMood(item, &info, TIMID); } angle = CreatureTurn(item, claw->maximum_turn); auto real_enemy = claw->enemy; claw->enemy = lara_item; if (lara_info.distance < CLAW_AWARE_DISTANCE || item->hit_status || TargetVisible(item, &lara_info)) AlertAllGuards(item_number); claw->enemy = real_enemy; switch (item->current_anim_state) { case CLAW_STOP: { claw->maximum_turn = 0; claw->flags = 0; head = info.angle; if (item->ai_bits & GUARD) { head = AIGuard(claw); item->goal_anim_state = CLAW_STOP; } else if (item->ai_bits & PATROL1) { item->goal_anim_state = CLAW_WALK; head = 0; } else if (claw->mood == ESCAPE_MOOD) item->goal_anim_state = CLAW_RUN; else if (info.bite && info.distance < CLAW_ATTACK1_RANGE) { torso_y = info.angle; torso_x = info.x_angle; item->goal_anim_state = (info.angle < 0 ? CLAW_SLASH_LEFT : CLAW_SLASH_RIGHT); } else if (info.bite && info.distance < CLAW_ATTACK3_RANGE) { torso_y = info.angle; torso_x = info.x_angle; item->goal_anim_state = CLAW_CLAW_ATAK; } else if (Targetable(item, &info) && ((info.distance > CLAW_FIRE_RANGE && !item->item_flags[0]) || info.zone_number != info.enemy_zone)) item->goal_anim_state = CLAW_FIRE_ATAK; else if (claw->mood == BORED_MOOD) item->goal_anim_state = CLAW_WALK; else if (item->required_anim_state) item->goal_anim_state = item->required_anim_state; else item->goal_anim_state = CLAW_RUN; break; } case CLAW_WALK: { claw->maximum_turn = CLAW_WALK_TURN; if (info.ahead) head = info.angle; if (item->ai_bits & PATROL1) { item->goal_anim_state = CLAW_WALK; head = 0; } else if (info.bite && info.distance < CLAW_ATTACK3_RANGE) { claw->maximum_turn = CLAW_WALK_TURN; item->goal_anim_state = (info.angle < 0 ? CLAW_WALK_ATAK1 : CLAW_WALK_ATAK2); } else if (Targetable(item, &info) && ((info.distance > CLAW_FIRE_RANGE && !item->item_flags[0]) || info.zone_number != info.enemy_zone)) { claw->maximum_turn = CLAW_WALK_TURN; item->goal_anim_state = CLAW_STOP; } else if (claw->mood == ESCAPE_MOOD || claw->mood == ATTACK_MOOD) item->goal_anim_state = CLAW_RUN; break; } case CLAW_RUN: { claw->maximum_turn = CLAW_RUN_TURN; if (info.ahead) head = info.angle; if (item->ai_bits & GUARD) item->goal_anim_state = CLAW_STOP; else if (claw->mood == BORED_MOOD) item->goal_anim_state = CLAW_STOP; else if (claw->flags && info.ahead) item->goal_anim_state = CLAW_STOP; else if (info.bite && info.distance < CLAW_ATTACK2_RANGE) item->goal_anim_state = (lara_item->speed == 0 ? CLAW_STOP : CLAW_RUN_ATAK); else if (Targetable(item, &info) && ((info.distance > CLAW_FIRE_RANGE && !item->item_flags[0]) || info.zone_number != info.enemy_zone)) { claw->maximum_turn = CLAW_WALK_TURN; item->goal_anim_state = CLAW_STOP; } claw->flags = 0; break; } case CLAW_WALK_ATAK1: case CLAW_WALK_ATAK2: case CLAW_SLASH_LEFT: case CLAW_SLASH_RIGHT: case CLAW_CLAW_ATAK: case CLAW_RUN_ATAK: { if (info.ahead) { torso_y = info.angle; torso_x = info.x_angle; } if (!claw->flags && (item->touch_bits & CLAW_TOUCH)) { lara_item->hit_status = 1; lara_item->hit_points -= CLAW_BITE_DAMAGE; CreatureEffect(item, &claw_bite_left, DoBloodSplat); CreatureEffect(item, &claw_bite_right, DoBloodSplat); claw->flags = 1; } item->item_flags[0] = 0; break; } case CLAW_FIRE_ATAK: { if (abs(info.angle) < CLAW_WALK_TURN) item->pos.y_rot += info.angle; else if (info.angle < 0) item->pos.y_rot -= CLAW_WALK_TURN; else item->pos.y_rot += CLAW_WALK_TURN; if (info.ahead) { torso_y = info.angle >> 1; torso_x = info.x_angle; } if (item->frame_number == anims[item->anim_number].frame_base && !(GetRandomControl() & 0x3)) item->item_flags[0] = 1; if (item->frame_number - anims[item->anim_number].frame_base < 28) TriggerPlasma(item_number); else if (item->frame_number - anims[item->anim_number].frame_base == 28) TriggerPlasmaBall(item, 0, nullptr, item->room_number, item->pos.y_rot); { int bright = item->frame_number - anims[item->anim_number].frame_base; if (bright > 16) if ((bright = anims[item->anim_number].frame_base + 28 + 16 - item->frame_number) > 16) bright = 16; if (bright > 0) { int rnd = GetRandomControl(), r = ((rnd & 7) * bright) >> 4, g = ((24 - ((rnd >> 6) & 3)) * bright) >> 4, b = ((31 - ((rnd >> 4) & 3)) * bright) >> 4; PHD_VECTOR pos { -32, -16, -192 }; GetJointAbsPosition(item, &pos, 13); TriggerDynamicLight(pos.x, pos.y, pos.z, 13, r, g, b); } } } } } CreatureTilt(item, tilt); CreatureJoint(item, 0, torso_x); CreatureJoint(item, 1, torso_y); CreatureJoint(item, 2, head); CreatureAnimation(item_number, angle, tilt); } void TriggerPlasma(int16_t item_number) { int dx = lara_item->pos.x_pos - items[item_number].pos.x_pos, dz = lara_item->pos.z_pos - items[item_number].pos.z_pos; if (g_effects_draw_distance != -1 && (dx < -g_effects_draw_distance || dx > g_effects_draw_distance || dz < -g_effects_draw_distance || dz > g_effects_draw_distance)) return; auto sptr = &spark[GetFreeSpark()]; int size = (GetRandomControl() & 31) + 64; sptr->On = 1; sptr->sB = 255; sptr->sG = 48 + (GetRandomControl() & 31); sptr->sR = 48; sptr->dB = 192 + (GetRandomControl() & 63); sptr->dG = 128 + (GetRandomControl() & 63); sptr->dR = 32; sptr->ColFadeSpeed = 12 + (GetRandomControl() & 3); sptr->FadeToBlack = 8; sptr->sLife = sptr->Life = (GetRandomControl() & 7) + 24; sptr->TransType = COLADD; sptr->extras = 0; sptr->Dynamic = -1; sptr->x = ((GetRandomControl() & 15) - 8); sptr->y = 0; sptr->z = ((GetRandomControl() & 15) - 8); sptr->Xvel = ((GetRandomControl() & 31) - 16); sptr->Yvel = (GetRandomControl() & 15) + 16; sptr->Zvel = ((GetRandomControl() & 31) - 16); sptr->Friction = 3; if (GetRandomControl() & 1) { sptr->Flags = SP_SCALE | SP_DEF | SP_ROTATE | SP_EXPDEF | SP_ITEM | SP_NODEATTATCH; sptr->RotAng = GetRandomControl() & 4095; sptr->RotAdd = ((GetRandomControl() & 1) ? -(GetRandomControl() & 15) - 16 : (GetRandomControl() & 15) + 16); } else sptr->Flags = SP_SCALE | SP_DEF | SP_EXPDEF | SP_ITEM | SP_NODEATTATCH; sptr->Gravity = (GetRandomControl() & 31) + 16; sptr->MaxYvel = (GetRandomControl() & 7) + 16; sptr->FxObj = item_number; sptr->NodeNumber = SPN_CLAWMUTEPLASMA; sptr->Def = (PHDSPRITESTRUCT*)objects[EXPLOSION1].mesh_ptr; sptr->Scalar = 1; sptr->Width = sptr->sWidth = size; sptr->Height = sptr->sHeight = size; sptr->dWidth = size >> 2; sptr->dHeight = size >> 2; } void TriggerPlasmaBallFlame(int16_t fx_number, long type, long xv, long yv, long zv) { int dx = lara_item->pos.x_pos - effects[fx_number].pos.x_pos, dz = lara_item->pos.z_pos - effects[fx_number].pos.z_pos; if (g_effects_draw_distance != -1 && (dx < -g_effects_draw_distance || dx > g_effects_draw_distance || dz < -g_effects_draw_distance || dz > g_effects_draw_distance)) return; auto sptr = &spark[GetFreeSpark()]; int size = (GetRandomControl() & 31) + 64; sptr->On = 1; sptr->sB = 255; sptr->sG = 48 + (GetRandomControl() & 31); sptr->sR = 48; sptr->dB = 192 + (GetRandomControl() & 63); sptr->dG = 128 + (GetRandomControl() & 63); sptr->dR = 32; sptr->ColFadeSpeed = 12 + (GetRandomControl() & 3); sptr->FadeToBlack = 8; sptr->sLife = sptr->Life = (GetRandomControl() & 7) + 24; sptr->TransType = COLADD; sptr->extras = 0; sptr->Dynamic = -1; sptr->x = ((GetRandomControl() & 15) - 8); sptr->y = 0; sptr->z = ((GetRandomControl() & 15) - 8); sptr->Xvel = xv + (GetRandomControl() & 255) - 128; sptr->Yvel = yv; sptr->Zvel = zv + (GetRandomControl() & 255) - 128; sptr->Friction = 5; if (GetRandomControl() & 1) { sptr->Flags = SP_SCALE | SP_DEF | SP_ROTATE | SP_EXPDEF | SP_FX; sptr->RotAng = GetRandomControl() & 4095; sptr->RotAdd = ((GetRandomControl() & 1) ? -(GetRandomControl() & 15) - 16 : (GetRandomControl() & 15) + 16); } else sptr->Flags = SP_SCALE | SP_DEF | SP_EXPDEF | SP_FX; sptr->FxObj = fx_number; sptr->Def = (PHDSPRITESTRUCT*)objects[EXPLOSION1].mesh_ptr; sptr->Scalar = 1; sptr->Width = sptr->sWidth = size; sptr->Height = sptr->sHeight = size; sptr->dWidth = size >> 2; sptr->dHeight = size >> 2; sptr->Gravity = sptr->MaxYvel = 0; if (type == 0) { sptr->Yvel = (GetRandomControl() & 511) - 256; sptr->Xvel <<= 1; sptr->Zvel <<= 1; sptr->Scalar = 2; sptr->Friction = 5 | (5 << 4); sptr->dWidth >>= 1; sptr->dHeight >>= 1; } } void TriggerPlasmaBall(ITEM_INFO* item, long type, PHD_VECTOR* pos1, int16_t room_number, int16_t angle) { PHD_VECTOR pos; PHD_ANGLE_VEC angles; int speed; if (type == 0) { pos = { -32, -16, -192 }; GetJointAbsPosition(item, &pos, 13); speed = (GetRandomControl() & 7) + 8; angles = phd_GetVectorAngles({ lara_item->pos.x_pos - pos.x, lara_item->pos.y_pos - pos.y - 256, lara_item->pos.z_pos - pos.z }); angles.x = item->pos.y_rot; } else { pos = { pos1->x, pos1->y, pos1->z }; speed = (GetRandomControl() & 15) + 16; angles.x = GetRandomControl() << 1; angles.y = 0x2000; } if (auto fx_number = CreateEffect(room_number); fx_number != NO_ITEM) { auto fx = &effects[fx_number]; fx->pos.x_pos = pos.x; fx->pos.y_pos = pos.y; fx->pos.z_pos = pos.z; fx->pos.y_rot = angles.x; fx->pos.x_rot = angles.y; fx->object_number = EXTRAFX1; fx->speed = speed; fx->fallspeed = 0; fx->flag1 = type; } } void ControlClawmutePlasmaBall(int16_t fx_number) { auto fx = &effects[fx_number]; int old_x = fx->pos.x_pos, old_y = fx->pos.y_pos, old_z = fx->pos.z_pos; if (fx->speed < 384 && fx->flag1 == 0) fx->speed += (fx->speed >> 3) + 4; if (fx->flag1 == 1) { fx->fallspeed++; if (fx->speed > 8) fx->speed -= 2; if (fx->pos.x_rot > -0x3c00) fx->pos.x_rot -= 0x100; } int speed = (fx->speed * phd_cos(fx->pos.x_rot)) >> W2V_SHIFT; fx->pos.z_pos += (speed * phd_cos(fx->pos.y_rot)) >> W2V_SHIFT; fx->pos.x_pos += (speed * phd_sin(fx->pos.y_rot)) >> W2V_SHIFT; fx->pos.y_pos += -((fx->speed * phd_sin(fx->pos.x_rot)) >> W2V_SHIFT) + fx->fallspeed; if (wibble & 4) TriggerPlasmaBallFlame(fx_number, fx->flag1, 0, fx->flag1 == 0 ? (abs(old_y - fx->pos.y_pos) << 3) : 0, 0); auto room_number = fx->room_number; auto floor = GetFloor(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos, &room_number); if (fx->pos.y_pos >= GetHeight(floor, fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos) || fx->pos.y_pos < GetCeiling(floor, fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos)) { if (fx->flag1 == 0) { PHD_VECTOR pos { old_x, old_y, old_z }; for (int i = 0; i < (5 + (GetRandomControl() & 3)); ++i) TriggerPlasmaBall(nullptr, 1, &pos, fx->room_number, fx->pos.y_rot); } KillEffect(fx_number); return; } if (room[room_number].flags & UNDERWATER) { KillEffect(fx_number); return; } if (ItemNearLara(lara_item, &fx->pos, 200) && fx->flag1 == 0) { PHD_VECTOR pos { fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos }; for (int i = 0; i < (3 + (GetRandomControl() & 1)); ++i) TriggerPlasmaBall(nullptr, 1, &pos, fx->room_number, fx->pos.y_rot); lara_item->hit_points -= CLAW_PLASMA_DAMAGE; lara_item->hit_status = 1; KillEffect(fx_number); return; } if (room_number != fx->room_number) EffectNewRoom(fx_number, lara_item->room_number); uint8_t radtab[2] = { 13, 7 }; if (radtab[fx->flag1]) { int rnd = GetRandomControl(), b = 31 - ((rnd >> 4) & 3), g = 24 - ((rnd >> 6) & 3), r = rnd & 7; TriggerDynamicLight(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos, radtab[fx->flag1], r, g, b); } }
26.705989
167
0.648726
Tonyx97
ad32728610e0ead04a587989b860f9c32b6e0ab6
3,308
hpp
C++
OpenSimRoot/src/export/ExportBaseClass.hpp
nb-e/OpenRootSim
aaa1cd18e94ebf613c28737842401daba3b8d5ef
[ "BSD-3-Clause" ]
1
2021-08-03T00:52:58.000Z
2021-08-03T00:52:58.000Z
OpenSimRoot/src/export/ExportBaseClass.hpp
nb-e/OpenRootSim
aaa1cd18e94ebf613c28737842401daba3b8d5ef
[ "BSD-3-Clause" ]
null
null
null
OpenSimRoot/src/export/ExportBaseClass.hpp
nb-e/OpenRootSim
aaa1cd18e94ebf613c28737842401daba3b8d5ef
[ "BSD-3-Clause" ]
1
2021-08-03T00:52:59.000Z
2021-08-03T00:52:59.000Z
/* Copyright © 2016, The Pennsylvania State University All rights reserved. Copyright © 2016 Forschungszentrum Jülich GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted under the GNU General Public License v3 and provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You should have received the GNU GENERAL PUBLIC LICENSE v3 with this file in license.txt but can also be found at http://www.gnu.org/licenses/gpl-3.0.en.html NOTE: The GPL.v3 license requires that all derivative work is distributed under the same license. That means that if you use this source code in any other program, you can only distribute that program with the full source code included and licensed under a GPL license. */ /* * SHORT DESCRIPTION: Base class for export modules. If you are writing an * export module for simroot - you should inherit from this class and * */ #ifndef EXPORTBASECLASS_HPP_ #define EXPORTBASECLASS_HPP_ #include "../engine/DataDefinitions.hpp" #include <map> #include <vector> #include <set> class SimulaBase; //default export class class ExportBase{ public: ExportBase(std::string module); virtual ~ExportBase(); virtual void initialize()=0; virtual void run(const Time &t)=0; virtual void finalize()=0; std::string getName()const; bool &enabled(); Time getStartTime()const; Time getEndTime()const; Time getIntervalTime()const; Time &getCurrentTime(); Time getNextOutputTime(); protected: std::string moduleName; Time startTime, endTime, intervalTime, currentTime; std::set<Time> outputTimes; SimulaBase* controls; bool runModule; }; //global map for registration of export classes. //typedefinition of instantiation function of rate objects typedef ExportBase* (*exportBaseInstantiationFunction)(); //instantiation of map that lists all rate classes extern std::map<std::string, exportBaseInstantiationFunction > exportBaseClassesMap; typedef std::vector<ExportBase*> ModuleList; #endif /*EXPORTBASECLASS_HPP_*/
49.373134
755
0.796856
nb-e
ad34ff41bef08907bfa1b5c76777f7f6632f4050
19,327
cpp
C++
Pesto/src/EditorLayer.cpp
Tamookk/Basil
bdcdf4e6e13e64a34416b4412d366594f9d46f56
[ "Apache-2.0" ]
null
null
null
Pesto/src/EditorLayer.cpp
Tamookk/Basil
bdcdf4e6e13e64a34416b4412d366594f9d46f56
[ "Apache-2.0" ]
null
null
null
Pesto/src/EditorLayer.cpp
Tamookk/Basil
bdcdf4e6e13e64a34416b4412d366594f9d46f56
[ "Apache-2.0" ]
null
null
null
#include "EditorLayer.h" #include "Core/Application.h" #include "Math/Math.h" #include "Scene/SceneSerializer.h" #include "Utils/PlatfomUtils.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <imgui.h> #include <ImGuizmo.h> namespace Basil { extern const std::filesystem::path assetPath; // Constructor EditorLayer::EditorLayer() : Layer("Sandbox2D") { viewportFocused = false; viewportHovered = false; showPhysicsColliders = false; gizmoType = -1; sceneState = SceneState::Edit; } void EditorLayer::onAttach() { PROFILE_FUNCTION(); // Set play and stop icons iconPlay = Texture2D::create("res/icons/editor_play_stop/play_button.png"); iconStop = Texture2D::create("res/icons/editor_play_stop/stop_button.png"); // Create framebuffer FramebufferSpecification fbSpec; fbSpec.attachments = { FramebufferTextureFormat::RGBA8, FramebufferTextureFormat::RED_INTEGER, FramebufferTextureFormat::Depth }; fbSpec.width = 1280; fbSpec.height = 720; framebuffer = Framebuffer::create(fbSpec); // Create scene activeScene = makeShared<Scene>(); auto commandLineArgs = Application::get().getCommandLineArgs(); if (commandLineArgs.count > 1) { auto sceneFilePath = commandLineArgs[1]; SceneSerializer serializer(activeScene); serializer.deserialize(sceneFilePath); } // Set up editor camera editorCamera = EditorCamera(30.0f, 1.778f, 0.1f, 1000.0f); // Create square entities auto square = activeScene->createEntity("Green Square"); square.addComponent<SpriteRendererComponent>(glm::vec4{ 0.0f, 1.0f, 0.0f, 1.0f }); squareEntity = square; auto redSquare = activeScene->createEntity("Red Square"); redSquare.addComponent<SpriteRendererComponent>(glm::vec4{ 1.0f, 0.0f, 0.0f, 1.0f }); redSquare.getComponent<TransformComponent>().translation = { 0.0f, 1.0f, 0.0f }; cameraEntity = activeScene->createEntity("Camera"); cameraEntity.addComponent<CameraComponent>(); secondCameraEntity = activeScene->createEntity("Clip-Space Entity"); auto& cc = secondCameraEntity.addComponent<CameraComponent>(); cc.primary = false; class CameraController : public ScriptableEntity { public: void onCreate() override {} void onDestroy() override {} void onUpdate(Timestep timeStep) override { auto& translation = getComponent<TransformComponent>().translation; float speed = 5.0f; if (Input::isKeyPressed(KeyCode::A)) translation.x -= speed * timeStep; if (Input::isKeyPressed(KeyCode::D)) translation.x += speed * timeStep; if (Input::isKeyPressed(KeyCode::W)) translation.y += speed * timeStep; if (Input::isKeyPressed(KeyCode::S)) translation.y -= speed * timeStep; } }; cameraEntity.addComponent<NativeScriptComponent>().bind<CameraController>(); propertiesPanel.setContext(activeScene); sceneHierarchyPanel.setContext(activeScene); } void EditorLayer::onDetach() { PROFILE_FUNCTION(); } void EditorLayer::onUpdate(Timestep timeStep) { // Start timer for onUpdate PROFILE_FUNCTION(); // Stop flickering on resize { FramebufferSpecification spec = framebuffer->getSpecification(); if (viewportSize.x > 0.0f && viewportSize.y > 0.0f && (spec.width != viewportSize.x || spec.height != viewportSize.y)) { framebuffer->resize((uint32_t)viewportSize.x, (uint32_t)viewportSize.y); editorCamera.setViewportSize(viewportSize.x, viewportSize.y); activeScene->onViewportResize((uint32_t)viewportSize.x, (uint32_t)viewportSize.y); } } // Render Renderer2D::resetStats(); { PROFILE_SCOPE("Renderer Prep"); framebuffer->bind(); Renderer::setClearColor({ 0.1f, 0.1f, 0.1f, 1.0f }); Renderer::clear(); framebuffer->clearAttachment(1, -1); } // Update scene { PROFILE_SCOPE("Renderer Draw"); switch (sceneState) { case SceneState::Edit: { PROFILE_SCOPE("Editor Update"); editorCamera.onUpdate(timeStep); activeScene->onUpdateEditor(timeStep, editorCamera); break; } case SceneState::Play: { PROFILE_SCOPE("Play Update"); activeScene->onUpdateRuntime(timeStep); break; } } auto [mx, my] = ImGui::GetMousePos(); mx -= viewportBounds[0].x; my -= viewportBounds[0].y; glm::vec2 viewportSize = viewportBounds[1] - viewportBounds[0]; my = viewportSize.y - my; int mouseX = (int)mx; int mouseY = (int)my; if (mouseX >= 0 && mouseY >= 0 && mouseX < (int)viewportSize.x && mouseY < (int)viewportSize.y) { int pixelData = framebuffer->readPixel(1, mouseX, mouseY); hoveredEntity = pixelData == -1 ? Entity() : Entity((entt::entity)pixelData, activeScene.get()); } // Render the overlay onOverlayRender(); framebuffer->unbind(); } } void EditorLayer::onEvent(Event& e) { // Editor camera on event editorCamera.onEvent(e); // Dispatch key pressed event EventDispatcher dispatcher(e); dispatcher.dispatch<KeyPressedEvent>(BIND_EVENT(EditorLayer::onKeyPressed)); dispatcher.dispatch<MouseButtonPressedEvent>(BIND_EVENT(EditorLayer::onMouseButtonPressed)); } void EditorLayer::onImGuiRender() { PROFILE_FUNCTION(); // Setup variables static bool dockSpaceOpen = true; static bool optFullscreenPersistant = true; bool optFullscreen = optFullscreenPersistant; static ImGuiDockNodeFlags dockSpaceFlags = ImGuiDockNodeFlags_None; // Set flags ImGuiWindowFlags windowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; // If fullscreen if (optFullscreen) { // Setup fullscreen mode ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->Pos); ImGui::SetNextWindowSize(viewport->Size); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); windowFlags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; windowFlags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } // Set some flags if (dockSpaceFlags & ImGuiDockNodeFlags_PassthruCentralNode) windowFlags |= ImGuiWindowFlags_NoBackground; // Create the ImGui instance ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace Demo", &dockSpaceOpen, windowFlags); ImGui::PopStyleVar(); if (optFullscreen) ImGui::PopStyleVar(2); ImGuiIO& io = ImGui::GetIO(); ImGuiStyle& style = ImGui::GetStyle(); float minWinSizeX = style.WindowMinSize.x; style.WindowMinSize.x = 370.0f; if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dockspaceID = ImGui::GetID("MyDockspace"); ImGui::DockSpace(dockspaceID, ImVec2(0.0f, 0.0f), dockSpaceFlags); } style.WindowMinSize.x = minWinSizeX; // Menu bar if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("File")) { // New scene if (ImGui::MenuItem("New", "Ctrl+N")) newScene(); // Open scene file if (ImGui::MenuItem("Open...", "Ctrl+O")) openScene(); // Save scene file if (ImGui::MenuItem("Save...", "Ctrl+S")) saveScene(); // Save scene file as if (ImGui::MenuItem("Save As...", "Ctrl+Shift+S")) saveSceneAs(); // Exit application if (ImGui::MenuItem("Exit")) Application::get().close(); ImGui::EndMenu(); } ImGui::EndMenuBar(); } // Content browser panel contentBrowserPanel.onImGuiRender(); // Scene hierarchy panel sceneHierarchyPanel.onImGuiRender(); // Properties panel propertiesPanel.onImGuiRender(sceneHierarchyPanel.getSelectedEntity()); // Stats panel ImGui::Begin("Stats"); Renderer2D::Statistics stats = Renderer2D::getStats(); ImGui::Text("Renderer2D Stats:"); ImGui::Text("Draw Calls: %d", stats.drawCalls); ImGui::Text("Quads: %d", stats.quadCount); ImGui::Text("Vertices: %d", stats.getTotalVertexCount()); ImGui::Text("Indices: %d", stats.getTotalIndexCount()); ImGui::End(); // Settings panel ImGui::Begin("Settings"); ImGui::Checkbox("Show Physics Colliders", &showPhysicsColliders); ImGui::End(); // Viewport ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 0, 0 }); ImGui::Begin("Viewport"); auto viewportMinRegion = ImGui::GetWindowContentRegionMin(); auto viewportMaxRegion = ImGui::GetWindowContentRegionMax(); auto viewportOffset = ImGui::GetWindowPos(); viewportBounds[0] = { viewportMinRegion.x + viewportOffset.x, viewportMinRegion.y + viewportOffset.y }; viewportBounds[1] = { viewportMaxRegion.x + viewportOffset.x, viewportMaxRegion.y + viewportOffset.y }; viewportFocused = ImGui::IsWindowFocused(); viewportHovered = ImGui::IsWindowHovered(); Application::get().getImGuiLayer()->setBlockEvents(!viewportFocused && !viewportHovered); ImVec2 viewportPanelSize = ImGui::GetContentRegionAvail(); viewportSize = { viewportPanelSize.x, viewportPanelSize.y }; uint64_t textureID = framebuffer->getColorAttachmentRendererID(); ImGui::Image(reinterpret_cast<void*>(textureID), viewportPanelSize, ImVec2{ 0, 1 }, ImVec2{ 1, 0 }); // Accept drag and drop data from the Content Browser panel (currently a scene file) if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* data = ImGui::AcceptDragDropPayload("CONTENT_BROWSER_ITEM")) { const wchar_t* path = (const wchar_t*)data->Data; // Open a scene openScene(std::filesystem::path(assetPath) / path); } ImGui::EndDragDropTarget(); } // Gizmos Entity selectedEntity = sceneHierarchyPanel.getSelectedEntity(); if (selectedEntity && gizmoType != -1) { ImGuizmo::SetOrthographic(false); ImGuizmo::SetDrawlist(); // Set rect size ImGuizmo::SetRect(viewportBounds[0].x, viewportBounds[0].y, viewportBounds[1].x - viewportBounds[0].x, viewportBounds[1].y - viewportBounds[0].y); // Set camera (runtime camera from entity) //auto cameraEntity = activeScene->getPrimaryCameraEntity(); //const auto& camera = cameraEntity.getComponent<CameraComponent>().camera; //const glm::mat4& cameraProjection = camera.getProjection(); //glm::mat4 cameraView = glm::inverse(cameraEntity.getComponent<TransformComponent>().getTransform()); // Editor camera const glm::mat4& cameraProjection = editorCamera.getProjection(); glm::mat4 cameraView = editorCamera.getViewMatrix(); // Entity transform auto& tc = selectedEntity.getComponent<TransformComponent>(); glm::mat4 transform = tc.getTransform(); // Snapping bool snap = Input::isKeyPressed(Key::LeftControl); float snapValue = 0.5f; if (gizmoType == ImGuizmo::OPERATION::ROTATE) snapValue = 45.0f; float snapValues[3] = { snapValue, snapValue, snapValue }; ImGuizmo::Manipulate(glm::value_ptr(cameraView), glm::value_ptr(cameraProjection), (ImGuizmo::OPERATION)gizmoType, ImGuizmo::LOCAL, glm::value_ptr(transform), nullptr, snap ? snapValues : nullptr); if (ImGuizmo::IsUsing()) { glm::vec3 translation, rotation, scale; Math::decomposeTransform(transform, translation, rotation, scale); glm::vec3 deltaRotation = rotation - tc.rotation; tc.translation = translation; tc.rotation += deltaRotation; tc.scale = scale; } } ImGui::End(); ImGui::PopStyleVar(); UI_Toolbar(); ImGui::End(); } // On key pressed function bool EditorLayer::onKeyPressed(KeyPressedEvent& e) { // Shortcuts if (e.getRepeatCount() > 0) return false; bool control = Input::isKeyPressed(Key::LeftControl) || Input::isKeyPressed(Key::RightControl); bool shift = Input::isKeyPressed(Key::LeftShift) || Input::isKeyPressed(Key::RightShift); switch (e.getKeycode()) { case (int)Key::N: if (control) newScene(); break; case (int)Key::O: if (control) openScene(); break; case (int)Key::S: if (control) if (shift) saveSceneAs(); else saveScene(); break; case (int)Key::D: if (control) onDuplicateEntity(); break; // Gizmos case (int)Key::Q: if(!ImGuizmo::IsUsing()) gizmoType = -1; break; case (int)Key::W: if (!ImGuizmo::IsUsing()) gizmoType = ImGuizmo::OPERATION::TRANSLATE; break; case (int)Key::E: if (!ImGuizmo::IsUsing()) gizmoType = ImGuizmo::OPERATION::ROTATE; break; case (int)Key::R: if (!ImGuizmo::IsUsing()) gizmoType = ImGuizmo::OPERATION::SCALE; break; } return false; } // On mouse button pressed function bool EditorLayer::onMouseButtonPressed(MouseButtonPressedEvent& e) { if (e.getMouseButton() == (int)Mouse::ButtonLeft) { if (viewportHovered && !ImGuizmo::IsOver() && !Input::isKeyPressed(Key::LeftAlt)) sceneHierarchyPanel.setSelectedEntity(hoveredEntity); } return false; } // On overlay render function void EditorLayer::onOverlayRender() { // Start a new batch to render physics colliders if (sceneState == SceneState::Play) { Entity camera = activeScene->getPrimaryCameraEntity(); Renderer2D::beginScene(camera.getComponent<CameraComponent>().camera, camera.getComponent<TransformComponent>().getTransform()); } else { Renderer2D::beginScene(editorCamera); } // If visualising physics colliders is enabled if (showPhysicsColliders) { // Render box colliders { PROFILE_SCOPE("Render Box Colliders"); // Get all components with box collider 2D components auto view = activeScene->getAllEntitiesWith<TransformComponent, BoxCollider2DComponent>(); for (auto entity : view) { // Get the transform and box collider 2D components for the entity auto [tc, bc2d] = view.get<TransformComponent, BoxCollider2DComponent>(entity); // Calculate the translation, scale, and transform of the box collider glm::vec3 translation = tc.translation + glm::vec3(bc2d.offset, 0.001f); glm::vec3 scale = tc.scale * glm::vec3(bc2d.size * 2.0f, 1.0f); glm::mat4 transform = glm::translate(glm::mat4(1.0f), translation) * glm::rotate(glm::mat4(1.0f), tc.rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)) * glm::scale(glm::mat4(1.0f), scale); // Render the box collider visualisation Renderer2D::drawRect(transform, glm::vec4(0, 1, 0, 1)); } } // Render circle colliders { PROFILE_SCOPE("Render Circle Colliders"); // Get all components with circle collider 2D components auto view = activeScene->getAllEntitiesWith<TransformComponent, CircleCollider2DComponent>(); for (auto entity : view) { // Get the transform and circle collider 2D components for the entity auto [tc, cc2d] = view.get<TransformComponent, CircleCollider2DComponent>(entity); // Calculate the translation, scale, and transform of the box collider glm::vec3 translation = tc.translation + glm::vec3(cc2d.offset, 0.001f); glm::vec3 scale = tc.scale * glm::vec3(cc2d.radius * 2.0f); glm::mat4 transform = glm::translate(glm::mat4(1.0f), translation) * glm::scale(glm::mat4(1.0f), scale); // Render the circle collider visualisation Renderer2D::drawCircle(transform, glm::vec4(0, 1, 0, 1), 0.01f); } } } // Finish the batch Renderer2D::endScene(); } // Make a new scene void EditorLayer::newScene() { activeScene = makeShared<Scene>(); activeScene->onViewportResize((uint32_t)viewportSize.x, (uint32_t)viewportSize.y); sceneHierarchyPanel.setContext(activeScene); editorScenePath = std::filesystem::path(); } // Open a scene void EditorLayer::openScene() { std::string filePath = FileDialogs::openFile("Basil Scene (*.scene)\0*.scene\0"); if (!filePath.empty()) openScene(filePath); } // Open a scene (with a given file path) void EditorLayer::openScene(const std::filesystem::path path) { // Close scene if it is playing if (sceneState != SceneState::Edit) onSceneStop(); if (path.extension().string() != ".scene") { LOG_WARN("Could not load {0} - not a scene file", path.filename().string()); return; } Shared<Scene> newScene = makeShared<Scene>(); SceneSerializer serializer(newScene); if (serializer.deserialize(path.string())) { editorScene = newScene; editorScene->onViewportResize((uint32_t)viewportSize.x, (uint32_t)viewportSize.y); sceneHierarchyPanel.setContext(editorScene); activeScene = editorScene; editorScenePath = path; } } // Save a scene void EditorLayer::saveScene() { if (!editorScenePath.empty()) serializeScene(activeScene, editorScenePath); else saveSceneAs(); } // Save a scene as void EditorLayer::saveSceneAs() { std::string filePath = FileDialogs::saveFile("Basil Scene (*.scene)\0*.scene\0"); if (!filePath.empty()) { serializeScene(activeScene, filePath); editorScenePath = filePath; } } // Serialize a scene void EditorLayer::serializeScene(Shared<Scene> scene, const std::filesystem::path& path) { SceneSerializer serializer(scene); serializer.serialize(path.string()); } // When the scene plays void EditorLayer::onScenePlay() { sceneState = SceneState::Play; activeScene = Scene::copy(editorScene); activeScene->onRuntimeStart(); sceneHierarchyPanel.setContext(activeScene); } // When the scene stops void EditorLayer::onSceneStop() { sceneState = SceneState::Edit; activeScene->onRuntimeStop(); activeScene = editorScene; sceneHierarchyPanel.setContext(activeScene); } // When an entity is duplicated void EditorLayer::onDuplicateEntity() { if (sceneState != SceneState::Edit) return; Entity selectedEntity = sceneHierarchyPanel.getSelectedEntity(); if (selectedEntity) editorScene->duplicateEntity(selectedEntity); } // -- UI -- // // Create the UI toolbar void EditorLayer::UI_Toolbar() { // Push style ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 2)); ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(0, 0)); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); auto& colors = ImGui::GetStyle().Colors; const auto& buttonHoveredColor = colors[ImGuiCol_ButtonHovered]; ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(buttonHoveredColor.x, buttonHoveredColor.y, buttonHoveredColor.z, 0.5f)); const auto& buttonActiveColor = colors[ImGuiCol_ButtonActive]; ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(buttonActiveColor.x, buttonActiveColor.y, buttonActiveColor.z, 0.5f)); // Create toolbar flags int toolbarFlags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoScrollbar; toolbarFlags |= ImGuiWindowFlags_NoScrollWithMouse; // Begin toolbar ImGui::Begin("##Toolbar", nullptr, toolbarFlags); // Set button size and icon float size = ImGui::GetWindowHeight() - 4; Shared<Texture2D> icon = sceneState == SceneState::Edit ? iconPlay : iconStop; ImGui::SetCursorPosX((ImGui::GetWindowContentRegionMax().x * 0.5) - (size * 0.5)); // If button pressed if (ImGui::ImageButton((ImTextureID)icon->getRendererID(), ImVec2(size, size), ImVec2(0, 0), ImVec2(1, 1), 0)) { if (sceneState == SceneState::Edit) onScenePlay(); else if (sceneState == SceneState::Play) onSceneStop(); } // End toolbar ImGui::PopStyleVar(2); ImGui::PopStyleColor(3); ImGui::End(); } }
29.551988
149
0.699384
Tamookk
ad35292af1d0299a74c438036ecdb3f975a4beb3
3,712
cpp
C++
engine/screens/source/EquipmentScreen.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/screens/source/EquipmentScreen.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/screens/source/EquipmentScreen.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "Conversion.hpp" #include "EquipmentScreen.hpp" #include "EquipmentTextKeys.hpp" #include "EquipmentTranslator.hpp" #include "Game.hpp" #include "OptionsComponent.hpp" #include "PromptTextKeys.hpp" #include "TextComponent.hpp" #include "TextKeys.hpp" using namespace std; EquipmentScreen::EquipmentScreen(DisplayPtr new_display, CreaturePtr new_creature) : Screen(new_display), creature(new_creature) { initialize(); } // Initialize the equipment screen, showing the user the list of eq // slots and displaying further information in the inventory prompt. void EquipmentScreen::initialize() { vector<ScreenComponentPtr> eq_screen; // Set the title information title_text_sid = TextKeys::EQUIPMENT; // Create the various options and text int current_id = 0; DisplayEquipmentMap dem = EquipmentTranslator::create_display_equipment(creature); uint longest = 0; for (DisplayEquipmentMap::const_iterator e_it = dem.begin(); e_it != dem.end(); e_it++) { EquipmentWornLocation worn_location = e_it->first; string worn_location_name = EquipmentTextKeys::get_equipment_text_from_given_worn_location(worn_location); if (worn_location_name.size() > longest) longest = worn_location_name.size() + 1; } for (DisplayEquipmentMap::const_iterator e_it = dem.begin(); e_it != dem.end(); e_it++) { ostringstream ss; EquipmentWornLocation worn_location = e_it->first; DisplayItem display_item = e_it->second; Colour item_colour = display_item.get_colour(); string worn_location_name = EquipmentTextKeys::get_equipment_text_from_given_worn_location(worn_location); string item_description = display_item.get_description(); ss << String::add_trailing_spaces(worn_location_name, longest) << ": "; vector<pair<string, Colour>> flags = display_item.get_flags(); OptionsComponentPtr options = std::make_shared<OptionsComponent>(); Option current_option; TextComponentPtr option_text_component = current_option.get_description(); option_text_component->add_text(ss.str()); option_text_component->add_text(item_description, item_colour); for (const TextColour& flag_pair : flags) { ostringstream flag_ss; flag_ss << " "; Colour colour = flag_pair.second; flag_ss << flag_pair.first; option_text_component->add_text(flag_ss.str(), colour); } current_option.set_id(current_id); options->add_option(current_option); options->add_option_description(""); current_id++; eq_screen.push_back(options); string res_abrv = StringTable::get(EquipmentTextKeys::EQUIPMENT_RESISTS_FLAGS); string item_addl_desc; string di_addl_desc = display_item.get_additional_description(); String::reset_and_pad(item_addl_desc, 6 /* 6 = extra padding for '[a] : ' */); // Only show the resistances abbreviation if the item's got anything... if (!di_addl_desc.empty()) { ostringstream ss; ss << String::add_trailing_spaces(res_abrv, longest) << ": " << di_addl_desc; di_addl_desc = ss.str(); } item_addl_desc += di_addl_desc; TextComponentPtr eq_text = std::make_shared<TextComponent>(item_addl_desc, Colour::COLOUR_BOLD_YELLOW); eq_screen.push_back(eq_text); } // Enable the equipment screen add_page(eq_screen); // Set the prompt PromptPtr eq_prompt = std::make_unique<Prompt>(PromptLocation::PROMPT_LOCATION_LOWER_RIGHT); // Accept any input - the equipment manager will take care of sorting out // what's a valid command and what is not. eq_prompt->set_accept_any_input(true); eq_prompt->set_text_sid(PromptTextKeys::PROMPT_EQUIPMENT); user_prompt = std::move(eq_prompt); line_increment = 1; }
33.142857
110
0.739763
prolog
ad392c4204e6794d3d7960ac0f35c44a5daf9403
1,213
cpp
C++
Arc/src/Arc/Renderer/EditorCamera.cpp
MohitSethi99/AGE
4291ebeaa4af5b60518bc55eae079fd2cfe55d8f
[ "Apache-2.0" ]
null
null
null
Arc/src/Arc/Renderer/EditorCamera.cpp
MohitSethi99/AGE
4291ebeaa4af5b60518bc55eae079fd2cfe55d8f
[ "Apache-2.0" ]
null
null
null
Arc/src/Arc/Renderer/EditorCamera.cpp
MohitSethi99/AGE
4291ebeaa4af5b60518bc55eae079fd2cfe55d8f
[ "Apache-2.0" ]
null
null
null
#include "arcpch.h" #include "EditorCamera.h" #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/quaternion.hpp> namespace ArcEngine { EditorCamera::EditorCamera(float fov, float aspectRatio, float nearClip, float farClip) : m_Fov(fov), m_AspectRatio(aspectRatio), m_NearClip(nearClip), m_FarClip(farClip), Camera(glm::perspective(glm::radians(fov), aspectRatio, nearClip, farClip)) { } void EditorCamera::OnUpdate(Timestep timestep) { ARC_PROFILE_SCOPE(); float cosYaw = glm::cos(glm::radians(m_Yaw)); float sinYaw = glm::sin(glm::radians(m_Yaw)); float cosPitch = glm::cos(glm::radians(m_Pitch)); float sinPitch = glm::sin(glm::radians(m_Pitch)); m_Forward.x = cosYaw * cosPitch; m_Forward.y = sinPitch; m_Forward.z = sinYaw * cosPitch; m_Forward = glm::normalize(m_Forward); m_Right = glm::normalize(glm::cross(m_Forward, {0, 1, 0})); m_Up = glm::normalize(glm::cross(m_Right, m_Forward)); m_ViewMatrix = glm::lookAt(m_Position, m_Position + m_Forward, m_Up); } void EditorCamera::SetViewportSize(float width, float height) { ARC_PROFILE_SCOPE(); m_AspectRatio = width / height; m_Projection = glm::perspective(m_Fov, m_AspectRatio, m_NearClip, m_FarClip); } }
28.880952
161
0.727947
MohitSethi99
ad3de03e4e9883f4a0183218a96a066647b2f42a
415
cpp
C++
leetcode/268_missing_number_xor.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
1
2021-02-20T00:14:35.000Z
2021-02-20T00:14:35.000Z
leetcode/268_missing_number_xor.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
null
null
null
leetcode/268_missing_number_xor.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
null
null
null
/* * * Filename: 268_missing_number_xor.cpp * * Author: Haibo Hao * Email : haohaibo@ncic.ac.cn * Description: --- * Create: 2017-10-28 22:49:10 * Last Modified: 2017-10-28 22:49:26 **/ class Solution { public: int missingNumber(vector<int>& nums) { int res = 0; for (int i = 1; i <= nums.size(); ++i) { res = res ^ i ^ nums[i - 1]; } return res; } };
19.761905
44
0.53012
haohaibo
ad3ec48083799e0c7cc8f15845653aae4698aa4c
6,512
cc
C++
components/viz/common/gl_nv12_converter_pixeltest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/viz/common/gl_nv12_converter_pixeltest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/viz/common/gl_nv12_converter_pixeltest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 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/viz/common/gl_nv12_converter.h" #include <GLES2/gl2ext.h> #include "cc/test/pixel_test.h" #include "cc/test/pixel_test_utils.h" #include "components/viz/test/gl_scaler_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" namespace viz { class GLNV12ConverterPixelTest : public cc::PixelTest, public GLScalerTestUtil, public testing::WithParamInterface< std::tuple<bool, bool, gfx::Vector2d, gfx::Vector2d>> { public: bool allow_mrt_path() const { return std::get<0>(GetParam()); } bool is_rgba() const { return std::get<1>(GetParam()); } gfx::Vector2d scale_from() const { return std::get<2>(GetParam()); } gfx::Vector2d scale_to() const { return std::get<3>(GetParam()); } GLNV12Converter* converter() const { return converter_.get(); } GLuint CreateTexture(const gfx::Size& size) { return texture_helper_->CreateTexture(size); } GLuint UploadTexture(const SkBitmap& bitmap) { return texture_helper_->UploadTexture(bitmap); } SkBitmap DownloadTexture(GLuint texture, const gfx::Size& size) { return texture_helper_->DownloadTexture(texture, size); } protected: void SetUp() final { cc::PixelTest::SetUpGLWithoutRenderer(gfx::SurfaceOrigin::kBottomLeft); converter_ = GLNV12Converter::CreateConverterForTest(context_provider(), allow_mrt_path()); texture_helper_ = std::make_unique<GLScalerTestTextureHelper>( context_provider()->ContextGL()); } void TearDown() final { texture_helper_.reset(); converter_.reset(); cc::PixelTest::TearDown(); } private: std::unique_ptr<GLNV12Converter> converter_; std::unique_ptr<GLScalerTestTextureHelper> texture_helper_; }; // Note: This test is pretty much the same as // GLScalerPixelTest.Example_ScaleAndExportForScreenVideoCapture. The goal of // this pixel test is to just confirm that everything internal to // GLNV12Converter has been plumbed-through correctly. TEST_P(GLNV12ConverterPixelTest, ScaleAndConvert) { GLNV12Converter::Parameters params; params.scale_from = scale_from(); params.scale_to = scale_to(); params.source_color_space = DefaultRGBColorSpace(); params.output_color_space = DefaultYUVColorSpace(); params.enable_precise_color_management = converter()->SupportsPreciseColorManagement(); params.quality = GLScaler::Parameters::Quality::GOOD; params.is_flipped_source = true; params.flip_output = true; params.swizzle[0] = is_rgba() ? GL_RGBA : GL_BGRA_EXT; // Swizzle for readback. ASSERT_TRUE(converter()->Configure(params)); const gfx::Size kSourceSize = gfx::Size(scale_from().x(), scale_from().y()); const GLuint src_texture = UploadTexture( CreateVerticallyFlippedBitmap(CreateSMPTETestImage(kSourceSize))); const gfx::Rect kOutputRect = gfx::Rect(0, 0, scale_to().x(), scale_to().y()); ASSERT_EQ(kOutputRect, GLNV12Converter::ToAlignedRect(kOutputRect)); SkBitmap expected = CreateSMPTETestImage(kOutputRect.size()); ConvertRGBABitmapToYUV(&expected); // While the output size is `kOutputRect.Size()`, the packing of 4 pixels into // one RGBA quad means that the texture width must be divided by 4 (for the Y // plane). Then, the chroma plane is half the size of the Y plane in both // dimensions, but the width is actually double that since we pack 2 values, // so `y_plane_size.width() * 1/2 * 2` term is simplified to just // `y_plane_size.width()`. const gfx::Size y_plane_size(kOutputRect.width() / 4, kOutputRect.height()); const gfx::Size chroma_plane_size(y_plane_size.width(), y_plane_size.height() / 2); const GLuint yuv_textures[2] = {CreateTexture(y_plane_size), CreateTexture(chroma_plane_size)}; ASSERT_TRUE(converter()->Convert(src_texture, kSourceSize, gfx::Vector2d(), kOutputRect, yuv_textures)); // Download the textures, and unpack them into an interleaved YUV bitmap, for // comparison against the |expected| rendition. SkBitmap actual = AllocateRGBABitmap(kOutputRect.size()); actual.eraseColor(SkColorSetARGB(0xff, 0x00, 0x00, 0x00)); SkBitmap y_plane = DownloadTexture(yuv_textures[0], y_plane_size); SkBitmap uv_plane = DownloadTexture(yuv_textures[1], chroma_plane_size); if (!is_rgba()) { // We've asked the converter to produce output in BGRA, & downloaded it to // RGBA SkBitmap, so swizzle it. SwizzleBitmap(&y_plane); SwizzleBitmap(&uv_plane); } UnpackPlanarBitmap(y_plane, 0, &actual); UnpackUVBitmap(uv_plane, &actual); // Provide generous error limits to account for the chroma subsampling in the // |actual| result when compared to the perfect |expected| rendition. constexpr float kAvgAbsoluteErrorLimit = 16.f; constexpr int kMaxAbsoluteErrorLimit = 0x80; EXPECT_TRUE(cc::FuzzyPixelComparator(false, 100.f, 0.f, kAvgAbsoluteErrorLimit, kMaxAbsoluteErrorLimit, 0) .Compare(expected, actual)) << "\nActual: " << cc::GetPNGDataUrl(actual) << "\nExpected: " << cc::GetPNGDataUrl(expected); } // Run the tests, first parameter controls whether the MRT path is allowed, // the second controls whether the converter will use RGBA format vs BGRA (true // for RGBA, i.e. no swizzling done by the converter, false for BGRA, i.e. the // converter will swizzle the results when writing to texture). // These parameters have been chosen based on: 1) overriding defaults, to // confirm Parameters plumbing; and 2) typical operation on most platforms // (e.g., flipped source textures, the need to swizzle outputs, etc.). In // addition, the `scale_to()` is made to return width that is divisible by 4, // but not by 8, to test alignment requirements. INSTANTIATE_TEST_SUITE_P( All, GLNV12ConverterPixelTest, testing::Combine(testing::Bool(), testing::Bool(), testing::Values(gfx::Vector2d(2160, 1440)), testing::Values(gfx::Vector2d(1280, 720), gfx::Vector2d(900, 600)))); } // namespace viz
42.012903
80
0.697942
zealoussnow
ad40256c053577a8bbb2d49273a2a3265ecf901c
655
cpp
C++
application/robotcontrol.cpp
hcmarchezi/manipulator-robot-api
6ec50278496b10d3b31557f92f62d1521edefa2a
[ "MIT" ]
null
null
null
application/robotcontrol.cpp
hcmarchezi/manipulator-robot-api
6ec50278496b10d3b31557f92f62d1521edefa2a
[ "MIT" ]
null
null
null
application/robotcontrol.cpp
hcmarchezi/manipulator-robot-api
6ec50278496b10d3b31557f92f62d1521edefa2a
[ "MIT" ]
null
null
null
#include "robotcontrol.h" #include <QLabel> #include <QMessageBox> #include <iostream> namespace HIC { RobotControl::RobotControl(QWidget *parent) : QWidget(parent), _glWidget(NULL) { this->setLayout(new QVBoxLayout(this)); } void RobotControl::setGLWidget(HIC::ApplicationGLWidget* glWidget) { _glWidget = glWidget; PDC::Robot* robot = _glWidget->robot(); for(int index=0; index < robot->LinkCount(); index++) { PDC::Link* link = robot->GetLink(index); HIC::JointControl* jointControl = new HIC::JointControl(this, link, _glWidget); this->layout()->addWidget(jointControl); } } } // namespace HIC
20.46875
87
0.674809
hcmarchezi
ad423dd0a3c0fb482672ce144132846e1a433c65
640
cpp
C++
Group4StudentApp/Group4StudentApp/Semester.cpp
Skinny229/CMPSCGroup4
078d84266633a2c5730d758d62c631c5c0c05712
[ "MIT" ]
null
null
null
Group4StudentApp/Group4StudentApp/Semester.cpp
Skinny229/CMPSCGroup4
078d84266633a2c5730d758d62c631c5c0c05712
[ "MIT" ]
null
null
null
Group4StudentApp/Group4StudentApp/Semester.cpp
Skinny229/CMPSCGroup4
078d84266633a2c5730d758d62c631c5c0c05712
[ "MIT" ]
null
null
null
#include<iostream> #include <cstdlib> #include "Semester.h" #include <string> using namespace std; namespace SpaghettiLizards { Semester::Semester(string year1,string springOrFall1) { year = year1; springOrFall = springOrFall1; } void Semester::setSemester(string springOrFall1, string year1) { springOrFall = springOrFall1; year = year1; } void Semester::setSpringOrFall(string springOrFall1) { springOrFall = springOrFall1; } void Semester::setYear(string year1) { year = year1; } string Semester::getYear() const { return year; } string Semester::getSpringOrFall() const { return springOrFall; } }
17.297297
63
0.726563
Skinny229
ad42adce43dc6195ea01496eb87eca5dde246f17
4,403
cpp
C++
globe/globe_overlay.cpp
MarkY-LunarG/LunarGlobe
d32a6145eebc68ad4d7e28bdd4fab88cbdd33545
[ "Apache-2.0" ]
2
2018-06-20T15:19:38.000Z
2018-07-13T15:13:30.000Z
globe/globe_overlay.cpp
MarkY-LunarG/LunarGlobe
d32a6145eebc68ad4d7e28bdd4fab88cbdd33545
[ "Apache-2.0" ]
25
2018-07-27T23:02:01.000Z
2019-03-15T17:00:05.000Z
globe/globe_overlay.cpp
MarkY-LunarG/LunarGravity
d32a6145eebc68ad4d7e28bdd4fab88cbdd33545
[ "Apache-2.0" ]
null
null
null
// // Project: LunarGlobe // SPDX-License-Identifier: Apache-2.0 // // File: globe/globe_overlay.hpp // Copyright(C): 2019; LunarG, Inc. // Author(s): Mark Young <marky@lunarg.com> // #include "globe_resource_manager.hpp" #include "globe_submit_manager.hpp" #include "globe_font.hpp" #include "globe_overlay.hpp" GlobeOverlay::GlobeOverlay(GlobeResourceManager* resource_manager, GlobeSubmitManager* submit_manager, VkDevice vk_device) : _resource_mgr(resource_manager), _submit_mgr(submit_manager), _vk_device(vk_device), _vk_render_pass(VK_NULL_HANDLE) {} GlobeOverlay::~GlobeOverlay() { for (const auto font_element : _fonts) { font_element.second->UnloadFromRenderPass(); _resource_mgr->FreeFont(font_element.second); } } void GlobeOverlay::UpdateViewport(float viewport_width, float viewport_height) { _viewport_width = viewport_width; _viewport_height = viewport_height; } bool GlobeOverlay::SetRenderPass(VkRenderPass render_pass) { if (VK_NULL_HANDLE != _vk_render_pass || VK_NULL_HANDLE == render_pass) { for (const auto font_element : _fonts) { font_element.second->UnloadFromRenderPass(); } } _vk_render_pass = render_pass; if (VK_NULL_HANDLE != render_pass) { for (const auto font_element : _fonts) { font_element.second->LoadIntoRenderPass(_vk_render_pass, _viewport_width, _viewport_height); } } return true; } bool GlobeOverlay::LoadFont(const std::string& font_name, float max_height) { auto font_present = _fonts.find(font_name); if (font_present == _fonts.end()) { _fonts[font_name] = _resource_mgr->LoadFontMap(font_name, max_height); if (VK_NULL_HANDLE != _vk_render_pass) { _fonts[font_name]->LoadIntoRenderPass(_vk_render_pass, _viewport_width, _viewport_height); } } else if (font_present->second->Size() < max_height) { _resource_mgr->FreeFont(font_present->second); _fonts[font_name] = _resource_mgr->LoadFontMap(font_name, max_height); } return (_fonts[font_name] != nullptr); } int32_t GlobeOverlay::AddScreenSpaceStaticText(const std::string& font_name, float font_height, float x, float y, const glm::vec3& fg_color, const glm::vec4& bg_color, const std::string& text) { auto font_present = _fonts.find(font_name); if (font_present == _fonts.end()) { return -1; } glm::vec3 starting_pos(x, y, 0.f); glm::vec3 text_dir(1.f, 0.f, 0.f); glm::vec3 up_dir(0.f, -1.f, 0.f); float text_height = font_height / _viewport_height; return _fonts[font_name]->AddStaticString(text, fg_color, bg_color, starting_pos, text_dir, up_dir, text_height, _submit_mgr->GetGraphicsQueueIndex()); } int32_t GlobeOverlay::AddScreenSpaceDynamicText(const std::string& font_name, float font_height, float x, float y, const glm::vec3& fg_color, const glm::vec4& bg_color, const std::string& text, uint32_t copies) { auto font_present = _fonts.find(font_name); if (font_present == _fonts.end()) { return -1; } glm::vec3 starting_pos(x, y, 0.f); glm::vec3 text_dir(1.f, 0.f, 0.f); glm::vec3 up_dir(0.f, -1.f, 0.f); float text_height = font_height / _viewport_height; return _fonts[font_name]->AddDynamicString(text, fg_color, bg_color, starting_pos, text_dir, up_dir, text_height, _submit_mgr->GetGraphicsQueueIndex(), copies); } bool GlobeOverlay::UpdateDynamicText(const std::string& font_name, int32_t string_index, const std::string& text, uint32_t copy) { auto font_present = _fonts.find(font_name); if (font_present == _fonts.end()) { return false; } return font_present->second->UpdateStringText(string_index, text, copy); } bool GlobeOverlay::Draw(VkCommandBuffer command_buffer, uint32_t copy) { glm::mat4 identity(1.f); for (const auto font_element : _fonts) { font_element.second->DrawStrings(command_buffer, identity, copy); } return true; }
40.394495
117
0.642062
MarkY-LunarG
ad445921ebab16d57cc5dc642653ff473b7d0f9e
3,596
cpp
C++
compiler/ProcessGroup.cpp
astronalta/gamepython
3927dfbb0ae9706cd99d4f15ea792b30512dd4c1
[ "MIT" ]
null
null
null
compiler/ProcessGroup.cpp
astronalta/gamepython
3927dfbb0ae9706cd99d4f15ea792b30512dd4c1
[ "MIT" ]
null
null
null
compiler/ProcessGroup.cpp
astronalta/gamepython
3927dfbb0ae9706cd99d4f15ea792b30512dd4c1
[ "MIT" ]
null
null
null
/* * Copyright (c) 2010 Matt Fichman * * 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, APEXPRESS 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 "ProcessGroup.hpp" #include <iostream> #include <cassert> #ifndef WINDOWS #include <unistd.h> #endif void ProcessGroup::process(std::string const& args) { #ifdef WINDOWS if (system(args.c_str())) { errors_++; } /* PROCESS_INFORMATION procinfo; STARTUPINFO sinfo; memset(&procinfo, 0, sizeof(procinfo)); memset(&sinfo, 0, sizeof(sinfo)); std::string args2 = args; // N.B.: CreateProcess modifies the lpCommandLine parameter BOOL ret = CreateProcess( NULL, (LPSTR)args2.c_str(), NULL, NULL, false, 0, NULL, NULL, &sinfo, &procinfo); if (!ret) { std::cerr << "Error: Couldn't start subprocess: " << args << std::endl; errors_++; } else { CloseHandle(procinfo.hThread); process_.push_back(procinfo.hProcess); } */ #else pid_t pid = fork(); if (pid < 0) { std::cerr << "Error: Couldn't fork" << std::endl; abort(); } else if (pid == 0) { if (system(args.c_str())) { exit(1); } else { exit(0); } } else { process_.push_back(pid); } #endif } void ProcessGroup::wait() { // Wait for all child processes to complete. Records the number of child // errors; these errors are stored in the 'errors' attribute. for (size_t i = 0; i < process_.size(); ++i) { #ifdef WINDOWS /* DWORD ret = WaitForSingleObject(process_[i], INFINITE); if (ret != WAIT_OBJECT_0) { std::cerr << "WaitForSingleObject() error: " << GetLastError() << std::endl; abort(); } DWORD exit_code = 0; if(!GetExitCodeProcess(process_[i], &exit_code)) { std::cerr << "GetExitCodeProcess() error" << std::endl; abort(); } assert(exit_code != STILL_ACTIVE && "Process is still running"); if (exit_code != 0) { errors_++; } */ #else while (true) { int status = 0; pid_t pid = waitpid(process_[i], &status, 0); if (pid < 0) { errors_++; break; } else if (WIFEXITED(status)) { if (WEXITSTATUS(status)) { errors_++; } break; } else if (WIFSIGNALED(status)) { errors_++; break; } } #endif } process_.clear(); }
30.218487
88
0.587041
astronalta
ad45686ea7db59413c54e15914aaabc500880acf
6,211
cpp
C++
v1/z80gpu/gpu_protocol.cpp
amirgeva/z80pc
2daaa319ad7b313abdf0c73fc3faee8d6c36ed3e
[ "BSD-2-Clause" ]
null
null
null
v1/z80gpu/gpu_protocol.cpp
amirgeva/z80pc
2daaa319ad7b313abdf0c73fc3faee8d6c36ed3e
[ "BSD-2-Clause" ]
null
null
null
v1/z80gpu/gpu_protocol.cpp
amirgeva/z80pc
2daaa319ad7b313abdf0c73fc3faee8d6c36ed3e
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <chrono> #include "gpu_protocol.h" namespace gpu { Protocol prot; bool flip_screen = false; unsigned long millis() { static auto start = std::chrono::system_clock::now(); auto cur = std::chrono::system_clock::now(); return uint32_t(std::chrono::duration_cast<std::chrono::milliseconds>(cur - start).count()); } uint16_t Protocol::get_header_len() { switch (Header.cmd.opcode) { case CMD_NOP: return sizeof(Command); case CMD_CLS: return sizeof(Command_CLS); case CMD_FLIP: return sizeof(Command_Flip); case CMD_TEXT_NEWLINE: return sizeof(Command_NewLine); case CMD_PUSH_CURSOR: return sizeof(Command_PushCursor); case CMD_POP_CURSOR: return sizeof(Command_PopCursor); case CMD_PIXEL_CURSOR: return sizeof(Command_PixelCursor); case CMD_TEXT_CURSOR: return sizeof(Command_TextCursor); case CMD_BLINK_CURSOR: return sizeof(Command_BlinkCursor); case CMD_FILL_RECT: return sizeof(Command_FillRect); case CMD_HORZ_LINE: return sizeof(Command_HorzLine); case CMD_VERT_LINE: return sizeof(Command_VertLine); case CMD_HORZ_PIXELS: return sizeof(Command_HorzPixels); case CMD_TEXT: return sizeof(Command_Text); case CMD_FG_COLOR: return sizeof(Command_FGColor); case CMD_BG_COLOR: return sizeof(Command_BGColor); case CMD_SET_SPRITE: return sizeof(Command_SetSprite); case CMD_DRAW_SPRITE: return sizeof(Command_DrawSprite); } return 1; } uint16_t Protocol::check_variable_len() { switch (Header.cmd.opcode) { case CMD_HORZ_PIXELS: return Header.horz_pixels.n * 2 + sizeof(Command_HorzPixels) - m_Pos; case CMD_TEXT: return Header.text.n + sizeof(Command_Text) - m_Pos; case CMD_SET_SPRITE: return 16 * 16 * 2 + sizeof(Command_SetSprite) - m_Pos; } return 0; } bool Protocol::process_command() { switch (Header.cmd.opcode) { case CMD_CLS: { //std::cout << "CLS\n"; m_BGColor = 0; m_FGColor = 0x3FFF; m_Screen.fill_rect(0, 0, WIDTH - 1, HEIGHT - 1, 0); m_CursorX = 0; m_CursorY = 0; return true; } case CMD_FLIP: { flip_screen = true; return true; } case CMD_PUSH_CURSOR: { m_CursorStack.push(m_CursorX, m_CursorY); return true; } case CMD_POP_CURSOR: { m_CursorStack.pop(m_CursorX, m_CursorY); return true; } case CMD_TEXT_NEWLINE: { m_Font.new_line(m_CursorX, m_CursorY, m_Screen); return true; } case CMD_PIXEL_CURSOR: { m_CursorX = Header.pixel_cursor.x; m_CursorY = Header.pixel_cursor.y; return true; } case CMD_TEXT_CURSOR: { m_CursorX = Header.text_cursor.x * m_Font.get_width(); m_CursorY = Header.text_cursor.y * m_Font.get_height(); return true; } case CMD_BLINK_CURSOR: { m_Blink = (Header.blink_cursor.state > 0); return true; } case CMD_FILL_RECT: { m_Screen.fill_rect(m_CursorX, m_CursorY, m_CursorX + Header.fill_rect.w - 1, m_CursorY + Header.fill_rect.h - 1, m_BGColor); return true; } case CMD_HORZ_LINE: { m_Screen.horz_line(m_CursorY, m_CursorX, m_CursorX + Header.horz_line.w - 1, m_FGColor); m_CursorX += Header.horz_line.w; return true; } case CMD_VERT_LINE: { m_Screen.vert_line(m_CursorX, m_CursorY, m_CursorY + Header.vert_line.h - 1, m_FGColor); m_CursorY += Header.vert_line.h; return true; } case CMD_HORZ_PIXELS: { const uint16_t* data = reinterpret_cast<const uint16_t*>(&Header.horz_pixels.opcode + sizeof(Command_HorzPixels)); for (int i = 0; i < Header.horz_pixels.n; ++i) m_Screen.pixel(m_CursorX++, m_CursorY, *data++); return true; } case CMD_TEXT: { const char* text = reinterpret_cast<const char*>(&Header.text.opcode + sizeof(Command_Text)); m_Font.draw(text, m_CursorX, m_CursorY, m_Screen, m_FGColor, m_BGColor, true); return true; } case CMD_FG_COLOR: { m_FGColor = Header.fg_color.color; return true; } case CMD_BG_COLOR: { m_BGColor = Header.bg_color.color; return true; } case CMD_SET_SPRITE: { Color* ptr = m_Sprites.get_sprite(Header.set_sprite.id); if (ptr) { const Color* src = reinterpret_cast<const Color*>(&Header.set_sprite.opcode + sizeof(Command_SetSprite)); constexpr uint8_t sixteen = 16; int w = Min(Header.set_sprite.w, sixteen); int h = Min(Header.set_sprite.h, sixteen); for (int i = 0; i < h; ++i) { for(int j = 0; j < w; ++j) *ptr++ = *src++; for(int j = w; j < 16; ++j) *ptr++ = 0; } for(int i = h; i < 16; ++i) for(int j = 0; j < 16; ++j) *ptr++ = 0; return true; } return false; } case CMD_DRAW_SPRITE: { //std::cout << "Draw sprite " << int(Header.draw_sprite.id) << " at " << m_CursorX << "," << m_CursorY << std::endl; Sprite spr(m_Sprites.get_sprite(Header.draw_sprite.id)); spr.draw(m_Screen, m_CursorX, m_CursorY); return true; } } return false; } void Protocol::loop() { if (m_Blink) { static bool on = false; static unsigned long start = 0; unsigned long cur = millis(); if (start == 0) start = cur; if ((cur - start) > 500) { const char* text = "\001"; uint16_t x = m_CursorX, y = m_CursorY; m_Font.draw(on ? text : " ", x, y, m_Screen, m_FGColor, m_BGColor, false); start = cur; on = !on; flip_screen = true; } } } void Protocol::add_byte(uint8_t b) { if (m_Pos == 0) { Header.cmd.opcode = b; m_BytesLeft = get_header_len() - 1; ++m_Pos; } else { uint8_t* ptr = &Header.cmd.opcode; ptr[m_Pos++] = b; ptr[m_Pos] = 0; --m_BytesLeft; } if (m_BytesLeft == 0) m_BytesLeft = check_variable_len(); if (m_BytesLeft == 0) { process_command(); m_Pos = 0; } } }
27.361233
122
0.610047
amirgeva
ad48b051ae477621bc78908566c8ef6c1b8c7e37
6,093
cpp
C++
src/cws_in_ascii.cpp
kampersanda/consistent_weighted_sampling
6fbcf372a23d778b4f346e1c181004d7a9e555c0
[ "MIT" ]
6
2019-07-22T08:53:14.000Z
2021-12-21T22:03:37.000Z
src/cws_in_ascii.cpp
kampersanda/consistent_weighted_sampling
6fbcf372a23d778b4f346e1c181004d7a9e555c0
[ "MIT" ]
null
null
null
src/cws_in_ascii.cpp
kampersanda/consistent_weighted_sampling
6fbcf372a23d778b4f346e1c181004d7a9e555c0
[ "MIT" ]
2
2021-02-17T17:09:58.000Z
2021-03-01T11:09:33.000Z
#include <chrono> #include <numeric> #include "cmdline.h" #include "misc.hpp" #include "splitmix.hpp" using namespace ascii_format; constexpr size_t BUFFER_VECS = 100'000; template <int Flags> int run(const cmdline::parser& p) { using data_loader_type = data_loader<Flags>; using data_vec_type = vector<elem_type<Flags>>; auto input_fn = p.get<string>("input_fn"); auto output_fn = p.get<string>("output_fn"); auto dat_dim = p.get<size_t>("dat_dim"); auto cws_dim = p.get<size_t>("cws_dim"); auto begin_id = p.get<uint32_t>("begin_id"); auto seed = p.get<size_t>("seed"); if (is_generalized<Flags>()) { dat_dim *= 2; } cout << "1) Generate random matrix data..." << endl; vector<float> R(dat_dim * cws_dim); vector<float> C(dat_dim * cws_dim); vector<float> B(dat_dim * cws_dim); splitmix64 seeder(seed); const size_t seed_R = seeder.next(); const size_t seed_C = seeder.next(); const size_t seed_B = seeder.next(); auto start_tp = chrono::system_clock::now(); #pragma omp parallel sections { #pragma omp section generate_random_matrix(gamma_t(2.0, 1.0), R, seed_R); #pragma omp section generate_random_matrix(gamma_t(2.0, 1.0), C, seed_C); #pragma omp section generate_random_matrix(uniform_t(0.0, 1.0), B, seed_B); } auto dur_cnt = chrono::duration_cast<chrono::seconds>(chrono::system_clock::now() - start_tp).count(); cout << "Elapsed time: " << dur_cnt / 3600 << "h" << dur_cnt / 60 % 60 << "m" << dur_cnt % 60 << "s" << endl; { // Consume (4 * num_samples * data_dim) bytes for each matrix auto MiB = (sizeof(float) * R.size() * 3) / (1024.0 * 1024.0); cout << "The random matrix data consumes " << MiB << " MiB" << endl; } cout << "2) Do consistent weighted sampling..." << endl; data_loader_type in(input_fn, begin_id); ofstream out = make_ofstream(output_fn + ".bvecs"); vector<data_vec_type> in_buffer(BUFFER_VECS); vector<uint8_t> out_buffer(BUFFER_VECS * cws_dim); size_t processed = 0; start_tp = chrono::system_clock::now(); while (true) { // Bulk Loading size_t num_vecs = 0; while (num_vecs < BUFFER_VECS) { if (!in.next()) { break; } in_buffer[num_vecs] = in.get(); num_vecs += 1; } if (num_vecs == 0) { break; } // Sampling #pragma omp parallel for for (size_t id = 0; id < num_vecs; ++id) { const data_vec_type& data_vec = in_buffer[id]; uint8_t* cws_vec = &out_buffer[id * cws_dim]; for (size_t i = 0; i < cws_dim; ++i) { const float* vec_R = &R[i * dat_dim]; const float* vec_C = &C[i * dat_dim]; const float* vec_B = &B[i * dat_dim]; float min_a = numeric_limits<float>::max(); size_t min_id = 0; for (const auto& feat : data_vec) { uint32_t j = feat.id(); float t = floor(log10(feat.weight()) / vec_R[j] + vec_B[j]); float a = log10(vec_C[j]) - (vec_R[j] * (t + 1.0 - vec_B[j])); if (a < min_a) { min_a = a; min_id = j; } } if (dat_dim <= min_id) { cerr << "error: min_id exceeds dat_dim" << endl; exit(1); } // Write the lowest 8 bits for samples cws_vec[i] = static_cast<uint8_t>(min_id & UINT8_MAX); } } // Write for (size_t id = 0; id < num_vecs; ++id) { write_value(out, static_cast<uint32_t>(cws_dim)); write_vec(out, &out_buffer[id * cws_dim], cws_dim); } processed += num_vecs; dur_cnt = chrono::duration_cast<chrono::seconds>(chrono::system_clock::now() - start_tp).count(); cout << processed << " vecs processed in "; cout << dur_cnt / 3600 << "h" << dur_cnt / 60 % 60 << "m" << dur_cnt % 60 << "s" << endl; } dur_cnt = chrono::duration_cast<chrono::seconds>(chrono::system_clock::now() - start_tp).count(); cout << "Completed!! --> " << processed << " vecs processed in "; cout << dur_cnt / 3600 << "h" << dur_cnt / 60 % 60 << "m" << dur_cnt % 60 << "s!!" << endl; cout << "Output " << output_fn << ".bvecs" << endl; return 0; } template <int Flags = 0> int run_with_flags(int flags, const cmdline::parser& p) { if constexpr (Flags > FLAGS_MAX) { cerr << "Error: invalid flags\n"; return 1; } else { if (flags == Flags) { return run<Flags>(p); } return run_with_flags<Flags + 1>(flags, p); } } int main(int argc, char** argv) { ios::sync_with_stdio(false); cout << "num threads: " << omp_get_max_threads() << endl; cmdline::parser p; p.add<string>("input_fn", 'i', "input file name of database vectors (in ASCII format)", true); p.add<string>("output_fn", 'o', "output file name of CWS-sketches (in bvecs format)", true); p.add<size_t>("dat_dim", 'd', "dimension of the input data", true); p.add<size_t>("cws_dim", 'D', "dimension of the output CWS-sketches", false, 64); p.add<uint32_t>("begin_id", 'b', "beginning ID of data column", false, 0); p.add<bool>("weighted", 'w', "Does the input data have weight?", false, false); p.add<bool>("generalized", 'g', "Does the input data need to be generalized?", false, false); p.add<bool>("labeled", 'l', "Does each input vector have a label at the head?", false, false); p.add<size_t>("seed", 's', "seed for random matrix data", false, 114514); p.parse_check(argc, argv); auto weighted = p.get<bool>("weighted"); auto generalized = p.get<bool>("generalized"); auto labeled = p.get<bool>("labeled"); auto flags = make_flags(weighted, generalized, labeled); return run_with_flags(flags, p); }
34.423729
113
0.561792
kampersanda
ad4be77542a61d5c46736bdd62c5d2aa2b560d07
22,634
cpp
C++
toonz/sources/toonzlib/sandor_fxs/blend.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/toonzlib/sandor_fxs/blend.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/toonzlib/sandor_fxs/blend.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
1
2019-10-07T17:12:30.000Z
2019-10-07T17:12:30.000Z
#include "blend.h" //TPoint structure #include "tgeometry.h" //Palette - pixel functions #include "tpalette.h" #include "tpixelutils.h" #include <vector> //================================================================================= //=========================== // Blur pattern class //--------------------------- //! The BlurPattern class delineates the idea of a 'blur' //! pattern from a number of random sample points taken //! in a neighbourhood of the blurred pixel. The pattern //! develops in a radial manner if specified, so that possible //! 'obstacles' in the blur can be identified. class BlurPattern { public: typedef std::vector<TPoint> SamplePath; std::vector<TPoint> m_samples; std::vector<SamplePath> m_samplePaths; BlurPattern(double distance, unsigned int samplesCount, bool radial); ~BlurPattern() {} }; //--------------------------------------------------------------------------------- //Builds the specified number of samples count, inside the specified distance //from the origin. If the pattern is radial, paths to the samples points are //calculated. BlurPattern::BlurPattern(double distance, unsigned int samplesCount, bool radial) { const double randFactor = 2.0 * distance / RAND_MAX; m_samples.resize(samplesCount); //Build the samples unsigned int i; for (i = 0; i < samplesCount; ++i) { //NOTE: The following method ensures a perfectly flat probability distribution. TPoint candidatePoint(tround(rand() * randFactor - distance), tround(rand() * randFactor - distance)); double distanceSq = sq(distance); while (sq(candidatePoint.x) + sq(candidatePoint.y) > distanceSq) candidatePoint = TPoint(tround(rand() * randFactor - distance), tround(rand() * randFactor - distance)); m_samples[i] = candidatePoint; } m_samplePaths.resize(samplesCount); //If necessary, build the paths if (radial) { for (i = 0; i < samplesCount; ++i) { TPoint &sample = m_samples[i]; int l = tmax(abs(sample.x), abs(sample.y)); m_samplePaths[i].reserve(l); double dx = sample.x / (double)l; double dy = sample.y / (double)l; double x, y; int j; for (j = 0, x = dx, y = dy; j < l; x += dx, y += dy, ++j) m_samplePaths[i].push_back(TPoint(tround(x), tround(y))); } } } //================================================================================= //================================= // Raster Selection classes //--------------------------------- struct SelectionData { UCHAR m_selectedInk : 1; UCHAR m_selectedPaint : 1; UCHAR m_pureInk : 1; UCHAR m_purePaint : 1; }; //================================================================================= // Implements an array of selection infos using bitfields. It seems that bitfields are more optimized than // using raw bits and bitwise operators, and use just the double of the space required with bit arrays. class SelectionArrayPtr { std::unique_ptr<SelectionData[]> m_buffer; public: inline void allocate(unsigned int count) { m_buffer.reset(new SelectionData[count]); memset(m_buffer.get(), 0, count * sizeof(SelectionData)); } inline void destroy() { m_buffer.reset(); } inline SelectionData *data() const { return m_buffer.get(); } inline SelectionData *data() { return m_buffer.get(); } }; //================================================================================= // Bitmap used to store blend color selections and pure color informations. class SelectionRaster { SelectionArrayPtr m_selection; int m_wrap; public: SelectionRaster(TRasterCM32P cm); void updateSelection(TRasterCM32P cm, const BlendParam &param); SelectionData *data() const { return m_selection.data(); } SelectionData *data() { return m_selection.data(); } void destroy() { m_selection.destroy(); } bool isSelectedInk(int xy) const { return (m_selection.data() + xy)->m_selectedInk; } bool isSelectedInk(int x, int y) const { return isSelectedInk(x + y * m_wrap); } bool isSelectedPaint(int xy) const { return (m_selection.data() + xy)->m_selectedPaint; } bool isSelectedPaint(int x, int y) const { return isSelectedPaint(x + y * m_wrap); } bool isPureInk(int xy) const { return (m_selection.data() + xy)->m_pureInk; } bool isPureInk(int x, int y) const { return isPureInk(x + y * m_wrap); } bool isPurePaint(int xy) const { return (m_selection.data() + xy)->m_purePaint; } bool isPurePaint(int x, int y) const { return isPurePaint(x + y * m_wrap); } bool isToneColor(int xy) const { return !(isPureInk(xy) || isPurePaint(xy)); } bool isToneColor(int x, int y) const { return isToneColor(x + y * m_wrap); } }; //--------------------------------------------------------------------------------- inline UCHAR linearSearch(const int *v, unsigned int vSize, int k) { const int *vEnd = v + vSize; for (; v < vEnd; ++v) if (*v == k) return 1; return 0; } //--------------------------------------------------------------------------------- // I've seen the std::binary_search go particularly slow... perhaps it was the debug mode, // but I guess this is the fastest version possible. inline UCHAR binarySearch(const int *v, unsigned int vSize, int k) { //NOTE: v.size() > 0 due to external restrictions. See SelectionRaster's constructor. int a = -1, b, c = vSize; for (b = c >> 1; b != a; b = (a + c) >> 1) { if (v[b] == k) return 1; else if (k < v[b]) c = b; else a = b; } return 0; } //--------------------------------------------------------------------------------- SelectionRaster::SelectionRaster(TRasterCM32P cm) { unsigned int lx = cm->getLx(), ly = cm->getLy(), wrap = cm->getWrap(); unsigned int size = lx * ly; m_wrap = lx; m_selection.allocate(size); cm->lock(); TPixelCM32 *pix, *pixBegin = (TPixelCM32 *)cm->getRawData(); SelectionData *selData = data(); unsigned int i, j; for (i = 0; i < ly; ++i) { pix = pixBegin + i * wrap; for (j = 0; j < lx; ++j, ++pix, ++selData) { selData->m_pureInk = pix->getTone() == 0; selData->m_purePaint = pix->getTone() == 255; } } cm->unlock(); } //--------------------------------------------------------------------------------- void SelectionRaster::updateSelection(TRasterCM32P cm, const BlendParam &param) { //Make a hard copy of color indexes. We do so since we absolutely prefer //having them SORTED! std::vector<int> cIndexes = param.colorsIndexes; std::sort(cIndexes.begin(), cIndexes.end()); unsigned int lx = cm->getLx(), ly = cm->getLy(), wrap = cm->getWrap(); //Scan each cm pixel, looking if its ink or paint is in param's colorIndexes. cm->lock(); TPixelCM32 *pix, *pixBegin = (TPixelCM32 *)cm->getRawData(); SelectionData *selData = data(); const int *v = &cIndexes[0]; //NOTE: cIndexes.size() > 0 due to external check. unsigned int vSize = cIndexes.size(); unsigned int i, j; //NOTE: It seems that linear searches are definitely best for small color indexes. if (vSize > 50) { for (i = 0; i < ly; ++i) { pix = pixBegin + i * wrap; for (j = 0; j < lx; ++j, ++pix, ++selData) { selData->m_selectedInk = binarySearch(v, vSize, pix->getInk()); selData->m_selectedPaint = binarySearch(v, vSize, pix->getPaint()); } } } else { for (i = 0; i < ly; ++i) { pix = pixBegin + i * wrap; for (j = 0; j < lx; ++j, ++pix, ++selData) { selData->m_selectedInk = linearSearch(v, vSize, pix->getInk()); selData->m_selectedPaint = linearSearch(v, vSize, pix->getPaint()); } } } cm->unlock(); } //================================================================================= //======================== // Blend functions //------------------------ // Pixel whose channels are doubles. Used to store intermediate values for pixel blending. struct DoubleRGBMPixel { double r; double g; double b; double m; DoubleRGBMPixel() : r(0.0), g(0.0), b(0.0), m(0.0) {} }; //--------------------------------------------------------------------------------- const double maxTone = TPixelCM32::getMaxTone(); // Returns the ink & paint convex factors associated with passed tone. inline void getFactors(int tone, double &inkFactor, double &paintFactor) { paintFactor = tone / maxTone; inkFactor = (1.0 - paintFactor); } //--------------------------------------------------------------------------------- // Copies the cmIn paint and ink colors to the output rasters. void buildLayers( const TRasterCM32P &cmIn, const std::vector<TPixel32> &palColors, TRaster32P &inkRaster, TRaster32P &paintRaster) { //Separate cmIn by copying the ink & paint colors directly to the layer rasters. TPixelCM32 *cmPix, *cmBegin = (TPixelCM32 *)cmIn->getRawData(); TPixel32 *inkPix = (TPixel32 *)inkRaster->getRawData(); TPixel32 *paintPix = (TPixel32 *)paintRaster->getRawData(); unsigned int i, j, lx = cmIn->getLx(), ly = cmIn->getLy(), wrap = cmIn->getWrap(); for (i = 0; i < ly; ++i) { cmPix = cmBegin + i * wrap; for (j = 0; j < lx; ++j, ++cmPix, ++inkPix, ++paintPix) { *inkPix = palColors[cmPix->getInk()]; *paintPix = palColors[cmPix->getPaint()]; //Should pure colors be checked...? } } } //--------------------------------------------------------------------------------- // Returns true or false whether the selectedColor is the only selectable color // in the neighbourhood. If so, the blend copies it to the output layer pixel directly. inline bool isFlatNeighbourhood( int selectedColor, const TRasterCM32P &cmIn, const TPoint &pos, const SelectionRaster &selRas, const BlurPattern &blurPattern) { TPixelCM32 &pix = cmIn->pixels(pos.y)[pos.x]; int lx = cmIn->getLx(), ly = cmIn->getLy(); unsigned int xy; TPoint samplePix; const TPoint *samplePoint = blurPattern.m_samples.empty() ? 0 : &blurPattern.m_samples[0]; //Read the samples to determine if they only have posSelectedColor unsigned int i, samplesCount = blurPattern.m_samples.size(); for (i = 0; i < samplesCount; ++i, ++samplePoint) { //Make sure the sample is inside the image samplePix.x = pos.x + samplePoint->x; samplePix.y = pos.y + samplePoint->y; xy = samplePix.x + lx * samplePix.y; if (samplePix.x < 0 || samplePix.y < 0 || samplePix.x >= lx || samplePix.y >= ly) continue; if (!selRas.isPurePaint(xy) && selRas.isSelectedInk(xy)) if (cmIn->pixels(samplePix.y)[samplePix.x].getInk() != selectedColor) return false; if (!selRas.isPureInk(xy) && selRas.isSelectedPaint(xy)) if (cmIn->pixels(samplePix.y)[samplePix.x].getPaint() != selectedColor) return false; } return true; } //--------------------------------------------------------------------------------- // Calculates the estimate of blend selection in the neighbourhood specified by // blurPattern. inline void addSamples( const TRasterCM32P &cmIn, const TPoint &pos, const TRaster32P &inkRas, const TRaster32P &paintRas, const SelectionRaster &selRas, const BlurPattern &blurPattern, DoubleRGBMPixel &pixSum, double &factorsSum) { double inkFactor, paintFactor; unsigned int xy, j, l; int lx = cmIn->getLx(), ly = cmIn->getLy(); TPixel32 *color; TPoint samplePos, pathPos; const TPoint *samplePoint = blurPattern.m_samples.empty() ? 0 : &blurPattern.m_samples[0]; const TPoint *pathPoint; unsigned int i, blurSamplesCount = blurPattern.m_samples.size(); for (i = 0; i < blurSamplesCount; ++i, ++samplePoint) { //Add each samples contribute to the sum samplePos.x = pos.x + samplePoint->x; samplePos.y = pos.y + samplePoint->y; if (samplePos.x < 0 || samplePos.y < 0 || samplePos.x >= lx || samplePos.y >= ly) continue; //Ensure that each pixel on the sample's path (if any) is selected l = blurPattern.m_samplePaths[i].size(); pathPoint = blurPattern.m_samplePaths[i].empty() ? 0 : &blurPattern.m_samplePaths[i][0]; for (j = 0; j < l; ++j, ++pathPoint) { pathPos.x = pos.x + pathPoint->x; pathPos.y = pos.y + pathPoint->y; xy = pathPos.x + lx * pathPos.y; if (!(selRas.isPurePaint(xy) || selRas.isSelectedInk(xy))) break; if (!(selRas.isPureInk(xy) || selRas.isSelectedPaint(xy))) break; } if (j < l) continue; xy = samplePos.x + lx * samplePos.y; if (selRas.isSelectedInk(xy) && !selRas.isPurePaint(xy)) { getFactors(cmIn->pixels(samplePos.y)[samplePos.x].getTone(), inkFactor, paintFactor); color = &inkRas->pixels(samplePos.y)[samplePos.x]; pixSum.r += inkFactor * color->r; pixSum.g += inkFactor * color->g; pixSum.b += inkFactor * color->b; pixSum.m += inkFactor * color->m; factorsSum += inkFactor; } if (selRas.isSelectedPaint(xy) && !selRas.isPureInk(xy)) { getFactors(cmIn->pixels(samplePos.y)[samplePos.x].getTone(), inkFactor, paintFactor); color = &paintRas->pixels(samplePos.y)[samplePos.x]; pixSum.r += paintFactor * color->r; pixSum.g += paintFactor * color->g; pixSum.b += paintFactor * color->b; pixSum.m += paintFactor * color->m; factorsSum += paintFactor; } } } //--------------------------------------------------------------------------------- typedef std::pair<TRaster32P, TRaster32P> RGBMRasterPair; //--------------------------------------------------------------------------------- // Performs a single color blending. This function can be repeatedly invoked to // perform multiple color blending. inline void doBlend( const TRasterCM32P &cmIn, RGBMRasterPair &inkLayer, RGBMRasterPair &paintLayer, const SelectionRaster &selRas, const std::vector<BlurPattern> &blurPatterns) { //Declare some vars unsigned int blurPatternsCount = blurPatterns.size(); int lx = cmIn->getLx(), ly = cmIn->getLy(); double totalFactor; TPixelCM32 *cmPix, *cmBegin = (TPixelCM32 *)cmIn->getRawData(); TPixel32 *inkIn = (TPixel32 *)inkLayer.first->getRawData(), *inkOut = (TPixel32 *)inkLayer.second->getRawData(), *paintIn = (TPixel32 *)paintLayer.first->getRawData(), *paintOut = (TPixel32 *)paintLayer.second->getRawData(); const BlurPattern *blurPattern, *blurPatternsBegin = &blurPatterns[0]; bool builtSamples = false; DoubleRGBMPixel samplesSum; //For every cmIn pixel TPoint pos; SelectionData *selData = selRas.data(); cmPix = cmBegin; for (pos.y = 0; pos.y < ly; ++pos.y, cmPix = cmBegin + pos.y * cmIn->getWrap()) for (pos.x = 0; pos.x < lx; ++pos.x, ++inkIn, ++inkOut, ++paintIn, ++paintOut, ++selData, ++cmPix) { blurPattern = blurPatternsBegin + (rand() % blurPatternsCount); //Build the ink blend color if (!selData->m_purePaint && selData->m_selectedInk) { if (!builtSamples) { //Build samples contributes totalFactor = 1.0; samplesSum.r = samplesSum.g = samplesSum.b = samplesSum.m = 0.0; if (!isFlatNeighbourhood(cmPix->getInk(), cmIn, pos, selRas, *blurPattern)) addSamples(cmIn, pos, inkLayer.first, paintLayer.first, selRas, *blurPattern, samplesSum, totalFactor); builtSamples = true; } //Output the blended pixel inkOut->r = (samplesSum.r + inkIn->r) / totalFactor; inkOut->g = (samplesSum.g + inkIn->g) / totalFactor; inkOut->b = (samplesSum.b + inkIn->b) / totalFactor; inkOut->m = (samplesSum.m + inkIn->m) / totalFactor; } else { //If the color is not blended, then just copy the old layer pixel *inkOut = *inkIn; } //Build the paint blend color if (!selData->m_pureInk && selData->m_selectedPaint) { if (!builtSamples) { //Build samples contributes totalFactor = 1.0; samplesSum.r = samplesSum.g = samplesSum.b = samplesSum.m = 0.0; if (!isFlatNeighbourhood(cmPix->getPaint(), cmIn, pos, selRas, *blurPattern)) addSamples(cmIn, pos, inkLayer.first, paintLayer.first, selRas, *blurPattern, samplesSum, totalFactor); builtSamples = true; } //Output the blended pixel paintOut->r = (samplesSum.r + paintIn->r) / totalFactor; paintOut->g = (samplesSum.g + paintIn->g) / totalFactor; paintOut->b = (samplesSum.b + paintIn->b) / totalFactor; paintOut->m = (samplesSum.m + paintIn->m) / totalFactor; } else { //If the color is not blended, then just copy the old layer pixel *paintOut = *paintIn; } builtSamples = false; } } //--------------------------------------------------------------------------------- typedef std::vector<BlurPattern> BlurPatternContainer; //--------------------------------------------------------------------------------- /*! This function performs a group of <a> spatial color blending <\a> operations on Toonz Images. The BlendParam structure stores the blend options recognized by this function; it includes a list of the palette indexes involved in the blend operation, plus: \li \b Intensity represents the \a radius of the blur operation between blend colors. \li \b Smoothness is the number of samples per pixel used to approximate the blur. <li> <b> Stop at Contour <\b> specifies if lines from pixels to neighbouring samples should not trespass color indexes not included in the blend operation <\li> The succession of input blend parameters are applied in the order. */ template <typename PIXEL> void blend(TToonzImageP ti, TRasterPT<PIXEL> rasOut, const std::vector<BlendParam> &params) { assert(ti->getRaster()->getSize() == rasOut->getSize()); //Extract the interesting raster. It should be the savebox of passed cmap, plus - if //some param has the 0 index as blending color - the intensity of that blend param. unsigned int i, j; TRect saveBox(ti->getSavebox()); int enlargement = 0; for (i = 0; i < params.size(); ++i) for (j = 0; j < params[i].colorsIndexes.size(); ++j) if (params[i].colorsIndexes[j] == 0) enlargement = tmax(enlargement, tceil(params[i].intensity)); saveBox = saveBox.enlarge(enlargement); TRasterCM32P cmIn(ti->getRaster()->extract(saveBox)); TRasterPT<PIXEL> rasOutExtract = rasOut->extract(saveBox); //Ensure that cmIn and rasOut have the same size unsigned int lx = cmIn->getLx(), ly = cmIn->getLy(); //Build the pure colors infos SelectionRaster selectionRaster(cmIn); //Now, build a little group of BlurPatterns - and for each, one for passed param. //A small number of patterns per param is needed to make the pattern look not ever the same. const int blurPatternsPerParam = 10; std::vector<BlurPatternContainer> blurGroup(params.size()); for (i = 0; i < params.size(); ++i) { BlurPatternContainer &blurContainer = blurGroup[i]; blurContainer.reserve(blurPatternsPerParam); for (j = 0; j < blurPatternsPerParam; ++j) blurContainer.push_back(BlurPattern(params[i].intensity, params[i].smoothness, params[i].stopAtCountour)); } //Build the palette TPalette *palette = ti->getPalette(); std::vector<TPixel32> paletteColors; paletteColors.resize(palette->getStyleCount()); for (i = 0; i < paletteColors.size(); ++i) paletteColors[i] = premultiply(palette->getStyle(i)->getAverageColor()); //Build the 4 auxiliary rasters for the blending procedure: they are ink / paint versus input / output in the blend. //The output raster is reused to spare some memory - it should be, say, the inkLayer's second at the end of the overall //blending procedure. It could be the first, without the necessity of clearing it before blending the layers, but things //get more complicated when PIXEL is TPixel64... RGBMRasterPair inkLayer, paintLayer; TRaster32P rasOut32P_1(lx, ly, lx, (TPixel32 *)rasOut->getRawData(), false); inkLayer.first = (params.size() % 2) ? rasOut32P_1 : TRaster32P(lx, ly); inkLayer.second = (params.size() % 2) ? TRaster32P(lx, ly) : rasOut32P_1; if (PIXEL::maxChannelValue >= TPixel64::maxChannelValue) { TRaster32P rasOut32P_2(lx, ly, lx, ((TPixel32 *)rasOut->getRawData()) + lx * ly, false); paintLayer.first = (params.size() % 2) ? rasOut32P_2 : TRaster32P(lx, ly); paintLayer.second = (params.size() % 2) ? TRaster32P(lx, ly) : rasOut32P_2; } else { paintLayer.first = TRaster32P(lx, ly); paintLayer.second = TRaster32P(lx, ly); } inkLayer.first->clear(); inkLayer.second->clear(); paintLayer.first->clear(); paintLayer.second->clear(); //Now, we have to perform the blur of each of the cm's pixels. cmIn->lock(); rasOut->lock(); inkLayer.first->lock(); inkLayer.second->lock(); paintLayer.first->lock(); paintLayer.second->lock(); //Convert the initial cmIn to fullcolor ink - paint layers buildLayers(cmIn, paletteColors, inkLayer.first, paintLayer.first); //Perform the blend on separated ink - paint layers for (i = 0; i < params.size(); ++i) { if (params[i].colorsIndexes.size() == 0) continue; selectionRaster.updateSelection(cmIn, params[i]); doBlend(cmIn, inkLayer, paintLayer, selectionRaster, blurGroup[i]); tswap(inkLayer.first, inkLayer.second); tswap(paintLayer.first, paintLayer.second); } //Release the unnecessary rasters inkLayer.second->unlock(); paintLayer.second->unlock(); inkLayer.second = TRaster32P(); paintLayer.second = TRaster32P(); //Clear rasOut - since it was reused to spare space... rasOut->clear(); //Add the ink & paint layers on the output raster double PIXELmaxChannelValue = PIXEL::maxChannelValue; double toPIXELFactor = PIXELmaxChannelValue / (double)TPixel32::maxChannelValue; double inkFactor, paintFactor; TPoint pos; PIXEL *outPix, *outBegin = (PIXEL *)rasOutExtract->getRawData(); TPixelCM32 *cmPix, *cmBegin = (TPixelCM32 *)cmIn->getRawData(); int wrap = rasOutExtract->getWrap(); TPixel32 *inkPix = (TPixel32 *)inkLayer.first->getRawData(); TPixel32 *paintPix = (TPixel32 *)paintLayer.first->getRawData(); for (i = 0; i < ly; ++i) { outPix = outBegin + wrap * i; cmPix = cmBegin + wrap * i; for (j = 0; j < lx; ++j, ++outPix, ++cmPix, ++inkPix, ++paintPix) { getFactors(cmPix->getTone(), inkFactor, paintFactor); outPix->r = tcrop(toPIXELFactor * (inkFactor * inkPix->r + paintFactor * paintPix->r), 0.0, PIXELmaxChannelValue); outPix->g = tcrop(toPIXELFactor * (inkFactor * inkPix->g + paintFactor * paintPix->g), 0.0, PIXELmaxChannelValue); outPix->b = tcrop(toPIXELFactor * (inkFactor * inkPix->b + paintFactor * paintPix->b), 0.0, PIXELmaxChannelValue); outPix->m = tcrop(toPIXELFactor * (inkFactor * inkPix->m + paintFactor * paintPix->m), 0.0, PIXELmaxChannelValue); } } inkLayer.first->unlock(); paintLayer.first->unlock(); cmIn->unlock(); rasOut->unlock(); //Destroy the auxiliary bitmaps selectionRaster.destroy(); } template void blend<TPixel32>(TToonzImageP cmIn, TRasterPT<TPixel32> rasOut, const std::vector<BlendParam> &params); template void blend<TPixel64>(TToonzImageP cmIn, TRasterPT<TPixel64> rasOut, const std::vector<BlendParam> &params);
31.133425
121
0.635769
ss23
ad4c8405afdb704229054c88a16e06129c3a9ab6
1,945
cpp
C++
algorithm-contest-3/code/2.cpp
crupest/what-can-a-programmer-do
e704ef15dcb0663192a353760108ce7d52ab840b
[ "MIT" ]
2
2021-11-28T06:38:13.000Z
2021-12-18T12:55:37.000Z
algorithm-contest-3/code/2.cpp
crupest/what-can-a-programmer-do
e704ef15dcb0663192a353760108ce7d52ab840b
[ "MIT" ]
null
null
null
algorithm-contest-3/code/2.cpp
crupest/what-can-a-programmer-do
e704ef15dcb0663192a353760108ce7d52ab840b
[ "MIT" ]
1
2021-12-18T14:03:19.000Z
2021-12-18T14:03:19.000Z
#include <algorithm> #include <cstdio> #include <vector> int ConvertYear(int x) { if (x >= 60) return 1900 + x; return 2000 + x; } bool CheckMonth(int x) { if (x <= 0 && x >= 13) { return false; } return true; } bool IsLeapYear(int y) { if (y == 2000) return false; if (y % 4) return false; return true; } int days[] = {0, 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; bool CheckDay(int day, int month, int year) { if (month == 2) { const bool leap = IsLeapYear(year); if (leap) { return day >= 1 && day <= 29; } else { return day >= 1 && day <= 28; } } return day >= 1 && day <= days[month]; } struct Date { int year; int month; int day; }; bool operator==(const Date &l, const Date &r) { return l.year == r.year && l.month == r.month && l.day == r.day; } bool operator<(const Date &l, const Date &r) { if (l.year < r.year) return true; else if (l.year > r.year) return false; else if (l.month < r.month) return true; else if (l.month > r.month) return false; else if (l.day < r.day) return true; return false; } bool Check(int year, int month, int day, Date *result) { if (!CheckMonth(month)) return false; const auto y = ConvertYear(year); if (!CheckDay(day, month, y)) return false; result->year = y; result->month = month; result->day = day; return true; } int main() { std::vector<Date> results; int a, b, c; std::scanf("%d/%d/%d", &a, &b, &c); Date temp; if (Check(a, b, c, &temp)) { results.push_back(temp); } if (Check(c, a, b, &temp)) { results.push_back(temp); } if (Check(c, b, a, &temp)) { results.push_back(temp); } results.erase(std::unique(results.begin(), results.end()), results.end()); std::sort(results.begin(), results.end()); for (const auto &r : results) { std::printf("%d-%02d-%02d\n", r.year, r.month, r.day); } return 0; }
18.17757
76
0.56401
crupest
ad4d51bdc877c068b8abe47c0a95ed2d7697aa3d
401
cpp
C++
components/xtl/tests/xtl/utils/sprintf.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/xtl/tests/xtl/utils/sprintf.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/xtl/tests/xtl/utils/sprintf.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include <stdio.h> #include <xtl/string.h> using namespace xtl; int main () { printf ("Results of sprintf_test:\n"); char char_buffer [9]; char_buffer [8] = 'A'; printf ("result='%s', len=%d\n", char_buffer, xsnprintf (char_buffer, 8, "Hello %s","world")); printf ("control: '%c'\n", char_buffer [8]); printf ("len=%d\n", xsnprintf (0, 0, "Hello %s", "world")); return 0; }
19.095238
96
0.59601
untgames
ad4f06230200f81f285126c1848aa00b63ec353d
1,124
cpp
C++
llarp/path/ihophandler.cpp
da4089/llarp
e223f5d023b1794638b9e9b47a86ed03c8c25306
[ "Zlib" ]
28
2018-01-25T17:39:25.000Z
2022-03-26T15:23:12.000Z
llarp/path/ihophandler.cpp
da4089/llarp
e223f5d023b1794638b9e9b47a86ed03c8c25306
[ "Zlib" ]
1
2021-05-05T12:20:41.000Z
2021-05-05T13:21:38.000Z
llarp/path/ihophandler.cpp
da4089/llarp
e223f5d023b1794638b9e9b47a86ed03c8c25306
[ "Zlib" ]
7
2018-05-21T12:34:50.000Z
2021-05-05T11:57:50.000Z
#include <path/ihophandler.hpp> namespace llarp { namespace path { // handle data in upstream direction bool IHopHandler::HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter*) { if(m_UpstreamQueue == nullptr) m_UpstreamQueue = std::make_shared< TrafficQueue_t >(); m_UpstreamQueue->emplace_back(); auto& pkt = m_UpstreamQueue->back(); pkt.first.resize(X.sz); std::copy_n(X.base, X.sz, pkt.first.begin()); pkt.second = Y; return true; } // handle data in downstream direction bool IHopHandler::HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter*) { if(m_DownstreamQueue == nullptr) m_DownstreamQueue = std::make_shared< TrafficQueue_t >(); m_DownstreamQueue->emplace_back(); auto& pkt = m_DownstreamQueue->back(); pkt.first.resize(X.sz); std::copy_n(X.base, X.sz, pkt.first.begin()); pkt.second = Y; return true; } } // namespace path } // namespace llarp
29.578947
80
0.607651
da4089
ad4f1244ee9f9444f461a2951d54f5b78e6d7cca
7,887
cpp
C++
src/third_party/skia/tests/DataRefTest.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
6,304
2015-01-05T23:45:12.000Z
2022-03-31T09:48:13.000Z
src/third_party/skia/tests/DataRefTest.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
67
2016-04-18T13:30:02.000Z
2022-03-31T23:06:55.000Z
src/third_party/skia/tests/DataRefTest.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
1,231
2015-01-05T03:17:39.000Z
2022-03-31T22:54:58.000Z
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkData.h" #include "include/core/SkDataTable.h" #include "include/core/SkRefCnt.h" #include "include/core/SkStream.h" #include "include/core/SkString.h" #include "include/core/SkTypes.h" #include "include/private/SkTArray.h" #include "include/private/SkTemplates.h" #include "src/core/SkOSFile.h" #include "src/core/SkTaskGroup.h" #include "src/utils/SkOSPath.h" #include "tests/Test.h" #include <cstdio> #include <cstring> #include <memory> static void test_is_equal(skiatest::Reporter* reporter, const SkDataTable* a, const SkDataTable* b) { REPORTER_ASSERT(reporter, a->count() == b->count()); for (int i = 0; i < a->count(); ++i) { size_t sizea, sizeb; const void* mema = a->at(i, &sizea); const void* memb = b->at(i, &sizeb); REPORTER_ASSERT(reporter, sizea == sizeb); REPORTER_ASSERT(reporter, !memcmp(mema, memb, sizea)); } } static void test_datatable_is_empty(skiatest::Reporter* reporter, SkDataTable* table) { REPORTER_ASSERT(reporter, table->isEmpty()); REPORTER_ASSERT(reporter, 0 == table->count()); } static void test_emptytable(skiatest::Reporter* reporter) { sk_sp<SkDataTable> table0(SkDataTable::MakeEmpty()); sk_sp<SkDataTable> table1(SkDataTable::MakeCopyArrays(nullptr, nullptr, 0)); sk_sp<SkDataTable> table2(SkDataTable::MakeCopyArray(nullptr, 0, 0)); sk_sp<SkDataTable> table3(SkDataTable::MakeArrayProc(nullptr, 0, 0, nullptr, nullptr)); test_datatable_is_empty(reporter, table0.get()); test_datatable_is_empty(reporter, table1.get()); test_datatable_is_empty(reporter, table2.get()); test_datatable_is_empty(reporter, table3.get()); test_is_equal(reporter, table0.get(), table1.get()); test_is_equal(reporter, table0.get(), table2.get()); test_is_equal(reporter, table0.get(), table3.get()); } static void test_simpletable(skiatest::Reporter* reporter) { const int idata[] = { 1, 4, 9, 16, 25, 63 }; int icount = SK_ARRAY_COUNT(idata); sk_sp<SkDataTable> itable(SkDataTable::MakeCopyArray(idata, sizeof(idata[0]), icount)); REPORTER_ASSERT(reporter, itable->count() == icount); for (int i = 0; i < icount; ++i) { size_t size; REPORTER_ASSERT(reporter, sizeof(int) == itable->atSize(i)); REPORTER_ASSERT(reporter, *itable->atT<int>(i, &size) == idata[i]); REPORTER_ASSERT(reporter, sizeof(int) == size); } } static void test_vartable(skiatest::Reporter* reporter) { const char* str[] = { "", "a", "be", "see", "deigh", "ef", "ggggggggggggggggggggggggggg" }; int count = SK_ARRAY_COUNT(str); size_t sizes[SK_ARRAY_COUNT(str)]; for (int i = 0; i < count; ++i) { sizes[i] = strlen(str[i]) + 1; } sk_sp<SkDataTable> table(SkDataTable::MakeCopyArrays((const void*const*)str, sizes, count)); REPORTER_ASSERT(reporter, table->count() == count); for (int i = 0; i < count; ++i) { size_t size; REPORTER_ASSERT(reporter, table->atSize(i) == sizes[i]); REPORTER_ASSERT(reporter, !strcmp(table->atT<const char>(i, &size), str[i])); REPORTER_ASSERT(reporter, size == sizes[i]); const char* s = table->atStr(i); REPORTER_ASSERT(reporter, strlen(s) == strlen(str[i])); } } static void test_globaltable(skiatest::Reporter* reporter) { static const int gData[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; int count = SK_ARRAY_COUNT(gData); sk_sp<SkDataTable> table( SkDataTable::MakeArrayProc(gData, sizeof(gData[0]), count, nullptr, nullptr)); REPORTER_ASSERT(reporter, table->count() == count); for (int i = 0; i < count; ++i) { size_t size; REPORTER_ASSERT(reporter, table->atSize(i) == sizeof(int)); REPORTER_ASSERT(reporter, *table->atT<const char>(i, &size) == i); REPORTER_ASSERT(reporter, sizeof(int) == size); } } DEF_TEST(DataTable, reporter) { test_emptytable(reporter); test_simpletable(reporter); test_vartable(reporter); test_globaltable(reporter); } static void* gGlobal; static void delete_int_proc(const void* ptr, void* context) { int* data = (int*)ptr; SkASSERT(context == gGlobal); delete[] data; } static void assert_len(skiatest::Reporter* reporter, const sk_sp<SkData>& ref, size_t len) { REPORTER_ASSERT(reporter, ref->size() == len); } static void assert_data(skiatest::Reporter* reporter, const sk_sp<SkData>& ref, const void* data, size_t len) { REPORTER_ASSERT(reporter, ref->size() == len); REPORTER_ASSERT(reporter, !memcmp(ref->data(), data, len)); } static void test_cstring(skiatest::Reporter* reporter) { const char str[] = "Hello world"; size_t len = strlen(str); sk_sp<SkData> r0(SkData::MakeWithCopy(str, len + 1)); sk_sp<SkData> r1(SkData::MakeWithCString(str)); REPORTER_ASSERT(reporter, r0->equals(r1.get())); sk_sp<SkData> r2(SkData::MakeWithCString(nullptr)); REPORTER_ASSERT(reporter, 1 == r2->size()); REPORTER_ASSERT(reporter, 0 == *r2->bytes()); } static void test_files(skiatest::Reporter* reporter) { SkString tmpDir = skiatest::GetTmpDir(); if (tmpDir.isEmpty()) { return; } SkString path = SkOSPath::Join(tmpDir.c_str(), "data_test"); const char s[] = "abcdefghijklmnopqrstuvwxyz"; { SkFILEWStream writer(path.c_str()); if (!writer.isValid()) { ERRORF(reporter, "Failed to create tmp file %s\n", path.c_str()); return; } writer.write(s, 26); } FILE* file = sk_fopen(path.c_str(), kRead_SkFILE_Flag); sk_sp<SkData> r1(SkData::MakeFromFILE(file)); REPORTER_ASSERT(reporter, r1.get() != nullptr); REPORTER_ASSERT(reporter, r1->size() == 26); REPORTER_ASSERT(reporter, strncmp(static_cast<const char*>(r1->data()), s, 26) == 0); int fd = sk_fileno(file); sk_sp<SkData> r2(SkData::MakeFromFD(fd)); REPORTER_ASSERT(reporter, r2.get() != nullptr); REPORTER_ASSERT(reporter, r2->size() == 26); REPORTER_ASSERT(reporter, strncmp(static_cast<const char*>(r2->data()), s, 26) == 0); } DEF_TEST(Data, reporter) { const char* str = "We the people, in order to form a more perfect union."; const int N = 10; sk_sp<SkData> r0(SkData::MakeEmpty()); sk_sp<SkData> r1(SkData::MakeWithCopy(str, strlen(str))); sk_sp<SkData> r2(SkData::MakeWithProc(new int[N], N*sizeof(int), delete_int_proc, gGlobal)); sk_sp<SkData> r3(SkData::MakeSubset(r1.get(), 7, 6)); assert_len(reporter, r0, 0); assert_len(reporter, r1, strlen(str)); assert_len(reporter, r2, N * sizeof(int)); assert_len(reporter, r3, 6); assert_data(reporter, r1, str, strlen(str)); assert_data(reporter, r3, "people", 6); sk_sp<SkData> tmp(SkData::MakeSubset(r1.get(), strlen(str), 10)); assert_len(reporter, tmp, 0); tmp = SkData::MakeSubset(r1.get(), 0, 0); assert_len(reporter, tmp, 0); test_cstring(reporter); test_files(reporter); } DEF_TEST(Data_empty, reporter) { sk_sp<SkData> array[] = { SkData::MakeEmpty(), SkData::MakeUninitialized(0), SkData::MakeFromMalloc(sk_malloc_throw(0), 0), SkData::MakeWithCopy("", 0), SkData::MakeWithProc(nullptr, 0, [](const void*, void*){}, nullptr), SkData::MakeWithoutCopy(nullptr, 0), }; constexpr int N = SK_ARRAY_COUNT(array); for (int i = 0; i < N; ++i) { REPORTER_ASSERT(reporter, array[i]->size() == 0); for (int j = 0; j < N; ++j) { REPORTER_ASSERT(reporter, array[i]->equals(array[j].get())); } } }
34.592105
96
0.640801
rhencke
ad51652b42155e2d682c2a5f2b97729194d11156
291
cpp
C++
algorithm_cpp/basic/get_line.cpp
eunjin115/TIL
2c9179e4dabdf5d8876871987de8b705c011b672
[ "MIT" ]
null
null
null
algorithm_cpp/basic/get_line.cpp
eunjin115/TIL
2c9179e4dabdf5d8876871987de8b705c011b672
[ "MIT" ]
null
null
null
algorithm_cpp/basic/get_line.cpp
eunjin115/TIL
2c9179e4dabdf5d8876871987de8b705c011b672
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(void){ char arr[10]; cout << "문자 입력"; cin.getline(arr,10, ' '); // 10은 최대 입력 가능 문자수, default 종결 문자는 \n (개행문자) // cin.getline(arr,10,' '); // [예] 세 번째 인자는 종결 문자 설정 -> 공백(' ') cout << arr << endl; return 0; }
22.384615
75
0.522337
eunjin115
ad51ad55a69883bc105c21095ef684ebc96c5c35
633
cpp
C++
EVENTS/UI/SiteConfig.cpp
claudioperez/R2DTool
7afa6bac42fe40a378878bda2efff423ac242e68
[ "BSD-2-Clause" ]
null
null
null
EVENTS/UI/SiteConfig.cpp
claudioperez/R2DTool
7afa6bac42fe40a378878bda2efff423ac242e68
[ "BSD-2-Clause" ]
null
null
null
EVENTS/UI/SiteConfig.cpp
claudioperez/R2DTool
7afa6bac42fe40a378878bda2efff423ac242e68
[ "BSD-2-Clause" ]
null
null
null
#include "SiteConfig.h" SiteConfig::SiteConfig(QObject *parent) : QObject(parent) { m_type = SiteType::Grid; m_site.location().set(0.0, 0.0); } Site &SiteConfig::site() { return m_site; } SiteGrid &SiteConfig::siteGrid() { return m_siteGrid; } SiteConfig::SiteType SiteConfig::getType() const { return m_type; } void SiteConfig::setType(const SiteType &type) { if(m_type != type) { m_type = type; emit typeChanged(m_type); } } QJsonObject SiteConfig::getJson() { if(m_type == SiteType::Single) return m_site.getJson(); else return m_siteGrid.getJson(); }
15.825
57
0.638231
claudioperez
ad51e5ab2ec0c7ecd6be302e3cc13731df5d6bce
4,387
hpp
C++
include/sprout/darkroom/intersects/intersection.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
4
2021-12-29T22:17:40.000Z
2022-03-23T11:53:44.000Z
dsp/lib/sprout/sprout/darkroom/intersects/intersection.hpp
TheSlowGrowth/TapeLooper
ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264
[ "MIT" ]
16
2021-10-31T21:41:09.000Z
2022-01-22T10:51:34.000Z
include/sprout/darkroom/intersects/intersection.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_DARKROOM_INTERSECTS_INTERSECTION_HPP #define SPROUT_DARKROOM_INTERSECTS_INTERSECTION_HPP #include <type_traits> #include <sprout/config.hpp> #include <sprout/tuple/tuple.hpp> #include <sprout/utility/forward.hpp> #include <sprout/type_traits/enabler_if.hpp> #include <sprout/darkroom/access/access.hpp> #include <sprout/darkroom/coords/vector.hpp> #include <sprout/darkroom/materials/material.hpp> namespace sprout { namespace darkroom { namespace intersects { // // intersection // typedef sprout::tuples::tuple< bool, double, sprout::darkroom::coords::vector3d_t, sprout::darkroom::coords::vector3d_t, sprout::darkroom::materials::material, bool > intersection; // // has_is_from_inside // template<typename T> struct has_is_from_inside : public sprout::bool_constant<(sprout::darkroom::access::size<T>::value >= 6)> {}; // // does_intersect // distance // point_of_intersection // normal // material // is_from_inside // template<typename T> inline SPROUT_CONSTEXPR auto does_intersect(T&& t) SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<0>(SPROUT_FORWARD(T, t))) -> decltype(sprout::darkroom::access::get<0>(SPROUT_FORWARD(T, t))) { return sprout::darkroom::access::get<0>(SPROUT_FORWARD(T, t)); } template<typename T> inline SPROUT_CONSTEXPR auto distance(T&& t) SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<1>(SPROUT_FORWARD(T, t))) -> decltype(sprout::darkroom::access::get<1>(SPROUT_FORWARD(T, t))) { return sprout::darkroom::access::get<1>(SPROUT_FORWARD(T, t)); } template<typename T> inline SPROUT_CONSTEXPR auto point_of_intersection(T&& t) SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<2>(SPROUT_FORWARD(T, t))) -> decltype(sprout::darkroom::access::get<2>(SPROUT_FORWARD(T, t))) { return sprout::darkroom::access::get<2>(SPROUT_FORWARD(T, t)); } template<typename T> inline SPROUT_CONSTEXPR auto normal(T&& t) SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<3>(SPROUT_FORWARD(T, t))) -> decltype(sprout::darkroom::access::get<3>(SPROUT_FORWARD(T, t))) { return sprout::darkroom::access::get<3>(SPROUT_FORWARD(T, t)); } template<typename T> inline SPROUT_CONSTEXPR auto material(T&& t) SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<4>(SPROUT_FORWARD(T, t))) -> decltype(sprout::darkroom::access::get<4>(SPROUT_FORWARD(T, t))) { return sprout::darkroom::access::get<4>(SPROUT_FORWARD(T, t)); } template< typename T, typename sprout::enabler_if<sprout::darkroom::intersects::has_is_from_inside<typename std::decay<T>::type>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR auto is_from_inside(T&& t) SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<5>(SPROUT_FORWARD(T, t))) -> decltype(sprout::darkroom::access::get<5>(SPROUT_FORWARD(T, t))) { return sprout::darkroom::access::get<5>(SPROUT_FORWARD(T, t)); } template< typename T, typename sprout::enabler_if<!sprout::darkroom::intersects::has_is_from_inside<typename std::decay<T>::type>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR typename sprout::darkroom::access::element<5, sprout::darkroom::intersects::intersection>::type is_from_inside(T&&) SPROUT_NOEXCEPT_IF_EXPR((typename sprout::darkroom::access::element<5, sprout::darkroom::intersects::intersection>::type())) { return typename sprout::darkroom::access::element<5, sprout::darkroom::intersects::intersection>::type(); } // // make_intersection // template<typename... Elements> inline SPROUT_CONSTEXPR sprout::tuples::tuple<Elements...> make_intersection(Elements const&... elems) { return sprout::tuples::make_tuple(elems...); } } // namespace intersects } // namespace darkroom } // namespace sprout #endif // #ifndef SPROUT_DARKROOM_INTERSECTS_INTERSECTION_HPP
34.81746
143
0.681787
thinkoid
ad53b323f2df0022f44b976a29c07a49db8ce267
233
cpp
C++
Examples/mp_subsystem/mp_subsystem.cpp
drbenmorgan/MicroPipeline
01a59f6ac79431f39917f58bf5a0ed297bf6b32d
[ "BSD-3-Clause" ]
null
null
null
Examples/mp_subsystem/mp_subsystem.cpp
drbenmorgan/MicroPipeline
01a59f6ac79431f39917f58bf5a0ed297bf6b32d
[ "BSD-3-Clause" ]
null
null
null
Examples/mp_subsystem/mp_subsystem.cpp
drbenmorgan/MicroPipeline
01a59f6ac79431f39917f58bf5a0ed297bf6b32d
[ "BSD-3-Clause" ]
null
null
null
// mp_subsystem - test of Poco's application/subsystem // // Copyright (c) 2013 by Ben Morgan <bmorgan.warwick@gmail.com> // Copyright (c) 2013 by The University of Warwick #include "MPSApplication.h" POCO_APP_MAIN(MPSApplication)
29.125
64
0.759657
drbenmorgan
ad569ed3e7dcd557c7fb5d3e4feff9445d941e8f
2,906
hpp
C++
src/px4/mavlink/common/mavlink_msg_param_ack_transaction.hpp
mfkiwl/GLMocap
72de3cc11256d0d8567e86b8a2487ffc81fc984e
[ "MIT" ]
10
2021-03-15T03:58:06.000Z
2021-12-30T15:33:38.000Z
src/px4/mavlink/common/mavlink_msg_param_ack_transaction.hpp
mfkiwl/GLMocap
72de3cc11256d0d8567e86b8a2487ffc81fc984e
[ "MIT" ]
1
2021-07-08T10:26:06.000Z
2021-07-08T10:31:11.000Z
src/px4/mavlink/common/mavlink_msg_param_ack_transaction.hpp
mfkiwl/GLMocap
72de3cc11256d0d8567e86b8a2487ffc81fc984e
[ "MIT" ]
8
2021-10-09T08:47:53.000Z
2022-01-17T07:45:33.000Z
// MESSAGE PARAM_ACK_TRANSACTION support class #pragma once namespace mavlink { namespace common { namespace msg { /** * @brief PARAM_ACK_TRANSACTION message * * Response from a PARAM_SET message when it is used in a transaction. */ struct PARAM_ACK_TRANSACTION : mavlink::Message { static constexpr msgid_t MSG_ID = 19; static constexpr size_t LENGTH = 24; static constexpr size_t MIN_LENGTH = 24; static constexpr uint8_t CRC_EXTRA = 137; static constexpr auto NAME = "PARAM_ACK_TRANSACTION"; uint8_t target_system; /*< Id of system that sent PARAM_SET message. */ uint8_t target_component; /*< Id of system that sent PARAM_SET message. */ std::array<char, 16> param_id; /*< Parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string */ float param_value; /*< Parameter value (new value if PARAM_ACCEPTED, current value otherwise) */ uint8_t param_type; /*< Parameter type. */ uint8_t param_result; /*< Result code. */ inline std::string get_name(void) const override { return NAME; } inline Info get_message_info(void) const override { return { MSG_ID, LENGTH, MIN_LENGTH, CRC_EXTRA }; } inline std::string to_yaml(void) const override { std::stringstream ss; ss << NAME << ":" << std::endl; ss << " target_system: " << +target_system << std::endl; ss << " target_component: " << +target_component << std::endl; ss << " param_id: \"" << to_string(param_id) << "\"" << std::endl; ss << " param_value: " << param_value << std::endl; ss << " param_type: " << +param_type << std::endl; ss << " param_result: " << +param_result << std::endl; return ss.str(); } inline void serialize(mavlink::MsgMap &map) const override { map.reset(MSG_ID, LENGTH); map << param_value; // offset: 0 map << target_system; // offset: 4 map << target_component; // offset: 5 map << param_id; // offset: 6 map << param_type; // offset: 22 map << param_result; // offset: 23 } inline void deserialize(mavlink::MsgMap &map) override { map >> param_value; // offset: 0 map >> target_system; // offset: 4 map >> target_component; // offset: 5 map >> param_id; // offset: 6 map >> param_type; // offset: 22 map >> param_result; // offset: 23 } }; } // namespace msg } // namespace common } // namespace mavlink
35.876543
281
0.579147
mfkiwl
ad57bfa905c555a89c327f57f1996baca4213954
3,069
hpp
C++
include/CobraModelParser/MatlabV5/ParserImpl.hpp
qacwnfq/CobraModelParser
9e03ff6e9f05e4a971b39a85360494925c72dbeb
[ "MIT" ]
null
null
null
include/CobraModelParser/MatlabV5/ParserImpl.hpp
qacwnfq/CobraModelParser
9e03ff6e9f05e4a971b39a85360494925c72dbeb
[ "MIT" ]
null
null
null
include/CobraModelParser/MatlabV5/ParserImpl.hpp
qacwnfq/CobraModelParser
9e03ff6e9f05e4a971b39a85360494925c72dbeb
[ "MIT" ]
null
null
null
#ifndef COBRAMODELPARSER_MATLABV5_PARSERIMPL_HPP #define COBRAMODELPARSER_MATLABV5_PARSERIMPL_HPP #include <algorithm> #include <fstream> #include <vector> #include <ostream> #include "CobraModelParser/Exceptions.hpp" #include "CobraModelParser/FileLoader.hpp" #include "CobraModelParser/ModelBuilder.hpp" #include "CobraModelParser/Parser.hpp" #include "CobraModelParser/MatlabV5/ArrayFlags.hpp" #include "CobraModelParser/MatlabV5/Header.hpp" #include "ArrayDimensions.hpp" #include "ArrayName.hpp" #include "FieldNameLength.hpp" #include "FieldNames.hpp" #include "Fields.hpp" #include "PolytopeParser.hpp" namespace CobraModelParser { namespace MatlabV5 { class ParserImpl : public Parser { public: Model parseModelFromFile(std::string filename) override { ByteParser byteParser; ByteQueue byteQueue = FileLoader::loadFileContentsAsByteQueue(filename); Header header(byteQueue, byteParser); const std::pair<Eigen::MatrixXd, Eigen::VectorXd> &data = parseBody(byteQueue, byteParser); return ModelBuilder() .setModelOrigin(filename) .setModelDescription(header.getHeaderText()) .setData(data.first, data.second) .build(); } private: std::pair<Eigen::MatrixXd, Eigen::VectorXd> parseBody(ByteQueue &byteQueue, const ByteParser &byteParser) const { TagParser tagParser(byteParser); Tag tag = tagParser.parseTag(byteQueue); if (byteQueue.getRemainingBytes() != tag.getNumberOfBytes()) { throw UnexpectedSizeException(byteQueue.getRemainingBytes(), tag.getNumberOfBytes()); } auto expectedType = DataTypeTable::lookUp(14); if (expectedType != tag.getType()) { throw UnexpectedDataTypeException(expectedType.getSymbol(), tag.getType().getSymbol()); } const ArrayFlags &arrayFlags = ArrayFlags::fromByteQueue(byteQueue, byteParser, tagParser); const ArrayDimensions &arrayDimensions = ArrayDimensions::fromByteQueue(byteQueue, byteParser, tagParser); const ArrayName &name = ArrayName::fromByteQueue(byteQueue, byteParser, tagParser); const FieldNameLength &fieldNameLength = FieldNameLength::fromByteQueue(byteQueue, byteParser); const FieldNames &fieldNames = FieldNames::fromByteQueue(byteQueue, byteParser, tagParser, fieldNameLength); const Fields &fields = Fields::fromByteQueue(byteQueue, byteParser, tagParser, fieldNames); return PolytopeParser::fromFields(fields, byteParser, tagParser); } }; } } #endif //COBRAMODELPARSER_MATLABV5_PARSERIMPL_HPP
40.92
111
0.623004
qacwnfq
ad57c191e0688deba12bf9b3fb676cf283bd46fe
2,024
hpp
C++
Libraries/Physics/Analyzer.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Libraries/Physics/Analyzer.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Physics/Analyzer.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once /// Tracks down which object, if any, was not sent to be checked /// for collision when it should have (assuming at least one broad phase caught /// it). #define OBJECT_TRACKING 1 namespace Zero { namespace Physics { // The result of a single frame struct BroadPhaseFrameData { BroadPhaseFrameData(void); /// Clears out all data for the next frame(sets to 0). void Reset(void); /// Information about the results of the broad phase. uint PossibleCollisionsReturned; uint ActualCollisions; real TimeTaken; }; // The statistics for a single broad phases entire life. struct Statistics { Statistics(void); /// Adds the frame results to the total results. void Update(const BroadPhaseFrameData& result); /// Prints the results out to a file. void PrintResults(void); /// The name of the broad phase String Name; /// The broad phase type, used to help determine what is a more optimal /// broad phase for certain situations. uint mType; /// Collisions data uint PossibleCollisionsReturned; uint ActualCollisions; uint CollisionsMissed; /// Iterations uint Iterations; /// Insertion / Removal. Profile::Record InsertionTime; Profile::Record RemovalTime; /// Time taken to update the broad phase (generally dynamic broad phases). Profile::Record UpdateTime; /// Time taken to test objects / get possible pairs. Profile::Record CollisionTime; /// Time taken for construction. Profile::Record ConstructionTime; /// Time taken for ray casts. Profile::Record RayCastTime; }; class Analyzer { public: Analyzer(void); ~Analyzer(void); typedef Array<Statistics*> StatisticsVec; void AnalyzePerformance(uint type, StatisticsVec& statistics); void AnalyzeDynamic(StatisticsVec& statistics); void AnalyzeStatic(StatisticsVec& statistics); void ReportSpike(const char* type, real ms); real CalculateScore(Statistics& stats); void PrintResults(); }; } // namespace Physics } // namespace Zero
23.534884
79
0.731719
RyanTylerRae
ad5868309d617990cf94e0603699f7c75e01f739
635
hpp
C++
src/jellyfish/Material.hpp
FelipeEd/Jellyfish3D
448ca5462fdab2a28677c7f4d05d2e733267da6f
[ "Apache-2.0" ]
null
null
null
src/jellyfish/Material.hpp
FelipeEd/Jellyfish3D
448ca5462fdab2a28677c7f4d05d2e733267da6f
[ "Apache-2.0" ]
null
null
null
src/jellyfish/Material.hpp
FelipeEd/Jellyfish3D
448ca5462fdab2a28677c7f4d05d2e733267da6f
[ "Apache-2.0" ]
null
null
null
#pragma once extern bool pbr; class Material { private: public: unsigned int m_texAlbedo; // TODO change to textures unsigned int m_texMetallic; unsigned int m_texNormal; unsigned int m_texRoughness; unsigned int m_texAo; // Load Ao Roughness and Metallic on one texture unsigned int m_texARM; glm::vec4 m_color; bool useNormalmap; public: Material(); // Flat color Material(const std::string &textureFile, const std::string &size); ~Material(){}; void deleteTextures(); void setColor(glm::vec4 color) { m_color = color; } void setUniforms(Shader &shader); };
19.242424
70
0.677165
FelipeEd
ad5920935ac5a29a023ee509a94db7e1f3378b70
719
cpp
C++
algorithms_2/BinaryInsertionSort/BinaryInsertionSort.cpp
neutrinobomber/c-stuff
0a98d8d618a8226e7e2a63b262ef8fe3ec43e185
[ "MIT" ]
null
null
null
algorithms_2/BinaryInsertionSort/BinaryInsertionSort.cpp
neutrinobomber/c-stuff
0a98d8d618a8226e7e2a63b262ef8fe3ec43e185
[ "MIT" ]
null
null
null
algorithms_2/BinaryInsertionSort/BinaryInsertionSort.cpp
neutrinobomber/c-stuff
0a98d8d618a8226e7e2a63b262ef8fe3ec43e185
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void BinaryInsertionSort(int arr[], int len) { for (int i = 1; i < len; i++) { int begin = 0; int end = i; int mid = i / 2; do { if (arr[i] > arr[mid]) { begin = mid + 1; } else if (arr[i] < arr[mid]) { end = mid; } else { break; } mid = (begin + end) / 2; } while (begin < end); if (mid < i) { int tmp = arr[i]; for (int j = i - 1; j >= mid; j--) { arr[j + 1] = arr[j]; } arr[mid] = tmp; } } } int main() { const int len = 5; int arr[len] = { 5, 4, 3, 2, 1 }; BinaryInsertionSort(arr, len); for (size_t i = 0; i < len; i++) { cout << arr[i] << " "; } cout << endl; return 0; }
12.614035
44
0.456189
neutrinobomber
ad5b9b85e72ccbcdee2181faec7b1f7565d41fe5
16,081
cc
C++
components/zucchini/algorithm_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/zucchini/algorithm_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/zucchini/algorithm_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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/zucchini/algorithm.h" #include <stddef.h> #include <stdint.h> #include "base/logging.h" #include "testing/gtest/include/gtest/gtest.h" namespace zucchini { namespace { // Casting functions to specify signed 8-bit and 16-bit integer constants. // For example, signed8(0xFF) == int8_t(-1). inline int8_t signed8(uint8_t v) { return *reinterpret_cast<const int8_t*>(&v); } inline int32_t signed16(uint16_t v) { return *reinterpret_cast<const int16_t*>(&v); } } // namespace TEST(AlgorithmTest, RangeIsBounded) { // Basic tests. EXPECT_TRUE(RangeIsBounded<uint8_t>(0U, +0U, 10U)); EXPECT_TRUE(RangeIsBounded<uint8_t>(0U, +10U, 10U)); EXPECT_TRUE(RangeIsBounded<uint8_t>(1U, +9U, 10U)); EXPECT_FALSE(RangeIsBounded<uint8_t>(1U, +10U, 10U)); EXPECT_TRUE(RangeIsBounded<uint8_t>(8U, +1U, 10U)); EXPECT_TRUE(RangeIsBounded<uint8_t>(8U, +2U, 10U)); EXPECT_TRUE(RangeIsBounded<uint8_t>(9U, +0U, 10U)); EXPECT_FALSE(RangeIsBounded<uint8_t>(10U, +0U, 10U)); // ! EXPECT_FALSE(RangeIsBounded<uint8_t>(100U, +0U, 10U)); EXPECT_FALSE(RangeIsBounded<uint8_t>(100U, +1U, 10U)); // Test at boundary of overflow. EXPECT_TRUE(RangeIsBounded<uint8_t>(42U, +137U, 255U)); EXPECT_TRUE(RangeIsBounded<uint8_t>(0U, +255U, 255U)); EXPECT_TRUE(RangeIsBounded<uint8_t>(1U, +254U, 255U)); EXPECT_FALSE(RangeIsBounded<uint8_t>(1U, +255U, 255U)); EXPECT_TRUE(RangeIsBounded<uint8_t>(254U, +0U, 255U)); EXPECT_TRUE(RangeIsBounded<uint8_t>(254U, +1U, 255U)); EXPECT_FALSE(RangeIsBounded<uint8_t>(255U, +0U, 255U)); EXPECT_FALSE(RangeIsBounded<uint8_t>(255U, +3U, 255U)); // Test with uint32_t. EXPECT_TRUE(RangeIsBounded<uint32_t>(0U, +0x1000U, 0x2000U)); EXPECT_TRUE(RangeIsBounded<uint32_t>(0x0FFFU, +0x1000U, 0x2000U)); EXPECT_TRUE(RangeIsBounded<uint32_t>(0x1000U, +0x1000U, 0x2000U)); EXPECT_FALSE(RangeIsBounded<uint32_t>(0x1000U, +0x1001U, 0x2000U)); EXPECT_TRUE(RangeIsBounded<uint32_t>(0x1FFFU, +1U, 0x2000U)); EXPECT_FALSE(RangeIsBounded<uint32_t>(0x2000U, +0U, 0x2000U)); // ! EXPECT_FALSE(RangeIsBounded<uint32_t>(0x3000U, +0U, 0x2000U)); EXPECT_FALSE(RangeIsBounded<uint32_t>(0x3000U, +1U, 0x2000U)); EXPECT_TRUE(RangeIsBounded<uint32_t>(0U, +0xFFFFFFFEU, 0xFFFFFFFFU)); EXPECT_TRUE(RangeIsBounded<uint32_t>(0U, +0xFFFFFFFFU, 0xFFFFFFFFU)); EXPECT_TRUE(RangeIsBounded<uint32_t>(1U, +0xFFFFFFFEU, 0xFFFFFFFFU)); EXPECT_FALSE(RangeIsBounded<uint32_t>(1U, +0xFFFFFFFFU, 0xFFFFFFFFU)); EXPECT_TRUE(RangeIsBounded<uint32_t>(0x80000000U, +0x7FFFFFFFU, 0xFFFFFFFFU)); EXPECT_FALSE( RangeIsBounded<uint32_t>(0x80000000U, +0x80000000U, 0xFFFFFFFFU)); EXPECT_TRUE(RangeIsBounded<uint32_t>(0xFFFFFFFEU, +1U, 0xFFFFFFFFU)); EXPECT_FALSE(RangeIsBounded<uint32_t>(0xFFFFFFFFU, +0U, 0xFFFFFFFFU)); // ! EXPECT_FALSE( RangeIsBounded<uint32_t>(0xFFFFFFFFU, +0xFFFFFFFFU, 0xFFFFFFFFU)); } TEST(AlgorithmTest, RangeCovers) { // Basic tests. EXPECT_TRUE(RangeCovers<uint8_t>(0U, +10U, 0U)); EXPECT_TRUE(RangeCovers<uint8_t>(0U, +10U, 5U)); EXPECT_TRUE(RangeCovers<uint8_t>(0U, +10U, 9U)); EXPECT_FALSE(RangeCovers<uint8_t>(0U, +10U, 10U)); EXPECT_FALSE(RangeCovers<uint8_t>(0U, +10U, 100U)); EXPECT_FALSE(RangeCovers<uint8_t>(0U, +10U, 255U)); EXPECT_FALSE(RangeCovers<uint8_t>(42U, +137U, 0U)); EXPECT_FALSE(RangeCovers<uint8_t>(42U, +137U, 41U)); EXPECT_TRUE(RangeCovers<uint8_t>(42U, +137U, 42U)); EXPECT_TRUE(RangeCovers<uint8_t>(42U, +137U, 100U)); EXPECT_TRUE(RangeCovers<uint8_t>(42U, +137U, 178U)); EXPECT_FALSE(RangeCovers<uint8_t>(42U, +137U, 179U)); EXPECT_FALSE(RangeCovers<uint8_t>(42U, +137U, 255U)); // 0-size ranges. EXPECT_FALSE(RangeCovers<uint8_t>(42U, +0U, 41U)); EXPECT_FALSE(RangeCovers<uint8_t>(42U, +0U, 42U)); EXPECT_FALSE(RangeCovers<uint8_t>(42U, +0U, 43U)); // Test at boundary of overflow. EXPECT_TRUE(RangeCovers<uint8_t>(254U, +1U, 254U)); EXPECT_FALSE(RangeCovers<uint8_t>(254U, +1U, 255U)); EXPECT_FALSE(RangeCovers<uint8_t>(255U, +0U, 255U)); EXPECT_TRUE(RangeCovers<uint8_t>(255U, +1U, 255U)); EXPECT_FALSE(RangeCovers<uint8_t>(255U, +5U, 0U)); // Test with unit32_t. EXPECT_FALSE(RangeCovers<uint32_t>(1234567U, +7654321U, 0U)); EXPECT_FALSE(RangeCovers<uint32_t>(1234567U, +7654321U, 1234566U)); EXPECT_TRUE(RangeCovers<uint32_t>(1234567U, +7654321U, 1234567U)); EXPECT_TRUE(RangeCovers<uint32_t>(1234567U, +7654321U, 4444444U)); EXPECT_TRUE(RangeCovers<uint32_t>(1234567U, +7654321U, 8888887U)); EXPECT_FALSE(RangeCovers<uint32_t>(1234567U, +7654321U, 8888888U)); EXPECT_FALSE(RangeCovers<uint32_t>(1234567U, +7654321U, 0x80000000U)); EXPECT_FALSE(RangeCovers<uint32_t>(1234567U, +7654321U, 0xFFFFFFFFU)); EXPECT_FALSE(RangeCovers<uint32_t>(0xFFFFFFFFU, +0, 0xFFFFFFFFU)); EXPECT_TRUE(RangeCovers<uint32_t>(0xFFFFFFFFU, +1, 0xFFFFFFFFU)); EXPECT_FALSE(RangeCovers<uint32_t>(0xFFFFFFFFU, +2, 0)); } TEST(AlgorithmTest, InclusiveClamp) { EXPECT_EQ(1U, InclusiveClamp<uint32_t>(0U, 1U, 9U)); EXPECT_EQ(1U, InclusiveClamp<uint32_t>(1U, 1U, 9U)); EXPECT_EQ(5U, InclusiveClamp<uint32_t>(5U, 1U, 9U)); EXPECT_EQ(8U, InclusiveClamp<uint32_t>(8U, 1U, 9U)); EXPECT_EQ(9U, InclusiveClamp<uint32_t>(9U, 1U, 9U)); EXPECT_EQ(9U, InclusiveClamp<uint32_t>(10U, 1U, 9U)); EXPECT_EQ(9U, InclusiveClamp<uint32_t>(0xFFFFFFFFU, 1U, 9U)); EXPECT_EQ(42U, InclusiveClamp<uint32_t>(0U, 42U, 42U)); EXPECT_EQ(42U, InclusiveClamp<uint32_t>(41U, 42U, 42U)); EXPECT_EQ(42U, InclusiveClamp<uint32_t>(42U, 42U, 42U)); EXPECT_EQ(42U, InclusiveClamp<uint32_t>(43U, 42U, 42U)); EXPECT_EQ(0U, InclusiveClamp<uint32_t>(0U, 0U, 0U)); EXPECT_EQ(0xFFFFFFFF, InclusiveClamp<uint32_t>(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF)); } TEST(AlgorithmTest, AlignCeil) { EXPECT_EQ(0U, AlignCeil<uint32_t>(0U, 2U)); EXPECT_EQ(2U, AlignCeil<uint32_t>(1U, 2U)); EXPECT_EQ(2U, AlignCeil<uint32_t>(2U, 2U)); EXPECT_EQ(4U, AlignCeil<uint32_t>(3U, 2U)); EXPECT_EQ(4U, AlignCeil<uint32_t>(4U, 2U)); EXPECT_EQ(11U, AlignCeil<uint32_t>(10U, 11U)); EXPECT_EQ(11U, AlignCeil<uint32_t>(11U, 11U)); EXPECT_EQ(22U, AlignCeil<uint32_t>(12U, 11U)); EXPECT_EQ(22U, AlignCeil<uint32_t>(21U, 11U)); EXPECT_EQ(22U, AlignCeil<uint32_t>(22U, 11U)); EXPECT_EQ(33U, AlignCeil<uint32_t>(23U, 11U)); } TEST(AlgorithmTest, IncrementForAlignCeil) { struct TestCase { int exp; // Increment to |pos| to get the next nearest aligned value. int pos; }; TestCase kTestCases2[] = { {0, 0}, {1, 1}, {0, 2}, {1, 3}, {0, 4}, {1, 5}, {1, 97}, {0, 98}, {1, 99}, {0, 100}, {1, -1}, {0, -2}, {1, -101}, {0, -100}, {1, -99}, {0, -98}, {1, -97}, {0, -96}, }; for (const auto& test_case : kTestCases2) { EXPECT_EQ(test_case.exp, IncrementForAlignCeil2<int32_t>(test_case.pos)); if (test_case.pos >= 0) EXPECT_EQ(test_case.exp, IncrementForAlignCeil2<uint32_t>(test_case.pos)); } TestCase kTestCases4[] = { {0, 0}, {3, 1}, {2, 2}, {1, 3}, {0, 4}, {3, 5}, {3, 97}, {2, 98}, {1, 99}, {0, 100}, {1, -1}, {2, -2}, {1, -101}, {0, -100}, {3, -99}, {2, -98}, {1, -97}, {0, -96}, }; for (const auto& test_case : kTestCases4) { EXPECT_EQ(test_case.exp, IncrementForAlignCeil4<int32_t>(test_case.pos)); if (test_case.pos >= 0) EXPECT_EQ(test_case.exp, IncrementForAlignCeil4<uint32_t>(test_case.pos)); } } TEST(AlgorithmTest, GetBit) { // 0xC5 = 0b1100'0101. constexpr uint8_t v = 0xC5; EXPECT_EQ(uint8_t(1), (GetBit<0>(v))); EXPECT_EQ(int8_t(0), (GetBit<1>(signed8(v)))); EXPECT_EQ(uint8_t(1), (GetBit<2>(v))); EXPECT_EQ(int8_t(0), (GetBit<3>(signed8(v)))); EXPECT_EQ(uint8_t(0), (GetBit<4>(v))); EXPECT_EQ(int8_t(0), (GetBit<5>(signed8(v)))); EXPECT_EQ(uint8_t(1), (GetBit<6>(v))); EXPECT_EQ(int8_t(1), (GetBit<7>(signed8(v)))); EXPECT_EQ(int16_t(1), (GetBit<3, int16_t>(0x0008))); EXPECT_EQ(uint16_t(0), (GetBit<14, uint16_t>(0xB000))); EXPECT_EQ(uint16_t(1), (GetBit<15, uint16_t>(0xB000))); EXPECT_EQ(uint32_t(1), (GetBit<0, uint32_t>(0xFFFFFFFF))); EXPECT_EQ(int32_t(1), (GetBit<31, int32_t>(0xFFFFFFFF))); EXPECT_EQ(uint32_t(0), (GetBit<0, uint32_t>(0xFF00A596))); EXPECT_EQ(int32_t(1), (GetBit<1, int32_t>(0xFF00A596))); EXPECT_EQ(uint32_t(1), (GetBit<4, uint32_t>(0xFF00A596))); EXPECT_EQ(int32_t(1), (GetBit<7, int32_t>(0xFF00A596))); EXPECT_EQ(uint32_t(0), (GetBit<9, uint32_t>(0xFF00A596))); EXPECT_EQ(int32_t(0), (GetBit<16, int32_t>(0xFF00A59))); EXPECT_EQ(uint32_t(1), (GetBit<24, uint32_t>(0xFF00A596))); EXPECT_EQ(int32_t(1), (GetBit<31, int32_t>(0xFF00A596))); EXPECT_EQ(uint64_t(0), (GetBit<62, uint64_t>(0xB000000000000000ULL))); EXPECT_EQ(int64_t(1), (GetBit<63, int64_t>(0xB000000000000000LL))); } TEST(AlgorithmTest, GetBits) { // Zero-extended: Basic cases for various values. uint32_t test_cases[] = {0, 1, 2, 7, 137, 0x10000, 0x69969669, 0xFFFFFFFF}; for (uint32_t v : test_cases) { EXPECT_EQ(uint32_t(v & 0xFF), (GetUnsignedBits<0, 7>(v))); EXPECT_EQ(uint32_t((v >> 8) & 0xFF), (GetUnsignedBits<8, 15>(v))); EXPECT_EQ(uint32_t((v >> 16) & 0xFF), (GetUnsignedBits<16, 23>(v))); EXPECT_EQ(uint32_t((v >> 24) & 0xFF), (GetUnsignedBits<24, 31>(v))); EXPECT_EQ(uint32_t(v & 0xFFFF), (GetUnsignedBits<0, 15>(v))); EXPECT_EQ(uint32_t((v >> 1) & 0x3FFFFFFF), (GetUnsignedBits<1, 30>(v))); EXPECT_EQ(uint32_t((v >> 2) & 0x0FFFFFFF), (GetUnsignedBits<2, 29>(v))); EXPECT_EQ(uint32_t(v), (GetUnsignedBits<0, 31>(v))); } // Zero-extended: Reading off various nibbles. EXPECT_EQ(uint32_t(0x4), (GetUnsignedBits<20, 23>(0x00432100U))); EXPECT_EQ(uint32_t(0x43), (GetUnsignedBits<16, 23>(0x00432100))); EXPECT_EQ(uint32_t(0x432), (GetUnsignedBits<12, 23>(0x00432100U))); EXPECT_EQ(uint32_t(0x4321), (GetUnsignedBits<8, 23>(0x00432100))); EXPECT_EQ(uint32_t(0x321), (GetUnsignedBits<8, 19>(0x00432100U))); EXPECT_EQ(uint32_t(0x21), (GetUnsignedBits<8, 15>(0x00432100))); EXPECT_EQ(uint32_t(0x1), (GetUnsignedBits<8, 11>(0x00432100U))); // Sign-extended: 0x3CA5 = 0b0011'1100'1010'0101. EXPECT_EQ(signed16(0xFFFF), (GetSignedBits<0, 0>(0x3CA5U))); EXPECT_EQ(signed16(0x0001), (GetSignedBits<0, 1>(0x3CA5))); EXPECT_EQ(signed16(0xFFFD), (GetSignedBits<0, 2>(0x3CA5U))); EXPECT_EQ(signed16(0x0005), (GetSignedBits<0, 4>(0x3CA5))); EXPECT_EQ(signed16(0xFFA5), (GetSignedBits<0, 7>(0x3CA5U))); EXPECT_EQ(signed16(0xFCA5), (GetSignedBits<0, 11>(0x3CA5))); EXPECT_EQ(signed16(0x0005), (GetSignedBits<0, 3>(0x3CA5U))); EXPECT_EQ(signed16(0xFFFA), (GetSignedBits<4, 7>(0x3CA5))); EXPECT_EQ(signed16(0xFFFC), (GetSignedBits<8, 11>(0x3CA5U))); EXPECT_EQ(signed16(0x0003), (GetSignedBits<12, 15>(0x3CA5))); EXPECT_EQ(signed16(0x0000), (GetSignedBits<4, 4>(0x3CA5U))); EXPECT_EQ(signed16(0xFFFF), (GetSignedBits<5, 5>(0x3CA5))); EXPECT_EQ(signed16(0x0002), (GetSignedBits<4, 6>(0x3CA5U))); EXPECT_EQ(signed16(0x1E52), (GetSignedBits<1, 14>(0x3CA5))); EXPECT_EQ(signed16(0xFF29), (GetSignedBits<2, 13>(0x3CA5U))); EXPECT_EQ(int32_t(0x00001E52), (GetSignedBits<1, 14>(0x3CA5))); EXPECT_EQ(int32_t(0xFFFFFF29), (GetSignedBits<2, 13>(0x3CA5U))); // 64-bits: Extract from middle 0x66 = 0b0110'0110. EXPECT_EQ(uint64_t(0x0000000000000009LL), (GetUnsignedBits<30, 33>(int64_t(0x2222222661111111LL)))); EXPECT_EQ(int64_t(0xFFFFFFFFFFFFFFF9LL), (GetSignedBits<30, 33>(uint64_t(0x2222222661111111LL)))); } TEST(AlgorithmTest, SignExtend) { // 0x6A = 0b0110'1010. EXPECT_EQ(uint8_t(0x00), (SignExtend<uint8_t>(0, 0x6A))); EXPECT_EQ(signed8(0xFE), (SignExtend<int8_t>(1, signed8(0x6A)))); EXPECT_EQ(uint8_t(0x02), (SignExtend<uint8_t>(2, 0x6A))); EXPECT_EQ(signed8(0xFA), (SignExtend<int8_t>(3, signed8(0x6A)))); EXPECT_EQ(uint8_t(0x0A), (SignExtend<uint8_t>(4, 0x6A))); EXPECT_EQ(signed8(0xEA), (SignExtend<int8_t>(5, signed8(0x6A)))); EXPECT_EQ(uint8_t(0xEA), (SignExtend<uint8_t>(6, 0x6A))); EXPECT_EQ(signed8(0x6A), (SignExtend<int8_t>(7, signed8(0x6A)))); EXPECT_EQ(signed16(0xFFFA), (SignExtend<int16_t>(3, 0x6A))); EXPECT_EQ(uint16_t(0x000A), (SignExtend<uint16_t>(4, 0x6A))); EXPECT_EQ(int32_t(0xFFFF8000), (SignExtend<int32_t>(15, 0x00008000))); EXPECT_EQ(uint32_t(0x00008000U), (SignExtend<uint32_t>(16, 0x00008000))); EXPECT_EQ(int32_t(0xFFFFFC00), (SignExtend<int32_t>(10, 0x00000400))); EXPECT_EQ(uint32_t(0xFFFFFFFFU), (SignExtend<uint32_t>(31, 0xFFFFFFFF))); EXPECT_EQ(int64_t(0xFFFFFFFFFFFFFE6ALL), (SignExtend<int64_t>(9, 0x000000000000026ALL))); EXPECT_EQ(int64_t(0x000000000000016ALL), (SignExtend<int64_t>(9, 0xFFFFFFFFFFFFFD6ALL))); EXPECT_EQ(uint64_t(0xFFFFFFFFFFFFFE6AULL), (SignExtend<uint64_t>(9, 0x000000000000026AULL))); EXPECT_EQ(uint64_t(0x000000000000016AULL), (SignExtend<uint64_t>(9, 0xFFFFFFFFFFFFFD6AULL))); } TEST(AlgorithmTest, SignExtendTemplated) { // 0x6A = 0b0110'1010. EXPECT_EQ(uint8_t(0x00), (SignExtend<0, uint8_t>(0x6A))); EXPECT_EQ(signed8(0xFE), (SignExtend<1, int8_t>(signed8(0x6A)))); EXPECT_EQ(uint8_t(0x02), (SignExtend<2, uint8_t>(0x6A))); EXPECT_EQ(signed8(0xFA), (SignExtend<3, int8_t>(signed8(0x6A)))); EXPECT_EQ(uint8_t(0x0A), (SignExtend<4, uint8_t>(0x6A))); EXPECT_EQ(signed8(0xEA), (SignExtend<5, int8_t>(signed8(0x6A)))); EXPECT_EQ(uint8_t(0xEA), (SignExtend<6, uint8_t>(0x6A))); EXPECT_EQ(signed8(0x6A), (SignExtend<7, int8_t>(signed8(0x6A)))); EXPECT_EQ(signed16(0xFFFA), (SignExtend<3, int16_t>(0x6A))); EXPECT_EQ(uint16_t(0x000A), (SignExtend<4, uint16_t>(0x6A))); EXPECT_EQ(int32_t(0xFFFF8000), (SignExtend<15, int32_t>(0x00008000))); EXPECT_EQ(uint32_t(0x00008000U), (SignExtend<16, uint32_t>(0x00008000))); EXPECT_EQ(int32_t(0xFFFFFC00), (SignExtend<10, int32_t>(0x00000400))); EXPECT_EQ(uint32_t(0xFFFFFFFFU), (SignExtend<31, uint32_t>(0xFFFFFFFF))); EXPECT_EQ(int64_t(0xFFFFFFFFFFFFFE6ALL), (SignExtend<9, int64_t>(0x000000000000026ALL))); EXPECT_EQ(int64_t(0x000000000000016ALL), (SignExtend<9, int64_t>(0xFFFFFFFFFFFFFD6ALL))); EXPECT_EQ(uint64_t(0xFFFFFFFFFFFFFE6AULL), (SignExtend<9, uint64_t>(0x000000000000026AULL))); EXPECT_EQ(uint64_t(0x000000000000016AULL), (SignExtend<9, uint64_t>(0xFFFFFFFFFFFFFD6AULL))); } TEST(AlgorithmTest, SignedFit) { for (int v = -0x80; v < 0x80; ++v) { EXPECT_EQ(v >= -1 && v < 1, (SignedFit<1, int8_t>(v))); EXPECT_EQ(v >= -1 && v < 1, (SignedFit<1, uint8_t>(v))); EXPECT_EQ(v >= -2 && v < 2, (SignedFit<2, int8_t>(v))); EXPECT_EQ(v >= -4 && v < 4, (SignedFit<3, uint8_t>(v))); EXPECT_EQ(v >= -8 && v < 8, (SignedFit<4, int16_t>(v))); EXPECT_EQ(v >= -16 && v < 16, (SignedFit<5, uint32_t>(v))); EXPECT_EQ(v >= -32 && v < 32, (SignedFit<6, int32_t>(v))); EXPECT_EQ(v >= -64 && v < 64, (SignedFit<7, uint64_t>(v))); EXPECT_TRUE((SignedFit<8, int8_t>(v))); EXPECT_TRUE((SignedFit<8, uint8_t>(v))); } EXPECT_TRUE((SignedFit<16, uint32_t>(0x00000000))); EXPECT_TRUE((SignedFit<16, uint32_t>(0x00007FFF))); EXPECT_TRUE((SignedFit<16, uint32_t>(0xFFFF8000))); EXPECT_TRUE((SignedFit<16, uint32_t>(0xFFFFFFFF))); EXPECT_TRUE((SignedFit<16, int32_t>(0x00007FFF))); EXPECT_TRUE((SignedFit<16, int32_t>(0xFFFF8000))); EXPECT_FALSE((SignedFit<16, uint32_t>(0x80000000))); EXPECT_FALSE((SignedFit<16, uint32_t>(0x7FFFFFFF))); EXPECT_FALSE((SignedFit<16, uint32_t>(0x00008000))); EXPECT_FALSE((SignedFit<16, uint32_t>(0xFFFF7FFF))); EXPECT_FALSE((SignedFit<16, int32_t>(0x00008000))); EXPECT_FALSE((SignedFit<16, int32_t>(0xFFFF7FFF))); EXPECT_TRUE((SignedFit<48, int64_t>(0x00007FFFFFFFFFFFLL))); EXPECT_TRUE((SignedFit<48, int64_t>(0xFFFF800000000000LL))); EXPECT_FALSE((SignedFit<48, int64_t>(0x0008000000000000LL))); EXPECT_FALSE((SignedFit<48, int64_t>(0xFFFF7FFFFFFFFFFFLL))); } } // namespace zucchini
46.077364
80
0.699646
sarang-apps
ad5fc91f5069b2eaa46e855e02c428883200814d
17,358
cpp
C++
src/libtsduck/dtv/tsSignalizationDemux.cpp
ASTRO-Strobel/tsduck
f1da3d49df35b3d9740fb2c8031c92d0f261829a
[ "BSD-2-Clause" ]
2
2020-02-27T04:34:41.000Z
2020-04-29T10:43:23.000Z
src/libtsduck/dtv/tsSignalizationDemux.cpp
mirakc/tsduck-arib
c400025b7d31e26c0c15471e81adf2ad50632281
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/dtv/tsSignalizationDemux.cpp
mirakc/tsduck-arib
c400025b7d31e26c0c15471e81adf2ad50632281
[ "BSD-2-Clause" ]
1
2019-10-27T03:19:28.000Z
2019-10-27T03:19:28.000Z
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2020, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- #include "tsSignalizationDemux.h" TSDUCK_SOURCE; //---------------------------------------------------------------------------- // Constructors and destructors. //---------------------------------------------------------------------------- ts::SignalizationDemux::SignalizationDemux(DuckContext& duck, SignalizationHandlerInterface* handler, std::initializer_list<TID> tids) : _duck(duck), _demux(duck, this, this), _handler(handler), _tids(), _service_ids(), _last_pat(), _last_pat_handled(false) { _last_pat.invalidate(); for (auto it = tids.begin(); it != tids.end(); ++it) { addTableId(*it); } } //---------------------------------------------------------------------------- // Get the NIT PID, either from last PAT or default PID. //---------------------------------------------------------------------------- ts::PID ts::SignalizationDemux::nitPID() const { return _last_pat.isValid() && _last_pat.nit_pid != PID_NULL ? _last_pat.nit_pid : PID(PID_NIT); } //---------------------------------------------------------------------------- // Reset the demux. //---------------------------------------------------------------------------- void ts::SignalizationDemux::reset() { _demux.reset(); _demux.setPIDFilter(NoPID); _tids.clear(); _service_ids.clear(); _last_pat.invalidate(); _last_pat_handled = false; } //---------------------------------------------------------------------------- // Add a signalization table id to filter. //---------------------------------------------------------------------------- bool ts::SignalizationDemux::addTableId(TID tid) { // Do not repeat already filtered table ids. if (hasTableId(tid)) { return true; } // Configure the demux according to the table id. switch (tid) { case TID_PAT: { _demux.addPID(PID_PAT); // The current PAT may have already been received without notification to the application. if (_last_pat.isValid() && _handler != nullptr && !_last_pat_handled) { _last_pat_handled = true; _handler->handlePAT(_last_pat, PID_PAT); } break; } case TID_CAT: { _demux.addPID(PID_CAT); break; } case TID_PMT: { // We need the PAT to get PMT PID's. _demux.addPID(PID_PAT); // If a PAT is known, add all PMT PID's. if (_last_pat.isValid()) { for (auto it = _last_pat.pmts.begin(); it != _last_pat.pmts.end(); ++it) { _demux.addPID(it->second); } } break; } case TID_TSDT: { _demux.addPID(PID_TSDT); break; } case TID_NIT_ACT: case TID_NIT_OTH: { // We need the PAT to get the NIT PID. _demux.addPID(PID_PAT); _demux.addPID(nitPID()); break; } case TID_SDT_ACT: case TID_SDT_OTH: case TID_BAT: { // SDT and BAT share the same PID. _demux.addPID(PID_SDT); break; } case TID_RST: { _demux.addPID(PID_RST); break; } case TID_TDT: case TID_TOT: { // TDT and TOT share the same PID. _demux.addPID(PID_TDT); break; } case TID_MGT: case TID_CVCT: case TID_TVCT: case TID_RRT: case TID_STT: { // With ATSC, the PSIP base PID contains almost all tables. _demux.addPID(PID_PSIP); break; } default: { // Unsupported table id. return false; } } // Add the table id. _tids.insert(tid); return true; } //---------------------------------------------------------------------------- // Remove a signalization table id to filter. //---------------------------------------------------------------------------- bool ts::SignalizationDemux::removeTableId(TID tid) { // Do nothing if the table id was not filtered. if (!hasTableId(tid)) { return false; } // Remove the table id first. _tids.erase(tid); // Configure the demux according to the table id. switch (tid) { case TID_PAT: { // Stop monitoring the PAT only when there is no need to get PMT's or NIT. if (!hasTableId(TID_PMT) && _service_ids.empty() && !hasTableId(TID_NIT_ACT) && !hasTableId(TID_NIT_OTH)) { _demux.removePID(PID_PAT); } break; } case TID_CAT: { _demux.removePID(PID_CAT); break; } case TID_PMT: { // If a PAT is known, remove all PMT PID's which are not specifically monitored by service id. if (_last_pat.isValid()) { for (auto it = _last_pat.pmts.begin(); it != _last_pat.pmts.end(); ++it) { if (!hasServiceId(it->first)) { _demux.removePID(it->second); } } } break; } case TID_TSDT: { _demux.removePID(PID_TSDT); break; } case TID_NIT_ACT: case TID_NIT_OTH: { // Remove the PID only if no type of NIT is monitored. if (!hasTableId(TID_NIT_ACT) && !hasTableId(TID_NIT_OTH)) { _demux.removePID(nitPID()); } break; } case TID_SDT_ACT: case TID_SDT_OTH: case TID_BAT: { // SDT and BAT share the same PID. Remove the PID only if none is monitored. if (!hasTableId(TID_SDT_ACT) && !hasTableId(TID_SDT_OTH) && !hasTableId(TID_BAT)) { _demux.removePID(PID_SDT); } break; } case TID_RST: { _demux.removePID(PID_RST); break; } case TID_TDT: case TID_TOT: { // TDT and TOT share the same PID. Remove the PID only if none is monitored. if (!hasTableId(TID_TDT) && !hasTableId(TID_TOT)) { _demux.removePID(PID_TDT); } break; } case TID_MGT: case TID_CVCT: case TID_TVCT: case TID_RRT: case TID_STT: { // With ATSC, the PSIP base PID contains almost all tables. if (!hasTableId(TID_MGT) && !hasTableId(TID_CVCT) && !hasTableId(TID_TVCT) && !hasTableId(TID_RRT) && !hasTableId(TID_STT)) { _demux.removePID(PID_PSIP); } break; } default: { // Unsupported table id. return false; } } // Table id successfully removed. return true; } //---------------------------------------------------------------------------- // Add a service id to filter its PMT. //---------------------------------------------------------------------------- void ts::SignalizationDemux::addServiceId(uint16_t sid) { // Do something only when the service is not yet monitored. if (!hasServiceId(sid)) { // Remember the service id to monitor. _service_ids.insert(sid); // We need the PAT to get PMT PID's. _demux.addPID(PID_PAT); // If a PAT is known and references the service, add its PMT PID. if (_last_pat.isValid()) { const auto it(_last_pat.pmts.find(sid)); if (it != _last_pat.pmts.end()) { _demux.addPID(it->second); } } } } //---------------------------------------------------------------------------- // Remove a service id to filter its PMT. //---------------------------------------------------------------------------- void ts::SignalizationDemux::removeServiceId(uint16_t sid) { // Do something only when the service is currently monitored. if (hasServiceId(sid)) { // Forget the service id to monitor. _service_ids.erase(sid); // If a PAT is known and references the service, remove its PMT PID. // If all PMT's are still monitored, don't change anything. if (_last_pat.isValid() && !hasTableId(TID_PMT)) { const auto it(_last_pat.pmts.find(sid)); if (it != _last_pat.pmts.end()) { _demux.removePID(it->second); } } } } //---------------------------------------------------------------------------- // Remove all service ids to filter PMT's. //---------------------------------------------------------------------------- void ts::SignalizationDemux::removeAllServiceIds() { // If a PAT is known, remove all PMT PID's. // If all PMT's are still monitored, don't change anything. if (_last_pat.isValid() && !hasTableId(TID_PMT)) { for (auto it = _last_pat.pmts.begin(); it != _last_pat.pmts.end(); ++it) { _demux.removePID(it->second); } } // Forget all service ids. _service_ids.clear(); } //---------------------------------------------------------------------------- // Invoked by SectionDemux when a complete table is received. //---------------------------------------------------------------------------- void ts::SignalizationDemux::handleTable(SectionDemux&, const BinaryTable& table) { const PID pid = table.sourcePID(); const TID tid = table.tableId(); // The PAT needs to be monitored outside explicit filtering. if (tid == TID_PAT && pid == PID_PAT) { const PAT pat(_duck, table); if (pat.isValid()) { // Check if all PMT's are monitored. const bool all_pmts = hasTableId(TID_PMT); // If a previous PAT was there, remove unused PMT PID's. if (_last_pat.isValid() && (all_pmts || !_service_ids.empty())) { // Loop on all previous services for (auto it1 = _last_pat.pmts.begin(); it1 != _last_pat.pmts.end(); ++it1) { // If the service no longer exists or has changed its PMT PID, remove the previous PMT PID. const auto it2(pat.pmts.find(it1->first)); if (it2 == pat.pmts.end() || it2->second != it1->second) { _demux.removePID(it1->second); } } } // Remember the last PAT. _last_pat = pat; _last_pat_handled = false; // Then, monitor new PMT PID's. Some of them may be already monitored. for (auto it = pat.pmts.begin(); it != pat.pmts.end(); ++it) { if (all_pmts || hasServiceId(it->first)) { _demux.addPID(it->second); } } // Monitor non-standard NIT PID. if (hasTableId(TID_NIT_ACT) || hasTableId(TID_NIT_OTH)) { _demux.addPID(nitPID()); } // Notify the PAT to the application. if (_handler != nullptr && hasTableId(TID_PAT)) { _last_pat_handled = true; _handler->handlePAT(pat, pid); } } } // Other tables have no special treatment. They are directly passed to the application. // PMT may be selectively filtered by service id (table id extention). else if (_handler != nullptr && (hasTableId(tid) || (tid == TID_PMT && hasServiceId(table.tableIdExtension())))) { switch (tid) { case TID_CAT: { const CAT cat(_duck, table); if (cat.isValid() && pid == PID_CAT) { _handler->handleCAT(cat, pid); } break; } case TID_PMT: { const PMT pmt(_duck, table); if (pmt.isValid()) { _handler->handlePMT(pmt, pid); } break; } case TID_TSDT: { const TSDT tsdt(_duck, table); if (tsdt.isValid() && pid == PID_TSDT) { _handler->handleTSDT(tsdt, pid); } break; } case TID_NIT_ACT: case TID_NIT_OTH: { const NIT nit(_duck, table); if (nit.isValid() && pid == nitPID()) { _handler->handleNIT(nit, pid); } break; } case TID_SDT_ACT: case TID_SDT_OTH: { const SDT sdt(_duck, table); if (sdt.isValid() && pid == PID_SDT) { _handler->handleSDT(sdt, pid); } break; } case TID_BAT: { const BAT bat(_duck, table); if (bat.isValid() && pid == PID_BAT) { _handler->handleBAT(bat, pid); } break; } case TID_RST: { const RST rst(_duck, table); if (rst.isValid() && pid == PID_RST) { _handler->handleRST(rst, pid); } break; } case TID_TDT: { const TDT tdt(_duck, table); if (tdt.isValid() && pid == PID_TDT) { _handler->handleTDT(tdt, pid); } break; } case TID_TOT: { const TOT tot(_duck, table); if (tot.isValid() && pid == PID_TOT) { _handler->handleTOT(tot, pid); } break; } case TID_MGT: { const MGT mgt(_duck, table); if (mgt.isValid() && pid == PID_PSIP) { _handler->handleMGT(mgt, pid); } break; } case TID_CVCT: { const CVCT vct(_duck, table); if (vct.isValid() && pid == PID_PSIP) { // Call specific and generic form of VCT handler. _handler->handleCVCT(vct, pid); _handler->handleVCT(vct, pid); } break; } case TID_TVCT: { const TVCT vct(_duck, table); if (vct.isValid() && pid == PID_PSIP) { // Call specific and generic form of VCT handler. _handler->handleTVCT(vct, pid); _handler->handleVCT(vct, pid); } break; } case TID_RRT: { const RRT rrt(_duck, table); if (rrt.isValid() && pid == PID_PSIP) { _handler->handleRRT(rrt, pid); } break; } default: { // Unsupported table id or processed elsewhere (PAT, STT). break; } } } } //---------------------------------------------------------------------------- // Invoked by SectionDemux when a section is received. //---------------------------------------------------------------------------- void ts::SignalizationDemux::handleSection(SectionDemux&, const Section& section) { // We use this handler for ATSC System Time Table (STT) only. // This table violates the common usage rules of MPEG sections, see file tsSTT.h. if (_handler != nullptr && section.tableId() == TID_STT && hasTableId(TID_STT) && section.sourcePID() == PID_PSIP) { const STT stt(_duck, section); if (stt.isValid()) { _handler->handleSTT(stt, PID_PSIP); } } }
34.372277
137
0.474997
ASTRO-Strobel
ad6222e6c100a11297409217fcdb1f11d8d82b08
3,880
cpp
C++
project/Windows/Engine/BlurEffect.cpp
mholtkamp/vakz
ad72c9b971c442450d530b82fb8d976c0fccbff7
[ "MIT" ]
5
2016-12-15T18:36:40.000Z
2019-12-04T00:48:40.000Z
project/Windows/Engine/BlurEffect.cpp
mholtkamp/vakz
ad72c9b971c442450d530b82fb8d976c0fccbff7
[ "MIT" ]
null
null
null
project/Windows/Engine/BlurEffect.cpp
mholtkamp/vakz
ad72c9b971c442450d530b82fb8d976c0fccbff7
[ "MIT" ]
1
2021-04-15T09:37:43.000Z
2021-04-15T09:37:43.000Z
#include "BlurEffect.h" #include "Log.h" #include "VGL.h" #include "VInput.h" #include "Settings.h" // Vertex data needed to render quad that covers entire screen static float s_arPosition[8] = {-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f}; static float s_arTexCoord[8] = {0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f}; //***************************************************************************** // Constructor //***************************************************************************** BlurEffect::BlurEffect() { m_nType = EFFECT_BLUR; m_nBlurFactor = 4; m_nSampleDistance = 1; } //***************************************************************************** // Destructor //***************************************************************************** BlurEffect::~BlurEffect() { } //***************************************************************************** // Render //***************************************************************************** void BlurEffect::Render(void* pScene, unsigned int hFBO, unsigned int hColorAttach, unsigned int hDepthAttach) { static int s_nTestFactor = 1; unsigned int hProg = GetShaderProgram(BLUR_EFFECT_PROGRAM); int hTexture = -1; int hDimensions = -1; int hBlurFactor = -1; int hSampleDistance = -1; int hPosition = -1; int hTexCoord = -1; glUseProgram(hProg); glBindBuffer(GL_ARRAY_BUFFER, 0); hTexture = glGetUniformLocation(hProg, "uTexture"); hDimensions = glGetUniformLocation(hProg, "uDimensions"); hBlurFactor = glGetUniformLocation(hProg, "uBlurFactor"); hSampleDistance = glGetUniformLocation(hProg, "uSampleDistance"); hPosition = glGetAttribLocation(hProg, "aPosition"); hTexCoord = glGetAttribLocation(hProg, "aTexCoord"); glBindTexture(GL_TEXTURE_2D, hColorAttach); glUniform1i(hTexture, 0); glUniform1i(hBlurFactor, 6); glUniform1i(hSampleDistance, m_nSampleDistance); glUniform2f(hDimensions, static_cast<float>(g_nResolutionX), static_cast<float>(g_nResolutionY)); glEnableVertexAttribArray(hPosition); glEnableVertexAttribArray(hTexCoord); glVertexAttribPointer(hPosition, 2, GL_FLOAT, GL_FALSE, 0, s_arPosition); glVertexAttribPointer(hTexCoord, 2, GL_FLOAT, GL_FALSE, 0, s_arTexCoord); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } //***************************************************************************** // SetBlurFactor //***************************************************************************** void BlurEffect::SetBlurFactor(int nFactor) { if (nFactor >= MIN_BLUR_FACTOR && nFactor <= MAX_BLUR_FACTOR) { m_nBlurFactor = nFactor; } else { LogWarning("Invalid blur factor in BlurEffect::SetBlurFactor()"); } } //***************************************************************************** // SetSampleDistance //***************************************************************************** void BlurEffect::SetSampleDistance(int nDistance) { if (nDistance >= MIN_SAMPLE_DISTANCE && nDistance <= MAX_SAMPLE_DISTANCE) { m_nSampleDistance = nDistance; } else { LogWarning("Invalid sample distance in BlurEffect::SetSampleDistance()"); } }
32.066116
81
0.439948
mholtkamp
ad642f05c572a280b07527fb1a0008e24f52ff10
3,923
cpp
C++
day05/ex00/Bureaucrat.cpp
psprawka/Cpp_Piscine
73fdb50d654c49587d7d3a2d475b1c57033c8dd4
[ "MIT" ]
1
2019-09-15T08:29:00.000Z
2019-09-15T08:29:00.000Z
day05/ex00/Bureaucrat.cpp
psprawka/Cpp_Piscine
73fdb50d654c49587d7d3a2d475b1c57033c8dd4
[ "MIT" ]
1
2019-09-15T08:28:48.000Z
2019-09-15T08:28:48.000Z
day05/ex00/Bureaucrat.cpp
psprawka/Cpp_Piscine
73fdb50d654c49587d7d3a2d475b1c57033c8dd4
[ "MIT" ]
1
2020-03-04T16:14:40.000Z
2020-03-04T16:14:40.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Bureaucrat.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: psprawka <psprawka@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/02 12:28:08 by psprawka #+# #+# */ /* Updated: 2018/07/03 22:19:15 by psprawka ### ########.fr */ /* */ /* ************************************************************************** */ #include "Bureaucrat.hpp" #include <iostream> /* --------------------------- CANONICAL MODE --------------------------------*/ Bureaucrat::Bureaucrat(void): _grade(0) ,_name("NoName") {} Bureaucrat::Bureaucrat(int grade, std::string const name): _name(name) { try { if (grade > 150) throw Bureaucrat::GradeTooLowException(); else if (grade < 1) throw Bureaucrat::GradeTooHighException(); else this->_grade = grade; } catch (std::exception & e) { std::cout << e.what() << std::endl; this->_grade = 0; } } Bureaucrat::Bureaucrat(Bureaucrat const &obj) { *this = obj; } Bureaucrat::~Bureaucrat(void) {} /* ----------------------------- OPERATORS ---------------------------------*/ Bureaucrat &Bureaucrat::operator=(Bureaucrat const &obj) { this->_grade = obj.getGrade(); return (*this); } std::ostream &operator<<(std::ostream &os, Bureaucrat const &obj) { os << obj.getName() << ", bureaucrat grade " << obj.getGrade(); return (os); } /* ------------------------------ GETTERS ----------------------------------*/ int Bureaucrat::getGrade(void) const { return (this->_grade); } std::string const Bureaucrat::getName(void) const { return (this->_name); } /* ------------------------------ SETTERS ----------------------------------*/ void Bureaucrat::setGrade(int grade) { try { if (grade > 150) throw Bureaucrat::GradeTooLowException(); else if (grade < 1) throw Bureaucrat::GradeTooHighException(); else this->_grade = grade; } catch (std::exception & e) { std::cout << e.what() << std::endl; } } /* ----------------------------- FUNCTIONS ----------------------------------*/ const char *Bureaucrat::GradeTooLowException::what() const throw() { return ("Grade too low."); } const char *Bureaucrat::GradeTooHighException::what() const throw() { return ("Grade too high."); } void Bureaucrat::gradeIncrement(void) { try { if (this->_grade - 1 < 1) throw Bureaucrat::GradeTooHighException(); else this->_grade--; } catch (std::exception & e) { std::cout << e.what() << std::endl; } } void Bureaucrat::gradeDecrement(void) { try { if (this->_grade + 1 > 150) throw Bureaucrat::GradeTooLowException(); else this->_grade++; } catch (std::exception & e) { std::cout << e.what() << std::endl; } } Bureaucrat::GradeTooLowException::GradeTooLowException(void) {} Bureaucrat::GradeTooLowException::GradeTooLowException(GradeTooLowException const &) {} Bureaucrat::GradeTooLowException &Bureaucrat::GradeTooLowException::operator=(GradeTooLowException const &) {return (*this);} Bureaucrat::GradeTooLowException::~GradeTooLowException(void) throw() {} Bureaucrat::GradeTooHighException::GradeTooHighException(void) {} Bureaucrat::GradeTooHighException::GradeTooHighException(GradeTooHighException const &) {} Bureaucrat::GradeTooHighException &Bureaucrat::GradeTooHighException::operator=(GradeTooHighException const &) {return (*this);} Bureaucrat::GradeTooHighException::~GradeTooHighException(void) throw() {}
27.822695
128
0.503696
psprawka
ad66124e89381da2a18d6281e39597f5fa615abe
2,041
cpp
C++
src/wspp_wrapper.cpp
osmiumhydorogen/CppRosBridge_demo
a8b9eb442654f54465cf58ca62da8c583fb746e4
[ "MIT" ]
null
null
null
src/wspp_wrapper.cpp
osmiumhydorogen/CppRosBridge_demo
a8b9eb442654f54465cf58ca62da8c583fb746e4
[ "MIT" ]
null
null
null
src/wspp_wrapper.cpp
osmiumhydorogen/CppRosBridge_demo
a8b9eb442654f54465cf58ca62da8c583fb746e4
[ "MIT" ]
1
2022-03-17T01:38:05.000Z
2022-03-17T01:38:05.000Z
#include <wspp_wrapper.hpp> //#include <websocketpp/common/memory.hpp> namespace crb_sock { WsppWrapper::WsppWrapper() { _client_ep.clear_access_channels(websocketpp::log::alevel::all); _client_ep.clear_error_channels(websocketpp::log::elevel::all); _client_ep.init_asio(); _client_ep.start_perpetual(); m_thread.reset(new websocketpp::lib::thread(&wspp_client_t::run, &_client_ep)); } int WsppWrapper::connect(std::string const &uri) { websocketpp::lib::error_code ec; wspp_client_t::connection_ptr con = _client_ep.get_connection(uri, ec); _con = con; if (ec) { std::cout << "> Connect initialization error: " << ec.message() << std::endl; return -1; } /* _on_message = [&](websocketpp::connection_hdl hdl_, wspp_client_t::message_ptr msg_) { std::cout << "Something resieved." << std::endl; if (msg_->get_opcode() == websocketpp::frame::opcode::text) { this->_callbk(msg_->get_payload()); } }; // */ con->set_message_handler(websocketpp::lib::bind( &WsppWrapper::_on_message, this, websocketpp::lib::placeholders::_1, websocketpp::lib::placeholders::_2 )); hdl=con->get_handle(); _client_ep.connect(con); } void WsppWrapper::_on_message(websocketpp::connection_hdl hdl_, wspp_client_t::message_ptr msg_) { //std::cout << "Something recieved." << std::endl; if (msg_->get_opcode() == websocketpp::frame::opcode::text) { this->_callbk(msg_->get_payload()); } } int WsppWrapper::sendStr(const std::string &str) { websocketpp::lib::error_code ec; //std::cout <<"sending:" << str <<std::endl; _client_ep.send(hdl, str, websocketpp::frame::opcode::text, ec); } int WsppWrapper::setRecieveCb(SockCallback_t cb) { _callbk = cb; } WsppWrapper::~WsppWrapper() { /* websocketpp::lib::error_code ec; _client_ep.close(hdl, websocketpp::close::status::going_away, "", ec); if (ec) { std::cout << "> Error closing connection " << ": " << ec.message() << std::endl; } m_thread->join(); // */ } }
25.197531
97
0.66242
osmiumhydorogen
ad66cdab6826874238158ee269e325fe71d062e1
1,255
cpp
C++
src/Disks/LocalDirectorySyncGuard.cpp
evryfs/ClickHouse
a9648af0b9e2506ce783106315814ed8dbd0a952
[ "Apache-2.0" ]
15,577
2019-09-23T11:57:53.000Z
2022-03-31T18:21:48.000Z
src/Disks/LocalDirectorySyncGuard.cpp
evryfs/ClickHouse
a9648af0b9e2506ce783106315814ed8dbd0a952
[ "Apache-2.0" ]
16,476
2019-09-23T11:47:00.000Z
2022-03-31T23:06:01.000Z
src/Disks/LocalDirectorySyncGuard.cpp
evryfs/ClickHouse
a9648af0b9e2506ce783106315814ed8dbd0a952
[ "Apache-2.0" ]
3,633
2019-09-23T12:18:28.000Z
2022-03-31T15:55:48.000Z
#include <Disks/LocalDirectorySyncGuard.h> #include <Common/Exception.h> #include <Disks/IDisk.h> #include <fcntl.h> // O_RDWR /// OSX does not have O_DIRECTORY #ifndef O_DIRECTORY #define O_DIRECTORY O_RDWR #endif namespace DB { namespace ErrorCodes { extern const int CANNOT_FSYNC; extern const int FILE_DOESNT_EXIST; extern const int CANNOT_OPEN_FILE; extern const int CANNOT_CLOSE_FILE; } LocalDirectorySyncGuard::LocalDirectorySyncGuard(const String & full_path) : fd(::open(full_path.c_str(), O_DIRECTORY)) { if (-1 == fd) throwFromErrnoWithPath("Cannot open file " + full_path, full_path, errno == ENOENT ? ErrorCodes::FILE_DOESNT_EXIST : ErrorCodes::CANNOT_OPEN_FILE); } LocalDirectorySyncGuard::~LocalDirectorySyncGuard() { try { #if defined(OS_DARWIN) if (fcntl(fd, F_FULLFSYNC, 0)) throwFromErrno("Cannot fcntl(F_FULLFSYNC)", ErrorCodes::CANNOT_FSYNC); #endif if (-1 == ::fsync(fd)) throw Exception("Cannot fsync", ErrorCodes::CANNOT_FSYNC); if (-1 == ::close(fd)) throw Exception("Cannot close file", ErrorCodes::CANNOT_CLOSE_FILE); } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } }
24.607843
92
0.680478
evryfs
ad66eb1e8eb04907ffcbcead70c6462695a816a0
1,017
cpp
C++
stringPattern.cpp
thomasjmurphy/dataStructures
1a2fef47cb3734574e7bd7948b0a705b915940da
[ "MIT" ]
null
null
null
stringPattern.cpp
thomasjmurphy/dataStructures
1a2fef47cb3734574e7bd7948b0a705b915940da
[ "MIT" ]
null
null
null
stringPattern.cpp
thomasjmurphy/dataStructures
1a2fef47cb3734574e7bd7948b0a705b915940da
[ "MIT" ]
null
null
null
#include <sstream> #include <string> #include <unordered_map> using namespace std; //Given a pattern and a string, check if the string can be mapped bijectively to that //pattern. see LeetCode problem 290. vector<string> split(string str) { stringstream ss(str); vector<string> ret; string word; while(getline(ss,word,' ')) { ret.push_back(word); } return ret; } class Solution { public: bool wordPattern(string pattern, string str) { vector<string> vec = split(str); if(vec.size() != pattern.length()) { return 0; } unordered_map<char,string> map; unordered_map<string,int> mapInj; for(int i = 0; i < vec.size(); i++) { if(map[pattern[i]].empty() && mapInj[vec[i]] == 0) { map[pattern[i]] = vec[i]; mapInj[vec[i]] = 1; } else { if(map[pattern[i]] != vec[i]) { return 0; } } } return 1; } };
20.34
85
0.52999
thomasjmurphy
ad682fe7eebba2cddbcfd6d37f866fd2258444ea
655
inl
C++
src/ivorium_core/Attribute/Fields/PrivField.inl
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
3
2021-02-26T02:59:09.000Z
2022-02-08T16:44:21.000Z
src/ivorium_core/Attribute/Fields/PrivField.inl
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
src/ivorium_core/Attribute/Fields/PrivField.inl
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
namespace iv { //==================== PrivField_Owner ================================= template< class T > void PrivField_Owner< T >::Field_Modify( PrivField< T > * field, T const & val ) { field->Modify( val ); } //==================== LField_RW ================================= template< class T > PrivField< T >::PrivField( Instance * inst, PrivField_Owner< T > * impl ) : Field< T >( inst ), impl( impl ) { } template< class T > void PrivField< T >::Modify( T const & val ) { this->Field< T >::Modify( val ); } template< class T > void PrivField< T >::OnChanged( bool real ) { this->impl->Field_OnChanged( this, real ); } }
20.46875
80
0.519084
ivorne
ad696df102133daeabc06ece304610ebe0163a3a
1,610
hpp
C++
Lib/Chip/ATSAMD21G18A.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/ATSAMD21G18A.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/ATSAMD21G18A.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstdint> #include <Chip/CM0+/Atmel/ATSAMD21G18A/AC.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/ADC.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/DAC.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/DMAC.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/DSU.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/EIC.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/EVSYS.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/GCLK.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/I2S.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/MTB.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/NVMCTRL.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/PAC0.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/PAC1.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/PAC2.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/PM.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/PORT.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/RTC.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM0.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM1.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM2.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM3.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM4.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM5.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/SYSCTRL.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/TC3.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/TC4.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/TC5.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/TCC0.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/TCC1.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/TCC2.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/USB.hpp> #include <Chip/CM0+/Atmel/ATSAMD21G18A/WDT.hpp>
46
51
0.775776
operativeF