hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
b3a22ea5902539b113043302d5d364afba9a0601
1,646
cpp
C++
sort-search/FindMinimuminRotatedSortedArray_153.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
sort-search/FindMinimuminRotatedSortedArray_153.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
sort-search/FindMinimuminRotatedSortedArray_153.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
/* *********************************************************************** > File Name: FindMinimuminRotatedSortedArray_153.cpp > Author: zzy > Mail: 942744575@qq.com ********************************************************************** */ #include <stdio.h> #include <vector> #include <string> #include <stdio.h> #include <climits> #include <gtest/gtest.h> using std::vector; using std::string; /* * 寻找旋转排序数组中的最小值 * 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 * * ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 * * 请找出其中最小的元素。 * * 你可以假设数组中不存在重复元素。 */ class Solution_2 { public: int findMin(vector<int>& nums) { if (nums.size() == 1) return nums[0]; int left = 0, right = nums.size(); if (nums[right-1] > nums[left]) return nums[left]; while(left < right) { int mid = left + (right - left) / 2; if (nums[mid] < nums[mid-1]) { return nums[mid]; } if (nums[mid] > nums[0]) { left = mid + 1; } else { right = mid; } } return nums[left]; } }; class Solution { public: int findMin(vector<int>& nums) { if (nums.empty()) return 0; int left = 0, right = nums.size() - 1; if (nums[right] >= nums[left]) return nums[left]; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] > nums[mid+1]) { return nums[mid+1]; } // 第一个递增区间上 if (nums[mid] > nums[right]) { left = mid + 1; // 第一个递增区间并且大于right 说明肯定在mid的右边 } else { // <= right 说明在递减区间上,同时mid可能就是最小值,所以不能减1 right = mid; } } return left; } }; TEST(testCase,test0) { } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
19.364706
74
0.537667
[ "vector" ]
a2a33867bac429babdc29607313ef66ff9344b74
2,231
cpp
C++
MMOCoreORB/src/server/zone/objects/intangible/IntangibleObjectImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/objects/intangible/IntangibleObjectImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/objects/intangible/IntangibleObjectImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #include "server/zone/objects/intangible/IntangibleObject.h" #include "server/zone/objects/intangible/TheaterObject.h" #include "server/zone/packets/intangible/IntangibleObjectMessage3.h" #include "server/zone/packets/intangible/IntangibleObjectMessage6.h" #include "server/zone/packets/intangible/IntangibleObjectDeltaMessage3.h" #include "server/zone/packets/scene/IsFlattenedTheaterMessage.h" void IntangibleObjectImplementation::initializeTransientMembers() { SceneObjectImplementation::initializeTransientMembers(); setLoggingName("IntangibleObject"); } void IntangibleObjectImplementation::sendBaselinesTo(SceneObject* player) { debug("sending intangible object baselines"); BaseMessage* itno3 = new IntangibleObjectMessage3(_this.getReferenceUnsafeStaticCast()); player->sendMessage(itno3); BaseMessage* itno6 = new IntangibleObjectMessage6(_this.getReferenceUnsafeStaticCast()); player->sendMessage(itno6); if (isTheaterObject()) { TheaterObject* theater = cast<TheaterObject*>(_this.getReferenceUnsafeStaticCast()); if (theater != nullptr && theater->shouldFlattenTheater()) { BaseMessage* ift = new IsFlattenedTheaterMessage(getObjectID(), true); player->sendMessage(ift); } } } void IntangibleObjectImplementation::updateStatus(int newStatus, bool notifyClient) { if (status == newStatus) return; status = newStatus; if (!notifyClient) return; ManagedReference<SceneObject*> strongParent = getParent().get(); if (strongParent == nullptr) return; ManagedReference<SceneObject*> player = strongParent->getParent().get(); if (player == nullptr) return; IntangibleObjectDeltaMessage3* delta = new IntangibleObjectDeltaMessage3(_this.getReferenceUnsafeStaticCast()); delta->updateStatus(newStatus); delta->close(); player->sendMessage(delta); } void IntangibleObjectImplementation::setCustomObjectName(const UnicodeString& name, bool notifyClient) { customName = name; if (!notifyClient) return; IntangibleObjectDeltaMessage3* ditno3 = new IntangibleObjectDeltaMessage3(_this.getReferenceUnsafeStaticCast()); ditno3->updateName(name); ditno3->close(); broadcastMessage(ditno3, true); }
30.148649
113
0.788436
[ "object" ]
a2a97bd5870c71d90ce529e3f42b57725df45410
515
cpp
C++
ECS/src/Object.cpp
jcoder39/Quasura
f6a8b43620aa77f5488327f0cfe4773b7301bae4
[ "MIT" ]
null
null
null
ECS/src/Object.cpp
jcoder39/Quasura
f6a8b43620aa77f5488327f0cfe4773b7301bae4
[ "MIT" ]
null
null
null
ECS/src/Object.cpp
jcoder39/Quasura
f6a8b43620aa77f5488327f0cfe4773b7301bae4
[ "MIT" ]
null
null
null
/* * Object.cpp * * Created by Viacheslav Borisenko * * Copyright (c) 2018 spectrobyte http://spectrobyte.com * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * */ #include "Quasura/ECS/Object.hpp" ECS_NAMESPACE_BEGIN std::string Object::GetID() { return _id; } Object::Object() { _id = quasura::common::StringGenerator::Instance()->Create(20); } Object::~Object() = default; ECS_NAMESPACE_END
17.758621
66
0.666019
[ "object" ]
a2ac15341102e979a4640b8ba38fdc5984a3a324
1,249
cpp
C++
Leetcode/Day020/longest_common_subsequence.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day020/longest_common_subsequence.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day020/longest_common_subsequence.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
// first solution class Solution { public: int longestCommonSubsequence(string text1, string text2) { int n = text1.length(); int m = text2.length(); int dp[m+1][n+1]; for(int i=0; i<=m; i++) dp[i][0] = 0; for(int i=0; i<=n; i++) dp[0][i] = 0; for(int i=1; i<=m; i++) { for(int j=1; j<=n; j++) { if(text2[i-1] == text1[j-1]) dp[i][j] = dp[i-1][j-1]+1; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } return dp[m][n]; } }; // optimized solution class Solution { public: int longestCommonSubsequence(string text1, string text2) { int n = text1.length(); int m = text2.length(); vector< vector<int>> dp(m+1, vector<int> (n+1,0)); for(int i=1; i<=m; i++) { for(int j=1; j<=n; j++) { if(text2[i-1] == text1[j-1]) dp[i][j] = dp[i-1][j-1]+1; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } return dp[m][n]; } };
22.709091
61
0.366693
[ "vector" ]
a2ad0bc88a849a0eca6dde8839a0e08509286554
1,067
cpp
C++
c10e19oftenDict/c10e19oftenDict/c10e19oftenDict.cpp
abicorios/MyCppExercises
e8ca408c1aac6a780eaf92018aa7da4fd692459a
[ "Unlicense" ]
null
null
null
c10e19oftenDict/c10e19oftenDict/c10e19oftenDict.cpp
abicorios/MyCppExercises
e8ca408c1aac6a780eaf92018aa7da4fd692459a
[ "Unlicense" ]
null
null
null
c10e19oftenDict/c10e19oftenDict/c10e19oftenDict.cpp
abicorios/MyCppExercises
e8ca408c1aac6a780eaf92018aa7da4fd692459a
[ "Unlicense" ]
null
null
null
// c10e19oftenDict.cpp: определяет точку входа для консольного приложения. // #include "stdafx.h" #include <iostream> #include <string> #include <fstream> #include <vector> #include <map> int count(std::string, std::string); int count(std::string bigs, std::string subs) { int n = 0; int found = bigs.find(subs); while (found != std::string::npos) { n++; found = bigs.find(subs, found + 1); } return n; } std::map<std::string, int> f(std::istream&,std::vector<std::string>); std::map<std::string, int> f(std::istream& is, std::vector<std::string> v) { std::string s; std::map<std::string, int> m; while (std::getline(is, s)) { for (auto vi : v) { m[vi] += count(s, vi); } } return m; } int main() { /*std::ofstream ofs("test.txt", std::ofstream::out); for (int j = 0; j < 1000; j++) ofs << "0123456789\n"; ofs.close();*/ std::ifstream f0("test.txt"); std::vector<std::string> v0{ "1","2","8","4" }; std::map<std::string, int> m1; m1=f(f0,v0 ); for (auto mi : m1) { std::cout << mi.first << ' ' << mi.second << std::endl; } }
20.132075
74
0.60075
[ "vector" ]
a2b7c0ddd5afc2a9d44f203932c0fd1c83d5b9bf
16,900
cpp
C++
code/utils/xrAI/motion_simulator.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/utils/xrAI/motion_simulator.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/utils/xrAI/motion_simulator.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
5
2020-10-18T11:55:26.000Z
2022-03-28T07:21:35.000Z
#include "stdafx.h" #include "cl_intersect.h" #include "motion_simulator.h" #include "compiler.h" struct cl_tri { Fvector e10; float e10s; Fvector e21; float e21s; Fvector e02; float e02s; Fvector p[3]; Fvector N; float d; }; struct SCollisionData { // data about player movement Fvector vVelocity; Fvector vSourcePoint; // for error handling Fvector vLastSafePosition; BOOL bStuck; // data for collision response bool bFoundCollision; float fNearestDistance; // nearest distance to hit Fvector vNearestIntersectionPoint; // on sphere Fvector vNearestPolygonIntersectionPoint; // on polygon Fvector vRadius; }; using vecTris = xr_vector<cl_tri>; static int psCollideActDepth = 8; static int psCollideActStuckDepth = 16; static float cl_epsilon = EPS_L; static vecTris clContactedT; // ---------------------------------------------------------------------- // Name : classifyPoint() // Input : point - point we wish to classify // pO - Origin of plane // pN - Normal to plane // Notes : // Return: One of 3 classification codes // ----------------------------------------------------------------------- IC float classifyPoint(const Fvector& point, const Fvector& planeO, const Fvector& planeN) { Fvector dir; dir.sub (point,planeO); return dir.dotproduct(planeN); } // ---------------------------------------------------------------------- // Name : intersectRayPlane() // Input : rOrigin - origin of ray in world space // rVector - xr_vector describing direction of ray in world space // pOrigin - Origin of plane // pNormal - Normal to plane // Notes : Normalized directional vectors expected // Return: distance to plane in world units, -1 if no intersection. // ----------------------------------------------------------------------- IC float intersectRayPlane( const Fvector& rayOrigin, const Fvector& rayDirection, const Fvector& planeOrigin, const Fvector& planeNormal) { float numer = classifyPoint(rayOrigin,planeOrigin,planeNormal); float denom = planeNormal.dotproduct(rayDirection); if (denom == 0) // normal is orthogonal to xr_vector, cant intersect return (-1.0f); return -(numer / denom); } // ---------------------------------------------------------------------- // Name : closestPointOnLine() // Input : a - first end of line segment // b - second end of line segment // p - point we wish to find closest point on line from // Notes : Helper function for closestPointOnTriangle() // Return: closest point on line segment // ----------------------------------------------------------------------- IC void closestPointOnLine(Fvector& res, const Fvector& a, const Fvector& b, const Fvector& p) { // Determine t (the length of the xr_vector from ‘a’ to ‘p’) Fvector c; c.sub(p,a); Fvector V; V.sub(b,a); float d = V.magnitude(); V.div(d); float t = V.dotproduct(c); // Check to see if ‘t’ is beyond the extents of the line segment if (t <= 0.0f) { res.set(a); return; } if (t >= d) { res.set(b); return; } // Return the point between ‘a’ and ‘b’ // set length of V to t. V is normalized so this is easy res.mad (a,V,t); } IC void closestPointOnEdge(Fvector& res, // result const Fvector& a, const Fvector& b, // points const Fvector& ED, float elen, // edge direction (b-a) and length const Fvector& P) // query point { // Determine t (the length of the xr_vector from ‘a’ to ‘p’) Fvector c; c.sub(P,a); float t = ED.dotproduct(c); // Check to see if ‘t’ is beyond the extents of the line segment if (t <= 0.0f) { res.set(a); return; } if (t >= elen) { res.set(b); return; } // Return the point between ‘a’ and ‘b’ res.mad(a,ED,t); } // ---------------------------------------------------------------------- // Name : closestPointOnTriangle() // p - point we wish to find closest point on triangle from // Return: closest point on line triangle edge // ----------------------------------------------------------------------- IC void closestPointOnTriangle(Fvector& result, const Fvector* V, const Fvector& p) { Fvector Rab; closestPointOnLine(Rab, V[0], V[1], p); float dAB = p.distance_to_sqr(Rab); Fvector Rbc; closestPointOnLine(Rbc, V[1], V[2], p); float dBC = p.distance_to_sqr(Rbc); Fvector Rca; closestPointOnLine(Rca, V[2], V[0], p); float dCA = p.distance_to_sqr(Rca); float min = dAB; result.set(Rab); if (dBC < min) { min = dBC; result.set(Rbc); } if (dCA < min) result.set(Rca); } IC void closestPointOnTriangle(Fvector& result, const cl_tri& T, const Fvector& P) { Fvector Rab; closestPointOnEdge(Rab, T.p[0], T.p[1], T.e10, T.e10s, P); float dAB = P.distance_to_sqr(Rab); Fvector Rbc; closestPointOnEdge(Rbc, T.p[1], T.p[2], T.e21, T.e21s, P); float dBC = P.distance_to_sqr(Rbc); Fvector Rca; closestPointOnEdge(Rca, T.p[2], T.p[0], T.e02, T.e02s, P); float dCA = P.distance_to_sqr(Rca); float min; if (dBC < dAB) { min = dBC; result.set(Rbc); } else { min = dAB; result.set(Rab); } if (dCA < min) result.set(Rca); } // ---------------------------------------------------------------------- // Name : intersectRaySphere() // Input : rO - origin of ray in world space // rV - xr_vector describing direction of ray in world space // sO - Origin of sphere // sR - radius of sphere // Notes : Normalized directional vectors expected // Return: distance to sphere in world units, -1 if no intersection. // ----------------------------------------------------------------------- IC float intersectRaySphere(const Fvector& rO, const Fvector& rV, const Fvector& sO, float sR) { Fvector Q; Q.sub(sO,rO); float c = Q.magnitude(); float v = Q.dotproduct(rV); float d = sR*sR - (c*c - v*v); // If there was no intersection, return -1 if (d < 0.0) return (-1.0f); // Return the distance to the [first] intersecting point return (v - _sqrt(d)); } IC float intersectRayIdentitySphere(const Fvector& rO, const Fvector& rV) { Fvector Q; Q.invert(rO); float c = Q.magnitude(); float v = Q.dotproduct(rV); float d = 1 - (c*c - v*v); // If there was no intersection, return -1 if (d < 0.0) return (-1.0f); // Return the distance to the [first] intersecting point return (v - _sqrt(d)); } // ---------------------------------------------------------------------- // Name : CheckPointInSphere() // Input : point - point we wish to check for inclusion // sO - Origin of sphere // sR - radius of sphere // Notes : // Return: TRUE if point is in sphere, FALSE if not. // ----------------------------------------------------------------------- IC bool CheckPointInSphere(const Fvector& point, const Fvector& sO, float sR) { return (sO.distance_to_sqr(point)< sR*sR); } IC bool CheckPointInIdentitySphere(const Fvector& point) { return (point.square_magnitude() <= 1); } // ----------------------------------------------------------------------- void msimulator_CheckCollision(SCollisionData& cl) { // from package Fvector source; Fvector velocity; source.set (cl.vSourcePoint); velocity.set (cl.vVelocity); // keep a copy of this as it's needed a few times Fvector normalizedVelocity; normalizedVelocity.normalize_safe(cl.vVelocity); // intersection data Fvector sIPoint; // sphere intersection point Fvector pIPoint; // plane intersection point Fvector polyIPoint; // polygon intersection point // how long is our velocity float distanceToTravel = velocity.magnitude(); float distToPlaneIntersection; float distToEllipsoidIntersection; for (u32 i_t=0; i_t!=clContactedT.size(); i_t++){ cl_tri& T=clContactedT[i_t]; //ignore backfaces. What we cannot see we cannot collide with ;) if (T.N.dotproduct(normalizedVelocity) < 0.0f) { // calculate sphere intersection point (in future :) // OLES: 'cause our radius has unit length, this point lies exactly on sphere sIPoint.sub(source, T.N); // find the plane intersection point // classify point to determine if ellipsoid span the plane BOOL bInsideTri; if ((sIPoint.dotproduct(T.N)+T.d) < -EPS_S) { // plane is embedded in ellipsoid / sphere // find plane intersection point by shooting a ray from the // sphere intersection point along the planes normal. bInsideTri = CDB::TestRayTri2(sIPoint,T.N,T.p,distToPlaneIntersection); // calculate plane intersection point pIPoint.mad(sIPoint,T.N,distToPlaneIntersection); } else { // shoot ray along the velocity xr_vector bInsideTri = CDB::TestRayTri2(sIPoint,normalizedVelocity,T.p,distToPlaneIntersection); // calculate plane intersection point pIPoint.mad(sIPoint,normalizedVelocity,distToPlaneIntersection); } // find polygon intersection point. By default we assume its equal to the // plane intersection point polyIPoint.set(pIPoint); distToEllipsoidIntersection = distToPlaneIntersection; if (!bInsideTri) { // if not in triangle closestPointOnTriangle(polyIPoint, T, pIPoint); Fvector _normalizedVelocity; _normalizedVelocity.invert(normalizedVelocity); distToEllipsoidIntersection = intersectRaySphere(polyIPoint, _normalizedVelocity, source, 1.0f); if (distToEllipsoidIntersection >= 0){ // calculate true sphere intersection point sIPoint.mad(polyIPoint, normalizedVelocity, -distToEllipsoidIntersection); } } // Here we do the error checking to see if we got ourself stuck last frame if (CheckPointInSphere(polyIPoint, source, 1.0f)) { cl.bStuck = TRUE; } // Ok, now we might update the collision data if we hit something if ((distToEllipsoidIntersection >= 0) && (distToEllipsoidIntersection <= distanceToTravel)) { if ((cl.bFoundCollision == FALSE) || (distToEllipsoidIntersection < cl.fNearestDistance)) { // if we are hit we have a closest hit so far. We save the information cl.fNearestDistance = distToEllipsoidIntersection; cl.vNearestIntersectionPoint.set(sIPoint); cl.vNearestPolygonIntersectionPoint.set(polyIPoint); cl.bFoundCollision = TRUE; } } } // if not backface } // for all faces } //----------------------------------------------------------------------------- void msimulator_ResolveStuck(SCollisionData& cl, Fvector& position) { // intersection data Fvector polyIPoint; // polygon intersection point Fvector stuckDir; int stuckCount; float dist; float safe_R = 1.f + EPS_L*2;//psSqueezeVelocity*Device.fTimeDelta; for (int passes=0; passes<psCollideActStuckDepth; passes++) { // initialize stuckDir.set (0,0,0); stuckCount = 0; // for all faces for (u32 i_t=0; i_t!=clContactedT.size(); i_t++) { cl_tri& T=clContactedT[i_t]; Fvector N_inv; N_inv.invert(T.N); // find plane intersection point by shooting a ray from the // sphere intersection point along the planes normal. if (CDB::TestRayTri2(position,N_inv,T.p,dist)){ // calculate plane intersection point polyIPoint.mad(position,N_inv,dist); }else{ // calculate plane intersection point Fvector tmp; tmp.mad(position,N_inv,dist); closestPointOnTriangle(polyIPoint, T, tmp); } if (CheckPointInSphere(polyIPoint, position, safe_R)) { Fvector dir; dir.sub(position,polyIPoint); float len = dir.magnitude(); dir.mul( (safe_R-len)/len ); stuckDir.add(dir); stuckCount++; } } if (stuckCount){ stuckDir.div(float(stuckCount)); position.add(stuckDir); if (stuckDir.magnitude()<EPS) break; } else break; } } //----------------------------------------------------------------------------- // Name: collideWithWorld() // Desc: Recursive part of the collision response. This function is the // one who actually calls the collision check on the meshes //----------------------------------------------------------------------------- Fvector msimulator_CollideWithWorld(SCollisionData& cl, Fvector position, Fvector velocity, WORD cnt) { // msimulator_ResolveStuck(cl,position); // do we need to worry ? // if (fsimilar(position.x,target.x,EPS_L)&&fsimilar(position.z,target.z,EPS_L)) if (velocity.magnitude()<EPS_L) { cl.vVelocity.set(0,0,0); return position; } if (cnt>psCollideActDepth) return cl.vLastSafePosition; Fvector ret_pos; Fvector destinationPoint; destinationPoint.add(position,velocity); // reset the collision package we send to the mesh cl.vVelocity.set (velocity); cl.vSourcePoint.set (position); cl.bFoundCollision = FALSE; cl.bStuck = FALSE; cl.fNearestDistance = -1; // Check collision msimulator_CheckCollision (cl); // check return value here, and possibly call recursively if (cl.bFoundCollision == FALSE && !cl.bStuck) { // if no collision move very close to the desired destination. float l = velocity.magnitude(); Fvector V; V.mul(velocity,(l-cl_epsilon)/l); // return the final position ret_pos.add(position,V); // update the last safe position for future error recovery cl.vLastSafePosition.set(ret_pos); return ret_pos; }else{ // There was a collision // OK, first task is to move close to where we hit something : Fvector newSourcePoint; // If we are stuck, we just back up to last safe position if (cl.bStuck){ return cl.vLastSafePosition; } // only update if we are not already very close if (cl.fNearestDistance >= cl_epsilon) { Fvector V; V.set(velocity); V.set_length(cl.fNearestDistance-cl_epsilon); newSourcePoint.add(cl.vSourcePoint,V); }else { newSourcePoint.set(cl.vSourcePoint); } // Now we must calculate the sliding plane Fvector slidePlaneOrigin; slidePlaneOrigin.set(cl.vNearestPolygonIntersectionPoint); Fvector slidePlaneNormal; slidePlaneNormal.sub(newSourcePoint,cl.vNearestPolygonIntersectionPoint); // We now project the destination point onto the sliding plane float l = intersectRayPlane(destinationPoint, slidePlaneNormal, slidePlaneOrigin, slidePlaneNormal); // We can now calculate a _new destination point on the sliding plane Fvector newDestinationPoint; newDestinationPoint.mad(destinationPoint,slidePlaneNormal,l); // Generate the slide xr_vector, which will become our _new velocity xr_vector // for the next iteration Fvector newVelocityVector; newVelocityVector.sub(newDestinationPoint, cl.vNearestPolygonIntersectionPoint); // now we recursively call the function with the _new position and velocity cl.vLastSafePosition.set(position); return msimulator_CollideWithWorld(cl, newSourcePoint, newVelocityVector,cnt+1); } } IC void create_bb(Fbox& B, Fvector& P, float r, float h) { B.set(P.x-r, P.y, P.z-r, P.x+r, P.y+h, P.z+r); } void msimulator_Simulate( Fvector& result, Fvector& start, Fvector& end, float _radius, float _height) { SCollisionData cl_data; float half_height = _height/2; // Calc BB Fbox b1,b2,bb; create_bb (b1,start, _radius,_height); create_bb (b2,end, _radius,_height); bb.merge (b1,b2); bb.grow (0.05f); // Collision query Fvector bbC,bbD; bb.get_CD (bbC,bbD); XRC.box_options (0); XRC.box_query (&Level,bbC,bbD); // XForm everything to ellipsoid space Fvector xf; xf.set (1/_radius,1/half_height,1/_radius); Fvector Lposition; Lposition.set (start); Lposition.y += half_height; Lposition.mul (xf); Fvector target; target.set (end); target.y += half_height; target.mul (xf); Fvector Lvelocity; Lvelocity.sub (end,start); Lvelocity.mul (xf); cl_data.vLastSafePosition.set (Lposition); // Get the data for the triangles in question and scale to ellipsoid space int tri_count = XRC.r_count(); clContactedT.resize (tri_count); if (tri_count) { Fvector vel_dir; vel_dir.normalize_safe (Lvelocity); for (int i_t=0; i_t<tri_count; i_t++){ cl_tri& T = clContactedT[i_t]; CDB::RESULT& rp = XRC.r_begin()[i_t]; // CDB::TRI& O = *(Level.get_tris()+rp.id); T.p[0].mul (rp.verts[0],xf); T.p[1].mul (rp.verts[1],xf); T.p[2].mul (rp.verts[2],xf); T.N.mknormal (T.p[0],T.p[1],T.p[2]); T.d = -T.N.dotproduct(T.p[0]); T.e10.sub(T.p[1],T.p[0]); T.e10s = T.e10.magnitude(); T.e10.div(T.e10s); T.e21.sub(T.p[2],T.p[1]); T.e21s = T.e21.magnitude(); T.e21.div(T.e21s); T.e02.sub(T.p[0],T.p[2]); T.e02s = T.e02.magnitude(); T.e02.div(T.e02s); } } // call the recursive collision response function Fvector POS; for (int i=0; i<3; i++) { POS.set(msimulator_CollideWithWorld(cl_data, Lposition, Lvelocity, 0)); if (fsimilar(POS.x,target.x)&&fsimilar(POS.z,target.z)) break; Lposition.set (POS); Lvelocity.sub (target,POS); Lvelocity.y = 0; } result.div(POS,xf); result.y-=half_height; }
32.068311
108
0.638107
[ "mesh" ]
a2ba42cac8a4dad5303db962410a561d9d19f6c3
4,019
cpp
C++
src/python/pytypes.cpp
ArmindoFlores/cppy
5ce0832e79bbdb56b11cd03490ee1d6d09a454a0
[ "MIT" ]
5
2021-12-24T00:11:22.000Z
2022-01-06T23:53:10.000Z
src/python/pytypes.cpp
ArmindoFlores/cppy
5ce0832e79bbdb56b11cd03490ee1d6d09a454a0
[ "MIT" ]
null
null
null
src/python/pytypes.cpp
ArmindoFlores/cppy
5ce0832e79bbdb56b11cd03490ee1d6d09a454a0
[ "MIT" ]
null
null
null
#include "pytypes.h" #include "pyhelpers.h" #include "pybuiltins.h" #include "pyint.h" #include "pybool.h" #include "pybaseobject.h" #include "pylist.h" #include "pydict.h" #include "pytuple.h" #include "pynotimplemented.h" #include "pystring.h" #include "pygarbagecollector.h" #include "pyglobalinstances.h" #include "pytraceback.h" using namespace cppy; using namespace cppy::globals; #include <iostream> std::shared_ptr<BuiltinTypes> BuiltinTypes::instance = nullptr; BuiltinTypes::BuiltinTypes() { // <class 'object'> types["object"] = std::make_shared<PyType>( "object", PyBaseObject::construct, helpers::new_tuple() ); // <class 'type'> types["type"] = std::make_shared<PyType>( "type", PyType::construct, helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(types["object"])})) ); // <class 'function'> types["function"] = std::make_shared<PyType>( "function", PyFunction::construct, helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(types["object"])})) ); // <class 'NoneType'> types["none"] = std::make_shared<PyType>( "NoneType", PyNone::construct, helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(types["object"])})) ); // <class 'NotImplemented'> types["notimpl"] = std::make_shared<PyType>( "NotImplemented", PyNotImplemented::construct, helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(types["object"])})) ); // <class 'str'> types["str"] = std::make_shared<PyType>( "str", PyString::construct, helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(types["object"])})) ); // <class 'int'> types["int"] = std::make_shared<PyType>( "int", PyInt::construct, helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(types["object"])})) ); // <class 'bool'> types["bool"] = std::make_shared<PyType>( "bool", PyBool::construct, helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(types["object"]), std::weak_ptr(types["int"])})) ); // <class 'list'> types["list"] = std::make_shared<PyType>( "list", PyList::construct, helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(types["object"])})) ); // <class 'tuple'> types["tuple"] = std::make_shared<PyType>( "tuple", PyTuple::construct, helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(types["object"])})) ); // <class 'dict'> types["dict"] = std::make_shared<PyType>( "dict", PyDict::construct, helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(types["object"])})) ); init_builtin_types(); } BuiltinTypes &BuiltinTypes::the() { if (instance == nullptr) { instance = std::shared_ptr<BuiltinTypes>(new BuiltinTypes()); } return *instance; } PyObjectPtr BuiltinTypes::get_type_named(const std::string& name) const { return types.at(name); } bool BuiltinTypes::is_builtin_type(PyObjectPtr t) const { for (const auto &pair: types) { if (pair.second == t) return true; } return false; } void BuiltinTypes::init_builtin_types() { // Hardcode MROs for the builtin types for (auto &pair : types) { if (pair.first != "object" && pair.first != "bool") pair.second->setattr("__mro__", helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(pair.second), std::weak_ptr(types["object"])}))); else if (pair.first == "object") pair.second->setattr("__mro__", helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(pair.second)}))); else pair.second->setattr("__mro__", helpers::new_tuple(std::vector<PyObjectAnyPtr>({std::weak_ptr(pair.second), std::weak_ptr(types["int"]), std::weak_ptr(types["object"])}))); } }
29.335766
184
0.616571
[ "object", "vector" ]
a2ca9f6fc8d41fde712249f5c1ef66c9b3f9c94f
570
cpp
C++
source/scapes/visual/resources/IBLTexture.cpp
eZii-jester-data/pbr-sandbox
853aa023f063fd48760a8c3848687976189f3f98
[ "MIT" ]
null
null
null
source/scapes/visual/resources/IBLTexture.cpp
eZii-jester-data/pbr-sandbox
853aa023f063fd48760a8c3848687976189f3f98
[ "MIT" ]
null
null
null
source/scapes/visual/resources/IBLTexture.cpp
eZii-jester-data/pbr-sandbox
853aa023f063fd48760a8c3848687976189f3f98
[ "MIT" ]
null
null
null
#include <scapes/visual/Resources.h> #include <RenderUtils.h> using namespace scapes; using namespace scapes::visual; /* */ void ::ResourcePipeline<resources::IBLTexture>::destroy( foundation::resources::ResourceManager *resource_manager, IBLTextureHandle handle, foundation::render::Device *device ) { resources::IBLTexture *texture = handle.get(); resource_manager->destroy(texture->prefiltered_specular_cubemap, device); resource_manager->destroy(texture->diffuse_irradiance_cubemap, device); device->destroyBindSet(texture->bindings); *texture = {}; }
23.75
74
0.777193
[ "render" ]
a2cf4bba39c42889a280b9285378f4095e7b17ac
879
cpp
C++
COJ/HowManyPrimes.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
1
2019-09-29T03:58:35.000Z
2019-09-29T03:58:35.000Z
COJ/HowManyPrimes.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
COJ/HowManyPrimes.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <string> #include <cctype> #include <stack> #include <queue> #include <list> #include <vector> #include <map> #include <cmath> #include <utility> #include <set> #include <stdio.h> using namespace std; #define MAX 1000000 char* primes; void cachePrimes(){ int i,j; primes[0] = 1; primes[1] = 1; for(i=4;i<=MAX;i+=2) primes[i] = 1; for(i=3;i*i<=MAX;i+=2) if(!primes[i]) for(j=i*i;j<=MAX;j+=i){ primes[j] = 1; } } int main(){ int a, b, i, ac; primes = (char*) malloc(MAX+1); for (int j = 0; j <= MAX; j++) { primes[j] = 0; } cachePrimes(); cin >> a >> b; for(;a!=0;){ ac = 0; for(i=a; i<=b; i++){ if(primes[i]==0) ac++; } printf("%d\n", ac); cin >> a >> b; } }
17.235294
36
0.506257
[ "vector" ]
a2d1ebcdd2fc41be4eec900cac030055eab75caf
16,777
cpp
C++
printscan/print/drivers/usermode/unidrv2/vector/hpgl2col/render/vector.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/print/drivers/usermode/unidrv2/vector/hpgl2col/render/vector.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/print/drivers/usermode/unidrv2/vector/hpgl2col/render/vector.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1999-2001 Microsoft Corporation All rights reserved. Module Name: vector.cpp Abstract: Implementation of DDI vector drawing hooks specific to HP-GL/2 Environment: Windows 2000 Unidrv driver Revision History: 04/07/97 -sandram- Created it. --*/ #include "hpgl2col.h" //Precompiled header file #ifndef WINNT_40 ///////////////////////////////////////////////////////////////////////////// // HPGLAlphaBlend // // Routine Description: // // Handles DrvAlphaBlend. Actually we don't handle it. We don't do alpha // blending in this driver. What we do here is punt back to the OS. // // Arguments: // // psoDest - points to target surface. // psoSrc - points to the source surface // pco - clip region // pxloSrcDCto32 - specifies how color indices should be translated between // the source and target // prclDest - RECTL structure that defines area to be modified // prclSrc - source rectangle // pBlendObj - how blend should happen // // Return Value: // // TRUE if successful, FALSE if there is an error ///////////////////////////////////////////////////////////////////////////// BOOL APIENTRY HPGLAlphaBlend( SURFOBJ *psoDest, SURFOBJ *psoSrc, CLIPOBJ *pco, XLATEOBJ *pxloSrcDCto32, RECTL *prclDest, RECTL *prclSrc, BLENDOBJ *pBlendObj ) { TERSE(("HPGLAlphaBlend() entry.\r\n")); PDEVOBJ pdevobj = (PDEVOBJ)psoDest->dhpdev; REQUIRE_VALID_DATA(pdevobj, return FALSE); POEMPDEV poempdev = (POEMPDEV)pdevobj->pdevOEM; REQUIRE_VALID_DATA( poempdev, return FALSE); PDEV *pPDev = (PDEV *)pdevobj; // // To see the explanation of PF2_WHITEN_SURFACE, PDEVF_RENDER_TRANSPARENT // read the HPGLGradientFill. // In AlphaBlend too, GDI calls DrvCopyBits with psoSrc=STYPE_BITMAP and // psoDst=STYPE_DEVICE. // BOOL bRetVal = FALSE; pPDev->fMode2 |= PF2_WHITEN_SURFACE; poempdev->dwFlags |= PDEVF_RENDER_TRANSPARENT; bRetVal = EngAlphaBlend( psoDest, psoSrc, pco, pxloSrcDCto32, prclDest, prclSrc, pBlendObj); // // EngAlphaBlend can call some Drvxxx which can call into // some plugin module, which can overwrite our pdevOEM. // So we need to reset pdevOEM // BRevertToHPGLpdevOEM (pdevobj); pPDev->fMode2 &= ~PF2_WHITEN_SURFACE; poempdev->dwFlags &= ~PDEVF_RENDER_TRANSPARENT; pPDev->fMode2 &= ~PF2_SURFACE_WHITENED; return bRetVal; } ///////////////////////////////////////////////////////////////////////////// // HPGLGradientFill // // Routine Description: // // Handles DrvGradientFill. Actually we don't handle it. What we do here // is punt back to the OS. // // Arguments: // // psoDest - points to target surface. // pco - clip region // pxlo - specifies how color indices should be translated between // the source and target // pVertex - array of vertices // nVertex - number of vertices in pVertex // pMest - unknown // nMesh - unknown // prclExtents - unknown // pptlDitherOrg - unknown // ulMode - unknown // // Return Value: // // TRUE if successful, FALSE if there is an error ///////////////////////////////////////////////////////////////////////////// BOOL APIENTRY HPGLGradientFill( SURFOBJ *psoDest, CLIPOBJ *pco, XLATEOBJ *pxlo, TRIVERTEX *pVertex, ULONG nVertex, PVOID pMesh, ULONG nMesh, RECTL *prclExtents, POINTL *pptlDitherOrg, ULONG ulMode ) { TERSE(("HPGLGradientFill() entry.\r\n")); PDEVOBJ pdevobj = (PDEVOBJ)psoDest->dhpdev; REQUIRE_VALID_DATA(pdevobj, return FALSE); POEMPDEV poempdev = (POEMPDEV)pdevobj->pdevOEM; REQUIRE_VALID_DATA( poempdev, return FALSE); PDEV *pPDev = (PDEV *)pdevobj; BOOL bRetVal = FALSE; // // If the GradientFill is a TRIANGLE_FILL and // EngGradientFill is called, GDI calls DrvCopyBits with psoSrc=STYPE_BITMAP and // psoDst=STYPE_DEVICE because it wants the driver to copy whats on the device to // the bitmap surface. The driver does not keep track of whats on the device. So it // cannot honestly fill out the surface. So the driver decides to simply whiten the // Bitmap Surface assuming that nothing was drawn on the paper earlier. // Note that by doing so, the whole rectangular area is // whitened, even though the actual image is only in a triangle. If this image is // downloaded, the white part will overwrite whatever is present on the destination. // To prevent this, the image should be downloaded with Source Tranpsarency set // as TRANSPARENT (Esc*v0n), so that white does not overwrite the destination. // Whatever is already underneath the image will still peep through. // So now we need to do 2 things // 1. Set a flag so that DrvCopyBits will whiten the surface // 2. Set a flag so that when we(HPGL Driver)get an image to download, we set the transparency // mode to TRANSPARENT. // NOTE : GDI is planning to change the behavior for Windows XP, but if you want to see // this happening, run this driver on Windows2000 machine. // if ( ulMode == GRADIENT_FILL_TRIANGLE ) { // // For this special case, We'll render the bitmap transparent. // poempdev->dwFlags |= PDEVF_RENDER_TRANSPARENT; pPDev->fMode2 |= PF2_WHITEN_SURFACE; } bRetVal = EngGradientFill( psoDest, pco, pxlo, pVertex, nVertex, pMesh, nMesh, prclExtents, pptlDitherOrg, ulMode); // // EngGradientBlt can call some Drvxxx which can call into // some plugin module, which can overwrite our pdevOEM. // So we need to reset pdevOEM // BRevertToHPGLpdevOEM (pdevobj); // // When DrvCopyBits whitens the surface it sets the PF2_RENDER_TRANSPARENT flag in // pPDev->fMode2. So we have to reset that flag too. // poempdev->dwFlags &= ~PDEVF_RENDER_TRANSPARENT; pPDev->fMode2 &= ~PF2_WHITEN_SURFACE; pPDev->fMode2 &= ~PF2_SURFACE_WHITENED; return bRetVal; } #endif //ifndef WINNT_40 ///////////////////////////////////////////////////////////////////////////// // OEMFillPath // // Routine Description: // // Handles DrvFillPath. // // Arguments: // // pso - points to target surface. // ppo - path to fill // pco - clip region // pbo - brush to fill with // pptBrushOrg - pattern brush offset // mix - contains ROP codes // flOptions - fill options such as winding or alternate // // Return Value: // // TRUE if successful, FALSE if there is an error ///////////////////////////////////////////////////////////////////////////// BOOL APIENTRY HPGLFillPath( SURFOBJ *pso, PATHOBJ *ppo, CLIPOBJ *pco, BRUSHOBJ *pbo, POINTL *pptlBrushOrg, MIX mix, FLONG flOptions ) { PDEVOBJ pdevobj; POEMPDEV poempdev; BOOL bRetVal = TRUE; HPGLMARKER Brush; TERSE(("HPGLFillPath() entry.\r\n")); // // Validate input parameters // pdevobj = (PDEVOBJ)pso->dhpdev; ASSERT(VALID_PDEVOBJ(pdevobj) && (poempdev = (POEMPDEV)pdevobj->pdevOEM)); poempdev = (POEMPDEV)pdevobj->pdevOEM; REQUIRE_VALID_DATA( (pso && poempdev), return FALSE ); ZeroMemory(&Brush, sizeof (HPGLMARKER)); TRY { // // If the clipping region is complex, we cannot handle // it. The output file size gets too big. So ask GDI to do it. // if ( pco && (pco->iDComplexity == DC_COMPLEX) ) { bRetVal = FALSE; goto finish; } BChangeAndTrackObjectType (pdevobj, eHPGLOBJECT); // Set up current graphics state // clipping path // foreground/background mix mode // Pen // line attributes // // Send the path object to the printer and stroke it // if (! SelectMix(pdevobj, mix) || ! SelectClipEx(pdevobj, pco, flOptions) || ! CreateHPGLPenBrush(pdevobj, &Brush, pptlBrushOrg, pbo, flOptions, kBrush, FALSE) || ! MarkPath(pdevobj, ppo, NULL, &Brush) || ! HPGL_SelectTransparency(pdevobj, eOPAQUE, 0) ) { WARNING(("Cannot fill path\n")); TOSS(DDIError); } bRetVal = TRUE; } CATCH(DDIError) { bRetVal = FALSE; } ENDTRY; finish: return bRetVal; } ///////////////////////////////////////////////////////////////////////////// // HPGLStrokePath // // Routine Description: // // Handles DrvStrokePath. // // Arguments: // // pso - points to target surface. // ppo - path to edge // pco - clip region // pxo - transform obj // pbo - brush to edge with // pptBrushOrg - pattern brush offset // plineattrs - line attributes such as dot/dash, width and caps & joins // mix - contains ROP codes // // Return Value: // // TRUE if successful, FALSE if there is an error ///////////////////////////////////////////////////////////////////////////// BOOL APIENTRY HPGLStrokePath( SURFOBJ *pso, PATHOBJ *ppo, CLIPOBJ *pco, XFORMOBJ *pxo, BRUSHOBJ *pbo, POINTL *pptlBrushOrg, LINEATTRS *plineattrs, MIX mix ) { PDEVOBJ pdevobj; POEMPDEV poempdev; BOOL bRetVal; HPGLMARKER Pen; TERSE(("HPGLStrokePath() entry.\r\n")); // // Validate input parameters // pdevobj = (PDEVOBJ)pso->dhpdev; ASSERT(VALID_PDEVOBJ(pdevobj) && (poempdev = (POEMPDEV)pdevobj->pdevOEM)); poempdev = (POEMPDEV)pdevobj->pdevOEM; REQUIRE_VALID_DATA( (poempdev && pso), return FALSE ); ZeroMemory(&Pen, sizeof (HPGLMARKER)); TRY { BChangeAndTrackObjectType (pdevobj, eHPGLOBJECT); // Set up current graphics state // clipping path // foreground/background mix mode // Pen // line attributes // // Send the path object to the printer and stroke it // if (! SelectMix(pdevobj, mix) || ! SelectClip(pdevobj, pco) || ! CreateHPGLPenBrush(pdevobj, &Pen, pptlBrushOrg, pbo, 0, kPen, FALSE) || ! SelectLineAttrs(pdevobj, plineattrs, pxo) || ! MarkPath(pdevobj, ppo, &Pen, NULL) || ! HPGL_SelectTransparency(pdevobj, eOPAQUE, 0) ) { WARNING(("Cannot stroke path\n")); TOSS(DDIError); } bRetVal = TRUE; } CATCH(DDIError) { bRetVal = FALSE; } ENDTRY; return bRetVal; } ///////////////////////////////////////////////////////////////////////////// // HPGLStrokeAndFillPath // // Routine Description: // // Handles DrvStrokeAndFillPath // // Arguments: // // pso - points to target surface. // ppo - path to stroke & fill // pco - clip region // pxo - transform obj // pboStroke - brush to edge with // plineattrs - line attributes such as dot/dash, width and caps & joins // pboFill - brush to fill with // pptBrushOrg - pattern brush offset // mix - contains ROP codes // flOptions - fill mode // // Return Value: // // TRUE if successful, FALSE if there is an error ///////////////////////////////////////////////////////////////////////////// BOOL APIENTRY HPGLStrokeAndFillPath( SURFOBJ *pso, PATHOBJ *ppo, CLIPOBJ *pco, XFORMOBJ *pxo, BRUSHOBJ *pboStroke, LINEATTRS *plineattrs, BRUSHOBJ *pboFill, POINTL *pptlBrushOrg, MIX mixFill, FLONG flOptions ) { PDEVOBJ pdevobj; POEMPDEV poempdev; BOOL bRetVal; HPGLMARKER Pen; HPGLMARKER Brush; TERSE(("HPGLStrokeAndFillPath() entry.\r\n")); // // Validate input parameters // pdevobj = (PDEVOBJ)pso->dhpdev; ASSERT(VALID_PDEVOBJ(pdevobj) && (poempdev = (POEMPDEV)pdevobj->pdevOEM)); poempdev = (POEMPDEV)pdevobj->pdevOEM; REQUIRE_VALID_DATA( (poempdev && pso), return FALSE ); ZeroMemory(&Pen, sizeof (HPGLMARKER)); ZeroMemory(&Brush, sizeof (HPGLMARKER)); TRY { BChangeAndTrackObjectType (pdevobj, eHPGLOBJECT); // Set up current graphics state // clipping path // foreground/background mix mode // Pen // line attributes // // Send the path object to the printer and stroke it // if (! SelectMix(pdevobj, mixFill) || ! SelectClipEx(pdevobj, pco, flOptions) || ! CreateHPGLPenBrush(pdevobj, &Pen, pptlBrushOrg, pboStroke, 0, kPen, TRUE) || ! CreateHPGLPenBrush(pdevobj, &Brush, pptlBrushOrg, pboFill, flOptions, kBrush, FALSE) || ! SelectLineAttrs(pdevobj, plineattrs, pxo) || ! MarkPath(pdevobj, ppo, &Pen, &Brush) || ! HPGL_SelectTransparency(pdevobj, eOPAQUE, 0) ) { WARNING(("Cannot stroke & fill path\n")); TOSS(DDIError); } bRetVal = TRUE; } CATCH(DDIError) { bRetVal = FALSE; } ENDTRY; // // Look above. There are 2 calls to CreateHPGLPenBrush, one for pboStroke // and other from pboFill. Both the calls can cause an entry in brush cache. // We do not want pboFill to overwrite pboStroke entry in the brush cache // so we marked pboStroke's entry as non-overwriteable or sticky. // (The parameter TRUE in CreateHPGLPenBrush). // Now that we are done with this function, we can safely // make it overwriteable i.e. set sticky attribute to FALSE // if (Pen.lPatternID) { poempdev->pBrushCache->BSetStickyFlag(Pen.lPatternID, FALSE); } return bRetVal; } ///////////////////////////////////////////////////////////////////////////// // OEMStrokeAndFillPath // // Routine Description: // // Handles DrvStrokeAndFillPath // // Arguments: // // pso - points to target surface. // ppo - path to stroke & fill // pco - clip region // pxo - transform obj // pboStroke - brush to edge with // plineattrs - line attributes such as dot/dash, width and caps & joins // pboFill - brush to fill with // pptBrushOrg - pattern brush offset // mix - contains ROP codes // flOptions - fill mode // // Return Value: // // TRUE if successful, FALSE if there is an error ///////////////////////////////////////////////////////////////////////////// BOOL APIENTRY HPGLPaint( SURFOBJ *pso, CLIPOBJ *pco, BRUSHOBJ *pbo, POINTL *pptlBrushOrg, MIX mix ) { TERSE(("HPGLPaint() entry.\r\n")); PDEVOBJ pdevobj = (PDEVOBJ)pso->dhpdev; ASSERT(VALID_PDEVOBJ(pdevobj)); POEMPDEV poempdev = (POEMPDEV)pdevobj->pdevOEM; REQUIRE_VALID_DATA( poempdev, return FALSE); // // turn around to call Unidrv // return (((PFN_DrvPaint)(poempdev->pfnUnidrv[UD_DrvPaint])) ( pso, pco, pbo, pptlBrushOrg, mix)); } BOOL APIENTRY HPGLLineTo( SURFOBJ *pso, CLIPOBJ *pco, BRUSHOBJ *pbo, LONG x1, LONG y1, LONG x2, LONG y2, RECTL *prclBounds, MIX mix ) { TERSE(("HPGLLineTo() entry.\r\n")); PDEVOBJ pdevobj = (PDEVOBJ)pso->dhpdev; ASSERT(VALID_PDEVOBJ(pdevobj)); POEMPDEV poempdev = (POEMPDEV)pdevobj->pdevOEM; REQUIRE_VALID_DATA( poempdev, return FALSE); // // turn around to call Unidrv // return (((PFN_DrvLineTo)(poempdev->pfnUnidrv[UD_DrvLineTo])) ( pso, pco, pbo, x1, y1, x2, y2, prclBounds, mix)); }
27.868771
102
0.54676
[ "render", "object", "vector", "transform" ]
a2d3f24af282cc52199499b22a6c7b73e8dda3b4
3,938
hpp
C++
include/epiworld/userdata-meat.hpp
gvegayon/world-epi
197d8cc0e8fb86c06ec1ac2df6316e89d4857218
[ "MIT" ]
null
null
null
include/epiworld/userdata-meat.hpp
gvegayon/world-epi
197d8cc0e8fb86c06ec1ac2df6316e89d4857218
[ "MIT" ]
null
null
null
include/epiworld/userdata-meat.hpp
gvegayon/world-epi
197d8cc0e8fb86c06ec1ac2df6316e89d4857218
[ "MIT" ]
null
null
null
#ifndef EPIWORLD_USERDATA_MEAT_HPP #define EPIWORLD_USERDATA_MEAT_HPP template<typename TSeq> class UserData; template<typename TSeq> inline UserData<TSeq>::UserData(std::vector< std::string > names) { k = names.size(); data_names = names; } template<typename TSeq> inline void UserData<TSeq>::add(std::vector<epiworld_double> x) { if (x.size() != k) throw std::out_of_range( "The size of -x-, " + std::to_string(x.size()) + ", does not match " + "the number of elements registered (" + std::to_string(k)); for (auto & i : x) data_data.push_back(i); data_dates.push_back(model->today()); n++; last_day = model->today(); } template<typename TSeq> inline void UserData<TSeq>::add(unsigned int j, epiworld_double x) { // Starting with a new day? if (static_cast<int>(model->today()) != last_day) { std::vector< epiworld_double > tmp(k, 0.0); tmp[j] = x; add(tmp); } else { this->operator()(n - 1, j) = x; } } template<typename TSeq> inline std::vector< std::string > & UserData<TSeq>::get_names() { return data_names; } template<typename TSeq> inline std::vector< int > & UserData<TSeq>::get_dates() { return data_dates; } template<typename TSeq> inline std::vector< epiworld_double > & UserData<TSeq>::get_data() { return data_data; } template<typename TSeq> inline void UserData<TSeq>::get_all( std::vector< std::string > * names, std::vector< int > * dates, std::vector< epiworld_double > * data ) { if (names != nullptr) names = &this->data_names; if (dates != nullptr) dates = &this->data_dates; if (data != nullptr) data = &this->data_data; } template<typename TSeq> inline epiworld_double & UserData<TSeq>::operator()( unsigned int i, unsigned int j ) { if (j >= k) throw std::out_of_range("j cannot be greater than k - 1."); if (i >= n) throw std::out_of_range("j cannot be greater than n - 1."); return data_data[k * i + j]; } template<typename TSeq> inline epiworld_double & UserData<TSeq>::operator()( unsigned int i, std::string name ) { int loc = -1; for (unsigned int l = 0u; l < k; ++l) { if (name == data_names[l]) { loc = l; break; } } if (loc < 0) throw std::range_error( "The variable \"" + name + "\" is not present " + "in the user UserData database." ); return operator()(i, static_cast<unsigned int>(loc)); } template<typename TSeq> inline unsigned int UserData<TSeq>::nrow() const { return n; } template<typename TSeq> inline unsigned int UserData<TSeq>::ncol() const { return k; } template<typename TSeq> inline void UserData<TSeq>::write(std::string fn) { std::ofstream file_ud(fn, std::ios_base::out); // File header file_ud << "\"date\""; for (auto & cn : data_names) file_ud << " \"" + cn + "\""; file_ud << "\n"; unsigned int ndata = 0u; for (unsigned int i = 0u; i < n; ++i) { file_ud << data_dates[i]; for (unsigned int j = 0u; j < k; ++j) file_ud << " " << data_data[ndata++]; file_ud << "\n"; } return; } template<typename TSeq> inline void UserData<TSeq>::print() const { // File header printf_epiworld("Total records: %i\n", n); printf_epiworld("date"); for (auto & cn : data_names) { printf_epiworld(" %s", cn.c_str()); } printf_epiworld("\n"); unsigned int ndata = 0u; for (unsigned int i = 0u; i < n; ++i) { printf_epiworld("%i", data_dates[i]); for (unsigned int j = 0u; j < k; ++j) { printf_epiworld(" %.2f", data_data[ndata++]); } printf_epiworld("\n"); } return; } #endif
18.147465
82
0.568817
[ "vector", "model" ]
a2e19de72abc34889dc44e68b033b784b170be43
5,337
cpp
C++
relaxation/cutByDinic.cpp
napinoco/BBCPOP
7ba674da284ae7727b3385ef0f2036509da0c98d
[ "MIT" ]
1
2020-02-06T15:17:56.000Z
2020-02-06T15:17:56.000Z
relaxation/cutByDinic.cpp
napinoco/BBCPOP
7ba674da284ae7727b3385ef0f2036509da0c98d
[ "MIT" ]
null
null
null
relaxation/cutByDinic.cpp
napinoco/BBCPOP
7ba674da284ae7727b3385ef0f2036509da0c98d
[ "MIT" ]
1
2020-02-06T15:17:55.000Z
2020-02-06T15:17:55.000Z
#include <vector> #include <limits> #include <queue> #include <string.h> // #include <iostream> #include "mex.h" #include "matrix.h" const int INF = std::numeric_limits<int>::max(); struct edge { int to; double cap; int rev; }; // rev-id typedef std::vector<edge> edges; typedef std::vector<edges> graph; void add_edge(graph &G, int from, int to, double cap) { G[from].push_back((edge){to, cap, (int)G[to].size()}); G[to].push_back((edge){from, 0, (int)G[from].size() - 1 }); } void compute_min_dist_by_bfs(graph &G, int *level, int s) { memset(level, -1, sizeof(int) * G.size()); std::queue<int> que; level[s] = 0; que.push(s); while (!que.empty()) { int v = que.front(); que.pop(); for (int i = 0; i < G[v].size(); i++) { edge &e = G[v][i]; if (e.cap > 0 && level[e.to] < 0) { level[e.to] = level[v] + 1; que.push(e.to); } } } } double find_augment_path_by_dfs(graph &G, int *level, int *iter, int v, int t, double f) { if (v == t) return f; for (int &i = iter[v]; i < G[v].size(); i++){ edge &e = G[v][i]; if (e.cap > 0 && level[v] < level[e.to]) { double d = find_augment_path_by_dfs(G, level, iter, e.to, t, std::min(f, e.cap)); if (d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } double max_flow(graph &G, int s, int t) { double flow = 0; int n = G.size(); int *level = new int[n]; int *iter = new int[n]; for (;;) { compute_min_dist_by_bfs(G, level, s); if (level[t] < 0) { delete[] level; delete[] iter; return flow; } memset(iter, 0, sizeof(int) * n); double f; while ((f = find_augment_path_by_dfs(G, level, iter, s, t, INF)) > 0) { flow += f; } } } void check_reachability_from(graph &G, bool *reachable, int s) { memset(reachable, false, sizeof(bool) * G.size()); std::queue<int> que; reachable[s] = true; que.push(s); while (!que.empty()) { int v = que.front(); que.pop(); for (int i = 0; i < G[v].size(); i++) { edge &e = G[v][i]; if (e.cap > 0 && !reachable[e.to]) { reachable[e.to] = true; que.push(e.to); } } } } void check_reachability_to(graph &G, bool *reachable, int t) { memset(reachable, false, sizeof(bool) * G.size()); std::queue<int> que; reachable[t] = true; que.push(t); while (!que.empty()) { int v = que.front(); que.pop(); for (int i = 0; i < G[v].size(); i++) { edge &e = G[v][i]; if (G[e.to][e.rev].cap > 0 && !reachable[e.to]) { reachable[e.to] = true; que.push(e.to); } } } } double min_cut(graph &G, bool *reachable, int s, int t) { double f; f = max_flow(G, s, t); check_reachability_to(G, reachable, t); return f; } // int main(){ // int MAX_V = 5; // graph G(MAX_V); // int s = 0; // int t = 4; // add_edge(G, 0, 1, 10); // add_edge(G, 0, 2, 2); // add_edge(G, 1, 2, 6); // add_edge(G, 1, 3, 6); // add_edge(G, 3, 2, 3); // add_edge(G, 2, 4, 5); // add_edge(G, 3, 4, 8); // // bool *reachable = new bool[MAX_V]; // // std::cout << min_cut(G, reachable, s, t) << std::endl; // for (int i = 0; i < MAX_V; i++) { // std::cout << reachable[i]; // } // std::cout << std::endl; // delete[] reachable; // return 0; // } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { /* CHECK FOR PROPER NUMBER OF ARGUMENTS */ if (nrhs != 3) { mexErrMsgTxt("[val, Z] = cutByDinic(CapacityMat, s, t) requires 3 input arguments."); } if (nlhs != 2) { mexErrMsgTxt("[val, Z] = cutByDinic(CapacityMat, s, t) requires 2 output arguments."); } /* Check the proper input type */ if (!mxIsSparse(prhs[0])) { mexErrMsgTxt("CoapacityMat must be sparse"); } // if (!mxIsScalar(prhs[1]) || !mxIsScalar(prhs[2])) { mexErrMsgTxt("s and t must be scalar."); } if (!(mxGetM(prhs[1]) == 1) || !(mxGetM(prhs[2]) == 1) || !(mxGetN(prhs[1]) == 1) || !(mxGetN(prhs[2]) == 1)) { mexErrMsgTxt("s and t must be scalar."); } /* Read inputs */ mwSize m = mxGetM(prhs[0]); mwSize n = mxGetN(prhs[0]); if (m != n) {mexErrMsgTxt("CapacityMat must be square.");} //double *CapacityMat = mxGetPr(prhs[0]); double *pr = mxGetPr(prhs[0]); mwIndex *jc = mxGetJc(prhs[0]); mwIndex *ir = mxGetIr(prhs[0]); graph G(n); for (mwIndex j = 0; j < n; j++) { for (mwIndex k = jc[j]; k < jc[j+1]; k++) { mwIndex i = ir[k]; double capacity = pr[k]; //g[i].push_back(Edge(i , j, capacity)); add_edge(G, i, j, capacity); } } mwIndex s = (mwIndex)mxGetScalar(prhs[1])-1; mwIndex t = (mwIndex)mxGetScalar(prhs[2])-1; /* Allocate space for output vector */ plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); plhs[1] = mxCreateLogicalMatrix(1, n); double *val = mxGetPr(plhs[0]); bool *Z = mxGetLogicals(plhs[1]); /* solve */ *val = min_cut(G, Z, s, t); }
28.388298
109
0.50609
[ "vector" ]
a2e6399de9b0ed07f01ca2e118fef19273739d2c
7,864
hh
C++
include/chainhash.hh
mit-pdos/sv6
f2283fbabf432c476ba3b9ec955a24ea675df607
[ "MIT-0" ]
21
2017-11-02T07:40:50.000Z
2022-03-10T14:09:54.000Z
include/chainhash.hh
mit-pdos/sv6
f2283fbabf432c476ba3b9ec955a24ea675df607
[ "MIT-0" ]
null
null
null
include/chainhash.hh
mit-pdos/sv6
f2283fbabf432c476ba3b9ec955a24ea675df607
[ "MIT-0" ]
5
2017-11-21T21:51:18.000Z
2018-12-24T21:35:41.000Z
#pragma once /* * A bucket-chaining hash table. */ #include "spinlock.hh" #include "seqlock.hh" #include "lockwrap.hh" #include "hash.hh" #include "ilist.hh" #include "hpet.hh" #include "cpuid.hh" template<class K, class V> class chainhash { private: struct item : public rcu_freed { item(const K& k, const V& v) : rcu_freed("chainhash::item", this, sizeof(*this)), key(k), val(v) {} void do_gc() override { delete this; } NEW_DELETE_OPS(item); islink<item> link; seqcount<u32> seq; const K key; V val; }; struct bucket { spinlock lock __mpalign__; islist<item, &item::link> chain; ~bucket() { while (!chain.empty()) { item *i = &chain.front(); chain.pop_front(); gc_delayed(i); } } }; u64 nbuckets_; bool dead_; bucket* buckets_; public: chainhash(u64 nbuckets) : nbuckets_(nbuckets), dead_(false) { buckets_ = new bucket[nbuckets_]; assert(buckets_); } ~chainhash() { delete[] buckets_; } NEW_DELETE_OPS(chainhash); bool insert(const K& k, const V& v, u64 *tsc = NULL) { if (dead_ || lookup(k)) return false; bucket* b = &buckets_[hash(k) % nbuckets_]; scoped_acquire l(&b->lock); if (dead_) return false; for (const item& i: b->chain) if (i.key == k) return false; b->chain.push_front(new item(k, v)); if (tsc) *tsc = get_tsc(); return true; } bool remove(const K& k, const V& v, u64 *tsc = NULL) { if (!lookup(k)) return false; bucket* b = &buckets_[hash(k) % nbuckets_]; scoped_acquire l(&b->lock); auto i = b->chain.before_begin(); auto end = b->chain.end(); for (;;) { auto prev = i; ++i; if (i == end) return false; if (i->key == k && i->val == v) { b->chain.erase_after(prev); gc_delayed(&*i); if (tsc) *tsc = get_tsc(); return true; } } } bool remove(const K& k, u64 *tsc = NULL) { if (!lookup(k)) return false; bucket* b = &buckets_[hash(k) % nbuckets_]; scoped_acquire l(&b->lock); auto i = b->chain.before_begin(); auto end = b->chain.end(); for (;;) { auto prev = i; ++i; if (i == end) return false; if (i->key == k) { b->chain.erase_after(prev); gc_delayed(&*i); if (tsc) *tsc = get_tsc(); return true; } } } bool replace_from(const K& kdst, const V* vpdst, chainhash* src, const K& ksrc, const V& vsrc, chainhash *subdir, const K& ksubdir, const V& vsubdir, u64 *tsc = NULL) { /* * A special API used by rename. Atomically performs the following * steps, returning false if any of the checks fail: * * For file renames: * - checks that this hash table has not been killed (by unlink) * - if vpdst!=nullptr, checks this[kdst]==*vpdst * - if vpdst==nullptr, checks this[kdst] is not set * - checks src[ksrc]==vsrc * - removes src[ksrc] * - sets this[kdst] = vsrc * * For directory renames (i.e., subdir != nullptr), in addition to the * above: * - checks that subdir's hash table has not been killed (by unlink) * - sets subdir[ksubdir] = vsubdir * - TODO: Also deal with the directory that was replaced from the * destination directory by subdir. */ bucket* bdst = &buckets_[hash(kdst) % nbuckets_]; bucket* bsrc = &src->buckets_[hash(ksrc) % src->nbuckets_]; bucket* bsubdir = subdir ? (&subdir->buckets_[hash(ksubdir) % subdir->nbuckets_]) : nullptr; // Acquire the locks for the source, destination and the subdir directory // hash tables in the order of increasing bucket addresses. scoped_acquire lk[3]; std::vector<bucket*> buckets; if (bsubdir != nullptr && bsubdir != bsrc && bsubdir != bdst) buckets.push_back(bsubdir); if (bsrc != bdst) buckets.push_back(bsrc); buckets.push_back(bdst); std::sort(buckets.begin(), buckets.end()); int i = 0; for (auto &b : buckets) lk[i++] = b->lock.guard(); /* * Abort the rename if the destination directory's hash table has been * killed by a concurrent unlink. */ if (killed()) return false; if (subdir && subdir->killed()) return false; auto srci = bsrc->chain.before_begin(); auto srcend = bsrc->chain.end(); auto srcprev = srci; for (;;) { ++srci; if (srci == srcend) return false; if (srci->key != ksrc) { srcprev = srci; continue; } if (srci->val != vsrc) return false; break; } for (item& i: bdst->chain) { if (i.key == kdst) { if (vpdst == nullptr || i.val != *vpdst) return false; auto w = i.seq.write_begin(); i.val = vsrc; bsrc->chain.erase_after(srcprev); gc_delayed(&*srci); if (bsubdir != nullptr) { for (item& isubdir : bsubdir->chain) { if (isubdir.key == ksubdir) { auto wsubdir = isubdir.seq.write_begin(); isubdir.val = vsubdir; } } } if (tsc) *tsc = get_tsc(); return true; } } if (vpdst != nullptr) return false; bsrc->chain.erase_after(srcprev); gc_delayed(&*srci); bdst->chain.push_front(new item(kdst, vsrc)); if (bsubdir != nullptr) { for (item& isubdir : bsubdir->chain) { if (isubdir.key == ksubdir) { auto wsubdir = isubdir.seq.write_begin(); isubdir.val = vsubdir; } } } if (tsc) *tsc = get_tsc(); return true; } bool enumerate(const K* prev, K* out) const { scoped_gc_epoch rcu_read; bool prevbucket = (prev != nullptr); for (u64 i = prev ? hash(*prev) % nbuckets_ : 0; i < nbuckets_; i++) { bucket* b = &buckets_[i]; bool found = false; for (const item& i: b->chain) { if ((!prevbucket || *prev < i.key) && (!found || i.key < *out)) { *out = i.key; found = true; } } if (found) return true; prevbucket = false; } return false; } template<class CB> void enumerate(CB cb) const { scoped_gc_epoch rcu_read; for (u64 i = 0; i < nbuckets_; i++) { bucket* b = &buckets_[i]; for (const item& i: b->chain) { V val = *seq_reader<V>(&i.val, &i.seq); if (cb(i.key, val)) return; } } } bool lookup(const K& k, V* vptr = nullptr) const { scoped_gc_epoch rcu_read; bucket* b = &buckets_[hash(k) % nbuckets_]; for (const item& i: b->chain) { if (i.key != k) continue; if (vptr) *vptr = *seq_reader<V>(&i.val, &i.seq); return true; } return false; } bool remove_and_kill(const K& k, const V& v) { if (dead_) return false; for (u64 i = 0; i < nbuckets_; i++) for (const item& ii: buckets_[i].chain) if (ii.key != k || ii.val != v) return false; for (u64 i = 0; i < nbuckets_; i++) buckets_[i].lock.acquire(); bool killed = !dead_; for (u64 i = 0; i < nbuckets_; i++) for (const item& ii: buckets_[i].chain) if (ii.key != k || ii.val != v) killed = false; if (killed) { dead_ = true; bucket* b = &buckets_[hash(k) % nbuckets_]; item* i = &b->chain.front(); assert(i->key == k && i->val == v); b->chain.pop_front(); gc_delayed(i); } for (u64 i = 0; i < nbuckets_; i++) buckets_[i].lock.release(); return killed; } bool killed() const { return dead_; } };
23.758308
77
0.532172
[ "vector" ]
a2e85998e696f3c6d8b734151ab3d863982fc935
5,134
hpp
C++
affinity.hpp
0400H/thread-pool
922c4041d6b575cdcd6391d035ab372e64dc8388
[ "MIT" ]
null
null
null
affinity.hpp
0400H/thread-pool
922c4041d6b575cdcd6391d035ab372e64dc8388
[ "MIT" ]
null
null
null
affinity.hpp
0400H/thread-pool
922c4041d6b575cdcd6391d035ab372e64dc8388
[ "MIT" ]
null
null
null
#pragma once #ifndef __HPC_AFFINITY_HPP__ #define __HPC_AFFINITY_HPP__ #include "cpu.hpp" namespace hpc { std::vector<int> cal_parallel_cores(bool affinity=true) { std::vector<int> cores; if (affinity) { return get_thread_affinity(false); } else { auto hardware_concurrency = get_hardware_concurrency(); for (auto i = 0; i < hardware_concurrency; i++) { cores.emplace_back(i); } } return cores; } std::size_t cal_thread_num(int thread_num, int core_num) { if (thread_num < 0 || thread_num > MAX_THREADS) { throw std::exception(); } else if (thread_num == 0){ return core_num; } else { return thread_num; } } std::size_t cal_stream_num(int stream_num) { return stream_num != 0 ? stream_num : get_hardware_sockets(); } std::vector<std::vector<int>> cal_thread_affinity( int thread_num, std::vector<int>& cores) { std::vector<std::vector<int>> thread_affinity(thread_num, std::vector<int>({})); auto core_num = cores.size(); if (thread_num <= core_num) { int tail_cores_per_thread = core_num / thread_num; int head_cores_per_thread = tail_cores_per_thread + 1; int head_thread_num = core_num % thread_num; // std::cout << head_thread_num << ", " << head_cores_per_thread << ", " << tail_cores_per_thread << std::endl; int thread_idx = 0, core_idx = 0; for (; thread_idx < head_thread_num; thread_idx++) { auto core_stop = core_idx + head_cores_per_thread; for (; core_idx < core_stop; core_idx++) { thread_affinity[thread_idx].emplace_back(core_idx); } } for (; thread_idx < thread_num; thread_idx++) { auto core_stop = core_idx + tail_cores_per_thread; for (; core_idx < core_stop; core_idx++) { thread_affinity[thread_idx].emplace_back(core_idx); } } } else { int tail_thread_per_cores = thread_num / core_num; int head_thread_per_cores = tail_thread_per_cores + 1; int head_thread_num = (thread_num % core_num) * head_thread_per_cores; // std::cout << head_thread_num << ", " << head_thread_per_cores << ", " << tail_thread_per_cores << std::endl; int thread_idx = 0, core_idx = 0; for (; thread_idx < head_thread_num; thread_idx++) { thread_affinity[thread_idx].emplace_back(core_idx); if (thread_idx % head_thread_per_cores == head_thread_per_cores-1) { core_idx++; }; } for (; thread_idx < thread_num; thread_idx++) { thread_affinity[thread_idx].emplace_back(core_idx); if ((thread_idx-head_thread_num) % tail_thread_per_cores == tail_thread_per_cores-1) { core_idx++; }; } } for (auto i = 0; i < thread_affinity.size(); i++) { for (auto j = 0; j < thread_affinity[i].size(); j++) { thread_affinity[i][j] = cores[thread_affinity[i][j]]; } } return thread_affinity; } std::vector<std::vector<std::vector<int>>> cal_streams_affinity( int streams, int threads, bool affinity, bool verbose) { auto cores = cal_parallel_cores(affinity); auto cores_num = cores.size(); auto thread_num = cal_thread_num(threads, cores_num); auto stream_num = cal_stream_num(streams); std::vector<std::vector<int>> thread_affinity = cal_thread_affinity(thread_num, cores); int threads_per_stream = thread_num / stream_num; int threads_tail = thread_num % stream_num; std::vector<std::vector<std::vector<int>>> streams_affinity; auto thread_idx = 0; for (auto i = 0; i < stream_num; i++) { thread_idx = i * threads_per_stream; std::vector<std::vector<int>> threads_affinity; for (; thread_idx < (i+1)*threads_per_stream; thread_idx++) { threads_affinity.emplace_back(thread_affinity[thread_idx]); } streams_affinity.emplace_back(threads_affinity); } for (; thread_idx < thread_num; thread_idx++) { streams_affinity[stream_num-1].emplace_back(thread_affinity[thread_idx]); } if (verbose) { for (auto stream : streams_affinity) { std::cout << "stream affinity cores {"; for (auto thread : stream) { std::cout << "["; for (auto core : thread) { std::cout << core << ","; } std::cout << "],"; } std::cout << "}," << std::endl; } } return streams_affinity; } } #endif // __HPC_AFFINITY_HPP__
36.671429
123
0.552006
[ "vector" ]
a2ff1a1a5f2d6b630230e9c73018fdcb8b9c1410
4,444
cpp
C++
tc 160+/ChangePurse.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/ChangePurse.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/ChangePurse.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> #include <utility> #include <functional> using namespace std; class ChangePurse { public: vector <int> optimalCoins(vector <int> coinTypes, int value) { vector< pair<int, int> > v; for (int i=0; i<(int)coinTypes.size(); ++i) v.push_back(make_pair(coinTypes[i], i)); sort(v.begin(), v.end(), greater< pair<int, int> >()); vector<int> cnt(v.size(), 0); for (int i=0; i<(int)v.size(); ++i) if ((value+1)%v[i].first == 0) { cnt[i] = (value+1)/v[i].first - 1; value = v[i].first-1; } vector<int> sol(v.size(), 0); for (int i=0; i<(int)v.size(); ++i) sol[v[i].second] = cnt[i]; return sol; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } } void test_case_0() { int Arr0[] = {1,25,10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 49; int Arr2[] = { 24, 1, 0 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(0, Arg2, optimalCoins(Arg0, Arg1)); } void test_case_1() { int Arr0[] = {1,7}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 49; int Arr2[] = { 49, 0 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(1, Arg2, optimalCoins(Arg0, Arg1)); } void test_case_2() { int Arr0[] = {11,5,10,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 109; int Arr2[] = { 9, 0, 0, 10 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(2, Arg2, optimalCoins(Arg0, Arg1)); } void test_case_3() { int Arr0[] = {29210, 58420, 350520, 708072, 720035, 230, 42355, 1, 59006, 985, 236024, 163, 701040}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 929579039; int Arr2[] = { 1, 5, 1, 0, 0, 126, 0, 229, 0, 0, 0, 0, 1325 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(3, Arg2, optimalCoins(Arg0, Arg1)); } void test_case_4() { int Arr0[] = {795, 5536, 26, 915, 18590, 60840, 49140, 2, 119700, 162235, 369000, 383936, 478800, 505995, 949, 95984, 455, 8, 420, 239400, 276800, 191968, 619305, 654810, 706420, 393120, 738000, 767872, 425880, 786240, 830400, 676, 4500, 851760, 957600, 648940, 1, 112, 180, 457}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 687245439; int Arr2[] = { 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 1, 0, 13, 0, 0, 0, 1, 0, 0, 0, 0, 0, 894, 0, 0, 0, 0, 0, 0, 0, 0, 1, 856, 0, 0 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(4, Arg2, optimalCoins(Arg0, Arg1)); } void test_case_5() { int Arr0[] = {494208, 722376, 731798, 809064, 920448, 1, 988416, 9152, 158, 991014, 282720, 40132, 608, 143, 289755, 734, 579510, 828400, 330338, 816, 460224, 27456, 675783, 331, 436, 82368, 729, 306, 202266, 247104, 414200, 705}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 419088383; int Arr2[] = { 1, 0, 0, 0, 0, 142, 423, 2, 0, 0, 0, 0, 0, 63, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(5, Arg2, optimalCoins(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { ChangePurse ___test; ___test.run_test(-1); } // END CUT HERE
56.974359
413
0.577633
[ "vector" ]
0c0467e1c9de3ed33f426de3012f824492627bfa
3,741
cpp
C++
Software_Final Version/build-Inertial_Navigation_with_QT-Desktop_Qt_5_14_2_MinGW_64_bit-Debug/debug/moc_about_window.cpp
GimHuang/inertial-navigation
88c7aea844c26b5a2b7a2314ba4ca428c532d8f6
[ "MIT" ]
2
2021-05-30T18:17:17.000Z
2021-11-24T07:16:49.000Z
Software_Final Version/build-Inertial_Navigation_with_QT-Desktop_Qt_5_14_2_MinGW_64_bit-Debug/debug/moc_about_window.cpp
jhuang-86/inertial-navigation
88c7aea844c26b5a2b7a2314ba4ca428c532d8f6
[ "MIT" ]
null
null
null
Software_Final Version/build-Inertial_Navigation_with_QT-Desktop_Qt_5_14_2_MinGW_64_bit-Debug/debug/moc_about_window.cpp
jhuang-86/inertial-navigation
88c7aea844c26b5a2b7a2314ba4ca428c532d8f6
[ "MIT" ]
4
2021-04-16T08:51:59.000Z
2021-12-31T01:13:08.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'about_window.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../../Inertial_Navigation_with_QT/about_window.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'about_window.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.14.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_about_window_t { QByteArrayData data[4]; char stringdata0[60]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_about_window_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_about_window_t qt_meta_stringdata_about_window = { { QT_MOC_LITERAL(0, 0, 12), // "about_window" QT_MOC_LITERAL(1, 13, 23), // "on_pushButton_2_clicked" QT_MOC_LITERAL(2, 37, 0), // "" QT_MOC_LITERAL(3, 38, 21) // "on_pushButton_clicked" }, "about_window\0on_pushButton_2_clicked\0" "\0on_pushButton_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_about_window[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 24, 2, 0x08 /* Private */, 3, 0, 25, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, 0 // eod }; void about_window::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<about_window *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_pushButton_2_clicked(); break; case 1: _t->on_pushButton_clicked(); break; default: ; } } Q_UNUSED(_a); } QT_INIT_METAOBJECT const QMetaObject about_window::staticMetaObject = { { QMetaObject::SuperData::link<QMainWindow::staticMetaObject>(), qt_meta_stringdata_about_window.data, qt_meta_data_about_window, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *about_window::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *about_window::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_about_window.stringdata0)) return static_cast<void*>(this); return QMainWindow::qt_metacast(_clname); } int about_window::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
29.928
96
0.632184
[ "object" ]
0c09bdbe9683f73e507be6ce8aa7a7409ddd84bf
12,578
cpp
C++
DejaVuGUI.cpp
adamk33n3r/Deja-Vu
d65e73b03a10fb2be5e92512721295f2ae74934f
[ "MIT" ]
2
2021-02-08T06:39:57.000Z
2021-11-03T16:16:08.000Z
DejaVuGUI.cpp
adamk33n3r/Deja-Vu
d65e73b03a10fb2be5e92512721295f2ae74934f
[ "MIT" ]
6
2020-02-02T06:58:07.000Z
2021-11-12T16:29:39.000Z
DejaVuGUI.cpp
adamk33n3r/Deja-Vu
d65e73b03a10fb2be5e92512721295f2ae74934f
[ "MIT" ]
2
2021-01-30T04:08:38.000Z
2021-03-06T09:59:05.000Z
#include "pch.h" #include "DejaVu.h" #include "vendor/imgui/imgui.h" #include "vendor/imgui/imgui_stdlib.h" #undef max void DejaVu::Render() { if (!this->isWindowOpen) { cvarManager->executeCommand("togglemenu " + GetMenuName()); return; } if (this->openQuickNote) { #if DEV std::set<std::string> matchMetList = { "0" }; if (this->curMatchGUID.has_value()) matchMetList = this->matchesMetLists[this->curMatchGUID.value()]; #else if (!this->curMatchGUID.has_value()) { LOG(INFO) << "Closing quick note because there is no match guid"; this->openQuickNote = false; return; } const std::set<std::string>& matchMetList = this->matchesMetLists[this->curMatchGUID.value()]; #endif DEV ImGui::OpenPopup("Quick Note"); ImGui::SetNextWindowSize(ImVec2(ImGui::GetIO().DisplaySize.x / 2, ImGui::GetIO().DisplaySize.y / 4), ImGuiCond_Appearing); if (ImGui::BeginPopupModal("Quick Note")) { float reserveHeight = ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().FramePadding.y * 2; ImGui::BeginChild("#dejavu_quick_note", ImVec2(0, -reserveHeight)); ImGui::Columns(2, "Quick Note Edit"); ImGui::SetColumnWidth(0, std::max(ImGui::GetColumnWidth(0), 200.0f)); ImGui::Separator(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Player Note"); ImGui::NextColumn(); ImGui::Separator(); for (const auto& uniqueID : matchMetList) { auto& playerData = this->data["players"][uniqueID]; ImGui::Text(playerData["name"].get<std::string>().c_str()); ImGui::NextColumn(); float buttonPos = ImGui::GetCursorPosX() + ImGui::GetColumnWidth() - ImGui::GetScrollX() - 2 * ImGui::GetStyle().ItemSpacing.x; if (!playerData.contains("note")) playerData["note"] = ""; float buttonWidth = 2 * ImGui::GetStyle().FramePadding.x + ImGui::CalcTextSize("Edit").x; ImGui::BeginChild((std::string("#note") + uniqueID).c_str(), ImVec2(ImGui::GetColumnWidth() - buttonWidth - 2 * ImGui::GetStyle().ItemSpacing.x, ImGui::GetFrameHeightWithSpacing()), false, ImGuiWindowFlags_NoScrollbar); ImGui::TextWrapped(playerData["note"].get<std::string>().c_str()); ImGui::EndChild(); ImGui::SameLine(); ImGui::SetCursorPosX(buttonPos - buttonWidth); if (ImGui::Button((std::string("Edit##") + uniqueID).c_str(), ImVec2(0, ImGui::GetFrameHeightWithSpacing()))) { ImGui::OpenPopup("Edit note"); this->playersNoteToEdit = uniqueID; } ImGui::NextColumn(); } RenderEditNoteModal(); ImGui::EndChild(); int escIdx = ImGui::GetIO().KeyMap[ImGuiKey_Escape]; if (ImGui::Button("Close", ImVec2(120, 0)) || (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && escIdx >= 0 && ImGui::IsKeyPressed(escIdx))) { this->openQuickNote = false; ImGui::CloseCurrentPopup(); CloseMenu(); } ImGui::EndPopup(); } this->shouldBlockInput = ImGui::GetIO().WantCaptureMouse || ImGui::GetIO().WantCaptureKeyboard; return; } //ImGui::SetNextWindowPos(ImVec2(100, 100), ImGuiCond_FirstUseEver); //ImGui::SetNextWindowSize(ImVec2(256, 384), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSizeConstraints(ImVec2(55 + 250 + 55 + 250 + 80 + 100, 600), ImVec2(FLT_MAX, FLT_MAX)); ImGuiWindowFlags windowFlags = 0 | ImGuiWindowFlags_MenuBar //| ImGuiWindowFlags_NoCollapse ; if (!ImGui::Begin(GetMenuTitle().c_str(), &this->isWindowOpen, windowFlags)) { // Early out if the window is collapsed, as an optimization. this->shouldBlockInput = ImGui::GetIO().WantCaptureMouse || ImGui::GetIO().WantCaptureKeyboard; ImGui::End(); return; } //ImGui::SetNextWindowSizeConstraints(ImVec2(55 + 250 + 55 + 250 + 80 + 100, 600), ImVec2(FLT_MAX, FLT_MAX)); //ImGui::Begin(menuTitle.c_str(), &isWindowOpen, ImGuiWindowFlags_NoCollapse); //const char* playlists[] = {"asdf", "fff"}; static const char* items[]{"Apple", "Banana", "Orange"}; static Playlist selectedPlaylist = Playlist::ANY; //ImGui::ListBox("Fruit", &this->gui_selectedPlaylist, this->playlists, 2); //ImGui::ListBox("Playlist Filter", &this->gui_selectedPlaylist, this->playlists, IM_ARRAYSIZE(this->playlists)); //ImGui::Combo("Playlist Filter", &this->gui_selectedPlaylist, this->playlists, IM_ARRAYSIZE(this->playlists)); const char* preview = (selectedPlaylist != Playlist::ANY) ? PlaylistNames[selectedPlaylist].c_str() : "Select..."; if (ImGui::BeginCombo("Playlist Filter", preview)) { for (auto it = PlaylistNames.begin(); it != PlaylistNames.end(); ++it) { bool isSelected = selectedPlaylist == it->first; if (ImGui::Selectable(it->second.c_str(), isSelected)) selectedPlaylist = it->first; if (isSelected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } static char nameFilter[65] = ""; ImGui::InputText("Name", nameFilter, IM_ARRAYSIZE(nameFilter), ImGuiInputTextFlags_AutoSelectAll); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); ImGui::BeginChild("#DejaVuDataDisplay", ImVec2(0, ImGui::GetTextLineHeight() + ImGui::GetStyle().ItemSpacing.y * 2 + ImGui::GetStyle().FramePadding.y), false, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysUseWindowPadding); //ImGui::ListBoxHeader() ImGui::Columns(5, "dejavu_stats"); //ImGui::SetColumnWidth(0, 55); //ImGui::SetColumnWidth(1, 250); //ImGui::SetColumnWidth(2, 55); //ImGui::SetColumnWidth(3, 250); //ImGui::SetColumnWidth(4, 55); ImGui::Separator(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Met Count"); ImGui::NextColumn(); ImGui::Text("Total Record With"); ImGui::NextColumn(); ImGui::Text("Total Record Against"); ImGui::NextColumn(); ImGui::Text("Player Note"); ImGui::NextColumn(); ImGui::Separator(); ImGui::EndChild(); //ImGui::SetCursorPosY(ImGui::GetCursorPosY() - ImGui::GetStyle().WindowPadding.y); ImGui::BeginChild("#DejaVuDataDisplayBody", ImVec2(0, 0), false, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysUseWindowPadding); ImGui::Columns(5, "dejavu_stats_body"); ImGui::Separator(); std::string selectedPlaylistIDStr = std::to_string(static_cast<int>(selectedPlaylist)); auto nameFilterView = std::string_view(nameFilter); int i = 0; this->playerIDsToDisplay.resize(this->data["players"].size()); for (auto& player : this->data["players"].items()) { if (selectedPlaylist != Playlist::ANY && (!player.value()["playlistData"].contains(selectedPlaylistIDStr) || player.value()["playlistData"][selectedPlaylistIDStr]["records"].is_null())) continue; std::string name; try { name = player.value()["name"].get<std::string>(); } catch (const std::exception& e) { this->gameWrapper->Toast("DejaVu Error", "Check console/log for details"); this->cvarManager->log(e.what()); LOG(INFO) << e.what(); continue; } bool nameFound = std::search(name.begin(), name.end(), nameFilterView.begin(), nameFilterView.end(), [](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); }) == name.end(); if (nameFilterView.size() > 0 && nameFound) continue; this->playerIDsToDisplay[i++] = player.key(); } this->playerIDsToDisplay.resize(i); ImGuiListClipper clipper((int)this->playerIDsToDisplay.size()); while (clipper.Step()) { for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { std::string uniqueID = this->playerIDsToDisplay[i]; auto& playerData = this->data["players"][uniqueID]; int metCount = playerData["metCount"].get<int>(); std::string name = playerData["name"].get<std::string>(); auto sameRecord = GetRecord(uniqueID, selectedPlaylist, Side::Same); auto otherRecord = GetRecord(uniqueID, selectedPlaylist, Side::Other); ImGui::Text(name.c_str()); ImGui::NextColumn(); ImGui::Text(std::to_string(metCount).c_str()); ImGui::NextColumn(); std::ostringstream sameRecordFormatted; sameRecordFormatted << sameRecord.wins << ":" << sameRecord.losses; ImGui::Text(sameRecordFormatted.str().c_str()); ImGui::NextColumn(); std::ostringstream otherRecordFormatted; otherRecordFormatted << otherRecord.wins << ":" << otherRecord.losses; ImGui::Text(otherRecordFormatted.str().c_str()); ImGui::NextColumn(); float buttonPos = ImGui::GetCursorPosX() + ImGui::GetColumnWidth() - ImGui::GetScrollX() - 2 * ImGui::GetStyle().ItemSpacing.x; if (!playerData.contains("note")) playerData["note"] = ""; float buttonWidth = 2 * ImGui::GetStyle().FramePadding.x + ImGui::CalcTextSize("Edit").x; ImGui::BeginChild((std::string("#note") + uniqueID).c_str(), ImVec2(ImGui::GetColumnWidth() - buttonWidth - 2 * ImGui::GetStyle().ItemSpacing.x, ImGui::GetFrameHeightWithSpacing()), false, ImGuiWindowFlags_NoScrollbar); ImGui::TextWrapped(playerData["note"].get<std::string>().c_str()); ImGui::EndChild(); ImGui::SameLine(); ImGui::SetCursorPosX(buttonPos - buttonWidth); if (ImGui::Button((std::string("Edit##") + uniqueID).c_str(), ImVec2(0, ImGui::GetFrameHeightWithSpacing()))) { ImGui::OpenPopup("Edit note"); this->playersNoteToEdit = uniqueID; } ImGui::NextColumn(); ImGui::Separator(); } } RenderEditNoteModal(); //if (ImGui::BeginMenuBar()) //{ // if (ImGui::BeginMenu("File")) // { // if (ImGui::MenuItem("Open..", "Ctrl+O")) { /* Do stuff */ } // if (ImGui::MenuItem("Save", "Ctrl+S")) { /* Do stuff */ } // if (ImGui::MenuItem("Close", "Ctrl+W")) { this->isWindowOpen = false; } // ImGui::EndMenu(); // } // ImGui::EndMenuBar(); //} ImGui::PopStyleVar(); ImGui::EndChild(); this->shouldBlockInput = ImGui::GetIO().WantCaptureMouse || ImGui::GetIO().WantCaptureKeyboard; ImGui::End(); } void DejaVu::RenderEditNoteModal() { ImGui::SetNextWindowSize(ImVec2(ImGui::GetIO().DisplaySize.x / 3, ImGui::GetIO().DisplaySize.y / 3), ImGuiCond_Appearing); if (ImGui::BeginPopupModal("Edit note")) { if (this->playersNoteToEdit.empty()) { ImGui::CloseCurrentPopup(); } else { json::value_type playerData = this->data["players"][this->playersNoteToEdit]; if (!playerData.contains("note")) playerData["note"] = ""; auto playerNote = playerData["note"].get_ptr<std::string*>(); ImVec2 textSize( ImGui::GetWindowWidth() - 2 * ImGui::GetStyle().WindowPadding.x, ImGui::GetWindowHeight() - 2 * ImGui::GetStyle().WindowPadding.y - ImGui::GetTextLineHeightWithSpacing() - 4 * ImGui::GetStyle().FramePadding.y - 4 * ImGui::GetStyle().ItemSpacing.y ); if (ImGui::InputTextMultiline("##note", playerNote, textSize)) { this->data["players"][this->playersNoteToEdit]["note"] = *playerNote; auto blueMember = std::find_if(this->blueTeamRenderData.begin(), this->blueTeamRenderData.end(), [this](const RenderData& renderData) { return renderData.id == this->playersNoteToEdit; }); if (blueMember != this->blueTeamRenderData.end()) (*blueMember).note = *playerNote; else { auto orangeMember = std::find_if(this->orangeTeamRenderData.begin(), this->orangeTeamRenderData.end(), [this](const RenderData& renderData) { return renderData.id == this->playersNoteToEdit; }); if (orangeMember != this->orangeTeamRenderData.end()) (*orangeMember).note = *playerNote; } } if (ImGui::IsWindowAppearing()) ImGui::SetKeyboardFocusHere(); int escIdx = ImGui::GetIO().KeyMap[ImGuiKey_Escape]; if (ImGui::Button("OK", ImVec2(120, 0)) || (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && escIdx >= 0 && ImGui::IsKeyPressed(escIdx))) ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } std::string DejaVu::GetMenuName() { return "dejavu"; } std::string DejaVu::GetMenuTitle() { return this->menuTitle; } void DejaVu::SetImGuiContext(uintptr_t ctx) { ImGui::SetCurrentContext(reinterpret_cast<ImGuiContext*>(ctx)); ImGui::GetIO().ConfigWindowsResizeFromEdges = true; } bool DejaVu::ShouldBlockInput() { return this->shouldBlockInput; } bool DejaVu::IsActiveOverlay() { return true; } void DejaVu::LaunchQuickNoteModal() { this->openQuickNote = true; if (!this->isWindowOpen) cvarManager->executeCommand("togglemenu " + GetMenuName()); } void DejaVu::OnOpen() { this->isWindowOpen = true; this->cvarManager->getCvar("cl_dejavu_log").setValue(true); this->playerIDsToDisplay.resize(this->data["players"].size()); } void DejaVu::OnClose() { this->isWindowOpen = false; WriteData(); } void DejaVu::OpenMenu() { if (!this->isWindowOpen) ToggleMenu(); } void DejaVu::CloseMenu() { if (this->isWindowOpen) ToggleMenu(); } void DejaVu::ToggleMenu() { cvarManager->executeCommand("togglemenu " + GetMenuName()); }
34.27248
244
0.689935
[ "render" ]
0c0b2618a0ef0a28116cb2214840660473662bfc
3,318
cpp
C++
PowderGame/src/Graphics.cpp
Markek1/Powder-Game
5d3a9c83cd72ada5f0586973ee8dd06386f7278c
[ "MIT" ]
1
2022-03-29T10:02:28.000Z
2022-03-29T10:02:28.000Z
PowderGame/src/Graphics.cpp
Markek1/Powder-Game
5d3a9c83cd72ada5f0586973ee8dd06386f7278c
[ "MIT" ]
null
null
null
PowderGame/src/Graphics.cpp
Markek1/Powder-Game
5d3a9c83cd72ada5f0586973ee8dd06386f7278c
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <SDL.h> #include "Graphics.h" #include "Helpers.h" #include "Settings.h" #include "Engine/Engine.h" #include "Engine/Elements/Element.h" SDL_Window* Graphics::createCenteredWindow(int width, int height, const char* title) { // Get current device's Display Mode to calculate window position SDL_DisplayMode DM; SDL_GetCurrentDisplayMode(0, &DM); int x = DM.w / 2 - width / 2; int y = DM.h / 2 - height / 2; SDL_Window* window = SDL_CreateWindow(title, x, y, width, height, SDL_WINDOW_ALLOW_HIGHDPI); catchError(window, "Failed to create Window\n"); return window; } // Create an SDL Texture to use as a "back buffer" SDL_Texture* Graphics::createBackBufferTexture(SDL_Renderer* renderer) { SDL_Texture* texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, windowSize.x, windowSize.y); catchError(texture, "Failed to create Back Buffer Texture\n"); return texture; } void Graphics::shutdown() { if (texture) { SDL_DestroyTexture(texture); texture = nullptr; } if (renderer) { SDL_DestroyRenderer(renderer); renderer = nullptr; } if (window) { SDL_DestroyWindow(window); window = nullptr; } } bool Graphics::initialize() { SDL_Init(SDL_INIT_VIDEO); window = createCenteredWindow(windowSize.x, windowSize.y, windowTitle); if (!catchError(window, "No Window. Aborting...")) { shutdown(); return false; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED + SDL_RENDERER_PRESENTVSYNC); //renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!catchError(renderer, "No Renderer. Aborting...")) { shutdown(); return false; } texture = createBackBufferTexture(renderer); if (!catchError(texture, "No back buffer Texture. Aborting...")) { shutdown(); return false; } return true; } void Graphics::render(SDL_Texture* texture, Grid& grid) { // The Back Buffer texture may be stored with an extra bit of width (pitch) on the video card in order to properly // align it in VRAM should the width not lie on the correct memory boundary (usually four bytes). int32_t pitch = 0; // This will hold a pointer to the memory position in VRAM where our Back Buffer texture lies uint32_t* pixelBuffer = nullptr; SDL_LockTexture(texture, NULL, (void**)&pixelBuffer, &pitch); // The pitch of the Back Buffer texture in VRAM must be divided by four bytes // as it will always be a multiple of four pitch /= sizeof(uint32_t); // For each cell puts the corresponding color value into the pixelBuffer int yPixel = 0; for (int yCell = 0; yCell < grid.size.y; yCell++) for (int i = 0; i < cellToPixelScaleFactor; i++, yPixel++) { int xPixel = 0; for (int xCell = 0; xCell < grid.size.x; xCell++) for (int j = 0; j < cellToPixelScaleFactor; j++, xPixel++) { int pixelPos = yPixel * windowSize.x + xPixel; int cellPos = yCell * grid.size.x + xCell; Cell& cell = grid.grid[cellPos]; Element& element = elements[cell.elementId]; //treating the 4 bytes as an unsigned int allows for fast conversion pixelBuffer[pixelPos] = *((uint32_t*)element.color); } } SDL_UnlockTexture(texture); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); }
23.366197
115
0.709162
[ "render" ]
0c23fbbb0161842e62d6c50f90d53696870e2247
18,938
cpp
C++
src/visualisation/VTKWriter.cpp
FireDynamics/ARTSS
a700835be57ac1c99ed55c6664d36ecf8afda3d8
[ "MIT" ]
10
2020-03-25T10:15:09.000Z
2020-09-09T12:27:41.000Z
src/visualisation/VTKWriter.cpp
FireDynamics/ARTSS
a700835be57ac1c99ed55c6664d36ecf8afda3d8
[ "MIT" ]
152
2020-03-25T10:18:02.000Z
2022-03-22T08:35:44.000Z
src/visualisation/VTKWriter.cpp
FireDynamics/ARTSS
a700835be57ac1c99ed55c6664d36ecf8afda3d8
[ "MIT" ]
11
2020-03-25T21:29:50.000Z
2021-12-09T12:25:50.000Z
/// \file VTKWriter.cpp /// \brief class to write out vtk files /// \date Jun 25, 2020 /// \author My Linh Wuerzburger /// \copyright <2015-2020> Forschungszentrum Juelich GmbH. All rights reserved. #include "VTKWriter.h" #include "../Domain.h" #include "visit_writer.h" //( https://wci.llnl.gov/codes/visit/ ) static std::string ending = ".vtk"; void VTKWriter::write_numerical_debug(const FieldController &field_controller, const std::string &filename) { auto u = field_controller.get_field_u_data(); auto v = field_controller.get_field_v_data(); auto w = field_controller.get_field_w_data(); auto p = field_controller.get_field_p_data(); auto div = field_controller.get_field_rhs_data(); auto T = field_controller.get_field_T_data(); auto C = field_controller.get_field_concentration_data(); auto s = field_controller.get_field_sight_data(); auto nu_t = field_controller.get_field_nu_t_data(); auto S_T = field_controller.get_field_source_T_data(); auto S_C = field_controller.get_field_source_concentration_data(); auto f_x = field_controller.get_field_force_x_data(); auto f_y = field_controller.get_field_force_y_data(); auto f_z = field_controller.get_field_force_z_data(); auto kappa = field_controller.get_field_kappa_data(); auto gamma = field_controller.get_field_gamma_data(); int size_vars = 16; read_ptr data[16] = {u, v, w, p, div, T, C, s, nu_t, S_T, S_C, f_x, f_y, f_z, kappa, gamma}; // Initialise variables int var_dims[size_vars + 6]; // Dimensions of variables (x,y,z,u,v,w,p,div,T) int centering[size_vars + 6]; // Whether the variables are centered in a cell: 0 for zonal! for (int i = 0; i < size_vars + 6; i++) { var_dims[i] = 1; centering[i] = 0; } const char *var_names[] = {"x-coords", "y-coords", "z-coords", "index_i", "index_j", "index_k", "x-velocity", "y-velocity", "z-velocity", "pressure", "divergence", "temperature", "concentration", "sight", "nu_t", "source_T", "source_C", "force_x", "force_y", "force_z", "kappa", "gamma"}; VTKWriter::vtk_prepare_and_write_debug((filename + ending).c_str(), data, size_vars, var_names, centering, var_dims); delete[] (*var_names); delete[] (*data); } void VTKWriter::write_numerical(const FieldController &field_controller, const std::string &filename) { auto u = field_controller.get_field_u_data(); auto v = field_controller.get_field_v_data(); auto w = field_controller.get_field_w_data(); auto p = field_controller.get_field_p_data(); auto div = field_controller.get_field_rhs_data(); auto T = field_controller.get_field_T_data(); auto C = field_controller.get_field_concentration_data(); auto sight = field_controller.get_field_sight_data(); auto nu_t = field_controller.get_field_nu_t_data(); auto source_T = field_controller.get_field_source_T_data(); VTKWriter::vtk_prepare_and_write((filename + ending).c_str(), u, v, w, p, div, T, C, sight, nu_t, source_T); } void VTKWriter::write_analytical(const Solution &solution, const std::string &filename) { auto u = solution.get_return_ptr_data_u(); auto v = solution.get_return_ptr_data_v(); auto w = solution.get_return_ptr_data_w(); auto p = solution.get_return_ptr_data_p(); auto T = solution.get_return_ptr_data_T(); VTKWriter::vtk_prepare_and_write((filename + ending).c_str(), u, v, w, p, T); } //================================= Visualization (VTK) ================================== // *************************************************************************************** /// \brief Prepares the (numerical) arrays in a correct format and writes the structured grid /// and its variables /// \param fname xml-file name (via argument) /// \param u constant input value (\a x -velocity) /// \param v constant input value (\a y -velocity) /// \param w constant input value (\a z -velocity) /// \param p constant input value (pressure) /// \param div constant input value (divergence) /// \param T constant input value (temperature) /// \param C constant input value (concentration) /// \param sight constant input value (sight) /// \param nu_t constant input value (turbulent viscosity) /// \param source_T constant input values (energy source) /// \author Severt // *************************************************************************************** void VTKWriter::vtk_prepare_and_write(const char *filename, read_ptr u, read_ptr v, read_ptr w, read_ptr p, read_ptr div, read_ptr T, read_ptr C, read_ptr sight, read_ptr nu_t, read_ptr source_T) { Domain *domain = Domain::getInstance(); real X1 = domain->get_X1(); real Y1 = domain->get_Y1(); real Z1 = domain->get_Z1(); int Nx = static_cast<int>(domain->get_Nx()); int Ny = static_cast<int>(domain->get_Ny()); int Nz = static_cast<int>(domain->get_Nz()); real dx = domain->get_dx(); real dy = domain->get_dy(); real dz = domain->get_dz(); int size = static_cast<int>(domain->get_size()); // Initialise variables int size_vars = 13; // Number of variables // Dimensions of variables (x,y,z,u,v,w,p,div,T,C,s,nu_t) int var_dims[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; // Whether the variables are centered in a cell: 0 for zonal! int centering[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; const char *var_names[] = {"x-coords", "y-coords", "z-coords", "x-velocity", "y-velocity", "z-velocity", "pressure", "divergence", "temperature", "concentration", "sight", "turb_visc", "source_T"}; // Dimensions of the rectilinear array (+1 for zonal values) int dims[] = {Nx + 1, Ny + 1, Nz + 1}; auto *x_coords = new float[(Nx + 1)]; auto *y_coords = new float[(Ny + 1)]; auto *z_coords = new float[(Nz + 1)]; // Initialise grid // faces of the grid cells for (int i = 0; i < Nx + 1; i++) { x_coords[i] = static_cast<float> (X1 + (i - 1) * dx); } for (int j = 0; j < Ny + 1; j++) { y_coords[j] = static_cast<float> (Y1 + (j - 1) * dy); } for (int k = 0; k < Nz + 1; k++) { z_coords[k] = static_cast<float> (Z1 + (k - 1) * dz); } // centers of the grid cells auto *x_centres = new float[size]; auto *y_centres = new float[size]; auto *z_centres = new float[size]; // velocities auto *u_vel = new float[size]; auto *v_vel = new float[size]; auto *w_vel = new float[size]; // pressure auto pres = new float[size]; // divergence auto vel_div = new float[size]; // temperature auto Temp = new float[size]; // smoke concentration auto Con = new float[size]; // boundary sight auto Sight = new float[size]; // turbulent viscosity auto turb_visc = new float[size]; // energy source auto Source_T = new float[size]; // Cast variables to floats for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { size_t index = IX(i, j, k, Nx, Ny); x_centres[index] = x_coords[i] + static_cast<float> (0.5 * dx); y_centres[index] = y_coords[j] + static_cast<float> (0.5 * dy); z_centres[index] = z_coords[k] + static_cast<float> (0.5 * dz); u_vel[index] = static_cast<float>(u[index]); v_vel[index] = static_cast<float>(v[index]); w_vel[index] = static_cast<float>(w[index]); pres[index] = static_cast<float>(p[index]); vel_div[index] = static_cast<float>(div[index]); Temp[index] = static_cast<float>(T[index]); Con[index] = static_cast<float>(C[index]); Sight[index] = static_cast<float>(sight[index]); turb_visc[index] = static_cast<float>(nu_t[index]); Source_T[index] = static_cast<float>(source_T[index]); } } } // Summarise pointers to variables in an array float *vars[] = {static_cast<float *> (x_centres), static_cast<float *> (y_centres), static_cast<float *> (z_centres), static_cast<float *> (u_vel), static_cast<float *> (v_vel), static_cast<float *> (w_vel), static_cast<float *> (pres), static_cast<float *> (vel_div), static_cast<float *> (Temp), static_cast<float *> (Con), static_cast<float *> (Sight), static_cast<float *> (turb_visc), static_cast<float *> (Source_T)}; // Use visit_writer to write data on mesh write_rectilinear_mesh(filename, 1, dims, x_coords, y_coords, z_coords, size_vars, var_dims, centering, var_names, vars); // Clean up delete[] (x_coords); delete[] (y_coords); delete[] (z_coords); delete[] (x_centres); delete[] (y_centres); delete[] (z_centres); delete[] (u_vel); delete[] (v_vel); delete[] (w_vel); delete[] (pres); delete[] (vel_div); delete[] (Temp); delete[] (Con); delete[] (Sight); delete[] (turb_visc); delete[] (Source_T); } //================================= Visualization (VTK) ============================================ // ************************************************************************************************* /// \brief Prepares the (analytical) arrays in a correct format and writes the structured grid /// and its variables /// \param filename xml filename (via argument) /// \param u constant input value (\a x -velocity) /// \param v constant input value (\a y -velocity) /// \param w constant input value (\a z -velocity) /// \param p constant input value (pressure) /// \param T constant input value (temperature) /// \param s constant input value (sight) /// \author Severt // ************************************************************************************************* void VTKWriter::vtk_prepare_and_write(const char *filename, read_ptr u, read_ptr v, read_ptr w, read_ptr p, read_ptr T) { Domain *domain = Domain::getInstance(); real X1 = domain->get_X1(); real Y1 = domain->get_Y1(); real Z1 = domain->get_Z1(); int Nx = static_cast<int>(domain->get_Nx()); int Ny = static_cast<int>(domain->get_Ny()); int Nz = static_cast<int>(domain->get_Nz()); real dx = domain->get_dx(); real dy = domain->get_dy(); real dz = domain->get_dz(); int size = static_cast<int>(domain->get_size()); // Initialise variables int size_vars = 8; // Number of variables // Dimensions of variables (x,y,z,u,v,w,p,div,T) int var_dims[] = {1, 1, 1, 1, 1, 1, 1, 1}; // Whether the variables are centered in a cell: 0 for zonal! int centering[] = {0, 0, 0, 0, 0, 0, 0, 0}; const char *var_names[] = {"x-coords", "y-coords", "z-coords", "x-velocity", "y-velocity", "z-velocity", "pressure", "temperature"}; // Dimensions of the rectilinear array (+1 for zonal values) int dims[] = {Nx + 1, Ny + 1, Nz + 1}; auto x_coords = new float[(Nx + 1)]; auto y_coords = new float[(Ny + 1)]; auto z_coords = new float[(Nz + 1)]; // Initialise grid // faces of the grid cells for (int i = 0; i < Nx + 1; i++) { x_coords[i] = static_cast<float> (X1 + (i - 1) * dx); } for (int j = 0; j < Ny + 1; j++) { y_coords[j] = static_cast<float> (Y1 + (j - 1) * dy); } for (int k = 0; k < Nz + 1; k++) { z_coords[k] = static_cast<float> (Z1 + (k - 1) * dz); } // centers of the grid cells auto x_centres = new float[size]; auto y_centres = new float[size]; auto z_centres = new float[size]; // velocities auto u_vel = new float[size]; auto v_vel = new float[size]; auto w_vel = new float[size]; // pressure auto pres = new float[size]; // temperature auto Temp = new float[size]; // Cast variables to floats for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { size_t index = IX(i, j, k, Nx, Ny); x_centres[index] = x_coords[i] + static_cast<float> (0.5 * dx); y_centres[index] = y_coords[j] + static_cast<float> (0.5 * dy); z_centres[index] = z_coords[k] + static_cast<float> (0.5 * dz); u_vel[index] = static_cast<float>(u[index]); v_vel[index] = static_cast<float>(v[index]); w_vel[index] = static_cast<float>(w[index]); pres[index] = static_cast<float>(p[index]); Temp[index] = static_cast<float>(T[index]); } } } // Summarise pointers to variables in an array float *vars[] = {static_cast<float *> (x_centres), static_cast<float *> (y_centres), static_cast<float *> (z_centres), static_cast<float *> (u_vel), static_cast<float *> (v_vel), static_cast<float *> (w_vel), static_cast<float *> (pres), static_cast<float *> (Temp)}; // Use visit_writer to write data on mesh write_rectilinear_mesh(filename, 1, dims, x_coords, y_coords, z_coords, size_vars, var_dims, centering, var_names, vars); // Clean up delete[] (x_coords); delete[] (y_coords); delete[] (z_coords); delete[] (x_centres); delete[] (y_centres); delete[] (z_centres); delete[] (u_vel); delete[] (v_vel); delete[] (w_vel); delete[] (pres); delete[] (Temp); } //================================= Visualization (VTK) ============================================ // ************************************************************************************************* /// \brief Prepares the arrays given in data in a correct format and writes the structured grid /// and its variables /// \param filename xml filename (via argument) /// \param data containing all data fields to be written out /// \param size_vars length of data /// \param var_names title to be written out for the respective field in data /// \param centering whether values are in the middle (0 for zonal value) /// \param var_dims dimension of the respective field in data /// \author Severt // ************************************************************************************************* void VTKWriter::vtk_prepare_and_write_debug(const char *filename, read_ptr *data, int size_vars, const char * const *var_names, int *centering, int *var_dims) { Domain *domain = Domain::getInstance(); real X1 = domain->get_X1(); real Y1 = domain->get_Y1(); real Z1 = domain->get_Z1(); int Nx = static_cast<int>(domain->get_Nx()); int Ny = static_cast<int>(domain->get_Ny()); int Nz = static_cast<int>(domain->get_Nz()); real dx = domain->get_dx(); real dy = domain->get_dy(); real dz = domain->get_dz(); int size = static_cast<int>(domain->get_size()); // Dimensions of the rectilinear array (+1 for zonal values) int dims[] = {Nx + 1, Ny + 1, Nz + 1}; auto x_coords = new float[(Nx + 1)]; auto y_coords = new float[(Ny + 1)]; auto z_coords = new float[(Nz + 1)]; // Initialise grid // faces of the grid cells for (int i = 0; i < Nx + 1; i++) { x_coords[i] = static_cast<float> (X1 + (i - 1) * dx); } for (int j = 0; j < Ny + 1; j++) { y_coords[j] = static_cast<float> (Y1 + (j - 1) * dy); } for (int k = 0; k < Nz + 1; k++) { z_coords[k] = static_cast<float> (Z1 + (k - 1) * dz); } float *write_out[size_vars + 6]; for (int i = 0; i < size_vars + 6; i++){ write_out[i] = new float[size]; } // Cast variables to floats for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { size_t index = IX(i, j, k, Nx, Ny); write_out[0][index] = x_coords[i] + static_cast<float> (0.5 * dx); write_out[1][index] = y_coords[j] + static_cast<float> (0.5 * dy); write_out[2][index] = z_coords[k] + static_cast<float> (0.5 * dz); write_out[3][index] = static_cast<float> (i); write_out[4][index] = static_cast<float> (j); write_out[5][index] = static_cast<float> (k); for (int v = 0; v < size_vars; v++){ write_out[v + 6][index] = static_cast<float>(data[v][index]); } } } } // Summarise pointers to variables in an array float *vars[size_vars + 6]; for (int i = 0; i < size_vars + 6; i++){ vars[i] = static_cast<float *> (write_out[i]); } // Use visit_writer to write data on mesh write_rectilinear_mesh(filename, 1, dims, x_coords, y_coords, z_coords, size_vars + 6, var_dims, centering, var_names, vars); // Clean up delete[] (x_coords); delete[] (y_coords); delete[] (z_coords); }
40.552463
129
0.515736
[ "mesh" ]
0c259003e274cefe5fe9762bed65b893ab375588
824
cpp
C++
ch5/Shell_Sort/algorithm.cpp
omar659/Algorithms-Sequential-Parallel-Distributed
3543631139a20625f413cea2ba1f013f3a40d123
[ "MIT" ]
2
2020-02-19T09:27:20.000Z
2020-02-19T09:28:21.000Z
ch5/Shell_Sort/algorithm.cpp
omar-3/Algorithms-Sequential-Parallel-Distributed
3543631139a20625f413cea2ba1f013f3a40d123
[ "MIT" ]
null
null
null
ch5/Shell_Sort/algorithm.cpp
omar-3/Algorithms-Sequential-Parallel-Distributed
3543631139a20625f413cea2ba1f013f3a40d123
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> template<typename T> void InsertionSubSort(std::vector<T>& L, int k) { for (int i = k ; i < L.size ; i++) { T current = L[i]; int position = i - k; while ((position >= 0) && (current < L[position])) { L[position + k] = L[position]; position = position - k; } L[position + k] = current; } } template<typename T> void ShellSort(std::vector<T>& L , std::vector<int> k) { for (int i = 0 ; i < k.size() ; i++) { InsertionSubSort(L, k[i]); } } int main () { std::vector<int> omar = {4,3,2,0,12,10,2,9,8,-1,-2,3,6,58,8,34,54,62,61,54,50}; std::vector<int> k = {6,5,4,3,2,1}; ShellSort(omar, k); for(int i = 0 ; i < omar.size() ; i++) { std::cout << omar[i] << std::endl; } }
26.580645
83
0.5
[ "vector" ]
0c283d1df0741afb879e571755f4e40cc250b023
8,190
hh
C++
src/thirdparty/acg_localizer/src/sfm/parse_bundler.hh
rajvishah/ms-sfm
0de1553c471c416ce5ca3d19c65abe36d8e17a07
[ "MIT" ]
null
null
null
src/thirdparty/acg_localizer/src/sfm/parse_bundler.hh
rajvishah/ms-sfm
0de1553c471c416ce5ca3d19c65abe36d8e17a07
[ "MIT" ]
null
null
null
src/thirdparty/acg_localizer/src/sfm/parse_bundler.hh
rajvishah/ms-sfm
0de1553c471c416ce5ca3d19c65abe36d8e17a07
[ "MIT" ]
null
null
null
/*===========================================================================*\ * * * ACG Localizer * * Copyright (C) 2011-2012 by Computer Graphics Group, RWTH Aachen * * www.rwth-graphics.de * * * *---------------------------------------------------------------------------* * This file is part of ACG Localizer * * * * ACG Localizer is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * ACG Localizer 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 ACG Localizer. If not, see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ #ifndef PARSE_BUNDLER_HH #define PARSE_BUNDLER_HH /** * Parses a bundle.out file created by Bundler into a set of * 3D points and the corresponding descriptors. * * author: Torsten Sattler (tsattler@cs.rwth-aachen.de) * date : 11-08-2012 **/ #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <stdint.h> #include <cstdlib> #include <string> #include "../features/SIFT_keypoint.hh" #include "../features/SIFT_loader.hh" #include "bundler_camera.hh" //////////////////////////// // Simple definition of a 3D point // consisting of x,y,z coordinates // and a point color. //////////////////////////// class point3D { public: float x,y,z; unsigned char r,g,b; point3D() { x = y = z = 0.0; r = g = b = 0; } point3D( float x_, float y_, float z_ ) { x = x_; y = y_; z = z_; r = g = b = 0; } point3D( float x_, float y_, float z_, unsigned char r_, unsigned char g_, unsigned char b_ ) { x = x_; y = y_; z = z_; r = r_; g = g_; b = b_; } point3D( const point3D &other ) { x = other.x; y = other.y; z = other.z; r = other.r; g = other.g; b = other.b; } void operator=( const point3D &other ) { x = other.x; y = other.y; z = other.z; r = other.r; g = other.g; b = other.b; } }; //////////////////////////// // A view of a 3D point as defined by Bundler. It // contains the index of the camera the point was seen it, // the keypoint index in the .key file of that camera corresponding // to the projection of the 3D point, the x- and y-positions of that keypoint // in a reference frame where the center of the coordinate system is the center // of the cameras image, as well as the scale and orientation of that keypoint. // (see http://phototour.cs.washington.edu/bundler/bundler-v0.4-manual.html) //////////////////////////// struct view { uint32_t camera; // index of the camera this feature was detected in uint32_t key; // index of this feature in the corresponding .key file containing the cameras SIFT features float x,y; float scale; // scale at which the feature was detected as taken from the original image float orientation; // orientation of that features as detected in the image view() { camera = key = 0; x = y = 0.0; scale = 0.0f; orientation = 0.0f; } }; //////////////////////////// // Information about a reconstructed 3D point. The structure contains information about the 3D position // of the point, its color, and a list of views in which the point can be seen and the corresponding SIFT descriptors. // The descriptor for view view_list[i] is stored in descriptors[128*i]...descriptors[128*i+127] //////////////////////////// class feature_3D_info { public: point3D point; std::vector< view > view_list; std::vector< unsigned char > descriptors; // constructor feature_3D_info( ) { view_list.clear(); descriptors.clear(); } // copy constructor feature_3D_info( const feature_3D_info &other ) { view_list.clear(); descriptors.clear(); view_list.resize( other.view_list.size() ); descriptors.resize( other.descriptors.size() ); for( uint32_t i=0; i< (uint32_t) other.view_list.size(); ++i ) { view_list[i].camera = other.view_list[i].camera; view_list[i].key = other.view_list[i].key; view_list[i].x = other.view_list[i].x; view_list[i].y = other.view_list[i].y; view_list[i].scale = other.view_list[i].scale; view_list[i].orientation = other.view_list[i].orientation; } for( uint32_t i=0; i<(uint32_t)other.descriptors.size(); ++i ) descriptors[i] = other.descriptors[i]; point = other.point; } // destructor ~feature_3D_info( ) { view_list.clear(); descriptors.clear(); } // reset all data void clear_data() { view_list.clear(); descriptors.clear(); } }; //////////////////////////// // Class to parse the output files generated by Bundler. // The class is able to further load the .key files of all cameras in // the reconstruction given that the .key files are not zipped (Bundler // generally uses gzip to compress the .key files). It can also // load the file format generated by Bundle2Info. //////////////////////////// class parse_bundler { public: // standard constructor parse_bundler(); // standard destructor ~parse_bundler( ); // get the number of 3D points in the reconstruction uint32_t get_number_of_points( ); // get the number of cameras in the reconstruction uint32_t get_number_of_cameras( ); // get the actual 3D points from the loaded reconstruction void get_points( std::vector< point3D > &points ); // get the feature information extracted from the reconstruction std::vector< feature_3D_info >& get_feature_infos( ); // get the cameras included in the reconstruction std::vector< bundler_camera >& get_cameras( ); // Parses the output text file generated by bundler. // Input parameters: The filename of the output file (usually bundle.out) and // the filename of the list of images (usually list.txt). bool parse_data( const char* bundle_out_filename_, const char* image_list_filename ); // Load the information from a binary file constructed with Bundle2Info. // The format parameter specifies whether the binary file contains // no camera information (format=0, as generated by Bundle2Info) or does // contain camera information (format=1, for example the aachen.info file // released with the Aachen dataset from the paper // // Torsten Sattler, Tobias Weyand, Bastian Leibe, Leif Kobbelt. // Image Retrieval for Image-Based Localization Revisited. // BMVC 2012. bool load_from_binary( const char* filename, const int format ); // clear the loaded data void clear(); private: std::vector< bundler_camera > mCameras; std::vector< feature_3D_info > mFeatureInfos; uint32_t mNbPoints, mNbCameras; }; #endif
32.244094
118
0.552991
[ "vector", "3d" ]
0c457f971041bb5f4945b5f7b089309f61543767
5,666
cpp
C++
0201-0300/212-word-search-ii/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
0201-0300/212-word-search-ii/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
0201-0300/212-word-search-ii/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
#include <algorithm> #include <iostream> #include <set> #include <string> #include <unordered_set> #include <vector> class Cache { static constexpr long long p = 31; static constexpr long long p1 = 838709685; // x * p1 == x / p mod m static constexpr long long m = 1e9 + 9; std::vector<std::string> _strs; public: bool in(const std::string& word) { const size_t len = word.size(); const long long substr_hash = hash(word); for (const std::string& str : _strs) { if (str.size() > len) { continue; } if (str.size() == len) { if (str == word) { return true; } continue; } // Now, for the rolling hash part... long long prev_hash = hash(str, len); if (prev_hash == substr_hash && cmp(str, 0, word)) { return true; } for (size_t ind = 1; ind <= (str.size() - len); ++ind) { const long long next_hash = hash(str, ind, len, prev_hash); if (next_hash == substr_hash && cmp(str, ind, word)) { return true; } prev_hash = next_hash; } } return false; } void add(const std::string& word) { _strs.push_back(word); } private: static long long hash(const std::string& s) { long long hash_value = 0; long long p_pow = 1; for (char c : s) { hash_value = (hash_value + hash(c) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash_value; } // Hash first len characters of s static long long hash(const std::string& s, size_t len) { long long hash_value = 0; long long p_pow = 1; for (size_t ii = 0; ii < len; ++ii) { hash_value = (hash_value + hash(s[ii]) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash_value; } // Hash s[ind:ind+len] such that prev = hash(s[ind-1:ind+len-1]). static long long hash(const std::string& s, size_t ind, size_t len, long long prev) { long long hash_value = prev - hash(s[ind - 1]); while (hash_value < 0) { hash_value += m; } hash_value = (hash_value * p1 + (hash(s[ind + len - 1]) * ipow(p, len - 1))) % m; return hash_value; } static long long hash(const char c) { return c - 'a' + 1; } // Elias Yarrkov / Static Overflow <https://stackoverflow.com/a/101613/14020202>, CC BY-SA 3.0 static long long ipow(long long base, long long exp) { long long result = 1; for (;;) { if (exp & 1) result *= base; exp >>= 1; if (!exp) break; base *= base; } return result % m; } // Compare str[ind : ind+substr.size()] and substr static bool cmp(const std::string& str, size_t ind, const std::string& substr) { for (size_t ii = 0; ii < ind; ++ii) { if (str[ind + ii] != substr[ii]) { return false; } } return true; } }; class Solution { std::vector<std::vector<char>> _board; std::multiset<char> _chars; size_t _width, _height; public: std::vector<std::string> findWords(const std::vector<std::vector<char>>& board, std::vector<std::string> words) { _board = board; _width = board.at(0).size(); _height = board.size(); for (const std::vector<char>& row : _board) { for (const char c : row) { _chars.insert(c); } } Cache cache; // Sort words by length in reverse std::sort(std::begin(words), std::end(words), [](const std::string& l, const std::string& r) { return l.size() > r.size(); }); std::vector<std::string> result; for (const std::string& word : words) { if (!isPossible(word)) { continue; } if (cache.in(word)) { result.push_back(word); continue; } refillBoard(board); if (find(word)) { cache.add(word); result.push_back(word); } } return result; } private: bool find(const std::string& word) { // Go through the entire grid for (size_t x = 0; x < _width; ++x) { for (size_t y = 0; y < _height; ++y) { if (find(word, 0, x, y)) { return true; } } } return false; } bool find(const std::string& word, size_t ind, size_t x, size_t y) { if (ind == word.size()) { return true; } if (x >= _width || y >= _height) { return false; } const char ch = word[ind]; if (_board[y][x] != ch) { return false; } _board[y][x] = ' '; const bool result = find(word, ind + 1, x - 1, y) || find(word, ind + 1, x + 1, y) || find(word, ind + 1, x, y - 1) || find(word, ind + 1, x, y + 1); _board[y][x] = ch; return result; } void refillBoard(const std::vector<std::vector<char>>& board) { for (size_t x = 0; x < _width; ++x) { for (size_t y = 0; y < _height; ++y) { _board[y][x] = board[y][x]; } } } bool isPossible(const std::string& word) { std::multiset<char> chars; for (const char c : word) { chars.insert(c); } for (const char c : chars) { if (chars.count(c) > _chars.count(c)) { return false; } } return true; } }; int main() { const std::vector<std::vector<char>> board{ { 'o', 'a', 'a', 'n' }, { 'e', 't', 'a', 'e' }, { 'i', 'h', 'k', 'r' }, { 'i', 'f', 'l', 'v' } }; const std::vector<std::string> words{ "oath", "pea", "eat", "rain" }; const std::unordered_set<std::string> expected{ "eat", "oath" }; Solution soln; std::unordered_set<std::string> actual; for (const std::string& word : soln.findWords(board, words)) { actual.insert(word); } // Compare expected and actual for (const std::string& word : actual) { std::cout << "Checking if " << word << " in expected" << std::endl; if (expected.count(word) == 0) { std::cout << word << " not in expected" << std::endl; } } for (const std::string& word : expected) { std::cout << "Checking if " << word << " in actual" << std::endl; if (actual.count(word) == 0) { std::cout << word << " not in actual" << std::endl; } } }
21.708812
128
0.576774
[ "vector" ]
0c4a0b5497b85769dd49c20614f744ad7ced6cc0
2,739
cpp
C++
source/gloperate-qtquick/source/RenderItemRenderer_ogl.cpp
lordgeorg/gloperate
13a6363fdac1f9ff06d91c9bc99649eacd87078e
[ "MIT" ]
34
2015-10-07T12:26:27.000Z
2021-04-06T06:35:01.000Z
source/gloperate-qtquick/source/RenderItemRenderer_ogl.cpp
lordgeorg/gloperate
13a6363fdac1f9ff06d91c9bc99649eacd87078e
[ "MIT" ]
219
2015-07-07T15:55:03.000Z
2018-09-28T08:54:36.000Z
source/gloperate-qtquick/source/RenderItemRenderer_ogl.cpp
lordgeorg/gloperate
13a6363fdac1f9ff06d91c9bc99649eacd87078e
[ "MIT" ]
21
2015-07-07T14:33:08.000Z
2018-12-23T12:43:56.000Z
#include <gloperate-qtquick/RenderItemRenderer.h> #include <glm/vec2.hpp> #include <cppassist/memory/make_unique.h> #include <glbinding/gl/gl.h> #include <globjects/base/AbstractStringSource.h> #include <globjects/Framebuffer.h> #include <globjects/Texture.h> #include <globjects/Program.h> #include <globjects/Shader.h> #include <gloperate/rendering/ScreenAlignedQuad.h> #include <gloperate/base/Canvas.h> #include <gloperate-qt/base/GLContext.h> #include <gloperate-qtquick/RenderItem.h> namespace gloperate_qtquick { RenderItemRenderer::RenderItemRenderer(RenderItem * renderItem) : m_renderItem(renderItem) , m_contextInitialized(false) , m_canvasInitialized(false) , m_width(0) , m_height(0) , m_canvas(renderItem->canvas()) { } RenderItemRenderer::~RenderItemRenderer() { // Deinitialize canvas (must be performed in the render thread!) m_renderItem->canvas()->setOpenGLContext(nullptr); } void RenderItemRenderer::configureFbo(int fboId, unsigned int width, unsigned int height) { // Create wrapper for the outer FBO m_fbo = globjects::Framebuffer::fromId(fboId); // Save FBO size m_width = width; m_height = height; // Set texture options glm::ivec2 size = glm::ivec2(width, height); gl::GLenum format = gl::GL_RGBA; gl::GLenum internalFormat = gl::GL_RGBA; gl::GLenum dataType = gl::GL_UNSIGNED_BYTE; // Resize color texture m_texColor->image2D(0, internalFormat, size.x, size.y, 0, format, dataType, nullptr); // Resize depth texture m_texDepth->image2D(0, gl::GL_DEPTH_COMPONENT, size.x, size.y, 0, gl::GL_DEPTH_COMPONENT, gl::GL_UNSIGNED_BYTE, nullptr); // Create FBO m_innerFbo = cppassist::make_unique<globjects::Framebuffer>(); m_innerFbo->setDrawBuffers({ gl::GL_COLOR_ATTACHMENT0 }); m_innerFbo->attachTexture(gl::GL_COLOR_ATTACHMENT0, m_texColor.get()); m_innerFbo->attachTexture(gl::GL_DEPTH_ATTACHMENT, m_texDepth.get()); } void RenderItemRenderer::initializeFboAttachments() { // Create color texture m_texColor = globjects::Texture::createDefault(gl::GL_TEXTURE_2D); // Create depth texture m_texDepth = globjects::Texture::createDefault(gl::GL_TEXTURE_2D); // Create screen-aligned quad m_screenAlignedQuad = cppassist::make_unique<gloperate::ScreenAlignedQuad>(); m_screenAlignedQuad->setInverted(true); } void RenderItemRenderer::renderTexture() { m_fbo->bind(gl::GL_FRAMEBUFFER); gl::glViewport(0, 0, m_width, m_height); gl::glDisable(gl::GL_DEPTH_TEST); gl::glEnable(gl::GL_BLEND); gl::glDisable(gl::GL_CULL_FACE); m_screenAlignedQuad->setTexture(m_texColor.get()); m_screenAlignedQuad->draw(); } } // namespace gloperate_qtquick
27.666667
125
0.729828
[ "render" ]
0c50be32d761ed8e5a6fa9aaf0b2ec354e18ec3d
376
cpp
C++
HackerRank/Challenges/utopian-tree.cpp
Diggzinc/solutions-spoj
eb552311011e466039e059cce07894fea0817613
[ "MIT" ]
null
null
null
HackerRank/Challenges/utopian-tree.cpp
Diggzinc/solutions-spoj
eb552311011e466039e059cce07894fea0817613
[ "MIT" ]
null
null
null
HackerRank/Challenges/utopian-tree.cpp
Diggzinc/solutions-spoj
eb552311011e466039e059cce07894fea0817613
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int nCases, nCase, height; cin >> nCases; while (nCases--) { cin >> nCase; height = 1; for (int i = 0; i < nCase; i++) { if (i % 2 == 0) { height*=2; } else { height++; } } cout << height << endl; } return 0; }
13.925926
35
0.547872
[ "vector" ]
31b4c3d8c4942cea091ca7953dbec55e93b392e9
405
cpp
C++
leetcode/plus1.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
leetcode/plus1.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
leetcode/plus1.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
null
null
null
class Solution { public: vector<int> plusOne(vector<int> &digits) { vector<int> res; int carry=1; for(int i=digits.size()-1; i>=0; i--){ int sum = digits[i]+carry; res.insert(res.begin(),sum%10); carry=sum/10; } if(carry!=0){ res.insert(res.begin(),carry); } return res; } };
22.5
46
0.446914
[ "vector" ]
31b6af24a64a651da662bf6cf54a60596338193d
7,580
cpp
C++
main.cpp
intheswim/soccer_ball_gl
cd8a68072abc4635603603c1031bc361488fd997
[ "Linux-OpenIB" ]
1
2020-06-16T06:48:34.000Z
2020-06-16T06:48:34.000Z
main.cpp
intheswim/soccer_ball_gl
cd8a68072abc4635603603c1031bc361488fd997
[ "Linux-OpenIB" ]
null
null
null
main.cpp
intheswim/soccer_ball_gl
cd8a68072abc4635603603c1031bc361488fd997
[ "Linux-OpenIB" ]
null
null
null
/* Soccerball with OpenGL, Copyright (c) 2020 Yuriy Yakimenko * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation. No representations are made about the suitability of this * software for any purpose. It is provided "as is" without express or * implied warranty. */ #include <GL/glut.h> #include "math.h" #include <stdio.h> #include <vector> #include <assert.h> #include "SoccerBallGL.h" static double rotate_y = 0; static double rotate_x = 0; static std::vector<Hextagon> pentagons, hexagons; static void Init (void) { float position[] = { -5.0, 5.0, 5.0, 0.0 }; float local_view[] = { 0.0 }; glEnable (GL_DEPTH_TEST); glDepthFunc (GL_LESS); glLightfv (GL_LIGHT0, GL_POSITION, position); glLightModelfv (GL_LIGHT_MODEL_LOCAL_VIEWER, local_view); glFrontFace (GL_CW); glEnable (GL_LIGHTING); glEnable (GL_LIGHT0); glEnable (GL_AUTO_NORMAL); glEnable (GL_NORMALIZE); glClearColor (0.0, 0.65, 0.1, 1.0); // green } static void setPentColors () { float ambient[] = { 0.01175, 0.01175, 0.01175 }; float diffuse[] = { 0.04136, 0.04136, 0.04136 }; float specular[] = { 0.626959, 0.626959, 0.626959 }; glMaterialfv (GL_FRONT, GL_AMBIENT, ambient); glMaterialfv (GL_FRONT, GL_DIFFUSE, diffuse); glMaterialfv (GL_FRONT, GL_SPECULAR, specular); glMaterialf (GL_FRONT, GL_SHININESS, 0.6*128.0); } static void setHexColors () { float ambient[] = { 1.2175, 1.2175, 1.2175 }; float diffuse[] = { 0.7136, 0.7136, 1.2136 }; float specular[] = { 0.626959, 0.626959, 0.626959 }; glMaterialfv (GL_FRONT, GL_AMBIENT, ambient); glMaterialfv (GL_FRONT, GL_DIFFUSE, diffuse); glMaterialfv (GL_FRONT, GL_SPECULAR, specular); glMaterialf (GL_FRONT, GL_SHININESS, 0.7*128.0); } ///////////////////////////////////////////////////////////////////////////// // // recursive call. // when level > 0, split triangle into four smaller triangles and call this // function recursively for each of them. // norm is normal to "seam" line, which is used to "dent" the surface // ///////////////////////////////////////////////////////////////////////////// static void DisplayTriangle (int level, DPoint a, DPoint b, DPoint c, DPoint & norm) { const int ADDED_DETAIL_ALONG_SEAMS = 1; // keep this number between [0 .. 2] inclusive. if (level <= 0) { const double R = 0.022; // this value controls how deep and thick seams are. double coef_a = 1, coef_b = 1, coef_c = 1; bool is_edge = false; double angle = a.getAngleAsin (norm); if (angle < R) { coef_a = 1 - R + sqrt (R * R - (angle - R) * (angle - R)); is_edge = true; } angle = b.getAngleAsin (norm); if (angle < R) { coef_b = 1 - R + sqrt (R * R - (angle - R) * (angle - R)); is_edge = true; } angle = c.getAngleAsin (norm); if (angle < R) { coef_c = 1 - R + sqrt (R * R - (angle - R) * (angle - R)); is_edge = true; } if (is_edge && (level > -ADDED_DETAIL_ALONG_SEAMS)) { DPoint ab = a.midpointTo (b); DPoint ac = a.midpointTo (c); DPoint bc = b.midpointTo (c); DisplayTriangle (level - 1, a, ab, ac, norm); DisplayTriangle (level - 1, b, ab, bc, norm); DisplayTriangle (level - 1, c, ac, bc, norm); DisplayTriangle (level - 1, ab, ac, bc, norm); return; } else // level < 0 or is_edge is false { if (level == -ADDED_DETAIL_ALONG_SEAMS) { a.MultiplyBy (coef_a); b.MultiplyBy (coef_b); c.MultiplyBy (coef_c); } DPoint norm = a.getNormal (b, c); glNormal3f (norm.x, norm.y, norm.z); glVertex3f ( a.x, a.y, a.z ); glVertex3f (b.x, b.y, b.z); glVertex3f (c.x, c.y, c.z); } } else { // create 4 smaller triangles. // compute median points on all three sides DPoint ab = a.midpointTo (b); DPoint ac = a.midpointTo (c); DPoint bc = b.midpointTo (c); DisplayTriangle (level - 1, a, ab, ac, norm); DisplayTriangle (level - 1, b, ab, bc, norm); DisplayTriangle (level - 1, c, ac, bc, norm); DisplayTriangle (level - 1, ab, ac, bc, norm); } } static void DisplayBall () { glClear (GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glLoadIdentity (); glColorMaterial (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glRotatef (rotate_x, 1.0, 0.0, 0.0); glRotatef (rotate_y, 0.0, 1.0, 0.0); const int DETAIL_LEVEL = 5; setPentColors (); glBegin (GL_TRIANGLES); for (auto & pent : pentagons ) { for (size_t i = 0; i < pent.ordered_vertices.size(); i++) { auto & a = pent.ordered_vertices[i]; auto & b = pent.ordered_vertices[ (i + 1) % 5]; DPoint seam_normal (0.0,0.0,0.0); seam_normal = seam_normal.getNormal (a, b); DisplayTriangle (DETAIL_LEVEL, pent.center, a, b, seam_normal); } } setHexColors (); for (auto & pent : hexagons ) { for (size_t i = 0; i < pent.ordered_vertices.size(); i++) { auto & a = pent.ordered_vertices [i]; auto & b = pent.ordered_vertices [ (i + 1) % 6]; DPoint seam_normal (0.0,0.0,0.0); seam_normal = seam_normal.getNormal (a, b); DisplayTriangle (DETAIL_LEVEL, pent.center, a, b, seam_normal); } } glEnd (); glutSwapBuffers (); // glFlush is done implicitly inside this call. } // ---------------------------------------------------------- // specialKeys() Callback Function // ---------------------------------------------------------- static void specialKeys( int key, int x, int y ) { // Right arrow - increase rotation by 5 degree if (key == GLUT_KEY_RIGHT) { rotate_y += 5; } // Left arrow - decrease rotation by 5 degree else if (key == GLUT_KEY_LEFT) { rotate_y -= 5; } else if (key == GLUT_KEY_UP) { rotate_x += 5; } else if (key == GLUT_KEY_DOWN) { rotate_x -= 5; } // Request display update glutPostRedisplay(); } static void Reshape(int w, int h) { glViewport (0, 0, (GLint)w, (GLint)h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); // this is to avoid stretching the image: float aspect = (float)w / (float)h; glOrtho(-2 * aspect, 2 * aspect, -2.0, 2.0, -1.0, 6.0); glMatrixMode (GL_MODELVIEW); glLoadIdentity(); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(800, 800); GLenum type = GLUT_DEPTH | GLUT_RGB | GLUT_DOUBLE | GLUT_MULTISAMPLE; glutInitDisplayMode (type); glutCreateWindow("Soccer ball. Use keyboard arrow keys to rotate"); Init (); SoccerBallGL soccerBall; soccerBall.Init (pentagons, hexagons); glutReshapeFunc (Reshape); glutDisplayFunc (DisplayBall); glutSpecialFunc (specialKeys); glutMainLoop (); return EXIT_SUCCESS; }
25.694915
91
0.562137
[ "vector" ]
31b9ffc6745d55e2b8d32f373e457359bc8ee642
40,825
cpp
C++
Goldeneye Revenge/game.cpp
scruffyfox/Goldeneye-Revenge
29b9a9ca668260f7516b1651d06820dd89be9444
[ "OLDAP-2.7", "OLDAP-2.6", "OLDAP-2.4", "OLDAP-2.5", "OLDAP-2.3" ]
null
null
null
Goldeneye Revenge/game.cpp
scruffyfox/Goldeneye-Revenge
29b9a9ca668260f7516b1651d06820dd89be9444
[ "OLDAP-2.7", "OLDAP-2.6", "OLDAP-2.4", "OLDAP-2.5", "OLDAP-2.3" ]
null
null
null
Goldeneye Revenge/game.cpp
scruffyfox/Goldeneye-Revenge
29b9a9ca668260f7516b1651d06820dd89be9444
[ "OLDAP-2.7", "OLDAP-2.6", "OLDAP-2.4", "OLDAP-2.5", "OLDAP-2.3" ]
null
null
null
////////////////////////////////////////////////////////////// // // Golden Eye Reveng - 2011 Games design project by // Callum Taylor // // game.cpp - This file will handle all the game rendering // ////////////////////////////////////////////////////////////// // Let us include the main file for all the system includes and prototypes #include "main.h" // Initialize the FPS variables int averageFPS = 0; int fpsCount = 0; // Initialize the models vairables Map *dam; Object *skyBox; Object *crosshair; // Text strings for the menu // TextString 0: Select Mission // TextString 1: Options // TextString 2: Exit Game // TextString 3: Screen Resolution // TextString 4: Game Volume // TextString 5: Use Joystick // TextString 6: Joystick Sensitivity // TextString 7: Keyboard Key Mode // TextString 9: Invert Y Axis TextString *menuStrings[10]; // Buttons for the menu // Button 0: back to main menu // Button 1: back to Mission screen // Button 2: Start Misson // Button 3: Resume Game // Button 4: Mission 1 button Object *buttons[5]; // Menu screens // Menu 0: Main Menu // Menu 1: Select Mission // Menu 2: Mission Brefing // Menu 3: Options Object *menu[8]; // Paused menu text // Paused Menu 0: Resume game // Paused Menu 1: Settings // Paused Menu 2: Exit TextString *pausedMenu[8]; // Initialize the sound variables // Sounds 0: Menu background // Sounds 1: Page turn // Sounds 2: Mission 1 background Sound *sounds[3]; // Create an array of available screen resolutions Size screenRes[8]; // Create the text string for the current screen resolution TextString *currentScreenResolution; // Create the text string for the current game volume TextString *currentGameVolume; // Create the text string for the use joystick toggler TextString *useJoystick; // Create the text string for the joystick sensitvity TextString *joystickSensitivity; int currentScreenRes = 0; // Create the text string for the current key mode TextString *currentKeyMode; // Create the text string for the inverted y axis status TextString *invertYAxis; // Initialize the lighting variables GLfloat lightAmbient[] = {.5f, .5f, .5f, 1.0f}; GLfloat lightDiffuse[] = {.7f, .7f, .7f, 1.0f}; GLfloat lightSpecular[] = {1, 1, 1, 1}; float lightPos[] = {0, 0, 0, 1.0}; Size menuSize; Size menuChange; ////////////////////////////////////////////////////////////// // // This function will handle the mouse presses // button 0: left mouse down // button 1: right mouse down // button 2: scroll wheel down // button 3: left mouse up // button 4: right mouse up // button 5: scroll wheel up // ////////////////////////////////////////////////////////////// int fireTick = 0; void checkMouse(int button, int x, int y) { if (button == 3) { if (GAME_MODE == IN_MENU) { if (MENU_ID == MENU1) { // We need to check each object for button presses // Select Mission menuStrings[0]->checkMouse(x, y, button, selectMissionPress); // Options menuStrings[1]->checkMouse(x, y, button, optionsButtonPress); // Exit Game menuStrings[2]->checkMouse(x, y, button, exitGame); } else if (MENU_ID == MENU2) { // Back to main menu buttons[0]->checkMouse(x, y, button, mainMenu); // Mission 1 button buttons[4]->checkMouse(x, y, button, missionBriefing); } else if (MENU_ID == MENU3) { // Back to Mission screen buttons[1]->checkMouse(x, y, button, missionSelection); // Start Game buttons[2]->checkMouse(x, y, button, startGame); } else if (MENU_ID == OPTIONS) { // Back to Main Menu buttons[0]->checkMouse(x, y, button, mainMenu); currentScreenResolution->checkMouse(x, y, button, changeScreenRes); currentGameVolume->checkMouse(x, y, button, changeGameVolume); useJoystick->checkMouse(x, y, button, toggleJoystick); joystickSensitivity->checkMouse(x, y, button, changeJoystickSensitivity); currentKeyMode->checkMouse(x, y, button, changeKeyMode); invertYAxis->checkMouse(x, y, button, changeInvert); } else if (MENU_ID == GAME_OPTIONS) { // Resume Game buttons[3]->checkMouse(x, y, button, showPausedMenu); currentScreenResolution->checkMouse(x, y, button, changeScreenRes); currentGameVolume->checkMouse(x, y, button, changeGameVolume); useJoystick->checkMouse(x, y, button, toggleJoystick); joystickSensitivity->checkMouse(x, y, button, changeJoystickSensitivity); currentKeyMode->checkMouse(x, y, button, changeKeyMode); invertYAxis->checkMouse(x, y, button, changeInvert); } } if (GAME_STATE == GAME_PAUSED) { // Resume Game pausedMenu[0]->checkMouse(x, y, button, togglePause); // Options pausedMenu[1]->checkMouse(x, y, button, showOptionsInGame); // Exit Game pausedMenu[2]->checkMouse(x, y, button, exitGame); } } if (GAME_MODE == IN_GAME && GAME_STATE != GAME_PAUSED) { PLAYER->fireWeapon(button); } } ////////////////////////////////////////////////////////////// // // This function closes the game // ////////////////////////////////////////////////////////////// void exitGame() { deInitialize(); } ////////////////////////////////////////////////////////////// // // This function toggles the pause and play state // ////////////////////////////////////////////////////////////// void togglePause() { if (GAME_MODE != IN_GAME) return; if (GAME_STATE == GAME_PAUSED) { // Reset the position of the mouse so the screen dosen't // jump everywhere SetCursorPos(middle.x, middle.y); GAME_STATE = GAME_RUNNING; } else { GAME_STATE = GAME_PAUSED; } } ////////////////////////////////////////////////////////////// // // This function will handle the other key presses such as // menu, pause etc. // ////////////////////////////////////////////////////////////// void checkInputs(WPARAM wParam) { switch(wParam) { // Key: R case 82: { PLAYER->reloadWeapon(); break; } // Key: 1 case 49: { PLAYER->setCurrentWeapon(0); break; } // Key: 2 case 50: { PLAYER->setCurrentWeapon(1); break; } // Key: 3 case 51: { PLAYER->setCurrentWeapon(2); break; } } } ////////////////////////////////////////////////////////////// // // This function checks for the inputs made by the joystick // ////////////////////////////////////////////////////////////// void checkJoystickInput() { if (GAME_MODE != IN_GAME) return; static int button; if (joystick->getState().Gamepad.wButtons == 0) { // Check if the button is not 0 if (button != 0) { if (button & XINPUT_GAMEPAD_START) { // Toggle the pause menu togglePause(); } else if (button & XINPUT_GAMEPAD_X) { // Reload the weapon PLAYER->reloadWeapon(); } else if (button & XINPUT_GAMEPAD_LEFT_SHOULDER) { // Cycle through the weapons backwards PLAYER->previousWeapon(); } else if (button & XINPUT_GAMEPAD_RIGHT_SHOULDER) { // Cycle through the weapons forwards PLAYER->nextWeapon(); } button = 0; } } else { button = joystick->getState().Gamepad.wButtons; } } ////////////////////////////////////////////////////////////// // // This function checks for the user movement (keys W, A, S, D) // and (UP, LEFT, DOWN, RIGHT) // ////////////////////////////////////////////////////////////// void checkMovement() { if (GAME_MODE == IN_GAME) { // Check if we are using a joystick or keyboard if (joystick->isUsable()) { if (useThumbPad) { // Get the coordinates Vector2 joystickPos = Vector2 ( (joystick->getStickMagnitude(XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) * 2) * joystick->getCoordsFromLStick().x, (joystick->getStickMagnitude(XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) * 2) * joystick->getCoordsFromLStick().y ); // For some reason we have to swap the coordinates PLAYER->moveY(joystickPos.x * (MOVE_SPEED * 5)); PLAYER->moveX(joystickPos.y * MOVE_SPEED); } else { XINPUT_GAMEPAD movementState = joystick->getState().Gamepad; if (movementState.wButtons & XINPUT_GAMEPAD_DPAD_UP) { if (!PLAYER->collisionTest(dam, 'w')) { PLAYER->moveX(MOVE_SPEED); } } if (movementState.wButtons & XINPUT_GAMEPAD_DPAD_DOWN) { if (!PLAYER->collisionTest(dam, 's')) { PLAYER->moveX(-MOVE_SPEED); } } if (movementState.wButtons & XINPUT_GAMEPAD_DPAD_LEFT) { if (!PLAYER->collisionTest(dam, 'a')) { PLAYER->moveY(-MOVE_SPEED * 5); } } if (movementState.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) { if (!PLAYER->collisionTest(dam, 'd')) { PLAYER->moveY(MOVE_SPEED * 5); } } } } else { if (GetKeyState(keys[0 + selectedMovementMode]) & 0x80) { if (!PLAYER->collisionTest(dam, 'w')) { PLAYER->moveX(MOVE_SPEED); } } if (GetKeyState(keys[2 + selectedMovementMode]) & 0x80) { if (!PLAYER->collisionTest(dam, 's')) { PLAYER->moveX(-MOVE_SPEED); } } if (GetKeyState(keys[1 + selectedMovementMode]) & 0x80) { if (!PLAYER->collisionTest(dam, 'a')) { PLAYER->moveY(-MOVE_SPEED * 5); } } if (GetKeyState(keys[3 + selectedMovementMode]) & 0x80) { if (!PLAYER->collisionTest(dam, 'd')) { PLAYER->moveY(MOVE_SPEED * 5); } } } } } ////////////////////////////////////////////////////////////// // // This function will draw the crosshair // ////////////////////////////////////////////////////////////// void drawCrosshair() { // Here we need to either get the mouse coordinates, or // joysticks. Vector2 mousePos; if (joystick->isUsable()) { mousePos = joystick->getCoodinates(); } else { POINT _mousePos; GetCursorPos(&_mousePos); ScreenToClient(g_hWnd, &_mousePos); mousePos.x = _mousePos.x; mousePos.y = _mousePos.y; } crosshair->position(mousePos.x - (crosshair->getSize().width / 2), mousePos.y - (crosshair->getSize().height / 2)); crosshair->drawObject(); } ////////////////////////////////////////////////////////////// // // This function generates the texture IDs // ////////////////////////////////////////////////////////////// void generateMenuTextures() { menu[0]->genTexture(); menu[1]->genTexture(); menu[2]->genTexture(); menu[3]->genTexture(); crosshair->genTexture(); buttons[0]->genTexture(); buttons[1]->genTexture(); buttons[2]->genTexture(); buttons[3]->genTexture(); // Loop through and find what screen resolution in our array is the // one we are currently using for (int screenLoop = 0; screenLoop < ARRAY_LENGTH(screenRes); screenLoop++) { if (screenRes[screenLoop].width == SCREEN_WIDTH && screenRes[screenLoop].height == SCREEN_HEIGHT) { currentScreenResolution->setText(toString(screenRes[screenLoop].width) + "x" + toString(screenRes[screenLoop].height)); currentScreenRes = screenLoop; } } } void generateGameTextures() { PLAYER->generateWeaponTextures(); dam->generateAllBuffers(); skyBox->genTexture(); Waypoint wPoint; wPoint.position = CAMERA.cameraPosition + Vector3(10, 0, 0); wPoint.view = CAMERA.cameraView + Vector3(10, 0, 0); wPoint.speed = 0.1; CAMERA.addWaypoint(wPoint); wPoint.position = CAMERA.cameraPosition + Vector3(25, 10, 0); wPoint.view = CAMERA.cameraView + Vector3(20, 0, 0); wPoint.up = CAMERA.cameraUpVector + Vector3(10, 0, 0); wPoint.speed = 0.1; CAMERA.addWaypoint(wPoint); } ////////////////////////////////////////////////////////////// // // This function initializes the open GL functions so we can // use them // ////////////////////////////////////////////////////////////// void initializeARB() { if ((glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB")) == NULL) { error("Your video card does not support glGenBuffersARB."); } if ((glBindBufferARB = (PFNGLBINDBUFFERARBPROC)wglGetProcAddress("glBindBufferARB")) == NULL) { error("Your video card does not support glBindBufferARB."); } if ((glBufferDataARB = (PFNGLBUFFERDATAARBPROC)wglGetProcAddress("glBufferDataARB")) == NULL) { error("Your video card does not support glBufferDataARB."); } if ((glBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)wglGetProcAddress("glBufferSubDataARB")) == NULL) { error("Your video card does not support glBuffersSubDataARB"); } if ((glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)wglGetProcAddress("glActiveTextureARB")) == NULL) { error("Your video card does not support glActiveTextureARB"); } } ////////////////////////////////////////////////////////////// // // This function initializes the sound library // ////////////////////////////////////////////////////////////// void initializeAL() { // Initialize openAL alutInit(NULL, 0); alGetError(); } ////////////////////////////////////////////////////////////// // // This function initializes the GL stage // ////////////////////////////////////////////////////////////// void initializeGL(int width, int height) { g_hDC = GetDC(g_hWnd); if (!setupPixelFormat(g_hDC)) { PostQuitMessage(0); } // Set the current context to be openGL g_hRC = wglCreateContext(g_hDC); wglMakeCurrent(g_hDC, g_hRC); int pcVer = atof((const char *)glGetString(GL_VERSION)) >= 3.0; if (!pcVer) { error("You need a minimum of OpenGL 3.0 to run this game"); } // Initialize the ARB functions which we need for VBO's initializeARB(); resizeScene(SCREEN_WIDTH, SCREEN_HEIGHT); glEnable(GL_BLEND); // Enable alpha testing to remove alpha channels glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0); glDisable(GL_BLEND); // Enable lighting and texturing glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); // Set the available screen resolution screenRes[0] = Size(800, 600); screenRes[1] = Size(1024, 768); screenRes[2] = Size(1280, 720); screenRes[3] = Size(1280, 800); screenRes[4] = Size(1440, 900); screenRes[5] = Size(1600, 900); screenRes[6] = Size(1920, 1080); screenRes[7] = Size(1920, 1200); memset(sounds, NULL, ARRAY_LENGTH(sounds)); menuSize = Size(SCREEN_HEIGHT - 50, SCREEN_HEIGHT - 50); menuChange = Size(menuSize.width / 544.0, menuSize.height / 534.0); } ////////////////////////////////////////////////////////////// // // This function handles the lighting. // ////////////////////////////////////////////////////////////// void initializeLighting() { glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient); glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, lightSpecular); glLightfv(GL_LIGHT0, GL_POSITION, lightPos); } ////////////////////////////////////////////////////////////// // // This function changes the current matrix stack to enable // the use of 2D Functions. This is needed for the HUD display // ////////////////////////////////////////////////////////////// void loadFor2D() { // Disable the lighting from the 3d projection otherwise // it messes with out lovely 2d texturing glDisable(GL_LIGHTING); // Disable depth text otherwise it wont be 2d glDisable(GL_DEPTH_TEST); // Set the matrix mode to projection so we can modify the // projection glMatrixMode(GL_PROJECTION); // Set the orthographic (2D) view glLoadIdentity(); glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1); // Set the matrix mode to model view so we can draw the game glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } ////////////////////////////////////////////////////////////// // // This function changes the matrix to 3D to enable the user // of the 3D functions. This is needed for the game scene // rendering // ////////////////////////////////////////////////////////////// void loadFor3D() { // Enable the required matricies for 3d projection glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glEnable(GL_POLYGON_SMOOTH); // Show the lighting initializeLighting(); // Set the matrix mode to projection so we can modify the // projection glMatrixMode(GL_PROJECTION); // Set the perspective view glLoadIdentity(); gluPerspective(70.0, (GLfloat)SCREEN_WIDTH / (GLfloat)SCREEN_HEIGHT, 0.005f, 1000.0f); // Set the matrix mode to model view so we can draw the game glMatrixMode(GL_MODELVIEW); // Clear the stage glLoadIdentity(); } ////////////////////////////////////////////////////////////// // // This function loads the sounds // ////////////////////////////////////////////////////////////// void loadMenuSounds() { sounds[0] = new Sound(); sounds[0]->loadSound("sound/menu/menu.wav", true); sounds[1] = new Sound(); sounds[1]->loadSound("sound/menu/menuchange.wav"); } void loadGameSounds() { sounds[2] = new Sound(); sounds[2]->loadSound("sound/ambient/mission1.wav"); } ////////////////////////////////////////////////////////////// // // This function loads the needed textures and models // ////////////////////////////////////////////////////////////// void loadMenuTextures() { // Cursor crosshair crosshair = new Object(); crosshair->loadTexture("graphics/textures/crosshair.tga"); crosshair->setTransparency(true); crosshair->size(52, 52); // Main Menu background menu[0] = new Object(); menu[0]->loadTexture("graphics/textures/menu/menu1.tga"); menu[0]->setTransparency(true); // Select Mission background menu[1] = new Object(); menu[1]->loadTexture("graphics/textures/menu/menu2.tga"); menu[1]->setTransparency(true); // Mission Briefing background menu[2] = new Object(); menu[2]->loadTexture("graphics/textures/menu/menu3.tga"); menu[2]->setTransparency(true); // Settings screen background menu[3] = new Object(); menu[3]->loadTexture("graphics/textures/menu/settings.tga"); menu[3]->setTransparency(true); // Select Mission text menuStrings[0] = new TextString("Select Mission"); menuStrings[0]->setFontFace(courierNew32); // Options text menuStrings[1] = new TextString("Options"); menuStrings[1]->setFontFace(courierNew32); // Exit game text menuStrings[2] = new TextString("Exit Game"); menuStrings[2]->setFontFace(courierNew32); // Screen Resolution text menuStrings[3] = new TextString("Screen Resolution:"); menuStrings[3]->setFontFace(courierNew32); // Game Volume Text menuStrings[4] = new TextString("Volume:"); menuStrings[4]->setFontFace(courierNew32); // Use Joystick Text menuStrings[5] = new TextString("Use Joystick:"); menuStrings[5]->setFontFace(courierNew32); // Joystick Sensitivity Text menuStrings[6] = new TextString("Joystick Sensitivity:"); menuStrings[6]->setFontFace(courierNew32); // Keyboard key mode menuStrings[7] = new TextString("Key Mode:"); menuStrings[7]->setFontFace(courierNew32); // Invert Y Axis menuStrings[9] = new TextString("Invert Y Axis:"); menuStrings[9]->setFontFace(courierNew32); // Invert Y Axis placeholder text invertYAxis = new TextString(CAMERA.invertYAxis ? "Yes" : "No"); invertYAxis->setFontFace(courierNew32); // Game Volume placeholder text currentGameVolume = new TextString(); currentGameVolume->setFontFace(courierNew32); // Screen Resolution placeholder text currentScreenResolution = new TextString(); currentScreenResolution->setFontFace(courierNew32); // Joystick toggler placeholder text useJoystick = new TextString(); useJoystick->setFontFace(courierNew32); // Keymode placeholder text currentKeyMode = new TextString(); currentKeyMode->setFontFace(courierNew32); // Joystick sensitivity toggler text joystickSensitivity = new TextString(); joystickSensitivity->setFontFace(courierNew32); // Back to main menu buttons[0] = new Object(); buttons[0]->loadTexture("graphics/textures/back.tga"); buttons[0]->setTransparency(true); // Back to missions buttons[1] = new Object(); buttons[1]->loadTexture("graphics/textures/back.tga"); buttons[1]->setTransparency(true); // Start Mission buttons[2] = new Object(); buttons[2]->loadTexture("graphics/textures/start.tga"); buttons[2]->setTransparency(true); // Resume Game buttons[3] = new Object(); buttons[3]->loadTexture("graphics/textures/back.tga"); buttons[3]->setTransparency(true); // Mission 1 button buttons[4] = new Object(); buttons[4]->color(255, 255, 255, 0); buttons[4]->setTransparency(true); setMenuPositions(); sounds[0]->playSound(); } ////////////////////////////////////////////////////////////// // // This function sets the menu positions and sizes when the // resolution is changed // ////////////////////////////////////////////////////////////// void setMenuPositions() { menuSize = Size(SCREEN_HEIGHT - 50, SCREEN_HEIGHT - 50); menuChange = Size(menuSize.width / 544.0, menuSize.height / 534.0); Vector3 menuPosition = Vector3((SCREEN_WIDTH - (SCREEN_HEIGHT - 50)) / 2, (SCREEN_HEIGHT - (SCREEN_HEIGHT - 50)) / 2, 0); Size backSize = Size(SCREEN_HEIGHT / 20, ((57 / 27) * (SCREEN_HEIGHT / 20))); Vector3 backPosition = Vector3(menuPosition.x + menuSize.width - (backSize.width * 1.5), menuPosition.y + (backSize.height), 0); Vector3 backPosition2 = Vector3(0, menuChange.height * 130, 0); Vector3 mission1Position = Vector3(menuPosition.x + (menuChange.width * 16), menuPosition.y + (menuChange.height * 69), 0); // Main Menu menu[0]->position(menuPosition); menu[0]->size(menuSize); // Mission Page menu[1]->position(menuPosition); menu[1]->size(menuSize); // Mission Briefing menu[2]->position(menuPosition); menu[2]->size(menuSize); // Options Page menu[3]->position(menuPosition); menu[3]->size(menuSize); // Select Mission menuStrings[0]->scaleMag = menuChange.width / 1.1; menuStrings[0]->color(255, 255, 255); menuStrings[0]->setCharacerSpacing(18 * menuChange.width); menuStrings[0]->position(middle.x - (menuStrings[0]->getCalculatedSize().width / 1.9), middle.y); // Options menuStrings[1]->scaleMag = menuChange.width / 1.1; menuStrings[1]->color(255, 255, 255); menuStrings[1]->setCharacerSpacing(18 * menuChange.width); menuStrings[1]->position(middle.x - (menuStrings[1]->getCalculatedSize().width / 1.9), middle.y + (menuChange.height * 50)); // Exit Game menuStrings[2]->scaleMag = menuChange.width / 1.1; menuStrings[2]->color(255, 255, 255); menuStrings[2]->setCharacerSpacing(18 * menuChange.width); menuStrings[2]->position(middle.x - (menuStrings[2]->getCalculatedSize().width / 1.9), middle.y + (menuChange.height * 100)); // Screen Resolution menuStrings[3]->scaleMag = menuChange.width / 1.5; menuStrings[3]->color(255, 255, 255); menuStrings[3]->setCharacerSpacing(14 * menuChange.width); menuStrings[3]->position(menuPosition.x + (menuChange.width * 50), menuPosition.y + (menuChange.height * 70)); // Current Screen Resolution currentScreenResolution->scaleMag = menuChange.width / 1.5; currentScreenResolution->color(255, 255, 255); currentScreenResolution->setCharacerSpacing(14 * menuChange.width); currentScreenResolution->position(menuStrings[3]->getPosition().x + menuStrings[3]->getCalculatedSize().width + (menuChange.height * 20), menuStrings[3]->getPosition().y); // Game Volume menuStrings[4]->scaleMag = menuChange.width / 1.5; menuStrings[4]->color(255, 255, 255); menuStrings[4]->setCharacerSpacing(14 * menuChange.width); menuStrings[4]->position(menuStrings[3]->getPosition().x, menuStrings[3]->getPosition().y + (menuChange.height * 50)); // Current Volume Text currentGameVolume->scaleMag = menuChange.width / 1.5; currentGameVolume->color(255, 255, 255); currentGameVolume->setCharacerSpacing(14 * menuChange.width); currentGameVolume->position(menuStrings[4]->getPosition().x + menuStrings[4]->getCalculatedSize().width + (menuChange.height * 20), menuStrings[4]->getPosition().y); // Use Joystick menuStrings[5]->scaleMag = menuChange.width / 1.5; menuStrings[5]->color(255, 255, 255); menuStrings[5]->setCharacerSpacing(14 * menuChange.width); menuStrings[5]->position(menuStrings[4]->getPosition().x, menuStrings[4]->getPosition().y + (menuChange.height * 50)); // Joystick toggler text useJoystick->scaleMag = menuChange.width / 1.5; useJoystick->color(255, 255, 255); useJoystick->setCharacerSpacing(14 * menuChange.width); useJoystick->position(menuStrings[5]->getPosition().x + menuStrings[5]->getCalculatedSize().width + (menuChange.height * 20), menuStrings[5]->getPosition().y); // Joystick Sensitivity menuStrings[6]->scaleMag = menuChange.width / 1.5; menuStrings[6]->color(255, 255, 255); menuStrings[6]->setCharacerSpacing(14 * menuChange.width); menuStrings[6]->position(menuStrings[5]->getPosition().x, menuStrings[5]->getPosition().y + (menuChange.height * 50)); joystickSensitivity->scaleMag = menuChange.width / 1.5; joystickSensitivity->color(255, 255, 255); joystickSensitivity->setCharacerSpacing(14 * menuChange.width); joystickSensitivity->position(menuStrings[6]->getPosition().x + menuStrings[6]->getCalculatedSize().width + (menuChange.height * 20), menuStrings[6]->getPosition().y); joystickSensitivity->setText(toString((int)(joystick->sensitivity * 100.0f)) + "%"); // Key Mode menuStrings[7]->scaleMag = menuChange.width / 1.5; menuStrings[7]->color(255, 255, 255); menuStrings[7]->setCharacerSpacing(14 * menuChange.width); if (joystick->isUsable()) { useJoystick->setText("Yes"); menuStrings[7]->position(menuStrings[6]->getPosition().x, menuStrings[6]->getPosition().y + (menuChange.height * 50)); } else { useJoystick->setText("No"); } // Key Mode currentKeyMode->scaleMag = menuChange.width / 1.5; currentKeyMode->color(255, 255, 255); currentKeyMode->setCharacerSpacing(14 * menuChange.width); currentKeyMode->position(menuStrings[7]->getPosition().x + menuStrings[7]->getCalculatedSize().width + (menuChange.height * 20), menuStrings[7]->getPosition().y); // Invert Y menuStrings[9]->scaleMag = menuChange.width / 1.5; menuStrings[9]->color(255, 255, 255); menuStrings[9]->setCharacerSpacing(14 * menuChange.width); menuStrings[9]->position(menuStrings[7]->getPosition().x, menuStrings[7]->getPosition().y + (menuChange.height * 50)); invertYAxis->scaleMag = menuChange.width / 1.5; invertYAxis->color(255, 255, 255); invertYAxis->setCharacerSpacing(14 * menuChange.width); invertYAxis->position(menuStrings[9]->getPosition().x + menuStrings[9]->getCalculatedSize().width + (menuChange.height * 20), menuStrings[9]->getPosition().y); // Back to main menu buttons[0]->position(backPosition); buttons[0]->size(backSize); // Back to mission menu buttons[1]->position(backPosition + backPosition2); buttons[1]->size(backSize); // Start Mission buttons[2]->position(backPosition); buttons[2]->size(backSize); // Resume Game buttons[3]->position(backPosition); buttons[3]->size(backSize); // Mission 1 button buttons[4]->vertex(Rect(0, 0, menuChange.width * 114, menuChange.height * 88)); buttons[4]->position(mission1Position); menuBackground->size(SCREEN_WIDTH, SCREEN_HEIGHT); } ////////////////////////////////////////////////////////////// // // This function loads the game textures into memory // ////////////////////////////////////////////////////////////// Matrix4 fpMatrix; void loadGameTextures() { // Load the map settings dam = new Map(); dam->loadSettings("maps/dam/dam.ini"); // Create the skybox skyBox = new Object(); skyBox->position(0, 0); skyBox->loadTexture("graphics/textures/skybox.tga"); // Resume Game pausedMenu[0] = new TextString(); pausedMenu[0]->setFontFace(courierNew32); pausedMenu[0]->setText("Resume Game"); pausedMenu[0]->color(255, 255, 255, 255); // Settings pausedMenu[1] = new TextString(); pausedMenu[1]->setFontFace(courierNew32); pausedMenu[1]->setText("Settings"); pausedMenu[1]->color(255, 255, 255, 255); // Exit game pausedMenu[2] = new TextString(); pausedMenu[2]->setFontFace(courierNew32); pausedMenu[2]->setText("Exit Game"); pausedMenu[2]->color(255, 255, 255, 255); // Create the first person matrix fpMatrix = Matrix4 ( 1, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, -0.005, -0.03, 1.0 ); setGamePositions(); } void setGamePositions() { menuSize = Size(SCREEN_HEIGHT - 50, SCREEN_HEIGHT - 50); menuChange = Size(menuSize.width / 544.0, menuSize.height / 534.0); skyBox->size(SCREEN_WIDTH, SCREEN_HEIGHT); // Resume Game pausedMenu[0]->setCharacerSpacing(18 * menuChange.width); pausedMenu[0]->scaleMag = menuChange.width / 1.1; pausedMenu[0]->position(middle.x - ((pausedMenu[0]->getCalculatedSize().width / 2)), middle.y - (menuChange.height * 50)); // Settings pausedMenu[1]->setCharacerSpacing(18 * menuChange.width); pausedMenu[1]->scaleMag = menuChange.width / 1.1; pausedMenu[1]->position(middle.x - ((pausedMenu[1]->getCalculatedSize().width / 2)), pausedMenu[0]->getPosition().y + (menuChange.height * 50)); // Exit Game pausedMenu[2]->setCharacerSpacing(18 * menuChange.width); pausedMenu[2]->scaleMag = menuChange.width / 1.1; pausedMenu[2]->position(middle.x - ((pausedMenu[2]->getCalculatedSize().width / 2)), pausedMenu[1]->getPosition().y + (menuChange.height * 50)); } ////////////////////////////////////////////////////////////// // // This function renders the game stage // ////////////////////////////////////////////////////////////// void renderGame() { glPushMatrix(); CAMERA.drawCamera(); dam->drawMap(); glPopMatrix(); } void renderPlayer() { glPushMatrix(); // This resets the view matrix basically making the gun // follow the camera glLoadMatrixf(fpMatrix); PLAYER->drawCurrentWeapon(); glPopMatrix(); } void renderGame2D() { glPushMatrix(); PLAYER->drawHUD(); glPopMatrix(); } ////////////////////////////////////////////////////////////// // // This function will determine on what is rendered depending // on the current game mode // ////////////////////////////////////////////////////////////// void renderScreen() { // Clear the screen with the default colour glClearColor(GL_COLOR_REDf[0], GL_COLOR_BLACKf[1], GL_COLOR_BLACKf[2], GL_COLOR_BLACKf[3]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (GAME_STATE == GAME_RUNNING) { ++averageFPS; if (GAME_MODE == IN_GAME) { // Lets create a backdrop on the game loadFor2D(); { skyBox->drawObject(); } } loadFor3D(); { switch(GAME_MODE) { case IN_GAME: { CAMERA.moveByMouse = true; renderGame(); renderPlayer(); break; } } // Update the FPS if (abs(currentTime - time(0)) >= 2) { currentTime = time(0); FPS = averageFPS; averageFPS = 0; } } loadFor2D(); { switch(GAME_MODE) { case IN_MENU: { switch (MENU_ID) { case MENU1: { showMenu1(); break; } case MENU2: { showMenu2(); break; } case MENU3: { showMenu3(); break; } case GAME_OPTIONS: case OPTIONS: { showOptions(); break; } } drawCrosshair(); CAMERA.moveByMouse = false; break; } case IN_GAME: { renderGame2D(); break; } } glPushMatrix(); string text; text = "FPS: "; text += toString(FPS); TextString *fps = new TextString(); fps->setFontFace(courierNew); fps->setCharacerSpacing(12); fps->color(255, 255, 255); fps->setText(text); fps->position(10, 10, 0); fps->drawString(); delete fps; glPopMatrix(); } } else if (GAME_STATE == GAME_PAUSED) { loadFor2D(); { menuBackground->drawObject(); pausedMenu[0]->drawString(); pausedMenu[1]->drawString(); pausedMenu[2]->drawString(); drawCrosshair(); } } else if (GAME_STATE == GAME_LOADING) { loadFor2D(); { menuBackground->drawObject(); TextString *loading = new TextString(); loading->scaleMag = 1.7f; loading->setCharacerSpacing(14); loading->setFontFace(courierNew); loading->color(255, 255, 255, 255); loading->setText("LOADING..."); loading->position(middle.x - (loading->getCalculatedSize().width / 2), middle.y, 0); loading->drawString(); delete loading; } } SwapBuffers(g_hDC); } ////////////////////////////////////////////////////////////// // // Golden Eye Revenge - 2011 Games design project by // Callum Taylor // // Button Handlers // ////////////////////////////////////////////////////////////// void selectMissionPress() { sounds[1]->playSound(); MENU_ID = MENU2; } void optionsButtonPress() { sounds[1]->playSound(); MENU_ID = OPTIONS; } void mainMenu(int button) { sounds[1]->playSound(); MENU_ID = MENU1; } void missionBriefing(int button) { sounds[1]->playSound(); MENU_ID = MENU3; } void missionSelection(int button) { sounds[1]->playSound(); MENU_ID = MENU2; } void startGame(int button) { sounds[1]->playSound(); buttons[5]->setClickable(false); // Load the main game GAME_STATE = GAME_LOADING; HANDLE threadHandle = 0; threadHandle = CreateThread(NULL, 0, loadGame, NULL, 0, NULL); // Show the loading screen while (GAME_STATE == GAME_LOADING) { renderScreen(); } // The thread has finished so lets close it and finish // loading the game WaitForSingleObject(threadHandle, INFINITE); CloseHandle(threadHandle); // Load the player settings PLAYER = new Player(); Vector3 position = PLAYER->getPlayerPos(); // Set the position of the camera CAMERA.positionCamera(position.x, position.y, position.z, 0, 1.5, 5, 0, 1, 0); // Now all the textures have been coppied to RAM, we need // to generate their ID's so we can actually use them generateGameTextures(); sounds[0]->stopSound(); sounds[2]->playSound(); GAME_MODE = IN_GAME; } ////////////////////////////////////////////////////////////// // // This function changes the screen resolution // ////////////////////////////////////////////////////////////// void changeScreenRes() { if (currentScreenRes == ARRAY_LENGTH(screenRes) || maxScreenRes == screenRes[currentScreenRes]) { currentScreenRes = 0; currentScreenResolution->setText(toString(screenRes[currentScreenRes].width) + "x" + toString(screenRes[currentScreenRes].height)); resizeWindow(screenRes[currentScreenRes].width, screenRes[currentScreenRes].height); } else { currentScreenRes++; currentScreenResolution->setText(toString(screenRes[currentScreenRes].width) + "x" + toString(screenRes[currentScreenRes].height)); resizeWindow(screenRes[currentScreenRes].width, screenRes[currentScreenRes].height); } settings->writeSetting("main", "width", (char *)toString(screenRes[currentScreenRes].width).c_str(), true); settings->writeSetting("main", "height", (char *)toString(screenRes[currentScreenRes].height).c_str(), true); } ////////////////////////////////////////////////////////////// // // This function changes game volume // ////////////////////////////////////////////////////////////// void changeGameVolume() { if (soundVolume + 0.1 >= 1.1) { soundVolume = 0.0; } else { soundVolume += 0.1; } for (int soundsLoop = 0; soundsLoop < ARRAY_LENGTH(sounds); soundsLoop++) { if (sounds[soundsLoop] != NULL) { sounds[soundsLoop]->updateVolume(soundVolume); } } settings->writeSetting("sound", "volume", (char *)toString(soundVolume).c_str(), true); } ////////////////////////////////////////////////////////////// // // This function updates the joystick sensitivity // ////////////////////////////////////////////////////////////// void changeKeyMode() { if (joystick->isUsable()) { useThumbPad = !useThumbPad; settings->writeSetting("joystick", "keymode", (useThumbPad ? "0" : "1"), true); } else { if (selectedMovementMode == 0) { selectedMovementMode = 4; settings->writeSetting("keyboard", "keymode", "1", true); } else { selectedMovementMode = 0; settings->writeSetting("keyboard", "keymode", "0", true); } } } ////////////////////////////////////////////////////////////// // // This function updates the invert y axis bool in the camera // ////////////////////////////////////////////////////////////// void changeInvert() { CAMERA.invertYAxis = !CAMERA.invertYAxis; invertYAxis->setText(CAMERA.invertYAxis ? "Yes" : "No"); settings->writeSetting("control", "inverty", (char *)toString(CAMERA.invertYAxis).c_str(), true); } ////////////////////////////////////////////////////////////// // // This function updates the joystick sensitivity // ////////////////////////////////////////////////////////////// void changeJoystickSensitivity() { if (joystick->sensitivity + 0.1 >= 1.1) { joystick->sensitivity = 0.1; } else { joystick->sensitivity += 0.1; } joystickSensitivity->setText(toString((int)(joystick->sensitivity * 100.0f)) + "%"); settings->writeSetting("joystick", "sensitivity", (char *)toString(joystick->sensitivity).c_str(), true); } ////////////////////////////////////////////////////////////// // // This function turns the joystick on or off // ////////////////////////////////////////////////////////////// void toggleJoystick() { if (joystick->isUsable()) { SetCursorPos(joystick->getCoodinates().x, joystick->getCoodinates().y); joystick->disconnect(); useJoystick->setText("No"); } else { POINT mousePoint; GetCursorPos(&mousePoint); ScreenToClient(g_hWnd, &mousePoint); joystick->updateCoordinates(mousePoint.x, mousePoint.y); joystick->connect(); useJoystick->setText("Yes"); } settings->writeSetting("joystick", "usejoystick", (char *)toString(joystick->isUsable()).c_str(), true); } ////////////////////////////////////////////////////////////// // // This function resumes the game // ////////////////////////////////////////////////////////////// void resumeGame(int button) { GAME_STATE = GAME_RUNNING; GAME_MODE = IN_GAME; MENU_ID = 0; } ////////////////////////////////////////////////////////////// // // Golden Eye Reveng - 2011 Games design project by // Callum Taylor // // Menu Functions // ////////////////////////////////////////////////////////////// void showMenu1() { menuBackground->drawObject(); menu[0]->drawObject(); menuStrings[0]->drawString(); menuStrings[1]->drawString(); menuStrings[2]->drawString(); } void showMenu2() { menuBackground->drawObject(); menu[1]->drawObject(); // Back to main menu buttons[0]->drawObject(); // Mission 1 button buttons[4]->drawObject(); } void showMenu3() { menuBackground->drawObject(); menu[2]->drawObject(); // Back to missions buttons[1]->drawObject(); // Start Game buttons[2]->drawObject(); } ////////////////////////////////////////////////////////////// // // This is the options menu // ////////////////////////////////////////////////////////////// void showOptions() { menuBackground->drawObject(); menu[3]->drawObject(); buttons[3]->drawObject(); // Draw the screen resolution text menuStrings[3]->drawString(); currentScreenResolution->drawString(); // Draw the volume string menuStrings[4]->drawString(); currentGameVolume->setText(toString((int)(soundVolume * 100)) + "%"); currentGameVolume->drawString(); if (joystick->isConnected()) { // Draw the use joystick string currentKeyMode->setText(useThumbPad ? "Thumb Pad" : "D PAD"); menuStrings[5]->drawString(); useJoystick->drawString(); if (joystick->isUsable()) { // Draw the joystick sensitivity string currentKeyMode->setText(useThumbPad ? "Thumb Pad" : "D PAD"); menuStrings[6]->drawString(); joystickSensitivity->drawString(); menuStrings[7]->position(menuStrings[6]->getPosition().x, menuStrings[6]->getPosition().y + (menuChange.height * 50)); } else { currentKeyMode->setText(selectedMovementMode == 0 ? "WASD" : "Arrows"); menuStrings[7]->position(menuStrings[5]->getPosition().x, menuStrings[5]->getPosition().y + (menuChange.height * 50)); } } else { currentKeyMode->setText(selectedMovementMode == 0 ? "WASD" : "Arrows"); menuStrings[7]->position(menuStrings[4]->getPosition().x, menuStrings[4]->getPosition().y + (menuChange.height * 50)); } // Draw the arrow option strings menuStrings[7]->drawString(); currentKeyMode->position(menuStrings[7]->getPosition().x + menuStrings[7]->getCalculatedSize().width + (menuChange.height * 20), menuStrings[7]->getPosition().y); currentKeyMode->drawString(); // Draw the invert y axis option strings menuStrings[9]->position(menuStrings[7]->getPosition().x, menuStrings[7]->getPosition().y + (menuChange.height * 50)); menuStrings[9]->drawString(); invertYAxis->position(menuStrings[9]->getPosition().x + menuStrings[9]->getCalculatedSize().width + (menuChange.height * 20), menuStrings[9]->getPosition().y); invertYAxis->drawString(); } void showOptionsInGame() { GAME_STATE = GAME_RUNNING; GAME_MODE = IN_MENU; MENU_ID = GAME_OPTIONS; } void showPausedMenu() { GAME_STATE = GAME_PAUSED; GAME_MODE = IN_GAME; }
26.947195
172
0.621066
[ "object", "model", "3d" ]
31c30d636813e146dc690f2b021e941cc9d769f7
974
cpp
C++
232.Implement Queue using Stacks/test.cpp
ReZeroS/LeetCode
807ae800437e0b6224bd4672f28007388625437b
[ "MIT" ]
2
2018-10-24T03:34:44.000Z
2020-07-16T15:34:44.000Z
232.Implement Queue using Stacks/test.cpp
ReZeroS/LeetCode
807ae800437e0b6224bd4672f28007388625437b
[ "MIT" ]
null
null
null
232.Implement Queue using Stacks/test.cpp
ReZeroS/LeetCode
807ae800437e0b6224bd4672f28007388625437b
[ "MIT" ]
null
null
null
class MyQueue { public: stack<int> a, b; /** Initialize your data structure here. */ MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { while(!a.empty()) { b.push(a.top()); a.pop(); } a.push(x); while(!b.empty()) { a.push(b.top()); b.pop(); } } /** Removes the element from in front of queue and returns that element. */ int pop() { int e = a.top(); a.pop(); return e; } /** Get the front element. */ int peek() { return a.top(); } /** Returns whether the queue is empty. */ bool empty() { return a.empty(); } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */
20.291667
79
0.468172
[ "object" ]
31c4545b3363e84a408f56f6c84425d15569e96d
4,939
cpp
C++
c++03/test_cpp03.cpp
gnbond/Rectangular
49b1ba789abfbc1949c0014d831e170f12925720
[ "Unlicense" ]
1
2020-08-01T01:16:18.000Z
2020-08-01T01:16:18.000Z
c++03/test_cpp03.cpp
gnbond/Rectangular
49b1ba789abfbc1949c0014d831e170f12925720
[ "Unlicense" ]
null
null
null
c++03/test_cpp03.cpp
gnbond/Rectangular
49b1ba789abfbc1949c0014d831e170f12925720
[ "Unlicense" ]
null
null
null
/* * catch2 only works with C++11, so hardwire some tests for C++03 */ #include "rectangular.hpp" #include "test_macros.hpp" typedef gnb::rectangular<int> R; typedef gnb::checked_rectangular<int> CR; static int test_create() { TEST_CASE_BEGIN("rectangular create"); R i(2, 2); REQUIRE(i.size() == 4); REQUIRE(i.height() == 2); REQUIRE(i.width() == 2); REQUIRE(i.at(0,0) == 0); REQUIRE(i.at(1,1) == 0); REQUIRE(i[0][0] == 0); REQUIRE(i[0][0] == 0); REQUIRE(i[1][1] == 0); TEST_CASE_END(); } static int test_create_checked() { TEST_CASE_BEGIN("checked create"); CR i(2, 2); REQUIRE(i.size() == 4); REQUIRE(i.height() == 2); REQUIRE(i.width() == 2); REQUIRE(i.at(1,1) == 0); REQUIRE(i.at(0,0) == 0); REQUIRE(i[0][0] == 0); REQUIRE(i[1][1] == 0); TEST_CASE_END(); } static int test_create_iterators() { TEST_CASE_BEGIN("create iterator"); std::string s("123456"); R i(2, 3, s.begin(), s.end()); REQUIRE(i.size() == 6); REQUIRE(i.height() == 2); REQUIRE(i.width() == 3); REQUIRE(i.at(0,0) == '1'); REQUIRE(i.at(1,1) == '5'); REQUIRE(i[0][1] == '2'); REQUIRE(i[1][2] == '6'); TEST_CASE_END(); } static int test_create_vector() { TEST_CASE_BEGIN("create vector"); std::vector<int> v; for (int i = '1'; i <= '6'; ++i) v.push_back(i); REQUIRE(v.size() == 6); R i(2, 3, v); REQUIRE(i.size() == 6); REQUIRE(i.height() == 2); REQUIRE(i.width() == 3); REQUIRE(i.at(0,0) == '1'); REQUIRE(i.at(1,1) == '5'); REQUIRE(i[0][1] == '2'); REQUIRE(i[1][2] == '6'); REQUIRE(v.size() == 0); TEST_CASE_END(); } static int test_create_checked_iterators() { TEST_CASE_BEGIN("checked create iterator"); std::string s("123456"); CR i(2, 3, s.begin(), s.end()); REQUIRE(i.size() == 6); REQUIRE(i.height() == 2); REQUIRE(i.width() == 3); REQUIRE(i.at(0,0) == '1'); REQUIRE(i.at(1,1) == '5'); REQUIRE(i[0][1] == '2'); REQUIRE(i[1][2] == '6'); TEST_CASE_END(); } static int test_create_iterator_throws() { TEST_CASE_BEGIN("iterator create throws"); std::string s("1234"); REQUIRE_THROWS_AS(R(1,2, s.begin(), s.end()).size(), std::out_of_range); REQUIRE_THROWS_AS(R(3,2, s.begin(), s.end()).size(), std::out_of_range); TEST_CASE_END(); } static int test_throws() { TEST_CASE_BEGIN("rectangular throws"); R i(2, 2); REQUIRE_THROWS_AS(i.at(2,0), std::out_of_range); REQUIRE_THROWS_AS(i.at(0,2), std::out_of_range); REQUIRE_THROWS_AS(i.at(-2,0), std::out_of_range); REQUIRE_THROWS_AS(i.at(0,-2), std::out_of_range); TEST_CASE_END(); } static int test_checked_throws() { TEST_CASE_BEGIN("rectangular checked throws"); CR i(2, 2); REQUIRE_THROWS_AS(i[2][0], std::out_of_range); REQUIRE_THROWS_AS(i[0][2], std::out_of_range); REQUIRE_THROWS_AS(i[-2][0], std::out_of_range); REQUIRE_THROWS_AS(i[0][-2], std::out_of_range); TEST_CASE_END(); } static int test_resize() { TEST_CASE_BEGIN("resize"); std::string s("123456"); R i(1,6, s.begin(), s.end()); i.resize(2, 3); REQUIRE(i.height() == 2); REQUIRE(i.width() == 3); TEST_CASE_END(); } static int test_swap() { TEST_CASE_BEGIN("swap"); R x(1,6); R y; REQUIRE(x.size() == 6); REQUIRE(y.size() == 0); std::swap(x, y); REQUIRE(x.size() == 0); REQUIRE(y.size() == 6); TEST_CASE_END(); } static int test_fill() { TEST_CASE_BEGIN("swap"); R x(1,6); REQUIRE(x.size() == 6); REQUIRE(x[0][0] == 0); REQUIRE(x[0][5] == 0); x.fill(1); REQUIRE(x[0][0] == 1); REQUIRE(x[0][5] == 1); TEST_CASE_END(); } static int test_iterators() { TEST_CASE_BEGIN("iterators"); R i(3,2); R::iterator b = i.begin(); R::iterator e = i.end(); REQUIRE(e - b == 6); // RandomAccessIterator *b = 5; REQUIRE(i[0][0] == 5); TEST_CASE_END(); } static int test_const_iterators() { TEST_CASE_BEGIN("const_iterators"); const R i(3,2); R::const_iterator b = i.begin(); R::const_iterator e = i.end(); REQUIRE(e - b == 6); // RandomAccessIterator REQUIRE(*b == 0); TEST_CASE_END(); } int main(int, char**) { int ret(0); ret += test_create(); ret += test_create_checked(); ret += test_create_iterators(); ret += test_create_vector(); ret += test_create_checked_iterators(); ret += test_create_iterator_throws(); ret += test_throws(); ret += test_checked_throws(); ret += test_resize(); ret += test_swap(); ret += test_fill(); ret += test_iterators(); ret += test_const_iterators(); if (ret) std::cout << "** " << ret << " tests failed! **" << std::endl; else std::cout << "All passed OK" << std::endl; return !!ret; }
20.325103
76
0.556185
[ "vector" ]
31c6af5cef4b7d330a34fd9061dd34303ab602d9
3,454
cpp
C++
src/xray/editor/dialog/sources/dialog_control_panel.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/editor/dialog/sources/dialog_control_panel.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/editor/dialog/sources/dialog_control_panel.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//------------------------------------------------------------------------------------------- // Created : 17.12.2009 // Author : Sergey Prishchepa // Copyright (C) GSC Game World - 2009 //------------------------------------------------------------------------------------------- #include "pch.h" #include "dialog_control_panel.h" #include "dialog_editor.h" #include <xray/editor/base/images/images70x53.h> #include <xray/editor/base/images_loading.h> using xray::dialog_editor::dialog_control_panel; using xray::dialog_editor::drag_drop_create_operation; using xray::editor::controls::drag_cursor_collection; void dialog_control_panel::in_constructor(void) { ImageList^ images_list = xray::editor_base::image_loader::load_images("images70x53", 70, safe_cast<int>(editor_base::images70x53_count), this->GetType()); pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); pictureBox2 = (gcnew System::Windows::Forms::PictureBox()); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(pictureBox1))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(pictureBox2))->BeginInit(); SuspendLayout(); // pictureBox1 pictureBox1->Image = safe_cast<System::Drawing::Image^>(images_list->Images[editor_base::single_node]); pictureBox1->Location = System::Drawing::Point(5, 5); pictureBox1->Name = L"pictureBox1"; pictureBox1->Size = System::Drawing::Size(48, 40); pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; pictureBox1->TabIndex = 0; pictureBox1->TabStop = false; pictureBox1->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &dialog_control_panel::single_node_mouse_down); // pictureBox2 pictureBox2->Image = safe_cast<System::Drawing::Image^>(images_list->Images[editor_base::two_nodes]); pictureBox2->Location = System::Drawing::Point(59, 5); pictureBox2->Name = L"pictureBox2"; pictureBox2->Size = System::Drawing::Size(48, 40); pictureBox2->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; pictureBox2->TabIndex = 1; pictureBox2->TabStop = false; pictureBox2->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &dialog_control_panel::quest_answ_mouse_down); Controls->Add(pictureBox2); Controls->Add(pictureBox1); safe_cast<System::ComponentModel::ISupportInitialize^ >(pictureBox1)->EndInit(); safe_cast<System::ComponentModel::ISupportInitialize^ >(pictureBox2)->EndInit(); m_cursors = gcnew xray::editor::controls::drag_cursor_collection(); HideOnClose = true; ResumeLayout(false); } System::Void dialog_control_panel::single_node_mouse_down(System::Object^ , System::Windows::Forms::MouseEventArgs^ e) { if(e->Button==System::Windows::Forms::MouseButtons::Left) { m_cursors->make_cursors(pictureBox1->Image); DoDragDrop(drag_drop_create_operation::single_node, System::Windows::Forms::DragDropEffects::Copy); } } System::Void dialog_control_panel::quest_answ_mouse_down(System::Object^ , System::Windows::Forms::MouseEventArgs^ e) { if(e->Button==System::Windows::Forms::MouseButtons::Left) { m_cursors->make_cursors(pictureBox2->Image); DoDragDrop(drag_drop_create_operation::question_answer, System::Windows::Forms::DragDropEffects::Copy); } } void dialog_control_panel::OnGiveFeedback(GiveFeedbackEventArgs^ e) { e->UseDefaultCursors = false; m_cursors->set_cursor_for(e->Effect); }
44.282051
156
0.71106
[ "object" ]
31cf6ec0c67611c5f0f1454bf5ca3126ee8ee5ef
4,057
cpp
C++
rtpose_wrapper/src/caffe/layers/euclideanmask_loss_layer.cpp
ammolitor/open_ptrack_v2
a4af0c24883e38a298fb65dd03f76d39ad835616
[ "BSD-3-Clause" ]
null
null
null
rtpose_wrapper/src/caffe/layers/euclideanmask_loss_layer.cpp
ammolitor/open_ptrack_v2
a4af0c24883e38a298fb65dd03f76d39ad835616
[ "BSD-3-Clause" ]
null
null
null
rtpose_wrapper/src/caffe/layers/euclideanmask_loss_layer.cpp
ammolitor/open_ptrack_v2
a4af0c24883e38a298fb65dd03f76d39ad835616
[ "BSD-3-Clause" ]
null
null
null
#include <vector> #include "caffe/layers/euclideanmask_loss_layer.hpp" #include "caffe/util/math_functions.hpp" #include <iostream> using namespace std; namespace caffe { template <typename Dtype> void EuclideanmaskLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); CHECK_EQ(bottom[0]->count(1), bottom[1]->count(1)) << "Inputs must have the same dimension."; diff_.ReshapeLike(*bottom[0]); } template <typename Dtype> void EuclideanmaskLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { int count_per_ch = bottom[0]->shape()[2] * bottom[0]->shape()[3]; int batch = bottom[0]->shape()[0]; int channel = bottom[0]->shape()[1]; //num_part + 1 //int height = bottom[0]->shape()[2]; //int width = bottom[0]->shape()[3]; Dtype loss = 0; for(int n=0; n<batch; n++){ for(int c=0; c<channel; c++){ const Dtype* mask_this = bottom[2]->cpu_data() + (n*channel + c); Dtype mask = (c!=channel-1) ? *mask_this : 1; if(mask > 0.5){ caffe_sub( count_per_ch, bottom[0]->cpu_data() + (n*channel + c)*count_per_ch, bottom[1]->cpu_data() + (n*channel + c)*count_per_ch, diff_.mutable_cpu_data() + (n*channel + c)*count_per_ch); Dtype dot = caffe_cpu_dot(count_per_ch, diff_.cpu_data() + (n*channel + c)*count_per_ch, diff_.cpu_data() + (n*channel + c)*count_per_ch); loss += dot / bottom[0]->num() / Dtype(2); // for(int y = 0; y < 1; y++) { // for(int x = 0; x < 1; x++){ // LOG(INFO) << bottom[0]->cpu_data()[(n*channel + c)*count_per_ch + y*height + x] << " "; // } // } } } //LOG(INFO) << "loss accumluated to n = " << n << " " << loss; } // for(int i=0;i<46;i++){ // for(int j=0;j<46;j++){ // printf("%.1f ", 10 * bottom[1]->cpu_data()[i*46+j]); // } // printf("\n"); // } top[0]->mutable_cpu_data()[0] = loss; } template <typename Dtype> void EuclideanmaskLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { int count_per_ch = bottom[0]->shape()[2] * bottom[0]->shape()[3]; int batch = bottom[0]->shape()[0]; int channel = bottom[0]->shape()[1]; //num_part + 1 for (int i = 0; i < 2; ++i) { if (propagate_down[i]) { const Dtype sign = (i == 0) ? 1 : -1; for(int n=0; n<batch; n++){ for(int c=0; c<channel; c++){ const Dtype* mask_this = bottom[2]->cpu_data() + (n*channel + c); Dtype mask = (c!=channel-1) ? *mask_this : 1; const Dtype alpha = (mask > 0.5 ? Dtype(1) : Dtype(0)) * sign * top[0]->cpu_diff()[0] / bottom[i]->num(); caffe_cpu_axpby( count_per_ch, // count alpha, // alpha diff_.cpu_data() + (n*channel + c)*count_per_ch, // X Dtype(0), // beta bottom[i]->mutable_cpu_diff() + (n*channel + c)*count_per_ch); // Y (store back at) // if(i == 0){ // const Dtype* store_point = bottom[i]->cpu_diff() + (n*channel + c)*count_per_ch; // LOG(INFO) << "gradient n = " << n << " c = " << c << ": " << store_point[0] << " " // << store_point[1] << " " // << store_point[2] << " " // << store_point[3] << " "; // } } } } } } #ifdef CPU_ONLY STUB_GPU(EuclideanmaskLossLayer); #endif INSTANTIATE_CLASS(EuclideanmaskLossLayer); REGISTER_LAYER_CLASS(EuclideanmaskLoss); } // namespace caffe
36.223214
115
0.501109
[ "shape", "vector" ]
31d2b51758f4621a14b750f0f561e5cc51b87334
15,363
cpp
C++
Tracker/Archive/tracker_horst_optimized/Pylon_with_OpenCV/Tracker.cpp
horsto/2P_tracking
d3eab554841a5f746a9231d770777f718267da6d
[ "MIT" ]
1
2018-07-16T07:08:42.000Z
2018-07-16T07:08:42.000Z
Tracker/Archive/tracker_horst_optimized/Pylon_with_OpenCV/Tracker.cpp
horsto/2P_tracking
d3eab554841a5f746a9231d770777f718267da6d
[ "MIT" ]
null
null
null
Tracker/Archive/tracker_horst_optimized/Pylon_with_OpenCV/Tracker.cpp
horsto/2P_tracking
d3eab554841a5f746a9231d770777f718267da6d
[ "MIT" ]
1
2018-07-16T07:08:46.000Z
2018-07-16T07:08:46.000Z
// Pylon_with_OpenCV.cpp /* Note: Before getting started, Basler recommends reading the Programmer's Guide topic in the pylon C++ API documentation that gets installed with pylon. If you are upgrading to a higher major version of pylon, Basler also strongly recommends reading the Migration topic in the pylon C++ API documentation. This sample illustrates how to grab and process images using the CInstantCamera class and OpenCV. The images are grabbed and processed asynchronously, i.e., while the application is processing a buffer, the acquisition of the next buffer is done in parallel. OpenCV is used to demonstrate an image display, an image saving and a video recording. The CInstantCamera class uses a pool of buffers to retrieve image data from the camera device. Once a buffer is filled and ready, the buffer can be retrieved from the camera object for processing. The buffer and additional image data are collected in a grab result. The grab result is held by a smart pointer after retrieval. The buffer is automatically reused when explicitly released or when the smart pointer object is destroyed. */ #include "stdafx.h" #include <sstream> #include <iomanip> #include <iostream> #include <fstream> #include <vector> // Include files to use the PYLON API. #include <pylon/PylonIncludes.h> #ifdef PYLON_WIN_BUILD # include <pylon/PylonGUI.h> #endif // Include files used by samples. #include "ConfigurationEventPrinter.h" #include "CameraEventPrinter.h" // Include files to use OpenCV API. #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/video/video.hpp> #include <opencv2/features2d.hpp> #include "opencv2/core/cvdef.h" #include "thresh_tracking.h" #include "init_func.h" #include <pylon/usb/BaslerUsbInstantCamera.h> using namespace Pylon; // Settings for using Basler USB cameras. #include <pylon/usb/BaslerUsbInstantCamera.h> typedef Pylon::CBaslerUsbInstantCamera Camera_t; typedef CBaslerUsbCameraEventHandler CameraEventHandler_t; // Or use Camera_t::CameraEventHandler_t using namespace Basler_UsbCameraParams; // Namespace for using OpenCV objects. using namespace cv; // Namespace for using cout. using namespace std; using namespace GenApi; // Number of images to be grabbed. static const uint32_t c_countOfImagesToGrab = 100; vector<double> framerate_vec; vector<double> frame_id_vec; //Enumeration used for distinguishing different events. enum MyEvents { ExposureEndEvent = 100 // More events can be added here. }; // Example handler for camera events. class CSampleCameraEventHandler : public CameraEventHandler_t { public: virtual void OnCameraEvent(Camera_t& camera, intptr_t userProvidedId, GenApi::INode* /* pNode */) { switch (userProvidedId) { case ExposureEndEvent: // Exposure End event int64_t tic = camera.EventExposureEndTimestamp.GetValue(); cout << "Exposure End event. FrameID: " << camera.EventExposureEndFrameID.GetValue() << " Timestamp: " << tic << endl; frame_id_vec.push_back(camera.EventExposureEndFrameID.GetValue()); framerate_vec.push_back(tic); break; // More events can be added here. } } }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { // The exit code of the sample application. int exitCode = 0; int retval = 0; int exposure_time = 3000; int delay_us = 0; int debouncer_us = 0; int gain_increase = 0; int saveImages = 0; int recordVideo = 0; int acq_frame_height; int acq_frame_width; int scale_factor; int red_h_low; int red_s_low; int red_v_low; int red_h_high; int red_s_high; int red_v_high; int green_h_low; int green_s_low; int green_v_low; int green_h_high; int green_s_high; int green_v_high; int playback_speed_video; cout << "Reading ini-file..." << endl; retval = init(exposure_time, delay_us, gain_increase, debouncer_us, saveImages, recordVideo, acq_frame_height, acq_frame_width, scale_factor, red_h_low,red_s_low, red_v_low, red_h_high, red_s_high, red_v_high, green_h_low, green_s_low, green_v_low, green_h_high, green_s_high, green_v_high, playback_speed_video); // Automagically call PylonInitialize and PylonTerminate to ensure the pylon runtime system // is initialized during the lifetime of this object. Pylon::PylonAutoInitTerm autoInitTerm; SYSTEMTIME st; GetLocalTime(&st); //GetSystemTime(&st); cout << endl << endl << "Started: " << st.wYear << "-" << st.wMonth << "-" << st.wDay << " " << st.wHour << ":" << st.wMinute << ":" << st.wSecond << endl; // Create an example event handler. In the present case, we use one single camera handler for handling multiple camera events. // The handler prints a message for each received event. CSampleCameraEventHandler* Handler_exposure_ev = new CSampleCameraEventHandler; try { CDeviceInfo info; info.SetDeviceClass(Camera_t::DeviceClass()); // Create an instant camera object with the camera device found first. Camera_t camera( CTlFactory::GetInstance().CreateFirstDevice()); // ENABLE HARDWARE TRIGGERING HERE camera.GrabCameraEvents = true; camera.RegisterCameraEventHandler(Handler_exposure_ev, "EventExposureEndData", ExposureEndEvent, RegistrationMode_ReplaceAll, Cleanup_None); // Print the model name of the camera. cout << "Using device " << camera.GetDeviceInfo().GetVendorName() << " " << camera.GetDeviceInfo().GetModelName() << endl; // Get a camera nodemap in order to access camera parameters. INodeMap& nodemap = camera.GetNodeMap(); // Open the camera before accessing any parameters. camera.Open(); if (!GenApi::IsAvailable(camera.EventSelector)) { throw RUNTIME_EXCEPTION("The device doesn't support events."); } // Enable sending of Exposure End events. camera.EventSelector.SetValue(EventSelector_ExposureEnd); camera.EventNotification.SetValue(EventNotification_On); // The parameter MaxNumBuffer can be used to control the count of buffers // allocated for grabbing. The default value of this parameter is 10. camera.MaxNumBuffer = 10; CIntegerPtr(nodemap.GetNode("Width"))->SetValue(acq_frame_width); CIntegerPtr(nodemap.GetNode("Height"))->SetValue(acq_frame_height); CIntegerPtr(nodemap.GetNode("OffsetX"))->SetValue(0); CIntegerPtr(nodemap.GetNode("OffsetY"))->SetValue(0); CEnumerationPtr gainAuto(nodemap.GetNode("GainAuto")); CEnumerationPtr exposureAuto(nodemap.GetNode("ExposureAuto")); CEnumerationPtr exposureMode(nodemap.GetNode("ExposureMode")); // set gain and exposure time cout << "Setting auto gain to off" << endl; //gainAuto->FromString("Off"); cout << "Setting auto exposure to off" << endl; exposureAuto->FromString("Off"); CFloatPtr gain(nodemap.GetNode("Gain")); double newGain = gain->GetMin() + gain_increase; cout << "Setting gain to " << newGain << endl; gain->SetValue(newGain); // exposure time CFloatPtr(nodemap.GetNode("ExposureTime"))->SetValue(exposure_time); // Set the pixel format to RGB8 8bit CEnumerationPtr(nodemap.GetNode("PixelFormat"))->FromString("RGB8"); // Set to hardware trigger mode: // Select the frame start trigger camera.TriggerSelector.SetValue(TriggerSelector_FrameStart); camera.TriggerMode.SetValue(TriggerMode_On); camera.TriggerSource.SetValue(TriggerSource_Line1); camera.TriggerActivation.SetValue(TriggerActivation_RisingEdge); camera.TriggerDelay.SetValue(delay_us); camera.LineSelector.SetValue(LineSelector_Line1); camera.LineDebouncerTime.SetValue(debouncer_us); // Output signal on Line2 when exposing image: camera.LineSelector.SetValue(LineSelector_Line2); camera.LineSource.SetValue(LineSource_ExposureActive); // Create an OpenCV video creator. VideoWriter cvVideoCreator; // Define the video file name. std::string videoFileName= "openCvVideo.avi"; // Define the video frame size. cv::Size frameSize= Size(acq_frame_width/scale_factor, acq_frame_height/scale_factor); cvVideoCreator.open(videoFileName, CV_FOURCC('M', 'J', 'P', 'G'), playback_speed_video, frameSize, true); // 'M','J','P','G' // Get a fresh timestamp: SYSTEMTIME st; GetLocalTime(&st); //GetSystemTime(&st); cout << "Started: " << st.wYear << "-" << st.wMonth << "-" << st.wDay << " " << st.wHour << ":" << st.wMinute << ":" << st.wSecond << endl; // create text file ofstream output_timestamps; output_timestamps.open("export_timestamps.csv"); output_timestamps << camera.GetDeviceInfo().GetVendorName() << "_" << camera.GetDeviceInfo().GetModelName() << "\n"; output_timestamps << "Tracking height (px): " << acq_frame_height/scale_factor << " | Tracking width (px): " << acq_frame_width / scale_factor << "\n"; output_timestamps << "File creation timestamp: " << st.wYear << "-" << st.wMonth << "-" << st.wDay << " " << st.wHour << ":" << st.wMinute << ":" << st.wSecond << "\n"; // Header written, now actual columns: output_timestamps << "frame,cam_timestamp,green_x,green_y,red_x,red_y\n"; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create display windows namedWindow("OpenCV Tracker", CV_WINDOW_NORMAL); // other options: CV_AUTOSIZE, CV_FREERATIO, CV_WINDOW_NORMAL resizeWindow("OpenCV Tracker", 500, 500); namedWindow("OpenCV Tracker Thresh", CV_WINDOW_NORMAL); resizeWindow("OpenCV Tracker Thresh", 500, 500); cv::Mat tracking_result; // what comes out of the actual tracking function vector<double> g_x; vector<double> r_x; vector<double> g_y; vector<double> r_y; int64_t tic; double framerate_calc = 0.; // Initialize grabbed matrix: cv::Mat mat8_uc3_c(acq_frame_height, acq_frame_width, CV_8UC3); int64_t grabbedImages = 0; // initialize matrices: cv::Mat mat8_uc3(acq_frame_height, acq_frame_width, CV_8UC3); Size size_small(acq_frame_height / scale_factor, acq_frame_width / scale_factor); // resize cv::Mat mat8_uc3_small(acq_frame_height / scale_factor, acq_frame_width / scale_factor, CV_8UC3); // black image- stays black cv::Mat mat8_uc3_small_video(acq_frame_height / scale_factor, acq_frame_width / scale_factor, CV_8UC3); // for showing in video camera.AcquisitionStart.Execute(); camera.StartGrabbing(GrabStrategy_LatestImageOnly, GrabLoop_ProvidedByUser); cout << "Starting grabbing..." << endl; CGrabResultPtr ptrGrabResult; while (1) // camera.IsGrabbing() { // calculate running framerate: if (grabbedImages > 0) framerate_calc = 1000000000./((framerate_vec.back() - framerate_vec.at(0)) / framerate_vec.size()); // Wait for an image and then retrieve it. A timeout of 5000 ms is used. camera.WaitForFrameTriggerReady(INFINITE, TimeoutHandling_Return); camera.RetrieveResult(5000, ptrGrabResult, TimeoutHandling_ThrowException); // wait for 5 seconds then stop CCommandPtr(nodemap.GetNode("TimestampLatch"))->Execute(); // Get the timestamp value int64_t tic = CIntegerPtr(nodemap.GetNode("TimestampLatchValue"))->GetValue(); cout << tic << endl; // Image grabbed successfully? if (ptrGrabResult->GrabSucceeded()) { grabbedImages++; // Create an OpenCV image from a grabbed image. cv::Mat mat8_uc3(acq_frame_height, acq_frame_width, CV_8UC3, (uintmax_t *)ptrGrabResult->GetBuffer()); resize(mat8_uc3, mat8_uc3_small, size_small); //resize images mat8_uc3_small.copyTo(mat8_uc3_small_video); // create a copy // Start tracking here tracking_result = GetThresholdedImage(mat8_uc3_small, red_h_low, red_s_low, red_v_low, red_h_high, red_s_high, red_v_high, green_h_low, green_s_low, green_v_low, green_h_high, green_s_high, green_v_high); // draw tracking Point pt_green = Point(tracking_result.at<double>(0, 0), tracking_result.at<double>(0, 1)); circle(mat8_uc3_small, pt_green, 1, cvScalar(0, 0, 255), 1.5); Point pt_red = Point(tracking_result.at<double>(1, 0), tracking_result.at<double>(1, 1)); circle(mat8_uc3_small, pt_red, 1, cvScalar(0, 255, 0), 1.5); // save: output_timestamps << frame_id_vec.back() << "," << framerate_vec.back() << "," << tracking_result.at<double>(0, 0) << "," << tracking_result.at<double>(0, 1) << "," << tracking_result.at<double>(1, 0) << "," << tracking_result.at<double>(1, 1) << "\n"; g_x.push_back(tracking_result.at<double>(0, 0)); r_x.push_back(tracking_result.at<double>(1, 0)); g_y.push_back(tracking_result.at<double>(0, 1)); r_y.push_back(tracking_result.at<double>(1, 1)); for (int i = 0; i < g_x.size(); i++) { pt_green = Point(g_x.at(i), g_y.at(i)); circle(mat8_uc3_small, pt_green, 1, cvScalar(0, 0, 250), 1); pt_red = Point(r_x.at(i), r_y.at(i)); circle(mat8_uc3_small, pt_red, 1, cvScalar(0, 250, 0), 1); } // invert channel order cv::cvtColor(mat8_uc3_small_video, mat8_uc3_small_video, cv::COLOR_BGR2RGB); mat8_uc3_small_video = mat8_uc3_small_video * 4; // only for viewing purposes (make it all a bit brighter) // Set saveImages to '1' to save images. if (saveImages) { // Create the current image name for saving. std::ostringstream s; // Create image name files with ascending grabbed image numbers. s << "export/image_" << grabbedImages << ".jpg"; std::string imageName(s.str()); // Save an OpenCV image. imwrite(imageName, mat8_uc3_small_video); } // Set recordVideo to '1' to record AVI video file. if (recordVideo) cvVideoCreator.write(mat8_uc3_small_video); // Burn framerate into image std::ostringstream strs; strs << fixed << setprecision(1) << framerate_calc << " fps"; std::string str = strs.str(); putText(mat8_uc3_small, str, cvPoint(3, 15), FONT_HERSHEY_SIMPLEX, 0.35, cvScalar(255, 255, 255), 0, CV_AA); // Create an OpenCV display window. imshow("OpenCV Tracker", mat8_uc3_small_video); imshow("OpenCV Tracker Thresh", mat8_uc3_small); tracking_result.release(); waitKey(1); #ifdef PYLON_WIN_BUILD // Display the grabbed image in pylon. //Pylon::DisplayImage(1, ptrGrabResult); #endif } else { cout << "Error: " << ptrGrabResult->GetErrorCode() << " " << ptrGrabResult->GetErrorDescription() << endl; } } // close timestamp file output_timestamps.close(); camera.EventSelector.SetValue(EventSelector_ExposureEnd); camera.EventNotification.SetValue(EventNotification_Off); // Release the video file on leaving. if (recordVideo) cvVideoCreator.release(); } catch (GenICam::GenericException &e) { // Error handling. cout << "An exception occurred." << endl << e.GetDescription() << endl; exitCode = 1; } // Delete the event handlers. delete Handler_exposure_ev; // Comment the following two lines to disable waiting on exit. cerr << endl << "Press Enter to exit." << endl; while( cin.get() != '\n'); // Releases all pylon resources. //PylonTerminate(); return exitCode; }
39.493573
172
0.698106
[ "object", "vector", "model" ]
31d2e6bc025df866abb8df11e49b21e75a39a97f
16,008
cc
C++
cpp/parquetjni/parquetjni.cc
twosigma/parquetjni
afbf24cd605c00e056a4efa41dd63e597cb5024a
[ "Apache-2.0" ]
null
null
null
cpp/parquetjni/parquetjni.cc
twosigma/parquetjni
afbf24cd605c00e056a4efa41dd63e597cb5024a
[ "Apache-2.0" ]
null
null
null
cpp/parquetjni/parquetjni.cc
twosigma/parquetjni
afbf24cd605c00e056a4efa41dd63e597cb5024a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Two Sigma Investments, LP. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define PARQUETJNI_PROFILE #include "parquetjni/parquetjni.h" #include <arrow/io/file.h> #include <arrow/ipc/api.h> #include <arrow/ipc/options.h> #include <arrow/table.h> #include <parquet/api/reader.h> #include <parquet/statistics.h> #include <deque> #include <future> #include <queue> #include <thread> #include <vector> #include "parquetjni/memory_tracking.h" #include "parquetjni/s3file.h" #include "parquetjni/util.h" /// The number of rows to feed through JNI at a time. const int64_t kReaderChunkSize = 32768; /// Wrap a TableBatchReader to keep the associated table alive. class OwningTableBatchReader : public arrow::RecordBatchReader { public: explicit OwningTableBatchReader(std::shared_ptr<arrow::Table> table) : table_(table) { reader_ = std::make_shared<arrow::TableBatchReader>(*table_); reader_->set_chunksize(kReaderChunkSize); } ~OwningTableBatchReader() = default; std::shared_ptr<arrow::Schema> schema() const override { return reader_->schema(); } arrow::Status ReadNext(std::shared_ptr<arrow::RecordBatch> *batch) override { return reader_->ReadNext(batch); } private: std::shared_ptr<arrow::Table> table_; std::shared_ptr<arrow::TableBatchReader> reader_; }; arrow::Status SingleFileParquetJniReader::Open(const std::string &file_path, ParquetJniReader **out) { // Memory-mapped file ARROW_ASSIGN_OR_RAISE( auto arrow_file, arrow::io::MemoryMappedFile::Open(file_path, arrow::io::FileMode::READ)); return Open(file_path, arrow_file, out); } arrow::Status SingleFileParquetJniReader::Open(const std::string &endpoint, const std::string &bucket, const std::string &key, const std::string &auth_token, ParquetJniReader **out) { S3Path path{bucket, key}; std::shared_ptr<arrow::io::RandomAccessFile> arrow_file; ARROW_RETURN_NOT_OK(OpenS3File(path, endpoint, auth_token, &arrow_file)); return Open(key, arrow_file, out); } arrow::Status SingleFileParquetJniReader::Open( std::string name, std::shared_ptr<arrow::io::RandomAccessFile> arrow_file, ParquetJniReader **out) { const auto profile_start = std::chrono::steady_clock::now(); // Enable parallel reads. parquet::ArrowReaderProperties properties; properties.set_use_threads(true); properties.set_pre_buffer(true); parquet::ReaderProperties parquet_properties = parquet::ReaderProperties(GetTrackedPool()); std::unique_ptr<parquet::arrow::FileReader> arrow_reader; // TODO(lidavidm): measure overhead of this call; likely makes a // request to TS3 parquet::arrow::FileReaderBuilder builder; ARROW_RETURN_NOT_OK(builder.Open(std::move(arrow_file), parquet_properties)); ARROW_RETURN_NOT_OK(builder.properties(properties) ->memory_pool(GetTrackedPool()) ->Build(&arrow_reader)); *out = new SingleFileParquetJniReader(std::move(name), std::move(arrow_reader)); TRACE("ParquetJniReader::Open", profile_start, open_end); return arrow::Status::OK(); } arrow::Status SingleFileParquetJniReader::GetSchema( std::shared_ptr<arrow::Schema> *out) { return arrow_reader_->GetSchema(out); } arrow::Status SingleFileParquetJniReader::GetRecordBatchReader( const std::vector<std::string> &columns, const std::string &time_column, const int64_t min_utc_ns, const int64_t max_utc_ns, const bool filter_row_groups, std::shared_ptr<arrow::RecordBatchReader> *out) { const parquet::ParquetFileReader *parquet_reader = arrow_reader_->parquet_reader(); const bool has_column_filter = !columns.empty(); std::vector<int> row_group_indices; std::vector<int> column_indices; const auto profile_start = std::chrono::steady_clock::now(); std::shared_ptr<parquet::FileMetaData> metadata = parquet_reader->metadata(); TRACE_WITH("ParquetJniReader::ReadMetadata", name_, profile_start, metadata_end); for (int i = 0; i < arrow_reader_->num_row_groups(); i++) { bool include_row_group = true; if (time_column != "" || has_column_filter) { std::unique_ptr<parquet::RowGroupMetaData> row_metadata = metadata->RowGroup(i); for (int col_index = 0; col_index < row_metadata->num_columns(); col_index++) { std::unique_ptr<parquet::ColumnChunkMetaData> col_metadata = row_metadata->ColumnChunk(col_index); // If a column list was supplied, check if the column is in // the list const auto &col_name = col_metadata->path_in_schema()->ToDotString(); if (has_column_filter) { if (std::find(columns.begin(), columns.end(), col_name) != columns.end()) { column_indices.push_back(col_index); } } // If a time column was supplied, check if the row group falls // in the given bounds if (col_name != time_column) { continue; } std::shared_ptr<parquet::Statistics> stats = col_metadata->statistics(); if (stats->physical_type() != parquet::Type::type::INT64) { LOG(WARNING) << "Could not interpret physical type of time column"; break; } const parquet::Int64Statistics *typed_stats = static_cast<const parquet::Int64Statistics *>(stats.get()); // Skip row groups that don't fall in bounds include_row_group = (typed_stats->min() <= max_utc_ns) && (typed_stats->max() >= min_utc_ns); break; } } if (include_row_group) { row_group_indices.push_back(i); } } TRACE_WITH("ParquetJniReader::FilterRowsColumns", name_, metadata_end, filter_end); if (row_group_indices.size() == 0) { // No data to read *out = nullptr; return arrow::Status::OK(); } if (filter_row_groups && has_column_filter) { ARROW_RETURN_NOT_OK(arrow_reader_->GetRecordBatchReader( row_group_indices, column_indices, out)); } else if (filter_row_groups) { ARROW_RETURN_NOT_OK( arrow_reader_->GetRecordBatchReader(row_group_indices, out)); } else if (has_column_filter) { // Column list supplied std::shared_ptr<arrow::Table> table; ARROW_RETURN_NOT_OK(arrow_reader_->ReadTable(column_indices, &table)); *out = std::make_shared<OwningTableBatchReader>(table); } else { // No column list supplied, read all columns std::shared_ptr<arrow::Table> table; ARROW_RETURN_NOT_OK(arrow_reader_->ReadTable(&table)); *out = std::make_shared<OwningTableBatchReader>(table); } TRACE_WITH("ParquetJniReader::OpenRecordBatchReader", name_, filter_end, open_end); return arrow::Status::OK(); } arrow::Status SingleFileParquetJniReader::Close() { return arrow::Status::OK(); } /// The maximum number of Parquet files to hold in memory at once. constexpr int8_t kMaxFilesBuffered = 3; /// State for a single Parquet file being buffered. class BufferedFile { public: explicit BufferedFile(std::string name, arrow::Status status, std::unique_ptr<ParquetJniReader> file, std::shared_ptr<arrow::RecordBatchReader> reader) : name_(std::move(name)), status_(status), file_(std::move(file)), reader_(std::move(reader)) {} const std::string &name() const { return name_; } arrow::Status Close() { RETURN_NOT_OK(status_); reader_.reset(); return file_->Close(); } arrow::Status GetReader( std::shared_ptr<arrow::RecordBatchReader> *reader) const { RETURN_NOT_OK(status_); *reader = reader_; return arrow::Status::OK(); } private: std::string name_; arrow::Status status_; // These pointers are only valid if status is Status::OK. std::unique_ptr<ParquetJniReader> file_; std::shared_ptr<arrow::RecordBatchReader> reader_; }; class DatasetBatchReader : public arrow::RecordBatchReader { public: explicit DatasetBatchReader(std::shared_ptr<ParquetJniDataset> dataset, const std::vector<std::string> &columns, const std::string &time_column, const int64_t min_utc_ns, const int64_t max_utc_ns, const bool filter_row_groups) : dataset_(std::move(dataset)), columns_(columns), time_column_(time_column), min_utc_ns_(min_utc_ns), max_utc_ns_(max_utc_ns), filter_row_groups_(filter_row_groups), schema_(nullptr), file_readers_(), file_queue_(std::deque<std::string>(dataset_->keys_.begin(), dataset_->keys_.end())) {} ~DatasetBatchReader() = default; static arrow::Status Open(std::shared_ptr<ParquetJniDataset> dataset, const std::vector<std::string> &columns, const std::string &time_column, int64_t min_utc_ns, int64_t max_utc_ns, bool filter_row_groups, std::shared_ptr<arrow::RecordBatchReader> *out) { const auto profile_start = std::chrono::steady_clock::now(); *out = std::make_shared<DatasetBatchReader>(std::move(dataset), columns, time_column, min_utc_ns, max_utc_ns, filter_row_groups); // TODO(lidavidm): use Datasets to do partition filtering here if needed // Access private fields DatasetBatchReader *reader = static_cast<DatasetBatchReader *>(out->get()); // Load the first file and get the schema. ARROW_RETURN_NOT_OK(reader->EnqueueReads(kMaxFilesBuffered)); if (reader->file_readers_.empty()) { return arrow::Status::Invalid("No files in dataset"); } TRACE("ParquetJniDataset::Open::LoadNext", profile_start, load_end); std::shared_ptr<arrow::RecordBatchReader> batch_reader; RETURN_NOT_OK(reader->file_readers_.front().get().GetReader(&batch_reader)); reader->schema_ = batch_reader->schema(); TRACE("ParquetJniDataset::Open::Schema", load_end, open_end); return arrow::Status::OK(); } arrow::Status LoadNext() { if (!file_readers_.empty()) { BufferedFile &buffered_file = const_cast<BufferedFile &>(file_readers_.front().get()); RETURN_NOT_OK(buffered_file.Close()); file_readers_.pop(); } return EnqueueReads(kMaxFilesBuffered); } arrow::Status EnqueueReads(size_t max_files) { const auto profile_start = std::chrono::steady_clock::now(); while (file_readers_.size() < max_files && !file_queue_.empty()) { const std::string next_file = file_queue_.front(); file_queue_.pop(); std::packaged_task<BufferedFile()> task( [next_file, this, profile_start]() { ParquetJniReader *jni_reader; arrow::Status status = SingleFileParquetJniReader::Open( dataset_->endpoint_, dataset_->bucket_, next_file, dataset_->auth_token_, &jni_reader); if (!status.ok()) { return BufferedFile(next_file, status, nullptr, nullptr); } std::shared_ptr<arrow::RecordBatchReader> batch_reader; status = jni_reader->GetRecordBatchReader( columns_, time_column_, min_utc_ns_, max_utc_ns_, filter_row_groups_, &batch_reader); if (!status.ok()) { return BufferedFile(next_file, status, nullptr, nullptr); } TRACE_WITH("ParquetJniDataset::EnqueueReads", next_file, profile_start, load_end); return BufferedFile(next_file, arrow::Status::OK(), std::unique_ptr<ParquetJniReader>(jni_reader), std::move(batch_reader)); }); std::future<BufferedFile> future = task.get_future(); std::thread thread(std::move(task)); thread.detach(); file_readers_.emplace(std::move(future)); } TRACE("ParquetJniDataset::EnqueueReads", profile_start, load_end); return arrow::Status::OK(); } std::shared_ptr<arrow::Schema> schema() const override { return schema_; } arrow::Status ReadNext(std::shared_ptr<arrow::RecordBatch> *batch) override { const auto profile_start = std::chrono::steady_clock::now(); ARROW_RETURN_NOT_OK(EnqueueReads(kMaxFilesBuffered)); TRACE("ParquetJniDataset::ReadNext::EnqueueReads", profile_start, enqueue_end); if (file_readers_.empty()) { *batch = nullptr; return arrow::Status::OK(); } std::shared_ptr<arrow::RecordBatchReader> batch_reader; const BufferedFile &file = file_readers_.front().get(); TRACE_WITH("ParquetJniDataset::ReadNext::GetFront", file.name(), enqueue_end, get_end); ARROW_RETURN_NOT_OK(file.GetReader(&batch_reader)); TRACE_WITH("ParquetJniDataset::ReadNext::GetReader", file.name(), get_end, reader_end); ARROW_RETURN_NOT_OK(batch_reader->ReadNext(batch)); TRACE_WITH("ParquetJniDataset::ReadNext::ReadNext", file.name(), reader_end, reading_end); if (batch == nullptr || *batch == nullptr) { // This file was drained, load a new file // Copy name for tracing to avoid use-after-free const std::string old_name = file.name(); ARROW_RETURN_NOT_OK(LoadNext()); TRACE_WITH("ParquetJniDataset::ReadNext (EOF)", old_name, reading_end, read_end); return ReadNext(batch); } TRACE_WITH("ParquetJniDataset::ReadNext", file.name(), reading_end, read_end); return arrow::Status::OK(); } private: std::shared_ptr<ParquetJniDataset> dataset_; std::vector<std::string> columns_; std::string time_column_; int64_t min_utc_ns_; int64_t max_utc_ns_; bool filter_row_groups_; std::shared_ptr<arrow::Schema> schema_; // Queue of files buffered for reading. The head of the queue is the // file currently being read. std::queue<std::shared_future<BufferedFile>> file_readers_; std::queue<std::string> file_queue_; }; arrow::Status ParquetJniDataset::Open(const std::string &endpoint, const std::string &auth_token, const std::string &bucket, const std::vector<std::string> &keys, std::shared_ptr<ParquetJniReader> *out) { *out = std::unique_ptr<ParquetJniDataset>( new ParquetJniDataset(endpoint, auth_token, bucket, keys)); return arrow::Status::OK(); } arrow::Status ParquetJniDataset::GetRecordBatchReader( const std::vector<std::string> &columns, const std::string &time_column, const int64_t min_utc_ns, const int64_t max_utc_ns, const bool filter_row_groups, std::shared_ptr<arrow::RecordBatchReader> *out) { return DatasetBatchReader::Open(shared_from_this(), columns, time_column, min_utc_ns, max_utc_ns, filter_row_groups, out); } arrow::Status ParquetJniDataset::Close() { return arrow::Status::OK(); }
39.428571
80
0.650987
[ "vector" ]
31d6bef026c4a80e56fdd77e19de5b36fce6e5a0
1,033
cpp
C++
COJ/AnotherSortingProblemII.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
1
2019-09-29T03:58:35.000Z
2019-09-29T03:58:35.000Z
COJ/AnotherSortingProblemII.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
COJ/AnotherSortingProblemII.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> #define for0(i, n) for(i = 0; i < n; i++) #define for1(i, n) for(i = 1; i <= n; i++) #define fora(i, a, n) for(i = a; i < n; i++) #define dprc(x) printf("| %c\n", x) #define dprd(x) printf("| %d\n", x) #define dprd2(x,y) printf("| %d %d\n", x, y) #define prd(x) printf("%d\n", x) #define prd2(x,y) printf("%d %d\n", x, y) #define scd(x) scanf("%d", &x) #define scd2(x, y) scanf("%d%d", &x, &y) #define NL() printf("\n") #define PB push_back #define MP make_pair #define MT(x, y, z) MP(MP(x, y), z) #define MTi(x, y, z) MP(x, MP(y, z)) #define MAX(x, y) ((x>y)?x:y) #define X first #define Y second using namespace std; typedef vector<int> vi; typedef pair<int, int> ii; typedef long long ll; typedef unsigned long long ull; int main() { int t, n, a[55], i, j, r; cin >> t; while(t--){ cin >> n; r = 0; for(i = 1; i <= n; i++){ cin >> a[i]; } for(i = 1; i <= n; i++){ j = i; while(a[j] != j){ r += abs(a[j] - j); swap(a[j], j); } } cout << r << endl; } }
18.446429
44
0.515005
[ "vector" ]
31f8113872b8c469a3cc49aee859d5c4e17837db
946
cc
C++
src/client/compatibility.cc
protocolocon/nanoWeb
a89b3f9d9c9b7421a5005971565795519728f31b
[ "BSD-2-Clause" ]
null
null
null
src/client/compatibility.cc
protocolocon/nanoWeb
a89b3f9d9c9b7421a5005971565795519728f31b
[ "BSD-2-Clause" ]
null
null
null
src/client/compatibility.cc
protocolocon/nanoWeb
a89b3f9d9c9b7421a5005971565795519728f31b
[ "BSD-2-Clause" ]
null
null
null
/* -*- mode: c++; coding: utf-8; c-file-style: "stroustrup"; -*- Contributors: Asier Aguirre All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE.txt file. */ #include "compatibility.h" #include "context.h" #include <stdlib.h> namespace { render::Cursor currentCursor; // server communication const char* serverIp = "127.0.0.1"; const char* serverPort = "3000"; } #ifdef __EMSCRIPTEN__ # include "compatibility_emscripten.cc" #else # include "compatibility_desktop.cc" #endif namespace render { void setCursorInner(Cursor c); // cursors common part void setCursor(Cursor c) { if (c != currentCursor) { currentCursor = c; setCursorInner(c); } } // server communication void serverInit(const char* ip, const char* port) { serverIp = ip; serverPort = port; } }
19.708333
65
0.633192
[ "render" ]
31ffa3ee745ed81fbb77efeb5a98ed3aba22cb75
3,297
cpp
C++
src/03/p1/main.cpp
progBorg/advent-of-code-2018
7f41ad7145b55452b0b632d10b66b4c193bd0c4a
[ "MIT" ]
null
null
null
src/03/p1/main.cpp
progBorg/advent-of-code-2018
7f41ad7145b55452b0b632d10b66b4c193bd0c4a
[ "MIT" ]
null
null
null
src/03/p1/main.cpp
progBorg/advent-of-code-2018
7f41ad7145b55452b0b632d10b66b4c193bd0c4a
[ "MIT" ]
null
null
null
/* * main.cpp * * Copyright 2018 Tom Veldman <t.c.veldman@student.utwente.nl> * * 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; 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 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 Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ #include <iostream> #include <fstream> #include <string> #include <vector> #include "area.h" using namespace std; int main(int argc, char **argv) { // Open input file for reading // Realize that the input differs per user ifstream inputFile; inputFile.open("input"); // Set up variables to be used in loop string inputLine; vector<Area> patches; // The collection of patches // Loop through inputFile until eof is reached // This will extract all patches and parse them into objects while (getline(inputFile, inputLine)) { // Basically push_back, but memory efficient // Creates a new Area() in place at the end of patches patches.emplace_back(inputLine); } // Find the maximum distance from point zero // i.e. the dimension of the superarea int fullWidth = 0; int fullHeight = 0; for (Area patch : patches) { if ((patch.getVert() + patch.getHeight()) > fullHeight) { fullHeight = patch.getVert() + patch.getHeight(); } if ((patch.getHori() + patch.getWidth()) > fullWidth) { fullWidth = patch.getHori() + patch.getWidth(); } } cout << "Superarea dimensions: " << fullWidth << 'x' << fullHeight << endl; // Sweep over the superarea, checking each point for overlap // Claims/patches are 0-indexed bool isPointClaimed; int multipleClaimedSpace = 0; for (int x = 0; x < fullWidth; x++) { for (int y = 0; y < fullHeight; y++) { // Reset point status isPointClaimed = false; // For the current point in the superarea, loop through all patches for (Area claim : patches) { // If the current patch encapsulates the current x if (claim.getHori() <= x && (claim.getHori() + claim.getWidth()) > x) { // If the current patch also encapsulates the current y if (claim.getVert() <= y && (claim.getVert() + claim.getHeight()) > y) { // If the current point has already been claimed before if (isPointClaimed) { // Increment the counter multipleClaimedSpace++; // Retrieve the next point in the superarea // We need to break out of multiple for-loops, // so using a goto is our best option goto nextAreaPoint; } else { // ..else claim the point isPointClaimed = true; } } } } nextAreaPoint: continue; // Each label needs at least one command } } cout << "Square inches of space with multiple claims: " << multipleClaimedSpace << endl; // Be nice and close the inputFile inputFile.close(); return 0; }
29.4375
89
0.678192
[ "vector" ]
ee022adbc5d828d797e7ada0e3e5e52b7b2cffad
1,578
cpp
C++
C++/sort-integers-by-the-power-value.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/sort-integers-by-the-power-value.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/sort-integers-by-the-power-value.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n) on average // Space: O(n) class Solution { public: int getKth(int lo, int hi, int k) { vector<pair<int, int>> arr; for (int i = lo; i <= hi; ++i) { arr.emplace_back(power_value(i), i); } auto it = begin(arr) + k - 1; nth_element(begin(arr), it, end(arr)); return it->second; } private: int power_value(int x) { int y = x, result = 0; while (x > 1 && !Solution::dp_.count(x)) { ++result; if (x & 1) { x = 3 * x + 1; } else { x >>= 1; } } Solution::dp_[y] = result + Solution::dp_[x]; return Solution::dp_[y]; } static unordered_map<int, int> dp_; }; unordered_map<int, int> Solution::dp_; // Time: O(nlogn) // Space: O(n) class Solution2 { public: int getKth(int lo, int hi, int k) { vector<pair<int, int>> arr; for (int i = lo; i <= hi; ++i) { arr.emplace_back(power_value(i), i); } sort(begin(arr), end(arr)); return arr[k - 1].second; } private: int power_value(int x) { int y = x, result = 0; while (x > 1 && !Solution2::dp_.count(x)) { ++result; if (x & 1) { x = 3 * x + 1; } else { x >>= 1; } } Solution2::dp_[y] = result + Solution2::dp_[x]; return Solution2::dp_[y]; } static unordered_map<int, int> dp_; }; unordered_map<int, int> Solution2::dp_;
23.552239
55
0.453105
[ "vector" ]
ee068f7ff06abbc694ddcd6024c9b9cbf9843fbf
283
hpp
C++
dometer/metrics/handler/prometheus/options.hpp
maxenglander/dometer
baf9ed81f9d1e8bb67750ac278af5a9e0c4b89b9
[ "MIT" ]
null
null
null
dometer/metrics/handler/prometheus/options.hpp
maxenglander/dometer
baf9ed81f9d1e8bb67750ac278af5a9e0c4b89b9
[ "MIT" ]
null
null
null
dometer/metrics/handler/prometheus/options.hpp
maxenglander/dometer
baf9ed81f9d1e8bb67750ac278af5a9e0c4b89b9
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "dometer/metrics/handler/prometheus/transport_options.hpp" namespace dometer::metrics::handler::prometheus { struct options { const unsigned int max_time_series; const std::vector<transport_options> transports; }; }
21.769231
67
0.727915
[ "vector" ]
ee0ad048ca6136f4eadc9239b285de0d870404db
1,171
cpp
C++
source/unit_tests/ColourUtils_test.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
source/unit_tests/ColourUtils_test.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
source/unit_tests/ColourUtils_test.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "gtest/gtest.h" TEST(SW_ColourUtils, get_alternate_hue) { std::vector<std::pair<Colour, Colour>> old_new_hue = {{Colour::COLOUR_BLACK, Colour::COLOUR_BOLD_BLACK}, {Colour::COLOUR_RED, Colour::COLOUR_BOLD_RED}, {Colour::COLOUR_GREEN, Colour::COLOUR_BOLD_GREEN}, {Colour::COLOUR_YELLOW, Colour::COLOUR_BOLD_YELLOW}, {Colour::COLOUR_BLUE, Colour::COLOUR_BOLD_BLUE}, {Colour::COLOUR_MAGENTA, Colour::COLOUR_BOLD_MAGENTA}, {Colour::COLOUR_CYAN, Colour::COLOUR_BOLD_CYAN}, {Colour::COLOUR_WHITE, Colour::COLOUR_BOLD_WHITE}}; for (const auto& colour_pair : old_new_hue) { EXPECT_EQ(colour_pair.second, ColourUtils::get_alternate_hue(colour_pair.first)); EXPECT_EQ(colour_pair.first, ColourUtils::get_alternate_hue(colour_pair.second)); } }
58.55
111
0.505551
[ "vector" ]
ee0fa47b23e031bccb1607caec5360943e29670b
6,237
cc
C++
Geometry/CaloEventSetup/test/TestEcalGetWindow.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Geometry/CaloEventSetup/test/TestEcalGetWindow.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Geometry/CaloEventSetup/test/TestEcalGetWindow.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include <memory> #include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Utilities/interface/ESGetToken.h" #include "Geometry/Records/interface/CaloGeometryRecord.h" #include "Geometry/Records/interface/CaloTopologyRecord.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloTopology/interface/CaloSubdetectorTopology.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "DataFormats/EcalDetId/interface/EcalTrigTowerDetId.h" #include <TCanvas.h> #include <TVirtualPad.h> #include <TStyle.h> #include <TROOT.h> #include <TH2F.h> #include <TBox.h> #include <iostream> class TestEcalGetWindow : public edm::one::EDAnalyzer<> { public: explicit TestEcalGetWindow(const edm::ParameterSet&); ~TestEcalGetWindow() override; void beginJob() override {} void analyze(edm::Event const& iEvent, edm::EventSetup const&) override; void endJob() override {} private: void build(const CaloGeometry& cg, const CaloTopology& etmap, DetId::Detector det, int subdetn, const char* name); int towerColor(const EcalTrigTowerDetId& theTower); edm::ESGetToken<CaloTopology, CaloTopologyRecord> topologyToken_; edm::ESGetToken<CaloGeometry, CaloGeometryRecord> geometryToken_; int pass_; }; TestEcalGetWindow::TestEcalGetWindow(const edm::ParameterSet& /*iConfig*/) : topologyToken_{esConsumes<CaloTopology, CaloTopologyRecord>(edm::ESInputTag{})}, geometryToken_{esConsumes<CaloGeometry, CaloGeometryRecord>(edm::ESInputTag{})} { //now do what ever initialization is needed pass_ = 0; // some setup for root gROOT->SetStyle("Plain"); // white fill colors etc. gStyle->SetPaperSize(TStyle::kA4); } TestEcalGetWindow::~TestEcalGetWindow() {} void TestEcalGetWindow::build( const CaloGeometry& /*cg*/, const CaloTopology& ct, DetId::Detector det, int subdetn, const char* name) { if (det == DetId::Ecal && subdetn == EcalEndcap) { TCanvas* canv = new TCanvas("c", "", 1000, 1000); canv->SetLeftMargin(0.15); canv->SetBottomMargin(0.15); gStyle->SetOptStat(0); TH2F* h = new TH2F("", "", 10, 0.5, 100.5, 10, 0.5, 100.5); h->Draw(); //gPad->SetGridx(); //gPad->SetGridy(); gPad->Update(); h->SetXTitle("x index"); h->SetYTitle("y index"); h->GetXaxis()->SetTickLength(-0.03); h->GetYaxis()->SetTickLength(-0.03); h->GetXaxis()->SetLabelOffset(0.03); h->GetYaxis()->SetLabelOffset(0.03); h->GetXaxis()->SetLabelSize(0.04); h->GetYaxis()->SetLabelSize(0.04); // axis titles h->GetXaxis()->SetTitleSize(0.04); h->GetYaxis()->SetTitleSize(0.04); h->GetXaxis()->SetTitleOffset(1.8); h->GetYaxis()->SetTitleOffset(1.9); h->GetXaxis()->CenterTitle(true); h->GetYaxis()->CenterTitle(true); const CaloSubdetectorTopology* topology = ct.getSubdetectorTopology(det, subdetn); std::vector<DetId> eeDetIds; eeDetIds.emplace_back(EEDetId(1, 50, 1, EEDetId::XYMODE)); eeDetIds.emplace_back(EEDetId(25, 50, 1, EEDetId::XYMODE)); eeDetIds.emplace_back(EEDetId(50, 1, 1, EEDetId::XYMODE)); eeDetIds.emplace_back(EEDetId(50, 25, 1, EEDetId::XYMODE)); eeDetIds.emplace_back(EEDetId(3, 60, 1, EEDetId::XYMODE)); for (const auto& eeDetId : eeDetIds) { EEDetId myId(eeDetId); if (myId.zside() == -1) continue; std::vector<DetId> myNeighbours = topology->getWindow(myId, 13, 13); for (const auto& myNeighbour : myNeighbours) { EEDetId myEEId(myNeighbour); TBox* box = new TBox(myEEId.ix() - 0.5, myEEId.iy() - 0.5, myEEId.ix() + 0.5, myEEId.iy() + 0.5); box->SetFillColor(1); box->Draw(); } } gPad->SaveAs(name); delete canv; delete h; } if (det == DetId::Ecal && subdetn == EcalBarrel) { TCanvas* canv = new TCanvas("c", "", 1000, 1000); canv->SetLeftMargin(0.15); canv->SetBottomMargin(0.15); gStyle->SetOptStat(0); TH2F* h = new TH2F("", "", 10, -85.5, 85.5, 10, 0.5, 360.5); h->Draw(); //gPad->SetGridx(); //gPad->SetGridy(); gPad->Update(); h->SetXTitle("eta index"); h->SetYTitle("phi index"); h->GetXaxis()->SetTickLength(-0.03); h->GetYaxis()->SetTickLength(-0.03); h->GetXaxis()->SetLabelOffset(0.03); h->GetYaxis()->SetLabelOffset(0.03); h->GetXaxis()->SetLabelSize(0.04); h->GetYaxis()->SetLabelSize(0.04); // axis titles h->GetXaxis()->SetTitleSize(0.04); h->GetYaxis()->SetTitleSize(0.04); h->GetXaxis()->SetTitleOffset(1.8); h->GetYaxis()->SetTitleOffset(1.9); h->GetXaxis()->CenterTitle(true); h->GetYaxis()->CenterTitle(true); const CaloSubdetectorTopology* topology = ct.getSubdetectorTopology(det, subdetn); std::vector<DetId> ebDetIds; ebDetIds.emplace_back(EBDetId(1, 1)); ebDetIds.emplace_back(EBDetId(30, 30)); ebDetIds.emplace_back(EBDetId(-1, 120)); ebDetIds.emplace_back(EBDetId(85, 1)); for (const auto& ebDetId : ebDetIds) { EBDetId myId(ebDetId); std::vector<DetId> myNeighbours = topology->getWindow(myId, 13, 13); for (const auto& myNeighbour : myNeighbours) { EBDetId myEBId(myNeighbour); TBox* box = new TBox(myEBId.ieta() - 0.5, myEBId.iphi() - 0.5, myEBId.ieta() + 0.5, myEBId.iphi() + 0.5); box->SetFillColor(1); box->Draw(); } } gPad->SaveAs(name); delete canv; delete h; } } // ------------ method called to produce the data ------------ void TestEcalGetWindow::analyze(const edm::Event& /*iEvent*/, const edm::EventSetup& iSetup) { std::cout << "Here I am " << std::endl; const auto& theCaloTopology = iSetup.getData(topologyToken_); const auto& pG = iSetup.getData(geometryToken_); if (pass_ == 1) { build(pG, theCaloTopology, DetId::Ecal, EcalBarrel, "EBGetWindowTest.eps"); } if (pass_ == 2) { build(pG, theCaloTopology, DetId::Ecal, EcalEndcap, "EEGetWindowTest.eps"); } pass_++; } //define this as a plug-in DEFINE_FWK_MODULE(TestEcalGetWindow);
32.149485
116
0.665384
[ "geometry", "vector" ]
ee17e38da0658797de356b1de2ec6591776cff76
8,879
cc
C++
src/FileIO/filestruct.cc
tech-pi/BBSLMIRP
21bd8780c0e7df255a7dd4a6967d8fabc882ef42
[ "MIT" ]
4
2019-07-18T03:14:32.000Z
2021-07-07T18:15:49.000Z
src/FileIO/filestruct.cc
chengaoyu/BBSLMIRP
21bd8780c0e7df255a7dd4a6967d8fabc882ef42
[ "MIT" ]
null
null
null
src/FileIO/filestruct.cc
chengaoyu/BBSLMIRP
21bd8780c0e7df255a7dd4a6967d8fabc882ef42
[ "MIT" ]
1
2019-11-28T02:52:45.000Z
2019-11-28T02:52:45.000Z
/* @brief: the definition of @auther: chengaoyu2013@gmail.com @date: 2017/10/29 */ #include"filestruct.h" #include"datastruct.h" #include<iostream> #include<iomanip> #include"grid.h" #include"ray.h" #include"patch.h" namespace BBSLMIRP { FileController::FileController(){ } FileController::~FileController(){ } bool FileController::ReadImage(const std::string &image_name, Grid3D &image) const{ std::ifstream infile(image_name, std::ios_base::in); if(! infile.good()){ std::cerr<<"ReadImg(): no file "<<image_name <<"!"<<std::endl; std::exit(-1); } size_t nX = image.get_block().get_num_grid().get_num_x(); size_t nY = image.get_block().get_num_grid().get_num_y(); size_t nZ = image.get_block().get_num_grid().get_num_z(); for (size_t k=0; k<nZ;k++){ for(size_t j=0; j<nY; j++){ for(size_t i=0; i<nX; i++){ //define a mesh index. MeshIndex mi(i,j,k); float value; //read the value of the image voxels. infile>>value; image.set_mesh(mi,value); } } } return true; } bool FileController::ReadImageBin(const std::string &image_name, Grid3D &image) const{ std::ifstream infile(image_name, std::ios_base::in); if(! infile.good()){ std::cerr<<"ReadImg(): no file "<<image_name <<"!"<<std::endl; std::exit(-1); } size_t nX = image.get_block().get_num_grid().get_num_x(); size_t nY = image.get_block().get_num_grid().get_num_y(); size_t nZ = image.get_block().get_num_grid().get_num_z(); for (size_t k=0; k<nZ;k++){ for(size_t j=0; j<nY; j++){ for(size_t i=0; i<nX; i++){ //define a mesh index. MeshIndex mi(i,j,k); float value; //read the value of the image voxels. infile.read((char*)&value,sizeof(float)); image.set_mesh(mi,value); } } } return true; } bool FileController::SaveImage(const std::string &image_name, const Grid3D &image) const{ std::ofstream outfile(image_name, std::ios_base::out); if(! outfile.good()){ std::cerr<<"SaveImg(): Error while open file!"<<std::endl; return false; } size_t nX = image.get_block().get_num_grid().get_num_x(); size_t nY = image.get_block().get_num_grid().get_num_y(); size_t nZ = image.get_block().get_num_grid().get_num_z(); for (size_t k=0; k<nZ;k++){ for(size_t j=0; j<nY; j++){ for(size_t i=0; i<nX; i++){ MeshIndex mi(i,j,k); outfile<< image.get_mesh(mi)<<std::endl; } } } return true; } bool FileController::SaveImageBin(const std::string image_name, const Grid3D &image) const{ std::ofstream outfile(image_name, std::ios_base::out|std::ios_base::binary); if(! outfile.good()){ std::cerr<<"SaveImg(): Error while open file!"<<std::endl; return false; } size_t nX = image.get_block().get_num_grid().get_num_x(); size_t nY = image.get_block().get_num_grid().get_num_y(); size_t nZ = image.get_block().get_num_grid().get_num_z(); for (size_t k=0; k<nZ;k++){ for(size_t j=0; j<nY; j++){ for(size_t i=0; i<nX; i++){ MeshIndex mi(i,j,k); float value = image.get_mesh(mi); outfile.write((char*)&value, sizeof(float)); } } } return true; } bool FileController::ReadEvent(std::ifstream &inStream, Event &evt) const{ // if(!inStream.good()){ // std::cerr<<"ReadEvt(): Error while open file!"<<std::endl; // return false; // } Point3D pt1 = ReadPoint(inStream); Point3D pt2 = ReadPoint(inStream); evt.get_ray().SetRay(pt1,pt2); float tof_distance; inStream >> tof_distance; evt.set_tof_distance(tof_distance); return true; } bool FileController::SaveEvent(std::ofstream &outStream, Event &evt) const{ // if(!outStream.good()){ // std::cerr<<"SaveEvent(): Error while open file!"<<std::endl; // return false; // } SavePoint(outStream,evt.get_ray().get_startpoint()); SavePoint(outStream,evt.get_ray().get_endpoint()); outStream << std::setw(20) << evt.get_tof_distance()<<std::endl; return true; } bool FileController::LoadEvents(const std::string &file_name, int pos, int list_size, CoinEventList &evtlist){ std::ifstream infile(file_name,std::ios_base::in|std::ios_base::binary); if(!infile.good()){ std::cerr<<"LoadEvents(): error when open file "<<file_name<<"!"<<std::endl; std::exit(-1); } // move to the position to be loaded. infile.seekg(7*pos*sizeof(float),std::ios_base::beg); int data_size = list_size*7; float* buffer = new float[data_size]; infile.read((char*) buffer,sizeof(float)*data_size); evtlist.clear(); for (int i = 0; i < list_size; i++){ CoinEvent evt; int epos = i*7; evt.pos1_x = buffer[epos]; evt.pos1_y = buffer[epos+1]; evt.pos1_z = buffer[epos+2]; evt.pos2_x = buffer[epos+3]; evt.pos2_y = buffer[epos+4]; evt.pos2_z = buffer[epos+5]; evt.tof_dis = buffer[epos+6]; evtlist.push_back(evt); } delete [] buffer; return true; } bool FileController::SaveEvents(const std::string &file_name, CoinEventList &evtlist){ std::ofstream outfile(file_name,std::ios_base::out|std::ios_base::binary|std::ios_base::app); if(!outfile.good()){ std::cerr<<"SaveEvents(): error when open file "<<file_name<<"!"<<std::endl; std::exit(-1); } // move to the position to be loaded. //outfile.seekp(pos,std::ios_base::beg); int list_size = evtlist.size(); int data_size = list_size*7; float* buffer = new float[data_size]; for (int i = 0; i < list_size; i++){ CoinEvent evt = evtlist[i]; int epos = i*7; buffer[epos] = evt.pos1_x; buffer[epos+1] = evt.pos1_y; buffer[epos+2] = evt.pos1_z; buffer[epos+3] = evt.pos2_x; buffer[epos+4] = evt.pos2_y; buffer[epos+5] = evt.pos2_z; buffer[epos+6] = evt.tof_dis; } outfile.write((char*) buffer,data_size*sizeof(float)); delete [] buffer; return true; } bool FileController::ReadListModeEvent(std::ifstream &inStream, LMEvent &lmevent) const{ } bool FileController::SaveListModeEvent(std::ofstream &outStream, LMEvent &lmevent) const{ } bool FileController::ReadHeader(const std::string& file_name, int &num_events) const{ std::ifstream header_file(file_name+".hdr",std::ios_base::in); if(!header_file.good()){ std::cerr<<"ReadHeader(): Error while open file!"<<std::endl; std::exit(-1); } header_file>>num_events; return true; } bool FileController::SaveHeader(const std::string& file_name, int &num_events) const{ std::ofstream header_file(file_name+".hdr",std::ios_base::out); if(!header_file.good()){ std::cerr<<"SaveHeader(): Error while open file!"<<std::endl; return false; } header_file<<num_events<<std::endl; return true; } bool FileController::ReadPatch(std::ifstream & inStream, Patch& patch )const{ if(!inStream.good()){ std::cerr<<"ReadPatch(): Error while open file!"<<std::endl; std::exit(-1); } int num_vertice; inStream>> num_vertice; Face in_face; Face out_face; for (int iVertex = 0; iVertex < num_vertice; iVertex++){ in_face.push_back(ReadPoint(inStream)); } for (int iVertex = 0; iVertex < num_vertice; iVertex++){ out_face.push_back(ReadPoint(inStream)); } return patch.Initialize(in_face, out_face); } Point3D FileController::ReadPoint(std::ifstream & inStream)const{ float px,py,pz; inStream >> px >> py >> pz; return Point3D(px,py,pz); } void FileController::SavePoint(std::ofstream &outStream,const Point3D &pt) const{ outStream << std::setw(20) << pt.get_px(); outStream << std::setw(20) << pt.get_py(); outStream << std::setw(20) << pt.get_pz(); } void FileController::ReadPETConfigure(const std::string &file_name, std::string &pet_category) const{ std::ifstream pet_configure(file_name,std::ios_base::in); if(!pet_configure.good()){ std::cerr<<"ReadPETConfigure(): Error while open file!"<<std::endl; std::exit(-1); } else{ std::string pet_name; pet_configure>>pet_name; if(pet_name == "PETScanner:"){ pet_configure>>pet_category; } else{ std::cerr<<"ReadPETConfigure(): configure file is bad!"<<std::endl; std::exit(-1); } } pet_configure.close(); } void FileController::ReadTaskFile(const std::string &file_name) const{ } }
32.52381
110
0.603784
[ "mesh" ]
ee19a1b13ed2feb50d8a9a2eb432c8e6587499f8
384
cpp
C++
Teme/Tema1_AA/algo1.cpp
teodutu/PA
9abaf9f0ebbce8beac274edd672473a17575fe03
[ "MIT" ]
7
2019-02-12T15:14:12.000Z
2020-05-05T13:48:52.000Z
Teme/Tema1_AA/algo1.cpp
teodutu/PA
9abaf9f0ebbce8beac274edd672473a17575fe03
[ "MIT" ]
null
null
null
Teme/Tema1_AA/algo1.cpp
teodutu/PA
9abaf9f0ebbce8beac274edd672473a17575fe03
[ "MIT" ]
7
2020-03-22T09:46:19.000Z
2021-03-11T20:53:19.000Z
#include "fermat.h" #define NUM_TESTS 8 std::vector<int> filter_non_prime(const std::vector<int>& sequence) { std::vector<int> primes; // se ruleaza cate 8 teste cu algoritmul lui Fermat pentru fiecare numar din secventa data for (int n : sequence) { if(is_fermat_prime(n, NUM_TESTS)) { primes.emplace_back(n); } } return primes; }
22.588235
94
0.643229
[ "vector" ]
ee1e9caaa54255439066b666c30d3e776681c119
515
cpp
C++
rt/rt/coordmappers/plane.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/rt/coordmappers/plane.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/rt/coordmappers/plane.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
#include <core/float4.h> #include <rt/coordmappers/plane.h> #include <rt/intersection.h> namespace rt { PlaneCoordMapper::PlaneCoordMapper(const Vector& e1, const Vector& e2) : m(Matrix::inverseOf(Float4(e1.x, e2.x, (cross(e1, e2)).x, 0), Float4(e1.y, e2.y, (cross(e1, e2)).y, 0), Float4(e1.z, e2.z, (cross(e1, e2)).z, 0), Float4(0, 0, 0, 1))) { } Point PlaneCoordMapper::getCoords(const Intersection& hit) const { const auto tmp = m * Float4(hit.local()); return Point(tmp[0], tmp[1], 0.f); } }
27.105263
70
0.648544
[ "vector" ]
ee2671dc17aa58f562e4009171b65f026564324f
6,474
hpp
C++
include/PhysicsGrid.hpp
lwesterl/PhysicsEngine
b528145a6b570a7bbb42c31552d8d8a99beb8d43
[ "MIT" ]
null
null
null
include/PhysicsGrid.hpp
lwesterl/PhysicsEngine
b528145a6b570a7bbb42c31552d8d8a99beb8d43
[ "MIT" ]
null
null
null
include/PhysicsGrid.hpp
lwesterl/PhysicsEngine
b528145a6b570a7bbb42c31552d8d8a99beb8d43
[ "MIT" ]
null
null
null
/** * @file PhysicsGrid.hpp * @author Lauri Westerholm * @brief Header for class PhysicsGrid */ #pragma once #include "../utils/Rect.hpp" #include "../utils/Vector2.hpp" #include "PhysicsObject.hpp" #include "DynamicObject.hpp" #include "StaticObject.hpp" #include <list> #include <vector> /** * @namespace pe * @remark Stands for PhysicsEngine */ namespace pe { /** * @struct Cell * @brief struct representing one cell in Grid */ template<class T> struct Cell { std::list<T> entities; /**< list of entities Cell contains */ bool active_cell; /**< Whether Cell is active or not */ }; /** * @class PhysicsGrid * @brief Container for PhysicsObject of PhysicsWorld * @details Consists of Cell structs. PhysicsGrid and it's Cells take * ownership of PhysicsObjects so their memory deletion is handled by Grid. * Do NOT delete objects memory elsewhere */ class PhysicsGrid { public: /** * @brief Standard empty constructor */ PhysicsGrid(); /** * @brief Deconstructor * @details Frees all memory allocated by the Grid */ virtual ~PhysicsGrid(); /** * @brief Copy constructor * @param grid Grid which is copied */ PhysicsGrid(const PhysicsGrid& grid); /** * @brief Assignment operator overload * @param grid Grid which is copied */ PhysicsGrid& operator=(const PhysicsGrid& grid); /** * @brief Add cells to Grid, this must be called prior accessing PhysicsGrid * @details After Cell is added, Grid maintains removal of the entities * @param gridWidth width of the whole grid, symmetrically distributed around zero * @param gridHeight height of the whole game area, symmetrically distributed around zero * @param cellSize size of one grid cell */ void addCells(int gridWidth, int gridHeight, int gridCellSize); /** * @brief Add PhysicsObject to Cell in the Grid * @param object to be added * @return true if object was added, otherwise false * @details object cannot be added if there is no Cell matching to * the position of object * @remark This is not very trustworthy, only the center of object * is checked whether it's inside Cell or not */ bool addObject(PhysicsObject* object); /** * @brief Remove PhysicsObject from PhysicsGrid * @param object to be removed * @return true if object successfully removes, otherwise false */ bool removeObject(PhysicsObject* object); /** * @brief Move all objects to correct grid cells * @details PhysicsObject checked for move its moved bool is true. * After possibly moving sets the moved to false. DynamicObject * needs to be moved if its position isn't inside the grid cell * @remark This is necessarily quite heavy method and it should be * called only from PhysicsWorld update */ void moveObjects(); /** * @brief Get const iterator to the beginning of cell * @return cells.cbegin() */ inline std::vector<std::vector<Cell<PhysicsObject*>*>>::const_iterator cbegin() { return cells.cbegin(); } /** * @brief Get const iterator to the end of cell * @return cells.cend() */ inline std::vector<std::vector<Cell<PhysicsObject*>*>>::const_iterator cend() { return cells.cend(); } /** * @brief Get iterator to the beginning of cell * @return cells.begin() */ inline std::vector<std::vector<Cell<PhysicsObject*>*>>::iterator begin() { return cells.begin(); } /** * @brief Get iterator to the end of cell * @return cell.cend() */ inline std::vector<std::vector<Cell<PhysicsObject*>*>>::iterator end() { return cells.end(); } /** * @brief Get loose_cell * @return pointer to loose_cell */ inline Cell<PhysicsObject*>* getLooseCell() { return loose_cell; } /** * @brief Get cells size * @return cells.size */ inline unsigned getCellsSize() { return cells.size(); } private: /** * @brief Clear Grid * @details Removes all cells and their objects. Deletes also memory used for * those */ void Clear(); /** * @brief Copy Grid * @details Makes hard copy of the Grid, i.e. allocates new pointers for * objects * @param grid Grid to be copied */ void Copy(const PhysicsGrid& grid); /** * @brief Activate / deactivate Cell * @details Cell is active if it contains at least one DynamicObject * @param cell Cell to be checked * @return true if cell active, otherwise false */ bool ActivateCell(Cell<PhysicsObject*>* cell); /** * @brief Try to insert object to cell * @param object PhysicsObject to be inserted * @return true if successful, otherwise false -> object should be * inserted to loose_cell */ bool insertObject(PhysicsObject* object); /** * @brief Move loose_cell PhysicsObjects * @remark This should be called only from moveObjects */ void moveLooseCellObjects(); /** * @brief Get Cell that matches position * @param pos position vector * @return Cell or nullptr if no Cell found */ Cell<PhysicsObject*>* GetCorrectCell(const Vector2f pos) const; std::vector<std::vector<Cell<PhysicsObject*>*>> cells; Cell<PhysicsObject*>* loose_cell = nullptr; /**< Cell for all PhysicsObjects which are not in a single Cell, cells */ int gridWidth = 0; int gridHeight = 0; int gridCellSize = 0; }; } // end of namespace pe
30.976077
125
0.561631
[ "object", "vector" ]
ee26d0206473d8657b0bdd8478c7278d0109efc3
1,756
cpp
C++
src/JMT.cpp
usedlobster/CarND-T3-P1
47ab5cd7c73fa0b6088d06d22df18891d895f8ca
[ "MIT" ]
null
null
null
src/JMT.cpp
usedlobster/CarND-T3-P1
47ab5cd7c73fa0b6088d06d22df18891d895f8ca
[ "MIT" ]
null
null
null
src/JMT.cpp
usedlobster/CarND-T3-P1
47ab5cd7c73fa0b6088d06d22df18891d895f8ca
[ "MIT" ]
null
null
null
#include "JMT.hpp" #include "Eigen-3.3/Eigen/Core" #include "Eigen-3.3/Eigen/QR" #include "Eigen-3.3/Eigen/LU" using namespace std; using Eigen::MatrixXd ; using Eigen::VectorXd ; void QuinticPath::JMT( double tBase, double Tperiod ) { T = Tperiod ; t0 = tBase ; t1 = t0 + T ; double T2 = ( T * T ) ; double T3 = ( T2 * T ) ; double T4 = ( T3 * T ) ; double T5 = ( T4 * T ) ; MatrixXd A = MatrixXd(3, 3); // A << T3, T4, T5, 3*T2, 4*T3, 5*T4, 6*T, 12*T2, 20*T3 ; MatrixXd B = MatrixXd( 3, 1 ) ; B << ec[0] - ( ic[0]+ic[1]*T+0.5*ic[2]*T2 ), ec[1] - ( ic[1]+ic[2]*T ), ec[2] - ( ic[2] ) ; MatrixXd Ai ; Ai = A.inverse(); MatrixXd C = Ai*B; //vector <double> result = {start[0], start[1], .5*start[2]}; poly[0] = ic[0] ; poly[1] = ic[1] ; poly[2] = 0.5*ic[2] ; poly[3] = C(0); poly[4] = C(1); poly[5] = C(2); } double QuinticPath::get( double t ) { t -= t0 ; if ( t > T ) t =T ; else if ( t < 0.0 ) t = 0.0 ; return (((( poly[5] * t + poly[4] ) * t + poly[3] ) * t + poly[2] ) * t + poly[1] ) * t + poly[0] ; } double QuinticPath::get1d( double t ) { t -= t0 ; if ( t > T ) t =T ; else if ( t < 0.0 ) t = 0.0 ; return ((( 5.0 * poly[5] * t + 4.0 * poly[4] ) * t + 3.0*poly[3] ) * t + 2.0*poly[2] ) * t + poly[1] ; } double QuinticPath::get2d( double t ) { t -= t0 ; if ( t > T ) t =T ; else if ( t < 0.0 ) t = 0.0 ; return (( 20.0 * poly[5] * t + 12.0 * poly[4] ) * t + 6.0*poly[3] ) * t + 2 * poly[2] ; } double QuinticPath::get3d( double t ) { t -= t0 ; if ( t > T ) t =T ; else if ( t < 0.0 ) t = 0.0 ; return ( 60.0 * poly[5] * t + 24.0 * poly[4] ) * t + 6.0 *poly[3] ; } // return [-1,+1] => [-inf,+inf]
19.511111
105
0.464123
[ "vector" ]
ee29de1af83e6dd04a9baeff35008f5642c27574
4,645
cpp
C++
src/game/agent/htnTasks/MovementTasks.cpp
makuto/galavant
3da5ee8cfe5f12f0d842f808d22aafc9493941db
[ "MIT" ]
11
2016-11-15T03:12:23.000Z
2021-08-11T16:27:46.000Z
src/game/agent/htnTasks/MovementTasks.cpp
makuto/galavant
3da5ee8cfe5f12f0d842f808d22aafc9493941db
[ "MIT" ]
null
null
null
src/game/agent/htnTasks/MovementTasks.cpp
makuto/galavant
3da5ee8cfe5f12f0d842f808d22aafc9493941db
[ "MIT" ]
4
2016-10-20T10:18:29.000Z
2021-05-25T05:46:18.000Z
#include "MovementTasks.hpp" #include "util/Logging.hpp" #include "world/Position.hpp" #include "world/WorldResourceLocator.hpp" namespace gv { bool FindResourceTask::StateMeetsPreconditions(const gv::WorldState& state, const Htn::ParameterList& parameters) const { return parameters.size() == 1 && parameters[0].Type == Htn::Parameter::ParamType::Int && gv::WorldResourceLocator::ResourceExistsInWorld( (gv::WorldResourceType)parameters[0].IntValue); } void FindResourceTask::ApplyStateChange(gv::WorldState& state, const Htn::ParameterList& parameters) { // TODO: Should this be the case? Should StateMeetsPreconditions find the position? This isn't // that much of a problem if ResourceLocator caches searches float manhattanTo = 0.f; gv::WorldResourceLocator::Resource* resource = gv::WorldResourceLocator::FindNearestResource( (gv::WorldResourceType)parameters[0].IntValue, state.SourceAgent.position, false, manhattanTo); if (resource) { state.SourceAgent.TargetPosition = resource->position; state.SourceAgent.TargetEntity = resource->entity; } } Htn::TaskExecuteStatus FindResourceTask::Execute(gv::WorldState& state, const Htn::ParameterList& parameters) { float manhattanTo = 0.f; gv::WorldResourceLocator::Resource* resource = gv::WorldResourceLocator::FindNearestResource( (gv::WorldResourceType)parameters[0].IntValue, state.SourceAgent.position, false, manhattanTo); if (resource) { LOGD << "Found resource at " << state.SourceAgent.TargetPosition; // TODO: Execute and ApplyStateChange duplicate code state.SourceAgent.TargetPosition = resource->position; state.SourceAgent.TargetEntity = resource->entity; Htn::TaskExecuteStatus status{Htn::TaskExecuteStatus::ExecutionStatus::Succeeded}; return status; } else LOGD << "Couldn't find resource!"; LOGD << "Failed to find resource"; Htn::TaskExecuteStatus status{Htn::TaskExecuteStatus::ExecutionStatus::Failed}; return status; } void MoveToTask::Initialize(MovementManager* newMovementManager) { movementManager = newMovementManager; } bool MoveToTask::StateMeetsPreconditions(const gv::WorldState& state, const Htn::ParameterList& parameters) const { // We're good to move to a position as long as we have a target if (state.SourceAgent.TargetPosition) return true; return false; } void MoveToTask::ApplyStateChange(gv::WorldState& state, const Htn::ParameterList& parameters) { state.SourceAgent.position = state.SourceAgent.TargetPosition; } Htn::TaskExecuteStatus MoveToTask::Execute(gv::WorldState& state, const Htn::ParameterList& parameters) { if (movementManager) { gv::EntityList entitiesToMove{state.SourceAgent.SourceEntity}; std::vector<gv::Position> positions{state.SourceAgent.TargetPosition}; LOGD << "Moving Ent[" << state.SourceAgent.SourceEntity << "] to " << state.SourceAgent.TargetPosition; movementManager->PathEntitiesTo(entitiesToMove, positions); Htn::TaskExecuteStatus status{Htn::TaskExecuteStatus::ExecutionStatus::WaitForEvent}; return status; } Htn::TaskExecuteStatus status{Htn::TaskExecuteStatus::ExecutionStatus::Failed}; return status; } void GetResourceTask::Initialize(FindResourceTask* newFindResourceTask, MoveToTask* newMoveToTask) { FindResourceTaskRef.Initialize(newFindResourceTask); MoveToTaskRef.Initialize(newMoveToTask); } bool GetResourceTask::StateMeetsPreconditions(const gv::WorldState& state, const Htn::ParameterList& parameters) const { // TODO: What is the purpose of the compound task checking preconditions if they'll be near // identical to the combined primitive task preconditions? bool parametersValid = parameters.size() == 1 && parameters[0].Type == Htn::Parameter::ParamType::Int; LOGD_IF(!parametersValid) << "GetResourceTask parameters invalid! Expected Int"; return parametersValid; } bool GetResourceTask::Decompose(Htn::TaskCallList& taskCallList, const gv::WorldState& state, const Htn::ParameterList& parameters) { Htn::ParameterList findResourceParams = parameters; Htn::ParameterList moveToParams; Htn::TaskCall FindResourceTaskCall{&FindResourceTaskRef, findResourceParams}; Htn::TaskCall MoveToTaskCall{&MoveToTaskRef, moveToParams}; // TODO: Make it clear that users should only ever push to this list taskCallList.push_back(FindResourceTaskCall); taskCallList.push_back(MoveToTaskCall); return true; } }
36.865079
100
0.733907
[ "vector" ]
ee2bbcde5ee66ff9496a42c4de2e63562da149d5
1,162
cpp
C++
Main.cpp
HackyTeam/HackyASM
eb0e61aefdf46a9422919c75d78c1041c331cfc8
[ "MIT" ]
null
null
null
Main.cpp
HackyTeam/HackyASM
eb0e61aefdf46a9422919c75d78c1041c331cfc8
[ "MIT" ]
null
null
null
Main.cpp
HackyTeam/HackyASM
eb0e61aefdf46a9422919c75d78c1041c331cfc8
[ "MIT" ]
null
null
null
#include "lib/BasicIInterpreter.hpp" int main() { using namespace hsd::string_view_literals; hasm::basic_iinterpreter interpreter = "TestInter.hasm"_sv; interpreter.add_extern_func( "malloc"_sv, [](hsd::vector<hsd::u64>& args) { hasm::call( [&](hsd::u64 arg) { args.push_back(reinterpret_cast<hsd::u64>(malloc(arg))); }, args ); } ); interpreter.add_extern_func( "free"_sv, [](hsd::vector<hsd::u64>& args) { hasm::call( [](hsd::u64 arg) { free(reinterpret_cast<void*>(arg)); }, args ); } ); interpreter.add_extern_func( "printlnf"_sv, [](hsd::vector<hsd::u64>& args) { hasm::call([](hsd::f64 arg) { hsd_println("{}", arg); }, args); } ); interpreter.add_extern_func( "printlni"_sv, [](hsd::vector<hsd::u64>& args) { hasm::call([](hsd::u64 arg) { printf("%#0x\n", arg); }, args); } ); interpreter.run(); }
24.723404
76
0.461274
[ "vector" ]
0c583630971d5d80b193eb3995be84b9b079e8f4
8,261
cpp
C++
dynamorio/clients/drcachesim/tests/cache_miss_analyzer_test.cpp
andre-motta/Project3Compilers
fa366d93ec8d49768fbc86f0c1431391822baf12
[ "MIT" ]
107
2021-08-28T20:08:42.000Z
2022-03-22T08:02:16.000Z
dynamorio/clients/drcachesim/tests/cache_miss_analyzer_test.cpp
andre-motta/Project3Compilers
fa366d93ec8d49768fbc86f0c1431391822baf12
[ "MIT" ]
1
2021-06-01T12:10:25.000Z
2021-06-01T12:10:25.000Z
dynamorio/clients/drcachesim/tests/cache_miss_analyzer_test.cpp
andre-motta/Project3Compilers
fa366d93ec8d49768fbc86f0c1431391822baf12
[ "MIT" ]
16
2021-08-30T06:57:36.000Z
2022-03-22T08:05:52.000Z
/* ********************************************************** * Copyright (c) 2015-2018 Google, LLC All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Google, Inc. 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 GOOGLE, LLC 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 <iostream> #include "../simulator/cache_miss_analyzer.h" #include "../simulator/cache_simulator.h" #include "../common/memref.h" static memref_t generate_mem_ref(const addr_t addr, const addr_t pc) { memref_t memref; memref.data.type = TRACE_TYPE_READ; memref.data.pid = 11111; memref.data.tid = 22222; memref.data.addr = addr; memref.data.size = 8; memref.data.pc = pc; return memref; } // A test with no dominant stride. bool no_dominant_stride() { const unsigned int kLineSize = 64; // Create the cache simulator knobs object. cache_simulator_knobs_t knobs; knobs.line_size = kLineSize; knobs.LL_size = 1024 * 1024; knobs.data_prefetcher = "none"; // Create the cache miss analyzer object. cache_miss_analyzer_t analyzer(knobs, 1000, 0.01, 0.75); // Analyze a stream of memory load references with no dominant stride. addr_t addr = 0x1000; for (int i = 0; i < 50000; ++i) { analyzer.process_memref(generate_mem_ref(addr, 0xAAAA)); addr += kLineSize; analyzer.process_memref(generate_mem_ref(addr, 0xAAAA)); addr += (kLineSize * 3); analyzer.process_memref(generate_mem_ref(addr, 0xAAAA)); addr += (kLineSize * 5); analyzer.process_memref(generate_mem_ref(addr, 0xAAAA)); addr += (kLineSize * 7); analyzer.process_memref(generate_mem_ref(addr, 0xAAAA)); addr += (kLineSize * 5); } // Generate the analyzer's result and check it. std::vector<prefetching_recommendation_t *> recommendations = analyzer.generate_recommendations(); if (recommendations.empty()) { std::cout << "no_dominant_stride test passed." << std::endl; return true; } else { std::cerr << "no_dominant_stride test failed." << std::endl; return false; } } // A test with one dominant stride. bool one_dominant_stride() { const int kStride = 7; const unsigned int kLineSize = 64; // Create the cache simulator knobs object. cache_simulator_knobs_t knobs; knobs.line_size = kLineSize; knobs.LL_size = 1024 * 1024; knobs.data_prefetcher = "none"; // Create the cache miss analyzer object. cache_miss_analyzer_t analyzer(knobs, 1000, 0.01, 0.75); // Analyze a stream of memory load references with one dominant stride. addr_t addr = 0x1000; for (int i = 0; i < 50000; ++i) { analyzer.process_memref(generate_mem_ref(addr, 0xAAAA)); addr += (kLineSize * kStride); analyzer.process_memref(generate_mem_ref(addr, 0xAAAA)); addr += (kLineSize * kStride); analyzer.process_memref(generate_mem_ref(addr, 0xAAAA)); addr += (kLineSize * kStride); analyzer.process_memref(generate_mem_ref(addr, 0xAAAA)); addr += (kLineSize * kStride); analyzer.process_memref(generate_mem_ref(addr, 0xAAAA)); addr += 1000; } // Generate the analyzer's result and check it. std::vector<prefetching_recommendation_t *> recommendations = analyzer.generate_recommendations(); if (recommendations.size() == 1) { if (recommendations[0]->pc == 0xAAAA && recommendations[0]->stride == (kStride * kLineSize)) { std::cout << "one_dominant_stride test passed." << std::endl; return true; } else { std::cerr << "one_dominant_stride test failed: wrong recommendation: " << "pc=" << recommendations[0]->pc << ", stride=" << recommendations[0]->stride << std::endl; return false; } } else { std::cerr << "one_dominant_stride test failed: number of recommendations " << "should be exactly 1, but was " << recommendations.size() << std::endl; return false; } } // A test with two dominant strides. bool two_dominant_strides() { const int kStride1 = 3; const int kStride2 = 11; const unsigned int kLineSize = 64; // Create the cache simulator knobs object. cache_simulator_knobs_t knobs; knobs.line_size = kLineSize; knobs.LL_size = 1024 * 1024; knobs.data_prefetcher = "none"; // Create the cache miss analyzer object. cache_miss_analyzer_t analyzer(knobs, 1000, 0.01, 0.75); // Analyze a stream of memory load references with two dominant strides. addr_t addr1 = 0x1000; addr_t addr2 = 0x2000; for (int i = 0; i < 50000; ++i) { analyzer.process_memref(generate_mem_ref(addr1, 0xAAAA)); addr1 += (kLineSize * kStride1); analyzer.process_memref(generate_mem_ref(addr1, 0xAAAA)); addr1 += (kLineSize * kStride1); analyzer.process_memref(generate_mem_ref(addr2, 0xBBBB)); addr2 += (kLineSize * kStride2); analyzer.process_memref(generate_mem_ref(addr1, 0xAAAA)); addr1 += (kLineSize * kStride1); analyzer.process_memref(generate_mem_ref(addr2, 0xBBBB)); addr2 += (kLineSize * kStride2); analyzer.process_memref(generate_mem_ref(addr2, 0xBBBB)); addr2 += (kLineSize * kStride2); } // Generate the analyzer's result and check it. std::vector<prefetching_recommendation_t *> recommendations = analyzer.generate_recommendations(); if (recommendations.size() == 2) { if ((recommendations[0]->pc == 0xAAAA && recommendations[0]->stride == (kStride1 * kLineSize) && recommendations[1]->pc == 0xBBBB && recommendations[1]->stride == (kStride2 * kLineSize)) || (recommendations[1]->pc == 0xAAAA && recommendations[1]->stride == (kStride1 * kLineSize) && recommendations[0]->pc == 0xBBBB && recommendations[0]->stride == (kStride2 * kLineSize))) { std::cout << "two_dominant_strides test passed." << std::endl; return true; } else { std::cerr << "two_dominant_strides test failed: wrong recommendations." << std::endl; return false; } } else { std::cerr << "two_dominant_strides test failed: number of recommendations " << "should be exactly 2, but was " << recommendations.size() << std::endl; return false; } } int main(int argc, const char *argv[]) { if (no_dominant_stride() && one_dominant_stride() && two_dominant_strides()) { return 0; } else { std::cerr << "cache_miss_analyzer_test failed" << std::endl; exit(1); } }
37.721461
83
0.639874
[ "object", "vector" ]
0c5cc43c349aebe512f8f5dff3fca9b1c363e463
8,591
cpp
C++
Code/CommonFiles/src/FuzzyLite/LinguisticVariable.cpp
P4ALLcerthiti/P4ALL_FallDetection
f3fcab26d66f4d36ddca4ba69262022e289a128b
[ "BSD-3-Clause" ]
2
2017-08-28T21:12:40.000Z
2021-02-20T06:58:19.000Z
Code/CommonFiles/src/FuzzyLite/LinguisticVariable.cpp
P4ALLcerthiti/P4ALL_Fall_Detection_Web_Services
4d2b4fc4ed326d0ebfb3934ac88f13b78433af7a
[ "BSD-3-Clause" ]
null
null
null
Code/CommonFiles/src/FuzzyLite/LinguisticVariable.cpp
P4ALLcerthiti/P4ALL_Fall_Detection_Web_Services
4d2b4fc4ed326d0ebfb3934ac88f13b78433af7a
[ "BSD-3-Clause" ]
null
null
null
/* Copyright 2010 Juan Rada-Vilela 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 "stdafx.h" #include "LinguisticVariable.h" #include "FuzzyExceptions.h" #include "StrOp.h" #include <algorithm> #include <math.h> #include "ShoulderTerm.h" #include "TriangularTerm.h" #include "TrapezoidalTerm.h" namespace fl { LinguisticVariable::LinguisticVariable() : _fuzzy_operator(NULL) { setFuzzyOperator(FuzzyOperator::DefaultFuzzyOperator()); } LinguisticVariable::LinguisticVariable(const std::string& name) : _fuzzy_operator(NULL), _name(name) { setFuzzyOperator(FuzzyOperator::DefaultFuzzyOperator()); } LinguisticVariable::LinguisticVariable(const FuzzyOperator& fuzzy_op, const std::string& name) : _fuzzy_operator(&fuzzy_op), _name(name) { } LinguisticVariable::~LinguisticVariable() { for (int i = numberOfTerms() - 1; i >= 0; --i) { delete removeTerm(i); } } std::string LinguisticVariable::name() const { return this->_name; } void LinguisticVariable::setName(const std::string& name) { this->_name = name; } void LinguisticVariable::setFuzzyOperator(const FuzzyOperator& fuzzy_operator) { this->_fuzzy_operator = &fuzzy_operator; } const FuzzyOperator& LinguisticVariable::fuzzyOperator() const { return *this->_fuzzy_operator; } int LinguisticVariable::positionFor(const LinguisticTerm* lterm) { for (int i = 0; i < numberOfTerms(); ++i) { if (FuzzyOperation::IsLEq(lterm->minimum(), term(i)->minimum())) { if (FuzzyOperation::IsEq(lterm->minimum(), term(i)->minimum())) { return lterm->membership(lterm->minimum()) > term(i)->membership(lterm->minimum()) ? i : i + 1; } return i; } } return numberOfTerms(); } void LinguisticVariable::addTerm(LinguisticTerm* term) { int pos = positionFor(term); _terms.insert(_terms.begin() + pos, term); } LinguisticTerm* LinguisticVariable::term(int index) const { return _terms[index]; } LinguisticTerm* LinguisticVariable::term(const std::string& name) const { int index = indexOf(name); return index == -1 ? NULL : term(index); } int LinguisticVariable::indexOf(const std::string& name) const { for (int i = 0; i < numberOfTerms(); ++i) { if (term(i)->name() == name) { return i; } } return -1; } LinguisticTerm* LinguisticVariable::removeTerm(int index) { LinguisticTerm* result = _terms[index]; _terms.erase(_terms.begin() + index); return result; } LinguisticTerm* LinguisticVariable::removeTerm(const std::string& name) { int index = indexOf(name); return index == -1 ? NULL : removeTerm(index); } LinguisticTerm* LinguisticVariable::firstTerm() const { return numberOfTerms() > 0 ? term(0) : NULL; } LinguisticTerm* LinguisticVariable::lastTerm() const { return numberOfTerms() > 0 ? term(numberOfTerms() - 1) : NULL; } bool LinguisticVariable::isEmpty() const { return numberOfTerms() == 0; } int LinguisticVariable::numberOfTerms() const { return _terms.size(); } flScalar LinguisticVariable::minimum() const { return numberOfTerms() == 0 ? sqrt(-1.0) : firstTerm()->minimum(); } flScalar LinguisticVariable::maximum() const { return numberOfTerms() == 0 ? sqrt(-1.0) : lastTerm()->maximum(); } CompoundTerm LinguisticVariable::compound() const { CompoundTerm result("Accumulated " + name(), minimum(), maximum()); for (int i = 0; i < numberOfTerms(); ++i) { result.addTerm(*term(i)); } return result; } std::string LinguisticVariable::fuzzify(flScalar crisp) const { std::vector<std::string> fuzzyness; for (int i = 0; i < numberOfTerms(); ++i) { flScalar degree = term(i)->membership(crisp); fuzzyness.push_back(StrOp::ScalarToString(degree) + "/" + term(i)->name()); } // StringOperator::sort(fuzzyness, false); std::string result; for (size_t i = 0; i < fuzzyness.size(); ++i) { result += fuzzyness[i] + (i < fuzzyness.size() - 1 ? " + " : ""); } return result; } LinguisticTerm* LinguisticVariable::bestFuzzyApproximation(flScalar crisp) { LinguisticTerm* result = NULL; flScalar highest_degree = -1.0; for (int i = 0; i < numberOfTerms(); ++i) { flScalar degree = term(i)->membership(crisp); if (degree > highest_degree) { result = term(i); highest_degree = degree; } } return result; } void LinguisticVariable::createTerms(int number_of_terms, LinguisticTerm::eMembershipFunction mf, flScalar min, flScalar max, const std::vector<std::string>& labels) { std::vector<std::string> final_labels; for (int i = 0; i < number_of_terms; ++i) { if ((int) labels.size() <= i) { final_labels.push_back(name() + "-" + StrOp::IntToString(i + 1)); } else { final_labels.push_back(labels[i]); } } fl::flScalar intersection = sqrt(-1.0); //Proportion of intersection between terms if (mf == LinguisticTerm::MF_TRAPEZOIDAL) { intersection = 4.0 / 5.0; } else { intersection = 0.5; } //TODO: What is the intersection in other terms? fl::flScalar term_range = (max - min) / (number_of_terms - number_of_terms / 2); fl::flScalar current_step = min + (1 - intersection) * term_range; for (int i = 0; i < number_of_terms; ++i) { fl::LinguisticTerm* term = NULL; switch (mf) { case LinguisticTerm::MF_TRIANGULAR: term = new fl::TriangularTerm(final_labels.at(i), current_step - (1 - intersection) * term_range, current_step + intersection * term_range); break; case LinguisticTerm::MF_SHOULDER: if (i == 0 || i == number_of_terms - 1) { term = new fl::ShoulderTerm(final_labels[i], current_step - (1 - intersection) * term_range, current_step + intersection * term_range, i == 0); } else { term = new fl::TriangularTerm(final_labels.at(i), current_step - (1 - intersection) * term_range, current_step + intersection * term_range); } break; case LinguisticTerm::MF_TRAPEZOIDAL: term = new fl::TrapezoidalTerm(final_labels.at(i), current_step - (1 - intersection) * term_range, current_step + intersection * term_range); // term = new fl::TriangularTerm(final_labels.at(i), current_step // - (1 - intersection) * term_range, current_step + intersection // * term_range); break; default: throw fl::InvalidArgumentException(FL_AT, "Invalid option for membership function"); } current_step += intersection * term_range; addTerm(term); } } std::string LinguisticVariable::toString() const { std::string result(name()); result += "={ "; for (int i = 0; i < numberOfTerms(); ++i) { result += term(i)->name() + " "; } result += "}"; return result; } }
35.647303
104
0.562449
[ "vector" ]
0c638098074abb25f23f5d977b18ceea5c440c1f
1,703
cpp
C++
Old/lib/functions.cpp
waterswims/MC_HAMR
eb0492bc12a6eb67ec1709e5b59bdd53ee999892
[ "MIT" ]
1
2021-08-02T23:14:45.000Z
2021-08-02T23:14:45.000Z
Old/lib/functions.cpp
waterswims/MC_HAMR
eb0492bc12a6eb67ec1709e5b59bdd53ee999892
[ "MIT" ]
null
null
null
Old/lib/functions.cpp
waterswims/MC_HAMR
eb0492bc12a6eb67ec1709e5b59bdd53ee999892
[ "MIT" ]
1
2021-08-02T23:14:45.000Z
2021-08-02T23:14:45.000Z
#include "../includes/functions.hpp" #include <stdexcept> #include <iostream> #include <cmath> #include <sstream> double mean(std::vector<double> &oY){ double s(0); for (int i=0; i < oY.size(); i++){ s += oY[i]; } return s / oY.size(); } double std_dev(std::vector<double> &x){ double av_x = mean(x); int size = x.size(); double sum = 0; for(int i(0); i < size; i++){ sum += pow(x[i] - av_x, 2); } double var = sum/(size - 1.); return pow(var, 0.5); } double norm(std::vector<double> vals) { double s = 0; for(std::vector<double>::iterator it = vals.begin(); it != vals.end(); it++) { s += pow(*it, 2); } return pow(s, 0.5); } double sum(std::vector<double> &oY) { double s = 0; for(std::vector<double>::iterator it = oY.begin(); it != oY.end(); it++) { s += *it; } return s; } int sum(std::vector<int> &oY) { int s = 0; for(std::vector<int>::iterator it = oY.begin(); it != oY.end(); it++) { s += *it; } return s; } void AtoLn(double amean, double asd, double &lmean, double &lsd) { double av = pow(asd, 2); double am2 = pow(amean, 2); lmean = log(am2 / pow(av+am2, 0.5)); lsd = pow(log(1 + av / am2), 0.5); } int mod(int a, int b) { int r = a % b; return r < 0 ? r + b : r; } void c_prod( const xt::xtensorf<double, xt::xshape<4>> &s1, const xt::xtensorf<double, xt::xshape<4>> &s2, xt::xtensorf<double, xt::xshape<4>> &out) { out[0] = s1[1]*s2[2] - s1[2]*s2[1]; out[1] = s1[2]*s2[0] - s1[0]*s2[2]; out[2] = s1[0]*s2[1] - s1[1]*s2[0]; }
21.556962
84
0.496183
[ "vector" ]
0c64d80f415bc9f6d6c7971ad80b565f8b2da79d
2,032
cpp
C++
code/framework/src/integrations/client/instance.cpp
Deewarz/Framework
4feb55cd9bcde691694af8dcad12c291f1b4d353
[ "OpenSSL" ]
null
null
null
code/framework/src/integrations/client/instance.cpp
Deewarz/Framework
4feb55cd9bcde691694af8dcad12c291f1b4d353
[ "OpenSSL" ]
null
null
null
code/framework/src/integrations/client/instance.cpp
Deewarz/Framework
4feb55cd9bcde691694af8dcad12c291f1b4d353
[ "OpenSSL" ]
null
null
null
/* * MafiaHub OSS license * Copyright (c) 2021, MafiaHub. All rights reserved. * * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. * See LICENSE file in the source repository for information regarding licensing. */ #include "instance.h" #include <logging/logger.h> namespace Framework::Integrations::Client { Instance::Instance() { _presence = std::make_unique<External::Discord::Wrapper>(); _renderer = std::make_unique<Graphics::Renderer>(); _worldEngine = std::make_unique<World::Engine>(); } ClientError Instance::Init(InstanceOptions &opts) { _opts = opts; if (opts.usePresence) { if (_presence && opts.discordAppId > 0) { _presence->Init(opts.discordAppId); } } if (opts.useRenderer) { if (_renderer) { _renderer->Init(opts.rendererOptions); } } if (_worldEngine) { _worldEngine->Init(); } PostInit(); Framework::Logging::GetLogger(FRAMEWORK_INNER_INTEGRATIONS)->debug("Initialize success"); _initialized = true; return ClientError::CLIENT_NONE; } ClientError Instance::Shutdown() { PreShutdown(); if (_renderer && _renderer->IsInitialized()) { _renderer->Shutdown(); } if (_presence && _presence->IsInitialized()) { _presence->Shutdown(); } if (_worldEngine) { _worldEngine->Shutdown(); } return ClientError::CLIENT_NONE; } void Instance::Update() { if (_presence && _presence->IsInitialized()) { _presence->Update(); } if (_worldEngine) { _worldEngine->Update(); } PostUpdate(); } void Instance::Render() { if (_renderer && _renderer->IsInitialized()) { _renderer->Update(); } } } // namespace Framework::Integrations::Client
24.780488
97
0.565945
[ "render" ]
0c65f83d9071d4c62a3c14e8a10984a17e025dd7
7,185
cpp
C++
Server/src/commandparser.cpp
radu781/Train-manager
74f41dc7f3a61df56f670956b7d65d89e956ee4d
[ "MIT" ]
null
null
null
Server/src/commandparser.cpp
radu781/Train-manager
74f41dc7f3a61df56f670956b7d65d89e956ee4d
[ "MIT" ]
null
null
null
Server/src/commandparser.cpp
radu781/Train-manager
74f41dc7f3a61df56f670956b7d65d89e956ee4d
[ "MIT" ]
null
null
null
#include "pc.h" #include "communication/commandparser.hpp" #include "commands/arrivals.hpp" #include "commands/departures.hpp" #include "commands/help.hpp" #include "commands/late.hpp" #include "commands/today.hpp" #include "communication/client.hpp" pugi::xml_document CommandParser::doc{}; std::unordered_set<std::string> CommandParser::cityNames; std::unordered_set<std::string> CommandParser::trainNumbers; std::mutex CommandParser::m; Command *CommandParser::sharedCmd = nullptr; const std::unordered_map<std::string, CommandParser::Args> CommandParser::commandRules = { {"today", {2, -1u, CommandTypes::TODAY}}, {"departures", {2, -1u, CommandTypes::DEPARTURES}}, {"arrivals", {2, -1u, CommandTypes::ARRIVALS}}, {"late", {2, -1u, CommandTypes::LATE}}, {"help", {0, 1u, CommandTypes::HELP}}, }; CommandParser::CommandParser(const std::string &str) { if (str == "") return; std::string trimmed = WordOperation::trim(str); char *cstr = new char[trimmed.size() + 1]{}; trimmed.copy(cstr, trimmed.size()); const char *delim = " ,;'?"; char *ptr = strtok(cstr, delim); while (ptr != nullptr) { command.push_back(ptr); ptr = strtok(NULL, delim); } delete[] cstr; } CommandParser::CommandTypes CommandParser::validate() { std::transform(command[0].begin(), command[0].end(), command[0].begin(), tolower); bool foundUndo = std::any_of(command.begin(), command.end(), [](const std::string &str) { return str == "-u"; }); if (foundUndo) { auto it = std::remove(command.begin(), command.end(), "-u"); command.erase(it, command.end()); } if (commandRules.contains(command[0])) { Args pos = commandRules.at(command[0]); if (command.size() - 1 < pos.mandatory) return CommandTypes::NOT_ENOUGH_ARGS; if (pos.optional != -1u && command.size() - 1 > pos.mandatory + pos.optional) return CommandTypes::TOO_MANY_ARGS; if (command.size() - 1 >= pos.mandatory && (pos.optional == -1u || command.size() - 1 <= pos.mandatory + pos.optional)) { if (foundUndo) return (CommandTypes)((unsigned int)pos.type + undoEnumOffset); return pos.type; } } return CommandTypes::NOT_FOUND; } std::string CommandParser::execute(Client *client) { if (command.size() == 0) return ""; try { auto cmd = commandRules.at(command[0]); std::string out; Command *icmd = client->cmd; switch (validate()) { case CommandTypes::NOT_ENOUGH_ARGS: return "Command " + command[0] + " has " + Types::toString<unsigned>(cmd.mandatory) + " mandatory arguments, " + Types::toString<unsigned>(command.size() - 1u) + " provided"; case CommandTypes::TOO_MANY_ARGS: return "Command " + command[0] + " has up to " + Types::toString<unsigned>(cmd.mandatory + cmd.optional) + " arguments, " + Types::toString<unsigned>(command.size() - 1u) + " provided"; case CommandTypes::NOT_FOUND: return "Command " + command[0] + " not found"; case CommandTypes::TODAY: icmd = new Today(CommandParser::sharedCmd, &command); return callToExecute(icmd); case CommandTypes::DEPARTURES: icmd = new Departures(CommandParser::sharedCmd, &command); return callToExecute(icmd); case CommandTypes::ARRIVALS: icmd = new Arrivals(CommandParser::sharedCmd, &command); return callToExecute(icmd); case CommandTypes::LATE: icmd = new Late(CommandParser::sharedCmd, &command); return callToExecute(icmd); case CommandTypes::HELP: icmd = new Help(CommandParser::sharedCmd, &command); return callToExecute(icmd); case CommandTypes::TODAY_UNDO: icmd = new Today(CommandParser::sharedCmd, &command); return callToUndo(icmd); case CommandTypes::DEPARTURES_UNDO: icmd = new Departures(CommandParser::sharedCmd, &command); return callToUndo(icmd); case CommandTypes::ARRIVALS_UNDO: icmd = new Arrivals(CommandParser::sharedCmd, &command); return callToUndo(icmd); case CommandTypes::LATE_UNDO: icmd = new Late(CommandParser::sharedCmd, &command); return callToUndo(icmd); case CommandTypes::HELP_UNDO: icmd = new Help(CommandParser::sharedCmd, &command); return callToUndo(icmd); default: LOG_DEBUG("Unexpected command " + command[0]); return "Try again"; } } catch (const std::out_of_range &e) // caused by the commandRules.at() { return "Command " + command[0] + " not found"; } } std::string CommandParser::callToExecute(Command *cmd) { std::string out = cmd->execute(); delete cmd; return out; } std::string CommandParser::callToUndo(Command *cmd) { std::string out = cmd->undo(); delete cmd; return out; } void CommandParser::getFile() { const std::string localPath = "resources/cfr_2021.xml"; const std::string web = "https://data.gov.ro/dataset/c4f71dbb-de39-49b2-b697-5b60a5f299a2/resource/5af0366b-f9cb-4d6e-991b-e91789fc7d2c/download/sntfc-cfr-cltori-s.a.-1232-trenuri_2021.xml "; const std::string args = "--tries=3 -O " + localPath; if (!std::filesystem::exists(localPath)) { std::scoped_lock<std::mutex> lock(m); LOG_DEBUG("Xml does not exist locally, attempting to download"); if (!std::filesystem::exists("resources/")) std::filesystem::create_directory("resources/"); if (system(("wget " + web + args).c_str()) < 0) LOG_DEBUG("Xml failed to download"); else LOG_DEBUG("Xml downloaded"); } LOG_DEBUG("Loaded xml"); doc.load_file(localPath.c_str()); auto trenuri = doc.child("XmlIf").child("XmlMts").child("Mt").child("Trenuri").children(); std::unordered_set<std::string> tmpCities; for (const auto &tren : trenuri) { auto trasa = tren.child("Trase").child("Trasa").children(); for (const auto &ele : trasa) { tmpCities.insert(ele.attribute(staOrig).as_string()); tmpCities.insert(ele.attribute(staDest).as_string()); } const std::string categ = tren.attribute(CatTren).as_string(); const std::string number = tren.attribute(Numar).as_string(); trainNumbers.insert(categ + number); } for (const auto &ele : tmpCities) cityNames.insert(WordOperation::removeDiacritics(ele)); sharedCmd->init(&doc, &cityNames, &trainNumbers); LOG_DEBUG("Shared data initialized"); }
34.052133
196
0.585943
[ "transform" ]
0c6c5e369513de3afaa1f4da78655204f2e065b3
1,016
cpp
C++
boost_python/test.cpp
naoki009/samples
dac3bbddbd06374c39768cbe17fefd0110fe316f
[ "BSD-2-Clause" ]
null
null
null
boost_python/test.cpp
naoki009/samples
dac3bbddbd06374c39768cbe17fefd0110fe316f
[ "BSD-2-Clause" ]
null
null
null
boost_python/test.cpp
naoki009/samples
dac3bbddbd06374c39768cbe17fefd0110fe316f
[ "BSD-2-Clause" ]
1
2020-08-14T11:44:42.000Z
2020-08-14T11:44:42.000Z
#include <iostream> //#include <boost/python.hpp> #include <boost/python/numpy.hpp> namespace py = boost::python; namespace np = boost::python::numpy; double my_add( double a, double b ) { return a + b; } void show_array( np::ndarray a ) { float *data = (float *) a.get_data(); int ndim = a.get_nd(); int num_data = 1; for( int i = 0; i < ndim; i++ ) { num_data *= a.shape( i ); } for( int i = 0; i < num_data; i++ ) { std::cout << data[i] << ","; } std::cout << std::endl; } void show_list( py::list a ) { py::ssize_t len = py::len( a ); for( int i = 0; i < len; i++ ) { double val = py::extract<double>( a[i] ); std::cout << val << ","; } std::cout << std::endl; } BOOST_PYTHON_MODULE(my_add) { /* following 2 lines needed for python_numpy */ Py_Initialize(); np::initialize(); py::def( "my_add", my_add ); py::def( "show_array", show_array ); py::def( "show_list", show_list ); }
19.169811
51
0.534449
[ "shape" ]
0c6da7277f4d72a261eb1f50be1c312b8638ae67
7,841
cpp
C++
openvino-trt-app/src/yolo_ov.cpp
KaiL4eK/keras_traffic_signs_localization
38d5f9b2a11c5db04850ddba3ae91f18dcb98066
[ "MIT" ]
4
2019-01-03T18:21:39.000Z
2022-01-25T00:24:07.000Z
openvino-trt-app/src/yolo_ov.cpp
KaiL4eK/keras_traffic_signs_localization
38d5f9b2a11c5db04850ddba3ae91f18dcb98066
[ "MIT" ]
1
2020-09-26T00:37:57.000Z
2020-09-26T00:37:57.000Z
openvino-trt-app/src/yolo_ov.cpp
KaiL4eK/keras_traffic_signs_localization
38d5f9b2a11c5db04850ddba3ae91f18dcb98066
[ "MIT" ]
null
null
null
#include "yolo_ov.hpp" using namespace std; #include <ext_list.hpp> namespace ie = InferenceEngine; #include <boost/filesystem.hpp> namespace fs = boost::filesystem; /** * @brief Sets image data stored in cv::Mat object to a given Blob object. * @param orig_image - given cv::Mat object with an image data. * @param blob - Blob object which to be filled by an image data. * @param batchIndex - batch index of an image inside of the blob. */ template <typename T> void matU8ToBlob(const cv::Mat &orig_image, InferenceEngine::Blob::Ptr &blob, int batchIndex = 0) { InferenceEngine::SizeVector blobSize = blob->getTensorDesc().getDims(); const size_t width = blobSize[3]; const size_t height = blobSize[2]; const size_t channels = blobSize[1]; T *blob_data = blob->buffer().as<T *>(); if (static_cast<int>(width) != orig_image.size().width || static_cast<int>(height) != orig_image.size().height) { throw invalid_argument("Invalid size!"); } int batchOffset = batchIndex * width * height * channels; for (size_t c = 0; c < channels; c++) { for (size_t h = 0; h < height; h++) { for (size_t w = 0; w < width; w++) { blob_data[batchOffset + c * width * height + h * width + w] = orig_image.at<cv::Vec3b>(h, w)[c]; } } } } YOLO_OpenVINO::YOLO_OpenVINO(std::string cfg_fpath) : CommonYOLO(cfg_fpath) { } bool YOLO_OpenVINO::init(std::string ir_fpath, std::string device_type) { // cout << ie_core.GetVersions(g_device_type) << endl; cout << "InferenceEngine: " << ie::GetInferenceEngineVersion() << endl; cout << "Loading Inference Engine" << endl; if (device_type == "CPU") { mIeCore.AddExtension(make_shared<ie::Extensions::Cpu::CpuExtensions>(), "CPU"); } string ir_bin_path = fs::path(ir_fpath).replace_extension(".bin").string(); cout << "Loading network files:\n\t" << ir_fpath << "\n\t" << ir_bin_path << endl; ie::CNNNetReader net_reader; net_reader.ReadNetwork(ir_fpath); net_reader.ReadWeights(ir_bin_path); mNetwork = net_reader.getNetwork(); cout << "Preparing input blobs" << endl; ie::InputsDataMap net_inputs_info(mNetwork.getInputsInfo()); ie::InputInfo::Ptr &input_data = net_inputs_info.begin()->second; input_data->setPrecision(ie::Precision::U8); mInputName = net_inputs_info.begin()->first; cout << "Loading to device" << endl; mExecutableNetwork = mIeCore.LoadNetwork(mNetwork, device_type); for ( auto &info : mExecutableNetwork.GetOutputsInfo() ) mOutputNames.push_back(info.first); for ( size_t i = 0; i < mCfg._tile_cnt; i++ ) { ie::InferRequest::Ptr request = mExecutableNetwork.CreateInferRequestPtr(); mInferRequests.push_back(request); } } void YOLO_OpenVINO::infer(cv::Mat raw_image, vector<DetectionObject> &detections) { chrono::time_point<chrono::steady_clock> inf_start_time = chrono::steady_clock::now(); ImageResizeConfig rsz_cfg; initResizeConfig(raw_image, rsz_cfg); vector<cv::Mat> input_frames; for ( size_t i = 0; i < mInferRequests.size(); i++ ) { ie::InferRequest::Ptr &request = mInferRequests[i]; ie::Blob::Ptr input_blob = request->GetBlob(mInputName); cv::Mat inputFrame; rsz_cfg.tile_idx = i; resizeForNetwork(raw_image, inputFrame, rsz_cfg); input_frames.push_back(inputFrame); matU8ToBlob<uint8_t>(inputFrame, input_blob, 0); request->StartAsync(); } vector<RawDetectionObject> global_dets; #define FULL_PROCESSING for ( size_t i = 0; i < mInferRequests.size(); i++ ) { ie::InferRequest::Ptr &request = mInferRequests[i]; request->Wait(ie::IInferRequest::WaitMode::RESULT_READY); #ifdef FULL_PROCESSING for (size_t i_layer = 0; i_layer < mOutputNames.size(); i_layer++) { const ie::Blob::Ptr output_blob = request->GetBlob(mOutputNames[i_layer]); const ie::SizeVector &output_dims = output_blob->getTensorDesc().getDims(); vector<cv::Point> anchors = get_anchors(i_layer); const float grid_w = output_dims[3]; const float grid_h = output_dims[2]; const size_t chnl_count = output_dims[1]; const float *detection = static_cast<ie::PrecisionTrait<ie::Precision::FP32>::value_type *>(output_blob->buffer()); const size_t b_stride = (output_dims[1] * output_dims[2] * output_dims[3]); const size_t c_stride = (output_dims[2] * output_dims[3]); const size_t h_stride = output_dims[3]; size_t c_idx; const size_t class_count = output_dims[1] / anchors.size() - 5; const size_t box_count = class_count + 5; float obj_thresh = mCfg._objectness_thresh; for (size_t b_idx = 0; b_idx < output_dims[0]; b_idx++) { for (size_t h_idx = 0; h_idx < output_dims[2]; h_idx++) { for (size_t w_idx = 0; w_idx < output_dims[3]; w_idx++) { size_t grid_offset = b_idx * b_stride + h_idx * h_stride + w_idx; for (size_t anc_idx = 0; anc_idx < anchors.size(); anc_idx++) { RawDetectionObject det; size_t chnl_offset = anc_idx * box_count; // size_t box_idx_x = 0; // size_t box_idx_y = 1; // size_t box_idx_w = 2; // size_t box_idx_h = 3; // size_t obj_idx = 4; // size_t cls_idx = 5; float obj = detection[grid_offset + c_stride * (4 + chnl_offset)]; obj = sigmoid(obj); if (obj < obj_thresh) continue; det.x = detection[grid_offset + c_stride * (0 + chnl_offset)]; det.y = detection[grid_offset + c_stride * (1 + chnl_offset)]; det.w = detection[grid_offset + c_stride * (2 + chnl_offset)]; det.h = detection[grid_offset + c_stride * (3 + chnl_offset)]; det.w = anchors[anc_idx].x * exp(det.w) / mCfg._infer_sz.width; det.h = anchors[anc_idx].y * exp(det.h) / mCfg._infer_sz.height; det.x = (sigmoid(det.x) + w_idx) / grid_w; det.y = (sigmoid(det.y) + h_idx) / grid_h; for (size_t i_cls = 0; i_cls < class_count; i_cls++) { float class_val = detection[grid_offset + c_stride * ((i_cls + 5) + chnl_offset)]; det.conf = sigmoid(class_val) * obj; if ( det.conf < obj_thresh ) continue; det.cls_idx = i_cls; global_dets.push_back(det); } } } } } } rsz_cfg.tile_idx = i; postprocessBoxes(global_dets, rsz_cfg); #endif //FULL_PROCESSING } filterBoxes(global_dets, detections); chrono::duration<double> inf_elapsed = chrono::steady_clock::now() - inf_start_time; cout << "Inference time: " << chrono::duration_cast<chrono::milliseconds>(inf_elapsed).count() << " [ms]" << endl; }
36.469767
127
0.554521
[ "object", "vector" ]
0c75be4ecf0204ea4b20b7608cfffc135fb2eada
3,324
hpp
C++
tests/unit/coherence/native/BackTraceTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
tests/unit/coherence/native/BackTraceTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
tests/unit/coherence/native/BackTraceTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "cxxtest/TestSuite.h" #include "coherence/lang.ns" using namespace coherence::lang; /** * Test Suite for BackTraceTest * * Tests Bug21155867. The BackTrace * methods are not all thread-safe. * * To reproduce the issue, increase the threads to 20, * and the iterations to 1000. */ class BackTraceTest : public CxxTest::TestSuite { public: /** * Test Dbg thread safety */ void testThreads() { Object::View v = Object::create(); Runnable::Handle hTask = DoExceptions::create(v, 20); s_fStart = false; Thread::Handle ahThreads[THREADS]; String::View vsName; for (int32_t i = 0; i < THREADS; i++) { ahThreads[i] = Thread::create(hTask, COH_TO_STRING(getPREFIX() << i)); String::View str = COH_TO_STRING(getPREFIX() << i); ahThreads[i]->start(); } COH_SYNCHRONIZED (v) { s_fStart = true; v->notifyAll(); } for (int32_t i = 0; i < THREADS; i++) { ahThreads[i]->join(); } } //----- Inner Class DoExceptions class DoExceptions : public class_spec<DoExceptions, extends<Object>, implements<Runnable> > { friend class factory<DoExceptions>; protected: /** * Constructor */ DoExceptions(Object::View v, int32_t nIterations) : f_vMonitor(self(), v), m_nIterations(nIterations) { } // ----- Runnable interface --------------------------------------------- public: void run() { COH_SYNCHRONIZED (f_vMonitor) { while (!s_fStart) { f_vMonitor->wait(); } } for (int i = 0; i < m_nIterations; i++ ) { try { COH_THROW(NullPointerException::create()); } catch (NullPointerException::View /* vNPE */) { } } } // ----- data members --------------------------------------------------- private: FinalView<Object> f_vMonitor; int32_t m_nIterations; }; // ----- class local constants ------------------------------------------- public: static String::View getPREFIX() { return String::create("Thread-"); } // ----- fields and constants ------------------------------------------- public: static const int32_t THREADS = 5; static Volatile<bool> s_fStart; }; Volatile<bool> BackTraceTest::s_fStart(System::common());
25.767442
86
0.420277
[ "object" ]
0c76c31075c6a4c4cf3ef29a2adbc2ba2a5552df
611
cpp
C++
Learn_cpp/for_each/a01_for_each.cpp
bhishanpdl/Tutorial_Cpp
49aabcd2f1cce4a1698cee79d171a2fcbf7574b4
[ "MIT" ]
null
null
null
Learn_cpp/for_each/a01_for_each.cpp
bhishanpdl/Tutorial_Cpp
49aabcd2f1cce4a1698cee79d171a2fcbf7574b4
[ "MIT" ]
null
null
null
Learn_cpp/for_each/a01_for_each.cpp
bhishanpdl/Tutorial_Cpp
49aabcd2f1cce4a1698cee79d171a2fcbf7574b4
[ "MIT" ]
null
null
null
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. * File Name : for_each_eg.cpp * Purpose : * Creation Date : May 26, 2019 Sun * Last Modified : Sun May 26 15:57:14 2019 * Created By : Bhishan Poudel * * For-each syntax for (element_declaration : array) statement; _._._._._._._._._._._._._._._._._._._._._.*/ #include<iostream> #include<vector> using namespace std; int main(int argc, char **argv){ //int fibonacci[] = {0, 1,1,2,3,5,8,13}; // using array vector<int> fibonacci = {0,1,1,2,3,5,8,13}; // using vector for (int number: fibonacci) cout << number*2 << ' '; return 0; }
21.068966
63
0.572831
[ "vector" ]
0c7c0431c96d5ce1901075cc12daf8b033b7f072
13,048
cpp
C++
planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/src/node.cpp
hamlinzheng/AutowareArchitectureProposal.iv
8a1343019aca3a648754fa50e6cab72b98db2df5
[ "Apache-2.0" ]
null
null
null
planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/src/node.cpp
hamlinzheng/AutowareArchitectureProposal.iv
8a1343019aca3a648754fa50e6cab72b98db2df5
[ "Apache-2.0" ]
9
2021-08-09T14:15:58.000Z
2021-08-19T07:56:14.000Z
planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/src/node.cpp
hamlinzheng/AutowareArchitectureProposal.iv
8a1343019aca3a648754fa50e6cab72b98db2df5
[ "Apache-2.0" ]
1
2021-02-09T01:24:13.000Z
2021-02-09T01:24:13.000Z
/* * Copyright 2020 Tier IV, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <behavior_velocity_planner/node.h> #include <pcl_ros/transforms.h> #include <tf2_eigen/tf2_eigen.h> #include <lanelet2_extension/utility/message_conversion.h> #include <utilization/path_utilization.h> // Scene modules #include <scene_module/blind_spot/manager.h> #include <scene_module/crosswalk/manager.h> #include <scene_module/intersection/manager.h> #include <scene_module/stop_line/manager.h> #include <scene_module/traffic_light/manager.h> #include <scene_module/detection_area/manager.h> namespace { template <class T> T getParam(const ros::NodeHandle & nh, const std::string & key, const T & default_value) { T value; nh.param<T>(key, value, default_value); return value; } template <class T> T waitForParam(const ros::NodeHandle & nh, const std::string & key) { T value; ros::Rate rate(1.0); while (ros::ok()) { const auto result = nh.getParam(key, value); if (result) { return value; } ROS_INFO("waiting for parameter `%s` ...", key.c_str()); rate.sleep(); } return {}; } std::shared_ptr<geometry_msgs::TransformStamped> getTransform( const tf2_ros::Buffer & tf_buffer, const std::string & from, const std::string & to, const ros::Time & time = ros::Time(0), const ros::Duration & duration = ros::Duration(0.1)) { try { return std::make_shared<geometry_msgs::TransformStamped>( tf_buffer.lookupTransform(from, to, time, duration)); } catch (tf2::TransformException & ex) { return {}; } } geometry_msgs::TransformStamped waitForTransform( const tf2_ros::Buffer & tf_buffer, const std::string & from, const std::string & to, const ros::Time & time = ros::Time(0), const ros::Duration & duration = ros::Duration(0.1)) { ros::Rate rate(1.0); while (ros::ok()) { const auto transform = getTransform(tf_buffer, from, to, time, duration); if (transform) { return *transform; } ROS_INFO( "waiting for transform from `%s` to `%s` ... (time = %f, now = %f)", from.c_str(), to.c_str(), time.toSec(), ros::Time::now().toSec()); rate.sleep(); } } geometry_msgs::PoseStamped transform2pose(const geometry_msgs::TransformStamped & transform) { geometry_msgs::PoseStamped pose; pose.header = transform.header; pose.pose.position.x = transform.transform.translation.x; pose.pose.position.y = transform.transform.translation.y; pose.pose.position.z = transform.transform.translation.z; pose.pose.orientation = transform.transform.rotation; return pose; } autoware_planning_msgs::Path to_path(const autoware_planning_msgs::PathWithLaneId & path_with_id) { autoware_planning_msgs::Path path; for (const auto & path_point : path_with_id.points) { path.points.push_back(path_point.point); } return path; } } // namespace BehaviorVelocityPlannerNode::BehaviorVelocityPlannerNode() : nh_(), pnh_("~"), tf_listener_(tf_buffer_) { // Trigger Subscriber trigger_sub_path_with_lane_id_ = pnh_.subscribe("input/path_with_lane_id", 1, &BehaviorVelocityPlannerNode::onTrigger, this); // Subscribers sub_dynamic_objects_ = pnh_.subscribe( "input/dynamic_objects", 1, &BehaviorVelocityPlannerNode::onDynamicObjects, this); sub_no_ground_pointcloud_ = pnh_.subscribe( "input/no_ground_pointcloud", 1, &BehaviorVelocityPlannerNode::onNoGroundPointCloud, this); sub_vehicle_velocity_ = pnh_.subscribe( "input/vehicle_velocity", 1, &BehaviorVelocityPlannerNode::onVehicleVelocity, this); sub_lanelet_map_ = pnh_.subscribe("input/vector_map", 10, &BehaviorVelocityPlannerNode::onLaneletMap, this); sub_traffic_light_states_ = pnh_.subscribe( "input/traffic_light_states", 10, &BehaviorVelocityPlannerNode::onTrafficLightStates, this); sub_external_crosswalk_states_ = pnh_.subscribe( "input/external_crosswalk_states", 10, &BehaviorVelocityPlannerNode::onExternalCrosswalkStates, this); sub_external_intersection_states_ = pnh_.subscribe( "input/external_intersection_states", 10, &BehaviorVelocityPlannerNode::onExternalIntersectionStates, this); sub_external_traffic_light_states_ = pnh_.subscribe( "input/external_traffic_light_states", 10, &BehaviorVelocityPlannerNode::onExternalTrafficLightStates, this); // Publishers path_pub_ = pnh_.advertise<autoware_planning_msgs::Path>("output/path", 1); stop_reason_diag_pub_ = pnh_.advertise<diagnostic_msgs::DiagnosticStatus>("output/stop_reason", 1); debug_viz_pub_ = pnh_.advertise<visualization_msgs::MarkerArray>("debug/path", 1); // Parameters pnh_.param("forward_path_length", forward_path_length_, 1000.0); pnh_.param("backward_path_length", backward_path_length_, 5.0); // Vehicle Parameters planner_data_.wheel_base = waitForParam<double>(pnh_, "/vehicle_info/wheel_base"); planner_data_.front_overhang = waitForParam<double>(pnh_, "/vehicle_info/front_overhang"); planner_data_.rear_overhang = waitForParam<double>(pnh_, "/vehicle_info/rear_overhang"); planner_data_.vehicle_width = waitForParam<double>(pnh_, "/vehicle_info/vehicle_width"); planner_data_.vehicle_length = waitForParam<double>(pnh_, "/vehicle_info/vehicle_length"); // Additional Vehicle Parameters pnh_.param( "max_accel", planner_data_.max_stop_acceleration_threshold_, -5.0); // TODO read min_acc in velocity_controller_param.yaml? pnh_.param("delay_response_time", planner_data_.delay_response_time_, 1.3); // TODO(Kenji Miyake): get from additional vehicle_info? planner_data_.base_link2front = planner_data_.front_overhang + planner_data_.wheel_base; // Initialize PlannerManager if (getParam<bool>(pnh_, "launch_stop_line", true)) planner_manager_.launchSceneModule(std::make_shared<StopLineModuleManager>()); if (getParam<bool>(pnh_, "launch_crosswalk", true)) planner_manager_.launchSceneModule(std::make_shared<CrosswalkModuleManager>()); if (getParam<bool>(pnh_, "launch_traffic_light", true)) planner_manager_.launchSceneModule(std::make_shared<TrafficLightModuleManager>()); if (getParam<bool>(pnh_, "launch_intersection", true)) planner_manager_.launchSceneModule(std::make_shared<IntersectionModuleManager>()); if (getParam<bool>(pnh_, "launch_blind_spot", true)) planner_manager_.launchSceneModule(std::make_shared<BlindSpotModuleManager>()); if (getParam<bool>(pnh_, "launch_detection_area", true)) planner_manager_.launchSceneModule(std::make_shared<DetectionAreaModuleManager>()); } geometry_msgs::PoseStamped BehaviorVelocityPlannerNode::getCurrentPose() { return transform2pose(waitForTransform(tf_buffer_, "map", "base_link")); } bool BehaviorVelocityPlannerNode::isDataReady() { const auto & d = planner_data_; // from tf if (d.current_pose.header.frame_id == "") return false; // from callbacks if (!d.current_velocity) return false; if (!d.dynamic_objects) return false; if (!d.no_ground_pointcloud) return false; if (!d.lanelet_map) return false; return true; } void BehaviorVelocityPlannerNode::onDynamicObjects( const autoware_perception_msgs::DynamicObjectArray::ConstPtr & msg) { planner_data_.dynamic_objects = msg; } void BehaviorVelocityPlannerNode::onNoGroundPointCloud( const sensor_msgs::PointCloud2::ConstPtr & msg) { const auto transform = getTransform(tf_buffer_, "map", msg->header.frame_id, msg->header.stamp, ros::Duration(0.1)); if (!transform) { ROS_WARN("no transform found for no_ground_pointcloud"); return; } pcl::PointCloud<pcl::PointXYZ>::Ptr no_ground_pointcloud(new pcl::PointCloud<pcl::PointXYZ>); Eigen::Matrix4f affine = tf2::transformToEigen(transform->transform).matrix().cast<float>(); sensor_msgs::PointCloud2 transformed_msg; pcl_ros::transformPointCloud(affine, *msg, transformed_msg); pcl::fromROSMsg(transformed_msg, *no_ground_pointcloud); planner_data_.no_ground_pointcloud = no_ground_pointcloud; } void BehaviorVelocityPlannerNode::onVehicleVelocity( const geometry_msgs::TwistStamped::ConstPtr & msg) { planner_data_.current_velocity = msg; } void BehaviorVelocityPlannerNode::onLaneletMap(const autoware_lanelet2_msgs::MapBin::ConstPtr & msg) { // Load map planner_data_.lanelet_map = std::make_shared<lanelet::LaneletMap>(); lanelet::utils::conversion::fromBinMsg( *msg, planner_data_.lanelet_map, &planner_data_.traffic_rules, &planner_data_.routing_graph); // Build graph { using lanelet::Locations; using lanelet::Participants; using lanelet::routing::RoutingGraph; using lanelet::routing::RoutingGraphConstPtr; using lanelet::routing::RoutingGraphContainer; using lanelet::traffic_rules::TrafficRulesFactory; const auto traffic_rules = TrafficRulesFactory::create(Locations::Germany, Participants::Vehicle); const auto pedestrian_rules = TrafficRulesFactory::create(Locations::Germany, Participants::Pedestrian); RoutingGraphConstPtr vehicle_graph = RoutingGraph::build(*planner_data_.lanelet_map, *traffic_rules); RoutingGraphConstPtr pedestrian_graph = RoutingGraph::build(*planner_data_.lanelet_map, *pedestrian_rules); RoutingGraphContainer overall_graphs({vehicle_graph, pedestrian_graph}); planner_data_.overall_graphs = std::make_shared<const RoutingGraphContainer>(overall_graphs); } } void BehaviorVelocityPlannerNode::onTrafficLightStates( const autoware_perception_msgs::TrafficLightStateArray::ConstPtr & msg) { for (const auto & state : msg->states) { autoware_perception_msgs::TrafficLightStateStamped traffic_light_state; traffic_light_state.header = msg->header; traffic_light_state.state = state; planner_data_.traffic_light_id_map_[state.id] = traffic_light_state; } } void BehaviorVelocityPlannerNode::onExternalCrosswalkStates( const autoware_api_msgs::CrosswalkStatus::ConstPtr & msg) { planner_data_.external_crosswalk_status_input = *msg; } void BehaviorVelocityPlannerNode::onExternalIntersectionStates( const autoware_api_msgs::IntersectionStatus::ConstPtr & msg) { planner_data_.external_intersection_status_input = *msg; } void BehaviorVelocityPlannerNode::onExternalTrafficLightStates( const autoware_perception_msgs::TrafficLightStateArray::ConstPtr & msg) { for (const auto & state : msg->states) { autoware_perception_msgs::TrafficLightStateStamped traffic_light_state; traffic_light_state.header = msg->header; traffic_light_state.state = state; planner_data_.external_traffic_light_id_map_[state.id] = traffic_light_state; } } void BehaviorVelocityPlannerNode::onTrigger( const autoware_planning_msgs::PathWithLaneId & input_path_msg) { // Check ready planner_data_.current_pose = getCurrentPose(); if (!isDataReady()) { return; } // Plan path velocity const auto velocity_planned_path = planner_manager_.planPathVelocity( std::make_shared<const PlannerData>(planner_data_), input_path_msg); // screening const auto filtered_path = filterLitterPathPoint(to_path(velocity_planned_path)); // interpolation const auto interpolated_path_msg = interpolatePath(filtered_path, forward_path_length_); // check stop point auto output_path_msg = filterStopPathPoint(interpolated_path_msg); output_path_msg.header.frame_id = "map"; output_path_msg.header.stamp = ros::Time::now(); // TODO: This must be updated in each scene module, but copy from input message for now. output_path_msg.drivable_area = input_path_msg.drivable_area; path_pub_.publish(output_path_msg); stop_reason_diag_pub_.publish(planner_manager_.getStopReasonDiag()); publishDebugMarker(output_path_msg, debug_viz_pub_); return; }; void BehaviorVelocityPlannerNode::publishDebugMarker( const autoware_planning_msgs::Path & path, const ros::Publisher & pub) { if (pub.getNumSubscribers() < 1) return; visualization_msgs::MarkerArray output_msg; for (size_t i = 0; i < path.points.size(); ++i) { visualization_msgs::Marker marker; marker.header = path.header; marker.id = i; marker.type = visualization_msgs::Marker::ARROW; marker.pose = path.points.at(i).pose; marker.scale.y = marker.scale.z = 0.05; marker.scale.x = 0.25; marker.action = visualization_msgs::Marker::ADD; marker.lifetime = ros::Duration(0.5); marker.color.a = 0.999; // Don't forget to set the alpha! marker.color.r = 1.0; marker.color.g = 1.0; marker.color.b = 1.0; output_msg.markers.push_back(marker); } pub.publish(output_msg); }
36.75493
113
0.757741
[ "transform" ]
0c7f470a5b19cdeb33df7286d1e9c38a527bb378
31,178
cpp
C++
src/minisef/gcsdk/sqlaccess/recordinfo.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/minisef/gcsdk/sqlaccess/recordinfo.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/minisef/gcsdk/sqlaccess/recordinfo.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //============================================================================= #include "stdafx.h" //#include "sqlaccess.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" namespace GCSDK { // Memory pool for CRecordInfo CThreadSafeClassMemoryPool <CRecordInfo> CRecordInfo::sm_MemPoolRecordInfo(10, UTLMEMORYPOOL_GROW_FAST); #ifdef _DEBUG // validation tracking CUtlRBTree<CRecordInfo *, int > CRecordInfo::sm_mapPMemPoolRecordInfo( DefLessFunc( CRecordInfo *) ); CThreadMutex CRecordInfo::sm_mutexMemPoolRecordInfo; #endif //----------------------------------------------------------------------------- // determine if this fieldset is equal to the other one //----------------------------------------------------------------------------- /* static */ bool FieldSet_t::CompareFieldSets(const FieldSet_t &refThis, CRecordInfo *pRecordInfoThis, const FieldSet_t &refOther, CRecordInfo *pRecordInfoOther) { // same number of columns? int cColumns = refThis.GetCount(); if (refOther.GetCount() != cColumns) return false; int cIncludedColumns = refThis.GetIncludedCount(); if (refOther.GetIncludedCount() != cIncludedColumns) return false; // do the regular columns first; this is order-dependent for (int m = 0; m < cColumns; m++) { int nThisField = refThis.GetField(m); const CColumnInfo &refThisColumn = pRecordInfoThis->GetColumnInfo(nThisField); int nOtherField = refOther.GetField(m); const CColumnInfo &refOtherColumn = pRecordInfoOther->GetColumnInfo(nOtherField); if (refOtherColumn != refThisColumn) { return false; } } // do the included columns now; order independent for (int m = 0; m < cIncludedColumns; m++) { int nThisField = refThis.GetIncludedField(m); const CColumnInfo &refThisColumn = pRecordInfoThis->GetColumnInfo(nThisField); bool bFoundMatch = false; for (int n = 0; n < cIncludedColumns; n++) { int nOtherField = refOther.GetIncludedField(n); const CColumnInfo &refOtherColumn = pRecordInfoOther->GetColumnInfo(nOtherField); if (refOtherColumn == refThisColumn) { bFoundMatch = true; break; } } if (!bFoundMatch) return false; } return true; } //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CRecordInfo::CRecordInfo() : m_MapIColumnInfo(0, 0, CaselessStringLessThan) { m_rgchName[0] = 0; m_bPreparedForUse = false; m_bAllColumnsAdded = false; m_bHaveChecksum = false; m_bHaveColumnNameIndex = false; m_nHasPrimaryKey = k_EPrimaryKeyTypeNone; m_iPKIndex = -1; m_cubFixedSize = 0; m_nChecksum = 0; m_eSchemaCatalog = k_ESchemaCatalogInvalid; m_nTableID = 0; } //----------------------------------------------------------------------------- // Purpose: Initializes this record info from DS equivalent information //----------------------------------------------------------------------------- void CRecordInfo::InitFromDSSchema(CSchema *pSchema) { // copy the name over SetName(pSchema->GetPchName()); // copy each of the fields, preallocating capacity int cFields = pSchema->GetCField(); m_VecColumnInfo.EnsureCapacity(cFields); for (int iField = 0; iField < cFields; iField++) { Field_t &field = pSchema->GetField(iField); AddColumn(field.m_rgchSQLName, iField + 1, field.m_EType, field.m_cubLength, field.m_nColFlags, field.m_cchMaxLength); } m_nTableID = pSchema->GetITable(); // copy the list of PK index fields m_iPKIndex = pSchema->GetPKIndex(); // copy the list of Indexes m_VecIndexes = pSchema->GetIndexes(); // which schema? m_eSchemaCatalog = pSchema->GetESchemaCatalog(); // copy full-text column list // and the index of the catalog it will create on m_vecFTSFields = pSchema->GetFTSColumns(); m_nFullTextCatalogIndex = pSchema->GetFTSIndexCatalog(); // Copy over the FK data int cFKs = pSchema->GetFKCount(); for (int i = 0; i < cFKs; ++i) { FKData_t &fkData = pSchema->GetFKData(i); AddFK(fkData); } // prepare for use PrepareForUse(); } //----------------------------------------------------------------------------- // Purpose: Adds a new column to this record info // Input: pchName - column name // nSQLColumn - column index in SQL to bind to (1-based) // eType - data type of column // cubFixedSize - for fixed-size fields, the size // nColFlags - attributes //----------------------------------------------------------------------------- void CRecordInfo::AddColumn(const char *pchName, int nSQLColumn, EGCSQLType eType, int cubFixedSize, int nColFlags, int cchMaxSize) { Assert(!m_bPreparedForUse); if (m_bPreparedForUse) return; uint32 unColumn = m_VecColumnInfo.AddToTail(); CColumnInfo &columnInfo = m_VecColumnInfo[unColumn]; columnInfo.Set(pchName, nSQLColumn, eType, cubFixedSize, nColFlags, cchMaxSize); } //----------------------------------------------------------------------------- // Purpose: Adds a new FK to this record info //----------------------------------------------------------------------------- void CRecordInfo::AddFK(const FKData_t &fkData) { m_VecFKData.AddToTail(fkData); } //----------------------------------------------------------------------------- // Purpose: compare function to sort by column name //----------------------------------------------------------------------------- int __cdecl CompareColumnInfo(const CColumnInfo *pColumnInfoLeft, const CColumnInfo *pColumnInfoRight) { const char *pchLeft = ((CColumnInfo *) pColumnInfoLeft)->GetName(); const char *pchRight = ((CColumnInfo *) pColumnInfoRight)->GetName(); Assert(pchLeft && pchLeft[0]); Assert(pchRight && pchRight[0]); return Q_stricmp(pchLeft, pchRight); } //----------------------------------------------------------------------------- // Purpose: compares this record info to another record info //----------------------------------------------------------------------------- bool CRecordInfo::EqualTo(CRecordInfo *pOther) { int nOurs = GetChecksum(); int nTheirs = pOther->GetChecksum(); // if this much isn't equal, we're no good if (nOurs != nTheirs) return false; if (!CompareIndexLists(pOther)) return false; if (!CompareFKs(pOther)) return false; return CompareFTSIndexLists(pOther); } //----------------------------------------------------------------------------- // Purpose: format the index list into a string //----------------------------------------------------------------------------- void CRecordInfo::GetIndexFieldList(CFmtStr1024 *pstr, int nIndents) const { // table name at first pstr->sprintf("Table %s:\n", this->GetName()); // for each of the indexes ... for (int n = 0; n < m_VecIndexes.Count(); n++) { const FieldSet_t &fs = m_VecIndexes[n]; // indent enough for (int x = 0; x < nIndents; x++) { pstr->Append("\t"); } // show if it is clustered or not pstr->AppendFormat("Index %d (%s): %sclustered, %sunique {", n, fs.GetIndexName(), fs.IsClustered() ? "" : "non-", fs.IsUnique() ? "" : "non-"); // then show all the columns for (int m = 0; m < fs.GetCount(); m++) { int x = fs.GetField(m); const char *pstrName = m_VecColumnInfo[x].GetName(); pstr->AppendFormat("%s %s", (m == 0) ? "" : ",", pstrName); } // then the included columns, too for (int m = 0; m < fs.GetIncludedCount(); m++) { int x = fs.GetIncludedField(m); const char *pstrName = m_VecColumnInfo[x].GetName(); pstr->AppendFormat(", *%s", pstrName); } pstr->Append(" }\n"); } return; } //----------------------------------------------------------------------------- // Purpose: Get the number of foreign key constraints defined for the table //----------------------------------------------------------------------------- int CRecordInfo::GetFKCount() { return m_VecFKData.Count(); } //----------------------------------------------------------------------------- // Purpose: Get data for a foreign key by index (valid for 0...GetFKCount()-1) //----------------------------------------------------------------------------- FKData_t &CRecordInfo::GetFKData(int iIndex) { return m_VecFKData[iIndex]; } //----------------------------------------------------------------------------- // Purpose: format the FK list into a string //----------------------------------------------------------------------------- void CRecordInfo::GetFKListString(CFmtStr1024 *pstr, int nIndents) { // table name at first pstr->sprintf("Table %s Foreign Keys: \n", this->GetName()); if (m_VecFKData.Count() == 0) { // indent enough pstr->AppendIndent(nIndents); pstr->Append("No foreign keys for table\n"); } else { for (int n = 0; n < m_VecFKData.Count(); n++) { // indent enough pstr->AppendIndent(nIndents); FKData_t &fkData = m_VecFKData[n]; CFmtStr sColumns, sParentColumns; FOR_EACH_VEC(fkData.m_VecColumnRelations, i) { FKColumnRelation_t &colRelation = fkData.m_VecColumnRelations[i]; if (i > 0) { sColumns += ","; sParentColumns += ","; } sColumns += colRelation.m_rgchCol; sParentColumns += colRelation.m_rgchParentCol; } pstr->AppendFormat("CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s(%s) ON DELETE %s ON UPDATE %s\n", fkData.m_rgchName, sColumns.Access(), fkData.m_rgchParentTableName, sParentColumns.Access(), PchNameFromEForeignKeyAction(fkData.m_eOnDeleteAction), PchNameFromEForeignKeyAction(fkData.m_eOnUpdateAction)); } } return; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CRecordInfo::AddFTSFields(CUtlVector<int> &vecFields) { AssertMsg(m_vecFTSFields.Count() == 0, "Only one FTS index per table"); FOR_EACH_VEC(vecFields, n) { int nField = vecFields[n]; m_vecFTSFields.AddToTail(nField); } return; } //----------------------------------------------------------------------------- // Purpose: compares FK lists in this record with those of another //----------------------------------------------------------------------------- bool CRecordInfo::CompareFKs(CRecordInfo *pOther) { if (pOther->m_VecFKData.Count() != m_VecFKData.Count()) return false; for (int i = 0; i < m_VecFKData.Count(); ++i) { FKData_t &fkDataMine = m_VecFKData[i]; bool bFoundInOther = false; for (int j = 0; j < pOther->m_VecFKData.Count(); ++j) { FKData_t &fkDataOther = pOther->m_VecFKData[j]; if (fkDataMine == fkDataOther) { bFoundInOther = true; break; } } if (!bFoundInOther) return false; } return true; } //----------------------------------------------------------------------------- // Purpose: Locate an index by its properties (ignoring the name). // Returns position of index in the index array, or -1 if not found. //----------------------------------------------------------------------------- int CRecordInfo::FindIndex(CRecordInfo *pRec, const FieldSet_t &fieldSet) { for (int i = 0; i < m_VecIndexes.Count(); i++) { if (FieldSet_t::CompareFieldSets(m_VecIndexes[i], this, fieldSet, pRec)) return i; } // Not found return -1; } //----------------------------------------------------------------------------- // Purpose: Locate an index with the given name. // Returns position of index in the index array, or -1 if not found. //----------------------------------------------------------------------------- int CRecordInfo::FindIndexByName(const char *pszName) const { for (int i = 0; i < m_VecIndexes.Count(); i++) { if (V_stricmp(m_VecIndexes[i].GetIndexName(), pszName) == 0) return i; } // Not found return -1; } //----------------------------------------------------------------------------- // Purpose: compares index lists in this record with those of another //----------------------------------------------------------------------------- bool CRecordInfo::CompareIndexLists(CRecordInfo *pOther) { // compare the index lists (but don't use CRCs) // different size? can't be the same if (pOther->GetIndexFieldCount() != GetIndexFieldCount()) { return false; } // We have to loop through both lists of indexes and try to find a match. // We also must make sure the match is exact, and that no previous match // can alias another attempt at a match. Pretty messy, but with no available // identity over index objects, we're forced to a suboptimal solution. int nIndexes = GetIndexFieldCount(); // get a copy of the other index vector, which we'll remove items from as // matches are found. CUtlVector <FieldSet_t> vecOtherIndexes; vecOtherIndexes.CopyArray(pOther->GetIndexFields().Base(), nIndexes); for (int nOurs = 0; nOurs < nIndexes; nOurs++) { int nOtherMatchIndex = -1; const FieldSet_t &refOurs = GetIndexFields()[nOurs]; // rip through copy of other to find one that matches for (int nOther = 0; nOther < vecOtherIndexes.Count(); nOther++) { const FieldSet_t &refOther = vecOtherIndexes[nOther]; if (FieldSet_t::CompareFieldSets(refOurs, this, refOther, pOther)) { nOtherMatchIndex = nOther; break; } } if (nOtherMatchIndex >= 0) { // this works! remove it from other copy vecOtherIndexes.Remove(nOtherMatchIndex); } else { // something didn't match, so bail out early return false; } } return true; } //----------------------------------------------------------------------------- // Purpose: compares full-text indexes for this record with those of another // column order in an FTS is irrelevant, so this is a simple match //----------------------------------------------------------------------------- bool CRecordInfo::CompareFTSIndexLists(CRecordInfo *pOther) const { // compare full-text index columns if (m_vecFTSFields.Count() != pOther->m_vecFTSFields.Count()) { // counts don't match, so obviously no good return false; } for (int nColumnIndex = 0; nColumnIndex < m_vecFTSFields.Count(); nColumnIndex++) { bool bFound = false; for (int nInnerIndex = 0; nInnerIndex < pOther->m_vecFTSFields.Count(); nInnerIndex++) { if (m_vecFTSFields[nInnerIndex] == pOther->m_vecFTSFields[nColumnIndex]) { bFound = true; break; } } if (!bFound) return false; } return true; } //----------------------------------------------------------------------------- // Purpose: Returns the checksum for this record info //----------------------------------------------------------------------------- int CRecordInfo::GetChecksum() { Assert(m_bPreparedForUse); // calculate it now if we haven't already if (!m_bHaveChecksum) CalculateChecksum(); return m_nChecksum; } //----------------------------------------------------------------------------- // Purpose: Prepares this object for use after all columns have been added //----------------------------------------------------------------------------- void CRecordInfo::PrepareForUse() { Assert(!m_bPreparedForUse); Assert(0 == m_cubFixedSize); Assert(0 == m_nChecksum); SetAllColumnsAdded(); FOR_EACH_VEC(m_VecColumnInfo, nColumn) { CColumnInfo &columnInfo = m_VecColumnInfo[nColumn]; // keep track of total fixed size of all columns if (!columnInfo.BIsVariableLength()) m_cubFixedSize += columnInfo.GetFixedSize(); if (columnInfo.BIsPrimaryKey()) { // a PK column! if we have seen one before, // know we have a-column PK; otherwise, a single column PK if (m_nHasPrimaryKey == k_EPrimaryKeyTypeNone) m_nHasPrimaryKey = k_EPrimaryKeyTypeSingle; else m_nHasPrimaryKey = k_EPrimaryKeyTypeMulti; } } // make sure count matches the enum /* Assert( ( m_nHasPrimaryKey == k_EPrimaryKeyTypeNone && m_VecPKFields.Count() == 0 ) || ( m_nHasPrimaryKey == k_EPrimaryKeyTypeMulti && m_VecPKFields.Count() > 1) || ( m_nHasPrimaryKey == k_EPrimaryKeyTypeSingle && m_VecPKFields.Count() == 1) ); */ m_bPreparedForUse = true; } //----------------------------------------------------------------------------- // Purpose: Returns index of column with specified name // Input: pchName - column name // punColumn - pointer to fill in with index // Output: return true if found, false otherwise //----------------------------------------------------------------------------- bool CRecordInfo::BFindColumnByName(const char *pchName, int *punColumn) { Assert(m_bAllColumnsAdded); Assert(pchName && *pchName); Assert(punColumn); *punColumn = -1; // if we haven't already built the name index, build it now if (!m_bHaveColumnNameIndex) BuildColumnNameIndex(); *punColumn = m_MapIColumnInfo.Find(pchName); return (m_MapIColumnInfo.InvalidIndex() != *punColumn); } //----------------------------------------------------------------------------- // Purpose: Sets the name of this record info // Input: pchName - name // Notes: record info that describes a table will have a name (the table name); // record info that describes a result set will not //----------------------------------------------------------------------------- void CRecordInfo::SetName(const char *pchName) { Assert(pchName && *pchName); Assert(!m_bPreparedForUse); // don't change this after prepared for use Q_strncpy(m_rgchName, pchName, Q_ARRAYSIZE(m_rgchName)); } //----------------------------------------------------------------------------- // Purpose: Builds the column name index for fast lookup by name //----------------------------------------------------------------------------- void CRecordInfo::BuildColumnNameIndex() { AUTO_LOCK(m_Mutex); if (m_bHaveColumnNameIndex) return; Assert(m_bAllColumnsAdded); Assert(0 == m_MapIColumnInfo.Count()); FOR_EACH_VEC(m_VecColumnInfo, nColumn) { // build name->column index map CColumnInfo &columnInfo = m_VecColumnInfo[nColumn]; m_MapIColumnInfo.Insert(columnInfo.GetName(), nColumn); } m_bHaveColumnNameIndex = true; } //----------------------------------------------------------------------------- // Purpose: Calculates the checksum for this record info //----------------------------------------------------------------------------- void CRecordInfo::CalculateChecksum() { AUTO_LOCK(m_Mutex); if (m_bHaveChecksum) return; // build the column name index if necessary if (!m_bHaveColumnNameIndex) BuildColumnNameIndex(); CRC32_t crc32; CRC32_Init(&crc32); FOR_EACH_MAP(m_MapIColumnInfo, iMapItem) { uint32 unColumn = m_MapIColumnInfo[iMapItem]; CColumnInfo &columnInfo = m_VecColumnInfo[unColumn]; // calculate checksum of all of our columns columnInfo.CalculateChecksum(); int nChecksum = columnInfo.GetChecksum(); CRC32_ProcessBuffer(&crc32, (void *) &nChecksum, sizeof(nChecksum)); } // keep checksum for entire record info CRC32_Final(&crc32); m_nChecksum = crc32; m_bHaveChecksum = true; } //----------------------------------------------------------------------------- // Purpose: add another index disallowing duplicates. If a duplicate item is // found, we'll set the flags on the new item from the existing one. //----------------------------------------------------------------------------- int CRecordInfo::AddIndex(const FieldSet_t &fieldSet) { for (int n = 0; n < m_VecIndexes.Count(); n++) { FieldSet_t &fs = m_VecIndexes[n]; if (FieldSet_t::CompareFieldSets(fieldSet, this, fs, this)) { fs.SetClustered(fs.IsClustered()); return -1; } } int nRet = m_VecIndexes.AddToTail(fieldSet); return nRet; } //----------------------------------------------------------------------------- // Purpose: Returns true if there is an IDENTITY column in the record info //----------------------------------------------------------------------------- bool CRecordInfo::BHasIdentity() const { FOR_EACH_VEC(m_VecColumnInfo, nColumn) { if (m_VecColumnInfo[nColumn].BIsAutoIncrement()) return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CColumnInfo::CColumnInfo() { m_rgchName[0] = 0; m_nSQLColumn = 0; m_eType = k_EGCSQLTypeInvalid; m_nColFlags = 0; m_cubFixedSize = 0; m_cchMaxSize = 0; m_nChecksum = 0; m_bHaveChecksum = false; } //----------------------------------------------------------------------------- // Purpose: Sets column info for this column // Input: pchName - column name // nSQLColumn - column index in SQL to bind to (1-based) // eType - data type of column // cubFixedSize - for fixed-size fields, the size // nColFlags - attributes //----------------------------------------------------------------------------- void CColumnInfo::Set(const char *pchName, int nSQLColumn, EGCSQLType eType, int cubFixedSize, int nColFlags, int cchMaxSize) { Assert(!m_rgchName[0]); Q_strncpy(m_rgchName, pchName, Q_ARRAYSIZE(m_rgchName)); m_nSQLColumn = nSQLColumn; m_eType = eType; m_nColFlags = nColFlags; ValidateColFlags(); if (!BIsVariableLength()) { Assert(cubFixedSize > 0); m_cubFixedSize = cubFixedSize; m_cchMaxSize = 0; } else { // it's variable length, so we need a max length m_cchMaxSize = cchMaxSize; m_cubFixedSize = 0; } } //----------------------------------------------------------------------------- // Purpose: returns whether this column is variable length //----------------------------------------------------------------------------- bool CColumnInfo::BIsVariableLength() const { return m_eType == k_EGCSQLType_Blob || m_eType == k_EGCSQLType_String || m_eType == k_EGCSQLType_Image; } //----------------------------------------------------------------------------- // Purpose: convert column flags to a visible representation //----------------------------------------------------------------------------- void CColumnInfo::GetColFlagDescription(char *pstrOut, int cubOutLength) const { if (m_nColFlags == 0) Q_strncpy(pstrOut, "(none)", cubOutLength); else { pstrOut[0] = 0; if (m_nColFlags & k_nColFlagIndexed) Q_strncat(pstrOut, "(Indexed)", cubOutLength); if (m_nColFlags & k_nColFlagUnique) Q_strncat(pstrOut, "(Unique)", cubOutLength); if (m_nColFlags & k_nColFlagPrimaryKey) Q_strncat(pstrOut, "(PrimaryKey)", cubOutLength); if (m_nColFlags & k_nColFlagAutoIncrement) Q_strncat(pstrOut, "(AutoIncrement)", cubOutLength); if (m_nColFlags & k_nColFlagClustered) Q_strncat(pstrOut, "(Clustered)", cubOutLength); } return; } //----------------------------------------------------------------------------- // Purpose: sets column flag bits // Input: nColFlag - bits to set. (Other bits are not cleared.) //----------------------------------------------------------------------------- void CColumnInfo::SetColFlagBits(int nColFlag) { ValidateColFlags(); m_nColFlags |= nColFlag; // set these bits ValidateColFlags(); } //----------------------------------------------------------------------------- // Purpose: Calculates the checksum for this column //----------------------------------------------------------------------------- void CColumnInfo::CalculateChecksum() { if (m_bHaveChecksum) return; // calculate checksum of this column for easy comparsion CRC32_t crc32; CRC32_Init(&crc32); CRC32_ProcessBuffer(&crc32, (void *) m_rgchName, Q_strlen(m_rgchName)); CRC32_ProcessBuffer(&crc32, (void *) &m_nColFlags, sizeof(m_nColFlags)); CRC32_ProcessBuffer(&crc32, (void *) &m_eType, sizeof(m_eType)); CRC32_ProcessBuffer(&crc32, (void *) &m_cubFixedSize, sizeof(m_cubFixedSize)); CRC32_ProcessBuffer(&crc32, (void *) &m_cchMaxSize, sizeof(m_cchMaxSize)); CRC32_Final(&crc32); m_nChecksum = crc32; m_bHaveChecksum = true; } //----------------------------------------------------------------------------- // determine if this CColumnInfo is the same as the referenced //----------------------------------------------------------------------------- bool CColumnInfo::operator==(const CColumnInfo &refOther) const { if (m_eType != refOther.m_eType) return false; if (m_cubFixedSize != refOther.m_cubFixedSize) return false; if (m_cchMaxSize != refOther.m_cchMaxSize) return false; if (m_nColFlags != refOther.m_nColFlags) return false; if (0 != Q_strcmp(m_rgchName, refOther.m_rgchName)) return false; return true; } //----------------------------------------------------------------------------- // Purpose: Validates that column flags are set in valid combinations //----------------------------------------------------------------------------- void CColumnInfo::ValidateColFlags() const { // Check that column flags follow rules about how columns get expressed in SQL if (m_nColFlags & k_nColFlagPrimaryKey) { // a primary key must also be unique and indexed Assert(m_nColFlags & k_nColFlagUnique); Assert(m_nColFlags & k_nColFlagIndexed); } // a column with uniqueness constraint must also be indexed if (m_nColFlags & k_nColFlagUnique) Assert(m_nColFlags & k_nColFlagIndexed); } CRecordInfo *CRecordInfo::Alloc() { CRecordInfo *pRecordInfo = sm_MemPoolRecordInfo.Alloc(); #ifdef _DEBUG AUTO_LOCK( sm_mutexMemPoolRecordInfo ); sm_mapPMemPoolRecordInfo.Insert( pRecordInfo ); #endif return pRecordInfo; } void CRecordInfo::DestroyThis() { #ifdef _DEBUG AUTO_LOCK( sm_mutexMemPoolRecordInfo ); sm_mapPMemPoolRecordInfo.Remove( this ); #endif sm_MemPoolRecordInfo.Free(this); } #ifdef DBGFLAG_VALIDATE void CRecordInfo::ValidateStatics( CValidator &validator, const char *pchName ) { VALIDATE_SCOPE_STATIC( "CRecordInfo class statics" ); ValidateObj( sm_MemPoolRecordInfo ); #ifdef _DEBUG AUTO_LOCK( sm_mutexMemPoolRecordInfo ); ValidateObj( sm_mapPMemPoolRecordInfo ); FOR_EACH_MAP_FAST( sm_mapPMemPoolRecordInfo, i ) { sm_mapPMemPoolRecordInfo[i]->Validate( validator, "sm_mapPMemPoolRecordInfo[i]" ); } #endif } void CRecordInfo::Validate( CValidator &validator, const char *pchName ) { VALIDATE_SCOPE(); m_VecIndexes.Validate( validator, "m_VecIndexes" ); ValidateObj( m_VecFKData ); FOR_EACH_VEC( m_VecFKData, i ) { ValidateObj( m_VecFKData[i] ); } for ( int iIndex = 0; iIndex < m_VecIndexes.Count(); iIndex++ ) { ValidateObj( m_VecIndexes[iIndex] ); } ValidateObj( m_vecFTSFields ); ValidateObj( m_VecColumnInfo ); FOR_EACH_VEC( m_VecColumnInfo, nColumn ) { CColumnInfo &columnInfo = GetColumnInfo( nColumn ); ValidateObj( columnInfo ); } ValidateObj( m_MapIColumnInfo ); } void CColumnInfo::Validate( CValidator &validator, const char *pchName ) { VALIDATE_SCOPE(); } #endif // DBGFLAG_VALIDATE } // namespace GCSDK
37.072533
119
0.491725
[ "object", "vector" ]
0c8091c70d1fb5a854a7b52db3bdbfee766b3280
18,822
hpp
C++
example/multi_fem/Nonlinear.hpp
ORNL-CEES/kokkos
70d113838b7dade09218a46c1e8aae44b6dbd321
[ "BSD-3-Clause" ]
1
2019-10-15T19:26:22.000Z
2019-10-15T19:26:22.000Z
example/multi_fem/Nonlinear.hpp
ORNL-CEES/kokkos
70d113838b7dade09218a46c1e8aae44b6dbd321
[ "BSD-3-Clause" ]
16
2019-04-15T20:52:05.000Z
2020-01-24T05:13:25.000Z
example/multi_fem/Nonlinear.hpp
ORNL-CEES/kokkos
70d113838b7dade09218a46c1e8aae44b6dbd321
[ "BSD-3-Clause" ]
1
2019-11-25T14:06:26.000Z
2019-11-25T14:06:26.000Z
/* //@HEADER // ************************************************************************ // // Kokkos v. 2.0 // Copyright (2014) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER */ #ifndef HYBRIDFEM_NONLINEAR_HPP #define HYBRIDFEM_NONLINEAR_HPP #include <utility> #include <iostream> #include <iomanip> #include <Kokkos_Core.hpp> #include <SparseLinearSystem.hpp> #include <SparseLinearSystemFill.hpp> #include <NonlinearFunctors.hpp> #include <FEMesh.hpp> #include <HexElement.hpp> //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- namespace HybridFEM { namespace Nonlinear { struct PerformanceData { double mesh_time; double graph_time; double elem_time; double matrix_gather_fill_time; double matrix_boundary_condition_time; double cg_iteration_time; size_t cg_iteration_count; size_t newton_iteration_count; double error_max; PerformanceData() : mesh_time(0), graph_time(0), elem_time(0), matrix_gather_fill_time(0), matrix_boundary_condition_time(0), cg_iteration_time(0), cg_iteration_count(0), newton_iteration_count(0), error_max(0) {} void best(const PerformanceData& rhs) { mesh_time = std::min(mesh_time, rhs.mesh_time); graph_time = std::min(graph_time, rhs.graph_time); elem_time = std::min(elem_time, rhs.elem_time); matrix_gather_fill_time = std::min(matrix_gather_fill_time, rhs.matrix_gather_fill_time); matrix_boundary_condition_time = std::min( matrix_boundary_condition_time, rhs.matrix_boundary_condition_time); cg_iteration_time = std::min(cg_iteration_time, rhs.cg_iteration_time); cg_iteration_count = std::min(cg_iteration_count, rhs.cg_iteration_count); newton_iteration_count = std::min(newton_iteration_count, rhs.newton_iteration_count); error_max = std::min(error_max, rhs.error_max); } }; //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- class ManufacturedSolution { public: // Manufactured solution for one dimensional nonlinear PDE // // -K T_zz + T^2 = 0 ; T(zmin) = T_zmin ; T(zmax) = T_zmax // // Has an analytic solution of the form: // // T(z) = ( a ( z - zmin ) + b )^(-2) where K = 1 / ( 6 a^2 ) // // Given T_0 and T_L compute K for this analytic solution. // // Two analytic solutions: // // Solution with singularity: // , a( ( 1.0 / sqrt(T_zmax) + 1.0 / sqrt(T_zmin) ) / ( zmax - zmin ) ) // , b( -1.0 / sqrt(T_zmin) ) // // Solution without singularity: // , a( ( 1.0 / sqrt(T_zmax) - 1.0 / sqrt(T_zmin) ) / ( zmax - zmin ) ) // , b( 1.0 / sqrt(T_zmin) ) const double zmin; const double zmax; const double T_zmin; const double T_zmax; const double a; const double b; const double K; ManufacturedSolution(const double arg_zmin, const double arg_zmax, const double arg_T_zmin, const double arg_T_zmax) : zmin(arg_zmin), zmax(arg_zmax), T_zmin(arg_T_zmin), T_zmax(arg_T_zmax), a((1.0 / std::sqrt(T_zmax) - 1.0 / std::sqrt(T_zmin)) / (zmax - zmin)), b(1.0 / std::sqrt(T_zmin)), K(1.0 / (6.0 * a * a)) {} double operator()(const double z) const { const double tmp = a * (z - zmin) + b; return 1.0 / (tmp * tmp); } }; //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- template <typename Scalar, class FixtureType> PerformanceData run(const typename FixtureType::FEMeshType& mesh, const int, // global_max_x , const int, // global_max_y , const int global_max_z, const bool print_error) { typedef Scalar scalar_type; typedef FixtureType fixture_type; typedef typename fixture_type::execution_space execution_space; // typedef typename execution_space::size_type size_type ; // unused typedef typename fixture_type::FEMeshType mesh_type; typedef typename fixture_type::coordinate_scalar_type coordinate_scalar_type; enum { ElementNodeCount = fixture_type::element_node_count }; const comm::Machine machine = mesh.parallel_data_map.machine; const size_t element_count = mesh.elem_node_ids.dimension_0(); //------------------------------------ // The amount of nonlinearity is proportional to the ratio // between T(zmax) and T(zmin). For the manufactured solution // 0 < T(zmin) and 0 < T(zmax) const ManufacturedSolution exact_solution(/* zmin */ 0, /* zmax */ global_max_z, /* T(zmin) */ 1, /* T(zmax) */ 20); //----------------------------------- // Convergence Criteria and perf data: const size_t cg_iteration_limit = 200; const double cg_tolerance = 1e-14; const size_t newton_iteration_limit = 150; const double newton_tolerance = 1e-14; size_t cg_iteration_count_total = 0; double cg_iteration_time = 0; size_t newton_iteration_count = 0; double residual_norm_init = 0; double residual_norm = 0; PerformanceData perf_data; //------------------------------------ // Sparse linear system types: typedef Kokkos::View<scalar_type*, execution_space> vector_type; typedef Kokkos::CrsMatrix<scalar_type, execution_space> matrix_type; typedef typename matrix_type::graph_type matrix_graph_type; typedef typename matrix_type::coefficients_type matrix_coefficients_type; typedef GraphFactory<matrix_graph_type, mesh_type> graph_factory; //------------------------------------ // Problem setup types: typedef ElementComputation<mesh_type, scalar_type> ElementFunctor; typedef DirichletSolution<mesh_type, scalar_type> DirichletSolutionFunctor; typedef DirichletResidual<mesh_type, scalar_type> DirichletResidualFunctor; typedef typename ElementFunctor::elem_matrices_type elem_matrices_type; typedef typename ElementFunctor::elem_vectors_type elem_vectors_type; typedef GatherFill<matrix_type, mesh_type, elem_matrices_type, elem_vectors_type> GatherFillFunctor; //------------------------------------ matrix_type jacobian; vector_type residual; vector_type delta; vector_type nodal_solution; typename graph_factory::element_map_type element_map; //------------------------------------ // Generate mesh and corresponding sparse matrix graph Kokkos::Timer wall_clock; //------------------------------------ // Generate sparse matrix graph and element->graph map. wall_clock.reset(); graph_factory::create(mesh, jacobian.graph, element_map); execution_space().fence(); perf_data.graph_time = comm::max(machine, wall_clock.seconds()); //------------------------------------ // Allocate linear system coefficients and rhs: const size_t local_owned_length = jacobian.graph.row_map.dimension_0() - 1; const size_t local_total_length = mesh.node_coords.dimension_0(); jacobian.coefficients = matrix_coefficients_type( "jacobian_coeff", jacobian.graph.entries.dimension_0()); // Nonlinear residual for owned nodes: residual = vector_type("residual", local_owned_length); // Nonlinear solution for owned and ghosted nodes: nodal_solution = vector_type("solution", local_total_length); // Nonlinear solution update for owned nodes: delta = vector_type("delta", local_owned_length); //------------------------------------ // Allocation of arrays to fill the linear system elem_matrices_type elem_matrices; // Jacobian matrices elem_vectors_type elem_vectors; // Residual vectors if (element_count) { elem_matrices = elem_matrices_type(std::string("elem_matrices"), element_count); elem_vectors = elem_vectors_type(std::string("elem_vectors"), element_count); } //------------------------------------ // For boundary condition set the correct values in the solution vector // The 'zmin' face is assigned to 'T_zmin'. // The 'zmax' face is assigned to 'T_zmax'. // The resulting solution is one dimensional along the 'Z' axis. DirichletSolutionFunctor::apply(nodal_solution, mesh, exact_solution.zmin, exact_solution.zmax, exact_solution.T_zmin, exact_solution.T_zmax); for (;;) { // Nonlinear loop #if defined(KOKKOS_ENABLE_MPI) { //------------------------------------ // Import off-processor nodal solution values // for residual and jacobian computations Kokkos::AsyncExchange<typename vector_type::value_type, execution_space, Kokkos::ParallelDataMap> exchange(mesh.parallel_data_map, 1); Kokkos::PackArray<vector_type>::pack( exchange.buffer(), mesh.parallel_data_map.count_interior, mesh.parallel_data_map.count_send, nodal_solution); exchange.setup(); exchange.send_receive(); Kokkos::UnpackArray<vector_type>::unpack( nodal_solution, exchange.buffer(), mesh.parallel_data_map.count_owned, mesh.parallel_data_map.count_receive); } #endif //------------------------------------ // Compute element matrices and vectors: wall_clock.reset(); ElementFunctor(mesh, elem_matrices, elem_vectors, nodal_solution, exact_solution.K); execution_space().fence(); perf_data.elem_time += comm::max(machine, wall_clock.seconds()); //------------------------------------ // Fill linear system coefficients: wall_clock.reset(); fill(jacobian.coefficients.dimension_0(), 0, jacobian.coefficients); fill(residual.dimension_0(), 0, residual); GatherFillFunctor::apply(jacobian, residual, mesh, element_map, elem_matrices, elem_vectors); execution_space().fence(); perf_data.matrix_gather_fill_time += comm::max(machine, wall_clock.seconds()); // Apply boundary conditions: wall_clock.reset(); // Updates jacobian matrix to 1 on the diagonal, zero elsewhere, // and 0 in the residual due to the solution vector having the correct value DirichletResidualFunctor::apply(jacobian, residual, mesh, exact_solution.zmin, exact_solution.zmax); execution_space().fence(); perf_data.matrix_boundary_condition_time += comm::max(machine, wall_clock.seconds()); //------------------------------------ // Has the residual converged? residual_norm = norm2(mesh.parallel_data_map.count_owned, residual, mesh.parallel_data_map.machine); if (0 == newton_iteration_count) { residual_norm_init = residual_norm; } if (residual_norm / residual_norm_init < newton_tolerance) { break; } //------------------------------------ // Solve linear sytem size_t cg_iteration_count = 0; double cg_residual_norm = 0; cgsolve(mesh.parallel_data_map, jacobian, residual, delta, cg_iteration_count, cg_residual_norm, cg_iteration_time, cg_iteration_limit, cg_tolerance); perf_data.cg_iteration_time += cg_iteration_time; cg_iteration_count_total += cg_iteration_count; // Update non-linear solution with delta... // delta is : - Dx = [Jacobian]^1 * Residual which is the negative update // LaTeX: // \vec {x}_{n+1} = \vec {x}_{n} - ( - \Delta \vec{x}_{n} ) // text: // x[n+1] = x[n] + Dx axpy(mesh.parallel_data_map.count_owned, -1.0, delta, nodal_solution); ++newton_iteration_count; if (newton_iteration_limit < newton_iteration_count) { break; } }; if (newton_iteration_count) { perf_data.elem_time /= newton_iteration_count; perf_data.matrix_gather_fill_time /= newton_iteration_count; perf_data.matrix_boundary_condition_time /= newton_iteration_count; } if (cg_iteration_count_total) { perf_data.cg_iteration_time /= cg_iteration_count_total; } perf_data.newton_iteration_count = newton_iteration_count; perf_data.cg_iteration_count = cg_iteration_count_total; //------------------------------------ { // For extracting the nodal solution and its coordinates: typename mesh_type::node_coords_type::HostMirror node_coords_host = Kokkos::create_mirror(mesh.node_coords); typename vector_type::HostMirror nodal_solution_host = Kokkos::create_mirror(nodal_solution); Kokkos::deep_copy(node_coords_host, mesh.node_coords); Kokkos::deep_copy(nodal_solution_host, nodal_solution); double tmp = 0; for (size_t i = 0; i < mesh.parallel_data_map.count_owned; ++i) { const coordinate_scalar_type x = node_coords_host(i, 0); const coordinate_scalar_type y = node_coords_host(i, 1); const coordinate_scalar_type z = node_coords_host(i, 2); const double Tx = exact_solution(z); const double Ts = nodal_solution_host(i); const double Te = std::abs(Tx - Ts) / std::abs(Tx); tmp = std::max(tmp, Te); if (print_error && 0.02 < Te) { std::cout << " node( " << x << " " << y << " " << z << " ) = " << Ts << " != exact_solution " << Tx << std::endl; } } perf_data.error_max = comm::max(machine, tmp); } return perf_data; } //---------------------------------------------------------------------------- template <typename Scalar, class Device, class FixtureElement> void driver(const char* const label, comm::Machine machine, const int gang_count, const int elem_count_beg, const int elem_count_end, const int runs) { typedef Scalar scalar_type; typedef Device execution_space; typedef double coordinate_scalar_type; typedef FixtureElement fixture_element_type; typedef BoxMeshFixture<coordinate_scalar_type, execution_space, fixture_element_type> fixture_type; typedef typename fixture_type::FEMeshType mesh_type; const size_t proc_count = comm::size(machine); const size_t proc_rank = comm::rank(machine); if (elem_count_beg == 0 || elem_count_end == 0 || runs == 0) return; if (comm::rank(machine) == 0) { std::cout << std::endl; std::cout << "\"Kokkos::HybridFE::Nonlinear " << label << "\"" << std::endl; std::cout << "\"Size\" , \"Size\" , \"Graphing\" , \"Element\" , " "\"Fill\" , \"Boundary\" , \"CG-Iter\" , \"CG-Iter\" , " " \"Newton-Iter\" , \"Max-node-error\"" << std::endl << "\"elems\" , \"nodes\" , \"millisec\" , \"millisec\" , " "\"millisec\" , \"millisec\" , \"millisec\" , \"total-count\" " ", \"total-count\" , \"ratio\"" << std::endl; } const bool print_sample = 0; const double x_curve = 1.0; const double y_curve = 1.0; const double z_curve = 0.8; for (int i = elem_count_beg; i < elem_count_end; i *= 2) { const int ix = std::max(1, (int)cbrt(((double)i) / 2.0)); const int iy = 1 + ix; const int iz = 2 * iy; const int global_elem_count = ix * iy * iz; const int global_node_count = (2 * ix + 1) * (2 * iy + 1) * (2 * iz + 1); mesh_type mesh = fixture_type::create(proc_count, proc_rank, gang_count, ix, iy, iz, x_curve, y_curve, z_curve); mesh.parallel_data_map.machine = machine; PerformanceData perf_data, perf_best; for (int j = 0; j < runs; j++) { perf_data = run<scalar_type, fixture_type>(mesh, ix, iy, iz, print_sample); if (j == 0) { perf_best = perf_data; } else { perf_best.best(perf_data); } } if (comm::rank(machine) == 0) { std::cout << std::setw(8) << global_elem_count << " , " << std::setw(8) << global_node_count << " , " << std::setw(10) << perf_best.graph_time * 1000 << " , " << std::setw(10) << perf_best.elem_time * 1000 << " , " << std::setw(10) << perf_best.matrix_gather_fill_time * 1000 << " , " << std::setw(10) << perf_best.matrix_boundary_condition_time * 1000 << " , " << std::setw(10) << perf_best.cg_iteration_time * 1000 << " , " << std::setw(7) << perf_best.cg_iteration_count << " , " << std::setw(3) << perf_best.newton_iteration_count << " , " << std::setw(10) << perf_best.error_max << std::endl; } } } //---------------------------------------------------------------------------- } /* namespace Nonlinear */ } /* namespace HybridFEM */ #endif /* #ifndef HYBRIDFEM_IMPLICIT_HPP */
34.920223
80
0.61104
[ "mesh", "vector" ]
0c83ff926479d7e6bd78f8a950486769075bc529
2,914
cpp
C++
Motor2D/UiItem_Image.cpp
pink-king/Final-Fantasy-Tactics
b5dcdd0aa548900b3b2279cd4c6d4220f5869c08
[ "Unlicense" ]
9
2019-04-19T17:25:34.000Z
2022-01-30T14:46:30.000Z
Motor2D/UiItem_Image.cpp
pink-king/Final-Fantasy-Tactics
b5dcdd0aa548900b3b2279cd4c6d4220f5869c08
[ "Unlicense" ]
44
2019-03-22T10:22:19.000Z
2019-08-08T07:48:27.000Z
Motor2D/UiItem_Image.cpp
pink-king/Final-Fantasy-Tactics
b5dcdd0aa548900b3b2279cd4c6d4220f5869c08
[ "Unlicense" ]
1
2022-01-30T14:46:34.000Z
2022-01-30T14:46:34.000Z
#include "UiItem_Image.h" #include "j1App.h" #include "j1Textures.h" #include "j1Render.h" #include "j1Gui.h" #include "j1Scene.h" #include "j1Input.h" #include "LootEntity.h" UiItem_Image::UiItem_Image(iPoint position, const SDL_Rect* section, std::string& name, UiItem* const parent, bool swapPosition, bool isTabbable, bool autorefresh) : UiItem(position, name, parent) { this->section = *section; this->guiType = GUI_TYPES::IMAGE; this->swapPosition = swapPosition; this->hitBox.w = section->w; this->hitBox.h = section->h; section_item = *section; if (isTabbable == 1) { tabbable = true; } if (autorefresh == 1) { this->autorefresh = true; } if (name == "tick") this->hide = true; // the parent this->parent = parent; this->hitBox.x = position.x; this->hitBox.y = position.y; } UiItem_Image::UiItem_Image(iPoint position, const SDL_Rect* section, UiItem* const parent, SDL_Texture* newTex, UiItem_Description* myDescr) : UiItem(position, parent) { this->section = *section; this->guiType = GUI_TYPES::IMAGE; this->hitBox.w = section->w; this->hitBox.h = section->h; // the parent this->parent = parent; this->hitBox.x = position.x; this->hitBox.y = position.y; // new texture for loot image this->newTex = newTex; if (this->parent->guiType == GUI_TYPES::INVENTORY) // image in inventory { this->myDescr = myDescr; this->tabbable = true; } } UiItem_Image::~UiItem_Image() { } void UiItem_Image::Draw(const float& dt) { if (!hide) { // TODO: don't blit the icon in the loot item description using the GUI atlas, but instead the Loot atlas if (!printFromLoot) { if (this->autorefresh) { section = App->input->GetSectionForElement(this->name); } float speed = 0.0f; if (!useCamera) speed = 1.0f; App->render->BlitGui(App->gui->GetAtlas(), hitBox.x, hitBox.y, &this->section, speed, 1.0f, 0.0f, resizedRect); } else { if (this->parent->guiType == GUI_TYPES::DESCRIPTION) // DESCRIPTION image { float speed = 0.0f; if (!App->scene->inventory->enable) // when in game, icon image speed is 1.0f speed = 1.0f; App->render->BlitGui(newTex, hitBox.x, hitBox.y, &this->section, speed, scaleFactor); // 4.0f } else if (this->parent->guiType == GUI_TYPES::INVENTORY) // INVENTORY image { App->render->BlitGui(newTex, hitBox.x, hitBox.y, &this->section, 0.0f, 1.4f); } } } if (App->gui->selected_object == this) { App->scene->tab_controls->hitBox.x = App->gui->selected_object->hitBox.x - 8; App->scene->tab_controls->hitBox.y = App->gui->selected_object->hitBox.y - 7; if (App->gui->selected_object->autorefresh) { App->input->ListeningInputFor(this->name); } } } void UiItem_Image::CleanUp() { /*if(myDescr != nullptr) myDescr->to_delete = true;*/ if (newTex != nullptr) { //App->tex->UnLoad(newTex); newTex = nullptr; } }
20.521127
196
0.656143
[ "render" ]
0c8715c1cb4f5418ebea345962fd5e98e8209d7d
8,435
cpp
C++
UFFBAPS/methods/reverse_chemical_shift_changes.cpp
shambo001/peat
7a26e896aa9914b084a9064df09ed15df4047cf3
[ "MIT" ]
3
2016-11-11T06:11:03.000Z
2021-09-12T22:13:51.000Z
UFFBAPS/methods/reverse_chemical_shift_changes.cpp
shambo001/peat
7a26e896aa9914b084a9064df09ed15df4047cf3
[ "MIT" ]
null
null
null
UFFBAPS/methods/reverse_chemical_shift_changes.cpp
shambo001/peat
7a26e896aa9914b084a9064df09ed15df4047cf3
[ "MIT" ]
2
2016-02-15T16:10:36.000Z
2018-02-27T10:33:21.000Z
/* # # UFFBAPS - Unified Force Field for Binding And Protein Stability # Copyright (C) 2010 Jens Erik Nielsen & Chresten Soendergaard # # 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, either version 3 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Contact information: # Email: Jens.Nielsen_at_gmail.com # Normal mail: # Jens Nielsen # SBBS, Conway Institute # University College Dublin # Dublin 4, Ireland */ #include "reverse_chemical_shift_changes.h" Reverse_Chemical_Shift_Changes::Reverse_Chemical_Shift_Changes(FILE * reporter):Method(reporter) { /*** write out to out file **/ writeDescription(reporter); set_parameters(); } Reverse_Chemical_Shift_Changes::Reverse_Chemical_Shift_Changes(FILE * reporter,vector<Soup*> A):Method(reporter) { /*** write out to out file **/ writeDescription(reporter); cout<<"checkpoint 1"<<endl; set_parameters(); cout<<"checkpoint 2"<<endl; calculate_dielectrics(A); } Reverse_Chemical_Shift_Changes::~Reverse_Chemical_Shift_Changes(){} void Reverse_Chemical_Shift_Changes::calculate_dielectrics(vector<Soup*> A) { for(vector<Soup*>::iterator soup = A.begin(); soup != A.end(); soup++) calculate_dielectrics(*soup); } void Reverse_Chemical_Shift_Changes::calculate_dielectrics(Soup * A) { A->set_sybyl_atom_types(); calculate_dielectrics(A->getAtoms()); } void Reverse_Chemical_Shift_Changes::calculate_dielectrics(vector<Atom*> atoms_in) { atoms = atoms_in; read_in_chemical_shifts(data_file); FILE * mfile = fopen("dielectrics.txt","w"); fprintf(mfile,"Residue, Residue number, Dielectric, Distance, electrostatic field, electrostatic potential\n"); for(vector<amide>::iterator cur_amide = amides.begin(); cur_amide != amides.end(); cur_amide++ ) { // charge, distance, vectors (*cur_amide).dielectric = CSC.induced_shift(affector_atom, (*cur_amide).N,(*cur_amide).H, (*cur_amide).C); //units of e/(A*A) // convert to SI units (*cur_amide).dielectric = (*cur_amide).dielectric * e / (1e-10*1e-10); //units of C/(m*m) // constants (*cur_amide).dielectric = (*cur_amide).dielectric * alpha/(4*pi*eps_0*(*cur_amide).experimental_chemical_shift); //units: ppm/au /(C*C/(J*m)*ppm)*C/(m*m) = J /(C*m) * 1/au // a u (*cur_amide).dielectric = (*cur_amide).dielectric * e*a0/Eh; //units: ppm cout<<"Distance: "<<(*cur_amide).N->residue_no<<(*cur_amide).N->residue<< " "<<D.calculate(affector_atom, (*cur_amide).N, true) <<" to "; (*cur_amide).N->display(); cout<<"Distance: "<< (*cur_amide).H->residue_no<< (*cur_amide).H->residue<< " "<<D.calculate(affector_atom, (*cur_amide).H, true) <<" to "; (*cur_amide).H->display(); cout<<"Affector atom: "; affector_atom->display(); float distance = sqrt((((*cur_amide).N->x+(*cur_amide).H->x)/2 - affector_atom->x)*(((*cur_amide).N->x+(*cur_amide).H->x)/2 - affector_atom->x)+ (((*cur_amide).N->y+(*cur_amide).H->y)/2 - affector_atom->y)*(((*cur_amide).N->y+(*cur_amide).H->y)/2 - affector_atom->y)+ (((*cur_amide).N->z+(*cur_amide).H->z)/2 - affector_atom->z)*(((*cur_amide).N->z+(*cur_amide).H->z)/2 - affector_atom->z)); // electric field (*cur_amide).electrostatic_field = 1/(4*pi*eps_0*(*cur_amide).dielectric)*affector_atom->charge*e/(distance*1e-10*distance*1e-10); // electrostatic potential (*cur_amide).electrostatic_potential = 1/(4*pi*eps_0*(*cur_amide).dielectric)*affector_atom->charge*e/(distance*1e-10); cout<<(*cur_amide).dielectric<<" dist:"<< distance<<endl; fprintf(mfile,"%3s %4d %10.2e %10.2e %10.2e %10.2e\n",(*cur_amide).H->residue.c_str(),(*cur_amide).H->residue_no,(*cur_amide).dielectric, distance, (*cur_amide).electrostatic_field, (*cur_amide).electrostatic_potential); } fclose(mfile); } void Reverse_Chemical_Shift_Changes::read_in_chemical_shifts(string filename) { ifstream list(filename.c_str()); cout<<"hallllos"<<endl; if(! list.is_open()) { cout << "Error:File '"<<filename<<"' could not be found\n"; exit(0); } string line,affector_name; vector<string> words; //set affector atom getline(list, line); set_affector_atom(line); cout<<"spasser"<<endl; while (!list.eof()) { // get line and split it into words getline(list, line); /*** replaces ',' with ' ' ***/ for(int i=0; i<line.size(); i++) if(string(line,i,1) ==",") { line.replace(i, 1, string(" ")); i++; } words.clear(); char temp[300]; istringstream stream(line.c_str()); while(stream>>temp) { words.push_back(string(temp)); } // insert value in amide chem shift list if(words.size()>1) { // check if last word can be converted to float istringstream i(words[words.size()-1]); float chem_shift; if (i >> chem_shift) if(words.size()==2) //Only backbone amides!!! { int res_no = atoi(words[0].substr(1,words[0].size()-1).c_str()); insert_amide(res_no, chem_shift); } } } } void Reverse_Chemical_Shift_Changes::insert_amide(int residue, float chem_shift) { amide temp; cout<<chem_shift<<" for residue "<<residue<<endl; // set atoms for(vector<Atom*>::iterator atom = atoms.begin();atom!=atoms.end();atom++) { if((*atom)->residue_no == residue) { if((*atom)->name == "N") temp.N = *atom; if((*atom)->name == "H") temp.H = *atom; } if((*atom)->residue_no == residue-1) if((*atom)->name == "C") temp.C = *atom; } // set chem shift temp.experimental_chemical_shift = chem_shift; cout<<"Inserted residue: "<<residue<<" with the chemical shift "<<chem_shift<<endl; temp.N->display(); temp.H->display(); temp.C->display(); // store amides.push_back(temp); } void Reverse_Chemical_Shift_Changes::set_affector_atom(string residue) { cout<<"looking for "<<residue<<endl; cout<<"split "<<residue.substr(10,4)<<endl; int residue_no = atoi(residue.substr(10,4).c_str()); cout<<"residue no "<<residue_no<<endl; // find affector atom for(vector<Atom*>::iterator atom = atoms.begin(); atom != atoms.end(); atom++ ) if((*atom)->residue_no == residue_no && CSC.titratable_residues.count((*atom)->generic_key)==1) { affector_atom = *atom; affector_atom_charge = CSC.titratable_residues[(*atom)->generic_key]; } // set the charge affector_atom->charge = CSC.titratable_residues[affector_atom->generic_key]; cout<<"Affector "<<residue_no<<" "; affector_atom->display(); } void Reverse_Chemical_Shift_Changes::set_parameters() { // alpha = 70.0; //ppm/au alpha = 977.0; //A|| for C-N pi = 3.14159265; eps_0 = 8.85419e-12;//C*C/(J*m) e = 1.602177e-19; //C a0 = 5.291772e-11; //m Eh = 4.359744e-18; //J ifstream parameters; parameters.open("reverse_chemical_shift_changes.cfg"); if(! parameters.is_open()) { cout << "Error:File 'reverse_chemical_shift_changes.cfg' could not be found\n"; exit(0); } printf("Setting parameters\n"); string dummy; while (!parameters.eof()) { parameters >> dummy; if(dummy == "EXPERIMENTAL_DATA_FILE:") parameters >> data_file; } //end read file //printing all configurations printf("Configurations for reverse chemical shift changes:\n"); printf("\n"); printf("\n"); printf("EXPERIMENTAL_DATA_FILE: %s\n", data_file.c_str()); printf("\n"); printf("Version: $Id: es.cpp 160 2007-11-26 19:44:53Z chresten $\n"); printf("\n"); } void Reverse_Chemical_Shift_Changes::writeDescription(FILE * reporter) { /*** write out to out file **/ version =string("$Id: reverse_chemical_shift_changes.cpp 18 2005-11-15 09:56:08Z chresten $"); description = string(""); fprintf(reporter,"%s\n",version.c_str()); fprintf(reporter,"%s\n",description.c_str()); }
28.023256
225
0.654653
[ "vector" ]
0c8a2c0a95fbffe0fe28fd1eae4260249c4044d7
5,848
cpp
C++
DT3Core/Scripting/ScriptingTimerUpReset.cpp
9heart/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2018-10-05T15:03:27.000Z
2019-03-19T11:01:56.000Z
DT3Core/Scripting/ScriptingTimerUpReset.cpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
1
2016-01-28T14:39:49.000Z
2016-01-28T22:12:07.000Z
DT3Core/Scripting/ScriptingTimerUpReset.cpp
adderly/DT3
e2605be091ec903d3582e182313837cbaf790857
[ "MIT" ]
3
2016-01-25T16:44:51.000Z
2021-01-29T19:59:45.000Z
//============================================================================== /// /// File: ScriptingTimerUpReset.cpp /// /// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== #include "DT3Core/Scripting/ScriptingTimerUpReset.hpp" #include "DT3Core/System/Factory.hpp" #include "DT3Core/System/Profiler.hpp" #include "DT3Core/Types/FileBuffer/ArchiveData.hpp" #include "DT3Core/Types/FileBuffer/Archive.hpp" #include "DT3Core/World/World.hpp" //============================================================================== //============================================================================== namespace DT3 { //============================================================================== /// Register with object factory //============================================================================== IMPLEMENT_FACTORY_CREATION_SCRIPT(ScriptingTimerUpReset,"Timers",NULL) IMPLEMENT_PLUG_NODE(ScriptingTimerUpReset) IMPLEMENT_PLUG_INFO_INDEX(_speed) IMPLEMENT_PLUG_INFO_INDEX(_time) IMPLEMENT_PLUG_INFO_INDEX(_t) IMPLEMENT_PLUG_INFO_INDEX(_active) //============================================================================== //============================================================================== BEGIN_IMPLEMENT_PLUGS(ScriptingTimerUpReset) PLUG_INIT(_speed,"Speed") .set_input(true) .affects(PLUG_INFO_INDEX(_t)) .affects(PLUG_INFO_INDEX(_time)); PLUG_INIT(_active,"Active") .set_input(true) .affects(PLUG_INFO_INDEX(_t)) .affects(PLUG_INFO_INDEX(_time)); PLUG_INIT(_time,"Time") .set_output(true); PLUG_INIT(_t,"t") .set_output(true); END_IMPLEMENT_PLUGS //============================================================================== /// Standard class constructors/destructors //============================================================================== ScriptingTimerUpReset::ScriptingTimerUpReset (void) : _upper_range (10.0F), _speed (PLUG_INFO_INDEX(_speed), 1.0F), _active (PLUG_INFO_INDEX(_active), true), _time (PLUG_INFO_INDEX(_time), 0.0F), _t (PLUG_INFO_INDEX(_t), 0.0F), _reset_when_inactive (false) { } ScriptingTimerUpReset::ScriptingTimerUpReset (const ScriptingTimerUpReset &rhs) : ScriptingBase (rhs), _upper_range (rhs._upper_range), _speed (rhs._speed), _active (rhs._active), _time (rhs._time), _t (rhs._t), _reset_when_inactive (rhs._reset_when_inactive) { } ScriptingTimerUpReset & ScriptingTimerUpReset::operator = (const ScriptingTimerUpReset &rhs) { // Make sure we are not assigning the class to itself if (&rhs != this) { ScriptingBase::operator = (rhs); _upper_range = rhs._upper_range; _speed = rhs._speed; _active = rhs._active; _time = rhs._time; _t = rhs._t; _reset_when_inactive = rhs._reset_when_inactive; } return (*this); } ScriptingTimerUpReset::~ScriptingTimerUpReset (void) { } //============================================================================== //============================================================================== void ScriptingTimerUpReset::initialize (void) { ScriptingBase::initialize(); } //============================================================================== //============================================================================== void ScriptingTimerUpReset::archive (const std::shared_ptr<Archive> &archive) { ScriptingBase::archive(archive); archive->push_domain (class_id ()); *archive << ARCHIVE_DATA(_upper_range, DATA_PERSISTENT | DATA_SETTABLE); *archive << ARCHIVE_PLUG(_speed, DATA_PERSISTENT | DATA_SETTABLE); *archive << ARCHIVE_PLUG(_active, DATA_PERSISTENT | DATA_SETTABLE); *archive << ARCHIVE_PLUG(_time, DATA_PERSISTENT | DATA_SETTABLE); *archive << ARCHIVE_PLUG(_t, DATA_PERSISTENT); *archive << ARCHIVE_DATA(_reset_when_inactive, DATA_PERSISTENT | DATA_SETTABLE); archive->pop_domain (); } //============================================================================== //============================================================================== void ScriptingTimerUpReset::tick (const DTfloat dt) { PROFILER(SCRIPTING); DTfloat time = _time.value_without_compute(); // Since we are evaluating _time, reading it the other // way would keep causing this function to be called if (_active) { time += (dt) * (_speed); // Clamp time while (time > _upper_range) { time -= _upper_range; } while (time < 0.0F) { time += _upper_range; } _t = time / _upper_range; _time = time; } else if (_reset_when_inactive) { _t = 0.0F; _time = 0.0F; } } //============================================================================== //============================================================================== void ScriptingTimerUpReset::add_to_world(World *world) { ScriptingBase::add_to_world(world); world->register_for_tick(this, make_callback(this, &type::tick)); } void ScriptingTimerUpReset::remove_from_world (void) { world()->unregister_for_tick(this, make_callback(this, &type::tick)); ScriptingBase::remove_from_world(); } //============================================================================== //============================================================================== } // DT3
31.106383
104
0.487346
[ "object" ]
0c8dd5b8275972481e1ee37522af008feabcc54b
2,237
cpp
C++
behavioral/observer/observer.cpp
stefanpantic/cpp-design-patterns
887f9ddebbb99a773ba132c6298fee37eec25609
[ "MIT" ]
2
2021-01-21T11:03:08.000Z
2021-01-31T17:47:12.000Z
behavioral/observer/observer.cpp
stefanpantic/cpp-design-patterns
887f9ddebbb99a773ba132c6298fee37eec25609
[ "MIT" ]
null
null
null
behavioral/observer/observer.cpp
stefanpantic/cpp-design-patterns
887f9ddebbb99a773ba132c6298fee37eec25609
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <mutex> #include <any> class Person; class IPersonListener { public: virtual ~IPersonListener() = default; virtual void person_changed(Person&, const std::string& property, const std::any& value) = 0; }; class Person { size_t m_age; std::vector<IPersonListener*> m_listeners; mutable std::recursive_mutex m_mtx; public: explicit Person(size_t age) : m_age{age} {} int age() const { return m_age; } bool can_vote() const { return m_age >= 18; } void set_age(size_t age) { std::lock_guard<decltype(m_mtx)> lock(m_mtx); if(age != m_age) { m_age = age; notify("age", age); } } void subscribe(IPersonListener* pl) { std::lock_guard<decltype(m_mtx)> lock(m_mtx); if(std::find(m_listeners.cbegin(), m_listeners.cend(), pl) == m_listeners.cend()) { m_listeners.emplace_back(pl); } } void unsubscribe(IPersonListener* pl) { std::lock_guard<decltype(m_mtx)> lock(m_mtx); auto it{std::find(m_listeners.begin(), m_listeners.end(), pl)}; if(it != m_listeners.end()) { *it = nullptr; } } void notify(const std::string& property, const std::any& value) { std::lock_guard<decltype(m_mtx)> lock(m_mtx); m_listeners.erase( std::remove(std::begin(m_listeners), std::end(m_listeners), nullptr), std::end(m_listeners) ); for(auto* listener : m_listeners) { listener->person_changed(*this, property, value); } } }; class ConsoleListener : public IPersonListener { public: void person_changed(Person&, const std::string& property, const std::any& value) override { std::cout << "Person's " << property << " has been changed to "; if(property == "age") { std::cout << std::any_cast<size_t>(value); } std::cout << std::endl; } }; class BadListener : public IPersonListener { void person_changed(Person& p, const std::string&, const std::any&) override { p.unsubscribe(this); } }; int main() { Person p(10); ConsoleListener cr; BadListener bl; p.subscribe(std::addressof(cr)); p.set_age(11); p.set_age(12); p.subscribe(std::addressof(bl)); p.set_age(13); p.unsubscribe(std::addressof(cr)); p.set_age(17); return 0; }
17.896
94
0.669647
[ "vector" ]
0c90ed2604ce60d27352997e2151e5217c724993
3,487
cpp
C++
src/record.cpp
vadimostanin2/sneeze-detector
2bac0d08cb4960b7dc16492b8c69ff1459dd9334
[ "MIT" ]
11
2015-04-18T23:42:44.000Z
2021-04-03T18:23:44.000Z
src/record.cpp
vadimostanin2/sneeze-detector
2bac0d08cb4960b7dc16492b8c69ff1459dd9334
[ "MIT" ]
null
null
null
src/record.cpp
vadimostanin2/sneeze-detector
2bac0d08cb4960b7dc16492b8c69ff1459dd9334
[ "MIT" ]
3
2017-06-02T17:07:08.000Z
2019-04-18T05:59:48.000Z
/* * record.cpp * * Created on: Dec 1, 2014 * Author: vostanin */ #include "record.h" #include "training_sound_config.h" #include "MainWindow.h" #include <stdlib.h> const unsigned int channels_count = 1; unsigned int sampleRate = 16000; const unsigned int desiredBufferFrames = sampleRate; // 8000 sample frames static RtAudio * global_adc = NULL; int record( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData ) { static vector<float> past_signal; static vector<float> present_signal; static vector<float> future_signal; if ( status ) { cout << "Stream overflow detected!" << endl << flush ; return 0; } static unsigned int time_signal_init = 1; float *buffer = (float *) inputBuffer; record_process_callback callback = (record_process_callback )userData; if( time_signal_init == 1 ) { present_signal.assign( buffer, buffer + nBufferFrames ); time_signal_init++; return 0; } else if( time_signal_init == 2 ) { future_signal.assign( buffer, buffer + nBufferFrames ); time_signal_init++; return 0; } past_signal = present_signal; present_signal = future_signal; future_signal.clear(); future_signal.assign( buffer, buffer + nBufferFrames ); vector<float> signal( present_signal.begin(), present_signal.end() ); const float threshold_amplitude = 0.1; unsigned int max_index = 0; float max_value = 0.0; if( false == condition_check_signal_threshold( signal, threshold_amplitude, max_value, max_index ) ) { cout << "max_amplitude=" << max_value << endl; sneeze_status_set( SOUND_STATUS_PREPARED_E ); return 0; } cout << "max_amplitude=" << max_value << endl; global_adc->stopStream(); callback( past_signal, present_signal, future_signal, threshold_amplitude ); global_adc->startStream(); return 0; } bool record_init( RtAudio& adc, record_process_callback callback ) { int device_count = adc.getDeviceCount(); if ( device_count < 1 ) { std::cout << "\nNo audio devices found!\n"; return false; } bool stream_started = false; for( int devices_i = 0 ; devices_i < device_count ; devices_i++ ) { RtAudio::StreamParameters parameters; parameters.deviceId = devices_i;//adc.getDefaultInputDevice(); parameters.nChannels = channels_count; parameters.firstChannel = 0; unsigned int bufferFrames = desiredBufferFrames; try { adc.openStream( NULL, &parameters, RTAUDIO_FLOAT32, sampleRate, &bufferFrames, record, (void*)callback ); if( bufferFrames != desiredBufferFrames ) { adc.closeStream(); continue; } stream_started = true; break; } catch ( RtAudioError& e ) { e.printMessage(); adc.closeStream(); continue; } } if( stream_started == true ) { std::cout << "\nRecording ..."; adc.startStream(); global_adc = & adc; } return stream_started; } void record_stop(RtAudio& adc) { try { // Stop the stream adc.stopStream(); } catch (RtAudioError& e) { e.printMessage(); } if ( adc.isStreamOpen() ) { adc.closeStream(); } }
24.730496
117
0.620017
[ "vector" ]
0c999415a6bd3e0bc059984f39e7f2fc44283286
1,882
hpp
C++
src/NPCManager.hpp
Zenpock/OpenFusion
2af33da4e8174158ac7016b7f381eab6475d39d9
[ "MIT" ]
null
null
null
src/NPCManager.hpp
Zenpock/OpenFusion
2af33da4e8174158ac7016b7f381eab6475d39d9
[ "MIT" ]
null
null
null
src/NPCManager.hpp
Zenpock/OpenFusion
2af33da4e8174158ac7016b7f381eab6475d39d9
[ "MIT" ]
null
null
null
#pragma once #include "CNProtocol.hpp" #include "PlayerManager.hpp" #include "NPC.hpp" #include "contrib/JSON.hpp" #include <map> #include <vector> #define RESURRECT_HEIGHT 400 // this should really be called vec3 or something... struct WarpLocation { int x, y, z, instanceID, isInstance, limitTaskID, npcID; }; namespace NPCManager { extern std::map<int32_t, BaseNPC*> NPCs; extern std::map<int32_t, WarpLocation> Warps; extern std::vector<WarpLocation> RespawnPoints; extern nlohmann::json NPCData; extern int32_t nextId; void init(); void addNPC(std::vector<Chunk*> viewableChunks, int32_t id); void removeNPC(std::vector<Chunk*> viewableChunks, int32_t id); void destroyNPC(int32_t); void updateNPCPosition(int32_t, int X, int Y, int Z, int angle); void updateNPCPosition(int32_t, int X, int Y, int Z); void updateNPCInstance(int32_t, uint64_t instanceID); void sendToViewable(BaseNPC* npc, void* buf, uint32_t type, size_t size); void npcBarkHandler(CNSocket* sock, CNPacketData* data); void npcSummonHandler(CNSocket* sock, CNPacketData* data); void npcUnsummonHandler(CNSocket* sock, CNPacketData* data); void npcWarpHandler(CNSocket* sock, CNPacketData* data); void npcWarpTimeMachine(CNSocket* sock, CNPacketData* data); void npcVendorStart(CNSocket* sock, CNPacketData* data); void npcVendorTable(CNSocket* sock, CNPacketData* data); void npcVendorBuy(CNSocket* sock, CNPacketData* data); void npcVendorSell(CNSocket* sock, CNPacketData* data); void npcVendorBuyback(CNSocket* sock, CNPacketData* data); void npcVendorBuyBattery(CNSocket* sock, CNPacketData* data); void npcCombineItems(CNSocket* sock, CNPacketData* data); void handleWarp(CNSocket* sock, int32_t warpId); BaseNPC* getNearestNPC(std::vector<Chunk*> chunks, int X, int Y, int Z); }
34.851852
77
0.7322
[ "vector" ]
0c9d681d37f81c2a954ee12b4c4f53be3f9fdfb3
161,102
cpp
C++
src/Overlook/Indicators.cpp
sppp/Overlook
264f6b64d40dc4cf0cb7b7ad6046a0f10eb2297b
[ "BSD-3-Clause" ]
7
2017-07-21T09:10:50.000Z
2021-01-23T09:21:40.000Z
src/Overlook/Indicators.cpp
OuluLinux/Overlook
264f6b64d40dc4cf0cb7b7ad6046a0f10eb2297b
[ "BSD-3-Clause" ]
null
null
null
src/Overlook/Indicators.cpp
OuluLinux/Overlook
264f6b64d40dc4cf0cb7b7ad6046a0f10eb2297b
[ "BSD-3-Clause" ]
8
2017-04-30T08:30:21.000Z
2020-03-14T03:18:41.000Z
#include "Overlook.h" namespace Overlook { double SimpleMA ( const int position, const int period, ConstBuffer& value ) { double result = 0.0; if ( position >= period && period > 0 ) { for ( int i = 0; i < period; i++) result += value.Get( position - i ); result /= period; } return ( result ); } double ExponentialMA ( const int position, const int period, const double prev_value, ConstBuffer& value ) { double result = 0.0; if ( period > 0 ) { double pr = 2.0 / ( period + 1.0 ); result = value.Get( position ) * pr + prev_value * ( 1 - pr ); } return ( result ); } double SmoothedMA ( const int position, const int period, const double prev_value, ConstBuffer& value ) { double result = 0.0; if ( period > 0 ) { if ( position == period - 1 ) { for ( int i = 0;i < period;i++ ) result += value.Get( position - i ); result /= period; } if ( position >= period ) result = ( prev_value * ( period - 1 ) + value.Get( position ) ) / period; } return ( result ); } double LinearWeightedMA ( const int position, const int period, ConstBuffer& value ) { double result = 0.0, sum = 0.0; int i, wsum = 0; if ( position >= period - 1 && period > 0 ) { for ( i = period;i > 0;i-- ) { wsum += i; sum += value.Get( position - i + 1 ) * ( period - i + 1 ); } result = sum / wsum; } return ( result ); } int SimpleMAOnBuffer ( const int rates_total, const int prev_calculated, const int begin, const int period, ConstBuffer& value, Buffer& buffer ) { int i, limit; if ( period <= 1 || rates_total - begin < period ) return ( 0 ); if ( prev_calculated <= 1 ) { limit = period + begin; for ( i = 0;i < limit - 1;i++ ) buffer.Set( i, 0.0 ); double first_value = 0; for ( i = begin; i < limit;i++ ) first_value += value.Get(i); first_value /= period; buffer.Set( limit - 1, first_value); } else limit = prev_calculated - 1; for ( i = limit; i < rates_total; i++) buffer.Set( i, buffer.Get( i - 1 ) + ( value.Get(i) - value.Get( i - period ) ) / period ); return ( rates_total ); } int ExponentialMAOnBuffer ( const int rates_total, const int prev_calculated, const int begin, const int period, ConstBuffer& value, Buffer& buffer ) { int i, limit; if ( period <= 1 || rates_total - begin < period ) return ( 0 ); double dSmoothFactor = 2.0 / ( 1.0 + period ); if ( prev_calculated == 0 ) { limit = period + begin; for ( i = 0;i < begin;i++ ) buffer.Set( i, 0.0 ); buffer.Set( begin, value.Get( begin ) ); for ( i = begin + 1;i < limit;i++ ) buffer.Set( i, value.Get(i) * dSmoothFactor + buffer.Get( i - 1 ) * ( 1.0 - dSmoothFactor ) ); } else limit = prev_calculated - 1; for ( i = limit;i < rates_total;i++ ) buffer.Set( i, value.Get(i) * dSmoothFactor + buffer.Get( i - 1 ) * ( 1.0 - dSmoothFactor ) ); return ( rates_total ); } int LinearWeightedMAOnBuffer ( const int rates_total, const int prev_calculated, const int begin, const int period, ConstBuffer& value, Buffer& buffer, int &weightsum ) { int i, limit; double sum; if ( period <= 1 || rates_total - begin < period ) return ( 0 ); if ( prev_calculated == 0 ) { weightsum = 0; limit = period + begin; for ( i = 0;i < limit;i++ ) buffer.Set( i, 0.0 ); double first_value = 0; for ( i = begin;i < limit; i++) { int k = i - begin + 1; weightsum += k; first_value += k * value.Get(i); } first_value /= ( double ) weightsum; buffer.Set( limit - 1, first_value ); } else limit = prev_calculated - 1; for ( i = limit;i < rates_total; i++) { sum = 0; for ( int j = 0;j < period;j++ ) sum += ( period - j ) * value.Get( i - j ); buffer.Set( i, sum / weightsum ); } return ( rates_total ); } int SmoothedMAOnBuffer ( const int rates_total, const int prev_calculated, const int begin, const int period, ConstBuffer& value, Buffer& buffer ) { int i, limit; if ( period <= 1 || rates_total - begin < period ) return ( 0 ); if ( prev_calculated == 0 ) { limit = period + begin; for ( i = 0;i < limit - 1;i++ ) buffer.Set( i, 0.0 ); double first_value = 0; for ( i = begin;i < limit;i++ ) first_value += value.Get(i); first_value /= period; buffer.Set( limit - 1, first_value ); } else limit = prev_calculated - 1; for ( i = limit;i < rates_total; i++) buffer.Set( i, ( buffer.Get( i - 1 ) * ( period - 1 ) + value.Get(i) ) / period ); return rates_total; } Normalized::Normalized() { } void Normalized::Init() { SetCoreSeparateWindow(); int draw_begin; if (ma_period < 2) ma_period = 13; draw_begin = ma_period - 1; SetBufferColor(0, Blue()); SetBufferColor(1, Red()); SetBufferBegin(0, draw_begin ); } void Normalized::Start() { int bars = GetBars(); int prev_counted = GetCounted(); ConstBuffer& openbuf = GetInputBuffer(0, 0); Buffer& valuebuf = GetBuffer(0); Buffer& avbuf = GetBuffer(1); Buffer& lnbuf = GetBuffer(2); if (!prev_counted) { avbuf.Set(0, Open(0)); prev_counted++; } for(int i = prev_counted; i < bars; i++) { double change = openbuf.Get(i) / openbuf.Get(i-1); double value = log(change); lnbuf.Set(i, value); var.Add(value); } double mean = var.GetMean(); double dev = var.GetDeviation(); double pr = 2.0 / ( ma_period + 1 ); for(int i = prev_counted; i < bars; i++) { double value = lnbuf.Get(i); double x = 1 / (1 + exp(-((value - mean)/(dev)))); valuebuf.Set(i, x); avbuf.Set(i, x * pr + avbuf.Get(i-1) * ( 1 - pr )); } } HurstWindow::HurstWindow() { } void HurstWindow::Init() { SetCoreSeparateWindow(); SetCoreLevelCount(1); SetCoreLevel(0, 0.5); SetCoreMaximum(1); SetCoreMinimum(0); int draw_begin; if (period < 2) period = 13; draw_begin = period - 1; avwin.SetPeriod(period); SetBufferColor(0, Red()); SetBufferBegin(0, draw_begin ); } void HurstWindow::Start() { int bars = GetBars(); int prev_counted = GetCounted(); ConstBuffer& openbuf = GetInputBuffer(0, 0); Buffer& hurstbuf = GetBuffer(0); const Vector<double>& win = avwin.GetWindow(); LabelSignal& ls = GetLabelBuffer(0, 0); Vector<double> x, y; x.SetCount(period); y.SetCount(period); if (!prev_counted) { prev_counted = period; for(int i = 0; i < period; i++) { double open = openbuf.Get(i); avwin.Add(open); } } for(int i = prev_counted; i < bars; i++) { double prev = openbuf.Get(i-1); double open = openbuf.Get(i); avwin.Add(open); double mean = avwin.GetMean(); double sums = 0; for(int k = 0; k < period; k++) { double d = win[k] - mean; x[k] = d; sums += d * d; } double maxY = x[0]; double minY = x[0]; y[0] = x[0]; for(int k = 1; k < period; k++) { y[k] = y[k-1] + x[k]; maxY = max(y[k], maxY); minY = min(y[k], minY); } double iValue = 0; double hurst = 0; if(sums != 0) iValue = (maxY - minY) / (koef * sqrt(sums/period)); if(iValue > 0) hurst = log(iValue) / log(period); hurstbuf.Set(i, hurst); bool sig = open < prev; if (hurst < 0.5) sig = !sig; ls.signal.Set(i, sig); } } SimpleHurstWindow::SimpleHurstWindow() { } void SimpleHurstWindow::Init() { SetCoreSeparateWindow(); //SetCoreLevelCount(1); // normalized //SetCoreLevel(0, 0.5); SetCoreMaximum(1); SetCoreMinimum(-1); // normalized int draw_begin; if (period < 2) period = 13; draw_begin = period - 1; SetBufferColor(0, Red()); SetBufferBegin(0, draw_begin ); } void SimpleHurstWindow::Start() { int bars = GetBars(); int prev_counted = GetCounted(); ConstBuffer& openbuf = GetInputBuffer(0, 0); Buffer& hurstbuf = GetBuffer(0); LabelSignal& ls = GetLabelBuffer(0, 0); if (prev_counted < period) prev_counted = period + 1; for(int i = prev_counted; i < bars; i++) { double hurst = GetSimpleHurst(openbuf, i, period); hurst = (hurst - 0.5) * 2.0; // normalized hurstbuf.Set(i, hurst); double o1 = openbuf.Get(i-1); double o0 = openbuf.Get(i); bool sig = o0 < o1; if (hurst < 0.0) sig = !sig; // normalized ls.signal.Set(i, sig); } } double GetSimpleHurst(ConstBuffer& openbuf, int i, int period) { int pos = 0, neg = 0; for(int j = 0; j < period; j++) { double o2 = openbuf.Get(i-2-j); double o1 = openbuf.Get(i-1-j); double o0 = openbuf.Get(i-j); double d0 = o0-o1; double d1 = o1-o2; double d = d0 * d1; if (d >= 0) pos++; else neg++; } double hurst = (double)pos / (double) period; return hurst; } MovingAverage::MovingAverage() { ma_period = 13; ma_shift = -6; ma_method = 0; ma_counted = 0; } void MovingAverage::Init() { int draw_begin; if (ma_period < 2) ma_period = 13; draw_begin = ma_period - 1; SetBufferColor(0, Red()); SetBufferShift(0, ma_shift); SetBufferBegin(0, draw_begin ); } void MovingAverage::Start() { int bars = GetBars(); if ( bars <= ma_period ) throw ConfExc(); ma_counted = GetCounted(); if ( ma_counted < 0 ) throw DataExc(); if ( ma_counted > 0 ) ma_counted--; int begin = ma_counted; switch ( ma_method ) { case MODE_SIMPLE: Simple(); break; case MODE_EXPONENTIAL: Exponential(); break; case MODE_SMOOTHED: Smoothed(); break; case MODE_LINWEIGHT: LinearlyWeighted(); } Buffer& buffer = GetBuffer(0); VectorBool& signal = GetLabelBuffer(0, 0).signal; SetSafetyLimit(ma_counted-1); double prev = ma_counted > 0 ? buffer.Get(ma_counted-1) : 0.0; for(int i = ma_counted; i < bars; i++) { SetSafetyLimit(i); double cur = buffer.Get(i); bool label_value = cur < prev; signal.Set(i, label_value); prev = cur; } } void MovingAverage::Simple() { Buffer& buffer = GetBuffer(0); double sum = 0; int bars = GetBars(); int pos = ma_counted; if (pos < ma_period) pos = ma_period; SetSafetyLimit(pos); for (int i = 1; i < ma_period; i++) sum += Open(pos - i); while (pos < bars) { SetSafetyLimit(pos); sum += Open( pos ); buffer.Set(pos, sum / ma_period); sum -= Open( pos - ma_period + 1 ); pos++; } if (ma_counted < 1) for (int i = 0; i < ma_period; i++) buffer.Set(i, Open(i)); } void MovingAverage::Exponential() { Buffer& buffer = GetBuffer(0); int bars = GetBars(); double pr = 2.0 / ( ma_period + 1 ); int pos = 1; if ( ma_counted > 2 ) pos = ma_counted + 1; while (pos < bars) { SetSafetyLimit(pos); if (pos == 1) buffer.Set(pos-1, Open(pos - 1)); buffer.Set(pos, Open(pos) * pr + buffer.Get(pos-1) * ( 1 - pr )); pos++; } } void MovingAverage::Smoothed() { Buffer& buffer = GetBuffer(0); double sum = 0; int bars = GetBars(); int pos = ma_period; if (pos < ma_counted) pos = ma_counted; while (pos < bars) { SetSafetyLimit(pos); if (pos == ma_period) { for (int i = 0, k = pos; i < ma_period; i++, k--) { sum += Open(k); buffer.Set(k, 0); } } else sum = buffer.Get(pos-1) * ( ma_period - 1 ) + Open(pos); buffer.Set(pos, sum / ma_period); pos++; } } void MovingAverage::LinearlyWeighted() { Buffer& buffer = GetBuffer(0); double sum = 0.0, lsum = 0.0; double value; int bars = GetBars(); int weight = 0, pos = ma_counted + 1; if (pos > bars - ma_period) pos = bars - ma_period; for (int i = 1; i <= ma_period; i++, pos++) { SetSafetyLimit(pos); value = Open( pos ); sum += value * i; lsum += value; weight += i; } pos--; int i = pos - ma_period; while (pos < bars) { buffer.Set(pos, sum / weight); pos++; i++; if ( pos == bars ) break; SetSafetyLimit(pos); value = Open(pos); sum = sum - lsum + value * ma_period; lsum -= Open(i); lsum += value; } if ( ma_counted < 1 ) for (i = 0; i < ma_period; i++) buffer.Set(i, Open(i)); } MovingAverageConvergenceDivergence::MovingAverageConvergenceDivergence() { fast_ema_period = 12; slow_ema_period = 26; signal_sma_period = 9; } void MovingAverageConvergenceDivergence::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Silver); SetBufferColor(1, Red); SetBufferLineWidth(0, 2); SetBufferBegin ( 1, signal_sma_period ); SetBufferStyle(0, DRAW_HISTOGRAM); SetBufferStyle(1, DRAW_LINE); SetBufferLabel(0,"MACD"); SetBufferLabel(1,"Signal"); AddSubCore<MovingAverage>().Set("period", fast_ema_period).Set("method", method); AddSubCore<MovingAverage>().Set("period", slow_ema_period).Set("method", method); } void MovingAverageConvergenceDivergence::Start() { Buffer& buffer = GetBuffer(0); Buffer& signal_buffer = GetBuffer(1); int bars = GetBars(); if ( bars <= signal_sma_period ) throw DataExc(); int counted = GetCounted(); if ( counted > 0 ) counted--; else counted++; const Core& a_ind = At(0); const Core& b_ind = At(1); ConstBuffer& a_buf = a_ind.GetBuffer(0); ConstBuffer& b_buf = b_ind.GetBuffer(0); RefreshSubCores(); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double a_value = a_buf.Get(i); double b_value = b_buf.Get(i); double diff = a_value - b_value; buffer.Set(i, diff); } SimpleMAOnBuffer( bars, GetCounted(), 0, signal_sma_period, buffer, signal_buffer ); LabelSignal& signal = GetLabelBuffer(0, 0); LabelSignal& side = GetLabelBuffer(0, 1); LabelSignal& late = GetLabelBuffer(0, 2); LabelSignal& early = GetLabelBuffer(0, 3); for (int i = counted; i < bars; i++) { double value = buffer.Get(i); double prev = buffer.Get(i-1); double ma = signal_buffer.Get(i); bool value_sig = value < prev; early.signal.Set(i, value_sig); early.enabled.Set(i, (!value_sig && value < 0) || (value_sig && value > 0)); late.signal.Set(i, value_sig); late.enabled.Set(i, (value_sig && value < 0) || (!value_sig && value > 0)); side.signal.Set(i, value < 0); signal.signal.Set(i, value < ma); } } AverageDirectionalMovement::AverageDirectionalMovement() { period_adx = 14; } void AverageDirectionalMovement::Init() { SetCoreSeparateWindow(); SetBufferColor(0, LightSeaGreen); SetBufferColor(1, YellowGreen); SetBufferColor(2, Wheat); SetBufferLabel(0,"ADX"); SetBufferLabel(1,"+DI"); SetBufferLabel(2,"-DI"); if ( period_adx >= 10000 || period_adx <= 1 ) throw ConfExc(); SetBufferBegin ( 0, period_adx ); SetBufferBegin ( 1, period_adx ); SetBufferBegin ( 2, period_adx ); } void AverageDirectionalMovement::Start() { Buffer& adx_buffer = GetBuffer(0); Buffer& pdi_buffer = GetBuffer(1); Buffer& ndi_buffer = GetBuffer(2); Buffer& pd_buffer = GetBuffer(3); Buffer& nd_buffer = GetBuffer(4); Buffer& tmp_buffer = GetBuffer(5); int bars = GetBars(); if ( bars < period_adx ) throw ConfExc(); int counted = GetCounted(); if ( counted > 0 ) counted--; else { counted = 2; for(int i = 0; i < 2; i++) { SetSafetyLimit(i); pdi_buffer.Set(i, 0.0); ndi_buffer.Set(i, 0.0); adx_buffer.Set(i, 0.0); } } for ( int i = counted; i < bars; i++) { SetSafetyLimit(i); double Hi = High(i - 1); double prev_hi = High(i - 2); double Lo = Low(i - 1); double prev_lo = Low(i - 2); double prev_cl = Open(i); double tmp_p = Hi - prev_hi; double tmp_n = prev_lo - Lo; if ( tmp_p < 0.0 ) tmp_p = 0.0; if ( tmp_n < 0.0 ) tmp_n = 0.0; if ( tmp_p > tmp_n ) tmp_n = 0.0; else { if ( tmp_p < tmp_n ) tmp_p = 0.0; else { tmp_p = 0.0; tmp_n = 0.0; } } double tr = Upp::max( Upp::max( fabs ( Hi - Lo ), fabs ( Hi - prev_cl ) ), fabs ( Lo - prev_cl ) ); if ( tr != 0.0 ) { pd_buffer.Set(i, 100.0 * tmp_p / tr); nd_buffer.Set(i, 100.0 * tmp_n / tr); } else { pd_buffer.Set(i, 0); nd_buffer.Set(i, 0); } pdi_buffer.Set(i, ExponentialMA ( i, period_adx, pdi_buffer.Get( i - 1 ), pd_buffer )); ndi_buffer.Set(i, ExponentialMA ( i, period_adx, ndi_buffer.Get( i - 1 ), nd_buffer )); double tmp = pdi_buffer.Get(i) + ndi_buffer.Get(i); if ( tmp != 0.0 ) tmp = 100.0 * fabs ( ( pdi_buffer.Get(i) - ndi_buffer.Get(i) ) / tmp ); else tmp = 0.0; tmp_buffer.Set(i, tmp); adx_buffer.Set(i, ExponentialMA ( i, period_adx, adx_buffer.Get ( i - 1 ), tmp_buffer )); } } BollingerBands::BollingerBands() { bands_period = 20; bands_shift = 0; bands_deviation = 2.0; deviation = 20; plot_begin = 0; } void BollingerBands::Init() { SetCoreChartWindow(); bands_deviation = deviation * 0.1; SetBufferColor(0, LightSeaGreen); SetBufferColor(1, LightSeaGreen); SetBufferColor(2, LightSeaGreen); SetBufferStyle(0,DRAW_LINE); SetBufferShift(0,bands_shift); SetBufferLabel(0,"Bands SMA"); SetBufferStyle(1,DRAW_LINE); SetBufferShift(1,bands_shift); SetBufferLabel(1,"Bands Upper"); SetBufferStyle(2,DRAW_LINE); SetBufferShift(2,bands_shift); SetBufferLabel(2,"Bands Lower"); if ( bands_period < 2 ) throw ConfExc(); if ( bands_deviation == 0.0 ) throw ConfExc(); plot_begin = bands_period - 1; SetBufferBegin ( 0, bands_period ); SetBufferBegin ( 1, bands_period ); SetBufferBegin ( 2, bands_period ); SetBufferShift ( 0, bands_shift ); SetBufferShift ( 1, bands_shift ); SetBufferShift ( 2, bands_shift ); } void BollingerBands::Start() { Buffer& ml_buffer = GetBuffer(0); Buffer& tl_buffer = GetBuffer(1); Buffer& bl_buffer = GetBuffer(2); Buffer& stddev_buffer = GetBuffer(3); int bars = GetBars(); int pos; int counted = GetCounted(); if ( bars < plot_begin ) throw DataExc(); if ( counted > 1 ) pos = counted - 1; else pos = 0; ConstBuffer& open = GetInputBuffer(0, 0); LabelSignal& sig = GetLabelBuffer(0, 0); for ( int i = pos; i < bars; i++) { SetSafetyLimit(i); double ma = SimpleMA( i, bands_period, open ); if (ma == 0.0) ma = open.Get(i); ml_buffer.Set(i, ma); stddev_buffer.Set(i, StdDev_Func ( i, ml_buffer, bands_period )); double tl = ml_buffer.Get(i) + bands_deviation * stddev_buffer.Get(i); double bl = ml_buffer.Get(i) - bands_deviation * stddev_buffer.Get(i); tl_buffer.Set(i, tl); bl_buffer.Set(i, bl); double o = open.Get(i); bool signal = o < ma; bool enabled = o <= bl || o >= tl; sig.signal.Set(i, signal); sig.enabled.Set(i, enabled); } } double BollingerBands::StdDev_Func ( int position, const Buffer& MAvalue, int period ) { double tmp = 0.0; if ( position < period ) return tmp; int bars = GetBars(); for (int i = 0; i < period; i++) { double value = Open (position - i ); tmp += pow ( value - MAvalue.Get( position ), 2 ); } tmp = sqrt( tmp / period ); return tmp; } Envelopes::Envelopes() { ma_period = 14; ma_shift = 0; ma_method = MODE_SMA; deviation = 0.1; dev = 10; } void Envelopes::Init() { SetCoreChartWindow(); deviation = dev * 0.1; SetBufferColor(0, Blue); SetBufferColor(1, Red); SetBufferBegin ( 0, ma_period - 1 ); SetBufferShift ( 0, ma_shift ); SetBufferShift ( 1, ma_shift ); SetBufferStyle(0, DRAW_LINE); SetBufferStyle(1, DRAW_LINE); AddSubCore<MovingAverage>().Set("period", ma_period).Set("offset", 0).Set("method", ma_method); } void Envelopes::Start() { Buffer& up_buffer = GetBuffer(0); Buffer& down_buffer = GetBuffer(1); Buffer& ma_buffer = GetBuffer(2); int bars = GetBars(); if ( bars < ma_period ) throw DataExc(); int counted = GetCounted(); if (counted) counted--; else counted = ma_period; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double value = Open(i); ASSERT(value != 0); ma_buffer.Set(i, value); up_buffer.Set(i, ( 1 + deviation / 100.0 ) * ma_buffer.Get(i)); down_buffer.Set(i, ( 1 - deviation / 100.0 ) * ma_buffer.Get(i)); } } Channel::Channel() { } void Channel::Init() { SetCoreChartWindow(); SetBufferColor(0, Red); SetBufferColor(1, Blue); SetBufferStyle(0, DRAW_LINE); SetBufferStyle(1, DRAW_LINE); ec.SetSize(period); } void Channel::Start() { Buffer& lo_buffer = GetBuffer(0); Buffer& hi_buffer = GetBuffer(1); ConstBuffer& open_buf = GetInputBuffer(0, 0); ConstBuffer& low_buf = GetInputBuffer(0, 1); ConstBuffer& high_buf = GetInputBuffer(0, 2); int bars = GetBars(); if ( bars < period ) throw ConfExc(); int counted = GetCounted(); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double lo = i == 0 ? open_buf.Get(i) : low_buf.Get(i-1); double hi = i == 0 ? open_buf.Get(i) : high_buf.Get(i-1); ec.Add(lo, hi); int highest = ec.GetHighest(); int lowest = ec.GetLowest(); if (i == 0 || highest == 0 || lowest == 0) { lo_buffer.Set(i, open_buf.Get(i)); hi_buffer.Set(i, open_buf.Get(i)); } else { lo_buffer.Set(i, low_buf.Get(lowest-1)); hi_buffer.Set(i, high_buf.Get(highest-1)); } } } ParabolicSAR::ParabolicSAR() { sar_step = 0.02; sar_maximum = 0.2; step = 20; maximum = 20; } void ParabolicSAR::Init() { SetCoreChartWindow(); sar_step = step * 0.001; sar_maximum = maximum * 0.01; SetBufferColor(0, Lime); if (sar_step <= 0.0) throw ConfExc(); if (sar_maximum <= 0.0) throw ConfExc(); last_rev_pos = 0; direction_long = false; SetBufferStyle(0, DRAW_ARROW); SetBufferArrow(0, 159); } void ParabolicSAR::Start () { Buffer& sar_buffer = GetBuffer(0); Buffer& ep_buffer = GetBuffer(1); Buffer& af_buffer = GetBuffer(2); int counted = GetCounted(); int bars = GetBars(); if ( bars < 3 ) throw DataExc(); int pos = counted - 1; if ( pos < 1 ) { SetSafetyLimit(1); pos = 1; af_buffer.Set(0, sar_step); af_buffer.Set(1, sar_step); sar_buffer.Set(0, High( 0 )); last_rev_pos = 0; direction_long = false; sar_buffer.Set(1, GetHigh( pos-1, last_rev_pos )); double low = Low( 0 ); ep_buffer.Set(0, low); ep_buffer.Set(1, low); } if (pos == 0) pos++; int prev_pos = pos - 1; if (prev_pos < 0) prev_pos = 0; SetSafetyLimit(prev_pos+1); double prev_high = High( prev_pos ); double prev_low = Low( prev_pos ); //bars--; LabelSignal& sig = GetLabelBuffer(0, 0); for (int i = pos; i < bars; i++) { SetSafetyLimit(i); double low = Low(i-1); double high = High(i-1); if ( direction_long ) { if ( sar_buffer.Get(i-1) > low ) { direction_long = false; sar_buffer.Set(i-1, GetHigh( i-1, last_rev_pos )); ep_buffer.Set(i, low); last_rev_pos = i; af_buffer.Set(i, sar_step); } } else { if ( sar_buffer.Get(i-1) < high ) { direction_long = true; sar_buffer.Set(i-1, GetLow( i-1, last_rev_pos )); ep_buffer.Set(i, high); last_rev_pos = i; af_buffer.Set(i, sar_step); } } if ( direction_long ) { if ( high > ep_buffer.Get(i-1) && i != last_rev_pos ) { ep_buffer.Set(i, high); af_buffer.Set(i, af_buffer.Get(i-1) + sar_step); if ( af_buffer.Get(i) > sar_maximum ) af_buffer.Set(i, sar_maximum); } else { if ( i != last_rev_pos ) { af_buffer.Set(i, af_buffer.Get (i-1)); ep_buffer.Set(i, ep_buffer.Get (i-1)); } } double value = sar_buffer.Get(i-1) + af_buffer.Get(i) * ( ep_buffer.Get(i) - sar_buffer.Get(i-1) ); sar_buffer.Set(i, value); if ( value > low || value > prev_low ) sar_buffer.Set(i, Upp::min( low, prev_low )); } else { if ( low < ep_buffer.Get(i-1) && i != last_rev_pos ) { ep_buffer.Set(i, low); af_buffer.Set(i, af_buffer.Get(i-1) + sar_step); if ( af_buffer.Get(i) > sar_maximum ) af_buffer.Set(i, sar_maximum); } else { if ( i != last_rev_pos ) { af_buffer.Set(i, af_buffer.Get(i-1)); ep_buffer.Set(i, ep_buffer.Get(i-1)); } } double value = sar_buffer.Get(i-1) + af_buffer.Get(i) * ( ep_buffer.Get(i) - sar_buffer.Get(i-1) ); sar_buffer.Set(i, value); if ( value < high || value < prev_high ) sar_buffer.Set(i, Upp::max( high, prev_high )); } sig.signal.Set(i, !direction_long); prev_high = high; prev_low = low; } } double ParabolicSAR::GetHigh( int pos, int start_pos ) { ASSERT(pos >= start_pos); int bars = GetBars(); double result = High( start_pos ); for ( int i = start_pos+1; i <= pos; i++) { double high = High(i); if ( result < high ) result = high; } return ( result ); } double ParabolicSAR::GetLow( int pos, int start_pos ) { ASSERT(pos >= start_pos); int bars = GetBars(); double result = Low( start_pos ); for ( int i = start_pos+1; i <= pos; i++) { double low = Low(i); if ( result > low ) result = low; } return ( result ); } StandardDeviation::StandardDeviation() { period = 20; ma_method = 0; } void StandardDeviation::Init() { SetCoreSeparateWindow(); SetCoreMinimum(0); SetBufferColor(0, Blue); SetBufferBegin ( 0, period ); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0, "StdDev"); AddSubCore<MovingAverage>().Set("period", period).Set("offset", 0).Set("method", ma_method); } void StandardDeviation::Start() { Buffer& stddev_buffer = GetBuffer(0); double value, amount, ma; int bars = GetBars(); if ( bars <= period ) throw DataExc(); int counted = GetCounted(); if ( counted > 0 ) counted--; else counted = period; ConstBuffer& ma_buf = At(0).GetBuffer(0); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); amount = 0.0; ma = ma_buf.Get(i); for ( int j = 0; j < period; j++ ) { value = Open( i - j ); amount += ( value - ma ) * ( value - ma ); } stddev_buffer.Set(i, sqrt ( amount / period )); } } AverageTrueRange::AverageTrueRange() { period = 14; } void AverageTrueRange::Init() { SetCoreSeparateWindow(); SetBufferColor(0, DodgerBlue); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0, "ATR"); if ( period <= 0 ) throw ConfExc(); SetBufferBegin ( 0, period ); } void AverageTrueRange::Start() { Buffer& atr_buffer = GetBuffer(0); Buffer& tr_buffer = GetBuffer(1); int bars = GetBars(); int counted = GetCounted(); if ( bars <= period || period <= 0 ) throw DataExc(); if ( counted == 0 ) { tr_buffer.Set(0, 0.0); atr_buffer.Set(0, 0.0); for (int i = 1; i < bars; i++) { SetSafetyLimit(i); double h = High(i-1); double l = Low(i-1); double c = Open(i); tr_buffer.Set(i, Upp::max( h, c ) - Upp::min( l, c )); } double first_value = 0.0; for (int i = 1; i <= period; i++) { atr_buffer.Set(i, 0.0); first_value += tr_buffer.Get(i); } first_value /= period; atr_buffer.Set(period, first_value); counted = period + 1; } else counted--; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double h = High(i-1); double l = Low(i-1); double c = Open(i); tr_buffer.Set(i, Upp::max( h, c ) - Upp::min( l, c )); atr_buffer.Set(i, atr_buffer.Get( i - 1 ) + ( tr_buffer.Get(i) - tr_buffer.Get( i - period ) ) / period); } } BearsPower::BearsPower() { period = 13; } void BearsPower::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Silver); SetBufferStyle(0,DRAW_HISTOGRAM); SetBufferLabel(0,"ATR"); AddSubCore<MovingAverage>().Set("period", period).Set("offset", 0).Set("method", MODE_EMA); } void BearsPower::Start() { Buffer& buffer = GetBuffer(0); int bars = GetBars(); int counted = GetCounted(); if ( bars <= period ) throw DataExc(); if ( counted > 0 ) counted--; else counted++; ConstBuffer& ma_buf = At(0).GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double value = Low(i-1) - ma_buf.Get(i); buffer.Set(i, value); sig.signal.Set(i, value < 0); sig.enabled.Set(i, value < 0); } } BullsPower::BullsPower() { period = 13; } void BullsPower::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Silver); SetBufferStyle(0,DRAW_HISTOGRAM); SetBufferLabel(0,"Bulls"); AddSubCore<MovingAverage>().Set("period", period).Set("offset", 0).Set("method", MODE_EMA); } void BullsPower::Start() { Buffer& buffer = GetBuffer(0); int bars = GetBars(); int counted = GetCounted(); if ( bars <= period ) throw DataExc(); if ( counted > 0 ) counted--; else counted++; ConstBuffer& ma_buf = At(0).GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); for ( int i = counted; i < bars; i++) { SetSafetyLimit(i); double value = High(i-1) - ma_buf.Get(i); buffer.Set(i, value); sig.signal.Set(i, value < 0); sig.enabled.Set(i, value > 0); } } CommodityChannelIndex::CommodityChannelIndex() { period = 14; } void CommodityChannelIndex::Init() { SetCoreSeparateWindow(); SetBufferColor(0, LightSeaGreen); SetCoreLevelCount(2); SetCoreLevel(0, -1.0); SetCoreLevel(1, 1.0); SetCoreLevelsColor(Silver); SetCoreLevelsStyle(STYLE_DOT); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0,"CCI"); if ( period <= 1 ) throw ConfExc(); SetBufferBegin ( 0, period ); } void CommodityChannelIndex::Start() { Buffer& cci_buffer = GetBuffer(0); Buffer& value_buffer = GetBuffer(1); Buffer& mov_buffer = GetBuffer(2); LabelSignal& sig = GetLabelBuffer(0, 0); int i, k, pos; double sum, mul; int bars = GetBars(); int counted = GetCounted(); if ( bars <= period || period <= 1 ) throw ConfExc(); if ( counted < 1 ) { for ( i = 1; i < period; i++) { SetSafetyLimit(i); double h = High(i-1); double l = Low(i-1); double c = Open(i); cci_buffer.Set(i, 0.0); value_buffer.Set(i, ( h + l + c ) / 3); mov_buffer.Set(i, 0.0); } } pos = counted - 1; if ( pos < period ) pos = period; if (pos == 0) pos++; //bars--; for ( i = pos; i < bars; i++) { SetSafetyLimit(i); double h = High(i-1); double l = Low(i-1); double c = Open(i); value_buffer.Set(i, ( h + l + c ) / 3); mov_buffer.Set(i, SimpleMA ( i, period, value_buffer )); } mul = 0.015 / period; pos = period - 1; if ( pos < counted - 1 ) pos = counted - 2; i = pos; while ( i < bars ) { SetSafetyLimit(i); sum = 0.0; k = i + 1 - period; SafetyInspect(k); while ( k <= i ) { SafetyInspect(k); sum += fabs ( value_buffer.Get(k) - mov_buffer.Get(i) ); k++; } sum *= mul; double value = 0; if ( sum != 0.0 ) value = ( value_buffer.Get(i) - mov_buffer.Get(i) ) / sum; value *= 0.01; // normalized cci_buffer.Set(i, value); sig.signal.Set(i, value < 0); i++; } } DeMarker::DeMarker() { period = 14; } void DeMarker::Init() { SetCoreSeparateWindow(); SetCoreMinimum(-1); // normalized SetCoreMaximum(1); SetBufferColor(0, DodgerBlue); SetCoreLevelCount(2); SetCoreLevel(0, -0.4); // normalized SetCoreLevel(1, 0.4); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0,"DeMarker"); SetBufferBegin ( 0, period ); } void DeMarker::Start() { Buffer& buffer = GetBuffer(0); Buffer& max_buffer = GetBuffer(1); Buffer& min_buffer = GetBuffer(2); LabelSignal& sig = GetLabelBuffer(0, 0); double num; int bars = GetBars(); int counted = GetCounted(); if ( bars <= period ) throw DataExc(); max_buffer.Set(0, 0.0); min_buffer.Set(0, 0.0); if ( counted > 2 ) counted--; else counted = 2; SetSafetyLimit(counted); double prev_high = counted >= 2 ? High( counted - 1 ) : 0; double prev_low = counted >= 2 ? Low( counted - 1 ) : 0; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double high = High(i-1); double low = Low(i-1); num = high - prev_high; if ( num < 0.0 ) num = 0.0; max_buffer.Set(i, num); num = prev_low - low; if ( num < 0.0 ) num = 0.0; min_buffer.Set(i, num); prev_high = high; prev_low = low; } if ( counted == 0 ) for (int i = 0; i < period; i++) buffer.Set(bars - i, 0.0); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double maxvalue = SimpleMA ( i, period, max_buffer ); num = maxvalue + SimpleMA ( i, period, min_buffer ); double value = 0.0; if ( num != 0.0 ) value = maxvalue / num; value = (value - 0.5) * 2.0; // normalized buffer.Set(i, value); sig.signal.Set(i, value < 0.0); // normalized } } ForceIndex::ForceIndex() { period = 13; ma_method = 0; } void ForceIndex::Init() { SetCoreSeparateWindow(); SetBufferColor(0, DodgerBlue); SetBufferStyle(0,DRAW_LINE); SetBufferBegin(0,period); SetBufferBegin ( 0, period ); AddSubCore<MovingAverage>().Set("period", period).Set("offset", 0).Set("method", ma_method); } void ForceIndex::Start() { Buffer& buffer = GetBuffer(0); int bars = GetBars(); int counted = GetCounted(); if (bars <= period) throw DataExc(); if (counted > 0) counted--; if (counted == 0) counted++; ConstBuffer& ma_buf = At(0).GetBuffer(0); for ( int i = counted; i < bars; i++) { SetSafetyLimit(i); double volume = Volume(i-1); double ma1 = ma_buf.Get(i); double ma2 = ma_buf.Get( i - 1 ); buffer.Set(i, volume * (ma1 - ma2)); } } Momentum::Momentum() { period = 32; shift = -7; } void Momentum::Init() { SetCoreSeparateWindow(); SetBufferColor(0, DodgerBlue); if ( period <= 0 ) throw ConfExc(); SetBufferBegin(0, period); SetBufferShift(0, shift); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0,"Momentum"); } void Momentum::Start() { Buffer& buffer = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); if ( bars <= period || period <= 0 ) throw DataExc(); if ( counted <= 0 ) { for (int i = 0; i < period; i++) { SetSafetyLimit(i); buffer.Set(i, 0.0); } counted = period; } else counted--; SetSafetyLimit(counted-1); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double close1 = Open( i ); double close2 = Open( i - period ); double value = close1 * 100 / close2 - 100; buffer.Set(i, value); sig.signal.Set(i, value < 0); } } OsMA::OsMA() { fast_ema_period = 12; slow_ema_period = 26; signal_sma_period = 9; value_mean = 0.0; value_count = 0; diff_mean = 0.0; diff_count = 0; } void OsMA::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Silver); SetBufferLineWidth(0, 2); SetBufferColor(1, Red); SetBufferLineWidth(1, 1); SetBufferStyle(0,DRAW_HISTOGRAM); SetBufferStyle(1,DRAW_LINE); SetBufferBegin ( 0, signal_sma_period ); AddSubCore<MovingAverage>().Set("period", fast_ema_period).Set("offset", 0).Set("method", MODE_EMA); AddSubCore<MovingAverage>().Set("period", slow_ema_period).Set("offset", 0).Set("method", MODE_EMA); } void OsMA::Start() { Buffer& osma_buffer = GetBuffer(0); Buffer& diff_buffer = GetBuffer(1); Buffer& buffer = GetBuffer(2); Buffer& signal_buffer = GetBuffer(3); int bars = GetBars(); int counted = GetCounted(); if ( bars <= signal_sma_period ) return; if ( counted > 0 ) counted--; ConstBuffer& ma1_buf = At(0).GetBuffer(0); ConstBuffer& ma2_buf = At(1).GetBuffer(0); ASSERT(ma1_buf.GetCount() >= bars); ASSERT(ma2_buf.GetCount() >= bars); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double ma1 = ma1_buf.GetUnsafe(i); double ma2 = ma2_buf.GetUnsafe(i); double d = ma1 - ma2; buffer.Set(i, d); } SetSafetyLimit(bars); SimpleMAOnBuffer( bars, counted, 0, signal_sma_period, buffer, signal_buffer ); for (int i = counted; i < bars; i++) { double d = buffer.Get(i) - signal_buffer.Get(i); if (d != 0.0) AddValue(fabs(d)); osma_buffer.Set(i, d); } double value_mul = 1.0 / (value_mean * 3.0); for (int i = counted; i < bars; i++) { double d = osma_buffer.Get(i) * value_mul; osma_buffer.Set(i, d); if (i == 0) continue; double prev = osma_buffer.Get(i-1); double diff = d - prev; if (diff != 0.0) AddDiff(fabs(diff)); diff_buffer.Set(i, diff); } double diff_mul = 1.0 / (diff_mean * 3.0); for (int i = counted; i < bars; i++) { double d = diff_buffer.Get(i) * diff_mul; diff_buffer.Set(i, d); } for (int i = counted; i < bars; i++) { osma_buffer.Set(i, Upp::max(-1.0, Upp::min(+1.0, osma_buffer.Get(i)))); diff_buffer.Set(i, Upp::max(-1.0, Upp::min(+1.0, diff_buffer.Get(i)))); } } RelativeStrengthIndex::RelativeStrengthIndex() { period = 32; } void RelativeStrengthIndex::Init() { SetCoreSeparateWindow(); SetCoreMinimum(-1); // normalized SetCoreMaximum(1); SetBufferColor(0, DodgerBlue); SetBufferColor(1, White()); SetBufferColor(2, White()); SetCoreLevelCount(2); SetCoreLevel(0, -0.4); // normalized SetCoreLevel(1, 0.4); SetCoreLevelsColor(Silver); SetCoreLevelsStyle(STYLE_DOT); if ( period < 1 ) throw ConfExc(); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0, "RSI"); } void RelativeStrengthIndex::Start() { Buffer& buffer = GetBuffer(0); Buffer& pos_buffer = GetBuffer(1); Buffer& neg_buffer = GetBuffer(2); LabelSignal& sig = GetLabelBuffer(0, 0); double diff; int bars = GetBars(); int counted = GetCounted(); if ( bars <= period ) throw DataExc(); int pos = counted - 1; if ( pos <= period ) { buffer.Set(0, 0.0); pos_buffer.Set(0, 0.0); neg_buffer.Set(0, 0.0); double sum_p = 0.0; double sum_n = 0.0; double prev_value = Open( 0 ); for (int i = 1; i <= period; i++) { SetSafetyLimit(i); double value = Open(i); if ( prev_value == 0 ) { prev_value = value; continue; } buffer.Set(i, 0.0); pos_buffer.Set(i, 0.0); neg_buffer.Set(i, 0.0); diff = value - prev_value; sum_p += ( diff > 0 ? diff : 0 ); sum_n += ( diff < 0 ? -diff : 0 ); prev_value = value; } pos_buffer.Set(period, sum_p / period); neg_buffer.Set(period, sum_n / period); buffer.Set(period, (1.0 - ( 1.0 / ( 1.0 + pos_buffer.Get(period) / neg_buffer.Get(period) ) )) * 100); pos = period + 1; } SetSafetyLimit(pos-1); double prev_value = Open(pos-1); for (int i = pos; i < bars; i++) { SetSafetyLimit(i); double value = Open(i); diff = value - prev_value; pos_buffer.Set(i, ( pos_buffer.Get(i - 1) * ( period - 1 ) + ( diff > 0.0 ? diff : 0.0 ) ) / period); neg_buffer.Set(i, ( neg_buffer.Get(i - 1) * ( period - 1 ) + ( diff < 0.0 ? -diff : 0.0 ) ) / period); double rsi = (1.0 - 1.0 / ( 1.0 + pos_buffer.Get(i) / neg_buffer.Get(i) )) * 100; rsi = (rsi * 0.01 - 0.5) * 2.0; // normalized buffer.Set(i, rsi); prev_value = value; sig.signal.Set(i, rsi < 0); // normalized } } RelativeVigorIndex::RelativeVigorIndex() { period = 10; } void RelativeVigorIndex::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Green); SetBufferColor(1, Red); SetBufferBegin ( 0, period + 3 ); SetBufferBegin ( 1, period + 7 ); SetBufferStyle(0,DRAW_LINE); SetBufferStyle(1,DRAW_LINE); SetBufferLabel(0,"RVI"); SetBufferLabel(1,"RVIS"); } void RelativeVigorIndex::Start() { Buffer& buffer = GetBuffer(0); Buffer& signal_buffer = GetBuffer(1); LabelSignal& sig = GetLabelBuffer(0, 0); double value_up, value_down, num, denum; int bars = GetBars(); int counted = GetCounted(); if ( bars <= period + 8 ) throw DataExc(); if ( counted < 0 ) throw DataExc(); if (counted < 4+period) counted = 4+period; //bars--; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); num = 0.0; denum = 0.0; for ( int j = i; j > i - period && j >= 0; j-- ) { double close0 = Open( j ); // peek is fixed at for loop double close1 = Open( j - 1 ); double close2 = Open( j - 2 ); double close3 = Open( j - 3 ); double open0 = Open ( j - 1 ); double open1 = Open ( j - 2 ); double open2 = Open ( j - 3 ); double open3 = Open ( j - 4 ); double high0 = High( j - 1 ); double high1 = High( j - 2 ); double high2 = High( j - 3 ); double high3 = High( j - 4 ); double low0 = Low( j - 1 ); double low1 = Low( j - 2 ); double low2 = Low( j - 3 ); double low3 = Low( j - 4 ); value_up = ( ( close0 - open0 ) + 2 * ( close1 - open1 ) + 2 * ( close2 - open2 ) + ( close3 - open3 ) ) / 6; value_down = ( ( high0 - low0 ) + 2 * ( high1 - low1 ) + 2 * ( high2 - low2 ) + ( high3 - low3 ) ) / 6; num += value_up; denum += value_down; } if ( denum != 0.0 ) buffer.Set(i, num / denum); else buffer.Set(i, num); } if ( counted < 8 ) counted = 8; for ( int i = counted; i < bars; i++) { double bufvalue = buffer.Get(i); double value = ( bufvalue + 2 * buffer.Get(i-1) + 2 * buffer.Get(i-2) + buffer.Get(i-3) ) / 6; signal_buffer.Set(i, value); sig.signal.Set(i, bufvalue < value); } } StochasticOscillator::StochasticOscillator() { k_period = 5; d_period = 3; slowing = 3; } void StochasticOscillator::Init() { SetCoreSeparateWindow(); SetCoreMinimum(-1); // normalized SetCoreMaximum(1); SetBufferColor(0, LightSeaGreen); SetBufferColor(1, Red); SetCoreLevelCount(2); SetCoreLevel(0, -0.6); // normalized SetCoreLevel(1, 0.6); SetCoreLevelsColor(Silver); SetCoreLevelsStyle(STYLE_DOT); SetBufferLabel( 0, "Main"); SetBufferLabel( 1, "Signal" ); SetBufferBegin(0, k_period + slowing - 2 ); SetBufferBegin(1, k_period + d_period ); SetBufferStyle(0, DRAW_LINE); SetBufferStyle(1, DRAW_LINE); SetBufferType(1, STYLE_DOT); } void StochasticOscillator::Start() { Buffer& buffer = GetBuffer(0); Buffer& signal_buffer = GetBuffer(1); Buffer& high_buffer = GetBuffer(2); Buffer& low_buffer = GetBuffer(3); LabelSignal& sig = GetLabelBuffer(0, 0); int start; int bars = GetBars(); int counted = GetCounted(); if ( bars <= k_period + d_period + slowing ) throw ConfExc(); start = k_period; if ( start + 1 < counted ) start = counted - 2; else { for (int i = 0; i < start; i++) { SetSafetyLimit(i); low_buffer.Set(i, 0.0); high_buffer.Set(i, 0.0); } } int low_length = k_period; int high_length = k_period; double dmin = 1000000.0; double dmax = -1000000.0; for (int i = start; i < bars; i++) { SetSafetyLimit(i); if (low_length >= k_period) { dmin = 1000000.0; for (int k = i - k_period; k < i; k++) { double low = Low( k ); if ( dmin > low ) dmin = low; } low_length = 0; } else { low_length++; double low = Low( i - 1 ); if ( dmin > low ) dmin = low; } if (high_length >= k_period) { dmax = -1000000.0; for (int k = i - k_period; k < i; k++) { double high = High( k ); if ( dmax < high ) dmax = high; } high_length = 0; } else { high_length++; double high = High( i - 1 ); if ( dmax < high ) dmax = high; } low_buffer.Set(i, dmin); high_buffer.Set(i, dmax); } start = k_period - 1 + slowing - 1; if ( start + 1 < counted ) start = counted - 2; else { for (int i = 0; i < start; i++) buffer.Set(i, 0.0); } //bars--; double sumlow = 0.0; double sumhigh = 0.0; for(int i = Upp::max(1, start - slowing); i < start; i++) { if (i <= 0) continue; SetSafetyLimit(i); double close = Open(i); double low = Upp::min(close, low_buffer.Get(i-1)); double high = Upp::max(close, high_buffer.Get(i-1)); sumlow += close - low; sumhigh += high - low; } for (int i = Upp::max(1, start); i < bars; i++) { SetSafetyLimit(i); int j = i - slowing; if (j > 0) { double close = Open(j); double low = Upp::min(close, low_buffer.Get(j-1)); double high = Upp::max(close, high_buffer.Get(j-1)); sumlow -= close - low; sumhigh -= high - low; } double close = Open(i); double low = Upp::min(close, low_buffer.Get(i-1)); double high = Upp::max(close, high_buffer.Get(i-1)); sumlow += close - low; sumhigh += high - low; double value = 1.0; if ( sumhigh != 0.0 ) value = sumlow / sumhigh * 100; value = (value * 0.01 - 0.5) * 2.0; // normalized buffer.Set(i, value); sig.signal.Set(i, value < 0); // normalized } start = d_period - 1; if ( start + 1 < counted ) start = counted - 2; else { for (int i = 0;i < start; i++) signal_buffer.Set(i, 0.0); } for (int i = start; i < bars; i++) { double sum = 0.0; for (int k = 0; k < d_period; k++ ) sum += buffer.Get(i - k); signal_buffer.Set(i, sum / d_period); } } WilliamsPercentRange::WilliamsPercentRange() { period = 14; } void WilliamsPercentRange::Init() { SetCoreSeparateWindow(); SetCoreMinimum(-100); SetCoreMaximum(0); SetBufferColor(0, DodgerBlue); SetCoreLevelCount(2); SetCoreLevel(0, -20); SetCoreLevel(1, -80); SetBufferBegin ( 0, period ); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0,"WPR"); } void WilliamsPercentRange::Start() { Buffer& buffer = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); if ( bars <= period ) throw DataExc(); if (!counted) { counted++; buffer.Set(0, 0); } //bars--; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); int highest = HighestHigh( period, i-1 ); int lowest = LowestLow( period, i-1 ); double max_high = High( highest ); double min_low = Low( lowest ); double close = Open( i ); double cur = -100 * ( max_high - close ) / ( max_high - min_low ); buffer.Set(i, cur); sig.signal.Set(i, cur < -50); } } AccumulationDistribution::AccumulationDistribution() { } void AccumulationDistribution::Init() { SetCoreSeparateWindow(); SetBufferColor(0, LightSeaGreen); SetBufferStyle(0,DRAW_LINE); } bool IsEqualDoubles ( double d1, double d2, double epsilon = 0.00001 ) { if ( epsilon < 0.0 ) epsilon = -epsilon; if ( epsilon > 0.1 ) epsilon = 0.00001; double diff = d1 - d2; if ( diff > epsilon || diff < -epsilon ) return ( false ); return ( true ); } void AccumulationDistribution::Start() { Buffer& buffer = GetBuffer(0); int bars = GetBars(); int counted = GetCounted(); if (!counted) { counted++; buffer.Set(0, 0); } //bars--; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double close = Open(i); buffer.Set(i, (close - Low(i-1)) - (High(i-1) - close)); if (buffer.Get(i) != 0.0) { double diff = High(i-1) - Low(i-1); if (diff < 0.000000001) buffer.Set(i, 0.0); else { buffer.Set(i, buffer.Get(i) / diff); buffer.Set(i, buffer.Get(i) * (double)Volume(i-1)); } } buffer.Set(i, buffer.Get(i) + buffer.Get(i-1)); } } MoneyFlowIndex::MoneyFlowIndex() { period = 14; } void MoneyFlowIndex::Init() { SetCoreSeparateWindow(); SetCoreMinimum(0); SetCoreMaximum(100); SetCoreLevelCount(2); SetCoreLevel(0, 20); SetCoreLevel(1, 80); SetBufferColor(0, Blue); SetBufferBegin ( 0, period ); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0,"MFI"); } void MoneyFlowIndex::Start() { Buffer& buffer = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); double pos_mf, neg_mf, cur_tp, prev_tp; int bars = GetBars(); int counted = GetCounted(); if ( bars <= period ) throw DataExc(); if (counted < period + 2) counted = period + 2; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); pos_mf = 0.0; neg_mf = 0.0; cur_tp = ( High(i-1) + Low(i-1) + Open(i) ) / 3; for (int j = 0; j < period; j++) { prev_tp = ( High(i-j-2) + Low(i-j-2) + Open(i-j-1) ) / 3; if ( cur_tp > prev_tp ) pos_mf += Volume(i-j-1) * cur_tp; else { if ( cur_tp < prev_tp ) neg_mf += Volume(i-j-1) * cur_tp; } cur_tp = prev_tp; } double value; if ( neg_mf != 0.0 ) value = 100 - 100 / ( 1 + pos_mf / neg_mf ); else value = 100; buffer.Set(i, value); sig.signal.Set(i, value < 50); } } ValueAndVolumeTrend::ValueAndVolumeTrend() { applied_value = 5; } void ValueAndVolumeTrend::Init() { SetCoreSeparateWindow(); SetBufferColor(0, DodgerBlue); SetBufferStyle(0, DRAW_LINE); } void ValueAndVolumeTrend::Start() { Buffer& buffer = GetBuffer(0); double cur_value, prev_value; int bars = GetBars(); int counted = GetCounted(); if ( counted > 0 ) counted--; if (counted < 2) counted = 2; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double volume = Volume(i-1); cur_value = GetAppliedValue ( applied_value, i - 1); prev_value = GetAppliedValue ( applied_value, i - 2 ); buffer.Set(i, buffer.Get(i-1) + volume * ( cur_value - prev_value ) / prev_value); } } OnBalanceVolume::OnBalanceVolume() { applied_value = 5; } void OnBalanceVolume::Init() { SetCoreSeparateWindow(); SetBufferColor(0, DodgerBlue); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0, "OBV"); } void OnBalanceVolume::Start() { Buffer& buffer = GetBuffer(0); int bars = GetBars(); int counted = GetCounted(); if ( counted > 0 ) counted--; if (counted < 2) counted = 2; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double cur_value = GetAppliedValue ( applied_value, i - 1); double prev_value = GetAppliedValue ( applied_value, i - 2); if ( cur_value == prev_value ) buffer.Set(i, buffer.Get(i)); else { if ( cur_value < prev_value ) buffer.Set(i, buffer.Get(i) - Volume(i - 1)); else buffer.Set(i, buffer.Get(i) + Volume(i - 1)); } } } Volumes::Volumes() { } void Volumes::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Green); SetBufferStyle(0, DRAW_HISTOGRAM); SetBufferLabel(0,"Volume"); } void Volumes::Start() { Buffer& buffer = GetBuffer(0); int bars = GetBars(); int counted = GetCounted(); if (!counted) counted++; else counted--; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); buffer.Set(i, Volume(i)); } } VolumeOscillator::VolumeOscillator() { } void VolumeOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Green); SetBufferLabel(0,"Volume"); SetCoreMinimum(0.0); SetCoreMaximum(1.0); SetCoreLevelCount(2); SetCoreLevel(0, 0.5); SetCoreLevel(1, 0.9); ec.SetSize(1440); } void VolumeOscillator::Start() { Buffer& buffer = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double vol = Volume(max(0, i - 1)); if (vol != 0 || !i) ec.Add(vol, vol); else { double vol = Volume(ec.GetLowest()); ec.Add(vol, vol); } int highest = ec.GetHighest(); int lowest = ec.GetLowest(); double high = Volume(highest); double low = Volume(lowest); vol = (vol - low) / (high - low); buffer.Set(i, vol); sig.enabled.Set(i, vol >= 0.9); } } SpeculationOscillator::SpeculationOscillator() { } void SpeculationOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Green); SetBufferLabel(0,"Volume"); //SetCoreMinimum(0.0); //SetCoreMaximum(1.0); SetCoreLevelCount(1); SetCoreLevel(0, 0); } void SpeculationOscillator::Start() { DataBridgeCommon& dbc = GetDataBridgeCommon(); const Index<Time>& idx = dbc.GetTimeIndex(GetTf()); Buffer& buffer = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); double point = GetDataBridge()->GetPoint(); int bars = GetBars(); int counted = GetCounted(); if (!counted) counted++; else counted--; double limit = 10.0 / 60.0 * GetMinutePeriod(); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double vol = Volume(i-1); Time t = idx[i]; int wday = DayOfWeek(t); double open = Open(i-1); double close = Open(i); double absch = fabs(open / close - 1); double volch = vol != 0.0 ? absch / vol : 0.0; if (vol >= limit && wday != 0 && i > counted && IsFin(volch)) { av.Add(volch); } double mean = av.GetMean(); double relch = mean != 0.0 ? volch / mean - 1.0: 0; buffer.Set(i, relch); if (relch > 0) { signal = close < open; } sig.signal.Set(i, signal); } } GlobalSpeculationOscillator::GlobalSpeculationOscillator() { } void GlobalSpeculationOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Green); SetCoreLevelCount(1); SetCoreLevel(0, 0); } void GlobalSpeculationOscillator::Start() { Buffer& buffer = GetBuffer(0); LabelSignal& sig0 = GetLabelBuffer(0, 0); LabelSignal& sig1 = GetLabelBuffer(0, 1); LabelSignal& sig2 = GetLabelBuffer(0, 2); double point = GetDataBridge()->GetPoint(); int bars = GetBars(); int counted = GetCounted(); if (!counted) counted++; Index<int> syms; for(int i = 0; i < CommonSpreads().GetCount(); i++) syms.Add(GetSystem().FindSymbol(CommonSpreads().GetKey(i))); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double sum = 0; for(int j = 0; j < syms.GetCount(); j++) { ConstBuffer& buf = GetInputBuffer(1, syms[j], GetTf(), 0); if (i < buf.GetCount()) sum += buf.Get(i); } buffer.Set(i, sum); var.Add(sum); double cdf = var.GetCDF(sum, false); bool is_enabled = cdf >= 0.975; sig0.enabled.Set(i, is_enabled); if (is_enabled && i > 0) { double close = Open(i); double open = Open(i-1); sig0.signal.Set(i, close < open); } is_enabled = cdf >= 0.875; sig1.enabled.Set(i, is_enabled); if (is_enabled && i > 0) { double close = Open(i); double open = Open(i-1); sig1.signal.Set(i, close < open); } is_enabled = cdf >= 0.775; sig2.enabled.Set(i, is_enabled); if (is_enabled && i > 0) { double close = Open(i); double open = Open(i-1); sig2.signal.Set(i, close < open); } } } SpeculationQuality::SpeculationQuality() { tfs.Add(0); tfs.Add(2); tfs.Add(4); tfs.Add(5); tfs.Add(6); } void SpeculationQuality::Init() { System& sys = GetSystem(); String sym = sys.GetSymbol(GetSymbol()); SetCoreSeparateWindow(); SetBufferColor(0, Green); SetCoreLevelCount(1); SetCoreLevel(0, 0.5); SetCoreMaximum(1.0); SetCoreMinimum(0.0); if (GetSymbol() < sys.GetNormalSymbolCount()) { String a = sym.Left(3); String b = sym.Mid(3,3); for(int i = 0; i < tfs.GetCount(); i++) { CoreList& cl = this->cl.Add(); cl.AddSymbol(a + "1"); cl.AddSymbol(b + "1"); cl.AddTf(tfs[i]); cl.AddIndi(System::Find<SpeculationOscillator>()); cl.Init(); } } } void SpeculationQuality::Start() { System& sys = GetSystem(); DataBridgeCommon& dbc = GetDataBridgeCommon(); const Index<Time>& idx = dbc.GetTimeIndex(GetTf()); Buffer& buffer = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); double point = GetDataBridge()->GetPoint(); int bars = GetBars(); int counted = GetCounted(); String sym = sys.GetSymbol(GetSymbol()); for(int i = 0; i < cl.GetCount(); i++) cl[i].Refresh(); double max_sum = 0.0; Vector<ConstLabelSignal*> sym_lbls, a_lbls, b_lbls; Vector<const Index<Time>* > tf_idxs; for(int i = 0; i < tfs.GetCount(); i++) { sym_lbls.Add(&CoreIO::GetInputLabel(1, GetSymbol(), tfs[i], 0)); double mult = 1.0 + 1.0 - (double)i / (double)tfs.GetCount(); max_sum += mult; tf_idxs.Add(&dbc.GetTimeIndex(tfs[i])); } if (GetSymbol() < sys.GetNormalSymbolCount()) { String a = sym.Left(3); String b = sym.Mid(3,3); int ai = sys.FindSymbol(a+"1"); int bi = sys.FindSymbol(b+"1"); if (ai >= 0 && bi >= 0) { for(int i = 0; i < tfs.GetCount(); i++) { //a_lbls.Add(&CoreIO::GetInputLabel(1, ai, tfs[i], 0)); //b_lbls.Add(&CoreIO::GetInputLabel(1, bi, tfs[i], 0)); a_lbls.Add(&cl[i].GetLabelSignal(0, 0, 0)); b_lbls.Add(&cl[i].GetLabelSignal(1, 0, 0)); double mult = 1.0 + 1.0 - (double)i / (double)tfs.GetCount(); max_sum += mult * 2; } } } int stat_min = bars * 0.9; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); Time t = idx[i]; double sum = 0.0; for(int j = 0; j < tfs.GetCount(); j++) { double mult = 1.0 + 1.0 - (double)j / (double)tfs.GetCount(); Time t2 = SyncTime(tfs[j], t); int pos = tf_idxs[j]->Find(t2); bool b = sym_lbls[j]->signal.Get(pos); sum += (b ? -1 : +1) * mult; if (!a_lbls.IsEmpty()) { bool av = a_lbls[j]->signal.Get(pos); bool bv = b_lbls[j]->signal.Get(pos); int ab = (av ? -1 : +1) + (bv ? +1 : -1); if (ab) sum += (ab < 0 ? -2 : +2) * mult; } } PosSigSum& pss = queue.Add(); pss.pos = i; pss.sig = sum < 0; pss.sum = fabs(sum) / max_sum * 100; ProcessQueue(); #if 0 double value = stats.GetAdd(pss.sum).GetMean(); buffer.Set(i, value); if (i >= stat_min) { var.Add(value); if (value >= 0.5) { sig.enabled.Set(i, var.GetCDF(value, false) >= 0.90); sig.signal.Set(i, pss.sig); } else { sig.enabled.Set(i, var.GetCDF(value, true) >= 0.90); sig.signal.Set(i, !pss.sig); } } else sig.enabled.Set(i, false); #else buffer.Set(i, pss.sum * 0.01); sig.signal.Set(i, pss.sig); #endif } } void SpeculationQuality::ProcessQueue() { ConstBuffer& open = GetInputBuffer(0, 0); double point = GetDataBridge()->GetPoint(); for(int i = 0; i < queue.GetCount(); i++) { const PosSigSum& pss = queue[i]; double o = open.Get(pss.pos); double hi = o + pips * point; double lo = o - pips * point; bool end_found = false; for(int j = pss.pos+1; j < open.GetCount(); j++) { double cur = open.Get(j); if (cur >= hi) { bool success = pss.sig == false; stats.GetAdd(pss.sum).Add(success); end_found = true; break; } else if (cur >= lo) { bool success = pss.sig == true; stats.GetAdd(pss.sum).Add(success); end_found = true; break; } } if (end_found) { queue.Remove(i); i--; } } } BuySellVolume::BuySellVolume() { } void BuySellVolume::Init() { SetCoreSeparateWindow(); SetBufferColor(2, Green); SetBufferStyle(2, DRAW_HISTOGRAM); SetBufferColor(1, Red); SetBufferStyle(1, DRAW_HISTOGRAM); SetBufferColor(0, Yellow); SetBufferStyle(0, DRAW_HISTOGRAM); } void BuySellVolume::Start() { DataBridgeCommon& dbc = GetDataBridgeCommon(); const Index<Time>& fast_idx = dbc.GetTimeIndex(0); const Index<Time>& idx = dbc.GetTimeIndex(GetTf()); Buffer& buy = GetBuffer(2); Buffer& sell = GetBuffer(1); Buffer& diff = GetBuffer(0); ConstBuffer& fast_open = GetInputBuffer(0, GetSymbol(), 0, 0); ConstBuffer& fast_vol = GetInputBuffer(0, GetSymbol(), 0, 3); ConstBuffer& open_buf = GetInputBuffer(0, 0); LabelSignal& sig = GetLabelBuffer(0, 0); Time prev_t(1970,1,1); int prev_j = -1; for (int i = fast_counted; i < fast_open.GetCount() - 1; i++) { Time fast_t = fast_idx[i]; Time t = SyncTime(GetTf(), fast_t); int j; if (prev_t == t) j = prev_j; else j = idx.Find(t); prev_j = j; prev_t = t; if (j == -1) continue; double open = fast_open.Get(i); double close = fast_open.Get(i+1); double vol = fast_vol.Get(i); if (open <= close) { buy.Inc(j, vol); } else { sell.Inc(j, -vol); } double d = buy.Get(j) + sell.Get(j); diff.Set(j, d); } fast_counted = fast_idx.GetCount() - 1; int counted = GetCounted(); int bars = GetBars(); if (!counted) counted++; for(int i = counted; i < bars; i++) { double prev_diff = diff.Get(i-1); bool prev_diff_sig = prev_diff < 0; double close = open_buf.Get(i); double open = open_buf.Get(i-1); bool prev_price_sig = close < open; sig.signal.Set(i, prev_price_sig); sig.enabled.Set(i, prev_price_sig != prev_diff_sig); } } #define PERIOD_FAST 5 #define PERIOD_SLOW 34 #undef DATA_LIMIT #define DATA_LIMIT 3 AcceleratorOscillator::AcceleratorOscillator() { } void AcceleratorOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Black); SetBufferColor(1, Green); SetBufferColor(2, Red); SetBufferStyle ( 0, DRAW_NONE ); SetBufferStyle ( 1, DRAW_HISTOGRAM ); SetBufferStyle ( 2, DRAW_HISTOGRAM ); SetBufferBegin ( 0, DATA_LIMIT ); SetBufferBegin ( 1, DATA_LIMIT ); SetBufferBegin ( 2, DATA_LIMIT ); AddSubCore<MovingAverage>().Set("period", PERIOD_FAST).Set("offset", 0).Set("method", MODE_SMA); AddSubCore<MovingAverage>().Set("period", PERIOD_SLOW).Set("offset", 0).Set("method", MODE_SMA); } void AcceleratorOscillator::Start() { Buffer& buffer = GetBuffer(0); Buffer& up_buffer = GetBuffer(1); Buffer& down_buffer = GetBuffer(2); Buffer& macd_buffer = GetBuffer(3); Buffer& signal_buffer = GetBuffer(4); LabelSignal& sig = GetLabelBuffer(0, 0); double prev = 0.0, current; int bars = GetBars(); int counted = GetCounted(); if ( bars <= DATA_LIMIT ) throw DataExc(); Buffer& ind1 = At(0).GetBuffer(0); Buffer& ind2 = At(1).GetBuffer(0); if ( counted > 0 ) { SetSafetyLimit(counted); counted--; prev = macd_buffer.Get(counted) - signal_buffer.Get(counted); } for (int i = counted; i < bars; i++) { SetSafetyLimit(i); macd_buffer.Set(i, ind1.Get(i) - ind2.Get(i)); } SimpleMAOnBuffer ( bars, counted, 0, 5, macd_buffer, signal_buffer ); bool up = true; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); current = macd_buffer.Get(i) - signal_buffer.Get(i); if ( current > prev ) up = true; if ( current < prev ) up = false; if ( !up ) { up_buffer.Set(i, 0.0); down_buffer.Set(i, current); } else { up_buffer.Set(i, current); down_buffer.Set(i, 0.0); } buffer.Set(i, current); sig.signal.Set(i, current < 0); prev = current; } } GatorOscillator::GatorOscillator() { jaws_period = 13; jaws_shift = 8; teeth_period = 8; teeth_shift = 5; lips_period = 5; lips_shift = 3; ma_method = 2; applied_value = PRICE_MEDIAN; } void GatorOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Black); SetBufferColor(1, Red); SetBufferColor(2, Green); SetBufferColor(3, Black); SetBufferColor(4, Red); SetBufferColor(5, Green); SetBufferBegin ( 1, jaws_period + jaws_shift - teeth_shift ); SetBufferBegin ( 2, jaws_period + jaws_shift - teeth_shift ); SetBufferBegin ( 4, teeth_period + teeth_shift - lips_shift ); SetBufferBegin ( 5, teeth_period + teeth_shift - lips_shift ); SetBufferShift ( 0, teeth_shift ); SetBufferShift ( 1, teeth_shift ); SetBufferShift ( 2, teeth_shift ); SetBufferShift ( 3, lips_shift ); SetBufferShift ( 4, lips_shift ); SetBufferShift ( 5, lips_shift ); AddSubCore<MovingAverage>().Set("period", teeth_period).Set("offset", teeth_shift - lips_shift).Set("method", ma_method); AddSubCore<MovingAverage>().Set("period", lips_period).Set("offset", 0).Set("method", ma_method); AddSubCore<MovingAverage>().Set("period", jaws_period).Set("offset", jaws_shift - teeth_shift).Set("method", ma_method); AddSubCore<MovingAverage>().Set("period", teeth_period).Set("offset", 0).Set("method", ma_method); SetBufferStyle(0,DRAW_NONE); SetBufferStyle(1,DRAW_HISTOGRAM); SetBufferStyle(2,DRAW_HISTOGRAM); SetBufferStyle(3,DRAW_NONE); SetBufferStyle(4,DRAW_HISTOGRAM); SetBufferStyle(5,DRAW_HISTOGRAM); SetBufferLabel(0,"GatorUp"); SetBufferLabel(1,NULL); SetBufferLabel(2,NULL); SetBufferLabel(3,"GatorDown"); SetBufferLabel(4,NULL); SetBufferLabel(5,NULL); } void GatorOscillator::Start() { Buffer& up_buffer = GetBuffer(0); Buffer& up_red_buffer = GetBuffer(1); Buffer& up_green_buffer = GetBuffer(2); Buffer& down_buffer = GetBuffer(3); Buffer& down_red_buffer = GetBuffer(4); Buffer& down_green_buffer = GetBuffer(5); double prev, current; int bars = GetBars(); int counted = GetCounted(); ConstBuffer& ind1 = At(0).GetBuffer(0); ConstBuffer& ind2 = At(1).GetBuffer(0); ConstBuffer& ind3 = At(2).GetBuffer(0); ConstBuffer& ind4 = At(3).GetBuffer(0); if ( counted <= teeth_period + teeth_shift - lips_shift ) counted = ( teeth_period + teeth_shift - lips_shift ); if (counted > 0) counted--; else counted++; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); current = ind1.Get(i) - ind2.Get(i); if ( current <= 0.0 ) down_buffer.Set(i, current); else down_buffer.Set(i, -current); } for (int i = counted; i < bars; i++) { SetSafetyLimit(i); prev = down_buffer.Get(i-1); current = down_buffer.Get(i); if ( current < prev ) { down_red_buffer.Set(i, 0.0); down_green_buffer.Set(i, current); } if ( current > prev ) { down_red_buffer.Set(i, current); down_green_buffer.Set(i, 0.0); } if ( current == prev ) { if ( down_red_buffer.Get(i-1) < 0.0 ) down_red_buffer.Set(i, current); else down_green_buffer.Set(i, current); } } counted = GetCounted(); if ( counted <= jaws_period + jaws_shift - teeth_shift ) counted = ( jaws_period + jaws_shift - teeth_shift ); if (counted > 1) counted--; else counted++; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); current = ind3.Get(i) - ind4.Get(i); if ( current >= 0.0 ) up_buffer.Set(i, current); else up_buffer.Set(i, -current); } for (int i = counted; i < bars; i++) { SetSafetyLimit(i); prev = up_buffer.Get(i-1); current = up_buffer.Get(i); if ( current > prev ) { up_red_buffer.Set(i, 0.0); up_green_buffer.Set(i, current); } if ( current < prev ) { up_red_buffer.Set(i, current); up_green_buffer.Set(i, 0.0); } if ( current == prev ) { if ( up_green_buffer.Get(i-1) > 0.0 ) up_green_buffer.Set(i, current); else up_red_buffer.Set(i, current); } } } #undef DATA_LIMIT #define PERIOD_FAST 5 #define PERIOD_SLOW 34 #define DATA_LIMIT 34 AwesomeOscillator::AwesomeOscillator() { } void AwesomeOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Black); SetBufferColor(1, Green); SetBufferColor(2, Red); SetBufferStyle ( 0, DRAW_NONE ); SetBufferStyle ( 1, DRAW_HISTOGRAM ); SetBufferStyle ( 2, DRAW_HISTOGRAM ); SetBufferBegin ( 0, DATA_LIMIT ); SetBufferBegin ( 1, DATA_LIMIT ); SetBufferBegin ( 2, DATA_LIMIT ); AddSubCore<MovingAverage>().Set("period", PERIOD_FAST).Set("offset", 0).Set("method", MODE_SMA); AddSubCore<MovingAverage>().Set("period", PERIOD_SLOW).Set("offset", 0).Set("method", MODE_SMA); } void AwesomeOscillator::Start() { Buffer& buffer = GetBuffer(0); Buffer& up_buffer = GetBuffer(1); Buffer& down_buffer = GetBuffer(2); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); double prev = 0.0, current; if ( bars <= DATA_LIMIT ) throw DataExc(); ConstBuffer& ind1 = At(0).GetBuffer(0); ConstBuffer& ind2 = At(1).GetBuffer(0); if (counted > 0) { counted--; SetSafetyLimit(counted); if (counted) prev = buffer.Get(counted - 1); } for (int i = counted; i < bars; i++) { SetSafetyLimit(i); buffer.Set(i, ind1.Get(i) - ind2.Get(i)); } bool up = true; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); current = buffer.Get(i); if ( current > prev ) up = true; if ( current < prev ) up = false; if ( !up ) { down_buffer.Set(i, current); up_buffer.Set(i, 0.0); } else { up_buffer.Set(i, current); down_buffer.Set(i, 0.0); } sig.signal.Set(i, current < 0); prev = current; } } Fractals::Fractals() { left_bars = 3; right_bars = 0; } void Fractals::Init() { SetCoreChartWindow(); SetBufferColor(0, Blue); SetBufferColor(1, Blue); SetBufferColor(2, Blue); SetBufferColor(3, Blue); SetBufferColor(4, Blue); SetBufferColor(5, Blue); SetBufferStyle(0, DRAW_LINE); SetBufferArrow(0, 158); SetBufferStyle(1, DRAW_LINE); SetBufferArrow(1, 158); SetBufferStyle(2, DRAW_ARROW); SetBufferArrow(2, 119); SetBufferStyle(3, DRAW_ARROW); SetBufferArrow(3, 119); SetBufferStyle(4, DRAW_ARROW); SetBufferArrow(4, 119); SetBufferStyle(5, DRAW_ARROW); SetBufferArrow(5, 119); } void Fractals::Start() { Buffer& line_up_buf1 = GetBuffer(0); Buffer& line_up_buf2 = GetBuffer(1); Buffer& arrow_up_buf = GetBuffer(2); Buffer& arrow_down_buf = GetBuffer(3); Buffer& arrow_breakup_buf = GetBuffer(4); Buffer& arrow_breakdown_buf = GetBuffer(5); int bars = GetBars(); int counted = GetCounted(); if(counted==0) counted = 1 + Upp::max(left_bars, right_bars); else counted--; SetSafetyLimit(counted); double prev_close = Open(counted); //bars--; for(int i = counted; i < bars; i++) { SetSafetyLimit(i); double close = Open(i); line_up_buf1.Set(i, IsFractalUp(i-1, left_bars, right_bars, bars)); if (line_up_buf1.Get(i) == 0) line_up_buf1.Set(i, line_up_buf1.Get(i-1)); else arrow_up_buf.Set(i, line_up_buf1.Get(i)); line_up_buf2.Set(i, IsFractalDown(i-1, left_bars, right_bars, bars)); if (line_up_buf2.Get(i) == 0) line_up_buf2.Set(i, line_up_buf2.Get(i-1)); else arrow_down_buf.Set(i, line_up_buf2.Get(i)); if (close < line_up_buf2.Get(i) && prev_close >= line_up_buf2.Get(i-1)) arrow_breakdown_buf.Set(i, close); prev_close = close; } } double Fractals::IsFractalUp(int index, int left, int right, int maxind) { double max = High(index); for(int i = index - left; i <= (index + right); i++) { if (i < 0 || i > maxind) return(0); double high = High(i); if(!(high > 0.0)) return(0); if (max < high && i != index) { if(max < high) return(0); if(abs(i - index) > 1) return(0); } } return(max); } double Fractals::IsFractalDown(int index, int left, int right, int maxind) { double min = Low(index); for(int i = index - left; i <= (index + right); i++) { if (i < 0 || i > maxind) return(0); double low = Low(i); if (!(low > 0.0)) return(0); if (min > low && i != index) { if(min > low) return(0); if(abs(i - index) > 1) return(0); } } return(min); } FractalOsc::FractalOsc() { left_bars = 3; right_bars = 0; smoothing_period = 12; } void FractalOsc::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Red); SetBufferColor(1, Blue); SetBufferStyle(0, DRAW_LINE); SetBufferStyle(1, DRAW_LINE); AddSubCore<Fractals>().Set("left_bars", left_bars).Set("right_bars", right_bars); } void FractalOsc::Start() { Buffer& buf = GetBuffer(0); Buffer& av = GetBuffer(1); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); if (counted > 0) counted--; else counted = 1 + Upp::max(left_bars,right_bars); ConstBuffer& ind1 = At(0).GetBuffer(0); ConstBuffer& ind2 = At(0).GetBuffer(1); //bars--; for(int i = counted; i < bars; i++) { SetSafetyLimit(i); double close = Open(i); double buf1 = ind1.Get(i); double buf2 = ind2.Get(i); double v = (close - buf2) / (buf1 - buf2); if ( v > 1) v = 1; else if ( v < 0) v = 0; double value = (v - 0.5) * 2.0; buf.Set(i, value); // normalized av.Set(i, SimpleMA( i, smoothing_period, buf )); sig.signal.Set(i, value < 0); } } MarketFacilitationIndex::MarketFacilitationIndex() { } void MarketFacilitationIndex::Init() { SetCoreSeparateWindow(); SetCoreLevelCount(2); SetCoreLevel(0, 20); SetCoreLevel(1, 80); SetBufferColor(0, Lime); SetBufferColor(1, SaddleBrown); SetBufferColor(2, Blue); SetBufferColor(3, Pink); SetBufferStyle ( 0, DRAW_HISTOGRAM ); SetBufferStyle ( 1, DRAW_HISTOGRAM ); SetBufferStyle ( 2, DRAW_HISTOGRAM ); SetBufferStyle ( 3, DRAW_HISTOGRAM ); SetBufferLabel ( 0, "MFI Up, Volume Up" ); SetBufferLabel ( 1, "MFI Down, Volume Down" ); SetBufferLabel ( 2, "MFI Up, Volume Down" ); SetBufferLabel ( 3, "MFI Down, Volume Up" ); } void MarketFacilitationIndex::Start() { Buffer& up_up_buffer = GetBuffer(0); Buffer& down_down_buffer = GetBuffer(1); Buffer& up_down_buffer = GetBuffer(2); Buffer& down_up_buffer = GetBuffer(3); Buffer& buffer = GetBuffer(4); bool mfi_up = true, vol_up = true; int bars = GetBars(); int counted = GetCounted(); if (counted > 0) counted--; else counted++; double point = 0.00001; if (GetSymbol() < GetMetaTrader().GetSymbolCount()) { const Symbol& sym = GetMetaTrader().GetSymbol(GetSymbol()); point = sym.point; } for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double volume = Volume(i-1); if ( IsEqualDoubles ( volume, 0.0 ) ) { if ( i == 0 ) buffer.Set(i, 0.0); else buffer.Set(i, buffer.Get(i-1)); } else buffer.Set(i, ( High(i-1) - Low(i-1) ) / ( volume * point )); } if ( counted > 1 ) { int i = counted -1; if ( up_up_buffer.Get(i) != 0.0 ) { mfi_up = true; vol_up = true; } if ( down_down_buffer.Get(i) != 0.0 ) { mfi_up = false; vol_up = false; } if ( up_down_buffer.Get(i) != 0.0 ) { mfi_up = true; vol_up = false; } if ( down_up_buffer.Get(i) != 0.0 ) { mfi_up = false; vol_up = true; } } double volume_prev; SetSafetyLimit(counted); if (counted > 0) volume_prev = Volume(counted-1); else { volume_prev = Volume(counted-1); counted++; } for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double volume = Volume(i-1); if ( i < bars - 1 ) { if ( buffer.Get(i) > buffer.Get(i-1) ) mfi_up = true; if ( buffer.Get(i) < buffer.Get(i-1) ) mfi_up = false; if ( volume > volume_prev ) vol_up = true; if ( volume < volume_prev ) vol_up = false; } if ( mfi_up && vol_up ) { up_up_buffer.Set(i, buffer.Get(i)); down_down_buffer.Set(i, 0.0); up_down_buffer.Set(i, 0.0); down_up_buffer.Set(i, 0.0); volume_prev = volume; continue; } if ( !mfi_up && !vol_up ) { up_up_buffer.Set(i, 0.0); down_down_buffer.Set(i, buffer.Get(i)); up_down_buffer.Set(i, 0.0); down_up_buffer.Set(i, 0.0); volume_prev = volume; continue; } if ( mfi_up && !vol_up ) { up_up_buffer.Set(i, 0.0); down_down_buffer.Set(i, 0.0); up_down_buffer.Set(i, buffer.Get(i)); down_up_buffer.Set(i, 0.0); volume_prev = volume; continue; } if ( !mfi_up && vol_up ) { up_up_buffer.Set(i, 0.0); down_down_buffer.Set(i, 0.0); up_down_buffer.Set(i, 0.0); down_up_buffer.Set(i, buffer.Get(i)); volume_prev = volume; continue; } volume_prev = volume; } } ZigZag::ZigZag() { input_depth = 12; // Depth input_deviation = 5; // Deviation input_backstep = 3; // Backstep extremum_level = 3; // recounting's depth of extremums } void ZigZag::Init() { SetCoreChartWindow(); SetBufferColor(0, Red()); SetBufferColor(1, Red()); if (input_backstep >= input_depth) { input_backstep = input_depth-1; } SetBufferStyle(0, DRAW_NONE); SetBufferStyle(1, DRAW_SECTION); } void ZigZag::Start() { Buffer& osc = GetBuffer(0); Buffer& keypoint_buffer = GetBuffer(1); Buffer& high_buffer = GetBuffer(2); Buffer& low_buffer = GetBuffer(3); int counter_z, whatlookfor = 0; int back, pos, lasthighpos = 0, lastlowpos = 0; double extremum; double curlow = 0.0, curhigh = 0.0, lasthigh = 0.0, lastlow = 0.0; int bars = GetBars(); int counted = GetCounted(); VectorBool& label = GetLabelBuffer(0,0).signal; label.SetCount(bars); if ( bars < input_depth || input_backstep >= input_depth ) throw DataExc(); if ( counted == 0 ) counted = input_backstep; else { int i = bars-1; counter_z = 0; SetSafetyLimit(i); while ( counter_z < extremum_level && i >= bars-100 && i >= 0 ) { if ( keypoint_buffer.Get(i) != 0.0 ) counter_z++; i--; } if (i < 0) i = 0; if ( counter_z == 0 ) counted = input_backstep; else { counted = i+1; if ( low_buffer.Get(i) != 0.0 ) { curlow = low_buffer.Get(i); whatlookfor = 1; } else { curhigh = high_buffer.Get(i); whatlookfor = -1; } for (int i = counted; i < bars; i++) { keypoint_buffer.Set(i, 0.0); low_buffer.Set(i, 0.0); high_buffer.Set(i, 0.0); } } } double point = 0.00001; if (GetSymbol() < GetMetaTrader().GetSymbolCount()) { const Symbol& sym = GetMetaTrader().GetSymbol(GetSymbol()); point = sym.point; } ExtremumCache ec(input_depth); int begin = Upp::max(0, counted - input_depth); ec.pos = begin - 1; for(int i = begin; i < counted; i++) { SetSafetyLimit(i+1); double low = Low(i); double high = High(i); ec.Add(low, high); } for (int i = counted; i < bars; i++) { SetSafetyLimit(i+1); // This indicator peeks anyway double low = Low(i); double high = High(i); ec.Add(low, high); int lowest = ec.GetLowest(); extremum = Low(lowest); if ( extremum == lastlow ) extremum = 0.0; else { lastlow = extremum; if ( low - extremum > input_deviation*point ) extremum = 0.0; else { for ( back = 1; back <= input_backstep; back++ ) { pos = i - back; if (pos < 0) pos = 0; if ( low_buffer.Get(pos) != 0 && low_buffer.Get(pos) > extremum ) low_buffer.Set(pos, 0.0); } } } if ( low == extremum ) low_buffer.Set(i, extremum); else low_buffer.Set(i, 0.0); int highest = ec.GetHighest(); extremum = High(highest); if ( extremum == lasthigh ) extremum = 0.0; else { lasthigh = extremum; if ( extremum - high > input_deviation*point ) extremum = 0.0; else { for ( back = 1; back <= input_backstep; back++ ) { pos = i - back; if (pos < 0) pos = 0; if ( high_buffer.Get(pos) != 0 && high_buffer.Get(pos) < extremum ) high_buffer.Set(pos, 0.0); } } } if ( high == extremum ) high_buffer.Set(i, extremum); else high_buffer.Set(i, 0.0); } if ( whatlookfor == 0 ) { lastlow = 0.0; lasthigh = 0.0; } else { lastlow = curlow; lasthigh = curhigh; } for (int i = counted; i < bars; i++) { SetSafetyLimit(i+1); // This indicator peeks anyway double low = Low(i); double high = High(i); osc.Set(i, whatlookfor); switch ( whatlookfor ) { case 0: // look for peak or lawn if ( lastlow == 0.0 && lasthigh == 0.0 ) { if ( high_buffer.Get(i) != 0.0 ) { lasthighpos = i; lasthigh = high_buffer.Get(lasthighpos); whatlookfor = -1; keypoint_buffer.Set(lasthighpos, lasthigh); } if ( low_buffer.Get(i) != 0.0 ) { lastlowpos = i; lastlow = low_buffer.Get(lastlowpos); whatlookfor = 1; keypoint_buffer.Set(lastlowpos, lastlow); } } break; case 1: // look for peak if ( low_buffer.Get(i) != 0.0 && low_buffer.Get(i) < lastlow && high_buffer.Get(i) == 0.0 ) { keypoint_buffer.Set(lastlowpos, 0.0); lastlowpos = i; lastlow = low_buffer.Get(lastlowpos); keypoint_buffer.Set(lastlowpos, lastlow); } if ( high_buffer.Get(i) != 0.0 && low_buffer.Get(i) == 0.0 ) { lasthighpos = i; lasthigh = high_buffer.Get(lasthighpos); keypoint_buffer.Set(lasthighpos, lasthigh); whatlookfor = -1; } break; case - 1: // look for lawn if ( high_buffer.Get(i) != 0.0 && high_buffer.Get(i) > lasthigh && low_buffer.Get(i) == 0.0 ) { keypoint_buffer.Set(lasthighpos, 0.0); lasthighpos = i; lasthigh = high_buffer.Get(lasthighpos); keypoint_buffer.Set(lasthighpos, lasthigh); } if ( low_buffer.Get(i) != 0.0 && high_buffer.Get(i) == 0.0 ) { lastlowpos = i; lastlow = low_buffer.Get(lastlowpos); keypoint_buffer.Set(lastlowpos, lastlow); whatlookfor = 1; } break; } } bool current = false; for (int i = counted-1; i >= 0; i--) { if (keypoint_buffer.Get(i) != 0.0) { current = high_buffer.Get(i) != 0.0; // going down after high break; } } if (!counted) counted++; for (int i = counted; i < bars; i++) { label.Set(i-1, current); if (keypoint_buffer.Get(i) != 0.0) { current = high_buffer.Get(i) != 0.0; // going down after high } } } ZigZagOsc::ZigZagOsc() { depth = 12; deviation = 5; backstep = 3; } void ZigZagOsc::Init() { SetCoreSeparateWindow(); SetBufferColor(0, GrayColor()); SetBufferStyle(0, DRAW_HISTOGRAM); AddSubCore<ZigZag>().Set("depth", depth).Set("deviation", deviation).Set("backstep", backstep); } void ZigZagOsc::Start() { Buffer& osc = GetBuffer(0); int bars = GetBars(); int counted = GetCounted(); ConstBuffer& ind1 = At(0).GetBuffer(0); ConstBuffer& ind2 = At(0).GetBuffer(1); double prev, next; bool has_prev = false, has_next = false;; int prev_pos, next_pos; if (counted) { counted = Upp::min(counted, GetBars()-1); for (; counted > 0; counted--) { double v = ind2.Get(counted); if (!v) continue; break; } } double diff, step; for (int i = counted; i < bars; i++) { SetSafetyLimit(i+1); // This indicator peeks anyway if (has_prev) { if (has_next && next_pos == i) { prev_pos = i; prev = next; has_next = false; } } else { double v = ind2.Get(i); if (v == 0) continue; has_prev = true; prev = v; prev_pos = i; } if (!has_next) { for (int j = i+1; j < bars; j++) { double v = ind2.Get(j); if (!v) continue; next = v; has_next = true; next_pos = j; break; } if (!has_next) break; diff = next - prev; step = diff / (prev_pos - next_pos); } double v = (i - prev_pos) * step + prev; double value_diff = GetAppliedValue(PRICE_TYPICAL, i) - v; osc.Set(i, value_diff); } } LinearTimeFrames::LinearTimeFrames() { } void LinearTimeFrames::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Red); SetBufferColor(1, Green); SetBufferColor(2, Blue); SetBufferColor(3, Yellow); SetBufferLineWidth(0, 3); SetBufferLineWidth(1, 2); SetBufferLineWidth(2, 1); SetCoreMinimum(0); SetCoreMaximum(1); } void LinearTimeFrames::Start() { ConstBuffer& src_time = GetInputBuffer(0,4); Buffer& day = GetBuffer(0); Buffer& month = GetBuffer(1); Buffer& year = GetBuffer(2); Buffer& week = GetBuffer(3); int bars = GetBars(); int counted = GetCounted(); System& base = GetSystem(); for(int i = counted; i < bars; i++) { SetSafetyLimit(i); Time t = Time(1970,1,1) + src_time.Get(i); double h = t.hour; double t1 = ((double)t.minute + h * 60.0 ) / (24.0 * 60.0); day.Set(i, t1); double days = GetDaysOfMonth(t.month, t.year); double wday = (DayOfWeek(t) + t1) / 7.0; week.Set(i, wday); double d = t.day + t1; double t2 = d / days; month.Set(i, t2); double m = t.month + t2; double t3 = m / 12.0; year.Set(i, t3); } } LinearWeekTime::LinearWeekTime() { } void LinearWeekTime::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Green); SetBufferLineWidth(0, 3); SetCoreMinimum(-1); SetCoreMaximum(+1); } void LinearWeekTime::Start() { ConstBuffer& src_time = GetInputBuffer(0,4); Buffer& week = GetBuffer(0); int bars = GetBars(); int counted = GetCounted(); System& base = GetSystem(); for(int i = counted; i < bars; i++) { SetSafetyLimit(i); Time t = Time(1970,1,1) + src_time.Get(i); double h = t.hour; double t1 = ((double)t.minute + h * 60.0 ) / (24.0 * 60.0); double days = GetDaysOfMonth(t.month, t.year); double wday = (DayOfWeek(t) + t1) / 7.0; week.Set(i, wday); } } SupportResistance::SupportResistance() { period = 300; max_crosses = 100; max_radius = 100; } void SupportResistance::Init() { SetCoreChartWindow(); SetBufferColor(0, Red); SetBufferColor(1, Green); } void SupportResistance::Start() { Buffer& support = GetBuffer(0); Buffer& resistance = GetBuffer(1); int bars = GetBars(); int counted = GetCounted(); double point = 0.00001; if (GetSymbol() < GetMetaTrader().GetSymbolCount()) { const Symbol& sym = GetMetaTrader().GetSymbol(GetSymbol()); point = sym.point; } ASSERT(point > 0); if (counted) counted--; else counted++; //bars--; Vector<int> crosses; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); int highest = HighestHigh(period, i-1); int lowest = LowestLow(period, i-1); double highesthigh = High(highest); double lowestlow = Low(lowest); int count = (int)((highesthigh - lowestlow) / point + 1); double inc = point; int inc_points = 1; while (count > 1000) { count /= 10; inc *= 10; inc_points *= 10; } if (count <= 0) continue; if (crosses.GetCount() < count) crosses.SetCount(count); for(int j = 0; j < count; j++) crosses[j] = 0; for(int j = i - period; j < i ; j++) { if (j < 0) continue; double high = High(j); double low = Low(j); int low_pos = (int)((low - lowestlow) / inc); int high_pos = (int)((high - lowestlow) / inc); if (high_pos >= count) high_pos = count - 1; for(int k = low_pos; k <= high_pos; k++) { crosses[k]++; } } double close = Open(i); int value_pos = (int)((close - lowestlow) / inc); if (value_pos >= count) value_pos = count - 1; if (value_pos < 0) value_pos = 0; // Find support int max = 0; int max_pos = value_pos; int max_cross_count = crosses[value_pos]; for(int j = value_pos - 1; j >= 0; j--) { int cross_count = crosses[j]; if (cross_count > max) { max = cross_count; max_pos = j; max_cross_count = cross_count; } int pos_diff = max_pos - j; if (pos_diff > max_radius) break; if (cross_count < max_cross_count - max_crosses) break; } support.Set(i, lowestlow + max_pos * inc); // Find resistance max = 0; max_pos = value_pos; max_cross_count = crosses[value_pos]; for(int j = value_pos + 1; j < count; j++) { int cross_count = crosses[j]; if (cross_count > max) { max = cross_count; max_pos = j; max_cross_count = cross_count; } int pos_diff = j - max_pos; if (pos_diff > max_radius) break; if (cross_count < max_cross_count - max_crosses) break; } resistance.Set(i, lowestlow + max_pos * inc); } } SupportResistanceOscillator::SupportResistanceOscillator() { period = 300; max_crosses = 100; max_radius = 100; smoothing_period = 30; } void SupportResistanceOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Green); SetBufferColor(1, Red); SetCoreMinimum(-1); SetCoreMaximum(1); AddSubCore<SupportResistance>().Set("period", period).Set("max_crosses", max_crosses).Set("max_radius", max_radius); } void SupportResistanceOscillator::Start() { Buffer& osc_av = GetBuffer(0); Buffer& osc = GetBuffer(1); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); ConstBuffer& ind1 = At(0).GetBuffer(0); ConstBuffer& ind2 = At(0).GetBuffer(1); RefreshSubCores(); int prev_pos = counted ? counted-1 : 0; SetSafetyLimit(counted-1); double prev_value = counted ? osc_av.Get(counted-1) : 0; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double applied_value = Open(i); double s = ind1.Get(i); double r = ind2.Get(i); double range = r - s; double value = (applied_value - s) / range * 2 - 1; if (value > 1) value = 1; if (value < -1) value = -1; osc.Set(i, value); sig.signal.Set(i, value < 0); value = ExponentialMA( i, smoothing_period, prev_value, osc ); osc_av.Set(i, value); prev_pos = i; prev_value = value; } } ChannelOscillator::ChannelOscillator() { period = 300; } void ChannelOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Red); SetCoreMinimum(-1); SetCoreMaximum(1); } void ChannelOscillator::Start() { Buffer& osc = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); ec.SetSize(period); SetSafetyLimit(counted-1); for (int i = ec.pos+1; i < bars; i++) { SetSafetyLimit(i); double open = Open(i); double low = i > 0 ? Low(i-1) : open; double high = i > 0 ? High(i-1) : open; double max = Upp::max(open, high); double min = Upp::min(open, low); ec.Add(max, min); double ch_high = High(ec.GetHighest()); double ch_low = Low(ec.GetLowest()); double ch_diff = ch_high - ch_low; double value = (open - ch_low) / ch_diff * 2.0 - 1.0; osc.Set(i, value); sig.signal.Set(i, value < 0); } } ScissorChannelOscillator::ScissorChannelOscillator() { period = 30; } void ScissorChannelOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Red); SetCoreMinimum(-1); SetCoreMaximum(1); } void ScissorChannelOscillator::Start() { Buffer& osc = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); ec.SetSize(period); SetSafetyLimit(counted-1); for (int i = ec.pos+1; i < bars; i++) { SetSafetyLimit(i); double open = Open(i); double low = i > 0 ? Low(i-1) : open; double high = i > 0 ? High(i-1) : open; double max = Upp::max(open, high); double min = Upp::min(open, low); ec.Add(max, min); int high_pos = ec.GetHighest(); int low_pos = ec.GetLowest(); double ch_high = High(high_pos); double ch_low = Low(low_pos); double ch_diff = ch_high - ch_low; double highest_change = DBL_MAX; int highest_change_pos = 0; double lowest_change = DBL_MAX; int lowest_change_pos = 0; for(int j = Upp::min(high_pos+1, low_pos+1); j <= i; j++) { double open = Open(j); if (j >= high_pos) { int dist = j - high_pos; double change = ch_high - open; double av_change = change / dist; if (av_change < highest_change) { highest_change = av_change; highest_change_pos = j; } } if (j >= low_pos) { int dist = j - low_pos; double change = open - ch_low; double av_change = change / dist; if (av_change < lowest_change) { lowest_change = av_change; lowest_change_pos = j; } } } int high_dist = i - high_pos; double high_limit = ch_high - high_dist * highest_change; int low_dist = i - low_pos; double low_limit = ch_low + low_dist * lowest_change; double limit_diff = high_limit - low_limit; double value = (open - low_limit) / limit_diff * 2.0 - 1.0; if (!IsFin(value)) value = 0.0; osc.Set(i, value); sig.signal.Set(i, value < 0); } } Psychological::Psychological() { period = 25; } void Psychological::Init() { SetCoreSeparateWindow(); SetBufferColor(0, DodgerBlue()); SetBufferStyle(0, DRAW_LINE); SetBufferBegin(0, period); SetBufferLabel(0, "Psychological"); } void Psychological::Start() { Buffer& buf = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); if(counted < 0) throw DataExc(); if(counted > 0) counted--; if (bars < period) throw DataExc(); if (counted == 0) counted = (1 + period + 1); //bars--; for(int i = counted; i < bars; i++) { SetSafetyLimit(i); int count=0; for (int j=i-period+1; j <= i; j++) { if (Open(j) > Open(j-1)) { count++; } } if (Open(i) > Open(i-1)) { count++; } if (Open(i-period) > Open(i-period-1)) { count--; } double value = ((double)count / period) *100.0; buf.Set(i, value); sig.signal.Set(i, value < 50); } } TrendChange::TrendChange() { period = 13; method = 0; SetCoreSeparateWindow(); } void TrendChange::Init() { int draw_begin; if (period < 2) period = 13; draw_begin = period - 1; SetBufferColor(0, Red()); SetBufferBegin(0, draw_begin ); AddSubCore<MovingAverage>().Set("period", period).Set("method", method); SetCoreLevelCount(1); SetCoreLevel(0, 0); SetCoreLevelsColor(GrayColor(192)); SetCoreLevelsStyle(STYLE_DOT); } void TrendChange::Start() { Buffer& buffer = GetBuffer(0); int bars = GetBars(); if ( bars <= period ) throw DataExc(); int counted = GetCounted(); if ( counted < 0 ) throw DataExc(); if ( counted > 0 ) counted--; // The newest part can't be evaluated. Only after 'shift' amount of time. int shift = period / 2; counted = Upp::max(0, counted - shift); //bars -= shift; // Calculate averages ConstBuffer& dbl = At(0).GetBuffer(0); // Prepare values for loop SetSafetyLimit(counted); double prev1 = dbl.Get(Upp::max(0, counted-1)); double prev2 = dbl.Get(Upp::max(0, counted-1+shift)); double prev_value = counted > 0 ? buffer.Get(counted-1) : 0; double prev_diff = counted > 1 ? prev_value - buffer.Get(counted-2) : 0; // Loop unprocessed range of time for(int i = counted; i < bars-shift; i++) { SetSafetyLimit(i); // Calculate values double d1 = dbl.Get(i); double d2 = dbl.Get(i+shift); double diff1 = d1 - prev1; double diff2 = d2 - prev2; double value = diff1 * diff2; double diff = value - prev_value; // Set value buffer.Set(i, value); // Store values for next snapation prev1 = d1; prev2 = d2; prev_value = value; prev_diff = diff; } } TrendChangeEdge::TrendChangeEdge() { period = 13; method = 0; slowing = 54; SetCoreSeparateWindow(); } void TrendChangeEdge::Init() { int draw_begin; if (period < 2) period = 13; draw_begin = period - 1; SetBufferColor(0, Red()); SetBufferBegin(0, draw_begin ); AddSubCore<MovingAverage>().Set("period", period).Set("method", method); AddSubCore<MovingAverage>().Set("period", slowing).Set("method", method).Set("offset", -slowing/2); } void TrendChangeEdge::Start() { Buffer& buffer = GetBuffer(0); Buffer& edge = GetBuffer(1); Buffer& symlr = GetBuffer(2); int bars = GetBars(); if ( bars <= period ) throw DataExc(); int counted = GetCounted(); if ( counted < 0 ) throw DataExc(); if ( counted > 0 ) counted-=3; // The newest part can't be evaluated. Only after 'shift' amount of time. int shift = period / 2; counted = Upp::max(0, counted - shift); // Refresh source data Core& cont = At(0); Core& slowcont = At(1); cont.Refresh(); slowcont.Refresh(); // Prepare values for looping ConstBuffer& dbl = cont.GetBuffer(0); ConstBuffer& slow_dbl = slowcont.GetBuffer(0); double prev_slow = slow_dbl.Get(Upp::max(0, counted-1)); double prev1 = dbl.Get(Upp::max(0, counted-1)) - prev_slow; double prev2 = dbl.Get(Upp::max(0, counted-1+shift)) - prev_slow; // Calculate 'TrendChange' data locally. See info for that. for(int i = counted; i < bars-shift; i++) { SetSafetyLimit(i); double slow = slow_dbl.Get(i); double d1 = dbl.Get(i) - slow; double d2 = dbl.Get(i+shift) - slow; double diff1 = d1 - prev1; double diff2 = d2 - prev2; double r1 = diff1 * diff2; symlr.Set(i, r1); prev1 = d1; prev2 = d2; } // Loop unprocessed area for(int i = Upp::max(2, counted); i < bars - 2; i++) { SetSafetyLimit(i + 2); // Finds local maximum value for constant range. TODO: optimize double high = 0; int high_pos = -1; for(int j = 0; j < period; j++) { int pos = i - j; if (pos < 0) continue; double d = fabs(symlr.Get(pos)); if (d > high) { high = d; high_pos = pos; } } double mul = high_pos == -1 ? 0 : (high - fabs(symlr.Get(i) - 0.0)) / high; // Calculates edge filter value double edge_value = 1.0 * symlr.Get(i-2) + 2.0 * symlr.Get(i-1) + -2.0 * symlr.Get(i+1) + -1.0 * symlr.Get(i+2); // Store value edge.Set(i, edge_value); double d = Upp::max(0.0, edge_value * mul); ASSERT(IsFin(d)); buffer.Set(i, d); } } PeriodicalChange::PeriodicalChange() { } void PeriodicalChange::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Red); SetCoreLevelCount(1); SetCoreLevel(0, 0.0); tfmin = GetMinutePeriod(); int w1 = 7 * 24 * 60; int count = 0; split_type = 0; if (GetTf() >= PHASETF) {count = 7; split_type = 1;} else if (tfmin >= w1) {count = 4; split_type = 2;} else if (tfmin >= 24 * 60) {count = 7; split_type = 1;} else {count = 7 * 24 * 60 / tfmin; split_type = 0;} means.SetCount(count, 0.0); counts.SetCount(count, 0); } void PeriodicalChange::Start() { System& sys = GetSystem(); ConstBuffer& src = GetInputBuffer(0, 0); ConstBuffer& src_time = GetInputBuffer(0,4); Buffer& dst = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars() - 1; int counted = GetCounted(); for(int i = counted; i < bars; i++) { SetSafetyLimit(i+1); double prev = src.Get(i); if (prev == 0.0) continue; double change = src.Get(i+1) / prev - 1.0; if (!IsFin(change)) continue; Time t = Time(1970,1,1) + src_time.Get(i); if (split_type == 0) { int wday = DayOfWeek(t); int wdaymin = (wday * 24 + t.hour) * 60 + t.minute; int avpos = wdaymin / tfmin; Add(avpos, change); } else if (split_type == 1) { int wday = DayOfWeek(t); Add(wday, change); } else if (split_type == 3) { int pos = i % this->means.GetCount(); Add(pos, change); } else { int pos = (DayOfYear(t) % (7 * 4)) / 7; Add(pos, change); } } if (counted) counted--; bars++; for(int i = counted; i < bars; i++) { SetSafetyLimit(i); Time t = Time(1970,1,1) + src_time.Get(i); double av_change = 0; if (split_type == 0) { int wday = DayOfWeek(t); int wdaymin = (wday * 24 + t.hour) * 60 + t.minute; int avpos = wdaymin / tfmin; av_change = means[avpos]; } else if (split_type == 1) { int wday = DayOfWeek(t); av_change = means[wday]; } else if (split_type == 3) { int pos = i % this->means.GetCount(); av_change = means[pos]; } else { int pos = (DayOfYear(t) % (7 * 4)) / 7; av_change = means[pos]; } dst.Set(i, av_change); sig.signal.Set(i, av_change < 0); } } VolatilityAverage::VolatilityAverage() { period = 10; } void VolatilityAverage::Init() { SetCoreSeparateWindow(); SetCoreMinimum(-1.0); SetCoreMaximum(+1.0); SetBufferColor(0, Color(85, 255, 150)); SetBufferLineWidth(0, 2); SetCoreLevelCount(2); SetCoreLevel(0, +0.5); SetCoreLevel(1, -0.5); SetCoreLevelsColor(Silver); SetCoreLevelsStyle(STYLE_DOT); } void VolatilityAverage::Start() { System& sys = GetSystem(); ConstBuffer& low = GetInputBuffer(0, 1); ConstBuffer& high = GetInputBuffer(0, 2); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); if (counted >= bars) return; if (!counted) counted++; Buffer& dst = GetBuffer(0); double sum = 0.0; SetSafetyLimit(counted); for(int i = Upp::max(1, counted - period); i < counted; i++) { double change = fabs(high.Get(i) / low.Get(i-1) - 1.0); sum += change; } for(int i = counted; i < bars; i++) { SetSafetyLimit(i+1); // Add current double change = fabs(high.Get(i) / low.Get(i-1) - 1.0); sum += change; // Subtract int j = i - period; if (j > 0) { double prev_change = fabs(high.Get(j) / low.Get(j-1) - 1.0); sum -= prev_change; } double average = sum / period; int av = average * 100000; stats.GetAdd(av,0)++; dst.Set(i, average); } SortByKey(stats, StdLess<int>()); stats_limit.SetCount(stats.GetCount()); int64 total = 0; for(int i = 0; i < stats.GetCount(); i++) { stats_limit[i] = total; total += stats[i]; } for(int i = counted; i < bars; i++) { SetSafetyLimit(i+1); double average = dst.Get(i); int av = average * 100000; double j = stats_limit[stats.Find(av)]; double sens = j / total * 2.0 - 1.0; dst.Set(i, sens); sig.enabled.Set(i, sens >= 0.5); } } MinimalLabel::MinimalLabel() { } void MinimalLabel::Init() { SetCoreChartWindow(); SetBufferColor(0, Color(85, 255, 150)); SetBufferStyle(0, DRAW_ARROW); SetBufferArrow(0, 159); } void MinimalLabel::Start() { int bars = GetBars(); int symbol = GetSymbol(); int tf = GetTf(); DataBridge* db = dynamic_cast<DataBridge*>(GetInputCore(0, symbol, tf)); ConstBuffer& open_buf = GetInputBuffer(0, 0); double spread_point = db->GetPoint(); double cost = spread_point * (1 + cost_level); ASSERT(spread_point > 0.0); VectorBool& labelvec = GetLabelBuffer(0,0).signal; labelvec.SetCount(bars); Buffer& buf = GetBuffer(0); for(int i = prev_counted; i < bars; i++) { SetSafetyLimit(i); double open = open_buf.GetUnsafe(i); double close = open; int j = i + 1; bool can_break = false; bool break_label; double prev = open; bool clean_break = false; for(; j < bars; j++) { close = open_buf.GetUnsafe(j); if (!can_break) { double abs_diff = fabs(close - open); if (abs_diff >= cost) { break_label = close < open; can_break = true; } } else { bool change_label = close < prev; if (change_label != break_label) { clean_break = true; j--; break; } } prev = close; } bool label = close < open; for(int k = i; k < j; k++) { SetSafetyLimit(k); open = open_buf.GetUnsafe(k); labelvec.Set(k, label); if (label) buf.Set(k, open - 10 * spread_point); else buf.Set(k, open + 10 * spread_point); } if (clean_break) prev_counted = i; i = j - 1; } } VolatilitySlots::VolatilitySlots() { } void VolatilitySlots::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Color(113, 42, 150)); SetBufferStyle(0, DRAW_LINE); int tf_mins = GetMinutePeriod(); if (tf_mins < 10080) slot_count = (5 * 24 * 60) / tf_mins; else slot_count = 1; if (GetTf() >= PHASETF) {slot_count = 7;} stats.SetCount(slot_count); } void VolatilitySlots::Start() { Buffer& buffer = GetBuffer(0); ConstBuffer& open_buf = GetInputBuffer(0, 0); ConstBuffer& time_buf = GetInputBuffer(0, 4); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); if (counted == 0) counted++; int tf_mins = GetMinutePeriod(); for(int i = counted; i < bars; i++) { { Time t = Time(1970,1,1) + time_buf.Get(i-1); int wday = DayOfWeek(t); int slot_id; if (GetTf() < PHASETF) slot_id = ((wday - 1) * 24 * 60 + t.hour * 60 + t.minute) / tf_mins; else slot_id = wday - 1; double cur = open_buf.Get(i); double prev = open_buf.Get(i-1); double change = fabs(cur / prev - 1.0); if (slot_id >= 0 && slot_id < stats.GetCount()) { OnlineVariance& av = stats[slot_id]; av.Add(change); total.Add(change); } } bool enabled = false; { Time t = Time(1970,1,1) + time_buf.Get(i); int wday = DayOfWeek(t); int slot_id; if (GetTf() < PHASETF) slot_id = ((wday - 1) * 24 * 60 + t.hour * 60 + t.minute) / tf_mins; else slot_id = wday - 1; if (slot_id >= 0 && slot_id < stats.GetCount()) { slot_id = (slot_id + shift) % stats.GetCount(); OnlineVariance& av = stats[slot_id]; double mean = av.GetMean(); buffer.Set(i, mean); enabled = total.GetCDF(mean, false) >= 0.75; } } sig.enabled.Set(i, enabled); } } VolumeSlots::VolumeSlots() { } void VolumeSlots::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Color(113, 42, 150)); SetBufferStyle(0, DRAW_LINE); SetCoreLevelCount(3); SetCoreLevel(0, 0.0002); SetCoreLevel(1, 0.001); SetCoreLevel(2, 0.010); SetCoreLevelsColor(Silver); SetCoreLevelsStyle(STYLE_DOT); int tf_mins = GetMinutePeriod(); if (tf_mins < 10080) slot_count = (5 * 24 * 60) / tf_mins; else slot_count = 1; if (GetTf() >= PHASETF) {slot_count = 7;} stats.SetCount(slot_count); } void VolumeSlots::Start() { Buffer& buffer = GetBuffer(0); ConstBuffer& vol_buf = GetInputBuffer(0, 3); ConstBuffer& time_buf = GetInputBuffer(0, 4); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); int tf_mins = GetMinutePeriod(); if (counted == 0) counted++; for(int i = counted; i < bars; i++) { SetSafetyLimit(i); { Time t = Time(1970,1,1) + time_buf.Get(i-1); int wday = DayOfWeek(t); int slot_id; if (GetTf() < PHASETF) slot_id = ((wday - 1) * 24 * 60 + t.hour * 60 + t.minute) / tf_mins; else slot_id = wday - 1; double vol = vol_buf.Get(i-1); if (slot_id >= 0 && slot_id < stats.GetCount()) { OnlineVariance& av = stats[slot_id]; if (vol != 0.0) { av.Add(vol); total.Add(vol); } } } bool enabled = false; { Time t = Time(1970,1,1) + time_buf.Get(i); int wday = DayOfWeek(t); int slot_id; if (GetTf() < PHASETF) slot_id = ((wday - 1) * 24 * 60 + t.hour * 60 + t.minute) / tf_mins; else slot_id = wday - 1; if (slot_id >= 0 && slot_id < stats.GetCount()) { slot_id = (slot_id + shift) % stats.GetCount(); OnlineVariance& av = stats[slot_id]; double mean = av.GetMean(); buffer.Set(i, mean); enabled = total.GetCDF(mean, false) >= 0.75; } } sig.enabled.Set(i, enabled); } } TrendIndex::TrendIndex() { } void TrendIndex::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Blue); SetBufferColor(1, Green); SetBufferColor(2, Red); if ( period < 1 ) throw ConfExc(); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0, "TrendIndex"); } void TrendIndex::Start() { Buffer& buffer = GetBuffer(0); Buffer& err_buffer = GetBuffer(1); Buffer& change_buf = GetBuffer(2); ConstBuffer& open_buf = GetInputBuffer(0, 0); double diff; int bars = GetBars(); int counted = GetCounted(); if ( bars <= period ) throw DataExc(); VectorBool& label = GetLabelBuffer(0,0).signal; label.SetCount(bars); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); bool bit_value; double err, av_change, buf_value; Process(open_buf, i, period, err_div, err, buf_value, av_change, bit_value); err_buffer.Set(i, err); buffer.Set(i, buf_value); change_buf.Set(i, av_change); label.Set(i, bit_value); } int true_count = 0; for (int i = 0; i < bars; i++) { if (label.Get(i)) true_count++; } ASSERT(true_count > 0); } void TrendIndex::Process(ConstBuffer& open_buf, int i, int period, int err_div, double& err, double& buf_value, double& av_change, bool& bit_value) { double current = open_buf.GetUnsafe(i); int trend_begin_pos = Upp::max(0, i - period); double begin = open_buf.GetUnsafe(trend_begin_pos); int len = (i - trend_begin_pos); if (len <= 0) return; av_change = fabs(current - begin) / len; err = 0; for(int j = trend_begin_pos; j < i; j++) { double change = open_buf.GetUnsafe(j+1) - open_buf.GetUnsafe(j); double diff = change - av_change; err += fabs(diff); } err /= len; err /= err_div; buf_value = av_change - err; bit_value = begin > current; } OnlineMinimalLabel::OnlineMinimalLabel() { } void OnlineMinimalLabel::Init() { SetCoreChartWindow(); } void OnlineMinimalLabel::Start() { int bars = GetBars(); int symbol = GetSymbol(); int tf = GetTf(); DataBridge* db = dynamic_cast<DataBridge*>(GetInputCore(0, symbol, tf)); ConstBuffer& open_buf = GetInputBuffer(0, 0); double spread = db->GetSpread(); double point = db->GetPoint(); double cost = spread + point * cost_level; if (cost <= 0.0) cost = point; VectorBool& labelvec = GetLabelBuffer(0,0).signal; for(int i = GetCounted(); i < bars; i++) { SetSafetyLimit(i); const int count = 1; bool sigbuf[count]; int begin = Upp::max(0, i - 100); int end = i + 1; GetMinimalSignal(cost, open_buf, begin, end, sigbuf, count); bool label = sigbuf[count - 1]; labelvec.Set(i, label); } } void OnlineMinimalLabel::GetMinimalSignal(double cost, ConstBuffer& open_buf, int begin, int end, bool* sigbuf, int sigbuf_size) { int write_begin = end - sigbuf_size; for(int i = begin; i < end; i++) { double open = open_buf.GetUnsafe(i); double close = open; for (int j = i-1; j >= begin; j--) { open = open_buf.GetUnsafe(j); double abs_diff = fabs(close - open); if (abs_diff >= cost) { break; } } bool label = close < open; int buf_pos = i - write_begin; if (buf_pos >= 0) sigbuf[buf_pos] = label; } } SelectiveMinimalLabel::SelectiveMinimalLabel() { } void SelectiveMinimalLabel::Init() { SetCoreChartWindow(); SetBufferColor(0, Color(85, 255, 150)); SetBufferStyle(0, DRAW_ARROW); SetBufferArrow(0, 159); } void SelectiveMinimalLabel::Start() { int bars = GetBars(); int symbol = GetSymbol(); int tf = GetTf(); // Too heavy to calculate every time and too useless if (GetCounted()) return; VectorMap<int, Order> orders; DataBridge* db = dynamic_cast<DataBridge*>(GetInputCore(0, symbol, tf)); ConstBuffer& open_buf = GetInputBuffer(0, 0); double spread_point = db->GetPoint(); double cost = spread_point * (1 + cost_level); ASSERT(spread_point > 0.0); VectorBool& labelvec = GetLabelBuffer(0,0).signal; VectorBool& enabledvec = GetLabelBuffer(0,0).enabled; labelvec.SetCount(bars); enabledvec.SetCount(bars); Buffer& buf = GetBuffer(0); bars--; for(int i = 0; i < bars; i++) { SetSafetyLimit(i); double open = open_buf.GetUnsafe(i); double close = open; int j = i + 1; bool can_break = false; bool break_label; double prev = open; for(; j < bars; j++) { close = open_buf.GetUnsafe(j); if (!can_break) { double abs_diff = fabs(close - open); if (abs_diff >= cost) { break_label = close < open; can_break = true; } } else { bool change_label = close < prev; if (change_label != break_label) { j--; break; } } prev = close; } bool label = close < open; for(int k = i; k < j; k++) { SetSafetyLimit(k); labelvec.Set(k, label); } i = j - 1; } bool prev_label = labelvec.Get(0); int prev_switch = 0; for(int i = 1; i < bars; i++) { bool label = labelvec.Get(i); int len = i - prev_switch; if (label != prev_label) { Order& o = orders.Add(i); o.label = prev_label; o.start = prev_switch; o.stop = i; o.len = o.stop - o.start; double open = open_buf.GetUnsafe(o.start); double close = open_buf.GetUnsafe(o.stop); o.av_change = fabs(close - open) / len; double err = 0; for(int k = o.start; k < o.stop; k++) { SetSafetyLimit(k); double diff = open_buf.GetUnsafe(k+1) - open_buf.GetUnsafe(k); err += fabs(diff); } o.err = err / len; prev_switch = i; prev_label = label; } } struct ChangeSorter { bool operator ()(const Order& a, const Order& b) const { return a.av_change < b.av_change; } }; Sort(orders, ChangeSorter()); for(int i = 0; i < orders.GetCount(); i++) { Order& o = orders[i]; o.av_idx = (double)i / (double)(orders.GetCount() - 1); } struct LengthSorter { bool operator ()(const Order& a, const Order& b) const { return a.len < b.len; } }; Sort(orders, LengthSorter()); for(int i = 0; i < orders.GetCount(); i++) { Order& o = orders[i]; o.len_idx = (double)i / (double)(orders.GetCount() - 1); } struct ErrorSorter { bool operator ()(const Order& a, const Order& b) const { return a.err > b.err; } }; Sort(orders, ErrorSorter()); for(int i = 0; i < orders.GetCount(); i++) { Order& o = orders[i]; o.err_idx = (double)i / (double)(orders.GetCount() - 1); o.idx = o.av_idx + o.err_idx + 2 * o.len_idx; } struct IndexSorter { bool operator ()(const Order& a, const Order& b) const { return a.idx < b.idx; } }; Sort(orders, IndexSorter()); for(int i = 0; i < orders.GetCount(); i++) { Order& o = orders[i]; o.idx_norm = (double)i / (double)(orders.GetCount() - 1); } /* struct PosSorter { bool operator ()(const Order& a, const Order& b) const { return a.start < b.start; } }; Sort(orders, PosSorter()); if (GetCounted() == 0) {DUMPC(orders);}*/ double idx_limit_f = idx_limit * 0.01; for(int i = 0; i < orders.GetCount(); i++) { Order& o = orders[i]; if (o.idx_norm < idx_limit_f) continue; ASSERT(o.start <= o.stop); for(int k = o.start; k < o.stop; k++) { SetSafetyLimit(k); enabledvec.Set(k, true); double open = open_buf.GetUnsafe(k); if (o.label) buf.Set(k, open - 10 * spread_point); else buf.Set(k, open + 10 * spread_point); } } } VolatilityContext::VolatilityContext() { } void VolatilityContext::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Blue); if ( period < 1 ) throw ConfExc(); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0, "VolatilityContext"); } void VolatilityContext::Start() { ConstBuffer& open = GetInputBuffer(0, 0); ConstBuffer& low = GetInputBuffer(0, 1); ConstBuffer& high = GetInputBuffer(0, 2); Buffer& buffer = GetBuffer(0); double diff; int bars = GetBars(); int counted = GetCounted(); if (!counted) counted++; double point = dynamic_cast<DataBridge*>(GetInputCore(0))->GetPoint(); for (int cursor = counted; cursor < bars; cursor++) { double diff = fabs(open.Get(cursor) - open.Get(cursor - 1)); int step = (int)((diff + point * 0.5) / point); median_map.GetAdd(step, 0)++; } SortByKey(median_map, StdLess<int>()); volat_divs.SetCount(0); int64 total = 0; for(int i = 0; i < median_map.GetCount(); i++) total += median_map[i]; int64 count_div = total / div; total = 0; int64 next_div = count_div; volat_divs.Add(median_map.GetKey(0) * point); for(int i = 0; i < median_map.GetCount(); i++) { total += median_map[i]; if (total >= next_div) { next_div += count_div; volat_divs.Add(median_map.GetKey(i) * point); } } if (volat_divs.GetCount() < div) { volat_divs.Add(median_map.TopKey() * point); } for (int cursor = counted; cursor < bars; cursor++) { SetSafetyLimit(cursor); double diff = fabs(open.Get(cursor) - open.Get(cursor - 1)); int lvl = -1; for(int i = 0; i < volat_divs.GetCount(); i++) { if (diff < volat_divs[i]) { lvl = i - 1; break; } } if (lvl == -1) lvl = div - 1; buffer.Set(cursor, lvl / (double)(volat_divs.GetCount()-2)); } } ChannelContext::ChannelContext() { } void ChannelContext::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Blue); if ( period < 1 ) throw ConfExc(); SetBufferStyle(0,DRAW_LINE); SetBufferLabel(0, "ChannelContext"); } void ChannelContext::Start() { ConstBuffer& open = GetInputBuffer(0, 0); ConstBuffer& low = GetInputBuffer(0, 1); ConstBuffer& high = GetInputBuffer(0, 2); Buffer& buffer = GetBuffer(0); VectorBool& enabled_buf = GetLabelBuffer(0,0).signal; double diff; int bars = GetBars(); int counted = GetCounted(); if (!counted) counted++; enabled_buf.SetCount(bars); double point = dynamic_cast<DataBridge*>(GetInputCore(0))->GetPoint(); channel.SetSize(period); for(int i = 0; i < period; i++) { int cursor = max(1, counted - i - 1); double l = low.Get(cursor - 1); double h = high.Get(cursor - 1); channel.Add(l, h); } channel.pos = counted-1; for (int cursor = counted; cursor < bars; cursor++) { double l = low.Get(cursor - 1); double h = high.Get(cursor - 1); channel.Add(l, h); l = low.Get(channel.GetLowest()); h = high.Get(channel.GetHighest()); double diff = h - l; int step = (int)((diff + point * 0.5) / point); median_map.GetAdd(step, 0)++; } SortByKey(median_map, StdLess<int>()); volat_divs.SetCount(0); int64 total = 0; for(int i = 0; i < median_map.GetCount(); i++) total += median_map[i]; int64 count_div = total / div; total = 0; int64 next_div = count_div; volat_divs.Add(median_map.GetKey(0) * point); for(int i = 0; i < median_map.GetCount(); i++) { total += median_map[i]; if (total >= next_div) { next_div += count_div; volat_divs.Add(median_map.GetKey(i) * point); } } if (volat_divs.GetCount() < div) { volat_divs.Add(median_map.TopKey() * point); } channel.SetSize(period); for(int i = 0; i < period; i++) { int cursor = max(1, counted - i - 1); double l = low.Get(cursor - 1); double h = high.Get(cursor - 1); channel.Add(l, h); } channel.pos = counted-1; for (int cursor = counted; cursor < bars; cursor++) { SetSafetyLimit(cursor); double l = low.Get(cursor - 1); double h = high.Get(cursor - 1); channel.Add(l, h); l = low.Get(channel.GetLowest()); h = high.Get(channel.GetHighest()); double diff = h - l; int lvl = -1; for(int i = 0; i < volat_divs.GetCount(); i++) { if (diff < volat_divs[i]) { lvl = i - 1; break; } } if (lvl == -1) lvl = div - 1; buffer.Set(cursor, lvl / (double)(volat_divs.GetCount()-2)); enabled_buf.Set(cursor, lvl < useable_div); } } GridSignal::GridSignal() { } void GridSignal::Init() { //SetCoreSeparateWindow(); SetBufferColor(0, Red); } void GridSignal::Start() { ConstBuffer& open = GetInputBuffer(0, 0); ConstBuffer& low = GetInputBuffer(0, 1); ConstBuffer& high = GetInputBuffer(0, 2); Buffer& out = GetBuffer(0); VectorBool& signal = GetLabelBuffer(0,0).signal; int counted = GetCounted(); int bars = GetBars(); double grid_step = GetDataBridge()->GetPoint() * ((double)main_interval * 0.1); if (!counted) { double first_price_value = open.Get(1); double diffBegin = open.Get(1) - open.Get(0); //---- first value ----------------------------------------------- //---- high at begin if (diffBegin >= 0) { trend = 1; line_value = first_price_value - grid_interval*grid_step; out.Set(1, line_value); } else //---- low at begin { trend = -1; line_value = first_price_value + grid_interval*grid_step; out.Set(1, line_value); } } //---- main loop //================================================================ for (int i = counted; i < bars; i++) { double price = open.Get(i); //---- up trend (blue line) ----------------------------------- if (trend == 1) { //---- translate up linie if (price - grid_interval*grid_step > line_value + grid_step) line_value = price - grid_interval*grid_step; else line_value = line_value + grid_step; out.Set(i, line_value); signal.Set(i, 0); //---- reverse from up-trend / down-trend if (price < line_value) { trend = -1; line_value = price + grid_interval*grid_step; out.Set(i, line_value); signal.Set(i, 1); } } else //---- down trend (red line) ---------------------------------- if (trend == -1) { //---- translate down linie if (price + grid_interval*grid_step < line_value - grid_step) line_value = price + grid_interval*grid_step; else line_value = line_value - grid_step; out.Set(i, line_value); signal.Set(i, 1); //---- reverse from down-trend / up-trend if (price > line_value) { trend = 1; line_value = price - grid_interval*grid_step; out.Set(i, line_value); signal.Set(i, 0); } } } } Anomaly::Anomaly() { } void Anomaly::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Red); SetCoreMaximum(1.0); SetCoreMinimum(0.0); SetCoreLevelCount(3); SetCoreLevel(0, 0.25); SetCoreLevel(1, 0.5); SetCoreLevel(2, 0.75); tfmin = GetMinutePeriod(); int w1 = 7 * 24 * 60; int count = 0; split_type = 0; if (GetTf() >= PHASETF) {count = 7; split_type = 1;} else if (tfmin >= w1) {count = 4; split_type = 2;} else if (tfmin >= 24 * 60) {count = 7; split_type = 1;} else {count = 7 * 24 * 60 / tfmin; split_type = 0;} var.SetCount(count); } void Anomaly::Start() { System& sys = GetSystem(); ConstBuffer& src = GetInputBuffer(0, 0); ConstBuffer& src_time = GetInputBuffer(0,4); LabelSignal& sig = GetLabelBuffer(0, 0); Buffer& dst = GetBuffer(0); int bars = GetBars() - 1; int counted = GetCounted(); if (counted) counted--; else counted++; for(int i = counted; i < bars; i++) { SetSafetyLimit(i+1); double prev = src.Get(i-1); if (prev == 0.0) continue; double change = src.Get(i) / prev - 1.0; if (!IsFin(change)) continue; double fchange = fabs(change); Time t = Time(1970,1,1) + src_time.Get(i); OnlineVariance* var; if (split_type == 0) { int wday = DayOfWeek(t); int wdaymin = (wday * 24 + t.hour) * 60 + t.minute; int avpos = wdaymin / tfmin; var = &this->var[avpos]; } else if (split_type == 1) { int wday = DayOfWeek(t); var = &this->var[wday]; } else if (split_type == 3) { int pos = i % this->var.GetCount(); var = &this->var[pos]; } else { int pos = (DayOfYear(t) % (7 * 4)) / 7; var = &this->var[pos]; } var->Add(fchange); double mean = var->GetMean(); double value; if (fchange >= mean) { value = var->GetCDF(fchange, false); } else { value = var->GetCDF(fchange, true); } value = (value - 0.5) * 2.0; dst.Set(i, value); if (!inverse) sig.signal.Set(i, change <= 0); else sig.signal.Set(i, change >= 0); sig.enabled.Set(i, value >= 0.75); } } VariantDifference::VariantDifference() { } void VariantDifference::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Red); SetCoreLevelCount(1); SetCoreLevel(0, 0.0); } void VariantDifference::Start() { System& sys = GetSystem(); ConstBuffer& src = GetInputBuffer(0, 0); ConstBuffer& src_time = GetInputBuffer(0,4); LabelSignal& sig = GetLabelBuffer(0, 0); Buffer& dst = GetBuffer(0); int bars = GetBars() - 1; int counted = GetCounted(); if (counted) counted--; else counted = period + 1; const VariantList& vl = sys.GetVariants(GetSymbol()); for(int j = 0; j < vl.symbols.GetCount(); j++) { const VariantSymbol& vs = vl.symbols[j]; ConstBuffer& p1 = GetInputBuffer(0, vs.p1, GetTf(), 0); ConstBuffer& p2 = GetInputBuffer(0, vs.p2, GetTf(), 0); bars = min(bars, p1.GetCount()); bars = min(bars, p2.GetCount()); } for(int i = counted; i < bars; i++) { SetSafetyLimit(i+1); double open = src.Get(i); double mom = open - src.Get(i - period); open += mom * multiplier; double av = 0; for(int j = 0; j < vl.symbols.GetCount(); j++) { const VariantSymbol& vs = vl.symbols[j]; ConstBuffer& p1 = GetInputBuffer(0, vs.p1, GetTf(), 0); ConstBuffer& p2 = GetInputBuffer(0, vs.p2, GetTf(), 0); double o1 = p1.Get(i); double o2 = p2.Get(i); double mom1 = o1 - p1.Get(i - period); double mom2 = o2 - p2.Get(i - period); o1 += mom1 * multiplier; o2 += mom2 * multiplier; double o; switch (vs.math) { case 0: // 0 - "S1 / S2" o = o1 / o2; break; case 1: // 1 - "S1 * S2" o = o1 * o2; break; case 2: // 2 - "1 / (S1 * S2)"; o = 1 / (o1 * o2); break; case 3: // 3 - "S2 / S1" o = o2 / o1; break; } av += o; } av /= vl.symbols.GetCount(); double diff = open - av; dst.Set(i, diff); sig.signal.Set(i, diff < 0); sig.enabled.Set(i, diff != 0.0); } } ScalperSignal::ScalperSignal() { } void ScalperSignal::Init() { } void ScalperSignal::Start() { System& sys = GetSystem(); ConstBuffer& open_buf = GetInputBuffer(0, 0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars() - 1; int counted = GetCounted(); if (counted) counted--; else counted++; int cost_level = 1; DataBridge* db = dynamic_cast<DataBridge*>(GetInputCore(0, GetSymbol(), GetTf())); double point = db->GetPoint(); double spread = max(db->GetSpread(), 3 * point); double cost = spread + point * cost_level; ASSERT(spread > 0.0); int max_opposite = 2; for(int i = counted; i < bars; i++) { SetSafetyLimit(i); double o0 = open_buf.GetUnsafe(i); double o1 = open_buf.GetUnsafe(i - 1); bool label = o0 < o1; int start = i; double start_price = o0; int opposite_count = 0; for(int j = i-1; j >= 1; j--) { double on0 = open_buf.GetUnsafe(j+1); double on1 = open_buf.GetUnsafe(j); bool nlabel = on0 < on1; if (nlabel != label && on0 != on1) { opposite_count++; if (opposite_count >= max_opposite) break; } start_price = on1; start = j; } double diff = o0 - start_price; double absdiff = fabs(diff); if (absdiff >= cost) { for(int j = start; j < i; j++) { sig.signal.Set(j, label); sig.enabled.Set(j, true); } } sig.enabled.Set(i, false); } } EasierScalperSignal::EasierScalperSignal() { } void EasierScalperSignal::Init() { } void EasierScalperSignal::Start() { System& sys = GetSystem(); ConstBuffer& open_buf = GetInputBuffer(0, 0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars() - 1; int counted = GetCounted(); if (counted) counted--; else counted++; int cost_level = 2; DataBridge* db = dynamic_cast<DataBridge*>(GetInputCore(0, GetSymbol(), GetTf())); double point = db->GetPoint(); double spread = max(db->GetSpread(), 3 * point); double cost = spread + point * cost_level; ASSERT(spread > 0.0); for(int i = counted; i < bars; i++) { SetSafetyLimit(i); double o0 = open_buf.GetUnsafe(i); double o1 = open_buf.GetUnsafe(i - 1); bool label = o0 < o1; label = !label; // Only after trend has gone we know usually int start = i; double start_price = o0; for(int j = i-2; j >= 1; j--) { double on0 = open_buf.GetUnsafe(j+1); double on1 = open_buf.GetUnsafe(j); bool nlabel = on0 < on1; if (nlabel != label && on0 != on1) break; start_price = on1; start = j; } start++; // The best start is usually missed double diff = start < i ? o0 - open_buf.GetUnsafe(start) : 0; double absdiff = fabs(diff); if (absdiff >= cost) { for(int j = start; j < i; j++) { sig.signal.Set(j, label); sig.enabled.Set(j, true); } } sig.enabled.Set(i, false); } } const char* PulseIndicator::symlist[10] = {"EURUSD", "GBPUSD", "USDCHF", "USDJPY", "USDCAD", "AUDUSD", "NZDUSD", "EURCHF", "EURGBP", "EURJPY"}; PulseIndicator::PulseIndicator() { } void PulseIndicator::Init() { } void PulseIndicator::Start() { System& sys = GetSystem(); ConstBuffer& open_buf = GetInputBuffer(0, 0); LabelSignal& sig = GetLabelBuffer(0, 0); Vector<ConstBuffer*> bufs; bufs.SetCount(symcount); for(int i = 0; i < symcount; i++) bufs[i] = &GetInputBuffer(0, sys.FindSymbol(symlist[i]), GetTf(), 0); Vector<int> dirs; String sym = sys.GetSymbol(GetSymbol()); String a = sym.Left(3); String b = sym.Mid(3,3); dirs.SetCount(symcount, 0); for(int i = 0; i < symcount; i++) { String othersym = symlist[i]; String oa = othersym.Left(3); String ob = othersym.Mid(3,3); if (oa == a || ob == b) dirs[i] = +1; else if (oa == b || ob == a) dirs[i] = -1; } int bars = GetBars(); for(int i = 0; i < symcount; i++) bars = min(bars, bufs[i]->GetCount()); for(int i = max(1, GetCounted()-1); i < bars; i++) { int triggers = 0; int trigger_dir = 0; for(int j = 0; j < symcount; j++) { double o0 = bufs[j]->Get(i); double o1 = bufs[j]->Get(i - 1); if (o0 != o1) { triggers++; trigger_dir += (o0 > o1 ? +1 : -1) * dirs[j]; } } sig.enabled.Set(i, triggers >= min_simultaneous); sig.signal.Set(i, trigger_dir < 0); } } Avoidance::Avoidance() { } void Avoidance::Init() { System& sys = GetSystem(); SetCoreSeparateWindow(); SetCoreLevelCount(1); SetCoreLevel(0, 0.0); SetBufferColor(1, Blue); // Get label source buffers String symstr1 = sys.GetSymbol(GetSymbol()); String A1 = symstr1.Left(3); String B1 = symstr1.Mid(3,3); for(int i = 1; i < inputs.GetCount(); i++) { for(int i2 = 0; i2 < inputs[i].GetCount(); i2++) { const Source& s = inputs[i][i2]; const Core& c = *dynamic_cast<Core*>(s.core); String symstr2 = sys.GetSymbol(c.GetSymbol()); String A2 = symstr2.Left(3); String B2 = symstr2.Mid(3,3); int mult = 0; if (A2 == A1) mult = +1; else if (B2 == A1) mult = -1; else if (A2 == B1) mult = -1; else if (B2 == B1) mult = +1; if (mult == 0) continue; for(int j = 0; j < c.GetLabelCount() && j < 1; j++) { ConstLabel& l = c.GetLabel(j); for(int k = 0; k < l.buffers.GetCount() && k < 1; k++) { ConstLabelSignal& src = l.buffers[k]; /* int changes = 0; bool prev = false; for (int l = 0; l < src.signal.GetCount(); l++) { bool b = src.signal.Get(l); if (b != prev) changes++; prev = b; } LOG(i << " " << i2 << " " << j << " " << k << " " << changes); sources.GetAdd(i*2).Add(SrcPtr(c.GetSymbol(), mult, &src)); */ if (symstr1 == symstr2) sources.GetAdd(i*2 + 1).Add(SrcPtr(c.GetSymbol(), +1, &src)); } } } } } void Avoidance::Start() { System& sys = GetSystem(); ConstBuffer& open_buf = GetInputBuffer(0, 0); double point = dynamic_cast<DataBridge*>(GetInputCore(0))->GetPoint(); Buffer& out = GetBuffer(0); Buffer& ma = GetBuffer(1); LabelSignal& sig = GetLabelBuffer(0, 0); int counted = GetCounted(); int bars = GetBars(); if (!counted) counted++; else counted--; data.SetCount(sources.GetCount()); for(int i = counted; i < bars; i++) { SetSafetyLimit(i); double pip_sum = 0; for(int j = 0; j < sources.GetCount(); j++) { Vector<DataPt>& data = this->data[j]; const Vector<SrcPtr>& sources = this->sources[j]; data.SetCount(bars); DataPt& pt = data[i]; if (i >= sources[0].c->signal.GetCount()) continue; pt.action = sources[0].c->signal.Get(i); if (sources[0].b < 0) pt.action = !pt.action; int pos = i; for (; pos > 0; pos--) { bool same = true; for(int k = 0; k < sources.GetCount() && same; k++) { if (pos >= sources[k].c->signal.GetCount()) continue; bool signal = sources[k].c->signal.Get(pos); bool enabled = sources[k].c->signal.Get(pos); if (sources[k].b < 0) signal = !signal; if (signal != pt.action || !enabled) same = false; } if (!same) break; } pt.len = min(255, i - pos); double begin = open_buf.Get(pos); double end = open_buf.Get(i); pt.pips = min(127, max(-127, (int)((end - begin) / point))); if (pt.action) pt.pips *= -1; pip_sum += pt.pips; } out.Set(i, pip_sum); sig.signal.Set(i, pip_sum < 0); sig.enabled.Set(i, pip_sum != 0); } SimpleMAOnBuffer ( bars, counted, 0, 10, out, ma ); /* for(int i = counted; i < bars; i++) { double prev = ma.Get(i-1); double cur = ma.Get(i); double diff = cur - prev; if (diff < 0) sig.signal.Set(i, !sig.signal.Get(i)); }*/ } AvoidancePeaks::AvoidancePeaks() { } void AvoidancePeaks::Init() { ec.SetSize(peak_period); } void AvoidancePeaks::Start() { System& sys = GetSystem(); ConstBuffer& open_buf = GetInputBuffer(0, 0); ConstBuffer& avoid_buf = GetInputBuffer(1, 0); //ConstLabelSignal& avoid_sig = GetInputLabel(1); LabelSignal& peak = GetLabelBuffer(0, 0); LabelSignal& before = GetLabelBuffer(0, 1); LabelSignal& after = GetLabelBuffer(0, 2); LabelSignal& sig = GetLabelBuffer(0, 3); int counted = GetCounted(); int bars = GetBars(); bool signal = 0, enabled = true; double open = open_buf.Get(0), total_change = 1.0; for(int i = counted; i < bars; i++) { SetSafetyLimit(i); peak .enabled.Set(i, false); before.enabled.Set(i, false); after .enabled.Set(i, false); double avoid = avoid_buf.Get(i); double prev_avoid = i > 0 ? avoid_buf.Get(i-1) : avoid; double avoid_diff = avoid - prev_avoid; ec.Add(avoid, avoid); int peak_pos = ec.GetHighest(); int peak_dist = i - peak_pos; double peak_value = avoid_buf.Get(peak_pos); if (peak_dist == 1) { bool type = GetType(i, open_buf, avoid_buf); peak.enabled.Set(i, true); peak.signal.Set(i, !type); } else if (avoid >= 0.25 * peak_value && avoid_diff > 0) { bool type = GetType(i, open_buf, avoid_buf); before.enabled.Set(i, true); before.signal.Set(i, type); if (enabled) { double close = open_buf.Get(i); double change = close / open; total_change *= change; signal = true; open = close; } } else if (avoid <= 0.25 * peak_value && avoid_diff < 0) { bool type = GetType(i, open_buf, avoid_buf); before.enabled.Set(i, true); before.signal.Set(i, type); if (enabled) { double close = open_buf.Get(i); double change = 1.0 - (close / open - 1.0); total_change *= change; signal = false; open = close; } } else if (avoid <= 0.0 * peak_value && avoid_diff > 0) { bool type = GetType(i, open_buf, avoid_buf); after.enabled.Set(i, true); after.signal.Set(i, type); } sig.signal.Set(i, signal); sig.enabled.Set(i, enabled); } DUMP(total_change); } bool AvoidancePeaks::GetType(int pos, ConstBuffer& open_buf, ConstBuffer& avoid_buf) { double diff_sum = 0; for (int i = pos, j = 0; i >= 1 && j < 10; i--, j++) { double o0 = open_buf.Get(i); double o1 = open_buf.Get(i-1); double a0 = avoid_buf.Get(i); double a1 = avoid_buf.Get(i-1); double o_diff = o0 - o1; double a_diff = a0 - a1; diff_sum += o_diff * a_diff; } return diff_sum < 0.0; } Laguerre::Laguerre() { } void Laguerre::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Red); SetCoreMaximum(1.0); SetCoreMinimum(-1.0); SetCoreLevelCount(2); SetCoreLevel(0, -0.5); SetCoreLevel(1, +0.5); // normalized } void Laguerre::Start() { System& sys = GetSystem(); ConstBuffer& src = GetInputBuffer(0, 0); ConstBuffer& src_time = GetInputBuffer(0, 4); LabelSignal& sig = GetLabelBuffer(0, 0); Buffer& dst = GetBuffer(0); int bars = GetBars() - 1; int counted = GetCounted(); if (counted) counted--; else counted++; double gammaf = gamma * 0.01; for (int i = counted; i < bars; i++) { SetSafetyLimit(i + 1); gd_120 = gd_88; gd_128 = gd_96; gd_136 = gd_104; gd_144 = gd_112; gd_88 = (1 - gammaf) * src.Get(i) + gammaf * gd_120; gd_96 = (-gammaf) * gd_88 + gd_120 + gammaf * gd_128; gd_104 = (-gammaf) * gd_96 + gd_128 + gammaf * gd_136; gd_112 = (-gammaf) * gd_104 + gd_136 + gammaf * gd_144; gd_160 = 0; gd_168 = 0; if (gd_88 >= gd_96) gd_160 = gd_88 - gd_96; else gd_168 = gd_96 - gd_88; if (gd_96 >= gd_104) gd_160 = gd_160 + gd_96 - gd_104; else gd_168 = gd_168 + gd_104 - gd_96; if (gd_104 >= gd_112) gd_160 = gd_160 + gd_104 - gd_112; else gd_168 = gd_168 + gd_112 - gd_104; if (gd_160 + gd_168 != 0.0) gd_152 = gd_160 / (gd_160 + gd_168); gd_152 = (gd_152 - 0.5) * 2.0; // normalized dst.Set(i, gd_152); sig.signal.Set(i, gd_152 <= 0); // normalized } } Calendar::Calendar() { } void Calendar::Init() { } double Calendar::GetTopDiff() { int bars = GetBars(); double diff = 0; for(int i = 0; i < stats.GetCount(); i++) { const CalendarStat& c = stats[i]; if (c.pos.Top() == bars - 1 && fabs(c.av_diff.mean) > fabs(diff)) { diff = c.av_diff.mean; } } return diff; } void Calendar::Start() { System& sys = GetSystem(); ConstBuffer& src = GetInputBuffer(0, 0); ConstBuffer& src_time = GetInputBuffer(0, 4); CalendarCommon& cal = GetSystem().GetCommon<CalendarCommon>(); while (!cal.IsReady()) Sleep(100); int bars = GetBars(); int counted = GetCounted(); #ifdef flagSECONDS int timestep = GetMinutePeriod(); // not "minutes" bug #else int timestep = GetMinutePeriod() * 60; #endif int prepost_step = 3600; int pre_step = max(1, prepost_step / timestep); int post_step = max(1, prepost_step / timestep); for (int i = counted; i < bars; i++) { Time t = Time(1970,1,1) + src_time.Get(i); Time next = i < bars-1 ? Time(1970,1,1) + src_time.Get(i+1) : t + timestep; double diff_sum[4] = {0.0, 0.0, 0.0, 0.0}; int diff_count[4] = {0, 0, 0, 0}; for (int is_pre = 0; is_pre < 1; is_pre++) { int& cal_cursor = is_pre ? pre_cal_cursor : main_cal_cursor; while (cal_cursor < cal.GetCount()) { if (cal_cursor == -1) cal_cursor = 0; const CalEvent& e = cal.GetEvent(cal_cursor); Time et = e.timestamp; if (is_pre) et -= prepost_step; if (et >= t && et < next) { int pos = i; String key = e.currency + " " + e.title; if (is_pre) { key += " pre"; pos -= pre_step; } CalendarStat& stat = stats.GetAdd(key); stat.pos.Add(pos); int post_pos = pos + post_step; if (post_pos >= bars) { stat.todo_stats.Add(pos); } else if (pos >= 0) { double o0 = src.Get(pos); double o1 = src.Get(post_pos); double diff = o0 - o1; stat.av_diff.Add(diff); if (e.forecast.GetCount() && e.actual.GetCount()) { double fc = ScanInt(e.forecast); double ac = ScanInt(e.actual); if (IsFin(fc) && IsFin(ac)) { if (fc == ac) stat.eq_ac.Add(diff >= 0 ? +1 : -1); else if (fc > ac) stat.pos_ac.Add(diff >= 0 ? +1 : -1); else stat.neg_ac.Add(diff >= 0 ? +1 : -1); } } } //if (!is_pre) { diff_sum[e.impact] += stat.av_diff.mean; diff_count[e.impact]++; //} } else if (et >= next) break; cal_cursor++; } } for(int j = 0; j < 4; j++) { LabelSignal& lbl = GetLabelBuffer(0, j); if (diff_count[j]) { lbl.enabled.Set(i, true); lbl.signal.Set(i, diff_sum[j] < 0); } else { lbl.enabled.Set(i, 0); } } } } QuantitativeQualitativeEstimation::QuantitativeQualitativeEstimation() { } void QuantitativeQualitativeEstimation::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Blue); SetCoreLevelCount(2); SetCoreLevel(0, -0.5); SetCoreLevel(1, +0.5); SetBufferLineWidth(0, 2); AddSubCore<RelativeStrengthIndex>() .Set("period", period); } void QuantitativeQualitativeEstimation::Start() { System& sys = GetSystem(); ConstBuffer& src = GetInputBuffer(0, 0); ConstBuffer& src_time = GetInputBuffer(0, 4); LabelSignal& sig = GetLabelBuffer(0, 0); Buffer& dst = GetBuffer(0); int bars = GetBars(); int counted = GetCounted(); if (counted) counted--; Buffer& rsi_ma_buffer = GetBuffer(1); ConstBuffer& rsi_buffer = At(0).GetBuffer(0); ExponentialMAOnBuffer( bars, counted, 0, period, rsi_buffer, rsi_ma_buffer ); Buffer& rsi_absdiff_buffer = GetBuffer(2); for (int i = max(1, counted); i < bars; i++) { double cur = rsi_ma_buffer.Get(i); double prev = rsi_ma_buffer.Get(i-1); double val = fabs(prev - cur); rsi_absdiff_buffer.Set(i, val); } Buffer& rsi_absdiff_ma_buffer = GetBuffer(3); ExponentialMAOnBuffer( bars, counted, 0, period, rsi_absdiff_buffer, rsi_absdiff_ma_buffer ); double d = counted > 0 ? dst.Get(counted - 1) : 0.0; for (int i = max(1, counted); i < bars; i++) { SetSafetyLimit(i + 1); double cur_rsi_ma = rsi_ma_buffer.Get(i); double cur_rsi_ma_prev = rsi_ma_buffer.Get(i-1); double cur_absdiff_ma = rsi_absdiff_ma_buffer.Get(i); double cur = 4.236 * cur_absdiff_ma; double d2 = d; if (cur_rsi_ma < d) { d = cur_rsi_ma + cur_absdiff_ma; if (cur_rsi_ma_prev < d2) if (d > d2) d = d2; } else if (cur_rsi_ma > d) { d = cur_rsi_ma - cur_absdiff_ma; if (cur_rsi_ma_prev > d2) if (d < d2) d = d2; } d = (d * 0.01 - 0.5) * 4.0; // normalized dst.Set(i, d); sig.signal.Set(i, d <= 0); // normalized } } TickBalanceOscillator::TickBalanceOscillator() { } void TickBalanceOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Blue); SetCoreLevelCount(1); SetBufferLineWidth(0, 2); } void TickBalanceOscillator::Start() { System& sys = GetSystem(); ConstBuffer& src = GetInputBuffer(0, 0); LabelSignal& sig = GetLabelBuffer(0, 0); Buffer& dst = GetBuffer(0); int bars = GetBars(); int counted = GetCounted(); if (counted) counted--; for (int i = max(period+1, counted); i < bars; i++) { SetSafetyLimit(i + 1); double pos_sum = 0, neg_sum = 0; int pos_count = 0, neg_count = 0; for(int j = 0; j < period; j++) { double o0 = src.Get(i-j); double o1 = src.Get(i-j-1); double diff = o0 - o1; if (diff > 0) {pos_sum += diff; pos_count++;} else {neg_sum -= diff; neg_count++;} } double pos_av = pos_count ? pos_sum / pos_count : 0; double neg_av = neg_count ? neg_sum / neg_count : 0; double d = pos_av - neg_av; dst.Set(i, d); sig.signal.Set(i, d < 0); } } PeekChange::PeekChange() { } void PeekChange::Init() { } void PeekChange::Start() { System& sys = GetSystem(); ConstBuffer& src = GetInputBuffer(0, 0); ConstBuffer& src_time = GetInputBuffer(0, 4); ConstBuffer& fast_src = GetInputBuffer(0, GetSymbol(), 0, 0); ConstBuffer& fast_src_time = GetInputBuffer(0, GetSymbol(), 0, 4); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); if (counted) counted--; for (int i = counted; i < bars; i++) { SetSafetyLimit(i + 1); int time = src_time.Get(i); for (;fast_cursor < fast_src.GetCount(); fast_cursor++) { int fast_time = fast_src_time.Get(fast_cursor); if (time <= fast_time) break; } int next_pos = min(fast_src.GetCount() - 1, fast_cursor + period); double o0 = fast_src.Get(next_pos); double o1 = fast_src.Get(fast_cursor); double diff = o0 - o1; sig.signal.Set(i, diff < 0); } } NewsNow::NewsNow() { } void NewsNow::Init() { SetCoreSeparateWindow(); SetCoreLevelCount(1); SetCoreLevel(0, 0); av.SetPeriod(period); } void NewsNow::Start() { System& sys = GetSystem(); int newsnet = sys.FindSymbol("NewsNet"); int afternewsnet = sys.FindSymbol("AfterNewsNet"); ConstBuffer& now = GetInputBuffer(0, newsnet, GetTf(), 0); ConstBuffer& after = GetInputBuffer(0, afternewsnet, GetTf(), 0); Buffer& buf = GetBuffer(0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = min(now.GetCount(), after.GetCount()); for (int i = prev_counted; i < bars; i++) { SetSafetyLimit(i + 1); double nm_prev = av.GetMeanA(); double am_prev = av.GetMeanB(); double n = now.Get(i); double a = after.Get(i); av.Add(n, a); double nm = av.GetMeanA(); double am = av.GetMeanB(); double nm_diff = nm - nm_prev; double am_diff = am - am_prev; double diff = fabs(nm_diff) - fabs(am_diff); buf.Set(i, diff); sig.enabled.Set(i, diff >= 0); sig.signal.Set(i, nm_diff < 0); } prev_counted = bars; } VolatilityEarlyLate::VolatilityEarlyLate() { } void VolatilityEarlyLate::Init() { SetCoreSeparateWindow(); SetCoreLevelCount(1); SetCoreLevel(0, 0); SetBufferStyle(1, STYLE_DASH); SetBufferColor(1, Blue()); av.SetPeriod(period); ma.SetPeriod(ma_period); } void VolatilityEarlyLate::Start() { System& sys = GetSystem(); Buffer& buf = GetBuffer(0); Buffer& ma_buf = GetBuffer(1); ConstBuffer& open_buf = GetInputBuffer(0, 0); ConstBuffer& volat_buf = GetInputBuffer(1, 0); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); for (int i = prev_counted; i < bars; i++) { SetSafetyLimit(i + 1); double o0 = open_buf.Get(i); double o1 = open_buf.Get(i > 0 ? i - 1 : i); double diff = o0 - o1; double volat = fabs(diff); double av_volat = i > 0 ? volat_buf.Get(i-1) : volat; av.Add(volat, av_volat); double vm = av.GetMeanA(); double am = av.GetMeanB(); double mdiff = fabs(vm) - fabs(am); buf.Set(i, mdiff); double prev_ma = ma.GetMean(); ma.Add(mdiff); double cur_ma = ma.GetMean(); sig.enabled.Set(i, mdiff >= 0.0 && mdiff >= cur_ma && cur_ma > prev_ma); sig.signal.Set(i, diff <= 0); ma_buf.Set(i, cur_ma); } prev_counted = bars; } SweetSpot::SweetSpot() { } void SweetSpot::Init() { } void SweetSpot::Start() { System& sys = GetSystem(); ConstBuffer& open_buf = GetInputBuffer(0, 0); ConstLabelSignal& news_lbl = CoreIO::GetInputLabel(1, GetSymbol(), GetTf(), 3); ConstLabelSignal& volat_lbl = GetInputLabel(2); LabelSignal& sig = GetLabelBuffer(0, 0); int counted = GetCounted(); int bars = GetBars(); int min_period = GetMinutePeriod(); int news_steps = max(1, news_delay / min_period); int volat_steps = max(1, volat_delay / min_period); for (int i = counted; i < bars; i++) { SetSafetyLimit(i + 1); bool news_enabled = news_lbl.enabled.Get(i); bool volat_enabled = volat_lbl.enabled.Get(i); if (news_enabled) news_counter = news_steps; if (volat_enabled) volat_counter = volat_steps; bool enabled = news_counter == 0 && volat_counter == 0; sig.enabled.Set(i, enabled); if (news_counter) news_counter--; if (volat_counter) volat_counter--; } } UnsustainableMovement::UnsustainableMovement() { } void UnsustainableMovement::Init() { SetCoreChartWindow(); } void UnsustainableMovement::Start() { System& sys = GetSystem(); ConstBuffer& open_buf = GetInputBuffer(0, 0); LabelSignal& sig = GetLabelBuffer(0, 0); Buffer& main = GetBuffer(0); Buffer& lo = GetBuffer(1); Buffer& hi = GetBuffer(2); int counted = GetCounted(); int bars = GetBars(); Vector<double> x, y; x.SetCount(period); y.SetCount(period); for(int i = 0; i < period; i++) { x[i] = i; y[i] = open_buf.Get(max(0, counted - i - 1)); } for (int i = counted; i < bars; i++) { SetSafetyLimit(i + 1); double cur = open_buf.Get(i); y.Insert(0, cur); y.Remove(period); double a, b, c; GetParabola(x, y, a, b, c); OnlineVariance var; for(int j = 0; j < period; j++) { double yv = a*j*j + b*j + c; double diff = yv - y[j]; var.Add(diff); } var_window.Add(var.GetVariance()); abc_window.Add(a); abc_window.Add(b); abc_window.Add(c); if (var_window.GetCount() > varperiod) { var_window.Remove(0); abc_window.Remove(0, 3); } double min_var = DBL_MAX; int min_pos = -1; for(int j = 0; j < var_window.GetCount(); j++) { double var = var_window[j]; if (var < min_var) { min_var = var; min_pos = j; } } double x = -(var_window.GetCount() - 1 - min_pos); a = abc_window[min_pos * 3 + 0]; b = abc_window[min_pos * 3 + 1]; c = abc_window[min_pos * 3 + 2]; double y = a*x*x + b*x + c; main.Set(i, y); double min_dev = sqrt(min_var); hi.Set(i, y + min_dev); lo.Set(i, y - min_dev); sig.signal.Set(i, cur < y); } } void UnsustainableMovement::GetParabola(const Vector<double>& x, const Vector<double>& y, double& a_out, double& b_out, double& c_out) { float matrix[3][4], ratio, a; float sum_x = 0, sum_y = 0, sum_x2 = 0, sum_x3 = 0, sum_x4 = 0, sum_xy = 0, sum_x2y = 0; int i, j , k; for (i = 0; i < x.GetCount(); i++) { Pointf p(x[i], y[i]); sum_x += p.x; sum_y += p.y; sum_x2 += pow(p.x, 2); sum_x3 += pow(p.x, 3); sum_x4 += pow(p.x, 4); sum_xy += p.x * p.y; sum_x2y += pow(p.x, 2) * p.y; } matrix[0][0] = x.GetCount(); matrix[0][1] = sum_x; matrix[0][2] = sum_x2; matrix[0][3] = sum_y; matrix[1][0] = sum_x; matrix[1][1] = sum_x2; matrix[1][2] = sum_x3; matrix[1][3] = sum_xy; matrix[2][0] = sum_x2; matrix[2][1] = sum_x3; matrix[2][2] = sum_x4; matrix[2][3] = sum_x2y; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { if (i != j) { ratio = matrix[j][i] / matrix[i][i]; for (k = 0; k < 4; k++) { matrix[j][k] -= ratio * matrix[i][k]; } } } } for (i = 0; i < 3; i++) { a = matrix[i][i]; for (j = 0; j < 4; j++) { matrix[i][j] /= a; } } a_out = matrix[2][3]; b_out = matrix[1][3]; c_out = matrix[0][3]; } PipChange::PipChange() { } void PipChange::Init() { SetCoreChartWindow(); av_win.SetPeriod(ticks); } void PipChange::Start() { System& sys = GetSystem(); ConstBuffer& open_buf = GetInputBuffer(0, 0); LabelSignal& sig = GetLabelBuffer(0, 0); double point = GetDataBridge()->GetPoint(); int counted = GetCounted(); int bars = GetBars(); signal.SetCount(bars); enabled.SetCount(bars); for (int i = counted; i < bars; i++) { SetSafetyLimit(i + 1); double cur = open_buf.Get(i); double prev = open_buf.Get(max(0, i-1)); int pips = (cur - prev) / point; av_win.Add(pips); double sum = av_win.GetSum(); if (fabs(sum) >= this->pips) { signal.Set(i, sum < 0); enabled.Set(i, true); } else { enabled.Set(i, false); } if (i > 0) { if (enabled.Get(i)) { bool now = signal.Get(i); if (now == signal.Get(i-1)) sig.enabled.Set(i, false); else { sig.signal.Set(i, now); sig.enabled.Set(i, true); } } else sig.enabled.Set(i, false); } } } SupplyDemand::SupplyDemand() { } void SupplyDemand::Init() { SetCoreChartWindow(); } void SupplyDemand::Start() { System& sys = GetSystem(); ConstBuffer& open_buf = GetInputBuffer(0, 0); LabelSignal& sig = GetLabelBuffer(0, 0); double point = GetDataBridge()->GetPoint(); double cost = point * cost_level; if (cost <= 0.0) cost = point; int counted = GetCounted(); int bars = GetBars(); minisig.SetCount(bars); for (int i = counted; i < bars; i++) { SetSafetyLimit(i); const int count = 1; bool sigbuf[count]; int begin = Upp::max(0, i - 100); int end = i + 1; OnlineMinimalLabel::GetMinimalSignal(cost, open_buf, begin, end, sigbuf, count); bool label = sigbuf[count - 1]; bool prev_label = i > 0 ? minisig.Get(i - 1) : false; minisig.Set(i, label); if (label != prev_label) { int peak_pos = i; double peak_value = open_buf.Get(i); for(int j = 0; j < trail_period; j++) { int pos = i - 1 - j; if (pos < 0) break; double cur = open_buf.Get(pos); if ((!label && cur < peak_value) || (label && cur > peak_value)) { peak_value = cur; peak_pos = pos; } } sig.signal.Set(peak_pos, label); sig.enabled.Set(peak_pos, true); int level = peak_value / point / level_div; bool level_exists = levels.Find(level) >= 0; levels.GetAdd(level).Add(peak_pos); if (!level_exists) SortByKey(levels, StdLess<int>()); } else { sig.enabled.Set(i, false); } int limit = i - level_len; for(int j = 0; j < levels.GetCount(); j++) { Vector<int>& pos = levels[j]; for(int k = 0; k < pos.GetCount(); k++) { if (pos[k] <= limit) { pos.Remove(k); k--; } } if (pos.IsEmpty()) { levels.Remove(j); j--; } } double cur_value = open_buf.Get(i); int cur_level = cur_value / point / level_div; if (levels.IsEmpty()) { for(int j = 0; j < 2; j++) { GetBuffer(j).Set(i, cur_value); } } else { int div = 0; for(int j = 0; j < levels.GetCount(); j++) { if (levels.GetKey(j) > cur_level) break; else div = j; } for(int j = 0; j < 1; j++) { int lo = max(0, div - j - 2); int hi = min(levels.GetCount()-1, div + 1 + j + 2); int lo_level = levels.GetKey(lo); int hi_level = levels.GetKey(hi); double lo_value = lo_level * level_div * point; double hi_value = hi_level * level_div * point; GetBuffer(1-1-j).Set(i, lo_value); GetBuffer(1+j).Set(i, hi_value); } } } } SupplyDemandOscillator::SupplyDemandOscillator() { } void SupplyDemandOscillator::Init() { SetCoreSeparateWindow(); SetBufferColor(0, Green); SetBufferColor(1, Red); SetCoreMinimum(-1); SetCoreMaximum(1); AddSubCore<SupplyDemand>().Set("cost_level", cost_level).Set("trail_period", trail_period).Set("level_div", level_div).Set("level_len", level_len); } void SupplyDemandOscillator::Start() { Buffer& osc_av = GetBuffer(0); Buffer& osc = GetBuffer(1); LabelSignal& sig = GetLabelBuffer(0, 0); int bars = GetBars(); int counted = GetCounted(); ConstBuffer& ind1 = At(0).GetBuffer(0); ConstBuffer& ind2 = At(0).GetBuffer(1); RefreshSubCores(); int prev_pos = counted ? counted-1 : 0; SetSafetyLimit(counted-1); double prev_value = counted ? osc_av.Get(counted-1) : 0; for (int i = counted; i < bars; i++) { SetSafetyLimit(i); double applied_value = Open(i); double s = ind1.Get(i); double r = ind2.Get(i); double range = r - s; double value = (applied_value - s) / range * 2 - 1; if (value > 1) value = 1; if (value < -1) value = -1; osc.Set(i, value); sig.signal.Set(i, value < 0); value = ExponentialMA( i, smoothing_period, prev_value, osc ); osc_av.Set(i, value); prev_pos = i; prev_value = value; } } ExampleAdvisor::ExampleAdvisor() { } void ExampleAdvisor::Init() { SetCoreSeparateWindow(); SetBufferColor(0, RainbowColor(Randomf())); String tf_str = GetSystem().GetPeriodString(GetTf()) + " "; SetJobCount(1); SetJob(0, tf_str + " Training") .SetBegin (THISBACK(TrainingBegin)) .SetIterator (THISBACK(TrainingIterator)) .SetEnd (THISBACK(TrainingEnd)) .SetInspect (THISBACK(TrainingInspect)) .SetCtrl <TrainingCtrl>(); } void ExampleAdvisor::Start() { if (once) { if (prev_counted > 0) prev_counted--; once = false; RefreshSourcesOnlyDeep(); } if (IsJobsFinished()) { int bars = GetBars(); if (prev_counted < bars) { LOG("ExampleAdvisor::Start Refresh"); RefreshAll(); } } } bool ExampleAdvisor::TrainingBegin() { training_pts.SetCount(max_rounds, 0); // In case of having other advisors as dependency: // Don't start if jobs of dependencies are not finished for(int i = 0; i < inputs.GetCount(); i++) { Input& in = inputs[i]; for(int j = 0; j < in.GetCount(); j++) { Source& src = in[j]; if (src.core) { Core* core = dynamic_cast<Core*>(src.core); if (core && !core->IsJobsFinished()) return false; } } } // Allow iterating return true; } bool ExampleAdvisor::TrainingIterator() { // Show progress GetCurrentJob().SetProgress(round, max_rounds); // ---- Do your training work here ---- // Put some result data here for graph training_pts[round] = sin(round * 0.01); // Keep count of iterations round++; // Stop eventually if (round >= max_rounds) { SetJobFinished(); } return true; } bool ExampleAdvisor::TrainingEnd() { RefreshAll(); return true; } bool ExampleAdvisor::TrainingInspect() { bool success = false; INSPECT(success, "ok: this is an example"); INSPECT(success, "warning: this is an example"); INSPECT(success, "error: this is an example"); // You can fail the inspection too //if (!success) return false; return true; } void ExampleAdvisor::RefreshAll() { RefreshSourcesOnlyDeep(); // ---- Do your final result work here ---- // Keep counted manually prev_counted = GetBars(); // Write oscillator indicator Buffer& buf = GetBuffer(0); for(int i = 0; i < GetBars(); i++) { buf.Set(i, sin(i * 0.01)); } } void ExampleAdvisor::TrainingCtrl::Paint(Draw& w) { Size sz = GetSize(); ImageDraw id(sz); id.DrawRect(sz, White()); ExampleAdvisor* ea = dynamic_cast<ExampleAdvisor*>(&*job->core); ASSERT(ea); DrawVectorPolyline(id, sz, ea->training_pts, polyline); w.DrawImage(0, 0, id); } }
20.792721
150
0.583519
[ "vector" ]
0cc08843ff512d66ab6967bd1e83ddcab1e1803c
1,407
cpp
C++
32blit/menu.cpp
Daft-Freak/DaftBoy32
721b1049a11742c57d8239491090d33aae2bbbe3
[ "MIT" ]
6
2021-01-18T23:06:02.000Z
2022-02-16T09:14:31.000Z
32blit/menu.cpp
Daft-Freak/DaftBoy32
721b1049a11742c57d8239491090d33aae2bbbe3
[ "MIT" ]
null
null
null
32blit/menu.cpp
Daft-Freak/DaftBoy32
721b1049a11742c57d8239491090d33aae2bbbe3
[ "MIT" ]
1
2021-12-10T23:45:28.000Z
2021-12-10T23:45:28.000Z
#include "menu.hpp" #include "control-icons.hpp" #include "engine/engine.hpp" Menu::Menu(std::string_view title, std::vector<Item> items, const blit::Font &font) : blit::Menu(title, nullptr, 0, font), items_vec(std::move(items)) { this->items = items_vec.data(); num_items = items_vec.size(); item_h = font.char_h + 2; item_adjust_y = 0; header_h = item_h; footer_h = 0; margin_y = 0; background_colour = blit::Pen(0x11, 0x11, 0x11); foreground_colour = blit::Pen(0xF7, 0xF7, 0xF7); selected_item_background = blit::Pen(0x22, 0x22, 0x22); } void Menu::set_on_item_activated(void (*func)(const Item &)) { on_item_pressed = func; } void Menu::render_item(const Item &item, int y, int index) const { blit::Menu::render_item(item, y, index); if(index == current_item) { const int iconSize = font.char_h > 8 ? 12 : 8; blit::Point iconPos = blit::Point(display_rect.x + display_rect.w - item_padding_x -iconSize, y + 1); // from the top-right blit::Pen icon_bg((header_foreground.r + header_background.r) / 2, (header_foreground.g + header_background.g) / 2, (header_foreground.b + header_background.b) / 2); duh::draw_control_icon(&blit::screen, duh::Icon::A, iconPos, iconSize, foreground_colour, icon_bg); } } void Menu::item_activated(const Item &item) { if(on_item_pressed) on_item_pressed(item); }
34.317073
173
0.67022
[ "vector" ]
0cc813390b166dfb5656093daf3de9c1f409ff12
1,291
cpp
C++
learningOpenCV3/Contour/main.cpp
colorhistory/computer-vision
88ddddcfd339ecb477edf24e46416f1c50627217
[ "MIT" ]
null
null
null
learningOpenCV3/Contour/main.cpp
colorhistory/computer-vision
88ddddcfd339ecb477edf24e46416f1c50627217
[ "MIT" ]
null
null
null
learningOpenCV3/Contour/main.cpp
colorhistory/computer-vision
88ddddcfd339ecb477edf24e46416f1c50627217
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2019 Xiaohai <xiaohaidotpro@outlook.com>. ** Contact: http://xiaohai.pro ** ** This file is part of learningOpenCV3 ** ** ****************************************************************************/ #include "bits/stdc++.h" #include "opencv2/opencv.hpp" cv::Mat gGrayImg, gBinaryImg; int gThresh = 100; void onTrackBar(int gThresh, void*) { cv::threshold(gGrayImg, gBinaryImg, gThresh, 255, cv::THRESH_BINARY); std::vector<std::vector<cv::Point>> contours; cv::findContours(gBinaryImg, contours, cv::noArray(), cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE); gBinaryImg = cv::Scalar::all(0); cv::drawContours(gBinaryImg, contours, -1, cv::Scalar::all(255)); cv::imshow("Contours", gBinaryImg); cv::imwrite("contours.jpg", gBinaryImg); } int main(int /* argc */, char** /* argv */) { gGrayImg = cv::imread("../../materials/face.jpg", cv::IMREAD_GRAYSCALE); if (gGrayImg.empty()) { std::cerr << "load image error..." << std::endl; return -1; } cv::namedWindow("Contours", cv::WINDOW_GUI_NORMAL); cv::createTrackbar("Threshold", "Contours", &gThresh, 255, onTrackBar); onTrackBar(0, 0); cv::waitKey(); return 0; }
28.065217
98
0.563129
[ "vector" ]
7b4c8e39e1c302941eb797b68e907338eb3f6df6
5,866
cpp
C++
tests/src/minimumtestcase.cpp
MacroGu/log4cxx_gcc_4_8
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
[ "Apache-2.0" ]
1
2016-10-06T20:09:32.000Z
2016-10-06T20:09:32.000Z
tests/src/minimumtestcase.cpp
MacroGu/log4cxx_gcc_4_8
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
[ "Apache-2.0" ]
null
null
null
tests/src/minimumtestcase.cpp
MacroGu/log4cxx_gcc_4_8
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2003,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <log4cxx/logger.h> #include <log4cxx/simplelayout.h> #include <log4cxx/ttcclayout.h> #include <log4cxx/fileappender.h> #include <log4cxx/helpers/absolutetimedateformat.h> #include "util/compare.h" #include "util/transformer.h" #include "util/linenumberfilter.h" #include "util/controlfilter.h" #include "util/absolutedateandtimefilter.h" #include "util/threadfilter.h" using namespace log4cxx; using namespace log4cxx::helpers; #define FILTERED _T("output/filtered") #define TTCC_PAT \ ABSOLUTE_DATE_AND_TIME_PAT \ _T(" \\[\\d*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message \\d{1,2}") #define TTCC2_PAT \ ABSOLUTE_DATE_AND_TIME_PAT \ _T(" \\[\\d*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - ") \ _T("Messages should bear numbers 0 through 23\\.") class MinimumTestCase : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(MinimumTestCase); CPPUNIT_TEST(simple); CPPUNIT_TEST(ttcc); CPPUNIT_TEST_SUITE_END(); public: void setUp() { root = Logger::getRootLogger(); root->removeAllAppenders(); } void tearDown() { root->getLoggerRepository()->resetConfiguration(); } void simple() { LayoutPtr layout = new SimpleLayout(); AppenderPtr appender = new FileAppender(layout, _T("output/simple"), false); root->addAppender(appender); common(); CPPUNIT_ASSERT(Compare::compare(_T("output/simple"), _T("witness/simple"))); } void ttcc() { LayoutPtr layout = new TTCCLayout(AbsoluteTimeDateFormat::DATE_AND_TIME_DATE_FORMAT); AppenderPtr appender = new FileAppender(layout, _T("output/ttcc"), false); root->addAppender(appender); common(); ControlFilter filter1; filter1 << TTCC_PAT << TTCC2_PAT; AbsoluteDateAndTimeFilter filter2; ThreadFilter filter3; std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(_T("output/ttcc"), FILTERED, filters); } catch(UnexpectedFormatException& e) { tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl; throw; } CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/ttcc"))); } void common() { int i = 0; // In the lines below, the category names are chosen as an aid in // remembering their level values. In general, the category names // have no bearing to level values. LoggerPtr ERR = Logger::getLogger(_T("ERR")); ERR->setLevel(Level::ERROR); LoggerPtr INF = Logger::getLogger(_T("INF")); INF->setLevel(Level::INFO); LoggerPtr INF_ERR = Logger::getLogger(_T("INF.ERR")); INF_ERR->setLevel(Level::ERROR); LoggerPtr DEB = Logger::getLogger(_T("DEB")); DEB->setLevel(Level::DEBUG); // Note: categories with undefined level LoggerPtr INF_UNDEF = Logger::getLogger(_T("INF.UNDEF")); LoggerPtr INF_ERR_UNDEF = Logger::getLogger(_T("INF.ERR.UNDEF")); LoggerPtr UNDEF = Logger::getLogger(_T("UNDEF")); // These should all log.---------------------------- LOG4CXX_FATAL(ERR, _T("Message ") << i); i++; //0 LOG4CXX_ERROR(ERR, _T("Message ") << i); i++; LOG4CXX_FATAL(INF, _T("Message ") << i); i++; // 2 LOG4CXX_ERROR(INF, _T("Message ") << i); i++; LOG4CXX_WARN(INF, _T("Message ") << i); i++; LOG4CXX_INFO(INF, _T("Message ") << i); i++; LOG4CXX_FATAL(INF_UNDEF, _T("Message ") << i); i++; //6 LOG4CXX_ERROR(INF_UNDEF, _T("Message ") << i); i++; LOG4CXX_WARN(INF_UNDEF, _T("Message ") << i); i++; LOG4CXX_INFO(INF_UNDEF, _T("Message ") << i); i++; LOG4CXX_FATAL(INF_ERR, _T("Message ") << i); i++; // 10 LOG4CXX_ERROR(INF_ERR, _T("Message ") << i); i++; LOG4CXX_FATAL(INF_ERR_UNDEF, _T("Message ") << i); i++; LOG4CXX_ERROR(INF_ERR_UNDEF, _T("Message ") << i); i++; LOG4CXX_FATAL(DEB, _T("Message ") << i); i++; //14 LOG4CXX_ERROR(DEB, _T("Message ") << i); i++; LOG4CXX_WARN(DEB, _T("Message ") << i); i++; LOG4CXX_INFO(DEB, _T("Message ") << i); i++; LOG4CXX_DEBUG(DEB, _T("Message ") << i); i++; // defaultLevel=DEBUG LOG4CXX_FATAL(UNDEF, _T("Message ") << i); i++; // 19 LOG4CXX_ERROR(UNDEF, _T("Message ") << i); i++; LOG4CXX_WARN(UNDEF, _T("Message ") << i); i++; LOG4CXX_INFO(UNDEF, _T("Message ") << i); i++; LOG4CXX_DEBUG(UNDEF, _T("Message ") << i); i++; // ------------------------------------------------- // The following should not log LOG4CXX_WARN(ERR, _T("Message ") << i); i++; LOG4CXX_INFO(ERR, _T("Message ") << i); i++; LOG4CXX_DEBUG(ERR, _T("Message ") << i); i++; LOG4CXX_DEBUG(INF, _T("Message ") << i); i++; LOG4CXX_DEBUG(INF_UNDEF, _T("Message ") << i); i++; LOG4CXX_WARN(INF_ERR, _T("Message ") << i); i++; LOG4CXX_INFO(INF_ERR, _T("Message ") << i); i++; LOG4CXX_DEBUG(INF_ERR, _T("Message ") << i); i++; LOG4CXX_WARN(INF_ERR_UNDEF, _T("Message ") << i); i++; LOG4CXX_INFO(INF_ERR_UNDEF, _T("Message ") << i); i++; LOG4CXX_DEBUG(INF_ERR_UNDEF, _T("Message ") << i); i++; // ------------------------------------------------- LOG4CXX_INFO(INF, _T("Messages should bear numbers 0 through 23.")); } LoggerPtr root; LoggerPtr logger; }; CPPUNIT_TEST_SUITE_REGISTRATION(MinimumTestCase);
25.955752
78
0.649847
[ "vector", "transform" ]
7b4ec7624303ad1d350e453f1c3c8b9c609c3a06
870
cpp
C++
Superprime Rib.cpp
Eggag/USACO
05eb5ebd73652ea5718e8e5832fac5ee3e946ccb
[ "MIT" ]
8
2018-10-27T04:29:01.000Z
2021-11-29T05:48:06.000Z
Superprime Rib.cpp
Eggag/USACO
05eb5ebd73652ea5718e8e5832fac5ee3e946ccb
[ "MIT" ]
null
null
null
Superprime Rib.cpp
Eggag/USACO
05eb5ebd73652ea5718e8e5832fac5ee3e946ccb
[ "MIT" ]
null
null
null
/* ID: egor_ga1 PROG: sprime LANG: C++11 */ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pi; #define mp make_pair #define pb push_back #define f first #define s second bool is_prime(int h){ for(int i = 2; i <= sqrt(h); i++){ if(h % i == 0){ return false; } } return true; } int main(){ freopen("sprime.in", "r", stdin); freopen("sprime.out", "w", stdout); int n; cin >> n; vi temp; vi temp1; for(int i = 2; i < 9; i++){ if(is_prime(i)){ temp.pb(i); } } for(int i = 1; i < n; i++){ for(int a = 0; a < temp.size(); a++){ for(int j = 0; j <= 9; j++){ int N = temp[a] * 10 + j; if(is_prime(N)){ temp1.pb(N); } } } temp.clear(); temp = temp1; temp1.clear(); } for(int i = 0; i < temp.size(); i++){ cout << temp[i] << endl; } return 0; }
15.818182
39
0.537931
[ "vector" ]
7b4fc7507c24dae7fdbd85bc5f00cc9cd2edb84d
1,131
hh
C++
src/Graph.hh
harrhunt/ClassDiagramTool
471e41c9e4574c323fd4fa41b9922b16bf035450
[ "Apache-2.0" ]
null
null
null
src/Graph.hh
harrhunt/ClassDiagramTool
471e41c9e4574c323fd4fa41b9922b16bf035450
[ "Apache-2.0" ]
1
2022-02-02T10:36:04.000Z
2022-02-02T10:36:04.000Z
src/Graph.hh
harrhunt/ClassDiagramTool
471e41c9e4574c323fd4fa41b9922b16bf035450
[ "Apache-2.0" ]
null
null
null
// // Created by Davis on 1/26/2022. // src/Graph.hh // #pragma once #include "Node.hh" #include "Edge.hh" #include <vector> /// Generic Graph data structure /// Contains a vector of Nodes and Edges template<class T> class Graph { public: Graph(); //add and remove nodes void addNode(Node<T> node) { nodes.push_back(node); } void addNodes(std::vector<Node<T>> newNodes) { for (Node<T> node: newNodes) { addNode(node); } } void removeNode(Node<T> node) { remove(nodes.begin(), nodes.end(), node); } //add and remove edges void addEdge(Edge<T> edge) { edges.push_back(edge); } void addEdges(std::vector<Edge<T>> newEdges) { for (Node<T> edge: newEdges) { addEdge(edge); } } void removeEdge(Node<Edge<T>> edge) { remove(edges.begin(), edges.end(), edge); } //getters std::vector<Node<T>> getNodes() { return nodes; } std::vector<Edge<T>> getEdges() { return edges; } private: std::vector<Node<T>> nodes; std::vector<Edge<T>> edges; };
19.842105
50
0.562334
[ "vector" ]
7b522cb1bd78ff0d3b55398af422dc8dd531a18f
1,312
cpp
C++
source/laplace/stem/s_app_flat.cpp
ogryzko/laplace
be63caa0c6d1c4fceab02ab5b41b6d307ef7baaf
[ "MIT" ]
null
null
null
source/laplace/stem/s_app_flat.cpp
ogryzko/laplace
be63caa0c6d1c4fceab02ab5b41b6d307ef7baaf
[ "MIT" ]
null
null
null
source/laplace/stem/s_app_flat.cpp
ogryzko/laplace
be63caa0c6d1c4fceab02ab5b41b6d307ef7baaf
[ "MIT" ]
null
null
null
/* laplace/stem/s_app_flat.cpp * * Base class for UI and 2D graphics application. * * Copyright (c) 2021 Mitya Selivanov * * This file is part of the Laplace project. * * Laplace 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 MIT License for more details. */ #include "../graphics/utils.h" #include "app_flat.h" namespace laplace::stem { using std::make_shared, std::abs, core::cref_family, ui::frame; app_flat::app_flat(int argc, char **argv, cref_family def_cfg) : application(argc, argv, def_cfg) { } app_flat::~app_flat() { } void app_flat::init() { application::init(); m_ui = make_shared<frame>(); } void app_flat::cleanup() { m_ui.reset(); application::cleanup(); } void app_flat::update(uint64_t delta_msec) { m_ui->tick(delta_msec, get_input(), false); } void app_flat::render() { graphics::clear(clear_color); m_ui->render(); get_gl().swap_buffers(); } void app_flat::adjust_layout(sl::whole width, sl::whole height) { application::adjust_layout(width, height); m_ui->set_rect({ .x = 0, .y = 0, .width = width, .height = height }); m_ui->refresh(); } }
22.62069
73
0.65625
[ "render" ]
7b5890a8f456bc8e51afe62bef904676a0a86764
8,535
tpp
C++
include/thpool.tpp
RRZE-HPC/RACE
d98c210aa8a3365c1fc856c557bc8b0ec5505e67
[ "MIT" ]
1
2021-02-24T20:18:46.000Z
2021-02-24T20:18:46.000Z
include/thpool.tpp
RRZE-HPC/RACE
d98c210aa8a3365c1fc856c557bc8b0ec5505e67
[ "MIT" ]
null
null
null
include/thpool.tpp
RRZE-HPC/RACE
d98c210aa8a3365c1fc856c557bc8b0ec5505e67
[ "MIT" ]
null
null
null
/* vim: set filetype=cpp: */ #include <functional> #include <sys/time.h> #include "timing.h" #include "test.h" #include<malloc.h> #include <unistd.h> #define DEFAULT_RACE_BLOCKCTR 200000 #define DEBUG 0 template< typename arg_t> thread<arg_t>::thread():pthread(NULL),workerTeam(NULL),jobPresent(false) { pthread = new pthread_t; } template<typename arg_t> thread<arg_t>::~thread() { delete pthread; delete signal; } /* interrupt has to be called before; coming to this*/ template<typename arg_t> void thread<arg_t>::kill() { jobPresent=1; //send signal to tell the thread to wake and destroy sendSignal(signal); } template<typename arg_t> void thread<arg_t>::init (int gid_, thpool<arg_t>* pool_) { gid = gid_; pool = pool_; signal = new Signal(pool->RACE_BLOCKCTR); if(gid != 0) { pthread_create(pthread, NULL, (void *(*)(void *)) run<arg_t>, this); pthread_detach(*pthread); } else { //master thread (*pthread) = pthread_self(); } } template<typename arg_t> void run(thread<arg_t> * thread) { thpool<arg_t>* pool = thread->pool; pthread_mutex_lock(pool->thcount_lock); pool->num_threads_alive++; pthread_mutex_unlock(pool->thcount_lock); while(!(__sync_fetch_and_add(&(pool->interrupt),0))) { //wait till jobPresent becomes true waitSignal(thread->signal, thread->jobPresent, true); //do RECV if master of the team is in different proc if(thread->jobPresent && (!pool->interrupt)) { #if DEBUG printf("tid = %u doing job\n",(unsigned) (* (thread->pthread))); #endif //do current job //START_TIME(work); thread->myJob.function(thread->myJob.arg); //STOP_TIME(work); //finish job thread->finishJob(); } } pthread_mutex_lock(pool->thcount_lock); pool->num_threads_alive--; pthread_mutex_unlock(pool->thcount_lock); } template<typename arg_t> void thread<arg_t>::addJob(std::function<void(arg_t)> function_, arg_t arg_, team<arg_t>* currTeam_) { bool master = ( pthread_self() == (*pthread) ); //START_TIME(add_job); if(jobPresent && !master) { ERROR_PRINT("thread = %d(%u), Previous job incomplete", gid, (unsigned)pthread_self()); } else { myJob.function = function_; myJob.arg = arg_; /* pthread_mutex_lock(signal->lock); jobPresent = true; pthread_mutex_unlock(signal->lock); */ //casted to void to avoid warning/error "value computed is not used" (void) __sync_lock_test_and_set(&jobPresent, 1); /*all the slaves belong to the current team, * master belongs to the parent team, this * is because master is a worker of previous * team and here he is the master; so don't * rewrite his team */ if(!master) { workerTeam = currTeam_; sendSignal(signal); //if my proc id not equal to curr child; then do SEND } } //STOP_TIME(add_job); } template<typename arg_t> void thread<arg_t>::finishJob() { bool master = ( pthread_self() == (*pthread) ); if(!jobPresent && !master) { ERROR_PRINT("Nothing to finish; job is already complete"); } else { //jobPresent = false; __sync_lock_release(&jobPresent); #if DEBUG printf("tid = %d(%u) finished job\n", gid, (unsigned) (* (pthread))); #endif if(__sync_add_and_fetch(&(workerTeam->num_jobs), 1) == workerTeam->num_slaves) { #if DEBUG printf("tid = %d(%u) sending barrier signal\n", gid, (unsigned) (* (pthread))); #endif sendSignal(workerTeam->barrierSignal); //if master not in same proc; do a MPI_SEND #if DEBUG printf("tid = %d(%u) sent barrier signal\n", gid, (unsigned) (* (pthread))); #endif } } } template<typename arg_t> thpool<arg_t>::thpool():initialized(false) { char* RACE_BLOCKCTR_str = getenv("RACE_BLOCKCTR"); if(RACE_BLOCKCTR_str == NULL) { RACE_BLOCKCTR = DEFAULT_RACE_BLOCKCTR; } else { RACE_BLOCKCTR = atoi(RACE_BLOCKCTR_str); } } template<typename arg_t> void thpool<arg_t>::init(int numThreads_) { if(numThreads_ > 0) { initialized = true; num_threads = std::max(numThreads_,1); num_threads_alive = 0; interrupt = 0; thcount_lock = new pthread_mutex_t; pthread_mutex_init(thcount_lock, NULL); //allocating threads threads = new thread<arg_t>[num_threads]; for(int tid=0; tid<num_threads; ++tid) { threads[tid].init(tid, this); } while(__sync_fetch_and_add(&num_threads_alive,0) != (num_threads-1)){/*wait till all spawned threads are initialized*/ } } } template<typename arg_t> thpool<arg_t>::~thpool() { //clean if pool is initialized before if(initialized) { interrupt = 1; //give Signal for(int i=1; i<num_threads; ++i) { threads[i].kill(); } while(__sync_fetch_and_add(&num_threads_alive,0) != 0) {/*wait till all are destroyed*/ } delete thcount_lock; delete[] threads; } } template<typename arg_t> team<arg_t>::team():initialized(false) { } template<typename arg_t> void team<arg_t>::init(std::vector<int> tid, thpool<arg_t>* pool) { num_threads = tid.size(); if(num_threads > 0) { initialized = true; num_slaves = num_threads-1; num_jobs = 0; //Construct task force taskForce = new thread<arg_t>*[num_threads]; for(int i=0; i<num_threads; ++i) { taskForce[i] = &(pool->threads[tid[i]]); } RACE_BLOCKCTR = pool->RACE_BLOCKCTR; barrierSignal = new Signal(RACE_BLOCKCTR); } } template<typename arg_t> team<arg_t>::~team() { if(initialized) { delete[] taskForce; delete barrierSignal; } } template<typename arg_t> void team<arg_t>::addJob(int tid, std::function<void(arg_t)> function_, arg_t arg_) { if(tid >= 0 && tid < num_threads) { #if DEBUG printf("tid = %d(%u), job added\n",tid, (unsigned)*(taskForce[tid]->pthread)); #endif taskForce[tid]->addJob(function_, arg_, this); } else { ERROR_PRINT("No job added; specified thread gid does not exists"); } } /* Master does his job and waits * until all the submitted jobs have finished */ template<typename arg_t> void team<arg_t>::barrier() { //current master does his job #if DEBUG printf("master: tid = %u doing job\n",(unsigned) (pthread_self())); #endif taskForce[0]->myJob.function(taskForce[0]->myJob.arg); taskForce[0]->jobPresent = 0;//false; #if DEBUG printf("master: tid = %u finished job\n",(unsigned) (pthread_self())); #endif /*timeval start, end; double startTime, endTime; gettimeofday(&start, NULL); startTime = start.tv_sec + start.tv_usec*1e-6;*/ //START_TIME(Barrier); waitSignal(barrierSignal, num_jobs, num_slaves); //If we have children in different procs do MPI_RECV; when counting check //only for children that do not belong to me __sync_lock_test_and_set(&num_jobs, 0); /*gettimeofday(&end, NULL); endTime = end.tv_sec + end.tv_usec*1e-6; barrierTime = endTime - startTime;*/ #if DEBUG printf("master: tid = %u barrier done\n",(unsigned) (pthread_self())); #endif // STOP_TIME(Barrier); } /*Make all threads in team to switch from * active to idle waiting*/ template<typename arg_t> void team<arg_t>::sleep() { for(int tid=1; tid<num_threads; ++tid) { //added with spin, since spin value is 0 if(__sync_fetch_and_add(&((taskForce[tid]->signal->mode)),spin)!=idle) { //wait till it starts spinning; //i.e its job is finished while(__sync_fetch_and_add(&(taskForce[tid]->signal->mode),spin)==released) { } sleepSignal(taskForce[tid]->signal); //wait till thread is idle while(__sync_fetch_and_add(&(taskForce[tid]->signal->mode),spin)!=idle) { } } } //reset BLOCKCTR value taskForce[0]->pool->RACE_BLOCKCTR = DEFAULT_RACE_BLOCKCTR; // __sync_synchronize(); }
25.029326
128
0.603046
[ "vector" ]
7b5a2f2294f83e564b808e44a1128026c0aa7395
15,032
cpp
C++
src/flexui/Render/Font.cpp
franciscod/flexui
9af2c32a8ac3fe7127a9dd6927abe8b1945237c4
[ "MIT" ]
23
2020-12-20T01:41:56.000Z
2021-11-14T20:26:40.000Z
src/flexui/Render/Font.cpp
franciscod/flexui
9af2c32a8ac3fe7127a9dd6927abe8b1945237c4
[ "MIT" ]
2
2020-12-23T16:29:55.000Z
2021-11-29T05:35:12.000Z
src/flexui/Render/Font.cpp
franciscod/flexui
9af2c32a8ac3fe7127a9dd6927abe8b1945237c4
[ "MIT" ]
4
2020-12-23T16:02:25.000Z
2021-09-30T08:37:51.000Z
#include "flexui/Render/Font.hpp" #include "flexui/Log.hpp" // FreeType 2 #include <ft2build.h> #include FT_FREETYPE_H constexpr auto MAX_VALID_UNICODE = 0x10FFFF; // https://github.com/skeeto/branchless-utf8 static int utf8_decode(uint32_t* c, const uint8_t* buf, const uint8_t* buf_end) { static const char lengths[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 }; static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 }; static const uint32_t mins[] = { 4194304, 0, 128, 2048, 65536 }; static const int shiftc[] = { 0, 18, 12, 6, 0 }; static const int shifte[] = { 0, 6, 4, 2, 0 }; unsigned char s[4]; s[0] = buf + 0 < buf_end ? buf[0] : 0; s[1] = buf + 1 < buf_end ? buf[1] : 0; s[2] = buf + 2 < buf_end ? buf[2] : 0; s[3] = buf + 3 < buf_end ? buf[3] : 0; int len = lengths[s[0] >> 3]; /* Compute the pointer to the next character early so that the next * iteration can start working on the next character. Neither Clang * nor GCC figure out this reordering on their own. */ unsigned char* next = s + len + !len; /* Assume a four-byte character and load four bytes. Unused bits are * shifted out. */ *c = (uint32_t)(s[0] & masks[len]) << 18; *c |= (uint32_t)(s[1] & 0x3f) << 12; *c |= (uint32_t)(s[2] & 0x3f) << 6; *c |= (uint32_t)(s[3] & 0x3f) << 0; *c >>= shiftc[len]; /* Accumulate the various error conditions. */ int e = 0; e = (*c < mins[len]) << 6; // non-canonical encoding e |= ((*c >> 11) == 0x1b) << 7; // surrogate half? e |= (*c > 0x10FFFF) << 8; // out of range? e |= (s[1] & 0xc0) >> 2; e |= (s[2] & 0xc0) >> 4; e |= (s[3]) >> 6; e ^= 0x2a; // top two bits of each tail byte correct? e >>= shifte[len]; return e ? (!!s[0] + !!s[1] + !!s[2] + !!s[3]) : (len + !len); } namespace flexui { FT_Library Font::s_FT_Library = nullptr; Font* Font::LoadFromMemory(const void* data, const size_t size) { if (FT_Init_FreeType(&s_FT_Library) != 0) { // TODO: this is not multithread friendly FUI_LOG_FATAL("%s", "Could not initialize FreeType library"); return nullptr; } // TODO: close the library... FT_Error error; FT_Face face; if ((error = FT_New_Memory_Face(Font::s_FT_Library, (FT_Byte*)data, (FT_Long)size, 0, &face)) == FT_Err_Ok) { // select encoding if ((error = FT_Select_Charmap(face, FT_ENCODING_UNICODE)) == FT_Err_Ok) { static unsigned int s_counter = 0; return new Font(face, s_counter++); } else { FUI_LOG_WARN("Could not select the Unicode charmap, error=%d", error); } } else { FUI_LOG_WARN("Could not load font, error=%d", error); } return nullptr; } Font::Font(FT_Face face, unsigned int id) : m_Face(face) , m_ID(id) { } Font::~Font() { FT_Done_Face(m_Face); } bool Font::getGlyphDescription(GlyphCodepoint codepoint, const TextStyle& style, GlyphDescription& description) { GlyphHash idx = (style.bold * ((GlyphHash)1 << 31)) | // 1 bit (style.italic * ((GlyphHash)1 << 30)) | // 1 bit ((GlyphHash)style.size << 21) | // 9 bits codepoint; // 21 bits (MAX_VALID_UNICODE) auto desc_it = m_DescriptionCache.find(idx); if (desc_it != m_DescriptionCache.end()) { // already computed description = (*desc_it).second; return description.valid; } FT_Int32 load_flags = FT_LOAD_DEFAULT; if (FT_HAS_COLOR(m_Face)) { // some bitmap glyphs may not return // metrics if they are not rendered (idk why) // example: TwemojiMozilla.ttf // TODO: this is expensive, fixme load_flags |= FT_LOAD_RENDER | FT_LOAD_COLOR; } if (!loadGlyph(codepoint, style.size, load_flags)) { description.valid = false; m_DescriptionCache.insert(std::make_pair(idx, description)); return false; } bool is_control = codepoint == ' ' || codepoint == '\t' || codepoint == '\r' || codepoint == '\n'; if (!is_control && m_Face->glyph->metrics.width == 0 && m_Face->glyph->bitmap.width == 0) { FUI_LOG_WARN("Loaded glyph U+%04X doesn't have size", codepoint); description.valid = false; m_DescriptionCache.insert(std::make_pair(idx, description)); return false; } description.valid = true; description.has_colors = FT_HAS_COLOR(m_Face) && m_Face->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA; description.width = (m_Face->glyph->metrics.width >> 6); description.height = (m_Face->glyph->metrics.height >> 6); description.advance = (m_Face->glyph->metrics.horiAdvance >> 6); description.bearingX = (m_Face->glyph->metrics.horiBearingX >> 6); description.bearingY = (m_Face->glyph->metrics.horiBearingY >> 6); if (description.width == 0) { // if metrics doesn't contain the size // of the glyph, use the bitmap dimensions description.width = m_Face->glyph->bitmap.width; description.height = m_Face->glyph->bitmap.rows; } m_DescriptionCache.insert(std::make_pair(idx, description)); return true; } bool Font::rasterizeGlyph(GlyphCodepoint codepoint, const TextStyle& style, unsigned char*& data, unsigned int& width, unsigned int& height) { FT_Int32 load_flags = FT_LOAD_RENDER; if (FT_HAS_COLOR(m_Face)) { // render colored glyphs like emojis load_flags |= FT_LOAD_COLOR; } if (!loadGlyph(codepoint, style.size, load_flags)) { return false; } if (m_Face->glyph->bitmap.buffer == nullptr) { FUI_LOG_WARN("Loaded glyph has a null bimap buffer codepoint=U+%04X", codepoint); return false; } width = m_Face->glyph->bitmap.width; height = m_Face->glyph->bitmap.rows; FUI_DEBUG_ASSERT(width * height > 0); data = (unsigned char*)malloc(width * height * 4); if (!data) return false; // malloc failed int pixels = width * height; auto source = m_Face->glyph->bitmap.buffer; switch (m_Face->glyph->bitmap.pixel_mode) { case FT_Pixel_Mode::FT_PIXEL_MODE_GRAY: { for (int i = 0; i < pixels; i++) { data[i * 4 + 0] = source[i]; data[i * 4 + 1] = source[i]; data[i * 4 + 2] = source[i]; data[i * 4 + 3] = 255; } return true; } case FT_Pixel_Mode::FT_PIXEL_MODE_BGRA: { for (int i = 0; i < pixels; i++) { data[i * 4 + 0] = source[i * 4 + 2]; data[i * 4 + 1] = source[i * 4 + 1]; data[i * 4 + 2] = source[i * 4 + 0]; data[i * 4 + 3] = source[i * 4 + 3]; } return true; } } return false; } void Font::generateTextLayout(const std::string& utf8_text, const TextLayoutSettings& layoutSettings, TextLayout& layout) { // TODO: alignment // TODO: use Harfbuzz as an optional dependency // to generate the shaping // TODO: bidi? // TODO: run a proper justification algorithm (Knuth/Plass maybe) layout.width = 0; layout.height = 0; layout.style = layoutSettings.style; if (!layoutSettings.skip_glyphs) { // reserve some initial space for the glyphs // some may be unused if a unicode codepoint spans // over multiple chars layout.glyphs.reserve(utf8_text.size()); } const uint8_t* text_start = (uint8_t*)utf8_text.c_str(); const uint8_t* text_end = (uint8_t*)utf8_text.c_str() + utf8_text.size(); GlyphCodepoint code, prev_code; GlyphDescription description; TextLayout::GlyphInstance instance; int i = 0; int last_whitespace_i = 0; int glyphs_since_last_wrap = 0; bool last_whitespace_was_wrap = false; int penX = 0, penY = layoutSettings.style.size; while (i < utf8_text.size()) { int code_length = utf8_decode(&code, text_start + i, text_end); // length in bytes FUI_DEBUG_ASSERT(code > 0 && code_length > 0); if (getGlyphDescription(code, layoutSettings.style, description)) { bool is_jump = code == '\n' || code == '\r'; bool is_whitespace = code == ' ' || code == '\t'; bool should_wrap = false; float kerning = i ? getKerning(prev_code, code, layoutSettings.style.size) : 0; instance = {}; instance.codepoint = code; instance.index = i; instance.x = penX + description.bearingX; instance.y = penY - description.bearingY; instance.w = description.width; instance.h = description.height; instance.has_colors = description.has_colors; if (layoutSettings.wrap != TextWrap::NONE && layoutSettings.maxWidth > 0 && glyphs_since_last_wrap > 0) { if (is_whitespace) { // keep track of whitespaces last_whitespace_i = i; last_whitespace_was_wrap = false; } else { if (std::max(layout.width, instance.x + instance.w) > layoutSettings.maxWidth) { // should wrap? if (layoutSettings.wrap == TextWrap::WORD) { // wrap the whole last word if (!last_whitespace_was_wrap) { // avoid infinite loop i = last_whitespace_i; last_whitespace_was_wrap = true; should_wrap = true; // remove all glyphs after the last space while (layout.glyphs.size() > 0 && layout.glyphs.back().index >= last_whitespace_i) layout.glyphs.pop_back(); } } else { // wrap chars should_wrap = true; } } } } if (is_jump || should_wrap) { penX = 0; penY += layoutSettings.style.size; glyphs_since_last_wrap = 0; if (should_wrap) { prev_code = 0; continue; // do not increment i } } else { layout.width = std::max(layout.width, instance.x + instance.w); layout.height = std::max(layout.height, instance.y + instance.h); if (!layoutSettings.skip_glyphs) layout.glyphs.emplace_back(instance); penX += description.advance - kerning; glyphs_since_last_wrap++; } } prev_code = code; i += code_length; } } bool Font::setCurrentSize(FontSize pixel_height) const { FT_Error error; if (FT_IS_SCALABLE(m_Face)) { // try to avoid calls to FT_Set_Pixel_Sizes // since it is an expensive function if (pixel_height != m_Face->size->metrics.x_ppem) { error = FT_Set_Pixel_Sizes(m_Face, 0, pixel_height); } else { error = FT_Err_Ok; } } else { FUI_DEBUG_ASSERT(m_Face->num_fixed_sizes > 0); int best_i = 0; // font has fixed sizes // find the closest height to target (and greater) for (int i = 1; i < m_Face->num_fixed_sizes; i++) { if (m_Face->available_sizes[i].y_ppem < (FT_Pos)pixel_height) { // it is lower, but consider it if it is // better than the current best if (m_Face->available_sizes[i].y_ppem > m_Face->available_sizes[best_i].y_ppem) best_i = i; } else if (m_Face->available_sizes[i].y_ppem < m_Face->available_sizes[best_i].y_ppem) { // it is greater but closer best_i = i; } } // select this strike error = FT_Select_Size(m_Face, best_i); } if (error != FT_Err_Ok) { FUI_LOG_WARN("Could not set pixel size size=%d, error=%d", pixel_height, error); return false; } return true; } bool Font::loadGlyph(GlyphCodepoint codepoint, FontSize pixel_height, int load_flags) { // lookup unicode -> glyph index uint32_t glyph_index = FT_Get_Char_Index(m_Face, codepoint); if (glyph_index == 0) { FUI_LOG_WARN("Could not find glyph index for U+%04X", codepoint); return false; } // set desired size if (!setCurrentSize(pixel_height)) { return false; } // load glyph FT_Error error; if ((error = FT_Load_Glyph(m_Face, glyph_index, load_flags)) != FT_Err_Ok) { FUI_LOG_WARN("Could not load glyph U+%04X, glyph_index=%d, error=%d", codepoint, glyph_index, error); return false; } return true; } float Font::getKerning(GlyphCodepoint left, GlyphCodepoint right, FontSize pixel_height) { if (left > 0 && right > 0 && FT_HAS_KERNING(m_Face) && setCurrentSize(pixel_height)) { FT_UInt left_index = FT_Get_Char_Index(m_Face, left); FT_UInt right_index = FT_Get_Char_Index(m_Face, right); FT_Vector kerning; FT_Get_Kerning(m_Face, left_index, right_index, FT_KERNING_DEFAULT, &kerning); if (!FT_IS_SCALABLE(m_Face)) return kerning.x; // already in pixels return (float)kerning.x / (float)(1 << 6); } return 0.0f; } void Font::getAvailableGlyphs(std::vector<GlyphCodepoint>& glyphs) const { glyphs.reserve(m_Face->num_glyphs); FT_UInt codepoint; FT_ULong charcode = FT_Get_First_Char(m_Face, &codepoint); while (codepoint != 0) { glyphs.push_back(charcode); charcode = FT_Get_Next_Char(m_Face, charcode, &codepoint); } } unsigned int Font::getID() const { return m_ID; } }
36.933661
144
0.532863
[ "render", "vector" ]
7b5c8b79a7c3183b5196a1eb0241d61a24b95884
4,641
hpp
C++
include/misc/shader.hpp
jdtaylor7/drone_viewer
18009b499c96255bd355db030522e97cc840d6ba
[ "MIT" ]
11
2020-08-25T22:19:46.000Z
2021-09-29T11:50:29.000Z
include/misc/shader.hpp
jdtaylor7/drone_viewer
18009b499c96255bd355db030522e97cc840d6ba
[ "MIT" ]
17
2020-07-10T00:35:09.000Z
2020-08-18T00:38:07.000Z
include/misc/shader.hpp
jdtaylor7/drone_viewer
18009b499c96255bd355db030522e97cc840d6ba
[ "MIT" ]
2
2021-02-11T17:37:32.000Z
2021-02-21T11:11:30.000Z
#ifndef SHADER_HPP #define SHADER_HPP #include <filesystem> #include <fstream> #include <sstream> #include <string> #include <glad/glad.h> #include <glm/glm.hpp> #include "logger.hpp" namespace fs = std::filesystem; class Shader { public: Shader() : vertex_path{}, fragment_path{} {} Shader(const fs::path& vpath, const fs::path& fpath) : vertex_path(vpath), fragment_path(fpath) {} void init(); void use(); void set_bool(const std::string& name, bool value) const; void set_int(const std::string& name, int value) const; void set_float(const std::string& name, float value) const; void set_vec3(const std::string& name, const glm::vec3& v); void set_mat4fv(const std::string& name, const glm::mat4& m); private: fs::path vertex_path; fs::path fragment_path; unsigned int id; }; void Shader::init() { std::string vertex_code; std::string fragment_code; std::ifstream vertex_shader_file; std::ifstream fragment_shader_file; vertex_shader_file.exceptions(std::ifstream::failbit | std::ifstream::badbit); fragment_shader_file.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { vertex_shader_file.open(vertex_path); fragment_shader_file.open(fragment_path); std::stringstream vertex_shader_stream; std::stringstream fragment_shader_stream; vertex_shader_stream << vertex_shader_file.rdbuf(); fragment_shader_stream << fragment_shader_file.rdbuf(); vertex_shader_file.close(); fragment_shader_file.close(); vertex_code = vertex_shader_stream.str(); fragment_code = fragment_shader_stream.str(); } catch (std::ifstream::failure e) { logger.log(LogLevel::error, "Shader::init: Shader file could not be read: ", e.what(), '\n'); } const char* vertex_shader_source = vertex_code.c_str(); const char* fragment_shader_source = fragment_code.c_str(); int success; char info_log[512]; // Create vertex shader object. unsigned int vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL); glCompileShader(vertex_shader); // Check for vertex shader compilation errors. glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertex_shader, 512, NULL, info_log); logger.log(LogLevel::error, "Shader::init: Vertex shader could not be compiled: ", info_log, '\n'); } // Create fragment shader object. unsigned int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL); glCompileShader(fragment_shader); // Check for fragment shader compilation errors. glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragment_shader, 512, NULL, info_log); logger.log(LogLevel::error, "Shader::init: Fragment shader could not be compiled: ", info_log, '\n'); } // Build shader program. id = glCreateProgram(); glAttachShader(id, vertex_shader); glAttachShader(id, fragment_shader); glLinkProgram(id); // Check for shader program link errors. glGetProgramiv(id, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(id, 512, NULL, info_log); logger.log(LogLevel::error, "Shader::init: Shader file could not be linked: ", info_log, '\n'); } // Delete the shader objects since they've already been linked into the // shader program. glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); } void Shader::use() { glUseProgram(id); } void Shader::set_bool(const std::string& name, bool value) const { glUniform1i(glGetUniformLocation(id, name.c_str()), (int)value); } void Shader::set_int(const std::string& name, int value) const { glUniform1i(glGetUniformLocation(id, name.c_str()), value); } void Shader::set_float(const std::string& name, float value) const { glUniform1f(glGetUniformLocation(id, name.c_str()), value); } void Shader::set_vec3(const std::string& name, const glm::vec3& v) { glUniform3f(glGetUniformLocation(id, name.c_str()), v.x, v.y, v.z); } void Shader::set_mat4fv(const std::string& name, const glm::mat4& m) { glUniformMatrix4fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, glm::value_ptr(m)); } #endif /* SHADER_HPP */
30.532895
110
0.669899
[ "object" ]
7b68af0b49a98c54885e187d602d83b74b343d9b
3,329
cpp
C++
med/shortest_reach/main.cpp
exbibyte/hr
100514dfc2a1c9b5366c12ec0a75e889132a620e
[ "MIT" ]
null
null
null
med/shortest_reach/main.cpp
exbibyte/hr
100514dfc2a1c9b5366c12ec0a75e889132a620e
[ "MIT" ]
null
null
null
med/shortest_reach/main.cpp
exbibyte/hr
100514dfc2a1c9b5366c12ec0a75e889132a620e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; namespace std { template <> struct hash<pair<int, int>> { std::size_t operator()(const pair<int, int> &k) const { using std::hash; using std::size_t; // Compute individual hash values for first, // second and third and combine them using XOR // and bit shifting: return ((hash<int>()(k.first) ^ (hash<int>()(k.second) << 1)) >> 1); } }; } // namespace std // min priority queue using Queue = priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>; void search(unordered_map<int, unordered_set<int>> &adj, unordered_map<pair<int, int>, int> &cost, unordered_map<int, int> &ret, Queue &q) { if (q.empty()) { return; } auto [top_cost, top] = q.top(); assert(ret.count(top) == 1); q.pop(); if (ret[top] < top_cost) { // discard top return search(adj, cost, ret, q); // tail call } else { for (auto neigh : adj[top]) { pair<int, int> key = {top, neigh}; assert(cost.count(key) == 1); int c = cost[key]; if (ret.count(neigh) == 0) { // non-exiting neighbour ret[neigh] = c + ret[top]; q.push({c, neigh}); // make neigh eligeable for search } else { if (c + ret[top] < ret[neigh]) { // top->neigh ret[neigh] = c + ret[top]; q.push({c, neigh}); // make neigh eligeable for search } } } return search(adj, cost, ret, q); // tail call } } void solve(unordered_map<int, unordered_set<int>> &adj, unordered_map<pair<int, int>, int> &cost, int start, int n) { unordered_map<int, int> ret; // best cost from single source start ret[start] = 0; Queue q; // queue to search q.push({0, start}); search(adj, cost, ret, q); for (int i = 1; i <= n; ++i) { if (i != start) { if (ret.count(i) == 0) { // cout << -1 << " "; printf("-1 "); } else { // cout << ret[i] << " "; printf("%d ", ret[i]); } } } // cout << endl; printf("\n"); } int main() { // ios_base::sync_with_stdio(false); // cin.tie(NULL); int t; scanf("%d", &t); // cin >> t; for (int i = 0; i < t; ++i) { // test case int n, m, s; // cin >> n >> m; scanf("%d %d", &n, &m); unordered_map<int, unordered_set<int>> adj; unordered_map<pair<int, int>, int> cost; for (int j = 0; j < m; ++j) { // edges int x, y; static int const r = 6; // constant edge weight // cin >> x >> y >> r; scanf("%d %d", &x, &y); // take min of cost if (cost.count({x, y}) == 0) { cost[{x, y}] = r; cost[{y, x}] = r; } else { cost[{x, y}] = min(cost[{x, y}], r); cost[{y, x}] = min(cost[{y, x}], r); } adj[x].insert(y); adj[y].insert(x); } // cin >> s; scanf("%d", &s); solve(adj, cost, s, n); } return 0; }
30.263636
76
0.444578
[ "vector" ]
7b6b676eea1586764cf08357365ee48d18a1e59a
2,097
hpp
C++
mlmodel/src/ResultReason.hpp
tucan9389/coremltools
705244e2be26c3fb7881fd7a731d25a55f5e4765
[ "BSD-3-Clause" ]
null
null
null
mlmodel/src/ResultReason.hpp
tucan9389/coremltools
705244e2be26c3fb7881fd7a731d25a55f5e4765
[ "BSD-3-Clause" ]
null
null
null
mlmodel/src/ResultReason.hpp
tucan9389/coremltools
705244e2be26c3fb7881fd7a731d25a55f5e4765
[ "BSD-3-Clause" ]
null
null
null
// // ResultReason.hpp // CoreML // // Created by Jeff Kilpatrick on 12/16/19. // Copyright © 2019 Apple Inc. All rights reserved. // #pragma once namespace CoreML { /** Super specific reasons for non-good Results. */ enum class ResultReason { UNKNOWN, // ----------------------------------------- // Model validation MODEL_INPUT_TYPE_INVALID, MODEL_OUTPUT_TYPE_INVALID, // ----------------------------------------- // Program validation BLOCK_INPUT_COUNT_MISMATCHED, BLOCK_OUTPUT_NAME_EMPTY, BLOCK_OUTPUT_COUNT_MISMATCHED, BLOCK_OUTPUT_TYPE_MISMATCHED, BLOCK_OUTPUT_VALUE_UNDEFINED, BLOCK_PARAM_NAME_EMPTY, BLOCK_PARAM_NAME_SHADOWS, FUNCTION_BLOCK_RETURN_COUNT_MISMATCHED, FUNCTION_BLOCK_RETURN_TYPE_MISMATCHED, FUNCTION_NAME_EMPTY, FUNCTION_PARAM_NAME_EMPTY, FUNCTION_PARAM_NAME_SHADOWS, FUNCTION_PARAM_TYPE_NULL, MODEL_MAIN_IMAGE_INPUT_SIZE_BAD, MODEL_MAIN_IMAGE_INPUT_TYPE_BAD, MODEL_MAIN_IMAGE_OUTPUT_SIZE_BAD, MODEL_MAIN_IMAGE_OUTPUT_TYPE_BAD, MODEL_MAIN_INPUT_COUNT_MISMATCHED, MODEL_MAIN_INPUT_OUTPUT_MISSING, MODEL_MAIN_INPUT_OUTPUT_TYPE_INVALID, MODEL_MAIN_INPUT_RANK_MISMATCHED, MODEL_MAIN_INPUT_SHAPE_MISMATCHED, MODEL_MAIN_INPUT_TYPE_MISMATCHED, MODEL_MAIN_OUTPUT_COUNT_MISMATCHED, MODEL_MAIN_OUTPUT_RANK_MISMATCHED, MODEL_MAIN_OUTPUT_SHAPE_MISMATCHED, MODEL_MAIN_OUTPUT_TYPE_MISMATCHED, OP_ARG_COUNT_MISMATCH, OP_ARG_NAME_EMPTY, OP_ARG_OUTPUT_CIRCULAR_DEFINITION, OP_ARG_TYPE_MISMATCH, OP_ARG_VALUE_UNDEFINED, OP_ATTRIBUTE_NAME_EMPTY, OP_ATTRIBUTE_VALUE_UNDEFINED, OP_BLOCK_COUNT_INVALID, OP_INVALID_IN_CONTEXT, OP_NAME_EMPTY, OP_OUTPUT_COUNT_MISMATCHED, OP_OUTPUT_NAME_EMPTY, OP_OUTPUT_NAME_SHADOWS, OP_OUTPUT_TYPE_INVALID, OP_PARAM_COUNT_MISMATCHED, OP_PARAM_INVALID, OP_PARAM_NAME_EMPTY, OP_REQUIRED_ARG_NOT_FOUND, PARAMETER_NAME_EMPTY, PARAMETER_VALUE_UNDEFINED, PROGRAM_MAIN_FUNCTION_MISSING, PROGRAM_NULL, PROGRAM_PARSE_THREW, }; }
24.964286
52
0.748689
[ "model" ]
7b6c1084af3f8547c940c5faaf1bde0c9e06e3e5
4,882
cpp
C++
week13/hw12_jiaxi.cpp
YiwenCui/NYU-Bridge-Winter-2021
bcada20fc0fd7d940f556322dabc560f59259e57
[ "MIT" ]
null
null
null
week13/hw12_jiaxi.cpp
YiwenCui/NYU-Bridge-Winter-2021
bcada20fc0fd7d940f556322dabc560f59259e57
[ "MIT" ]
null
null
null
week13/hw12_jiaxi.cpp
YiwenCui/NYU-Bridge-Winter-2021
bcada20fc0fd7d940f556322dabc560f59259e57
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> using namespace std; class Money { public: friend Money operator+(const Money &amount1, const Money &amount2); friend Money operator-(const Money &amount1, const Money &amount2); friend Money operator-(const Money &amount); friend bool operator==(const Money &amount1, const Money &amount2); friend bool operator<(const Money &amount1, const Money &amount2); Money(long dollars, int cents); Money(long dollars); Money(); double get_value() const { return all_cents; }; friend istream &operator>>(istream &ins, Money &amount); friend ostream &operator<<(ostream &outs, const Money &amount); private: long all_cents; }; class Check { private: string numOfCheck; double amountOfCheck; bool isCashed; Money temp; public: Check(string numOfCheck, Money t, bool isCashed) { this->numOfCheck = numOfCheck; // this->amountOfCheck = amountOfCheck;1 this->isCashed = isCashed; this->temp = t; }; string get_numOfCheck() { return this->numOfCheck; }; long get_temp() { return this->temp.get_value(); }; bool get_isCashed() { return this->isCashed; }; }; int main() { // vector<Check> allchecks; // bool isCashed = 0; // int cashCount = 0; char ifContinue = 'Y'; // while (ifContinue != 'N') // { // ifContinue = 'N'; // string checkID; // double amoutnOfCheck; // Money temp; // bool isCashed; // // cout << endl << temp.get_value() << endl; // cout << "Please enter the number of check, the amount of the check and whetehr or not it has been cashed. (1 or 0, separte your answers by space)" << endl; // cin >> checkID >> temp >> isCashed; // Check randomCheck = Check(checkID, temp, isCashed); // allchecks.push_back(randomCheck); // cashCount++; // cout << "Do you have another check to input? ('Y' for Yes and 'N' for No)" << endl; // cin >> ifContinue; // } // for (int i = 0; i < cashCount; i++) // { // cout << allchecks[i].get_numOfCheck() << '\t' << allchecks[i].get_temp() << '\t' << allchecks[i].get_isCashed() << endl; // } vector<Money> allDs; cout << "add dposiute" << endl; ifContinue = 'Y'; while (ifContinue != 'N') { Money d; cin >> d; allDs.push_back(d); cout << "Do you have another check to input? ('Y' for Yes and 'N' for No)" << endl; cin >> ifContinue; } return 0; } Money operator+(const Money &amount1, const Money &amount2) { Money temp; temp.all_cents = amount1.all_cents + amount2.all_cents; return temp; } Money operator-(const Money &amount1, const Money &amount2) { Money temp; temp.all_cents = amount1.all_cents - amount2.all_cents; return temp; } Money operator-(const Money &amount) { Money temp; temp.all_cents = -amount.all_cents; return temp; } bool operator==(const Money &amount1, const Money &amount2) { bool temp; if (amount1 == amount2) { temp = true; } else { temp = false; } return temp; } bool operator<(const Money &amount1, const Money &amount2) { bool temp; if (amount1 < amount2) { temp = true; } else { temp = false; } return temp; } Money::Money(long dollars, int cents) { all_cents = dollars * 100 + cents; }; Money::Money(long dollars) { all_cents = dollars * 100; }; Money::Money() : all_cents(0){}; istream &operator>>(istream &ins, Money &amount) { char one_char, decimal_point, digit1, digit2; //digits for the amount of cents long dollars; int cents; bool negative; //set to true if input is negative. ins >> one_char; if (one_char == '-') { negative = true; ins >> one_char; //read '$' } else { // if the input is legal, then one_char == '$' negative = false; } ins >> dollars >> decimal_point >> digit1 >> digit2; if (one_char != '$' || decimal_point != '.' || !isdigit(digit1) || !isdigit(digit2)) { cout << "Error illegal form for money input\n"; exit(1); } cents = 100; amount.all_cents = dollars * 100 + cents; if (negative) amount.all_cents = -amount.all_cents; return ins; } // ostream &operator<<(ostream &outs, const Money &amount) // { // long positive_cents, dollars, cents; // positive_cents = labs(amount.all_cents); // dollars = positive_cents / 100; // cents = positive_cents % 100; // if (amount.all_cents < 0) // outs << "- $" << dollars << '.'; // else // outs << "$" << dollars << '.'; // if (cents < 10) // outs << '0'; // outs << cents; // return outs; // }
23.931373
166
0.578247
[ "vector" ]
7b72dbb3bb6e3287f8ef2623da36eb5def8fc2f1
16,944
cpp
C++
src/libParkAssist.cpp
MatteoRagni/ParkAssistant
5d3941515ce2666d188564f8a65e0684d6979586
[ "BSD-3-Clause" ]
5
2015-04-30T13:10:15.000Z
2018-10-11T21:00:44.000Z
src/libParkAssist.cpp
MatteoRagni/ParkAssistant
5d3941515ce2666d188564f8a65e0684d6979586
[ "BSD-3-Clause" ]
1
2018-04-11T03:51:24.000Z
2018-04-11T06:58:32.000Z
src/libParkAssist.cpp
MatteoRagni/ParkAssistant
5d3941515ce2666d188564f8a65e0684d6979586
[ "BSD-3-Clause" ]
8
2015-04-30T13:10:17.000Z
2019-02-10T20:39:53.000Z
/* * libParkAssist.cpp * * Created on: Nov 10, 2013 * Author: Matteo Ragni */ #include "libParkAssist.hpp" void printCapProperties(VideoCapture cap){ cout << "┌─────────────────┐ " << endl; cout << "│ FILE PROPERTIES │" << endl; cout << "└──┬──────────────┘ " << endl; cout << " │ " << endl; cout << " ├─> Dimensions: " << cap.get(CV_CAP_PROP_FRAME_WIDTH) << "x" << cap.get(CV_CAP_PROP_FRAME_HEIGHT) << endl; cout << " ├─> Tot Frames: " << cap.get(CV_CAP_PROP_FRAME_COUNT) << endl; cout << " ├─> FPS: " << cap.get(CV_CAP_PROP_FPS) << endl; cout << " ├─> Times: " << cap.get(CV_CAP_PROP_POS_MSEC) << endl; cout << " ├─> Rel. pos: " << cap.get(CV_CAP_PROP_POS_AVI_RATIO) << endl; cout << " ├─> Convert RGB: " << cap.get(CV_CAP_PROP_CONVERT_RGB) << endl; cout << " ├─> Format: " << cap.get(CV_CAP_PROP_FORMAT) << endl; cout << " ├─> Mode: " << cap.get(CV_CAP_PROP_MODE) << endl; cout << " └─> Codec Code: " << cap.get(CV_CAP_PROP_FOURCC) << endl; cout << endl; } bool readConfFile(char* filePath){ // Apertura del file di configurazione: INFO("[LIBHW] Opening: " << filePath); FileStorage fs(filePath, FileStorage::READ); if (!fs.isOpened()) { cout << "[LIBHW] Cannot open file:" << filePath << endl; return FALSE; } fs["parking_spot"] >> nParkingSpot; INFO("[LIBHW] Identified: " << nParkingSpot << " parking spots"); FileNode spots = fs["spots"]; FileNodeIterator node = spots.begin(); FileNodeIterator node_end = spots.end(); for (int idx = 0; node != node_end; ++node, idx++) { parkingSpot[idx] = readParkSpot(*node); if (parkingSpot[idx].nspot == ERRORCODE) { cout << "[LIBHW] Cannot read spot:" << idx << endl; return FALSE; } } // Chiusura del file di configurazione fs.release(); return TRUE; } parkSpot readParkSpot(FileNode spot) { parkSpot tmp; std::vector<int> rect; std::vector<int> xpoly; std::vector<int> ypoly; std::vector<int> param; // Syntax check if(!checkIntSyntax(spot,"nspot")) { tmp.nspot = ERRORCODE; return tmp;} tmp.nspot = (int)spot["nspot"] - 1; spot["rect"] >> rect; spot["polyx"] >> xpoly; spot["polyy"] >> ypoly; spot["param"] >> param; // Assigning polyline points for (int i = 0; i < (int)xpoly.size(); i++) { tmp.PolyPoint[i] = Point((int)xpoly[i],(int)ypoly[i]); } // Assigning parameters for (int i = 0; i < (int)param.size(); i++) { tmp.parameters[i] = param[i]; } // Assigning rectangular values tmp.rectPoint = Point((int)rect[0],(int)rect[1]); tmp.rectDim[0] = (int)rect[2]; tmp.rectDim[1] = (int)rect[3]; return tmp; } bool checkIntSyntax(FileNode fn, const char* node) { if (fn[node].type() != FileNode::INT) { cout << "[LIBHW] Spot syntax error: " << node << endl; return FALSE; } else { return TRUE; } } void printSpot(parkSpot spot) { cout << endl; cout << "PARKING SPOT: " << spot.nspot << endl; cout << endl; cout << "Parameters:" << endl; for(int i = 0; i < PARAMETERS; i++) { cout << "[" << i << "]: " << spot.parameters[i] << " "; } cout << endl; cout << endl; cout << "Rectangle: P = (" << spot.rectPoint.x << "," << spot.rectPoint.y << ") "; cout << "S = (" << spot.rectDim[0] << "," << spot.rectDim[1] << ")" << endl; cout << "Polyline: "; for (int i = 0; i < MAXPOLY; i++ ) { cout << "P" << i << " = ("; cout << spot.PolyPoint[i].x << "," << spot.PolyPoint[i].y << "), "; } cout << endl; } float round2(float num, int dec) { float num_c = num; float mult = 1; for(int i = 0; i < dec; i++ ) { mult *= 10; } return cvRound(num_c*mult)/mult; } void histogramsWallClear() { Mat(HST_PLOT_W * HST_WALL_ROWS, HST_PLOT_H * HST_WALL_COLS, CV_8UC3, SCLBLACK).copyTo(HistogramsWall); } void histogramsWall(int pos, Histogram input) { int rows = cvRound(pos / HST_WALL_ROWS); int cols = pos - (rows * HST_WALL_COLS); Mat tmpInput = Mat(); Mat tmpRect = Mat(HST_PLOT_W, HST_PLOT_H, CV_8UC3, SCLBLACK); input.histSum.copyTo(tmpInput); // Creating the position of interest Rect ROI = Rect(rows * HST_PLOT_H, cols * HST_PLOT_W, HST_PLOT_W, HST_PLOT_H); // Aggiunta delle scritte: medie e deviazioni standard char position[5]; char means[25]; char stddevs[25]; sprintf(position, "%d", pos); sprintf(means, "M: %.2f %.2f %.2f", input.means[0], input.means[1], input.means[2]); sprintf(stddevs, "S: %.2f %.2f %.2f", input.stddev[0], input.stddev[1], input.stddev[2]); putText(tmpInput, position, Point(10,20), FONT_HERSHEY_COMPLEX_SMALL, 0.5, SCLWHITE, 1, CV_AA); putText(tmpInput, means, Point(10,40), FONT_HERSHEY_COMPLEX_SMALL, 0.5, SCLWHITE, 1, CV_AA); putText(tmpInput, stddevs, Point(10,60), FONT_HERSHEY_COMPLEX_SMALL, 0.5, SCLWHITE, 1, CV_AA); tmpInput.copyTo(HistogramsWall(ROI)); } /**************************/ // IMPLEMENTAZIONE CLASSE // /**************************/ /*******************/ // HISTOGRAM CLASS // /*******************/ Histogram::Histogram(Mat Frame) { this->histSum = Mat(HST_PLOT_H, HST_PLOT_W, CV_8UC3, SCLBLACK); this->refresh(Frame); } Histogram::Histogram() { for (int i = 0; i < HISTCOMP; i++) { this->hist[i] = Mat(); this->plane.push_back(Mat::ones(1,1,CV_8UC3)); } } void Histogram::refresh(Mat Frame){ this->SourceImage = Frame.clone(); this->refresh(); } void Histogram::refresh(){ int histSize = HST_SIZE; // numero di Bins = 32 float hist_range[] = { 0, HST_RANGE }; const float* histRange = { hist_range }; Mat TmpPlane; Mat TmpHist; split(this->SourceImage, this->plane); for(int i = 0; i < HISTCOMP; i++) { this->plane[i].copyTo(TmpPlane); calcHist( &(TmpPlane), 1, 0, Mat(), TmpHist, 1, &histSize, &histRange, HST_UNIFORM, HST_ACC); TmpHist.copyTo(this->hist[i]); } this->refreshHistSum(); this->evalValues(); //this->print(); } void Histogram::refreshHistSum(){ Scalar Color[HISTCOMP] = { SCLBLUE, SCLGREEN, SCLRED }; int hist_w = HST_PLOT_W; int hist_h = HST_PLOT_H; int bin_w = cvRound( (double) hist_w/HST_SIZE ); Mat TmpMat( HST_PLOT_H, HST_PLOT_W, CV_8UC3, SCLBLACK ); Mat TmpHist; for (int j = 0; j < HISTCOMP; j++) { (this->hist[j]).copyTo(TmpHist); normalize(TmpHist, TmpHist, 0, HST_PLOT_H, NORM_MINMAX, -1, Mat() ); for (int i = 0; i < HST_SIZE; i++) { line( TmpMat, Point( bin_w*(i-1), hist_h - cvRound(TmpHist.at<float>(i-1)) ) , \ Point( bin_w*(i), hist_h - cvRound(TmpHist.at<float>(i)) ), \ Color[j], 2, 8, 0 ); } } TmpMat.copyTo(this->histSum); } void Histogram::plot(char* window) { namedWindow(window,CV_WINDOW_KEEPRATIO | CV_WINDOW_NORMAL); resizeWindow(window, HST_PLOT_W, HST_PLOT_H); imshow(window, this->histSum); } void Histogram::print(){ cout << "┌───────────┐ " << endl; cout << "│ HISTOGRAM │ " << endl; cout << "└──┬────────┘ " << endl; cout << " │ " << endl; cout << " ├─> Dimensions: "; for (int i= 0; i < HISTCOMP; i++) { cout << " [" << i << "] " << this->plane[i].rows << "x" << this->plane[i].cols;} cout << endl; cout << " ├─> Dimensions: "; for (int i= 0; i < HISTCOMP; i++) { cout << " [" << i << "] " << this->hist[i].rows << "x" << this->hist[i].cols;} cout << endl; cout << " ├─> Dimensions: " << " [SUM] " << this->histSum.rows << "x" << this->histSum.cols << endl; cout << " │ " << endl; cout << " ├─> Tot Comps: "; for (int i= 0; i < HISTCOMP; i++) { cout << " [" << i << "] " << this->hist[i].total(); } cout << endl; cout << " ├─> Sum Tot Comps: " << " [SUM] " << this->histSum.total() << endl; cout << " │ " << endl; cout << " ├─> Means: "; for (int i= 0; i < HISTCOMP; i++) { cout << " [" << i << "] " << this->means[i]; } cout << endl; cout << " └─> Std Dev²: "; for (int i= 0; i < HISTCOMP; i++) { cout << " [" << i << "] " << this->stddev[i]; } cout << endl; } void Histogram::evalValues(){ Mat tmpHist; Mat tmpMean; Mat tmpSD; merge(this->hist, HISTCOMP, tmpHist); meanStdDev(tmpHist, tmpMean, tmpSD, Mat()); for (int i = 0; i < HISTCOMP; i++) { this->means[i] = round2(saturate_cast<float>(tmpMean.at<double>(i)),5); this->stddev[i] = round2(saturate_cast<float>(tmpSD.at<double>(i)),2); } } // PARKSPOTOBJ ParkSpotObj::ParkSpotObj(parkSpot inputStruct){ this->counter=0; this->nspot = inputStruct.nspot; // empty vectors this->parameters.clear(); this->PolyPoints.clear(); this->PolyPoints2f.clear(); this->warpingPts.clear(); for (int i = 0; i < PARAMETERS; i++){ this->parameters.push_back(inputStruct.parameters[i]); } for (int i = 0; i < MAXPOLY; i++){ this->PolyPoints.push_back(inputStruct.PolyPoint[i]); } // Align the polypoints vector and get the warped transformation matrix; this->sortCorners(); this->getWarpedDimension(); // Assign warpingPoints and PolyPoints2f; for (int i = 0; i < (int)this->PolyPoints.size(); i++) { this->PolyPoints2f.push_back(Point2f(saturate_cast<float>(this->PolyPoints[i].x), saturate_cast<float>(this->PolyPoints[i].y))); }; this->warpingMat = getPerspectiveTransform(this->PolyPoints2f, this->warpingPts); // Generates the rectangle this->ParkRect = Rect(inputStruct.rectPoint.x, \ inputStruct.rectPoint.y, \ inputStruct.rectDim[0], \ inputStruct.rectDim[1]); Mat tmpWarpSrc; Mat tmpWarpDst = Mat::zeros(this->warpedDim.x, this->warpedDim.y, CV_8UC3); tmpWarpDst.copyTo(this->fdbuffer); for (int i = 0; i < FDFRAME; i++) { ICbuffer[i].copyTo(tmpWarpSrc); warpPerspective(tmpWarpSrc, tmpWarpDst, this->warpingMat, tmpWarpDst.size()); tmpWarpDst.copyTo(this->buffer[i]); } tmpWarpSrc.release(); tmpWarpDst.release(); this->status = PARKFREE; this->fd = 0; Mat tmpHstImgHSV; cvtColor(this->buffer[0], tmpHstImgHSV, CV_CONVERSION); this->hist = Histogram(tmpHstImgHSV); cvtColor(this->buffer[1], tmpHstImgHSV, CV_CONVERSION); this->hist_old = Histogram(tmpHstImgHSV); this->status = ParkSpotObj::initialStatus(); this->show(); } void ParkSpotObj::refreshImage(){ this->shiftBuffers(); //this->buffer[FDFRAME-1] = (*LastFrame)(this->ParkRect); Mat tmpWarpSrc; Mat tmpWarpDst = Mat::zeros(this->warpedDim.x, this->warpedDim.y, CV_8UC3); ICbuffer[0].copyTo(tmpWarpSrc); warpPerspective(tmpWarpSrc, tmpWarpDst, this->warpingMat, tmpWarpDst.size()); tmpWarpDst.copyTo(this->buffer[0]); tmpWarpSrc.release(); tmpWarpDst.release(); } void ParkSpotObj::refreshImagefd(Mat input){ Mat tmpWarpSrc; Mat tmpWarpDst = Mat::zeros(this->warpedDim.x, this->warpedDim.y, CV_8UC3); input.copyTo(tmpWarpSrc); warpPerspective(tmpWarpSrc, tmpWarpDst, this->warpingMat, tmpWarpDst.size()); tmpWarpDst.copyTo(this->fdbuffer); tmpWarpSrc.release(); tmpWarpDst.release(); // Calcola la somma dell'fd e controlla che non superi la soglia param[0] this->fd = sum(this->fdbuffer)[0]; if(this->fd > this->parameters[0]) { this->status = PARKWAIT; } } void ParkSpotObj::refreshImageEdge(Mat input){ Mat tmpWarpSrc; Mat tmpWarpDst = Mat::zeros(this->warpedDim.x, this->warpedDim.y, CV_8UC3); input.copyTo(tmpWarpSrc); warpPerspective(tmpWarpSrc, tmpWarpDst, this->warpingMat, tmpWarpDst.size()); tmpWarpDst.copyTo(this->edgebuffer); tmpWarpSrc.release(); tmpWarpDst.release(); // Calcola la somma dell'fd e controlla che non superi la soglia param[0] this->edge = sum(this->edgebuffer)[0]; } void ParkSpotObj::shiftBuffers() { for (int i = FDFRAME - 2; i > -1; i--){ this->buffer[i + 1] = this->buffer[i]; } } void ParkSpotObj::refreshHist() { Mat tmpImage; cvtColor(this->buffer[0], tmpImage, CV_CONVERSION); this->hist.refresh(tmpImage); tmpImage.release(); } int ParkSpotObj::initialStatus() { double alpha = (double)this->parameters[2] * 0.1; double trans = (double)this->parameters[3]; /* Rotational Matrix * * R = [ cos(a) sin(a)] * [ -sin(a) cos(a)] * * R*V = [ V1*cos(a) + V2*sin(a) ] * [ -V1*sin(a) + V2*cos(a) ] * * where * V2 = mu2 (mean of second chrominance component) * V1 = sigma1 ( stdev of first chrominance component) * * Extract y V(2) -> -V1*sin(a) + V2*cos(a) * Translate V(2) -> V(2) - Q * * Check sign of this last element */ double ts = (cos(alpha)*(double)this->hist.means[2] - sin(alpha)*(double)this->hist.stddev[1]) - (double)trans; return (ts >= 0 ? PARKBUSY : PARKFREE); } void ParkSpotObj::plotPolyFill(Mat Frame){ Point tmpPoly[(int)this->PolyPoints.size()]; for(int i = 0; i < (int)this->PolyPoints.size(); i++) { tmpPoly[i].x = this->PolyPoints[i].x; tmpPoly[i].y = this->PolyPoints[i].y; } const Point* curves[1] = {tmpPoly}; int curvesPts[] = {MAXPOLY}; Scalar color; switch(this->status) { case PARKFREE: color = SCLGREEN; break; case PARKBUSY: color = SCLRED; break; case PARKWAIT: color = SCLBLUE; break; } polylines(Frame, curves, curvesPts, 1, true, color, 1); } void ParkSpotObj::plotRectangle(Mat Frame){ rectangle(Frame,this->ParkRect,SCLBLACK,2); } void ParkSpotObj::sortCorners() { vector<Point> top, bot; Point center; for (int i = 0; i < (int)this->PolyPoints.size(); i++) { center += this->PolyPoints[i]; } center *= (1. / this->PolyPoints.size()); for (int i = 0; i < (int)this->PolyPoints.size(); i++) { if (this->PolyPoints[i].y < center.y) top.push_back(this->PolyPoints[i]); else bot.push_back(this->PolyPoints[i]); } Point tl = (top[0].x > top[1].x ? top[1] : top[0]); Point tr = (top[0].x > top[1].x ? top[0] : top[1]); Point bl = (bot[0].x > bot[1].x ? bot[1] : bot[0]); Point br = (bot[0].x > bot[1].x ? bot[0] : bot[1]); this->PolyPoints.clear(); this->PolyPoints.push_back(tl); this->PolyPoints.push_back(tr); this->PolyPoints.push_back(br); this->PolyPoints.push_back(bl); } void ParkSpotObj::getWarpedDimension() { vector<int> xvec, yvec; vector<int> xdiff, ydiff; xvec.clear(); yvec.clear(); xdiff.clear(); ydiff.clear(); for (int i = 0; i < (int)this->PolyPoints.size(); i++) { xvec.push_back(this->PolyPoints[i].x); yvec.push_back(this->PolyPoints[i].y); } xdiff.push_back(xvec[1] - xvec[0]); xdiff.push_back(xvec[1] - xvec[3]); xdiff.push_back(xvec[2] - xvec[0]); xdiff.push_back(xvec[2] - xvec[3]); ydiff.push_back(yvec[3] - yvec[0]); ydiff.push_back(yvec[3] - yvec[1]); ydiff.push_back(yvec[2] - yvec[0]); ydiff.push_back(yvec[2] - yvec[1]); for (int i = 0; i < (int)xdiff.size(); i++) { xdiff[0] = (xdiff[0] >= xdiff[i] ? xdiff[0] : xdiff[i]); ydiff[0] = (ydiff[0] >= ydiff[i] ? ydiff[0] : ydiff[i]); } this->warpedDim = Point(xdiff[0], ydiff[0]); this->warpingPts.clear(); this->warpingPts.push_back(Point2f(0, 0)); this->warpingPts.push_back(Point2f(saturate_cast<float>(xdiff[0]), 0)); this->warpingPts.push_back(Point2f(saturate_cast<float>(xdiff[0]), saturate_cast<float>(ydiff[0]))); this->warpingPts.push_back(Point2f(0, saturate_cast<float>(ydiff[0]))); } void ParkSpotObj::plotParkNum(Mat input){ Point centralP(0,0); char P[5]; Scalar color; switch(this->status) { case PARKFREE: color = SCLGREEN; break; case PARKBUSY: color = SCLRED; break; case PARKWAIT: color = SCLBLUE; break; } for(int i = 0; i < (int)this->PolyPoints.size(); i++) { centralP += this->PolyPoints[i]; } centralP *= (1. / this->PolyPoints.size()); sprintf(P, "%d", this->nspot); putText(input, P, centralP, FONT_HERSHEY_COMPLEX_SMALL, 0.5, color, 1, CV_AA); } void ParkSpotObj::show(){ cout << "┌───────────┐ " << endl; cout << "│ PARK SPOT │ " << endl; cout << "└──┬────────┘ " << endl; cout << " │ " << endl; cout << " ├─> spot No: " << this->nspot << endl; cout << " │ " << endl; cout << " ├─> Posizione: " << this->ParkRect.x << ", " << this->ParkRect.y << endl; cout << " ├─> Dimensione: " << this->ParkRect.width << "x" << this->ParkRect.height << endl; cout << " │ " << endl; cout << " ├─> Status: " << this->status << endl; cout << " │ " << endl; cout << " ├─> IC buffer: "; for (int i = 0; i < FDFRAME; i++) { if(!(this->buffer[i].empty())) { cout << "[" << i << "]:EXISTS! "; } else { cout << "[" << i << "]:VOID! "; } } cout << endl; cout << " ├─> Hist New: "; for (int i = 0; i < HISTCOMP; i++) { if(!((this->hist.hist[i]).empty())) { cout << "["<< i <<"]:EXISTS! "; } else { cout << "[" << i << "]:VOID! "; } } cout << endl; cout << " ├─> Hist Old: "; for (int i = 0; i < HISTCOMP; i++) { if(!((this->hist_old.hist[i]).empty())) { cout << "[" << i << "]:EXISTS! "; } else { cout << "[" << i << "]:VOID! "; } } cout << endl; cout << " │ " << endl; cout << " ├─> Polyline: "; for (int i = 0; i < (int)this->PolyPoints.size(); i++) { cout << "P" << i << " = [" << this->PolyPoints[i].x << ", " << this->PolyPoints[i].y << "] "; } cout << endl; cout << " │ " << endl; cout << " └─> Parameters: "; for (int i = 0; i < (int)this->parameters.size(); i++) { cout << "[" << i << "]:[ " << this->parameters[i] << " ] "; } cout << endl; }
29.467826
167
0.602396
[ "vector" ]
7b7618a5a5c495cbdc263804fee3caa816043974
1,902
cpp
C++
Data Structure/Sort/Radix Sort/main.cpp
InnoFang/oh-my-algorithms
f559dba371ce725a926725ad28d5e1c2facd0ab2
[ "Apache-2.0" ]
19
2018-08-26T03:10:58.000Z
2022-03-07T18:12:52.000Z
Data Structure/Sort/Radix Sort/main.cpp
InnoFang/Algorithm-Library
1896b9d8b1fa4cd73879aaecf97bc32d13ae0169
[ "Apache-2.0" ]
null
null
null
Data Structure/Sort/Radix Sort/main.cpp
InnoFang/Algorithm-Library
1896b9d8b1fa4cd73879aaecf97bc32d13ae0169
[ "Apache-2.0" ]
6
2020-03-16T23:00:06.000Z
2022-01-13T07:02:08.000Z
#include <ctime> #include <queue> #include <vector> #include <algorithm> #include <iostream> void radixSort(std::vector<int>& arr) { int maxDigit = *max_element(arr.begin(), arr.end()); /* Counter consist of ten queues that store the number of the corresponding digit. */ std::queue<int> counter[10]; for (int i = 1, mod = 10, dev = 1; i < maxDigit; i *= 10, mod *= 10, dev *= 10) { for (int j = 0; j < arr.size(); ++j) { int bucket = (arr[j] % mod) / dev; counter[bucket].push(arr[j]); } int index = 0; /* `10` is the length of the counter */ for (int j = 0; j < 10; ++ j) { while (!counter[j].empty()) { arr[index++] = counter[j].front(); counter[j].pop(); } } } } std::vector<int> generateRandomArray(size_t length, size_t rangeFrom, size_t rangeTo); void printArray(const std::vector<int>& arr); int main() { size_t dataSize = 20; size_t rangeFrom = 1; size_t rangeTo = 10000; auto arr = generateRandomArray(dataSize, rangeFrom, rangeTo); std::cout << "Original array:" << std::endl; printArray(arr); radixSort(arr); std::cout << "Sorted array:" << std::endl; printArray(arr); return 0; } /* Randomly generate an array with the `dataSize`, which is from `rangeFrom` to `rangeTo` */ std::vector<int> generateRandomArray(size_t dataSize, size_t rangeFrom, size_t rangeTo) { size_t range = rangeTo - rangeFrom + 1; srand(time(nullptr)); std::vector<int> arr(dataSize); for (size_t i = 0; i < dataSize; ++ i) { arr[i] = rand() % range + rangeFrom; } return arr; } /* formatted output array */ void printArray(const std::vector<int>& arr) { for (const auto& num: arr) { std::cout << num << " "; } std::cout << std::endl; }
27.565217
92
0.564669
[ "vector" ]
7b7a8234088f37edf6dcd87dec0554ae26fb6719
1,725
cpp
C++
code/signet/commands/print_info/print_info.cpp
SamWindell/Signet
2f3ba0c75641360957d77b94fa335711dc3cd63b
[ "BSD-3-Clause" ]
11
2020-05-26T18:33:39.000Z
2022-02-24T15:14:23.000Z
code/signet/commands/print_info/print_info.cpp
SamWindell/Signet
2f3ba0c75641360957d77b94fa335711dc3cd63b
[ "BSD-3-Clause" ]
5
2020-05-26T13:48:06.000Z
2022-03-26T09:38:43.000Z
code/signet/commands/print_info/print_info.cpp
SamWindell/Signet
2f3ba0c75641360957d77b94fa335711dc3cd63b
[ "BSD-3-Clause" ]
1
2021-12-30T04:08:09.000Z
2021-12-30T04:08:09.000Z
#include "print_info.h" #include "CLI11.hpp" #include <cereal/archives/json.hpp> #include <cereal/types/optional.hpp> #include <cereal/types/string.hpp> #include <cereal/types/vector.hpp> #include "gain_calculators.h" CLI::App *PrintInfoCommand::CreateCommandCLI(CLI::App &app) { auto printer = app.add_subcommand( "print-info", "Prints information about the audio file(s), such as the embedded metadata, sample-rate and RMS."); return printer; } void PrintInfoCommand::ProcessFiles(AudioFiles &files) { for (auto &f : files) { std::string info_text; if (!f.GetAudio().metadata.IsEmpty()) { std::stringstream ss {}; { try { cereal::JSONOutputArchive archive(ss); archive(cereal::make_nvp("Metadata", f.GetAudio().metadata)); } catch (const std::exception &e) { ErrorWithNewLine(GetName(), f, "Internal error when writing fetch the metadata: {}", e.what()); } } info_text += ss.str() + "\n"; } else { info_text += "Contains no metadata that Signet understands\n"; } info_text += fmt::format("Channels: {}\n", f.GetAudio().num_channels); info_text += fmt::format("Sample Rate: {}\n", f.GetAudio().sample_rate); info_text += fmt::format("Bit-depth: {}\n", f.GetAudio().bits_per_sample); info_text += fmt::format("RMS: {:.5f}\n", GetRMS(f.GetAudio().interleaved_samples)); if (EndsWith(info_text, "\n")) info_text.resize(info_text.size() - 1); MessageWithNewLine(GetName(), f, "Info:\n{}", info_text); } }
37.5
107
0.578551
[ "vector" ]
7b7bbf8bdc4ea79fff76a344b57ec9835d6ec9f8
1,307
cpp
C++
coj.uci.cu/BadCowtractors.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
6
2016-09-10T03:16:34.000Z
2020-04-07T14:45:32.000Z
coj.uci.cu/BadCowtractors.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
null
null
null
coj.uci.cu/BadCowtractors.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
2
2018-08-11T20:55:35.000Z
2020-01-15T23:23:11.000Z
/* By: facug91 From: http://coj.uci.cu/24h/problem.xhtml?pid=1690 Name: Bad Cowtractors Date: 20/03/2015 */ #include <bits/stdc++.h> #define EPS 1e-9 #define DEBUG(x) cerr << "#" << (#x) << ": " << (x) << endl #define MP make_pair const double PI = 2.0*acos(0.0); #define INF 1000000000 //#define MOD 1000000 //#define MAXN 1000005 using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef vector<int> vi; typedef vector<ii> vii; int n, m, a, b, c, p[1005], number_sets, ans; vector<iii> edges; int find_set (int i) {return (i == p[i]) ? i : (p[i] = find_set(p[i]));} void union_set (int i, int j, int w) { int x = find_set(i); int y = find_set(j); if (x != y) { ans += w; p[y] = x; number_sets--; } } int main () { ios_base::sync_with_stdio(0); cin.tie(0); int i, j; cin>>n>>m; for (i=0; i<m; i++) { cin>>a>>b>>c; edges.push_back(MP(c, MP(a, b))); } sort(edges.begin(), edges.end(), greater<iii>()); for (i=1; i<=n; i++) p[i] = i; number_sets = n; ans = 0; for (i=0; i<edges.size(); i++) union_set(edges[i].second.first, edges[i].second.second, edges[i].first); if (number_sets == 1) cout<<ans<<"\n"; else cout<<"-1\n"; return 0; }
23.339286
106
0.557001
[ "vector" ]
7b80965c0bb37f8ef5f7e563b9e1618da657ad6f
8,331
cpp
C++
openstudiocore/src/utilities/geometry/Geometry.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/utilities/geometry/Geometry.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/utilities/geometry/Geometry.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2013, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <utilities/geometry/Geometry.hpp> #include <utilities/geometry/Transformation.hpp> #include <utilities/core/Assert.hpp> #include <boost/math/constants/constants.hpp> namespace openstudio{ /// convert degrees to radians double degToRad(double degrees) { return degrees*boost::math::constants::pi<double>()/180.0; } /// convert radians to degrees double radToDeg(double radians) { return radians*180.0/boost::math::constants::pi<double>(); } /// compute area from surface as Point3dVector boost::optional<double> getArea(const Point3dVector& points) { boost::optional<double> result; OptionalVector3d newall = getNewallVector(points); if (newall){ result = newall->length() / 2.0; } return result; } // compute Newall vector from Point3dVector, direction is same as outward normal // magnitude is twice the area OptionalVector3d getNewallVector(const Point3dVector& points) { OptionalVector3d result; unsigned N = points.size(); if (N >= 3){ Vector3d vec; for (unsigned i = 1; i < N-1; ++i){ Vector3d v1 = points[i] - points[0]; Vector3d v2 = points[i+1] - points[0]; vec += v1.cross(v2); } result = vec; } return result; } // compute outward normal from Point3dVector OptionalVector3d getOutwardNormal(const Point3dVector& points) { OptionalVector3d result = getNewallVector(points); if (result){ if (!result->normalize()){ result.reset(); } } return result; } /// compute centroid from surface as Point3dVector OptionalPoint3d getCentroid(const Point3dVector& points) { OptionalPoint3d result; if (points.size() >= 3){ // convert to face coordinates Transformation alignFace = Transformation::alignFace(points); Point3dVector surfacePoints = alignFace.inverse()*points; unsigned N = surfacePoints.size(); double A = 0; double cx = 0; double cy = 0; for (unsigned i = 0; i < N; ++i){ double x1, x2, y1, y2; if (i == N-1){ x1 = surfacePoints[i].x(); x2 = surfacePoints[0].x(); y1 = surfacePoints[i].y(); y2 = surfacePoints[0].y(); }else{ x1 = surfacePoints[i].x(); x2 = surfacePoints[i+1].x(); y1 = surfacePoints[i].y(); y2 = surfacePoints[i+1].y(); } double dA = (x1*y2-x2*y1); A += 0.5*dA; cx += (x1+x2)*dA; cy += (y1+y2)*dA; } if (A > 0){ // centroid in face coordinates Point3d surfaceCentroid(cx/(6.0*A), cy/(6.0*A), 0.0); // centroid result = alignFace*surfaceCentroid; } } return result; } /// reorder points to upper-left-corner convention Point3dVector reorderULC(const Point3dVector& points) { unsigned N = points.size(); if (N < 3){ return Point3dVector(); } // transformation to align face Transformation t = Transformation::alignFace(points); Point3dVector facePoints = t.inverse()*points; // find ulc index in face coordinates double maxY = std::numeric_limits<double>::min(); double minX = std::numeric_limits<double>::max(); unsigned ulcIndex = 0; for(unsigned i = 0; i < N; ++i){ OS_ASSERT(std::abs(facePoints[i].z()) < 0.001); if ((maxY < facePoints[i].y()) || ((maxY < facePoints[i].y() + 0.00001) && (minX > facePoints[i].x()))){ ulcIndex = i; maxY = facePoints[i].y(); minX = facePoints[i].x(); } } // no-op if (ulcIndex == 0){ return points; } // create result Point3dVector result; std::copy (points.begin() + ulcIndex, points.end(), std::back_inserter(result)); std::copy (points.begin(), points.begin() + ulcIndex, std::back_inserter(result)); OS_ASSERT(result.size() == N); return result; } std::vector<Point3d> removeColinear(const Point3dVector& points, double tol) { unsigned N = points.size(); if (N < 3){ return points; } std::vector<Point3d> result; Point3d lastPoint = points[0]; result.push_back(lastPoint); for (unsigned i = 1; i < N; ++i){ Point3d currentPoint = points[i]; Point3d nextPoint = points[0]; if (i < N-1){ nextPoint = points[i+1]; } Vector3d a = (currentPoint - lastPoint); Vector3d b = (nextPoint - currentPoint); // if these fail to normalize we have zero length vectors (e.g. adjacent points) if (a.normalize()){ if (b.normalize()){ Vector3d c = a.cross(b); if (c.length() >= tol){ // cross product is significant result.push_back(currentPoint); lastPoint = currentPoint; }else{ // see if dot product is near -1 double d = a.dot(b); if (d <= -1.0 + tol){ // this is a line reversal result.push_back(currentPoint); lastPoint = currentPoint; } } } } } return result; } double getDistance(const Point3d& point1, const Point3d& point2) { double dx = point1.x() - point2.x(); double dy = point1.y() - point2.y(); double dz = point1.z() - point2.z(); double result = std::sqrt(dx*dx + dy*dy + dz*dz); return result; } double getAngle(const Vector3d& vector1, const Vector3d& vector2) { Vector3d working1(vector1); working1.normalize(); Vector3d working2(vector2); working2.normalize(); return acos(working1.dot(working2)); } /// compute distance in meters between two points on the Earth's surface /// lat and lon are specified in degrees double getDistanceLatLon(double lat1, double lon1, double lat2, double lon2) { // for more accuracy would want to use WGS-84 ellipsoid params and Vincenty formula // Haversine formula double R = 6371000; // Earth radius meters double deltaLat = degToRad(lat2-lat1); double deltaLon = degToRad(lon2-lon1); double a = sin(deltaLat/2) * sin(deltaLat/2) + cos(degToRad(lat1)) * cos(degToRad(lat2)) * sin(deltaLon/2) * sin(deltaLon/2); double c = 2 * atan2(sqrt(a), sqrt(1-a)); double d = R * c; return d; } bool circularEqual(const Point3dVector& points1, const Point3dVector& points2, double tol) { unsigned N = points1.size(); if (N != points2.size()){ return false; } if (N == 0){ return true; } bool result = false; // look for a common starting point for (unsigned i = 0; i < N; ++i){ if (getDistance(points1[0], points2[i]) <= tol){ result = true; // check all other points for (unsigned j = 0; j < N; ++j){ if (getDistance(points1[j], points2[(i + j) % N]) > tol){ result = false; break; } } } if (result){ return result; } } return result; } } // openstudio
29.438163
111
0.569199
[ "geometry", "vector" ]
7b81c1f8b548e9d58c3f158e61ba1ca32ecbe1a0
4,388
cpp
C++
EasyCpp/Plugin/Manager.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
3
2018-02-06T05:12:41.000Z
2020-05-12T20:57:32.000Z
EasyCpp/Plugin/Manager.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
41
2016-07-11T12:19:10.000Z
2017-08-08T07:43:12.000Z
EasyCpp/Plugin/Manager.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
2
2019-08-02T10:24:36.000Z
2020-09-11T01:45:12.000Z
#include "Manager.h" #include "Plugin.h" #include <fstream> #include "IPluginDatabaseProvider.h" #include "IPluginScriptEngineFactoryProvider.h" #include "../Database/DatabaseDriverManager.h" #include "../Scripting/ScriptEngineManager.h" namespace EasyCpp { namespace Plugin { Manager::Manager() { } Manager::~Manager() { } void Manager::registerInterface(InterfacePtr iface) { auto name = iface->getName(); auto rev = iface->getVersion(); if (_server_ifaces.count({ name, rev })) { throw std::logic_error("Interface already registered"); } _server_ifaces.insert({ { name, rev }, iface }); } void Manager::loadPlugin(const std::string & name, const std::string & path, const std::vector<InterfacePtr>& server_ifaces) { if (_plugins.count(name)) throw std::runtime_error("Plugin name already used"); interface_map_t tmap = _server_ifaces; for (auto& e : server_ifaces) tmap.insert({ {e->getName(), e->getVersion()}, e }); auto plugin = std::make_shared<Plugin>(name, path, tmap); _plugins.insert({ name,plugin }); if (_autoregister) { // Autoregister EasyCpp Extensions if (this->hasInterface<IPluginDatabaseProvider>(name)) { auto iface = this->getInterface<IPluginDatabaseProvider>(name); for (auto& e : iface->getDriverMap()) { Database::DatabaseDriverManager::registerDriver(e.first, e.second); } } if (this->hasInterface<IPluginScriptEngineFactoryProvider>(name)) { auto iface = this->getInterface<IPluginScriptEngineFactoryProvider>(name); for (auto& e : iface->getFactories()) { Scripting::ScriptEngineManager::registerEngineFactory(e); } } } } void Manager::loadPluginFromMemory(const std::string & name, const std::vector<uint8_t>& data, const std::vector<InterfacePtr>& server_ifaces) { // Write data to a file and load it. char fname[L_tmpnam]; tmpnam((char*)&fname); { std::ofstream stream; stream.open(fname, std::ofstream::out | std::ofstream::binary); stream.write((const char*)data.data(), data.size()); stream.close(); } this->loadPlugin(name, fname, server_ifaces); } void Manager::deinitPlugin(const std::string & name) { if (!_plugins.count(name)) throw std::runtime_error("Plugin not found"); auto plugin = _plugins.at(name); if (_autoregister) { // Autoregister EasyCpp Extensions if (this->hasInterface<IPluginDatabaseProvider>(name)) { auto iface = this->getInterface<IPluginDatabaseProvider>(name); for (auto& e : iface->getDriverMap()) { Database::DatabaseDriverManager::deregisterDriver(e.first); } } if (this->hasInterface<IPluginScriptEngineFactoryProvider>(name)) { auto iface = this->getInterface<IPluginScriptEngineFactoryProvider>(name); for (auto& e : iface->getFactories()) { Scripting::ScriptEngineManager::deregisterEngineFactory(e); } } } plugin->deinit(); } bool Manager::canUnloadPlugin(const std::string & name) const { if (_plugins.count(name) == 0) throw std::runtime_error("Plugin not found"); return _plugins.at(name)->canUnload(); } void Manager::unloadPlugin(const std::string & name) { if (!_plugins.count(name)) throw std::runtime_error("Plugin not found"); auto plugin = _plugins.at(name); if (!plugin->canUnload()) throw std::runtime_error("Plugin is not ready for unloading"); _plugins.erase(name); } std::set<std::string> Manager::getPlugins() const { std::set<std::string> res; for (auto e : _plugins) res.insert(e.first); return res; } void Manager::setAutoRegisterExtensions(bool v) { _autoregister = v; } bool Manager::isAutoRegisterExtensions() const { return _autoregister; } InterfacePtr Manager::getInterface(const std::string & pluginname, const std::string & ifacename, uint64_t version) const { if (_plugins.count(pluginname) == 0) throw std::runtime_error("Plugin not found"); return _plugins.at(pluginname)->getInterface(ifacename, version); } bool Manager::hasInterface(const std::string & pluginname, const std::string & ifacename, uint64_t version) const { if (_plugins.count(pluginname) == 0) throw std::runtime_error("Plugin not found"); return _plugins.at(pluginname)->hasInterface(ifacename, version); } } }
29.253333
144
0.680264
[ "vector" ]
7b9669bcdfec63a5c9a0fad804c60a946698f385
8,174
cpp
C++
codeBase/CodeJam/2014/2014_Q_C/2014_Q_C.cpp
suren3141/codeBase
10ed9a56aca33631dc8c419cd83859c19dd6ff09
[ "Apache-2.0" ]
3
2020-03-16T14:59:08.000Z
2021-07-28T20:51:53.000Z
codeBase/CodeJam/2014/2014_Q_C/2014_Q_C.cpp
suren3141/codeBase
10ed9a56aca33631dc8c419cd83859c19dd6ff09
[ "Apache-2.0" ]
2
2016-04-16T05:39:20.000Z
2016-06-06T12:24:56.000Z
codeBase/CodeJam/2014/2014_Q_C/2014_Q_C.cpp
killerilaksha/codeBase
91cbd950fc90066903e58311000784aeba4ffc02
[ "Apache-2.0" ]
18
2020-02-17T23:17:37.000Z
2021-07-28T20:52:13.000Z
/* Copyright Hackers' Club, University Of Peradeniya Author : E/13/181 (Samurdhi Karunarathne) 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 <stdio.h> #include <iostream> #include <sstream> #include <cstring> #include <climits> #include <algorithm> #include <vector> #include <map> #include <cmath> #include <memory> #include <string> #include <set> using namespace std; vector<int> primes{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47}; vector<int> findd(vector<int> coins, map<int, vector<int> > &mp, int num, int x) { vector<int> ret; for (int i = 0; i < coins.size(); i++) { if (num % coins[i] == 0 && ((num - (num % coins[i])) / coins[i] <= x)) { vector<int> ret; for (int j = 0; j < (num - (num % coins[i])) / coins[i]; j++) ret.push_back(coins[i]); return ret; } } for (unsigned int i = coins.size(); i-- > 0;) { if (num > coins[i]) { vector<int> ans; if (mp.find(num - coins[i]) != mp.end()) ans = mp[num - coins[i]]; else { vector<int> tmp = findd(coins, mp, num - coins[i], x - 1); mp[num - coins[i]] = tmp; ans = tmp; } if (ans.size() != 0) { ans.push_back(coins[i]); sort(ans.begin(), ans.end()); return ans; } } } return ret; } bool solve(int r, int c, int m, int t) { char grid[r][c]; int e = r * c - m; if (e == 0) return false; if (m == 0) { cout << "Case #" << (t + 1) << ":" << endl; //<<r<<" "<<c<<" "<<m<<endl; for (int j = 0; j < r; j++) { for (int k = 0; k < c; k++) grid[j][k] = '.'; } grid[0][0] = 'c'; for (int j = 0; j < r; j++) { for (int k = 0; k < c; k++) cout << grid[j][k]; cout << endl; } return true; } if (r == 1) { cout << "Case #" << (t + 1) << ":" << endl; //<<r<<" "<<c<<" "<<m<<endl; cout << 'c'; for (int j = 1; j < e; j++) cout << '.'; for (int j = e; j < c; j++) cout << '*'; cout << endl; return true; } if (c == 1) { cout << "Case #" << (t + 1) << ":" << endl; //<<r<<" "<<c<<" "<<m<<endl; cout << 'c' << endl; for (int j = 1; j < e; j++) cout << '.' << endl; for (int j = e; j < r; j++) cout << '*' << endl; return true; } if (e == 1) { cout << "Case #" << (t + 1) << ":" << endl; for (int k = 0; k < r; k++) { for (int g = 0; g < c; g++) grid[k][g] = '*'; } grid[0][0] = 'c'; for (int k = 0; k < r; k++) { for (int g = 0; g < c; g++) cout << grid[k][g]; cout << endl; } return true; } if (e < 4) return false; for (int k = 0; k < r; k++) { for (int g = 0; g < c; g++) grid[k][g] = '-'; } for (int j = 2; j <= r; j++) { if (e % j == 0 && (e / j) <= c && (e / j) >= 2) { for (int k = 0; k < j; k++) { for (int g = 0; g < (e / j); g++) grid[k][g] = '.'; } grid[0][0] = 'c'; for (int k = 0; k < r; k++) { for (int g = 0; g < c; g++) { if (grid[k][g] != '.' && grid[k][g] != 'c') grid[k][g] = '*'; } } cout << "Case #" << (t + 1) << ":" << endl; for (int k = 0; k < r; k++) { for (int g = 0; g < c; g++) cout << grid[k][g]; cout << endl; } return true; } } if (e <= r * 2) { if (e % 2 == 0) { //cout<<"one"<<endl; for (int j = 0; j < e / 2; j++) {grid[j][0] = '.'; grid[j][1] = '.';} for (int j = e / 2; j < r; j++) {grid[j][0] = '*'; grid[j][1] = '*';} grid[0][0] = 'c'; for (int j = 2; j < c; j++) { for (int k = 0; k < r; k++) grid[k][j] = '*'; } cout << "Case #" << (t + 1) << ":" << endl; //<<r<<" "<<c<<" "<<m<<endl; for (int j = 0; j < r; j++) { for (int k = 0; k < c; k++) cout << grid[j][k]; cout << endl; } return true; } } if (e <= c * 2) { if (e % 2 == 0) { //cout<<"three"<<endl; for (int j = 0; j < e / 2; j++) {grid[0][j] = '.'; grid[1][j] = '.';} for (int j = e / 2; j < c; j++) {grid[0][j] = '*'; grid[1][j] = '*';} grid[0][0] = 'c'; cout << "Case #" << (t + 1) << ":" << endl; //<<r<<" "<<c<<" "<<m<<endl; for (int j = 0; j < 2; j++) { for (int k = 0; k < c; k++) cout << grid[j][k]; cout << endl; } for (int j = 2; j < r; j++) { for (int k = 0; k < c; k++) cout << '*'; cout << endl; } return true; } } for (int u = 3; u <= r; u++) { vector<int> feed; /*int ind=0; while(primes[ind]<u&&ind<=14){ feed.push_back(primes[ind]); ind++; }*/ for (int h = 2; h <= u; h++) feed.push_back(h); map<int, vector<int> > mp; vector<int> ret = findd(feed, mp, e - u * 2, c - 2); if (ret.size() != 0) { //cout<<"rrrr "<<u<<endl; sort(ret.rbegin(), ret.rend()); for (int j = 0; j < 2; j++) { for (int k = 0; k < u; k++) grid[k][j] = '.'; } for (int j = 2; j < (2 + ret.size()); j++) { for (int k = 0; k < ret[j - 2]; k++) grid[k][j] = '.'; } grid[0][0] = 'c'; for (int k = 0; k < r; k++) { for (int g = 0; g < c; g++) { if (grid[k][g] != '.' && grid[k][g] != 'c') grid[k][g] = '*'; } } cout << "Case #" << (t + 1) << ":" << endl; //<<r<<" "<<c<<" "<<m<<endl; for (int j = 0; j < r; j++) { for (int k = 0; k < c; k++) cout << grid[j][k]; cout << endl; } return true; } } for (int u = 3; u <= c; u++) { //cout<<"ccccc"<<endl; vector<int> feed; /*int ind=0; while(primes[ind]<u&&ind<=14){ feed.push_back(primes[ind]); ind++; }*/ for (int h = 2; h <= u; h++) feed.push_back(h); map<int, vector<int> > mp; vector<int> ret = findd(feed, mp, e - u * 2, r - 2); if (ret.size() != 0) { sort(ret.rbegin(), ret.rend()); for (int j = 0; j < 2; j++) { for (int k = 0; k < u; k++) grid[j][k] = '.'; } for (int j = 2; j < (2 + ret.size()); j++) { for (int k = 0; k < ret[j - 2]; k++) grid[j][k] = '.'; } grid[0][0] = 'c'; for (int k = 0; k < r; k++) { for (int g = 0; g < c; g++) { if (grid[k][g] != '.' && grid[k][g] != 'c') grid[k][g] = '*'; } } cout << "Case #" << (t + 1) << ":" << endl; //<<r<<" "<<c<<" "<<m<<endl; for (int j = 0; j < r; j++) { for (int k = 0; k < c; k++) cout << grid[j][k]; cout << endl; } return true; } } return false; } int main() { ios_base::sync_with_stdio(false); int t; cin >> t; for (int i = 0; i < t; i++) { int r, c, m; cin >> r >> c >> m; if (!solve(r, c, m, i)) cout << "Case #" << (i + 1) << ":" << endl << "Impossible" << endl; } return 0; }
34.782979
99
0.363347
[ "vector" ]
7b9ff32945673b6a57e67252f2c5db4575c82b86
15,579
cxx
C++
EVE/EveDet/AliEveITSModuleStepper.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
EVE/EveDet/AliEveITSModuleStepper.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
EVE/EveDet/AliEveITSModuleStepper.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
// $Id$ // Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007 /************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ #include "AliEveITSModuleStepper.h" #include "AliEveITSDigitsInfo.h" #include "AliEveITSScaledModule.h" #include <TEveManager.h> #include <TEveGedEditor.h> #include <TEveGridStepper.h> #include <TEveTrans.h> #include <TGLRnrCtx.h> #include <TGLIncludes.h> #include <TGLSelectRecord.h> #include <TGLUtil.h> #include <TGLViewer.h> #include <TGLAxis.h> #include <TMath.h> #include <THLimitsFinder.h> #include <TVirtualPad.h> #include <RVersion.h> //______________________________________________________________________________ // // Display scaled ITS modules in a paged layout, also providing // GL-overaly control GUI. ClassImp(AliEveITSModuleStepper) AliEveITSModuleStepper::AliEveITSModuleStepper(AliEveITSDigitsInfo* di) : TEveElementList("ITS 2DStore", "AliEveITSModuleStepper", kTRUE), fDigitsInfo(di), fScaleInfo(0), fStepper(0), fModuleIDs(), fPosition(0), fSubDet(-1), fModuleFont(), fTextFont(), fSymbolFont(), fAxis(0), fMenuHeight(0.13), fTextSize(64), fTextCol(kGray+1), fActiveCol(kRed-4), fActiveID(-1) { // Constructor. SetMainColorPtr(&fTextCol); fAxis = new TGLAxis(); // override member from base TEveElementList fChildClass = AliEveITSScaledModule::Class(); fDigitsInfo->IncRefCount(); fStepper = new TEveGridStepper(); fStepper->SetNs(5, 4); fScaleInfo = new AliEveDigitScaleInfo(); fScaleInfo->IncRefCount(); gEve->GetDefaultGLViewer()->AddOverlayElement(this); } AliEveITSModuleStepper::~AliEveITSModuleStepper() { // Destructor. gEve->GetDefaultGLViewer()->RemoveOverlayElement(this); fScaleInfo->DecRefCount(); fDigitsInfo->DecRefCount(); delete fStepper; delete fAxis; } /******************************************************************************/ void AliEveITSModuleStepper::Capacity() { // Make sure we have just enough children (module representations) // to store as many modules as required by the grid-stepper // configuration. Int_t n = fStepper->GetNx()*fStepper->GetNy(); if (n != NumChildren()) { DestroyElements(); for (Int_t m=0; m<n; ++m) { AddElement(new AliEveITSScaledModule(m, fDigitsInfo, fScaleInfo)); } } } /******************************************************************************/ void AliEveITSModuleStepper::SetFirst(Int_t first) { // Se module ID which apply to first item in stepper. Int_t lastpage = fModuleIDs.size()/Nxy(); if (fModuleIDs.size() % Nxy() ) lastpage++; Int_t firstLastpage = (lastpage - 1)*Nxy(); if (first > firstLastpage) first = firstLastpage; if (first < 0) first = 0; fPosition = first; Apply(); } void AliEveITSModuleStepper::Start() { // Go to first page. fPosition = 0; Apply(); } void AliEveITSModuleStepper::Next() { // Go to next page. SetFirst(fPosition + Nxy()); } void AliEveITSModuleStepper::Previous() { // Go to previous page. SetFirst(fPosition - Nxy()); } void AliEveITSModuleStepper::End() { // Go to last page. Int_t lastpage = fModuleIDs.size()/Nxy(); if (fModuleIDs.size() % Nxy()) lastpage++; fPosition = (lastpage - 1)*Nxy(); fStepper->Reset(); Apply(); } /******************************************************************************/ void AliEveITSModuleStepper::DisplayDet(Int_t det, Int_t layer) { // Select modules to display by sub-det type / layer. fSubDet = det; fModuleIDs.clear(); AliEveITSModuleSelection sel = AliEveITSModuleSelection(); sel.SetType (det); sel.SetLayer(layer); fDigitsInfo->GetModuleIDs(&sel, fModuleIDs); //in reder menu define a space between left and right pager Start(); } /******************************************************************************/ Int_t AliEveITSModuleStepper::GetCurrentPage() const { // Get number of current page. Int_t idx = fPosition + 1; Int_t n = idx/Nxy(); if (idx % Nxy()) n++; return n; } /******************************************************************************/ Int_t AliEveITSModuleStepper::GetPages() { // Get number of all pages. Int_t n = fModuleIDs.size()/Nxy(); if (fModuleIDs.size() % Nxy()) n++; return n; } /******************************************************************************/ void AliEveITSModuleStepper::Apply() { // Apply current settings to children modules. gEve->DisableRedraw(); Capacity(); UInt_t idx = fPosition; for(List_i childit=fChildren.begin(); childit!=fChildren.end(); ++childit) { if (idx < fModuleIDs.size()) { AliEveITSScaledModule* mod = static_cast<AliEveITSScaledModule*>(*childit); mod->SetID(fModuleIDs[idx], kFALSE); TEveTrans& tr = mod->RefMainTrans(); tr.UnitTrans(); tr.RotateLF(3,2,TMath::PiOver2()); tr.RotateLF(1,3,TMath::PiOver2()); // scaling Float_t mz, mx; Float_t* fp = mod->GetFrame()->GetFramePoints(); // switch x,z it will be rotated afterwards mx = -2*fp[0]; mz = -2*fp[2]; // fit width first Double_t sx = fStepper->GetDx(); Double_t sy = (mx*fStepper->GetDx())/mz; if (sy > fStepper->GetDy()) { sy = fStepper->GetDy(); sx = (mz*fStepper->GetDx())/mx; } Float_t scale = (0.85*sx)/mz; tr.Scale(scale, scale, scale); Float_t p[3]; fStepper->GetPosition(p); tr.SetPos(p[0]+0.5*fStepper->GetDx(), p[1]+0.5*fStepper->GetDy(), p[2]+0.5*fStepper->GetDz()); if (mod->GetSubDetID() == 2) mod->SetName(Form("SSD %d", idx)); else if (mod->GetSubDetID() == 1) mod->SetName(Form("SDD %d", idx)); else mod->SetName(Form("SPD %d", idx)); mod->SetRnrSelf(kTRUE); fStepper->Step(); idx++; } else { (*childit)->SetRnrSelf(kFALSE); } } fStepper->Reset(); ElementChanged(); gEve->EnableRedraw(); } /******************************************************************************/ // Virtual event handlers from TGLOverlayElement /******************************************************************************/ //______________________________________________________________________________ Bool_t AliEveITSModuleStepper::Handle(TGLRnrCtx & /*rnrCtx*/, TGLOvlSelectRecord & rec, Event_t * event) { // Handle overlay event. // Return TRUE if event was handled. switch (event->fType) { case kMotionNotify: { Int_t item = rec.GetN() < 2 ? -1 : (Int_t)rec.GetItem(1); if (fActiveID != item) { fActiveID = item; return kTRUE; } else { return kFALSE; } break; } case kButtonPress: { if (event->fCode != kButton1) { return kFALSE; } switch (rec.GetItem(1)) { case 1: Previous(); break; case 2: Start(); break; case 3: Next(); break; case 4: End(); break; case 5: { AliEveDigitScaleInfo* si = fScaleInfo; if (si->GetScale() < 5) { si->ScaleChanged(si->GetScale() + 1); ElementChanged(kTRUE, kTRUE); } break; } case 6: { AliEveDigitScaleInfo* si = fScaleInfo; if (si->GetScale() > 1) { si->ScaleChanged(si->GetScale() - 1); ElementChanged(kTRUE, kTRUE); } break; } case 7: gEve->GetEditor()->DisplayElement(*BeginChildren()); break; case 8: DisplayDet(0, -1); break; case 9: DisplayDet(1, -1); break; case 10: DisplayDet(2, -1); break; default: break; } return kTRUE; break; } default: break; } // end switch return kFALSE; } //______________________________________________________________________________ Bool_t AliEveITSModuleStepper::MouseEnter(TGLOvlSelectRecord& /*rec*/) { // Mouse has entered overlay area. return kTRUE; } //______________________________________________________________________________ void AliEveITSModuleStepper::MouseLeave() { // Mouse has left overlay area. fActiveID = -1; } /******************************************************************************/ // Protected sub-renderers /******************************************************************************/ //______________________________________________________________________________ void AliEveITSModuleStepper::RenderText(const char* txt, Int_t id, const TGLFont &font, Float_t step) { // Render text for button id. Float_t llx, lly, llz, urx, ury, urz; font.BBox(txt, llx, lly, llz, urx, ury, urz); (fActiveID == id && id > 0) ? TGLUtil::Color(fActiveCol) :TGLUtil::Color(fTextCol); if (step > 0) { // center text in the step interval glPushMatrix(); if (step>urx) glTranslatef((step-urx+llx)*0.5f-llx, 0, 0); glLoadName(id); font.Render(txt); glPopMatrix(); glTranslatef(step, 0, 0); } else { glLoadName(id); glPushMatrix(); font.Render(txt); glPopMatrix(); glTranslatef(urx, 0, 0); } } //______________________________________________________________________________ void AliEveITSModuleStepper::RenderPalette(TEveRGBAPalette* p) { // Render color palette with number axis. Float_t length = 7*fTextSize; Float_t x = 1.5*fTextSize; Float_t y = 0.2*fTextSize; glTranslatef(x, 0.8*fTextSize, 0); TGLCapabilitySwitch lights_off(GL_LIGHTING, kFALSE); glPushAttrib(GL_ENABLE_BIT | GL_POLYGON_BIT); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBegin(GL_QUAD_STRIP); TGLUtil::Color4ubv(p->ColorFromValue(p->GetMinVal())); glVertex2f(0, 0); glVertex2f(0, y); if (p->GetMaxVal() > p->GetMinVal() + 1) { Float_t xs = length/(p->GetMaxVal() - p->GetMinVal()); Float_t x0 = xs; for(Int_t i=p->GetMinVal() + 1; i<p->GetMaxVal(); i++) { TGLUtil::Color4ubv(p->ColorFromValue(i)); glVertex2f(x0, 0); glVertex2f(x0, y); x0+=xs; } } TGLUtil::Color4ubv(p->ColorFromValue(p->GetMaxVal())); glVertex2f(length, 0); glVertex2f(length, y); glEnd(); glRotatef(-90, 1, 0, 0 ); Double_t v1[3] = {0., 0., 0.}; Double_t v2[3] = {length, 0, 0.}; fAxis->SetTextColor(kGray+1); fAxis->SetLineColor(kGray+1); fAxis->PaintGLAxis(v1, v2, p->GetMinVal(), p->GetMaxVal(), 5); glPopAttrib(); } //______________________________________________________________________________ void AliEveITSModuleStepper::RenderMenu(Int_t curP, Int_t maxP, Int_t scaleX, Int_t scaleZ) { // Make UI to set page in stepper and UI to scale in the AliEveITSScaledModule. TGLUtil::Color(fTextCol); fTextFont.PreRender(); glTranslatef(0, fTextSize*0.3, 0); { // pager glTranslatef(fTextSize*0.2, 0 , 0); RenderText("9", 2, fSymbolFont); // last page RenderText("3", 1, fSymbolFont);//last page RenderText(Form("%d/%d", curP, maxP),-1, fTextFont, 2.7*fTextSize); //status { // bugg in webdings font , bbox does not give realistic value Float_t llx, lly, llz, urx, ury, urz; fSymbolFont.BBox("4", llx, lly, llz, urx, ury, urz); glTranslatef(-llx, 0, 0); } RenderText("4", 3, fSymbolFont); // next page RenderText(":",4, fSymbolFont); // last page } { // scale glTranslatef(fTextSize,0, 0); RenderText(Form("Zoom:"), -1, fTextFont); RenderText("6", 6, fSymbolFont); RenderText("5", 5, fSymbolFont); RenderText(Form("%dx%d", scaleX, scaleZ), -1, fTextFont, 2*fTextSize); } { // detectors glTranslatef(fTextSize, 0, 0); RenderText("SPD ", 8, fTextFont); RenderText("SDD ", 9, fTextFont); RenderText("SSD ", 10, fTextFont); fTextFont.PostRender(); } } //______________________________________________________________________________ void AliEveITSModuleStepper::RenderModuleIDs() { // Render module-ids. Double_t x, y, z; UInt_t idx = fPosition; Float_t llx, lly, llz, urx, ury, urz; fModuleFont.PreRender(); TGLUtil::Color(kWhite); for (List_i childit=fChildren.begin(); childit!=fChildren.end(); ++childit) { if (idx < fModuleIDs.size()) { AliEveITSScaledModule* mod = static_cast<AliEveITSScaledModule*>(*childit); TEveTrans& tr = mod->RefMainTrans(); tr.GetPos(x,y,z); x += fStepper->GetDx()*0.5; y -= fStepper->GetDy()*0.5; z += 0.4; // !!! MT hack - cross check with overlay rendering. const char* txt = Form("%d",mod->GetID()); fModuleFont.BBox(txt, llx, lly, llz, urx, ury, urz); glRasterPos3f(x, y, z); glBitmap(0, 0, 0, 0,-urx, 0, 0); fModuleFont.Render(txt); idx++; } } fModuleFont.PostRender(); } /******************************************************************************/ void AliEveITSModuleStepper::Render(TGLRnrCtx& rnrCtx) { // Render the overlay elements. AliEveITSScaledModule* sm = static_cast<AliEveITSScaledModule*>(*BeginChildren()); Int_t scaleIdx = fScaleInfo->GetScale() - 1; Int_t cnx = 0, cnz = 0; switch(sm->GetSubDetID()) { case 0: cnx = fDigitsInfo->fSPDScaleX[scaleIdx]; cnz = fDigitsInfo->fSPDScaleZ[scaleIdx]; break; case 1: cnx = fDigitsInfo->fSDDScaleX[scaleIdx]; cnz = fDigitsInfo->fSDDScaleZ[scaleIdx]; break; case 2: cnx = fDigitsInfo->fSSDScale[scaleIdx]; cnz = 1; break; } // init fonts if (fTextFont.GetMode() == TGLFont::kUndef) { #if ROOT_VERSION_CODE >= 332547 rnrCtx.RegisterFont(fTextSize, 4, TGLFont::kTexture, fTextFont); rnrCtx.RegisterFont(72, 31, TGLFont::kTexture, fSymbolFont); rnrCtx.RegisterFont(14, 4, TGLFont::kPixmap, fModuleFont); #else fTextFont = rnrCtx.GetFont(fTextSize, 4, TGLFont::kTexture); fSymbolFont = rnrCtx.GetFont(72, 31, TGLFont::kTexture); fModuleFont = rnrCtx.GetFont(14, 4, TGLFont::kPixmap); #endif } { // toolbar glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); if (rnrCtx.Selection()) { TGLRect rect(*rnrCtx.GetPickRectangle()); rnrCtx.GetCamera()->WindowToViewport(rect); gluPickMatrix(rect.X(), rect.Y(), rect.Width(), rect.Height(), (Int_t*) rnrCtx.GetCamera()->RefViewport().CArr()); } glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(-1, -1, 0); // translate to lower left corner Float_t txtScale = fMenuHeight/fTextSize*0.5; // scale text glScalef(txtScale, txtScale, 1.); //menu glPushName(0); RenderMenu(GetCurrentPage(), GetPages(), cnx, cnz); glPopName(); //palette Double_t labelSize = 1.6*txtScale*fTextSize; fAxis->SetLabelsSize(labelSize); fAxis->SetLabelsOffset(1.2*labelSize); RenderPalette(sm->GetPalette()); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } RenderModuleIDs(); }
25.835821
101
0.591566
[ "render" ]
7ba598b37c075d6f076caee5857982ea801fbb86
4,602
cpp
C++
kmeans/kmeans_flex.cpp
oprecomp/flexfloat-benchmarks
0acb1a53c57901e873ee7ba69e4f2bf9c2fbe348
[ "Apache-2.0" ]
2
2019-02-06T15:34:56.000Z
2020-02-20T23:44:27.000Z
kmeans/kmeans_flex.cpp
oprecomp/flexfloat-benchmarks
0acb1a53c57901e873ee7ba69e4f2bf9c2fbe348
[ "Apache-2.0" ]
null
null
null
kmeans/kmeans_flex.cpp
oprecomp/flexfloat-benchmarks
0acb1a53c57901e873ee7ba69e4f2bf9c2fbe348
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 - The OPRECOMP Project Consortium, Alma Mater Studiorum Università di Bologna. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "flexfloat.hpp" #define TH 0.001f #define MAX_ITERATIONS 500 #ifndef CLUSTERS #define CLUSTERS 4 #endif #ifndef OBJS #define OBJS 100 #endif #ifndef COORDS #define COORDS 18 #endif #ifndef FLOAT #define FLOAT double #endif FLOAT distance(int ndims, FLOAT *a, FLOAT *b) { flexfloat<EXP_DIST, FRAC_DIST> dist = 0.0; for(int i=0; i<ndims; ++i) dist += flexfloat<EXP_DIST, FRAC_DIST>((flexfloat<EXP_TEMP1, FRAC_TEMP1>(flexfloat<EXP_OBJECT, FRAC_OBJECT>(a[i]))-flexfloat<EXP_TEMP1, FRAC_TEMP1>(flexfloat<EXP_CLUSTER, FRAC_CLUSTER>(b[i]))))* flexfloat<EXP_DIST, FRAC_DIST>((flexfloat<EXP_TEMP2, FRAC_TEMP2>(flexfloat<EXP_OBJECT, FRAC_OBJECT>(a[i]))-flexfloat<EXP_TEMP2, FRAC_TEMP2>(flexfloat<EXP_CLUSTER, FRAC_CLUSTER>(b[i])))); return FLOAT(dist); } int find_nearest(int nclusters, int ndims, FLOAT *object, FLOAT **clusters) { int nearest_index = 0; flexfloat<EXP_DIST, FRAC_DIST> min_dist = flexfloat<EXP_DIST, FRAC_DIST>(distance(ndims, object, clusters[0])); flexfloat<EXP_DIST, FRAC_DIST> dist; for(int i=1; i<nclusters; ++i) { dist = flexfloat<EXP_DIST, FRAC_DIST>(distance(ndims, object, clusters[i])); if (dist < min_dist) { nearest_index = i; min_dist = dist; } } return nearest_index; } void kmeans(FLOAT **objects, int nobjs, int nclusters, int ndims, FLOAT threshold, int *memberof, FLOAT **clusters) { int index; int iterations=0; FLOAT delta; FLOAT **iterClusters; int *iterClustersSize; iterClusters = (FLOAT**) malloc(nclusters * sizeof(FLOAT*)); iterClusters[0] = (FLOAT*) malloc(nclusters * ndims * sizeof(FLOAT)); for(int i=1; i<nclusters; ++i) iterClusters[i] = iterClusters[i-1] + ndims; iterClustersSize = (int*) malloc(nclusters * sizeof(int)); for (int i=0; i<nobjs; ++i) memberof[i] = -1; do { delta = 0.0; for(int i=0; i<nobjs; ++i) { index = find_nearest(nclusters, ndims, objects[i], clusters); if(memberof[i] != index) delta += 1.0; memberof[i] = index; for(int j=0; j<ndims; ++j) iterClusters[index][j] += objects[i][j]; iterClustersSize[index]++; } for(int i=0; i<nclusters; ++i) { for (int j=0; j<ndims; ++j) { if(iterClustersSize[i] > 0) clusters[i][j] = iterClusters[i][j] / iterClustersSize[i]; iterClusters[i][j] = 0.0; } iterClustersSize[i] = 0; } delta /= nobjs; } while(delta > threshold && iterations++ < MAX_ITERATIONS); free(iterClusters[0]); free(iterClusters); free(iterClustersSize); } int main() { int nclusters = CLUSTERS; int ndims = COORDS; int nobjs = OBJS; int *memberof; FLOAT **objects; FLOAT **clusters; FLOAT threshold = TH; objects = (FLOAT**)malloc(nobjs * sizeof(FLOAT*)); objects[0] = (FLOAT*) malloc(nobjs * ndims * sizeof(FLOAT)); for(int i=1; i<nobjs; ++i) objects[i] = objects[i-1] + ndims; for(int i=0; i < nobjs; ++i) for(int j=0; j<ndims; ++j) objects[i][j] = ((FLOAT)rand() / (FLOAT)RAND_MAX) * i; memberof = (int*) malloc(nobjs * sizeof(int)); clusters = (FLOAT**) malloc(nclusters * sizeof(FLOAT*)); clusters[0] = (FLOAT*) malloc(nclusters * ndims * sizeof(FLOAT)); for (int i=1; i<nclusters; ++i) clusters[i] = clusters[i-1] + ndims; kmeans(objects, nobjs, nclusters, ndims, threshold, memberof, clusters); for(int i=0; i < nclusters * ndims; ++i) printf("%.15f,", clusters[0][i]); //print_flexfloat_stats(); free(objects[0]); free(objects); free(clusters[0]); free(clusters); free(memberof); return 0; }
30.68
202
0.619948
[ "object" ]
7baa3f0142172805c4a2ab9ac7b82d2d35eaf1f7
8,767
cpp
C++
json/json.cpp
LB--/json
3ca71de40a7a8ab2b68fef652dd76424720b92aa
[ "Unlicense" ]
1
2016-05-22T22:13:58.000Z
2016-05-22T22:13:58.000Z
json/json.cpp
LB--/json
3ca71de40a7a8ab2b68fef652dd76424720b92aa
[ "Unlicense" ]
2
2016-05-14T03:59:21.000Z
2016-10-11T22:19:44.000Z
json/json.cpp
LB--/json
3ca71de40a7a8ab2b68fef652dd76424720b92aa
[ "Unlicense" ]
null
null
null
#include "json.hpp" #include "LB/utf/utf.hpp" #include <functional> #include <iomanip> #include <limits> #include <sstream> #include <utility> namespace LB { namespace json { struct value::base { virtual ~base() noexcept = default; friend bool operator==(base const &a, base const &b) noexcept { return a.equals(b); } friend bool operator<(base const &a, base const &b) noexcept { return a.less(b); } virtual bool equals(base const &) const noexcept = 0; virtual bool less(base const &) const noexcept = 0; virtual base *clone() const noexcept = 0; }; template<typename T> struct value::wrap final : base { T v; wrap() noexcept : v{} { } wrap(T const &t) noexcept : v(t) { } wrap(T &&t) noexcept : v(t) { } wrap(wrap const &w) noexcept : v(w.v) { } wrap(wrap &&) noexcept = default; wrap &operator=(wrap const &) = delete; wrap &operator=(wrap &&) = delete; virtual bool equals(base const &p) const noexcept override { if(auto w = dynamic_cast<wrap const *>(&p)) { return v == w->v; } return false; } virtual bool less(base const &p) const noexcept override { if(auto w = dynamic_cast<wrap const *>(&p)) { return v < w->v; } return false; } virtual wrap *clone() const noexcept override { return new wrap{*this}; } }; value::value(std::nullptr_t) noexcept : t{type::null} , p{nullptr} { } value::value(bool v) : t{type::boolean} , p{new wrap<bool>{v}} { } value::value(integer v) : t{type::integer} , p{new wrap<integer>{v}} { } value::value(real v) : t{type::real} , p{new wrap<real>{v}} { } value::value(string const &v) : t{type::string} , p{new wrap<string>{v}} { } value::value(string &&v) : t{type::string} , p{new wrap<string>{v}} { } value::value(array const &v) : t{type::array} , p{new wrap<array>{v}} { } value::value(array &&v) : t{type::array} , p{new wrap<array>{v}} { } value::value(object const &v) : t{type::object} , p{new wrap<object>{v}} { } value::value(object &&v) : t{type::object} , p{new wrap<object>{v}} { } value::value(value const &v) : t{v.t} , p{v.p? v.p->clone() : nullptr} { } value::value(value &&) noexcept = default; value &value::operator=(value const &v) { t = v.t; p.reset(v.p? v.p->clone() : nullptr); return *this; } value &value::operator=(value &&) noexcept = default; value::~value() noexcept = default; bool operator==(value const &a, value const &b) noexcept { return a.t == b.t && a.t != type::null && *a.p == *b.p; } bool operator<(value const &a, value const &b) noexcept { return json::operator</*work around VC++ bug*/(a.t, b.t) || ( a.t == b.t && a.t != type::null && *a.p < *b.p); } bool value::boolean_value() const { return dynamic_cast<wrap<bool> const &>(*p).v; } bool const &value::boolean_cref() const & { return dynamic_cast<wrap<bool> const &>(*p).v; } bool &value::boolean_ref() & { return dynamic_cast<wrap<bool> &>(*p).v; } integer value::integer_value() const { return dynamic_cast<wrap<integer> const &>(*p).v; } integer const &value::integer_cref() const & { return dynamic_cast<wrap<integer> const &>(*p).v; } integer &value::integer_ref() & { return dynamic_cast<wrap<integer> &>(*p).v; } real value::real_value() const { return dynamic_cast<wrap<real> const &>(*p).v; } real const &value::real_cref() const & { return dynamic_cast<wrap<real> const &>(*p).v; } real &value::real_ref() & { return dynamic_cast<wrap<real> &>(*p).v; } string const &value::string_cref() const & { return dynamic_cast<wrap<string> const &>(*p).v; } string &value::string_ref() & { return dynamic_cast<wrap<string> &>(*p).v; } array const &value::array_cref() const & { return dynamic_cast<wrap<array> const &>(*p).v; } array &value::array_ref() & { return dynamic_cast<wrap<array> &>(*p).v; } object const &value::object_cref() const & { return dynamic_cast<wrap<object> const &>(*p).v; } object &value::object_ref() & { return dynamic_cast<wrap<object> &>(*p).v; } string escape(string const &s) { string ret; for(auto it = std::cbegin(s); it != std::cend(s); ++it) { if(*it == '"') { ret += "\\\""; } else if(*it == '\\') { ret += "\\\\"; } else if(*it == '\b') { ret += "\\b"; } else if(*it == '\f') { ret += "\\f"; } else if(*it == '\n') { ret += "\\n"; } else if(*it == '\r') { ret += "\\r"; } else if(*it == '\t') { ret += "\\t"; } else if(*it & 0b10000000u) { ret += *it; } else if(!std::isprint(*it)) { ret += "\\u"; std::ostringstream oss; oss << std::hex << std::setw(4) << std::setfill('0') << static_cast<std::uint16_t>(*it); ret += oss.str(); } else { ret += *it; } } return ret; } string unescape(string const &s) { string ret; for(auto it = std::cbegin(s); it != std::cend(s); ++it) { if(*it == '\\') { if(++it == std::cend(s)) { throw std::range_error{"invalid escape at end of string"}; } if(*it == '\"' || *it == '\\' || *it == '/') { ret += *it; } else if(*it == 'b') { ret += '\b'; } else if(*it == 'f') { ret += '\f'; } else if(*it == 'n') { ret += '\n'; } else if(*it == 'r') { ret += '\r'; } else if(*it == 't') { ret += '\t'; } else if(*it == 'u') { string hex; for(std::size_t i = 0; i < 4; ++i) { if(++it == std::cend(s)) { throw std::range_error{"invalid unicode escape at end of string"}; } hex += *it; } std::uint16_t n; std::istringstream is {hex}; if(!(is >> std::hex >> n)) { throw std::range_error{"invalid unicode escape"}; } ret += utf::encode_code_point<string::value_type>(n); } else { throw std::range_error{"invalid escape"}; } } else { ret += *it; } } return ret; } value deserialize(string const &s, deserialize_settings settings) { //TODO return nullptr; } void serialize(value const &v, string &s, std::size_t depth) { string const indent {depth? string(depth - std::size_t{1u}, '\t') : ""}; if(v == type::null) { s += "null"; } else if(auto w = dynamic_cast<value::wrap<bool> const *>(v.p.get())) { if(w->v) { s += "true"; } else { s += "false"; } } else if(auto w = dynamic_cast<value::wrap<integer> const *>(v.p.get())) { s += std::to_string(w->v); } else if(auto w = dynamic_cast<value::wrap<real> const *>(v.p.get())) { std::ostringstream oss; oss.precision(std::numeric_limits<real>::max_digits10); oss << w->v; s += oss.str(); if(oss.str().rfind('.') == std::string::npos) { s += ".0"; } } else if(auto w = dynamic_cast<value::wrap<string> const *>(v.p.get())) { s += '"' + escape(w->v) + '"'; } else if(auto w = dynamic_cast<value::wrap<array> const *>(v.p.get())) { s += (depth? indent + "[\n" : "["); bool first = true; for(auto const &e : w->v) { if(!first) { s += (depth? ",\n" : ","); } first = false; if(depth && e != type::array && e != type::object) { s += indent + '\t'; } serialize(e, s, (depth? depth + 1 : depth)); } if(depth && !first) { s += '\n'; } s += indent + ']'; } else if(auto w = dynamic_cast<value::wrap<object> const *>(v.p.get())) { s += (depth? indent + "{\n" : "{"); bool first = true; for(auto const &e : w->v) { if(!first) { s += (depth? ",\n" : ","); } first = false; if(depth) { s += indent + '\t'; } s += '"' + escape(e.first) + "\":"; if(depth) { if(e.second == type::array || e.second == type::object) { s += '\n'; } else { s += ' '; } } serialize(e.second, s, (depth? depth + 1 : depth)); } if(depth && !first) { s += '\n'; } s += indent + "}"; } } string serialize(value const &v, serialize_settings settings) { string s; serialize(v, s, (settings.formatting == serialize_formatting::pretty? 1 : 0)); return s; } } }
19.569196
93
0.496977
[ "object" ]
7baa516dfb08794040d2ca7dc132e708781cfe22
35,092
cc
C++
src/controller/controller.cc
dgolbourn/Metallic-Crow
0f073312c67d3f0542cc40f23e94a018bd5e52c5
[ "MIT" ]
null
null
null
src/controller/controller.cc
dgolbourn/Metallic-Crow
0f073312c67d3f0542cc40f23e94a018bd5e52c5
[ "MIT" ]
null
null
null
src/controller/controller.cc
dgolbourn/Metallic-Crow
0f073312c67d3f0542cc40f23e94a018bd5e52c5
[ "MIT" ]
null
null
null
#include "controller.h" #include "bind.h" #include "window.h" #include "menu.h" #include "script.h" #include "signal.h" #include <vector> #include "saves.h" #include <sstream> #include <algorithm> #include "sound.h" #include "player.h" namespace { enum class State : int { Start, Chapter, Load, Pause, Delete, Story, Player, PausePlayer }; typedef std::vector<std::string> Strings; typedef std::vector<boost::filesystem::path> Paths; auto FirstStart(game::Saves const& saves) -> bool { for(int i = 0; i < saves.Size(); ++i) { if(0 != saves.Progress(i)) { return false; } } return true; } auto NewStart(game::Saves const& saves) -> bool { return 0 == saves.Progress(saves.LastPlayed()); } auto CompleteStart(game::Saves const& saves, int complete) -> bool { return complete == saves.Current(saves.LastPlayed()); } auto FullStart(game::Saves const& saves) -> bool { for(int i = 0; i < saves.Size(); ++i) { if((0 == saves.Progress(i))) { return false; } } return true; } auto Chapters(lua::Stack& lua, Strings& names, Paths& files, boost::filesystem::path const& path) -> void { for(int index = 1, end = lua.Size(); index <= end; ++index) { lua::Guard guard = lua.Field(index); std::string name = lua.Field<std::string>("name"); std::string file = lua.Field<std::string>("file"); names.emplace_back(name); files.emplace_back(path / file); } } auto FirstStartOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Begin", false}); options.push_back({ "Controllers", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto ContinueStartOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Continue", false}); options.push_back({ "Continue From Chapter", false}); options.push_back({ "Start Again (current progress will be lost)", false }); options.push_back({ "Load Saved Game / Start New Game", false}); options.push_back({ "Controllers", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto StartFullOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Continue", false}); options.push_back({ "Continue From Chapter", false}); options.push_back({ "Start Again (current progress will be lost)", false }); options.push_back({ "Load Saved Game", false}); options.push_back({ "Controllers", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto CompleteStartOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Continue From Chapter", false}); options.push_back({ "Start Again (current progress will be lost)", false }); options.push_back({ "Load Saved Game / Start New Game", false}); options.push_back({ "Controllers", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto CompleteStartFullOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Continue From Chapter", false}); options.push_back({ "Start Again (current progress will be lost)", false }); options.push_back({ "Load Saved Game", false}); options.push_back({ "Controllers", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto NewStartOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Begin", false}); options.push_back({ "Load Saved Game / Start New Game", false}); options.push_back({ "Controllers", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto NewStartFullOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Begin", false}); options.push_back({ "Load Saved Game", false}); options.push_back({ "Controllers", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto DeleteOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({"Proceed (delete this save)", false}); options.push_back({"No! Keep this Save", false}); menu(options); } auto OneFirstStartOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Begin", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto OneContinueStartOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Continue", false}); options.push_back({ "Continue From Chapter", false}); options.push_back({ "Start Again (current progress will be lost)", false }); options.push_back({ "Load Saved Game / Start New Game", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto OneStartFullOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Continue", false}); options.push_back({ "Continue From Chapter", false}); options.push_back({ "Start Again (current progress will be lost)", false }); options.push_back({ "Load Saved Game", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto OneCompleteStartOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Continue From Chapter", false}); options.push_back({ "Start Again (current progress will be lost)", false }); options.push_back({ "Load Saved Game / Start New Game", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto OneCompleteStartFullOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Continue From Chapter", false}); options.push_back({ "Start Again (current progress will be lost)", false }); options.push_back({ "Load Saved Game", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto OneNewStartOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Begin", false}); options.push_back({ "Load Saved Game / Start New Game", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto OneNewStartFullOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({ "Begin", false}); options.push_back({ "Load Saved Game", false}); options.push_back({ "Quit to Desktop", false}); menu(options); } auto ChapterOptions(game::Menu& menu, int progress, Strings const& chapters) -> void { game::Menu::Options options; int max = static_cast<int>(chapters.size()) - 1; if(progress > max) { progress = max; } if(progress < 0) { progress = 0; } for(int i = 0; i <= progress; ++i) { options.push_back({chapters[i], false}); } menu(options); } auto LoadOptions(game::Menu& menu, game::Saves& saves, Strings const& chapters) -> void { game::Menu::Options options; for(int i = 0; i < saves.Size(); ++i) { int progress = saves.Progress(i); int current = saves.Current(i); std::string last_played = saves.LastPlayed(i); std::stringstream stream; if(0 == progress) { stream << "New profile " << i; } else { if(current != progress) { stream << chapters[current] << " / "; } if(static_cast<int>(chapters.size()) == progress) { stream << "Complete"; } else { stream << chapters[progress]; } stream << " " << last_played; } options.push_back({ stream.str(), false }); } menu(options); menu[saves.LastPlayed()]; } auto PlayerPauseMenuOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({"Resume Story", false}); options.push_back({"Controllers", false}); options.push_back({"Quit to Menu", false}); options.push_back({"Quit to Desktop", false}); menu(options); } auto OnePauseMenuOptions(game::Menu& menu) -> void { game::Menu::Options options; options.push_back({"Resume Story", false}); options.push_back({"Quit to Menu", false}); options.push_back({"Quit to Desktop", false}); menu(options); } } namespace game { class Controller::Impl final : public std::enable_shared_from_this<Impl> { public: Impl(lua::Stack& lua, event::Queue& queue, boost::filesystem::path const& path); auto Init() -> void; auto MoveEvent(int player, float x, float y) -> void; auto LookEvent(int player, float x, float y) -> void; auto ChoiceUpEvent(int player) -> void; auto ChoiceDownEvent(int player) -> void; auto ChoiceLeftEvent(int player) -> void; auto ChoiceRightEvent(int player) -> void; auto ActionLeftEvent(int player, bool state) -> void; auto ActionRightEvent(int player, bool state) -> void; auto RawUpEvent(int id) -> void; auto RawDownEvent(int id) -> void; auto AllUpEvent() -> void; auto AllDownEvent() -> void; auto AllSelectEvent() -> void; auto AllBackEvent() -> void; auto AllChoiceSelectEvent() -> void; auto AllChoiceBackEvent() -> void; auto JoinEvent(int player, bool state) -> void; auto Render() -> void; auto Quit(event::Command const& command) -> void; auto PauseContinue() -> void; auto PauseMainMenu() -> void; auto PauseQuit() -> void; auto StartPlay() -> void; auto StartChooseChapter() -> void; auto StartDeleteSave() -> void; auto StartLoad() -> void; auto StartQuit() -> void; auto DeletePlay() -> void; auto DeleteBack() -> void; auto Load(int slot) -> void; auto Chapter(int chapter) -> void; auto ChapterEnd() -> void; auto StartMenu() -> void; auto Add(int id) -> void; auto Remove(int id) -> void; auto Player() -> void; auto PausePlayer() -> void; auto PauseMenu() -> void; event::Queue queue_; display::Window window_; Menu one_pause_menu_; Menu player_pause_menu_; Menu pause_menu_; Menu first_start_menu_; Menu continue_start_menu_; Menu start_full_menu_; Menu new_start_menu_; Menu new_start_full_menu_; Menu complete_start_menu_; Menu complete_start_full_menu_; Menu chapter_menu_; Menu load_menu_; Menu start_menu_; Menu delete_menu_; Menu one_first_start_menu_; Menu one_continue_start_menu_; Menu one_start_full_menu_; Menu one_new_start_menu_; Menu one_new_start_full_menu_; Menu one_complete_start_menu_; Menu one_complete_start_full_menu_; Menu one_chapter_menu_; Menu one_load_menu_; Menu one_start_menu_; Script pause_script_; Script start_script_; Script story_script_; State state_; event::Signal signal_; Saves saves_; Strings chapter_names_; Paths chapter_files_; boost::filesystem::path path_; float volume_; audio::Sound navigate_; audio::Sound select_; audio::Sound back_; int sign_; game::Player player_; }; auto Controller::Impl::Player() -> void { state_ = State::Player; } auto Controller::Impl::PausePlayer() -> void { state_ = State::PausePlayer; } auto Controller::Impl::Load(int slot) -> void { saves_.Play(slot); ChapterOptions(chapter_menu_, saves_.Progress(saves_.LastPlayed()), chapter_names_); LoadOptions(load_menu_, saves_, chapter_names_); StartMenu(); if(NewStart(saves_)) { StartPlay(); } else { state_ = State::Start; } } auto Controller::Impl::Chapter(int chapter) -> void { saves_.Current(saves_.LastPlayed(), chapter); ChapterOptions(chapter_menu_, saves_.Progress(saves_.LastPlayed()), chapter_names_); LoadOptions(load_menu_, saves_, chapter_names_); StartMenu(); StartPlay(); } Controller::Impl::Impl(lua::Stack& lua, event::Queue& queue, boost::filesystem::path const& path) : state_(State::Start), queue_(queue), path_(path), sign_(0) { { lua::Guard guard = lua.Field("window"); window_ = display::Window(lua); } { lua::Guard guard = lua.Field("menu"); one_pause_menu_ = Menu(lua, window_, path_); } OnePauseMenuOptions(one_pause_menu_); { lua::Guard guard = lua.Field("menu"); player_pause_menu_ = Menu(lua, window_, path_); } PlayerPauseMenuOptions(player_pause_menu_); pause_script_ = Script(path_ / lua.Field<std::string>("pause_menu_script"), window_, queue_, path_, volume_); { lua::Guard guard = lua.Field("menu"); first_start_menu_ = Menu(lua, window_, path_); } FirstStartOptions(first_start_menu_); { lua::Guard guard = lua.Field("menu"); continue_start_menu_ = Menu(lua, window_, path_); } ContinueStartOptions(continue_start_menu_); { lua::Guard guard = lua.Field("menu"); start_full_menu_ = Menu(lua, window_, path_); } StartFullOptions(start_full_menu_); { lua::Guard guard = lua.Field("menu"); new_start_menu_ = Menu(lua, window_, path_); } NewStartOptions(new_start_menu_); { lua::Guard guard = lua.Field("menu"); new_start_full_menu_ = Menu(lua, window_, path_); } NewStartFullOptions(new_start_full_menu_); { lua::Guard guard = lua.Field("menu"); complete_start_menu_ = Menu(lua, window_, path_); } CompleteStartOptions(complete_start_menu_); { lua::Guard guard = lua.Field("menu"); complete_start_full_menu_ = Menu(lua, window_, path_); } CompleteStartFullOptions(complete_start_full_menu_); start_script_ = Script(path_ / lua.Field<std::string>("start_menu_script"), window_, queue_, path_, volume_); saves_ = Saves(path_ / lua.Field<std::string>("saves")); { lua::Guard guard = lua.Field("chapters"); Chapters(lua, chapter_names_, chapter_files_, path_); } { lua::Guard guard = lua.Field("menu"); chapter_menu_ = Menu(lua, window_, path_); } ChapterOptions(chapter_menu_, saves_.Progress(saves_.LastPlayed()), chapter_names_); { lua::Guard guard = lua.Field("menu"); load_menu_ = Menu(lua, window_, path_); } LoadOptions(load_menu_, saves_, chapter_names_); { lua::Guard guard = lua.Field("menu"); delete_menu_ = Menu(lua, window_, path_); } DeleteOptions(delete_menu_); { lua::Guard guard = lua.Field("menu"); one_first_start_menu_ = Menu(lua, window_, path_); } OneFirstStartOptions(one_first_start_menu_); { lua::Guard guard = lua.Field("menu"); one_continue_start_menu_ = Menu(lua, window_, path_); } OneContinueStartOptions(one_continue_start_menu_); { lua::Guard guard = lua.Field("menu"); one_start_full_menu_ = Menu(lua, window_, path_); } OneStartFullOptions(one_start_full_menu_); { lua::Guard guard = lua.Field("menu"); one_new_start_menu_ = Menu(lua, window_, path_); } OneNewStartOptions(one_new_start_menu_); { lua::Guard guard = lua.Field("menu"); one_new_start_full_menu_ = Menu(lua, window_, path_); } OneNewStartFullOptions(one_new_start_full_menu_); { lua::Guard guard = lua.Field("menu"); one_complete_start_menu_ = Menu(lua, window_, path_); } OneCompleteStartOptions(one_complete_start_menu_); { lua::Guard guard = lua.Field("menu"); one_complete_start_full_menu_ = Menu(lua, window_, path_); } OneCompleteStartFullOptions(one_complete_start_full_menu_); volume_ = lua.Field<float>("volume"); { lua::Guard guard = lua.Field("sound_navigate"); navigate_ = audio::Sound(lua, path_); } { lua::Guard guard = lua.Field("sound_select"); select_ = audio::Sound(lua, path_); } { lua::Guard guard = lua.Field("sound_back"); back_ = audio::Sound(lua, path_); } { lua::Guard guard = lua.Field("player"); player_ = game::Player(lua, window_, path_); } StartMenu(); PauseMenu(); navigate_.Resume(); select_.Resume(); back_.Resume(); } auto Controller::Impl::PauseMenu() -> void { if(player_) { pause_menu_ = player_pause_menu_; } else { pause_menu_ = one_pause_menu_; } } auto Controller::Impl::StartMenu() -> void { if(FirstStart(saves_)) { if(player_) { start_menu_ = first_start_menu_; } else { start_menu_ = one_first_start_menu_; } } else { bool new_start = NewStart(saves_); bool full_start = FullStart(saves_); bool complete_start = CompleteStart(saves_, chapter_files_.size()); if(new_start) { if(full_start) { if(player_) { start_menu_ = new_start_full_menu_; } else { start_menu_ = one_new_start_full_menu_; } } else { if(player_) { start_menu_ = new_start_menu_; } else { start_menu_ = one_new_start_menu_; } } } else if(complete_start) { if(full_start) { if(player_) { start_menu_ = complete_start_full_menu_; } else { start_menu_ = one_complete_start_full_menu_; } } else { if(player_) { start_menu_ = complete_start_menu_; } else { start_menu_ = one_complete_start_menu_; } } } else { if(full_start) { if(player_) { start_menu_ = start_full_menu_; } else { start_menu_ = one_start_full_menu_; } } else { if(player_) { start_menu_ = continue_start_menu_; } else { start_menu_ = one_continue_start_menu_; } } } } } auto Controller::Impl::Init() -> void { queue_.Add(function::Bind(&Impl::Render, shared_from_this())); one_pause_menu_.Add(0, function::Bind(&Impl::PauseContinue, shared_from_this())); one_pause_menu_.Add(1, function::Bind(&Impl::PauseMainMenu, shared_from_this())); one_pause_menu_.Add(2, function::Bind(&Impl::PauseQuit, shared_from_this())); player_pause_menu_.Add(0, function::Bind(&Impl::PauseContinue, shared_from_this())); player_pause_menu_.Add(1, function::Bind(&Impl::PausePlayer, shared_from_this())); player_pause_menu_.Add(2, function::Bind(&Impl::PauseMainMenu, shared_from_this())); player_pause_menu_.Add(3, function::Bind(&Impl::PauseQuit, shared_from_this())); first_start_menu_.Add(0, function::Bind(&Impl::StartPlay, shared_from_this())); first_start_menu_.Add(1, function::Bind(&Impl::Player, shared_from_this())); first_start_menu_.Add(2, function::Bind(&Impl::StartQuit, shared_from_this())); continue_start_menu_.Add(0, function::Bind(&Impl::StartPlay, shared_from_this())); continue_start_menu_.Add(1, function::Bind(&Impl::StartChooseChapter, shared_from_this())); continue_start_menu_.Add(2, function::Bind(&Impl::StartDeleteSave, shared_from_this())); continue_start_menu_.Add(3, function::Bind(&Impl::StartLoad, shared_from_this())); continue_start_menu_.Add(4, function::Bind(&Impl::Player, shared_from_this())); continue_start_menu_.Add(5, function::Bind(&Impl::StartQuit, shared_from_this())); start_full_menu_.Add(0, function::Bind(&Impl::StartPlay, shared_from_this())); start_full_menu_.Add(1, function::Bind(&Impl::StartChooseChapter, shared_from_this())); start_full_menu_.Add(2, function::Bind(&Impl::StartDeleteSave, shared_from_this())); start_full_menu_.Add(3, function::Bind(&Impl::StartLoad, shared_from_this())); start_full_menu_.Add(4, function::Bind(&Impl::Player, shared_from_this())); start_full_menu_.Add(5, function::Bind(&Impl::StartQuit, shared_from_this())); complete_start_menu_.Add(0, function::Bind(&Impl::StartChooseChapter, shared_from_this())); complete_start_menu_.Add(1, function::Bind(&Impl::StartDeleteSave, shared_from_this())); complete_start_menu_.Add(2, function::Bind(&Impl::StartLoad, shared_from_this())); complete_start_menu_.Add(3, function::Bind(&Impl::Player, shared_from_this())); complete_start_menu_.Add(4, function::Bind(&Impl::StartQuit, shared_from_this())); complete_start_full_menu_.Add(0, function::Bind(&Impl::StartChooseChapter, shared_from_this())); complete_start_full_menu_.Add(1, function::Bind(&Impl::StartDeleteSave, shared_from_this())); complete_start_full_menu_.Add(2, function::Bind(&Impl::StartLoad, shared_from_this())); complete_start_full_menu_.Add(3, function::Bind(&Impl::Player, shared_from_this())); complete_start_full_menu_.Add(4, function::Bind(&Impl::StartQuit, shared_from_this())); new_start_menu_.Add(0, function::Bind(&Impl::StartPlay, shared_from_this())); new_start_menu_.Add(1, function::Bind(&Impl::StartLoad, shared_from_this())); new_start_menu_.Add(2, function::Bind(&Impl::Player, shared_from_this())); new_start_menu_.Add(3, function::Bind(&Impl::StartQuit, shared_from_this())); new_start_full_menu_.Add(0, function::Bind(&Impl::StartPlay, shared_from_this())); new_start_full_menu_.Add(1, function::Bind(&Impl::StartLoad, shared_from_this())); new_start_full_menu_.Add(2, function::Bind(&Impl::Player, shared_from_this())); new_start_full_menu_.Add(3, function::Bind(&Impl::StartQuit, shared_from_this())); delete_menu_.Add(0, function::Bind(&Impl::DeletePlay, shared_from_this())); delete_menu_.Add(1, function::Bind(&Impl::DeleteBack, shared_from_this())); one_first_start_menu_.Add(0, function::Bind(&Impl::StartPlay, shared_from_this())); one_first_start_menu_.Add(1, function::Bind(&Impl::StartQuit, shared_from_this())); one_continue_start_menu_.Add(0, function::Bind(&Impl::StartPlay, shared_from_this())); one_continue_start_menu_.Add(1, function::Bind(&Impl::StartChooseChapter, shared_from_this())); one_continue_start_menu_.Add(2, function::Bind(&Impl::StartDeleteSave, shared_from_this())); one_continue_start_menu_.Add(3, function::Bind(&Impl::StartLoad, shared_from_this())); one_continue_start_menu_.Add(4, function::Bind(&Impl::StartQuit, shared_from_this())); one_start_full_menu_.Add(0, function::Bind(&Impl::StartPlay, shared_from_this())); one_start_full_menu_.Add(1, function::Bind(&Impl::StartChooseChapter, shared_from_this())); one_start_full_menu_.Add(2, function::Bind(&Impl::StartDeleteSave, shared_from_this())); one_start_full_menu_.Add(3, function::Bind(&Impl::StartLoad, shared_from_this())); one_start_full_menu_.Add(4, function::Bind(&Impl::StartQuit, shared_from_this())); one_complete_start_menu_.Add(0, function::Bind(&Impl::StartChooseChapter, shared_from_this())); one_complete_start_menu_.Add(1, function::Bind(&Impl::StartDeleteSave, shared_from_this())); one_complete_start_menu_.Add(2, function::Bind(&Impl::StartLoad, shared_from_this())); one_complete_start_menu_.Add(3, function::Bind(&Impl::StartQuit, shared_from_this())); one_complete_start_full_menu_.Add(0, function::Bind(&Impl::StartChooseChapter, shared_from_this())); one_complete_start_full_menu_.Add(1, function::Bind(&Impl::StartDeleteSave, shared_from_this())); one_complete_start_full_menu_.Add(2, function::Bind(&Impl::StartLoad, shared_from_this())); one_complete_start_full_menu_.Add(3, function::Bind(&Impl::StartQuit, shared_from_this())); one_new_start_menu_.Add(0, function::Bind(&Impl::StartPlay, shared_from_this())); one_new_start_menu_.Add(1, function::Bind(&Impl::StartLoad, shared_from_this())); one_new_start_menu_.Add(2, function::Bind(&Impl::StartQuit, shared_from_this())); one_new_start_full_menu_.Add(0, function::Bind(&Impl::StartPlay, shared_from_this())); one_new_start_full_menu_.Add(1, function::Bind(&Impl::StartLoad, shared_from_this())); one_new_start_full_menu_.Add(2, function::Bind(&Impl::StartQuit, shared_from_this())); for(int i = 0; i < saves_.Size(); ++i) { load_menu_.Add(i, function::Bind(&Impl::Load, shared_from_this(), i)); } for(Strings::size_type i = 0; i < chapter_names_.size(); ++i) { chapter_menu_.Add(i, function::Bind(&Impl::Chapter, shared_from_this(), i)); } player_.Move(function::Bind(&Impl::MoveEvent, shared_from_this())); player_.Look(function::Bind(&Impl::LookEvent, shared_from_this())); player_.ChoiceUp(function::Bind(&Impl::ChoiceUpEvent, shared_from_this())); player_.ChoiceDown(function::Bind(&Impl::ChoiceDownEvent, shared_from_this())); player_.ChoiceLeft(function::Bind(&Impl::ChoiceLeftEvent, shared_from_this())); player_.ChoiceRight(function::Bind(&Impl::ChoiceRightEvent, shared_from_this())); player_.ActionLeft(function::Bind(&Impl::ActionLeftEvent, shared_from_this())); player_.ActionRight(function::Bind(&Impl::ActionRightEvent, shared_from_this())); player_.RawUp(function::Bind(&Impl::RawUpEvent, shared_from_this())); player_.RawDown(function::Bind(&Impl::RawDownEvent, shared_from_this())); player_.AllUp(function::Bind(&Impl::AllUpEvent, shared_from_this())); player_.AllDown(function::Bind(&Impl::AllDownEvent, shared_from_this())); player_.AllSelect(function::Bind(&Impl::AllSelectEvent, shared_from_this())); player_.AllBack(function::Bind(&Impl::AllBackEvent, shared_from_this())); player_.AllChoiceSelect(function::Bind(&Impl::AllChoiceSelectEvent, shared_from_this())); player_.AllChoiceBack(function::Bind(&Impl::AllChoiceBackEvent, shared_from_this())); player_.Join(function::Bind(&Impl::JoinEvent, shared_from_this())); start_script_.Resume(); } auto Controller::Impl::JoinEvent(int player, bool state) -> void { PauseMenu(); if(story_script_) { if(state) { story_script_.Join(player); } else { story_script_.Leave(player); } } } auto Controller::Impl::ChapterEnd() -> void { int chapter = saves_.Current(saves_.LastPlayed()) + 1; if(chapter >= static_cast<int>(chapter_files_.size())) { chapter = static_cast<int>(chapter_files_.size()); saves_.Stop(); state_ = State::Start; StartMenu(); } story_script_ = Script(); saves_.Current(saves_.LastPlayed(), chapter); saves_.Save(); StartMenu(); LoadOptions(load_menu_, saves_, chapter_names_); ChapterOptions(chapter_menu_, saves_.Progress(saves_.LastPlayed()), chapter_names_); } auto Controller::Impl::DeletePlay() -> void { saves_.Stop(); saves_.Delete(saves_.LastPlayed()); StartMenu(); LoadOptions(load_menu_, saves_, chapter_names_); StartPlay(); } auto Controller::Impl::DeleteBack() -> void { state_ = State::Start; } auto Controller::Impl::PauseContinue() -> void { state_ = State::Story; pause_script_.Pause(); story_script_.Resume(); } auto Controller::Impl::PauseMainMenu() -> void { saves_.Stop(); state_ = State::Start; StartMenu(); pause_script_.Pause(); start_script_.Resume(); } auto Controller::Impl::PauseQuit() -> void { saves_.Stop(); signal_(); } auto Controller::Impl::StartDeleteSave() -> void { state_ = State::Delete; } auto Controller::Impl::StartPlay() -> void { state_ = State::Story; start_script_.Pause(); if(saves_.LastPlayed() >= static_cast<int>(chapter_files_.size())) { saves_.Current(saves_.LastPlayed(), 0); StartMenu(); } saves_.Play(saves_.LastPlayed()); story_script_ = Script(chapter_files_[saves_.Current(saves_.LastPlayed())], window_, queue_, path_, volume_); story_script_.Add(function::Bind(&Impl::ChapterEnd, shared_from_this())); for(auto i : player_.Current()) { story_script_.Join(i); } story_script_.Resume(); } auto Controller::Impl::StartChooseChapter() -> void { state_ = State::Chapter; } auto Controller::Impl::StartLoad() -> void { state_ = State::Load; LoadOptions(load_menu_, saves_, chapter_names_); StartMenu(); } auto Controller::Impl::StartQuit() -> void { signal_(); } auto Controller::Impl::Quit(event::Command const& command) -> void { signal_.Add(command); } auto Controller::Impl::Add(int id) -> void { player_.Add(id); StartMenu(); } auto Controller::Impl::Remove(int id) -> void { player_.Remove(id); StartMenu(); } auto Controller::Impl::MoveEvent(int player, float x, float y) -> void { switch(state_) { case State::Story: story_script_.Move(player, x, y); break; default: break; } } auto Controller::Impl::LookEvent(int player, float x, float y) -> void { switch(state_) { case State::Story: story_script_.Look(player, x, y); break; default: break; } } auto Controller::Impl::ChoiceUpEvent(int player) -> void { switch(state_) { case State::Story: story_script_.ChoiceUp(player); break; default: break; } } auto Controller::Impl::ChoiceDownEvent(int player) -> void { switch(state_) { case State::Story: story_script_.ChoiceDown(player); break; default: break; } } auto Controller::Impl::ChoiceLeftEvent(int player) -> void { switch(state_) { case State::Story: story_script_.ChoiceLeft(player); break; default: break; } } auto Controller::Impl::ChoiceRightEvent(int player) -> void { switch(state_) { case State::Story: story_script_.ChoiceRight(player); break; default: break; } } auto Controller::Impl::ActionLeftEvent(int player, bool state) -> void { switch(state_) { case State::Story: story_script_.ActionLeft(player, state); break; default: break; } } auto Controller::Impl::ActionRightEvent(int player, bool state) -> void { switch(state_) { case State::Story: story_script_.ActionRight(player, state); break; default: break; } } auto Controller::Impl::RawUpEvent(int id) -> void { switch(state_) { case State::PausePlayer: case State::Player: player_.Up(id); break; default: break; } } auto Controller::Impl::RawDownEvent(int id) -> void { switch(state_) { case State::PausePlayer: case State::Player: player_.Down(id); break; default: break; } } auto Controller::Impl::AllUpEvent() -> void { switch(state_) { case State::Start: navigate_(volume_); start_menu_.Previous(); break; case State::Pause: navigate_(volume_); pause_menu_.Previous(); break; case State::Chapter: navigate_(volume_); chapter_menu_.Previous(); break; case State::Load: navigate_(volume_); load_menu_.Previous(); break; case State::Delete: navigate_(volume_); delete_menu_.Previous(); break; default: break; } } auto Controller::Impl::AllDownEvent() -> void { switch(state_) { case State::Start: navigate_(volume_); start_menu_.Next(); break; case State::Pause: navigate_(volume_); pause_menu_.Next(); break; case State::Chapter: navigate_(volume_); chapter_menu_.Next(); break; case State::Load: navigate_(volume_); load_menu_.Next(); break; case State::Delete: navigate_(volume_); delete_menu_.Next(); break; default: break; } } auto Controller::Impl::AllSelectEvent() -> void { switch(state_) { case State::Start: select_(volume_); start_menu_.Select(); break; case State::Pause: select_(volume_); pause_menu_.Select(); break; case State::Chapter: select_(volume_); chapter_menu_.Select(); break; case State::Load: select_(volume_); load_menu_.Select(); break; case State::Delete: select_(volume_); delete_menu_.Select(); break; case State::Story: back_(volume_); state_ = State::Pause; story_script_.Pause(); pause_menu_[0]; pause_script_.Resume(); break; default: break; } } auto Controller::Impl::AllBackEvent() -> void { switch(state_) { case State::Pause: back_(volume_); state_ = State::Story; story_script_.Resume(); pause_script_.Pause(); break; case State::PausePlayer: back_(volume_); state_ = State::Pause; break; case State::Player: case State::Load: case State::Chapter: case State::Delete: back_(volume_); state_ = State::Start; StartMenu(); break; case State::Story: back_(volume_); state_ = State::Pause; story_script_.Pause(); pause_menu_[0]; pause_script_.Resume(); break; default: break; } } auto Controller::Impl::AllChoiceSelectEvent() -> void { switch(state_) { case State::Start: select_(volume_); start_menu_.Select(); break; case State::Pause: select_(volume_); pause_menu_.Select(); break; case State::Chapter: select_(volume_); chapter_menu_.Select(); break; case State::Load: select_(volume_); load_menu_.Select(); break; case State::Delete: select_(volume_); delete_menu_.Select(); break; default: break; } } auto Controller::Impl::AllChoiceBackEvent() -> void { switch(state_) { case State::Pause: back_(volume_); state_ = State::Story; story_script_.Resume(); pause_script_.Pause(); break; case State::PausePlayer: back_(volume_); state_ = State::Pause; break; case State::Player: case State::Load: case State::Chapter: case State::Delete: back_(volume_); state_ = State::Start; StartMenu(); break; default: break; } } auto Controller::Impl::Render() -> void { switch(state_) { case State::Start: window_.Clear(); start_script_.Render(); start_menu_.Render(); window_.Show(); break; case State::Chapter: window_.Clear(); start_script_.Render(); chapter_menu_.Render(); window_.Show(); break; case State::Load: window_.Clear(); start_script_.Render(); load_menu_.Render(); window_.Show(); break; case State::Pause: window_.Clear(); pause_script_.Render(); pause_menu_.Render(); window_.Show(); break; case State::Delete: window_.Clear(); start_script_.Render(); delete_menu_.Render(); window_.Show(); break; case State::Story: window_.Clear(); story_script_.Render(); window_.Show(); break; case State::PausePlayer: case State::Player: window_.Clear(); start_script_.Render(); player_.Render(); window_.Show(); break; default: break; } } Controller::Controller(lua::Stack& lua, event::Queue& queue, boost::filesystem::path const& path) : impl_(std::make_shared<Impl>(lua, queue, path)) { impl_->Init(); } auto Controller::Move(int id, float x, float y) -> void { impl_->player_.Move(id, x, y); } auto Controller::Look(int id, float x, float y) -> void { impl_->player_.Look(id, x, y); } auto Controller::ChoiceUp(int id) -> void { impl_->player_.ChoiceUp(id); } auto Controller::ChoiceDown(int id) -> void { impl_->player_.ChoiceDown(id); } auto Controller::ChoiceLeft(int id) -> void { impl_->player_.ChoiceLeft(id); } auto Controller::ChoiceRight(int id) -> void { impl_->player_.ChoiceRight(id); } auto Controller::ActionLeft(int id, bool state) -> void { impl_->player_.ActionLeft(id, state); } auto Controller::ActionRight(int id, bool state) -> void { impl_->player_.ActionRight(id, state); } auto Controller::Select(int id) -> void { impl_->player_.Select(id); } auto Controller::Back(int id) -> void { impl_->player_.Back(id); } auto Controller::Quit(event::Command const& command) -> void { impl_->Quit(command); } auto Controller::Add(int id) -> void { impl_->Add(id); } auto Controller::Remove(int id) -> void { impl_->Remove(id); } Controller::operator bool() const { return static_cast<bool>(impl_); } }
25.318903
158
0.675054
[ "render", "vector" ]
7baaf278786f0d97fbc26a6b914103ace2bfc6e9
218,484
hpp
C++
cisco-nx-os/ydk/models/cisco_nx_os/fragmented/Cisco_NX_OS_device_48.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-nx-os/ydk/models/cisco_nx_os/fragmented/Cisco_NX_OS_device_48.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-nx-os/ydk/models/cisco_nx_os/fragmented/Cisco_NX_OS_device_48.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _CISCO_NX_OS_DEVICE_48_ #define _CISCO_NX_OS_DEVICE_48_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> #include "Cisco_NX_OS_device_0.hpp" #include "Cisco_NX_OS_device_47.hpp" namespace cisco_nx_os { namespace Cisco_NX_OS_device { class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::DynItems : public ydk::Entity { public: DynItems(); ~DynItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string class PceItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::DynItems::PceItems class MetricItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::DynItems::MetricItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::DynItems::PceItems> pce_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::DynItems::MetricItems> metric_items; }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::DynItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::DynItems::PceItems : public ydk::Entity { public: PceItems(); ~PceItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::DynItems::PceItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::DynItems::MetricItems : public ydk::Entity { public: MetricItems(); ~MetricItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf metrictype; //type: SrteMetric ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::DynItems::MetricItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems : public ydk::Entity { public: ConstraintsItems(); ~ConstraintsItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string class SegmentItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::SegmentItems class AssocItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AssocItems class AffinityItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::SegmentItems> segment_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AssocItems> assoc_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems> affinity_items; }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::SegmentItems : public ydk::Entity { public: SegmentItems(); ~SegmentItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf prottype; //type: SrteProtectionType ydk::YLeaf datapln; //type: SrteDataPlane ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::SegmentItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AssocItems : public ydk::Entity { public: AssocItems(); ~AssocItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string class DisjItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AssocItems::DisjItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AssocItems::DisjItems> disj_items; }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AssocItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AssocItems::DisjItems : public ydk::Entity { public: DisjItems(); ~DisjItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf disjtype; //type: SrteDisjointType ydk::YLeaf id; //type: uint32 ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AssocItems::DisjItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems : public ydk::Entity { public: AffinityItems(); ~AffinityItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string class ExclanyItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems class InclallItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems class InclanyItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems> exclany_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems> inclall_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems> inclany_items; }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems : public ydk::Entity { public: ExclanyItems(); ~ExclanyItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string class AffcolItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems::AffcolItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems::AffcolItems> affcol_items; }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems::AffcolItems : public ydk::Entity { public: AffcolItems(); ~AffcolItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PolConstAffColorList; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems::AffcolItems::PolConstAffColorList ydk::YList polconstaffcolor_list; }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems::AffcolItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems::AffcolItems::PolConstAffColorList : public ydk::Entity { public: PolConstAffColorList(); ~PolConstAffColorList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::ExclanyItems::AffcolItems::PolConstAffColorList class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems : public ydk::Entity { public: InclallItems(); ~InclallItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string class AffcolItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems::AffcolItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems::AffcolItems> affcol_items; }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems::AffcolItems : public ydk::Entity { public: AffcolItems(); ~AffcolItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PolConstAffColorList; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems::AffcolItems::PolConstAffColorList ydk::YList polconstaffcolor_list; }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems::AffcolItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems::AffcolItems::PolConstAffColorList : public ydk::Entity { public: PolConstAffColorList(); ~PolConstAffColorList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclallItems::AffcolItems::PolConstAffColorList class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems : public ydk::Entity { public: InclanyItems(); ~InclanyItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt ydk::YLeaf opererr; //type: string class AffcolItems; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems::AffcolItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems::AffcolItems> affcol_items; }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems::AffcolItems : public ydk::Entity { public: AffcolItems(); ~AffcolItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PolConstAffColorList; //type: System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems::AffcolItems::PolConstAffColorList ydk::YList polconstaffcolor_list; }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems::AffcolItems class System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems::AffcolItems::PolConstAffColorList : public ydk::Entity { public: PolConstAffColorList(); ~PolConstAffColorList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string }; // System::SegrtItems::TeItems::PolicyItems::PolicyList::ExpcndpathsItems::PrefItems::PolPrefList::ConstraintsItems::AffinityItems::InclanyItems::AffcolItems::PolConstAffColorList class System::VrrpItems : public ydk::Entity { public: VrrpItems(); ~VrrpItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt class InstItems; //type: System::VrrpItems::InstItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::VrrpItems::InstItems> inst_items; }; // System::VrrpItems class System::VrrpItems::InstItems : public ydk::Entity { public: InstItems(); ~InstItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf ctrl; //type: string class IfItems; //type: System::VrrpItems::InstItems::IfItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::VrrpItems::InstItems::IfItems> if_items; }; // System::VrrpItems::InstItems class System::VrrpItems::InstItems::IfItems : public ydk::Entity { public: IfItems(); ~IfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class InterfaceList; //type: System::VrrpItems::InstItems::IfItems::InterfaceList ydk::YList interface_list; }; // System::VrrpItems::InstItems::IfItems class System::VrrpItems::InstItems::IfItems::InterfaceList : public ydk::Entity { public: InterfaceList(); ~InterfaceList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: string ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ class IdItems; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems class RtvrfMbrItems; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::RtvrfMbrItems class RtnwPathToIfItems; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::RtnwPathToIfItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems> id_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::VrrpItems::InstItems::IfItems::InterfaceList::RtvrfMbrItems> rtvrfmbr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::VrrpItems::InstItems::IfItems::InterfaceList::RtnwPathToIfItems> rtnwpathtoif_items; }; // System::VrrpItems::InstItems::IfItems::InterfaceList class System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems : public ydk::Entity { public: IdItems(); ~IdItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class IdList; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList ydk::YList id_list; }; // System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems class System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList : public ydk::Entity { public: IdList(); ~IdList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf id; //type: uint8 ydk::YLeaf primary; //type: string ydk::YLeaf advintvl; //type: uint8 ydk::YLeaf authtext; //type: string ydk::YLeaf authtype; //type: VrrpAuthType ydk::YLeaf preempt; //type: VrrpPreempt ydk::YLeaf pricfg; //type: uint8 ydk::YLeaf bfdpeeraddr; //type: string ydk::YLeaf fwdlwrthrld; //type: uint8 ydk::YLeaf fwduprthrld; //type: uint8 ydk::YLeaf adminst; //type: VrrpAdminSt ydk::YLeaf groupst; //type: VrrpGroupSt ydk::YLeaf groupstqual; //type: VrrpGroupStQual ydk::YLeaf mac; //type: string ydk::YLeaf masteraddr; //type: string ydk::YLeaf bfdsessionst; //type: VrrpBfdSessionSt class SecondaryItems; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::SecondaryItems class TrackItems; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::SecondaryItems> secondary_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems> track_items; }; // System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList class System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::SecondaryItems : public ydk::Entity { public: SecondaryItems(); ~SecondaryItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class SecondaryList; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::SecondaryItems::SecondaryList ydk::YList secondary_list; }; // System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::SecondaryItems class System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::SecondaryItems::SecondaryList : public ydk::Entity { public: SecondaryList(); ~SecondaryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf secondary; //type: string }; // System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::SecondaryItems::SecondaryList class System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems : public ydk::Entity { public: TrackItems(); ~TrackItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class NativeTrackItems; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::NativeTrackItems class TrackItems_; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::TrackItems_ std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::NativeTrackItems> nativetrack_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::TrackItems_> track_items; }; // System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems class System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::NativeTrackItems : public ydk::Entity { public: NativeTrackItems(); ~NativeTrackItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf id; //type: string ydk::YLeaf priority; //type: uint16 }; // System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::NativeTrackItems class System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::TrackItems_ : public ydk::Entity { public: TrackItems_(); ~TrackItems_(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ObjectTrackList; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::TrackItems_::ObjectTrackList ydk::YList objecttrack_list; }; // System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::TrackItems_ class System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::TrackItems_::ObjectTrackList : public ydk::Entity { public: ObjectTrackList(); ~ObjectTrackList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf id; //type: uint16 ydk::YLeaf decrementpriority; //type: uint16 }; // System::VrrpItems::InstItems::IfItems::InterfaceList::IdItems::IdList::TrackItems::TrackItems_::ObjectTrackList class System::VrrpItems::InstItems::IfItems::InterfaceList::RtvrfMbrItems : public ydk::Entity { public: RtvrfMbrItems(); ~RtvrfMbrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::VrrpItems::InstItems::IfItems::InterfaceList::RtvrfMbrItems class System::VrrpItems::InstItems::IfItems::InterfaceList::RtnwPathToIfItems : public ydk::Entity { public: RtnwPathToIfItems(); ~RtnwPathToIfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RtNwPathToIfList; //type: System::VrrpItems::InstItems::IfItems::InterfaceList::RtnwPathToIfItems::RtNwPathToIfList ydk::YList rtnwpathtoif_list; }; // System::VrrpItems::InstItems::IfItems::InterfaceList::RtnwPathToIfItems class System::VrrpItems::InstItems::IfItems::InterfaceList::RtnwPathToIfItems::RtNwPathToIfList : public ydk::Entity { public: RtNwPathToIfList(); ~RtNwPathToIfList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::VrrpItems::InstItems::IfItems::InterfaceList::RtnwPathToIfItems::RtNwPathToIfList class System::Vrrpv3Items : public ydk::Entity { public: Vrrpv3Items(); ~Vrrpv3Items(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt class InstItems; //type: System::Vrrpv3Items::InstItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::Vrrpv3Items::InstItems> inst_items; }; // System::Vrrpv3Items class System::Vrrpv3Items::InstItems : public ydk::Entity { public: InstItems(); ~InstItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf ctrl; //type: string class IfItems; //type: System::Vrrpv3Items::InstItems::IfItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::Vrrpv3Items::InstItems::IfItems> if_items; }; // System::Vrrpv3Items::InstItems class System::Vrrpv3Items::InstItems::IfItems : public ydk::Entity { public: IfItems(); ~IfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class InterfaceList; //type: System::Vrrpv3Items::InstItems::IfItems::InterfaceList ydk::YList interface_list; }; // System::Vrrpv3Items::InstItems::IfItems class System::Vrrpv3Items::InstItems::IfItems::InterfaceList : public ydk::Entity { public: InterfaceList(); ~InterfaceList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: string ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ class IdItems; //type: System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems class RtvrfMbrItems; //type: System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtvrfMbrItems class RtnwPathToIfItems; //type: System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtnwPathToIfItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems> id_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtvrfMbrItems> rtvrfmbr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtnwPathToIfItems> rtnwpathtoif_items; }; // System::Vrrpv3Items::InstItems::IfItems::InterfaceList class System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems : public ydk::Entity { public: IdItems(); ~IdItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class VrList; //type: System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList ydk::YList vr_list; }; // System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems class System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList : public ydk::Entity { public: VrList(); ~VrList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf id; //type: uint32 ydk::YLeaf af; //type: Vrrpv3VrAf ydk::YLeaf ip; //type: string ydk::YLeaf advintvl; //type: uint32 ydk::YLeaf pricfg; //type: uint32 ydk::YLeaf preempt; //type: Vrrpv3Preempt ydk::YLeaf name; //type: string ydk::YLeaf preemptdelaymin; //type: uint32 ydk::YLeaf adminst; //type: Vrrpv3AdminSt class TrackItems; //type: System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::TrackItems class AddrItems; //type: System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::AddrItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::TrackItems> track_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::AddrItems> addr_items; }; // System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList class System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::TrackItems : public ydk::Entity { public: TrackItems(); ~TrackItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ObjectTrackList; //type: System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::TrackItems::ObjectTrackList ydk::YList objecttrack_list; }; // System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::TrackItems class System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::TrackItems::ObjectTrackList : public ydk::Entity { public: ObjectTrackList(); ~ObjectTrackList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf id; //type: uint16 ydk::YLeaf decrprio; //type: uint16 }; // System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::TrackItems::ObjectTrackList class System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::AddrItems : public ydk::Entity { public: AddrItems(); ~AddrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AddrList; //type: System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::AddrItems::AddrList ydk::YList addr_list; }; // System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::AddrItems class System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::AddrItems::AddrList : public ydk::Entity { public: AddrList(); ~AddrList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf addr; //type: string }; // System::Vrrpv3Items::InstItems::IfItems::InterfaceList::IdItems::VrList::AddrItems::AddrList class System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtvrfMbrItems : public ydk::Entity { public: RtvrfMbrItems(); ~RtvrfMbrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtvrfMbrItems class System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtnwPathToIfItems : public ydk::Entity { public: RtnwPathToIfItems(); ~RtnwPathToIfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RtNwPathToIfList; //type: System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtnwPathToIfItems::RtNwPathToIfList ydk::YList rtnwpathtoif_list; }; // System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtnwPathToIfItems class System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtnwPathToIfItems::RtNwPathToIfList : public ydk::Entity { public: RtNwPathToIfList(); ~RtNwPathToIfList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::Vrrpv3Items::InstItems::IfItems::InterfaceList::RtnwPathToIfItems::RtNwPathToIfList class System::ScrtchpdrtItems : public ydk::Entity { public: ScrtchpdrtItems(); ~ScrtchpdrtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class RpmcliItems; //type: System::ScrtchpdrtItems::RpmcliItems class VlanmgrcliItems; //type: System::ScrtchpdrtItems::VlanmgrcliItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems> rpmcli_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::VlanmgrcliItems> vlanmgrcli_items; }; // System::ScrtchpdrtItems class System::ScrtchpdrtItems::RpmcliItems : public ydk::Entity { public: RpmcliItems(); ~RpmcliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt class AccesslistcliItems; //type: System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems class Pfxlistv4cliItems; //type: System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems class Pfxlistv6cliItems; //type: System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems class RtregcomcliItems; //type: System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems> accesslistcli_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems> pfxlistv4cli_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems> pfxlistv6cli_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems> rtregcomcli_items; }; // System::ScrtchpdrtItems::RpmcliItems class System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems : public ydk::Entity { public: AccesslistcliItems(); ~AccesslistcliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class RuleCliList; //type: System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems::RuleCliList ydk::YList rulecli_list; }; // System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems class System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems::RuleCliList : public ydk::Entity { public: RuleCliList(); ~RuleCliList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string class EntcliItems; //type: System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems::RuleCliList::EntcliItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems::RuleCliList::EntcliItems> entcli_items; }; // System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems::RuleCliList class System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems::RuleCliList::EntcliItems : public ydk::Entity { public: EntcliItems(); ~EntcliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf cliaction; //type: ScrtchpdAction ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf order; //type: uint32 ydk::YLeaf action; //type: RtfltAction ydk::YLeaf regex; //type: string }; // System::ScrtchpdrtItems::RpmcliItems::AccesslistcliItems::RuleCliList::EntcliItems class System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems : public ydk::Entity { public: Pfxlistv4cliItems(); ~Pfxlistv4cliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class RuleV4CliList; //type: System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems::RuleV4CliList ydk::YList rulev4cli_list; }; // System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems class System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems::RuleV4CliList : public ydk::Entity { public: RuleV4CliList(); ~RuleV4CliList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string class EntcliItems; //type: System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems::RuleV4CliList::EntcliItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems::RuleV4CliList::EntcliItems> entcli_items; }; // System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems::RuleV4CliList class System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems::RuleV4CliList::EntcliItems : public ydk::Entity { public: EntcliItems(); ~EntcliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf cliaction; //type: ScrtchpdAction ydk::YLeaf pfx; //type: string ydk::YLeaf mask; //type: string ydk::YLeaf criteria; //type: RtpfxCriteria ydk::YLeaf frompfxlen; //type: uint16 ydk::YLeaf topfxlen; //type: uint16 ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf order; //type: uint32 ydk::YLeaf action; //type: RtfltAction }; // System::ScrtchpdrtItems::RpmcliItems::Pfxlistv4cliItems::RuleV4CliList::EntcliItems class System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems : public ydk::Entity { public: Pfxlistv6cliItems(); ~Pfxlistv6cliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class RuleV6CliList; //type: System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems::RuleV6CliList ydk::YList rulev6cli_list; }; // System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems class System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems::RuleV6CliList : public ydk::Entity { public: RuleV6CliList(); ~RuleV6CliList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string class EntcliItems; //type: System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems::RuleV6CliList::EntcliItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems::RuleV6CliList::EntcliItems> entcli_items; }; // System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems::RuleV6CliList class System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems::RuleV6CliList::EntcliItems : public ydk::Entity { public: EntcliItems(); ~EntcliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf cliaction; //type: ScrtchpdAction ydk::YLeaf pfx; //type: string ydk::YLeaf mask; //type: string ydk::YLeaf criteria; //type: RtpfxCriteria ydk::YLeaf frompfxlen; //type: uint16 ydk::YLeaf topfxlen; //type: uint16 ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf order; //type: uint32 ydk::YLeaf action; //type: RtfltAction }; // System::ScrtchpdrtItems::RpmcliItems::Pfxlistv6cliItems::RuleV6CliList::EntcliItems class System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems : public ydk::Entity { public: RtregcomcliItems(); ~RtregcomcliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class RuleCliList; //type: System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList ydk::YList rulecli_list; }; // System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems class System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList : public ydk::Entity { public: RuleCliList(); ~RuleCliList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf type; //type: RtcomComT ydk::YLeaf mode; //type: RtcomMode class EntregcliItems; //type: System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntregcliItems class EntcliItems; //type: System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntregcliItems> entregcli_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems> entcli_items; }; // System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList class System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntregcliItems : public ydk::Entity { public: EntregcliItems(); ~EntregcliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf numofchildren; //type: uint32 ydk::YLeaf cliaction; //type: ScrtchpdAction ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf order; //type: uint32 ydk::YLeaf action; //type: RtfltAction ydk::YLeaf regex; //type: string }; // System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntregcliItems class System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems : public ydk::Entity { public: EntcliItems(); ~EntcliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf numofchildren; //type: uint32 ydk::YLeaf cliaction; //type: ScrtchpdAction ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf order; //type: uint32 ydk::YLeaf action; //type: RtfltAction ydk::YLeaf regex; //type: string class ItemcliItems; //type: System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems::ItemcliItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems::ItemcliItems> itemcli_items; }; // System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems class System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems::ItemcliItems : public ydk::Entity { public: ItemcliItems(); ~ItemcliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ItemCliList; //type: System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems::ItemcliItems::ItemCliList ydk::YList itemcli_list; }; // System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems::ItemcliItems class System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems::ItemcliItems::ItemCliList : public ydk::Entity { public: ItemCliList(); ~ItemCliList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string }; // System::ScrtchpdrtItems::RpmcliItems::RtregcomcliItems::RuleCliList::EntcliItems::ItemcliItems::ItemCliList class System::ScrtchpdrtItems::VlanmgrcliItems : public ydk::Entity { public: VlanmgrcliItems(); ~VlanmgrcliItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf operst; //type: NwEntOperSt class InstItems; //type: System::ScrtchpdrtItems::VlanmgrcliItems::InstItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ScrtchpdrtItems::VlanmgrcliItems::InstItems> inst_items; }; // System::ScrtchpdrtItems::VlanmgrcliItems class System::ScrtchpdrtItems::VlanmgrcliItems::InstItems : public ydk::Entity { public: InstItems(); ~InstItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf vxlannativevlans; //type: boolean ydk::YLeaf name; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf ctrl; //type: string }; // System::ScrtchpdrtItems::VlanmgrcliItems::InstItems class System::SectlItems : public ydk::Entity { public: SectlItems(); ~SectlItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class SwTLTestObjList; //type: System::SectlItems::SwTLTestObjList ydk::YList swtltestobj_list; }; // System::SectlItems class System::SectlItems::SwTLTestObjList : public ydk::Entity { public: SwTLTestObjList(); ~SwTLTestObjList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string ydk::YLeaf id; //type: uint64 ydk::YLeaf descr; //type: string ydk::YLeaf objdn; //type: string ydk::YLeaf prikey; //type: string class SeccItems; //type: System::SectlItems::SwTLTestObjList::SeccItems class IeccItems; //type: System::SectlItems::SwTLTestObjList::IeccItems class RttoObjItems; //type: System::SectlItems::SwTLTestObjList::RttoObjItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SectlItems::SwTLTestObjList::SeccItems> secc_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SectlItems::SwTLTestObjList::IeccItems> iecc_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SectlItems::SwTLTestObjList::RttoObjItems> rttoobj_items; }; // System::SectlItems::SwTLTestObjList class System::SectlItems::SwTLTestObjList::SeccItems : public ydk::Entity { public: SeccItems(); ~SeccItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class SwCTestObjList; //type: System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList ydk::YList swctestobj_list; }; // System::SectlItems::SwTLTestObjList::SeccItems class System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList : public ydk::Entity { public: SwCTestObjList(); ~SwCTestObjList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf swctestonly; //type: string ydk::YLeaf id; //type: uint64 ydk::YLeaf descr; //type: string ydk::YLeaf objdn; //type: string class RstoObjItems; //type: System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList::RstoObjItems class RttoObjItems; //type: System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList::RttoObjItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList::RstoObjItems> rstoobj_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList::RttoObjItems> rttoobj_items; }; // System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList class System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList::RstoObjItems : public ydk::Entity { public: RstoObjItems(); ~RstoObjItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList::RstoObjItems class System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList::RttoObjItems : public ydk::Entity { public: RttoObjItems(); ~RttoObjItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::SectlItems::SwTLTestObjList::SeccItems::SwCTestObjList::RttoObjItems class System::SectlItems::SwTLTestObjList::IeccItems : public ydk::Entity { public: IeccItems(); ~IeccItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class IfcCTestObjList; //type: System::SectlItems::SwTLTestObjList::IeccItems::IfcCTestObjList ydk::YList ifcctestobj_list; }; // System::SectlItems::SwTLTestObjList::IeccItems class System::SectlItems::SwTLTestObjList::IeccItems::IfcCTestObjList : public ydk::Entity { public: IfcCTestObjList(); ~IfcCTestObjList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf ifcctestonly; //type: string ydk::YLeaf id; //type: uint64 ydk::YLeaf descr; //type: string ydk::YLeaf objdn; //type: string class RttoObjItems; //type: System::SectlItems::SwTLTestObjList::IeccItems::IfcCTestObjList::RttoObjItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::SectlItems::SwTLTestObjList::IeccItems::IfcCTestObjList::RttoObjItems> rttoobj_items; }; // System::SectlItems::SwTLTestObjList::IeccItems::IfcCTestObjList class System::SectlItems::SwTLTestObjList::IeccItems::IfcCTestObjList::RttoObjItems : public ydk::Entity { public: RttoObjItems(); ~RttoObjItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::SectlItems::SwTLTestObjList::IeccItems::IfcCTestObjList::RttoObjItems class System::SectlItems::SwTLTestObjList::RttoObjItems : public ydk::Entity { public: RttoObjItems(); ~RttoObjItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::SectlItems::SwTLTestObjList::RttoObjItems class System::CaggrItems : public ydk::Entity { public: CaggrItems(); ~CaggrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class AggrIfList; //type: System::CaggrItems::AggrIfList ydk::YList aggrif_list; }; // System::CaggrItems class System::CaggrItems::AggrIfList : public ydk::Entity { public: AggrIfList(); ~AggrIfList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: string ydk::YLeaf operst; //type: L1OperSt ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf adminst; //type: L1AdminSt ydk::YLeaf speed; //type: L1Speed ydk::YLeaf duplex; //type: L1Duplex ydk::YLeaf autoneg; //type: L1AutoNeg ydk::YLeaf mtu; //type: uint32 ydk::YLeaf snmptrapst; //type: L1SnmpTrapSt ydk::YLeaf mode; //type: L1Mode ydk::YLeaf layer; //type: L1Layer ydk::YLeaf mdix; //type: L1Mdix ydk::YLeaf delay; //type: uint32 ydk::YLeaf linkdebounce; //type: uint16 ydk::YLeaf dot1qethertype; //type: uint32 ydk::YLeaf bw; //type: uint32 ydk::YLeaf medium; //type: L1Medium ydk::YLeaf inhbw; //type: uint32 ydk::YLeaf spanmode; //type: L1SpanMode ydk::YLeaf linklog; //type: L1LinkLog ydk::YLeaf trunklog; //type: L1TrunkLog ydk::YLeaf routermac; //type: string ydk::YLeaf portt; //type: EqptPortT ydk::YLeaf usage; //type: string ydk::YLeaf trunkvlans; //type: string ydk::YLeaf accessvlan; //type: string ydk::YLeaf controllerid; //type: string ydk::YLeaf nativevlan; //type: string ydk::YLeaf usercfgdflags; //type: string class DomItems; //type: System::CaggrItems::AggrIfList::DomItems class RtextConfItems; //type: System::CaggrItems::AggrIfList::RtextConfItems class RtbrConfItems; //type: System::CaggrItems::AggrIfList::RtbrConfItems class RtfvNodePortAttItems; //type: System::CaggrItems::AggrIfList::RtfvNodePortAttItems class RtvrfMbrItems; //type: System::CaggrItems::AggrIfList::RtvrfMbrItems class RtphysRtdConfItems; //type: System::CaggrItems::AggrIfList::RtphysRtdConfItems class Rtl3EncPhysRtdConfItems; //type: System::CaggrItems::AggrIfList::Rtl3EncPhysRtdConfItems class RtnwPathToIfItems; //type: System::CaggrItems::AggrIfList::RtnwPathToIfItems class RtLsNodeToIfItems; //type: System::CaggrItems::AggrIfList::RtLsNodeToIfItems class RsmbrIfsItems; //type: System::CaggrItems::AggrIfList::RsmbrIfsItems class RsactiveIfItems; //type: System::CaggrItems::AggrIfList::RsactiveIfItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::DomItems> dom_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::RtextConfItems> rtextconf_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::RtbrConfItems> rtbrconf_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::RtfvNodePortAttItems> rtfvnodeportatt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::RtvrfMbrItems> rtvrfmbr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::RtphysRtdConfItems> rtphysrtdconf_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::Rtl3EncPhysRtdConfItems> rtl3encphysrtdconf_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::RtnwPathToIfItems> rtnwpathtoif_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::RtLsNodeToIfItems> rtlsnodetoif_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::RsmbrIfsItems> rsmbrifs_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::RsactiveIfItems> rsactiveif_items; }; // System::CaggrItems::AggrIfList class System::CaggrItems::AggrIfList::DomItems : public ydk::Entity { public: DomItems(); ~DomItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class DomDefList; //type: System::CaggrItems::AggrIfList::DomItems::DomDefList ydk::YList domdef_list; }; // System::CaggrItems::AggrIfList::DomItems class System::CaggrItems::AggrIfList::DomItems::DomDefList : public ydk::Entity { public: DomDefList(); ~DomDefList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf dompkey; //type: string ydk::YLeaf instrimedcy; //type: FvImmediacy_ ydk::YLeaf name; //type: string class RsdomDefNsItems; //type: System::CaggrItems::AggrIfList::DomItems::DomDefList::RsdomDefNsItems class RsdomDefNsLocalItems; //type: System::CaggrItems::AggrIfList::DomItems::DomDefList::RsdomDefNsLocalItems class RtfvToDomDefItems; //type: System::CaggrItems::AggrIfList::DomItems::DomDefList::RtfvToDomDefItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::DomItems::DomDefList::RsdomDefNsItems> rsdomdefns_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::DomItems::DomDefList::RsdomDefNsLocalItems> rsdomdefnslocal_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CaggrItems::AggrIfList::DomItems::DomDefList::RtfvToDomDefItems> rtfvtodomdef_items; }; // System::CaggrItems::AggrIfList::DomItems::DomDefList class System::CaggrItems::AggrIfList::DomItems::DomDefList::RsdomDefNsItems : public ydk::Entity { public: RsdomDefNsItems(); ~RsdomDefNsItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::DomItems::DomDefList::RsdomDefNsItems class System::CaggrItems::AggrIfList::DomItems::DomDefList::RsdomDefNsLocalItems : public ydk::Entity { public: RsdomDefNsLocalItems(); ~RsdomDefNsLocalItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::DomItems::DomDefList::RsdomDefNsLocalItems class System::CaggrItems::AggrIfList::DomItems::DomDefList::RtfvToDomDefItems : public ydk::Entity { public: RtfvToDomDefItems(); ~RtfvToDomDefItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RtFvToDomDefList; //type: System::CaggrItems::AggrIfList::DomItems::DomDefList::RtfvToDomDefItems::RtFvToDomDefList ydk::YList rtfvtodomdef_list; }; // System::CaggrItems::AggrIfList::DomItems::DomDefList::RtfvToDomDefItems class System::CaggrItems::AggrIfList::DomItems::DomDefList::RtfvToDomDefItems::RtFvToDomDefList : public ydk::Entity { public: RtFvToDomDefList(); ~RtFvToDomDefList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::DomItems::DomDefList::RtfvToDomDefItems::RtFvToDomDefList class System::CaggrItems::AggrIfList::RtextConfItems : public ydk::Entity { public: RtextConfItems(); ~RtextConfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::RtextConfItems class System::CaggrItems::AggrIfList::RtbrConfItems : public ydk::Entity { public: RtbrConfItems(); ~RtbrConfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::RtbrConfItems class System::CaggrItems::AggrIfList::RtfvNodePortAttItems : public ydk::Entity { public: RtfvNodePortAttItems(); ~RtfvNodePortAttItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RtFvNodePortAttList; //type: System::CaggrItems::AggrIfList::RtfvNodePortAttItems::RtFvNodePortAttList ydk::YList rtfvnodeportatt_list; }; // System::CaggrItems::AggrIfList::RtfvNodePortAttItems class System::CaggrItems::AggrIfList::RtfvNodePortAttItems::RtFvNodePortAttList : public ydk::Entity { public: RtFvNodePortAttList(); ~RtFvNodePortAttList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::RtfvNodePortAttItems::RtFvNodePortAttList class System::CaggrItems::AggrIfList::RtvrfMbrItems : public ydk::Entity { public: RtvrfMbrItems(); ~RtvrfMbrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::RtvrfMbrItems class System::CaggrItems::AggrIfList::RtphysRtdConfItems : public ydk::Entity { public: RtphysRtdConfItems(); ~RtphysRtdConfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::RtphysRtdConfItems class System::CaggrItems::AggrIfList::Rtl3EncPhysRtdConfItems : public ydk::Entity { public: Rtl3EncPhysRtdConfItems(); ~Rtl3EncPhysRtdConfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RtL3EncPhysRtdConfList; //type: System::CaggrItems::AggrIfList::Rtl3EncPhysRtdConfItems::RtL3EncPhysRtdConfList ydk::YList rtl3encphysrtdconf_list; }; // System::CaggrItems::AggrIfList::Rtl3EncPhysRtdConfItems class System::CaggrItems::AggrIfList::Rtl3EncPhysRtdConfItems::RtL3EncPhysRtdConfList : public ydk::Entity { public: RtL3EncPhysRtdConfList(); ~RtL3EncPhysRtdConfList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::Rtl3EncPhysRtdConfItems::RtL3EncPhysRtdConfList class System::CaggrItems::AggrIfList::RtnwPathToIfItems : public ydk::Entity { public: RtnwPathToIfItems(); ~RtnwPathToIfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RtNwPathToIfList; //type: System::CaggrItems::AggrIfList::RtnwPathToIfItems::RtNwPathToIfList ydk::YList rtnwpathtoif_list; }; // System::CaggrItems::AggrIfList::RtnwPathToIfItems class System::CaggrItems::AggrIfList::RtnwPathToIfItems::RtNwPathToIfList : public ydk::Entity { public: RtNwPathToIfList(); ~RtNwPathToIfList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::RtnwPathToIfItems::RtNwPathToIfList class System::CaggrItems::AggrIfList::RtLsNodeToIfItems : public ydk::Entity { public: RtLsNodeToIfItems(); ~RtLsNodeToIfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::RtLsNodeToIfItems class System::CaggrItems::AggrIfList::RsmbrIfsItems : public ydk::Entity { public: RsmbrIfsItems(); ~RsmbrIfsItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RsMbrIfsList; //type: System::CaggrItems::AggrIfList::RsmbrIfsItems::RsMbrIfsList ydk::YList rsmbrifs_list; }; // System::CaggrItems::AggrIfList::RsmbrIfsItems class System::CaggrItems::AggrIfList::RsmbrIfsItems::RsMbrIfsList : public ydk::Entity { public: RsMbrIfsList(); ~RsMbrIfsList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::RsmbrIfsItems::RsMbrIfsList class System::CaggrItems::AggrIfList::RsactiveIfItems : public ydk::Entity { public: RsactiveIfItems(); ~RsactiveIfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CaggrItems::AggrIfList::RsactiveIfItems class System::CphysItems : public ydk::Entity { public: CphysItems(); ~CphysItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class PhysIfList; //type: System::CphysItems::PhysIfList ydk::YList physif_list; }; // System::CphysItems class System::CphysItems::PhysIfList : public ydk::Entity { public: PhysIfList(); ~PhysIfList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: string ydk::YLeaf operst; //type: L1OperSt ydk::YLeaf name; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf adminst; //type: L1AdminSt ydk::YLeaf speed; //type: L1Speed ydk::YLeaf duplex; //type: L1Duplex ydk::YLeaf autoneg; //type: L1AutoNeg ydk::YLeaf mtu; //type: uint32 ydk::YLeaf snmptrapst; //type: L1SnmpTrapSt ydk::YLeaf mode; //type: L1Mode ydk::YLeaf layer; //type: L1Layer ydk::YLeaf mdix; //type: L1Mdix ydk::YLeaf delay; //type: uint32 ydk::YLeaf linkdebounce; //type: uint16 ydk::YLeaf dot1qethertype; //type: uint32 ydk::YLeaf bw; //type: uint32 ydk::YLeaf medium; //type: L1Medium ydk::YLeaf inhbw; //type: uint32 ydk::YLeaf spanmode; //type: L1SpanMode ydk::YLeaf linklog; //type: L1LinkLog ydk::YLeaf trunklog; //type: L1TrunkLog ydk::YLeaf routermac; //type: string ydk::YLeaf portt; //type: EqptPortT ydk::YLeaf usage; //type: string ydk::YLeaf trunkvlans; //type: string ydk::YLeaf accessvlan; //type: string ydk::YLeaf controllerid; //type: string ydk::YLeaf nativevlan; //type: string ydk::YLeaf usercfgdflags; //type: string class DomItems; //type: System::CphysItems::PhysIfList::DomItems class RtextConfItems; //type: System::CphysItems::PhysIfList::RtextConfItems class RtbrConfItems; //type: System::CphysItems::PhysIfList::RtbrConfItems class RtfvNodePortAttItems; //type: System::CphysItems::PhysIfList::RtfvNodePortAttItems class RtvrfMbrItems; //type: System::CphysItems::PhysIfList::RtvrfMbrItems class RtphysRtdConfItems; //type: System::CphysItems::PhysIfList::RtphysRtdConfItems class Rtl3EncPhysRtdConfItems; //type: System::CphysItems::PhysIfList::Rtl3EncPhysRtdConfItems class RtnwPathToIfItems; //type: System::CphysItems::PhysIfList::RtnwPathToIfItems class RtLsNodeToIfItems; //type: System::CphysItems::PhysIfList::RtLsNodeToIfItems class RtmbrIfsItems; //type: System::CphysItems::PhysIfList::RtmbrIfsItems class RtactiveIfItems; //type: System::CphysItems::PhysIfList::RtactiveIfItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::DomItems> dom_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::RtextConfItems> rtextconf_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::RtbrConfItems> rtbrconf_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::RtfvNodePortAttItems> rtfvnodeportatt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::RtvrfMbrItems> rtvrfmbr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::RtphysRtdConfItems> rtphysrtdconf_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::Rtl3EncPhysRtdConfItems> rtl3encphysrtdconf_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::RtnwPathToIfItems> rtnwpathtoif_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::RtLsNodeToIfItems> rtlsnodetoif_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::RtmbrIfsItems> rtmbrifs_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::RtactiveIfItems> rtactiveif_items; }; // System::CphysItems::PhysIfList class System::CphysItems::PhysIfList::DomItems : public ydk::Entity { public: DomItems(); ~DomItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class DomDefList; //type: System::CphysItems::PhysIfList::DomItems::DomDefList ydk::YList domdef_list; }; // System::CphysItems::PhysIfList::DomItems class System::CphysItems::PhysIfList::DomItems::DomDefList : public ydk::Entity { public: DomDefList(); ~DomDefList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf dompkey; //type: string ydk::YLeaf instrimedcy; //type: FvImmediacy_ ydk::YLeaf name; //type: string class RsdomDefNsItems; //type: System::CphysItems::PhysIfList::DomItems::DomDefList::RsdomDefNsItems class RsdomDefNsLocalItems; //type: System::CphysItems::PhysIfList::DomItems::DomDefList::RsdomDefNsLocalItems class RtfvToDomDefItems; //type: System::CphysItems::PhysIfList::DomItems::DomDefList::RtfvToDomDefItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::DomItems::DomDefList::RsdomDefNsItems> rsdomdefns_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::DomItems::DomDefList::RsdomDefNsLocalItems> rsdomdefnslocal_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::CphysItems::PhysIfList::DomItems::DomDefList::RtfvToDomDefItems> rtfvtodomdef_items; }; // System::CphysItems::PhysIfList::DomItems::DomDefList class System::CphysItems::PhysIfList::DomItems::DomDefList::RsdomDefNsItems : public ydk::Entity { public: RsdomDefNsItems(); ~RsdomDefNsItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::DomItems::DomDefList::RsdomDefNsItems class System::CphysItems::PhysIfList::DomItems::DomDefList::RsdomDefNsLocalItems : public ydk::Entity { public: RsdomDefNsLocalItems(); ~RsdomDefNsLocalItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::DomItems::DomDefList::RsdomDefNsLocalItems class System::CphysItems::PhysIfList::DomItems::DomDefList::RtfvToDomDefItems : public ydk::Entity { public: RtfvToDomDefItems(); ~RtfvToDomDefItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RtFvToDomDefList; //type: System::CphysItems::PhysIfList::DomItems::DomDefList::RtfvToDomDefItems::RtFvToDomDefList ydk::YList rtfvtodomdef_list; }; // System::CphysItems::PhysIfList::DomItems::DomDefList::RtfvToDomDefItems class System::CphysItems::PhysIfList::DomItems::DomDefList::RtfvToDomDefItems::RtFvToDomDefList : public ydk::Entity { public: RtFvToDomDefList(); ~RtFvToDomDefList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::DomItems::DomDefList::RtfvToDomDefItems::RtFvToDomDefList class System::CphysItems::PhysIfList::RtextConfItems : public ydk::Entity { public: RtextConfItems(); ~RtextConfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::RtextConfItems class System::CphysItems::PhysIfList::RtbrConfItems : public ydk::Entity { public: RtbrConfItems(); ~RtbrConfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::RtbrConfItems class System::CphysItems::PhysIfList::RtfvNodePortAttItems : public ydk::Entity { public: RtfvNodePortAttItems(); ~RtfvNodePortAttItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RtFvNodePortAttList; //type: System::CphysItems::PhysIfList::RtfvNodePortAttItems::RtFvNodePortAttList ydk::YList rtfvnodeportatt_list; }; // System::CphysItems::PhysIfList::RtfvNodePortAttItems class System::CphysItems::PhysIfList::RtfvNodePortAttItems::RtFvNodePortAttList : public ydk::Entity { public: RtFvNodePortAttList(); ~RtFvNodePortAttList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::RtfvNodePortAttItems::RtFvNodePortAttList class System::CphysItems::PhysIfList::RtvrfMbrItems : public ydk::Entity { public: RtvrfMbrItems(); ~RtvrfMbrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::RtvrfMbrItems class System::CphysItems::PhysIfList::RtphysRtdConfItems : public ydk::Entity { public: RtphysRtdConfItems(); ~RtphysRtdConfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::RtphysRtdConfItems class System::CphysItems::PhysIfList::Rtl3EncPhysRtdConfItems : public ydk::Entity { public: Rtl3EncPhysRtdConfItems(); ~Rtl3EncPhysRtdConfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RtL3EncPhysRtdConfList; //type: System::CphysItems::PhysIfList::Rtl3EncPhysRtdConfItems::RtL3EncPhysRtdConfList ydk::YList rtl3encphysrtdconf_list; }; // System::CphysItems::PhysIfList::Rtl3EncPhysRtdConfItems class System::CphysItems::PhysIfList::Rtl3EncPhysRtdConfItems::RtL3EncPhysRtdConfList : public ydk::Entity { public: RtL3EncPhysRtdConfList(); ~RtL3EncPhysRtdConfList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::Rtl3EncPhysRtdConfItems::RtL3EncPhysRtdConfList class System::CphysItems::PhysIfList::RtnwPathToIfItems : public ydk::Entity { public: RtnwPathToIfItems(); ~RtnwPathToIfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RtNwPathToIfList; //type: System::CphysItems::PhysIfList::RtnwPathToIfItems::RtNwPathToIfList ydk::YList rtnwpathtoif_list; }; // System::CphysItems::PhysIfList::RtnwPathToIfItems class System::CphysItems::PhysIfList::RtnwPathToIfItems::RtNwPathToIfList : public ydk::Entity { public: RtNwPathToIfList(); ~RtNwPathToIfList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::RtnwPathToIfItems::RtNwPathToIfList class System::CphysItems::PhysIfList::RtLsNodeToIfItems : public ydk::Entity { public: RtLsNodeToIfItems(); ~RtLsNodeToIfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::RtLsNodeToIfItems class System::CphysItems::PhysIfList::RtmbrIfsItems : public ydk::Entity { public: RtmbrIfsItems(); ~RtmbrIfsItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::RtmbrIfsItems class System::CphysItems::PhysIfList::RtactiveIfItems : public ydk::Entity { public: RtactiveIfItems(); ~RtactiveIfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tdn; //type: string }; // System::CphysItems::PhysIfList::RtactiveIfItems class System::ClialiasItems : public ydk::Entity { public: ClialiasItems(); ~ClialiasItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class CliAliasList; //type: System::ClialiasItems::CliAliasList ydk::YList clialias_list; }; // System::ClialiasItems class System::ClialiasItems::CliAliasList : public ydk::Entity { public: CliAliasList(); ~CliAliasList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf aliasname; //type: string ydk::YLeaf aliascmd; //type: string }; // System::ClialiasItems::CliAliasList class System::ActionItems : public ydk::Entity { public: ActionItems(); ~ActionItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class TracertnveItems; //type: System::ActionItems::TracertnveItems class PathtracenveItems; //type: System::ActionItems::PathtracenveItems class EqptdiagruleItems; //type: System::ActionItems::EqptdiagruleItems class LsubjItems; //type: System::ActionItems::LsubjItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::TracertnveItems> tracertnve_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::PathtracenveItems> pathtracenve_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::EqptdiagruleItems> eqptdiagrule_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems> lsubj_items; }; // System::ActionItems class System::ActionItems::TracertnveItems : public ydk::Entity { public: TracertnveItems(); ~TracertnveItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class TraceRtNveList; //type: System::ActionItems::TracertnveItems::TraceRtNveList ydk::YList tracertnve_list; }; // System::ActionItems::TracertnveItems class System::ActionItems::TracertnveItems::TraceRtNveList : public ydk::Entity { public: TraceRtNveList(); ~TraceRtNveList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf session; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf startts; //type: one of uint64, string ydk::YLeaf type; //type: ActionType ydk::YLeaf rsz; //type: uint16 ydk::YLeaf rtm; //type: one of uint64, string ydk::YLeaf peerclassid; //type: string ydk::YLeaf adminst; //type: ActionAdminSt ydk::YLeaf freq; //type: one of uint64, string ydk::YLeaf profileid; //type: uint16 ydk::YLeaf dstip; //type: string ydk::YLeaf dstipv6; //type: string ydk::YLeaf dstmac; //type: string ydk::YLeaf srcip; //type: string ydk::YLeaf srcipv6; //type: string ydk::YLeaf dot1q; //type: uint16 ydk::YLeaf srcport; //type: uint16 ydk::YLeaf dstport; //type: uint16 ydk::YLeaf maxttl; //type: uint8 ydk::YLeaf vrf; //type: string ydk::YLeaf vni; //type: uint32 ydk::YLeaf timeout; //type: uint8 ydk::YLeaf egressif; //type: string ydk::YLeaf macsrcif; //type: string ydk::YLeaf verifyhost; //type: boolean ydk::YLeaf sessionid; //type: uint32 ydk::YLeaf payload_dot1q; //type: uint16 ydk::YLeaf payload_srcip; //type: string ydk::YLeaf payload_srcipv6; //type: string ydk::YLeaf payload_srcmac; //type: string ydk::YLeaf payload_dstip; //type: string ydk::YLeaf payload_dstipv6; //type: string ydk::YLeaf payload_dstmac; //type: string ydk::YLeaf payload_srcport; //type: uint16 ydk::YLeaf payload_dstport; //type: uint16 ydk::YLeaf payload_protocol; //type: uint16 ydk::YLeaf payload_srcif; //type: string class TrnversltItems; //type: System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems> trnverslt_items; }; // System::ActionItems::TracertnveItems::TraceRtNveList class System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems : public ydk::Entity { public: TrnversltItems(); ~TrnversltItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class TraceRtNveRsltList; //type: System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList ydk::YList tracertnverslt_list; }; // System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems class System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList : public ydk::Entity { public: TraceRtNveRsltList(); ~TraceRtNveRsltList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sessionid; //type: uint16 ydk::YLeaf dstip; //type: string ydk::YLeaf maxhops; //type: uint8 ydk::YLeaf errorcode; //type: string ydk::YLeaf failreason; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf startts; //type: one of uint64, string ydk::YLeaf type; //type: ActionType ydk::YLeaf rsz; //type: uint16 ydk::YLeaf rtm; //type: one of uint64, string ydk::YLeaf peerclassid; //type: string ydk::YLeaf qual; //type: string ydk::YLeaf ack; //type: boolean ydk::YLeaf endts; //type: one of uint64, string ydk::YLeaf operst; //type: ActionOperSt class PathtrItems; //type: System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems> pathtr_items; }; // System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList class System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems : public ydk::Entity { public: PathtrItems(); ~PathtrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PathTrList; //type: System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems::PathTrList ydk::YList pathtr_list; }; // System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems class System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems::PathTrList : public ydk::Entity { public: PathTrList(); ~PathTrList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf id; //type: uint8 class NodetrItems; //type: System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems::PathTrList::NodetrItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems::PathTrList::NodetrItems> nodetr_items; }; // System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems::PathTrList class System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems::PathTrList::NodetrItems : public ydk::Entity { public: NodetrItems(); ~NodetrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class NodeTrList; //type: System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems::PathTrList::NodetrItems::NodeTrList ydk::YList nodetr_list; }; // System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems::PathTrList::NodetrItems class System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems::PathTrList::NodetrItems::NodeTrList : public ydk::Entity { public: NodeTrList(); ~NodeTrList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint8 ydk::YLeaf addr; //type: string ydk::YLeaf v6addr; //type: string ydk::YLeaf elapsedtime; //type: one of uint64, string }; // System::ActionItems::TracertnveItems::TraceRtNveList::TrnversltItems::TraceRtNveRsltList::PathtrItems::PathTrList::NodetrItems::NodeTrList class System::ActionItems::PathtracenveItems : public ydk::Entity { public: PathtracenveItems(); ~PathtracenveItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class PathTraceNveList; //type: System::ActionItems::PathtracenveItems::PathTraceNveList ydk::YList pathtracenve_list; }; // System::ActionItems::PathtracenveItems class System::ActionItems::PathtracenveItems::PathTraceNveList : public ydk::Entity { public: PathTraceNveList(); ~PathTraceNveList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf session; //type: string ydk::YLeaf reqstats; //type: boolean ydk::YLeaf descr; //type: string ydk::YLeaf startts; //type: one of uint64, string ydk::YLeaf type; //type: ActionType ydk::YLeaf rsz; //type: uint16 ydk::YLeaf rtm; //type: one of uint64, string ydk::YLeaf peerclassid; //type: string ydk::YLeaf adminst; //type: ActionAdminSt ydk::YLeaf freq; //type: one of uint64, string ydk::YLeaf profileid; //type: uint16 ydk::YLeaf dstip; //type: string ydk::YLeaf dstipv6; //type: string ydk::YLeaf dstmac; //type: string ydk::YLeaf srcip; //type: string ydk::YLeaf srcipv6; //type: string ydk::YLeaf dot1q; //type: uint16 ydk::YLeaf srcport; //type: uint16 ydk::YLeaf dstport; //type: uint16 ydk::YLeaf maxttl; //type: uint8 ydk::YLeaf vrf; //type: string ydk::YLeaf vni; //type: uint32 ydk::YLeaf timeout; //type: uint8 ydk::YLeaf egressif; //type: string ydk::YLeaf macsrcif; //type: string ydk::YLeaf verifyhost; //type: boolean ydk::YLeaf sessionid; //type: uint32 ydk::YLeaf payload_dot1q; //type: uint16 ydk::YLeaf payload_srcip; //type: string ydk::YLeaf payload_srcipv6; //type: string ydk::YLeaf payload_srcmac; //type: string ydk::YLeaf payload_dstip; //type: string ydk::YLeaf payload_dstipv6; //type: string ydk::YLeaf payload_dstmac; //type: string ydk::YLeaf payload_srcport; //type: uint16 ydk::YLeaf payload_dstport; //type: uint16 ydk::YLeaf payload_protocol; //type: uint16 ydk::YLeaf payload_srcif; //type: string class PtrnversltItems; //type: System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems> ptrnverslt_items; }; // System::ActionItems::PathtracenveItems::PathTraceNveList class System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems : public ydk::Entity { public: PtrnversltItems(); ~PtrnversltItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PathTraceNveRsltList; //type: System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList ydk::YList pathtracenverslt_list; }; // System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems class System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList : public ydk::Entity { public: PathTraceNveRsltList(); ~PathTraceNveRsltList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sessionid; //type: uint16 ydk::YLeaf dstip; //type: string ydk::YLeaf maxhops; //type: uint8 ydk::YLeaf errorcode; //type: string ydk::YLeaf failreason; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf startts; //type: one of uint64, string ydk::YLeaf type; //type: ActionType ydk::YLeaf rsz; //type: uint16 ydk::YLeaf rtm; //type: one of uint64, string ydk::YLeaf peerclassid; //type: string ydk::YLeaf qual; //type: string ydk::YLeaf ack; //type: boolean ydk::YLeaf endts; //type: one of uint64, string ydk::YLeaf operst; //type: ActionOperSt class PathptrItems; //type: System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems> pathptr_items; }; // System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList class System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems : public ydk::Entity { public: PathptrItems(); ~PathptrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PathPtrList; //type: System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems::PathPtrList ydk::YList pathptr_list; }; // System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems class System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems::PathPtrList : public ydk::Entity { public: PathPtrList(); ~PathPtrList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf id; //type: uint8 class NodeptrItems; //type: System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems::PathPtrList::NodeptrItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems::PathPtrList::NodeptrItems> nodeptr_items; }; // System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems::PathPtrList class System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems::PathPtrList::NodeptrItems : public ydk::Entity { public: NodeptrItems(); ~NodeptrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class NodePtrList; //type: System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems::PathPtrList::NodeptrItems::NodePtrList ydk::YList nodeptr_list; }; // System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems::PathPtrList::NodeptrItems class System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems::PathPtrList::NodeptrItems::NodePtrList : public ydk::Entity { public: NodePtrList(); ~NodePtrList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint8 ydk::YLeaf addr; //type: string ydk::YLeaf v6addr; //type: string ydk::YLeaf nodename; //type: string ydk::YLeaf elapsedtime; //type: one of uint64, string ydk::YLeaf ingressif; //type: string ydk::YLeaf ingressifstate; //type: string ydk::YLeaf rxlen; //type: uint64 ydk::YLeaf rxbytes; //type: uint64 ydk::YLeaf rxpktrate; //type: uint64 ydk::YLeaf rxbyterate; //type: uint64 ydk::YLeaf rxload; //type: uint64 ydk::YLeaf rxucast; //type: uint64 ydk::YLeaf rxmcast; //type: uint64 ydk::YLeaf rxbcast; //type: uint64 ydk::YLeaf rxdiscards; //type: uint64 ydk::YLeaf rxerrors; //type: uint64 ydk::YLeaf rxunknown; //type: uint64 ydk::YLeaf rxbandwidth; //type: uint32 ydk::YLeaf egressif; //type: string ydk::YLeaf egressifstate; //type: string ydk::YLeaf txlen; //type: uint64 ydk::YLeaf txbytes; //type: uint64 ydk::YLeaf txpktrate; //type: uint64 ydk::YLeaf txbyterate; //type: uint64 ydk::YLeaf txload; //type: uint64 ydk::YLeaf txucast; //type: uint64 ydk::YLeaf txmcast; //type: uint64 ydk::YLeaf txbcast; //type: uint64 ydk::YLeaf txdiscards; //type: uint64 ydk::YLeaf txerrors; //type: uint64 ydk::YLeaf txbandwidth; //type: uint32 }; // System::ActionItems::PathtracenveItems::PathTraceNveList::PtrnversltItems::PathTraceNveRsltList::PathptrItems::PathPtrList::NodeptrItems::NodePtrList class System::ActionItems::EqptdiagruleItems : public ydk::Entity { public: EqptdiagruleItems(); ~EqptdiagruleItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class OnDRuleList; //type: System::ActionItems::EqptdiagruleItems::OnDRuleList ydk::YList ondrule_list; }; // System::ActionItems::EqptdiagruleItems class System::ActionItems::EqptdiagruleItems::OnDRuleList : public ydk::Entity { public: OnDRuleList(); ~OnDRuleList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf type; //type: uint16 ydk::YLeaf name; //type: string ydk::YLeaf ownerkey; //type: string ydk::YLeaf ownertag; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf trig; //type: TestTrig ydk::YLeaf freq; //type: one of uint64, string class SubjItems; //type: System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems> subj_items; }; // System::ActionItems::EqptdiagruleItems::OnDRuleList class System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems : public ydk::Entity { public: SubjItems(); ~SubjItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class OnDSubjList; //type: System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems::OnDSubjList ydk::YList ondsubj_list; }; // System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems class System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems::OnDSubjList : public ydk::Entity { public: OnDSubjList(); ~OnDSubjList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf odn; //type: string ydk::YLeaf adminst; //type: ActionAdminSt ydk::YLeaf opk; //type: string ydk::YLeaf osk; //type: string ydk::YLeaf operst; //type: TestOperSt ydk::YLeaf name; //type: string class RsltItems; //type: System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems::OnDSubjList::RsltItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems::OnDSubjList::RsltItems> rslt_items; }; // System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems::OnDSubjList class System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems::OnDSubjList::RsltItems : public ydk::Entity { public: RsltItems(); ~RsltItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RsltList; //type: System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems::OnDSubjList::RsltItems::RsltList ydk::YList rslt_list; }; // System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems::OnDSubjList::RsltItems class System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems::OnDSubjList::RsltItems::RsltList : public ydk::Entity { public: RsltList(); ~RsltList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf ts; //type: one of uint64, string ydk::YLeaf trig; //type: TestTrig ydk::YLeaf operst; //type: TestOperSt ydk::YLeaf qual; //type: string ydk::YLeaf name; //type: string }; // System::ActionItems::EqptdiagruleItems::OnDRuleList::SubjItems::OnDSubjList::RsltItems::RsltList class System::ActionItems::LsubjItems : public ydk::Entity { public: LsubjItems(); ~LsubjItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class LSubjList; //type: System::ActionItems::LsubjItems::LSubjList ydk::YList lsubj_list; }; // System::ActionItems::LsubjItems class System::ActionItems::LsubjItems::LSubjList : public ydk::Entity { public: LSubjList(); ~LSubjList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf odn; //type: string ydk::YLeaf ocl; //type: string class PingnveItems; //type: System::ActionItems::LsubjItems::LSubjList::PingnveItems class PingexecfabItems; //type: System::ActionItems::LsubjItems::LSubjList::PingexecfabItems class PingexectnItems; //type: System::ActionItems::LsubjItems::LSubjList::PingexectnItems class PingrsltfabItems; //type: System::ActionItems::LsubjItems::LSubjList::PingrsltfabItems class PingrslttnItems; //type: System::ActionItems::LsubjItems::LSubjList::PingrslttnItems class TrexecfabItems; //type: System::ActionItems::LsubjItems::LSubjList::TrexecfabItems class TrexectnItems; //type: System::ActionItems::LsubjItems::LSubjList::TrexectnItems class TrrsltfabItems; //type: System::ActionItems::LsubjItems::LSubjList::TrrsltfabItems class TrrslttnItems; //type: System::ActionItems::LsubjItems::LSubjList::TrrslttnItems class ImginsttaskrsltItems; //type: System::ActionItems::LsubjItems::LSubjList::ImginsttaskrsltItems class TrkipItems; //type: System::ActionItems::LsubjItems::LSubjList::TrkipItems class TrkmacItems; //type: System::ActionItems::LsubjItems::LSubjList::TrkmacItems class IprsltItems; //type: System::ActionItems::LsubjItems::LSubjList::IprsltItems class MacrsltItems; //type: System::ActionItems::LsubjItems::LSubjList::MacrsltItems class PingnversltItems; //type: System::ActionItems::LsubjItems::LSubjList::PingnversltItems class TracertnveItems; //type: System::ActionItems::LsubjItems::LSubjList::TracertnveItems class PathtracenveItems; //type: System::ActionItems::LsubjItems::LSubjList::PathtracenveItems class TrnversltItems; //type: System::ActionItems::LsubjItems::LSubjList::TrnversltItems class PtrnversltItems; //type: System::ActionItems::LsubjItems::LSubjList::PtrnversltItems class RslSubjToDomainRefItems; //type: System::ActionItems::LsubjItems::LSubjList::RslSubjToDomainRefItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::PingnveItems> pingnve_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::PingexecfabItems> pingexecfab_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::PingexectnItems> pingexectn_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::PingrsltfabItems> pingrsltfab_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::PingrslttnItems> pingrslttn_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::TrexecfabItems> trexecfab_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::TrexectnItems> trexectn_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::TrrsltfabItems> trrsltfab_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::TrrslttnItems> trrslttn_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::ImginsttaskrsltItems> imginsttaskrslt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::TrkipItems> trkip_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::TrkmacItems> trkmac_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::IprsltItems> iprslt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::MacrsltItems> macrslt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::PingnversltItems> pingnverslt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::TracertnveItems> tracertnve_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::PathtracenveItems> pathtracenve_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::TrnversltItems> trnverslt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::PtrnversltItems> ptrnverslt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::RslSubjToDomainRefItems> rslsubjtodomainref_items; }; // System::ActionItems::LsubjItems::LSubjList class System::ActionItems::LsubjItems::LSubjList::PingnveItems : public ydk::Entity { public: PingnveItems(); ~PingnveItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PingNveList; //type: System::ActionItems::LsubjItems::LSubjList::PingnveItems::PingNveList ydk::YList pingnve_list; }; // System::ActionItems::LsubjItems::LSubjList::PingnveItems class System::ActionItems::LsubjItems::LSubjList::PingnveItems::PingNveList : public ydk::Entity { public: PingNveList(); ~PingNveList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf session; //type: string ydk::YLeaf profileid; //type: uint16 ydk::YLeaf dstip; //type: string ydk::YLeaf dstipv6; //type: string ydk::YLeaf dstmac; //type: string ydk::YLeaf srcip; //type: string ydk::YLeaf srcipv6; //type: string ydk::YLeaf dot1q; //type: uint16 ydk::YLeaf srcport; //type: string ydk::YLeaf count; //type: uint16 ydk::YLeaf timeout; //type: uint8 ydk::YLeaf interval; //type: uint8 ydk::YLeaf datapattern; //type: uint16 ydk::YLeaf sweepmin; //type: uint16 ydk::YLeaf sweepmax; //type: uint16 ydk::YLeaf packetsz; //type: uint16 ydk::YLeaf vrf; //type: string ydk::YLeaf vni; //type: uint32 ydk::YLeaf egressif; //type: string ydk::YLeaf macsrcif; //type: string ydk::YLeaf operst; //type: ActionOperSt ydk::YLeaf sessionid; //type: uint32 ydk::YLeaf verifyhost; //type: boolean ydk::YLeaf payload_dot1q; //type: uint16 ydk::YLeaf payload_srcip; //type: string ydk::YLeaf payload_srcipv6; //type: string ydk::YLeaf payload_srcmac; //type: string ydk::YLeaf payload_dstip; //type: string ydk::YLeaf payload_dstipv6; //type: string ydk::YLeaf payload_dstmac; //type: string ydk::YLeaf payload_srcport; //type: uint16 ydk::YLeaf payload_dstport; //type: uint16 ydk::YLeaf payload_protocol; //type: uint16 ydk::YLeaf payload_srcif; //type: string ydk::YLeaf descr; //type: string ydk::YLeaf startts; //type: one of uint64, string ydk::YLeaf type; //type: ActionType ydk::YLeaf rsz; //type: uint16 ydk::YLeaf rtm; //type: one of uint64, string ydk::YLeaf peerclassid; //type: string ydk::YLeaf adminst; //type: ActionAdminSt ydk::YLeaf freq; //type: one of uint64, string class PingnversltItems; //type: System::ActionItems::LsubjItems::LSubjList::PingnveItems::PingNveList::PingnversltItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::ActionItems::LsubjItems::LSubjList::PingnveItems::PingNveList::PingnversltItems> pingnverslt_items; }; // System::ActionItems::LsubjItems::LSubjList::PingnveItems::PingNveList class System::ActionItems::LsubjItems::LSubjList::PingnveItems::PingNveList::PingnversltItems : public ydk::Entity { public: PingnversltItems(); ~PingnversltItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PingNveRsltList; //type: System::ActionItems::LsubjItems::LSubjList::PingnveItems::PingNveList::PingnversltItems::PingNveRsltList ydk::YList pingnverslt_list; }; // System::ActionItems::LsubjItems::LSubjList::PingnveItems::PingNveList::PingnversltItems class System::ActionItems::LsubjItems::LSubjList::PingnveItems::PingNveList::PingnversltItems::PingNveRsltList : public ydk::Entity { public: PingNveRsltList(); ~PingNveRsltList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sessionid; //type: uint16 ydk::YLeaf descr; //type: string ydk::YLeaf startts; //type: one of uint64, string ydk::YLeaf type; //type: ActionType ydk::YLeaf rsz; //type: uint16 ydk::YLeaf rtm; //type: one of uint64, string ydk::YLeaf peerclassid; //type: string ydk::YLeaf qual; //type: string ydk::YLeaf ack; //type: boolean ydk::YLeaf endts; //type: one of uint64, string ydk::YLeaf operst; //type: ActionOperSt ydk::YLeaf replyip; //type: string ydk::YLeaf replyipv6; //type: string ydk::YLeaf nodename; //type: string ydk::YLeaf errorcode; //type: string ydk::YLeaf failreason; //type: string ydk::YLeaf sport; //type: uint16 ydk::YLeaf packetsz; //type: uint16 ydk::YLeaf sentpkts; //type: uint32 ydk::YLeaf notsentpkts; //type: uint32 ydk::YLeaf rcvdpkts; //type: uint32 ydk::YLeaf minrtt; //type: uint32 ydk::YLeaf avgrtt; //type: uint32 ydk::YLeaf maxrtt; //type: uint32 ydk::YLeaf totalrtt; //type: uint32 }; // System::ActionItems::LsubjItems::LSubjList::PingnveItems::PingNveList::PingnversltItems::PingNveRsltList class System::ActionItems::LsubjItems::LSubjList::PingexecfabItems : public ydk::Entity { public: PingexecfabItems(); ~PingexecfabItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ExecFabList; //type: System::ActionItems::LsubjItems::LSubjList::PingexecfabItems::ExecFabList ydk::YList execfab_list; }; // System::ActionItems::LsubjItems::LSubjList::PingexecfabItems class System::ActionItems::LsubjItems::LSubjList::PingexecfabItems::ExecFabList : public ydk::Entity { public: ExecFabList(); ~ExecFabList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf srcnodeid; //type: uint16 ydk::YLeaf dstnodeid; //type: uint16 ydk::YLeaf descr; //type: string ydk::YLeaf startts; //type: one of uint64, string ydk::YLeaf type; //type: ActionType ydk::YLeaf rsz; //type: uint16 ydk::YLeaf rtm; //type: one of uint64, string ydk::YLeaf peerclassid; //type: string ydk::YLeaf adminst; //type: ActionAdminSt ydk::YLeaf freq; //type: one of uint64, string ydk::YLeaf ept; //type: OamEpT ydk::YLeaf vrf; //type: string ydk::YLeaf srcip; //type: string ydk::YLeaf dstip; //type: string ydk::YLeaf payloadsz; //type: uint16 ydk::YLeaf tenant; //type: string ydk::YLeaf srcmac; //type: string ydk::YLeaf dstmac; //type: string ydk::YLeaf vtep; //type: string ydk::YLeaf vtepencap; //type: string ydk::YLeaf operst; //type: ActionOperSt }; // System::ActionItems::LsubjItems::LSubjList::PingexecfabItems::ExecFabList } } #endif /* _CISCO_NX_OS_DEVICE_48_ */
54.566434
226
0.704747
[ "vector" ]
7bac75ddd90f5976636c6980d1824ca19402cc4b
4,978
cc
C++
src/Modules/Visualization/CreateTestingArrow.cc
kimjohn1/SCIRun
62ae6cb632100371831530c755ef0b133fb5c978
[ "MIT" ]
92
2015-02-09T22:42:11.000Z
2022-03-25T09:14:50.000Z
src/Modules/Visualization/CreateTestingArrow.cc
kimjohn1/SCIRun
62ae6cb632100371831530c755ef0b133fb5c978
[ "MIT" ]
1,618
2015-01-05T19:39:13.000Z
2022-03-27T20:28:45.000Z
src/Modules/Visualization/CreateTestingArrow.cc
kimjohn1/SCIRun
62ae6cb632100371831530c755ef0b133fb5c978
[ "MIT" ]
64
2015-02-20T17:51:23.000Z
2021-11-19T07:08:08.000Z
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Modules/Visualization/CreateTestingArrow.h> #include <Core/Datatypes/DenseMatrix.h> #include <Core/Datatypes/Feedback.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <Core/Datatypes/Legacy/Field/VMesh.h> #include <Core/Datatypes/Legacy/Field/VField.h> #include <Graphics/Widgets/WidgetFactory.h> #include <Graphics/Widgets/ArrowWidget.h> using namespace SCIRun; using namespace Modules::Visualization; using namespace Graphics::Datatypes; using namespace Core::Datatypes; using namespace Core::Algorithms::Visualization; using namespace Dataflow::Networks; using namespace Core::Geometry; namespace SCIRun { namespace Modules { namespace Visualization { class CreateTestingArrowImpl { public: Transform userWidgetTransform_; BBox box_initial_bounds_; BBox bbox_; Point origin_ {0,0,0}; Point currentLocation(ModuleStateHandle state) const; }; } } } ALGORITHM_PARAMETER_DEF(Visualization, XLocation); ALGORITHM_PARAMETER_DEF(Visualization, YLocation); ALGORITHM_PARAMETER_DEF(Visualization, ZLocation); MODULE_INFO_DEF(CreateTestingArrow, Visualization, SCIRun) CreateTestingArrow::CreateTestingArrow() : GeometryGeneratingModule(staticInfo_), impl_(new CreateTestingArrowImpl) { INITIALIZE_PORT(Arrow); INITIALIZE_PORT(GeneratedPoint); } void CreateTestingArrow::setStateDefaults() { auto state = get_state(); using namespace Parameters; state->setValue(XLocation, 0.0); state->setValue(YLocation, 0.0); state->setValue(ZLocation, 0.0); getOutputPort(Arrow)->connectConnectionFeedbackListener([this](const ModuleFeedback& var) { processWidgetFeedback(var); }); } void CreateTestingArrow::execute() { impl_->origin_ = impl_->currentLocation(get_state()); //std::cout << __FILE__ << __LINE__ << " " << impl_->origin_ << std::endl; CommonWidgetParameters common { 1.0, "red", impl_->origin_, {impl_->origin_, Point(impl_->origin_ + Point{1,1,1})}, 10 }; ArrowParameters arrowParams { common, impl_->origin_, Vector{1,1,1}, true, 2, 4 }; auto arrow = WidgetFactory::createArrowWidget( {*this, "testArrow1"}, arrowParams ); //std::cout << __FILE__ << __LINE__ << " " << (*(dynamic_cast<ArrowWidget*>(arrow.get())->subwidgetBegin()))->origin() << std::endl; sendOutput(Arrow, arrow); { FieldInformation fi("PointCloudMesh", 0, "double"); auto mesh = CreateMesh(fi); mesh->vmesh()->add_point(impl_->origin_); auto ofield = CreateField(fi, mesh); ofield->vfield()->resize_values(); sendOutput(GeneratedPoint, ofield); } } void CreateTestingArrow::processWidgetFeedback(const ModuleFeedback& var) { try { auto vsf = dynamic_cast<const ViewSceneFeedback&>(var); if (vsf.matchesWithModuleId(id()) && impl_->userWidgetTransform_ != vsf.transform) { adjustGeometryFromTransform(vsf.transform); enqueueExecuteAgain(false); } } catch (std::bad_cast&) { //ignore } } Point CreateTestingArrowImpl::currentLocation(ModuleStateHandle state) const { using namespace Parameters; return Point(state->getValue(XLocation).toDouble(), state->getValue(YLocation).toDouble(), state->getValue(ZLocation).toDouble()); } void CreateTestingArrow::adjustGeometryFromTransform(const Transform& transformMatrix) { impl_->origin_ = transformMatrix * impl_->origin_; auto state = get_state(); using namespace Parameters; state->setValue(XLocation, impl_->origin_.x()); state->setValue(YLocation, impl_->origin_.y()); state->setValue(ZLocation, impl_->origin_.z()); impl_->userWidgetTransform_ = transformMatrix; }
32.116129
134
0.745882
[ "mesh", "geometry", "vector", "transform" ]
7bad8c8b8ef5c5755e4e48be47bed6c6d0cf1776
3,066
cc
C++
kernel/krnl/abi/dtor.cc
foreverbell/BadAppleOS
695e4de5f41cc64e0d6a1b147ab6d84d50b91416
[ "MIT" ]
52
2015-07-11T02:35:11.000Z
2022-01-06T22:03:23.000Z
kernel/krnl/abi/dtor.cc
foreverbell/BadAppleOS
695e4de5f41cc64e0d6a1b147ab6d84d50b91416
[ "MIT" ]
null
null
null
kernel/krnl/abi/dtor.cc
foreverbell/BadAppleOS
695e4de5f41cc64e0d6a1b147ab6d84d50b91416
[ "MIT" ]
3
2018-06-10T06:52:37.000Z
2021-11-05T05:49:15.000Z
/* warning: this code is not carefully tested. */ #include <stdint.h> #include <stdio.h> #include <abi.h> #include <panic.h> #include <pair> #include <vector> #include <algorithm> using std::vector; using std::pair; using std::make_pair; using std::sort; typedef void (* fn_ptr) (void *); typedef pair<void *, int> atexit_info_t; // pobj, insert_index namespace abi { namespace { struct atexit_t { fn_ptr lpfn; vector<atexit_info_t> atexits; atexit_t *next; }; #define SLOT_SIZE 131 // prime atexit_t *slot_header[SLOT_SIZE]; size_t cur_insert_index; uint32_t hash(fn_ptr lpfn) { return uint32_t(lpfn) * uint32_t(2654435761); } /* we don't need dso_handle actually. */ int cxa_atexit(fn_ptr lpfn, void *pobj, void * /* dso_handle */) { printf("[cxa_atexit] Register lpfn = 0x%x, pobj = 0x%x\n", lpfn, pobj); uint32_t h = hash(lpfn) % SLOT_SIZE; atexit_t *patexit = slot_header[h]; while (patexit != NULL) { if (patexit->lpfn == lpfn) { break; } else { patexit = patexit->next; } } if (patexit == NULL) { patexit = new atexit_t(); patexit->lpfn = lpfn; patexit->next = slot_header[h]; slot_header[h] = patexit; } patexit->atexits.push_back(make_pair(pobj, ++cur_insert_index)); return 0; } void cxa_finalize(fn_ptr lpfn) { if (lpfn != NULL) { uint32_t h = hash(lpfn) % SLOT_SIZE; atexit_t *patexit = slot_header[h], *prev = NULL; while (patexit != NULL) { if (patexit->lpfn == lpfn) { break; } else { prev = patexit; patexit = patexit->next; } } if (patexit == NULL) { /* key lpfn is not found in the table .*/ panic::panic("[cxa_finalize] Bad function pointer."); } for (int i = int(patexit->atexits.size()) - 1; i >= 0; --i) { patexit->lpfn(patexit->atexits[i].first); } if (prev == NULL) { slot_header[h] = patexit->next; } else { prev->next = patexit->next; } delete patexit; } else { vector<pair<fn_ptr, atexit_info_t>> all; for (int i = 0; i < SLOT_SIZE; ++i) { atexit_t *p = slot_header[i]; while (p != NULL) { for (auto &item : p->atexits) { all.push_back(make_pair(p->lpfn, item)); } auto backup = p; p = p->next; delete backup; } } sort(all.begin(), all.end(), [&](const pair<fn_ptr, atexit_info_t> &a, const pair<fn_ptr, atexit_info_t> &b) -> bool { return a.second.second > b.second.second; // compared by insert order }); for (auto it = all.begin(); it != all.end(); ++it) { it->first(it->second.first); } } } } } /* abi */ /* exports go here. */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ void *__dso_handle = 0; int __cxa_atexit(fn_ptr lpfn, void *pobj, void *dso_handle) { return abi::cxa_atexit(lpfn, pobj, dso_handle); } void __cxa_finalize(fn_ptr lpfn) { abi::cxa_finalize(lpfn); } #ifdef __cplusplus } #endif /* __cplusplus */ namespace abi { void dtors(void) { __cxa_finalize(NULL); } } /* abi */
21.291667
122
0.60274
[ "vector" ]
7bb74674a1c50e26a34a1545952b94b7c8d18666
107,000
cpp
C++
openconfig/ydk/models/openconfig/openconfig_transport_line_protection.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
openconfig/ydk/models/openconfig/openconfig_transport_line_protection.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
openconfig/ydk/models/openconfig/openconfig_transport_line_protection.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "openconfig_transport_line_protection.hpp" using namespace ydk; namespace openconfig { namespace openconfig_transport_line_protection { APSPATHS::APSPATHS() : Identity("http://openconfig.net/yang/optical-transport-line-protection", "openconfig-transport-line-protection", "openconfig-transport-line-protection:APS_PATHS") { } APSPATHS::~APSPATHS() { } Aps::Aps() : aps_modules(std::make_shared<Aps::ApsModules>()) { aps_modules->parent = this; yang_name = "aps"; yang_parent_name = "openconfig-transport-line-protection"; is_top_level_class = true; has_list_ancestor = false; } Aps::~Aps() { } bool Aps::has_data() const { if (is_presence_container) return true; return (aps_modules != nullptr && aps_modules->has_data()); } bool Aps::has_operation() const { return is_set(yfilter) || (aps_modules != nullptr && aps_modules->has_operation()); } std::string Aps::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "openconfig-transport-line-protection:aps"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "aps-modules") { if(aps_modules == nullptr) { aps_modules = std::make_shared<Aps::ApsModules>(); } return aps_modules; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(aps_modules != nullptr) { _children["aps-modules"] = aps_modules; } return _children; } void Aps::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Aps::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr<ydk::Entity> Aps::clone_ptr() const { return std::make_shared<Aps>(); } std::string Aps::get_bundle_yang_models_location() const { return ydk_openconfig_models_path; } std::string Aps::get_bundle_name() const { return "openconfig"; } augment_capabilities_function Aps::get_augment_capabilities_function() const { return openconfig_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> Aps::get_namespace_identity_lookup() const { return openconfig_namespace_identity_lookup; } bool Aps::has_leaf_or_child_of_name(const std::string & name) const { if(name == "aps-modules") return true; return false; } Aps::ApsModules::ApsModules() : aps_module(this, {"name"}) { yang_name = "aps-modules"; yang_parent_name = "aps"; is_top_level_class = false; has_list_ancestor = false; } Aps::ApsModules::~ApsModules() { } bool Aps::ApsModules::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<aps_module.len(); index++) { if(aps_module[index]->has_data()) return true; } return false; } bool Aps::ApsModules::has_operation() const { for (std::size_t index=0; index<aps_module.len(); index++) { if(aps_module[index]->has_operation()) return true; } return is_set(yfilter); } std::string Aps::ApsModules::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "openconfig-transport-line-protection:aps/" << get_segment_path(); return path_buffer.str(); } std::string Aps::ApsModules::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "aps-modules"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "aps-module") { auto ent_ = std::make_shared<Aps::ApsModules::ApsModule>(); ent_->parent = this; aps_module.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : aps_module.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Aps::ApsModules::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Aps::ApsModules::set_filter(const std::string & value_path, YFilter yfilter) { } bool Aps::ApsModules::has_leaf_or_child_of_name(const std::string & name) const { if(name == "aps-module") return true; return false; } Aps::ApsModules::ApsModule::ApsModule() : name{YType::str, "name"} , config(std::make_shared<Aps::ApsModules::ApsModule::Config>()) , state(std::make_shared<Aps::ApsModules::ApsModule::State>()) , ports(std::make_shared<Aps::ApsModules::ApsModule::Ports>()) { config->parent = this; state->parent = this; ports->parent = this; yang_name = "aps-module"; yang_parent_name = "aps-modules"; is_top_level_class = false; has_list_ancestor = false; } Aps::ApsModules::ApsModule::~ApsModule() { } bool Aps::ApsModules::ApsModule::has_data() const { if (is_presence_container) return true; return name.is_set || (config != nullptr && config->has_data()) || (state != nullptr && state->has_data()) || (ports != nullptr && ports->has_data()); } bool Aps::ApsModules::ApsModule::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || (config != nullptr && config->has_operation()) || (state != nullptr && state->has_operation()) || (ports != nullptr && ports->has_operation()); } std::string Aps::ApsModules::ApsModule::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "openconfig-transport-line-protection:aps/aps-modules/" << get_segment_path(); return path_buffer.str(); } std::string Aps::ApsModules::ApsModule::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "aps-module"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "config") { if(config == nullptr) { config = std::make_shared<Aps::ApsModules::ApsModule::Config>(); } return config; } if(child_yang_name == "state") { if(state == nullptr) { state = std::make_shared<Aps::ApsModules::ApsModule::State>(); } return state; } if(child_yang_name == "ports") { if(ports == nullptr) { ports = std::make_shared<Aps::ApsModules::ApsModule::Ports>(); } return ports; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(config != nullptr) { _children["config"] = config; } if(state != nullptr) { _children["state"] = state; } if(ports != nullptr) { _children["ports"] = ports; } return _children; } void Aps::ApsModules::ApsModule::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::has_leaf_or_child_of_name(const std::string & name) const { if(name == "config" || name == "state" || name == "ports" || name == "name") return true; return false; } Aps::ApsModules::ApsModule::Config::Config() : name{YType::str, "name"}, revertive{YType::boolean, "revertive"}, primary_switch_threshold{YType::str, "primary-switch-threshold"}, primary_switch_hysteresis{YType::str, "primary-switch-hysteresis"}, secondary_switch_threshold{YType::str, "secondary-switch-threshold"}, secondary_switch_hysteresis{YType::str, "secondary-switch-hysteresis"} { yang_name = "config"; yang_parent_name = "aps-module"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Config::~Config() { } bool Aps::ApsModules::ApsModule::Config::has_data() const { if (is_presence_container) return true; return name.is_set || revertive.is_set || primary_switch_threshold.is_set || primary_switch_hysteresis.is_set || secondary_switch_threshold.is_set || secondary_switch_hysteresis.is_set; } bool Aps::ApsModules::ApsModule::Config::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || ydk::is_set(revertive.yfilter) || ydk::is_set(primary_switch_threshold.yfilter) || ydk::is_set(primary_switch_hysteresis.yfilter) || ydk::is_set(secondary_switch_threshold.yfilter) || ydk::is_set(secondary_switch_hysteresis.yfilter); } std::string Aps::ApsModules::ApsModule::Config::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "config"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Config::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); if (revertive.is_set || is_set(revertive.yfilter)) leaf_name_data.push_back(revertive.get_name_leafdata()); if (primary_switch_threshold.is_set || is_set(primary_switch_threshold.yfilter)) leaf_name_data.push_back(primary_switch_threshold.get_name_leafdata()); if (primary_switch_hysteresis.is_set || is_set(primary_switch_hysteresis.yfilter)) leaf_name_data.push_back(primary_switch_hysteresis.get_name_leafdata()); if (secondary_switch_threshold.is_set || is_set(secondary_switch_threshold.yfilter)) leaf_name_data.push_back(secondary_switch_threshold.get_name_leafdata()); if (secondary_switch_hysteresis.is_set || is_set(secondary_switch_hysteresis.yfilter)) leaf_name_data.push_back(secondary_switch_hysteresis.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Config::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Config::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Config::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } if(value_path == "revertive") { revertive = value; revertive.value_namespace = name_space; revertive.value_namespace_prefix = name_space_prefix; } if(value_path == "primary-switch-threshold") { primary_switch_threshold = value; primary_switch_threshold.value_namespace = name_space; primary_switch_threshold.value_namespace_prefix = name_space_prefix; } if(value_path == "primary-switch-hysteresis") { primary_switch_hysteresis = value; primary_switch_hysteresis.value_namespace = name_space; primary_switch_hysteresis.value_namespace_prefix = name_space_prefix; } if(value_path == "secondary-switch-threshold") { secondary_switch_threshold = value; secondary_switch_threshold.value_namespace = name_space; secondary_switch_threshold.value_namespace_prefix = name_space_prefix; } if(value_path == "secondary-switch-hysteresis") { secondary_switch_hysteresis = value; secondary_switch_hysteresis.value_namespace = name_space; secondary_switch_hysteresis.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Config::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } if(value_path == "revertive") { revertive.yfilter = yfilter; } if(value_path == "primary-switch-threshold") { primary_switch_threshold.yfilter = yfilter; } if(value_path == "primary-switch-hysteresis") { primary_switch_hysteresis.yfilter = yfilter; } if(value_path == "secondary-switch-threshold") { secondary_switch_threshold.yfilter = yfilter; } if(value_path == "secondary-switch-hysteresis") { secondary_switch_hysteresis.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Config::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name" || name == "revertive" || name == "primary-switch-threshold" || name == "primary-switch-hysteresis" || name == "secondary-switch-threshold" || name == "secondary-switch-hysteresis") return true; return false; } Aps::ApsModules::ApsModule::State::State() : name{YType::str, "name"}, revertive{YType::boolean, "revertive"}, primary_switch_threshold{YType::str, "primary-switch-threshold"}, primary_switch_hysteresis{YType::str, "primary-switch-hysteresis"}, secondary_switch_threshold{YType::str, "secondary-switch-threshold"}, secondary_switch_hysteresis{YType::str, "secondary-switch-hysteresis"}, active_path{YType::identityref, "active-path"} { yang_name = "state"; yang_parent_name = "aps-module"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::State::~State() { } bool Aps::ApsModules::ApsModule::State::has_data() const { if (is_presence_container) return true; return name.is_set || revertive.is_set || primary_switch_threshold.is_set || primary_switch_hysteresis.is_set || secondary_switch_threshold.is_set || secondary_switch_hysteresis.is_set || active_path.is_set; } bool Aps::ApsModules::ApsModule::State::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || ydk::is_set(revertive.yfilter) || ydk::is_set(primary_switch_threshold.yfilter) || ydk::is_set(primary_switch_hysteresis.yfilter) || ydk::is_set(secondary_switch_threshold.yfilter) || ydk::is_set(secondary_switch_hysteresis.yfilter) || ydk::is_set(active_path.yfilter); } std::string Aps::ApsModules::ApsModule::State::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "state"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::State::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); if (revertive.is_set || is_set(revertive.yfilter)) leaf_name_data.push_back(revertive.get_name_leafdata()); if (primary_switch_threshold.is_set || is_set(primary_switch_threshold.yfilter)) leaf_name_data.push_back(primary_switch_threshold.get_name_leafdata()); if (primary_switch_hysteresis.is_set || is_set(primary_switch_hysteresis.yfilter)) leaf_name_data.push_back(primary_switch_hysteresis.get_name_leafdata()); if (secondary_switch_threshold.is_set || is_set(secondary_switch_threshold.yfilter)) leaf_name_data.push_back(secondary_switch_threshold.get_name_leafdata()); if (secondary_switch_hysteresis.is_set || is_set(secondary_switch_hysteresis.yfilter)) leaf_name_data.push_back(secondary_switch_hysteresis.get_name_leafdata()); if (active_path.is_set || is_set(active_path.yfilter)) leaf_name_data.push_back(active_path.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::State::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } if(value_path == "revertive") { revertive = value; revertive.value_namespace = name_space; revertive.value_namespace_prefix = name_space_prefix; } if(value_path == "primary-switch-threshold") { primary_switch_threshold = value; primary_switch_threshold.value_namespace = name_space; primary_switch_threshold.value_namespace_prefix = name_space_prefix; } if(value_path == "primary-switch-hysteresis") { primary_switch_hysteresis = value; primary_switch_hysteresis.value_namespace = name_space; primary_switch_hysteresis.value_namespace_prefix = name_space_prefix; } if(value_path == "secondary-switch-threshold") { secondary_switch_threshold = value; secondary_switch_threshold.value_namespace = name_space; secondary_switch_threshold.value_namespace_prefix = name_space_prefix; } if(value_path == "secondary-switch-hysteresis") { secondary_switch_hysteresis = value; secondary_switch_hysteresis.value_namespace = name_space; secondary_switch_hysteresis.value_namespace_prefix = name_space_prefix; } if(value_path == "active-path") { active_path = value; active_path.value_namespace = name_space; active_path.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::State::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } if(value_path == "revertive") { revertive.yfilter = yfilter; } if(value_path == "primary-switch-threshold") { primary_switch_threshold.yfilter = yfilter; } if(value_path == "primary-switch-hysteresis") { primary_switch_hysteresis.yfilter = yfilter; } if(value_path == "secondary-switch-threshold") { secondary_switch_threshold.yfilter = yfilter; } if(value_path == "secondary-switch-hysteresis") { secondary_switch_hysteresis.yfilter = yfilter; } if(value_path == "active-path") { active_path.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::State::has_leaf_or_child_of_name(const std::string & name) const { if(name == "name" || name == "revertive" || name == "primary-switch-threshold" || name == "primary-switch-hysteresis" || name == "secondary-switch-threshold" || name == "secondary-switch-hysteresis" || name == "active-path") return true; return false; } Aps::ApsModules::ApsModule::Ports::Ports() : line_primary_in(std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryIn>()) , line_primary_out(std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryOut>()) , line_secondary_in(std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryIn>()) , line_secondary_out(std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryOut>()) , common_in(std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonIn>()) , common_output(std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonOutput>()) { line_primary_in->parent = this; line_primary_out->parent = this; line_secondary_in->parent = this; line_secondary_out->parent = this; common_in->parent = this; common_output->parent = this; yang_name = "ports"; yang_parent_name = "aps-module"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::~Ports() { } bool Aps::ApsModules::ApsModule::Ports::has_data() const { if (is_presence_container) return true; return (line_primary_in != nullptr && line_primary_in->has_data()) || (line_primary_out != nullptr && line_primary_out->has_data()) || (line_secondary_in != nullptr && line_secondary_in->has_data()) || (line_secondary_out != nullptr && line_secondary_out->has_data()) || (common_in != nullptr && common_in->has_data()) || (common_output != nullptr && common_output->has_data()); } bool Aps::ApsModules::ApsModule::Ports::has_operation() const { return is_set(yfilter) || (line_primary_in != nullptr && line_primary_in->has_operation()) || (line_primary_out != nullptr && line_primary_out->has_operation()) || (line_secondary_in != nullptr && line_secondary_in->has_operation()) || (line_secondary_out != nullptr && line_secondary_out->has_operation()) || (common_in != nullptr && common_in->has_operation()) || (common_output != nullptr && common_output->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ports"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "line-primary-in") { if(line_primary_in == nullptr) { line_primary_in = std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryIn>(); } return line_primary_in; } if(child_yang_name == "line-primary-out") { if(line_primary_out == nullptr) { line_primary_out = std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryOut>(); } return line_primary_out; } if(child_yang_name == "line-secondary-in") { if(line_secondary_in == nullptr) { line_secondary_in = std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryIn>(); } return line_secondary_in; } if(child_yang_name == "line-secondary-out") { if(line_secondary_out == nullptr) { line_secondary_out = std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryOut>(); } return line_secondary_out; } if(child_yang_name == "common-in") { if(common_in == nullptr) { common_in = std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonIn>(); } return common_in; } if(child_yang_name == "common-output") { if(common_output == nullptr) { common_output = std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonOutput>(); } return common_output; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(line_primary_in != nullptr) { _children["line-primary-in"] = line_primary_in; } if(line_primary_out != nullptr) { _children["line-primary-out"] = line_primary_out; } if(line_secondary_in != nullptr) { _children["line-secondary-in"] = line_secondary_in; } if(line_secondary_out != nullptr) { _children["line-secondary-out"] = line_secondary_out; } if(common_in != nullptr) { _children["common-in"] = common_in; } if(common_output != nullptr) { _children["common-output"] = common_output; } return _children; } void Aps::ApsModules::ApsModule::Ports::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Aps::ApsModules::ApsModule::Ports::set_filter(const std::string & value_path, YFilter yfilter) { } bool Aps::ApsModules::ApsModule::Ports::has_leaf_or_child_of_name(const std::string & name) const { if(name == "line-primary-in" || name == "line-primary-out" || name == "line-secondary-in" || name == "line-secondary-out" || name == "common-in" || name == "common-output") return true; return false; } Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::LinePrimaryIn() : config(std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config>()) , state(std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State>()) { config->parent = this; state->parent = this; yang_name = "line-primary-in"; yang_parent_name = "ports"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::~LinePrimaryIn() { } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::has_data() const { if (is_presence_container) return true; return (config != nullptr && config->has_data()) || (state != nullptr && state->has_data()); } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::has_operation() const { return is_set(yfilter) || (config != nullptr && config->has_operation()) || (state != nullptr && state->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "line-primary-in"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "config") { if(config == nullptr) { config = std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config>(); } return config; } if(child_yang_name == "state") { if(state == nullptr) { state = std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State>(); } return state; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(config != nullptr) { _children["config"] = config; } if(state != nullptr) { _children["state"] = state; } return _children; } void Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::set_filter(const std::string & value_path, YFilter yfilter) { } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::has_leaf_or_child_of_name(const std::string & name) const { if(name == "config" || name == "state") return true; return false; } Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::Config() : enabled{YType::boolean, "enabled"}, target_attenuation{YType::str, "target-attenuation"} { yang_name = "config"; yang_parent_name = "line-primary-in"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::~Config() { } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::has_data() const { if (is_presence_container) return true; return enabled.is_set || target_attenuation.is_set; } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::has_operation() const { return is_set(yfilter) || ydk::is_set(enabled.yfilter) || ydk::is_set(target_attenuation.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "config"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enabled.is_set || is_set(enabled.yfilter)) leaf_name_data.push_back(enabled.get_name_leafdata()); if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enabled") { enabled = value; enabled.value_namespace = name_space; enabled.value_namespace_prefix = name_space_prefix; } if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enabled") { enabled.yfilter = yfilter; } if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::Config::has_leaf_or_child_of_name(const std::string & name) const { if(name == "enabled" || name == "target-attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::State() : enabled{YType::boolean, "enabled"}, target_attenuation{YType::str, "target-attenuation"}, attenuation{YType::str, "attenuation"} , optical_power(std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower>()) { optical_power->parent = this; yang_name = "state"; yang_parent_name = "line-primary-in"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::~State() { } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::has_data() const { if (is_presence_container) return true; return enabled.is_set || target_attenuation.is_set || attenuation.is_set || (optical_power != nullptr && optical_power->has_data()); } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::has_operation() const { return is_set(yfilter) || ydk::is_set(enabled.yfilter) || ydk::is_set(target_attenuation.yfilter) || ydk::is_set(attenuation.yfilter) || (optical_power != nullptr && optical_power->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "state"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enabled.is_set || is_set(enabled.yfilter)) leaf_name_data.push_back(enabled.get_name_leafdata()); if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); if (attenuation.is_set || is_set(attenuation.yfilter)) leaf_name_data.push_back(attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "optical-power") { if(optical_power == nullptr) { optical_power = std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower>(); } return optical_power; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(optical_power != nullptr) { _children["optical-power"] = optical_power; } return _children; } void Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enabled") { enabled = value; enabled.value_namespace = name_space; enabled.value_namespace_prefix = name_space_prefix; } if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } if(value_path == "attenuation") { attenuation = value; attenuation.value_namespace = name_space; attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enabled") { enabled.yfilter = yfilter; } if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } if(value_path == "attenuation") { attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::has_leaf_or_child_of_name(const std::string & name) const { if(name == "optical-power" || name == "enabled" || name == "target-attenuation" || name == "attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::OpticalPower() : instant{YType::str, "instant"}, avg{YType::str, "avg"}, min{YType::str, "min"}, max{YType::str, "max"} { yang_name = "optical-power"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::~OpticalPower() { } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::has_data() const { if (is_presence_container) return true; return instant.is_set || avg.is_set || min.is_set || max.is_set; } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::has_operation() const { return is_set(yfilter) || ydk::is_set(instant.yfilter) || ydk::is_set(avg.yfilter) || ydk::is_set(min.yfilter) || ydk::is_set(max.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "optical-power"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (instant.is_set || is_set(instant.yfilter)) leaf_name_data.push_back(instant.get_name_leafdata()); if (avg.is_set || is_set(avg.yfilter)) leaf_name_data.push_back(avg.get_name_leafdata()); if (min.is_set || is_set(min.yfilter)) leaf_name_data.push_back(min.get_name_leafdata()); if (max.is_set || is_set(max.yfilter)) leaf_name_data.push_back(max.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "instant") { instant = value; instant.value_namespace = name_space; instant.value_namespace_prefix = name_space_prefix; } if(value_path == "avg") { avg = value; avg.value_namespace = name_space; avg.value_namespace_prefix = name_space_prefix; } if(value_path == "min") { min = value; min.value_namespace = name_space; min.value_namespace_prefix = name_space_prefix; } if(value_path == "max") { max = value; max.value_namespace = name_space; max.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "instant") { instant.yfilter = yfilter; } if(value_path == "avg") { avg.yfilter = yfilter; } if(value_path == "min") { min.yfilter = yfilter; } if(value_path == "max") { max.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryIn::State::OpticalPower::has_leaf_or_child_of_name(const std::string & name) const { if(name == "instant" || name == "avg" || name == "min" || name == "max") return true; return false; } Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::LinePrimaryOut() : config(std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config>()) , state(std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State>()) { config->parent = this; state->parent = this; yang_name = "line-primary-out"; yang_parent_name = "ports"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::~LinePrimaryOut() { } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::has_data() const { if (is_presence_container) return true; return (config != nullptr && config->has_data()) || (state != nullptr && state->has_data()); } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::has_operation() const { return is_set(yfilter) || (config != nullptr && config->has_operation()) || (state != nullptr && state->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "line-primary-out"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "config") { if(config == nullptr) { config = std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config>(); } return config; } if(child_yang_name == "state") { if(state == nullptr) { state = std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State>(); } return state; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(config != nullptr) { _children["config"] = config; } if(state != nullptr) { _children["state"] = state; } return _children; } void Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::set_filter(const std::string & value_path, YFilter yfilter) { } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::has_leaf_or_child_of_name(const std::string & name) const { if(name == "config" || name == "state") return true; return false; } Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::Config() : target_attenuation{YType::str, "target-attenuation"} { yang_name = "config"; yang_parent_name = "line-primary-out"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::~Config() { } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::has_data() const { if (is_presence_container) return true; return target_attenuation.is_set; } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::has_operation() const { return is_set(yfilter) || ydk::is_set(target_attenuation.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "config"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::Config::has_leaf_or_child_of_name(const std::string & name) const { if(name == "target-attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::State() : target_attenuation{YType::str, "target-attenuation"}, attenuation{YType::str, "attenuation"} , optical_power(std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower>()) { optical_power->parent = this; yang_name = "state"; yang_parent_name = "line-primary-out"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::~State() { } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::has_data() const { if (is_presence_container) return true; return target_attenuation.is_set || attenuation.is_set || (optical_power != nullptr && optical_power->has_data()); } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::has_operation() const { return is_set(yfilter) || ydk::is_set(target_attenuation.yfilter) || ydk::is_set(attenuation.yfilter) || (optical_power != nullptr && optical_power->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "state"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); if (attenuation.is_set || is_set(attenuation.yfilter)) leaf_name_data.push_back(attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "optical-power") { if(optical_power == nullptr) { optical_power = std::make_shared<Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower>(); } return optical_power; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(optical_power != nullptr) { _children["optical-power"] = optical_power; } return _children; } void Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } if(value_path == "attenuation") { attenuation = value; attenuation.value_namespace = name_space; attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } if(value_path == "attenuation") { attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::has_leaf_or_child_of_name(const std::string & name) const { if(name == "optical-power" || name == "target-attenuation" || name == "attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::OpticalPower() : instant{YType::str, "instant"}, avg{YType::str, "avg"}, min{YType::str, "min"}, max{YType::str, "max"} { yang_name = "optical-power"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::~OpticalPower() { } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::has_data() const { if (is_presence_container) return true; return instant.is_set || avg.is_set || min.is_set || max.is_set; } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::has_operation() const { return is_set(yfilter) || ydk::is_set(instant.yfilter) || ydk::is_set(avg.yfilter) || ydk::is_set(min.yfilter) || ydk::is_set(max.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "optical-power"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (instant.is_set || is_set(instant.yfilter)) leaf_name_data.push_back(instant.get_name_leafdata()); if (avg.is_set || is_set(avg.yfilter)) leaf_name_data.push_back(avg.get_name_leafdata()); if (min.is_set || is_set(min.yfilter)) leaf_name_data.push_back(min.get_name_leafdata()); if (max.is_set || is_set(max.yfilter)) leaf_name_data.push_back(max.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "instant") { instant = value; instant.value_namespace = name_space; instant.value_namespace_prefix = name_space_prefix; } if(value_path == "avg") { avg = value; avg.value_namespace = name_space; avg.value_namespace_prefix = name_space_prefix; } if(value_path == "min") { min = value; min.value_namespace = name_space; min.value_namespace_prefix = name_space_prefix; } if(value_path == "max") { max = value; max.value_namespace = name_space; max.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "instant") { instant.yfilter = yfilter; } if(value_path == "avg") { avg.yfilter = yfilter; } if(value_path == "min") { min.yfilter = yfilter; } if(value_path == "max") { max.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LinePrimaryOut::State::OpticalPower::has_leaf_or_child_of_name(const std::string & name) const { if(name == "instant" || name == "avg" || name == "min" || name == "max") return true; return false; } Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::LineSecondaryIn() : config(std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config>()) , state(std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State>()) { config->parent = this; state->parent = this; yang_name = "line-secondary-in"; yang_parent_name = "ports"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::~LineSecondaryIn() { } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::has_data() const { if (is_presence_container) return true; return (config != nullptr && config->has_data()) || (state != nullptr && state->has_data()); } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::has_operation() const { return is_set(yfilter) || (config != nullptr && config->has_operation()) || (state != nullptr && state->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "line-secondary-in"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "config") { if(config == nullptr) { config = std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config>(); } return config; } if(child_yang_name == "state") { if(state == nullptr) { state = std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State>(); } return state; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(config != nullptr) { _children["config"] = config; } if(state != nullptr) { _children["state"] = state; } return _children; } void Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::set_filter(const std::string & value_path, YFilter yfilter) { } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::has_leaf_or_child_of_name(const std::string & name) const { if(name == "config" || name == "state") return true; return false; } Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::Config() : enabled{YType::boolean, "enabled"}, target_attenuation{YType::str, "target-attenuation"} { yang_name = "config"; yang_parent_name = "line-secondary-in"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::~Config() { } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::has_data() const { if (is_presence_container) return true; return enabled.is_set || target_attenuation.is_set; } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::has_operation() const { return is_set(yfilter) || ydk::is_set(enabled.yfilter) || ydk::is_set(target_attenuation.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "config"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enabled.is_set || is_set(enabled.yfilter)) leaf_name_data.push_back(enabled.get_name_leafdata()); if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enabled") { enabled = value; enabled.value_namespace = name_space; enabled.value_namespace_prefix = name_space_prefix; } if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enabled") { enabled.yfilter = yfilter; } if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::Config::has_leaf_or_child_of_name(const std::string & name) const { if(name == "enabled" || name == "target-attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::State() : enabled{YType::boolean, "enabled"}, target_attenuation{YType::str, "target-attenuation"}, attenuation{YType::str, "attenuation"} , optical_power(std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower>()) { optical_power->parent = this; yang_name = "state"; yang_parent_name = "line-secondary-in"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::~State() { } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::has_data() const { if (is_presence_container) return true; return enabled.is_set || target_attenuation.is_set || attenuation.is_set || (optical_power != nullptr && optical_power->has_data()); } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::has_operation() const { return is_set(yfilter) || ydk::is_set(enabled.yfilter) || ydk::is_set(target_attenuation.yfilter) || ydk::is_set(attenuation.yfilter) || (optical_power != nullptr && optical_power->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "state"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enabled.is_set || is_set(enabled.yfilter)) leaf_name_data.push_back(enabled.get_name_leafdata()); if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); if (attenuation.is_set || is_set(attenuation.yfilter)) leaf_name_data.push_back(attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "optical-power") { if(optical_power == nullptr) { optical_power = std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower>(); } return optical_power; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(optical_power != nullptr) { _children["optical-power"] = optical_power; } return _children; } void Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enabled") { enabled = value; enabled.value_namespace = name_space; enabled.value_namespace_prefix = name_space_prefix; } if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } if(value_path == "attenuation") { attenuation = value; attenuation.value_namespace = name_space; attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enabled") { enabled.yfilter = yfilter; } if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } if(value_path == "attenuation") { attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::has_leaf_or_child_of_name(const std::string & name) const { if(name == "optical-power" || name == "enabled" || name == "target-attenuation" || name == "attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::OpticalPower() : instant{YType::str, "instant"}, avg{YType::str, "avg"}, min{YType::str, "min"}, max{YType::str, "max"} { yang_name = "optical-power"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::~OpticalPower() { } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::has_data() const { if (is_presence_container) return true; return instant.is_set || avg.is_set || min.is_set || max.is_set; } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::has_operation() const { return is_set(yfilter) || ydk::is_set(instant.yfilter) || ydk::is_set(avg.yfilter) || ydk::is_set(min.yfilter) || ydk::is_set(max.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "optical-power"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (instant.is_set || is_set(instant.yfilter)) leaf_name_data.push_back(instant.get_name_leafdata()); if (avg.is_set || is_set(avg.yfilter)) leaf_name_data.push_back(avg.get_name_leafdata()); if (min.is_set || is_set(min.yfilter)) leaf_name_data.push_back(min.get_name_leafdata()); if (max.is_set || is_set(max.yfilter)) leaf_name_data.push_back(max.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "instant") { instant = value; instant.value_namespace = name_space; instant.value_namespace_prefix = name_space_prefix; } if(value_path == "avg") { avg = value; avg.value_namespace = name_space; avg.value_namespace_prefix = name_space_prefix; } if(value_path == "min") { min = value; min.value_namespace = name_space; min.value_namespace_prefix = name_space_prefix; } if(value_path == "max") { max = value; max.value_namespace = name_space; max.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "instant") { instant.yfilter = yfilter; } if(value_path == "avg") { avg.yfilter = yfilter; } if(value_path == "min") { min.yfilter = yfilter; } if(value_path == "max") { max.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryIn::State::OpticalPower::has_leaf_or_child_of_name(const std::string & name) const { if(name == "instant" || name == "avg" || name == "min" || name == "max") return true; return false; } Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::LineSecondaryOut() : config(std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config>()) , state(std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State>()) { config->parent = this; state->parent = this; yang_name = "line-secondary-out"; yang_parent_name = "ports"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::~LineSecondaryOut() { } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::has_data() const { if (is_presence_container) return true; return (config != nullptr && config->has_data()) || (state != nullptr && state->has_data()); } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::has_operation() const { return is_set(yfilter) || (config != nullptr && config->has_operation()) || (state != nullptr && state->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "line-secondary-out"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "config") { if(config == nullptr) { config = std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config>(); } return config; } if(child_yang_name == "state") { if(state == nullptr) { state = std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State>(); } return state; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(config != nullptr) { _children["config"] = config; } if(state != nullptr) { _children["state"] = state; } return _children; } void Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::set_filter(const std::string & value_path, YFilter yfilter) { } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::has_leaf_or_child_of_name(const std::string & name) const { if(name == "config" || name == "state") return true; return false; } Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::Config() : target_attenuation{YType::str, "target-attenuation"} { yang_name = "config"; yang_parent_name = "line-secondary-out"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::~Config() { } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::has_data() const { if (is_presence_container) return true; return target_attenuation.is_set; } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::has_operation() const { return is_set(yfilter) || ydk::is_set(target_attenuation.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "config"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::Config::has_leaf_or_child_of_name(const std::string & name) const { if(name == "target-attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::State() : target_attenuation{YType::str, "target-attenuation"}, attenuation{YType::str, "attenuation"} , optical_power(std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower>()) { optical_power->parent = this; yang_name = "state"; yang_parent_name = "line-secondary-out"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::~State() { } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::has_data() const { if (is_presence_container) return true; return target_attenuation.is_set || attenuation.is_set || (optical_power != nullptr && optical_power->has_data()); } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::has_operation() const { return is_set(yfilter) || ydk::is_set(target_attenuation.yfilter) || ydk::is_set(attenuation.yfilter) || (optical_power != nullptr && optical_power->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "state"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); if (attenuation.is_set || is_set(attenuation.yfilter)) leaf_name_data.push_back(attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "optical-power") { if(optical_power == nullptr) { optical_power = std::make_shared<Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower>(); } return optical_power; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(optical_power != nullptr) { _children["optical-power"] = optical_power; } return _children; } void Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } if(value_path == "attenuation") { attenuation = value; attenuation.value_namespace = name_space; attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } if(value_path == "attenuation") { attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::has_leaf_or_child_of_name(const std::string & name) const { if(name == "optical-power" || name == "target-attenuation" || name == "attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::OpticalPower() : instant{YType::str, "instant"}, avg{YType::str, "avg"}, min{YType::str, "min"}, max{YType::str, "max"} { yang_name = "optical-power"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::~OpticalPower() { } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::has_data() const { if (is_presence_container) return true; return instant.is_set || avg.is_set || min.is_set || max.is_set; } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::has_operation() const { return is_set(yfilter) || ydk::is_set(instant.yfilter) || ydk::is_set(avg.yfilter) || ydk::is_set(min.yfilter) || ydk::is_set(max.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "optical-power"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (instant.is_set || is_set(instant.yfilter)) leaf_name_data.push_back(instant.get_name_leafdata()); if (avg.is_set || is_set(avg.yfilter)) leaf_name_data.push_back(avg.get_name_leafdata()); if (min.is_set || is_set(min.yfilter)) leaf_name_data.push_back(min.get_name_leafdata()); if (max.is_set || is_set(max.yfilter)) leaf_name_data.push_back(max.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "instant") { instant = value; instant.value_namespace = name_space; instant.value_namespace_prefix = name_space_prefix; } if(value_path == "avg") { avg = value; avg.value_namespace = name_space; avg.value_namespace_prefix = name_space_prefix; } if(value_path == "min") { min = value; min.value_namespace = name_space; min.value_namespace_prefix = name_space_prefix; } if(value_path == "max") { max = value; max.value_namespace = name_space; max.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "instant") { instant.yfilter = yfilter; } if(value_path == "avg") { avg.yfilter = yfilter; } if(value_path == "min") { min.yfilter = yfilter; } if(value_path == "max") { max.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::LineSecondaryOut::State::OpticalPower::has_leaf_or_child_of_name(const std::string & name) const { if(name == "instant" || name == "avg" || name == "min" || name == "max") return true; return false; } Aps::ApsModules::ApsModule::Ports::CommonIn::CommonIn() : config(std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonIn::Config>()) , state(std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonIn::State>()) { config->parent = this; state->parent = this; yang_name = "common-in"; yang_parent_name = "ports"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::CommonIn::~CommonIn() { } bool Aps::ApsModules::ApsModule::Ports::CommonIn::has_data() const { if (is_presence_container) return true; return (config != nullptr && config->has_data()) || (state != nullptr && state->has_data()); } bool Aps::ApsModules::ApsModule::Ports::CommonIn::has_operation() const { return is_set(yfilter) || (config != nullptr && config->has_operation()) || (state != nullptr && state->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::CommonIn::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "common-in"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::CommonIn::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::CommonIn::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "config") { if(config == nullptr) { config = std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonIn::Config>(); } return config; } if(child_yang_name == "state") { if(state == nullptr) { state = std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonIn::State>(); } return state; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::CommonIn::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(config != nullptr) { _children["config"] = config; } if(state != nullptr) { _children["state"] = state; } return _children; } void Aps::ApsModules::ApsModule::Ports::CommonIn::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Aps::ApsModules::ApsModule::Ports::CommonIn::set_filter(const std::string & value_path, YFilter yfilter) { } bool Aps::ApsModules::ApsModule::Ports::CommonIn::has_leaf_or_child_of_name(const std::string & name) const { if(name == "config" || name == "state") return true; return false; } Aps::ApsModules::ApsModule::Ports::CommonIn::Config::Config() : enabled{YType::boolean, "enabled"}, target_attenuation{YType::str, "target-attenuation"} { yang_name = "config"; yang_parent_name = "common-in"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::CommonIn::Config::~Config() { } bool Aps::ApsModules::ApsModule::Ports::CommonIn::Config::has_data() const { if (is_presence_container) return true; return enabled.is_set || target_attenuation.is_set; } bool Aps::ApsModules::ApsModule::Ports::CommonIn::Config::has_operation() const { return is_set(yfilter) || ydk::is_set(enabled.yfilter) || ydk::is_set(target_attenuation.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::CommonIn::Config::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "config"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::CommonIn::Config::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enabled.is_set || is_set(enabled.yfilter)) leaf_name_data.push_back(enabled.get_name_leafdata()); if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::CommonIn::Config::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::CommonIn::Config::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::CommonIn::Config::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enabled") { enabled = value; enabled.value_namespace = name_space; enabled.value_namespace_prefix = name_space_prefix; } if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::CommonIn::Config::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enabled") { enabled.yfilter = yfilter; } if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::CommonIn::Config::has_leaf_or_child_of_name(const std::string & name) const { if(name == "enabled" || name == "target-attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::CommonIn::State::State() : enabled{YType::boolean, "enabled"}, target_attenuation{YType::str, "target-attenuation"}, attenuation{YType::str, "attenuation"} , optical_power(std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower>()) { optical_power->parent = this; yang_name = "state"; yang_parent_name = "common-in"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::CommonIn::State::~State() { } bool Aps::ApsModules::ApsModule::Ports::CommonIn::State::has_data() const { if (is_presence_container) return true; return enabled.is_set || target_attenuation.is_set || attenuation.is_set || (optical_power != nullptr && optical_power->has_data()); } bool Aps::ApsModules::ApsModule::Ports::CommonIn::State::has_operation() const { return is_set(yfilter) || ydk::is_set(enabled.yfilter) || ydk::is_set(target_attenuation.yfilter) || ydk::is_set(attenuation.yfilter) || (optical_power != nullptr && optical_power->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::CommonIn::State::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "state"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::CommonIn::State::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enabled.is_set || is_set(enabled.yfilter)) leaf_name_data.push_back(enabled.get_name_leafdata()); if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); if (attenuation.is_set || is_set(attenuation.yfilter)) leaf_name_data.push_back(attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::CommonIn::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "optical-power") { if(optical_power == nullptr) { optical_power = std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower>(); } return optical_power; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::CommonIn::State::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(optical_power != nullptr) { _children["optical-power"] = optical_power; } return _children; } void Aps::ApsModules::ApsModule::Ports::CommonIn::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enabled") { enabled = value; enabled.value_namespace = name_space; enabled.value_namespace_prefix = name_space_prefix; } if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } if(value_path == "attenuation") { attenuation = value; attenuation.value_namespace = name_space; attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::CommonIn::State::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enabled") { enabled.yfilter = yfilter; } if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } if(value_path == "attenuation") { attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::CommonIn::State::has_leaf_or_child_of_name(const std::string & name) const { if(name == "optical-power" || name == "enabled" || name == "target-attenuation" || name == "attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::OpticalPower() : instant{YType::str, "instant"}, avg{YType::str, "avg"}, min{YType::str, "min"}, max{YType::str, "max"} { yang_name = "optical-power"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::~OpticalPower() { } bool Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::has_data() const { if (is_presence_container) return true; return instant.is_set || avg.is_set || min.is_set || max.is_set; } bool Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::has_operation() const { return is_set(yfilter) || ydk::is_set(instant.yfilter) || ydk::is_set(avg.yfilter) || ydk::is_set(min.yfilter) || ydk::is_set(max.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "optical-power"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (instant.is_set || is_set(instant.yfilter)) leaf_name_data.push_back(instant.get_name_leafdata()); if (avg.is_set || is_set(avg.yfilter)) leaf_name_data.push_back(avg.get_name_leafdata()); if (min.is_set || is_set(min.yfilter)) leaf_name_data.push_back(min.get_name_leafdata()); if (max.is_set || is_set(max.yfilter)) leaf_name_data.push_back(max.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "instant") { instant = value; instant.value_namespace = name_space; instant.value_namespace_prefix = name_space_prefix; } if(value_path == "avg") { avg = value; avg.value_namespace = name_space; avg.value_namespace_prefix = name_space_prefix; } if(value_path == "min") { min = value; min.value_namespace = name_space; min.value_namespace_prefix = name_space_prefix; } if(value_path == "max") { max = value; max.value_namespace = name_space; max.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "instant") { instant.yfilter = yfilter; } if(value_path == "avg") { avg.yfilter = yfilter; } if(value_path == "min") { min.yfilter = yfilter; } if(value_path == "max") { max.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::CommonIn::State::OpticalPower::has_leaf_or_child_of_name(const std::string & name) const { if(name == "instant" || name == "avg" || name == "min" || name == "max") return true; return false; } Aps::ApsModules::ApsModule::Ports::CommonOutput::CommonOutput() : config(std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonOutput::Config>()) , state(std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonOutput::State>()) { config->parent = this; state->parent = this; yang_name = "common-output"; yang_parent_name = "ports"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::CommonOutput::~CommonOutput() { } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::has_data() const { if (is_presence_container) return true; return (config != nullptr && config->has_data()) || (state != nullptr && state->has_data()); } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::has_operation() const { return is_set(yfilter) || (config != nullptr && config->has_operation()) || (state != nullptr && state->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::CommonOutput::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "common-output"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::CommonOutput::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::CommonOutput::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "config") { if(config == nullptr) { config = std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonOutput::Config>(); } return config; } if(child_yang_name == "state") { if(state == nullptr) { state = std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonOutput::State>(); } return state; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::CommonOutput::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(config != nullptr) { _children["config"] = config; } if(state != nullptr) { _children["state"] = state; } return _children; } void Aps::ApsModules::ApsModule::Ports::CommonOutput::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Aps::ApsModules::ApsModule::Ports::CommonOutput::set_filter(const std::string & value_path, YFilter yfilter) { } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::has_leaf_or_child_of_name(const std::string & name) const { if(name == "config" || name == "state") return true; return false; } Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::Config() : target_attenuation{YType::str, "target-attenuation"} { yang_name = "config"; yang_parent_name = "common-output"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::~Config() { } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::has_data() const { if (is_presence_container) return true; return target_attenuation.is_set; } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::has_operation() const { return is_set(yfilter) || ydk::is_set(target_attenuation.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "config"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::Config::has_leaf_or_child_of_name(const std::string & name) const { if(name == "target-attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::CommonOutput::State::State() : target_attenuation{YType::str, "target-attenuation"}, attenuation{YType::str, "attenuation"} , optical_power(std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower>()) { optical_power->parent = this; yang_name = "state"; yang_parent_name = "common-output"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::CommonOutput::State::~State() { } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::State::has_data() const { if (is_presence_container) return true; return target_attenuation.is_set || attenuation.is_set || (optical_power != nullptr && optical_power->has_data()); } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::State::has_operation() const { return is_set(yfilter) || ydk::is_set(target_attenuation.yfilter) || ydk::is_set(attenuation.yfilter) || (optical_power != nullptr && optical_power->has_operation()); } std::string Aps::ApsModules::ApsModule::Ports::CommonOutput::State::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "state"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::CommonOutput::State::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (target_attenuation.is_set || is_set(target_attenuation.yfilter)) leaf_name_data.push_back(target_attenuation.get_name_leafdata()); if (attenuation.is_set || is_set(attenuation.yfilter)) leaf_name_data.push_back(attenuation.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::CommonOutput::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "optical-power") { if(optical_power == nullptr) { optical_power = std::make_shared<Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower>(); } return optical_power; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::CommonOutput::State::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(optical_power != nullptr) { _children["optical-power"] = optical_power; } return _children; } void Aps::ApsModules::ApsModule::Ports::CommonOutput::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "target-attenuation") { target_attenuation = value; target_attenuation.value_namespace = name_space; target_attenuation.value_namespace_prefix = name_space_prefix; } if(value_path == "attenuation") { attenuation = value; attenuation.value_namespace = name_space; attenuation.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::CommonOutput::State::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "target-attenuation") { target_attenuation.yfilter = yfilter; } if(value_path == "attenuation") { attenuation.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::State::has_leaf_or_child_of_name(const std::string & name) const { if(name == "optical-power" || name == "target-attenuation" || name == "attenuation") return true; return false; } Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::OpticalPower() : instant{YType::str, "instant"}, avg{YType::str, "avg"}, min{YType::str, "min"}, max{YType::str, "max"} { yang_name = "optical-power"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true; } Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::~OpticalPower() { } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::has_data() const { if (is_presence_container) return true; return instant.is_set || avg.is_set || min.is_set || max.is_set; } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::has_operation() const { return is_set(yfilter) || ydk::is_set(instant.yfilter) || ydk::is_set(avg.yfilter) || ydk::is_set(min.yfilter) || ydk::is_set(max.yfilter); } std::string Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "optical-power"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (instant.is_set || is_set(instant.yfilter)) leaf_name_data.push_back(instant.get_name_leafdata()); if (avg.is_set || is_set(avg.yfilter)) leaf_name_data.push_back(avg.get_name_leafdata()); if (min.is_set || is_set(min.yfilter)) leaf_name_data.push_back(min.get_name_leafdata()); if (max.is_set || is_set(max.yfilter)) leaf_name_data.push_back(max.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "instant") { instant = value; instant.value_namespace = name_space; instant.value_namespace_prefix = name_space_prefix; } if(value_path == "avg") { avg = value; avg.value_namespace = name_space; avg.value_namespace_prefix = name_space_prefix; } if(value_path == "min") { min = value; min.value_namespace = name_space; min.value_namespace_prefix = name_space_prefix; } if(value_path == "max") { max = value; max.value_namespace = name_space; max.value_namespace_prefix = name_space_prefix; } } void Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "instant") { instant.yfilter = yfilter; } if(value_path == "avg") { avg.yfilter = yfilter; } if(value_path == "min") { min.yfilter = yfilter; } if(value_path == "max") { max.yfilter = yfilter; } } bool Aps::ApsModules::ApsModule::Ports::CommonOutput::State::OpticalPower::has_leaf_or_child_of_name(const std::string & name) const { if(name == "instant" || name == "avg" || name == "min" || name == "max") return true; return false; } PRIMARY::PRIMARY() : Identity("http://openconfig.net/yang/optical-transport-line-protection", "openconfig-transport-line-protection", "openconfig-transport-line-protection:PRIMARY") { } PRIMARY::~PRIMARY() { } SECONDARY::SECONDARY() : Identity("http://openconfig.net/yang/optical-transport-line-protection", "openconfig-transport-line-protection", "openconfig-transport-line-protection:SECONDARY") { } SECONDARY::~SECONDARY() { } } }
31.323185
228
0.689757
[ "vector" ]
7bbb8cf22be3fdf061ee13c673d4e3efe64d3f4d
8,356
cpp
C++
hackathon/wenqi/BrainVesselCPR/BrainVesselCPR_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
hackathon/wenqi/BrainVesselCPR/BrainVesselCPR_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
hackathon/wenqi/BrainVesselCPR/BrainVesselCPR_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
/* BrainVesselCPR_plugin.cpp * This is a plugin for Brain Vessel CPR in MRA&MRI image * 2019-5-14 : by Wenqi Huang */ #include "BrainVesselCPR_plugin.h" #include "BrainVesselCPR_filter.h" #include "BrainVesselCPR_centerline.h" #include "BrainVesselCPR_syncview.h" #include "BrainVesselCPR_sampleplane.h" void setWLWW(V3DPluginCallback2 &callback, QWidget *parent) { SetContrastWidget * setWLWW_widget = new SetContrastWidget(callback, parent); setWLWW_widget->show(); } Q_EXPORT_PLUGIN2(BrainVesselCPR, BrainVesselCPRPlugin); QStringList BrainVesselCPRPlugin::menulist() const { return QStringList() <<tr("Start CPR") <<tr("Set MRI WL/WW") <<tr("synchronize 3D viewers") <<tr("about"); } // menu bar settings // QStringList BrainVesselCPRPlugin::funclist() const // { // return QStringList() // <<tr("func1") // <<tr("func2") // <<tr("help"); // } void BrainVesselCPRPlugin::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent) { if (menu_name == tr("Start CPR")) { //v3d_msg("To be implemented."); startCPR(callback,parent); } else if(menu_name == tr("Set MRI WL/WW")) { setWLWW(callback,parent); } else if (menu_name == tr("synchronize 3D viewers")) { SynTwoImage(callback, parent); } else { v3d_msg(tr("This is a plugin for Brain Vessel CPR in MRA&MRI image. " "Developed by Wenqi Huang, 2019-5-14")); } } void startCPR(V3DPluginCallback2 &callback, QWidget *parent) { v3dhandleList win_list = callback.getImageWindowList(); v3dhandle curwin = callback.currentImageWindow(); if(win_list.size()<1) { v3d_msg("No MRA Image Opened!"); return; } //get 2 landmarks as start and end point LandmarkList landmark_list = callback.getLandmark(curwin); while(landmark_list.size()!=2) { v3d_msg("Please select TWO landmarks as start point and end point."); landmark_list = callback.getLandmark(curwin); //TODO: exception } //marker coord start from 1 instead of 0 for(long i=0;i<2;i++) { landmark_list[i].x-=1; landmark_list[i].y-=1; landmark_list[i].z-=1; } v3d_msg(QObject::tr("Start point: (%1, %2, %3)\nEnd point: (%4, %5, %6)").\ arg(landmark_list[0].x).arg(landmark_list[0].y).arg(landmark_list[0].z).\ arg(landmark_list[1].x).arg(landmark_list[1].y).arg(landmark_list[1].z)); // get 3d image info & 1d data vector Image4DSimple* p4DImage = callback.getImage(curwin); if (!p4DImage) { QMessageBox::information(0, "", "The image pointer is invalid. Ensure your data is valid and try again!"); return; } unsigned short int * data1d = (unsigned short int *) p4DImage->getRawData(); V3DLONG totalpxls = p4DImage->getTotalBytes(); V3DLONG pagesz = p4DImage->getTotalUnitNumberPerChannel(); V3DLONG x_length = p4DImage->getXDim(); V3DLONG y_length = p4DImage->getYDim(); V3DLONG z_length = p4DImage->getZDim(); V3DLONG channels = p4DImage->getCDim(); V3DLONG UnitBytes = p4DImage->getUnitBytes(); cout << "total bytes: " << totalpxls << endl << "width: " << x_length << endl \ << "height: " << y_length << endl << "slice num: " << z_length \ << endl << "channel: " << channels << endl << "unit bytes: " << UnitBytes << endl; //convert landmark to 1d data index V3DLONG start; V3DLONG goal; // test start (113, 123,138), id: , goal (138, 198, 76), id: // start = x_length * y_length * 138 + 123 * x_length + 113; // goal = x_length * y_length * 76 + 198 * x_length + 138; start = V3DLONG(landmark_list[0].x) + V3DLONG(landmark_list[0].y) * x_length + V3DLONG(landmark_list[0].z) * x_length * y_length; goal = V3DLONG(landmark_list[1].x) + V3DLONG(landmark_list[1].y) * x_length + V3DLONG(landmark_list[1].z) * x_length * y_length; //find path begins! cout << "begin find path!" << endl; float* data1d_gausssian = 0; //data1d_gausssian = new float[x_length*y_length*z_length]; V3DLONG *in_sz; in_sz = new V3DLONG[4]; in_sz[0] = x_length; in_sz[1] = y_length; in_sz[2] = z_length; in_sz[3] = 1; gaussian_filter(data1d, in_sz, 7, 7, 7, 1, 100, data1d_gausssian); unsigned short int * data1d_gaussian_uint16; data1d_gaussian_uint16 = new unsigned short int[x_length*y_length*z_length]; for(int i = 0; i < x_length*y_length*z_length; i++) { data1d_gaussian_uint16[i] = (unsigned short int)data1d_gausssian[i]; } vector<Coor3D> centerline = findPath(start, goal, data1d_gaussian_uint16, x_length, y_length, z_length, callback, parent); cout << "find path finished!" << endl; unsigned short int * cprdata1d = 0; int radius = 40; int winlen = radius*2+1; //cout<<"break: "<<__LINE__<<endl; //transfer to mri QString fileOpenName = QFileDialog::getOpenFileName(0, QObject::tr("Open MRI File"), "", QObject::tr("Supported file (*.tif)" )); if(fileOpenName.isEmpty()) return; Image4DSimple * cprImage = new Image4DSimple(); Image4DSimple * MRIImage = new Image4DSimple(); unsigned char * mri_data1d = 0; int datatype = 0; simple_loadimage_wrapper(callback,fileOpenName.toStdString().c_str(), mri_data1d, in_sz, datatype); //v3dhandle newwin = callback.newImageWindow("cpr"); // SelectMRI* selectmri = new SelectMRI(callback, parent); // cout << "break: " << __LINE__ << endl; // selectmri->show(); // cout << "break: " << __LINE__ << endl; // if(selectmri exec()) // while(!selectmri->mrihandle) // { // cout << "wait." <<endl; // } // Image4DSimple* MRIImage = callback.getImage(selectmri->mrihandle); // if (!MRIImage) // { // QMessageBox::information(0, "", "The image pointer is invalid. Ensure your data is valid and try again!"); // return; // } //mri_data1d = (unsigned short int *)MRIImage->getRawData(); cout << "break: " << __LINE__ << endl; cprdata1d = samplePlane((unsigned short int *)mri_data1d, centerline, x_length, y_length, z_length, radius, callback, parent); //cprdata1d = samplePlane((unsigned short int *)data1d, centerline, x_length, y_length, z_length, radius, callback, parent); cout << "break: " << __LINE__ << endl; //Image4DSimple * cprImage = new Image4DSimple(); cprImage->setData((unsigned char *)cprdata1d, winlen, winlen, centerline.size(), 1, V3D_UINT16); cout << "break: " << __LINE__ << endl; v3dhandle newwin = callback.newImageWindow("CPR Image1"); callback.setImage(newwin, cprImage); cout << "break: " << __LINE__ << endl; //// cprdata1d = samplePlane(data1d, centerline, x_length, y_length, z_length, radius, callback, parent); // Image4DSimple * cprImage_mra = new Image4DSimple(); // unsigned short int * cprdata1d_mra = samplePlane((unsigned short int *)data1d, centerline, x_length, y_length, z_length, radius, callback, parent); // cout << "break: " << __LINE__ << endl; // //Image4DSimple * cprImage = new Image4DSimple(); // //cprImage->setData((unsigned char *)cprdata1d, winlen, winlen, centerline.size(), 1, V3D_UINT16); // cprImage->setData((unsigned char *)cprdata1d_mra, winlen, winlen, centerline.size(), 1, V3D_UINT16); // v3dhandle newwin2 = callback.newImageWindow("CPR Image2"); // callback.setImage(newwin2, cprImage_mra); // //callback.updateImageWindow(newwin2); //sync 3d view of MRA and MRI } // menu bar funtions // bool BrainVesselCPRPlugin::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent) // { // vector<char*> infiles, inparas, outfiles; // if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p); // if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p); // if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p); // if (func_name == tr("func1")) // { // v3d_msg("To be implemented."); // } // else if (func_name == tr("func2")) // { // v3d_msg("To be implemented."); // } // else if (func_name == tr("help")) // { // v3d_msg("To be implemented."); // } // else return false; // return true; // }
33.96748
172
0.64325
[ "vector", "3d" ]
7bbcb5f0139b8dd6096d79cf873d4536879af6ad
3,697
cpp
C++
src/playerloader.cpp
NicoleIsDead/Fortune-Tourney-Tool
209517a4704a538c5f109055d754022e553ac80f
[ "MIT" ]
null
null
null
src/playerloader.cpp
NicoleIsDead/Fortune-Tourney-Tool
209517a4704a538c5f109055d754022e553ac80f
[ "MIT" ]
null
null
null
src/playerloader.cpp
NicoleIsDead/Fortune-Tourney-Tool
209517a4704a538c5f109055d754022e553ac80f
[ "MIT" ]
1
2021-04-18T21:16:03.000Z
2021-04-18T21:16:03.000Z
//MIT License //Copyright (c) 2021 NicoleIsDead //https://github.com/NicoleIsDead // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "playerloader.h" #include "player.h" #include "constants.h" #include <QDir> #include <QStringList> #include <QMessageBox> #include <QString> // --------------------------------------------------------------------------- // Constructors / Deconstructors // --------------------------------------------------------------------------- PlayerLoader::PlayerLoader() { } // --------------------------------------------------------------------------- // LoadPlayerList // Loads and returns a QVector of Players based on subdirectories of the input path // --------------------------------------------------------------------------- QVector<Player> PlayerLoader::LoadPlayerList(QString folderPath) { //The path string of the player database folder QString playerDatabaseFolderPath = folderPath; //An object for scanning the player database folder QDir playerDatabaseDirectory(playerDatabaseFolderPath); //The output QVector of the player data QVector<Player> returnVector; //Check if the PlayerDatabase folder is missing if (!playerDatabaseDirectory.isReadable()) { QMessageBox message; message.setText("PlayerDatabase folder missing at: " + playerDatabaseDirectory.absolutePath()); message.exec(); } QStringList stringList = playerDatabaseDirectory.entryList(); for (int i = 0; i < stringList.count(); i++){ QString characterName = stringList[i]; if (characterName == "." || characterName == "..") { continue; } returnVector.append(LoadPlayer(playerDatabaseFolderPath, characterName)); } return returnVector; } // --------------------------------------------------------------------------- // LoadPlayer // Loads and returns a Players object based on the input path // Checks if an emote is missing and if so, replaces it with freed jyanshi // --------------------------------------------------------------------------- Player PlayerLoader::LoadPlayer(QString playerFolderPath, QString playerName) { //Load the player's information QString inputPlayerName = playerName; QImage inputCharacterEmoteDefault(playerFolderPath+"\\"+playerName+"\\default"); QImage inputCharacterEmoteHappy(playerFolderPath+"\\"+playerName+"\\happy"); QImage inputCharacterEmoteSad(playerFolderPath+"\\"+playerName+"\\sad"); QImage inputCharacterEmoteRolling(playerFolderPath+"\\"+playerName+"\\rolling"); //check for missing images and replace these with freed jyanshi if (inputCharacterEmoteDefault.isNull()) { inputCharacterEmoteDefault.load(DEFAULT_EMOTE_PATH + "\\default.png"); } if (inputCharacterEmoteHappy.isNull()) { inputCharacterEmoteHappy.load(DEFAULT_EMOTE_PATH + "\\happy.png"); } if (inputCharacterEmoteSad.isNull()) { inputCharacterEmoteSad.load(DEFAULT_EMOTE_PATH + "\\sad.png"); } if (inputCharacterEmoteRolling.isNull()) { inputCharacterEmoteRolling.load(DEFAULT_EMOTE_PATH + "\\rolling.png"); } //if one of the images is still missing, the software will asume that the default player is not available if (inputCharacterEmoteDefault.isNull() || inputCharacterEmoteHappy.isNull() || inputCharacterEmoteSad.isNull() || inputCharacterEmoteRolling.isNull()) { QMessageBox message; message.setText("Default player emote not loaded"); message.exec(); } return Player(inputPlayerName, inputCharacterEmoteDefault, inputCharacterEmoteHappy, inputCharacterEmoteSad, inputCharacterEmoteRolling); }
41.539326
139
0.621856
[ "object" ]
7bbfe659ec05eafa4a8a13ac7341fffb1c892437
745
cpp
C++
cpp-leetcode/leetcode476-number-complement_converrt_to_string.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
45
2021-07-25T00:45:43.000Z
2022-03-24T05:10:43.000Z
cpp-leetcode/leetcode476-number-complement_converrt_to_string.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
null
null
null
cpp-leetcode/leetcode476-number-complement_converrt_to_string.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
15
2021-07-25T00:40:52.000Z
2021-12-27T06:25:31.000Z
#include<vector> #include<algorithm> #include<iostream> using namespace std; class Solution { public: int findComplement(int num) { string str = toReverseBinary(num); return stoi(str, nullptr, 2); /* 从2进制串转十进制数, 第3个参数2表示二进制 */ } string toReverseBinary(long n) /* 得到二进制数的补码字符串 */ { string res = ""; while (n > 0) { char r = n % 2 == 0 ? '1' : '0'; /* 得到每一位的反转值 */ res.push_back(r); /* 记住: 放进去的结果会导致低位在前, 高位在后 */ n /= 2; } reverse(res.begin(), res.end()); return res; } }; // Test int main() { Solution sol; int num = 5; auto res = sol.findComplement(num); cout << res << endl; return 0; }
20.135135
71
0.514094
[ "vector" ]
7bc04fe4e7467e5893a9b3ff6141b63b1f0da8c1
1,207
cpp
C++
SPOJ/IDC1948.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
SPOJ/IDC1948.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
SPOJ/IDC1948.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <sstream> #include <vector> #include <iomanip> #include <cmath> using namespace std; typedef long long LL; typedef pair<int,int> pii; #define MAX 10000 #define MOD 1000000007 int sieve[MAX],primes[MAX],k; void make_sieve() { for(int i=2;i<=100;i++) { if(!sieve[i]) for(int j=i*i;j<MAX;j+=i) sieve[j] = 1; } for(int i=2;i<MAX;i++) if(!sieve[i]) primes[k++] = i; } int main() { make_sieve(); ios::sync_with_stdio(false); int t,n,num,d; cin>>t; while(t--) { cin>>n; d = (int)log10(n) + 1; num = 0; for(int i=0;i<d;i++) num = num*10 + 9; num -= (2*n); if(num < 0) num = -num; if(num == 1 || num == -1) { cout<<-1<<endl; goto down; } int i; for(i=0;i<k;i++) { if(num%primes[i] == 0) { cout<<primes[i]<<endl; goto down; } } if(i == k) cout<<num<<endl; down:; } return 0; }
18.014925
38
0.431649
[ "vector" ]
dcfae4d5c16ae0e9c3a24958775434c795841d08
2,787
cpp
C++
Arrays/Max_XOR_of_Two_Array.cpp
siddhi-244/CompetitiveProgrammingQuestionBank
4c265d41b82a7d4370c14d367f78effa9ed95d3c
[ "MIT" ]
931
2020-04-18T11:57:30.000Z
2022-03-31T15:15:39.000Z
Arrays/Max_XOR_of_Two_Array.cpp
geekySapien/CompetitiveProgrammingQuestionBank
9e84a88a85dbabd95207391967abde298ddc031d
[ "MIT" ]
661
2020-12-13T04:31:48.000Z
2022-03-15T19:11:54.000Z
Arrays/Max_XOR_of_Two_Array.cpp
geekySapien/CompetitiveProgrammingQuestionBank
9e84a88a85dbabd95207391967abde298ddc031d
[ "MIT" ]
351
2020-08-10T06:49:21.000Z
2022-03-25T04:02:12.000Z
/* Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 ≤ i ≤ j < n. */ #include<iostream> #include<vector> using namespace std; // Constructing a trie struct trie { trie *zero,*one; }; //Building the trie void insert(int num,trie *root) { // Store the head trie *ptr=root; for(int i=31;i>=0;i--) { // Find the i-th bit int h = (num>>i & 1); if(h==0) { // If ptr->zero is NULL if(ptr->zero==NULL) { ptr->zero=new trie(); } // Update ptr to ptr->zero ptr=ptr->zero; } else { // If ptr->onr is NULL if(ptr->one==NULL) { ptr->one=new trie(); } // Update ptr to ptr->one ptr=ptr->one; } } } //Finding the maximum XOR for each element int comp(int num,trie *root) { trie *ptr = root; int sum=0; for(int i=31;i>=0;i--) { sum=sum<<1; // Finding ith bit int h = (num>>i & 1); // Check if the bit is 0 if(h==0) { // If right node exists if(ptr->one) { sum++; ptr=ptr->one; } else ptr=ptr->zero; } else { // Check if left node exists if(ptr->zero) { sum++; ptr=ptr->zero; } else ptr=ptr->one; } } return sum; } int findMaximumXOR(vector<int>& nums) { // head Node of Trie trie *root = new trie(); // Insert each element in trie for(int i=0;i<nums.size();i++) { insert(nums[i],root); } // Stores the maximum XOR value int maxm=0; // Traverse the given array for(int i=0;i<nums.size();i++) { maxm=max(comp(nums[i],root),maxm); } return maxm; } //Main Function int main() { vector<int>nums; int sz; cout<<"Enter the vector size\n"; cin>>sz; // size of the vector cout<<"Enter the elements in the vector\n"; for(int i=0;i<sz;i++) { int x; cin>>x; nums.push_back(x); } int answer = findMaximumXOR(nums); cout<<"The Maximum XOR of two numbers in the array/vector is : "<<answer<<endl; return 0; } /* Sample Text Case Enter the vector size 6 Enter the elements in the vector 3 10 5 25 2 8 The Maximum XOR of two numbers in the array/vector is : 28 Time Complexity : O(n) , where n is the number of elements in the vector. */
23.820513
85
0.455328
[ "vector" ]
dcff56b40befda73ea0c8144e7b3af025978f852
1,464
cc
C++
Tree/PathSum2.cc
plantree/LeetCode
0ac6734b6a4c6e826df15a3d2e43e8f8df92a510
[ "MIT" ]
null
null
null
Tree/PathSum2.cc
plantree/LeetCode
0ac6734b6a4c6e826df15a3d2e43e8f8df92a510
[ "MIT" ]
null
null
null
Tree/PathSum2.cc
plantree/LeetCode
0ac6734b6a4c6e826df15a3d2e43e8f8df92a510
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; TreeNode* createTree(vector<int> list, int start) { if (list[start] == -1) { return nullptr; } TreeNode* root = new TreeNode(list[start]); // 构造左右子树 int lnode = 2 * start + 1; int rnode = 2 * start + 2; if (lnode < list.size()) { root->left = createTree(list, lnode); } if (rnode < list.size()) { root->right = createTree(list, rnode); } return root; } void helper(TreeNode* node, int sum, vector<int>& out, vector<vector<int>>& res) { if (!node) { return; } out.push_back(node->val); if (node->val == sum && !node->left && !node->right) { res.push_back(out); } // 在中间结果的基础上递归 helper(node->left, sum-node->val, out, res); helper(node->right, sum-node->val, out, res); // 及时清理无关结果 out.pop_back(); } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; vector<int> out; helper(root, sum, out, res); return res; } int main() { vector<int> nodes = {5, 4, 8, 11, -1, 13, 4}; TreeNode *root = createTree(nodes, 0); auto res = pathSum(root, 17); for (auto line : res) { for (auto item : line) { cout << item << " "; } cout << endl; } }
22.181818
82
0.547131
[ "vector" ]
0d00f65c30e9808a2cc27c340bf4e06a2e21c4cd
4,122
hpp
C++
interfaces/offscreen_render_target.hpp
PiotrBanuba/OEP-module
d60204b8f6c3738e6fb8b5c2ea657460397be774
[ "MIT" ]
null
null
null
interfaces/offscreen_render_target.hpp
PiotrBanuba/OEP-module
d60204b8f6c3738e6fb8b5c2ea657460397be774
[ "MIT" ]
2
2022-03-16T13:01:29.000Z
2022-03-16T14:06:16.000Z
interfaces/offscreen_render_target.hpp
PiotrBanuba/OEP-module
d60204b8f6c3738e6fb8b5c2ea657460397be774
[ "MIT" ]
null
null
null
#pragma once #include <interfaces/image_format.hpp> #include <interfaces/pixel_buffer.hpp> #include <interfaces/render_context.hpp> namespace bnb::oep::interfaces { class offscreen_render_target; } using rendered_texture_t = void*; using offscreen_render_target_sptr = std::shared_ptr<bnb::oep::interfaces::offscreen_render_target>; namespace bnb::oep::interfaces { class offscreen_render_target { public: /** * Create the offscreen render target. * * @param rc - shared pointer to rendering context * * @return - shared pointer to the offscreen render target * * @example bnb::oep::interfaces::offscreen_render_target::create(my_rc) */ static offscreen_render_target_sptr create(render_context_sptr rc); virtual ~offscreen_render_target() = default; /** * Offscreen Render Target initialization. Includes initialization of gl context's * buffers and support objects. * Called by offscreen effect player. * * @param width Initial width of the offscreen render target * @param width Initial height of the offscreen render target * * @example init(1280, 720) */ virtual void init(int32_t width, int32_t height) = 0; /** * Offscreen Render Target deinitialization. Should be called within the same thread as init(); * Called by offscreen effect player. * * @example deinit() */ virtual void deinit() = 0; /** * Notify about rendering surface being resized. * Called by offscreen effect player. * * @param width New width for the rendering surface * @param height New height for the rendering surface * * @example surface_changed(1280, 720) */ virtual void surface_changed(int32_t width, int32_t height) = 0; /** * Activate context for current thread * * @example activate_context() */ virtual void activate_context() = 0; /** * Deactivate context in the corresponding thread * In the certain cases (GLFW on Windows) when it is intended to make OGL resource sharing * it is required that sharing context is not active in any thread. * * @example deactivate_context() */ virtual void deactivate_context() = 0; /** * Preparing texture for effect_player * Called by offscreen effect player. * * @example prepare_rendering() */ virtual void prepare_rendering() = 0; /** * Orientates the image * Called by offscreen effect player. * * @param orient output image orientation * * @example orient_image(rotation::deg180) */ virtual void orient_image(rotation orient) = 0; /** * Reading current buffer of active texture. * The implementation must definitely support for reading format image_format::bpc8_rgba * Called by image_processing_result * * @param format requested output image format * * @return pixel_buffer_sptr - the smart pointer to the instance of the pixel_buffer interface, * providing access to the output image byte data, or nullptr if the specified format is not supported. * Must have support for format image_format::bpc8_rgba * * @example read_current_buffer(image_format::bpc8_rgba) */ virtual pixel_buffer_sptr read_current_buffer(image_format format) = 0; /** * Get texture id used for rendering of frame * Called by offscreen effect player. * * @return texture id * * @example get_current_buffer_texture() */ virtual rendered_texture_t get_current_buffer_texture() = 0; }; /* class offscreen_render_target INTERFACE */ } /* namespace bnb::oep::interfaces */
32.714286
111
0.613052
[ "render" ]