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
c5f3e0826fb727ff0caedf1efad1809b7ecefea1
4,618
cpp
C++
ACore/src/Child.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
ACore/src/Child.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
ACore/src/Child.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // Name : // Author : Avi // Revision : $Revision: #4 $ // // Copyright 2009- ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // // Description : Specifies the different kinds of child commands // These are specified in the job file, and communicate with the server /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 #include <cassert> #include "Child.hpp" #include "Str.hpp" namespace ecf { std::string Child::to_string(Child::ZombieType zt) { switch (zt) { case Child::USER: return "user"; break; case Child::PATH: return "path"; break; case Child::ECF: return "ecf"; break; case Child::ECF_PID: return "ecf_pid"; break; case Child::ECF_PID_PASSWD: return "ecf_pid_passwd"; break; case Child::ECF_PASSWD: return "ecf_passwd"; break; case Child::NOT_SET: return "not_set"; break; } return std::string(); } Child::ZombieType Child::zombie_type(const std::string& s) { if (s == "user") return Child::USER; if (s == "ecf") return Child::ECF; if (s == "ecf_pid") return Child::ECF_PID; if (s == "ecf_pid_passwd") return Child::ECF_PID_PASSWD; if (s == "ecf_passwd") return Child::ECF_PASSWD; if (s == "path") return Child::PATH; return Child::NOT_SET; } bool Child::valid_zombie_type( const std::string& s) { if (s == "user") return true; if (s == "ecf") return true; if (s == "ecf_pid") return true; if (s == "ecf_pid_passwd") return true; if (s == "ecf_passwd") return true; if (s == "path") return true; return false; } std::string Child::to_string(const std::vector<Child::CmdType>& vec) { std::string ret; for(size_t i =0; i < vec.size(); ++i) { if (i == 0) ret += to_string(vec[i]); else { ret += ","; ret += to_string(vec[i]); } } return ret; } std::string Child::to_string( Child::CmdType ct) { switch (ct) { case Child::INIT: return "init"; break; case Child::EVENT: return "event"; break; case Child::METER: return "meter"; break; case Child::LABEL: return "label"; break; case Child::WAIT: return "wait"; break; case Child::QUEUE: return "queue"; break; case Child::ABORT: return "abort"; break; case Child::COMPLETE: return "complete"; break; } assert(false); return "init"; } std::vector<Child::CmdType> Child::child_cmds(const std::string& s) { // expect single or , separated tokens std::vector<std::string> tokens; Str::split(s,tokens,","); std::vector<Child::CmdType> ret; ret.reserve(tokens.size()); for(const auto & token : tokens) { ret.push_back(child_cmd(token)); } return ret; } Child::CmdType Child::child_cmd( const std::string& s) { if (s == "init") return Child::INIT; if (s == "event") return Child::EVENT; if (s == "meter") return Child::METER; if (s == "label") return Child::LABEL; if (s == "wait") return Child::WAIT; if (s == "queue") return Child::QUEUE; if (s == "abort") return Child::ABORT; if (s == "complete") return Child::COMPLETE; assert(false); return Child::INIT; } bool Child::valid_child_cmds( const std::string& s) { // empty means all children if (s.empty()) return true; // expect single or , separated tokens std::vector<std::string> tokens; Str::split(s,tokens,","); for(const auto & token : tokens) { if (!valid_child_cmd(token)) return false; } return true; } bool Child::valid_child_cmd( const std::string& s) { if (s == "init") return true; if (s == "event") return true; if (s == "meter") return true; if (s == "label") return true; if (s == "wait") return true; if (s == "queue") return true; if (s == "abort") return true; if (s == "complete") return true; return false; } std::vector<Child::CmdType> Child::list() { std::vector<ecf::Child::CmdType> child_cmds; child_cmds.push_back(ecf::Child::INIT); child_cmds.push_back(ecf::Child::EVENT); child_cmds.push_back(ecf::Child::METER); child_cmds.push_back(ecf::Child::LABEL); child_cmds.push_back(ecf::Child::WAIT); child_cmds.push_back(ecf::Child::QUEUE); child_cmds.push_back(ecf::Child::ABORT); child_cmds.push_back(ecf::Child::COMPLETE); return child_cmds; } }
29.227848
85
0.62278
[ "vector" ]
c5f442a23c26e9bb58834a430173e79b3869f3ae
5,173
cpp
C++
brlycmbd/CrdBrlySeg/PnlBrlySegDetail_evals.cpp
mpsitech/brly-BeamRelay
481ccb3e83ea6151fb78eba293b44ade62a0ec78
[ "MIT" ]
null
null
null
brlycmbd/CrdBrlySeg/PnlBrlySegDetail_evals.cpp
mpsitech/brly-BeamRelay
481ccb3e83ea6151fb78eba293b44ade62a0ec78
[ "MIT" ]
null
null
null
brlycmbd/CrdBrlySeg/PnlBrlySegDetail_evals.cpp
mpsitech/brly-BeamRelay
481ccb3e83ea6151fb78eba293b44ade62a0ec78
[ "MIT" ]
null
null
null
/** * \file PnlBrlySegDetail_evals.cpp * job handler for job PnlBrlySegDetail (implementation of availability/activation evaluation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 11 Jan 2021 */ // IP header --- ABOVE using namespace std; using namespace Sbecore; using namespace Xmlio; bool PnlBrlySegDetail::evalButSaveAvail( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalButSaveActive( DbsBrly* dbsbrly ) { // dirty() vector<bool> args; bool a; a = false; a = dirty; args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalTxtReuActive( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalButReuViewAvail( DbsBrly* dbsbrly ) { // seg.reuEq(0)|((pre.ixCrdaccCon()&seg.retEq(con))|(pre.ixCrdaccFlt()&seg.retEq(flt))) vector<bool> args; bool a, b; a = false; a = (recSeg.refUref == 0); args.push_back(a); a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCCON, jref) != 0); args.push_back(a); a = false; a = (recSeg.refIxVTbl == VecBrlyVMSegmentRefTbl::CON); args.push_back(a); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a && b); a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCFLT, jref) != 0); args.push_back(a); a = false; a = (recSeg.refIxVTbl == VecBrlyVMSegmentRefTbl::FLT); args.push_back(a); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a && b); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a || b); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a || b); return(args.back()); }; bool PnlBrlySegDetail::evalButReuViewActive( DbsBrly* dbsbrly ) { // !seg.reuEq(0) vector<bool> args; bool a; a = false; a = (recSeg.refUref == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); return(args.back()); }; bool PnlBrlySegDetail::evalTxfDphActive( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalTxfAl0Active( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalTxfAl1Active( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalTxfTh0Active( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalTxfTh1Active( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalTxfPh0Active( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalTxfPh1Active( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalTxfStaActive( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalTxfStoActive( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlBrlySegDetail::evalChkCdnActive( DbsBrly* dbsbrly ) { // pre.ixCrdaccSegIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecBrlyVPreset::PREBRLYIXCRDACCSEG, jref) & VecBrlyWAccess::EDIT); args.push_back(a); return(args.back()); };
21.114286
101
0.691282
[ "vector" ]
c5f69b854c235ab414d928260156fd9e085d00d2
3,876
cpp
C++
2018/23.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
2
2020-08-06T22:14:51.000Z
2020-08-10T19:42:36.000Z
2018/23.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
null
null
null
2018/23.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> const unsigned size=1000; unsigned long long abs(long long a){return a<0 ? -1*a:a;} struct nanobot { long long x,y,z; unsigned long long r; nanobot(long long _x,long long _y,long long _z,unsigned long long _r):x(_x),y(_y),z(_z),r(_r){}; bool in_range(long long _x,long long _y,long long _z){return abs(x-_x)+abs(y-_y)+abs(z-_z)<=r;} bool in_range(nanobot b){return in_range(b.x,b.y,b.z);} bool is_adj(nanobot b){return abs(x-b.x)+abs(y-b.y)+abs(z-b.z)<=r+b.r;} }; std::vector<nanobot> part1(std::istream& input_file); /* * implementation of Bron-Kerbosh, finds the good clique, but then does not finish in my lifetime with the given input. */ std::vector<std::vector<unsigned>> BK(std::vector<unsigned>& R,std::vector<unsigned>& P,std::vector<unsigned>& X, bool** adj_mat){ static std::vector<std::vector<unsigned>> max_cliques = {}; static unsigned long recur_depth = 0; recur_depth++; if(recur_depth<=960){for(auto a:max_cliques)std::cout<<a.size()<<' ';std::cout<<"at "<<recur_depth<<' '<<max_cliques.size()<<std::endl;} if(!P.size()&&!X.size())max_cliques.push_back(R); else while(P.size()) { //std::cout<<"HEY!"<<std::flush; std::vector<unsigned> new_P={},new_X={},new_R=R; //std::cout<<"HEy!"<<P.back()<<std::flush; bool push=true; for(auto a:R)if(a==P.back())push=false; if(push){ new_R.push_back(P.back()); // std::cout<<"pushed it!"<<std::endl; } //std::cout<<"HeY!"<<std::flush; for(auto a:P)if(a!=P.back()&&adj_mat[a][P.back()])new_P.push_back(a); //std::cout<<"hEY!"<<std::flush; for(auto a:X)if(a!=P.back()&&adj_mat[a][P.back()])new_X.push_back(a); //std::cout<<"Hey!"<<std::flush; BK(new_R,new_P,new_X,adj_mat); //std::cout<<"heY!"<<std::flush; X.emplace_back(P.back()); //std::cout<<"hEy!"<<std::flush; P.pop_back(); } //std::cout<<max_cliques.size()<<std::endl; recur_depth--; return max_cliques; } int main(int argc, char** argv){ if(argc<2){std::cout<<"usage: {program} {input_file}"<<std::endl;return 0;} std::ifstream input_file(argv[1]); if(!input_file.good()){std::cout<<argv[1]<<" is bad"<<std::endl;return 1;} std::vector<nanobot> nanobots = part1(input_file); bool **adj_mat = new bool*[nanobots.size()]; for(unsigned i=0;i<nanobots.size();i++){ adj_mat[i] = new bool[nanobots.size()]; for(unsigned j=0;j<nanobots.size();j++){ adj_mat[i][j]=nanobots[i].is_adj(nanobots[j]); // std::cout<<(adj_mat[i][j] ? '#' : '.'); }//std::cout<<'\n'; } std::vector<unsigned> R={},P={},X={}; for(int i=0;i<nanobots.size();i++)P.emplace_back(i); std::cout<<P.size()<<std::endl; std::vector<std::vector<unsigned>> units=BK(R,P,X,adj_mat); std::cout<<units.size()<<std::endl; return 0; } std::vector<nanobot> part1(std::istream& input_file) { std::vector<nanobot> nanobots = {};unsigned long long max_r = 0,max_index;for(;;){while(!input_file.eof()&&input_file.get()!='<');if(input_file.eof())break;long long x,y,z;unsigned long long r;input_file>>x;if(input_file.get()!=','){std::cout<<", expected"<<std::endl;exit(1);}input_file>>y;if(input_file.get()!=','){std::cout<<", expected"<<std::endl;exit(1);}input_file>>z;if(input_file.get()!='>'){std::cout<<"> expected"<<std::endl;exit(1);}while(!input_file.eof()&&input_file.get()!='=');if(input_file.eof()){std::cout<<"Weird..."<<std::endl;exit(1);}input_file>>r;if(input_file.get()!='\n'){std::cout<<"newline expected"<<std::endl;exit(1);}if(max_r<r){max_r=r;max_index=nanobots.size();}nanobots.emplace_back(x,y,z,r);}unsigned answer1 = 0;for(unsigned i=0;i<nanobots.size();i++)if(nanobots[max_index].in_range(nanobots[i]))answer1++; std::cout<<answer1<<std::endl; return nanobots; }
44.551724
845
0.620485
[ "vector" ]
c5fbae472764eccbf4257fac6f2e07f8467dabad
493
hpp
C++
tarefa_15/src/VectorN.hpp
liviabelirocha/mtn-num-2
8279f9dfcf468db0db854d3a2b51390994e1e5a7
[ "MIT" ]
1
2021-06-18T19:41:55.000Z
2021-06-18T19:41:55.000Z
tarefa_15/src/VectorN.hpp
liviabelirocha/mtn-num-2
8279f9dfcf468db0db854d3a2b51390994e1e5a7
[ "MIT" ]
null
null
null
tarefa_15/src/VectorN.hpp
liviabelirocha/mtn-num-2
8279f9dfcf468db0db854d3a2b51390994e1e5a7
[ "MIT" ]
1
2020-03-30T13:27:40.000Z
2020-03-30T13:27:40.000Z
#ifndef VECTOR_HPP #define VECTOR_HPP #include <iostream> #include <cmath> #include <vector> using namespace std; class VectorN { private: int size_; vector<double> vector_; public: VectorN(); VectorN(int size); void setElement(int i, double element); int getSize(); double getElement(int i); double norm(); void normalize(); void copyVector(VectorN v); double operator*(VectorN v); VectorN operator-(VectorN v); void print(); }; #endif
16.433333
43
0.663286
[ "vector" ]
c5fee3cdaffe7ea653982a6512f32cdbe42a1316
9,230
cpp
C++
renderer/Model.cpp
Korazza/renderer
f0f4a96ac81f2f8d0a637c5622068b7298297f05
[ "MIT" ]
null
null
null
renderer/Model.cpp
Korazza/renderer
f0f4a96ac81f2f8d0a637c5622068b7298297f05
[ "MIT" ]
null
null
null
renderer/Model.cpp
Korazza/renderer
f0f4a96ac81f2f8d0a637c5622068b7298297f05
[ "MIT" ]
null
null
null
#include "Model.hpp" Model::Model(const char *file, unsigned int instancing, std::vector<glm::mat4> instanceMatrix) { std::string text{get_file_contents(file)}; JSON = json::parse(text); Model::file = file; data = getData(); Model::instancing = instancing; Model::instanceMatrix = instanceMatrix; traverseNode(0); } void Model::Draw( Shader &shader, Camera &camera, glm::vec3 translation, glm::quat rotation, glm::vec3 scale) { for (unsigned int i{0}; i < meshes.size(); i++) meshes[i].Mesh::Draw(shader, camera, matricesMeshes[i], translation, rotation, scale); } void Model::loadMesh(unsigned int meshIndex) { unsigned int positionAccIndex{JSON["meshes"][meshIndex]["primitives"][0]["attributes"]["POSITION"]}; unsigned int normalAccIndex{JSON["meshes"][meshIndex]["primitives"][0]["attributes"]["NORMAL"]}; unsigned int textureAccIndex{JSON["meshes"][meshIndex]["primitives"][0]["attributes"]["TEXCOORD_0"]}; unsigned int indiceAccIndex{JSON["meshes"][meshIndex]["primitives"][0]["indices"]}; std::vector<float> posVec{getFloats(JSON["accessors"][positionAccIndex])}; std::vector<glm::vec3> positions{groupFloatsVec3(posVec)}; std::vector<float> normalVec{getFloats(JSON["accessors"][normalAccIndex])}; std::vector<glm::vec3> normals{groupFloatsVec3(normalVec)}; std::vector<float> texVec{getFloats(JSON["accessors"][textureAccIndex])}; std::vector<glm::vec2> texUVs{groupFloatsVec2(texVec)}; std::vector<Vertex> vertices{assembleVertices(positions, normals, texUVs)}; std::vector<GLuint> indices{getIndices(JSON["accessors"][indiceAccIndex])}; std::vector<Texture> textures{getTextures()}; meshes.push_back(Mesh(vertices, indices, textures, instancing, instanceMatrix)); } void Model::traverseNode(unsigned int nextNode, glm::mat4 matrix) { json node = JSON["nodes"][nextNode]; glm::vec3 translation{glm::vec3(0.0f, 0.0f, 0.0f)}; if (node.find("translation") != node.end()) { float translationValues[3]; for (unsigned int i{0}; i < node["translation"].size(); i++) translationValues[i] = (node["translation"][i]); translation = glm::make_vec3(translationValues); } glm::quat rotation{glm::quat(1.0f, 0.0f, 0.0f, 0.0f)}; if (node.find("rotation") != node.end()) { float rotationValues[]{ node["rotation"][3], node["rotation"][0], node["rotation"][1], node["rotation"][2]}; rotation = glm::make_quat(rotationValues); } glm::vec3 scale{glm::vec3(1.0f, 1.0f, 1.0f)}; if (node.find("scale") != node.end()) { float scaleValues[3]; for (unsigned int i{0}; i < node["scale"].size(); i++) scaleValues[i] = (node["scale"][i]); scale = glm::make_vec3(scaleValues); } glm::mat4 matrixNode{glm::mat4(1.0f)}; if (node.find("matrix") != node.end()) { float matValues[16]; for (unsigned int i{0}; i < node["matrix"].size(); i++) matValues[i] = (node["matrix"][i]); matrixNode = glm::make_mat4(matValues); } glm::mat4 trans{glm::mat4(1.0f)}; glm::mat4 rot{glm::mat4(1.0f)}; glm::mat4 sca{glm::mat4(1.0f)}; trans = glm::translate(trans, translation); rot = glm::mat4_cast(rotation); sca = glm::scale(sca, scale); glm::mat4 matrixNextNode{matrix * matrixNode * trans * rot * sca}; if (node.find("mesh") != node.end()) { translationsMeshes.push_back(translation); rotationsMeshes.push_back(rotation); scalesMeshes.push_back(scale); matricesMeshes.push_back(matrixNextNode); loadMesh(node["mesh"]); } if (node.find("children") != node.end()) { for (unsigned int i{0}; i < node["children"].size(); i++) traverseNode(node["children"][i], matrixNextNode); } } std::vector<unsigned char> Model::getData() { std::string bytesText; std::string uri{JSON["buffers"][0]["uri"]}; std::string fileStr{std::string(file)}; std::string fileDirectory{fileStr.substr(0, fileStr.find_last_of('/') + 1)}; bytesText = get_file_contents((fileDirectory + uri).c_str()); std::vector<unsigned char> data(bytesText.begin(), bytesText.end()); return data; } std::vector<float> Model::getFloats(json accessor) { std::vector<float> floatVec; unsigned int buffViewInd = accessor.value("bufferView", 1); unsigned int count{accessor["count"]}; unsigned int accByteOffset = accessor.value("byteOffset", 0); std::string type{accessor["type"]}; json bufferView = JSON["bufferViews"][buffViewInd]; unsigned int byteOffset{bufferView["byteOffset"]}; unsigned int numPerVert; if (type == "SCALAR") numPerVert = 1; else if (type == "VEC2") numPerVert = 2; else if (type == "VEC3") numPerVert = 3; else if (type == "VEC4") numPerVert = 4; else throw std::invalid_argument("Invalid type (not SCALAR, VEC2, VEC3, VEC4)"); unsigned int beginningOfData{byteOffset + accByteOffset}; unsigned int lengthOfData{count * 4 * numPerVert}; for (unsigned int i{beginningOfData}; i < beginningOfData + lengthOfData; i) { unsigned char bytes[]{data[i++], data[i++], data[i++], data[i++]}; float value; std::memcpy(&value, bytes, sizeof(float)); floatVec.push_back(value); } return floatVec; } std::vector<GLuint> Model::getIndices(json accessor) { std::vector<GLuint> indices; unsigned int buffViewInd = accessor.value("bufferView", 0); unsigned int count{accessor["count"]}; unsigned int accByteOffset = accessor.value("byteOffset", 0); unsigned int componentType{accessor["componentType"]}; json bufferView = JSON["bufferViews"][buffViewInd]; unsigned int byteOffset{bufferView["byteOffset"]}; unsigned int beginningOfData{byteOffset + accByteOffset}; if (componentType == 5125) { for (unsigned int i{beginningOfData}; i < byteOffset + accByteOffset + count * 4; i) { unsigned char bytes[]{data[i++], data[i++], data[i++], data[i++]}; unsigned int value; std::memcpy(&value, bytes, sizeof(unsigned int)); indices.push_back((GLuint)value); } } else if (componentType == 5123) { for (unsigned int i{beginningOfData}; i < byteOffset + accByteOffset + count * 2; i) { unsigned char bytes[]{data[i++], data[i++]}; unsigned short value; std::memcpy(&value, bytes, sizeof(unsigned short)); indices.push_back((GLuint)value); } } else if (componentType == 5122) { for (unsigned int i{beginningOfData}; i < byteOffset + accByteOffset + count * 2; i) { unsigned char bytes[]{data[i++], data[i++]}; short value; std::memcpy(&value, bytes, sizeof(short)); indices.push_back((GLuint)value); } } return indices; } std::vector<Texture> Model::getTextures() { std::vector<Texture> textures; std::string fileStr{std::string(file)}; std::string fileDirectory{fileStr.substr(0, fileStr.find_last_of('/') + 1)}; for (unsigned int i{0}; i < JSON["images"].size(); i++) { std::string texturePath{JSON["images"][i]["uri"]}; bool skip{false}; for (unsigned int j{0}; j < loadedTexturesName.size(); j++) { if (loadedTexturesName[j] == texturePath) { textures.push_back(loadedTextures[j]); skip = true; break; } } if (!skip) { if (texturePath.find("baseColor") != std::string::npos || texturePath.find("diffuse") != std::string::npos) { Texture diffuse((fileDirectory + texturePath).c_str(), "diffuse", loadedTextures.size()); textures.push_back(diffuse); loadedTextures.push_back(diffuse); loadedTexturesName.push_back(texturePath); } else if (texturePath.find("metallicRoughness") != std::string::npos || texturePath.find("specular") != std::string::npos) { Texture specular((fileDirectory + texturePath).c_str(), "specular", loadedTextures.size()); textures.push_back(specular); loadedTextures.push_back(specular); loadedTexturesName.push_back(texturePath); } } } return textures; } std::vector<Vertex> Model::assembleVertices( std::vector<glm::vec3> positions, std::vector<glm::vec3> normals, std::vector<glm::vec2> textureUVs) { std::vector<Vertex> vertices; for (int i{0}; i < positions.size(); i++) { vertices.push_back( Vertex{ positions[i], normals[i], glm::vec3(1.0f, 1.0f, 1.0f), textureUVs[i]}); } return vertices; } std::vector<glm::vec2> Model::groupFloatsVec2(std::vector<float> floatVec) { std::vector<glm::vec2> vectors; for (int i{0}; i < floatVec.size(); i) { vectors.push_back(glm::vec2(floatVec[i++], floatVec[i++])); } return vectors; } std::vector<glm::vec3> Model::groupFloatsVec3(std::vector<float> floatVec) { std::vector<glm::vec3> vectors; for (int i{0}; i < floatVec.size(); i) { vectors.push_back(glm::vec3(floatVec[i++], floatVec[i++], floatVec[i++])); } return vectors; } std::vector<glm::vec4> Model::groupFloatsVec4(std::vector<float> floatVec) { std::vector<glm::vec4> vectors; for (int i{0}; i < floatVec.size(); i) { vectors.push_back(glm::vec4(floatVec[i++], floatVec[i++], floatVec[i++], floatVec[i++])); } return vectors; }
30.562914
127
0.647237
[ "mesh", "vector", "model" ]
6802e85da057ea436306ae3edfeb0c940ab5bd79
7,479
cpp
C++
test/ProcessEpochImpTest.cpp
asmaalrawi/geopm
e93548dfdd693a17c81163787ba467891937356d
[ "BSD-3-Clause" ]
1
2018-11-27T16:53:06.000Z
2018-11-27T16:53:06.000Z
test/ProcessEpochImpTest.cpp
asmaalrawi/geopm
e93548dfdd693a17c81163787ba467891937356d
[ "BSD-3-Clause" ]
null
null
null
test/ProcessEpochImpTest.cpp
asmaalrawi/geopm
e93548dfdd693a17c81163787ba467891937356d
[ "BSD-3-Clause" ]
1
2018-06-24T17:32:25.000Z
2018-06-24T17:32:25.000Z
/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation * * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "gtest/gtest.h" #include "gmock/gmock.h" #include "ProcessEpochImp.hpp" #include "record.hpp" #include "Exception.hpp" #include "geopm.h" #include "geopm_test.hpp" using geopm::ProcessEpochImp; using geopm::record_s; class ProcessEpochImpTest : public ::testing::Test { protected: void update_all(void); ProcessEpochImp m_process; std::vector<record_s> m_records; }; void ProcessEpochImpTest::update_all(void) { for (const auto &rec : m_records) { m_process.update(rec); } } // shorter names for the enum event types enum { REGION_ENTRY = geopm::EVENT_REGION_ENTRY, REGION_EXIT = geopm::EVENT_REGION_EXIT, EPOCH_COUNT = geopm::EVENT_EPOCH_COUNT, HINT = geopm::EVENT_HINT, }; TEST_F(ProcessEpochImpTest, epoch_count) { // default value EXPECT_DOUBLE_EQ(0, m_process.epoch_count()); // pre-epoch regions m_records = { {0.1, 0, REGION_ENTRY, 0xCAFE}, {0.2, 0, REGION_EXIT, 0xCAFE} }; update_all(); EXPECT_DOUBLE_EQ(0, m_process.epoch_count()); m_records = { {0.3, 0, EPOCH_COUNT, 0x1}, }; update_all(); EXPECT_DOUBLE_EQ(1, m_process.epoch_count()); m_records = { {0.4, 0, EPOCH_COUNT, 0x2}, }; update_all(); EXPECT_DOUBLE_EQ(2, m_process.epoch_count()); m_records = { {0.5, 0, EPOCH_COUNT, 0x4}, }; update_all(); EXPECT_DOUBLE_EQ(4, m_process.epoch_count()); } TEST_F(ProcessEpochImpTest, epoch_runtime) { // default value EXPECT_TRUE(std::isnan(m_process.last_epoch_runtime())); // pre-epoch regions m_records = { {0.1, 0, REGION_ENTRY, 0xCAFE}, {0.2, 0, REGION_EXIT, 0xCAFE} }; update_all(); EXPECT_TRUE(std::isnan(m_process.last_epoch_runtime())); // first epoch m_records = { {0.3, 0, EPOCH_COUNT, 0x0}, }; update_all(); EXPECT_TRUE(std::isnan(m_process.last_epoch_runtime())); // second epoch m_records = { {0.8, 0, EPOCH_COUNT, 0x1}, }; update_all(); EXPECT_DOUBLE_EQ(0.5, m_process.last_epoch_runtime()); } TEST_F(ProcessEpochImpTest, hint_time) { // default values EXPECT_TRUE(std::isnan(m_process.last_epoch_runtime_network())); EXPECT_TRUE(std::isnan(m_process.last_epoch_runtime_ignore())); // pre-epoch regions m_records = { {0.1, 0, REGION_ENTRY, 0xCAFE}, {0.2, 0, REGION_EXIT, 0xCAFE} }; update_all(); EXPECT_TRUE(std::isnan(m_process.last_epoch_runtime_network())); EXPECT_TRUE(std::isnan(m_process.last_epoch_runtime_ignore())); // first epoch m_records = { {0.3, 0, EPOCH_COUNT, 0x0}, }; update_all(); EXPECT_TRUE(std::isnan(m_process.last_epoch_runtime_network())); EXPECT_TRUE(std::isnan(m_process.last_epoch_runtime_ignore())); // second epoch, no hint m_records = { {0.6, 0, REGION_ENTRY, 0xBABA}, {0.7, 0, REGION_EXIT, 0xBABA}, {0.8, 0, EPOCH_COUNT, 0x1}, }; update_all(); EXPECT_NEAR(0.0, m_process.last_epoch_runtime_network(), 0.0001); EXPECT_NEAR(0.0, m_process.last_epoch_runtime_ignore(), 0.0001); // ignore region m_records = { {0.9, 0, REGION_ENTRY, 0xBABA}, {0.9, 0, HINT, GEOPM_REGION_HINT_IGNORE}, {1.1, 0, REGION_EXIT, 0xBABA}, {1.1, 0, HINT, GEOPM_REGION_HINT_UNKNOWN}, {1.2, 0, EPOCH_COUNT, 0x2}, }; update_all(); EXPECT_NEAR(0.0, m_process.last_epoch_runtime_network(), 0.0001); EXPECT_NEAR(0.2, m_process.last_epoch_runtime_ignore(), 0.0001); // network time m_records = { {1.6, 0, REGION_ENTRY, 0xBABA}, {1.6, 0, HINT, GEOPM_REGION_HINT_NETWORK}, {1.8, 0, HINT, GEOPM_REGION_HINT_UNKNOWN}, {2.0, 0, REGION_EXIT, 0xBABA}, {2.0, 0, REGION_ENTRY, 0xDADA}, {2.1, 0, REGION_EXIT, 0xDADA}, {2.2, 0, EPOCH_COUNT, 0x3}, }; update_all(); EXPECT_NEAR(0.2, m_process.last_epoch_runtime_network(), 0.0001); EXPECT_NEAR(0.0, m_process.last_epoch_runtime_ignore(), 0.0001); // hint changes within region m_records = { {2.3, 0, REGION_ENTRY, 0xFACE}, {2.3, 0, HINT, GEOPM_REGION_HINT_IGNORE}, {2.4, 0, HINT, GEOPM_REGION_HINT_COMPUTE}, {2.5, 0, HINT, GEOPM_REGION_HINT_NETWORK}, {2.6, 0, HINT, GEOPM_REGION_HINT_IGNORE}, {2.7, 0, HINT, GEOPM_REGION_HINT_NETWORK}, {2.8, 0, HINT, GEOPM_REGION_HINT_NETWORK}, {2.9, 0, HINT, GEOPM_REGION_HINT_MEMORY}, {3.0, 0, HINT, GEOPM_REGION_HINT_IGNORE}, {3.1, 0, REGION_EXIT, 0xFACE}, {3.1, 0, HINT, GEOPM_REGION_HINT_UNKNOWN}, {3.2, 0, EPOCH_COUNT, 0x4}, }; update_all(); EXPECT_NEAR(0.3, m_process.last_epoch_runtime_network(), 0.0001); EXPECT_NEAR(0.3, m_process.last_epoch_runtime_ignore(), 0.0001); // hint across epochs m_records = { {3.3, 0, HINT, GEOPM_REGION_HINT_IGNORE}, {3.4, 0, EPOCH_COUNT, 0x5}, }; update_all(); EXPECT_NEAR(0.0, m_process.last_epoch_runtime_network(), 0.0001); EXPECT_NEAR(0.1, m_process.last_epoch_runtime_ignore(), 0.0001); m_records = { {3.6, 0, EPOCH_COUNT, 0x6}, }; update_all(); EXPECT_NEAR(0.0, m_process.last_epoch_runtime_network(), 0.0001); EXPECT_NEAR(0.2, m_process.last_epoch_runtime_ignore(), 0.0001); m_records = { {3.9, 0, HINT, GEOPM_REGION_HINT_NETWORK}, {4.0, 0, HINT, GEOPM_REGION_HINT_IGNORE}, {4.1, 0, EPOCH_COUNT, 0x7}, }; update_all(); EXPECT_NEAR(0.1, m_process.last_epoch_runtime_network(), 0.0001); EXPECT_NEAR(0.4, m_process.last_epoch_runtime_ignore(), 0.0001); EXPECT_THROW(m_process.last_epoch_runtime_hint(99), geopm::Exception); EXPECT_THROW(m_process.last_epoch_runtime_hint(-1), geopm::Exception); }
31.961538
74
0.660516
[ "vector" ]
680f94129aa6ae23f3ef7fe4e1c76dbad945af1d
5,417
cpp
C++
msvcfilt.cpp
mooware/msvcfilt
713f75e60ce80fe540535cb16b338061ff745c79
[ "MIT" ]
7
2017-07-01T08:45:14.000Z
2021-08-05T02:54:24.000Z
msvcfilt.cpp
mooware/msvcfilt
713f75e60ce80fe540535cb16b338061ff745c79
[ "MIT" ]
null
null
null
msvcfilt.cpp
mooware/msvcfilt
713f75e60ce80fe540535cb16b338061ff745c79
[ "MIT" ]
4
2016-06-18T21:17:12.000Z
2018-01-06T04:38:56.000Z
#include <iostream> #include <memory> #include <regex> #include <string> #include <tuple> #include <vector> #include <cstring> #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <DbgHelp.h> using namespace std; /// The regex pattern to recognize a decorated symbol. Only a guess. static const char *DECORATED_SYMBOL_PATTERN = "\\?[a-zA-Z0-9_@?$]+"; //------------------------------------------------------------------------------ /** * This class interacts with the DbgHelp symbol handler functions. * * It is designed as a Meyers' Singleton, so that SymInitialize() will only * be called if it is actually necessary, and that SymCleanup() will be called * at the end of the program. */ class SymbolHandler { public: /// The maximum length of a symbol name in bytes static const size_t MAX_SYMBOL_NAME_LEN = MAX_SYM_NAME; /** * Undecorates a decorated symbol. * * @param symbol The symbol to undecorate * @param result Receives the result * * @return True if the symbol was undecorated, otherwise false */ bool UndecorateSymbol(const string &symbol, string &result) { DWORD res = UnDecorateSymbolName(symbol.c_str(), undecorateBuffer.get(), MAX_SYMBOL_NAME_LEN, UNDNAME_COMPLETE); bool success = (res != 0); if (success) { result = undecorateBuffer.get(); } return success; } /// Returns the singleton instance of the class static SymbolHandler &GetInstance() { static SymbolHandler instance; return instance; } private: /// True if the instance was successfully initialized bool initialized; /// Windows handle for the current process HANDLE hProc; /// Internal buffer that receives the undecorated symbols unique_ptr<char[]> undecorateBuffer; // no copy ctor, copy assignment SymbolHandler(const SymbolHandler &); SymbolHandler &operator=(const SymbolHandler &); /// Default constructor SymbolHandler() : initialized(false), hProc(0) { hProc = GetCurrentProcess(); if (SymInitialize(hProc, NULL, FALSE) == TRUE) { initialized = true; // allocate the buffer that receives the undecorated symbols undecorateBuffer.reset(new char[MAX_SYMBOL_NAME_LEN]); } } /// Destructor ~SymbolHandler() { if (initialized) { SymCleanup(hProc); } } }; //------------------------------------------------------------------------------ int main(int argc, char **argv) { // if false, the decorated name will be replaced by the undecorated name. // is set by a command line option. bool keepOldName = false; // process cmdline arguments if (argc > 1) { for (int idx = 1; idx < argc; ++idx) { if (strcmp("-help", argv[idx]) == 0 || strcmp("--help", argv[idx]) == 0) { cout << "Usage: msvcfilt [OPTIONS]..." << endl << "Searches in STDIN for Microsoft Visual C++ decorated symbol names" << endl << "and replaces them with their undecorated equivalent." << endl << endl << "Options:" << endl << "\t-help, --help\tDisplay this help and exit." << endl << "\t-keep, --keep\tDoes not replace the original, decorated symbol name." << endl << "\t \tInstead, the undecorated name will be inserted after it." << endl << endl; return 0; } else if (strcmp("-keep", argv[idx]) == 0 || strcmp("--keep", argv[idx]) == 0) { keepOldName = true; } } } // instantiate the regex pattern to search for regex pattern(DECORATED_SYMBOL_PATTERN); while (cin.good()) { // read a line string line; getline(cin, line); // for every match, store the position and length of the original text, // and the string with which it will be replaced typedef tuple<size_t, size_t, string> replacement; vector<replacement> replacement_list; // iterate through the matches, store them and prepare the undecorated name const sregex_token_iterator end; for (sregex_token_iterator it(line.begin(), line.end(), pattern); it != end; ++it) { string result; bool success = SymbolHandler::GetInstance().UndecorateSymbol(it->str(), result); if (success) { tuple_element<0, replacement>::type pos = it->first - line.begin(); tuple_element<1, replacement>::type len = it->length(); replacement_list.push_back(make_tuple(pos, len, result)); } } // now process the replacements. the vector is traversed in reverse so that // the positions in the original string stay valid. for (auto it = replacement_list.rbegin(); it != replacement_list.rend(); ++it) { // 0 : position in original string // 1 : length of text in original string // 2 : replacement string if (keepOldName) { auto insertText = get<2>(*it); insertText.insert(0, " \"", 2); insertText += '"'; line.insert(get<0>(*it) + get<1>(*it), insertText); } else { line.replace(get<0>(*it), get<1>(*it), get<2>(*it)); } } cout << line << endl; } }
28.661376
100
0.581318
[ "vector" ]
6812d81853cf02699d45081b3016ced16d0cc142
1,409
cpp
C++
perf/run_fixture.cpp
DataDog/libddwaf
51909df85ca2ac217b39636efa04b3ea0771d2db
[ "Apache-2.0", "BSD-3-Clause" ]
4
2021-09-16T15:46:57.000Z
2021-09-21T12:29:57.000Z
perf/run_fixture.cpp
DataDog/libddwaf
51909df85ca2ac217b39636efa04b3ea0771d2db
[ "Apache-2.0", "BSD-3-Clause" ]
21
2021-09-17T14:03:46.000Z
2022-03-31T21:20:57.000Z
perf/run_fixture.cpp
DataDog/libddwaf
51909df85ca2ac217b39636efa04b3ea0771d2db
[ "Apache-2.0", "BSD-3-Clause" ]
1
2021-12-21T08:38:14.000Z
2021-12-21T08:38:14.000Z
// Unless explicitly stated otherwise all files in this repository are // dual-licensed under the Apache-2.0 License or BSD-3-Clause License. // // This product includes software developed at Datadog // (https://www.datadoghq.com/). Copyright 2022 Datadog, Inc. #include <ddwaf.h> #include <iostream> #include <vector> #include "random.hpp" #include "run_fixture.hpp" #include "utils.hpp" namespace ddwaf::benchmark { run_fixture::run_fixture( ddwaf_handle handle, std::vector<ddwaf_object> &&objects) : objects_(std::move(objects)), handle_(handle) {} run_fixture::~run_fixture() { for (auto &o : objects_) { ddwaf_object_free(&o); } } bool run_fixture::set_up() { ctx_ = ddwaf_context_init(handle_, nullptr); return ctx_ != nullptr; } uint64_t run_fixture::test_main() { ddwaf_object &data = objects_[random::get() % objects_.size()]; ddwaf_result res; auto code = ddwaf_run(ctx_, &data, &res, std::numeric_limits<uint32_t>::max()); if (code < 0) { throw std::runtime_error("WAF returned " + std::to_string(code)); } if (res.timeout) { throw std::runtime_error("WAF timed-out"); } uint64_t total_runtime = res.total_runtime; ddwaf_result_free(&res); return total_runtime; } void run_fixture::tear_down() { if (ctx_ != nullptr) { ddwaf_context_destroy(ctx_); } } } // namespace ddwaf::benchmark
22.725806
75
0.676366
[ "vector" ]
6819dcca6e62188bb91125a078d68aaff719b561
2,531
cc
C++
src/planet.cc
timsliu/pycli
a72777915d5eef28c12e3846fb4b32e21fab59f4
[ "MIT" ]
4
2021-01-17T06:10:54.000Z
2021-01-24T10:10:13.000Z
src/planet.cc
MicahRCM/pycli
a72777915d5eef28c12e3846fb4b32e21fab59f4
[ "MIT" ]
null
null
null
src/planet.cc
MicahRCM/pycli
a72777915d5eef28c12e3846fb4b32e21fab59f4
[ "MIT" ]
1
2021-01-24T10:10:46.000Z
2021-01-24T10:10:46.000Z
/* * Implementation of planet class. The planet class describes the * surface of the planet, the planet discretization, and the temperature. * */ #include <iostream> #include <cmath> #include <fstream> #include <iomanip> #include "planet.h" using namespace std; // constructor for a new planet Planet::Planet(vector<vector<SurfaceType>> &surface, map<string, double> &atmosphere): _longCells(surface[0].size()), _latCells(surface.size()), _surface(surface), _atmosphere(atmosphere), _cellLongDegrees(LONG_RANGE/static_cast<double>(_longCells)), _cellLatDegrees(LAT_RANGE/static_cast<double>(_latCells)), _radIn(_latCells){ // create empty vector for temperatures for (size_t i = 0; i < _latCells; i ++ ) { vector<double> latTemps(_longCells); _temperature.push_back(latTemps); } // call function to fill in the incoming radiation vector calcRadIn(); } // calculate the radiation at each cell void Planet::calcRadIn() { for (size_t i = 0; i < _latCells/2; i++ ) { double topBorderRad = (90 - i * _cellLatDegrees) * PI/180; double botBorderRad = (90 - (i + 1) * _cellLatDegrees) * PI/180; double rSq = _planetRadius * _planetRadius; double topBorderM = _planetRadius * sin(topBorderRad); double botBorderM = _planetRadius * sin(botBorderRad); double interceptedArea = calcFluxAntideri(topBorderM) - calcFluxAntideri(botBorderM); double surfaceArea = 2 * PI * rSq * (sin(topBorderRad) - sin(botBorderRad)); double _radInLat = W_SUN * interceptedArea/surfaceArea; _radIn[i] = _radInLat; } // radiation in is mirrored above and below the equator size_t j = 0; for (size_t i = _latCells/2; i < _latCells; i++) { _radIn[i] = _radIn[_latCells/2 - 1 - j]; j++; } } double Planet::calcFluxAntideri(double x) { double xSq = x * x; double rSq = _planetRadius * _planetRadius; if (abs((x - _planetRadius)/x) < 0.00001 ) { return rSq * PI/2; } double termOne = x * sqrt(rSq - xSq); double termTwo = rSq * atan(termOne/(xSq - rSq)); return termOne - termTwo; } void Planet::printPlanet(ofstream& outFile) { for (size_t i = 0; i < _latCells; i++) { for (size_t j = 0; j < _longCells; j++) { outFile << " " << setprecision(3) << _temperature[i][j] << " "; } outFile << endl; } } void Planet::setAverageTemp(float temp) { _averageTemp = temp; }
27.215054
92
0.631766
[ "vector" ]
681de67d888aa07dadbe2652cc069dbade17192e
2,453
hpp
C++
include/estimator/body_estimator.hpp
gaoxiangluke/cheetah_inekf_realtime
42529cfa5d08bb6eca3e731f261dc36d8aa633c3
[ "MIT" ]
7
2021-11-27T20:18:29.000Z
2022-03-23T05:56:08.000Z
include/estimator/body_estimator.hpp
gaoxiangluke/cheetah_inekf_realtime
42529cfa5d08bb6eca3e731f261dc36d8aa633c3
[ "MIT" ]
4
2021-12-04T10:50:27.000Z
2022-03-01T18:39:08.000Z
include/estimator/body_estimator.hpp
gaoxiangluke/cheetah_inekf_realtime
42529cfa5d08bb6eca3e731f261dc36d8aa633c3
[ "MIT" ]
4
2022-01-09T22:40:17.000Z
2022-03-18T14:35:47.000Z
#pragma once #ifndef BODYESTIMATOR_H #define BODYESTIMATOR_H #include <Eigen/Dense> #include <vector> #include "ros/ros.h" #include "utils/cheetah_data_t.hpp" #include "system/cheetah_state.hpp" #include "InEKF.h" #include <lcm/lcm-cpp.hpp> #include "communication/lcm-types/cheetah_inekf_lcm/pose_t.hpp" #include "geometry_msgs/Point.h" #include "nav_msgs/Path.h" // #include "visualization_msgs/MarkerArray.h" // #include "inekf_msgs/State.h" class BodyEstimator { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW BodyEstimator(lcm::LCM* lcm); bool enabled(); void enableFilter(); void disable(); bool biasInitialized(); void initBias(cheetah_lcm_packet_t& cheetah_data); // void initState(); void initState(const double t, const cheetah_lcm_packet_t& cheetah_data, const CheetahState& state); void setContacts(CheetahState& state); void update(cheetah_lcm_packet_t& cheetah_data, CheetahState& state); void correctKinematics(CheetahState& state); inekf::InEKF getFilter() const; inekf::RobotState getState() const; void publishMarkers(double time, std::string map_frame_id, uint32_t seq); void publishPath(); void publishPose(double time, std::string map_frame_id, uint32_t seq); private: // LCM related lcm::LCM* lcm_; std::string LCM_POSE_CHANNEL; // ROS related ros::Publisher visualization_pub_; std::vector<geometry_msgs::PoseStamped> poses_; // inekf related inekf::InEKF filter_; bool enabled_ = false; bool bias_initialized_ = false; bool static_bias_initialization_ = false; bool estimator_debug_enabled_ = false; bool lcm_publish_visualization_markers_ = false; std::vector<Eigen::Matrix<double,6,1>,Eigen::aligned_allocator<Eigen::Matrix<double,6,1>>> bias_init_vec_; Eigen::Vector3d bg0_ = Eigen::Vector3d::Zero(); Eigen::Vector3d ba0_ = Eigen::Vector3d::Zero(); double t_prev_; uint32_t seq_; Eigen::Matrix<double,6,1> imu_prev_; const Eigen::Matrix<double,12,12> encoder_cov_ = 0.0174533*0.0174533 * Eigen::Matrix<double,12,12>::Identity(); // 1 deg std dev const Eigen::Matrix<double,3,3> prior_kinematics_cov_ = 0.05*0.05 * Eigen::Matrix<double,3,3>::Identity(); // 5 cm std Adds to FK covariance }; #endif // BODYESTIMATOR_H
38.936508
148
0.679984
[ "vector" ]
681f8075e8656edef1f7d985c044188a1b79898f
6,728
cc
C++
src/ui/a11y/lib/semantics/tests/semantics_integration_test_fixture.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
src/ui/a11y/lib/semantics/tests/semantics_integration_test_fixture.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
src/ui/a11y/lib/semantics/tests/semantics_integration_test_fixture.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/ui/a11y/lib/semantics/tests/semantics_integration_test_fixture.h" #include <fuchsia/ui/input/accessibility/cpp/fidl.h> #include <fuchsia/ui/policy/cpp/fidl.h> #include <lib/fdio/spawn.h> #include <lib/fidl/cpp/binding.h> #include <lib/ui/scenic/cpp/view_token_pair.h> #include <lib/zx/clock.h> #include <lib/zx/time.h> #include <zircon/status.h> #include <vector> #include "src/lib/syslog/cpp/logger.h" namespace accessibility_test { namespace { constexpr zx::duration kTimeout = zx::sec(60); // Helper class to retrieve a view's koid which can be used to construct its ViewRef. // // Implements a |fuchsia::ui::input::accessibility::PointerEventListener| that // gets called for all pointer events. It extracts the view's koid from the event // while consuming them. class KoidListener : public fuchsia::ui::input::accessibility::PointerEventListener { public: void set_events(fuchsia::ui::input::accessibility::PointerEventListener::EventSender_* events) { events_ = events; } zx_koid_t koid() const { return koid_; } private: // |fuchsia::ui::input::accessibility::PointerEventListener| void OnEvent(fuchsia::ui::input::accessibility::PointerEvent pointer_event) override { if (pointer_event.has_viewref_koid()) { koid_ = pointer_event.viewref_koid(); } // Consume everything. FX_CHECK(pointer_event.has_phase()); if (pointer_event.phase() == fuchsia::ui::input::PointerEventPhase::ADD) { FX_CHECK(pointer_event.has_device_id()); FX_CHECK(pointer_event.has_pointer_id()); events_->OnStreamHandled(pointer_event.device_id(), pointer_event.pointer_id(), fuchsia::ui::input::accessibility::EventHandling::CONSUMED); } } fuchsia::ui::input::accessibility::PointerEventListener::EventSender_* events_ = nullptr; zx_koid_t koid_ = ZX_KOID_INVALID; }; // Copied from web_runner_pixel_tests.cc: // // Invokes the input tool for input injection. // See src/ui/tools/input/README.md or `input --help` for usage details. // Commands used here: // * tap <x> <y> (scaled out of 1000) void Input(std::vector<const char*> args) { // start with proc name, end with nullptr args.insert(args.begin(), "input"); args.push_back(nullptr); zx_handle_t proc; zx_status_t status = fdio_spawn(ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL, "/bin/input", args.data(), &proc); FX_CHECK(status == ZX_OK) << "fdio_spawn: " << zx_status_get_string(status); status = zx_object_wait_one(proc, ZX_PROCESS_TERMINATED, (zx::clock::get_monotonic() + kTimeout).get(), nullptr); FX_CHECK(status == ZX_OK) << "zx_object_wait_one: " << zx_status_get_string(status); zx_info_process_t info; status = zx_object_get_info(proc, ZX_INFO_PROCESS, &info, sizeof(info), nullptr, nullptr); FX_CHECK(status == ZX_OK) << "zx_object_get_info: " << zx_status_get_string(status); FX_CHECK(info.return_code == 0) << info.return_code; } } // namespace SemanticsIntegrationTest::SemanticsIntegrationTest(const std::string& environment_label) : environment_label_(environment_label), component_context_(sys::ComponentContext::Create()), view_manager_(std::make_unique<a11y::SemanticTreeServiceFactory>(), component_context_->outgoing()->debug_dir()), scenic_(component_context_->svc()->Connect<fuchsia::ui::scenic::Scenic>()) { scenic_.set_error_handler([](zx_status_t status) { FAIL() << "Lost connection to Scenic: " << zx_status_get_string(status); }); // Wait for scenic to get initialized by calling GetDisplayInfo. scenic_->GetDisplayInfo([this](fuchsia::ui::gfx::DisplayInfo info) { QuitLoop(); }); RunLoopWithTimeout(kTimeout); } void SemanticsIntegrationTest::SetUp() { TestWithEnvironment::SetUp(); // This is done in |SetUp| as opposed to the constructor to allow subclasses the opportunity to // override |CreateServices()|. auto services = TestWithEnvironment::CreateServices(); services->AddService(semantics_manager_bindings_.GetHandler(&view_manager_)); CreateServices(services); environment_ = CreateNewEnclosingEnvironment(environment_label_, std::move(services), {.inherit_parent_services = true}); } fuchsia::ui::views::ViewToken SemanticsIntegrationTest::CreatePresentationViewToken() { auto [view_token, view_holder_token] = scenic::ViewTokenPair::New(); auto presenter = real_services()->Connect<fuchsia::ui::policy::Presenter>(); presenter.set_error_handler( [](zx_status_t status) { FAIL() << "presenter: " << zx_status_get_string(status); }); presenter->PresentView(std::move(view_holder_token), nullptr); return std::move(view_token); } zx_koid_t SemanticsIntegrationTest::WaitForKoid() { // There are a few alternatives as to how to do this, of which tapping and intercepting is one. // // Another is to fake out Scenic. However, // * Chromium registers two views with Scenic, only one of which registers with accessibility. // * The dance between Scenic and runners can be pretty complex (e.g. initialization and // dimensioning), any part of which might result in the runner bailing. It's fragile to try to // fake this. // // Another is to add test-only methods to semantics manager, but this is also subject to the // initialization fidelity concerns unless a real Scenic is used anyway. // TODO(fxb/49011): Use ViewProvider::GetViewRef when available. auto pointer_event_registry = real_services()->Connect<fuchsia::ui::input::accessibility::PointerEventRegistry>(); KoidListener listener; fidl::Binding<fuchsia::ui::input::accessibility::PointerEventListener> binding(&listener); listener.set_events(&binding.events()); pointer_event_registry->Register(binding.NewBinding()); // fxb/42959: This will fail the first few times. binding.set_error_handler([&](auto) { pointer_event_registry->Register(binding.NewBinding()); }); const auto deadline = zx::clock::get_monotonic() + kTimeout; do { Input({"tap", "500", "500"}); // centered // The timing here between initializing, registering, rendering, and tapping can get pretty // messy without surefire ways of synchronizing, so rather than try to do anything clever let's // keep it simple. RunLoopWithTimeoutOrUntil([&listener] { return listener.koid() != ZX_KOID_INVALID; }); } while (listener.koid() == ZX_KOID_INVALID && zx::clock::get_monotonic() < deadline); return listener.koid(); } } // namespace accessibility_test
41.02439
99
0.722057
[ "vector" ]
68284b3341b340c7377ca9d8dcb8c6a30949a209
3,366
cpp
C++
3rdParty/boost/1.71.0/libs/algorithm/test/copy_n_test1.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
3rdParty/boost/1.71.0/libs/algorithm/test/copy_n_test1.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
3rdParty/boost/1.71.0/libs/algorithm/test/copy_n_test1.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
/* Copyright (c) Marshall Clow 2011-2012. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) For more information, see http://www.boost.org */ #include <boost/config.hpp> #include <boost/algorithm/cxx11/copy_n.hpp> #include <boost/algorithm/cxx14/equal.hpp> #include <boost/algorithm/cxx11/all_of.hpp> #include "iterator_test.hpp" #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <string> #include <iostream> #include <vector> #include <list> namespace ba = boost::algorithm; // namespace ba = boost; BOOST_CXX14_CONSTEXPR bool is_zero( int v ) { return v == 0; } template <typename Container> void test_sequence ( Container const &c ) { typedef typename Container::value_type value_type; std::vector<value_type> v; // Copy zero elements v.clear (); ba::copy_n ( c.begin (), 0, back_inserter ( v )); BOOST_CHECK ( v.size () == 0 ); ba::copy_n ( c.begin (), 0U, back_inserter ( v )); BOOST_CHECK ( v.size () == 0 ); if ( c.size () > 0 ) { // Just one element v.clear (); ba::copy_n ( c.begin (), 1, back_inserter ( v )); BOOST_CHECK ( v.size () == 1 ); BOOST_CHECK ( v[0] == *c.begin ()); v.clear (); ba::copy_n ( c.begin (), 1U, back_inserter ( v )); BOOST_CHECK ( v.size () == 1 ); BOOST_CHECK ( v[0] == *c.begin ()); // Half the elements v.clear (); ba::copy_n ( c.begin (), c.size () / 2, back_inserter ( v )); BOOST_CHECK ( v.size () == c.size () / 2); BOOST_CHECK ( std::equal ( v.begin (), v.end (), c.begin ())); // Half the elements + 1 v.clear (); ba::copy_n ( c.begin (), c.size () / 2 + 1, back_inserter ( v )); BOOST_CHECK ( v.size () == c.size () / 2 + 1 ); BOOST_CHECK ( std::equal ( v.begin (), v.end (), c.begin ())); // All the elements v.clear (); ba::copy_n ( c.begin (), c.size (), back_inserter ( v )); BOOST_CHECK ( v.size () == c.size ()); BOOST_CHECK ( std::equal ( v.begin (), v.end (), c.begin ())); } } BOOST_CXX14_CONSTEXPR inline bool test_constexpr() { const size_t sz = 64; int in_data[sz] = {0}; bool res = true; const int* from = in_data; const int* to = in_data + sz; int out_data[sz] = {0}; int* out = out_data; out = ba::copy_n ( from, 0, out ); // Copy none res = (res && out == out_data && ba::all_of(out, out + sz, is_zero)); out = ba::copy_n ( from, sz, out ); // Copy all res = (res && out == out_data + sz && ba::equal( input_iterator<const int *>(out_data), input_iterator<const int *>(out_data + sz), input_iterator<const int *>(from), input_iterator<const int *>(to))); return res; } void test_sequence1 () { std::vector<int> v; for ( int i = 5; i < 15; ++i ) v.push_back ( i ); test_sequence ( v ); BOOST_CXX14_CONSTEXPR bool constexpr_res = test_constexpr(); BOOST_CHECK(constexpr_res); std::list<int> l; for ( int i = 25; i > 15; --i ) l.push_back ( i ); test_sequence ( l ); } BOOST_AUTO_TEST_CASE( test_main ) { test_sequence1 (); }
28.285714
109
0.559121
[ "vector" ]
682c5168318937974c6d8fb847542df49778be3c
4,318
cpp
C++
Graph/SpaceSmugglers_msp.cpp
Satyabrat35/Programming
841ead1bf847b567d8e21963673413cbd65277f4
[ "Apache-2.0" ]
null
null
null
Graph/SpaceSmugglers_msp.cpp
Satyabrat35/Programming
841ead1bf847b567d8e21963673413cbd65277f4
[ "Apache-2.0" ]
null
null
null
Graph/SpaceSmugglers_msp.cpp
Satyabrat35/Programming
841ead1bf847b567d8e21963673413cbd65277f4
[ "Apache-2.0" ]
null
null
null
/**************erik****************/ #include<bits/stdc++.h> #include <cstdio> #include <iostream> #include <algorithm> using namespace std; typedef long long int ll; typedef unsigned long long int ull; //map<int,int> mp1; //set<int> s1; //set<int>::iterator it; #define maxm(a,b,c) max(a,max(c,b)) #define minm(a,b,c) min(a,min(c,b)) #define f(i,n) for(int i=1;i<n;i++) #define rf(i,n) for(int i=n-1;i>=0;i--) const int MAX = 100005; vector<pair<ll,int> > vec[MAX],vecd[MAX]; ll dist[MAX],dist2[MAX],dist3[MAX],dist4[MAX]; bool vis[MAX]; void initialize(int n){ for(int i=1;i<=n;i++){ vis[i]=0; } } void dijkstra(int source){ memset(vis, false , sizeof vis); dist[source] = 0; multiset < pair < ll , int > > s; s.insert({0 , source}); while(!s.empty()){ pair <ll , int> p = *s.begin(); s.erase(s.begin()); int x = p.second; if( vis[x] ) continue; vis[x] = true; for(int i = 0; i < vec[x].size(); i++){ int e = vec[x][i].second; ll w = vec[x][i].first; if(dist[x] + w < dist[e] ){ dist[e] = dist[x] + w; s.insert({dist[e], e} ); } } } } void dijkstra2(int source){ memset(vis, false , sizeof vis); dist2[source] = 0; multiset < pair < ll , int > > s; s.insert({0 , source}); while(!s.empty()){ pair <ll , int> p = *s.begin(); s.erase(s.begin()); int x = p.second; //int wei = p.first; if( vis[x] ) continue; vis[x] = true; for(int i = 0; i < vecd[x].size(); i++){ int e = vecd[x][i].second; ll w = vecd[x][i].first; if(dist2[x] + w < dist2[e] ){ dist2[e] = dist2[x] + w; s.insert({dist2[e], e} ); } } } } void dijkstra3(int source){ memset(vis, false , sizeof vis); dist3[source] = 0; multiset < pair < ll , int > > s; s.insert({0 , source}); while(!s.empty()){ pair <ll , int> p = *s.begin(); s.erase(s.begin()); int x = p.second; //int wei = p.first; if( vis[x] ) continue; vis[x] = true; for(int i = 0; i < vec[x].size(); i++){ int e = vec[x][i].second; ll w = vec[x][i].first; if(dist3[x] + w < dist3[e] ){ dist3[e] = dist3[x] + w; s.insert({dist3[e], e} ); } } } } void dijkstra4(int source){ memset(vis, false , sizeof vis); dist4[source] = 0; multiset < pair < ll , int > > s; s.insert({0 , source}); while(!s.empty()){ pair <int , int> p = *s.begin(); s.erase(s.begin()); int x = p.second; if( vis[x] ) continue; vis[x] = true; for(int i = 0; i < vecd[x].size(); i++){ int e = vecd[x][i].second; ll w = vecd[x][i].first; if(dist4[x] + w < dist4[e] ){ dist4[e] = dist4[x] + w; s.insert({dist4[e], e} ); } } } } int main() { int n,m,source,dest; cin>>n>>m>>source>>dest; for(int i=1;i<=n+2;i++){ vis[i]=0; dist[i]=1e9; dist2[i]=1e9; dist3[i]=1e9; dist4[i]=1e9; } for(int i=0;i<m;i++){ int x,y; ll wgt; cin>>x>>y>>wgt; vec[x].push_back(make_pair(wgt,y)); vecd[y].push_back(make_pair(wgt,x)); } dijkstra(source); dijkstra2(dest); dijkstra3(dest); dijkstra4(source); ll mn = 1e9; for(int i=1;i<=n;i++){ if(i!=source && i!=dest){ //cout<<i<<' '<<dist[source]<<' '<<dist4[source]<<' '<<dist2[dest]<<' '<<dist3[dest]<<endl; mn = min(mn, dist[i] + dist4[i] + dist2[i] + dist3[i]); } } if(mn == 1e9){ cout<<"-1"; } else { cout<<mn; } return 0; }
28.596026
103
0.407365
[ "vector" ]
682f2e5223bd283c233f5f8ae1a1ffdc4a9cf8de
4,642
cc
C++
src/daemon/entry/cri/naming.cc
Mu-L/iSulad
e16bae200141db99ba212bd1181d344b93347914
[ "MulanPSL-1.0" ]
34
2020-03-09T11:57:08.000Z
2022-03-29T12:18:33.000Z
src/daemon/entry/cri/naming.cc
Mu-L/iSulad
e16bae200141db99ba212bd1181d344b93347914
[ "MulanPSL-1.0" ]
null
null
null
src/daemon/entry/cri/naming.cc
Mu-L/iSulad
e16bae200141db99ba212bd1181d344b93347914
[ "MulanPSL-1.0" ]
8
2020-03-21T02:36:22.000Z
2021-11-13T18:15:43.000Z
/****************************************************************************** * Copyright (c) Huawei Technologies Co., Ltd. 2017-2019. All rights reserved. * iSulad licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR * PURPOSE. * See the Mulan PSL v2 for more details. * Author: tanyifeng * Create: 2017-11-22 * Description: provide naming functions *********************************************************************************/ #include "naming.h" #include <iostream> #include <vector> #include <sstream> #include <string> #include <errno.h> #include "cri_constants.h" #include "cri_helpers.h" #include "isula_libutils/log.h" #include "utils.h" namespace CRINaming { std::string MakeSandboxName(const runtime::v1alpha2::PodSandboxMetadata &metadata) { std::string sname; sname.append(CRI::Constants::kubePrefix); sname.append(CRI::Constants::nameDelimiter); sname.append(CRI::Constants::sandboxContainerName); sname.append(CRI::Constants::nameDelimiter); sname.append(metadata.name()); sname.append(CRI::Constants::nameDelimiter); sname.append(metadata.namespace_()); sname.append(CRI::Constants::nameDelimiter); sname.append(metadata.uid()); sname.append(CRI::Constants::nameDelimiter); sname.append(std::to_string(metadata.attempt())); return sname; } void ParseSandboxName(const google::protobuf::Map<std::string, std::string> &annotations, runtime::v1alpha2::PodSandboxMetadata &metadata, Errors &err) { if (annotations.count(CRIHelpers::Constants::SANDBOX_NAME_ANNOTATION_KEY) == 0) { err.Errorf("annotation don't contains the sandbox name, failed to parse it"); return; } if (annotations.count(CRIHelpers::Constants::SANDBOX_NAMESPACE_ANNOTATION_KEY) == 0) { err.Errorf("annotation don't contains the sandbox namespace, failed to parse it"); return; } if (annotations.count(CRIHelpers::Constants::SANDBOX_UID_ANNOTATION_KEY) == 0) { err.Errorf("annotation don't contains the sandbox uid, failed to parse it"); return; } if (annotations.count(CRIHelpers::Constants::SANDBOX_ATTEMPT_ANNOTATION_KEY) == 0) { err.Errorf("annotation don't contains the sandbox attempt, failed to parse it"); return; } metadata.set_name(annotations.at(CRIHelpers::Constants::SANDBOX_NAME_ANNOTATION_KEY)); metadata.set_namespace_(annotations.at(CRIHelpers::Constants::SANDBOX_NAMESPACE_ANNOTATION_KEY)); metadata.set_uid(annotations.at(CRIHelpers::Constants::SANDBOX_UID_ANNOTATION_KEY)); auto sandboxAttempt = annotations.at(CRIHelpers::Constants::SANDBOX_ATTEMPT_ANNOTATION_KEY); metadata.set_attempt(static_cast<google::protobuf::uint32>(std::stoul(sandboxAttempt))); } std::string MakeContainerName(const runtime::v1alpha2::PodSandboxConfig &s, const runtime::v1alpha2::ContainerConfig &c) { std::string sname; sname.append(CRI::Constants::kubePrefix); sname.append(CRI::Constants::nameDelimiter); sname.append(c.metadata().name()); sname.append(CRI::Constants::nameDelimiter); sname.append(s.metadata().name()); sname.append(CRI::Constants::nameDelimiter); sname.append(s.metadata().namespace_()); sname.append(CRI::Constants::nameDelimiter); sname.append(s.metadata().uid()); sname.append(CRI::Constants::nameDelimiter); sname.append(std::to_string(c.metadata().attempt())); return sname; } void ParseContainerName(const google::protobuf::Map<std::string, std::string> &annotations, runtime::v1alpha2::ContainerMetadata *metadata, Errors &err) { if (annotations.count(CRIHelpers::Constants::CONTAINER_NAME_ANNOTATION_KEY) == 0) { err.Errorf("annotation don't contains the container name, failed to parse it"); return; } metadata->set_name(annotations.at(CRIHelpers::Constants::CONTAINER_NAME_ANNOTATION_KEY)); std::string containerAttempt = "0"; if (annotations.count(CRIHelpers::Constants::CONTAINER_ATTEMPT_ANNOTATION_KEY) != 0) { containerAttempt = annotations.at(CRIHelpers::Constants::CONTAINER_ATTEMPT_ANNOTATION_KEY); } metadata->set_attempt(static_cast<google::protobuf::uint32>(std::stoul(containerAttempt))); } } // namespace CRINaming
40.719298
120
0.69776
[ "vector" ]
683032244c607386dcb2fd3bccd68859ff3889d1
2,293
cc
C++
industry-brain/src/model/AsyncResponsePostRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
industry-brain/src/model/AsyncResponsePostRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
industry-brain/src/model/AsyncResponsePostRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/industry-brain/model/AsyncResponsePostRequest.h> using AlibabaCloud::Industry_brain::Model::AsyncResponsePostRequest; AsyncResponsePostRequest::AsyncResponsePostRequest() : RpcServiceRequest("industry-brain", "2019-06-29", "AsyncResponsePost") { setMethod(HttpRequest::Method::Post); } AsyncResponsePostRequest::~AsyncResponsePostRequest() {} std::string AsyncResponsePostRequest::getData()const { return data_; } void AsyncResponsePostRequest::setData(const std::string& data) { data_ = data; setParameter("Data", data); } std::string AsyncResponsePostRequest::getContext()const { return context_; } void AsyncResponsePostRequest::setContext(const std::string& context) { context_ = context; setParameter("Context", context); } float AsyncResponsePostRequest::getProgress()const { return progress_; } void AsyncResponsePostRequest::setProgress(float progress) { progress_ = progress; setParameter("Progress", std::to_string(progress)); } std::string AsyncResponsePostRequest::getMessage()const { return message_; } void AsyncResponsePostRequest::setMessage(const std::string& message) { message_ = message; setParameter("Message", message); } std::string AsyncResponsePostRequest::getTaskId()const { return taskId_; } void AsyncResponsePostRequest::setTaskId(const std::string& taskId) { taskId_ = taskId; setParameter("TaskId", taskId); } std::string AsyncResponsePostRequest::getStatus()const { return status_; } void AsyncResponsePostRequest::setStatus(const std::string& status) { status_ = status; setParameter("Status", status); }
23.885417
75
0.743131
[ "model" ]
683b5f3741249517afc46f143b5f43db896c5746
1,995
cpp
C++
aws-cpp-sdk-medialive/source/model/InputLossImageType.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-medialive/source/model/InputLossImageType.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-medialive/source/model/InputLossImageType.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/medialive/model/InputLossImageType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace MediaLive { namespace Model { namespace InputLossImageTypeMapper { static const int COLOR_HASH = HashingUtils::HashString("COLOR"); static const int SLATE_HASH = HashingUtils::HashString("SLATE"); InputLossImageType GetInputLossImageTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == COLOR_HASH) { return InputLossImageType::COLOR; } else if (hashCode == SLATE_HASH) { return InputLossImageType::SLATE; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<InputLossImageType>(hashCode); } return InputLossImageType::NOT_SET; } Aws::String GetNameForInputLossImageType(InputLossImageType enumValue) { switch(enumValue) { case InputLossImageType::COLOR: return "COLOR"; case InputLossImageType::SLATE: return "SLATE"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace InputLossImageTypeMapper } // namespace Model } // namespace MediaLive } // namespace Aws
28.098592
92
0.619048
[ "model" ]
683dc3e9b849c18c6d9090d309f1dc19e1ea646d
15,052
cpp
C++
sources/calibn/tmp/calibcam.cpp
SimonsRoad/seq2map
cc8cd20842b3c6db01f73d2e6ecf543189e56891
[ "BSD-3-Clause" ]
null
null
null
sources/calibn/tmp/calibcam.cpp
SimonsRoad/seq2map
cc8cd20842b3c6db01f73d2e6ecf543189e56891
[ "BSD-3-Clause" ]
null
null
null
sources/calibn/tmp/calibcam.cpp
SimonsRoad/seq2map
cc8cd20842b3c6db01f73d2e6ecf543189e56891
[ "BSD-3-Clause" ]
1
2018-11-01T13:11:39.000Z
2018-11-01T13:11:39.000Z
#include <calibn/calibcam.hpp> #include <calibn/helpers.hpp> #include <stdio.h> using namespace std; using namespace cv; size_t CalibIntrinsics::NumParameters = 9; // fc,fu,uc,vc,k1,k2,p1,p2,k3 size_t CalibExtrinsics::NumParameters = 6; // rx,ry,rz,tx,ty,tz CalibBundleParams CalibBundleParams::NullParams(0,0); TermCriteria Calibratable::OptimTermCriteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 30, 1e-3); std::vector<double> CalibIntrinsics::ToVector() const { Mat K = CameraMatrix, D = DistortionMatrix; vector<double> vec(NumParameters); assert(K.size() == Size(3,3) && D.size() == Size(5,1)); size_t i = 0; vec[i++] = K.at<double>(0,0); // fu vec[i++] = K.at<double>(1,1); // fv vec[i++] = K.at<double>(0,2); // uc vec[i++] = K.at<double>(1,2); // uv vec[i++] = D.at<double>(0,0); // kappa1 vec[i++] = D.at<double>(0,1); // kappa2 vec[i++] = D.at<double>(0,2); // p1 vec[i++] = D.at<double>(0,3); // p2 vec[i++] = D.at<double>(0,4); // kappa3 return vec; } bool CalibIntrinsics::FromVector(const std::vector<double>& vec) { if (vec.size() != NumParameters) { return false; } Mat& K = CameraMatrix; Mat& D = DistortionMatrix; assert(K.size() == Size(3,3) && D.size() == Size(5,1)); size_t i = 0; K.at<double>(0,0) = vec[i++]; // fu K.at<double>(1,1) = vec[i++]; // fv K.at<double>(0,2) = vec[i++]; // uc K.at<double>(1,2) = vec[i++]; // vu D.at<double>(0,0) = vec[i++]; // kappa1 D.at<double>(0,1) = vec[i++]; // kappa2 D.at<double>(0,2) = vec[i++]; // p1 D.at<double>(0,3) = vec[i++]; // p2 D.at<double>(0,4) = vec[i++]; // kappa3 return true; } bool CalibIntrinsics::Write(FileStorage& fn) const { vector<double> vec = ToVector(); fn << "focalLength" << vector<double>(vec.begin() + 0, vec.begin() + 2); fn << "imageCentre" << vector<double>(vec.begin() + 2, vec.begin() + 4); fn << "distCoeffs" << vector<double>(vec.begin() + 4, vec.end()); return true; } std::vector<double> CalibExtrinsics::ToVector() const { Mat R = Rotation; Mat t = Translation; vector<double> vec(NumParameters); assert(R.size() == Size(3,3) && t.size() == Size(1,3)); Mat a; Rodrigues(R,a); // to angle-axis representation size_t i = 0; vec[i++] = a.at<double>(0,0); // ax vec[i++] = a.at<double>(1,0); // ay vec[i++] = a.at<double>(2,0); // az vec[i++] = t.at<double>(0,0); // tx vec[i++] = t.at<double>(1,0); // ty vec[i++] = t.at<double>(2,0); // tz return vec; } bool CalibExtrinsics::FromVector(const vector<double>& vec) { if (vec.size() != NumParameters) { return false; } Mat& R = Rotation; Mat& t = Translation; Mat a = Mat(3, 1, CV_64F); assert(R.size() == Size(3,3) && t.size() == Size(1,3)); size_t i = 0; a.at<double>(0,0) = vec[i++]; // ax a.at<double>(1,0) = vec[i++]; // ay a.at<double>(2,0) = vec[i++]; // az t.at<double>(0,0) = vec[i++]; // tx t.at<double>(1,0) = vec[i++]; // ty t.at<double>(2,0) = vec[i++]; // tz Rodrigues(a,R); // to matrix representation return true; } Mat CalibExtrinsics::GetMatrix4x4() const { Mat M = Mat::eye(4, 4, Rotation.type()); Rotation.copyTo(M.rowRange(0,3).colRange(0,3)); Translation.copyTo(M.rowRange(0,3).colRange(3,4)); return M; } bool CalibExtrinsics::Write(FileStorage& fn) const { vector<double> vec = ToVector(); fn << "rotation" << vector<double>(vec.begin() + 0, vec.begin() + 3); fn << "translation" << vector<double>(vec.begin() + 3, vec.begin() + 6); return true; } void CalibBundleParams::Create(size_t numCams, size_t refCamIdx) { m_numCams = numCams; m_refCamIdx = refCamIdx; } std::vector<double> CalibBundleParams::ToVector() const { assert(m_numCams == Intrinsics.size() && m_numCams == Extrinsics.size()); size_t m = Intrinsics.size(); size_t n = Extrinsics.size() - 1; size_t k = ImagePoses.size(); size_t d = m * CalibIntrinsics::NumParameters + (n + k) * CalibExtrinsics::NumParameters; std::vector<double> vec; for (CalibIntrinsicsList::const_iterator itr = Intrinsics.begin(); itr != Intrinsics.end(); itr++) { append(vec, itr->ToVector()); } CalibExtrinsicsList extrinsicsPoses; // extrinsics + image poses extrinsicsPoses.reserve((n + k) * CalibExtrinsics::NumParameters); // add all extrinsics excluding the reference camera's one because it's always identity append(extrinsicsPoses, Extrinsics); extrinsicsPoses.erase(extrinsicsPoses.begin() + m_refCamIdx); // add all image poses afterwards append(extrinsicsPoses, ImagePoses); // append all extrinsics (camera extrinsics + image extrinsics) for (CalibExtrinsicsList::const_iterator itr = extrinsicsPoses.begin(); itr != extrinsicsPoses.end(); itr++) { append(vec, itr->ToVector()); } assert (vec.size() == d); // size check return vec; } bool CalibBundleParams::FromVector(const vector<double>& vec) { size_t m = m_numCams; size_t n = m - 1; size_t k = (vec.size() - m * CalibIntrinsics::NumParameters - n * CalibExtrinsics::NumParameters) / CalibExtrinsics::NumParameters; size_t d = m * CalibIntrinsics::NumParameters + (n + k) * CalibExtrinsics::NumParameters; assert (vec.size() == d); // size check Intrinsics = CalibIntrinsicsList(m); CalibExtrinsicsList extrinsicsPoses = CalibExtrinsicsList(n+k); vector<double>::const_iterator v = vec.begin(); for (CalibIntrinsicsList::iterator itr = Intrinsics.begin(); itr != Intrinsics.end(); itr++) { if (!itr->FromVector(vector<double>(v, v + itr->GetSize()))) return false; v += itr->GetSize(); } for (CalibExtrinsicsList::iterator itr = extrinsicsPoses.begin(); itr != extrinsicsPoses.end(); itr++) { if (!itr->FromVector(vector<double>(v, v + itr->GetSize()))) return false; v += itr->GetSize(); } // split up extrinsics and image poses Extrinsics = CalibExtrinsicsList(extrinsicsPoses.begin(), extrinsicsPoses.begin() + n); ImagePoses = CalibExtrinsicsList(extrinsicsPoses.begin() + n, extrinsicsPoses.end()); // append an identity extrinsics of the reference camera Extrinsics.insert(Extrinsics.begin() + m_refCamIdx, CalibExtrinsics()); return true; } ImagePointList CalibBundleParams::Project(const ObjectPointList& pts3d, size_t camIdx, size_t imgIdx) const { ImagePointList y; CalibExtrinsics E = ImagePoses[imgIdx].Concatenate(Extrinsics[camIdx]); projectPoints(pts3d, E.Rotation, E.Translation, Intrinsics[camIdx].CameraMatrix, Intrinsics[camIdx].DistortionMatrix.t(), y); return y; } ImagePointList CalibBundleParams::ProjectUndistort(const ObjectPointList& pts3d, size_t camIdx, size_t imgIdx) const { return UndistortPoints(Project(pts3d, camIdx, imgIdx), camIdx); /* assert(m_rectOkay); Mat P = m_rectP[camIdx] * ImagePoses[imgIdx].GetMatrix4x4(); Mat x, y; convertPointsToHomogeneous(pts3d, x); convertPointsFromHomogeneous(P * x, y); return y; */ } ImagePointList CalibBundleParams::UndistortPoints(const ImagePointList& pts2d, size_t camIdx) const { assert(m_rectOkay); ImagePointList udst2d; undistortPoints(pts2d, udst2d, Intrinsics[camIdx].CameraMatrix, Intrinsics[camIdx].DistortionMatrix, m_rectR[camIdx], m_rectP[camIdx]); return udst2d; } bool CalibBundleParams::Store(cv::FileStorage& fn) const { size_t m = Intrinsics.size(); size_t n = Extrinsics.size(); size_t k = ImagePoses.size(); if (m != n) { return false; } fn << "{:"; fn << "cams" << "[:"; for (size_t cam = 0; cam < m; cam++) { fn << "{:" << "index" << (int) cam; if (!Intrinsics[cam].Write(fn) || !Extrinsics[cam].Write(fn)) { return false; } fn << "}"; } fn << "]"; fn << "imagePoses" << "[:"; for (size_t img = 0; img < k; img++) { fn << "{:" << "index" << (int) img; if (!ImagePoses[img].Write(fn)) { return false; } fn << "}"; } fn << "]"; fn << "}"; return true; } void CalibBundleParams::InitUndistortRectifyMaps(size_t cam0, size_t cam1, const Size& imageSize) { assert(m_numCams > 0); if (m_numCams == 1) // monocular case { InitMonocularUndistortMap(imageSize); return; } // for binocular and multinocular cases InitCollinearUndistortMaps(cam0, cam1, imageSize); } void CalibBundleParams::InitMonocularUndistortMap(const Size& imageSize) { assert(m_numCams == 1); m_rectMaps1 = vector<Mat>(1); m_rectMaps2 = vector<Mat>(1); m_rectR = vector<Mat>(1); m_rectP = vector<Mat>(1); m_rectR[0] = Mat::eye(3, 3, CV_64F); m_rectP[0] = Mat::zeros(3, 4, CV_64F); Mat K = m_rectP[0].colRange(0,3).rowRange(0,3); double alpha = 0; getOptimalNewCameraMatrix(Intrinsics[0].CameraMatrix, Intrinsics[0].DistortionMatrix, imageSize, alpha).copyTo(K); initUndistortRectifyMap( Intrinsics[0].CameraMatrix, // camera matrix Intrinsics[0].DistortionMatrix, // distortion coeffs Mat(), // rotation (identity for monocular case) K, // new camera matrix imageSize, // new image size (unchanged) CV_16SC2, // store x and y coordinates m_rectMaps1[0], // ..in one 2-channel matrix m_rectMaps2[0]); // ..interpolation coefficients? m_rectOkay = true; } void CalibBundleParams::InitCollinearUndistortMaps(size_t cam0, size_t cam1, const Size& imageSize) { m_rectMaps1 = vector<Mat>(m_numCams); m_rectMaps2 = vector<Mat>(m_numCams); m_rectR = vector<Mat>(m_numCams); m_rectP = vector<Mat>(m_numCams); assert(m_numCams > 1); CalibExtrinsics E01 = Extrinsics[cam0].GetInverse().Concatenate(Extrinsics[cam1]); // transformation from cam0 to cam1 Mat Q; Mat K0 = Intrinsics[cam0].CameraMatrix, D0 = Intrinsics[cam0].DistortionMatrix; Mat K1 = Intrinsics[cam1].CameraMatrix, D1 = Intrinsics[cam1].DistortionMatrix; double alpha = 0; int flags = CALIB_ZERO_DISPARITY; // solve stereo rectification first stereoRectify( K0, D0, K1, D1, imageSize, E01.Rotation, E01.Translation, m_rectR[cam0], m_rectR[cam1], m_rectP[cam0], m_rectP[cam1], Q, flags, alpha); //initUndistortRectifyMap(K0, D0, m_rectR[cam0], m_rectP[cam0], imageSize, CV_16SC2, m_rectMaps1[cam0], m_rectMaps2[cam0]); //initUndistortRectifyMap(K1, D1, m_rectR[cam1], m_rectP[cam1], imageSize, CV_16SC2, m_rectMaps1[cam1], m_rectMaps2[cam1]); for (size_t cam2 = 0; cam2 < m_numCams; cam2++) { Mat K2 = Intrinsics[cam2].CameraMatrix, D2 = Intrinsics[cam2].DistortionMatrix; if (cam2 != cam0 && cam2 != cam1) // do 3-view collinear rectification for each camera excepting cam0 and cam1 { CalibExtrinsics E02 = Extrinsics[cam0].GetInverse().Concatenate(Extrinsics[cam2]); // transformation from cam0 to cam1 rectify3Collinear( K0, D0, K1, D1, K2, D2, Mat(), Mat(), imageSize, E01.Rotation, E01.Translation, E02.Rotation, E02.Translation, m_rectR[cam0], m_rectR[cam1], m_rectR[cam2], m_rectP[cam0], m_rectP[cam1], m_rectP[cam2], Q, alpha, imageSize, NULL, NULL, flags); } initUndistortRectifyMap(K2, D2, m_rectR[cam2], m_rectP[cam2], imageSize, CV_16SC2, m_rectMaps1[cam2], m_rectMaps2[cam2]); } m_rectOkay = true; } Mat CalibBundleParams::Rectify(size_t camIdx, const Mat& im) const { assert(RectifyInitialised() && !m_rectMaps1[camIdx].empty() && !m_rectMaps2[camIdx].empty()); Mat imRect; remap(im, imRect, m_rectMaps1[camIdx], m_rectMaps2[camIdx], INTER_CUBIC, BORDER_CONSTANT, Scalar()); return imRect; } CalibCam::CalibCam(const FileNode& fn) { try { int index; fn["index"] >> index; SetIndex((size_t) index); FileNode dataNode = fn["data"]; for (FileNodeIterator itr = dataNode.begin(); itr != dataNode.end(); itr++) { CalibData data(*itr); if (!AddCalibData(data)) { return; } } // TODO: sort calibration data according to their indices } catch (std::exception& ex) { E_ERROR << "error restoring camera data"; E_ERROR << ex.what(); return; } } bool CalibCam::AddCalibData(CalibData& data) { if (data.IsOkay()) { if (m_imageSize == Size(0,0)) { m_imageSize = data.GetImageSize(); } else if(data.GetImageSize() != m_imageSize) { cerr << "Trying to add calibration data to a camera with inconsistent image size." << endl; cerr << "Size of added image " << data.GetImageSize().width << "x" << data.GetImageSize().height << " differs from " << m_imageSize.width << "x" << m_imageSize.height << endl; return false; } } m_data.push_back(data); return true; } double CalibCam::Calibrate() { size_t nImages = m_data.size(); m_imageIndcies.clear(); // build point correspondences std::vector<ImagePointList> imagePoints; std::vector<ObjectPointList> objectPoints; for (CalibDataSet::iterator data = m_data.begin(); data != m_data.end(); data++) { if (!data->IsOkay()) { continue; } assert(data->GetImageSize() == m_imageSize); m_imageIndcies.push_back(data->GetIndex()); imagePoints. push_back(data->GetImagePoints()); objectPoints. push_back(data->GetObjectPoints()); } if (m_imageIndcies.size() < 3) { E_ERROR << "calibration of cam #" << GetIndex() << " is not possible from " << m_imageIndcies.size() << " view(s)"; return -1; } std::vector<cv::Mat> rvecs; std::vector<cv::Mat> tvecs; // monocular calibration m_rpe = calibrateCamera( objectPoints, imagePoints, m_imageSize, m_intrinsics.CameraMatrix, m_intrinsics.DistortionMatrix, rvecs, tvecs, 0, OptimTermCriteria); // remap extrinsics m_extrinsics = CalibExtrinsicsList(m_data.size()); for (size_t i = 0; i < m_imageIndcies.size(); i++) { size_t idx = m_imageIndcies[i]; cv::Mat rmat_i; cv::Rodrigues(rvecs[i], rmat_i); m_extrinsics[idx] = CalibExtrinsics(rmat_i, tvecs[i]); } return m_rpe; } bool CalibCam::Write(FileStorage& f) const { f << "{:"; f << "index" << (int) GetIndex(); f << "data" << "[:"; for (size_t img = 0; img < m_data.size(); img++) { if (!m_data[img].Store(f)) return false; } f << "]"; f << "}"; return true; }
29.747036
188
0.608823
[ "vector" ]
6841ae1f2aca99c298e4e94f83beccc459dd3dcb
32,087
cpp
C++
rational.cpp
girving/poker
06fa71d03cbeeb18c1647d7c3d946d328031376b
[ "BSD-3-Clause" ]
10
2016-04-11T09:01:27.000Z
2021-06-15T14:16:32.000Z
rational.cpp
girving/poker
06fa71d03cbeeb18c1647d7c3d946d328031376b
[ "BSD-3-Clause" ]
null
null
null
rational.cpp
girving/poker
06fa71d03cbeeb18c1647d7c3d946d328031376b
[ "BSD-3-Clause" ]
3
2016-06-11T19:06:38.000Z
2017-04-17T05:16:00.000Z
// Fixed size rational numbers exposed to Python #define NPY_NO_DEPRECATED_API #include <stdint.h> #include <limits> #include <cmath> #include <stdexcept> #include <typeinfo> #include <iostream> #include <Python/Python.h> #include <Python/structmember.h> #include <numpy/arrayobject.h> #include <numpy/ufuncobject.h> namespace { using std::abs; using std::min; using std::max; using std::cout; using std::endl; using std::swap; using std::type_info; using std::exception; using std::numeric_limits; template<bool c> struct assertion_helper {}; template<> struct assertion_helper<true> { typedef int type; }; #define static_assert(condition) \ typedef assertion_helper<(condition)!=0>::type assertion_typedef_##__LINE__ typedef __int128_t int128_t; typedef __uint128_t uint128_t; // For now, we require a 64-bit machine static_assert(sizeof(void*)==8); // Relevant arithmetic exceptions class overflow : public exception { }; class zero_divide : public exception { }; // Integer arithmetic utilities template<class I> inline I safe_neg(I x) { if (x==numeric_limits<I>::min()) throw overflow(); return -x; } template<class I> inline I safe_abs(I x) { if (x>=0) return x; I nx = -x; if (nx<0) throw overflow(); return nx; } // Check for negative numbers without compiler warnings for unsigned types #define DEFINE_IS_NEGATIVE(bits) \ inline bool is_negative(int##bits##_t x) { return x<0; } \ inline bool is_negative(uint##bits##_t x) { return false; } DEFINE_IS_NEGATIVE(8) DEFINE_IS_NEGATIVE(16) DEFINE_IS_NEGATIVE(32) DEFINE_IS_NEGATIVE(64) DEFINE_IS_NEGATIVE(128) inline bool is_negative(long x) { return x<0; } template<class dst,class src> inline dst safe_cast(src x) { dst y = x; if (x != (src)y || is_negative(x)!=is_negative(y)) throw overflow(); return y; } template<class I> I gcd(I x, I y) { x = safe_abs(x); y = safe_abs(y); if (x < y) swap(x,y); while (y) { x = x%y; swap(x,y); } return x; } template<class I> I lcm(I x, I y) { if (!x || !y) return 0; x /= gcd(x,y); I lcm = x*y; if (lcm/y!=x) throw overflow(); return safe_abs(lcm); } // Fixed precision rational numbers class rational { public: typedef int64_t I; // The type of numerators and denominators typedef int128_t DI; // Double-wide integer type for detecting overflow I n; // numerator I dmm; // denominator minus one: numpy.zeros() uses memset(0) for non-object types, so need to ensure that rational(0) has all zero bytes rational(I n=0) :n(n),dmm(0) {} template<class SI> rational(SI n_, SI d_) { if (!d_) throw zero_divide(); SI g = gcd(n_,d_); n = safe_cast<I>(n_/g); I d = safe_cast<I>(d_/g); if (d <= 0) { d = -d; n = safe_neg(n); } dmm = d-1; } I d() const { return dmm+1; } private: struct fast {}; // Private to enforce that d > 0 template<class SI> rational(SI n_, SI d_, fast) { SI g = gcd(n_,d_); n = safe_cast<I>(n_/g); dmm = safe_cast<I>(d_/g)-1; } public: rational operator-() const { rational x; x.n = safe_neg(n); x.dmm = dmm; return x; } rational operator+(rational x) const { // Note that the numerator computation can never overflow int128_t, since each term is strictly under 2**128/4 (since d > 0). return rational(DI(n)*x.d()+DI(d())*x.n,DI(d())*x.d(),fast()); } rational operator-(rational x) const { // We're safe from overflow as with + return rational(DI(n)*x.d()-DI(d())*x.n,DI(d())*x.d(),fast()); } rational operator*(rational x) const { return rational(DI(n)*x.n,DI(d())*x.d(),fast()); } rational operator/(rational x) const { return rational(DI(n)*x.d(),DI(d())*x.n); } friend I floor(rational x) { // Always round down if (x.n>=0) return x.n/x.d(); // This can be done without casting up to 128 bits, but it requires working out all the sign cases return -((-DI(x.n)+x.d()-1)/x.d()); } friend I ceil(rational x) { return -floor(-x); } rational operator%(rational x) const { return *this-x*floor(*this/x); } friend rational abs(rational x) { rational y; y.n = safe_abs(x.n); y.dmm = x.dmm; return y; } friend I rint(rational x) { // Round towards nearest integer, moving exact half integers towards zero I d = x.d(); return (2*DI(x.n)+(x.n<0?-d:d))/(2*DI(d)); } friend int sign(rational x) { return x.n<0?-1:x.n==0?0:1; } friend rational inverse(rational x) { if (!x.n) throw zero_divide(); rational y; y.n = x.d(); I d = x.n; if (d <= 0) { d = safe_neg(d); y.n = -y.n; } y.dmm = d-1; return y; } private: struct unusable { void f(){} }; typedef void (unusable::*safe_bool)(); public: operator safe_bool() const { // allow conversion to bool without allowing conversion to T return n?&unusable::f:0; } }; inline bool operator==(rational x, rational y) { // Since we enforce d > 0, and store fractions in reduced form, equality is easy. return x.n==y.n && x.dmm==y.dmm; } inline bool operator!=(rational x, rational y) { return !(x==y); } inline bool operator<(rational x, rational y) { typedef rational::DI DI; return DI(x.n)*y.d() < DI(y.n)*x.d(); } inline bool operator>(rational x, rational y) { return y<x; } inline bool operator<=(rational x, rational y) { return !(y<x); } inline bool operator>=(rational x, rational y) { return !(x<y); } template<class D,class S> inline D cast(S x); #define DEFINE_INT_CAST(I) \ template<> inline I cast(rational x) { return safe_cast<I>(x.n/x.d()); } \ template<> inline rational cast(I n) { return safe_cast<int64_t>(n); } DEFINE_INT_CAST(int8_t) DEFINE_INT_CAST(uint8_t) DEFINE_INT_CAST(int16_t) DEFINE_INT_CAST(uint16_t) DEFINE_INT_CAST(int32_t) DEFINE_INT_CAST(uint32_t) DEFINE_INT_CAST(int64_t) DEFINE_INT_CAST(uint64_t) template<> inline long cast(rational x) { return safe_cast<long>(x.n/x.d()); } template<> inline float cast(rational x) { return (float) x.n/x.d(); } template<> inline double cast(rational x) { return (double)x.n/x.d(); } template<> inline bool cast(rational x) { return x.n!=0; } template<> inline rational cast(bool b) { return b; } bool scan_rational(const char*& s, rational& x) { long n,d; int offset; if (sscanf(s,"%ld%n",&n,&offset)<=0) return false; const char* ss = s+offset; if (*ss!='/') { s = ss; x = n; return true; } ss++; if (sscanf(ss,"%ld%n",&d,&offset)<=0 || d<=0) return false; s = ss+offset; x = rational(n,d); return true; } // Conversion from C++ to Python exceptions void set_python_error(const exception& e) { // Numpy will call us without access to the Python API, so we need to grab it before setting an error PyGILState_STATE state = PyGILState_Ensure(); const type_info& type = typeid(e); if (type==typeid(overflow)) PyErr_SetString(PyExc_OverflowError,"overflow in rational arithmetic"); else if (type==typeid(zero_divide)) PyErr_SetString(PyExc_ZeroDivisionError,"zero divide in rational arithmetic"); else PyErr_Format(PyExc_RuntimeError,"unknown exception %s: %s",type.name(),e.what()); PyGILState_Release(state); } // Expose rational to Python as a numpy scalar typedef struct { PyObject_HEAD; rational r; } PyRational; extern PyTypeObject PyRational_Type; inline bool PyRational_Check(PyObject* object) { return PyObject_IsInstance(object,(PyObject*)&PyRational_Type); } PyObject* PyRational_FromRational(rational x) { PyRational* p = (PyRational*)PyRational_Type.tp_alloc(&PyRational_Type,0); if (p) p->r = x; return (PyObject*)p; } PyObject* rational_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { if (kwds && PyDict_Size(kwds)) { PyErr_SetString(PyExc_TypeError,"constructor takes no keyword arguments"); return 0; } Py_ssize_t size = PyTuple_GET_SIZE(args); if (size>2) { PyErr_SetString(PyExc_TypeError,"expected rational or numerator and optional denominator"); return 0; } PyObject* x[2] = {PyTuple_GET_ITEM(args,0),PyTuple_GET_ITEM(args,1)}; if (size==1) { if (PyRational_Check(x[0])) { Py_INCREF(x[0]); return x[0]; } else if (PyString_Check(x[0])) { const char* s = PyString_AS_STRING(x[0]); rational x; if (scan_rational(s,x)) { for (const char* p = s; *p; p++) if (!isspace(*p)) goto bad; return PyRational_FromRational(x); } bad: PyErr_Format(PyExc_ValueError,"invalid rational literal '%s'",s); return 0; } } long n[2]={0,1}; for (int i=0;i<size;i++) { n[i] = PyInt_AsLong(x[i]); if (n[i]==-1 && PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_TypeError)) PyErr_Format(PyExc_TypeError,"expected integer %s, got %s",(i?"denominator":"numerator"),x[i]->ob_type->tp_name); return 0; } // Check that we had an exact integer PyObject* y = PyInt_FromLong(n[i]); if (!y) return 0; int eq = PyObject_RichCompareBool(x[i],y,Py_EQ); Py_DECREF(y); if (eq<0) return 0; if (!eq) { PyErr_Format(PyExc_TypeError,"expected integer %s, got %s",(i?"denominator":"numerator"),x[i]->ob_type->tp_name); return 0; } } rational r; try { r = rational(n[0],n[1]); } catch (const exception& e) { set_python_error(e); return 0; } return PyRational_FromRational(r); } // Returns Py_NotImplemented on most conversion failures, or raises an overflow error for too long ints #define AS_RATIONAL(object) ({ \ rational r; \ if (PyRational_Check(object)) \ r = ((PyRational*)object)->r; \ else { \ long n = PyInt_AsLong(object); \ if (n==-1 && PyErr_Occurred()) { \ if (PyErr_ExceptionMatches(PyExc_TypeError)) { \ PyErr_Clear(); \ Py_INCREF(Py_NotImplemented); \ return Py_NotImplemented; \ } \ return 0; \ } \ PyObject* y = PyInt_FromLong(n); \ if (!y) \ return 0; \ int eq = PyObject_RichCompareBool(object,y,Py_EQ); \ Py_DECREF(y); \ if (eq<0) \ return 0; \ if (!eq) { \ Py_INCREF(Py_NotImplemented); \ return Py_NotImplemented; \ } \ r = n; \ } \ r; }) PyObject* rational_richcompare(PyObject* a, PyObject* b, int op) { rational x = AS_RATIONAL(a), y = AS_RATIONAL(b); bool result = false; #define OP(py,op) case py: result = x op y; break; switch (op) { OP(Py_LT,<) OP(Py_LE,<=) OP(Py_EQ,==) OP(Py_NE,!=) OP(Py_GT,>) OP(Py_GE,>=) }; #undef OP return PyBool_FromLong(result); } PyObject* rational_repr(PyObject* self) { rational x = ((PyRational*)self)->r; if (x.d()!=1) return PyString_FromFormat("rational(%ld,%ld)",(long)x.n,(long)x.d()); else return PyString_FromFormat("rational(%ld)",(long)x.n); } PyObject* rational_str(PyObject* self) { rational x = ((PyRational*)self)->r; if (x.d()!=1) return PyString_FromFormat("%ld/%ld",(long)x.n,(long)x.d()); else return PyString_FromFormat("%ld",(long)x.n); } long rational_hash(PyObject* self) { rational x = ((PyRational*)self)->r; long h = 131071*x.n+524287*x.dmm; // Use a fairly weak hash as Python expects return h==-1?2:h; // Never return the special error value -1 } #define RATIONAL_BINOP_2(name,exp) \ PyObject* rational_##name(PyObject* a, PyObject* b) { \ rational x = AS_RATIONAL(a), \ y = AS_RATIONAL(b); \ rational z; \ try { \ z = exp; \ } catch (const exception& e) { \ set_python_error(e); \ return 0; \ } \ return PyRational_FromRational(z); \ } #define RATIONAL_BINOP(name,op) RATIONAL_BINOP_2(name,x op y) RATIONAL_BINOP(add,+) RATIONAL_BINOP(subtract,-) RATIONAL_BINOP(multiply,*) RATIONAL_BINOP(divide,/) RATIONAL_BINOP(remainder,%) RATIONAL_BINOP_2(floor_divide,floor(x/y)) #define RATIONAL_UNOP(name,type,exp,convert) \ PyObject* rational_##name(PyObject* self) { \ rational x = ((PyRational*)self)->r; \ type y; \ try { \ y = exp; \ } catch (const exception& e) { \ set_python_error(e); \ return 0; \ } \ return convert(y); \ } RATIONAL_UNOP(negative,rational,-x,PyRational_FromRational) RATIONAL_UNOP(absolute,rational,abs(x),PyRational_FromRational) RATIONAL_UNOP(int,long,cast<long>(x),PyInt_FromLong) RATIONAL_UNOP(float,double,cast<double>(x),PyFloat_FromDouble) PyObject* rational_positive(PyObject* self) { Py_INCREF(self); return self; } int rational_nonzero(PyObject* self) { rational x = ((PyRational*)self)->r; return x.n!=0; } PyNumberMethods rational_as_number = { rational_add, // nb_add rational_subtract, // nb_subtract rational_multiply, // nb_multiply rational_divide, // nb_divide rational_remainder, // nb_remainder 0, // nb_divmod 0, // nb_power rational_negative, // nb_negative rational_positive, // nb_positive rational_absolute, // nb_absolute rational_nonzero, // nb_nonzero 0, // nb_invert 0, // nb_lshift 0, // nb_rshift 0, // nb_and 0, // nb_xor 0, // nb_or 0, // nb_coerce rational_int, // nb_int rational_int, // nb_long rational_float, // nb_float 0, // nb_oct 0, // nb_hex 0, // nb_inplace_add 0, // nb_inplace_subtract 0, // nb_inplace_multiply 0, // nb_inplace_divide 0, // nb_inplace_remainder 0, // nb_inplace_power 0, // nb_inplace_lshift 0, // nb_inplace_rshift 0, // nb_inplace_and 0, // nb_inplace_xor 0, // nb_inplace_or rational_floor_divide, // nb_floor_divide rational_divide, // nb_true_divide 0, // nb_inplace_floor_divide 0, // nb_inplace_true_divide 0, // nb_index }; PyObject* rational_n(PyObject* self, void* closure) { return PyInt_FromLong(((PyRational*)self)->r.n); } PyObject* rational_d(PyObject* self, void* closure) { return PyInt_FromLong(((PyRational*)self)->r.d()); } PyGetSetDef rational_getset[] = { {(char*)"n",rational_n,0,(char*)"numerator",0}, {(char*)"d",rational_d,0,(char*)"denominator",0}, {0} // sentinel }; PyTypeObject PyRational_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, // ob_size "rational", // tp_name sizeof(PyRational), // tp_basicsize 0, // tp_itemsize 0, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare rational_repr, // tp_repr &rational_as_number, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping rational_hash, // tp_hash 0, // tp_call rational_str, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES, // tp_flags "Fixed precision rational numbers", // tp_doc 0, // tp_traverse 0, // tp_clear rational_richcompare, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext 0, // tp_methods 0, // tp_members rational_getset, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc rational_new, // tp_new 0, // tp_free }; // Numpy support PyObject* rational_getitem(void* data, void* arr) { rational r; memcpy(&r,data,sizeof(rational)); return PyRational_FromRational(r); } int rational_setitem(PyObject* item, void* data, void* arr) { rational r; if (PyRational_Check(item)) r = ((PyRational*)item)->r; else { long n = PyInt_AsLong(item); if (n==-1 && PyErr_Occurred()) return -1; PyObject* y = PyInt_FromLong(n); if (!y) return -1; int eq = PyObject_RichCompareBool(item,y,Py_EQ); Py_DECREF(y); if (eq<0) return -1; if (!eq) { PyErr_Format(PyExc_TypeError,"expected rational, got %s",item->ob_type->tp_name); return -1; } r = n; } memcpy(data,&r,sizeof(rational)); return 0; } template<class T> inline void byteswap(T& x) { char* p = (char*)&x; for (size_t i = 0; i < sizeof(T)/2; i++) swap(p[i],p[sizeof(T)-1-i]); } void rational_copyswapn(void* dst_, npy_intp dstride, void* src_, npy_intp sstride, npy_intp n, int swap, void* arr) { char *dst = (char*)dst_, *src = (char*)src_; if (!src) return; if (swap) for (npy_intp i = 0; i < n; i++) { rational& r = *(rational*)(dst+dstride*i); memcpy(&r,src+sstride*i,sizeof(rational)); byteswap(r.n); byteswap(r.dmm); } else if (dstride==sizeof(rational) && sstride==sizeof(rational)) memcpy(dst,src,n*sizeof(rational)); else for (npy_intp i = 0; i < n; i++) memcpy(dst+dstride*i,src+sstride*i,sizeof(rational)); } void rational_copyswap(void* dst, void* src, int swap, void* arr) { if (!src) return; rational& r = *(rational*)dst; memcpy(&r,src,sizeof(rational)); if (swap) { byteswap(r.n); byteswap(r.dmm); } } int rational_compare(const void* d0, const void* d1, void* arr) { rational x = *(rational*)d0, y = *(rational*)d1; return x<y?-1:x==y?0:1; } #define FIND_EXTREME(name,op) \ int rational_##name(void* data_, npy_intp n, npy_intp* max_ind, void* arr) { \ if (!n) \ return 0; \ const rational* data = (rational*)data_; \ npy_intp best_i = 0; \ rational best_r = data[0]; \ for (npy_intp i = 1; i < n; i++) \ if (data[i] op best_r) { \ best_i = i; \ best_r = data[i]; \ } \ *max_ind = best_i; \ return 0; \ } FIND_EXTREME(argmin,<) FIND_EXTREME(argmax,>) void rational_dot(void* ip0_, npy_intp is0, void* ip1_, npy_intp is1, void* op, npy_intp n, void* arr) { rational r; try { const char *ip0 = (char*)ip0_, *ip1 = (char*)ip1_; for (npy_intp i = 0; i < n; i++) { r = r + (*(rational*)ip0)*(*(rational*)ip1); ip0 += is0; ip1 += is1; } *(rational*)op = r; } catch (const exception& e) { set_python_error(e); } } npy_bool rational_nonzero(void* data, void* arr) { rational r; memcpy(&r,data,sizeof(r)); return r?NPY_TRUE:NPY_FALSE; } int rational_fill(void* data_, npy_intp length, void* arr) { rational* data = (rational*)data_; try { rational delta = data[1]-data[0]; rational r = data[1]; for (npy_intp i = 2; i < length; i++) { r = r+delta; data[i] = r; } } catch (const exception& e) { set_python_error(e); } return 0; } int rational_fillwithscalar(void* buffer_, npy_intp length, void* value, void* arr) { rational r = *(rational*)value; rational* buffer = (rational*)buffer_; for (npy_intp i = 0; i < length; i++) buffer[i] = r; return 0; } PyArray_ArrFuncs rational_arrfuncs; struct align_test { char c; struct {int64_t i[2];} r; }; PyArray_Descr rational_descr = { PyObject_HEAD_INIT(0) &PyRational_Type, // typeobj 'V', // kind 'r', // type '=', // byteorder // For now, we need NPY_NEEDS_PYAPI in order to make numpy detect our exceptions. This isn't technically necessary, // since we're careful about thread safety, and hopefully future versions of numpy will recognize that. NPY_NEEDS_PYAPI | NPY_USE_GETITEM | NPY_USE_SETITEM, // hasobject 0, // type_num sizeof(rational), // elsize offsetof(align_test,r), // alignment 0, // subarray 0, // fields 0, // names &rational_arrfuncs, // f }; template<class From,class To> void numpy_cast(void* from_, void* to_, npy_intp n, void* fromarr, void* toarr) { const From* from = (From*)from_; To* to = (To*)to_; try { for (npy_intp i = 0; i < n; i++) to[i] = cast<To>(from[i]); } catch (const exception& e) { set_python_error(e); } } template<class From,class To> int register_cast(PyArray_Descr* from_descr, int to_typenum, bool safe) { int r = PyArray_RegisterCastFunc(from_descr,to_typenum,numpy_cast<From,To>); if (!r && safe) r = PyArray_RegisterCanCast(from_descr,to_typenum,NPY_NOSCALAR); return r; } #define BINARY_UFUNC(name,intype0,intype1,outtype,exp) \ void name(char** args, npy_intp* dimensions, npy_intp* steps, void* data) { \ npy_intp is0 = steps[0], is1 = steps[1], os = steps[2], n = *dimensions; \ char *i0 = args[0], *i1 = args[1], *o = args[2]; \ try { \ for (int k = 0; k < n; k++) { \ intype0 x = *(intype0*)i0; \ intype1 y = *(intype1*)i1; \ *(outtype*)o = exp; \ i0 += is0; i1 += is1; o += os; \ } \ } catch (const exception& e) { \ set_python_error(e); \ } \ } #define RATIONAL_BINARY_UFUNC(name,type,exp) BINARY_UFUNC(rational_ufunc_##name,rational,rational,type,exp) RATIONAL_BINARY_UFUNC(add,rational,x+y) RATIONAL_BINARY_UFUNC(subtract,rational,x-y) RATIONAL_BINARY_UFUNC(multiply,rational,x*y) RATIONAL_BINARY_UFUNC(divide,rational,x/y) RATIONAL_BINARY_UFUNC(remainder,rational,x%y) RATIONAL_BINARY_UFUNC(floor_divide,rational,floor(x/y)) PyUFuncGenericFunction rational_ufunc_true_divide = rational_ufunc_divide; RATIONAL_BINARY_UFUNC(minimum,rational,min(x,y)) RATIONAL_BINARY_UFUNC(maximum,rational,max(x,y)) RATIONAL_BINARY_UFUNC(equal,bool,x==y) RATIONAL_BINARY_UFUNC(not_equal,bool,x!=y) RATIONAL_BINARY_UFUNC(less,bool,x<y) RATIONAL_BINARY_UFUNC(greater,bool,x>y) RATIONAL_BINARY_UFUNC(less_equal,bool,x<=y) RATIONAL_BINARY_UFUNC(greater_equal,bool,x>=y) BINARY_UFUNC(gcd_ufunc,int64_t,int64_t,int64_t,gcd(x,y)) BINARY_UFUNC(lcm_ufunc,int64_t,int64_t,int64_t,lcm(x,y)) #define UNARY_UFUNC(name,type,exp) \ void rational_ufunc_##name(char** args, npy_intp* dimensions, npy_intp* steps, void* data) { \ npy_intp is = steps[0], os = steps[1], n = *dimensions; \ char *i = args[0], *o = args[1]; \ try { \ for (int k = 0; k < n; k++) { \ rational x = *(rational*)i; \ *(type*)o = exp; \ i += is; o += os; \ } \ } catch (const exception& e) { \ set_python_error(e); \ } \ } UNARY_UFUNC(negative,rational,-x) UNARY_UFUNC(absolute,rational,abs(x)) UNARY_UFUNC(floor,rational,floor(x)) UNARY_UFUNC(ceil,rational,ceil(x)) UNARY_UFUNC(trunc,rational,cast<long>(x)) UNARY_UFUNC(square,rational,x*x) UNARY_UFUNC(rint,rational,rint(x)) UNARY_UFUNC(sign,rational,sign(x)) UNARY_UFUNC(reciprocal,rational,inverse(x)) UNARY_UFUNC(numerator,int64_t,x.n) UNARY_UFUNC(denominator,int64_t,x.d()) PyMethodDef module_methods[] = { {0} // sentinel }; } PyMODINIT_FUNC initrational() { // Initialize numpy import_array(); if (PyErr_Occurred()) return; import_umath(); if (PyErr_Occurred()) return; PyObject* numpy_str = PyString_FromString("numpy"); if (!numpy_str) return; PyObject* numpy = PyImport_Import(numpy_str); Py_DECREF(numpy_str); if (!numpy) return; // Can't set this until we import numpy PyRational_Type.tp_base = &PyGenericArrType_Type; // Initialize rational type object if (PyType_Ready(&PyRational_Type) < 0) return; // Initialize rational descriptor PyArray_InitArrFuncs(&rational_arrfuncs); rational_arrfuncs.getitem = rational_getitem; rational_arrfuncs.setitem = rational_setitem; rational_arrfuncs.copyswapn = rational_copyswapn; rational_arrfuncs.copyswap = rational_copyswap; rational_arrfuncs.compare = rational_compare; rational_arrfuncs.argmin = rational_argmin; rational_arrfuncs.argmax = rational_argmax; rational_arrfuncs.dotfunc = rational_dot; rational_arrfuncs.nonzero = rational_nonzero; rational_arrfuncs.fill = rational_fill; rational_arrfuncs.fillwithscalar = rational_fillwithscalar; // Left undefined: scanfunc, fromstr, sort, argsort rational_descr.ob_type = &PyArrayDescr_Type; int npy_rational = PyArray_RegisterDataType(&rational_descr); if (npy_rational<0) return; // Support dtype(rational) syntax if (PyDict_SetItemString(PyRational_Type.tp_dict,"dtype",(PyObject*)&rational_descr)<0) return; // Register casts to and from rational #define REGISTER_INT_CONVERSIONS(bits) \ if (register_cast<int##bits##_t,rational>(PyArray_DescrFromType(NPY_INT##bits),npy_rational,true)<0) return; \ if (register_cast<uint##bits##_t,rational>(PyArray_DescrFromType(NPY_UINT##bits),npy_rational,true)<0) return; \ if (register_cast<rational,int##bits##_t>(&rational_descr,NPY_INT##bits,false)<0) return; \ if (register_cast<rational,uint##bits##_t>(&rational_descr,NPY_UINT##bits,false)<0) return; REGISTER_INT_CONVERSIONS(8) REGISTER_INT_CONVERSIONS(16) REGISTER_INT_CONVERSIONS(32) REGISTER_INT_CONVERSIONS(64) if (register_cast<rational,float >(&rational_descr,NPY_FLOAT,false)<0) return; if (register_cast<rational,double>(&rational_descr,NPY_DOUBLE,true)<0) return; if (register_cast<bool,rational>(PyArray_DescrFromType(NPY_BOOL),npy_rational,true)<0) return; if (register_cast<rational,bool>(&rational_descr,NPY_BOOL,false)<0) return; // Register ufuncs #define REGISTER_UFUNC(name,...) ({ \ PyUFuncObject* ufunc = (PyUFuncObject*)PyObject_GetAttrString(numpy,#name); \ if (!ufunc) return; \ int _types[] = __VA_ARGS__; \ if (sizeof(_types)/sizeof(int)!=ufunc->nargs) { \ PyErr_Format(PyExc_AssertionError,"ufunc %s takes %d arguments, our loop takes %ld",#name,ufunc->nargs,sizeof(_types)/sizeof(int)); \ return; \ } \ if (PyUFunc_RegisterLoopForType((PyUFuncObject*)ufunc,npy_rational,rational_ufunc_##name,_types,0)<0) return; \ }); #define REGISTER_UFUNC_BINARY_RATIONAL(name) REGISTER_UFUNC(name,{npy_rational,npy_rational,npy_rational}) #define REGISTER_UFUNC_BINARY_COMPARE(name) REGISTER_UFUNC(name,{npy_rational,npy_rational,NPY_BOOL}) #define REGISTER_UFUNC_UNARY(name) REGISTER_UFUNC(name,{npy_rational,npy_rational}) // Binary REGISTER_UFUNC_BINARY_RATIONAL(add) REGISTER_UFUNC_BINARY_RATIONAL(subtract) REGISTER_UFUNC_BINARY_RATIONAL(multiply) REGISTER_UFUNC_BINARY_RATIONAL(divide) REGISTER_UFUNC_BINARY_RATIONAL(remainder) REGISTER_UFUNC_BINARY_RATIONAL(true_divide) REGISTER_UFUNC_BINARY_RATIONAL(floor_divide) REGISTER_UFUNC_BINARY_RATIONAL(minimum) REGISTER_UFUNC_BINARY_RATIONAL(maximum) // Comparisons REGISTER_UFUNC_BINARY_COMPARE(equal) REGISTER_UFUNC_BINARY_COMPARE(not_equal) REGISTER_UFUNC_BINARY_COMPARE(less) REGISTER_UFUNC_BINARY_COMPARE(greater) REGISTER_UFUNC_BINARY_COMPARE(less_equal) REGISTER_UFUNC_BINARY_COMPARE(greater_equal) // Unary REGISTER_UFUNC_UNARY(negative) REGISTER_UFUNC_UNARY(absolute) REGISTER_UFUNC_UNARY(floor) REGISTER_UFUNC_UNARY(ceil) REGISTER_UFUNC_UNARY(trunc) REGISTER_UFUNC_UNARY(rint) REGISTER_UFUNC_UNARY(square) REGISTER_UFUNC_UNARY(reciprocal) REGISTER_UFUNC_UNARY(sign) // Create module PyObject* m = Py_InitModule3("rational", module_methods, "Fixed precision rational numbers, including numpy support"); if (!m) return; // Add rational type Py_INCREF(&PyRational_Type); PyModule_AddObject(m,"rational",(PyObject*)&PyRational_Type); // Create numerator and denominator ufuncs #define NEW_UNARY_UFUNC(name,type,doc) ({ \ PyObject* ufunc = PyUFunc_FromFuncAndData(0,0,0,0,1,1,PyUFunc_None,(char*)#name,(char*)doc,0); \ if (!ufunc) return; \ int types[2] = {npy_rational,type}; \ if (PyUFunc_RegisterLoopForType((PyUFuncObject*)ufunc,npy_rational,rational_ufunc_##name,types,0)<0) return; \ PyModule_AddObject(m,#name,(PyObject*)ufunc); \ }) NEW_UNARY_UFUNC(numerator,NPY_INT64,"rational number numerator"); NEW_UNARY_UFUNC(denominator,NPY_INT64,"rational number denominator"); // Create gcd and lcm ufuncs #define GCD_LCM_UFUNC(name,type,doc) ({ \ static const PyUFuncGenericFunction func[1] = {name##_ufunc}; \ static const char types[3] = {type,type,type}; \ static void* data[1] = {0}; \ PyObject* ufunc = PyUFunc_FromFuncAndData((PyUFuncGenericFunction*)func,data,(char*)types,1,2,1,PyUFunc_One,(char*)#name,(char*)doc,0); \ if (!ufunc) return; \ PyModule_AddObject(m,#name,(PyObject*)ufunc); \ }) GCD_LCM_UFUNC(gcd,NPY_INT64,"greatest common denominator of two integers"); GCD_LCM_UFUNC(lcm,NPY_INT64,"least common multiple of two integers"); }
32.775281
145
0.58332
[ "object" ]
6844e5a3c732fe0415c10e0663971eb7b8f7e7c7
4,405
cpp
C++
wpa_supplicant/binder/supplicant.cpp
TinkerBoard-Android/external_wpa_supplicant_8
f0798391039d0741d7b32dc30489678f17a6239a
[ "Unlicense" ]
14
2015-02-15T03:03:20.000Z
2021-07-19T14:09:29.000Z
wpa_supplicant/binder/supplicant.cpp
TinkerBoard-Android/external_wpa_supplicant_8
f0798391039d0741d7b32dc30489678f17a6239a
[ "Unlicense" ]
8
2017-01-29T01:28:03.000Z
2017-01-29T20:50:32.000Z
wpa_supplicant/binder/supplicant.cpp
TinkerBoard-Android/external_wpa_supplicant_8
f0798391039d0741d7b32dc30489678f17a6239a
[ "Unlicense" ]
98
2015-01-01T14:03:52.000Z
2020-07-21T11:31:59.000Z
/* * binder interface for wpa_supplicant daemon * Copyright (c) 2004-2016, Jouni Malinen <j@w1.fi> * Copyright (c) 2004-2016, Roshan Pius <rpius@google.com> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "binder_manager.h" #include "supplicant.h" namespace wpa_supplicant_binder { Supplicant::Supplicant(struct wpa_global *global) : wpa_global_(global) { } android::binder::Status Supplicant::CreateInterface( const android::os::PersistableBundle &params, android::sp<fi::w1::wpa_supplicant::IIface> *aidl_return) { android::String16 driver, ifname, confname, bridge_ifname; /* Check if required Ifname argument is missing */ if (!params.getString(android::String16("Ifname"), &ifname)) return android::binder::Status::fromServiceSpecificError( ERROR_INVALID_ARGS, android::String8("Ifname missing in params.")); /* Retrieve the remaining params from the dictionary */ params.getString(android::String16("Driver"), &driver); params.getString(android::String16("ConfigFile"), &confname); params.getString(android::String16("BridgeIfname"), &bridge_ifname); /* * Try to get the wpa_supplicant record for this iface, return * an error if we already control it. */ if (wpa_supplicant_get_iface(wpa_global_, android::String8(ifname).string()) != NULL) return android::binder::Status::fromServiceSpecificError( ERROR_IFACE_EXISTS, android::String8("wpa_supplicant already controls this interface.")); android::binder::Status status; struct wpa_supplicant *wpa_s = NULL; struct wpa_interface iface; os_memset(&iface, 0, sizeof(iface)); iface.driver = os_strdup(android::String8(driver).string()); iface.ifname = os_strdup(android::String8(ifname).string()); iface.confname = os_strdup(android::String8(confname).string()); iface.bridge_ifname = os_strdup( android::String8(bridge_ifname).string()); /* Otherwise, have wpa_supplicant attach to it. */ wpa_s = wpa_supplicant_add_iface(wpa_global_, &iface, NULL); /* The supplicant core creates a corresponding binder object via * BinderManager when |wpa_supplicant_add_iface| is called. */ if (!wpa_s || !wpa_s->binder_object_key) { status = android::binder::Status::fromServiceSpecificError( ERROR_UNKNOWN, android::String8("wpa_supplicant couldn't grab this interface.")); } else { BinderManager *binder_manager = BinderManager::getInstance(); if (!binder_manager || binder_manager->getIfaceBinderObjectByKey( wpa_s->binder_object_key, aidl_return)) status = android::binder::Status::fromServiceSpecificError( ERROR_UNKNOWN, android::String8("wpa_supplicant encountered a binder error.")); else status = android::binder::Status::ok(); } os_free((void *) iface.driver); os_free((void *) iface.ifname); os_free((void *) iface.confname); os_free((void *) iface.bridge_ifname); return status; } android::binder::Status Supplicant::RemoveInterface(const std::string &ifname) { struct wpa_supplicant *wpa_s; wpa_s = wpa_supplicant_get_iface(wpa_global_, ifname.c_str()); if (!wpa_s || !wpa_s->binder_object_key) return android::binder::Status::fromServiceSpecificError( ERROR_IFACE_UNKNOWN, android::String8("wpa_supplicant does not control this interface.")); if (wpa_supplicant_remove_iface(wpa_global_, wpa_s, 0)) return android::binder::Status::fromServiceSpecificError( ERROR_UNKNOWN, android::String8("wpa_supplicant couldn't remove this interface.")); return android::binder::Status::ok(); } android::binder::Status Supplicant::GetInterface( const std::string &ifname, android::sp<fi::w1::wpa_supplicant::IIface> *aidl_return) { struct wpa_supplicant *wpa_s; wpa_s = wpa_supplicant_get_iface(wpa_global_, ifname.c_str()); if (!wpa_s || !wpa_s->binder_object_key) return android::binder::Status::fromServiceSpecificError( ERROR_IFACE_UNKNOWN, android::String8("wpa_supplicant does not control this interface.")); BinderManager *binder_manager = BinderManager::getInstance(); if (!binder_manager || binder_manager->getIfaceBinderObjectByKey(wpa_s->binder_object_key, aidl_return)) return android::binder::Status::fromServiceSpecificError( ERROR_UNKNOWN, android::String8("wpa_supplicant encountered a binder error.")); return android::binder::Status::ok(); } } /* namespace wpa_supplicant_binder */
34.960317
78
0.746879
[ "object" ]
969cc6657a387429cfbbce30d9bf94a83bfa7a1c
5,877
cpp
C++
Sources/Engine/Graphics/Scene/SkyBox.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Engine/Graphics/Scene/SkyBox.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Engine/Graphics/Scene/SkyBox.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
/*============================================================================= SkyBox.cpp Project: Sonata Engine Author: Julien Delezenne =============================================================================*/ #include "SkyBox.h" #include "Graphics/System/RenderSystem.h" #include "Graphics/SceneManager.h" #include "Graphics/Scene/Camera.h" #include "Graphics/Materials/DefaultMaterial.h" namespace SonataEngine { SE_IMPLEMENT_CLASS(SkyBox); SE_IMPLEMENT_REFLECTION(SkyBox); SkyBox::SkyBox() : Sky(), _distance(100.0f), _mesh(NULL) { Memory::Set(_planes, SkyBoxPlane_Count * sizeof(Texture*), NULL); } SkyBox::~SkyBox() { Destroy(); for (int i = 0; i < SkyBoxPlane_Count; i++) { _planes[i] = NULL; _mesh = NULL; } } Texture* SkyBox::GetPlaneTexture(SkyBoxPlane plane) const { if (plane < 0 || plane >= SkyBoxPlane_Count) return NULL; return _planes[plane]; } void SkyBox::SetPlaneTexture(SkyBoxPlane plane, Texture* face) { if (plane < 0 || plane >= SkyBoxPlane_Count) return; _planes[plane] = face; ((FFPPass*)((DefaultMaterial*)_mesh->GetMeshPart(plane)->GetShader())->GetTechnique()-> GetPassByIndex(0))->GetSamplerStateByIndex(0)->SetTexture(_planes[plane]); } bool SkyBox::Create() { Destroy(); RenderSystem* renderer = RenderSystem::Current(); if (renderer == NULL) { return false; } int i; VertexLayout* vertexLayout = NULL; HardwareBuffer* indexBuffer = NULL; if (!renderer->CreateVertexLayout(&vertexLayout)) { return false; } uint16 offset = 0; vertexLayout->AddElement(VertexElement(0, offset, VertexFormat_Float3, VertexSemantic_Position)); offset += VertexElement::GetTypeSize(VertexFormat_Float3); vertexLayout->AddElement(VertexElement(0, offset, VertexFormat_Float2, VertexSemantic_TextureCoordinate)); offset += VertexElement::GetTypeSize(VertexFormat_Float2); struct SkyGeometry { Vector3 Position; Vector2 TexCoord; }; SkyGeometry vertices[] = { //left Vector3( 1,-1,-1), Vector2(0.0, 1.0), Vector3( 1,-1, 1), Vector2(1.0, 1.0), Vector3( 1, 1, 1), Vector2(1.0, 0.0), Vector3( 1, 1,-1), Vector2(0.0, 0.0), //right Vector3(-1,-1, 1), Vector2(0.0, 1.0), Vector3(-1,-1,-1), Vector2(1.0, 1.0), Vector3(-1, 1,-1), Vector2(1.0, 0.0), Vector3(-1, 1, 1), Vector2(0.0, 0.0), //top Vector3( 1, 1, 1), Vector2(0.0, 1.0), Vector3(-1, 1, 1), Vector2(1.0, 1.0), Vector3(-1, 1,-1), Vector2(1.0, 0.0), Vector3( 1, 1,-1), Vector2(0.0, 0.0), //bottom Vector3(-1,-1, 1), Vector2(0.0, 0.0), Vector3( 1,-1, 1), Vector2(1.0, 0.0), Vector3( 1,-1,-1), Vector2(1.0, 1.0), Vector3(-1,-1,-1), Vector2(0.0, 1.0), //front Vector3(-1,-1, 1), Vector2(1.0, 1.0), Vector3( 1,-1, 1), Vector2(0.0, 1.0), Vector3( 1, 1, 1), Vector2(0.0, 0.0), Vector3(-1, 1, 1), Vector2(1.0, 0.0), //back Vector3( 1,-1,-1), Vector2(1.0, 1.0), Vector3(-1,-1,-1), Vector2(0.0, 1.0), Vector3(-1, 1,-1), Vector2(0.0, 0.0), Vector3( 1, 1,-1), Vector2(1.0, 0.0) }; // 3---2 // | / | // 0---1 uint16 indices[] = { 0, 1, 2, 0, 2, 3 }; HardwareBuffer* vertexBuffers[SkyBoxPlane_Count]; Memory::Set(vertexBuffers, SkyBoxPlane_Count * sizeof(HardwareBuffer*), NULL); SEtry { int16 vertexCount = 4; for (i = 0; i < SkyBoxPlane_Count; i++) { if (!renderer->CreateVertexBuffer(vertexCount * vertexLayout->GetSize(), HardwareBufferUsage_Static, &vertexBuffers[i])) { SEthrow(Exception()); } SEbyte* vbData; vertexBuffers[i]->Map(HardwareBufferMode_Normal, (void**)&vbData); Memory::Copy(vbData, &vertices[i*vertexCount], vertexCount * vertexLayout->GetSize()); vertexBuffers[i]->Unmap(); } int16 indexCount = 6; if (!renderer->CreateIndexBuffer(indexCount * sizeof(int16), IndexBufferFormat_Int16, HardwareBufferUsage_Static, &indexBuffer)) { SEthrow(Exception()); } SEbyte* ibData; indexBuffer->Map(HardwareBufferMode_Normal, (void**)&ibData); Memory::Copy(ibData, indices, indexCount * sizeof(int16)); indexBuffer->Unmap(); IndexData* indexData = new IndexData(); indexData->IndexBuffer = indexBuffer; indexData->IndexCount = indexCount; _mesh = new Mesh(); for (i = 0; i < SkyBoxPlane_Count; i++) { MeshPart* meshPart = new MeshPart(); VertexData* vertexData = new VertexData(); vertexData->VertexLayout = vertexLayout; vertexData->VertexStreams.Add(VertexStream(vertexBuffers[i], vertexLayout->GetSize())); vertexData->VertexCount = vertexCount; meshPart->SetVertexData(vertexData); meshPart->SetIndexData(indexData); meshPart->SetIndexed(true); meshPart->SetPrimitiveTypeAndCount(PrimitiveType_TriangleList, indexCount); _mesh->AddMeshPart(meshPart); DefaultMaterial* shader = new DefaultMaterial(); FFPPass* pass = (FFPPass*)shader->GetTechnique()->GetPassByIndex(0); pass->RasterizerState.CullMode = CullMode_None; pass->LightState.Lighting = false; pass->DepthState.Enable = false; pass->DepthState.WriteEnable = false; SamplerState* samplerState = pass->GetSamplerStateByIndex(0); samplerState->AddressModeU = TextureAddressMode_Clamp; samplerState->AddressModeV = TextureAddressMode_Clamp; samplerState->SetTexture(_planes[i]); meshPart->SetShader(shader); } return true; } SEcatch (Exception) { SE_DELETE(vertexLayout); for (i = 0; i < SkyBoxPlane_Count; i++) SE_DELETE(vertexBuffers[i]); SE_DELETE(indexBuffer); return false; } } void SkyBox::Destroy() { } void SkyBox::Update(const TimeValue& timeValue) { } void SkyBox::Render() { if (_mesh == NULL) return; Vector3 position = Vector3::Zero; if (SceneManager::Instance()->GetCamera() != NULL) { position = SceneManager::Instance()->GetCamera()->GetWorldPosition(); } Transform3 transform(position, Vector3(_distance), Quaternion::Identity); SceneManager::Instance()->RenderMesh(_mesh, transform.GetMatrix()); } }
24.185185
90
0.662072
[ "mesh", "render", "transform" ]
969f099cfb5d966740d02e30bddbbc247e44355e
8,972
cpp
C++
ObjectDetector.cpp
IvanSobko/Rise_of_the_Machines
45c02d5c5cdd7e9652778fe5ce8cd17d1c3c4f5e
[ "MIT" ]
null
null
null
ObjectDetector.cpp
IvanSobko/Rise_of_the_Machines
45c02d5c5cdd7e9652778fe5ce8cd17d1c3c4f5e
[ "MIT" ]
null
null
null
ObjectDetector.cpp
IvanSobko/Rise_of_the_Machines
45c02d5c5cdd7e9652778fe5ce8cd17d1c3c4f5e
[ "MIT" ]
null
null
null
// // Created by Sveta Morkva on 10/3/20. // #include "ObjectDetector.h" #include <opencv2/core.hpp> #include <opencv2/ml.hpp> #include <opencv2/xfeatures2d.hpp> #include <boost/filesystem.hpp> #include "opencv2/viz.hpp" #include <opencv2/opencv.hpp> #include <opencv2/core/cvstd.hpp> using namespace cv; using namespace cv::ml; namespace fs = boost::filesystem; ObjectDetector::ObjectDetector(bool brisk) : mBriskDescr(brisk) {} void ObjectDetector::train(std::vector<Mat> images, std::vector<int> labels, Ptr<ml::SVM> &model) { Mat samples = getDescriptors(images); std::string filename = "../trained_model/trained_"; // if(fs::exists(filename)){ // std::cout << "Found trained model: " << filename << ", loading it." << std::endl; // svm = SVM::load(filename); // return; // } model = SVM::create(); model->setType(ml::SVM::C_SVC); model->setKernel(ml::SVM::LINEAR); model->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6)); model->train(samples, ROW_SAMPLE, labels); std::cout << "Trained "<< (mBriskDescr ? "brisk" : "surf") << " SVM model." << std::endl; filename += mBriskDescr ? "svm_brisk.xml" : "svm_surf.xml"; model->save(filename); } void ObjectDetector::train(std::vector<cv::Mat> images, std::vector<int> labels, cv::Ptr<cv::ml::DTrees> &model) { Mat samples = getDescriptors(images); std::string filename = "../trained_model/trained_"; // if(fs::exists(filename)){ // std::cout << "Found trained model: " << filename << ", loading it." << std::endl; // svm = SVM::load(filename); // return; // } model = DTrees::create(); model->setCVFolds(1); model->setMaxDepth(15); model->train(samples, ROW_SAMPLE, labels); std::cout << "Trained "<< (mBriskDescr ? "brisk" : "surf") << " DTREES model." << std::endl; filename += mBriskDescr ? "dtrees_brisk.xml" : "drees_surf.xml"; model->save(filename); } void ObjectDetector::predict(std::vector<Mat> images, std::vector<int> labels, cv::ml::StatModel *model) { std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); Mat samples = getDescriptors(images); Mat predict_labels; model->predict(samples, predict_labels); std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); auto time = std::chrono::duration_cast<std::chrono::microseconds>(end - begin); printf("Time for detection and prediction: %f\n", time.count() / 1000000.0); int truePositivesS = 0, falsePositivesS = 0, truePositivesM = 0, falsePositivesM = 0, trueNegatives = 0, falseNegatives = 0, allS = 0, allM = 0; for (int i = 0; i < predict_labels.rows; i++) { if (labels[i] == 1) { predict_labels.at<float>(i, 0) == labels[i] ? truePositivesS++ : falsePositivesS++; allS++; } else if (labels[i] == 2) { predict_labels.at<float>(i, 0) == labels[i] ? truePositivesM++ : falsePositivesM++; allM++; } else { predict_labels.at<float>(i, 0) == labels[i] ? trueNegatives++ : falseNegatives++; } } printf("False positive sneaker: %d\nFalse positive money: %d\nFalse negative: %d\n", falsePositivesS, falsePositivesM, falseNegatives); double precisonS = truePositivesS * 1.0/(truePositivesS+falsePositivesS); double precisonM = truePositivesM * 1.0/(truePositivesM+falsePositivesM); double recallS = truePositivesS * 1.0/allS; double recallM = truePositivesM * 1.0/allM; double f1S = 2*precisonS*recallS/(precisonS+recallS); double f1M = 2*precisonM*recallM/(precisonM+recallM); printf("Precision sneaker: %f\nRecall sneaker: %f\nF1-score sneaker: %f\n", precisonS, recallS, f1S); printf("Precision money: %f\nRecall money: %f\nF1-score money: %f\n", precisonM, recallM, f1M); } cv::Mat ObjectDetector::getDescriptors(std::vector<Mat> images) { Ptr<DescriptorExtractor> extractor; if (mBriskDescr) { extractor = BRISK::create(); } else { extractor = xfeatures2d::SURF::create(); } Mat outSamples = Mat::zeros(images.size(), extractor->descriptorSize() * num_descr, CV_32FC1); for (int i = 0; i < images.size(); i++) { std::vector<KeyPoint> keypoints; cv::Mat descriptors; std::vector<int> clustNames; std::map<int, std::vector<Point2f>> clusters; auto img = images[i]; extractor->detect(img, keypoints); extractor->compute(img, keypoints, descriptors); if (keypoints.size() < num_clusters) { continue; } cv::Mat points(keypoints.size(), descriptors.cols + 2, CV_32FC1); for (int z = 0; z < keypoints.size(); z++) { auto p = keypoints[z].pt; for (int j = 0; j < descriptors.cols; j++) { points.at<float>(z, j) = mBriskDescr ? descriptors.at<uchar>(z, j) : descriptors.at<float>(z, j); } points.at<float>(z, descriptors.cols) = p.x; points.at<float>(z, descriptors.cols + 1) = p.y; } kmeans(points, num_clusters, clustNames, TermCriteria(TermCriteria::MAX_ITER, 10, 1.0), 3, KMEANS_PP_CENTERS); Mat img_keypoints; for (int j = 0; j < points.rows; j++) { Point2f p = {points.at<float>(j, descriptors.cols), points.at<float>(j, descriptors.cols + 1)}; clusters[clustNames[j]].push_back(p); } int biggestClusterNum = 0; int biggestClusterName; for (auto cl: clusters) { if (biggestClusterNum < cl.second.size()*0.95) { biggestClusterName = cl.first; biggestClusterNum = cl.second.size(); } else { auto r1 = boundingRect(cl.second); auto r2 = boundingRect(clusters[biggestClusterName]); Point center_of_rect1 = (r1.br() + r1.tl())*0.5; Point center_of_rect2 = (r2.br() + r2.tl())*0.5; Point center_of_img = {img.cols/2, img.rows/2}; double dist1 = cv::norm(center_of_img-center_of_rect1); double dist2 = cv::norm(center_of_img-center_of_rect2); if (dist1 < dist2) { biggestClusterName = cl.first; biggestClusterNum = cl.second.size(); } } } int num = 0; for (int z = 0; z < descriptors.rows; z++) { if (clustNames[z] == biggestClusterName) { for (int j = 0; j < descriptors.cols; j++) { outSamples.at<float>(i, num*descriptors.cols+j) = points.at<float>(z, j); } if (++num == num_descr) { break; } } } curImgBoundRect = boundingRect(clusters[biggestClusterName]); // rectangle(img, r, Scalar(255, 0, 0)); // imshow("SURF Keypoints", img); // waitKey(); } return outSamples; } void ObjectDetector::predictVideo(const std::string &filename, cv::VideoCapture video, cv::ml::StatModel *model) { if (!video.isOpened()) { std::cout << "Error opening video stream or file" << std::endl; return; } std::cout << "Processing video: " << filename << std::endl; std::vector<cv::Mat> resultVideo; while (true) { Mat frame; video >> frame; if (frame.empty()) { break; } cvtColor(frame, frame, COLOR_BGR2GRAY); auto img = getDescriptors({frame}); float label = model->predict(img); cv::cvtColor(frame, frame, cv::COLOR_GRAY2BGR); Scalar color; std::string overlay; if (label == 0) { color = cv::viz::Color::red(); overlay = "None objects were found."; }else if (label == 1) { color = cv::viz::Color::green(); overlay = "Sneaker object was found."; }else { color = cv::viz::Color::green(); overlay = "Money object was found."; } if (label != 0) { rectangle(frame, curImgBoundRect, cv::viz::Color::green(), 2); } auto point = Point(frame.cols / 2, frame.rows - frame.rows /4); cv::putText(frame, overlay, point, FONT_HERSHEY_PLAIN, 1.0, cv::viz::Color::white(), 2.0); resultVideo.push_back(frame); } VideoWriter writer = cv::VideoWriter(); auto size = cv::Size(static_cast<int>(video.get(cv::CAP_PROP_FRAME_WIDTH)), static_cast<int>(video.get(cv::CAP_PROP_FRAME_HEIGHT))); //avi format if (!writer.open(filename, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 10, size)) { std::cout << "Error: cant open file to write" << std::endl; return; } for (const auto &frame: resultVideo) { writer.write(frame); } }
39.179039
122
0.579804
[ "object", "vector", "model" ]
96a05e25daf769f2b768ac169d3f9ae19f0982cb
2,409
cc
C++
src/sys/fuzzing/framework/testing/engine.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2022-02-24T16:24:29.000Z
2022-02-25T22:33:10.000Z
src/sys/fuzzing/framework/testing/engine.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
src/sys/fuzzing/framework/testing/engine.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <fuchsia/fuzzer/cpp/fidl.h> #include <lib/fidl/cpp/interface_request.h> #include <lib/sys/cpp/component_context.h> #include <stddef.h> #include <memory> #include <gtest/gtest.h> #include "src/sys/fuzzing/common/input.h" #include "src/sys/fuzzing/common/options.h" #include "src/sys/fuzzing/framework/engine/adapter-client.h" #include "src/sys/fuzzing/framework/engine/corpus.h" // These tests replaces the engine when building a fuzzer test instead of a fuzzer. namespace fuzzing { using fuchsia::fuzzer::Options; using fuchsia::fuzzer::TargetAdapterSyncPtr; // Test fixtures std::unique_ptr<TargetAdapterClient> GetClient() { auto client = std::make_unique<TargetAdapterClient>(); fidl::InterfaceRequestHandler<TargetAdapter> handler = [](fidl::InterfaceRequest<TargetAdapter> request) { auto context = sys::ComponentContext::Create(); context->svc()->Connect(std::move(request)); }; client->SetHandler(std::move(handler)); auto options = std::make_shared<Options>(); TargetAdapterClient::AddDefaults(options.get()); client->Configure(std::move(options)); return client; } // Unit tests TEST(FuzzerTest, EmptyInputs) { auto client = GetClient(); Input input; EXPECT_EQ(client->Start(&input), ZX_OK); client->AwaitFinish(); EXPECT_TRUE(client->is_connected()); } TEST(FuzzerTest, EmptyInputs) { auto client = GetClient(); Input input; for (size_t i = 0; i < 3; ++i) { EXPECT_EQ(client->Start(&input), ZX_OK); client->AwaitFinish(); EXPECT_TRUE(client->is_connected()); } } TEST(FuzzerTest, SeedCorpus) { auto options = std::make_shared<Options>(); Corpus::AddDefaults(options.get()); auto client = GetClient(); auto parameters = client->GetParameters(); std::vector<std::string> seed_corpus_dirs; std::copy_if( parameters.begin(), parameters.end(), std::back_inserter(seed_corpus_dirs), [](const std::string& parameter) { return !parameter.empty() && parameter[0] != '-'; }); seed_corpus_->Load(seed_corpus_dirs); Input input; for (size_t i = 0; corpus.At(i, &input); ++i) { EXPECT_EQ(client->Start(&input), ZX_OK); client->AwaitFinish(); EXPECT_TRUE(client->is_connected()); } } } // namespace fuzzing
29.024096
94
0.704027
[ "vector" ]
96a5faa2f23b22f15f71b8c96e9132acddf67139
4,604
cpp
C++
Programming-II-C++/MW10_L8_Blanco.cpp
eebr99/CPlusPlus-Projects
e891cb6c82ca71bd8afbf95b55068ae71a0168f5
[ "MIT" ]
null
null
null
Programming-II-C++/MW10_L8_Blanco.cpp
eebr99/CPlusPlus-Projects
e891cb6c82ca71bd8afbf95b55068ae71a0168f5
[ "MIT" ]
null
null
null
Programming-II-C++/MW10_L8_Blanco.cpp
eebr99/CPlusPlus-Projects
e891cb6c82ca71bd8afbf95b55068ae71a0168f5
[ "MIT" ]
null
null
null
// Author: Eric Blanco // Course: COSC 1337 Spring 2020 MW10; Instructor: Thayer // Assignment: Lab 8 // Topic: This program /* IPO Chart INPUT class Board, the game board will have the following members declare enum Board_state_t private: char grid, for a 3 by 3 standard tic tac toe board Board_state_t state, for state of the board public: void reset(), to clear board for a new game make_move(), to make a move on the board and update it show(), to show current state of the board bool running, to run the while loop char play_again, either y or n, if y, play again, else, quit get_int(), avoids infinite loop if letter entered row, for board row# col, for board column# PROCESSING take player 1 input and place x in chosen spot take player 2 input and place o in chosen spot if spot already taken, display appropriate message and ask to retry continue until player 1 or 2 wins, or nobody wins keep program running and play again if players decide to quit if players are finished OUTPUT display greeting and explanation/instruction display player1 prompt and current board display player2 prompt and current board continue until end of game display result of game and ask to play again if play again, do all over else, display farewell message */ // Compiler directives #include <iostream> #include <iomanip> #include <string> #include <limits> #include <vector> // needed for vectors using namespace std; int getint (const string &prompt, string errNonDigit, string errRange, int lo, int hi) { while (bool getting_integer=true) { cout<<prompt<<" ("<<lo<<"-"<<hi<<"): "; int users_int_input=0; if(cin>>users_int_input) { if(users_int_input>=lo and users_int_input <= hi) { return users_int_input; // RETURN VALID USER INPUT VALUE } else cout<<errRange; } else { cout<<errNonDigit; cin.clear(); cin.ignore(1024, '\n'); } } } enum board_state_t {no_won, X_won, O_won, draw, original}; // create enum for game status class Board { //enum board_state_t {no_won, X_won, O_won, draw, original}; // create enum for game status private: char grid[3][3]; /*= {{'7','8','9'}, {'4','5','6'}, {'1','2','3'}};*/ board_state_t state; public: void reset(){ // need this to clear / reset board to start a new game grid[0][0] = '7'; grid[0][1] = '8'; grid[0][2] = '9'; grid[1][0] = '4'; grid[1][1] = '5'; grid[1][2] = '6'; grid[2][0] = '1'; grid[2][1] = '2'; grid[2][2] = '3'; } /*board_state_t*/ void make_move(int spot, char player){ // need this to make a move on the board, update board switch(spot){ case 1: grid[2][0] = player; break; case 2: grid[2][1] = player; break; case 3: grid[2][2] = player; break; case 4: grid[1][0] = player; break; case 5: grid[1][1] = player; break; case 6: grid[1][2] = player; break; case 7: grid[0][0] = player; break; case 8: grid[0][1] = player; break; case 9: grid[0][2] = player; break; } } void show(){ // need this to display the board after each move cout << "-----------" << endl; for (int row = 0; row < 3; row++){ for (int col = 0; col < 3; col++){ cout << grid[row][col] << " | "; } cout << "\n-----------"; cout << endl; } } }; int main(){ cout<<"\nHi! This is a game of tic tac toe! Here is the board:\n"; Board board; board.reset(); board.show(); cout << "The board is identical to the numpad on your computer."; cout << "\nPlease enter the corresponding number you wish to place your X or O on." << endl; bool playing=true; while (playing) { static char player='X'; // use a static char, so only one, not reset to 'X' every iteration of loop //board_state_t game_status; string prompt="\nEnter player "+string(1, player)+"'s move, 0 to quit. "; // need to convert char player 'X' into string "X" before I can use + to concatenate strings together // use getint() for validation checking, avoid infinite loop error if user enters letters int spot=getint(prompt+"location: ", "", "", 0, 9); // allow range 0-9, 0 to quit if (!spot) break; // break if spot is false, (or 0) // here, need to make a move on the board, then see if there is a winner, cat game (tie game), etc. /*game_status = */board.make_move(spot, player); player=((player=='X')?'O':'X'); // alternate player from X to O to X ... board.show(); } }
34.878788
116
0.619027
[ "vector" ]
96b936b758a8c460125de6b27701853444ee9cb1
512
cpp
C++
Dataset/Leetcode/train/78/27.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/78/27.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/78/27.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: //可以直接遍历,遇到一个数就把所有子集加上该数组成新的子集,遍历完毕即是所有子集 vector<vector<int>> XXX(vector<int>& nums) { if(nums.empty()) return vector<vector<int>>(); vector<vector<int>> res; res.push_back({}); for(auto num : nums) { vector<vector<int>> state = res; for(auto r : res) { r.push_back(num); state.push_back(r); } res = state; } return res; } };
23.272727
54
0.472656
[ "vector" ]
96ced0c9e984e00085d5a63cfcdc54c1b01ace59
3,717
hxx
C++
include/rex/Graphics/Scene.hxx
fastinvsqrt/rex
75aec2382e49b97f4ccf3a5202c026ac8f4349e9
[ "MIT", "Unlicense" ]
3
2015-02-23T05:37:40.000Z
2015-07-21T07:21:10.000Z
include/rex/Graphics/Scene.hxx
xoarinn/rex
75aec2382e49b97f4ccf3a5202c026ac8f4349e9
[ "MIT", "Unlicense" ]
null
null
null
include/rex/Graphics/Scene.hxx
xoarinn/rex
75aec2382e49b97f4ccf3a5202c026ac8f4349e9
[ "MIT", "Unlicense" ]
null
null
null
#pragma once #include "../Config.hxx" #include "../CUDA/DeviceList.hxx" #include "../GL/GLTexture2D.hxx" #include "../GL/GLWindow.hxx" #include "../Utility/Image.hxx" #include "Geometry/Octree.hxx" #include "Lights/AmbientLight.hxx" #include "Camera.hxx" #include "ShadePoint.hxx" #include "ViewPlane.hxx" struct GLFWwindow; // forward declare REX_NS_BEGIN /// <summary> /// An enumeration of possible render modes for the scene. /// </summary> enum class SceneRenderMode { ToImage, ToOpenGL }; /// <summary> /// Defines a scene. /// </summary> class Scene { REX_NONCOPYABLE_CLASS( Scene ) const SceneRenderMode _renderMode; ViewPlane _viewPlane; Color _backgroundColor; Camera _camera; DeviceList<Light*>* _lights; AmbientLight* _ambientLight; DeviceList<Geometry*>* _geometry; Octree* _octree; GLWindow* _window; GLTexture2D* _texture; Image* _image; /// <summary> /// Performs pre-render actions. /// </summary> __host__ bool OnPreRender(); /// <summary> /// Performs post-render actions. /// </summary> __host__ bool OnPostRender(); /// <summary> /// Updates the camera based on user input. /// <summary> /// <param name="dt">The time since the last frame.</param> /// <remarks> /// Only called when rendering to an OpenGL window. /// </remarks> __host__ void UpdateCamera( real64 dt ); /// <summary> /// Disposes of this scene. /// </summary> __host__ void Dispose(); /// <summary> /// The GLFW window key press callback. /// <summary> /// <param name="dt">The time since the last frame.</param> __host__ static void OnKeyPress( GLFWwindow* window, int key, int scancode, int action, int mods ); public: /// <summary> /// Creates a new scene. /// </summary> /// <param name="renderMode">The render mode to use.</param> __host__ Scene( SceneRenderMode renderMode ); /// <summary> /// Destroys this scene. /// </summary> __host__ ~Scene(); /// <summary> /// Saves this scene's image. /// </summary> /// <param name="fname">The file name.</param> __host__ void SaveImage( const char* fname ) const; /// <summary> /// Builds this scene. /// </summary> /// <param name="width">The width of the rendered scene. The maximum width is 2048.</param> /// <param name="height">The height of the rendered scene. The maximum height is 2048.</param> __host__ bool Build( uint16 width, uint16 height ); /// <summary> /// Builds this scene. /// </summary> /// <param name="width">The width of the rendered scene.</param> /// <param name="height">The height of the rendered scene.</param> /// <param name="samples">The sample count to render with.</param> __host__ bool Build( uint16 width, uint16 height, int32 samples ); /// <summary> /// Builds this scene. /// </summary> /// <param name="width">The width of the rendered scene.</param> /// <param name="height">The height of the rendered scene.</param> /// <param name="samples">The sample count to render with.</param> /// <param name="fullscreen">Whether or not to be building for a fullscreen window (only applies when rendering to OpenGL).</param> __host__ bool Build( uint16 width, uint16 height, int32 samples, bool fullscreen ); /// <summary> /// Gets this scene's camera. /// </summary> __host__ Camera& GetCamera(); /// <summary> /// Renders this scene. /// </summary> __host__ void Render(); }; REX_NS_END
28.813953
135
0.614743
[ "geometry", "render" ]
96d305b3b87e3da5801afcdc1776055e604728b8
1,088
cpp
C++
compiler/nnkit-tflite/support/src/TensorUtils.cpp
juitem/ONE
8c6a4b7738074573b6ac5c82dcf1f6697520d1ed
[ "Apache-2.0" ]
255
2020-05-22T07:45:29.000Z
2022-03-29T23:58:22.000Z
compiler/nnkit-tflite/support/src/TensorUtils.cpp
juitem/ONE
8c6a4b7738074573b6ac5c82dcf1f6697520d1ed
[ "Apache-2.0" ]
5,102
2020-05-22T07:48:33.000Z
2022-03-31T23:43:39.000Z
compiler/nnkit-tflite/support/src/TensorUtils.cpp
juitem/ONE
8c6a4b7738074573b6ac5c82dcf1f6697520d1ed
[ "Apache-2.0" ]
120
2020-05-22T07:51:08.000Z
2022-02-16T19:08:05.000Z
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. 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 "nnkit/support/tflite/TensorUtils.h" namespace nnkit { namespace support { namespace tflite { nncc::core::ADT::tensor::Shape tensor_shape(const TfLiteTensor *t) { nncc::core::ADT::tensor::Shape shape; const int rank = t->dims->size; shape.resize(rank); for (int axis = 0; axis < rank; ++axis) { shape.dim(axis) = t->dims->data[axis]; } return shape; } } // namespace tflite } // namespace support } // namespace nnkit
24.727273
75
0.70864
[ "shape" ]
96dddae51ef6014c871c707e1b2ccaebbc8f5416
2,482
cpp
C++
src/channel.cpp
BernatOlle/rsim-master
e90d76105518972da004d4ff7d08c62869121c26
[ "MIT" ]
null
null
null
src/channel.cpp
BernatOlle/rsim-master
e90d76105518972da004d4ff7d08c62869121c26
[ "MIT" ]
null
null
null
src/channel.cpp
BernatOlle/rsim-master
e90d76105518972da004d4ff7d08c62869121c26
[ "MIT" ]
null
null
null
#include "channel.hpp" #include "utilities.hpp" #include <cstdlib> #include <vector> #include <algorithm> Channel::Channel(int id): cid(id){ std::vector<int> ids_concurrent_tx_nodes; std::vector<int> ids_nodes_vector; } void Channel::update_token_current_node(int assig) { if(assig == 1){ token_current_node=(token_lenght*cid)+(token_current_node+1)%token_lenght; } if(assig == 2){ token_current_node= (token_current_node+1)%token_lenght; } if(assig == 3){ token_current_node= pos + (token_current_node-pos+1)%(token_lenght); } } void Channel::set_token_current_node(int assig) { // Initialize the position of the first token if(assig == 1){ token_current_node = token_lenght*cid; } if(assig == 2){ int nodes_token = Global_params::Instance()->get_ncores(); int number_channels=Global_params::Instance()->get_nchannels(); int NxC = ceil(nodes_token/number_channels); token_current_node=cid*NxC; } if(assig==3){ token_current_node=pos; } } int Channel::get_token_current_node() { return token_current_node; } int Channel::get_channel_id(){ return cid; } int Channel::get_pos(){ return pos; } void Channel::set_pos(int inici){ pos = inici; } void Channel::set_token_lenght(int NxC){ token_lenght = NxC; } int Channel::get_ids_concurrent_tx_nodes_size(){ return ids_concurrent_tx_nodes.size(); } void Channel::push_ids_concurrent_tx_nodes(int nid){ ids_concurrent_tx_nodes.push_back(nid); } void Channel::flush_ids_concurrent_tx_nodes(){ ids_concurrent_tx_nodes.erase(ids_concurrent_tx_nodes.begin(), ids_concurrent_tx_nodes.end()); } int Channel::get_unique_kids_concurrent_tx_nodes() { if (ids_concurrent_tx_nodes.size() == 1) { return ids_concurrent_tx_nodes.front(); } else { std::cout << "ERROR: none or multiple concurrent tx nodes still in vector, but you are asking for only one" << std::endl; abort(); // TODO: THIS IS NOT THE RIGHT WAY TO EXIT A PROGRAM. USE EXCEPTIONS OR JUST ERROR CODES } } std::vector<int>::const_iterator Channel::ids_concurrent_tx_nodes_begin() { return ids_concurrent_tx_nodes.begin(); } std::vector<int>::const_iterator Channel::ids_concurrent_tx_nodes_end() { return ids_concurrent_tx_nodes.end(); } int Channel::get_nodes_vector_size(){ return ids_nodes_vector.size(); } void Channel::push_nodes_vector(int n_id){ ids_nodes_vector.push_back(n_id); } std::vector<int> Channel::get_nodes_vector(){ return ids_nodes_vector; }
24.82
129
0.7361
[ "vector" ]
96e37bdd99a73ea455556f3f22bbf56c25aa006c
6,050
cpp
C++
Max2D/hoa.2d.rotate_tilde.cpp
CICM/HoaLibrary-Max
cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6
[ "Naumen", "Condor-1.1", "MS-PL" ]
71
2015-02-23T12:24:05.000Z
2022-02-15T00:18:30.000Z
Max2D/hoa.2d.rotate_tilde.cpp
pb5/HoaLibrary-Max
cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6
[ "Naumen", "Condor-1.1", "MS-PL" ]
13
2015-04-22T17:13:53.000Z
2020-11-12T10:54:29.000Z
Max2D/hoa.2d.rotate_tilde.cpp
pb5/HoaLibrary-Max
cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2015-04-11T21:34:51.000Z
2020-02-29T14:37:53.000Z
/* // Copyright (c) 2012-2015 Eliott Paris, Julien Colafrancesco & Pierre Guillot, CICM, Universite Paris 8. // For information on usage and redistribution, and for a DISCLAIMER OF ALL // WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ /** @file hoa.2d.rotate~.cpp @name hoa.2d.rotate~ @realname hoa.2d.rotate~ @type object @module hoa @author Julien Colafrancesco, Pierre Guillot, Eliott Paris. @digest A 2d ambisonic sound field rotation external @description <o>hoa.2d.rotate~</o> applies a rotation on the ambisonic sound field. @discussion <o>hoa.2d.rotate~</o> applies a rotation on the ambisonic sound field. @category 2d, Ambisonics, MSP @seealso hoa.2d.wider~, hoa.2d.encoder~, hoa.2d.decoder~, hoa.process~, hoa.mirror~, hoa.2d.space, hoa.2d.recomposer, hoa.2d.meter~, hoa.2d.scope~ */ #include "Hoa2D.max.h" typedef struct _hoa_rotate { t_pxobject f_ob; Rotate<Hoa2d, t_sample>* f_rotate; t_sample* f_ins; t_sample* f_outs; } t_hoa_rotate; t_class *hoa_rotate_class; void *hoa_rotate_new(t_symbol *s, long argc, t_atom *argv) { // @arg 0 @name decomposition-order @optional 0 @type int @digest The ambisonic order of decomposition // @description First argument is the ambisonic order of decomposition. t_hoa_rotate *x = NULL; ulong order = 1; x = (t_hoa_rotate *)object_alloc(hoa_rotate_class); if (x) { if(argc && atom_gettype(argv) == A_LONG) order = max<long>(atom_getlong(argv), 1); x->f_rotate = new Rotate<Hoa2d, t_sample>(order); dsp_setup((t_pxobject *)x, x->f_rotate->getNumberOfHarmonics() + 1); for (int i = 0; i < x->f_rotate->getNumberOfHarmonics(); i++) outlet_new(x, "signal"); x->f_ins = new t_sample[x->f_rotate->getNumberOfHarmonics() * HOA_MAXBLKSIZE]; x->f_outs = new t_sample[x->f_rotate->getNumberOfHarmonics() * HOA_MAXBLKSIZE]; } return (x); } t_hoa_err hoa_getinfos(t_hoa_rotate* x, t_hoa_boxinfos* boxinfos) { boxinfos->object_type = HOA_OBJECT_2D; boxinfos->autoconnect_inputs = x->f_rotate->getNumberOfHarmonics(); boxinfos->autoconnect_outputs = x->f_rotate->getNumberOfHarmonics(); boxinfos->autoconnect_inputs_type = HOA_CONNECT_TYPE_AMBISONICS; boxinfos->autoconnect_outputs_type = HOA_CONNECT_TYPE_AMBISONICS; return HOA_ERR_NONE; } void hoa_rotate_float(t_hoa_rotate *x, double f) { x->f_rotate->setYaw(f); } void hoa_rotate_int(t_hoa_rotate *x, long n) { x->f_rotate->setYaw(n); } void hoa_rotate_perform64_yaw(t_hoa_rotate *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam) { for(int i = 0; i < numouts; i++) { Signal<t_sample>::copy(sampleframes, ins[i], 1, x->f_ins+i, numouts); } for(int i = 0; i < sampleframes; i++) { x->f_rotate->setYaw(ins[numins-1][i]); x->f_rotate->process(x->f_ins + numouts * i, x->f_outs + numouts * i); } for(int i = 0; i < numouts; i++) { Signal<t_sample>::copy(sampleframes, x->f_outs+i, numouts, outs[i], 1); } } void hoa_rotate_perform64(t_hoa_rotate *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam) { for(int i = 0; i < numouts; i++) { Signal<t_sample>::copy(sampleframes, ins[i], 1, x->f_ins+i, numouts); } for(int i = 0; i < sampleframes; i++) { x->f_rotate->process(x->f_ins + numouts * i, x->f_outs + numouts * i); } for(int i = 0; i < numouts; i++) { Signal<t_sample>::copy(sampleframes, x->f_outs+i, numouts, outs[i], 1); } } void hoa_rotate_dsp64(t_hoa_rotate *x, t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags) { if(count[x->f_rotate->getNumberOfHarmonics()]) object_method(dsp64, gensym("dsp_add64"), x, hoa_rotate_perform64_yaw, 0, NULL); else object_method(dsp64, gensym("dsp_add64"), x, hoa_rotate_perform64, 0, NULL); } void hoa_rotate_assist(t_hoa_rotate *x, void *b, long m, long a, char *s) { if(a == x->f_rotate->getNumberOfHarmonics()) { sprintf(s,"(signal/float) Rotation"); } else { sprintf(s,"(signal) %s", x->f_rotate->getHarmonicName(a).c_str()); } } void hoa_rotate_free(t_hoa_rotate *x) { dsp_free((t_pxobject *)x); delete x->f_rotate; delete [] x->f_ins; delete [] x->f_outs; } #ifdef HOA_PACKED_LIB int hoa_2d_rotate_main(void) #else void ext_main(void *r) #endif { t_class *c; c = class_new("hoa.2d.rotate~", (method)hoa_rotate_new, (method)hoa_rotate_free, (long)sizeof(t_hoa_rotate), 0L, A_GIMME, 0); class_setname((char *)"hoa.2d.rotate~", (char *)"hoa.2d.rotate~"); hoa_initclass(c, (method)hoa_getinfos); // @method signal @digest Array of circular harmonic signals to be rotated, rotation angle. // @description Array of circular harmonic signals to be optimized. Set the angle of the rotation of the soundfield in radian in the last inlet at signal rate. The rotation angle is anti-clockwise and wrapped between 0. and 2π. class_addmethod(c, (method)hoa_rotate_dsp64, "dsp64", A_CANT, 0); class_addmethod(c, (method)hoa_rotate_assist, "assist", A_CANT, 0); // @method float @digest Set the rotation angle. // @description Set the angle of the rotation of the soundfield in radian in the last inlet at control rate. The rotation angle is anti-clockwise and wrapped between 0. and 2π. class_addmethod(c, (method)hoa_rotate_float, "float", A_FLOAT, 0); // @method int @digest Set the rotation angle. // @description Set the angle of the rotation of the soundfield in radian in the last inlet at control rate. The rotation angle is anti-clockwise and wrapped between 0. and 2π. class_addmethod(c, (method)hoa_rotate_int, "int", A_LONG, 0); class_dspinit(c); class_register(CLASS_BOX, c); class_alias(c, gensym("hoa.rotate~")); hoa_rotate_class = c; }
33.425414
231
0.678512
[ "object" ]
96e402595c04057d818c2c3598987492a763e905
4,335
cpp
C++
Src/Common/RenderControl/ADeferredShadingPass.cpp
StavrosBizelis/NetworkDistributedDeferredShading
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
[ "MIT" ]
null
null
null
Src/Common/RenderControl/ADeferredShadingPass.cpp
StavrosBizelis/NetworkDistributedDeferredShading
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
[ "MIT" ]
null
null
null
Src/Common/RenderControl/ADeferredShadingPass.cpp
StavrosBizelis/NetworkDistributedDeferredShading
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
[ "MIT" ]
null
null
null
#include "Common/RenderControl/ADeferredShadingPass.h" #include <memory> namespace RenderControl { ADeferredShadingPass::ADeferredShadingPass(const glm::vec2& a_resolution, const glm::vec2 &a_partialResolution, const glm::vec4& a_viewportSettings, const unsigned int& a_compressPacked) :IRenderPass(a_resolution), m_resolutionPart(a_partialResolution), m_viewPortSetting(a_viewportSettings), m_compressPacked(a_compressPacked) { GetCamera()->SetDimentsions(a_resolution); } ADeferredShadingPass::~ADeferredShadingPass() {} bool ADeferredShadingPass::AddRenderable(IRenderable * a_renderable, const GeometryPassMaterialFlags& a_geometryMaterialFlags) { if (!Exists(a_renderable)) { std::shared_ptr<IShaderProgram> l_selectedMat; // get the appropriate material func // simple color if ((a_geometryMaterialFlags & (NORMAL_MAP | DIFFUSE_MAP | SPECULAR_MAP | HARDNESS_MAP | EMISSION_MAP)) == (NORMAL_MAP | DIFFUSE_MAP | SPECULAR_MAP | HARDNESS_MAP | EMISSION_MAP)) l_selectedMat = GetMaterialManager()->GetColourNormalSpecHardnessEmissionGeometryPassMaterial("", ""); else if ((a_geometryMaterialFlags & (NORMAL_MAP | DIFFUSE_MAP | SPECULAR_MAP | HARDNESS_MAP )) == (NORMAL_MAP | DIFFUSE_MAP | SPECULAR_MAP | HARDNESS_MAP)) l_selectedMat = GetMaterialManager()->GetColourNormalSpecHardnessGeometryPassMaterial("", ""); else if ((a_geometryMaterialFlags & (NORMAL_MAP | DIFFUSE_MAP | SPECULAR_MAP)) == (NORMAL_MAP | DIFFUSE_MAP | SPECULAR_MAP)) l_selectedMat = GetMaterialManager()->GetColourNormalSpecGeometryPassMaterial("", ""); else if ((a_geometryMaterialFlags & (NORMAL_MAP | DIFFUSE_MAP)) == (NORMAL_MAP | DIFFUSE_MAP)) l_selectedMat = GetMaterialManager()->GetColourNormalGeometryPassMaterial("", ""); else if ((a_geometryMaterialFlags & (DIFFUSE_MAP)) == (DIFFUSE_MAP)) l_selectedMat = GetMaterialManager()->GetColourGeometryPassMaterial("", ""); else if ((a_geometryMaterialFlags & (EMISSION_MAP)) == (EMISSION_MAP)) l_selectedMat = GetMaterialManager()->GetEmissiveGeometryPassMaterial("", ""); else if ((a_geometryMaterialFlags & (SKYBOX)) == (SKYBOX)) l_selectedMat = GetMaterialManager()->GetSkyCubeMaterial("", ""); else l_selectedMat = GetMaterialManager()->GetGeometryPassMaterial("", ""); a_renderable->SetMaterial(l_selectedMat); m_toRender[l_selectedMat].push_back(a_renderable); return true; } return false; } void ADeferredShadingPass::RemoveRenderable(IRenderable* a_renderable) { for(std::unordered_map< std::shared_ptr<IShaderProgram>, std::vector<IRenderable*> >::iterator l_iter = m_toRender.begin(); l_iter != m_toRender.end(); ++l_iter ) { std::vector<IRenderable*>::iterator l_iter2 = std::find(l_iter->second.begin(), l_iter->second.end(), a_renderable); if (l_iter2 != l_iter->second.end()) l_iter->second.erase(l_iter2); } } bool ADeferredShadingPass::Exists(IRenderable * a_renderable) const { for (std::unordered_map< std::shared_ptr<IShaderProgram>, std::vector<IRenderable*> >::const_iterator l_iter = m_toRender.cbegin(); l_iter != m_toRender.cend(); ++l_iter) { std::vector<IRenderable*>::const_iterator l_iter2 = std::find(l_iter->second.cbegin(), l_iter->second.cend(), a_renderable); if (l_iter2 != l_iter->second.end()) return true; } return false; } void ADeferredShadingPass::SetMaterialManager(MaterialControl::IMaterialManager * a_materialManager) { IRenderPass::SetMaterialManager(a_materialManager); } void ADeferredShadingPass::AddLight(IRenderable * a_light, const LightTypeFlags& a_lightType) { switch (a_lightType) { case LightTypeFlags::POINT_LIGHT: a_light->SetMaterial( m_materialManager->GetStencilLightPassMaterial("",""), 1); a_light->SetMaterial( m_materialManager->GetPointLightPassMaterial("",""), 0); break; case LightTypeFlags::SPOT_LIGHT: a_light->SetMaterial(m_materialManager->GetStencilLightPassMaterial("", ""), 1); a_light->SetMaterial(m_materialManager->GetSpotLightPassMaterial("", ""), 0); break; case LightTypeFlags::DIRECTIONAL_LIGHT: a_light->SetMaterial(m_materialManager->GetFullScreenLightPassMaterial("", "") ); break; } m_lights.insert(a_light); } void ADeferredShadingPass::RemoveLight(IRenderable* a_light) { m_lights.erase(a_light); } }
42.920792
187
0.747174
[ "vector" ]
96e40bd6bffb57f9f3d9611cfd30813b3d4c1994
6,652
cpp
C++
src/catkin_projects/perception_sandbox/src/pointcloud2_capture_node.cpp
mpetersen94/spartan
6998c959d46a475ff73ef38d3e83f8a9f3695e6d
[ "BSD-3-Clause-Clear" ]
null
null
null
src/catkin_projects/perception_sandbox/src/pointcloud2_capture_node.cpp
mpetersen94/spartan
6998c959d46a475ff73ef38d3e83f8a9f3695e6d
[ "BSD-3-Clause-Clear" ]
null
null
null
src/catkin_projects/perception_sandbox/src/pointcloud2_capture_node.cpp
mpetersen94/spartan
6998c959d46a475ff73ef38d3e83f8a9f3695e6d
[ "BSD-3-Clause-Clear" ]
null
null
null
#include <ros/ros.h> #include <unistd.h> #include <mutex> #include <string> #include "Eigen/Dense" // For argument parsing #include <gflags/gflags.h> // PCL specific includes #include <pcl/features/integral_image_normal.h> #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> // OpenCV utilities for viz #include <opencv2/core/eigen.hpp> #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/opencv.hpp" #include <sensor_msgs/PointCloud2.h> #include "common_utils/cv_utils.h" #include "common_utils/pcl_utils.h" #include "common_utils/system_utils.h" /** This node subscribes to a published PointCloud2 channel on which a structured point cloud is published. It displays the (reconstructed from the structured point cloud) RGB and depth images, and allows key input for changing the depth near and far planes (to reject really far returns) and allow saving as a PCD with XYZ, RGB, and normals (via integral image.) **/ DEFINE_string(pointcloud_topic, "/camera_1112170110/depth_registered/points", "Point cloud ROS topic to subscribe to."); using namespace std; static const string OPENCV_WINDOW_NAME = "Point Cloud Viz Window"; class Grabber { ros::NodeHandle nh_; ros::Subscriber pc2_sub_; mutex data_update_lock_; bool cloud_valid_; pcl::PointCloud<pcl::PointXYZRGBNormal> latest_cloud_; cv::Mat latest_rgb_image_; cv::Mat latest_depth_image_; cv::Mat latest_normal_image_; double z_cutoff_plane_; public: Grabber() : cloud_valid_(false), z_cutoff_plane_(3.0) { // Subscrive to input video feed and publish output video feed string sub_channel = FLAGS_pointcloud_topic; printf("Subbing to %s\n", sub_channel.c_str()); pc2_sub_ = nh_.subscribe(sub_channel, 1, &Grabber::Pc2Cb, this); cv::namedWindow(OPENCV_WINDOW_NAME); } ~Grabber() { cv::destroyWindow(OPENCV_WINDOW_NAME); } void PrintCutoff() { printf("Cutoff: %f\n", z_cutoff_plane_); } void SaveLatestData() { string filename_prefix = getTimestampString() + "_"; string rgb_filename = filename_prefix + "rgb.png"; string depth_filename = filename_prefix + "depth.png"; string normal_filename = filename_prefix + "normal.png"; string pcd_filename = filename_prefix + "pc.pcd"; data_update_lock_.lock(); cv::imwrite(rgb_filename, latest_rgb_image_); cv::imwrite(depth_filename, latest_depth_image_); cv::imwrite(normal_filename, latest_normal_image_); pcl::io::savePCDFileBinary(pcd_filename, latest_cloud_); data_update_lock_.unlock(); printf("Saved data to file %s[rgb,depth,normal,pc].[png,pcd]\n", filename_prefix.c_str()); } void Update(char key_input) { if (cloud_valid_) { // Do visualization data_update_lock_.lock(); auto image_grid = makeGridOfImages( {latest_rgb_image_, convertToColorMap(latest_depth_image_, z_cutoff_plane_, 0.0), latest_normal_image_}, 3, 10); data_update_lock_.unlock(); cv::imshow(OPENCV_WINDOW_NAME, image_grid); // Handle keystrokes switch (key_input) { case 's': // save things SaveLatestData(); break; case '[': // Bring cutoff plane closer z_cutoff_plane_ -= 0.1; PrintCutoff(); break; case '{': z_cutoff_plane_ -= 1.0; PrintCutoff(); break; case ']': // Bring cutoff plane farther z_cutoff_plane_ += 0.1; PrintCutoff(); break; case '}': z_cutoff_plane_ += 1.0; PrintCutoff(); break; } } } void Pc2Cb(const sensor_msgs::PointCloud2ConstPtr& cloud_msg) { // Convert to PCL data type pcl::PCLPointCloud2 pcl_pc2; pcl_conversions::toPCL(*cloud_msg, pcl_pc2); // Ensure we're ready to extract the rgb and depth images // before grabbing the lock. int width = pcl_pc2.width; int height = pcl_pc2.height; if (latest_rgb_image_.rows != height || latest_rgb_image_.cols != width) { latest_rgb_image_ = cv::Mat::zeros(height, width, CV_8UC3); } if (latest_depth_image_.rows != height || latest_depth_image_.cols != width) { latest_depth_image_ = cv::Mat::zeros(height, width, CV_32FC1); } if (latest_normal_image_.rows != height || latest_normal_image_.cols != width) { latest_normal_image_ = cv::Mat::zeros(height, width, CV_8UC3); } data_update_lock_.lock(); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_without_normals( new pcl::PointCloud<pcl::PointXYZRGB>); pcl::fromPCLPointCloud2(pcl_pc2, *cloud_without_normals); // Do integral-image normal estimation, which should be pretty quick // as the input point cloud is structured in a grid. pcl::PointCloud<pcl::Normal> normals; pcl::IntegralImageNormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne; ne.setNormalEstimationMethod(ne.AVERAGE_3D_GRADIENT); ne.setMaxDepthChangeFactor(0.02f); ne.setNormalSmoothingSize(10.0f); ne.setInputCloud(cloud_without_normals); ne.compute(normals); pcl::concatenateFields(*cloud_without_normals, normals, latest_cloud_); for (int u = 0; u < height; u++) { for (int v = 0; v < width; v++) { // OpenCV defaults to bgr latest_rgb_image_.at<cv::Vec3b>(u, v)[2] = latest_cloud_(v, u).r; latest_rgb_image_.at<cv::Vec3b>(u, v)[1] = latest_cloud_(v, u).g; latest_rgb_image_.at<cv::Vec3b>(u, v)[0] = latest_cloud_(v, u).b; // RGB-encoding of normal vector: Map [-1,1] -> [0, 255] latest_normal_image_.at<cv::Vec3b>(u, v)[2] = (unsigned char)(255 * ((latest_cloud_(v, u).normal_x + 1.) / 2.)); latest_normal_image_.at<cv::Vec3b>(u, v)[1] = (unsigned char)(255 * ((latest_cloud_(v, u).normal_y + 1.) / 2.)); latest_normal_image_.at<cv::Vec3b>(u, v)[0] = (unsigned char)(255 * ((latest_cloud_(v, u).normal_z + 1.) / 2.)); latest_depth_image_.at<float>(u, v) = Vector3dFromPclPoint(latest_cloud_(v, u)).norm(); } } cloud_valid_ = true; data_update_lock_.unlock(); } }; int main(int argc, char** argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); ros::init(argc, argv, "pointcloud2_capture_node"); Grabber gr; while (ros::ok()) { // Wait 33 ms (~30hz update rate) and watch for keystrokes char k = cv::waitKey(33); gr.Update(k); ros::spinOnce(); } return 0; }
32.135266
78
0.660854
[ "vector" ]
96ed9c02c416139df0cd889f3cd7c91600021835
2,371
cpp
C++
src/memory.cpp
pouyajamali/semantic_vtr
f80130faffbab38ceeb0351c8aad22872027660f
[ "BSD-3-Clause" ]
8
2019-02-14T08:55:01.000Z
2022-02-08T00:38:26.000Z
src/memory.cpp
pouyajamali/semantic_vtr
f80130faffbab38ceeb0351c8aad22872027660f
[ "BSD-3-Clause" ]
null
null
null
src/memory.cpp
pouyajamali/semantic_vtr
f80130faffbab38ceeb0351c8aad22872027660f
[ "BSD-3-Clause" ]
7
2019-11-22T13:27:48.000Z
2021-11-03T00:50:34.000Z
/** Software License Agreement (BSD) \file memory.cpp \authors Faraz Shamshirdar <fshamshi@sfu.ca> \copyright Copyright (c) 2017, Autonomy Lab (Simon Fraser University), 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 Autonomy Lab 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 WAR- RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN- DIRECT, 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 "memory.h" Memory::Memory() : memory(new std::vector<multi_cftld_ros::Tracks>()) { imageMemory = new std::vector<sensor_msgs::Image>(); // for testing } Memory::~Memory() { delete memory; delete imageMemory; // for testing } void Memory::append(multi_cftld_ros::Tracks tracks) { memory->push_back(tracks); } // for testing void Memory::appendImage(sensor_msgs::Image image) { imageMemory->push_back(image); } int Memory::size() const { return memory->size(); } multi_cftld_ros::Tracks Memory::get(int index) const { return memory->at(index); } // for testing sensor_msgs::Image Memory::getImage(int index) const { return imageMemory->at(index); } void Memory::clear() { memory->clear(); imageMemory->clear(); }
34.362319
110
0.771404
[ "vector" ]
96f0b8231cc725e04bf83f9c52ba0952b733756c
13,244
cpp
C++
qt-creator-opensource-src-4.6.1/src/libs/modelinglib/qmt/diagram_scene/items/componentitem.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
qt-creator-opensource-src-4.6.1/src/libs/modelinglib/qmt/diagram_scene/items/componentitem.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
null
null
null
qt-creator-opensource-src-4.6.1/src/libs/modelinglib/qmt/diagram_scene/items/componentitem.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
/**************************************************************************** ** ** Copyright (C) 2016 Jochen Becher ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "componentitem.h" #include "qmt/diagram_controller/diagramcontroller.h" #include "qmt/diagram/dcomponent.h" #include "qmt/diagram_scene/diagramsceneconstants.h" #include "qmt/diagram_scene/diagramscenemodel.h" #include "qmt/diagram_scene/parts/contextlabelitem.h" #include "qmt/diagram_scene/parts/customiconitem.h" #include "qmt/diagram_scene/parts/editabletextitem.h" #include "qmt/diagram_scene/parts/stereotypesitem.h" #include "qmt/infrastructure/geometryutilities.h" #include "qmt/infrastructure/qmtassert.h" #include "qmt/stereotype/stereotypecontroller.h" #include "qmt/stereotype/stereotypeicon.h" #include "qmt/style/style.h" #include "qmt/tasks/diagramscenecontroller.h" #include <QGraphicsScene> #include <QGraphicsRectItem> #include <QGraphicsSimpleTextItem> #include <QBrush> #include <QPen> #include <QFont> #include <algorithm> namespace qmt { static const qreal RECT_HEIGHT = 15.0; static const qreal RECT_WIDTH = 45.0; static const qreal UPPER_RECT_Y = 10.0; static const qreal RECT_Y_DISTANCE = 10.0; static const qreal LOWER_RECT_MIN_Y = 10.0; static const qreal BODY_VERT_BORDER = 4.0; static const qreal BODY_HORIZ_BORDER = 4.0; ComponentItem::ComponentItem(DComponent *component, DiagramSceneModel *diagramSceneModel, QGraphicsItem *parent) : ObjectItem("component", component, diagramSceneModel, parent) { } ComponentItem::~ComponentItem() { } void ComponentItem::update() { prepareGeometryChange(); updateStereotypeIconDisplay(); const Style *style = adaptedStyle(stereotypeIconId()); // custom icon if (stereotypeIconDisplay() == StereotypeIcon::DisplayIcon) { if (!m_customIcon) m_customIcon = new CustomIconItem(diagramSceneModel(), this); m_customIcon->setStereotypeIconId(stereotypeIconId()); m_customIcon->setBaseSize(stereotypeIconMinimumSize(m_customIcon->stereotypeIcon(), CUSTOM_ICON_MINIMUM_AUTO_WIDTH, CUSTOM_ICON_MINIMUM_AUTO_HEIGHT)); m_customIcon->setBrush(style->fillBrush()); m_customIcon->setPen(style->outerLinePen()); m_customIcon->setZValue(SHAPE_ZVALUE); } else if (m_customIcon) { m_customIcon->scene()->removeItem(m_customIcon); delete m_customIcon; m_customIcon = nullptr; } // shape bool deleteRects = false; if (!m_customIcon) { if (!m_shape) m_shape = new QGraphicsRectItem(this); m_shape->setBrush(style->fillBrush()); m_shape->setPen(style->outerLinePen()); m_shape->setZValue(SHAPE_ZVALUE); if (!hasPlainShape()) { if (!m_upperRect) m_upperRect = new QGraphicsRectItem(this); m_upperRect->setBrush(style->fillBrush()); m_upperRect->setPen(style->outerLinePen()); m_upperRect->setZValue(SHAPE_DETAILS_ZVALUE); if (!m_lowerRect) m_lowerRect = new QGraphicsRectItem(this); m_lowerRect->setBrush(style->fillBrush()); m_lowerRect->setPen(style->outerLinePen()); m_lowerRect->setZValue(SHAPE_DETAILS_ZVALUE); } else { deleteRects = true; } } else { deleteRects = true; if (m_shape) { m_shape->scene()->removeItem(m_shape); delete m_shape; m_shape = nullptr; } } if (deleteRects) { if (m_lowerRect) { m_lowerRect->scene()->removeItem(m_lowerRect); delete m_lowerRect; m_lowerRect = nullptr; } if (m_upperRect) { m_upperRect->scene()->removeItem(m_upperRect); delete m_upperRect; m_upperRect = nullptr; } } // stereotypes updateStereotypes(stereotypeIconId(), stereotypeIconDisplay(), style); // component name updateNameItem(style); // context if (!suppressTextDisplay() && showContext()) { if (!m_contextLabel) m_contextLabel = new ContextLabelItem(this); m_contextLabel->setFont(style->smallFont()); m_contextLabel->setBrush(style->textBrush()); m_contextLabel->setContext(object()->context()); } else if (m_contextLabel) { m_contextLabel->scene()->removeItem(m_contextLabel); delete m_contextLabel; m_contextLabel = nullptr; } updateSelectionMarker(m_customIcon); updateRelationStarter(); updateAlignmentButtons(); updateGeometry(); } bool ComponentItem::intersectShapeWithLine(const QLineF &line, QPointF *intersectionPoint, QLineF *intersectionLine) const { QPolygonF polygon; if (m_customIcon) { // TODO use customIcon path as shape QRectF rect = object()->rect(); rect.translate(object()->pos()); polygon << rect.topLeft() << rect.topRight() << rect.bottomRight() << rect.bottomLeft() << rect.topLeft(); } else if (hasPlainShape()) { QRectF rect = object()->rect(); rect.translate(object()->pos()); polygon << rect.topLeft() << rect.topRight() << rect.bottomRight() << rect.bottomLeft() << rect.topLeft(); } else { QRectF rect = object()->rect(); rect.translate(object()->pos()); polygon << rect.topLeft() << rect.topRight() << rect.bottomRight() << rect.bottomLeft() << rect.bottomLeft() + QPointF(0, UPPER_RECT_Y + RECT_HEIGHT + RECT_Y_DISTANCE + RECT_HEIGHT) << rect.bottomLeft() + QPointF(-RECT_WIDTH * 0.5, UPPER_RECT_Y + RECT_HEIGHT + RECT_Y_DISTANCE + RECT_HEIGHT) << rect.bottomLeft() + QPointF(-RECT_WIDTH * 0.5, UPPER_RECT_Y) << rect.bottomLeft() + QPointF(0, UPPER_RECT_Y) << rect.topLeft(); } return GeometryUtilities::intersect(polygon, line, intersectionPoint, intersectionLine); } QSizeF ComponentItem::minimumSize() const { return calcMinimumGeometry(); } QList<ILatchable::Latch> ComponentItem::horizontalLatches(ILatchable::Action action, bool grabbedItem) const { return ObjectItem::horizontalLatches(action, grabbedItem); } QList<ILatchable::Latch> ComponentItem::verticalLatches(ILatchable::Action action, bool grabbedItem) const { return ObjectItem::verticalLatches(action, grabbedItem); } bool ComponentItem::hasPlainShape() const { auto diagramComponent = dynamic_cast<DComponent *>(object()); QMT_ASSERT(diagramComponent, return false); return diagramComponent->isPlainShape(); } QSizeF ComponentItem::calcMinimumGeometry() const { double width = 0.0; double height = 0.0; if (m_customIcon) { QSizeF sz = stereotypeIconMinimumSize(m_customIcon->stereotypeIcon(), CUSTOM_ICON_MINIMUM_AUTO_WIDTH, CUSTOM_ICON_MINIMUM_AUTO_HEIGHT); if (shapeIcon().textAlignment() != qmt::StereotypeIcon::TextalignTop && shapeIcon().textAlignment() != qmt::StereotypeIcon::TextalignCenter) return sz; width = sz.width(); } height += BODY_VERT_BORDER; if (CustomIconItem *stereotypeIconItem = this->stereotypeIconItem()) { width = std::max(width, stereotypeIconItem->boundingRect().width()); height += stereotypeIconItem->boundingRect().height(); } if (StereotypesItem *stereotypesItem = this->stereotypesItem()) { width = std::max(width, stereotypesItem->boundingRect().width()); height += stereotypesItem->boundingRect().height(); } if (nameItem()) { width = std::max(width, nameItem()->boundingRect().width()); height += nameItem()->boundingRect().height(); } if (m_contextLabel) height += m_contextLabel->height(); height += BODY_VERT_BORDER; if (!hasPlainShape()) { width = RECT_WIDTH * 0.5 + BODY_HORIZ_BORDER + width + BODY_HORIZ_BORDER + RECT_WIDTH * 0.5; double minHeight = UPPER_RECT_Y + RECT_HEIGHT + RECT_Y_DISTANCE + RECT_HEIGHT + LOWER_RECT_MIN_Y; if (height < minHeight) height = minHeight; } else { width = BODY_HORIZ_BORDER + width + BODY_HORIZ_BORDER; } return GeometryUtilities::ensureMinimumRasterSize(QSizeF(width, height), 2 * RASTER_WIDTH, 2 * RASTER_HEIGHT); } void ComponentItem::updateGeometry() { prepareGeometryChange(); // calc width and height double width = 0.0; double height = 0.0; QSizeF geometry = calcMinimumGeometry(); width = geometry.width(); height = geometry.height(); if (object()->isAutoSized()) { // nothing } else { QRectF rect = object()->rect(); if (rect.width() > width) width = rect.width(); if (rect.height() > height) height = rect.height(); } // update sizes and positions double left = -width / 2.0; double right = width / 2.0; double top = -height / 2.0; double y = top; setPos(object()->pos()); QRectF rect(left, top, width, height); // the object is updated without calling DiagramController intentionally. // attribute rect is not a real attribute stored on DObject but // a backup for the graphics item used for manual resized and persistency. object()->setRect(rect); if (m_customIcon) { m_customIcon->setPos(left, top); m_customIcon->setActualSize(QSizeF(width, height)); } if (m_shape) m_shape->setRect(rect); if (m_upperRect) { QRectF upperRect(0, 0, RECT_WIDTH, RECT_HEIGHT); m_upperRect->setRect(upperRect); m_upperRect->setPos(left - RECT_WIDTH * 0.5, top + UPPER_RECT_Y); } if (m_lowerRect) { QRectF lowerRect(0, 0, RECT_WIDTH, RECT_HEIGHT); m_lowerRect->setRect(lowerRect); m_lowerRect->setPos(left - RECT_WIDTH * 0.5, top + UPPER_RECT_Y + RECT_HEIGHT + RECT_Y_DISTANCE); } if (m_customIcon) { switch (shapeIcon().textAlignment()) { case qmt::StereotypeIcon::TextalignBelow: y += height + BODY_VERT_BORDER; break; case qmt::StereotypeIcon::TextalignCenter: { double h = 0.0; if (CustomIconItem *stereotypeIconItem = this->stereotypeIconItem()) h += stereotypeIconItem->boundingRect().height(); if (StereotypesItem *stereotypesItem = this->stereotypesItem()) h += stereotypesItem->boundingRect().height(); if (nameItem()) h += nameItem()->boundingRect().height(); if (m_contextLabel) h += m_contextLabel->height(); y = top + (height - h) / 2.0; break; } case qmt::StereotypeIcon::TextalignNone: // nothing to do break; case qmt::StereotypeIcon::TextalignTop: y += BODY_VERT_BORDER; break; } } else { y += BODY_VERT_BORDER; } if (CustomIconItem *stereotypeIconItem = this->stereotypeIconItem()) { stereotypeIconItem->setPos(right - stereotypeIconItem->boundingRect().width() - BODY_HORIZ_BORDER, y); y += stereotypeIconItem->boundingRect().height(); } if (StereotypesItem *stereotypesItem = this->stereotypesItem()) { stereotypesItem->setPos(-stereotypesItem->boundingRect().width() / 2.0, y); y += stereotypesItem->boundingRect().height(); } if (nameItem()) { nameItem()->setPos(-nameItem()->boundingRect().width() / 2.0, y); y += nameItem()->boundingRect().height(); } if (m_contextLabel) { if (m_customIcon) { m_contextLabel->resetMaxWidth(); } else { double maxContextWidth = width - 2 * BODY_HORIZ_BORDER - (hasPlainShape() ? 0 : RECT_WIDTH); m_contextLabel->setMaxWidth(maxContextWidth); } m_contextLabel->setPos(-m_contextLabel->boundingRect().width() / 2.0, y); } updateSelectionMarkerGeometry(rect); updateRelationStarterGeometry(rect); updateAlignmentButtonsGeometry(rect); updateDepth(); } } // namespace qmt
35.891599
158
0.641725
[ "geometry", "object", "shape" ]
96f6afd5f7df0b8ccbe1011720688db187162cbb
1,209
cpp
C++
lib/Parallelization/Tasks/LoadObjectFilesTask.cpp
mewbak/mull
fe270faa614e3c91b5ae2baf37916eaca2f4fa08
[ "Apache-2.0" ]
null
null
null
lib/Parallelization/Tasks/LoadObjectFilesTask.cpp
mewbak/mull
fe270faa614e3c91b5ae2baf37916eaca2f4fa08
[ "Apache-2.0" ]
null
null
null
lib/Parallelization/Tasks/LoadObjectFilesTask.cpp
mewbak/mull
fe270faa614e3c91b5ae2baf37916eaca2f4fa08
[ "Apache-2.0" ]
1
2019-06-10T02:43:04.000Z
2019-06-10T02:43:04.000Z
#include "mull/Parallelization/Tasks/LoadObjectFilesTask.h" #include "mull/Logger.h" #include "mull/Parallelization/Progress.h" using namespace mull; using namespace llvm; void LoadObjectFilesTask::operator()(iterator begin, iterator end, Out &storage, progress_counter &counter) { for (auto it = begin; it != end; it++, counter.increment()) { auto objectFilePath = *it; ErrorOr<std::unique_ptr<MemoryBuffer>> buffer = MemoryBuffer::getFile(objectFilePath); if (!buffer) { Logger::error() << "Cannot load object file: " << objectFilePath << "\n"; continue; } Expected<std::unique_ptr<object::ObjectFile>> objectOrError = object::ObjectFile::createObjectFile(buffer.get()->getMemBufferRef()); if (!objectOrError) { Logger::error() << "Cannot create object file: " << objectFilePath << "\n"; continue; } std::unique_ptr<object::ObjectFile> objectFile( std::move(objectOrError.get())); auto owningObject = object::OwningBinary<object::ObjectFile>( std::move(objectFile), std::move(buffer.get())); storage.push_back(std::move(owningObject)); } }
31.815789
80
0.641026
[ "object" ]
96f6cb550c141033ef0c33bacaea13f8db49a679
2,083
cpp
C++
src/gpx/sources/Partition.cpp
GAStudyGroup/VRP
54ec7ff3f0a4247d3effe609cf916fc235a08664
[ "MIT" ]
8
2018-11-28T15:13:26.000Z
2021-10-08T18:34:28.000Z
src/gpx/sources/Partition.cpp
GAStudyGroup/VRP
54ec7ff3f0a4247d3effe609cf916fc235a08664
[ "MIT" ]
4
2018-03-28T19:26:27.000Z
2018-04-07T03:02:15.000Z
src/gpx/sources/Partition.cpp
GAStudyGroup/VRP
54ec7ff3f0a4247d3effe609cf916fc235a08664
[ "MIT" ]
2
2019-12-12T09:36:48.000Z
2020-04-23T08:26:22.000Z
#include "Partition.hpp" Partition::Partition(){}; Partition::Partition(const int id, vector<string> nodes, vector<string> accessNodes) : id(id) , nodes(nodes) , accessNodes(accessNodes){}; vector<string>& Partition::getNodes() { return (nodes); } vector<string>& Partition::getAccessNodes() { return (accessNodes); } vector<Partition::PartitionConnected>& Partition::getConnections() { return (connections); } vector<pair<string, string>> Partition::getEntryAndExits() { return (entryAndExits); } int Partition::getId() { return (id); } vector<Partition::ConnectionNode>& Partition::getConnectedTo() { return connectedTo; } void Partition::setId(const int id) { this->id = id; } void Partition::setNodes(vector<string>& nodes) { this->nodes = nodes; } void Partition::setAccessNodes(vector<string>& accessNodes) { this->accessNodes = accessNodes; } void Partition::setConnections(vector<Partition::PartitionConnected> connections) { this->connections = connections; } void Partition::setConnectedTo(vector<ConnectionNode>& connectedTo) { this->connectedTo = connectedTo; } void Partition::setEntryAndExits(vector<pair<string, string>> entryAndExits) { this->entryAndExits = entryAndExits; } ostream& operator<<(ostream& output, const Partition& partition) { output << "Partition " << partition.id << "\n"; output << "Nodes: "; for (string i : partition.nodes) { output << i << " "; } output << "\n"; output << "Access List: "; for (string i : partition.accessNodes) { output << i << " "; } output << "connectedTo: \n"; for (auto a : partition.connectedTo) { //output << "partition " << a.first << " by node " << a.second.first << " wity " << a.second.second << "\n"; output << "partition " << a.connectedPartition << " by node " << a.node << " with " << a.connectedNode << "\n"; } output << "connections: \n"; for (auto a : partition.connections) { output << a.first << " with " << a.second << "\n"; } output.flush(); return (output); }
31.089552
119
0.645703
[ "vector" ]
8c0b4066669ca8fecab6bf9a3797c6f111e1f05f
1,766
cxx
C++
examples/buffon_pi_multithread.cxx
josephmckenna/2021_June_IOP_CAPS_2021
d3c2e1d661d5fffa7233bf831b76ceccd2a69d63
[ "MIT" ]
null
null
null
examples/buffon_pi_multithread.cxx
josephmckenna/2021_June_IOP_CAPS_2021
d3c2e1d661d5fffa7233bf831b76ceccd2a69d63
[ "MIT" ]
null
null
null
examples/buffon_pi_multithread.cxx
josephmckenna/2021_June_IOP_CAPS_2021
d3c2e1d661d5fffa7233bf831b76ceccd2a69d63
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> #include <thread> #include <vector> #include <random> class looper { private: std::thread* t; const uint64_t num; const std::mt19937_64::result_type seed; const double two_pi = 2 * M_PI; const double max; std::mt19937_64 rnd; uint64_t count; public: looper(int _num, std::mt19937_64::result_type _seed) : num(_num), seed(_seed), max((double)std::mt19937_64::max()) { std::mt19937_64 rnd(seed); count = 0; } const uint64_t GetCount() { return count; } void StartThread() { t=new std::thread(&looper::run,this); } void JoinThread() { t->join(); } void run() { for (uint64_t i = 0; i < num; i++) { double rand_1 = (double)rnd() / max; double y_0 = (double)rnd() / max; double y_coordinate = fabs(sin(two_pi*rand_1)); if (y_coordinate > y_0) count++; } return; } }; int main() { long long num; printf("What is N: "); scanf("%lld", &num); int threads; printf("# of threads: "); scanf("%d", &threads); struct timeval stop, start; gettimeofday(&start, NULL); std::vector<looper*> loopers; loopers.reserve(threads); for (int i = 0; i < threads; i++) { looper* a = new looper(num / threads, rand()); a->StartThread(); loopers.push_back(a); } uint64_t count = 0; for (int i = 0; i < threads; i++) { loopers[i]->JoinThread(); count += loopers[i]->GetCount(); } double frac_error = 2 * (((((double)num) / count) / M_PI_2) - 1); gettimeofday(&stop, NULL); printf("Count = %lu \n Fractional Error = %lf \n", count, frac_error); double time_dif = (stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec - start.tv_usec; printf("Time per = %f us/N \n", time_dif / num); exit(0); return 0; }
19.406593
115
0.622877
[ "vector" ]
8c0f3d46d59722d136228bcf35c986a993153216
1,360
hpp
C++
include/caffe/layers/cpfp_conversion_layer.hpp
dicecco1/fpga_caffe
7a191704efd7873071cfef35772d7e7bf3e3cfd6
[ "Intel", "BSD-2-Clause" ]
134
2016-10-05T22:10:19.000Z
2022-03-26T07:13:55.000Z
include/caffe/layers/cpfp_conversion_layer.hpp
honorpeter/fpga_caffe
7a191704efd7873071cfef35772d7e7bf3e3cfd6
[ "Intel", "BSD-2-Clause" ]
14
2016-11-20T21:16:38.000Z
2020-04-14T04:58:32.000Z
include/caffe/layers/cpfp_conversion_layer.hpp
honorpeter/fpga_caffe
7a191704efd7873071cfef35772d7e7bf3e3cfd6
[ "Intel", "BSD-2-Clause" ]
58
2016-10-03T01:23:47.000Z
2021-11-24T12:17:30.000Z
#ifndef CAFFE_CPFP_CONVERSION_LAYER_HPP_ #define CAFFE_CPFP_CONVERSION_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * @brief Converts the input blob from Dtype to half precision, but maintains * the shape and types. * */ template <typename Dtype> class CPFPConversionLayer : public Layer<Dtype> { public: /** * @param */ explicit CPFPConversionLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "CPFP Conversion"; } virtual inline int MinBottomBlobs() const { return 1; } virtual inline int MinTopBlobs() const { return 1; } virtual inline bool EqualNumBottomTopBlobs() const { return true; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); vector<int> bottom_shape_; bool convert_to_; }; } // namespace caffe #endif // CAFFE_CPFP_CONVERSION_LAYER_HPP_
28.333333
78
0.716176
[ "shape", "vector" ]
22c85fc8f9f97b05ded732dc9fb45183e039eb67
2,301
cc
C++
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_MouseTarget.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_MouseTarget.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_MouseTarget.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
#include "ag_MouseTarget.h" // Library headers. // PCRaster library headers. // Module headers. /*! \file This file contains the implementation of the MouseTarget class. */ //------------------------------------------------------------------------------ // DEFINITION OF STATIC MOUSETARGET MEMBERS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // DEFINITION OF MOUSETARGET MEMBERS //------------------------------------------------------------------------------ //! ctor ag::MouseTarget::MouseTarget() { } //! dtor ag::MouseTarget::~MouseTarget() { } //! Initializes the object. /*! After calling this function, moved() will return false. */ void ag::MouseTarget::initialize() { d_press = QPoint(); d_move = QPoint(); } //! Sets the position of the mouse press. /*! \param pos Position of mouse press. */ void ag::MouseTarget::press(const QPoint& pos) { d_press = pos; d_move = pos; } //! Sets position after mouse move. /*! \param pos Position of mouse after move. */ void ag::MouseTarget::move(const QPoint& pos) { d_move = pos; } //! Returns true if the mouse has moved since the press. /*! \return true if the mouse has moved. */ bool ag::MouseTarget::moved() const { return !(d_move - d_press).isNull(); } //! Returns the position where the mouse was pressed. /*! \return Mouse position. */ const QPoint& ag::MouseTarget::pressPosition() const { return d_press; } //! Returns the position where the mouse was moved to. /*! \return Mouse position. */ const QPoint& ag::MouseTarget::movePosition() const { return d_move; } //! Returns the amount of mouse movement since the press. /*! \return Amount of mouse movement. */ QPoint ag::MouseTarget::movement() const { return d_move - d_press; } //------------------------------------------------------------------------------ // DEFINITION OF FREE OPERATORS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // DEFINITION OF FREE FUNCTIONS //------------------------------------------------------------------------------
17.300752
80
0.479791
[ "object" ]
22d34797367c80f33b70c5662ea5c6b18ad22ebb
606
cpp
C++
projection-area-of-3d-shapes/projection-area-of-3d-shapes.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
2
2021-08-29T12:51:09.000Z
2021-10-18T23:24:41.000Z
projection-area-of-3d-shapes/projection-area-of-3d-shapes.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
null
null
null
projection-area-of-3d-shapes/projection-area-of-3d-shapes.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
null
null
null
class Solution { public: int projectionArea(vector<vector<int>>& grid) { int res=0; for(int i=0;i<grid.size() ; i++) { int maxi=0; for(int j=0;j<grid[0].size() ; j++) { maxi = max( maxi , grid[i][j] ); if(grid[i][j]>0 ) res++; } res+=maxi; } for(int j=0;j<grid[0].size(); j++) { int maxi=0; for(int i=0; i<grid.size() ; i++) maxi = max(maxi , grid[i][j]); res+=maxi; } return res; } };
25.25
51
0.364686
[ "vector" ]
22e030e740aa213059cb7d7ad6976ba4855e487d
10,775
cpp
C++
source/FAST/Streamers/RealSenseStreamer.cpp
SINTEFMedtek/FAST
d4c1ec49bd542f78d84c00e990bbedd2126cfffa
[ "BSD-2-Clause" ]
3
2019-12-13T07:53:51.000Z
2020-02-05T09:11:58.000Z
source/FAST/Streamers/RealSenseStreamer.cpp
SINTEFMedtek/FAST
d4c1ec49bd542f78d84c00e990bbedd2126cfffa
[ "BSD-2-Clause" ]
1
2020-02-05T09:28:37.000Z
2020-02-05T09:28:37.000Z
source/FAST/Streamers/RealSenseStreamer.cpp
SINTEFMedtek/FAST
d4c1ec49bd542f78d84c00e990bbedd2126cfffa
[ "BSD-2-Clause" ]
1
2020-12-10T12:40:59.000Z
2020-12-10T12:40:59.000Z
#include "RealSenseStreamer.hpp" #include "FAST/Data/Image.hpp" #include "FAST/Data/Mesh.hpp" #include <librealsense2/rs.hpp> #include "librealsense2/rsutil.h" #include <atomic> namespace fast { RealSenseStreamer::RealSenseStreamer() { createOutputPort<Image>(0); // RGB createOutputPort<Image>(1); // Depth image createOutputPort<Mesh>(2); // Point cloud mNrOfFrames = 0; mIsModified = true; } void RealSenseStreamer::execute() { startStream(); waitForFirstFrame(); } MeshVertex RealSenseStreamer::getPoint(int x, int y) { if(mDepthImage && mColorImage) { float upoint[3]; float upixel[2] = {(float) x, (float) y}; auto depthAccess = mDepthImage->getImageAccess(ACCESS_READ); float depth = depthAccess->getScalar(Vector2i(x, y)) / 1000.0f; // Get depth of current frame in meters rs2_deproject_pixel_to_point(upoint, intrinsics, upixel, depth); MeshVertex vertex(Vector3f(upoint[0] * 1000, upoint[1] * 1000, upoint[2] * 1000)); // Convert to mm auto colorAccess = mColorImage->getImageAccess(ACCESS_READ); Vector4f color = colorAccess->getVector(Vector2i(x, y)); vertex.setColor(Color(color.x()/255.0f, color.y()/255.0f, color.z()/255.0f)); // get color of current frame return vertex; } else { throw Exception("Can't call getPoint before any color or depth data has arrived."); } } static float get_depth_scale(rs2::device dev) { // Go over the device's sensors for (rs2::sensor& sensor : dev.query_sensors()) { // Check if the sensor if a depth sensor if (rs2::depth_sensor dpt = sensor.as<rs2::depth_sensor>()) { return dpt.get_depth_scale(); } } throw Exception("Device does not have a depth sensor"); } void RealSenseStreamer::generateStream() { reportInfo() << "Trying to set up real sense stream..." << reportEnd(); // Create a Pipeline - this serves as a top-level API for streaming and processing frames rs2::pipeline pipeline; rs2::config config; // Use a configuration object to request only depth from the pipeline config.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30); config.enable_stream(RS2_STREAM_COLOR, 640, 480, RS2_FORMAT_RGB8, 30); // Configure and start the pipeline rs2::pipeline_profile profile; try { profile = pipeline.start(config); } catch(rs2::error &e) { throw Exception("Error could not start real sense streaming pipeline: " + std::string(e.what())); } const float depth_scale = get_depth_scale(profile.get_device()); auto stream = profile.get_stream(RS2_STREAM_DEPTH).as<rs2::video_stream_profile>(); auto tmp = stream.get_intrinsics(); intrinsics = &tmp; // Create a rs2::align object. // rs2::align allows us to perform alignment of depth frames to others frames //The "align_to" is the stream type to which we plan to align depth frames. rs2::align align(RS2_STREAM_COLOR); // Declare filters rs2::decimation_filter dec_filter; // Decimation - reduces depth frame density rs2::spatial_filter spat_filter; // Spatial - edge-preserving spatial smoothing rs2::temporal_filter temp_filter; // Temporal - reduces temporal noise // Declare disparity transform from depth to disparity and vice versa rs2::disparity_transform depth_to_disparity(true); rs2::disparity_transform disparity_to_depth(false); // Declaring two concurrent queues that will be used to push and pop frames from different threads rs2::frame_queue color_data_queue; rs2::frame_queue depth_data_queue; // Atomic boolean to allow thread safe way to stop the thread std::atomic_bool stopped(false); // Create a thread for getting frames from the device and process them // to prevent UI thread from blocking due to long computations. std::thread processing_thread([&]() { while (!stopped) //While application is running { rs2::frameset frames = pipeline.wait_for_frames(); // Wait for next set of frames from the camera //Get processed aligned frame rs2::frameset processed = align.process(frames); // Trying to get both other and aligned depth frames rs2::video_frame color_frame = processed.first(RS2_STREAM_COLOR); rs2::depth_frame depth_frame = processed.get_depth_frame(); // Aligned depth frame //If one of them is unavailable, continue iteration if(!depth_frame || !color_frame) continue; rs2::frame filtered = depth_frame; // Does not copy the frame, only adds a reference /* Apply filters. The implemented flow of the filters pipeline is in the following order: 1. (apply decimation filter) 2. transform the scence into disparity domain 3. apply spatial filter 4. apply temporal filter 5. revert the results back (if step Disparity filter was applied to depth domain (each post processing block is optional and can be applied independantly). */ filtered = depth_to_disparity.process(filtered); filtered = spat_filter.process(filtered); filtered = temp_filter.process(filtered); filtered = disparity_to_depth.process(filtered); // Push filtered & original data to their respective queues // Note, pushing to two different queues might cause the application to display // original and filtered pointclouds from different depth frames // To make sure they are synchronized you need to push them together or add some // synchronization mechanisms depth_data_queue.enqueue(filtered); color_data_queue.enqueue(color_frame); } }); while(true) { { // Check if stop signal is sent std::unique_lock<std::mutex> lock(m_stopMutex); if(m_stop) { m_streamIsStarted = false; m_firstFrameIsInserted = false; break; } } // Block program until frames arrive rs2::frame depth_frame; depth_data_queue.poll_for_frame(&depth_frame); rs2::frame color_frame; color_data_queue.poll_for_frame(&color_frame); if(!color_frame || !depth_frame) continue; // Get the depth frame's dimensions const uint16_t* p_depth_frame = reinterpret_cast<const uint16_t*>(depth_frame.get_data()); uint8_t* p_other_frame = reinterpret_cast<uint8_t*>(const_cast<void*>(color_frame.get_data())); int width = static_cast<rs2::video_frame>(color_frame).get_width(); int height = static_cast<rs2::video_frame>(color_frame).get_height(); //std::cout << "color size: " << width << " " << height << std::endl; int other_bpp = static_cast<rs2::video_frame>(color_frame).get_bytes_per_pixel(); std::unique_ptr<float[]> depthData = std::make_unique<float[]>(width*height); std::vector<MeshVertex> points; for(int y = 0; y < height; y++) { auto depth_pixel_index = y * width; for(int x = 0; x < width; x++, ++depth_pixel_index) { // Get the depth value of the current pixel float pixels_distance = depth_scale * p_depth_frame[depth_pixel_index]; depthData[depth_pixel_index] = pixels_distance * 1000.0f; // To mm // Calculate the offset in other frame's buffer to current pixel auto offset = depth_pixel_index * other_bpp; // Check if the depth value is invalid (<=0) or greater than the threshold if(pixels_distance*1000 <= mMinRange || pixels_distance*1000 > mMaxRange) { // Set pixel to "background" color (0x999999) //std::cout << "setting pixel to bg.." << std::endl; std::memset(&p_other_frame[offset], 0x00, other_bpp); } else { //std::cout << "creating mesh point.." << std::endl; // Create point for point cloud float upoint[3]; float upixel[2] = {(float)x, (float)y}; rs2_deproject_pixel_to_point(upoint, intrinsics, upixel, pixels_distance); MeshVertex vertex(Vector3f(upoint[0]*1000, upoint[1]*1000, upoint[2]*1000)); // Convert to mm vertex.setColor(Color(p_other_frame[offset]/255.0f, p_other_frame[offset+1]/255.0f, p_other_frame[offset+2]/255.0f)); if(vertex.getPosition()[0] > mMaxWidth || vertex.getPosition()[0] < mMinWidth) continue; if(vertex.getPosition()[1] > mMaxHeight || vertex.getPosition()[1] < mMinHeight) continue; points.push_back(vertex); } } } // Create depth image Image::pointer depthImage = Image::New(); depthImage->create(width, height, TYPE_FLOAT, 1, std::move(depthData)); mDepthImage = depthImage; // Create mesh Mesh::pointer cloud = Mesh::New(); cloud->create(points); // Create RGB camera image std::unique_ptr<uint8_t[]> colorData = std::make_unique<uint8_t[]>(width*height*3); std::memcpy(colorData.get(), p_other_frame, width*height*sizeof(uint8_t)*3); Image::pointer colorImage = Image::New(); colorImage->create(width, height, TYPE_UINT8, 3, std::move(colorData)); mColorImage = colorImage; addOutputData(0, colorImage); addOutputData(1, depthImage); addOutputData(2, cloud); frameAdded(); mNrOfFrames++; } stopped = true; processing_thread.join(); reportInfo() << "Real sense streamer stopped" << Reporter::end(); } uint RealSenseStreamer::getNrOfFrames() const { return mNrOfFrames; } RealSenseStreamer::~RealSenseStreamer() { stop(); } void RealSenseStreamer::setMaxRange(float range) { if(range < 0) throw Exception("Range has to be >= 0"); mMaxRange = range; } void RealSenseStreamer::setMinRange(float range) { if(range < 0) throw Exception("Range has to be >= 0"); mMinRange = range; } void RealSenseStreamer::setMaxWidth(float range) { mMaxWidth = range; } void RealSenseStreamer::setMinWidth(float range) { mMinWidth = range; } void RealSenseStreamer::setMaxHeight(float range) { mMaxHeight = range; } void RealSenseStreamer::setMinHeight(float range) { mMinHeight = range; } }
38.758993
137
0.63471
[ "mesh", "object", "vector", "transform" ]
22e3b0c1110978f7c91c0e72be5d1473c7798c86
2,817
cpp
C++
model_phm_edges.cpp
alexkernphysiker/JPET-Model-scintillator-plate
326d6676bc4e32f12899a600bf5252332981f061
[ "MIT-0" ]
null
null
null
model_phm_edges.cpp
alexkernphysiker/JPET-Model-scintillator-plate
326d6676bc4e32f12899a600bf5252332981f061
[ "MIT-0" ]
null
null
null
model_phm_edges.cpp
alexkernphysiker/JPET-Model-scintillator-plate
326d6676bc4e32f12899a600bf5252332981f061
[ "MIT-0" ]
null
null
null
// this file is distributed under // MIT license #include <iostream> #include <sstream> #include <gnuplot_wrap.h> #include <math_h/tabledata.h> #include <RectScin/signal_processing.h> #include <RectScin/signal_statistics.h> #include "model_objects/plastic_scin.h" #include "model_objects/silicon.h" using namespace std; using namespace MathTemplates; using namespace GnuplotWrap; using namespace RectangularScintillator; using namespace Model; const size_t ev_n=200; Vec ScinSize={1000,1000,80},PosStep={ScinSize[0]/8.0,ScinSize[1]/8.0}, PhmStep_edge={4,4,4}; int main(int,char**){ Plotter::Instance().SetOutput(".","model.phm.edges.plot"); for(size_t order_statistic=0;order_statistic<3;order_statistic++){ Distribution2D<double> place_reconstruction(BinsByStep(-10.0,0.25,+10.0),BinsByStep(-10.0,0.25,+10.0)); BC420 scintillator({make_pair(0,ScinSize[0]),make_pair(0,ScinSize[1]),make_pair(0,ScinSize[2])}); auto output=make_shared<SignalsToFile>(); { auto hist_fill=make_shared<SignalsAnalyse>([&place_reconstruction](const Vec&P){ place_reconstruction.Fill(P[0],P[1]); }); auto trigger=make_shared<AllSignalsPresent>(); for(size_t dimension=0;dimension<2;dimension++){ auto time_diff=make_shared<SignalSumm>(); for(auto side=RectDimensions::Left;side<=RectDimensions::Right;inc(side)){ auto allside=make_shared<SignalSortAndSelect2>(order_statistic); for(double x=PhmStep_edge[dimension]/2.0;x<ScinSize[dimension];x+=PhmStep_edge[dimension]) for(double z=PhmStep_edge[2]/2.0;z<ScinSize[2];z+=PhmStep_edge[2]){ auto phm=hamamatsu({x,z},1.0); scintillator.Surface(dimension,side)>>phm; allside<<phm->Time(); } auto index=make_shared<Signal>(),time=make_shared<Signal>(), index_triggered=make_shared<Signal>(),time_triggered=make_shared<Signal>(); allside>>index>>time; (trigger<<index<<time)>>index_triggered>>time_triggered; output<<index_triggered<<time_triggered; auto pin2diff=SignalMultiply(pow(-1.0,double(int(side)))); time_triggered>>pin2diff; time_diff<<pin2diff; } hist_fill<<time_diff; } } scintillator.Configure(BC420::Reflections(7)); RandomUniform<> distrz(0,ScinSize[2]); for(double x=PosStep[0];x<ScinSize[0];x+=PosStep[0]) for(double y=PosStep[1];y<ScinSize[1];y+=PosStep[1]){ ostringstream name,name2; name<<"DATA."<<x<<"."<<y<<".edges."<<order_statistic<<".txt"; output->Redirect(name.str()); cout<<"BEGIN "<<name.str()<<endl; for(size_t cnt=0;cnt<ev_n;cnt++) scintillator.RegisterGamma({x,y,distrz()},3000); cout<<"END "<<name.str()<<endl; } PlotHist2d(sp2).Distr(place_reconstruction,to_string(order_statistic)); PlotHist2d(normal).Distr(place_reconstruction,to_string(order_statistic)); } cout<<"GOODBYE!"<<endl; }
40.826087
105
0.71601
[ "model" ]
22e47759269ca6244737a1bc36e32014e2e179c6
42,997
cpp
C++
src/cube.cpp
noerw/gdalcubes
ef530c7708894ec45ef7af75bef0f68d489fab8c
[ "Zlib", "NetCDF", "MIT-0", "MIT", "BSL-1.0" ]
null
null
null
src/cube.cpp
noerw/gdalcubes
ef530c7708894ec45ef7af75bef0f68d489fab8c
[ "Zlib", "NetCDF", "MIT-0", "MIT", "BSL-1.0" ]
null
null
null
src/cube.cpp
noerw/gdalcubes
ef530c7708894ec45ef7af75bef0f68d489fab8c
[ "Zlib", "NetCDF", "MIT-0", "MIT", "BSL-1.0" ]
null
null
null
/* MIT License Copyright (c) 2019 Marius Appel <marius.appel@uni-muenster.de> 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 "cube.h" #include <thread> #include <gdal_utils.h> // for GDAL translate #include <netcdf.h> #include <algorithm> // std::transform #include "build_info.h" #include "filesystem.h" #if defined(R_PACKAGE) && defined(__sun) && defined(__SVR4) #define USE_NCDF4 0 #endif #ifndef USE_NCDF4 #define USE_NCDF4 1 #endif namespace gdalcubes { void cube::write_chunks_gtiff(std::string dir, std::shared_ptr<chunk_processor> p) { if (!filesystem::exists(dir)) { filesystem::mkdir_recursive(dir); } if (!filesystem::is_directory(dir)) { throw std::string("ERROR in cube::write_chunks_gtiff(): output is not a directory."); } GDALDriver *gtiff_driver = (GDALDriver *)GDALGetDriverByName("GTiff"); if (gtiff_driver == NULL) { throw std::string("ERROR: cannot find GDAL driver for GTiff."); } std::shared_ptr<progress> prg = config::instance()->get_default_progress_bar()->get(); prg->set(0); // explicitly set to zero to show progress bar immediately std::function<void(chunkid_t, std::shared_ptr<chunk_data>, std::mutex &)> f = [this, dir, prg, gtiff_driver](chunkid_t id, std::shared_ptr<chunk_data> dat, std::mutex &m) { bounds_st cextent = this->bounds_from_chunk(id); // implemented in derived classes double affine[6]; affine[0] = cextent.s.left; affine[3] = cextent.s.top; affine[1] = _st_ref->dx(); affine[5] = -_st_ref->dy(); affine[2] = 0.0; affine[4] = 0.0; CPLStringList out_co; //out_co.AddNameValue("TILED", "YES"); //out_co.AddNameValue("BLOCKXSIZE", "256"); // out_co.AddNameValue("BLOCKYSIZE", "256"); for (uint16_t ib = 0; ib < dat->count_bands(); ++ib) { for (uint32_t it = 0; it < dat->size()[1]; ++it) { std::string out_file = filesystem::join(dir, (std::to_string(id) + "_" + std::to_string(ib) + "_" + std::to_string(it) + ".tif")); GDALDataset *gdal_out = gtiff_driver->Create(out_file.c_str(), dat->size()[3], dat->size()[2], 1, GDT_Float64, out_co.List()); CPLErr res = gdal_out->GetRasterBand(1)->RasterIO(GF_Write, 0, 0, dat->size()[3], dat->size()[2], ((double *)dat->buf()) + (ib * dat->size()[1] * dat->size()[2] * dat->size()[3] + it * dat->size()[2] * dat->size()[3]), dat->size()[3], dat->size()[2], GDT_Float64, 0, 0, NULL); if (res != CE_None) { GCBS_WARN("RasterIO (write) failed for band " + _bands.get(ib).name); } gdal_out->GetRasterBand(1)->SetNoDataValue(std::stod(_bands.get(ib).no_data_value)); char *wkt_out; OGRSpatialReference srs_out; srs_out.SetFromUserInput(_st_ref->srs().c_str()); srs_out.exportToWkt(&wkt_out); GDALSetProjection(gdal_out, wkt_out); GDALSetGeoTransform(gdal_out, affine); CPLFree(wkt_out); GDALClose(gdal_out); } } prg->increment((double)1 / (double)this->count_chunks()); }; p->apply(shared_from_this(), f); prg->finalize(); } void cube::write_tif_collection(std::string dir, std::string prefix, bool overviews, bool cog, std::map<std::string, std::string> creation_options, std::string overview_resampling, packed_export packing, bool drop_empty_slices, std::shared_ptr<chunk_processor> p) { if (!overviews && cog) { overviews = true; } if (!filesystem::exists(dir)) { filesystem::mkdir_recursive(dir); } if (!filesystem::is_directory(dir)) { throw std::string("ERROR in cube::write_tif_collection(): invalid output directory."); } GDALDataType ot = GDT_Float64; if (packing.type != packed_export::packing_type::PACK_NONE) { if (packing.type == packed_export::packing_type::PACK_UINT8) { ot = GDT_Byte; } else if (packing.type == packed_export::packing_type::PACK_UINT16) { ot = GDT_UInt16; } else if (packing.type == packed_export::packing_type::PACK_UINT32) { ot = GDT_UInt32; } else if (packing.type == packed_export::packing_type::PACK_INT16) { ot = GDT_Int16; } else if (packing.type == packed_export::packing_type::PACK_INT32) { ot = GDT_Int32; } else if (packing.type == packed_export::packing_type::PACK_FLOAT32) { ot = GDT_Float32; packing.offset = {0.0}; packing.scale = {1.0}; packing.nodata = {std::numeric_limits<float>::quiet_NaN()}; } if (!(packing.scale.size() == 1 || packing.scale.size() == size_bands())) { std::string msg; if (size_bands() == 1) { msg = "Packed export needs exactly 1 scale and offset value."; } else { msg = "Packed export needs either n or 1 scale / offset values for n bands."; } GCBS_ERROR(msg); throw(msg); } if (packing.scale.size() != packing.offset.size()) { std::string msg = "Unequal number of scale and offset values provided for packed export."; GCBS_ERROR(msg); throw(msg); } if (packing.scale.size() != packing.nodata.size()) { std::string msg = "Unequal number of scale and nodata values provided for packed export."; GCBS_ERROR(msg); throw(msg); } } GDALDriver *gtiff_driver = (GDALDriver *)GDALGetDriverByName("GTiff"); if (gtiff_driver == NULL) { throw std::string("ERROR: cannot find GDAL driver for GTiff."); } std::shared_ptr<progress> prg = config::instance()->get_default_progress_bar()->get(); prg->set(0); // explicitly set to zero to show progress bar immediately // avoid parallel RasterIO calls to the same file std::map<uint32_t, std::mutex> mtx; // time_slice_index -> mutex CPLStringList out_co; out_co.AddNameValue("TILED", "YES"); if (creation_options.find("BLOCKXSIZE") != creation_options.end()) { out_co.AddNameValue("BLOCKXSIZE", creation_options["BLOCKXSIZE"].c_str()); } else { out_co.AddNameValue("BLOCKXSIZE", "256"); } if (creation_options.find("BLOCKYSIZE") != creation_options.end()) { out_co.AddNameValue("BLOCKYSIZE", creation_options["BLOCKYSIZE"].c_str()); } else { out_co.AddNameValue("BLOCKYSIZE", "256"); } for (auto it = creation_options.begin(); it != creation_options.end(); ++it) { std::string key = it->first; std::transform(key.begin(), key.end(), key.begin(), (int (*)(int))std::toupper); if (key == "TILED") { GCBS_WARN("Setting" + it->first + "=" + it->second + "is not allowed, ignoring GeoTIFF creation option."); continue; } if (key == "BLOCKXSIZE" || key == "BLOCKYSIZE") continue; out_co.AddNameValue(it->first.c_str(), it->second.c_str()); } // create all datasets for (uint32_t it = 0; it < size_t(); ++it) { std::string name = cog ? filesystem::join(dir, prefix + (st_reference()->t0() + st_reference()->dt() * it).to_string() + "_temp.tif") : filesystem::join(dir, prefix + (st_reference()->t0() + st_reference()->dt() * it).to_string() + ".tif"); GDALDataset *gdal_out = gtiff_driver->Create(name.c_str(), size_x(), size_y(), size_bands(), ot, out_co.List()); char *wkt_out; OGRSpatialReference srs_out; srs_out.SetFromUserInput(_st_ref->srs().c_str()); srs_out.exportToWkt(&wkt_out); GDALSetProjection(gdal_out, wkt_out); double affine[6]; affine[0] = st_reference()->left(); affine[3] = st_reference()->top(); affine[1] = st_reference()->dx(); affine[5] = -st_reference()->dy(); affine[2] = 0.0; affine[4] = 0.0; GDALSetGeoTransform(gdal_out, affine); CPLFree(wkt_out); // Setting NoData value seems to be not needed for Float64 GeoTIFFs //gdal_out->GetRasterBand(1)->SetNoDataValue(NAN); // GeoTIFF supports only one NoData value for all bands if (packing.type != packed_export::packing_type::PACK_NONE) { if (packing.scale.size() > 1) { for (uint16_t ib = 0; ib < size_bands(); ++ib) { gdal_out->GetRasterBand(ib + 1)->SetNoDataValue(packing.nodata[ib]); gdal_out->GetRasterBand(ib + 1)->SetOffset(packing.offset[ib]); gdal_out->GetRasterBand(ib + 1)->SetScale(packing.scale[ib]); } } else { for (uint16_t ib = 0; ib < size_bands(); ++ib) { gdal_out->GetRasterBand(ib + 1)->SetNoDataValue(packing.nodata[0]); gdal_out->GetRasterBand(ib + 1)->SetOffset(packing.offset[0]); gdal_out->GetRasterBand(ib + 1)->SetScale(packing.scale[0]); } } } GDALClose((GDALDatasetH)gdal_out); } std::function<void(chunkid_t, std::shared_ptr<chunk_data>, std::mutex &)> f = [this, dir, prg, &mtx, &prefix, &packing, cog, overviews](chunkid_t id, std::shared_ptr<chunk_data> dat, std::mutex &m) { for (uint32_t it = 0; it < dat->size()[1]; ++it) { uint32_t cur_t_index = chunk_limits(id).low[0] + it; std::string name = cog ? filesystem::join(dir, prefix + (st_reference()->t0() + st_reference()->dt() * cur_t_index).to_string() + "_temp.tif") : filesystem::join(dir, prefix + (st_reference()->t0() + st_reference()->dt() * cur_t_index).to_string() + ".tif"); mtx[cur_t_index].lock(); GDALDataset *gdal_out = (GDALDataset *)GDALOpen(name.c_str(), GA_Update); if (!gdal_out) { GCBS_WARN("GDAL failed to open " + name); mtx[cur_t_index].unlock(); continue; } // apply packing if (packing.type != packed_export::packing_type::PACK_NONE) { for (uint16_t ib = 0; ib < size_bands(); ++ib) { double cur_scale; double cur_offset; double cur_nodata; if (packing.scale.size() == size_bands()) { cur_scale = packing.scale[ib]; cur_offset = packing.offset[ib]; cur_nodata = packing.nodata[ib]; } else { cur_scale = packing.scale[0]; cur_offset = packing.offset[0]; cur_nodata = packing.nodata[0]; } /* * If band of cube already has scale + offset, we do not apply this before. * As a consequence, provided scale and offset values refer to actual data values * but ignore band metadata. The following commented code would apply the * unpacking before */ /* if (bands().get(ib).scale != 1 || bands().get(ib).offset != 0) { for (uint32_t i = 0; i < dat->size()[2] * dat->size()[3]; ++i) { double &v = ((double *)(dat->buf()))[ib * dat->size()[1] * dat->size()[2] * dat->size()[3] + it * dat->size()[2] * dat->size()[3] + i]; v = v * bands().get(ib).scale + bands().get(ib).offset; } } */ for (uint32_t i = 0; i < dat->size()[2] * dat->size()[3]; ++i) { double &v = ((double *)(dat->buf()))[ib * dat->size()[1] * dat->size()[2] * dat->size()[3] + it * dat->size()[2] * dat->size()[3] + i]; if (std::isnan(v)) { v = cur_nodata; } else { v = std::round((v - cur_offset) / cur_scale); // use std::round to avoid truncation bias } } } } // if packing for (uint16_t ib = 0; ib < size_bands(); ++ib) { CPLErr res = gdal_out->GetRasterBand(ib + 1)->RasterIO(GF_Write, chunk_limits(id).low[2], size_y() - chunk_limits(id).high[1] - 1, dat->size()[3], dat->size()[2], ((double *)dat->buf()) + (ib * dat->size()[1] * dat->size()[2] * dat->size()[3] + it * dat->size()[2] * dat->size()[3]), dat->size()[3], dat->size()[2], GDT_Float64, 0, 0, NULL); if (res != CE_None) { GCBS_WARN("RasterIO (write) failed for " + name); break; } } GDALClose(gdal_out); mtx[cur_t_index].unlock(); } if (overviews) { prg->increment((double)0.5 / (double)this->count_chunks()); } else { prg->increment((double)1 / (double)this->count_chunks()); } }; p->apply(shared_from_this(), f); // build overviews and convert to COG (with IFDs of overviews at the beginning of the file) // TODO: use multiple threads if (overviews) { for (uint32_t it = 0; it < size_t(); ++it) { std::string name = cog ? filesystem::join(dir, prefix + (st_reference()->t0() + st_reference()->dt() * it).to_string() + "_temp.tif") : filesystem::join(dir, prefix + (st_reference()->t0() + st_reference()->dt() * it).to_string() + ".tif"); GDALDataset *gdal_out = (GDALDataset *)GDALOpen(name.c_str(), GA_Update); if (!gdal_out) { continue; } int n_overviews = (int)std::ceil(std::log2(std::fmax(double(size_x()), double(size_y())) / 256)); std::vector<int> overview_list; for (int i = 1; i <= n_overviews; ++i) { overview_list.push_back(std::pow(2, i)); } if (!overview_list.empty()) { CPLErr res = GDALBuildOverviews(gdal_out, overview_resampling.c_str(), n_overviews, overview_list.data(), 0, NULL, NULL, nullptr); if (res != CE_None) { GCBS_WARN("GDALBuildOverviews failed for " + name); GDALClose(gdal_out); continue; } } if (cog) { CPLStringList translate_args; translate_args.AddString("-of"); translate_args.AddString("GTiff"); translate_args.AddString("-co"); translate_args.AddString("COPY_SRC_OVERVIEWS=YES"); translate_args.AddString("-co"); translate_args.AddString("TILED=YES"); if (creation_options.find("BLOCKXSIZE") != creation_options.end()) { translate_args.AddString("-co"); translate_args.AddString(("BLOCKXSIZE=" + creation_options["BLOCKXSIZE"]).c_str()); } else { translate_args.AddString("-co"); translate_args.AddString("BLOCKXSIZE=256"); } if (creation_options.find("BLOCKYSIZE") != creation_options.end()) { translate_args.AddString("-co"); translate_args.AddString(("BLOCKYSIZE=" + creation_options["BLOCKYSIZE"]).c_str()); } else { translate_args.AddString("-co"); translate_args.AddString("BLOCKYSIZE=256"); } for (auto it = creation_options.begin(); it != creation_options.end(); ++it) { std::string key = it->first; std::transform(key.begin(), key.end(), key.begin(), (int (*)(int))std::toupper); if (key == "TILED") { GCBS_WARN("Setting" + it->first + "=" + it->second + "is not allowed, ignoring GeoTIFF creation option."); continue; } if (key == "BLOCKXSIZE" || key == "BLOCKYSIZE") continue; if (key == "COPY_SRC_OVERVIEWS") { GCBS_WARN("Setting" + it->first + "=" + it->second + "is not allowed, ignoring GeoTIFF creation option."); continue; } out_co.AddNameValue(it->first.c_str(), it->second.c_str()); translate_args.AddString("-co"); translate_args.AddString((it->first + "=" + it->second).c_str()); } GDALTranslateOptions *trans_options = GDALTranslateOptionsNew(translate_args.List(), NULL); if (trans_options == NULL) { GCBS_ERROR("ERROR in cube::write_tif_collection(): Cannot create gdal_translate options."); throw std::string("ERROR in cube::write_tif_collection(): Cannot create gdal_translate options."); } std::string cogname = filesystem::join(dir, prefix + (st_reference()->t0() + st_reference()->dt() * it).to_string() + ".tif"); GDALDatasetH gdal_cog = GDALTranslate(cogname.c_str(), (GDALDatasetH)gdal_out, trans_options, NULL); GDALClose((GDALDatasetH)gdal_out); filesystem::remove(name); GDALClose((GDALDatasetH)gdal_cog); GDALTranslateOptionsFree(trans_options); } prg->increment((double)0.5 / (double)size_t()); } } prg->set(1.0); prg->finalize(); } void cube::write_netcdf_file(std::string path, uint8_t compression_level, bool with_VRT, bool write_bounds, packed_export packing, bool drop_empty_slices, std::shared_ptr<chunk_processor> p) { std::string op = filesystem::make_absolute(path); if (filesystem::is_directory(op)) { throw std::string("ERROR in cube::write_netcdf_file(): output already exists and is a directory."); } if (filesystem::is_regular_file(op)) { GCBS_INFO("Existing file '" + op + "' will be overwritten for NetCDF export"); } if (!filesystem::exists(filesystem::parent(op))) { filesystem::mkdir_recursive(filesystem::parent(op)); } std::shared_ptr<progress> prg = config::instance()->get_default_progress_bar()->get(); prg->set(0); // explicitly set to zero to show progress bar immediately int ot = NC_DOUBLE; if (packing.type != packed_export::packing_type::PACK_NONE) { if (packing.type == packed_export::packing_type::PACK_UINT8) { ot = NC_UBYTE; } else if (packing.type == packed_export::packing_type::PACK_UINT16) { ot = NC_USHORT; } else if (packing.type == packed_export::packing_type::PACK_UINT32) { ot = NC_UINT; } else if (packing.type == packed_export::packing_type::PACK_INT16) { ot = NC_SHORT; } else if (packing.type == packed_export::packing_type::PACK_INT32) { ot = NC_INT; } else if (packing.type == packed_export::packing_type::PACK_FLOAT32) { ot = NC_FLOAT; packing.offset = {0.0}; packing.scale = {1.0}; packing.nodata = {std::numeric_limits<float>::quiet_NaN()}; } if (!(packing.scale.size() == 1 || packing.scale.size() == size_bands())) { std::string msg; if (size_bands() == 1) { msg = "Packed export needs exactly 1 scale and offset value."; } else { msg = "Packed export needs either n or 1 scale / offset values for n bands."; } GCBS_ERROR(msg); throw(msg); } if (packing.scale.size() != packing.offset.size()) { std::string msg = "Unequal number of scale and offset values provided for packed export."; GCBS_ERROR(msg); throw(msg); } if (packing.scale.size() != packing.nodata.size()) { std::string msg = "Unequal number of scale and nodata values provided for packed export."; GCBS_ERROR(msg); throw(msg); } } double *dim_x = (double *)std::calloc(size_x(), sizeof(double)); double *dim_y = (double *)std::calloc(size_y(), sizeof(double)); int *dim_t = (int *)std::calloc(size_t(), sizeof(int)); double *dim_x_bnds = nullptr; double *dim_y_bnds = nullptr; int *dim_t_bnds = nullptr; if (write_bounds) { dim_x_bnds = (double *)std::calloc(size_x() * 2, sizeof(double)); dim_y_bnds = (double *)std::calloc(size_y() * 2, sizeof(double)); dim_t_bnds = (int *)std::calloc(size_t() * 2, sizeof(int)); } if (_st_ref->dt().dt_unit == datetime_unit::WEEK) { _st_ref->dt_unit() = datetime_unit::DAY; _st_ref->dt_interval() *= 7; // UDUNIT does not support week } for (uint32_t i = 0; i < size_t(); ++i) { dim_t[i] = (i * st_reference()->dt().dt_interval); } for (uint32_t i = 0; i < size_y(); ++i) { dim_y[i] = st_reference()->win().bottom + size_y() * st_reference()->dy() - (i + 0.5) * st_reference()->dy(); // cell center } for (uint32_t i = 0; i < size_x(); ++i) { dim_x[i] = st_reference()->win().left + (i + 0.5) * st_reference()->dx(); } if (write_bounds) { for (uint32_t i = 0; i < size_t(); ++i) { dim_t_bnds[2 * i] = (i * st_reference()->dt().dt_interval); dim_t_bnds[2 * i + 1] = ((i + 1) * st_reference()->dt().dt_interval); } for (uint32_t i = 0; i < size_y(); ++i) { dim_y_bnds[2 * i] = st_reference()->win().bottom + size_y() * st_reference()->dy() - (i)*st_reference()->dy(); dim_y_bnds[2 * i + 1] = st_reference()->win().bottom + size_y() * st_reference()->dy() - (i + 1) * st_reference()->dy(); } for (uint32_t i = 0; i < size_x(); ++i) { dim_x_bnds[2 * i] = st_reference()->win().left + (i + 0) * st_reference()->dx(); dim_x_bnds[2 * i + 1] = st_reference()->win().left + (i + 1) * st_reference()->dx(); } } OGRSpatialReference srs = st_reference()->srs_ogr(); std::string yname = srs.IsProjected() ? "y" : "latitude"; std::string xname = srs.IsProjected() ? "x" : "longitude"; int ncout; #if USE_NCDF4 == 1 nc_create(op.c_str(), NC_NETCDF4, &ncout); #else nc_create(op.c_str(), NC_CLASSIC_MODEL, &ncout); #endif int d_t, d_y, d_x; nc_def_dim(ncout, "time", size_t(), &d_t); nc_def_dim(ncout, yname.c_str(), size_y(), &d_y); nc_def_dim(ncout, xname.c_str(), size_x(), &d_x); int d_bnds = -1; if (write_bounds) { nc_def_dim(ncout, "nv", 2, &d_bnds); } int v_t, v_y, v_x; nc_def_var(ncout, "time", NC_INT, 1, &d_t, &v_t); nc_def_var(ncout, yname.c_str(), NC_DOUBLE, 1, &d_y, &v_y); nc_def_var(ncout, xname.c_str(), NC_DOUBLE, 1, &d_x, &v_x); int v_tbnds, v_ybnds, v_xbnds; int d_tbnds[] = {d_t, d_bnds}; int d_ybnds[] = {d_y, d_bnds}; int d_xbnds[] = {d_x, d_bnds}; if (write_bounds) { nc_def_var(ncout, "time_bnds", NC_INT, 2, d_tbnds, &v_tbnds); nc_def_var(ncout, "y_bnds", NC_DOUBLE, 2, d_ybnds, &v_ybnds); nc_def_var(ncout, "x_bnds", NC_DOUBLE, 2, d_xbnds, &v_xbnds); } std::string att_source = "gdalcubes " + std::to_string(GDALCUBES_VERSION_MAJOR) + "." + std::to_string(GDALCUBES_VERSION_MINOR) + "." + std::to_string(GDALCUBES_VERSION_PATCH); nc_put_att_text(ncout, NC_GLOBAL, "Conventions", strlen("CF-1.6"), "CF-1.6"); nc_put_att_text(ncout, NC_GLOBAL, "source", strlen(att_source.c_str()), att_source.c_str()); // write json graph as metadata // std::string j = make_constructible_json().dump(); // nc_put_att_text(ncout, NC_GLOBAL, "process_graph", j.length(), j.c_str()); char *wkt; srs.exportToWkt(&wkt); double geoloc_array[6] = {st_reference()->left(), st_reference()->dx(), 0.0, st_reference()->top(), 0.0, st_reference()->dy()}; nc_put_att_text(ncout, NC_GLOBAL, "spatial_ref", strlen(wkt), wkt); nc_put_att_double(ncout, NC_GLOBAL, "GeoTransform", NC_DOUBLE, 6, geoloc_array); std::string dtunit_str; if (_st_ref->dt().dt_unit == datetime_unit::YEAR) { dtunit_str = "years"; // WARNING: UDUNITS defines a year as 365.2425 days } else if (_st_ref->dt().dt_unit == datetime_unit::MONTH) { dtunit_str = "months"; // WARNING: UDUNITS defines a month as 1/12 year } else if (_st_ref->dt().dt_unit == datetime_unit::DAY) { dtunit_str = "days"; } else if (_st_ref->dt().dt_unit == datetime_unit::HOUR) { dtunit_str = "hours"; } else if (_st_ref->dt().dt_unit == datetime_unit::MINUTE) { dtunit_str = "minutes"; } else if (_st_ref->dt().dt_unit == datetime_unit::SECOND) { dtunit_str = "seconds"; } dtunit_str += " since "; dtunit_str += _st_ref->t0().to_string(datetime_unit::SECOND); nc_put_att_text(ncout, v_t, "units", strlen(dtunit_str.c_str()), dtunit_str.c_str()); nc_put_att_text(ncout, v_t, "calendar", strlen("gregorian"), "gregorian"); nc_put_att_text(ncout, v_t, "long_name", strlen("time"), "time"); nc_put_att_text(ncout, v_t, "standard_name", strlen("time"), "time"); if (srs.IsProjected()) { // GetLinearUnits(char **) is deprecated since GDAL 2.3.0 #if GDAL_VERSION_MAJOR >= 2 && GDAL_VERSION_MINOR >= 3 && GDAL_VERSION_REV >= 0 const char *unit = nullptr; #else char *unit = nullptr; #endif srs.GetLinearUnits(&unit); nc_put_att_text(ncout, v_y, "units", strlen(unit), unit); nc_put_att_text(ncout, v_x, "units", strlen(unit), unit); int v_crs; nc_def_var(ncout, "crs", NC_INT, 0, NULL, &v_crs); nc_put_att_text(ncout, v_crs, "grid_mapping_name", strlen("easting_northing"), "easting_northing"); nc_put_att_text(ncout, v_crs, "crs_wkt", strlen(wkt), wkt); } else { // char* unit; // double scale = srs.GetAngularUnits(&unit); nc_put_att_text(ncout, v_y, "units", strlen("degrees_north"), "degrees_north"); nc_put_att_text(ncout, v_y, "long_name", strlen("latitude"), "latitude"); nc_put_att_text(ncout, v_y, "standard_name", strlen("latitude"), "latitude"); nc_put_att_text(ncout, v_x, "units", strlen("degrees_east"), "degrees_east"); nc_put_att_text(ncout, v_x, "long_name", strlen("longitude"), "longitude"); nc_put_att_text(ncout, v_x, "standard_name", strlen("longitude"), "longitude"); int v_crs; nc_def_var(ncout, "crs", NC_INT, 0, NULL, &v_crs); nc_put_att_text(ncout, v_crs, "grid_mapping_name", strlen("latitude_longitude"), "latitude_longitude"); nc_put_att_text(ncout, v_crs, "crs_wkt", strlen(wkt), wkt); } CPLFree(wkt); int d_all[] = {d_t, d_y, d_x}; std::vector<int> v_bands; for (uint16_t i = 0; i < bands().count(); ++i) { int v; nc_def_var(ncout, bands().get(i).name.c_str(), ot, 3, d_all, &v); std::size_t csize[3] = {_chunk_size[0], _chunk_size[1], _chunk_size[2]}; #if USE_NCDF4 == 1 nc_def_var_chunking(ncout, v, NC_CHUNKED, csize); #endif if (compression_level > 0) { #if USE_NCDF4 == 1 nc_def_var_deflate(ncout, v, 1, 1, compression_level); // TODO: experiment with shuffling #else GCBS_WARN("gdalcubes has been built to write netCDF-3 classic model files, compression will be ignored."); #endif } if (!bands().get(i).unit.empty()) nc_put_att_text(ncout, v, "units", strlen(bands().get(i).unit.c_str()), bands().get(i).unit.c_str()); double pscale = bands().get(i).scale; double poff = bands().get(i).offset; double pNAN = NAN; if (packing.type != packed_export::packing_type::PACK_NONE) { if (packing.scale.size() > 1) { pscale = packing.scale[i]; poff = packing.offset[i]; pNAN = packing.nodata[i]; } else { pscale = packing.scale[0]; poff = packing.offset[0]; pNAN = packing.nodata[0]; } } nc_put_att_double(ncout, v, "scale_factor", NC_DOUBLE, 1, &pscale); nc_put_att_double(ncout, v, "add_offset", NC_DOUBLE, 1, &poff); nc_put_att_text(ncout, v, "type", strlen(bands().get(i).type.c_str()), bands().get(i).type.c_str()); nc_put_att_text(ncout, v, "grid_mapping", strlen("crs"), "crs"); // this doesn't seem to solve missing spatial reference for multitemporal nc files // nc_put_att_text(ncout, v, "spatial_ref", strlen(wkt), wkt); // nc_put_att_double(ncout, v, "GeoTransform", NC_DOUBLE, 6, geoloc_array); nc_put_att_double(ncout, v, "_FillValue", ot, 1, &pNAN); v_bands.push_back(v); } nc_enddef(ncout); //////////////////////////////////////////////////// nc_put_var(ncout, v_t, (void *)dim_t); nc_put_var(ncout, v_y, (void *)dim_y); nc_put_var(ncout, v_x, (void *)dim_x); if (write_bounds) { nc_put_var(ncout, v_tbnds, (void *)dim_t_bnds); nc_put_var(ncout, v_ybnds, (void *)dim_y_bnds); nc_put_var(ncout, v_xbnds, (void *)dim_x_bnds); } if (dim_t) std::free(dim_t); if (dim_y) std::free(dim_y); if (dim_x) std::free(dim_x); if (write_bounds) { if (dim_t_bnds) std::free(dim_t_bnds); if (dim_y_bnds) std::free(dim_y_bnds); if (dim_x_bnds) std::free(dim_x_bnds); } std::function<void(chunkid_t, std::shared_ptr<chunk_data>, std::mutex &)> f = [this, op, prg, &v_bands, ncout, &packing](chunkid_t id, std::shared_ptr<chunk_data> dat, std::mutex &m) { chunk_size_btyx csize = dat->size(); bounds_nd<uint32_t, 3> climits = chunk_limits(id); std::size_t startp[] = {climits.low[0], size_y() - climits.high[1] - 1, climits.low[2]}; std::size_t countp[] = {csize[1], csize[2], csize[3]}; for (uint16_t i = 0; i < bands().count(); ++i) { if (packing.type != packed_export::packing_type::PACK_NONE) { double cur_scale; double cur_offset; double cur_nodata; if (packing.scale.size() == size_bands()) { cur_scale = packing.scale[i]; cur_offset = packing.offset[i]; cur_nodata = packing.nodata[i]; } else { cur_scale = packing.scale[0]; cur_offset = packing.offset[0]; cur_nodata = packing.nodata[0]; } /* * If band of cube already has scale + offset, we do not apply this before. * As a consequence, provided scale and offset values refer to actual data values * but ignore band metadata. The following commented code would apply the * unpacking before */ /* if (bands().get(i).scale != 1 || bands().get(i).offset != 0) { for (uint32_t i = 0; i < dat->size()[1] * dat->size()[2] * dat->size()[3]; ++i) { double &v = ((double *)(dat->buf()))[i * dat->size()[1] * dat->size()[2] * dat->size()[3] + i]; v = v * bands().get(i).scale + bands().get(i).offset; } } */ uint8_t *packedbuf = nullptr; if (packing.type == packed_export::packing_type::PACK_UINT8) { packedbuf = (uint8_t *)std::malloc(dat->size()[1] * dat->size()[2] * dat->size()[3] * sizeof(uint8_t)); for (uint32_t iv = 0; iv < dat->size()[1] * dat->size()[2] * dat->size()[3]; ++iv) { double &v = ((double *)(dat->buf()))[i * dat->size()[1] * dat->size()[2] * dat->size()[3] + iv]; if (std::isnan(v)) { v = cur_nodata; } else { v = std::round((v - cur_offset) / cur_scale); // use std::round to avoid truncation bias } ((uint8_t *)(packedbuf))[iv] = v; } m.lock(); nc_put_vara(ncout, v_bands[i], startp, countp, (void *)(packedbuf)); m.unlock(); } else if (packing.type == packed_export::packing_type::PACK_UINT16) { packedbuf = (uint8_t *)std::malloc(dat->size()[1] * dat->size()[2] * dat->size()[3] * sizeof(uint16_t)); for (uint32_t iv = 0; iv < dat->size()[1] * dat->size()[2] * dat->size()[3]; ++iv) { double &v = ((double *)(dat->buf()))[i * dat->size()[1] * dat->size()[2] * dat->size()[3] + iv]; if (std::isnan(v)) { v = cur_nodata; } else { v = std::round((v - cur_offset) / cur_scale); // use std::round to avoid truncation bias } ((uint16_t *)(packedbuf))[iv] = v; } m.lock(); nc_put_vara(ncout, v_bands[i], startp, countp, (void *)(packedbuf)); m.unlock(); } else if (packing.type == packed_export::packing_type::PACK_UINT32) { packedbuf = (uint8_t *)std::malloc(dat->size()[1] * dat->size()[2] * dat->size()[3] * sizeof(uint32_t)); for (uint32_t iv = 0; iv < dat->size()[1] * dat->size()[2] * dat->size()[3]; ++iv) { double &v = ((double *)(dat->buf()))[i * dat->size()[1] * dat->size()[2] * dat->size()[3] + iv]; if (std::isnan(v)) { v = cur_nodata; } else { v = std::round((v - cur_offset) / cur_scale); // use std::round to avoid truncation bias } ((uint32_t *)(packedbuf))[iv] = v; } m.lock(); nc_put_vara(ncout, v_bands[i], startp, countp, (void *)(packedbuf)); m.unlock(); } else if (packing.type == packed_export::packing_type::PACK_INT16) { packedbuf = (uint8_t *)std::malloc(dat->size()[1] * dat->size()[2] * dat->size()[3] * sizeof(int16_t)); for (uint32_t iv = 0; iv < dat->size()[1] * dat->size()[2] * dat->size()[3]; ++iv) { double &v = ((double *)(dat->buf()))[i * dat->size()[1] * dat->size()[2] * dat->size()[3] + iv]; if (std::isnan(v)) { v = cur_nodata; } else { v = std::round((v - cur_offset) / cur_scale); // use std::round to avoid truncation bias } ((int16_t *)(packedbuf))[iv] = v; } m.lock(); nc_put_vara(ncout, v_bands[i], startp, countp, (void *)(packedbuf)); m.unlock(); } else if (packing.type == packed_export::packing_type::PACK_INT32) { packedbuf = (uint8_t *)std::malloc(dat->size()[1] * dat->size()[2] * dat->size()[3] * sizeof(int32_t)); for (uint32_t iv = 0; iv < dat->size()[1] * dat->size()[2] * dat->size()[3]; ++iv) { double &v = ((double *)(dat->buf()))[i * dat->size()[1] * dat->size()[2] * dat->size()[3] + iv]; if (std::isnan(v)) { v = cur_nodata; } else { v = std::round((v - cur_offset) / cur_scale); // use std::round to avoid truncation bias } ((int32_t *)(packedbuf))[iv] = v; } m.lock(); nc_put_vara(ncout, v_bands[i], startp, countp, (void *)(packedbuf)); m.unlock(); } else if (packing.type == packed_export::packing_type::PACK_FLOAT32) { packedbuf = (uint8_t *)std::malloc(dat->size()[1] * dat->size()[2] * dat->size()[3] * sizeof(float)); for (uint32_t iv = 0; iv < dat->size()[1] * dat->size()[2] * dat->size()[3]; ++iv) { double &v = ((double *)(dat->buf()))[i * dat->size()[1] * dat->size()[2] * dat->size()[3] + iv]; ((float *)(packedbuf))[iv] = v; } m.lock(); nc_put_vara(ncout, v_bands[i], startp, countp, (void *)(packedbuf)); m.unlock(); } if (packedbuf) std::free(packedbuf); } else { m.lock(); nc_put_vara(ncout, v_bands[i], startp, countp, (void *)(((double *)dat->buf()) + (int)i * (int)csize[1] * (int)csize[2] * (int)csize[3])); m.unlock(); } } prg->increment((double)1 / (double)this->count_chunks()); }; p->apply(shared_from_this(), f); nc_close(ncout); prg->finalize(); // netCDF is now written, write additional per-time-slice VRT datasets if needed if (with_VRT) { for (uint32_t it = 0; it < size_t(); ++it) { std::string dir = filesystem::directory(path); std::string outfile = dir.empty() ? filesystem::stem(path) + +"_" + (st_reference()->t0() + st_reference()->dt() * it).to_string() + ".vrt" : filesystem::join(dir, filesystem::stem(path) + "_" + (st_reference()->t0() + st_reference()->dt() * it).to_string() + ".vrt"); std::ofstream fout(outfile); fout << "<VRTDataset rasterXSize=\"" << size_x() << "\" rasterYSize=\"" << size_y() << "\">" << std::endl; fout << "<SRS>" << st_reference()->srs() << "</SRS>" << std::endl; // TODO: if SRS is WKT, it must be escaped with ampersand sequences fout << "<GeoTransform>" << utils::dbl_to_string(st_reference()->left()) << ", " << utils::dbl_to_string(st_reference()->dx()) << ", " << "0.0" << ", " << utils::dbl_to_string(st_reference()->top()) << ", " << "0.0" << ", " << "-" << utils::dbl_to_string(st_reference()->dy()) << "</GeoTransform>" << std::endl; for (uint16_t ib = 0; ib < size_bands(); ++ib) { fout << "<VRTRasterBand dataType=\"Float64\" band=\"" << ib + 1 << "\">" << std::endl; fout << "<SimpleSource>" << std::endl; fout << "<NoDataValue>" << std::stod(_bands.get(ib).no_data_value) << "</NoDataValue>" << std::endl; fout << "<UnitType>" << _bands.get(ib).unit << "</UnitType>" << std::endl; fout << "<Offset>" << _bands.get(ib).offset << "</Offset>" << std::endl; fout << "<Scale>" << _bands.get(ib).scale << "</Scale>" << std::endl; std::string in_dataset = "NETCDF:\"" + filesystem::filename(path) + "\":" + _bands.get(ib).name; fout << "<SourceFilename relativeToVRT=\"1\">" << in_dataset << "</SourceFilename>" << std::endl; fout << "<SourceBand>" << it + 1 << "</SourceBand>" << std::endl; fout << "<SrcRect xOff=\"0\" yOff=\"0\" xSize=\"" << size_x() << "\" ySize=\"" << size_y() << "\"/>" << std::endl; fout << "<DstRect xOff=\"0\" yOff=\"0\" xSize=\"" << size_x() << "\" ySize=\"" << size_y() << "\"/>" << std::endl; fout << "</SimpleSource>" << std::endl; fout << "</VRTRasterBand>" << std::endl; } fout << "</VRTDataset>" << std::endl; fout.close(); } } } void chunk_processor_singlethread::apply(std::shared_ptr<cube> c, std::function<void(chunkid_t, std::shared_ptr<chunk_data>, std::mutex &)> f) { std::mutex mutex; uint32_t nchunks = c->count_chunks(); for (uint32_t i = 0; i < nchunks; ++i) { std::shared_ptr<chunk_data> dat = c->read_chunk(i); f(i, dat, mutex); } } void chunk_processor_multithread::apply(std::shared_ptr<cube> c, std::function<void(chunkid_t, std::shared_ptr<chunk_data>, std::mutex &)> f) { std::mutex mutex; std::vector<std::thread> workers; for (uint16_t it = 0; it < _nthreads; ++it) { workers.push_back(std::thread([this, &c, f, it, &mutex](void) { for (uint32_t i = it; i < c->count_chunks(); i += _nthreads) { try { std::shared_ptr<chunk_data> dat = c->read_chunk(i); f(i, dat, mutex); } catch (std::string s) { GCBS_ERROR(s); continue; } catch (...) { GCBS_ERROR("unexpected exception while processing chunk " + std::to_string(i)); continue; } } })); } for (uint16_t it = 0; it < _nthreads; ++it) { workers[it].join(); } } } // namespace gdalcubes
47.721421
292
0.529223
[ "vector", "model", "transform" ]
22e50f3f3cc82e079740b26b6edccf7b22e68d61
31,007
cc
C++
test/datablock_test_byte1.cc
cakebytheoceanLuo/Data_Blocks
72ba7e352118ca25f4d0cb5d07853e4e0976e07e
[ "MIT" ]
4
2021-01-12T07:39:49.000Z
2021-07-29T05:55:36.000Z
test/datablock_test_byte1.cc
cakebytheoceanLuo/Data_Blocks
72ba7e352118ca25f4d0cb5d07853e4e0976e07e
[ "MIT" ]
null
null
null
test/datablock_test_byte1.cc
cakebytheoceanLuo/Data_Blocks
72ba7e352118ca25f4d0cb5d07853e4e0976e07e
[ "MIT" ]
1
2021-04-12T00:17:41.000Z
2021-04-12T00:17:41.000Z
// --------------------------------------------------------------------------- // IMLAB // --------------------------------------------------------------------------- #include <math.h> #include <gtest/gtest.h> #include <algorithm> #include <cstdlib> #include <ctime> #include <iostream> #include <map> #include <tuple> #include <vector> #include "datablock_test_helper.cc" // NOLINT #include "imlab/datablock/DataBlock.h" #include "imlab/util/Random.h" #define DEBUG // --------------------------------------------------------------------------------------------------- namespace { // --------------------------------------------------------------------------------------------------- using imlab::util::Predicate; using imlab::util::EncodingType; using imlab::util::CompareType; using imlab::util::Random; using imlab::DataBlock; using imlab::util::SchemaType; // --------------------------------------------------------------------------------------------------- #ifdef DEBUG // --------------------------------------------------------------------------------------------------- static std::string l_shipmode[7] = {"RAIL", "SHIP", "MAIL", "TRUCK", "FOB", "REG AIR", "AIR"}; static std::string l_shipinstruct[4] = {"NONE", "TAKE BACK RETURN", "COLLECT COD", "DELIVER IN PERSON"}; // --------------------------------------------------------------------------------------------------- TEST(DataBlock, 8bit_EQUAL_l_shipmode_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipmode[random.Rand() % 7]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::EQUAL, [](std::string compared, std::string entry) {return compared == entry;} ); } TEST(DataBlock, 8bit_EQUAL_l_shipmode_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipmode[random.Rand() % 7]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::EQUAL, [](std::string compared, std::string entry) {return compared == entry;} ); } TEST(DataBlock, 8bit_GREATER_THAN_l_shipmode_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipmode[random.Rand() % 7]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::GREATER_THAN, [](std::string compared, std::string entry) {return compared < entry;} ); } TEST(DataBlock, 8bit_GREATER_THAN_l_shipmode_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipmode[random.Rand() % 7]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::GREATER_THAN, [](std::string compared, std::string entry) {return compared < entry;} ); } TEST(DataBlock, 8bit_LESS_THAN_l_shipmode_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipmode[random.Rand() % 7]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::LESS_THAN, [](std::string compared, std::string entry) {return compared > entry;} ); } TEST(DataBlock, 8bit_LESS_THAN_l_shipmode_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipmode[random.Rand() % 7]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::LESS_THAN, [](std::string compared, std::string entry) {return compared > entry;} ); } TEST(DataBlock, 8bit_BETWEEN_l_shipmode_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipmode[random.Rand() % 7]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_bin(size, str_table_portion, str_set_vec, std::move(db)); } TEST(DataBlock, 8bit_BETWEEN_l_shipmode_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipmode[random.Rand() % 7]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_bin(size, str_table_portion, str_set_vec, std::move(db)); } TEST(DataBlock, 8bit_EQUAL_l_shipinstruct_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipinstruct[random.Rand() >> (64 - 2)]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::EQUAL, [](std::string compared, std::string entry) {return compared == entry;} ); } TEST(DataBlock, 8bit_EQUAL_l_shipinstruct_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipinstruct[random.Rand() >> (64 - 2)]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::EQUAL, [](std::string compared, std::string entry) {return compared == entry;} ); } TEST(DataBlock, 8bit_GREATER_THAN_l_shipinstruct_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipinstruct[random.Rand() >> (64 - 2)]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::GREATER_THAN, [](std::string compared, std::string entry) {return compared < entry;} ); } TEST(DataBlock, 8bit_GREATER_THAN_l_shipinstruct_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipinstruct[random.Rand() >> (64 - 2)]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::GREATER_THAN, [](std::string compared, std::string entry) {return compared < entry;} ); } TEST(DataBlock, 8bit_LESS_THAN_l_shipinstruct_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipinstruct[random.Rand() >> (64 - 2)]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::LESS_THAN, [](std::string compared, std::string entry) {return compared > entry;} ); } TEST(DataBlock, 8bit_LESS_THAN_l_shipinstruct_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipinstruct[random.Rand() >> (64 - 2)]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_uni(size, str_table_portion, str_set_vec, std::move(db), CompareType::LESS_THAN, [](std::string compared, std::string entry) {return compared > entry;} ); } TEST(DataBlock, 8bit_BETWEEN_l_shipinstruct_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipinstruct[random.Rand() >> (64 - 2)]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_bin(size, str_table_portion, str_set_vec, std::move(db)); } TEST(DataBlock, 8bit_BETWEEN_l_shipinstruct_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<std::string>> str_table_portion(1); auto &col0 = str_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(l_shipinstruct[random.Rand() >> (64 - 2)]); } std::vector<std::vector<std::uint64_t>> int_table_portion; std::vector<SchemaType> schematypes{SchemaType::Char}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); std::array<uint8_t, 1> str_index_arr{{0}}; std::vector<std::set<std::string>> str_set_vec = db->decode_dictionary<1>(str_index_arr); scan_helper_str_singleCol_bin(size, str_table_portion, str_set_vec, std::move(db)); } // --------------------------------------------------------------------------------------------------- TEST(DataBlock, 8bit_EQUAL_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(random.Rand() >> 56); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); scan_helper_singleCol_uni(size, int_table_portion, std::move(db), CompareType::EQUAL, [](uint64_t compared, uint64_t entry) {return compared == entry;} ); } TEST(DataBlock, 8bit_EQUAL_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(random.Rand() >> 56); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); scan_helper_singleCol_uni(size, int_table_portion, std::move(db), CompareType::EQUAL, [](uint64_t compared, uint64_t entry) {return compared == entry;} ); } TEST(DataBlock, 8bit_GREATER_THAN_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(random.Rand() >> 56); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); scan_helper_singleCol_uni(size, int_table_portion, std::move(db), CompareType::GREATER_THAN, [](uint64_t compared, uint64_t entry) {return compared < entry;} ); } TEST(DataBlock, 8bit_GREATER_THAN_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(random.Rand() >> 56); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); scan_helper_singleCol_uni(size, int_table_portion, std::move(db), CompareType::GREATER_THAN, [](uint64_t compared, uint64_t entry) {return compared < entry;} ); } TEST(DataBlock, 8bit_LESS_THAN_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(random.Rand() >> 56); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); scan_helper_singleCol_uni(size, int_table_portion, std::move(db), CompareType::LESS_THAN, [](uint64_t compared, uint64_t entry) {return compared > entry;} ); } TEST(DataBlock, 8bit_LESS_THAN_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(random.Rand() >> 56); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); scan_helper_singleCol_uni(size, int_table_portion, std::move(db), CompareType::LESS_THAN, [](uint64_t compared, uint64_t entry) {return compared > entry;} ); } TEST(DataBlock, 8bit_BETWEEN_Random_Single_Vector_2_8) { size_t size = 1 << 8; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(random.Rand() >> 56); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); scan_helper_singleCol_bin(size, int_table_portion, std::move(db)); } TEST(DataBlock, 8bit_BETWEEN_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(random.Rand() >> 56); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); scan_helper_singleCol_bin(size, int_table_portion, std::move(db)); } TEST(DataBlock, 8bit_MULTI_EQUAL_Random_Single_Vector_2_16) { size_t size = 1 << 16; size_t dup_size = 1 << 4; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size - dup_size; ++i) { col0.push_back(random.Rand() >> 56); } for (size_t i = 0; i < dup_size; ++i) { col0.push_back(col0[random.Rand() % (size - dup_size - 1)]); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); for (size_t i = 0; i < size; ++i) { uint64_t random1 = random.Rand() >> 56; uint64_t random2 = random.Rand() >> 56; uint64_t random3 = random.Rand() >> 56; Predicate predicate_1(0, random1, CompareType::EQUAL); Predicate predicate_2(0, random2, CompareType::EQUAL); Predicate predicate_3(0, random3, CompareType::EQUAL); std::vector<Predicate> predicates; predicates.push_back(predicate_1); predicates.push_back(predicate_2); predicates.push_back(predicate_3); uint64_t count_if = std::count_if(col0.begin(), col0.end(), [random1, random2, random3](uint64_t entry) { return entry == random1 && entry == random2 && entry == random3;}); EXPECT_EQ(count_if, db.get()->scan(predicates, *index_vectors)); } } TEST(DataBlock, 8bit_MULTI_GREATER_THAN_Random_Single_Vector_2_16) { size_t size = 1 << 16; size_t dup_size = 1 << 4; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size - dup_size; ++i) { col0.push_back(random.Rand() >> 56); } for (size_t i = 0; i < dup_size; ++i) { col0.push_back(col0[random.Rand() % (size - dup_size - 1)]); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); for (size_t i = 0; i < size; ++i) { uint64_t random1 = random.Rand() >> 56; uint64_t random2 = random.Rand() >> 56; uint64_t random3 = random.Rand() >> 56; Predicate predicate_1(0, random1, CompareType::GREATER_THAN); Predicate predicate_2(0, random2, CompareType::GREATER_THAN); Predicate predicate_3(0, random3, CompareType::GREATER_THAN); std::vector<Predicate> predicates; predicates.push_back(predicate_1); predicates.push_back(predicate_2); predicates.push_back(predicate_3); uint64_t count_if = std::count_if(col0.begin(), col0.end(), [random1, random2, random3](uint64_t entry) { return entry > random1 && entry > random2 && entry > random3;}); EXPECT_EQ(count_if, db.get()->scan(predicates, *index_vectors)); } } TEST(DataBlock, 8bit_MULTI_LESS_THAN_Random_Single_Vector_2_16) { size_t size = 1 << 16; size_t dup_size = 1 << 4; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size - dup_size; ++i) { col0.push_back(random.Rand() >> 56); } for (size_t i = 0; i < dup_size; ++i) { col0.push_back(col0[random.Rand() % (size - dup_size - 1)]); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); for (size_t i = 0; i < size; ++i) { uint64_t random1 = random.Rand() >> 56; uint64_t random2 = random.Rand() >> 56; uint64_t random3 = random.Rand() >> 56; Predicate predicate_1(0, random1, CompareType::LESS_THAN); Predicate predicate_2(0, random2, CompareType::LESS_THAN); Predicate predicate_3(0, random3, CompareType::LESS_THAN); std::vector<Predicate> predicates; predicates.push_back(predicate_1); predicates.push_back(predicate_2); predicates.push_back(predicate_3); uint64_t count_if = std::count_if(col0.begin(), col0.end(), [random1, random2, random3](uint64_t entry) { return entry < random1 && entry < random2 && entry < random3;}); EXPECT_EQ(count_if, db.get()->scan(predicates, *index_vectors)); } } TEST(DataBlock, 8bit_MULTI_BETWEEN_Random_Single_Vector_2_16) { size_t size = 1 << 16; std::vector<std::vector<uint64_t>> int_table_portion(1); auto &col0 = int_table_portion[0]; col0.reserve(size); Random random; for (size_t i = 0; i < size; ++i) { col0.push_back(random.Rand() >> 56); } std::vector<std::vector<std::string>> str_table_portion; std::vector<SchemaType> schematypes{SchemaType::Interger}; auto db = imlab::DataBlock<1>::build(int_table_portion, str_table_portion, schematypes); EXPECT_EQ(col0.size(), db.get()->get_tupel_count()); for (size_t i = 0; i < size; ++i) { uint64_t random1 = random.Rand() >> 56; uint64_t random2 = random.Rand() >> 56; uint64_t random3 = random.Rand() >> 56; uint64_t random4 = random.Rand() >> 56; uint64_t random5 = random.Rand() >> 56; uint64_t random6 = random.Rand() >> 56; Predicate predicate_1(0, random1, random4, CompareType::BETWEEN); Predicate predicate_2(0, random2, random5, CompareType::BETWEEN); Predicate predicate_3(0, random3, random6, CompareType::BETWEEN); std::vector<Predicate> predicates; predicates.push_back(predicate_1); predicates.push_back(predicate_2); predicates.push_back(predicate_3); uint64_t count_if = std::count_if( col0.begin(), col0.end(), [random1, random2, random3, random4, random5, random6](uint64_t entry) { return random1 <= entry && entry <= random4 && random2 <= entry && entry <= random5 && random3 <= entry && entry <= random6; }); EXPECT_EQ(count_if, db.get()->scan(predicates, *index_vectors)); } } #endif // --------------------------------------------------------------------------------------------------- } // namespace // ---------------------------------------------------------------------------------------------------
37.629854
181
0.612926
[ "vector" ]
22e5e84fc7ee4247d2ce8d6cf8ed2ab31740e151
26,816
cpp
C++
XAML SpriteGame/DirectXPage.xaml.cpp
ksideris/DirectX-game-engine
215a46d65fdabf4439e4889c09cc54c799c6caa7
[ "Zlib" ]
3
2015-01-08T04:00:32.000Z
2019-08-30T01:42:26.000Z
XAML SpriteGame/DirectXPage.xaml.cpp
ksideris/DirectX-game-engine
215a46d65fdabf4439e4889c09cc54c799c6caa7
[ "Zlib" ]
null
null
null
XAML SpriteGame/DirectXPage.xaml.cpp
ksideris/DirectX-game-engine
215a46d65fdabf4439e4889c09cc54c799c6caa7
[ "Zlib" ]
4
2015-01-08T04:00:22.000Z
2021-09-10T01:31:02.000Z
// // BlankPage.xaml.cpp // Implementation of the BlankPage.xaml class. // #include "pch.h" #include "DirectXPage.xaml.h" #include <map> using namespace irr; using namespace io; //end xml imports using namespace GameEngine; using namespace Helpers; using namespace AudioEngine; using namespace Windows::UI::ViewManagement; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Input; using namespace Windows::UI::Core; using namespace Windows::System; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::Graphics::Display; using namespace Windows::UI::ApplicationSettings; using namespace Windows::UI::Popups; using namespace Windows::Storage; using namespace Windows::Storage::Streams; using namespace concurrency; DirectXPage::DirectXPage() { InitializeComponent(); IsInitialDataLoaded = false; hudIsClicked = false; //init the directX renderer m_renderer = ref new SpriteGame(); #ifdef W8_1 auto info = DisplayInformation::GetForCurrentView(); m_renderer->Initialize( Window::Current->CoreWindow, this, info->LogicalDpi ); info->DpiChanged+=ref new Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation ^, Platform::Object ^>(this, &GameEngine::DirectXPage::OnDpiChanged); #else m_renderer->Initialize( Window::Current->CoreWindow, this, DisplayProperties::LogicalDpi ); //notify renderer of changes in DPI DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &DirectXPage::OnLogicalDpiChanged); #endif Paused = false; MenuButtonsGrid->Visibility = Windows::UI::Xaml::Visibility::Visible; GamePlayGrid->Visibility = Windows::UI::Xaml::Visibility::Collapsed; LevelButtonsGrid->Visibility = Windows::UI::Xaml::Visibility::Collapsed; // wire the event for screen size monitoring. Important for retargeting the renderer and pausing Window::Current->CoreWindow->SizeChanged += ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXPage::OnWindowSizeChanged); Window::Current->CoreWindow->VisibilityChanged+=ref new Windows::Foundation::TypedEventHandler<Windows::UI::Core::CoreWindow ^, Windows::UI::Core::VisibilityChangedEventArgs ^>(this, &GameEngine::DirectXPage::OnVisibilityChanged); // main rendering event handler m_eventToken = CompositionTarget::Rendering += ref new EventHandler<Object^>(this, &DirectXPage::OnRendering); CheckNCreateFile(SAVEFILE); m_timer = ref new Timer(); UpdateWindowSize(); WireUpUIEvents(); active_UI = MenuButtonsGrid; Windows::Devices::Input::TouchCapabilities^ t = ref new Windows::Devices::Input::TouchCapabilities(); if (t->TouchPresent == 0) { ShootButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } } void DirectXPage::WireUpUIEvents() { MenuButtonsGrid->SizeChanged += ref new Windows::UI::Xaml::SizeChangedEventHandler(this, &GameEngine::DirectXPage::OnSizeChanged); LevelButtonsGrid->SizeChanged += ref new Windows::UI::Xaml::SizeChangedEventHandler(this, &GameEngine::DirectXPage::OnSizeChanged); GamePlayGrid->SizeChanged += ref new Windows::UI::Xaml::SizeChangedEventHandler(this, &GameEngine::DirectXPage::OnSizeChanged); PlayButton->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnTapped); ShareButton->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnTappedShare); tglMusic->Toggled += ref new Windows::UI::Xaml::RoutedEventHandler(this, &GameEngine::DirectXPage::OnToggled); sldMusicVolume->ValueChanged += ref new Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventHandler(this, &GameEngine::DirectXPage::OnValueChanged); tglSFX->Toggled += ref new Windows::UI::Xaml::RoutedEventHandler(this, &GameEngine::DirectXPage::OnToggled); sldSFXVolume->ValueChanged += ref new Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventHandler(this, &GameEngine::DirectXPage::OnValueChanged); dismissAudioSettings->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnDismissAudioTapped); dismissAbout->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnDismissAboutTapped); dismissPrivacy->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnDismissPrivacyTapped); PauseButton->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnPauseTapped); dismissPaused->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnUnPauseTapped); popupPaused->Closed += ref new Windows::Foundation::EventHandler<Platform::Object ^>(this, &GameEngine::DirectXPage::OnClosed); UnpauseButton->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnUnPauseTapped); SettingsBut->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnSettingsTapped); Quit->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnQuitTapped); ShootButton->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnShootTapped); ShootButton->PointerEntered += ref new Windows::UI::Xaml::Input::PointerEventHandler(this, &GameEngine::DirectXPage::OnShootPointerEntered); ShootButton->PointerExited += ref new Windows::UI::Xaml::Input::PointerEventHandler(this, &GameEngine::DirectXPage::OnShootPointerExited); backToMenu->Tapped+=ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnBackToMenuTapped); //Charm bar events auto dataTransferManager = Windows::ApplicationModel::DataTransfer::DataTransferManager::GetForCurrentView(); dataTransferManager->DataRequested += ref new Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager ^, Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs ^>(this, &GameEngine::DirectXPage::OnDataRequested); SettingsPane::GetForCurrentView()->CommandsRequested += ref new Windows::Foundation::TypedEventHandler<Windows::UI::ApplicationSettings::SettingsPane ^, Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^>(this, &GameEngine::DirectXPage::OnCommandsRequested); } void DirectXPage::CheckNCreateFile(String^ Filename) { if (!Exists(L"ApplicationInit")) { ApplicationData::Current->LocalFolder->CreateFileAsync(Filename); writeToText(Filename, "0,0,0,0,0"); Save(L"ApplicationInit", true); } } //deprecated will be removed void DirectXPage::LoadText(String^ Filename) { create_task(ApplicationData::Current->LocalFolder->GetFileAsync(Filename)).then([](StorageFile^ file) { return FileIO::ReadTextAsync(file); }, task_continuation_context::use_arbitrary()).then([this](String^ filecontents) { //test->Text = filecontents; }); } std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } void DirectXPage::LoadHighScores(String^ Filename) { create_task(ApplicationData::Current->LocalFolder->GetFileAsync(Filename)).then([this](StorageFile^ file) { return FileIO::ReadTextAsync(file); }, task_continuation_context::use_arbitrary()).then([this](String^ filecontents) { std::wstring fooW(filecontents->Begin()); std::string fooA(fooW.begin(), fooW.end()); auto separated_string = split(fooA, ','); for (auto str_score = separated_string.begin(); str_score != separated_string.end(); str_score++) { scores.push_front(atoi((*str_score).c_str())); } ShowScores(-1); }); } void DirectXPage::HandleGameOver() { if (m_renderer->gamestate == GameState::GameOver) { AudioManager::SetGameOverMusic(); m_renderer->gamestate = GameState::LevelLost; } else if (m_renderer->gamestate == GameState::LevelComplete) { UpdateScores(); m_renderer->gamestate = GameState::LevelWon; } GamePlayGrid->Visibility = Windows::UI::Xaml::Visibility::Collapsed; MenuButtonsGrid->Visibility = Windows::UI::Xaml::Visibility::Visible; } void DirectXPage::UpdateScores() { int i = 0; for (auto score = scores.begin(); score != scores.end(); score++) { if (m_renderer->score >= *score) { scores.insert(scores.begin() + i, m_renderer->score); break; } i++; } if (scores.size() > 5) scores.erase(scores.end() - 1); String^ newSave = ""; for (auto score = scores.begin(); score != scores.end(); score++) { newSave += (*score).ToString() + ","; } writeToText(SAVEFILE, newSave); ShowScores(i); } void DirectXPage::ShowScores(int highLightIndex) { TextBlock^ t = ref new TextBlock(); t->FontSize = 40; t->Text = "High Scores"; HighScoresPanel->Children->Clear(); t->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center; HighScoresPanel->Children->Append(t); std::sort(scores.begin(), scores.end(), std::greater<int>()); int i = 0; for (auto score = scores.begin(); score != scores.end(); score++) { TextBlock^ t = ref new TextBlock(); t->TextAlignment = Windows::UI::Xaml::TextAlignment::Center; t->FontSize = 30; if (i == highLightIndex) t->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Yellow); t->Text = (*score).ToString(); HighScoresPanel->Children->Append(t); i++; } //active_UI = MenuButtonsGrid; } void DirectXPage::writeToText(String^ Filename, String^ text) { if (text != nullptr && !text->IsEmpty()) { create_task(ApplicationData::Current->LocalFolder->GetFileAsync(Filename)).then([this, text](StorageFile^ file) { return FileIO::WriteTextAsync(file, text); }, task_continuation_context::use_arbitrary()).then([this]() { }); } } void DirectXPage::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args) { m_renderer->UpdateForWindowSizeChange(); UpdateWindowSize(); } void DirectXPage::UpdateWindowSize() { bool visibility = true; #ifdef W8_1 if (m_renderer->m_renderTargetSize.Width < 600) visibility = false; #else if (ApplicationView::Value == ApplicationViewState::Snapped) visibility = false; #endif if (visibility) { if (m_renderer->gamestate == GameState::Paused) { Unpause(); active_UI->Visibility = Windows::UI::Xaml::Visibility::Visible; PausedScreen->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } } else { active_UI->Visibility = Windows::UI::Xaml::Visibility::Collapsed; PausedScreen->Visibility = Windows::UI::Xaml::Visibility::Visible; Pause(); } } #ifdef W8_1 void GameEngine::DirectXPage::OnDpiChanged(Windows::Graphics::Display::DisplayInformation ^sender, Platform::Object ^args) { m_renderer->SetDpi(DisplayInformation::GetForCurrentView()->LogicalDpi); } #else void DirectXPage::OnLogicalDpiChanged(Platform::Object^ sender) { m_renderer->SetDpi(DisplayProperties::LogicalDpi); } #endif //handles render loop void DirectXPage::OnRendering(Platform::Object^ sender, Platform::Object^ args) { if (!Paused) { m_timer->Update(); framerate.push_back(1.f / m_timer->Delta); if (framerate.size() > 100) while (framerate.size() > 100) framerate.erase(framerate.begin()); float fps = 0; for (auto _fps : framerate) fps += _fps; fps /= framerate.size(); Clock->Text = (((int) m_timer->Total) / 60).ToString(); Clock->Text += ":" + (((int) m_timer->Total) % 60).ToString(); Score->Text = m_renderer->score.ToString(); if (m_renderer->gamestate == GameState::GameOver || m_renderer->gamestate == GameState::LevelComplete) { HandleGameOver(); } HealthBar->Width = max(m_renderer->spaceship->health, 0) * 350 / 100.f; health = m_renderer->spaceship->health; AudioManager::AudioEngineInstance.Render(); m_renderer->Update(m_timer->Total, m_timer->Delta); m_renderer->Render(); m_renderer->Present(); } } void DirectXPage::OnLoaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { LoadSettings(); m_renderer->LoadLevel("Menu.xml"); LoadHighScores(SAVEFILE); LoadLevels(L"Level Data\\Levels.xml"); IsInitialDataLoaded = true; } void DirectXPage::OnWindowActivated(Object^ sender, Windows::UI::Core::WindowActivatedEventArgs^ e) { if (e->WindowActivationState == Windows::UI::Core::CoreWindowActivationState::Deactivated) { } } void DirectXPage::OnKeyDown(Platform::Object^ sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^ e) { if (m_renderer->gamestate == Playing) { m_renderer->spaceship->ProcessKeyDown(e); //if (e->Key == VirtualKey::A) // m_renderer->spaceShipLight->m_currentEffect = m_renderer->spaceShipLight->m_pointSpecularEffect; //if (e->Key == VirtualKey::B) // m_renderer->spaceShipLight->m_currentEffect = m_renderer->spaceShipLight->m_spotSpecularEffect; } } void DirectXPage::OnKeyUp(Platform::Object^ sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^ e) { if (m_renderer->gamestate == Playing) { m_renderer->spaceship->ProcessKeyUp(e); } } void DirectXPage::OnDataRequested(Windows::ApplicationModel::DataTransfer::DataTransferManager ^sender, Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs ^args) { auto request = args->Request; request->Data->Properties->Title = "Share your Score!"; request->Data->Properties->Description = "Tell your friends how much you scored in the game engine"; request->Data->SetText("I just collected " + scores[0] + " stars in GameEngine!! "); } void DirectXPage::OnSettingsSelected(Windows::UI::Popups::IUICommand^ command) { if (command->Id->ToString() == "musicSfx") { stkMusicSfx->Width = 346.0f; grdSubMusicSfx->Height = m_renderer->m_renderTargetSize.Height; stkMusicSfx->IsOpen = true; } if (command->Id->ToString() == "about") { popupAbout->Width = 346.0f; grdAbout->Height = m_renderer->m_renderTargetSize.Height; popupAbout->IsOpen = true; } if (command->Id->ToString() == "privacy") { popupPrivacy->Width = 346.0f; grdPrivacy->Height = m_renderer->m_renderTargetSize.Height; popupPrivacy->IsOpen = true; } WindowActivationToken = Window::Current->Activated += ref new WindowActivatedEventHandler(this, &DirectXPage::OnWindowActivated); } void DirectXPage::OnCommandsRequested(Windows::UI::ApplicationSettings::SettingsPane ^sender, Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^args) { UICommandInvokedHandler^ handler = ref new UICommandInvokedHandler(this, &DirectXPage::OnSettingsSelected); SettingsCommand^ generalCommand = ref new SettingsCommand("musicSfx", "Music & SFX", handler); args->Request->ApplicationCommands->Append(generalCommand); SettingsCommand^ privacyCommand = ref new SettingsCommand("privacy", "Privacy", handler); args->Request->ApplicationCommands->Append(privacyCommand); SettingsCommand^ aboutCommand = ref new SettingsCommand("about", "About", handler); args->Request->ApplicationCommands->Append(aboutCommand); } void GameEngine::DirectXPage::OnDismissAboutTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { popupAbout->IsOpen = false; } void GameEngine::DirectXPage::OnDismissAudioTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { stkMusicSfx->IsOpen = false; } void GameEngine::DirectXPage::OnDismissPrivacyTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { popupPrivacy->IsOpen = false; } void GameEngine::DirectXPage::OnTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { MenuButtonsGrid->Visibility = Windows::UI::Xaml::Visibility::Collapsed; LevelButtonsGrid->Visibility = Windows::UI::Xaml::Visibility::Visible; active_UI = LevelButtonsGrid; } void GameEngine::DirectXPage::OnLevelTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { LevelButtonsGrid->Visibility = Windows::UI::Xaml::Visibility::Collapsed; GamePlayGrid->Visibility = Windows::UI::Xaml::Visibility::Visible; active_UI = GamePlayGrid; m_renderer->LoadLevel(((Button^) sender)->Tag + ".xml"); m_timer->Reset(); m_renderer->gamestate = Playing; } void GameEngine::DirectXPage::OnTappedShare(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { Windows::ApplicationModel::DataTransfer::DataTransferManager::GetForCurrentView()->ShowShareUI(); } void GameEngine::DirectXPage::OnSizeChanged(Platform::Object ^sender, Windows::UI::Xaml::SizeChangedEventArgs ^e) { } void DirectXPage::Save(Platform::String^ key, Platform::Object^ value) { ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings; auto values = localSettings->Values; values->Insert(key, value); } Platform::Object^ DirectXPage::Read(Platform::String^ key) { ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings; auto values = localSettings->Values; return values->Lookup(key); } bool DirectXPage::Exists(Platform::String^ key) { ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings; auto values = localSettings->Values; return values->HasKey(key); } void DirectXPage::LoadSettings() { bool MusicEnabled = false; bool SFXEnabled = false; int volume = 0, sfxvolume = 0; if (Exists(L"MusicEnabled")) { MusicEnabled = (bool) Read(L"MusicEnabled"); } else { MusicEnabled = true; } if (MusicEnabled) { tglMusic->IsOn = true; if (Exists(L"MusicVolume")) { volume = (int) Read(L"MusicVolume"); sldMusicVolume->Value = volume; } else { sldMusicVolume->Value = 100; volume = 100; Save(L"MusicVolume", volume); } } else { tglMusic->IsOn = false; sldMusicVolume->Value = 0; volume = 0; } if (Exists(L"SFXEnabled")) { SFXEnabled = (bool) Read(L"SFXEnabled"); } else { SFXEnabled = true; } if (SFXEnabled) { tglSFX->IsOn = true; if (Exists(L"SFXVolume")) { sfxvolume = (int) Read(L"SFXVolume"); sldSFXVolume->Value = sfxvolume; } else { sldSFXVolume->Value = 60; sfxvolume = 60; Save(L"SFXVolume", sfxvolume); } } else { tglSFX->IsOn = false; sldSFXVolume->Value = 0; sfxvolume = 0; } AudioManager::Initialize(); AudioManager::SetMainMenuMusic(); AudioManager::IsSFXStarted = true; if (true) { AudioManager::AudioEngineInstance.StartSFX(); } else { AudioManager::AudioEngineInstance.SuspendSFX(); } AudioManager::IsMusicStarted = true; if (true) { AudioManager::AudioEngineInstance.StartMusic(); } else { AudioManager::AudioEngineInstance.SuspendMusic(); } AudioManager::SetMusicVolume(volume); AudioManager::SetSFXVolume(sfxvolume); } void GameEngine::DirectXPage::OnToggled(Platform::Object ^sender, Windows::UI::Xaml::RoutedEventArgs ^e) { if (IsInitialDataLoaded) { if (tglMusic->IsOn) { if (Exists(L"MusicVolume")) { int volume = (int) Read(L"MusicVolume"); AudioEngine::AudioManager::SetMusicVolume(volume); sldMusicVolume->Value = volume; } else { AudioEngine::AudioManager::SetMusicVolume(100); sldMusicVolume->Value = 100; Save(L"MusicVolume", 100); } Save(L"MusicEnabled", true); } else { sldMusicVolume->Value = 0; AudioEngine::AudioManager::SetMusicVolume(0); Save(L"MusicEnabled", false); } if (tglSFX->IsOn) { if (Exists(L"SFXEnabled")) { int volume = (int) Read(L"SFXVolume"); AudioEngine::AudioManager::SetSFXVolume(volume); sldSFXVolume->Value = volume; } else { AudioEngine::AudioManager::SetSFXVolume(100); sldSFXVolume->Value = 60; Save(L"SFXVolume", 60); } Save(L"SFXEnabled", true); } else { sldSFXVolume->Value = 0; AudioEngine::AudioManager::SetSFXVolume(0); Save(L"SFXEnabled", false); } } } void GameEngine::DirectXPage::OnValueChanged(Platform::Object ^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs ^e) { if (IsInitialDataLoaded) { int volume = (int) sldMusicVolume->Value; AudioEngine::AudioManager::SetMusicVolume(volume); Save(L"MusicVolume", volume); if (volume == 0) tglMusic->IsOn = false; else tglMusic->IsOn = true; int sfxvolume = (int) sldSFXVolume->Value; if (sfxvolume == 0){ Save(L"SFXEnabled", false); tglSFX->IsOn = false; } else{ Save(L"SFXEnabled", true); tglSFX->IsOn = true; } AudioEngine::AudioManager::SetSFXVolume(sfxvolume); Save(L"SFXVolume", sfxvolume); } } void DirectXPage::LoadLevels(String^ levels_xml) { std::wstring level_xmlW(levels_xml->Begin()); std::string level_xmlA(level_xmlW.begin(), level_xmlW.end()); IrrXMLReader* xml = createIrrXMLReader(level_xmlA.c_str()); // strings for storing the data we want to get out of the file std::string stringdata2; std::string stringdata; std::wstring wstringdata; Platform::String^ final_data; // parse the file until end reached while (xml && xml->read()) { switch (xml->getNodeType()) { case EXN_ELEMENT: { if (!strcmp("Level", xml->getNodeName())) { Button^ b = ref new Button(); stringdata = xml->getAttributeValue("Name"); std::wstring wsTmp(stringdata.begin(), stringdata.end()); b->Content = ref new String(wsTmp.c_str()); stringdata = xml->getAttributeValue("Data"); std::wstring wsTmp2(stringdata.begin(), stringdata.end()); b->Tag = ref new String(wsTmp2.c_str()); b->Background = ref new SolidColorBrush(Windows::UI::Colors::Gray); b->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Left; b->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Top; b->Width = 400; b->Height = 60; b->Margin = Windows::UI::Xaml::Thickness(0, 10, 0, 0); b->FontSize = 23; b->Tapped += ref new Windows::UI::Xaml::Input::TappedEventHandler(this, &GameEngine::DirectXPage::OnLevelTapped); LevelsPanel->Children->Append(b); } break; } } } // delete the xml parser after usage delete xml; ///end xml testing } void GameEngine::DirectXPage::OnPauseTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { hudIsClicked = true; Pause(); } void GameEngine::DirectXPage::OnPointerPressed(Platform::Object ^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs ^e) { if (m_renderer->gamestate == Playing && !hudIsClicked) { if (e->Pointer->IsInContact && e->GetCurrentPoint(GamePlayGrid)->Position.Y > HUD->Height) { m_renderer->spaceship->ProcessPointerPressed(e->GetCurrentPoint((DirectXPage^) sender)); } } } void GameEngine::DirectXPage::OnPointerMoved(Platform::Object ^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs ^e) { if (m_renderer->gamestate == Playing && !hudIsClicked) { if (e->Pointer->IsInContact && e->GetCurrentPoint(GamePlayGrid)->Position.Y > HUD->Height) { m_renderer->spaceship->ProcessPointerMoved(e->GetCurrentPoint((DirectXPage^) sender)); } } } void GameEngine::DirectXPage::OnPointerReleased(Platform::Object ^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs ^e) { if (m_renderer->gamestate == Playing && !hudIsClicked) { if (e->Pointer->IsInContact && e->GetCurrentPoint(GamePlayGrid)->Position.Y > HUD->Height) { m_renderer->spaceship->ProcessPointerReleased(e->GetCurrentPoint((DirectXPage^) sender)); } } hudIsClicked = false; } void GameEngine::DirectXPage::OnUnPauseTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { Unpause(); } void GameEngine::DirectXPage::OnClosed(Platform::Object ^sender, Platform::Object ^args) { } void GameEngine::DirectXPage::OnQuitTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { Unpause(); m_renderer->LoadLevel("Menu.xml"); MenuButtonsGrid->Visibility = Windows::UI::Xaml::Visibility::Visible; LevelButtonsGrid->Visibility = Windows::UI::Xaml::Visibility::Collapsed; GamePlayGrid->Visibility = Windows::UI::Xaml::Visibility::Collapsed; active_UI = MenuButtonsGrid; } void GameEngine::DirectXPage::OnSettingsTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { SettingsPane::GetForCurrentView()->Show(); } void GameEngine::DirectXPage::OnShootTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { m_renderer->spaceship->Shoot(); } void GameEngine::DirectXPage::OnShootPointerEntered(Platform::Object ^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs ^e) { hudIsClicked = true; } void GameEngine::DirectXPage::OnShootPointerExited(Platform::Object ^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs ^e) { hudIsClicked = false; } void GameEngine::DirectXPage::Pause() { if (!Paused) { if (PausedScreen->Visibility == Windows::UI::Xaml::Visibility::Collapsed) { popupPaused->IsOpen = true; popupPaused->Width = 346.0f; grdPaused->Height = m_renderer->m_renderTargetSize.Height; } time_at_pause = m_timer->CurrentTime; previous_state = m_renderer->gamestate; m_renderer->gamestate = GameState::Paused; Paused = true; } if (PausedScreen->Visibility == Windows::UI::Xaml::Visibility::Visible) { popupPaused->IsOpen = false; } } void GameEngine::DirectXPage::Unpause() { if (Paused) { popupPaused->IsOpen = false; Paused = false; m_renderer->gamestate = previous_state; m_timer->Reset(time_at_pause); } } void GameEngine::DirectXPage::Suspend() { Pause(); m_renderer->Trim(); } void GameEngine::DirectXPage::Resume() { Unpause(); } void GameEngine::DirectXPage::OnVisibilityChanged(Windows::UI::Core::CoreWindow ^sender, Windows::UI::Core::VisibilityChangedEventArgs ^args) { if (args->Visible) Unpause(); else Pause(); } void GameEngine::DirectXPage::OnBackToMenuTapped(Platform::Object ^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs ^e) { MenuButtonsGrid->Visibility = Windows::UI::Xaml::Visibility::Visible; LevelButtonsGrid->Visibility = Windows::UI::Xaml::Visibility::Collapsed; active_UI = MenuButtonsGrid; } void GameEngine::DirectXPage::OnSuspending(Platform::Object ^sender, Windows::ApplicationModel::SuspendingEventArgs ^e) { m_renderer->Trim(); }
28.28692
283
0.728185
[ "render", "object", "vector" ]
22e734e81bad694cc33db37b43abd3cea639a1b0
8,887
cpp
C++
examples/mantevo/miniFE-1.1/optional/shards/example/example_03.cpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
1
2019-11-26T22:24:12.000Z
2019-11-26T22:24:12.000Z
examples/mantevo/miniFE-1.1/optional/shards/example/example_03.cpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
null
null
null
examples/mantevo/miniFE-1.1/optional/shards/example/example_03.cpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
null
null
null
//@HEADER // ************************************************************************ // // Shards : Shared Discretization Tools // Copyright 2008 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 Carter Edwards (hcedwar@sandia.gov), // Pavel Bochev (pbboche@sandia.gov), or // Denis Ridzal (dridzal@sandia.gov). // // ************************************************************************ //@HEADER /** \file \brief Example of the CellTools class. \author Created by P. Bochev, H. Carter Edwards and D. Ridzal */ #include <iostream> #include <iomanip> #include "Shards_CellTopology.hpp" using namespace std; using namespace shards; /** \brief Prints the vector with the selected topologies. \param topologies [in] - vector containing the selected topologies \param cellType [in] - enum for the selected cell type \param topologyType [in] - enum for the selected topology type */ void printSelectTopologies(const std::vector<CellTopology>& topologies, const ECellType cellType = ALL_CELLS, const ETopologyType topologyType = ALL_TOPOLOGIES); int main(int argc, char *argv[]) { std::cout \ << "===============================================================================\n" \ << "| |\n" \ << "| Example use of the Shards package: |\n" \ << "| |\n" \ << "| 1) Query of the available cell topologies |\n" \ << "| |\n" \ << "| Questions? Contact Pavel Bochev (pbboche@sandia.gov) |\n" \ << "| H. Carter Edwards (hcedwar@sandia.gov) |\n" \ << "| Denis Ridzal (dridzal@sandia.gov). |\n" \ << "| |\n" \ << "| shards's website: http://trilinos.sandia.gov/packages/shards |\n" \ << "| Trilinos website: http://trilinos.sandia.gov |\n" \ << "| |\n" \ << "===============================================================================\n\n"; /************************************************************************************************* * * * Cell type enums: ALL_CELLS, STANDARD_CELL, NONSTANDARD_CELL * * Topology type enums: ALL_TOPOLOGIES, BASE_TOPOLOGY, EXTENDED_TOPOLOGY * * * ***********************************************************************************************/ std::vector<CellTopology> topologies; std::cout \ << "===============================================================================\n"\ << "| EXAMPLE 1: Queries of predefined 0D, 1D, 2D and 3D cell topologies |\n"\ << "===============================================================================\n"; for(int cellDim = 0; cellDim < 4; cellDim++){ std::cout << "************ Selected cell dimension = " << cellDim << " ************\n"; // All cells shards::getTopologies(topologies, cellDim); printSelectTopologies(topologies); // All standard cells shards::getTopologies(topologies, cellDim, STANDARD_CELL); printSelectTopologies(topologies, STANDARD_CELL); // All standard cells with base topology shards::getTopologies(topologies, cellDim, STANDARD_CELL, BASE_TOPOLOGY); printSelectTopologies(topologies, STANDARD_CELL, BASE_TOPOLOGY); // All standard cells with extended topology shards::getTopologies(topologies, cellDim, STANDARD_CELL, EXTENDED_TOPOLOGY); printSelectTopologies(topologies, STANDARD_CELL, EXTENDED_TOPOLOGY); // All non-standard cells shards::getTopologies(topologies, cellDim, NONSTANDARD_CELL); printSelectTopologies(topologies, NONSTANDARD_CELL); // All non-standard 0D cells with base topology shards::getTopologies(topologies, cellDim, NONSTANDARD_CELL, BASE_TOPOLOGY); printSelectTopologies(topologies, NONSTANDARD_CELL, BASE_TOPOLOGY); // All non-standard cells with extended topology shards::getTopologies(topologies, cellDim, NONSTANDARD_CELL, EXTENDED_TOPOLOGY); printSelectTopologies(topologies, NONSTANDARD_CELL, EXTENDED_TOPOLOGY); } std::cout \ << "===============================================================================\n"\ << "| EXAMPLE 2: Query of all predefined cell topologies |\n"\ << "===============================================================================\n"; // This query uses default argument values for all input arguments: shards::getTopologies(topologies); printSelectTopologies(topologies); return 0; } /*************************************************************************************************** * * * Helper function * * * *************************************************************************************************/ void printSelectTopologies(const std::vector<CellTopology>& topologies, const ECellType cellType, const ETopologyType topologyType) { std::cout << "List of " << shards::ECellTypeToString(cellType) << " "; // If topologies contains all 33 predefined topologies do not print cell dimension if( topologies.size() == 33 ) { std::cout << "cells and "; } else if ( ! topologies.empty() ) { std::cout << topologies[0].getDimension() << "D cells and "; } std::cout << shards::ETopologyTypeToString(topologyType) << " topology types (total of " << topologies.size() << " cells)\n"; std::cout << "-------------------------------------------------------------------------------\n"; std::cout << setw(25) << " Cell Topology " << setw(25) << " Base topology" << setw(30) << "|\n"; std::cout << "-------------------------------------------------------------------------------\n"; for(unsigned i = 0; i < topologies.size(); i++){ std::cout << setw(25) << topologies[i].getName() << setw(25) << topologies[i].getBaseName() << "\n"; } std::cout << "===============================================================================\n\n"; }
41.919811
105
0.4726
[ "vector", "3d" ]
22ea6ed6b0b39e9b5a63460c906f67ca06a8054f
1,148
cpp
C++
radix_sort.cpp
agaitanis/my_algorithms
56e20f530f1bef850a61cdc0933830107a3e239a
[ "MIT" ]
1
2019-03-05T22:49:42.000Z
2019-03-05T22:49:42.000Z
radix_sort.cpp
agaitanis/my_algorithms
56e20f530f1bef850a61cdc0933830107a3e239a
[ "MIT" ]
null
null
null
radix_sort.cpp
agaitanis/my_algorithms
56e20f530f1bef850a61cdc0933830107a3e239a
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <climits> #include <cassert> #include <cmath> #include "radix_sort.hpp" #include "my_tools.hpp" using namespace std; static int digit_of(int a, int digit) { int ret = 0; for (int i = 0; i < digit; i++) { ret = a % 10; a /= 10; } return ret; } static void counting_sort_digit(vector<int> &a, int digit) { int n = a.size(); int k = 10; vector<int> b(n); vector<int> c(k, 0); for (int i = 0; i < n; i++) { c[digit_of(a[i], digit)]++; } for (int i = 1; i < k; i++) { c[i] += c[i-1]; } for (int i = n-1; i >= 0; i--) { b[c[digit_of(a[i], digit)]-1] = a[i]; c[digit_of(a[i], digit)]--; } a = b; } void radix_sort(vector<int> &a, int d) { for (int i = 1; i <= d; i++) { counting_sort_digit(a, i); } } void test_radix_sort() { for (int i = 0; i < 1000; i++) { int d = 3; int n = rand_int(1, 10); vector<int> a(n); for (int j = 0; j < n; j++) { a[j] = rand_int(0, pow(10, d)); } print_vec("unsorted: ", a); radix_sort(a, d); print_vec("sorted: ", a); printf("\n"); // alex for (int j = 1; j < n; j++) { assert(a[j] >= a[j-1]); } } }
15.105263
58
0.523519
[ "vector" ]
22f760e39f86b29ccf025a83b2a43c87882f9e02
5,583
cc
C++
lite/backends/npu/device.cc
Rachel-1207/Paddle-Lite
e6b3d883db8871600f1c46f6aa1a1dbf83d430d3
[ "Apache-2.0" ]
1
2020-07-13T09:57:34.000Z
2020-07-13T09:57:34.000Z
lite/backends/npu/device.cc
Rachel-1207/Paddle-Lite
e6b3d883db8871600f1c46f6aa1a1dbf83d430d3
[ "Apache-2.0" ]
null
null
null
lite/backends/npu/device.cc
Rachel-1207/Paddle-Lite
e6b3d883db8871600f1c46f6aa1a1dbf83d430d3
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/backends/npu/device.h" #include "lite/utils/cp_logging.h" #include "lite/utils/io.h" namespace paddle { namespace lite { namespace npu { std::shared_ptr<hiai::AiModelMngerClient> Device::Load( const std::string& model_name, std::vector<char>* model_buffer, bool* model_comp) { // Create a HiAI model manager client to load the HiAI om model auto model_client = std::make_shared<hiai::AiModelMngerClient>(); if (model_client->Init(nullptr) != hiai::AI_SUCCESS) { LOG(WARNING) << "[NPU] Init hiai model client failed!"; return nullptr; } // Check HiAI DDK version const char* ddk_version = model_client->GetVersion(); if (ddk_version) { LOG(INFO) << "[NPU] HiAI DDK version: " << ddk_version; } else { LOG(WARNING) << "[NPU] Unable to get HiAI DDK version!"; } // Check model compatibility auto model_desc = std::make_shared<hiai::AiModelDescription>( model_name, freq_level(), framework_type(), model_type(), device_type()); model_desc->SetModelBuffer( reinterpret_cast<const void*>(model_buffer->data()), model_buffer->size()); if (!*model_comp && model_client->CheckModelCompatibility(*model_desc, *model_comp) != hiai::AI_SUCCESS) { *model_comp = false; VLOG(3) << "[NPU] model is NOT compatiblitiable, setting model_comp to " << *model_comp; } else { *model_comp = true; VLOG(3) << "[NPU] model is compatiblitiable, setting model_comp to " << *model_comp; } // Rebuild and write the data of the compatible model to the model buffer if (!*model_comp) { std::shared_ptr<hiai::AiModelBuilder> model_builder = std::make_shared<hiai::AiModelBuilder>(model_client); hiai::MemBuffer* org_model_buffer = model_builder->InputMemBufferCreate( reinterpret_cast<void*>(model_buffer->data()), model_buffer->size()); if (org_model_buffer) { std::vector<hiai::MemBuffer*> org_model_buffers; org_model_buffers.push_back(org_model_buffer); hiai::MemBuffer* new_model_buffer = model_builder->OutputMemBufferCreate( framework_type(), org_model_buffers); // VLOG(3) << "[NPU] new model buffer memeory size is " << // new_model_buffer->GetMemBufferSize(); if (new_model_buffer) { uint32_t new_model_size = 0; if (model_builder->BuildModel(org_model_buffers, new_model_buffer, new_model_size) == hiai::AI_SUCCESS) { // need to change to new_model_size as GetMemBufferSize is not // correct. model_buffer->resize(new_model_size); memcpy(reinterpret_cast<void*>(model_buffer->data()), new_model_buffer->GetMemBufferData(), new_model_size); // Reset the model buffer model_desc->SetModelBuffer( reinterpret_cast<const void*>(model_buffer->data()), model_buffer->size()); VLOG(3) << "[NPU] Rebuild the compatible model done."; } else { LOG(WARNING) << "[NPU] Rebuild the compatible model failed!"; } model_builder->MemBufferDestroy(new_model_buffer); } else { LOG(WARNING) << "[NPU] OutputMemBufferCreate failed!"; } model_builder->MemBufferDestroy(org_model_buffer); } else { LOG(WARNING) << "[NPU] InputMemBufferCreate failed!"; } } // Load the compatible model std::vector<std::shared_ptr<hiai::AiModelDescription>> model_descs{ model_desc}; if (model_client->Load(model_descs) != hiai::AI_SUCCESS) { LOG(WARNING) << "[NPU] AiModelMngerClient load model failed!"; return nullptr; } VLOG(3) << "[NPU] Load model done."; return model_client; } bool Device::Build(std::vector<ge::Operator>& input_nodes, // NOLINT std::vector<ge::Operator>& output_nodes, // NOLINT std::vector<char>* model_buffer) { // Convert the HiAI IR graph to the HiAI om model ge::Graph ir_graph("graph"); ir_graph.SetInputs(input_nodes).SetOutputs(output_nodes); ge::Model om_model("model", "model"); om_model.SetGraph(ir_graph); // Build the HiAI om model, serialize and output it to the om buffer domi::HiaiIrBuild ir_build; domi::ModelBufferData om_buffer; if (!ir_build.CreateModelBuff(om_model, om_buffer)) { LOG(WARNING) << "[NPU] CreateModelBuff failed!"; return false; } if (!ir_build.BuildIRModel(om_model, om_buffer)) { LOG(WARNING) << "[NPU] BuildIRModel failed!"; ir_build.ReleaseModelBuff(om_buffer); return false; } model_buffer->resize(om_buffer.length); memcpy(reinterpret_cast<void*>(model_buffer->data()), reinterpret_cast<void*>(om_buffer.data), om_buffer.length); ir_build.ReleaseModelBuff(om_buffer); VLOG(3) << "[NPU] Build model done."; return true; } } // namespace npu } // namespace lite } // namespace paddle
39.316901
79
0.663622
[ "vector", "model" ]
fe01c7ae7eb08e40f462e3a53bd4ff46730dfce9
4,485
cpp
C++
src/Type.cpp
CESNET/libyang-cpp
e31f0c87cdd724d33c8899b1bf23289e062bb855
[ "BSD-3-Clause" ]
5
2021-06-09T15:09:37.000Z
2022-02-15T16:43:57.000Z
src/Type.cpp
CESNET/libyang-cpp
e31f0c87cdd724d33c8899b1bf23289e062bb855
[ "BSD-3-Clause" ]
3
2021-09-07T14:32:58.000Z
2022-02-17T14:56:01.000Z
src/Type.cpp
CESNET/libyang-cpp
e31f0c87cdd724d33c8899b1bf23289e062bb855
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2021 CESNET, https://photonics.cesnet.cz/ * * Written by Václav Kubernát <kubernat@cesnet.cz> * * SPDX-License-Identifier: BSD-3-Clause */ #include <libyang-cpp/Module.hpp> #include <libyang-cpp/SchemaNode.hpp> #include <libyang-cpp/Type.hpp> #include <libyang-cpp/Utils.hpp> #include <libyang/libyang.h> #include <span> #include "utils/enum.hpp" namespace libyang { Type::Type(const lysc_type* type, std::shared_ptr<ly_ctx> ctx) : m_type(type) , m_ctx(ctx) { } Type::Type(const lysp_type* type, std::shared_ptr<ly_ctx> ctx) : m_type(type->compiled) , m_typeParsed(type) , m_ctx(ctx) { } void Type::throwIfParsedUnavailable() const { if (!m_typeParsed) { throw libyang::Error("Context not created with libyang::ContextOptions::SetPrivParsed"); } } /** * Returns the base type of this Type. This is one of the YANG built-in types. */ LeafBaseType Type::base() const { return utils::toLeafBaseType(m_type->basetype); } types::Enumeration Type::asEnum() const { if (base() != LeafBaseType::Enum) { throw Error("Type is not an enum"); } return types::Enumeration{m_type, m_ctx}; } types::Bits Type::asBits() const { if (base() != LeafBaseType::Bits) { throw Error("Type is not a bit field"); } return types::Bits{m_type, m_ctx}; } types::IdentityRef Type::asIdentityRef() const { if (base() != LeafBaseType::IdentityRef) { throw Error("Type is not an identityref"); } return types::IdentityRef{m_type, m_ctx}; } types::LeafRef Type::asLeafRef() const { if (base() != LeafBaseType::Leafref) { throw Error("Type is not a leafref"); } return types::LeafRef{m_type, m_ctx}; } types::Union Type::asUnion() const { if (base() != LeafBaseType::Union) { throw Error("Type is not a union"); } return types::Union{m_type, m_ctx}; } std::vector<types::Enumeration::Enum> types::Enumeration::items() const { auto enm = reinterpret_cast<const lysc_type_enum*>(m_type); std::vector<types::Enumeration::Enum> res; for (const auto& it : std::span(enm->enums, LY_ARRAY_COUNT(enm->enums))) { auto& resIt = res.emplace_back(); resIt.m_ctx = m_ctx; resIt.name = it.name; resIt.value = it.value; } return res; } /** * Returns the name of the type. * This method only works if the associated context was created with the libyang::ContextOptions::SetPrivParsed flag. */ std::string_view Type::name() const { throwIfParsedUnavailable(); return m_typeParsed->name; } std::vector<types::Bits::Bit> types::Bits::items() const { auto enm = reinterpret_cast<const lysc_type_bits*>(m_type); std::vector<Bits::Bit> res; for (const auto& it : std::span(enm->bits, LY_ARRAY_COUNT(enm->bits))) { auto& resIt = res.emplace_back(); resIt.m_ctx = m_ctx; resIt.name = it.name; resIt.position = it.position; } return res; } std::vector<Identity> types::IdentityRef::bases() const { auto ident = reinterpret_cast<const lysc_type_identityref*>(m_type); std::vector<Identity> res; for (const auto& it : std::span(ident->bases, LY_ARRAY_COUNT(ident->bases))) { res.emplace_back(Identity{it, m_ctx}); } return res; } Identity::Identity(const lysc_ident* ident, std::shared_ptr<ly_ctx> ctx) : m_ident(ident) , m_ctx(ctx) { } std::vector<Identity> Identity::derived() const { std::vector<Identity> res; for (const auto& it : std::span(m_ident->derived, LY_ARRAY_COUNT(m_ident->derived))) { res.emplace_back(Identity{it, m_ctx}); } return res; } Module Identity::module() const { return Module{m_ident->module, m_ctx}; } std::string_view Identity::name() const { return m_ident->name; } std::string_view types::LeafRef::path() const { auto lref = reinterpret_cast<const lysc_type_leafref*>(m_type); return lyxp_get_expr(lref->path); } /** * Returns the first non-leafref type in the chain of leafrefs. */ Type types::LeafRef::resolvedType() const { auto lref = reinterpret_cast<const lysc_type_leafref*>(m_type); return Type{lref->realtype, m_ctx}; } std::vector<Type> types::Union::types() const { auto types = reinterpret_cast<const lysc_type_union*>(m_type)->types; std::vector<Type> res; for (const auto& it : std::span(types, LY_ARRAY_COUNT(types))) { res.emplace_back(Type{it, m_ctx}); } return res; } }
23.359375
117
0.658863
[ "vector" ]
fe0ab8e554836ee412e6b0ea725353bacbe2d457
19,357
cpp
C++
src/ir/ranges.cpp
NK-Nikunj/phylanx
6898992513a122c49d26947d877f329365486665
[ "BSL-1.0" ]
null
null
null
src/ir/ranges.cpp
NK-Nikunj/phylanx
6898992513a122c49d26947d877f329365486665
[ "BSL-1.0" ]
null
null
null
src/ir/ranges.cpp
NK-Nikunj/phylanx
6898992513a122c49d26947d877f329365486665
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2018 Parsa Amini // Copyright (c) 2018 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <phylanx/config.hpp> #include <phylanx/execution_tree/primitives/base_primitive.hpp> #include <phylanx/ir/ranges.hpp> #include <hpx/include/util.hpp> #include <hpx/throw_exception.hpp> #include <algorithm> #include <cstddef> #include <cstdint> #include <utility> #include <vector> namespace phylanx { namespace ir { ////////////////////////////////////////////////////////////////////////// reverse_range_iterator range_iterator::invert() { switch (it_.index()) { case 0: // int_range_type { int_range_type& p = util::get<0>(it_); return reverse_range_iterator{p.first, p.second}; } case 1: // args_iterator_type return reverse_range_iterator( args_reverse_iterator_type(util::get<1>(it_))); case 2: // args_const_iterator_type return reverse_range_iterator( args_reverse_const_iterator_type(util::get<2>(it_))); } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range_iterator::invert", "range_iterator object holds unsupported data type"); } execution_tree::primitive_argument_type range_iterator::dereference() const { switch (it_.index()) { case 0: // int_range_type return execution_tree::primitive_argument_type( util::get<0>(it_).first); case 1: // args_iterator_type return *(util::get<1>(it_)); case 2: // args_const_iterator_type return *(util::get<2>(it_)); } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range_iterator::dereference", "range_iterator object holds unsupported data type"); } bool range_iterator::equal(range_iterator const& other) const { // Ensure that have comparable iterators if (it_.index() != other.it_.index()) { return false; } switch (it_.index()) { case 0: // int_range_type return util::get<0>(it_).first == util::get<0>(other.it_).first; case 1: // args_iterator_type return util::get<1>(it_) == util::get<1>(other.it_); case 2: // args_const_iterator_type return util::get<2>(it_) == util::get<2>(other.it_); } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range_iterator::equal", "range_iterator object holds unsupported data type"); } void range_iterator::increment() { switch (it_.index()) { case 0: // int_range_type { int_range_type& p = util::get<0>(it_); p.first += p.second; break; } case 1: // args_iterator_type ++util::get<1>(it_); break; case 2: // args_const_iterator_type ++util::get<2>(it_); break; default: HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range_iterator::increment", "range_iterator object holds unsupported data type"); } } ////////////////////////////////////////////////////////////////////////// execution_tree::primitive_argument_type reverse_range_iterator::dereference() const { switch (it_.index()) { case 0: // int_range_type return execution_tree::primitive_argument_type( util::get<0>(it_).first); case 1: // args_iterator_type return *(util::get<1>(it_)); case 2: // args_const_iterator_type return *(util::get<2>(it_)); } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::reverse_range_iterator::dereference", "reverse_range_iterator object holds unsupported data type"); } bool reverse_range_iterator::equal(reverse_range_iterator const& other) const { // Ensure that have comparable iterators if (it_.index() != other.it_.index()) { return false; } switch (it_.index()) { case 0: // int_range_type return util::get<0>(it_).first == util::get<0>(other.it_).first; case 1: // args_iterator_type return util::get<1>(it_) == util::get<1>(other.it_); case 2: // args_const_iterator_type return util::get<2>(it_) == util::get<2>(other.it_); } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::reverse_range_iterator::equal", "reverse_range_iterator object holds unsupported data type"); } void reverse_range_iterator::increment() { switch (it_.index()) { case 0: // int_range_type { int_range_type& p = util::get<0>(it_); p.first -= p.second; break; } case 1: // args_iterator_type ++util::get<1>(it_); break; case 2: // args_const_iterator_type ++util::get<2>(it_); break; default: HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::reverse_range_iterator::increment", "reverse_range_iterator object holds unsupported data type"); } } ////////////////////////////////////////////////////////////////////////// range_iterator range::begin() { switch (data_.index()) { case 0: // int_range_type { int_range_type const& int_range = util::get<0>(data_); std::int64_t start = hpx::util::get<0>(int_range); std::int64_t step = hpx::util::get<2>(int_range); return range_iterator{start, step}; } case 1: // wrapped_args_type return util::get<1>(data_).get().begin(); case 2: // arg_pair_type return util::get<2>(data_).first; } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::begin", "range object holds unsupported data type"); } const range_iterator range::begin() const { switch (data_.index()) { case 0: // int_range_type { int_range_type const& int_range = util::get<0>(data_); std::int64_t start = hpx::util::get<0>(int_range); std::int64_t step = hpx::util::get<2>(int_range); return range_iterator{start, step}; } case 1: // wrapped_args_type return util::get<1>(data_).get().begin(); case 2: // arg_pair_type return util::get<2>(data_).first; } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::begin", "range object holds unsupported data type"); } range_iterator range::end() { switch (data_.index()) { case 0: // int_range_type { const int_range_type& int_range = util::get<0>(data_); const std::int64_t start = hpx::util::get<0>(int_range); const std::int64_t stop = hpx::util::get<1>(int_range); const std::int64_t step = hpx::util::get<2>(int_range); const std::int64_t distance_to_start = stop - start; const std::int64_t n_steps = distance_to_start / step; const std::int64_t remaining_step = distance_to_start % step != 0 ? step : 0; const std::int64_t actual_stop = start + n_steps * step + remaining_step; return range_iterator{actual_stop, step}; } case 1: // wrapped_args_type return util::get<1>(data_).get().end(); case 2: // arg_pair_type return util::get<2>(data_).second; } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::end", "range object holds unsupported data type"); } const range_iterator range::end() const { switch (data_.index()) { case 0: // int_range_type { const int_range_type& int_range = util::get<0>(data_); const std::int64_t start = hpx::util::get<0>(int_range); const std::int64_t stop = hpx::util::get<1>(int_range); const std::int64_t step = hpx::util::get<2>(int_range); const std::int64_t distance_to_start = stop - start; const std::int64_t n_steps = distance_to_start / step; const std::int64_t remaining_step = distance_to_start % step != 0 ? step : 0; const std::int64_t actual_stop = start + n_steps * step + remaining_step; return range_iterator{actual_stop, step}; } case 1: // wrapped_args_type return util::get<1>(data_).get().end(); case 2: // arg_pair_type return util::get<2>(data_).second; } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::end", "range object holds unsupported data type"); } reverse_range_iterator range::rbegin() { using args_iterator_type = std::vector< execution_tree::primitive_argument_type>::reverse_iterator; switch (data_.index()) { case 0: // int_range_type { const int_range_type& int_range = util::get<0>(data_); const std::int64_t start = hpx::util::get<0>(int_range); const std::int64_t stop = hpx::util::get<1>(int_range); const std::int64_t step = hpx::util::get<2>(int_range); const std::int64_t distance_to_start = stop - start; const std::int64_t n_steps = distance_to_start / step; const std::int64_t remaining_step = distance_to_start % step != 0 ? 0 : -step; const std::int64_t actual_begin = start + n_steps * step + remaining_step; return reverse_range_iterator{actual_begin, step}; } case 1: // wrapped_args_type return util::get<1>(data_).get().rbegin(); case 2: // arg_pair_type return util::get<2>(data_).second.invert(); } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::rbegin", "range object holds unsupported data type"); } reverse_range_iterator range::rend() { using args_iterator_type = std::vector< execution_tree::primitive_argument_type>::reverse_iterator; switch (data_.index()) { case 0: // int_range_type { int_range_type& int_range = util::get<0>(data_); std::int64_t start = hpx::util::get<0>(int_range); std::int64_t step = hpx::util::get<2>(int_range); return reverse_range_iterator{start - step, step}; } case 1: // wrapped_args_type return util::get<1>(data_).get().rend(); case 2: // arg_pair_type return util::get<2>(data_).first.invert(); } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::rend", "range object holds unsupported data type"); } std::ptrdiff_t range::size() const { switch (data_.index()) { case 0: // int_range_type { const int_range_type& int_range = util::get<0>(data_); const std::int64_t start = hpx::util::get<0>(int_range); const std::int64_t stop = hpx::util::get<1>(int_range); const std::int64_t step = hpx::util::get<2>(int_range); const std::int64_t distance_to_start = stop - start; const std::int64_t n_steps = distance_to_start / step; const std::int64_t remaining_step = distance_to_start % step > 0 ? 1 : 0; return n_steps + remaining_step; } case 1: // wrapped_args_type return util::get<1>(data_).get().size(); case 2: // arg_pair_type { auto const& first = util::get<2>(data_).first; auto const& second = util::get<2>(data_).second; return std::distance(second, first); } } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::rend", "range object holds unsupported data type"); } bool range::empty() const { switch (data_.index()) { case 0: // int_range_type { auto const& v = util::get<0>(data_); return hpx::util::get<0>(v) == hpx::util::get<1>(v); } case 1: // wrapped_args_type { auto const& v = util::get<1>(data_).get(); return v.begin() == v.end(); } case 2: // arg_pair_type { auto const& v = util::get<2>(data_); return v.first == v.second; } } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::empty", "range object holds unsupported data type"); } range::args_type& range::args() { wrapped_args_type* cv = util::get_if<wrapped_args_type>(&data_); if (cv != nullptr) return cv->get(); HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::args()", "range object holds unsupported data type"); } range::args_type const& range::args() const { wrapped_args_type const* cv = util::get_if<wrapped_args_type>(&data_); if (cv != nullptr) return cv->get(); HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::args&()", "range object holds unsupported data type"); } range::args_type range::copy() { switch (data_.index()) { case 0: // int_range_type { args_type result; std::copy(begin(), end(), std::back_inserter(result)); return result; } case 1: // wrapped_args_type return util::get<1>(data_).get(); case 2: // arg_pair_type { args_type result; auto const& v = util::get<2>(data_); std::copy(v.first, v.second, std::back_inserter(result)); return result; } default: break; } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::args()", "range object holds unsupported data type"); } range::args_type range::copy() const { switch (data_.index()) { case 0: // int_range_type { args_type result; std::copy(begin(), end(), std::back_inserter(result)); return result; } case 1: // wrapped_args_type return phylanx::util::get<1>(data_).get(); case 2: // arg_pair_type { args_type result; auto const& v = util::get<2>(data_); std::copy(v.first, v.second, std::back_inserter(result)); return result; } default: break; } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::args()", "range object holds unsupported data type"); } range range::ref() { switch (data_.index()) { case 0: HPX_FALLTHROUGH; // int_range_type case 1: HPX_FALLTHROUGH; // wrapped_args_type case 2: // arg_pair_type return range{begin(), end()}; default: break; } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::ref()", "range object holds unsupported data type"); } range const range::ref() const { switch (data_.index()) { case 0: HPX_FALLTHROUGH; // int_range_type case 1: HPX_FALLTHROUGH; // wrapped_args_type case 2: // arg_pair_type return range{begin(), end()}; default: break; } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::ref() const", "range object holds unsupported data type"); } bool range::is_ref() const { switch (data_.index()) { case 1: // wrapped_args_type return false; case 0: HPX_FALLTHROUGH; // int_range_type case 2: // arg_pair_type return true; default: break; } HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::is_ref()", "range object holds unsupported data type"); } ////////////////////////////////////////////////////////////////////////// bool range::operator==(range const& other) const { return data_ == other.data_; } bool range::operator!=(range const& other) const { return data_ != other.data_; } void range::serialize(hpx::serialization::output_archive& ar, unsigned) { std::size_t index = data_.index(); ar << index; switch (index) { case 0: // int_range_type { int_range_type& int_range = util::get<0>(data_); ar << hpx::util::get<0>(int_range) << hpx::util::get<1>(int_range) << hpx::util::get<2>(int_range); break; } case 1: // wrapped_args_type { ar << util::get<1>(data_); break; } case 2: // arg_pair_type { arg_pair_type p = util::get<2>(data_); args_type m; std::copy(p.first, p.second, std::back_inserter(m)); break; } default: HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::serialize()", "range object holds unsupported data type"); } } void range::serialize(hpx::serialization::input_archive& ar, unsigned) { std::size_t index = 0; ar >> index; switch (index) { case 0: // int_range_type { std::int64_t start, stop, step; ar >> start >> stop >> step; data_ = int_range_type(start, stop, step); break; } case 1: // wrapped_args_type { args_type m; ar >> m; data_ = std::move(m); break; } default: HPX_THROW_EXCEPTION(hpx::invalid_status, "phylanx::ir::range::serialize()", "range object holds unsupported data type"); } } }}
32.048013
81
0.522395
[ "object", "vector" ]
fe16ff5dac78a58ebfdfb97453418fe009f1a20e
1,019
cc
C++
cartographer/mapping/internal/3d/scan_matching/intensity_cost_function_3d.cc
laotie/cartographer
b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9
[ "Apache-2.0" ]
5,196
2016-08-04T14:52:31.000Z
2020-04-02T18:30:00.000Z
cartographer/mapping/internal/3d/scan_matching/intensity_cost_function_3d.cc
laotie/cartographer
b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9
[ "Apache-2.0" ]
1,206
2016-08-03T14:27:00.000Z
2020-03-31T21:14:18.000Z
cartographer/mapping/internal/3d/scan_matching/intensity_cost_function_3d.cc
laotie/cartographer
b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9
[ "Apache-2.0" ]
1,810
2016-08-03T05:45:02.000Z
2020-04-02T03:44:18.000Z
#include "cartographer/mapping/internal/3d/scan_matching/intensity_cost_function_3d.h" namespace cartographer { namespace mapping { namespace scan_matching { // This method is defined here instead of the header file as it was observed // that defining it in the header file has a negative impact on the runtime // performance. ceres::CostFunction* IntensityCostFunction3D::CreateAutoDiffCostFunction( const double scaling_factor, const float intensity_threshold, const sensor::PointCloud& point_cloud, const IntensityHybridGrid& hybrid_grid) { CHECK(!point_cloud.intensities().empty()); return new ceres::AutoDiffCostFunction< IntensityCostFunction3D, ceres::DYNAMIC /* residuals */, 3 /* translation variables */, 4 /* rotation variables */>( new IntensityCostFunction3D(scaling_factor, intensity_threshold, point_cloud, hybrid_grid), point_cloud.size()); } } // namespace scan_matching } // namespace mapping } // namespace cartographer
39.192308
86
0.741904
[ "3d" ]
fe1934037894b9b15bef04ccf8453fc69c4ac96d
2,857
cc
C++
tests/buffer.cc
eichf/pipeBB
7c992f644f9fc132ad0cc6f36bffdfd02601e388
[ "Apache-2.0" ]
null
null
null
tests/buffer.cc
eichf/pipeBB
7c992f644f9fc132ad0cc6f36bffdfd02601e388
[ "Apache-2.0" ]
null
null
null
tests/buffer.cc
eichf/pipeBB
7c992f644f9fc132ad0cc6f36bffdfd02601e388
[ "Apache-2.0" ]
null
null
null
// // Copyright 2018- Florian Eich <florian.eich@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "catch.h" #include "buffer.h" #include "channel.h" #include "counter.h" // // explicitly instantiate class to make sure compiler generates the class fully // (enables meaningful test coverage analysis) // template class pipebb::buffer<pipebb::channel<double>>; // TEST_CASE("functionality of buffer gates", "[buffer_gates]") { pipebb::channel<double> p_manifold{"p_manifold", "mbar", 1.0, 0.0}; SECTION("buffer") { // Instantiate buffer object. auto buf = pipebb::make_buffer(p_manifold); // // The following usage is also possible and (in this case) equally elegant // since C++17 supports template class parameter deduction. The // make_approximate function is provided for consistency with the other // library elements. // // pipebb::buffer cxx_17_ctor_test{p_manifold}; // // // Without a C++17-capable compiler (g++ 7 or later), this becomes: // pipebb::buffer<decltype(p_manifold)> cxx_14_ctor_test{p_manifold}; // p_manifold << 2500.0; REQUIRE(buf() == 2500.0); p_manifold << 2600.0; REQUIRE(buf() == 2500.0); buf.reset(); REQUIRE(buf() == 2600.0); buf.reset(); p_manifold << 0.0; REQUIRE(buf() == 0.0); p_manifold << 2600.0; REQUIRE(buf() == 2600.0); } SECTION("switched_buffer") { // Instantiate switch_buffer object. auto sbuf = pipebb::make_switched_buffer(p_manifold); // // The following usage is also possible and (in this case) equally elegant // since C++17 supports template class parameter deduction. The // make_approximate function is provided for consistency with the other // library elements. // // pipebb::switched_buffer cxx17_ctor_test{p_manifold}; // // // Without a C++17-capable compiler (g++ 7 or later), this becomes: // pipebb::switched_buffer<decltype(p_manifold)> cxx14_ctor_test{p_manifold}; // REQUIRE(!sbuf.state()); p_manifold << 2500.0; REQUIRE(sbuf() == 2500.0); p_manifold << 2600.0; REQUIRE(sbuf() == 2500.0); sbuf.toggle(); REQUIRE(sbuf() == 2600.0); p_manifold << 2700.0; REQUIRE(sbuf() == 2600.0); sbuf.reset(); REQUIRE(sbuf() == 2700.0); } }
26.95283
79
0.661533
[ "object" ]
fe203bd2b7f00a1fcd7141bc37ff9a9de86bdef0
2,996
cpp
C++
src/main.cpp
Kerosene2000/particle-system
501f52181bbe77c62de8f321da84e8045bc11f69
[ "MIT" ]
null
null
null
src/main.cpp
Kerosene2000/particle-system
501f52181bbe77c62de8f321da84e8045bc11f69
[ "MIT" ]
null
null
null
src/main.cpp
Kerosene2000/particle-system
501f52181bbe77c62de8f321da84e8045bc11f69
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: crenault <crenault@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/02/11 11:41:05 by crenault #+# #+# */ /* Updated: 2016/02/15 00:23:20 by crenault ### ########.fr */ /* */ /* ************************************************************************** */ #include "Window.hpp" #include "Particles.hpp" #include "pers_proj.hpp" // test cl.hpp #include "cl.hpp" #include <stdio.h> int main(int argc, char const **argv) { Window window("Particle System", 854, 480, GL_FALSE); Particles particles(1000); #pragma message("put this in the particles object") (void)argc; (void)argv; glClearColor(0.175f, 0.175f, 0.175f, 1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // t_mat4 proj_mat; t_mat4 trans_mat; t_mat4 rot_mat; t_mat4 scale_mat; t_mat4 model_mat; t_mat4 view_mat; // matrices float screen_ratio = (float)window.get_width() / (float)window.get_height(); proj_mat = mat4_pers_proj_rh(60.f, screen_ratio, 0.1f, 1000.f); // trans_mat = mat4_trans(-0.5f * map_size.x, 0.f, -0.5f * map_size.y); trans_mat = mat4_ident(); // rot_mat = mat4_rotate(0.0f, vec3(0.f, 1.f, 0.f)); rot_mat = mat4_ident(); float scale_ratio = 1.f; // 0.08f scale_mat = mat4_scale(scale_ratio, scale_ratio, scale_ratio); model_mat = mat4_mult(rot_mat, mat4_mult(scale_mat, trans_mat)); t_vec3 cam_pos = vec3(0, 1, 6); view_mat = mat4_view_lookat(cam_pos, vec3(0, 0, 0), vec3(0, 1, 0)); //*/ // loading matrices GLint tmp_location; particles.use_gl_program(); tmp_location = particles.get_uniform_location("proj_mat"); glUniformMatrix4fv(tmp_location, 1, GL_FALSE, proj_mat.m); tmp_location = particles.get_uniform_location("model_mat"); glUniformMatrix4fv(tmp_location, 1, GL_FALSE, model_mat.m); tmp_location = particles.get_uniform_location("view_mat"); glUniformMatrix4fv(tmp_location, 1, GL_FALSE, view_mat.m); while (glfwWindowShouldClose(window.get_ptr()) == GL_FALSE) { glfwPollEvents(); if (GLFW_PRESS == glfwGetKey(window.get_ptr(), GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose(window.get_ptr(), GL_TRUE); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); #pragma message("update FPS counter here !!!") // create fps counter with particles turning around gravity points !!! // particles.bind_array(); particles.draw_arrays(); glfwSwapBuffers(window.get_ptr()); } return (0); }
32.565217
80
0.539052
[ "object" ]
fe24967f1d192b3b0b9109e9aa8adcb4fb2fe5c5
5,809
hpp
C++
adaptivlib/include/adaptiv/utility/input/parsers.hpp
seriouslyhypersonic/adaptiv_co
2421d7dc91d0291dd45702a2a2ddadab9adda91d
[ "BSL-1.0" ]
null
null
null
adaptivlib/include/adaptiv/utility/input/parsers.hpp
seriouslyhypersonic/adaptiv_co
2421d7dc91d0291dd45702a2a2ddadab9adda91d
[ "BSL-1.0" ]
null
null
null
adaptivlib/include/adaptiv/utility/input/parsers.hpp
seriouslyhypersonic/adaptiv_co
2421d7dc91d0291dd45702a2a2ddadab9adda91d
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) Nuno Alves de Sousa 2019 * * Use, modification and distribution is subject to the Boost Software License, * Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #ifndef ADAPTIV_PARSERS_HPP #define ADAPTIV_PARSERS_HPP #include <adaptiv/macros.hpp> #include <adaptiv/traits/traits.hpp> #include <adaptiv/utility/input/auxiliary_parsers.hpp> #include <adaptiv/utility/input/character_parsers.hpp> #include <adaptiv/utility/input/numeric_parsers.hpp> #include <boost/spirit/home/x3.hpp> #include <boost/spirit/home/x3/support/utility/error_reporting.hpp> /// Static assertion: assert type \c T is std::vector todo: move to macros.hpp #define ADAPTIV_ASSERT_STD_VECTOR(T, ...) \ static_assert( \ traits::is_specialization_v<T, std::vector>,\ __VA_ARGS__) \ /// Static assertion: assert type \c T is arithmetic or std::string todo: move to macros.hpp #define ADAPTIV_ASSERT_ARITHMETIC_OR_STRING(T, ...) \ static_assert( \ std::is_arithmetic_v<T> || traits::is_basic_string_v<T>,\ __VA_ARGS__) ADAPTIV_NAMESPACE_BEGIN ADAPTIV_UTILITY_NAMESPACE_BEGIN ADAPTIV_INPUT_NAMESPACE_BEGIN /// X3 parsers conforming to adaptiv-specific grammars namespace parsers { namespace x3 = boost::spirit::x3; /// The error handler used to report a parsing failure struct ErrorHandler { template<class Iterator, class Exception, class Context> x3::error_handler_result on_error( Iterator& first, Iterator const& last, Exception const& exception, Context const& context) { // Get the error handler from the parser context auto& error_handler = x3::get<x3::error_handler_tag>(context).get(); // Pass the position and error message std::string message = "parse error: " + exception.which() + " here:"; error_handler(exception.where(), message); // The parser will quit and fail immediately return x3::error_handler_result::fail; } }; namespace detail { // Metafunction to create a tag that inherits the ErrorHandler when required template<bool withErrorHandling> struct make_tag { }; template<> struct make_tag<true>: ErrorHandler { }; } // namespace detail /** * Make an X3 parser using a grammar for comma separated elements * @tparam T The type of list elements * @tparam withErrorHandling Flag used to provide error handling support * @return The X3 parser according to the type of list elements * @note Numeric types are parsed according to their specific X3 numeric parser * @note Strings are parsed as quoted text */ template<class T, bool withErrorHandling = true> auto makeListParser() { ADAPTIV_ASSERT_ARITHMETIC_OR_STRING(T, "list elements must be an arithmetic type or a std::string"); struct list_tag: detail::make_tag<withErrorHandling> { }; using auxiliary::eolist; using character::comma; if constexpr (std::is_arithmetic_v<T>) { // The numeric parser for type T using num_tag = typename numeric::get_numeric_parser<T>::tag; auto num_name = numeric::get_numeric_parser<T>::name; auto num_def = numeric::get_numeric_parser<T>::parser; auto const num = x3::rule<num_tag, T>{num_name} = num_def; // The parser for a numeric list auto const list = x3::rule<list_tag, std::vector<T>>{"numeric list"} = x3::expect[num] > (eolist | (*(comma > num) > eolist)); return list; } else { // The quoted string parser using character::quotedString; // The parser for a list of quoted strings auto const list = x3::rule<list_tag, std::vector<T>>{"quoted string list"} = x3::expect[quotedString] > (eolist | (*(comma > quotedString) > eolist)); return list; } } /** * Make an X3 parser using a grammar for arrays: [elem1 elem2 ... elemN] * @tparam T The type of array elements * @tparam withErrorHandling Flag used to provide error handling support * @return The X3 parser according to the type of array elements * @note Numeric types are parsed according to their specific X3 numeric parser * @note Strings are parsed as quoted text */ template<class T, bool withErrorHandling = true> auto makeArrayParser() { ADAPTIV_ASSERT_ARITHMETIC_OR_STRING(T, "array elements must be an arithmetic type or a std::string"); struct array_tag: detail::make_tag<withErrorHandling> { }; using character::obracket; using character::cbracket; if constexpr (std::is_arithmetic_v<T>) { // The numeric parser for type T using num_tag = typename numeric::get_numeric_parser<T>::tag; auto num_name = numeric::get_numeric_parser<T>::name; auto num_def = numeric::get_numeric_parser<T>::parser; auto const num = x3::rule<num_tag, T>{num_name} = num_def; // The parser for a numeric array auto const array = x3::rule<array_tag, std::vector<T>>{"numeric array"} = x3::expect[obracket] > *num > cbracket; return array; } else { // The quoted string parser using character::quotedString; // The parser for an array of quoted strings auto const array = x3::rule<array_tag, std::vector<T>>{"quoted string array"} = x3::expect[obracket] > *quotedString > cbracket; return array; } } } // namespace parsers ADAPTIV_INPUT_NAMESPACE_END ADAPTIV_UTILITY_NAMESPACE_END ADAPTIV_NAMESPACE_END #endif //ADAPTIV_PARSERS_HPP
33.385057
104
0.661732
[ "vector" ]
fe29b6bfed636ddfa9aaccce082fa39418a21f31
17,492
cc
C++
inc.cc
chenshuo/cppindex
762b51ffddf6763649cf932bf50cf7fc84e9218e
[ "BSD-3-Clause" ]
19
2016-04-20T20:43:30.000Z
2021-06-22T14:46:24.000Z
inc.cc
chenshuo/cppindex
762b51ffddf6763649cf932bf50cf7fc84e9218e
[ "BSD-3-Clause" ]
null
null
null
inc.cc
chenshuo/cppindex
762b51ffddf6763649cf932bf50cf7fc84e9218e
[ "BSD-3-Clause" ]
3
2016-12-06T21:16:00.000Z
2019-11-07T13:34:36.000Z
#include "build/record.pb.h" #include "llvm/Support/MD5.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/Preprocessor.h" #include "clang/Tooling/Tooling.h" #include "leveldb/db.h" #include <boost/noncopyable.hpp> #include <iostream> #include <iomanip> #include <set> namespace indexer { using namespace clang; using std::string; #include "sink.h" class CommonHeader { public: CommonHeader() { leveldb::Options options; options.create_if_missing = true; leveldb::DB* db; leveldb::Status status = leveldb::DB::Open(options, "testdb", &db); assert (status.ok()); db_.reset(db); } void save(const std::set<string>& seen) { auto common= merge(seen); std::cout << common.size() << " common headers\n"; proto::CompilationUnit cu; for (const string& file : common) { cu.add_files(file); } Sink sink(db_.get()); sink.writeOrDie("inc:", cu.SerializeAsString()); } private: bool load(proto::CompilationUnit* cu) { std::string content; leveldb::Status s = db_->Get(leveldb::ReadOptions(), "inc:", &content); if (s.ok()) { return cu->ParseFromString(content); } else { return false; } } std::set<string> merge(const std::set<string>& seen) { proto::CompilationUnit cu; if (load(&cu)) { std::set<string> common; /* if (cu.files().size() < seen.size() / 10) { for (const string& file : cu.files()) { if (seen.find(file) != seen.end()) { common.insert(file); } } } else */ { std::set_intersection(seen.begin(), seen.end(), cu.files().begin(), cu.files().end(), std::inserter<>(common, common.end())); } return common; } else { return seen; } } std::unique_ptr<leveldb::DB> db_; }; /// \brief This interface provides a way to observe the actions of the /// preprocessor as it does its thing. /// /// Clients can define their hooks here to implement preprocessor level tools. class IncludePPCallbacks : public clang::PPCallbacks { public: IncludePPCallbacks(clang::CompilerInstance& compiler) : compiler_(compiler), preprocessor_(compiler.getPreprocessor()), sourceManager_(compiler.getSourceManager()) { std::cout << "IncludePPCallbacks " << filePath(sourceManager_.getMainFileID()) << "\n"; } ~IncludePPCallbacks() override { std::cout << "~IncludePPCallbacks\n\n"; } string filePath(clang::FileID fileId) const { if (fileId.isInvalid()) return "<invalid location>"; if (const clang::FileEntry* fileEntry = sourceManager_.getFileEntryForID(fileId)) return fileEntry->getName(); return kBuiltInFileName; } std::string filePath(clang::SourceLocation location) const { if (location.isInvalid()) return "<invalid location>"; if (location.isFileID()) return filePath(sourceManager_.getFileID(location)); return "<unknown>"; } static constexpr const char* kBuiltInFileName = "<built-in>"; static const char* reasonString(clang::PPCallbacks::FileChangeReason reason) { switch (reason) { case clang::PPCallbacks::EnterFile: return "Enter"; case clang::PPCallbacks::ExitFile: return "Exit"; case clang::PPCallbacks::SystemHeaderPragma: return "SystemHeaderPragma"; case clang::PPCallbacks::RenameFile: return "Rename"; default: return "Unknown"; } } /* enum FileChangeReason { EnterFile, ExitFile, SystemHeaderPragma, RenameFile }; */ /// \brief Callback invoked whenever a source file is entered or exited. /// /// \param Loc Indicates the new location. /// \param PrevFID the file that was exited if \p Reason is ExitFile. void FileChanged(SourceLocation loc, FileChangeReason reason, SrcMgr::CharacteristicKind fileType, FileID prevFID) override { const std::string file_changed = filePath(loc); bool reenter = false; if (reason == EnterFile) { ++indent_; if (!seen_files_.insert(file_changed).second) { reenter = true; reenter_files_.insert(file_changed); } } else if (reason == ExitFile) --indent_; std::cout << "FileChanged: " << std::setw(3) << indent_ << string(2*indent_, ' ') << reasonString(reason) << " " << file_changed << " FROM " << filePath(prevFID) << (reenter ? " REENTER" : "") << "\n"; } /// \brief Callback invoked whenever a source file is skipped as the result /// of header guard optimization. /// /// \param ParentFile The file that \#included the skipped file. /// /// \param FilenameTok The token in ParentFile that indicates the /// skipped file. void FileSkipped(const FileEntry &parentFile, const Token &filenameTok, SrcMgr::CharacteristicKind FileType) override { std::cout << "FileSkipped: " << string(2*indent_, ' ') << "Skip " << preprocessor_.getSpelling(filenameTok) << " OF " << parentFile.getName() << "\n"; } /// \brief Callback invoked whenever an inclusion directive results in a /// file-not-found error. /// /// \param FileName The name of the file being included, as written in the /// source code. /// /// \param RecoveryPath If this client indicates that it can recover from /// this missing file, the client should set this as an additional header /// search patch. /// /// \returns true to indicate that the preprocessor should attempt to recover /// by adding \p RecoveryPath as a header search path. bool FileNotFound(StringRef FileName, SmallVectorImpl<char> &RecoveryPath) override { return false; } /// \brief Callback invoked whenever an inclusion directive of /// any kind (\c \#include, \c \#import, etc.) has been processed, regardless /// of whether the inclusion will actually result in an inclusion. /// /// \param HashLoc The location of the '#' that starts the inclusion /// directive. /// /// \param IncludeTok The token that indicates the kind of inclusion /// directive, e.g., 'include' or 'import'. /// /// \param FileName The name of the file being included, as written in the /// source code. /// /// \param IsAngled Whether the file name was enclosed in angle brackets; /// otherwise, it was enclosed in quotes. /// /// \param FilenameRange The character range of the quotes or angle brackets /// for the written file name. /// /// \param File The actual file that may be included by this inclusion /// directive. /// /// \param SearchPath Contains the search path which was used to find the file /// in the file system. If the file was found via an absolute include path, /// SearchPath will be empty. For framework includes, the SearchPath and /// RelativePath will be split up. For example, if an include of "Some/Some.h" /// is found via the framework path /// "path/to/Frameworks/Some.framework/Headers/Some.h", SearchPath will be /// "path/to/Frameworks/Some.framework/Headers" and RelativePath will be /// "Some.h". /// /// \param RelativePath The path relative to SearchPath, at which the include /// file was found. This is equal to FileName except for framework includes. /// /// \param Imported The module, whenever an inclusion directive was /// automatically turned into a module import or null otherwise. /// void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName, bool IsAngled, CharSourceRange FilenameRange, const FileEntry *File, StringRef SearchPath, StringRef RelativePath, const Module *Imported) override { } /// \brief Callback invoked when the end of the main file is reached. /// /// No subsequent callbacks will be made. void EndOfMainFile() override { std::cout << "EndOfMainFile: "; clang::FileID fileId = sourceManager_.getMainFileID(); if (const clang::FileEntry* fileEntry = sourceManager_.getFileEntryForID(fileId)) { std::cout << fileEntry->getName(); } std::cout << "\n\n"; std::cout << "Seen:\n"; for (const string& file : seen_files_) { std::cout << file << "\n"; } std::cout << "\nReenter:\n"; for (const string& file : reenter_files_) { std::cout << file << "\n"; } std::cout << "\n"; CommonHeader ch; ch.save(seen_files_); } #if 0 { /// \brief Callback invoked whenever there was an explicit module-import /// syntax. /// /// \param ImportLoc The location of import directive token. /// /// \param Path The identifiers (and their locations) of the module /// "path", e.g., "std.vector" would be split into "std" and "vector". /// /// \param Imported The imported module; can be null if importing failed. /// virtual void moduleImport(SourceLocation ImportLoc, ModuleIdPath Path, const Module *Imported) { } /// \brief Callback invoked when a \#ident or \#sccs directive is read. /// \param Loc The location of the directive. /// \param str The text of the directive. /// virtual void Ident(SourceLocation Loc, const std::string &str) { } /// \brief Callback invoked when start reading any pragma directive. virtual void PragmaDirective(SourceLocation Loc, PragmaIntroducerKind Introducer) { } /// \brief Callback invoked when a \#pragma comment directive is read. virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, const std::string &Str) { } /// \brief Callback invoked when a \#pragma detect_mismatch directive is /// read. virtual void PragmaDetectMismatch(SourceLocation Loc, const std::string &Name, const std::string &Value) { } /// \brief Callback invoked when a \#pragma clang __debug directive is read. /// \param Loc The location of the debug directive. /// \param DebugType The identifier following __debug. virtual void PragmaDebug(SourceLocation Loc, StringRef DebugType) { } /// \brief Determines the kind of \#pragma invoking a call to PragmaMessage. enum PragmaMessageKind { /// \brief \#pragma message has been invoked. PMK_Message, /// \brief \#pragma GCC warning has been invoked. PMK_Warning, /// \brief \#pragma GCC error has been invoked. PMK_Error }; /// \brief Callback invoked when a \#pragma message directive is read. /// \param Loc The location of the message directive. /// \param Namespace The namespace of the message directive. /// \param Kind The type of the message directive. /// \param Str The text of the message directive. virtual void PragmaMessage(SourceLocation Loc, StringRef Namespace, PragmaMessageKind Kind, StringRef Str) { } /// \brief Callback invoked when a \#pragma gcc dianostic push directive /// is read. virtual void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) { } /// \brief Callback invoked when a \#pragma gcc dianostic pop directive /// is read. virtual void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) { } /// \brief Callback invoked when a \#pragma gcc dianostic directive is read. virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace, diag::Severity mapping, StringRef Str) {} /// \brief Called when an OpenCL extension is either disabled or /// enabled with a pragma. virtual void PragmaOpenCLExtension(SourceLocation NameLoc, const IdentifierInfo *Name, SourceLocation StateLoc, unsigned State) { } /// \brief Callback invoked when a \#pragma warning directive is read. virtual void PragmaWarning(SourceLocation Loc, StringRef WarningSpec, ArrayRef<int> Ids) { } /// \brief Callback invoked when a \#pragma warning(push) directive is read. virtual void PragmaWarningPush(SourceLocation Loc, int Level) { } /// \brief Callback invoked when a \#pragma warning(pop) directive is read. virtual void PragmaWarningPop(SourceLocation Loc) { } } #endif /// \brief Called by Preprocessor::HandleMacroExpandedIdentifier when a /// macro invocation is found. virtual void MacroExpands(const Token &MacroNameTok, const MacroDirective *MD, SourceRange Range, const MacroArgs *Args) { } /// \brief Hook called whenever a macro definition is seen. virtual void MacroDefined(const Token &MacroNameTok, const MacroDirective *MD) { } /// \brief Hook called whenever a macro \#undef is seen. /// /// MD is released immediately following this callback. virtual void MacroUndefined(const Token &MacroNameTok, const MacroDirective *MD) { } /// \brief Hook called whenever the 'defined' operator is seen. /// \param MD The MacroDirective if the name was a macro, null otherwise. virtual void Defined(const Token &MacroNameTok, const MacroDirective *MD, SourceRange Range) { } /// \brief Hook called when a source range is skipped. /// \param Range The SourceRange that was skipped. The range begins at the /// \#if/\#else directive and ends after the \#endif/\#else directive. virtual void SourceRangeSkipped(SourceRange Range) { } /* enum ConditionValueKind { CVK_NotEvaluated, CVK_False, CVK_True }; */ /// \brief Hook called whenever an \#if is seen. /// \param Loc the source location of the directive. /// \param ConditionRange The SourceRange of the expression being tested. /// \param ConditionValue The evaluated value of the condition. /// // FIXME: better to pass in a list (or tree!) of Tokens. virtual void If(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue) { } /// \brief Hook called whenever an \#elif is seen. /// \param Loc the source location of the directive. /// \param ConditionRange The SourceRange of the expression being tested. /// \param ConditionValue The evaluated value of the condition. /// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive. // FIXME: better to pass in a list (or tree!) of Tokens. virtual void Elif(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue, SourceLocation IfLoc) { } /// \brief Hook called whenever an \#ifdef is seen. /// \param Loc the source location of the directive. /// \param MacroNameTok Information on the token being tested. /// \param MD The MacroDirective if the name was a macro, null otherwise. virtual void Ifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDirective *MD) { } /// \brief Hook called whenever an \#ifndef is seen. /// \param Loc the source location of the directive. /// \param MacroNameTok Information on the token being tested. /// \param MD The MacroDirective if the name was a macro, null otherwise. virtual void Ifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDirective *MD) { } /// \brief Hook called whenever an \#else is seen. /// \param Loc the source location of the directive. /// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive. virtual void Else(SourceLocation Loc, SourceLocation IfLoc) { } /// \brief Hook called whenever an \#endif is seen. /// \param Loc the source location of the directive. /// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive. virtual void Endif(SourceLocation Loc, SourceLocation IfLoc) { } clang::CompilerInstance& compiler_; const clang::Preprocessor& preprocessor_; clang::SourceManager& sourceManager_; int indent_ = 0; std::set<string> seen_files_; std::set<string> reenter_files_; }; } // namespace indexer class PreprocessAction : public clang::PreprocessOnlyAction { protected: void ExecuteAction() override { auto& compiler = getCompilerInstance(); auto* pp = new indexer::IncludePPCallbacks(compiler); compiler.getPreprocessor().addPPCallbacks(pp); clang::PreprocessOnlyAction::ExecuteAction(); } }; int main(int argc, char* argv[]) { std::vector<std::string> commands; for (int i = 0; i < argc; ++i) commands.push_back(argv[i]); commands.push_back("-fno-spell-checking"); llvm::IntrusiveRefCntPtr<clang::FileManager> files( new clang::FileManager(clang::FileSystemOptions())); clang::tooling::ToolInvocation tool(commands, new PreprocessAction, files.get()); bool succeed = tool.run(); return succeed ? 0 : -1; }
33.128788
91
0.644123
[ "vector" ]
fe2d162a5ae42ba83d5def6d6d7bd950ec13ec89
3,908
cpp
C++
AliceEngine/ALC/Content/Texture.cpp
ARAMODODRAGON/Project-Alice
49d3189ba065911c8495cfb04761a2050d3a0702
[ "MIT" ]
null
null
null
AliceEngine/ALC/Content/Texture.cpp
ARAMODODRAGON/Project-Alice
49d3189ba065911c8495cfb04761a2050d3a0702
[ "MIT" ]
null
null
null
AliceEngine/ALC/Content/Texture.cpp
ARAMODODRAGON/Project-Alice
49d3189ba065911c8495cfb04761a2050d3a0702
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2021 Domara Shlimon * * 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 "Texture.hpp" #include <glew.h> #define STBI_NO_GIF // we dont want any gif loading #define STB_IMAGE_IMPLEMENTATION #include "detail\stb_image.h" namespace ALC { Texture::Texture() : m_textureID(0), m_textureSize(0) { } Texture::Texture(std::nullptr_t) : Texture() { } Texture::Texture(const uint32 textureID, const uvec2& textureSize) : m_textureID(textureID), m_textureSize(textureSize) { } bool Texture::IsValid() const { return m_textureID != 0; } Texture::operator uint32() const { return m_textureID; } uint32 Texture::GetID() const { return m_textureID; } uvec2 Texture::GetSize() const { return m_textureSize; } rect Texture::GetBounds() const { return rect(vec2(0.0f), m_textureSize); } rect Texture::GetCenteredBounds() const { return rect(-vec2(m_textureSize) * 0.5f, vec2(m_textureSize) * 0.5f); } bool Texture::operator==(const Texture& other) const { return m_textureID == other.m_textureID; } bool Texture::operator!=(const Texture& other) const { return m_textureID != other.m_textureID; } Texture Texture::Load(const string& path) { // load the texture data int width, height, channels; stbi_uc* pixels = stbi_load(path.c_str(), &width, &height, &channels, STBI_rgb_alpha); // failed to load if (pixels == nullptr) { ALC_DEBUG_ERROR("Failed to load file: " + path); return nullptr; } // create texture ID uint32 textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); //uint32 mode = 0; // set the texture mode //if (channels == STBI_rgb_alpha) // mode = GL_RGBA; //else if (channels == STBI_rgb) // mode = GL_RGB; //else if (channels == STBI_grey_alpha) // mode = GL_RG; //else if (channels == STBI_grey) // mode = GL_R; //// invalid? dunno if this really will do anything //else { // ALC_DEBUG_ERROR("Invalid image channel mode when loading " + path); // stbi_image_free(pixels); // return nullptr; //} // load in and then free the texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); stbi_image_free(pixels); // Wrapping and filtering options glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // unbind glBindTexture(GL_TEXTURE_2D, 0); // create the texture object and then return Texture texture; texture.m_textureID = textureID; texture.m_textureSize = uvec2(width, height); return texture; } void Texture::Delete(const Texture& texture) { // delete the texture glDeleteTextures(1, &texture.m_textureID); } }
30.061538
95
0.729017
[ "object" ]
fe35dcb718dc7e4b4a7e5b4096247d48882dacc6
8,514
cc
C++
tensorflow/compiler/xla/service/gpu/ir_emission_utils.cc
salvatoretrimarchi/tensorflow
e089567660d465f486a8244431d9ceaa6f70c5a6
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/xla/service/gpu/ir_emission_utils.cc
salvatoretrimarchi/tensorflow
e089567660d465f486a8244431d9ceaa6f70c5a6
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/xla/service/gpu/ir_emission_utils.cc
salvatoretrimarchi/tensorflow
e089567660d465f486a8244431d9ceaa6f70c5a6
[ "Apache-2.0" ]
1
2021-06-04T17:13:46.000Z
2021-06-04T17:13:46.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include <algorithm> #include <vector> #include "external/llvm/include/llvm/IR/Module.h" #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/window_util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/protobuf.h" namespace xla { namespace gpu { namespace { // Return whether the given shape is a matrix with no padding. bool IsRank2WithNoPadding(const Shape& shape) { return ShapeUtil::Rank(shape) == 2 && !LayoutUtil::IsPadded(shape); } // In a gemm operation where output = lhs * rhs, check whether the given shapes // are valid for the operation. bool AreValidGemmShapes(const Shape& lhs_shape, const Shape& rhs_shape, const Shape& output_shape) { // The inputs and the output must // 1) be matrices with no padding and a non-zero number of elements, // 2) have an allowed element type. bool type_is_allowed = (output_shape.element_type() == F32 || output_shape.element_type() == F64); return type_is_allowed && IsRank2WithNoPadding(lhs_shape) && IsRank2WithNoPadding(rhs_shape) && IsRank2WithNoPadding(output_shape) && !ShapeUtil::HasZeroElements(lhs_shape) && !ShapeUtil::HasZeroElements(rhs_shape); } } // namespace bool ImplementedAsGemm(const HloInstruction& hlo) { // We can only do this if the HLO is unnested. if (hlo.parent() != hlo.GetModule()->entry_computation()) { return false; } // For certain types of Dot, we can call pre-canned BLAS gemm. if (hlo.opcode() == HloOpcode::kDot) { const Shape& lhs_shape = hlo.operand(0)->shape(); const Shape& rhs_shape = hlo.operand(1)->shape(); // If gemm can accept the operand shapes, use it rather than a custom // kernel. if (AreValidGemmShapes(lhs_shape, rhs_shape, hlo.shape())) { // The size of the reduction dimension should match. The shape inference // guarantees this invariant, so the check here is for programming // errors. CHECK_EQ(lhs_shape.dimensions(1), rhs_shape.dimensions(0)); return true; } } if (hlo.opcode() == HloOpcode::kFusion && hlo.fusion_kind() == HloInstruction::FusionKind::kTransposeDot && hlo.fused_expression_root()->opcode() == HloOpcode::kDot) { return true; } return false; } bool ImplementedAsDnnConvolution(const HloInstruction& hlo) { // We can only do this if the HLO is unnested. if (hlo.parent() != hlo.GetModule()->entry_computation()) { return false; } // Forward convolution. if (hlo.opcode() == HloOpcode::kConvolution) { const ConvolutionDimensionNumbers& dnums = hlo.convolution_dimension_numbers(); if (dnums.spatial_dimensions_size() > 3) { return false; } // CuDNN does not accept zero-element arguments if (ShapeUtil::HasZeroElements(hlo.operand(0)->shape()) || ShapeUtil::HasZeroElements(hlo.operand(1)->shape())) { return false; } return true; } // Backward convolution. if (hlo.opcode() == HloOpcode::kFusion && (hlo.fusion_kind() == HloInstruction::FusionKind::kConvBackwardFilter || hlo.fusion_kind() == HloInstruction::FusionKind::kConvBackwardInput)) { return true; } return false; } bool ImplementedAsLibraryCall(const HloInstruction& hlo) { return ImplementedAsGemm(hlo) || ImplementedAsDnnConvolution(hlo); } bool IsReductionToVector(const HloInstruction& reduce) { if (HloOpcode::kReduce != reduce.opcode()) { return false; } const HloInstruction* input = reduce.operand(0); std::vector<int64> dims_to_keep; for (int64 dim = 0; dim < input->shape().dimensions().size(); ++dim) { if (!std::count(reduce.dimensions().begin(), reduce.dimensions().end(), dim)) { dims_to_keep.push_back(dim); } } return LayoutUtil::AreDimensionsConsecutive(input->shape().layout(), dims_to_keep) && ShapeUtil::Equal(reduce.shape(), ShapeUtil::FilterDimensions( [&dims_to_keep](int64 dim) { return std::count( dims_to_keep.begin(), dims_to_keep.end(), dim); }, input->shape())); } llvm::Value* EmitDeviceFunctionCall( const string& callee_name, tensorflow::gtl::ArraySlice<llvm::Value*> operands, tensorflow::gtl::ArraySlice<PrimitiveType> input_types, PrimitiveType output_type, tensorflow::gtl::ArraySlice<llvm::Attribute::AttrKind> attributes, llvm::IRBuilder<>* builder) { std::vector<llvm::Type*> ir_input_types; for (PrimitiveType input_type : input_types) { ir_input_types.push_back( llvm_ir::PrimitiveTypeToIrType(input_type, builder)); } llvm::FunctionType* callee_type = llvm::FunctionType::get( llvm_ir::PrimitiveTypeToIrType(output_type, builder), // The return type. ir_input_types, // The parameter types. false); // No variadic arguments. // Declares the callee if it is not declared already. llvm::Function* callee = llvm::cast<llvm::Function>( builder->GetInsertBlock()->getModule()->getOrInsertFunction( llvm_ir::AsStringRef(callee_name), callee_type)); for (auto attribute : attributes) { callee->addFnAttr(attribute); } return builder->CreateCall(callee, llvm_ir::AsArrayRef(operands)); } llvm::Value* EmitShuffleDown(llvm::Value* value, llvm::Value* offset, llvm::IRBuilder<>* builder) { int bit_width = value->getType()->getPrimitiveSizeInBits(); // Special case for efficiency if (value->getType()->isFloatTy() && bit_width == 32) { return EmitDeviceFunctionCall( "amdgcn.shfl.down.f32", {value, offset, builder->getInt32(kWarpSize - 1)}, {F32, S32, S32}, F32, {}, builder); } // We must split values wider than 32 bits as the "shfl" instruction operates // on 32-bit values. int num_segments = CeilOfRatio(bit_width, 32); llvm::Value* x = builder->CreateBitCast( builder->CreateZExt( builder->CreateBitCast(value, builder->getIntNTy(bit_width)), builder->getIntNTy(32 * num_segments)), llvm::VectorType::get(builder->getInt32Ty(), num_segments)); for (int i = 0; i < num_segments; ++i) { x = builder->CreateInsertElement( x, EmitDeviceFunctionCall("amdgcn.shfl.down.f32", {builder->CreateExtractElement(x, i), offset, builder->getInt32(kWarpSize - 1)}, {F32, S32, S32}, F32, {}, builder), i); } return builder->CreateBitCast( builder->CreateTrunc( builder->CreateBitCast(x, builder->getIntNTy(32 * num_segments)), builder->getIntNTy(bit_width)), value->getType()); } const HloInstruction* LatestNonGteAncestor(const HloInstruction* hlo) { while (hlo->opcode() == HloOpcode::kGetTupleElement) { hlo = hlo->operand(0); } return hlo; } } // namespace gpu } // namespace xla
37.342105
80
0.644938
[ "shape", "vector" ]
fe36be8d30aa77e7b7c1f9b456eec133660a9359
3,672
cpp
C++
tc 160+/TheProduct.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/TheProduct.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/TheProduct.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> using namespace std; vector<int> A; int n; int D; int dummy = 51; const long long INF = 123456789012345678LL; long long dp2[50][52][11]; bool done[50][52][11], done2[50][52][11]; long long go(int, int, int); long long go2(int p, int last, int k) { // min if (k == 0) { return 1; } if (p==n || last!=dummy && p-last>D) { return INF; } long long &ret = dp2[p][last][k]; if (done2[p][last][k]) { return ret; } done2[p][last][k] = 1; ret = INF; long long t = go2(p+1, last, k); if (t < INF) { ret = t; } t = (A[p]>=0 ? go2(p+1, p, k-1) : go(p+1, p, k-1)); if (t<INF && (ret==INF || A[p]*t<ret)) { ret = A[p]*t; } return ret; } long long dp[50][52][11]; long long go(int p, int last, int k) { // max if (k == 0) { return 1; } if (p==n || last!=dummy && p-last>D) { return INF; } long long &ret = dp[p][last][k]; if (done[p][last][k]) { return ret; } done[p][last][k] = 1; ret = INF; long long t = go(p+1, last, k); if (t < INF) { ret = t; } t = (A[p]>=0 ? go(p+1, p, k-1) : go2(p+1, p, k-1)); if (t<INF && (ret==INF || A[p]*t>ret)) { ret = A[p]*t; } return ret; } class TheProduct { public: long long maxProduct(vector <int> numbers, int k, int maxDist) { A = numbers; n = A.size(); D = maxDist; memset(done, 0, sizeof done); memset(done2, 0, sizeof done2); return go(0, dummy, k); } // 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(); } 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 long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {7, 4, 7}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 1; long long Arg3 = 28LL; verify_case(0, Arg3, maxProduct(Arg0, Arg1, Arg2)); } void test_case_1() { int Arr0[] = {7, 4, 7}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 50; long long Arg3 = 49LL; verify_case(1, Arg3, maxProduct(Arg0, Arg1, Arg2)); } void test_case_2() { int Arr0[] = {-3, -5, -8, -9, -1, -2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; int Arg2 = 3; long long Arg3 = -10LL; verify_case(2, Arg3, maxProduct(Arg0, Arg1, Arg2)); } void test_case_3() { int Arr0[] = {3, 0, -2, 10, 0, 0, 3, -8, 0, 2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 2; long long Arg3 = 0LL; verify_case(3, Arg3, maxProduct(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { TheProduct ___test; ___test.run_test(-1); } // END CUT HERE
34
321
0.522059
[ "vector" ]
fe3aaf3c622c68659166735afdb18a9dc54447c1
5,383
cc
C++
bindings/pydrake/common/test/cpp_template_pybind_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
bindings/pydrake/common/test/cpp_template_pybind_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
bindings/pydrake/common/test/cpp_template_pybind_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
#include "drake/bindings/pydrake/common/cpp_template_pybind.h" // @file // Tests the public interfaces in `cpp_template.py` and // `cpp_template_pybind.h`. #include <string> #include <utility> #include <vector> #include "pybind11/embed.h" #include "pybind11/eval.h" #include "pybind11/pybind11.h" #include <gtest/gtest.h> #include "drake/bindings/pydrake/test/test_util_pybind.h" #include "drake/common/nice_type_name.h" #include "drake/common/test_utilities/expect_throws_message.h" using std::string; using std::vector; namespace drake { namespace pydrake { namespace { using test::SynchronizeGlobalsForPython3; template <typename... Ts> struct SimpleTemplate { vector<string> GetNames() { return {NiceTypeName::Get<Ts>()...}; } }; template <typename... Ts> auto BindSimpleTemplate(py::module m) { using Class = SimpleTemplate<Ts...>; py::class_<Class> py_class(m, TemporaryClassName<Class>().c_str()); py_class // BR .def(py::init<>()) .def("GetNames", &Class::GetNames); AddTemplateClass(m, "SimpleTemplate", py_class, GetPyParam<Ts...>()); return py_class; } template <typename T> void CheckValue(const string& expr, const T& expected) { EXPECT_EQ(py::eval(expr).cast<T>(), expected); } GTEST_TEST(CppTemplateTest, TemplateClass) { py::module m = py::module::create_extension_module("__main__", "", new PyModuleDef()); auto cls_1 = BindSimpleTemplate<int>(m); m.attr("DefaultInst") = cls_1; auto cls_2 = BindSimpleTemplate<int, double>(m); const vector<string> expected_1 = {"int"}; const vector<string> expected_2 = {"int", "double"}; SynchronizeGlobalsForPython3(m); CheckValue("DefaultInst().GetNames()", expected_1); CheckValue("SimpleTemplate[int]().GetNames()", expected_1); CheckValue("SimpleTemplate[int, float]().GetNames()", expected_2); m.def("simple_func", [](const SimpleTemplate<int>&) {}); SynchronizeGlobalsForPython3(m); // Check error message if a function is called with the incorrect arguments. // N.B. We use `[^\0]` because C++ regex does not have an equivalent of // Python re's DOTALL flag. `[\s\S]` *should* work, but Apple LLVM 10.0.0 // does not work with it. DRAKE_EXPECT_THROWS_MESSAGE(py::eval("simple_func('incorrect value')"), std::runtime_error, R"([^\0]*incompatible function arguments[^\0]*\(arg0: __main__\.SimpleTemplate\[int\]\)[^\0]*)"); // NOLINT // Add dummy constructors to check __call__ pseudo-deduction. cls_1.def(py::init([](int) { return SimpleTemplate<int>(); })); cls_2.def(py::init([](double) { return SimpleTemplate<int, double>(); })); // int - infer first (cls_1). CheckValue("SimpleTemplate(0).GetNames()", expected_1); // double - infer second (cls_2). CheckValue("SimpleTemplate(0.).GetNames()", expected_2); } template <typename... Ts> vector<string> SimpleFunction() { return {NiceTypeName::Get<Ts>()...}; } GTEST_TEST(CppTemplateTest, TemplateFunction) { py::module m = py::module::create_extension_module("__main__", "", new PyModuleDef()); AddTemplateFunction(m, "SimpleFunction", // BR &SimpleFunction<int>, GetPyParam<int>()); AddTemplateFunction(m, "SimpleFunction", // BR &SimpleFunction<int, double>, GetPyParam<int, double>()); const vector<string> expected_1 = {"int"}; const vector<string> expected_2 = {"int", "double"}; SynchronizeGlobalsForPython3(m); CheckValue("SimpleFunction[int]()", expected_1); CheckValue("SimpleFunction[int, float]()", expected_2); } std::string Callee(int) { return "int"; } std::string Callee(double) { return "double"; } GTEST_TEST(CppTemplateTest, Call) { py::module m = py::module::create_extension_module("__main__", "", new PyModuleDef()); AddTemplateFunction( m, "Callee", py::overload_cast<int>(&Callee), GetPyParam<int>()); AddTemplateFunction( m, "Callee", py::overload_cast<double>(&Callee), GetPyParam<double>()); const std::string expected_1 = "int"; const std::string expected_2 = "double"; SynchronizeGlobalsForPython3(m); CheckValue("Callee(0)", expected_1); CheckValue("Callee(0.)", expected_2); } struct SimpleType { template <typename... Ts> vector<string> SimpleMethod() { return {NiceTypeName::Get<Ts>()...}; } }; GTEST_TEST(CppTemplateTest, TemplateMethod) { py::module m = py::module::create_extension_module("__main__", "", new PyModuleDef()); py::class_<SimpleType> py_class(m, "SimpleType"); py_class // BR .def(py::init<>()); AddTemplateMethod(py_class, "SimpleMethod", &SimpleType::SimpleMethod<int>, GetPyParam<int>()); AddTemplateMethod(py_class, "SimpleMethod", &SimpleType::SimpleMethod<int, double>, GetPyParam<int, double>()); const vector<string> expected_1 = {"int"}; const vector<string> expected_2 = {"int", "double"}; SynchronizeGlobalsForPython3(m); CheckValue("SimpleType().SimpleMethod[int]()", expected_1); CheckValue("SimpleType().SimpleMethod[int, float]()", expected_2); } int main(int argc, char** argv) { // Reconstructing `scoped_interpreter` multiple times (e.g. via `SetUp()`) // while *also* importing `numpy` wreaks havoc. py::scoped_interpreter guard; ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } } // namespace } // namespace pydrake } // namespace drake int main(int argc, char** argv) { return drake::pydrake::main(argc, argv); }
31.479532
114
0.692179
[ "vector" ]
fe3cc4e8b5fdaa47f7bfe172c375f61ad7c60c23
18,496
cc
C++
src/interpreter/Interpreter.cc
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
1
2020-01-06T09:43:56.000Z
2020-01-06T09:43:56.000Z
src/interpreter/Interpreter.cc
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
src/interpreter/Interpreter.cc
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
#include <array> #include <fmt/format.h> #include <string_view> #include <vector> #include "Constants.hh" #include "CTypeWrapper.hh" #include "Interpreter.hh" #include "OPCode.hh" #include "builtin/BuiltIn.hh" #include "dynlib/DynLibLoader.hh" #include "dynlib/DynLib.hh" #include "fmt/core.h" #include "ir/QuadCollection.hh" #include "types/CType.hh" void runtime_error(const std::string& message) { fmt::print("{}\n", message); exit(EXIT_FAILURE); } Interpreter::Interpreter(const QuadCollection& quads, StringTable* string_table, bool verbose) : m_quads { quads }, m_string_table { string_table }, m_registers(std::vector<Operand>(quads.register_count)), m_verbose { verbose } {} void Interpreter::interpret() { m_stack_frames.push(StackFrame { 0, nullptr }); interpret_function(m_quads.main_function_id); } void Interpreter::interpret_function(unsigned function_id) { if (m_verbose) { fmt::print("Interpreting function with id {}\n", function_id); } current_frame()->set_program_counter( m_quads.function_to_quad.at(function_id)); while (true) { const Quad& quad = m_quads.quads[current_frame()->program_counter()]; // fmt::print("Interpreting quad: {}\n", quad.to_string()); switch (quad.opcode()) { case OPCode::ADD: add(quad); break; case OPCode::SUB: sub(quad); break; case OPCode::MULT: mult(quad); break; case OPCode::DIV: div(quad); break; case OPCode::CMP_EQ: cmp_eq(quad); break; case OPCode::CMP_GT: cmp_gt(quad); break; case OPCode::CMP_LT: cmp_lt(quad); break; case OPCode::CMP_GTEQ: cmp_gteq(quad); break; case OPCode::CMP_LTEQ: cmp_lteq(quad); break; case OPCode::CMP_NOTEQ: cmp_noteq(quad); break; case OPCode::JMP: jmp(quad); break; case OPCode::JMP_Z: jmp_z(quad); break; case OPCode::JMP_NZ: jmp_nz(quad); break; case OPCode::PUSH_ARG: push_arg(quad); break; case OPCode::POP_ARG: pop_arg(quad); break; case OPCode::SAVE: save(quad); break; case OPCode::RESTORE: restore(quad); break; case OPCode::CALL: call(quad); break; case OPCode::CALL_C: call_c(quad); break; case OPCode::SET_RET_TYPE: set_ret_type(quad); break; case OPCode::RET: ret(quad); break; case OPCode::MOVE: move(quad); break; case OPCode::INDEX_MOVE: index_move(quad); break; case OPCode::INDEX_ASSIGN: index_assign(quad); break; case OPCode::AND: interpret_and(quad); break; case OPCode::OR: interpret_or(quad); break; default: ASSERT_NOT_REACHED_MSG( fmt::format("Invalid OPCode: {}", opcode_to_string(quad.opcode())) .c_str()); } if (current_frame()->jump_performed()) { current_frame()->set_jump_performed(false); } else { current_frame()->increment_program_counter(); } } } Operand Interpreter::resolve_register(Register reg) const { return m_registers[reg.index()]; } void Interpreter::set_register(Register reg, Operand operand) { m_registers[reg.index()] = std::move(operand); } unsigned Interpreter::resolve_label(const QuadDest& dest) const { return dest.as_label().value; } ValueOperand Interpreter::resolve_source(const QuadSource& source) const { // TODO: Support functions ASSERT(!source.is_function()); if (source.is_value()) { return source.as_value(); } if (source.is_register()) { return resolve_register(source.as_register()).as_value(); } ASSERT_NOT_REACHED_MSG( fmt::format("Invalid QuadSource type: {}", source.to_string()).c_str()); } template <class BinaryOperator> struct BinOpVisitor { template <typename T, typename U> ValueOperand operator()(T, U) { ASSERT_NOT_REACHED(); } ValueOperand operator()(StringOperand, StringOperand) { ASSERT_NOT_REACHED(); } ValueOperand operator()(VectorOperand, VectorOperand) { ASSERT_NOT_REACHED(); } template <typename T> ValueOperand operator()(T a, T b) { return ValueOperand { T { BinaryOperator {}(a, b) } }; } }; struct BinOpPlusVisitor { BinOpPlusVisitor(StringTable* string_table) : string_table(string_table) {} StringTable* string_table; template <typename T, typename U> ValueOperand operator()(T, U) { ASSERT_NOT_REACHED(); } ValueOperand operator()(StringOperand a, StringOperand b) { std::string result = *a.resolve() + *b.resolve(); StringTable::Entry entry = string_table->add(std::move(result)); return ValueOperand { StringOperand { entry.key, string_table } }; } ValueOperand operator()(VectorOperand, VectorOperand) { ASSERT_NOT_REACHED(); } template <typename T> ValueOperand operator()(T a, T b) { return ValueOperand { T { a + b } }; } }; template <class Operator> void binop_helper(Interpreter* interpreter, const Quad& quad) { ValueOperand lhs = interpreter->resolve_source(quad.src_a()); ValueOperand rhs = interpreter->resolve_source(quad.src_b()); Operand result = Operand(std::visit(BinOpVisitor<Operator> {}, lhs.value, rhs.value)); interpreter->set_register(quad.dest().as_register(), result); } void plus_helper(Interpreter* interpreter, const Quad& quad, StringTable* string_table) { ValueOperand lhs = interpreter->resolve_source(quad.src_a()); ValueOperand rhs = interpreter->resolve_source(quad.src_b()); Operand result = Operand(std::visit(BinOpPlusVisitor {string_table}, lhs.value, rhs.value)); interpreter->set_register(quad.dest().as_register(), result); } void Interpreter::add(const Quad& quad) { ASSERT(quad.opcode() == OPCode::ADD); plus_helper(this, quad, m_string_table); } void Interpreter::sub(const Quad& quad) { ASSERT(quad.opcode() == OPCode::SUB); binop_helper<std::minus<>>(this, quad); } void Interpreter::mult(const Quad& quad) { ASSERT(quad.opcode() == OPCode::MULT); binop_helper<std::multiplies<>>(this, quad); } void Interpreter::div(const Quad& quad) { ASSERT(quad.opcode() == OPCode::DIV); binop_helper<std::divides<>>(this, quad); } template <class Operator> struct CmpVisitor { CmpVisitor(StringTable* string_table) : string_table(string_table) {} StringTable* string_table; template <typename T, typename U> bool operator()(T, U) { ASSERT_NOT_REACHED(); } template <typename T> bool operator()(T a, T b) { return Operator {}(a.value, b.value); } template<> bool operator()(StringOperand a, StringOperand b) { return Operator {}(*a.resolve(), *b.resolve()); } }; template <class Operator> void cmp_helper(Interpreter* interpreter, StringTable* string_table, const Quad& quad) { ValueOperand lhs = interpreter->resolve_source(quad.src_a()); ValueOperand rhs = interpreter->resolve_source(quad.src_b()); bool result = std::visit(CmpVisitor<Operator> { string_table }, lhs.value, rhs.value); Operand ret = Operand { ValueOperand { IntOperand { result } } }; interpreter->set_register(quad.dest().as_register(), ret); } void Interpreter::cmp_eq(const Quad& quad) { cmp_helper<std::equal_to<>>(this, m_string_table, quad); } void Interpreter::cmp_gt(const Quad& quad) { cmp_helper<std::greater<>>(this, m_string_table, quad); } void Interpreter::cmp_lt(const Quad& quad) { cmp_helper<std::less<>>(this, m_string_table, quad); } void Interpreter::cmp_gteq(const Quad& quad) { cmp_helper<std::greater_equal<>>(this, m_string_table, quad); } void Interpreter::cmp_lteq(const Quad& quad) { cmp_helper<std::less_equal<>>(this, m_string_table, quad); } void Interpreter::cmp_noteq(const Quad& quad) { cmp_helper<std::not_equal_to<>>(this, m_string_table, quad); } void Interpreter::jmp(const Quad& quad) { unsigned label_id = resolve_label(quad.dest()); auto target_quad = m_quads.label_to_quad.find(label_id); ASSERT(target_quad != m_quads.label_to_quad.end()); current_frame()->set_program_counter(target_quad->second); current_frame()->set_jump_performed(true); } void Interpreter::jmp_z(const Quad& quad) { ValueOperand condition = resolve_source(quad.src_a()); if (condition.as_int() == 0) { jmp(quad); } } void Interpreter::jmp_nz(const Quad& quad) { ValueOperand condition = resolve_source(quad.src_a()); if (condition.as_int() != 0) { jmp(quad); } } void Interpreter::push_arg(const Quad& quad) { // TODO: Built-ins will break from this as they do not have parameter names ValueOperand value = resolve_source(quad.src_a()); m_arguments.push(ArgumentWrapper { value }); } void Interpreter::pop_arg(const Quad& quad) { ASSERT(!m_arguments.empty()); ArgumentWrapper argument = m_arguments.front(); m_arguments.pop(); set_register(quad.dest().as_register(), Operand { argument.value }); } void Interpreter::save(const Quad& quad) { int start_idx = quad.src_a().as_register().index(); int end_index = quad.src_b().as_register().index(); for (int i = start_idx; i <= end_index; ++i) { m_stack.push(m_registers.at(i)); } } void Interpreter::restore(const Quad& quad) { int start_idx = quad.src_a().as_register().index(); int end_index = quad.src_b().as_register().index(); for (int i = end_index; i >= start_idx; --i) { set_register(Register(i), m_stack.top()); m_stack.pop(); } } void Interpreter::call(const Quad& quad) { ASSERT(quad.opcode() == OPCode::CALL); FunctionOperand func = quad.src_a().as_function(); if (BuiltIn::is_builtin(func)) { std::vector<ValueOperand> args {}; while (!m_arguments.empty()) { args.push_back(m_arguments.front().value); m_arguments.pop(); } ValueOperand ret = BuiltIn::call_builtin_function(func, args); set_register(quad.dest().as_register(), Operand { ret }); return; } enter_new_frame(); // Program counter will be incremented in interpret function current_frame()->set_program_counter(m_quads.function_to_quad.at(func) - 1); } void Interpreter::call_c(const Quad& quad) { ASSERT(quad.opcode() == OPCode::CALL_C); std::vector<ValueOperand> args {}; while (!m_arguments.empty()) { args.push_back(m_arguments.front().value); m_arguments.pop(); } StringTable::Key lib = quad.src_a().as_value().as_string(); StringTable::Key func = quad.src_b().as_value().as_string(); std::optional<ValueOperand> return_value = call_c_func(lib, func, args, take_pending_type_id()); if (return_value.has_value()) { set_register(quad.dest().as_register(), Operand { return_value.value() }); } } void Interpreter::set_ret_type(const Quad& quad) { ASSERT(quad.opcode() == OPCode::SET_RET_TYPE); set_pending_type_id(quad.src_a().as_value().as_int()); } void Interpreter::ret(const Quad& quad) { auto source = quad.src_a(); if (current_frame()->is_main_frame()) { ValueOperand value = resolve_source(QuadSource { Register(0) }); exit(value.as_int()); } if (current_frame()->return_variable()) { exit_frame(); set_register(Register(0), Operand { resolve_source(source) }); } else { exit_frame(); } } void Interpreter::move(const Quad& quad) { ASSERT(quad.opcode() == OPCode::MOVE); ValueOperand source = resolve_source(quad.src_a()); if (source.is_vector()) { source = ValueOperand{ source.as_vector().copy() }; } set_register(quad.dest().as_register(), Operand { source }); } void bounds_check(StringOperand s, int index) { if (index < 0) { runtime_error( fmt::format("Cannot index string with negative index [{}]", index)); } StringTable::value_type_t value = s.resolve(); if (index >= static_cast<int>(value->size())) { runtime_error( fmt::format("Index out-of-bounds error. Error indexing string of " "size {} with index {}", value->size(), index)); } } void bounds_check(VectorOperand::value_type_t vec, int index) { if (index < 0) { runtime_error( fmt::format("Cannot index vector with negative index [{}]", index)); } if (index >= static_cast<int>(vec->size())) { runtime_error( fmt::format("Index out-of-bounds error. Error indexing vector of " "size {} with index {}", vec->size(), index)); } } void Interpreter::index_move(const Quad& quad) { int index = resolve_source(quad.src_b()).as_int(); ValueOperand operand = resolve_source(quad.src_a()); ValueOperand value; if (operand.is_string()) { StringOperand indexed = operand.as_string(); bounds_check(indexed, index); const std::string& resolved = *indexed.resolve(); char value_at_index = resolved[index]; StringTable::Entry entry = m_string_table->add(value_at_index); value = ValueOperand { StringOperand { entry.key, m_string_table } }; } else if (operand.is_vector()) { VectorOperand::value_type_t indexed = operand.as_vector().value; bounds_check(indexed, index); value = indexed->at(index); } else { ASSERT_NOT_REACHED(); } set_register(quad.dest().as_register(), Operand { value }); } void Interpreter::index_assign(const Quad& quad) { int index = resolve_source(quad.src_a()).as_int(); VectorOperand::value_type_t indexed = resolve_source(QuadSource { quad.dest().as_register() }).as_vector(); ValueOperand value = resolve_source(quad.src_b()); bounds_check(indexed, index); indexed->at(index) = value; } void Interpreter::interpret_and(const Quad& quad) { ValueOperand lhs = resolve_source(quad.src_a()); ValueOperand rhs = resolve_source(quad.src_b()); Operand result = Operand { ValueOperand { IntOperand { lhs.as_int() && rhs.as_int() } } }; set_register(quad.dest().as_register(), result); } void Interpreter::interpret_or(const Quad& quad) { ValueOperand lhs = resolve_source(quad.src_a()); ValueOperand rhs = resolve_source(quad.src_b()); Operand result = Operand { ValueOperand { IntOperand { lhs.as_int() || rhs.as_int() } } }; set_register(quad.dest().as_register(), result); } StackFrame* Interpreter::current_frame() { return &m_stack_frames.top(); } void Interpreter::enter_new_frame() { m_stack_frames.emplace(current_frame()->program_counter(), current_frame()); }; void Interpreter::exit_frame() { // fmt::print("exit_frame()\n"); m_stack_frames.pop(); } unsigned Interpreter::take_pending_type_id() { ASSERT(m_pending_return_type.has_value()); unsigned tmp = m_pending_return_type.value(); m_pending_return_type.reset(); return tmp; } void Interpreter::set_pending_type_id(unsigned value) { ASSERT(!m_pending_return_type.has_value()); m_pending_return_type = value; } std::optional<ValueOperand> Interpreter::call_c_func( StringTable::Key lib, StringTable::Key func, const std::vector<ValueOperand>& args, unsigned return_type_id) { Result<dynlib::DynamicLibrary*> loaded_lib_or_error = dynlib::load_lib(*m_string_table->get_at(lib)); if (loaded_lib_or_error.is_error()) { ASSERT_NOT_REACHED_MSG("Could not load expected library"); } dynlib::DynamicLibrary* loaded_lib = loaded_lib_or_error.get(); ASSERT(loaded_lib->has_symbol(*m_string_table->get_at(func))); dynlib::DynamicLibrary::Callable callable = loaded_lib->get_callable(*m_string_table->get_at(func)); std::vector<ptr_t<vm::CTypeWrapper>> wrapped_args; for (const ValueOperand& op : args) { wrapped_args.push_back(vm::CTypeWrapper::from(m_string_table, op)); } ctype::TypeInfo type_info = ctype::from_type_id(return_type_id); vm::CResultWrapper result_wrapper { type_info.c_type }; switch (wrapped_args.size()) { case 0: callable.call(); break; case 1: callable.call<1>(result_wrapper, wrapped_args); break; case 2: callable.call<2>(result_wrapper, wrapped_args); break; default: ASSERT_NOT_REACHED_MSG(fmt::format("Unsupported number of arguments passed to C function: {}", wrapped_args.size())); } switch (type_info.seal_type.primitive()) { case Primitive::VOID: { return {}; } case Primitive::INT: { unsigned long val = *(static_cast<unsigned long*>(result_wrapper.buffer())); return ValueOperand { IntOperand {val} }; } case Primitive::FLOAT: { double val = *(reinterpret_cast<double*>(result_wrapper.buffer())); return ValueOperand { RealOperand { val } }; } case Primitive::STRING: { std::string val = *(reinterpret_cast<char**>(result_wrapper.buffer())); StringTable::Entry entry = m_string_table->add(std::move(val)); return ValueOperand { StringOperand { entry.key, m_string_table } }; } default: ASSERT_NOT_REACHED(); } return {}; }
29.688604
129
0.615863
[ "vector" ]
fe40c297252e5756bd112ffcbf86671ecbab22b3
687
cpp
C++
Courses/100 - Algorithms on Strings/week2_BWT_suffix_arrays/bwtinverse/bwtinverse.cpp
aKhfagy/Data-Structures-and-Algorithms-Specialization
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
1
2021-01-25T09:56:15.000Z
2021-01-25T09:56:15.000Z
Courses/100 - Algorithms on Strings/week2_BWT_suffix_arrays/bwtinverse/bwtinverse.cpp
aKhfagy/data-structures-algorithms
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
null
null
null
Courses/100 - Algorithms on Strings/week2_BWT_suffix_arrays/bwtinverse/bwtinverse.cpp
aKhfagy/data-structures-algorithms
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <string> #include <vector> #include <utility> using std::cin; using std::cout; using std::endl; using std::string; using std::vector; using std::pair; using std::make_pair; string InverseBWT(const string& bwt) { string text = ""; vector<pair<char, int> > col(bwt.size()); for (int i = 0; i < bwt.size(); i++) col[i] = make_pair(bwt[i], i); sort(col.begin(), col.end()); pair<char, int> symbol = col[0]; for (int i = 0; i < bwt.size(); i++) { symbol = col[symbol.second]; text += symbol.first; } return text; } int main() { string bwt; cin >> bwt; cout << InverseBWT(bwt) << endl; return 0; }
16.756098
43
0.606987
[ "vector" ]
fe433a248a3a13619fb7009ae36655476492cb80
17,935
cc
C++
src/benchmark/etc_bench.cc
calvincaulfield/lib_calvin
cecf2d8b9cc7b6a4e7f269d0e94e0b80774fc30b
[ "Apache-2.0" ]
null
null
null
src/benchmark/etc_bench.cc
calvincaulfield/lib_calvin
cecf2d8b9cc7b6a4e7f269d0e94e0b80774fc30b
[ "Apache-2.0" ]
null
null
null
src/benchmark/etc_bench.cc
calvincaulfield/lib_calvin
cecf2d8b9cc7b6a4e7f269d0e94e0b80774fc30b
[ "Apache-2.0" ]
null
null
null
#include <vector> #include <string> #include <algorithm> #include <random> #include <unordered_set> #include "random.h" #include "etc_bench.h" #include "bench.h" #include "stopwatch.h" #include "intro_sort.h" #include "merge_sort.h" using namespace lib_calvin_benchmark::etc; void lib_calvin_benchmark::etc::etc_bench() { //memory_access_bench(); //linear_time_sorting_bench(); //sort_by_group_bench(); //following_link_bench(); n_nlogn_bench(); } void lib_calvin_benchmark::etc::memory_access_bench() { using namespace std; string category = "Etc."; string subCategory = "Instruction-level parallelism"; string title = "Iterating speed (minimum working set)"; string comment = ""; string unit = "M/s"; size_t benchOrder = 0; vector<string> testCases = { "1K", "10K", "100K", "1M", "10M" }; vector<size_t> testSizes = { 1000, 1000 * 10, 1000 * 100, 1000 * 1000, 1000 * 1000 * 10 }; vector<vector<double>> results; results.push_back(linked_list_access()); results.push_back(pointer_array_access()); lib_calvin_benchmark::save_bench(category, subCategory, title, comment, { {"linked list"}, {"array of pointers"} }, results, testCases, unit, benchOrder++); } void lib_calvin_benchmark::etc::linear_time_sorting_bench() { using namespace std; string category = "Etc."; string subCategory = "Algorithm complexity (+ overhead), cache efficiency, and instruction-level parallelism"; string title = "Sorting (final positions of elemements are known)"; string comment = ""; string unit = "M/s"; size_t benchOrder = 0; vector<string> testCases = { "1K", "10K", "100K", "1M", "10M" }; vector<size_t> testSizes = { 1000, 1000*10, 1000*100, 1000*1000, 1000*1000*10 }; vector<vector<double>> results; results.push_back(linear_method()); results.push_back(linear_method_inplace()); results.push_back(block_qsort()); lib_calvin_benchmark::save_bench(category, subCategory, title, comment, { { "Linear method using O(N) space" }, { "Linear method inplace" }, { "Block qsort" } }, results, testCases, unit, benchOrder++); } void lib_calvin_benchmark::etc::sort_by_group_bench() { using namespace std; string category = "Etc."; string subCategory = "Conditional branches"; string title = "Sorting into " + std::to_string(numGroups) + " groups, and sorting each group"; string comment = ""; string unit = "M/s"; size_t benchOrder = 0; vector<string> testCases = { "1K", "10K", "100K", "1M", "10M" }; vector<size_t> testSizes = { 1000, 1000 * 10, 1000 * 100, 1000 * 1000, 1000 * 1000 * 10 }; vector<vector<double>> results; results.push_back(one_pass_sorting()); results.push_back(two_pass_sorting()); lib_calvin_benchmark::save_bench(category, subCategory, title, comment, { { "One-pass sorting" },{ "Two-pass sorting" } }, results, testCases, unit, benchOrder++); } void lib_calvin_benchmark::etc::following_link_bench() { using namespace std; string category = "Etc."; string subCategory = "Conditional branches"; string title = "Iterating binary tree"; string comment = ""; string unit = "M/s"; size_t benchOrder = 0; vector<string> testCases = { "1K", "10K", "100K", "1M", "10M" }; vector<size_t> testSizes = { 1000, 1000 * 10, 1000 * 100, 1000 * 1000, 1000 * 1000 * 10 }; vector<vector<double>> results; results.push_back(null_pointer()); results.push_back(null_flag()); lib_calvin_benchmark::save_bench(category, subCategory, title, comment, { { "null pointer" }, { "null flag" } }, results, testCases, unit, benchOrder++); } void lib_calvin_benchmark::etc::n_nlogn_bench() { using namespace std; string category = "Etc."; string subCategory = "Algorithm complexity (+ overhead), cache efficiency, and instruction-level parallelism"; string title = "O(N) vs O(Nlog(N))"; string comment = ""; string unit = "M/s"; size_t benchOrder = 0; vector<string> testCases = { "1K", "10K", "100K", "1M", "10M" }; vector<size_t> testSizes = { 1000, 1000 * 10, 1000 * 100, 1000 * 1000, 1000 * 1000 * 10 }; vector<vector<double>> results; results.push_back(hashing()); results.push_back(build_tree()); results.push_back(sorting()); results.push_back(block_qsort_int()); lib_calvin_benchmark::save_bench(category, subCategory, title, comment, { { "std::unordered_set" }, { "std::set" }, { "std::sort" }, { "lib_calvin::block_qsort" } }, results, testCases, unit, benchOrder++); } std::vector<double> lib_calvin_benchmark::etc::linked_list_access() { std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; Node *elems = new Node[testSize]; for (size_t i = 0; i < testSize; i++) { elems[i].key_ = i; elems[i].data_[0] = 2 * i; elems[i].data_[1] = 3 * i; elems[i].data_[2] = 4 * i; elems[i].next_ = nullptr; } //std::shuffle(elems, elems + testSize, std::mt19937_64(0)); size_t primeNumber = 9973; size_t position = 0; for (size_t i = 0; i < testSize; i++) { size_t nextPosition = (position + primeNumber) % testSize; elems[position].next_ = &elems[nextPosition]; position = nextPosition; } for (size_t i = 0; i < testSize; i++) { if (elems[i].next_ == nullptr) { std::cout << "linked_list_access\n"; exit(0); } } double min = 1000000; size_t checksum = 0; Node *curNode = &elems[0]; for (size_t j = 0; j < numIter; j++) { lib_calvin::stopwatch watch; watch.start(); for (size_t i = 0; i < testSize; i++) { checksum += size_t(*curNode); curNode = curNode->next_; } watch.stop(); if (watch.read() < min) { min = watch.read(); } } delete[] elems; double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "Checksum: " << checksum << " speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::pointer_array_access() { std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; Node *elems = new Node[testSize]; for (size_t i = 0; i < testSize; i++) { elems[i].key_ = i; elems[i].data_[0] = 2 * i; elems[i].data_[1] = 3 * i; elems[i].data_[2] = 4 * i; elems[i].next_ = nullptr; } Node **pointerArray = new Node*[testSize]; for (size_t i = 0; i < testSize; i++) { pointerArray[i] = &elems[i]; } size_t checksum = 0; lib_calvin::stopwatch watch; double min = 1000000; for (size_t j = 0; j < numIter; j++) { std::shuffle(pointerArray, pointerArray + testSize, std::mt19937_64(0)); watch.start(); for (size_t i = 0; i < testSize; i++) { checksum += size_t(*pointerArray[i]); } watch.stop(); if (watch.read() < min) { min = watch.read(); } } delete[] elems; delete[] pointerArray; double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "Checksum: " << checksum << " speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::linear_method() { using namespace lib_calvin; stopwatch watch; std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; double min = 1000000; for (size_t j = 0; j < numIter; j++) { auto randomArray = getRandomNodeArray(testSize); watch.start(); auto copy = randomArray; for (auto node : randomArray) { size_t index = node.key_ / 10; copy[index] = node; } randomArray = copy; watch.stop(); if (watch.read() < min) { min = watch.read(); } } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "linear_method speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::linear_method_inplace() { using namespace lib_calvin; stopwatch watch; std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; double min = 1000000; for (size_t j = 0; j < numIter; j++) { auto inputArray = getRandomNodeArray(testSize); auto copy = inputArray; watch.start(); size_t start_index = 0; while (start_index < inputArray.size()) { auto node_to_insert = inputArray[start_index]; while (true) { size_t index_to_insert = node_to_insert.key_ / 10; auto temp = inputArray[index_to_insert]; inputArray[index_to_insert] = node_to_insert; node_to_insert = temp; if (index_to_insert == start_index) { // we got a cycle break; } } start_index++; while (true) { if (start_index == inputArray.size()) { break;; } else if (inputArray[start_index].key_ / 10 == start_index) { start_index++; } else { break; } } } watch.stop(); if (watch.read() < min) { min = watch.read(); } lib_calvin_sort::blockIntroSort(copy.begin(), copy.end()); if (inputArray != copy) { std::cout << "linear_method_inplace error\n"; exit(0); } } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "linear_method_inplace speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::block_qsort() { using namespace lib_calvin; stopwatch watch; std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; double min = 1000000; for (size_t j = 0; j < numIter; j++) { auto inputArray = getRandomNodeArray(testSize); watch.start(); lib_calvin_sort::blockIntroSort(inputArray.begin(), inputArray.end()); watch.stop(); if (watch.read() < min) { min = watch.read(); } } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "block_qsort speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::one_pass_sorting() { using namespace lib_calvin; stopwatch watch; std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; double min = 1000000; for (size_t j = 0; j < numIter; j++) { auto inputArray = getRandomNodeArray(testSize); watch.start(); lib_calvin_sort::blockIntroSort(inputArray.begin(), inputArray.end(), all_compare()); watch.stop(); if (watch.read() < min) { min = watch.read(); } } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "one_pass_sorting speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::two_pass_sorting() { using namespace lib_calvin; stopwatch watch; std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; double min = 1000000; for (size_t j = 0; j < numIter; j++) { auto inputArray = getRandomNodeArray(testSize); auto copy = inputArray; watch.start(); lib_calvin_sort::blockIntroSort(inputArray.begin(), inputArray.end(), key_compare()); lib_calvin_sort::mergeSort(inputArray.begin(), inputArray.end(), group_compare()); watch.stop(); if (watch.read() < min) { min = watch.read(); } lib_calvin_sort::blockIntroSort(copy.begin(), copy.end(), all_compare()); if (inputArray != copy) { std::cout << "two_pass_sorting error\n"; exit(0); } } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "two_pass_sorting speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::null_pointer() { std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; Node *null_node = new Node(); null_node->is_null = true; Node **chains = new Node *[testSize]; for (size_t i = 0; i < testSize; i++) { Node * node1 = new Node(); Node * node2 = new Node(); node1->next_ = node2; node2->next_ = nullptr; node1->is_null = false; node2->is_null = true; chains[i] = node1; } double min = 1000000; size_t checksum = 0; for (size_t j = 0; j < numIter; j++) { lib_calvin::stopwatch watch; watch.start(); size_t index = 0; for (size_t i = 0; i < testSize; i++) { auto curNode = chains[index]; while (curNode) { checksum += size_t(*curNode); curNode = curNode->next_; } index = (index + 9973) % testSize; } watch.stop(); if (watch.read() < min) { min = watch.read(); } } for (size_t i = 0; i < testSize; i++) { delete chains[i]->next_; delete chains[i]; } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "null_pointer Checksum: " << checksum << " speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::null_flag() { std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; Node **chains = new Node *[testSize]; for (size_t i = 0; i < testSize; i++) { Node * node1 = new Node(); Node * node2 = new Node(); node1->next_ = node2; node2->next_ = nullptr; node1->is_null = false; node2->is_null = true; chains[i] = node1; } double min = 1000000; size_t checksum = 0; for (size_t j = 0; j < numIter; j++) { lib_calvin::stopwatch watch; watch.start(); size_t index = 0; for (size_t i = 0; i < testSize; i++) { auto curNode = chains[index]; while (!curNode->is_null) { checksum += size_t(*curNode); curNode = curNode->next_; } index = (index + 9973) % testSize; } watch.stop(); if (watch.read() < min) { min = watch.read(); } } for (size_t i = 0; i < testSize; i++) { delete chains[i]->next_; delete chains[i]; } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "null flag Checksum: " << checksum << " speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::hashing() { using namespace lib_calvin; stopwatch watch; std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; double min = 1000000; for (size_t j = 0; j < numIter; j++) { auto inputArray = getRandomIntArray(testSize); std::unordered_set<size_t> hashSet; watch.start(); for (size_t i = 0; i < testSize; i++) { hashSet.insert(inputArray[i]); } watch.stop(); if (watch.read() < min) { min = watch.read(); } } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "hashing speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::build_tree() { using namespace lib_calvin; stopwatch watch; std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; double min = 1000000; for (size_t j = 0; j < numIter; j++) { auto inputArray = getRandomIntArray(testSize); std::set<size_t> treeSet; watch.start(); for (size_t i = 0; i < testSize; i++) { treeSet.insert(inputArray[i]); } watch.stop(); if (watch.read() < min) { min = watch.read(); } } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "tree speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::sorting() { using namespace lib_calvin; stopwatch watch; std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; double min = 1000000; for (size_t j = 0; j < numIter; j++) { auto inputArray = getRandomIntArray(testSize); auto copy = inputArray; watch.start(); std::sort(inputArray.begin(), inputArray.end()); watch.stop(); if (watch.read() < min) { min = watch.read(); } } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "tree speed: " << speed << "\n"; } return results; } std::vector<double> lib_calvin_benchmark::etc::block_qsort_int() { using namespace lib_calvin; stopwatch watch; std::vector<double> results; for (size_t i = 0; i < testSizes.size(); i++) { size_t testSize = testSizes[i]; size_t numIter = numIters[i]; double min = 1000000; for (size_t j = 0; j < numIter; j++) { auto inputArray = getRandomIntArray(testSize); auto copy = inputArray; watch.start(); lib_calvin_sort::blockIntroSort(inputArray.begin(), inputArray.end()); watch.stop(); if (watch.read() < min) { min = watch.read(); } } double speed = testSize / min / 1000 / 1000; results.push_back(speed); std::cout << "tree speed: " << speed << "\n"; } return results; } std::vector<size_t> lib_calvin_benchmark::etc::getRandomIntArray(size_t size) { using namespace lib_calvin; std::vector<size_t> test_vector(size); for (size_t i = 0; i < size; i++) { test_vector[i] = i; } std::shuffle(test_vector.begin(), test_vector.end(), std::mt19937(std::random_device()())); return test_vector; } std::vector<lib_calvin_benchmark::etc::Node> lib_calvin_benchmark::etc::getRandomNodeArray(size_t size) { using namespace lib_calvin; std::vector<Node> test_vector(size); lib_calvin::random_number_generator g; for (size_t i = 0; i < size; i++) { size_t random = g(); test_vector[i].key_ = i * 10; // multiply 10 to use it in linear_method test_vector[i].group_ = i % numGroups; } std::shuffle(test_vector.begin(), test_vector.end(), std::mt19937(std::random_device()())); return test_vector; }
25.992754
111
0.638528
[ "vector" ]
1cffbe397fa079bf648fc584a5313f0db9ddcf15
14,221
cc
C++
system.cc
yonsei-icsl/RelSim
33ff9009ca679d1fa6f23b53de188e5af3890f7d
[ "BSD-3-Clause" ]
null
null
null
system.cc
yonsei-icsl/RelSim
33ff9009ca679d1fa6f23b53de188e5af3890f7d
[ "BSD-3-Clause" ]
null
null
null
system.cc
yonsei-icsl/RelSim
33ff9009ca679d1fa6f23b53de188e5af3890f7d
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <vector> #include <thread> #include "system.h" #include "use.h" using namespace std; rel_system_t::rel_system_t() : target_mttf(0.0) { // Nothing to do } rel_system_t::~rel_system_t() { // Delete models for(size_t m = 0; m < models.size(); m++) { delete models[m]; } models.clear(); } // Disabled copy construction rel_system_t::rel_system_t(const rel_system_t &m_sys) { // Nothing to do } // Find the system component in the vector. rel_component_t* rel_system_t::get_component(string m_name) { rel_component_t *comp = 0; for(size_t c = 0; c < components.size(); c++) { if(components[c]->name == m_name) { comp = components[c]; break; } } return comp; } // Find the reliability model in the vector. rel_model_t* rel_system_t::get_model(std::string m_name) { rel_model_t *rel_model = 0; for(size_t m = 0; m < models.size(); m++) { if(rel_type_str[models[m]->type] == m_name) { rel_model = models[m]; break; } } return rel_model; } // Initialize the system. void rel_system_t::calibrate(void) { // Initialize component groups. for(size_t g = 0; groups.size(); g++) { groups[g].init(); } // Initialize component and model parameters. vector<rel_model_t*> r_model; for(size_t m = 0; m < components[0]->rel_models.size(); m++) { rel_model_t *copy = components[0]->rel_models[m]; r_model.push_back( copy->copy() ); } // Find min integer ratio among different processing units. // Express the area of each components as a ratio of min integer(grid block) // For example, "CPU(0.4), ACCEL(0.6)" updates to "CPU(2), ACCEL(3)" size_t com = (components[0]->area)*100; for(size_t c= 1; c < components.size(); c++) { if(com > components[c]->area*100) { com = gcd (com, components[c]->area*100); } else { com = gcd(components[c]->area*100, com); } } for(size_t c = 0 ; c < components.size(); c++) { components[c]->area = (components[c]->area)*100/com; } // Count how many actual components there need to be. size_t num_components = 0; size_t num_models = components[0]->rel_models.size(); size_t n_use_case = components[0]->target_conditions.size(); for(size_t c = 0; c < components.size(); c++) { num_components += components[c]->count*components[c]->area; } // Reserve the vector space. components.reserve(num_components); // Replicate components for the ones with count > 1. for(vector<rel_component_t*>::iterator r = components.begin(); r < components.end();) { rel_component_t *comp = *r; // Replicate the component. components.insert(r, (comp->area)*(comp->count) - 1, comp); r += (comp->area)*(comp->count); } double* guess = new double[iterations]; double expected_life = 0; srand((unsigned int)time(NULL)); default_random_engine generate; generate.seed(rand()); std::uniform_real_distribution<double> random(0.0, 1.0); double* target_guess = new double[num_components]; double* life_per_model = new double[components[0]->rel_models.size()]; double err_rate = 0.1; double* model_target = new double[num_models]; for(size_t m = 0; m < num_models; m++) { life_per_model[m] = target_mttf*num_models; model_target[m] = 1; } int* crit = new int[iterations]; double* time = new double[n_use_case]; for(size_t uc = 0; uc < n_use_case; uc++) { time[uc] = components[0]->target_conditions[uc].duty_cycle; } // Find approximate model MTTF for setting initial A with loose bound for(size_t m = 0; m < num_models; m++) { expected_life = 0; vector<thread> threads; vector<rel_model_t*> t_r_model; for(size_t t = 0; t < r_model.size(); t++) { rel_model_t *copy = components[0]->rel_models[m]; t_r_model.push_back(copy->copy()); } for(size_t tid = 0; tid < num_threads; tid++) { threads.push_back(thread(target, tid, iterations, model_target, guess, t_r_model, 1, num_models, generate, random, crit, components, 0, 1, time)); } for(auto& thread:threads) { thread.join(); } for(int i = 0; i < iterations; i++) { expected_life += guess[i]/(double)(iterations); } life_per_model[m] = target_mttf/expected_life; } for(size_t m = 0; m < num_models; m++) { model_target[m] = life_per_model[m]; } // Set initial A satisfying approximate model MTTF with loose bound // (10% error rate) for(size_t m = 0; m < r_model.size(); m++) { vector<rel_model_t*> temp_r_model; for(size_t t= 0; t < r_model.size(); t++) { rel_model_t *copy = components[0]->rel_models[m]; temp_r_model.push_back(copy->copy()); } double err_shoot; while(1) { for(size_t c = 0; c < num_components; c++) { target_guess[c] = 1/lambda(components[c]->rel_models[m], components[c]->target_conditions[0], 0); } vector<thread> threads_m; expected_life = 0; for(size_t tid = 0; tid < num_threads; tid++) { threads_m.push_back(thread(target, tid, iterations, target_guess, guess, temp_r_model, num_components, 1, generate, random, crit, components, 0, 1, time)); } for(auto& thread:threads_m) { thread.join(); } for(int i = 0; i < iterations; i++) { expected_life += guess[i]/(double)(iterations); } err_shoot = (expected_life-life_per_model[m] )/life_per_model[m]; // If A satisfying model MTTF with loose bound, // Setting initial A ends. if( abs(expected_life - life_per_model[m]) < err_rate*life_per_model[m] ) { life_per_model[m] = expected_life; break; } else { for(size_t c = 0; c < num_components; ){ components[c]->rel_models[m]->scale *= err_shoot; c += (components[c]->count)*(components[c]->area); } } } } // Finetuning A for each model with two target : // 1. system MTTF, 2. model criticality double b_s; double acc=0.001; double p_crit[num_models] ={0}; double* temp_target_guess = new double[num_components*num_models*n_use_case]; size_t count = 0; double interval = target_mttf; while(1) { count = 0; // Store MTTF of each R(t) with updated A for(size_t c = 0; c < num_components; c++) { for(size_t m = 0; m < num_models; m++) { for(size_t uc = 0; uc < n_use_case; uc++) { temp_target_guess[c*num_models*n_use_case+m*n_use_case+uc] = 1/(lambda(components[c]->rel_models[m], components[c]->target_conditions[uc], 0)); } } } expected_life = 0; vector<thread>threads2; for(size_t tid = 0; tid < num_threads; tid++) { threads2.push_back(thread(target, tid, iterations, temp_target_guess, guess, r_model, num_components, num_models, generate, random, crit, components, interval, n_use_case, time)); } for(auto& thread:threads2) { thread.join(); } for(int i = 0; i < iterations; i++) { expected_life += guess[i]/(double)(iterations); p_crit[crit[i]]++; } for(size_t m = 0; m < num_models; m++) { p_crit[m] = p_crit[m]/(double)iterations; } // Count the number of model satisfying target model criticality(1/N) for(size_t m = 0; m < num_models; m++) { if( (0.995/(double)num_models < p_crit[m]) && ( p_crit[m] < 1.005/(double)num_models) ) { count++; } } // Error rate of system MTTF b_s = (expected_life - target_mttf)/target_mttf; // If 1.system MTTF and 2. model criticality are satisfied, // Initialization end. if(abs(b_s) < acc) { interval = time_interval; if(count == num_models) { cout << "scale of each model and criticality" << endl; for(size_t m = 0; m < num_models; m++) { cout << "model " << m << " : " << components[0]->rel_models[m]->scale << ", criticality : " << p_crit[m] << endl; } cout << endl; break; } } // Update A in each model, considering in proportion to // 1. system MTTF error rate, and 2. model criticality error rate for(size_t m = 0; m < num_models; m++) { for(size_t c = 0; c < num_components;) { components[c]->rel_models[m]->scale *= (1 + b_s)*(1 + ((double)1/num_models - p_crit[m])); c += (components[c]->count)*(components[c]->area); } p_crit[m] = 0; } } delete [] guess; delete [] model_target; delete [] life_per_model; delete [] target_guess; delete [] temp_target_guess; delete [] time; #ifdef DEBUG for(size_t i = 0; i < components.size(); i++) { cout << components[i]->name << ":" << endl; for(size_t j = 0; j < components[i]->use_cases.size(); j++) { cout << "use_case: " << components[i]->use_cases[j].name << endl; } for(size_t j = 0; j < components[i]->target_conditions.size(); j++) { cout << "target_conditions: " << components[i]->target_conditions[j].name << endl; } } #endif } double rel_system_t::evaluate(void) { size_t n_model = components[0]->rel_models.size(); size_t n_use_case = components[0]->use_cases.size(); size_t n_comp_type = 0; // Random generator for Monte Carlo simulation srand((unsigned int)time(NULL)); default_random_engine generate; generate.seed(rand()); std::uniform_real_distribution<double> random(0.0, 1.0); size_t s_comp = 0; //for rotation system // Count the number of PU type for(size_t c = 0; c < components.size();) { n_comp_type++; // For rotation management scheme s_comp += (components[c]->count + components[c]->spare_count) *(components[c]->area); c += components[c]->count * components[c]->area; } int *spares = new int[iterations*n_comp_type](); int *crit = new int[iterations]; size_t idx = 0; for(int i = 0; i < iterations; i++) { idx = 0; rel_component_t* comp = components[idx]; for(size_t t = 0; t < n_comp_type; t++) { spares[i*n_comp_type+t] = comp->spare_count; idx += (comp->count)*(comp->area); comp = components[idx]; } } // Check if system modeling is rotation system bool rotate = 0; idx = 0; for(size_t t = 0; t < n_comp_type; t++) { if(components[idx]->mngt_scheme == mngt_rotate) { rotate = 1; } idx+=(components[t]->count)*(components[t]->area); } if(rotate){ components.reserve(s_comp); size_t t = 0; for(vector<rel_component_t*>::iterator r = components.begin(); r < components.end();) { rel_component_t *comp = *r; components.insert(r, spares[t]*(comp->area), comp); comp->count += spares[t]; r += (comp->count)*(comp->area); t++; } } int k = 0; for(size_t t = 0; t < n_comp_type; t++) { rel_component_t *comp = components[k]; size_t n_cond = comp->use_cases[0].temp.size(); for(size_t m = 0; m < n_model; m++) { rel_model_t *model = comp->rel_models[m]; model->use_avg.reserve(n_use_case*n_cond); for(size_t u = 0; u < n_use_case; u++) { for(size_t cond = 0; cond < n_cond; cond++) { model->use_avg[cond*n_use_case+u] = 1 / (components[idx]->use_cases[u].activity * lambda(model, comp->use_cases[u], cond)); } } } k += (comp->count)*(comp->area); } // Variables for Monte Carlo simulation double *single_life = new double[iterations](); double expected_life=0; int *crit_hist = new int[n_comp_type](); for(size_t t = 0; t < n_comp_type; t++) { crit_hist[t] = 0; } expected_life = 0; vector<thread> threads; for(size_t tid = 0; tid < num_threads; tid++) { threads.push_back(thread(monte_carlo, tid, iterations, single_life, spares, crit, components, n_comp_type, generate, random, rotate, time_interval)); } for(auto& thread: threads) thread.join(); for(int i = 0; i < iterations; i++) { expected_life += single_life[i] / (double)iterations; crit_hist[crit[i]]++; } cout << "Expected lifetime is " << expected_life << " years" << endl; cout << "Criticality is " << endl; for(size_t i = 0; i < n_comp_type; i++) { cout << crit_hist[i]/(double)iterations*100 << "% for component type " << i << endl; } delete [] single_life; delete [] spares; delete [] crit; delete [] crit_hist; return expected_life; }
34.941032
92
0.532382
[ "vector", "model" ]
e80a8c563a91a1bbcdbd1773535f5b8b5a62174a
2,001
cpp
C++
LeetCode/ThousandOne/0140-word_berak_2.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0140-word_berak_2.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0140-word_berak_2.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 140. 单词拆分 II 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。 返回所有这些可能的句子。 说明: 分隔时可以重复使用字典中的单词。 你可以假设字典中没有重复的单词。 示例 1: 输入: s = "catsanddog" wordDict = ["cat", "cats", "and", "sand", "dog"] 输出: [ "cats and dog", "cat sand dog" ] 示例 2: 输入: s = "pineapplepenapple" wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] 输出: [ "pine apple pen apple", "pineapple pen apple", "pine applepen apple" ] 解释: 注意你可以重复使用字典中的单词。 示例 3: 输入: s = "catsandog" wordDict = ["cats", "dog", "sand", "and", "cat"] 输出: [] */ // https://leetcode.com/problems/word-break-ii/discuss/44178/11ms-C%2B%2B-solution-(concise) // 抄的 class Solution { unordered_map<string, vector<string>> m; unordered_set<string> t; vector<string> combine(string const& word, vector<string> prev) { for (string& p : prev) { p.push_back(' '); p += word; } return prev; } vector<string> dfs(string s) { vector<string> r; auto it = m.find(s); if (it != m.end()) return it->second; if (t.find(s) != t.end()) r.push_back(s); int len = static_cast<int>(s.length()); for (int i = 1; i < len; ++i) { string w = s.substr(i); if (t.find(w) != t.end()) { vector<string> left = combine(w, dfs(s.substr(0, i))); int dd = static_cast<int>(left.size()); for (int d = 0; d < dd; ++d) r.push_back(move(left[d])); } } m[s] = r; return r; } public: vector<string> wordBreak(string s, vector<string>& dict) { m.clear(); unordered_set<string>(dict.begin(), dict.end()).swap(t); vector<string> r = dfs(s); return r; } }; int main() { vector<string> a = { "leet", "code" }, b = { "apple", "pen" }, c = { "cats", "dog", "sand", "and", "cat" }; Solution s; output(s.wordBreak("leetcode", a), "\n", "Word Break II"); output(s.wordBreak("applepenapple", b), "\n", "Word Break II"); output(s.wordBreak("catsandog", c), "\n", "Word Break II"); output(s.wordBreak("catsanddog", c), "\n", "Word Break II"); }
18.877358
92
0.598701
[ "vector" ]
e80cf165bf11ad9925cdc6eb59251c705340c57e
8,008
cpp
C++
src/old/RouletteLFO.cpp
miRackModular/FrozenWasteland
2e21f41cb121c2a4036b509a26061bf7981d4d9a
[ "CC0-1.0" ]
null
null
null
src/old/RouletteLFO.cpp
miRackModular/FrozenWasteland
2e21f41cb121c2a4036b509a26061bf7981d4d9a
[ "CC0-1.0" ]
null
null
null
src/old/RouletteLFO.cpp
miRackModular/FrozenWasteland
2e21f41cb121c2a4036b509a26061bf7981d4d9a
[ "CC0-1.0" ]
null
null
null
#undef V1_COMPAT #include <string.h> #include "../FrozenWasteland.hpp" #include "dsp/digital.hpp" #define BUFFER_SIZE 512 namespace old { struct RouletteLFO : Module { enum ParamIds { FIXED_RADIUS_PARAM, ROTATING_RADIUS_PARAM, DISTANCE_PARAM, FREQUENCY_PARAM, EPI_HYPO_PARAM, FIXED_D_PARAM, NUM_PARAMS }; enum InputIds { FIXED_RADIUS_INPUT, ROATATING_RADIUS_INPUT, DISTANCE_INPUT, FREQUENCY_INPUT, NUM_INPUTS }; enum OutputIds { OUTPUT_X, OUTPUT_Y, NUM_OUTPUTS }; enum RouletteTypes { HYPOTROCHOID_ROULETTE, EPITROCHIID_ROULETTE }; float bufferX1[BUFFER_SIZE] = {}; float bufferY1[BUFFER_SIZE] = {}; int bufferIndex = 0; float frameIndex = 0; float scopeDeltaTime = powf(2.0, -8); //SchmittTrigger resetTrigger; float x1 = 0.0; float y1 = 0.0; float phase = 0.0; RouletteLFO() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {} void step() override; // For more advanced Module features, read Rack's engine.hpp header file // - toJson, fromJson: serialization of internal data // - onSampleRateChange: event triggered by a change of sample rate // - onReset, onRandomize, onCreate, onDelete: implements special behavior when user clicks these from the context menu }; void RouletteLFO::step() { float pitch = fminf(params[FREQUENCY_PARAM].value + inputs[FREQUENCY_INPUT].value, 8.0); float freq = powf(2.0, pitch); float deltaTime = 1.0 / engineGetSampleRate(); float deltaPhase = fminf(freq * deltaTime, 0.5); phase += deltaPhase; if (phase >= 1.0) phase -= 1.0; if(params[EPI_HYPO_PARAM].value == HYPOTROCHOID_ROULETTE) { float r = clamp(params[ROTATING_RADIUS_PARAM].value + inputs[ROATATING_RADIUS_INPUT].value,1.0,10.0); float R = clamp(params[FIXED_RADIUS_PARAM].value +inputs[FIXED_RADIUS_INPUT].value,r,20.0); float d = clamp(params[DISTANCE_PARAM].value + inputs[DISTANCE_INPUT].value,1.0,10.0); if(params[FIXED_D_PARAM].value) { d=r; } float amplitudeScaling = 5.0 / (R-r+d); float theta = phase * 2 * M_PI; x1 = amplitudeScaling * (((R-r) * cosf(theta)) + (d * cosf((R-r)/r * theta))); y1 = amplitudeScaling * (((R-r) * sinf(theta)) - (d * sinf((R-r)/r * theta))); } else { float R = clamp(params[FIXED_RADIUS_PARAM].value +inputs[FIXED_RADIUS_INPUT].value,1.0,20.0); float r = clamp(params[ROTATING_RADIUS_PARAM].value + inputs[ROATATING_RADIUS_INPUT].value,1.0,10.0); float d = clamp(params[DISTANCE_PARAM].value + inputs[DISTANCE_INPUT].value,1.0,20.0); if(params[FIXED_D_PARAM].value) { d=r; } float amplitudeScaling = 5.0 / (R+r+d); float theta = phase * 2 * M_PI; x1 = amplitudeScaling * (((R+r) * cosf(theta)) - (d * cosf((R+r)/r * theta))); y1 = amplitudeScaling * (((R+r) * sinf(theta)) - (d * sinf((R+r)/r * theta))); } outputs[OUTPUT_X].value = x1; outputs[OUTPUT_Y].value = y1; //Update scope. int frameCount = (int)ceilf(scopeDeltaTime * engineGetSampleRate()); // Add frame to buffers if (bufferIndex < BUFFER_SIZE) { if (++frameIndex > frameCount) { frameIndex = 0; bufferX1[bufferIndex] = x1; bufferY1[bufferIndex] = y1; bufferIndex++; } } // Are we waiting on the next trigger? if (bufferIndex >= BUFFER_SIZE) { bufferIndex = 0; frameIndex = 0; } } struct RouletteScopeDisplay : TransparentWidget { RouletteLFO *module; int frame = 0; std::shared_ptr<Font> font; RouletteScopeDisplay() { } void drawWaveform(NVGcontext *vg, float *valuesX, float *valuesY) { if (!valuesX) return; nvgSave(vg); Rect b = Rect(Vec(0, 15), box.size.minus(Vec(0, 15*2))); nvgScissor(vg, b.pos.x, b.pos.y, b.size.x, b.size.y); nvgBeginPath(vg); // Draw maximum display left to right for (int i = 0; i < BUFFER_SIZE; i++) { float x, y; if (valuesY) { x = valuesX[i] / 2.0 + 0.5; y = valuesY[i] / 2.0 + 0.5; } else { x = (float)i / (BUFFER_SIZE - 1); y = valuesX[i] / 2.0 + 0.5; } Vec p; p.x = b.pos.x + b.size.x * x; p.y = b.pos.y + b.size.y * (1.0 - y); if (i == 0) nvgMoveTo(vg, p.x, p.y); else nvgLineTo(vg, p.x, p.y); } nvgLineCap(vg, NVG_ROUND); nvgMiterLimit(vg, 2.0); nvgStrokeWidth(vg, 1.5); nvgGlobalCompositeOperation(vg, NVG_LIGHTER); nvgStroke(vg); nvgResetScissor(vg); nvgRestore(vg); } void draw(NVGcontext *vg) override { //float gainX = powf(2.0, 1); //float gainY = powf(2.0, 1); //float offsetX = module->x1; //float offsetY = module->y1; float valuesX[BUFFER_SIZE]; float valuesY[BUFFER_SIZE]; for (int i = 0; i < BUFFER_SIZE; i++) { int j = i; // Lock display to buffer if buffer update deltaTime <= 2^-11 j = (i + module->bufferIndex) % BUFFER_SIZE; valuesX[i] = (module->bufferX1[j]) / 5.0; valuesY[i] = (module->bufferY1[j]) / 5.0; } // Draw waveforms for LFO 1 // X x Y nvgStrokeColor(vg, nvgRGBA(0x9f, 0xe4, 0x36, 0xc0)); drawWaveform(vg, valuesX, valuesY); } }; struct RouletteLFOWidget : ModuleWidget { RouletteLFOWidget(RouletteLFO *module); }; RouletteLFOWidget::RouletteLFOWidget(RouletteLFO *module) : ModuleWidget(module) { box.size = Vec(15*13, RACK_GRID_HEIGHT); { SVGPanel *panel = new SVGPanel(); panel->box.size = box.size; panel->setBackground(SVG::load(assetPlugin(pluginInstance, "res/old/RouletteLFO.svg"))); addChild(panel); } addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH - 12, 0))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH + 12, 0))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH-12, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH + 12, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); { RouletteScopeDisplay *display = new RouletteScopeDisplay(); display->module = module; display->box.pos = Vec(0, 35); display->box.size = Vec(box.size.x, 140); addChild(display); } addParam(ParamWidget::create<RoundBlackKnob>(Vec(10, 186), module, RouletteLFO::FIXED_RADIUS_PARAM, 1, 20.0, 5)); addParam(ParamWidget::create<RoundBlackKnob>(Vec(60, 186), module, RouletteLFO::ROTATING_RADIUS_PARAM, 1, 10.0, 3)); addParam(ParamWidget::create<RoundBlackKnob>(Vec(113, 186), module, RouletteLFO::DISTANCE_PARAM, 1, 10.0, 5.0)); addParam(ParamWidget::create<RoundBlackKnob>(Vec(160, 186), module, RouletteLFO::FREQUENCY_PARAM, -8.0, 4.0, 0.0)); addParam(ParamWidget::create<CKSS>(Vec(55, 265), module, RouletteLFO::EPI_HYPO_PARAM, 0.0, 1.0, 0.0)); addParam(ParamWidget::create<CKSS>(Vec(130, 265), module, RouletteLFO::FIXED_D_PARAM, 0.0, 1.0, 0.0)); //addParam(ParamWidget::create<RoundBlackKnob>(Vec(87, 265), module, RouletteLFO::FREQX2_PARAM, -8.0, 3.0, 0.0)); //addParam(ParamWidget::create<RoundBlackKnob>(Vec(137, 265), module, RouletteLFO::FREQY2_PARAM, -8.0, 3.0, 1.0)); addInput(Port::create<PJ301MPort>(Vec(13, 219), Port::INPUT, module, RouletteLFO::FIXED_RADIUS_INPUT)); addInput(Port::create<PJ301MPort>(Vec(63, 219), Port::INPUT, module, RouletteLFO::ROATATING_RADIUS_INPUT)); addInput(Port::create<PJ301MPort>(Vec(116, 219), Port::INPUT, module, RouletteLFO::DISTANCE_INPUT)); addInput(Port::create<PJ301MPort>(Vec(163, 219), Port::INPUT, module, RouletteLFO::FREQUENCY_INPUT)); addOutput(Port::create<PJ301MPort>(Vec(57, 335), Port::OUTPUT, module, RouletteLFO::OUTPUT_X)); addOutput(Port::create<PJ301MPort>(Vec(113, 335), Port::OUTPUT, module, RouletteLFO::OUTPUT_Y)); //addChild(ModuleLightWidget::create<MediumLight<BlueLight>>(Vec(21, 59), module, LissajousLFO::BLINK_LIGHT_1)); //addChild(ModuleLightWidget::create<MediumLight<BlueLight>>(Vec(41, 59), module, LissajousLFO::BLINK_LIGHT_2)); //addChild(ModuleLightWidget::create<MediumLight<BlueLight>>(Vec(61, 59), module, LissajousLFO::BLINK_LIGHT_3)); //addChild(ModuleLightWidget::create<MediumLight<BlueLight>>(Vec(81, 59), module, LissajousLFO::BLINK_LIGHT_4)); } Model *modelRouletteLFO_old = Model::create<RouletteLFO, RouletteLFOWidget>("Frozen Wasteland", "RouletteLFO", "Roulette LFO (Legacy)", LFO_TAG); }
31.777778
145
0.691059
[ "model" ]
e80e9d2fb878a89203bb1ed79a7c8211a0955852
878
hpp
C++
include/boost/simd/function/fast_rsqrt.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/function/fast_rsqrt.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/function/fast_rsqrt.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
//================================================================================================== /*! @file @copyright 2016 NumScale SAS @copyright 2016 J.T. Lapreste Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_FAST_RSQRT_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_FAST_RSQRT_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-arithmetic Function object implementing fast_rsqrt capabilities Computes fast_rsqrt value of its parameter. **/ const boost::dispatch::functor<tag::fast_rsqrt_> fast_rsqrt = {}; } } #endif #include <boost/simd/function/scalar/fast_rsqrt.hpp> #endif
26.606061
100
0.587699
[ "object" ]
e8127577d413d5c6224d485546cbfa80b9ee2df0
6,322
cpp
C++
sources/main.cpp
Gyebro/aoc18
6c606a84f10496366611cd295d049fb2b3beefd4
[ "MIT" ]
null
null
null
sources/main.cpp
Gyebro/aoc18
6c606a84f10496366611cd295d049fb2b3beefd4
[ "MIT" ]
null
null
null
sources/main.cpp
Gyebro/aoc18
6c606a84f10496366611cd295d049fb2b3beefd4
[ "MIT" ]
null
null
null
#include <iostream> #include "config.h" #include "days.h" #include "common.h" using namespace std; int main() { #ifndef RUN_BENCHMARKS #ifdef DAY01 day01("day01.txt"); day01("day01.txt", false); #endif #ifdef DAY02 day02("day02.txt"); day02("day02.txt", false); #endif #ifdef DAY03 day03("day03.txt"); day03("day03.txt", false); #endif #ifdef DAY04 day04("day04.txt"); day04("day04.txt", false); #endif #ifdef DAY05 day05("day05.txt"); day05("day05.txt", false); #endif #ifdef DAY06 day06("day06.txt"); day06("day06.txt", false); #endif #ifdef DAY07 day07("day07.txt"); day07("day07.txt", false); #endif #ifdef DAY08 //day08("day08_test.txt"); // Passed: 138 day08("day08.txt"); //day08("day08_test.txt", false); // Passed: 66 day08("day08.txt", false); #endif #ifdef DAY09 // day09("day09_tests.txt"); All five tests: Passed day09("day09.txt"); day09("day09.txt", false); #endif #ifdef DAY10 day10("day10.txt"); #endif #ifdef DAY11 day11("day11.txt"); day11("day11.txt", false); #endif #ifdef DAY12 //day12("day12_test.txt"); // Passed: 325 day12("day12.txt"); day12("day12.txt", false); #endif #ifdef DAY13 day13("day13.txt"); day13("day13.txt", false); #endif #ifdef DAY14 day14("day14.txt"); day14("day14.txt", false); #endif #ifdef DAY15 //day15("day15_test1.txt"); // Passed 36334 //day15("day15_test2.txt"); // Passed 39514 //day15("day15_test3.txt"); // Passed 27755 //day15("day15_test4.txt"); // Passed 28944 //day15("day15_test5.txt"); // Passed 18740 day15("day15.txt"); //day15("day15_test5.txt", false); // Passed 34, 1140 day15("day15.txt", false); #endif #ifdef DAY16 day16("day16.txt"); day16("day16.txt", false); #endif #ifdef DAY17 //day17("day17_test.txt"); // Passed 57 day17("day17.txt"); //day17("day17.txt", false); day17("day17.txt", false); #endif #ifdef DAY18 //day18("day18_test.txt"); // Passed 1147 day18("day18.txt"); day18("day18.txt", false); #endif #ifdef DAY19 day19("day19.txt"); day19("day19.txt", false); #endif #ifdef DAY20 //day20("day20_test1.txt"); // Map: OK, BFS: OK //day20("day20_test2.txt"); // Map: OK, BFS: OK //day20("day20_test3.txt"); // Map: OK, BFS: OK //day20("day20_test4.txt"); // Map: OK, BFS: OK day20("day20.txt"); day20("day20.txt", false); #endif #ifdef DAY21 day21("day21.txt"); day21("day21.txt", false); #endif #ifdef DAY22 day22("day22.txt"); day22("day22.txt", false); #endif #ifdef DAY23 day23("day23.txt"); day23("day23.txt", false); #endif #ifdef DAY24 day24("day24_test.txt", true, true); // Passed 5216 day24("day24.txt", true, true); day24("day24.txt", false, true); #endif #ifdef DAY25 day25("day25.txt"); #endif #endif #ifdef RUN_BENCHMARKS vector<string> tasks, tasks_terminal; vector<double> time_ms; vector<string> day_titles = { "Chronal Calibration", "Inventory Management System", "No Matter How You Slice It", "Repose Record", "Alchemical Reduction", "Chronal Coordinates", "The Sum of Its Parts", "Memory Maneuver", "Marble Mania", "The Stars Align", "Chronal Charge", "Subterranean Sustainability", "Mine Cart Madness", "Chocolate Charts", "Beverage Bandits", "Chronal Classification", "Reservoir Research", "Settlers of The North Pole", "Go With The Flow", "A Regular Map", "Chronal Conversion", "Mode Maze", "Experimental Emergency Teleportation", "Immune System Simulator 20XX", "Four-Dimensional Adventure" }; void (*day_functions[])(string, bool, bool) = { &day01, &day02, &day03, &day04, &day05, &day06, &day07, &day08, &day09, &day10, &day11, &day12, &day13, &day14, &day15, &day16, &day17, &day18, &day19, &day20, &day21, &day22, &day23, &day24, &day25, }; Clock c; string day, day_w_title, inputfile, num; for (size_t d = 1; d <= 25; d++) { if (d < 10) { num = "0"+to_string(d); } else { num = to_string(d); } inputfile = "day"+num+".txt"; cout << endl << "Day "+num << endl; tasks_terminal.emplace_back("Day "+num); tasks.emplace_back("Day "+num+": "+day_titles[d-1]); // Run part one c.start(); day_functions[d-1](inputfile, true, false); c.stop(); time_ms.push_back(c.read_msec()); c.start(); day_functions[d-1](inputfile, false, false); c.stop(); time_ms.push_back(c.read_msec()); } // Print result to cout cout << endl << endl; cout << "Task \t\tP1 [ms]\t\tP2 [ms]\n"; cout << "------\t\t-------\t\t-------\n"; cout << setprecision(3) << fixed; for (size_t i=0; i<tasks.size(); i++) { cout << tasks_terminal[i] << "\t\t" << time_ms[2*i] << "\t\t" << time_ms[2*i+1] << '\n'; } flush(cout); // Also print to readme.md ofstream out("../README.md"); out << "# aoc18\n"; out << "Advent of Code 2018 in C++\n"; out << "## Computation times (no optimization, both parts run separately).\n"; out << "Processor: Intel Core i7-7700HQ, single thread unless indicated\n"; out << endl; out << "Day | Part One [ms] | Part Two [ms]\n"; out << "--- | ---: | ---:\n"; out << setprecision(3) << fixed; double time_sum = 0; for (size_t i=0; i<tasks.size(); i++) { if (i != 10-1 && i != 25-1) { out << tasks[i] << " | " << time_ms[2*i] << " | " << time_ms[2*i+1] << '\n'; time_sum += time_ms[2*i]+time_ms[2*i+1]; } else { out << tasks[i] << " | " << time_ms[2*i] << " | - \n"; time_sum += time_ms[2*i]; } } out << endl; out << "Total time: " << time_sum/1000.0 << " seconds\n"; out << endl; out << "## And so the time stream has been fixed\n"; out << "![AoC18 calendar](calendar18.gif)"; out.close(); #endif return 0; }
24.503876
96
0.54777
[ "vector" ]
e8168c724018e96672c1297e16d8a55468f1d5d9
4,340
cpp
C++
dev/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderComponent.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
8
2019-10-07T16:33:47.000Z
2020-12-07T03:59:58.000Z
dev/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderComponent.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderComponent.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
5
2020-08-27T20:44:18.000Z
2021-08-21T22:54:11.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "ImageProcessing_precompiled.h" #include "AtlasBuilderComponent.h" #include <AzCore/Serialization/SerializeContext.h> namespace TextureAtlasBuilder { // AZ Components should only initialize their members to null and empty in constructor // Allocation of data should occur in Init(), once we can guarantee reflection and registration of types AtlasBuilderComponent::AtlasBuilderComponent() { } // Handle deallocation of your memory allocated in Init() AtlasBuilderComponent::~AtlasBuilderComponent() { } // Init is where you'll actually allocate memory or create objects // This ensures that any dependency components will have been been created and serialized void AtlasBuilderComponent::Init() { } // Activate is where you'd perform registration with other objects and systems. // All builder classes owned by this component should be registered here // Any EBuses for the builder classes should also be connected at this point void AtlasBuilderComponent::Activate() { AssetBuilderSDK::AssetBuilderDesc builderDescriptor; builderDescriptor.m_name = "Atlas Worker Builder"; builderDescriptor.m_patterns.emplace_back(AssetBuilderSDK::AssetBuilderPattern("*.texatlas", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); builderDescriptor.m_busId = azrtti_typeid<AtlasBuilderWorker>(); builderDescriptor.m_createJobFunction = AZStd::bind(&AtlasBuilderWorker::CreateJobs, &m_atlasBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); builderDescriptor.m_processJobFunction = AZStd::bind(&AtlasBuilderWorker::ProcessJob, &m_atlasBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); m_atlasBuilder.BusConnect(builderDescriptor.m_busId); AssetBuilderSDK::AssetBuilderBus::Broadcast(&AssetBuilderSDK::AssetBuilderBusTraits::RegisterBuilderInformation, builderDescriptor); } // Disconnects from any EBuses we connected to in Activate() // Unregisters from objects and systems we register with in Activate() void AtlasBuilderComponent::Deactivate() { m_atlasBuilder.BusDisconnect(); // We don't need to unregister the builder - the AP will handle this for us, because it is managing the lifecycle of this component } // Reflect the input and output formats for the serializer void AtlasBuilderComponent::Reflect(AZ::ReflectContext* context) { // components also get Reflect called automatically // this is your opportunity to perform static reflection or type registration of any types you want the serializer to know about if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context)) { serialize->Class<AtlasBuilderComponent, AZ::Component>() ->Version(0) ->Attribute(AZ::Edit::Attributes::SystemComponentTags, AZStd::vector<AZ::Crc32>({ AssetBuilderSDK::ComponentTags::AssetBuilder })) ; } AtlasBuilderInput::Reflect(context); } void AtlasBuilderComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { provided.push_back(AZ_CRC("Atlas Builder Plugin Service", 0x35974d0d)); } void AtlasBuilderComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("Atlas Builder Plugin Service", 0x35974d0d)); } void AtlasBuilderComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { AZ_UNUSED(required); } void AtlasBuilderComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) { AZ_UNUSED(dependent); } }
43.838384
163
0.734101
[ "vector" ]
e819e4964410a6d4028938f7aa002e9bf870f825
1,153
cpp
C++
test/ut_ts_packet.cpp
sergeyrachev/sandstream
bad2c90f075f1abdc027dec9f47875239ce99bf3
[ "MIT" ]
null
null
null
test/ut_ts_packet.cpp
sergeyrachev/sandstream
bad2c90f075f1abdc027dec9f47875239ce99bf3
[ "MIT" ]
null
null
null
test/ut_ts_packet.cpp
sergeyrachev/sandstream
bad2c90f075f1abdc027dec9f47875239ce99bf3
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "ts_packet.h" using challenge::ts_packet_t; TEST(ts_packet, parse_itself_no_adaptation_field_no_pusi){ const size_t ts_packet_header_length = 4; const std::array<uint8_t, ts_packet_t::ts_packet_size> content = {0x47, 0x00, 0x21, 0x11, 0x01 }; ts_packet_t packet(content.data(), content.size()); ASSERT_EQ(0x21, packet.pid); ASSERT_FALSE(packet.payload_unit_start_indicator); ASSERT_EQ(0x01, packet.payload.data[0]); } TEST(ts_packet, parse_itself_with_adaptation_field_and_pusi){ const size_t ts_packet_header_length = 4; const size_t adaptation_field_occupied_length = 8; std::vector<uint8_t> expected_payload(ts_packet_t::ts_packet_size - ts_packet_header_length - adaptation_field_occupied_length); expected_payload[0] = 0xe0; const std::array<uint8_t, ts_packet_t::ts_packet_size> content = {0x47, 0x40, 0x21, 0x30, 0x07, 0x50, 0x00, 0x06, 0xc7, 0xd7, 0x7e, 0x00, 0xe0 }; ts_packet_t packet(content.data(), content.size()); ASSERT_EQ(0x21, packet.pid); ASSERT_TRUE(packet.payload_unit_start_indicator); ASSERT_EQ(0xe0, packet.payload.data[0]); }
36.03125
149
0.751951
[ "vector" ]
e8218386396c8ba83bc4d1455c61facf4d72fcbd
4,123
cpp
C++
src/equation/cg.cpp
rigarash/monolish-debian-package
70b4917370184bcf07378e1907c5239a1ad9579b
[ "Apache-2.0" ]
null
null
null
src/equation/cg.cpp
rigarash/monolish-debian-package
70b4917370184bcf07378e1907c5239a1ad9579b
[ "Apache-2.0" ]
3
2021-07-08T02:02:27.000Z
2021-09-15T08:36:12.000Z
src/equation/cg.cpp
termoshtt/monolish
1cba60864002b55bc666da9baa0f8c2273578e01
[ "Apache-2.0" ]
1
2021-04-06T07:12:11.000Z
2021-04-06T07:12:11.000Z
#include "../../include/monolish_blas.hpp" #include "../../include/monolish_equation.hpp" #include "../../include/monolish_vml.hpp" #include "../internal/monolish_internal.hpp" #include <fstream> #include <iomanip> #include <string> namespace monolish { template <typename MATRIX, typename T> int equation::CG<MATRIX, T>::monolish_CG(MATRIX &A, vector<T> &x, vector<T> &b) { Logger &logger = Logger::get_instance(); logger.solver_in(monolish_func); if (A.get_row() != A.get_col()) { throw std::runtime_error("error, A.row != A.col"); } if (A.get_device_mem_stat() != x.get_device_mem_stat() && A.get_device_mem_stat() != b.get_device_mem_stat()) { throw std::runtime_error("error, A.get_device_mem_stat != " "x.get_device_mem_stat != b.get_device_mem_stat"); } vector<T> r(A.get_row(), 0.0); vector<T> p(A.get_row(), 0.0); vector<T> q(A.get_row(), 0.0); vector<T> z(A.get_row(), 0.0); if (A.get_device_mem_stat() == true) { monolish::util::send(r, p, q, z); } this->precond.create_precond(A); // r = b-Ax blas::matvec(A, x, q); vml::sub(b, q, r); // p0 = Mr0 this->precond.apply_precond(r, z); blas::copy(z, p); for (size_t iter = 0; iter < this->get_maxiter(); iter++) { blas::matvec(A, p, q); auto tmp = blas::dot(z, r); auto alpha = tmp / blas::dot(p, q); blas::axpy(alpha, p, x); blas::axpy(-alpha, q, r); this->precond.apply_precond(r, z); auto beta = blas::dot(z, r) / tmp; blas::xpay(beta, z, p); // p = z + beta*p T resid = this->get_residual(r); if (this->get_print_rhistory() == true) { *this->rhistory_stream << iter + 1 << "\t" << std::scientific << resid << std::endl; } if (resid < this->get_tol() && this->get_miniter() <= iter + 1) { logger.solver_out(); return MONOLISH_SOLVER_SUCCESS; } if (std::isnan(resid)) { return MONOLISH_SOLVER_RESIDUAL_NAN; } } logger.solver_out(); return MONOLISH_SOLVER_MAXITER; } template int equation::CG<matrix::Dense<double>, double>::monolish_CG( matrix::Dense<double> &A, vector<double> &x, vector<double> &b); template int equation::CG<matrix::Dense<float>, float>::monolish_CG( matrix::Dense<float> &A, vector<float> &x, vector<float> &b); template int equation::CG<matrix::CRS<double>, double>::monolish_CG( matrix::CRS<double> &A, vector<double> &x, vector<double> &b); template int equation::CG<matrix::CRS<float>, float>::monolish_CG( matrix::CRS<float> &A, vector<float> &x, vector<float> &b); template int equation::CG<matrix::LinearOperator<double>, double>::monolish_CG( matrix::LinearOperator<double> &A, vector<double> &x, vector<double> &b); template int equation::CG<matrix::LinearOperator<float>, float>::monolish_CG( matrix::LinearOperator<float> &A, vector<float> &x, vector<float> &b); /// template <typename MATRIX, typename T> int equation::CG<MATRIX, T>::solve(MATRIX &A, vector<T> &x, vector<T> &b) { Logger &logger = Logger::get_instance(); logger.solver_in(monolish_func); int ret = 0; if (this->get_lib() == 0) { ret = monolish_CG(A, x, b); } logger.solver_out(); return ret; // err code } template int equation::CG<matrix::Dense<double>, double>::solve( matrix::Dense<double> &A, vector<double> &x, vector<double> &b); template int equation::CG<matrix::Dense<float>, float>::solve( matrix::Dense<float> &A, vector<float> &x, vector<float> &b); template int equation::CG<matrix::CRS<double>, double>::solve( matrix::CRS<double> &A, vector<double> &x, vector<double> &b); template int equation::CG<matrix::CRS<float>, float>::solve( matrix::CRS<float> &A, vector<float> &x, vector<float> &b); template int equation::CG<matrix::LinearOperator<double>, double>::solve( matrix::LinearOperator<double> &A, vector<double> &x, vector<double> &b); template int equation::CG<matrix::LinearOperator<float>, float>::solve( matrix::LinearOperator<float> &A, vector<float> &x, vector<float> &b); } // namespace monolish
32.984
79
0.63643
[ "vector" ]
e8252015bd03a147914ede2bae518b5177964b46
11,264
cpp
C++
files/stripper/main.cpp
endlessm/freedesktop-sdk
3bfc8a401096a4a0a660a7276a8ceae734aac79e
[ "MIT" ]
null
null
null
files/stripper/main.cpp
endlessm/freedesktop-sdk
3bfc8a401096a4a0a660a7276a8ceae734aac79e
[ "MIT" ]
null
null
null
files/stripper/main.cpp
endlessm/freedesktop-sdk
3bfc8a401096a4a0a660a7276a8ceae734aac79e
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019 Codethink Ltd. * * 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 "thread_pool.hpp" #include "mapped_file.hpp" #include "fd.hpp" #include "named_tmp_file.hpp" #include "arch.hpp" #include "elfutils.hpp" #include "run.hpp" #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <getopt.h> #include <fstream> #include <iostream> #include <map> #include <set> struct result_t { known_arch arch; std::vector<std::string> source_files; }; struct script { script(): optimize(true), jobs(2*std::thread::hardware_concurrency()) { } std::unique_ptr<result_t> preprocess_file(std::filesystem::path const& p) { fd_t fd(p, O_RDONLY); auto st = fd.get_stat(); if (st.st_size < (off_t)sizeof(Elf32_Ehdr)) { return nullptr; } mapped_file m(fd); auto header = static_cast<Elf32_Ehdr const*>(m.ptr(0)); std::string magic(ELFMAG); if (magic.compare(0, SELFMAG, (char*)(header->e_ident), SELFMAG) != 0) { return nullptr; } auto arch = get_arch(header); if (has_debuglink(fd)) { return nullptr; } if (st.st_nlink > 1) { throw std::runtime_error("Multiple links!"); } named_tmp_file listfile; int debugedit_status = run (std::vector<std::string> {"debugedit", "-i", "--list-file", listfile.get_path(), "--base-dir="+buildroot.string(), "--dest-dir="+destdir.string(), p.string()}); if (debugedit_status != 0) { throw std::runtime_error("Unexpected exit from debugedit"); } if (optimize) { int status = run(std::vector<std::string>{"eu-elfcompress", "--type=none", p.string()}); if (status != 0) { throw std::runtime_error("Unexpected exit from eu-elfcompress"); } } std::unique_ptr<result_t> result(new result_t{}); result->arch = arch; std::ifstream liststream(listfile.get_path()); while (liststream) { std::string path; getline(liststream, path, '\0'); result->source_files.push_back(path); } return result; } bool classify() { std::vector<std::tuple<std::filesystem::path, std::future<std::unique_ptr<result_t> > > > results; constexpr auto exec = std::filesystem::perms::owner_exec | std::filesystem::perms::group_exec | std::filesystem::perms::others_exec; for (auto& p : std::filesystem::recursive_directory_iterator(install_root)) { auto status = symlink_status(p); if (status.type() == std::filesystem::file_type::regular) { auto name = p.path().filename().string(); if (bool(status.permissions() & exec) || (name.rfind(".so") != std::string::npos) || ((name.length() >= 5) && (name.compare(name.length()-5, 5, ".cmxs") == 0)) || ((name.length() >= 5) && (name.compare(name.length()-5, 5, ".node") == 0))) { results.push_back (std::make_tuple (p, pool->post([&, p] { return preprocess_file(p); }))); } } } bool has_error = false; for (auto& result : results) { try { auto r = std::get<1>(result).get(); if (!r) continue ; by_arch[r->arch].push_back(std::get<0>(result)); for (auto const& source : r->source_files) { source_files.insert(source); } } catch (std::exception const& e) { has_error = true; std::cerr << std::get<0>(result) << ": " << e.what() << '\n'; } } return !has_error; } bool run_opt() { std::vector<std::future<void> > opt_results; for (auto const& value : by_arch) { auto const& arch = std::get<0>(value); auto const& binaries = std::get<1>(value); auto do_optimize = [&, arch, binaries] { auto debug = dwzdir / get_triplet(arch); auto realpath = install_root / relative(debug, "/"); create_directories(realpath.parent_path()); std::vector<std::string> cmd{"dwz", "-m", realpath.string(), "-M", debug.string()}; for (auto const& binary : binaries) { cmd.push_back(binary); } auto status = run(cmd); if (status != 0) { throw std::runtime_error("dwz failed"); } }; opt_results.push_back(pool->post(std::move(do_optimize))); } bool has_error = false; for (auto& result : opt_results) { try { result.get(); } catch (std::exception const& e) { has_error = true; std::cerr << e.what() << '\n'; } } return !has_error; } void strip_and_compress_file(std::filesystem::path const& toolchain, std::filesystem::path const& binary) { auto realpath = relative(binary, install_root); auto debugfile = install_root / relative(debugdir, "/") / realpath; debugfile.replace_filename(debugfile.filename().string() + ".debug"); create_directories(debugfile.parent_path()); if (0 != run(std::vector<std::string>{(toolchain / "objcopy").string(), "--only-keep-debug", "--compress-debug-sections", binary, debugfile})) { throw std::runtime_error("objcopy failed"); } chmod(debugfile.c_str(), 0644); auto st = status(binary); if (0 != access(binary.c_str(), W_OK)) { chmod(binary.c_str(), 0755); } if (0 != run(std::vector<std::string>{(toolchain / "strip").string(), "--remove-section=.comment", "--remove-section=.note", "--strip-unneeded", "--remove-section=.gnu_debugaltlink", binary})) { throw std::runtime_error("strip failed"); } if (0 != run(std::vector<std::string>{(toolchain / "objcopy").string(), "--add-gnu-debuglink", debugfile, binary})) { throw std::runtime_error("objcopy failed"); } if (0 != run(std::vector<std::string>{"eu-elfcompress", debugfile})) { throw std::runtime_error("eu-elfcompress failed"); } chmod(binary.c_str(), (unsigned)st.permissions()); } bool strip() { std::vector<std::tuple<std::filesystem::path, std::future<void> > > final_tasks; for (auto& value : by_arch) { auto& arch = std::get<0>(value); auto& binaries = std::get<1>(value); std::filesystem::path toolchain; try { toolchain = get_toolchain(toolchain_prefixes, arch); } catch (std::exception const& e) { std::cerr << e.what() << '\n'; return false; } for (auto& binary : binaries) { auto task = [this, toolchain, binary] { strip_and_compress_file(toolchain, binary); }; final_tasks.push_back(std::make_tuple(binary, pool->post(std::move(task)))); } } bool has_error = false; for (auto& t : final_tasks) { try { std::get<1>(t).get(); } catch (std::exception const& e) { has_error = true; std::cerr << std::get<0>(t) << ": " << e.what() << '\n'; } } if (has_error) return false; return true; } void copy_source() { for (auto& source: source_files) { auto dst = install_root / relative(destdir, "/") / source; auto src = buildroot / source; if (!exists(dst)) { if (is_directory(src)) { create_directories(dst); } else if (exists(src)) { create_directories(dst.parent_path()); copy_file(src, dst); } } } } bool operator()() { pool.reset(new thread_pool{jobs}); if (!classify()) { return false; } auto source_copy_res = pool->post([this] { copy_source(); }); if (optimize) { if (!run_opt()) return false; } if (!strip()) return false; source_copy_res.get(); return true; } std::unique_ptr<thread_pool> pool; bool optimize; std::vector<std::string> toolchain_prefixes; std::size_t jobs; std::filesystem::path buildroot; std::filesystem::path destdir; std::filesystem::path dwzdir; std::filesystem::path debugdir; std::filesystem::path install_root; std::set<std::string> source_files; std::map<known_arch, std::vector<std::filesystem::path> > by_arch; }; int main(int argc, char* argv[]) { script s; static struct option long_options[] = { {"no-optimize", no_argument, nullptr, 'n'}, {"toolchain-prefix", required_argument, nullptr, 't'}, {"jobs", required_argument, nullptr, 'j'}, {nullptr, 0, nullptr, 0} }; auto usage = [&] { std::cerr << "Usage: " << argv[0] << " [OPTIONS] BUILD_ROOT DESTDIR DWZDIR DEBUGDIR INSTALL_ROOT\n" << " Options:\n" << " -j|--jobs JOBS Number of parallel jobs\n" << " -n|--no-optimize Disable dwz optimization\n" << " -t|--toolchain-prefix PATH Search for toolchain in that prefix\n"; }; while (true) { int option_index = 0; int c = getopt_long(argc, argv, "nt:j:", long_options, &option_index); if (c == -1) break; switch (c) { case 'j': { std::istringstream iss(optarg); iss >> s.jobs; if (!iss.eof() || !iss.good()) { usage(); exit(1); } break ; } case 'n': s.optimize = false; break ; case 't': s.toolchain_prefixes.push_back(optarg); break ; default: usage(); return 1; } } std::vector<std::string> args; for (int i = optind; i < argc; ++i) { args.push_back(argv[i]); } if (args.size() != 5) { usage(); return 1; } s.buildroot = args[0]; s.destdir = args[1]; s.dwzdir = args[2]; s.debugdir = args[3]; s.install_root = args[4]; if (s()) { return 0; } else { return 1; } }
28.808184
105
0.560369
[ "vector" ]
e8289daf308c6611fd18ec477c93a0473cd46dd1
918
cpp
C++
LUCKYSTR.cpp
anant-agarwal/codechef
33e73300f02830c3897ffe2ace95938b56d58f92
[ "MIT" ]
null
null
null
LUCKYSTR.cpp
anant-agarwal/codechef
33e73300f02830c3897ffe2ace95938b56d58f92
[ "MIT" ]
null
null
null
LUCKYSTR.cpp
anant-agarwal/codechef
33e73300f02830c3897ffe2ace95938b56d58f92
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<vector> #include<cstring> #include<algorithm> using namespace std; vector<string>v; int is(string s, string v); int chk(string s) { if(s.size() >=47) return 1; int k=v.size(); for(int i=0;i<k;i++) { /* for(int j=0;j<s.size()-v[i].size();j++) { int fl=0; for(int k=0;k<v[i].size() && j+k<s.size();k++) { if(s[j+k]!=v[i][k]) {fl=1;break;} } if(fl==0) return 1; } */ if(is(s,v[i]))return 1; } return 0; } int is(string s, string v) { int fl=1; for(int i=0;i<s.size();i++) { int j; for( j=0;j<v.size() && i+j< s.size();j++) { if(s[i+j]!=v[j]) break; } if(j==v.size())return 1; } return 0; } int main() { int n,k; cin>>k>>n; for(int i=0;i<k;i++) { string s; cin>>s; v.push_back(s); } for(int i=0;i<n;i++) { string s; cin>>s; if(chk(s)) printf("Good\n"); else printf("Bad\n"); } }
13.701493
49
0.509804
[ "vector" ]
e836c3e89f93ec493521657520b4d44ac237f4bf
21,462
hpp
C++
src/serializable.hpp
AggroBird/propane
83134d11f6a90798db8937761ab707d95c520f1b
[ "MIT" ]
3
2021-02-28T12:52:43.000Z
2021-12-31T00:12:48.000Z
src/serializable.hpp
AggroBird/propane
83134d11f6a90798db8937761ab707d95c520f1b
[ "MIT" ]
null
null
null
src/serializable.hpp
AggroBird/propane
83134d11f6a90798db8937761ab707d95c520f1b
[ "MIT" ]
null
null
null
#ifndef _HEADER_SERIALIZABLE #define _HEADER_SERIALIZABLE #include "propane_block.hpp" #include "block_writer.hpp" #include "common.hpp" #include <vector> #include <map> #include <string_view> #include <type_traits> namespace propane { namespace serialization { // Get elements template<typename... elem_t> struct serializable_elements { static constexpr size_t count = sizeof...(elem_t); }; template<typename value_t> struct get_serializable_elements { using type = serializable_elements<>; }; // Is packed template<typename value_t> struct is_packed { static constexpr bool value = std::is_arithmetic_v<value_t> || std::is_enum_v<value_t>; }; template<typename value_t> constexpr bool is_packed_v = is_packed<value_t>::value; // Is serializable template<typename value_t> struct is_serializable { static constexpr bool value = is_packed_v<value_t>; }; template<> struct is_serializable<std::string> { static constexpr bool value = true; }; template<> struct is_serializable<std::string_view> { static constexpr bool value = true; }; template<typename value_t> struct is_serializable<block<value_t>> { static constexpr bool value = is_serializable<value_t>::value; }; template<typename value_t> struct is_serializable<std::vector<value_t>> { static constexpr bool value = is_serializable<value_t>::value; }; template<typename key_t, typename value_t> struct is_serializable<std::map<key_t, value_t>> { static constexpr bool value = is_serializable<key_t>::value && is_serializable<value_t>::value; }; template<typename key_t, typename value_t> struct is_serializable<indexed_vector<key_t, value_t>> { static constexpr bool value = is_serializable<value_t>::value; }; template<typename value_t> constexpr bool is_serializable_v = is_serializable<value_t>::value; // Compatibility template<typename lhs_t, typename rhs_t> struct is_serialization_compatible { static constexpr bool value = std::is_same_v<lhs_t, rhs_t> || (is_serializable_v<lhs_t> && is_serializable_v<rhs_t>); }; template<> struct is_serialization_compatible<std::string, static_string> { static constexpr bool value = true; }; template<> struct is_serialization_compatible<std::string_view, static_string> { static constexpr bool value = true; }; template<typename lhs_t, typename rhs_t> struct is_serialization_compatible<block<lhs_t>, static_block<rhs_t>> { static constexpr bool value = is_serialization_compatible<lhs_t, rhs_t>::value; }; template<typename lhs_t, typename rhs_t> struct is_serialization_compatible<std::vector<lhs_t>, static_block<rhs_t>> { static constexpr bool value = is_serialization_compatible<lhs_t, rhs_t>::value; }; template<typename lhs_key_t, typename lhs_value_t, typename rhs_key_t, typename rhs_value_t> struct is_serialization_compatible<std::map<lhs_key_t, lhs_value_t>, static_lookup_block<rhs_key_t, rhs_value_t>> { static constexpr bool value = is_serialization_compatible<lhs_key_t, rhs_key_t>::value || is_serialization_compatible<lhs_value_t, rhs_value_t>::value; }; template<typename lhs_key_t, typename lhs_value_t, typename rhs_key_t, typename rhs_value_t> struct is_serialization_compatible<indexed_vector<lhs_key_t, lhs_value_t>, indexed_static_block<rhs_key_t, rhs_value_t>> { static constexpr bool value = is_serialization_compatible<lhs_value_t, rhs_value_t>::value; }; template<typename lhs_t, typename rhs_t> constexpr bool is_serialization_compatible_v = is_serialization_compatible<lhs_t, rhs_t>::value; // Serializable size check template<typename value_t, typename... rest_t> struct serializable_size_check_recursive; template<typename value_t> struct serializable_size_check_recursive<value_t> { static constexpr size_t size = sizeof(value_t); }; template<typename value_t, typename... rest_t> struct serializable_size_check_recursive { static constexpr size_t size = sizeof(value_t) + serializable_size_check_recursive<rest_t...>::size; }; template<typename value_t, typename... rest_t> struct serializable_size_check { static constexpr size_t member_size = serializable_size_check_recursive<rest_t...>::size; static constexpr size_t object_size = sizeof(value_t); static constexpr bool value = member_size == object_size; }; template<typename value_t, typename... rest_t> constexpr size_t serializable_size_check_v = serializable_size_check<value_t, rest_t...>::value; // Get type at idx template<typename> constexpr bool false_condition = false; template<size_t idx, typename elements> struct serializable_element; template<size_t idx> struct serializable_element<idx, serializable_elements<>> { static_assert(false_condition<std::integral_constant<size_t, idx>>, "index out of bounds"); }; template<typename value_t, typename... rest_t> struct serializable_element<0, serializable_elements<value_t, rest_t...>> { using type = value_t; }; template<size_t idx, typename value_t, typename... rest_t> struct serializable_element<idx, serializable_elements<value_t, rest_t...>> : public serializable_element<idx - 1, serializable_elements<rest_t...>> { }; // Compatibility check template<typename elem_t, size_t idx, typename value_t, typename... rest_t> struct check_serialization_compatible_recursive; template<typename elem_t, size_t idx, typename value_t> struct check_serialization_compatible_recursive<elem_t, idx, value_t> { using elements = typename get_serializable_elements<elem_t>::type; using element = typename serializable_element<idx, elements>::type; static constexpr bool value = is_serialization_compatible_v<element, value_t>; }; template<typename elem_t, size_t idx, typename value_t, typename... rest_t> struct check_serialization_compatible_recursive { using elements = typename get_serializable_elements<elem_t>::type; using element = typename serializable_element<idx, elements>::type; static constexpr bool value = is_serialization_compatible_v<element, value_t> && check_serialization_compatible_recursive<elem_t, idx + 1, rest_t...>::value; }; template<typename elem_t, typename... rest_t> struct check_serialization_compatible { static constexpr bool value = check_serialization_compatible_recursive<elem_t, 0, rest_t...>::value; }; template<typename value_t, typename... rest_t> constexpr bool check_serialization_compatible_v = check_serialization_compatible<value_t, rest_t...>::value; // Serialization check template<typename value_t, typename... rest_t> struct serializable_check_recursive; template<typename value_t> struct serializable_check_recursive<value_t> { static constexpr bool value = is_serializable_v<value_t>; }; template<typename value_t, typename... rest_t> struct serializable_check_recursive { static constexpr bool value = is_serializable_v<value_t> && serializable_check_recursive<rest_t...>::value; }; template<typename value_t, typename... rest_t> struct serializable_check { static constexpr bool value = serializable_check_recursive<rest_t...>::value; }; template<typename value_t, typename... rest_t> constexpr bool serializable_check_v = serializable_check<value_t, rest_t...>::value; template<typename value_t> struct serializer; template<typename dst_t> inline const dst_t& read_data(const void*& data) noexcept { return *reinterpret_cast<const dst_t*&>(data)++; } // Write binary template<typename value_t, bool compact> struct serialize_binary { inline static void write(block_writer& writer, const value_t& value) { static_assert(is_serializable_v<value_t>, "Type is not serializable"); serializer<value_t>::write(writer, value); } inline static void write(block_writer& writer, const value_t* ptr, size_t count) { static_assert(is_serializable_v<value_t>, "Type is not serializable"); for (size_t i = 0; i < count; i++) { serializer<value_t>::write(writer, ptr[i]); } } inline static void read(const void*& data, value_t& value) { static_assert(is_serializable_v<value_t>, "Type is not serializable"); serializer<value_t>::read(data, value); } inline static void read(const void*& data, value_t* ptr, size_t count) { static_assert(is_serializable_v<value_t>, "Type is not serializable"); for (size_t i = 0; i < count; i++) { serializer<value_t>::read(data, ptr[i]); } } }; template<typename value_t> struct serialize_binary<value_t, true> { inline static void write(block_writer& writer, const value_t& value) { static_assert(std::is_trivially_copyable_v<value_t>, "type is not trivially copyable"); writer.write_direct(value); } inline static void write(block_writer& writer, const value_t* ptr, size_t count) { static_assert(std::is_trivially_copyable_v<value_t>, "type is not trivially copyable"); writer.write_direct(ptr, uint32_t(count)); } inline static void read(const void*& data, value_t& value) { static_assert(std::is_trivially_copyable_v<value_t>, "type is not trivially copyable"); value = *reinterpret_cast<const value_t*&>(data)++; } inline static void read(const void*& data, value_t* ptr, size_t count) { static_assert(std::is_trivially_copyable_v<value_t>, "type is not trivially copyable"); memcpy(ptr, data, count * sizeof(value_t)); reinterpret_cast<const value_t*&>(data) += count; } }; // Impl (override this for specific implementation) template<typename value_t> struct serializer { inline static void write(block_writer& writer, const value_t& value) { static_assert(serialization::is_serializable_v<value_t>, "type is not serializable"); serialize_binary<value_t, is_packed_v<value_t>>::write(writer, value); } inline static void read(const void*& data, value_t& value) { serialize_binary<value_t, is_packed_v<value_t>>::read(data, value); } }; // Vector template<typename value_t> struct serializer<std::vector<value_t>> { inline static void write(block_writer& writer, const std::vector<value_t>& value) { auto& w = writer.write_deferred(); serialize_binary<value_t, is_packed_v<value_t>>::write(w, value.data(), value.size()); w.increment_length(uint32_t(value.size())); } inline static void read(const void*& data, std::vector<value_t>& value) { const auto& r = read_data<static_block<value_t>>(data); value.resize(r.size()); const void* ptr = r.data(); serialize_binary<value_t, is_packed_v<value_t>>::read(ptr, value.data(), value.size()); } }; // Block template<typename value_t> struct serializer<block<value_t>> { inline static void write(block_writer& writer, const block<value_t>& value) { auto& w = writer.write_deferred(); serialize_binary<value_t, is_packed_v<value_t>>::write(w, value.data(), value.size()); w.increment_length(uint32_t(value.size())); } inline static void read(const void*& data, block<value_t>& value) { const auto& r = read_data<static_block<value_t>>(data); value = block<value_t>(r.size()); const void* ptr = r.data(); serialize_binary<value_t, is_packed_v<value_t>>::read(ptr, value.data(), value.size()); } }; // Map template<typename key_t, typename value_t> struct serializer<std::map<key_t, value_t>> { inline static void write(block_writer& writer, const std::map<key_t, value_t>& value) { auto& w = writer.write_deferred(); for (auto& it : value) { serializer<key_t>::write(w, it.first); serializer<value_t>::write(w, it.second); } w.increment_length(uint32_t(value.size())); } inline static void read(const void*& data, std::map<key_t, value_t>& value) { throw 0; } }; // Indexed vector template<typename key_t, typename value_t> struct serializer<indexed_vector<key_t, value_t>> { inline static void write(block_writer& writer, const indexed_vector<key_t, value_t>& value) { auto& w = writer.write_deferred(); serialize_binary<value_t, is_packed_v<value_t>>::write(w, value.data(), value.size()); w.increment_length(uint32_t(value.size())); } inline static void read(const void*& data, indexed_vector<key_t, value_t>& value) { const auto& r = read_data<indexed_static_block<key_t, value_t>>(data); value.resize(r.size()); const void* ptr = r.data(); serialize_binary<value_t, is_packed_v<value_t>>::read(ptr, value.data(), value.size()); } }; // Recursive (for the macro) template<typename value_t, typename... elem_t> struct serialize_recursive; template<typename value_t> struct serialize_recursive<value_t> { inline static void write(block_writer& writer, const value_t& value) { serializer<value_t>::write(writer, value); } inline static void read(const void*& data, value_t& value) { serializer<value_t>::read(data, value); } }; template<typename value_t, typename... elem_t> struct serialize_recursive { inline static void write(block_writer& writer, const value_t& value, const elem_t&... elem) { serializer<value_t>::write(writer, value); serialize_recursive<elem_t...>::write(writer, elem...); } inline static void read(const void*& data, value_t& value, elem_t&... elem) { serializer<value_t>::read(data, value); serialize_recursive<elem_t...>::read(data, elem...); } }; } } #define _SER_EVAL(...) __VA_ARGS__ #define _SER_VARCOUNT_IMPL(_,_15,_14,_13,_12,_11,_10,_9,_8,_7,_6,_5,_4,_3,_2,X_,...) X_ #define _SER_VARCOUNT(...) _SER_EVAL(_SER_VARCOUNT_IMPL(__VA_ARGS__,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,)) #define _SER_COMBINE_IMPL(x, y) x##y #define _SER_COMBINE(x, y) _SER_COMBINE_IMPL(x,y) #define _SER_FIRST_IMPL(x, ...) x #define _SER_FIRST(...) _SER_EVAL(_SER_FIRST_IMPL(__VA_ARGS__,)) #define _SER_TUPLE_TAIL_IMPL(x, ...) (__VA_ARGS__) #define _SER_TUPLE_TAIL(...) _SER_EVAL(_SER_TUPLE_TAIL_IMPL(__VA_ARGS__)) #define _SER_TRANSFORM(t, v, args) (_SER_COMBINE(_SER_TRANSFORM_, _SER_VARCOUNT args)(t, v, args)) #define _SER_TRANSFORM_1(t, v, args) v(t, _SER_FIRST args) #define _SER_TRANSFORM_2(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_1(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_3(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_2(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_4(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_3(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_5(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_4(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_6(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_5(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_7(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_6(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_8(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_7(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_9(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_8(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_10(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_9(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_11(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_10(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_12(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_11(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_13(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_12(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_14(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_13(t, v, _SER_TUPLE_TAIL args) #define _SER_TRANSFORM_15(t, v, args) v(t, _SER_FIRST args), _SER_TRANSFORM_14(t, v, _SER_TUPLE_TAIL args) #define _SER_MAKE_INIT(...) __VA_ARGS__ #define _SER_MAKE_PARAM(t, x) decltype(t::x) #define _SER_MAKE_PARAMS(t, ...) _SER_EVAL(_SER_MAKE_INIT _SER_TRANSFORM(t, _SER_MAKE_PARAM, (__VA_ARGS__))) #define _SER_MAKE_ARG(t, x) const decltype(t::x)& x #define _SER_MAKE_ARGS(t, ...) _SER_EVAL(_SER_MAKE_INIT _SER_TRANSFORM(t, _SER_MAKE_ARG, (__VA_ARGS__))) #define _SER_MAKE_FWD(i, x) i.x #define _SER_MAKE_FORWARD(i, ...) _SER_EVAL(_SER_MAKE_INIT _SER_TRANSFORM(i, _SER_MAKE_FWD, (__VA_ARGS__))) #define SERIALIZABLE_CHECK(src_t, ...) \ static_assert(std::is_trivially_default_constructible_v<src_t>, #src_t " is not serializable: type is not trivially default constructible"); \ static_assert(propane::serialization::serializable_size_check_v<src_t, _SER_MAKE_PARAMS(src_t, __VA_ARGS__)>, #src_t " is not serializable: object contains padding"); \ template<> struct propane::serialization::is_packed<src_t> { static constexpr bool value = true; }; \ template<> struct propane::serialization::is_serializable<src_t> { static constexpr bool value = true; } #define SERIALIZABLE(src_t, ...) \ SERIALIZABLE_CHECK(src_t, __VA_ARGS__); \ template<> struct propane::serialization::serializer<src_t> \ { \ inline static void write(propane::block_writer& writer, const src_t& value) \ { \ writer.write_direct(value); \ } \ inline static void read(const void*& data, src_t& value) \ { \ value = *reinterpret_cast<const src_t*&>(data)++; \ } \ } #define SERIALIZABLE_PAIR(src_t, dst_t, ...) \ SERIALIZABLE_CHECK(dst_t, __VA_ARGS__); \ static_assert(propane::serialization::serializable_check_v<src_t, _SER_MAKE_PARAMS(src_t, __VA_ARGS__)>, #src_t " is not serializable: object contains members that are not serializable"); \ template<> struct propane::serialization::get_serializable_elements<src_t> { using type = propane::serialization::serializable_elements<_SER_MAKE_PARAMS(src_t, __VA_ARGS__)>; }; \ static_assert(propane::serialization::check_serialization_compatible_v<src_t, _SER_MAKE_PARAMS(dst_t, __VA_ARGS__)>, #dst_t " is not serializable: destination type is not compatible"); \ template<> struct propane::serialization::is_serializable<src_t> { static constexpr bool value = true; }; \ template<> struct propane::serialization::is_serialization_compatible<src_t, dst_t> { static constexpr bool value = true; }; \ template<> struct propane::serialization::serializer<src_t> \ { \ inline static void write(propane::block_writer& writer, const src_t& value) \ { \ propane::serialization::serialize_recursive<_SER_MAKE_PARAMS(src_t, __VA_ARGS__)>::write(writer, _SER_MAKE_FORWARD(value, __VA_ARGS__)); \ } \ inline static void read(const void*& data, src_t& value) \ { \ propane::serialization::serialize_recursive<_SER_MAKE_PARAMS(src_t, __VA_ARGS__)>::read(data, _SER_MAKE_FORWARD(value, __VA_ARGS__)); \ } \ inline static void read(const dst_t& data, src_t& value) \ { \ const void* ptr = &data; \ propane::serialization::serialize_recursive<_SER_MAKE_PARAMS(src_t, __VA_ARGS__)>::read(ptr, _SER_MAKE_FORWARD(value, __VA_ARGS__)); \ } \ } #define CUSTOM_SERIALIZER(src_t, dst_t) \ template<> struct propane::serialization::is_serializable<src_t> { static constexpr bool value = true; }; \ template<> struct propane::serialization::is_serialization_compatible<src_t, dst_t> { static constexpr bool value = true; }; \ template<> struct propane::serialization::serializer<src_t> #endif
51.591346
221
0.661169
[ "object", "vector" ]
e83f069ede5e6dfe084ccf6e3859749c1a600940
1,916
cpp
C++
TOI16/Programming TH/1015.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
TOI16/Programming TH/1015.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
TOI16/Programming TH/1015.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include<vector> using namespace std; int floadfill(int *v ,int x,int y,int prevc, int newc,int n) { if(x<0||y<0||x>=n||y>=n) return 0; if(*(v+x*n+y)!=prevc) return 0; int ans=0; if(*(v+x*n+y)!=0) { ans++; *(v+x*n+y)=newc; } else return 0; ans+=floadfill(v,x+1,y,prevc,newc,n); ans+=floadfill(v,x-1,y,prevc,newc,n); ans+=floadfill(v,x,y+1,prevc,newc,n); ans+=floadfill(v,x,y-1,prevc,newc,n); return ans; } bool check(int *v,int *v2,int x,int y,int newc,int n) { if(*(v+x*n+y)==0) return false; int temp=floadfill(v,x,y,*(v+x*n+y),newc,n); if(temp!=3) return false; if(*(v2+(x+1)*n+y)==*(v2+x*n+y)&&*(v2+x*n+(y+1))==*(v2+x*n+y)) return true; if(*(v2+(x-1)*n+y)==*(v2+x*n+y)&&*(v2+x*n+(y+1))==*(v2+x*n+y)) return true; if(*(v2+(x+1)*n+y)==*(v2+x*n+y)&&*(v2+x*n+(y-1))==*(v2+x*n+y)) return true; if(*(v2+(x-1)*n+y)==*(v2+x*n+y)&&*(v2+x*n+(y-1))==*(v2+x*n+y)) return true; if(*(v2+(x+1)*n+(y+1))==*(v2+x*n+y)&&*(v2+x*n+(y+1))==*(v2+x*n+y)) return true; if(*(v2+(x-1)*n+(y+1))==*(v2+x*n+y)&&*(v2+x*n+(y+1))==*(v2+x*n+y)) return true; if(*(v2+(x+1)*n+(y-1))==*(v2+x*n+y)&&*(v2+x*n+(y-1))==*(v2+x*n+y)) return true; if(*(v2+(x-1)*n+(y-1))==*(v2+x*n+y)&&*(v2+x*n+(y-1))==*(v2+x*n+y)) return true; if(*(v2+(x+1)*n+(y-1))==*(v2+x*n+y)&&*(v2+(x+1)*n+y)==*(v2+x*n+y)) return true; if(*(v2+(x+1)*n+(y+1))==*(v2+x*n+y)&&*(v2+(x+1)*n+y)==*(v2+x*n+y)) return true; if(*(v2+(x-1)*n+(y-1))==*(v2+x*n+y)&&*(v2+(x-1)*n+y)==*(v2+x*n+y)) return true; if(*(v2+(x-1)*n+(y+1))==*(v2+x*n+y)&&*(v2+(x-1)*n+y)==*(v2+x*n+y)) return true; return false; } main() { int n; cin>>n; int mat[n][n]; int mat2[n][n]; int *p,*p2; p=&mat[0][0]; p2=&mat2[0][0]; for(int i=0;i<n;i++) for(int j=0;j<n;j++) { cin>>mat[i][j]; mat2[i][j]=mat[i][j]; } int c=0; for(int i=0;i<n;i++) for(int j=0;j<n;j++) if(check(p,p2,i,j,0,n)) c++; cout<<c; }
24.253165
80
0.489562
[ "vector" ]
e842764a2f1e4bfda0faaa13e01d1b9ff9a758c9
1,093
cpp
C++
interview_questions/question2.cpp
perryizgr8/scratchpad
d7dbd65d53fd0936df6e9112b9468855b9c5089e
[ "MIT" ]
null
null
null
interview_questions/question2.cpp
perryizgr8/scratchpad
d7dbd65d53fd0936df6e9112b9468855b9c5089e
[ "MIT" ]
null
null
null
interview_questions/question2.cpp
perryizgr8/scratchpad
d7dbd65d53fd0936df6e9112b9468855b9c5089e
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <iostream> #include <fstream> #include <vector> int main() { int64_t num = 0, store = 0; std::vector <int> res; std::cin >> num; store = num; if (num == 0) { std::cout << -1; //std::cin >> num; //to wait return 0; } else if (num == 1) { std::cout << 1; //std::cin >> num; //to wait return 0; } while (num > 1) { if ((num % 9) == 0) { res.push_back(9); num = num / 9; } else if ((num % 8) == 0) { res.push_back(8); num = num / 8; } else if ((num % 7) == 0) { res.push_back(7); num = num / 7; } else if ((num % 6) == 0) { res.push_back(6); num = num / 6; } else if ((num % 5) == 0) { res.push_back(5); num = num / 5; } else if ((num % 4) == 0) { res.push_back(4); num = num / 4; } else if ((num % 3) == 0) { res.push_back(3); num = num / 3; } else if ((num % 2) == 0) { res.push_back(2); num = num / 2; } else { std::cout << -1; //std::cin >> num; //to wait return 0; } } std::cout << res.size(); //std::cin >> num; //to wait return 0; }
15.84058
31
0.467521
[ "vector" ]
e843fe67051c2d301b7725d108148f7887de416f
933
cpp
C++
codes/algorithms/strings/cpp/anagrams.cpp
shuvamkumar/first-pr-Hacktoberfest--2019
39a4c2e64fca58ea530263f9c4f50cbf55aaf883
[ "MIT" ]
8
2019-10-09T18:55:05.000Z
2020-09-18T05:44:00.000Z
codes/algorithms/strings/cpp/anagrams.cpp
shuvamkumar/first-pr-Hacktoberfest--2019
39a4c2e64fca58ea530263f9c4f50cbf55aaf883
[ "MIT" ]
2
2019-10-18T14:22:30.000Z
2020-09-30T08:36:36.000Z
codes/algorithms/strings/cpp/anagrams.cpp
shuvamkumar/first-pr-Hacktoberfest--2019
39a4c2e64fca58ea530263f9c4f50cbf55aaf883
[ "MIT" ]
55
2019-10-09T18:11:17.000Z
2021-02-01T18:06:20.000Z
#include <bits/stdc++.h> using namespace std; bool isAnagram(string a, string b) { sort(a.begin(),a.end()); sort(b.begin(),b.end()); if(a.compare(b)==0) return true; return false; } vector<int> findAnagrams(string arr[], int n) { vector<int> v; for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { if(isAnagram(arr[i], arr[j])) { v.push_back(i+1); v.push_back(j+1); cout<<arr[i]<<"-->"<<arr[j]<<endl; } } } for(int i=0;i<v.size();i++) cout<<v[i]<<endl; return v; } int main(int argc, char const *argv[]) { string arr[] = {"cat","dog","god","tca"}; int n = sizeof(arr)/sizeof(arr[0]); vector<int> ress = findAnagrams(arr, n); for(int i=0;i<ress.size()-1;i+=2) { cout<<"["<<ress[i]<<" "<<ress[i+1]<<"] "; } cout<<endl; return 0; }
20.733333
50
0.460879
[ "vector" ]
e845873fb0629ac25194048807bf94ebf0e09a17
6,130
cpp
C++
CLocalplayer.cpp
spyrothelegend/Mogelmodul-Recode
cc69b31489ba16e256e1227754989b874dfb8c95
[ "MIT" ]
1
2018-06-10T16:22:15.000Z
2018-06-10T16:22:15.000Z
CLocalplayer.cpp
spyrothelegend/Mogelmodul-Recode
cc69b31489ba16e256e1227754989b874dfb8c95
[ "MIT" ]
null
null
null
CLocalplayer.cpp
spyrothelegend/Mogelmodul-Recode
cc69b31489ba16e256e1227754989b874dfb8c95
[ "MIT" ]
null
null
null
#include "Includes.h" #include "CLocalplayer.h" #include <vector> #include <unordered_set> typedef struct { float x, y, z; }Vector; uint32_t CLocalplayer::getLocal() { return g_pMemory->Read< uint32_t >(g_pMemory->getClientAddress() + Offsets::signatures::dwLocalPlayer); } int CLocalplayer::getFlags() { return g_pMemory->Read< int >(this->getLocal() + Offsets::netvars::m_fFlags); } int CLocalplayer::getHealth() { return g_pMemory->Read< int >(this->getLocal() + Offsets::netvars::m_iHealth); } int CLocalplayer::getEntityHealth( int entity ) { return g_pMemory->Read< int >(entity + Offsets::netvars::m_iHealth); } void CLocalplayer::doJump() { g_pMemory->Write< int >(g_pMemory->getClientAddress() + Offsets::signatures::dwForceJump, 6); } int CLocalplayer::GetEngineState() { return g_pMemory->Read< int >(g_pMemory->getEngineAddress() + Offsets::signatures::dwClientState); } void CLocalplayer::doStrafe() { DWORD EngineState = GetEngineState(); static Vector prevViewAngle; Vector currentViewAngles = g_pMemory->Read<Vector>(EngineState + Offsets::signatures::dwClientState_ViewAngles); if (!(g_pLocalplayer->getFlags() & 1)) { if (currentViewAngles.y > prevViewAngle.y) { g_pMemory->Write< int >(g_pMemory->getClientAddress() + Offsets::signatures::dwForceLeft, 6); } else if (currentViewAngles.y < prevViewAngle.y) { g_pMemory->Write< int >(g_pMemory->getClientAddress() + Offsets::signatures::dwForceRight, 6); } prevViewAngle = currentViewAngles; } } //Radar-Start int CLocalplayer::CurrentPlayer() { return 0; } int CLocalplayer::CurrentPlayerDormant() { return g_pMemory->Read< int >(this->CurrentPlayer() + 0xE9); } int CLocalplayer::CurrentPlayerSpotted() { return g_pMemory->Read< int >(this->CurrentPlayer() + Offsets::netvars::m_bSpotted); } void CLocalplayer::doRadar() { return g_pMemory->Write< int >(this->CurrentPlayer() + Offsets::netvars::m_bSpotted, 1); } //Radar-Ende //Trigger-Start int CLocalplayer::LocalPlayerTeam() { return g_pMemory->Read< int >(this->getLocal() + Offsets::netvars::m_iTeamNum); } int CLocalplayer::GetEntityTeam(int entity) { return g_pMemory->Read< int >(entity + Offsets::netvars::m_iTeamNum); } int CLocalplayer::InCross() { return g_pMemory->Read< int >(this->getLocal() + Offsets::netvars::m_iCrosshairId); } int CLocalplayer::TriggerEntityBase() { return g_pMemory->Read< int >(g_pMemory->getClientAddress() + Offsets::signatures::dwEntityList + (this->InCross() - 1) * 16); } int CLocalplayer::TriggerEntityBaseTeamID() { return g_pMemory->Read< int >(this->TriggerEntityBase() + Offsets::netvars::m_iTeamNum); } int CLocalplayer::WeaponIndex() { return g_pMemory->Read< int >(this->getLocal() + Offsets::netvars::m_hActiveWeapon) & 0XFFF; } int CLocalplayer::WeaponEntity() { return g_pMemory->Read< int >(g_pMemory->getClientAddress() + Offsets::signatures::dwEntityList + (this->WeaponIndex() - 1) * 0x10); } int CLocalplayer::WeaponID() { return g_pMemory->Read< int >(this->WeaponEntity() + Offsets::netvars::m_iItemDefinitionIndex); } void CLocalplayer::Shoot() { mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); Sleep(2); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); } void CLocalplayer::Shoot2() { mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); Sleep(100); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); } //Trigger-Ende //NoFlash-Start float CLocalplayer::FlashMaxAlpha() { return g_pMemory->Read< float >(this->getLocal() + Offsets::netvars::m_flFlashMaxAlpha); } void CLocalplayer::notflashed() { g_pMemory->Write< float >(g_pLocalplayer->getLocal() + Offsets::netvars::m_flFlashMaxAlpha, 0.f); } //NoFlash-Ende //Glow std::uintptr_t CLocalplayer::getGlowObjectManager() const { return g_pMemory->Read< std::uintptr_t >(g_pMemory->getClientAddress() + Offsets::signatures::dwGlowObjectManager); } int CLocalplayer::getClientstate() { return g_pMemory->Read< int >(g_pMemory->getEngineAddress() + Offsets::signatures::dwClientState); } int CLocalplayer::getGamestate() { return g_pMemory->Read< int >(this->getClientstate() + Offsets::signatures::dwClientState_State); } int CLocalplayer::Shotsfired() { return g_pMemory->Read<int>(g_pLocalplayer->getLocal() + Offsets::netvars::m_iShotsFired); } std::unordered_set<int> pistol = { 1,2,3,4,30,32,36,61,63,64 }; std::unordered_set<int> rifles = { 7, 8, 10, 13, 14, 16, 60, 17, 19, 24, 26, 27, 28, 33, 34, 39 }; std::unordered_set<int> sniper = { 40,9,38,11 }; std::unordered_set<int> shotgun = { 35,25,39,27 }; int CLocalplayer::get_weapongroup(int i ) { if (pistol.find(i) != pistol.cend()) { return 1; } else if (rifles.find(i) != rifles.cend()) { return 2; } else if (sniper.find(i) != sniper.cend()) { return 3; } else if (shotgun.find(i) != shotgun.cend()) { return 4; } } bool CLocalplayer::fullload() { if (g_pLocalplayer->getGamestate() == SIGNONSTATE_FULL && g_pChecker->getActive() ) { return true; } else { return false; } } int CLocalplayer::gettickbase() { int tickbase = g_pMemory->Read<int>(g_pLocalplayer->getLocal() + Offsets::netvars::m_nTickBase); return tickbase; } uintptr_t CLocalplayer::baseglobalvars() { uintptr_t globalvars = g_pMemory->Read<uintptr_t>(g_pMemory->getEngineAddress() + Offsets::signatures::dwGlobalVars); return globalvars; } float CLocalplayer::intervalpertrick() { float intervalpertick = g_pMemory->Read<float>(g_pLocalplayer->baseglobalvars() + 32); return intervalpertick; } float CLocalplayer::getservertime() { float servertime = (g_pLocalplayer->gettickbase() + g_pLocalplayer->intervalpertrick()); return servertime; } float CLocalplayer::nextattack() { float nextattack = g_pMemory->Read<float>(g_pLocalplayer->getLocal() + Offsets::netvars::m_flNextPrimaryAttack); return nextattack; } CLocalplayer* g_pLocalplayer = new CLocalplayer();
23.396947
134
0.688091
[ "vector" ]
e84e4c5228c8d1091a456e3f4fe2206262480938
319
cpp
C++
MCommandCPP/MStd.cpp
Minamin1234/MCommandCPP
40fdd4650bc577154a9d91bfa22c3884287ce91e
[ "MIT" ]
null
null
null
MCommandCPP/MStd.cpp
Minamin1234/MCommandCPP
40fdd4650bc577154a9d91bfa22c3884287ce91e
[ "MIT" ]
1
2022-01-17T04:57:44.000Z
2022-01-17T07:00:00.000Z
MCommandCPP/MStd.cpp
Minamin1234/MCommandCPP
40fdd4650bc577154a9d91bfa22c3884287ce91e
[ "MIT" ]
null
null
null
#include "MStd.h" MStd::MStd() { this->ModuleName = "std"; this->Commands.push_back("print"); this->Commands.push_back("help"); } void MStd::ExecuteCommand(vector<string> args) { if (args[1] == this->Commands[0]) { cout << args[2] << endl; } else if (args[1] == this->Commands[1]) { this->ShowHelp(); } }
15.95
46
0.611285
[ "vector" ]
e85202f22f3f5a25c407084dbe0a798f681f7f80
6,200
cpp
C++
src/core/dummy/DummyCatalog.cpp
EricKTCheung/dmlite
7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d
[ "Apache-2.0" ]
null
null
null
src/core/dummy/DummyCatalog.cpp
EricKTCheung/dmlite
7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d
[ "Apache-2.0" ]
null
null
null
src/core/dummy/DummyCatalog.cpp
EricKTCheung/dmlite
7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d
[ "Apache-2.0" ]
null
null
null
/// @file core/dummy/DummyCatalog.cpp /// @brief DummyCatalog implementation. /// @details It makes sense as a base for other decorator plug-ins. /// @author Alejandro Álvarez Ayllón <aalvarez@cern.ch> #include <dmlite/cpp/dummy/DummyCatalog.h> using namespace dmlite; /// Little of help here to avoid redundancy #define DELEGATE(method, ...) \ if (this->decorated_ == NULL)\ throw DmException(DMLITE_SYSERR(ENOSYS), "There is no plugin in the stack that implements "#method);\ this->decorated_->method(__VA_ARGS__); /// Little of help here to avoid redundancy #define DELEGATE_RETURN(method, ...) \ if (this->decorated_ == NULL)\ throw DmException(DMLITE_SYSERR(ENOSYS), "There is no plugin in the stack that implements "#method);\ return this->decorated_->method(__VA_ARGS__); DummyCatalog::DummyCatalog(Catalog* decorated) throw (DmException) { this->decorated_ = decorated; } DummyCatalog::~DummyCatalog() { delete this->decorated_; } void DummyCatalog::setStackInstance(StackInstance* si) throw (DmException) { BaseInterface::setStackInstance(this->decorated_, si); } void DummyCatalog::setSecurityContext(const SecurityContext* ctx) throw (DmException) { BaseInterface::setSecurityContext(this->decorated_, ctx); } void DummyCatalog::changeDir(const std::string& path) throw (DmException) { DELEGATE(changeDir, path); } std::string DummyCatalog::getWorkingDir(void) throw (DmException) { DELEGATE_RETURN(getWorkingDir); } DmStatus DummyCatalog::extendedStat(ExtendedStat &xstat, const std::string& path, bool follow) throw (DmException) { DELEGATE_RETURN(extendedStat, xstat, path, follow); } ExtendedStat DummyCatalog::extendedStat(const std::string& path, bool follow) throw (DmException) { DELEGATE_RETURN(extendedStat, path, follow); } ExtendedStat DummyCatalog::extendedStatByRFN(const std::string& rfn) throw (DmException) { DELEGATE_RETURN(extendedStatByRFN, rfn); } bool DummyCatalog::access(const std::string& path, int mode) throw (DmException) { DELEGATE_RETURN(access, path, mode); } bool DummyCatalog::accessReplica(const std::string& replica, int mode) throw (DmException) { DELEGATE_RETURN(accessReplica, replica, mode); } void DummyCatalog::addReplica(const Replica& replica) throw (DmException) { DELEGATE(addReplica, replica); } void DummyCatalog::deleteReplica(const Replica& replica) throw (DmException) { DELEGATE(deleteReplica, replica); } std::vector<Replica> DummyCatalog::getReplicas(const std::string& path) throw (DmException) { DELEGATE_RETURN(getReplicas, path); } void DummyCatalog::symlink(const std::string& oldpath, const std::string& newpath) throw (DmException) { DELEGATE(symlink, oldpath, newpath); } std::string DummyCatalog::readLink(const std::string& path) throw (DmException) { DELEGATE_RETURN(readLink, path); } void DummyCatalog::unlink(const std::string& path) throw (DmException) { DELEGATE(unlink, path); } void DummyCatalog::create(const std::string& path, mode_t mode) throw (DmException) { DELEGATE(create, path, mode); } mode_t DummyCatalog::umask(mode_t mask) throw () { DELEGATE_RETURN(umask, mask); } void DummyCatalog::setMode(const std::string& path, mode_t mode) throw (DmException) { DELEGATE(setMode, path, mode); } void DummyCatalog::setOwner(const std::string& path, uid_t newUid, gid_t newGid, bool fs) throw (DmException) { DELEGATE(setOwner, path, newUid, newGid, fs); } void DummyCatalog::setSize(const std::string& path, size_t newSize) throw (DmException) { DELEGATE(setSize, path, newSize); } void DummyCatalog::setChecksum(const std::string& path, const std::string& csumtype, const std::string& csumvalue) throw (DmException) { DELEGATE(setChecksum, path, csumtype, csumvalue); } void DummyCatalog::getChecksum(const std::string& path, const std::string& csumtype, std::string& csumvalue, const std::string& pfn, const bool forcerecalc, const int waitsecs) throw (DmException) { DELEGATE(getChecksum, path, csumtype, csumvalue, pfn, forcerecalc, waitsecs); } void DummyCatalog::setAcl(const std::string& path, const Acl& acls) throw (DmException) { DELEGATE(setAcl, path, acls); } void DummyCatalog::utime(const std::string& path, const struct utimbuf* buf) throw (DmException) { DELEGATE(utime, path, buf); } std::string DummyCatalog::getComment(const std::string& path) throw (DmException) { DELEGATE_RETURN(getComment, path); } void DummyCatalog::setComment(const std::string& path, const std::string& comment) throw (DmException) { DELEGATE(setComment, path, comment); } void DummyCatalog::setGuid(const std::string& path, const std::string& guid) throw (DmException) { DELEGATE(setGuid, path, guid); } void DummyCatalog::updateExtendedAttributes(const std::string& path, const Extensible& attr) throw (DmException) { DELEGATE(updateExtendedAttributes, path, attr); } Directory* DummyCatalog::openDir(const std::string& path) throw (DmException) { DELEGATE_RETURN(openDir, path); } void DummyCatalog::closeDir(Directory* dir) throw (DmException) { DELEGATE(closeDir, dir); } struct dirent* DummyCatalog::readDir(Directory* dir) throw (DmException) { DELEGATE_RETURN(readDir, dir); } ExtendedStat* DummyCatalog::readDirx(Directory* dir) throw (DmException) { DELEGATE_RETURN(readDirx, dir); } void DummyCatalog::makeDir(const std::string& path, mode_t mode) throw (DmException) { DELEGATE(makeDir, path, mode); } void DummyCatalog::rename(const std::string& oldPath, const std::string& newPath) throw (DmException) { DELEGATE(rename, oldPath, newPath); } void DummyCatalog::removeDir(const std::string& path) throw (DmException) { DELEGATE(removeDir, path); } Replica DummyCatalog::getReplicaByRFN(const std::string& rfn) throw (DmException) { DELEGATE_RETURN(getReplicaByRFN, rfn); } void DummyCatalog::updateReplica(const Replica& replica) throw (DmException) { DELEGATE(updateReplica, replica); }
20.805369
114
0.719032
[ "vector" ]
e8598873bd577dd202551133df374f30c060046b
4,435
cpp
C++
src/db/redisdb/client/RedisMng.cpp
yuanmartin/ubiquitous-perception
1f9ca8947523e71259c9736eed7c62c525eb77d8
[ "MulanPSL-1.0" ]
null
null
null
src/db/redisdb/client/RedisMng.cpp
yuanmartin/ubiquitous-perception
1f9ca8947523e71259c9736eed7c62c525eb77d8
[ "MulanPSL-1.0" ]
null
null
null
src/db/redisdb/client/RedisMng.cpp
yuanmartin/ubiquitous-perception
1f9ca8947523e71259c9736eed7c62c525eb77d8
[ "MulanPSL-1.0" ]
null
null
null
#include "RedisMng.h" #include "log4cxx/Loging.h" using namespace std; using namespace REDIS_DB; using namespace common_cmmobj; using namespace common_template; const int s32MaxDefaultConnections = 20; const int s32InitDefaultConnections = 10; const int nDefaultRedisPort = 47393; const string strDefaultRedisIp = "127.0.0.1"; const string strDefaultRedisPwd = ""; const int s32RedisDefaultConnTimeOut = 2; const int s32RedisDefaultRWTimeout = 5; extern "C" bool IF_REDIS::RedisInit(const string& strRdIp, const string& strRdPwd, int s32RdPort, int s32RdConnTimeout, int s32RdRWTimeout, int maxConnections, int initConnections) { return SRedisMng.Init(strRdIp, strRdPwd, s32RdPort, s32RdConnTimeout, s32RdRWTimeout, maxConnections, initConnections); } extern "C" bool IF_REDIS::RedisSaveData(const std::string& strKey, const std::string& strData) { bool bLongConn = true; Redis* pRedis = SRedisMng.Get(bLongConn); if (!pRedis) { return false; } int s32Ret = pRedis->rpush_list(strKey, strData.c_str()); SRedisMng.Put(pRedis, bLongConn); return (0 == s32Ret) ? true : false; } extern "C" void IF_REDIS::RedisReadData(const std::string& strKey, std::vector<std::string>& vecData) { bool bLongConn = true; Redis* pRedis = SRedisMng.Get(bLongConn); if (!pRedis) { return; } pRedis->lrange_list(strKey, vecData); SRedisMng.Put(pRedis, bLongConn); } extern "C" void IF_REDIS::RedisDelData(const std::string& strKey) { bool bLongConn = true; Redis* pRedis = SRedisMng.Get(bLongConn); if (!pRedis) { return; } pRedis->del_list(strKey); SRedisMng.Put(pRedis, bLongConn); } RedisMng::RedisMng() : m_maxConnections(0), m_currentConnections(0) { } RedisMng::~RedisMng() { delete[]m_connections; delete[]m_is_free; } Redis * RedisMng::newConnection(bool& bLongConn) { Redis *redis = new Redis(); redis->Init(m_strRedisIp, m_strRedisPwd, m_s32RedisPort, m_s32RedisConnectTimeout, m_s32RedisRWTimeout); if (!redis->connect()) { delete redis; redis = NULL; return NULL; } //only creat short connect when the current connections > maxconnections if (m_currentConnections >= m_maxConnections) { LOG_WARN("db_redis") << string_format("RedisMng: connection exceed max connection count %d��", m_maxConnections); bLongConn = false; return redis; } m_connections[m_currentConnections] = redis; m_is_free[m_currentConnections] = true; redis->setPoolIndex(m_currentConnections); m_currentConnections++; bLongConn = true; return redis; } bool RedisMng::Init(const string& strRdIp, const string& strRdPwd, int s32RdPort, int s32RdConnTimeout, int s32RdRWTimeout, int maxConnections, int initConnections) { //������������ m_strRedisIp = (strRdIp.empty()) ? strDefaultRedisIp : strRdIp; m_strRedisPwd = (strRdPwd.empty()) ? strDefaultRedisPwd : strRdPwd; m_s32RedisPort = (0 >= s32RdPort) ? nDefaultRedisPort : s32RdPort; m_s32RedisConnectTimeout = (0 >= s32RdConnTimeout) ? s32RedisDefaultConnTimeOut : s32RdConnTimeout; m_s32RedisRWTimeout = (0 >= s32RdRWTimeout) ? s32RedisDefaultRWTimeout : s32RdRWTimeout; if (initConnections > maxConnections) { LOG_WARN("db_redis") << string_format("redis maxConnections(%d) < initConnections(%d)\n", maxConnections, initConnections); maxConnections = initConnections; } m_maxConnections = 0 < maxConnections ? maxConnections : s32MaxDefaultConnections; //creat Redis obj array m_connections = new Redis*[m_maxConnections](); m_is_free = new bool[m_maxConnections](); for (int i = 0; i < m_maxConnections; i++) { m_connections[i] = nullptr; m_is_free[i] = true; } return true; } Redis * RedisMng::Get(bool& bLongConn) { Redis *redis = NULL; CLock lock(&m_mutex_of_connection); for (int i = 0; i < m_currentConnections; i++) { if (m_is_free[i]) { m_is_free[i] = false; redis = m_connections[i]; bLongConn = true; return redis; } } if (!redis) { redis = newConnection(bLongConn); } return redis; } void RedisMng::Put(Redis * redis, bool bLongConn) { if (!redis) { return; } //release short connect and redis if (!bLongConn) { delete redis; redis = NULL; return; } //put redis to pool CLock lock(&m_mutex_of_connection); int s32ConnIndex = redis->getPoolIndex(); m_is_free[s32ConnIndex] = true; }
25.635838
181
0.703269
[ "vector" ]
e8736a8ef6bf2081c4041ccbc22c165960f749b1
3,244
cpp
C++
ecs/src/main.cpp
Xikeb/elSandbox
f0d2474672016a87aae9720b6ee9346904f21cd2
[ "MIT" ]
null
null
null
ecs/src/main.cpp
Xikeb/elSandbox
f0d2474672016a87aae9720b6ee9346904f21cd2
[ "MIT" ]
null
null
null
ecs/src/main.cpp
Xikeb/elSandbox
f0d2474672016a87aae9720b6ee9346904f21cd2
[ "MIT" ]
null
null
null
#include "Manager.hpp" #include "Entity.hpp" #include "el/detail/pretty_print.hpp" #include <iostream> #include <string> #include <type_traits> #include <chrono> using namespace std; using namespace std::chrono; #include "Scheduler.hpp" namespace test { struct Vector2i { Vector2i(int x = 0, int y = 0): x(x), y(y) {} int x; int y; }; struct Vector3i { Vector3i(int x = 0, int y = 0, int z = 0): x(x), y(y), z(z) {} int x; int y; int z; }; struct Vector2f { Vector2f(float x = 0, float y = 0): x(x), y(y) {} float x; float y; }; struct Vector3f { Vector3f(float x = 0, float y = 0, float z = 0): x(x), y(y), z(z) {} float x; float y; float z; }; struct Transform { Vector2f pos; Vector2f rot; Vector2f sca; }; union Color { char rgba[4]; int col; }; struct Drawable { Color col; float depth; }; struct Inverted; using Components = ecs::ComponentList< Vector2f, Vector3f, Vector2i, Vector3i, std::string, Transform, Color, Drawable >; using Tags = ecs::TagList<Inverted>; using Settings = ecs::Settings<Components, Tags>; using HasString = ecs::Signature<Settings::Basic, std::string>; } // test using namespace test; #include "System.hpp" #include "SystemSpecs.hpp" namespace sys { constexpr auto printCallback = [](auto &e, auto &count) { std::cout << '\t'; if (e.template hasComponent<std::string>()) std::cout << e.template getComponent<std::string>(); else std::cout << "No std::string component!"; std::cout << std::endl; ++count; }; auto print = ecs::SystemSpecs{printCallback} .template instantiateWith<int>() .after(el::type_c<el::type_list<>>) .matching(el::type_c<test::HasString>)() ; } // sys int main() { cout << boolalpha; using Manager = ecs::Manager<test::Settings>; Manager mgr; cout << "Tags:\t"; el::detail::pretty_print(el::type_c<Manager::Settings::TagList>); cout << endl; cout << "IsTag: " << Manager::isTag<test::Inverted> << endl; cout << endl; //pretty_print(Manager::componentId<Transform>); for (int i = 0; i < 100; ++i) { auto e = mgr.createEntity(); e.template addComponent<Vector2f>(5, 5); e.template addTag<Inverted>(); e.template addComponent<std::string>("Hello"); if (i % 2 == 0) e.template removeComponent<Vector2f>(); if (i % 3 == 0) e.template removeTag<Inverted>(); } mgr.forEntitiesMatching(HasString(), [](auto &e) { e.template getComponent<std::string>() += " World!"; }); std::size_t idx = 0; mgr.forEntities([&](auto &e, size_t &idx) { e.template removeTag<Inverted>(); if (idx % 2 == 1) e.kill(); ++idx; }, idx); mgr.forEntitiesMatching(HasString(), [&](auto &e, std::string const &) { // cout << intro << ": " << e.template getComponent<std::string>() << endl; cout << e.template hasComponent<Vector2f>() << " " << e.template hasTag<Inverted>() << " " << e.template getComponent<std::string>() << "(" << "inPhase: " << e.isInPhase() << ", valid: " << e.isValid() << ")" << endl; }, "I say"); cout << endl << "Print system launch: " << endl; sys::print(mgr); cout << "Printing system has worked on [" << sys::print.image() << "] entities" << endl; // cout << "Trivially constructible:"; return 0; }
22.685315
89
0.616215
[ "transform" ]
e8781e79c162b61e243d1193b359837f98b95950
1,107
cpp
C++
Codeforces/CF1611F.cpp
Nickel-Angel/Coding-Practice
6fb70e9c9542323f82a9a8714727cc668ff58567
[ "MIT" ]
null
null
null
Codeforces/CF1611F.cpp
Nickel-Angel/Coding-Practice
6fb70e9c9542323f82a9a8714727cc668ff58567
[ "MIT" ]
1
2021-11-18T15:10:29.000Z
2021-11-20T07:13:31.000Z
Codeforces/CF1611F.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
/* * @author Nickel_Angel (1239004072@qq.com) * @copyright Copyright (c) 2021 */ #include <algorithm> #include <cmath> #include <cstdio> #include <cstring> #include <vector> typedef long long ll; using std::min; using std::max; using std::sort; using std::swap; const int maxn = 2e5 + 10; int n, s, a[maxn]; int q[maxn], l, r, L, R; inline void solve() { scanf("%d%d", &n, &s); for (int i = 1; i <= n; ++i) scanf("%d", a + i); L = 1, R = 0; ll sum = 0; int ans = 0; for (int i = 1; i <= n; ++i) { while (L <= R && sum + s < 0) { sum -= a[q[L]]; ++L; } if (sum + s >= 0 && ans < R - L + 1) { ans = R - L + 1; l = q[L], r = q[R]; } q[++R] = i; sum += a[i]; } if (sum + s >= 0 && ans < R - L + 1) { ans = R - L + 1; l = q[L], r = q[R]; } if (!ans) { puts("-1"); return; } printf("%d %d\n", l, r); } int main() { int t; scanf("%d", &t); while (t--) solve(); return 0; }
16.772727
44
0.394761
[ "vector" ]
e8790bf6b52ebfaebb1d95124a5c2a4bd522ae1d
3,921
cc
C++
code/qttoolkit/nody/shady/code/project/shadyproject.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/qttoolkit/nody/shady/code/project/shadyproject.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/qttoolkit/nody/shady/code/project/shadyproject.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // shadyproject.cc // (C) 2015-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "shadyproject.h" #include "scene/nodescene.h" #include "node/shadynode.h" #include "variation/variationdatabase.h" #include "scene/graphics/nodegraphicssceneview.h" using namespace Nody; namespace Shady { __ImplementClass(Shady::ShadyProject, 'SPRO', Nody::Project); __ImplementSingleton(Shady::ShadyProject); //------------------------------------------------------------------------------ /** */ ShadyProject::ShadyProject() { __ConstructSingleton; } //------------------------------------------------------------------------------ /** */ ShadyProject::~ShadyProject() { __DestructSingleton } //------------------------------------------------------------------------------ /** */ void ShadyProject::Apply(const Ptr<NodeScene>& scene) { n_assert(scene.isvalid()); // clear scene scene->Clear(); // make temporary dictionary of nodes Util::Dictionary<Util::Guid, Ptr<ShadyNode>> nodeMap; // setup nodes IndexT i; for (i = 0; i < this->nodes.Size(); i++) { Ptr<ShadyNode> node = ShadyNode::Create();; const NodeState& state = this->nodes[i]; nodeMap.Add(state.id, node); // setup node if (state.superNode) { const Ptr<SuperVariation>& var = VariationDatabase::Instance()->GetSuperVariationByName(state.variation); node->Setup(var); } else { const Ptr<Variation>& var = VariationDatabase::Instance()->GetVariationByName(state.variation); node->Setup(var); } // add node to scene scene->AddNode(node.upcast<Nody::Node>()); // setup node values IndexT j; for (j = 0; j < state.values.Size(); j++) { node->SetValue(state.values.KeyAtIndex(j), state.values.ValueAtIndex(j)); } // set position now when we have a graphical representation node->GetGraphics()->SetPosition(state.pos); } // setup links for (i = 0; i < this->links.Size(); i++) { const LinkState& state = this->links[i]; // get nodes const Ptr<ShadyNode>& from = nodeMap[state.from]; const Ptr<ShadyNode>& to = nodeMap[state.to]; const Ptr<VariableInstance>& var1 = from->GetVariation()->GetOutput(state.fromName); Ptr<VariableInstance> var2; if (to->IsSuperNode()) var2 = to->GetSuperVariation()->GetInput(state.toName); else var2 = to->GetVariation()->GetInput(state.toName); // create link in scene, this is slightly ugly since the previous link object is really not necessary... scene->CreateLink(var1, var2); } NodeGraphicsSceneView* view = static_cast<NodeGraphicsSceneView*>(scene->GetNodeSceneGraphics()->views()[0]); QPointF center; center.setX(this->globalState.viewCenter.x()); center.setY(this->globalState.viewCenter.y()); view->SetOrigin(center); // clear project when we have applied, just to save memory this->Clear(); } //------------------------------------------------------------------------------ /** */ void ShadyProject::Store(const Ptr<NodeScene>& scene) { n_assert(scene.isvalid()); // clear project first this->Clear(); // get nodes and save to project const Util::Array<Ptr<Node>>& nodes = scene->GetNodes(); IndexT i; for (i = 0; i < nodes.Size(); i++) { const Ptr<Node>& node = nodes[i]; this->AddNode(node); } const Util::Array<Ptr<Link>>& links = scene->GetLinks(); for (i = 0; i < links.Size(); i++) { const Ptr<Link>& link = links[i]; this->AddLink(link); } } } // namespace Shady
28.413043
117
0.541954
[ "object" ]
e87d576f6f56f54aeb8bc31641e1e513cadbb4e0
2,625
hpp
C++
batch-testing/BatchEnvironment.hpp
iauns/cpm-gl-batch-testing
fc60f90cf98159d8d0e77d928b038162e7a4ef93
[ "MIT" ]
1
2016-04-06T00:18:28.000Z
2016-04-06T00:18:28.000Z
batch-testing/BatchEnvironment.hpp
iauns/cpm-gl-batch-testing
fc60f90cf98159d8d0e77d928b038162e7a4ef93
[ "MIT" ]
null
null
null
batch-testing/BatchEnvironment.hpp
iauns/cpm-gl-batch-testing
fc60f90cf98159d8d0e77d928b038162e7a4ef93
[ "MIT" ]
null
null
null
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2013 Scientific Computing and Imaging Institute, University of Utah. 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. */ /// \author James Hughes /// \date November 2013 #ifndef IAUNS_GL_BATCH_ENVIRONMENT_HPP #define IAUNS_GL_BATCH_ENVIRONMENT_HPP #include <stdint.h> #include <string> #include <vector> #include <memory> #include "gl-platform/GLPlatform.hpp" namespace CPM_GL_BATCH_CONTEXT_NS { class Context; } namespace CPM_GL_BATCH_TESTING_NS { /// OpenGL batch rendering environment. class BatchEnvironment { public: BatchEnvironment(uint32_t width, uint32_t height, int32_t colorBits, int32_t depthBits, int32_t stencilBits, bool doubleBuffer, bool visible); virtual ~BatchEnvironment(); /// Writes a PNG file of the current FBO state. void writeFBO(const std::string& file); int getScreenWidth(); int getScreenHeight(); // We really want an interface definition here (really want BatchEnvironment's // type to conform to some idea of what a context is). void makeCurrent(); void swapBuffers(); private: int mWidth; int mHeight; /// We aren't supporting c++11, so we don't use a shared ptr here. std::shared_ptr<CPM_GL_BATCH_CONTEXT_NS::Context> mContext; /// Pre-allocated image data. The memory we use to pull image data /// from OpenGL. std::vector<uint8_t> mRawImage; GLuint mGLFrameBuffer; GLuint mGLColorTexture; GLuint mGLDepthBuffer; }; } // namespace CPM_GL_BATCH_ENV_NS #endif
29.829545
80
0.744381
[ "vector" ]
e88efa117ecd2dea247b3bc806cbfb0b7bc43848
35,673
cc
C++
src/enc/partitioner.cc
RReverser/libwebp2
c90b5b476004c9a98731ae1c175cebab5de50fbf
[ "Apache-2.0" ]
4
2020-11-10T17:46:57.000Z
2022-03-22T06:24:17.000Z
src/enc/partitioner.cc
RReverser/libwebp2
c90b5b476004c9a98731ae1c175cebab5de50fbf
[ "Apache-2.0" ]
null
null
null
src/enc/partitioner.cc
RReverser/libwebp2
c90b5b476004c9a98731ae1c175cebab5de50fbf
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // ----------------------------------------------------------------------------- // // Tool for finding the best block layout. // // Author: Yannis Guyon (yguyon@google.com) #include "src/enc/partitioner.h" #include <algorithm> #include <numeric> #include "src/common/lossy/block_size.h" #include "src/common/lossy/block_size_io.h" #include "src/enc/analysis.h" #include "src/utils/utils.h" #include "src/wp2/base.h" namespace WP2 { //------------------------------------------------------------------------------ WP2Status Partitioner::Init(const EncoderConfig& config, const YUVPlane& yuv, const Rectangle& tile_rect, PartitionScoreFunc* const score_func) { config_ = &config; tile_rect_ = tile_rect; src_ = &yuv; num_block_cols_ = SizeBlocks(yuv.Y.w_); num_block_rows_ = SizeBlocks(yuv.Y.h_); score_func_ = score_func; WP2_CHECK_ALLOC_OK(occupancy_.resize(num_block_cols_ * num_block_rows_)); return WP2_STATUS_OK; } bool Partitioner::IsOccupied(const Block& block) const { const uint32_t stride = num_block_cols_; const bool* occupancy = occupancy_.data() + block.y() * stride + block.x(); for (uint32_t y = 0; y < block.h(); ++y) { for (uint32_t x = 0; x < block.w(); ++x) { if (occupancy[x]) return true; } occupancy += num_block_cols_; } return false; } void Partitioner::Occupy(const Block& block) { const uint32_t stride = num_block_cols_; bool* occupancy = occupancy_.data() + block.y() * stride + block.x(); for (uint32_t y = 0; y < block.h(); ++y) { for (uint32_t x = 0; x < block.w(); ++x) occupancy[x] = true; occupancy += num_block_cols_; } } bool Partitioner::IsBlockValid(const Block& block, const Block& max_block, size_t num_forced_blocks) const { if (block.w() > max_block.w()) return false; if (block.h() > max_block.h()) return false; // Thanks to the FrontMgrLexico, this 'block' can only be rejected // because of other forced blocks or forced snapping. if (config_->partition_snapping && !block.IsSnapped()) return false; if (num_forced_blocks > 0) return !IsOccupied(block); assert(!IsOccupied(block)); return true; } //------------------------------------------------------------------------------ WP2Status AddForcedBlocks(const EncoderConfig& config, const Rectangle& padded_tile_rect, VectorNoCtor<Block>* const out) { if (config.info == nullptr) return WP2_STATUS_OK; for (const Rectangle& rect_px : config.info->force_partition) { if (rect_px.x < padded_tile_rect.x || rect_px.y < padded_tile_rect.y) { continue; // Ignore this block, it's outside of this tile. } const Rectangle local_rect = {rect_px.x - padded_tile_rect.x, rect_px.y - padded_tile_rect.y, rect_px.width, rect_px.height}; if (local_rect.x >= padded_tile_rect.width || local_rect.y >= padded_tile_rect.height) { continue; // Ignore this block, it's outside of this tile. } WP2_CHECK_OK((local_rect.x + local_rect.width <= padded_tile_rect.width && local_rect.y + local_rect.height <= padded_tile_rect.height), WP2_STATUS_INVALID_CONFIGURATION); WP2::BlockSize matching_size = BLK_LAST; for (const BlockSize* size = GetBlockSizes(config.partition_set); *size != BLK_LAST; ++size) { if (local_rect.width == WP2::BlockWidthPix(*size) && local_rect.height == WP2::BlockHeightPix(*size)) { matching_size = *size; break; } } WP2_CHECK_OK(matching_size != BLK_LAST, WP2_STATUS_INVALID_CONFIGURATION); // Create a Block that matches the rectangle. Block block(local_rect.x / kMinBlockSizePix, local_rect.y / kMinBlockSizePix, matching_size); assert(local_rect.width == block.w_pix() && local_rect.height == block.h_pix()); // Verify that position coordinates are aligned on the block grid (multiples // of kMinBlockSizePix). Width and height are checked and asserted above. WP2_CHECK_OK(local_rect.x == block.x_pix() && local_rect.y == block.y_pix(), WP2_STATUS_INVALID_CONFIGURATION); // No IsSnapped() check, trust the user's intention on that. WP2_CHECK_ALLOC_OK(out->push_back(block)); } return WP2_STATUS_OK; } WP2Status Partitioner::RegisterForcedBlocks( const VectorNoCtor<Block>& forced_blocks, uint32_t* const max_num_blocks_left) { for (const Block& block : forced_blocks) { WP2_CHECK_OK(!IsOccupied(block), WP2_STATUS_INVALID_CONFIGURATION); Occupy(block); assert(*max_num_blocks_left >= block.w() * block.h()); *max_num_blocks_left -= block.w() * block.h(); } return WP2_STATUS_OK; } //------------------------------------------------------------------------------ WP2Status TopLeftBestPartitioner::GetBestPartition( VectorNoCtor<Block>* const blocks) { std::fill(occupancy_.begin(), occupancy_.end(), false); const uint32_t max_num_blocks = num_block_cols_ * num_block_rows_; uint32_t max_num_blocks_left = max_num_blocks; // Begin with the user-defined blocks, if any (debug). WP2_CHECK_STATUS(RegisterForcedBlocks(*blocks, &max_num_blocks_left)); // Sort forced blocks by position for binary search below. VectorNoCtor<Block> forced_blocks; WP2_CHECK_ALLOC_OK(forced_blocks.resize(blocks->size())); std::copy(blocks->begin(), blocks->end(), forced_blocks.begin()); std::sort(forced_blocks.begin(), forced_blocks.end()); // Use a front manager to easily browse the blocks. FrontMgrLexico front_mgr; WP2_CHECK_STATUS(front_mgr.Init(config_->partition_set, config_->partition_snapping, src_->Y.w_, src_->Y.h_)); while (!front_mgr.Done()) { // TODO(yguyon): This is using a top-most first order. Find an order that // maximizes top and left context instead. const Block max_block = front_mgr.GetMaxFittingBlock(); // Binary search to find if 'max_block' is already one of the forced blocks. const auto forced_block_it = std::lower_bound(forced_blocks.begin(), forced_blocks.end(), max_block); Block best_block; if (forced_block_it != forced_blocks.end() && forced_block_it->x() == max_block.x() && forced_block_it->y() == max_block.y()) { best_block = *forced_block_it; } else { assert(max_num_blocks_left > 0); WP2_CHECK_STATUS( GetBestSize(max_block, forced_blocks.size(), &best_block)); RegisterOrderForVDebug(0, 0, best_block, blocks->size(), max_num_blocks); WP2_CHECK_ALLOC_OK(blocks->push_back(best_block)); // The following instructions are done only for assertions/debug // because the front manager should handle everything, except for // the forced blocks but these are checked above. assert((Occupy(best_block), true)); assert(max_num_blocks_left >= best_block.w() * best_block.h()); max_num_blocks_left -= best_block.w() * best_block.h(); } assert(best_block.dim() != BLK_LAST); WP2_CHECK_ALLOC_OK(front_mgr.UseSize(best_block.dim(), /*ind=*/0u, nullptr)); front_mgr.Use(best_block); WP2_CHECK_STATUS(score_func_->Use(best_block)); } assert(max_num_blocks_left == 0); return WP2_STATUS_OK; } WP2Status TopLeftBestPartitioner::GetBestSize(const Block& max_block, size_t num_forced_blocks, Block* const best_block) { const BlockSize* const sizes = GetBlockSizes(config_->partition_set); float best_score = 0.f; // Test each size and keep the best score. for (const BlockSize* size = sizes; *size != BLK_LAST; ++size) { const Block block = Block(max_block.x(), max_block.y(), *size); if (IsBlockValid(block, max_block, num_forced_blocks)) { float score; WP2_CHECK_STATUS(score_func_->GetScore(block, &score)); const bool first_score = (size == sizes); // Increasing sizes: keep the largest one if same score (rare). if (first_score || score >= best_score) { best_score = score; *best_block = block; } } } return WP2_STATUS_OK; } //------------------------------------------------------------------------------ WP2Status AreaRDOptPartitioner::GetBestPartition( VectorNoCtor<Block>* const blocks) { std::fill(occupancy_.begin(), occupancy_.end(), false); uint32_t max_num_blocks_left = num_block_cols_ * num_block_rows_; // TODO(yguyon): Handle forced blocks WP2_CHECK_OK(blocks->empty(), WP2_STATUS_UNSUPPORTED_FEATURE); for (uint32_t area_y = 0; area_y < src_->Y.h_; area_y += area_height_) { for (uint32_t area_x = 0; area_x < src_->Y.w_; area_x += area_width_) { const Rectangle area = Rectangle(area_x, area_y, area_width_, area_height_) .ClipWith({0, 0, src_->Y.w_, src_->Y.h_}); // Padded. WP2_CHECK_STATUS( GetAreaBestPartition(area, blocks, &max_num_blocks_left)); } } assert(max_num_blocks_left == 0); return WP2_STATUS_OK; } WP2Status AreaRDOptPartitioner::GetAreaBestPartition( const Rectangle& area, VectorNoCtor<Block>* const blocks, uint32_t* const max_num_blocks_left) { AreaScoreFunc* const score_func = reinterpret_cast<AreaScoreFunc*>(score_func_); assert(area.x == score_func->GetCurrentArea().x && area.y == score_func->GetCurrentArea().y); VectorNoCtor<Block> area_blocks, area_best_blocks; // Start with the default partition as a reference score. float best_score; WP2_CHECK_STATUS( score_func->GetAreaDefaultScore(&area_best_blocks, &best_score)); // Test a uniform block grid for each block size and keep the best score. for (const BlockSize* size = GetBlockSizes(config_->partition_set); *size != BLK_LAST; ++size) { if (BlockWidthPix(*size) <= area.width && BlockHeightPix(*size) <= area.height) { area_blocks.clear(); float score; WP2_CHECK_STATUS( score_func->GetAreaGridScore(*size, &area_blocks, &score)); if (score > best_score) { best_score = score; WP2_CHECK_ALLOC_OK(area_best_blocks.resize(area_blocks.size())); std::copy(area_blocks.begin(), area_blocks.end(), area_best_blocks.begin()); } } } // Mark each block of the best partition as final. for (const Block& block : area_best_blocks) { assert(*max_num_blocks_left > 0); *max_num_blocks_left -= block.rect().GetArea(); WP2_CHECK_ALLOC_OK(blocks->push_back(block)); WP2_CHECK_STATUS(score_func_->Use(block)); } return WP2_STATUS_OK; } //------------------------------------------------------------------------------ WP2Status SubAreaRDOptPartitioner::GetBestPartition( VectorNoCtor<Block>* const blocks) { WP2_CHECK_STATUS(front_mgr_.Init(config_->partition_set, config_->partition_snapping, tile_rect_.width, tile_rect_.height)); return AreaRDOptPartitioner::GetBestPartition(blocks); } WP2Status SubAreaRDOptPartitioner::GetAreaBestPartition( const Rectangle& area, VectorNoCtor<Block>* const blocks, uint32_t* const max_num_blocks_left) { const uint32_t max_num_blocks = num_block_cols_ * num_block_rows_; assert(area.x == front_mgr_.GetMaxPossibleBlock().x_pix() && area.y == front_mgr_.GetMaxPossibleBlock().y_pix()); while (!front_mgr_.Done()) { const Block max_block = front_mgr_.GetMaxPossibleBlock(); // Exit the loop when the 'area' is complete. if (!area.Contains(max_block.x_pix(), max_block.y_pix())) break; assert(*max_num_blocks_left > 0); Block best_block; float best_score = std::numeric_limits<float>::lowest(); const BlockSize* const sizes = GetBlockSizes(config_->partition_set); for (const BlockSize* size = sizes; *size != BLK_LAST; ++size) { const Block block = Block(max_block.x(), max_block.y(), *size); if (block.w() <= max_block.w() && block.h() <= max_block.h()) { float score; WP2_CHECK_STATUS(score_func_->GetScore(block, &score)); if (score >= best_score) { best_score = score; best_block = block; } } } const uint32_t block_index = max_num_blocks - *max_num_blocks_left; RegisterOrderForVDebug(0, 0, best_block, block_index, max_num_blocks); *max_num_blocks_left -= best_block.rect().GetArea(); WP2_CHECK_ALLOC_OK(blocks->push_back(best_block)); WP2_CHECK_ALLOC_OK(front_mgr_.UseSize(best_block.dim(), 0u, nullptr)); front_mgr_.Use(best_block); WP2_CHECK_STATUS(score_func_->Use(best_block)); } return WP2_STATUS_OK; } //------------------------------------------------------------------------------ constexpr SplitRecursePartitioner::SplitInfo SplitRecursePartitioner::kNoSplitInfo; WP2Status SplitRecursePartitioner::Init(const EncoderConfig& config, const YUVPlane& yuv, const Rectangle& tile_rect, PartitionScoreFunc* const score_func) { WP2_CHECK_STATUS(Partitioner::Init(config, yuv, tile_rect, score_func)); WP2_CHECK_STATUS(split_info_.Resize(num_block_cols_, num_block_rows_)); return WP2_STATUS_OK; } WP2Status SplitRecursePartitioner::GetBestPartition( VectorNoCtor<Block>* const blocks) { std::fill(occupancy_.begin(), occupancy_.end(), false); split_info_.Fill(kNoSplitInfo); const uint32_t max_num_blocks = num_block_cols_ * num_block_rows_; uint32_t max_num_blocks_left = max_num_blocks; // Begin with the user-defined blocks, if any (debug). WP2_CHECK_STATUS(RegisterForcedBlocks(*blocks, &max_num_blocks_left)); // Sort forced blocks by position for binary search below. VectorNoCtor<Block> forced_blocks; WP2_CHECK_ALLOC_OK(forced_blocks.resize(blocks->size())); std::copy(blocks->begin(), blocks->end(), forced_blocks.begin()); std::sort(forced_blocks.begin(), forced_blocks.end()); // Use a front manager to easily browse the blocks. FrontMgrLexico front_mgr; WP2_CHECK_STATUS(front_mgr.Init(config_->partition_set, config_->partition_snapping, src_->Y.w_, src_->Y.h_)); Vector<SplitPattern> patterns; WP2_CHECK_ALLOC_OK(patterns.reserve(10)); // maximum 10 ways to split a block BlockScoreFunc* const score_func = (BlockScoreFunc*)score_func_; while (!front_mgr.Done()) { const Block max_block = front_mgr.GetMaxPossibleBlock(); // Binary search to find if 'max_block' is already one of the forced blocks. const auto forced_block_it = std::lower_bound(forced_blocks.begin(), forced_blocks.end(), max_block); if (forced_block_it != forced_blocks.end() && forced_block_it->x() == max_block.x() && forced_block_it->y() == max_block.y()) { const Block block = *forced_block_it; assert(block.dim() != BLK_LAST); WP2_CHECK_ALLOC_OK(front_mgr.UseSize(block.dim(), /*ind=*/0u, nullptr)); front_mgr.Use(block); WP2_CHECK_STATUS(score_func_->Use(block)); } else { assert(max_num_blocks_left > 0); // Retrieve the previous decision to split this block, if any. const SplitInfo& split_info = GetSplitInfo(max_block.x(), max_block.y()); if (split_info == kNoSplitInfo || split_info.recursive) { // Nothing decided or recursive allowed: try more split patterns. Block block; if (split_info == kNoSplitInfo) { block = Block(max_block.x(), max_block.y(), GetMaxFittingBlockSize(max_block, forced_blocks.size())); } else { block = Block(max_block.x(), max_block.y(), split_info.size); } assert(IsBlockValid(block, max_block, forced_blocks.size())); assert(IsSplitInfo(block, split_info)); // Get all split patterns and keep the one with the best score. patterns.clear(); GetSplitPatterns(config_->partition_set, block.dim(), &patterns); SplitPattern best_pattern; if (patterns.size() == 1) { best_pattern = patterns.front(); } else { best_pattern = {/*num_blocks=*/0, {BLK_LAST}}; float best_score = 0.f; for (const SplitPattern& pattern : patterns) { Block pattern_blocks[4]; GetSplitPatternBlocks(block, pattern, pattern_blocks); float score; WP2_CHECK_STATUS(score_func->GetScore(pattern_blocks, pattern.num_blocks, &score)); if (best_pattern.num_blocks == 0 || score > best_score) { best_pattern = pattern; best_score = score; } } assert(best_pattern.num_blocks > 0); } // Remember the decision. Block best_pattern_blocks[4]; GetSplitPatternBlocks(block, best_pattern, best_pattern_blocks); for (uint32_t i = 0; i < best_pattern.num_blocks; ++i) { const bool recursive = (best_pattern.num_blocks > 1 && best_pattern_blocks[i].dim() != BLK_4x4); SetSplitInfo(best_pattern_blocks[i], recursive); // TODO(yguyon): Recurse in fewer situations to save CPU. } } else { // This 'block' was decided as is with no possibility of recursion. const Block block = Block(max_block.x(), max_block.y(), split_info.size); assert(IsBlockValid(block, max_block, forced_blocks.size())); assert(IsSplitInfo(block, split_info)); RegisterOrderForVDebug(0, 0, block, blocks->size(), max_num_blocks); WP2_CHECK_ALLOC_OK(blocks->push_back(block)); WP2_CHECK_ALLOC_OK(front_mgr.UseSize(block.dim(), /*ind=*/0u, nullptr)); front_mgr.Use(block); WP2_CHECK_STATUS(score_func_->Use(block)); // The following instructions are done only for assertions/debug // because the front manager should handle everything, except for // the forced blocks but these are checked above. assert((Occupy(block), true)); assert(max_num_blocks_left >= block.w() * block.h()); max_num_blocks_left -= block.w() * block.h(); assert(block.dim() != BLK_LAST); } } } assert(max_num_blocks_left == 0); return WP2_STATUS_OK; } BlockSize SplitRecursePartitioner::GetMaxFittingBlockSize( const Block& max_block, uint32_t num_forced_blocks) const { BlockSize best_size = BLK_LAST; const BlockSize* const sizes = GetBlockSizes(config_->partition_set); for (const BlockSize* size = sizes; *size != BLK_LAST; ++size) { const Block block = Block(max_block.x(), max_block.y(), *size); if ((best_size == BLK_LAST || BlockWidth[*size] * BlockHeight[*size] > BlockWidth[best_size] * BlockHeight[best_size]) && IsBlockValid(block, max_block, num_forced_blocks) && IsSplitInfo(block, kNoSplitInfo)) { best_size = block.dim(); } } assert(best_size != BLK_LAST); return best_size; } static BlockSize GetExactBlockSize(PartitionSet set, uint32_t w, uint32_t h) { const BlockSize s = GetBlockSize(std::max(1u, w), std::max(1u, h)); if (IsBlockSizeInSet(set, s) && BlockWidth[s] == w && BlockHeight[s] == h) { return s; } return BLK_LAST; } void SplitRecursePartitioner::GetSplitPatterns(PartitionSet set, BlockSize size, Vector<SplitPattern>* const p) { assert(p->empty() && p->capacity() >= 10); if (IsBlockSizeInSet(set, size)) p->push_back_no_resize({1, {size}}); const uint32_t width = BlockWidth[size], height = BlockHeight[size]; // The BlockSize variable names below are based on a 4x4 block reference. const BlockSize b2x2 = GetExactBlockSize(set, width / 2, height / 2); const BlockSize b4x1 = GetExactBlockSize(set, width, height / 4); const BlockSize b1x4 = GetExactBlockSize(set, width / 4, height); const BlockSize b4x2 = GetExactBlockSize(set, width, height / 2); const BlockSize b2x4 = GetExactBlockSize(set, width / 2, height); if (b2x2 != BLK_LAST) p->push_back_no_resize({4, {b2x2, b2x2, b2x2, b2x2}}); if (b4x1 != BLK_LAST) p->push_back_no_resize({4, {b4x1, b4x1, b4x1, b4x1}}); if (b1x4 != BLK_LAST) p->push_back_no_resize({4, {b1x4, b1x4, b1x4, b1x4}}); if (b4x2 != BLK_LAST) { p->push_back_no_resize({2, {b4x2, b4x2}}); if (b2x2 != BLK_LAST) p->push_back_no_resize({3, {b4x2, b2x2, b2x2}}); if (b2x2 != BLK_LAST) p->push_back_no_resize({3, {b2x2, b2x2, b4x2}}); } if (b2x4 != BLK_LAST) { p->push_back_no_resize({2, {b2x4, b2x4}}); if (b2x2 != BLK_LAST) p->push_back_no_resize({3, {b2x4, b2x2, b2x2}}); if (b2x2 != BLK_LAST) p->push_back_no_resize({3, {b2x2, b2x4, b2x2}}); } assert(!p->empty()); } void SplitRecursePartitioner::GetSplitPatternBlocks(const Block& block, const SplitPattern& pattern, Block blocks[4]) { assert(pattern.num_blocks >= 1 && pattern.num_blocks <= 4); // Treat this special case differently. Others can be done row by row. const bool is_2x4_2x2_2x2 = (pattern.num_blocks == 3 && BlockHeight[pattern.block_sizes[0]] == block.h()); uint32_t num_blocks = 0, x = block.x(), y = block.y(); while (num_blocks < pattern.num_blocks) { if (x == block.x() + block.w()) { // End of a row. // Start a new row aligned under the first block, unless 'is_2x4_2x2_2x2'. x = blocks[is_2x4_2x2_2x2 ? 1 : 0].x(); y += blocks[is_2x4_2x2_2x2 ? 1 : 0].h(); } assert(x < block.x() + block.w() && y < block.y() + block.h()); blocks[num_blocks] = Block(x, y, pattern.block_sizes[num_blocks]); x += blocks[num_blocks].w(); ++num_blocks; } } const SplitRecursePartitioner::SplitInfo& SplitRecursePartitioner::GetSplitInfo( uint32_t x, uint32_t y) const { return split_info_.At(x, y); } bool SplitRecursePartitioner::IsSplitInfo(const Block& block, const SplitInfo& split_info) const { const SplitInfo* row = &split_info_.At(block.x(), block.y()); for (uint32_t y = 0; y < block.h(); ++y, row += split_info_.Step()) { for (uint32_t x = 0; x < block.w(); ++x) { if (row[x] != split_info) return false; } } return true; } void SplitRecursePartitioner::SetSplitInfo(const Block& block, bool recursive) { SplitInfo* row = &split_info_.At(block.x(), block.y()); for (uint32_t y = 0; y < block.h(); ++y, row += split_info_.Step()) { for (uint32_t x = 0; x < block.w(); ++x) row[x] = {block.dim(), recursive}; } } //------------------------------------------------------------------------------ static constexpr uint32_t kBlkStart = BLK_LAST; WP2Status ExhaustivePartitioner::Init(const EncoderConfig& config, const YUVPlane& yuv, const Rectangle& tile_rect, PartitionScoreFunc* const score_func) { WP2_CHECK_STATUS(Partitioner::Init(config, yuv, tile_rect, score_func)); const BlockSize* size = GetBlockSizes(config_->partition_set); next_block_sizes_[kBlkStart] = *size; // First one. for (; *size != BLK_LAST; ++size) next_block_sizes_[*size] = *(size + 1); WP2_CHECK_STATUS(front_mgr_.Init(config_->partition_set, config_->partition_snapping, src_->Y.w_, src_->Y.h_)); return WP2_STATUS_OK; } WP2Status ExhaustivePartitioner::GetBestPartition( VectorNoCtor<Block>* const blocks) { std::fill(occupancy_.begin(), occupancy_.end(), false); WP2_CHECK_ALLOC_OK(forced_blocks_.resize(blocks->size())); std::copy(blocks->begin(), blocks->end(), forced_blocks_.begin()); // Only occupy the forced blocks, the others are determined by 'front_mgr_'. for (const Block& block : forced_blocks_) Occupy(block); // Sort the 'forced_blocks_' by position for binary search later on. std::sort(forced_blocks_.begin(), forced_blocks_.end()); float best_score = 0.f; VectorNoCtor<Block>* const best_partition = blocks; best_partition->clear(); front_mgr_.Clear(); partition_.clear(); size_t num_iterations = 0; while (true) { bool found; float score; WP2_CHECK_STATUS(GetNextPartitionScore(&found, &score)); if (!found) break; // Make sure the partition fills exactly the tile. assert(std::accumulate(partition_.begin(), partition_.end(), 0u, [](uint32_t sum, const Block& block) { return sum + (BlockWidth[block.dim()] * BlockHeight[block.dim()]); }) == num_block_cols_ * num_block_rows_); if (best_partition->empty() || score > best_score) { best_score = score; WP2_CHECK_ALLOC_OK(best_partition->resize(partition_.size())); std::copy(partition_.begin(), partition_.end(), best_partition->begin()); } ++num_iterations; } RegisterScoreForVDebug(best_score, best_partition->size(), num_iterations); return WP2_STATUS_OK; } WP2Status ExhaustivePartitioner::GetNextPartitionScore(bool* const found, float* const score) { // Begin the tree search. BlockSize next_block_size = next_block_sizes_[kBlkStart]; bool is_first_branch = partition_.empty(); // Find a new branch in the search tree if possible. while (is_first_branch || FindNewBranch(&next_block_size)) { is_first_branch = false; // Try to go down the new branch. do { Block block; VectorNoCtor<Block>::iterator forced_block_it; // Check if the 'next_block_size' can fit, then if the 'block' is snapped // or does not need to, then if the 'block' is forced or intersecting one. if (front_mgr_.TryGetNextBlock(next_block_size, &block) && (!config_->partition_snapping || block.IsSnapped()) && (forced_blocks_.empty() || !IsOccupied(block) || ((forced_block_it = std::lower_bound(forced_blocks_.begin(), forced_blocks_.end(), block)) != forced_blocks_.end() && *forced_block_it == block))) { if (forced_blocks_.empty()) assert(!IsOccupied(block)); // 'block' is valid. WP2_CHECK_ALLOC_OK(front_mgr_.UseSize(next_block_size, /*ind=*/0u, &block)); front_mgr_.Use(block); WP2_CHECK_ALLOC_OK(partition_.push_back(block)); if (front_mgr_.Done()) { // 'partition_' is complete. Get its score. WP2_CHECK_STATUS(tile_score_func_->TryEncode(partition_, score)); *found = true; return WP2_STATUS_OK; } else { // 'partition_' is incomplete. Go deeper. next_block_size = next_block_sizes_[kBlkStart]; } } else { // 'block' is invalid. Try the next size or leave this branch. next_block_size = next_block_sizes_[next_block_size]; } } while (next_block_size != BLK_LAST); } *found = false; return WP2_STATUS_OK; } bool ExhaustivePartitioner::FindNewBranch(BlockSize* const next_block_size) { while (!partition_.empty()) { *next_block_size = next_block_sizes_[partition_.back().dim()]; front_mgr_.UndoUse(partition_.back()); front_mgr_.UndoUseSize(partition_.back()); partition_.pop_back(); if (*next_block_size != BLK_LAST) return true; // Found new branch. } return false; // Browsed the whole tree. } //------------------------------------------------------------------------------ using Pass = MultiScoreFunc::Pass; WP2Status MultiPassPartitioner::GetBestPartition( VectorNoCtor<Block>* const blocks) { std::fill(occupancy_.begin(), occupancy_.end(), false); uint32_t max_num_blocks_left = num_block_cols_ * num_block_rows_; WP2_CHECK_STATUS(RegisterForcedBlocks(*blocks, &max_num_blocks_left)); // Run several passes to select matching blocks with a given size. // GetBlocks() will skip any pass with a BlockSize not belonging to the // current PartitionSet. // Start with easy-to-spot flat blocks (narrow range of values in the // original luma and alpha planes). for (BlockSize block_size : {BLK_32x32, BLK_32x16, BLK_16x32, BLK_16x16, BLK_16x8, BLK_8x16, BLK_8x8}) { WP2_CHECK_STATUS(GetBlocks(Pass::LumaAlphaGradient, block_size, Grid::Snapped, &max_num_blocks_left, blocks)); } if (config_->speed >= MultiScoreFunc::kMinSpeedForGoodQuantDCT) { // Blocks having a DCT that still gives a good result when quantized. WP2_CHECK_STATUS(GetBlocks(Pass::GoodQuantDCT, BLK_32x32, Grid::Snapped, &max_num_blocks_left, blocks)); } // Pick a few not-too-small blocks that are following a luma edge. for (const BlockSize* block_size = GetBlockSizes(ALL_RECTS) + GetNumBlockSizes(ALL_RECTS) - 1u; *block_size != BLK_4x4; --block_size) { if (BlockWidth[*block_size] * BlockHeight[*block_size] < 4) continue; WP2_CHECK_STATUS(GetBlocks(Pass::Direction, *block_size, Grid::All, &max_num_blocks_left, blocks)); } // Choose smaller and smaller blocks based on variance. constexpr PartitionSet variance_partition_set = SMALL_RECTS; assert(*GetBlockSizes(variance_partition_set) == BLK_4x4); for (const BlockSize* allowed_block_size = GetBlockSizes(variance_partition_set) + GetNumBlockSizes(variance_partition_set) - 1u; *allowed_block_size != BLK_4x4; --allowed_block_size) { WP2_CHECK_STATUS(GetBlocks(Pass::NarrowStdDev, *allowed_block_size, Grid::All, &max_num_blocks_left, blocks)); } // Merge all remaining small blocks that are following a luma edge. for (const BlockSize* block_size = GetBlockSizes(ALL_RECTS) + GetNumBlockSizes(ALL_RECTS) - 1u; *block_size != BLK_4x4; --block_size) { if (BlockWidth[*block_size] * BlockHeight[*block_size] >= 4) continue; WP2_CHECK_STATUS(GetBlocks(Pass::Direction, *block_size, Grid::All, &max_num_blocks_left, blocks)); } // Fill the remaining empty areas. WP2_CHECK_STATUS( GetBlocks(Pass::Any, BLK_4x4, Grid::All, &max_num_blocks_left, blocks)); assert(max_num_blocks_left == 0); return WP2_STATUS_OK; } WP2Status MultiPassPartitioner::GetBlocks(Pass pass, BlockSize block_size, Grid restrict_to, uint32_t* const max_num_blocks_left, VectorNoCtor<Block>* const out) { if (GetFittingBlockSize(config_->partition_set, block_size) != block_size) { return WP2_STATUS_OK; } // Only keep snapped blocks if the config forces it. if (config_->partition_snapping) { if (restrict_to == Grid::NonSnapped) return WP2_STATUS_OK; restrict_to = Grid::Snapped; } const uint32_t num_blocks_before = out->size(); Block block(0, 0, block_size); // Make sure the 'block_size' is valid and there is at least one remaining. if (block.w() > num_block_cols_ || block.h() > num_block_rows_ || block.rect().GetArea() > *max_num_blocks_left) { RegisterPassForVDebug(pass, block_size, out->size() - num_blocks_before); ++pass_index_; return WP2_STATUS_OK; } struct BlockScore { Block blk; float score; }; VectorNoCtor<BlockScore> block_scores; multi_score_func_->SetPass(pass); uint32_t x = 0, y = 0; const uint32_t max_x = num_block_cols_ - block.w(); const uint32_t max_y = num_block_rows_ - block.h(); const bool* occupancy = occupancy_.data(); // Browse the grid of selectable blocks. while (y <= max_y) { while (x <= max_x) { if (!occupancy[x]) { // Quickly skip top-left-occupied blocks. block.SetXY(x, y); if (restrict_to == Grid::Snapped) assert(block.IsSnapped()); // Assume snapped blocks were already tried if 'restrict_to==NonSnapped' const bool tried_block_earlier = (restrict_to == Grid::NonSnapped && block.IsSnapped()); if (!tried_block_earlier && !IsOccupied(block)) { float score; WP2_CHECK_STATUS(score_func_->GetScore(block, &score)); if (score >= MultiScoreFunc::kMinScore) { if (restrict_to == Grid::Snapped) { // Immediately select any passing block. WP2_CHECK_STATUS( SelectBlock(pass, block, max_num_blocks_left, out)); } else { // Keep the scores of the passing blocks in memory. WP2_CHECK_ALLOC_OK(block_scores.push_back({block, score})); } } } } x += (restrict_to == Grid::Snapped) ? block.w() : 1; } const uint32_t num_incr_rows = (restrict_to == Grid::Snapped) ? block.h() : 1; y += num_incr_rows; occupancy += num_incr_rows * num_block_cols_; x = 0; } if (restrict_to != Grid::Snapped) { // Select blocks with best (=lowest) score first. // stable_sort() is used for its determinism. std::stable_sort(block_scores.begin(), block_scores.end(), [](const BlockScore& l, const BlockScore& r) { return l.score < r.score; }); for (const BlockScore& bs : block_scores) { if (IsOccupied(bs.blk)) continue; // 'occupancy_' might have changed. WP2_CHECK_STATUS(SelectBlock(pass, bs.blk, max_num_blocks_left, out)); } } RegisterPassForVDebug(pass, block_size, out->size() - num_blocks_before); ++pass_index_; return WP2_STATUS_OK; } WP2Status MultiPassPartitioner::SelectBlock(MultiScoreFunc::Pass pass, const Block& block, uint32_t* const max_num_blocks_left, VectorNoCtor<Block>* const out) { RegisterOrderForVDebug((uint32_t)pass, pass_index_, block, out->size(), num_block_cols_ * num_block_rows_); Occupy(block); const uint32_t block_area = block.w() * block.h(); assert(*max_num_blocks_left >= block_area); *max_num_blocks_left -= block_area; WP2_CHECK_ALLOC_OK(out->push_back(block)); WP2_CHECK_STATUS(score_func_->Use(block)); return WP2_STATUS_OK; } //------------------------------------------------------------------------------ } // namespace WP2
41.003448
80
0.631037
[ "vector" ]
e88f5a1502a29bf353ea9fbdcfaed1c87c44c1b3
2,097
cpp
C++
object/src/object.cpp
pierrebai/dak
3da144aecfc941efe10abe0167b1d3a838a6a0d5
[ "MIT" ]
null
null
null
object/src/object.cpp
pierrebai/dak
3da144aecfc941efe10abe0167b1d3a838a6a0d5
[ "MIT" ]
null
null
null
object/src/object.cpp
pierrebai/dak
3da144aecfc941efe10abe0167b1d3a838a6a0d5
[ "MIT" ]
null
null
null
#include <dak/object/object.h> #include <dak/object/transaction.h> namespace dak::object { ////////////////////////////////////////////////////////////////////////// // // Modifications. object_t& object_t::operator +=(const object_t & an_obj) { append(an_obj); return *this; } void object_t::append(const object_t & an_obj) { for (const auto& [n, e] : an_obj.my_values) (*this)[n] = e; } bool object_t::erase(const name_t& n) { iterator pos = my_values.find(n); if (pos == my_values.end()) return false; my_values.erase(pos); return true; } // Reset the object. void object_t::clear() { my_values.clear(); } void object_t::swap(object_t& an_other) { my_values.swap(an_other.my_values); } ////////////////////////////////////////////////////////////////////////// // // Data access. bool object_t::contains(const name_t& n) const { return 0 != my_values.count(n); } index_t object_t::size() const { return my_values.size(); } value_t & object_t::operator [](const name_t& n) { return my_values[n]; } const value_t & object_t::operator [](const name_t& n) const { const_iterator pos = my_values.find(n); if(my_values.end() == pos) return value_t::empty; else return pos->second; } object_t::iterator object_t::begin() { return my_values.begin(); } object_t::iterator object_t::end() { return my_values.end(); } object_t::const_iterator object_t::begin() const { return my_values.begin(); } object_t::const_iterator object_t::end() const { return my_values.end(); } ////////////////////////////////////////////////////////////////////////// // // Modification in a transaction. edit_ref_t<object_t> object_t::modify(transaction_t& a_trans) const { edit_ref_t<object_t> edit_this(const_cast<object_t*>(this)); a_trans.add(edit_this); return edit_this; } }
20.163462
77
0.526466
[ "object" ]
e892b1b7b1b7621a692842ab34d7a594fcf2a7ed
1,262
cpp
C++
lab2/greatestproduct/GreatestProduct.cpp
Adrjanjan/JiMP-Exercises
0c5de5878bcf0ede27fedcdf3cebbe081679e180
[ "MIT" ]
null
null
null
lab2/greatestproduct/GreatestProduct.cpp
Adrjanjan/JiMP-Exercises
0c5de5878bcf0ede27fedcdf3cebbe081679e180
[ "MIT" ]
null
null
null
lab2/greatestproduct/GreatestProduct.cpp
Adrjanjan/JiMP-Exercises
0c5de5878bcf0ede27fedcdf3cebbe081679e180
[ "MIT" ]
null
null
null
// // Created by adrja on 16.03.2018. // #include "GreatestProduct.h" int max(int x1, int x2) { return x1 > x2 ? x1 : x2; } int GreatestProduct(const std::vector<int> &numbers, int k) { if (numbers.empty()) { return 0; } std::vector<int> new_vector(numbers); int result = 1; sort(new_vector.begin(), new_vector.end()); if (k % 2 && new_vector[new_vector.size() - 1] <= 0) { for (int i = 1; i <= k; ++i) { result *= new_vector[new_vector.size() - 1]; new_vector.pop_back(); } } else { int positive_mul, negative_mul; while (k > 1) { negative_mul = new_vector[0] * new_vector[1]; positive_mul = new_vector[new_vector.size() - 1] * new_vector[new_vector.size() - 2]; if (negative_mul > positive_mul) { result *= negative_mul; new_vector.erase(new_vector.begin(), new_vector.begin() + 1); } else { result *= positive_mul; new_vector.erase(new_vector.end() - 1, new_vector.end()); } k -= 2; } } if (k == 1) result *= max(new_vector[new_vector.size() - 1], new_vector[new_vector.size() - 2]); return result; }
28.681818
100
0.530903
[ "vector" ]
e89ac1cff9d84b468bcffbe3d4528b991d05e322
3,710
hpp
C++
include/utility/test/throwing.hpp
rogiervd/utility
10a3f45ee5bdedd4bbe6fca973b5bb44e142c80f
[ "Apache-2.0" ]
null
null
null
include/utility/test/throwing.hpp
rogiervd/utility
10a3f45ee5bdedd4bbe6fca973b5bb44e142c80f
[ "Apache-2.0" ]
null
null
null
include/utility/test/throwing.hpp
rogiervd/utility
10a3f45ee5bdedd4bbe6fca973b5bb44e142c80f
[ "Apache-2.0" ]
null
null
null
/* Copyright 2009, 2014 Rogier van Dalen. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef UTILITY_TEST_THROWING_HPP_INCLUDED #define UTILITY_TEST_THROWING_HPP_INCLUDED #include <type_traits> #include <memory> #include <utility> #include <type_traits> #include <boost/test/test_tools.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/not.hpp> #include "thrower.hpp" #include "utility/is_assignable.hpp" namespace utility { /** Wrapper around object that makes it throw in various circumstances. This is useful to check exception-safety. */ template <class Content, bool ThrowOnConstruction = false, bool ThrowOnCopy = false, bool ThrowOnMove = false, bool ThrowOnCopyAssign = false, bool ThrowOnMoveAssign = false, bool ThrowOnConversion = false > class throwing { thrower & thrower_; Content content_; public: template <class ... Arguments> throwing (thrower & t, Arguments && ... arguments) noexcept (std::is_nothrow_constructible <Content, Arguments ...>::value && !ThrowOnConstruction) : thrower_ (t), content_ (std::forward <Arguments> (arguments) ...) { thrower_.template throw_point_if <ThrowOnConstruction>(); } throwing (throwing const & other) noexcept (std::is_nothrow_constructible <Content, Content const & >::value && !ThrowOnCopy) : thrower_ (other.thrower_), content_ (other.content_) { thrower_.template throw_point_if <ThrowOnCopy>(); } throwing (throwing && other) noexcept (std::is_nothrow_constructible <Content, Content && >::value && !ThrowOnMove) : thrower_ (other.thrower_), content_ (std::move (other.content_)) { thrower_.template throw_point_if <ThrowOnMove>(); } ~throwing() {} throwing & operator = (throwing const & other) noexcept (utility::is_nothrow_assignable <Content &, Content const & >::value && !ThrowOnCopyAssign) { content_ = other.content_; thrower_.template throw_point_if <ThrowOnCopyAssign>(); return *this; } throwing & operator = (throwing && other) noexcept (utility::is_nothrow_assignable <Content &, Content &&>::value && !ThrowOnMoveAssign) { content_ = std::move (other.content_); thrower_.template throw_point_if <ThrowOnMoveAssign>(); return *this; } const Content & content() const { return content_; } Content & content() { return content_; } operator Content() const { thrower_.template throw_point_if <ThrowOnConversion>(); return content(); } bool operator == (const throwing & o) const { return content_ == o.content_; } }; template <class T> struct is_throwing : public boost::mpl::bool_ <false> {}; template <class Content, bool B1, bool B2, bool B3, bool B4> struct is_throwing <throwing <Content, B1, B2, B3, B4> > : public boost::mpl::bool_ <true> {}; } // namespace utility #endif // UTILITY_TEST_THROWING_HPP_INCLUDED
32.26087
79
0.649865
[ "object" ]
e89e941f6f50f800820956d36fc2955adb59ad8e
11,556
cpp
C++
src/main.cpp
jake314159/tiny-ci
125e9991124ebfb8311b70e024d19a8c0f6d61c4
[ "Apache-2.0" ]
null
null
null
src/main.cpp
jake314159/tiny-ci
125e9991124ebfb8311b70e024d19a8c0f6d61c4
[ "Apache-2.0" ]
null
null
null
src/main.cpp
jake314159/tiny-ci
125e9991124ebfb8311b70e024d19a8c0f6d61c4
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <unistd.h> //Unix timer. Note this makes this code Unix only! #include <unistd.h> // Used to get home directory (Unix only) #include <sys/types.h> // #include <pwd.h> // #include <time.h> //for the time #include <boost/regex.hpp> //delay between checks in seconds #define DELAY 60 //Regex to check for things which shouldn't be passed to a bash shell or SQL boost::regex badInput(".*(>|<|&&|\\||DELETE|INSERT|UPDATE|=|DROP|;).*"); using namespace std; //#include "MakeTest.h" #include "gitTools.h" #include "dir.h" #include "database.h" void printHelp(); void printAddHelp(); //#include "MakeTest.h" const char *homedir; std::string gitRootDir = ""; std::vector<Test*> tests; test_database db; void initHomeDir() { struct passwd *pw = getpwuid(getuid()); homedir = pw->pw_dir; //cout << "Home dir " << homedir << endl; gitRootDir = std::string(homedir) + "/" + HOME_DIR; //cout << "git root dir " << gitRootDir << endl; } int onFail(string testName, Result &result) { // Check if processor is available if (!system(NULL)) { exit (EXIT_FAILURE); } //run command std::string cmd = std::string("python ") + homedir + "/" + HOME_DIR + "/processError.py '" + testName + "' '" + result.getReturnString() + "'"; return system((char*)cmd.c_str()); } void addTaskToStore(MakeTest &t) { FILE *fp = fopen( (char*)(std::string(gitRootDir) + "/.tasks").c_str(),"a"); cout << "fp is " << fp << endl; if(fp != NULL) { t.saveTest(fp); fclose(fp); } else { cout << "Err fp is null " << endl; } } void updateTasksFromFile() { int size = tests.size(); for(int i=0; i<size; i++) { delete tests.at(i); } tests.clear(); db.getTasks(&tests); for(int i=0; i<size; i++) { string lastHash = db.getTestRunsHash(std::to_string(tests.at(i)->getID())); tests.at(i)->setLastHash( lastHash ); } } void listTasks() { updateTasksFromFile(); int size = tests.size(); for(int i=0; i<size; i++) { Test *test = tests.at(i); //convert the ID to a string stringstream ss; ss << test->getID(); TestMode mode = db.getLastTestResult( ss.str() );//test->getMode(); if(mode == PASS) { cout << "[ PASS ]"; } else if(mode == FAIL) { cout << "[ FAIL ]"; } else if(mode == UNTESTED) { cout << "[ ]"; } else if(mode == PAUSED) { cout << "[PAUSED]"; } else { cout << "[ ERR ]"; } cout << " " << test->getID() << ") " << test->getTestName() << endl; } } int start() { updateTasksFromFile(); Result r; while(true) { updateTasksFromFile(); int size = tests.size(); for (int i=0; i<size; i++) { int check = tests.at(i)->checkForChange(); time_t rawtime; time (&rawtime); if(check) { if(tests.at(i)->performTest(r)) { onFail(tests.at(i)->getTestName(), r); cout << "[ FAIL ] " << tests.at(i)->getTestName() << " failed on " << ctime (&rawtime); //ctime ends with a '\n' } else { //Success cout << "[ PASS ] " << tests.at(i)->getTestName() << " passed on " << ctime (&rawtime); //ctime ends with a '\n' } db.addTestRun(tests.at(i)->getID(), tests.at(i)->getStoredLastHash(), r.getReturnValue()); } } sleep(DELAY); } return 0; } int handleAddTask(int argc, char *argv[]) { if(argc >= 3 && !std::string(argv[2]).compare("help")) { printAddHelp(); return 0; } else if(argc >= 3 && !std::string(argv[2]).compare("make")) { if(argc < 5) { cout << "Not enough arguments to make a new task" << endl; printHelp(); return 1; } if(boost::regex_match(argv[3], badInput)) { cout << "Badly formed test name " << argv[3] << ". Unable to continue" << endl; return 10; } else if(boost::regex_match(argv[4], badInput)) { cout << "Badly formed git url. Unable to continue" << endl; return 10; } bool runTest = false; if(argc > 5 && !std::string(argv[5]).compare("true")) { runTest = true; } cout << "Name: " << argv[3] << endl; cout << "Directory: " << gitRootDir + "/" + argv[3] << endl; cout << "Git URL: " << argv[4] << endl; cout << "Run test?: " << (runTest ? "Yes" : "No") << endl << endl; //cout << "Git url check: " << boost::regex_match(argv[4], badInput) << endl; MakeTest t(-1, argv[3], gitRootDir + "/" + argv[3], argv[4], runTest); db.addTask(t); t.createNewRepo(); } else if(argc >= 3 && !std::string(argv[2]).compare("maven")) { if(argc < 4) { cout << "Not enough arguments to make a new task" << endl; printHelp(); return 1; } if(boost::regex_match(argv[3], badInput)) { cout << "Badly formed test name " << argv[3] << ". Unable to continue" << endl; return 10; } else if(boost::regex_match(argv[4], badInput)) { cout << "Badly formed git url. Unable to continue" << endl; return 10; } cout << "Name: " << argv[3] << endl; cout << "Directory: " << gitRootDir + "/" + argv[3] << endl; cout << "Git URL: " << argv[4] << endl; //cout << "Git url check: " << boost::regex_match(argv[4], badInput) << endl; MavenTest t(-1, argv[3], gitRootDir + "/" + argv[3], argv[4]); db.addTask(t); t.createNewRepo(); } else if(argc >= 3 && !std::string(argv[2]).compare("bash")) { if(argc < 5) { cout << "Not enough arguments to make a new task" << endl; printHelp(); return 1; } if(boost::regex_match(argv[3], badInput)) { cout << "Badly formed test name " << argv[3] << ". Unable to continue" << endl; return 10; } else if(boost::regex_match(argv[4], badInput)) { cout << "Badly formed bash file name. Unable to continue" << endl; return 10; } else if(boost::regex_match(argv[5], badInput)) { cout << "Badly formed git url. Unable to continue" << endl; return 10; } /*bool runTest = false; if(argc > 5 && !std::string(argv[5]).compare("true")) { runTest = true; }*/ cout << "Name: " << argv[3] << endl; cout << "Directory: " << gitRootDir + "/" + argv[3] << endl; cout << "Bash script: " << argv[4] << endl << endl; cout << "Git URL: " << argv[5] << endl; //cout << "Git url check: " << boost::regex_match(argv[4], badInput) << endl; BashTest t(-1, argv[3], gitRootDir + "/" + argv[3], string(argv[4]), string(argv[5])); db.addTask(t); t.createNewRepo(); } else { cout << "I don't know what '" << argv[2] << "' is sorry" << endl; printAddHelp(); } return 0; } void printHelp() { cout << "Did you mean one of these?" << endl << endl << "tiny-ci start Starts the server program" << endl << "tiny-ci list Lists all the current tasks" << endl << "tiny-ci remove ID Removes the task with the ID given" << endl << "tiny-ci add name gitURL Adds a test to run" << endl << endl; } void printAddHelp() { cout << "tiny-ci add can be used to add tasks to be run by the tiny-ci program." << endl << endl << "The required arguments are:" << endl << " <name>: The name of the new task" << endl << " <gitURL>: The url for the git repository" << endl << " <runtest?>: Should tiny-ci attempt to run any tests? ('true' or 'false')" << endl << " <bashFile>: The name of the bash file to run" << endl << endl << "The command should then be in the form:" << endl << " tiny-ci add make <name> <gitURL>" << endl << " tiny-ci add make <name> <gitURL> <runTest?>" << endl << " tiny-ci add maven <name> <gitURL>" << endl << " tiny-ci add bash <name> <bashFile> <gitURL>" << endl; } bool checkArgs(int argc, char *argv[]) { bool result = true; for(int i=1; i<argc; i++) { if(boost::regex_match(argv[i], badInput)) { cout << "Badly formed input '" << argv[i] << "'. Unable to continue" << endl; result = false; } } return result; } int main(int argc, char *argv[]) { //Check that all inputs don't have anything banned if(!checkArgs(argc, argv)) { return 101; } initHomeDir(); db.openConnection(); db.initTable(); if(!db.isOpen()) { return 13; } if(argc <= 1) { cout << "Not enough arguments!" << endl; printHelp(); return 1; } if(!std::string(argv[1]).compare("start")) { start(); } else if(!std::string(argv[1]).compare("add")) { return handleAddTask(argc, argv); //addTaskToStore(t); } else if(!std::string(argv[1]).compare("remove")) { if(argc<3) { cout << "Not enough arguments"; printHelp(); return 1; } else if(boost::regex_match(argv[2], badInput)) { cout << "Badly formed input " << argv[2] << ". Unable to continue" << endl; return 13; } cout << endl << endl << "You are about to delete the task shown below:" << endl; db.listTask(argv[2]); cout << endl << "Are you sure you want to delete this (y/n)? "; string response = "n"; cin >> response; if(!response.compare("y")) { db.deleteTask(argv[2]); cout << "Task deleted" << endl; } else { cout << "Delete canceled" << endl; } } else if(!std::string(argv[1]).compare("list")) { if(argc >= 3 && !boost::regex_match(argv[2], badInput)) { db.listTestRuns(argv[2]); //cout << "The last hash was: "<< db.getTestRunsHash(argv[2]) << endl; } else { db.getTasks(&tests); listTasks(); } } else if(!std::string(argv[1]).compare("dev-fail")) { // Unpublished dev option which runs a fake test fail // Can be used to test that fails are handled as expected Result r; r.setReturnValue(1); r.setReturnString("An example of a failed test\n\nAn example of a failed test\n"); onFail("Example-Test", r); } else { cout << "Incorrect argument!" << endl; printHelp(); return 1; } return 0; }
32.369748
147
0.483991
[ "vector" ]
e89f6a6c2103dedaa808c7cc85e06780d830f8e4
785
hpp
C++
src/Game.hpp
Rikora/Boids
582c0c7de41062c23da83dae4115fa4a631dfca5
[ "MIT" ]
null
null
null
src/Game.hpp
Rikora/Boids
582c0c7de41062c23da83dae4115fa4a631dfca5
[ "MIT" ]
null
null
null
src/Game.hpp
Rikora/Boids
582c0c7de41062c23da83dae4115fa4a631dfca5
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics.hpp> #define WIDTH 1000U #define HEIGHT 600U #define BOID_SIZE 7.f #define BOID_VELOCITY 30.f #define BOID_RADIUS 100.f namespace fb { struct Boid { Boid(const sf::CircleShape& body, const sf::Vector2f& velocity = sf::Vector2f(BOID_VELOCITY, BOID_VELOCITY)) : body(body), velocity(velocity) {} sf::CircleShape body; sf::Vector2f velocity; }; class Game { public: Game(); void run(); private: void render(); void pollEvents(); void update(sf::Time dt); void checkBoundaries(Boid& boid); // Rules sf::Vector2f alignment(const Boid& targetBoid); sf::Vector2f cohesion(const Boid& targetBoid); sf::Vector2f separation(const Boid& targetBoid); sf::RenderWindow m_window; std::vector<Boid> m_boids; }; }
18.255814
113
0.703185
[ "render", "vector" ]
e8a29ca56b21b3c7f39326ff24729ab794bbc993
12,602
cpp
C++
src/PSV_Core.cpp
MSeys/PSV_2DCore
b2d1bff669b3e920c03502ac44aabe0b4eca5874
[ "MIT" ]
8
2019-08-14T10:40:12.000Z
2020-07-26T21:19:46.000Z
src/PSV_Core.cpp
MSeys/PSV_2DCore
b2d1bff669b3e920c03502ac44aabe0b4eca5874
[ "MIT" ]
1
2019-08-28T18:21:22.000Z
2019-08-28T18:21:22.000Z
src/PSV_Core.cpp
MSeys/PSV_2DCore
b2d1bff669b3e920c03502ac44aabe0b4eca5874
[ "MIT" ]
null
null
null
#include "PSV_Core.h" #include "PSV_Utils.h" #define PSV_HOLD_TIME 0.4 #define PSV_JOY_THRESHOLD 40 std::vector<std::string> PSV_ButtonStrings { "Cross", "Circle", "Square", "Triangle", "L-Trigger", "R-Trigger", "D-Pad Up", "D-Pad Down", "D-Pad Left", "D-Pad Right", "Start", "Select" }; std::vector<std::string> PSV_JoystickDirectionStrings { "North West", "North", "North East", "West", "East", "South West", "South", "South East", "Middle" }; std::vector<std::string> PSV_JoystickTypeStrings { "L-Stick", "R-Stick" }; std::vector<std::string> PSV_TouchSwipeDirectionStrings { "Swipe Up", "Swipe Down", "Swipe Left", "Swipe Right" }; std::unordered_map<PSV_ButtonType, PSV_Button> PSV_Buttons; std::unordered_map<PSV_JoystickType, PSV_Joystick> PSV_Joysticks; std::unordered_map<PSV_TouchpadType, PSV_Touchpad> PSV_Touchpads; std::queue<PSV_Event> PSV_EventsQueue; #pragma region PSV Button PSV_Button::PSV_Button(const SceCtrlButtons& sceCtrlButton, const PSV_ButtonType& buttonType) : sceCtrlButton(sceCtrlButton) , buttonType(buttonType) , isPressed(false) , isHeld(false) , isReleased(false) , press_time(0) { } PSV_Event PSV_Button::Update(SceCtrlData& pad) { PSV_Event e{}; e.bEvent = PSV_ButtonEvent{ buttonType }; const float timeNow = GetTimeNow(); isReleased = false; if(pad.buttons & sceCtrlButton) { isReleased = false; if(isPressed && !isHeld && (timeNow - press_time > PSV_HOLD_TIME)) { isHeld = true; isPressed = false; e.eType = PSV_KEYHELD; return e; } if(!isPressed && !isHeld) { isPressed = true; press_time = GetTimeNow(); e.eType = PSV_KEYDOWN; return e; } } else { if(isPressed || isHeld) { isReleased = true; } isPressed = false; isHeld = false; } if(isReleased) { e.eType = PSV_KEYUP; return e; } e.eType = PSV_NONE; return e; } #pragma endregion PSV Button #pragma region PSV Joystick PSV_Joystick::PSV_Joystick(const PSV_JoystickType& joystickType) : joyType(joystickType) , joyDirection(MIDDLE) , x(0) , y(0) { } PSV_Event PSV_Joystick::Update(SceCtrlData& pad) { PSV_Event e{}; const PSV_JoystickDirection previousDirection{ joyDirection }; const Point2f center{ 128.f, 128.f }; Point2f joyPos{}; if(joyType == LSTICK) { joyPos = Point2f{ float(pad.lx), float(pad.ly) }; x = pad.lx; y = pad.ly; } else { joyPos = Point2f{ float(pad.rx), float(pad.ry) }; x = pad.rx; y = pad.ry; } float angleRad = AngleBetweenPoints(center, joyPos); const int angleDegrees = RadiansToDegrees(angleRad); // Radian angle correction if (angleRad < 0) { angleRad += M_PI * 2; } if(DistanceBetweenPoints(center, joyPos) > PSV_JOY_THRESHOLD) { // EAST if ((AngleInRange(angleDegrees, 0, 22.5) || AngleInRange(angleDegrees, 337.5, 360)) && joyDirection != E) { joyDirection = E; } // NORTH EAST if(AngleInRange(angleDegrees, 22.5, 67.5) && joyDirection != NE) { joyDirection = NE; } // NORTH if (AngleInRange(angleDegrees, 67.5, 112.5) && joyDirection != N) { joyDirection = N; } // NORTH WEST if (AngleInRange(angleDegrees, 112.5, 157.5) && joyDirection != NW) { joyDirection = NW; } // WEST if (AngleInRange(angleDegrees, 157.5, 202.5) && joyDirection != W) { joyDirection = W; } // SOUTH WEST if (AngleInRange(angleDegrees, 202.5, 247.5) && joyDirection != SW) { joyDirection = SW; } // SOUTH if (AngleInRange(angleDegrees, 247.5, 292.5) && joyDirection != S) { joyDirection = S; } // SOUTH EAST if (AngleInRange(angleDegrees, 292.5, 337.5) && joyDirection != SE) { joyDirection = SE; } } else { joyDirection = MIDDLE; } // Final event check if(previousDirection != joyDirection) { e.eType = PSV_JOYSTICKMOTION; e.jEvent = PSV_JoystickEvent{ joyType, joyDirection, joyPos.x, joyPos.y, angleDegrees, angleRad }; } else { e.eType = PSV_NONE; } return e; } #pragma endregion PSV Joystick #pragma region PSV Touchpad PSV_Touchpad::PSV_Touchpad(const PSV_TouchpadType& touchpadType) : touchpadType(touchpadType) { if (touchpadType == FRONT) { maxTouches = 6; } else { maxTouches = 4; } for (int i{ 0 }; i < maxTouches; i++) { pressTouches.emplace_back(0, 0); motionTouches.emplace_back(0, 0); releaseTouches.emplace_back(0, 0); touchIsReleased.push_back(false); touchIsPressed.push_back(false); touchPressTimes.push_back(0); } } std::queue<PSV_Event> PSV_Touchpad::Update(SceTouchData* touch, SceTouchData* touchOld) { std::queue<PSV_Event> events; const int reportNum{ int(touch[int(touchpadType)].reportNum) }; const int touchVPos{ reportNum - 1 }; for (int i{}; i < maxTouches; i++) { // release default set to false touchIsReleased[i] = false; // PRESS/MOTION ON or ABOVE current touch position if(touchVPos >= i) { if (PSV_TSMode != PSV_TOUCH_SWIPE) { // Touch position isn't in PRESSED state if (!touchIsPressed[i]) { // set pressed and pressed coordinate. touchIsPressed[i] = true; pressTouches[i] = Point2f{ float(touch[int(touchpadType)].report[i].x) / 2.f, float(touch[int(touchpadType)].report[i].y) / 2.f }; touchPressTimes[i] = GetTimeNow(); // PUSHING EVENT TO QUEUE { // Events declarations and defining PSV_Event e{ PSV_TOUCHPAD_DOWN }; PSV_TouchpadEvent tpEvent{ touchpadType }; // set tpEvent variables tpEvent.pressTouch = pressTouches[i]; tpEvent.touchVectorNum = i; tpEvent.reportNum = reportNum; // set PSV_Event tpEvent as local tpEvent e.tpEvent = tpEvent; // Pushing the PSV_Event to the local queue events.push(e); } } // Touch is in PRESSED state else { // If TouchSamplingMode is set on Touch Motion if (PSV_TSMode == PSV_TOUCH_MOTION) { motionTouches[i] = Point2f{ float(touch[int(touchpadType)].report[i].x) / 2.f, float(touch[int(touchpadType)].report[i].y) / 2.f }; // PUSHING EVENT TO QUEUE { // Events declarations and defining PSV_Event e{ PSV_TOUCHPAD_MOTION }; PSV_TouchpadEvent tpEvent{ touchpadType }; // set tpEvent variables tpEvent.motionTouch = motionTouches[i]; tpEvent.touchVectorNum = i; tpEvent.reportNum = reportNum; // set PSV_Event tpEvent as local tpEvent e.tpEvent = tpEvent; // Pushing the PSV_Event to the local queue events.push(e); } } } } else { // Touch position isn't in PRESSED state if (!touchIsPressed[i]) { // set pressed and pressed coordinate. touchIsPressed[i] = true; pressTouches[i] = Point2f{ float(touch[int(touchpadType)].report[i].x) / 2.f, float(touch[int(touchpadType)].report[i].y) / 2.f }; touchPressTimes[i] = GetTimeNow(); } } } // PRESS UNDER current touch position or NO PRESS (anymore, e.g. touchVPos is -1 and i is 0) // Triggered on a release of a finger at the latest i not hitting the above i index. else { // if it was pressed while the num if (touchIsPressed[i]) { touchIsReleased[i] = true; } touchIsPressed[i] = false; if (touchIsReleased[i]) { // Set release position at index i releaseTouches[i] = Point2f{ float(touch[int(touchpadType)].report[i].x) / 2.f, float(touch[int(touchpadType)].report[i].y) / 2.f }; if (PSV_TSMode == PSV_TOUCH_SWIPE) { // PUSHING EVENT TO QUEUE { // Events declarations and defining PSV_Event e{ PSV_TOUCHPAD_SWIPE }; PSV_TouchpadEvent tpEvent{ touchpadType }; // set tpEvent variables tpEvent.releaseTouch = releaseTouches[i]; tpEvent.pressTouch = pressTouches[i]; tpEvent.touchVectorNum = i; tpEvent.reportNum = reportNum; tpEvent.angleRad = AngleBetweenPoints(pressTouches[i], releaseTouches[i]); tpEvent.angleDegrees = RadiansToDegrees(tpEvent.angleRad); tpEvent.length = DistanceBetweenPoints(pressTouches[i], releaseTouches[i]); tpEvent.velocity = tpEvent.length / (GetTimeNow() - touchPressTimes[i]); // Radian angle correction if (tpEvent.angleRad < 0) { tpEvent.angleRad += M_PI * 2; } const PSV_TouchpadSwipeDirection direction{ GetDirection(tpEvent.angleDegrees) }; tpEvent.touchpadSwipeDirection = direction; // set PSV_Event tpEvent as local tpEvent e.tpEvent = tpEvent; // Pushing the PSV_Event to the local queue events.push(e); } } else { // PUSHING EVENT TO QUEUE { // Events declarations and defining PSV_Event e{ PSV_TOUCHPAD_UP }; PSV_TouchpadEvent tpEvent{ touchpadType }; // set tpEvent variables tpEvent.releaseTouch = releaseTouches[i]; tpEvent.touchVectorNum = i; tpEvent.reportNum = reportNum; // set PSV_Event tpEvent as local tpEvent e.tpEvent = tpEvent; // Pushing the PSV_Event to the local queue events.push(e); } } } } } return events; } PSV_TouchpadSwipeDirection PSV_Touchpad::GetDirection(int angle) { if (AngleInRange(angle, 45, 135)) { return SWIPE_UP; } if (AngleInRange(angle, 0, 45) || AngleInRange(angle, 315, 360)) { return SWIPE_RIGHT; } if (AngleInRange(angle, 225, 315)) { return SWIPE_DOWN; } return SWIPE_LEFT; } #pragma endregion PSV Touchpad #pragma region PSV Functions void PSV_Init() { PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{CROSS, PSV_Button{ SCE_CTRL_CROSS, CROSS } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{CIRCLE, PSV_Button{ SCE_CTRL_CIRCLE, CIRCLE } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{SQUARE, PSV_Button{ SCE_CTRL_SQUARE, SQUARE } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{TRIANGLE, PSV_Button{ SCE_CTRL_TRIANGLE, TRIANGLE } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{ LTRIGGER, PSV_Button{ SCE_CTRL_LTRIGGER, LTRIGGER } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{ RTRIGGER, PSV_Button{ SCE_CTRL_RTRIGGER, RTRIGGER } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{ DPAD_UP, PSV_Button{ SCE_CTRL_UP, DPAD_UP } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{ DPAD_DOWN, PSV_Button{ SCE_CTRL_DOWN, DPAD_DOWN } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{ DPAD_LEFT, PSV_Button{ SCE_CTRL_LEFT, DPAD_LEFT } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{ DPAD_RIGHT, PSV_Button{ SCE_CTRL_RIGHT, DPAD_RIGHT } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{ START, PSV_Button{ SCE_CTRL_START, START } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{ SELECT, PSV_Button{ SCE_CTRL_SELECT, SELECT } }); PSV_Buttons.insert(std::pair<PSV_ButtonType, PSV_Button>{ SELECT, PSV_Button{ SCE_CTRL_SELECT, SELECT } }); PSV_Joysticks.insert(std::pair<PSV_JoystickType, PSV_Joystick>{ LSTICK, PSV_Joystick{ LSTICK } }); PSV_Joysticks.insert(std::pair<PSV_JoystickType, PSV_Joystick>{ RSTICK, PSV_Joystick{ RSTICK } }); PSV_Touchpads.insert(std::pair<PSV_TouchpadType, PSV_Touchpad>{ FRONT, PSV_Touchpad{ FRONT }}); PSV_Touchpads.insert(std::pair<PSV_TouchpadType, PSV_Touchpad>{ BACK, PSV_Touchpad{ BACK }}); } void PSV_Update(SceCtrlData& pad, SceTouchData* touch, SceTouchData* touchOld) { for (std::pair<const PSV_ButtonType, PSV_Button>& pair : PSV_Buttons) { PSV_EventsQueue.push(pair.second.Update(pad)); } for (std::pair<const PSV_JoystickType, PSV_Joystick>& pair : PSV_Joysticks) { PSV_EventsQueue.push(pair.second.Update(pad)); } for (std::pair<const PSV_TouchpadType, PSV_Touchpad>& pair : PSV_Touchpads) { std::queue<PSV_Event> touchEventsQueue = pair.second.Update(touch, touchOld); while(!touchEventsQueue.empty()) { PSV_EventsQueue.push(touchEventsQueue.front()); touchEventsQueue.pop(); } } } int PSV_PollEvent(PSV_Event& e) { if(!PSV_EventsQueue.empty()) { e = PSV_EventsQueue.front(); PSV_EventsQueue.pop(); return 1; } return 0; } #pragma endregion PSV Functions
25.876797
139
0.654103
[ "vector" ]
e8a29fbbfa3720137dad38059a59a8f1a63713d5
10,943
cpp
C++
c/lib/miscl/Debug.cpp
knowm/nSpace
1e5380a8778e013f7e8c44c130ba32e9668755ed
[ "BSD-3-Clause" ]
2
2020-05-06T21:45:13.000Z
2020-06-14T11:48:03.000Z
c/lib/miscl/Debug.cpp
knowm/nSpace
1e5380a8778e013f7e8c44c130ba32e9668755ed
[ "BSD-3-Clause" ]
null
null
null
c/lib/miscl/Debug.cpp
knowm/nSpace
1e5380a8778e013f7e8c44c130ba32e9668755ed
[ "BSD-3-Clause" ]
3
2017-09-18T14:46:03.000Z
2021-09-26T17:10:36.000Z
//////////////////////////////////////////////////////////////////////// // // DIST.CPP // // Implementation of the distribution node // //////////////////////////////////////////////////////////////////////// #include "miscl_.h" #include <stdio.h> // Globals static WCHAR wDbgBfr[16384]; static WCHAR wDbgBfr2[sizeof(wDbgBfr)/sizeof(WCHAR)]; static sysCS csDebug; #define DBGSZ sizeof(wDbgBfr)/sizeof(WCHAR) Debug :: Debug ( void ) { //////////////////////////////////////////////////////////////////////// // // PURPOSE // - Constructor for the node // //////////////////////////////////////////////////////////////////////// pDctLog = NULL; // Windows specific performance frequency #ifdef _WIN32 LARGE_INTEGER li; QueryPerformanceFrequency ( &li ); lFreq = li.QuadPart; #endif } // Debug void Debug :: appendDbg ( const WCHAR *pwStr ) { //////////////////////////////////////////////////////////////////////// // // PURPOSE // - Append a string to the debug output buffer. // // PARAMETERS // - pwStr is the string to append // //////////////////////////////////////////////////////////////////////// // Only append if there is room if (wcslen(wDbgBfr)+wcslen(pwStr)+1 < DBGSZ) WCSCAT ( wDbgBfr, sizeof(wDbgBfr)/sizeof(wDbgBfr[0]), pwStr ); else dbgprintf ( L"WARNING:Debug buffer too small\r\n" ); } // appendDbg HRESULT Debug :: onAttach ( bool bAttach ) { //////////////////////////////////////////////////////////////////////// // // PURPOSE // - Called when this behaviour is assigned to a node // // PARAMETERS // - bAttach is true for attachment, false for detachment. // // RETURN VALUE // S_OK if successful // //////////////////////////////////////////////////////////////////////// HRESULT hr = S_OK; // Attach if (bAttach) { adtValue v; // Default message ? if (pnDesc->load ( adtString(L"Message"), v ) == S_OK) strMsg = v; } // if // Detach else { // Clean up _RELEASE(pDctLog); } // else return hr; } // onAttach void Debug :: logCallback ( cLogEntry *e, void *p ) { //////////////////////////////////////////////////////////////////////// // // PURPOSE // - Call back function for logging. // // PARAMETERS // - e is the log entry // - p is the callback parameters // //////////////////////////////////////////////////////////////////////// HRESULT hr = S_OK; Debug *pThis = (Debug *)p; adtDate date; // Logging dictionary needed ? if (hr == S_OK && pThis->pDctLog == NULL) hr = COCREATE(L"Adt.Dictionary",IID_IDictionary,&(pThis->pDctLog)); // Transfer information to dictionary CCLTRY ( pThis->pDctLog->clear() ); // CCLTRY ( adtDate::fromSystemTime ( &(e->date), &(date.vdate) ) ); // CCLTRY ( pThis->pDctLog->store ( adtString(L"Date"), date ) ); // CCLTRY ( pThis->pDctLog->store ( adtString(L"Function"), adtString((WCHAR *)(e->func+1)) ) ); CCLTRY ( pThis->pDctLog->store ( adtString(L"File"), adtString((WCHAR *)(e->file+1)) ) ); CCLTRY ( pThis->pDctLog->store ( adtString(L"Line"), adtInt(e->line) ) ); CCLTRY ( pThis->pDctLog->store ( adtString(L"Level"), adtInt(e->level) ) ); CCLTRY ( pThis->pDctLog->store ( adtString(L"Value"), adtString((WCHAR *)(e->str+1)) ) ); // Emit entry // CCLOK ( pThis->peOnLog->emit(adtIUnknown(pThis->pDctLog) ); ) } // logCallback HRESULT Debug :: onReceive ( IReceptor *pr, const ADTVALUE &v ) { //////////////////////////////////////////////////////////////////////// // // FROM IBehaviour // // PURPOSE // - The node has received a value on the specified receptor. // // PARAMETERS // - pr is the receptor // - v is the value // // RETURN VALUE // S_OK if successful // //////////////////////////////////////////////////////////////////////// HRESULT hr = S_OK; // Fire if (_RCP(Fire)) { adtString sValue; adtValue vL,vDbg; // Thread safety if (!csDebug.enter()) return E_UNEXPECTED; // Setup WCSCPY ( wDbgBfr, sizeof(wDbgBfr)/sizeof(wDbgBfr[0]), L"" ); // For easier identification of source of debug, access the definition // of the container graph. if (strPath.length() == 0) { IDictionary *pPar = NULL; IDictionary *pDsc = NULL; adtIUnknown unkV; // Path to this location nspcPathTo ( pnLoc, L"./", strPath ); // if (!WCASECMP(strPath,L"/apps/auto/default/TreeDirect/Render/list/static/tree/.visual/Debug/")) // dbgprintf ( L"Hi\r\n" ); // Reference location for hosting graph if ( pnLoc->load ( strnRefPar, vL ) == S_OK && (IUnknown *)(NULL) != (unkV=vL) && _QI(unkV,IID_IDictionary,&pPar) == S_OK && // pPar->load ( strnRefDesc, vL ) == S_OK && // (IUnknown *)(NULL) != (unkV=vL) && // _QI(unkV,IID_IDictionary,&pDsc) == S_OK && // pDsc->load ( strnRefLocn, vL ) == S_OK && pPar->load ( strnRefLocn, vL ) == S_OK && adtValue::toString ( vL, sValue ) == S_OK) { strPath.append ( L" (" ); strPath.append ( sValue ); strPath.append ( L")" ); } // if // Clean up _RELEASE(pDsc); _RELEASE(pPar); } // if // Path to node appendDbg ( strPath ); appendDbg ( L": " ); // Message if (strMsg.length()) { appendDbg ( strMsg ); appendDbg ( L": " ); } // if // Value for debug if (hr == S_OK && v.vtype == (VTYPE_VALUE|VTYPE_BYREF) && v.pval != NULL) hr = adtValue::copy ( *(v.pval), vDbg ); else hr = adtValue::copy ( v, vDbg ); // Debug // if (!WCASECMP(strPath,L"/apps/auto/default/TestInst/Render/list/static/tree/Debug/ (render/gdi/dict/)")) // dbgprintf ( L"Hi\r\n" ); // Value switch (adtValue::type(vDbg)) { // Object ? case VTYPE_UNK : { IUnknown *punk = NULL; IDictionary *pLoc = NULL; IReceptor *pRecep = NULL; IByteStream *pStm = NULL; IMemoryMapped *pMem = NULL; IDictionary *pD = NULL; IList *pL = NULL; // Unknown ptr. punk = vDbg.punk; // Object type if (punk == NULL) appendDbg ( L"null," ); else if (_QI(punk,IID_IDictionary,&pD) == S_OK) { IIt *pKeys = NULL; adtValue vKey,vValue; swprintf ( SWPF(wDbgBfr2,DBGSZ), L"Dictionary(%p):", punk ); appendDbg ( wDbgBfr2 ); CCLTRY ( pD->keys ( &pKeys ) ); while (pKeys->read ( vKey ) == S_OK) { // Key if ( adtValue::toString ( vKey, sValue ) == S_OK) { swprintf ( SWPF(wDbgBfr2,DBGSZ), L"%ls(%d)=", (LPCWSTR) sValue, vKey.vtype ); appendDbg ( wDbgBfr2 ); } // if if ( pD->load ( vKey, vValue ) == S_OK && adtValue::toString ( vValue, sValue ) == S_OK) { swprintf ( SWPF(wDbgBfr2,DBGSZ), L"%ls(%d),", (LPCWSTR) sValue, vValue.vtype ); appendDbg ( wDbgBfr2 ); } // if // Next key pKeys->next(); } // while // Clean up _RELEASE(pKeys); } // else if else if (_QI(punk,IID_IList,&pL) == S_OK) { IIt *pIt = NULL; adtValue vValue; // Print out values swprintf ( SWPF(wDbgBfr2,DBGSZ), L"Container(%p):", punk ); appendDbg ( wDbgBfr2 ); CCLTRY ( pL->iterate ( &pIt ); ) while (hr == S_OK && pIt->read ( vValue ) == S_OK) { if ( adtValue::toString ( vValue, sValue ) == S_OK) { swprintf ( SWPF(wDbgBfr2,DBGSZ), L"%ls,", (LPCWSTR) sValue ); appendDbg ( wDbgBfr2 ); } // if // Next key pIt->next(); } // while // Clean up _RELEASE(pIt); } // else if /* else if (_QI(punk,IID_ILocation,&pLoc) == S_OK) { IDictionary *pDesc = NULL; IDictionary *pEmit = NULL; adtValue v; adtIUnknown unkV; adtString strName,strBehave; // Optional descriptor CCLTRY ( pLoc->load ( adtString(STR_NSPC_DESC), v ) ); CCLTRY ( _QISAFE((unkV=v),IID_IDictionary,&pDesc) ); CCLTRY ( pDesc->load ( adtString(STR_NSPC_NAME), v ) ); CCLOK ( strName = v; ) CCLTRY ( pDesc->load ( adtString(STR_NSPC_BEHAVE), v ) ); CCLOK ( strBehave = v; ) // Debug swprintf ( SWPF(wDbgBfr2,DBGSZ), L"Location:%p", pLoc ); appendDbg ( wDbgBfr2 ); if (hr == S_OK) { swprintf ( SWPF(wDbgBfr2,DBGSZ), L":%ls:%ls", (LPCWSTR)strName, (LPCWSTR)strBehave ); appendDbg ( wDbgBfr2 ); } // if // Clean up _RELEASE(pDesc); _RELEASE(pEmit); _RELEASE(pLoc); } // else if */ else if (_QI(punk,IID_IReceptor,&pRecep) == S_OK) { swprintf ( SWPF(wDbgBfr2,DBGSZ), L"Receptor:%p", punk ); appendDbg ( wDbgBfr2 ); } // else if else if (_QI(punk,IID_IByteStream,&pStm) == S_OK) { U64 pos = 0,len = 0; // Current position and length CCLTRY ( pStm->seek ( 0, STREAM_SEEK_CUR, &pos ) ); CCLTRY ( pStm->available ( &len ) ); swprintf ( SWPF(wDbgBfr2,DBGSZ), L"Stream:Position %d/Length %d", (S32)pos, (S32)(pos+len) ); appendDbg ( wDbgBfr2 ); } // else if else if (_QI(punk,IID_IMemoryMapped,&pMem) == S_OK) { U32 sz = 0; // Current size CCLTRY( pMem->getSize(&sz) ); swprintf ( SWPF(wDbgBfr2,DBGSZ), L"Memory:Size %d bytes", sz ); appendDbg ( wDbgBfr2 ); } // else if else { swprintf ( SWPF(wDbgBfr2,DBGSZ), L"Object (%p)", punk ); appendDbg ( wDbgBfr2 ); } // else // Clean up _RELEASE(pL); _RELEASE(pD); _RELEASE(pMem); _RELEASE(pStm); _RELEASE(pRecep); _RELEASE(pLoc); } // VT_UNKNOWN break; // Other default : adtValue::toString ( vDbg, sValue ); swprintf ( SWPF(wDbgBfr2,DBGSZ), L"%ls (%d)", (LPCWSTR)sValue, vDbg.vtype ); appendDbg ( wDbgBfr2 ); } // switch // Done lprintf ( LOG_DBG, L"%s\r\n", wDbgBfr ); // dbgprintf ( L"%s\r\n", wDbgBfr ); csDebug.leave(); } // if /* // Logging on/off else if (_RCP(Log)) { adtBool bLog(v); // Enable/disable logging sink // TODO: Multiple callbacks logSink ( (bLog == true) ? logCallback : NULL, this ); } // else if */ // Debug break else if (_RCP(Break)) { dbgprintf ( L"MiscDebug::receive:Break @ %s\r\n", (LPCWSTR)strnName ); #ifdef _DEBUG DebugBreak(); #endif dbgprintf ( L"MiscDebug::receive:Break @ %s\r\n", (LPCWSTR)strnName ); } // else if // Timing else if (_RCP(Reset)) { #ifdef _WIN32 LARGE_INTEGER lCnt; QueryPerformanceCounter ( &lCnt ); lRst = lCnt.QuadPart; #endif // dbgprintf ( L"MiscDebug::%s:%d\r\n", (LPCWSTR)strMsg, dwT0 ); } // else if else if (_RCP(Mark)) { #ifdef _WIN32 LARGE_INTEGER lCnt; QueryPerformanceCounter ( &lCnt ); // Compute difference double dt = ((lCnt.QuadPart-lRst) * 1.0) / lFreq; dbgprintf ( L"MiscDebug:%s:%s:%g s\r\n", (LPCWSTR)strMsg, (LPCWSTR) strnName, dt );//, dwT1, dwT0 ); #endif } // else if else if (_RCP(Sleep)) { adtInt iMs(v); #ifdef _WIN32 Sleep(iMs); #else usleep(iMs*1000); #endif } // else if else hr = ERROR_NO_MATCH; return hr; } // receive
25.627635
108
0.535776
[ "render", "object" ]
e8a32ff2a69f2572bd4f2374730f485486072a1b
60,299
cpp
C++
spencer-tracing/src/main/c++/NativeInterface.cpp
kaeluka/spencer-all
fc3e17137a3b7ee3f27d1316588c7db79451c468
[ "MIT" ]
null
null
null
spencer-tracing/src/main/c++/NativeInterface.cpp
kaeluka/spencer-all
fc3e17137a3b7ee3f27d1316588c7db79451c468
[ "MIT" ]
null
null
null
spencer-tracing/src/main/c++/NativeInterface.cpp
kaeluka/spencer-all
fc3e17137a3b7ee3f27d1316588c7db79451c468
[ "MIT" ]
null
null
null
#define ENABLED #include "Debug.h" #include "NativeInterface.h" #include <iostream> #include "events.h" #include "MonitorGuard.hh" #include "tagging.hh" #include <fcntl.h> #include <unistd.h> #include <capnp/serialize.h> #include <sstream> #include <netdb.h> #include <netinet/tcp.h> #include <stdlib.h> #include <algorithm> #include <pwd.h> using namespace std; //extern std::atomic_long nextObjID; /*******************************************************************/ /* Global Data */ /*******************************************************************/ int capnproto_fd; #define SOCKET_PORT "1345" std::string tracefilename = "none"; bool traceToDisk = false; // global ref to jvmti enviroment static jvmtiEnv *g_jvmti = NULL; static bool flag_application_only = false; // indicates JVM initialization static bool g_init = false; // indicates JVM death static bool g_dead = false; jvmtiError g_jvmtiError; // prefixes of classes that will not be instrumented before the live phase: std::vector<std::string> onlyDuringLivePhaseMatch; struct SpencerClassRedefinition { std::string name; jvmtiClassDefinition klassDef; }; std::vector<SpencerClassRedefinition> redefineDuringLivePhase; string kindToStr(jint v) { ASSERT(NativeInterface_SPECIAL_VAL_NORMAL <= v && v <= NativeInterface_SPECIAL_VAL_MAX); switch (v) { case NativeInterface_SPECIAL_VAL_NORMAL: return "SPECIAL_VAL_NORMAL"; case NativeInterface_SPECIAL_VAL_THIS: return "SPECIAL_VAL_THIS"; case NativeInterface_SPECIAL_VAL_STATIC: return "SPECIAL_VAL_STATIC"; case NativeInterface_SPECIAL_VAL_NOT_IMPLEMENTED: return "SPECIAL_VAL_NOT_IMPLEMENTED"; default: ERR("can't interpret val kind v"); return ""; } } static jrawMonitorID g_lock; std::string getThreadName() { // return "a thread"; jvmtiThreadInfo info; jthread thread; jvmtiError err = g_jvmti->GetCurrentThread(&thread); err = g_jvmti->GetThreadInfo(NULL, &info); if (err == JVMTI_ERROR_WRONG_PHASE) { //return "<unknown thread>"; if (thread == NULL) { return "<JVM_Thread 0x0>"; } else { // GetThreadInfo works only during live phase std::stringstream ss; jlong tag; err = g_jvmti->GetTag(thread, &tag); ASSERT_NO_JVMTI_ERR(g_jvmti, err); if (tag == 0) { tag = nextObjID.fetch_add(1); DBG("tagging thread "<<thread<<" with "<<tag); err = g_jvmti->SetTag(thread, tag); ASSERT_NO_JVMTI_ERR(g_jvmti, err); } ss<<"<JVM_Thread "<<tag<<">"; return ss.str(); } } else { ASSERT_NO_JVMTI_ERR(g_jvmti, err); std::string ret(info.name); g_jvmti->Deallocate((unsigned char*)info.name); if (ret == "") { return "<unnamed thread>"; } else { return ret; } } /* jvmtiThreadInfo info; err = g_jvmti->GetThreadInfo(thread, &info); if (err == JVMTI_ERROR_WRONG_PHASE) { if (thread == NULL) { threadName = "JVM_Thread<0x0>"; } else { DBG("tagging startup thread "<<thread); // GetThreadInfo works only during live phase std::stringstream ss; jlong tag; err = g_jvmti->GetTag(thread, &tag); ASSERT_NO_JVMTI_ERR(g_jvmti, err); if (tag == 0) { tag = nextObjID.fetch_add(20); err = g_jvmti->SetTag(thread, tag); ASSERT_NO_JVMTI_ERR(g_jvmti, err); } //getOrDoTag(NativeInterface_SPECIAL_VAL_NORMAL, thread, "java/lang/Thread", "wat", *g_jvmti, g_lock); //err = g_jvmti->SetTag(thread, tag); ss<<"JVM_Thread<"<<tag<<">"; threadName = ss.str(); } */ } std::string toCanonicalForm(std::string typ) { std::string ret = typ; std::replace(ret.begin(), ret.end(), '/', '.'); return ret; } std::string toInternalForm(std::string typ) { std::string ret = typ; std::replace(ret.begin(), ret.end(), '.', '/'); return ret; } void doFramePop(std::string mname, std::string cname) { std::string threadName = getThreadName(); capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; MethodExitEvt::Builder msgbuilder = innermessage.initRoot<MethodExitEvt>(); // "java/lang/Thread", thread, g_jvmti, g_lock); msgbuilder.setThreadName(threadName); msgbuilder.setName(mname); msgbuilder.setCname(cname); ASSERT(std::string("") != msgbuilder.getName().cStr()); anybuilder.setMethodexit(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } } inline bool isInLivePhase() { jvmtiPhase phase; jvmtiError err = g_jvmti->GetPhase(&phase); ASSERT_NO_JVMTI_ERR(g_jvmti, err); return (phase == JVMTI_PHASE_LIVE); } #define REQUIRE_LIVE() {if (!isInLivePhase()) { return; } } /*******************************************************************/ /* Socket management */ /*******************************************************************/ int setupSocket() { int sock; int status; struct addrinfo hints; struct addrinfo *servinfo; // address info for socket memset(&hints, 0, sizeof hints); // make sure the struct is empty hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6 hints.ai_socktype = SOCK_STREAM; // TCP stream sockets hints.ai_flags = AI_PASSIVE; // fill in my IP for me if ((status = getaddrinfo(NULL, SOCKET_PORT, &hints, &servinfo)) != 0) { ERR("getaddrinfo error: " << gai_strerror(status)); } sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol); if (sock < 0) { ERR("could not open socket (" << sock << ")"); } if (connect(sock, servinfo->ai_addr, servinfo->ai_addrlen) != 0) { ERR("Could not connect! Please make sure that the transformer " "program is running (path/to/java-alias-agent/transformer)"); } freeaddrinfo(servinfo); int flag = 1; setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int)); return sock; } void closeSocket(int sock) { close(sock); } size_t recvClass(int sock, unsigned char **data) { DBG("receiving class"); union { long i; unsigned char bs[8]; } x; x.i = 0; ssize_t rlen = recv(sock, x.bs, 8 * sizeof(unsigned char), 0); if (rlen == -1) { ERR("could not receive"); } size_t len = 0; for (int i = 0; i <= 7; ++i) { len += (size_t)(x.bs[i] << (8 * (7 - i))); } DBG("received length " << len); *data = (unsigned char *)calloc(len, sizeof(unsigned char)); rlen = recv(sock, *data, len * sizeof(unsigned char), MSG_WAITALL); DBG("rlen=" << rlen); ASSERT(rlen == len); closeSocket(sock); return (size_t)rlen; } void sendClass(int sock, const unsigned char *data, uint32_t len) { DBG("sending class, length = " << len); union { uint32_t i; unsigned char bs[4]; } x; x.i = len; send(sock, x.bs, sizeof(unsigned char) * 4, 0); send(sock, data, sizeof(unsigned char) * len, 0); //if (len >= 1000) { // return; //} //char empty[1000] = {0}; //ASSERT(sizeof(empty)==1000); //send(sock, empty, sizeof(empty), 0); closeSocket(sock); } void transformClass(const unsigned char *class_data, uint32_t class_data_len, unsigned char **new_class_data, uint32_t *new_class_data_len) { int sock; sock = setupSocket(); sendClass(sock, class_data, class_data_len); sock = setupSocket(); *new_class_data_len = (uint32_t)recvClass(sock, new_class_data); ASSERT(*new_class_data != class_data); } void handleLoadFieldA( JNIEnv *env, jclass native_interface, jobject val, jint holderKind, jobject holder, std::string holderClass, std::string fname, std::string type, std::string callerClass, std::string callerMethod, jint callerKind, jobject caller); void handleStoreFieldA( JNIEnv *env, jclass native_interface, jint holderKind, jobject holder, jobject newval, jobject oldval, std::string holderClass, std::string fname, std::string type, std::string callerClass, std::string callerMethod, jint callerKind, jobject caller); void handleModify(JNIEnv *env, jclass native_interface, jint calleeKind, jobject callee, std::string calleeClass, std::string fname, jint callerKind, jobject caller, std::string callerClass); void handleRead(JNIEnv *env, jclass native_interface, jint calleeKind, jobject callee, std::string calleeClass, std::string fname, jint callerKind, jobject caller, std::string callerClass); std::string getTypeForObj(JNIEnv *jni_env, jobject obj); /* returns a c++ string with content copied from a java str */ std::string toStdString(JNIEnv *env, jstring str) { //DBG("getting string "<<str); if (str == NULL) { return "NULL"; } const char *c_str = env->GetStringUTFChars(str, NULL); //DBG("got "<<c_str); const std::string result(c_str); env->ReleaseStringUTFChars(str, c_str); return result; } /*******************************************************************/ /* Event Callbacks */ /*******************************************************************/ /* * Class: NativeInterface * Method: loadArrayA * Signature: ([Ljava/lang/Object;ILjava/lang/Object;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)V */ JNIEXPORT void JNICALL Java_NativeInterface_loadArrayA (JNIEnv *env, jclass native_interface, jobjectArray arr, jint idx, jobject val, jstring _holderClass, jstring _callerMethod, jstring _callerClass, jint callerValKind, jobject caller) { REQUIRE_LIVE(); LOCK; stringstream field; field<<"_"<<idx; std::string holderClass = toStdString(env, _holderClass); std::string callerMethod = toStdString(env, _callerMethod); std::string callerClass = toStdString(env, _callerClass); std::string elementType = holderClass.substr(1); ASSERT_EQ("["+elementType, holderClass); handleLoadFieldA(env, native_interface, val, NativeInterface_SPECIAL_VAL_NORMAL, arr, holderClass, field.str(), elementType, callerClass, callerMethod, callerValKind, caller); } /* * Class: NativeInterface * Method: storeArrayA * Signature: (Ljava/lang/Object;[Ljava/lang/Object;ILjava/lang/Object;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)V */ JNIEXPORT void JNICALL Java_NativeInterface_storeArrayA (JNIEnv *env, jclass native_interface, jobject newVal, jobjectArray arr, jint idx, jobject oldVal, jstring _holderClass, jstring _callerMethod, jstring _callerClass, jint callerValKind, jobject caller) { REQUIRE_LIVE(); LOCK; stringstream field; field<<"_"<<idx; //std::string holderClass = toStdString(env, _holderClass); std::string callerMethod = toStdString(env, _callerMethod); std::string callerClass = toStdString(env, _callerClass); std::string holderClass = toStdString(env, _holderClass); std::string elementType = holderClass.substr(1); ASSERT_EQ("["+elementType, holderClass); handleStoreFieldA(env, native_interface, NativeInterface_SPECIAL_VAL_NORMAL, arr, newVal, oldVal, holderClass, field.str(), elementType, callerClass, callerMethod, callerValKind, caller); } /* * Class: NativeInterface * Method: readArray * Signature: (Ljava/lang/Object;IILjava/lang/Object;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_NativeInterface_readArray (JNIEnv *env, jclass nativeInterface, jobject arr, jint idx, jint callerValKind, jobject caller, jstring callerClass) { REQUIRE_LIVE(); LOCK; stringstream field; field<<"_"<<idx; handleRead(env, nativeInterface, NativeInterface_SPECIAL_VAL_NORMAL, arr, getTypeForObj(env, arr), field.str(), callerValKind, caller, toStdString(env, callerClass)); } /* * Class: NativeInterface * Method: modifyArray * Signature: (Ljava/lang/Object;IILjava/lang/Object;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_NativeInterface_modifyArray (JNIEnv *env, jclass nativeInterface, jobject arr, jint idx, jint callerValKind, jobject caller, jstring callerClass) { REQUIRE_LIVE(); LOCK; stringstream field; field<<"_"<<idx; handleModify(env, nativeInterface, NativeInterface_SPECIAL_VAL_NORMAL, arr, getTypeForObj(env, arr), field.str(), callerValKind, caller, toStdString(env, callerClass)); } JNIEXPORT void JNICALL Java_NativeInterface_methodExit(JNIEnv *env, jclass, jstring _mname, jstring _cname) { #ifdef ENABLED REQUIRE_LIVE(); LOCK; const auto mname = toStdString(env, _mname); const auto cname = toStdString(env, _cname); ASSERT(mname != ""); DBG("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); DBG("Java_NativeInterface_methodExit: ...::"<<mname<<"), thd: "<<getThreadName()); ASSERT(mname != "ClassRep"); doFramePop(mname, cname); DBG("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); #endif } /** Get the currently running this (best effort, will return NULL at least for native methods and before the live phase). Must not be called from static method. */ jobject getThis() { LOCK; jobject ret; if (g_jvmti == NULL) { return NULL; } jvmtiError err = g_jvmti->GetLocalObject(NULL, //use current thread 0, //stack depth 0, //variable 0 -- this &ret); if (err == JVMTI_ERROR_OPAQUE_FRAME || JVMTI_ERROR_WRONG_PHASE) { return NULL; } else { ASSERT_NO_JVMTI_ERR(g_jvmti, err); return ret; } } std::string getTypeForObj(JNIEnv *jni_env, jobject obj) { ASSERT(obj != NULL); jclass klassKlass = jni_env->FindClass("java/lang/Class"); jmethodID getName = jni_env->GetMethodID(klassKlass, "getName", "()Ljava/lang/String;"); ASSERT(getName != NULL); jclass klass = jni_env->GetObjectClass(obj); jstring name = (jstring)jni_env->CallObjectMethod(klass, getName); if (name == NULL) { return "<anonymousClass>"; } // we tag the string as not instrumented, as we don't want it to end up in the data! jvmtiError err = g_jvmti->SetTag(name, NativeInterface_SPECIAL_VAL_NOT_INSTRUMENTED); if (err == JVMTI_ERROR_INVALID_OBJECT || err == JVMTI_ERROR_WRONG_PHASE) { WARN("got JVMTI_ERROR_INVALID_OBJECT or JVMTI_ERROR_WRONG_PHASE"); } else { ASSERT_NO_JVMTI_ERR(g_jvmti, err); } std::string nameStr = toStdString(jni_env, name); std::replace(nameStr.begin(), nameStr.end(), '.', '/'); return nameStr; } std::string getClassName(JNIEnv *jni_env, jclass obj) { jclass klassKlass = jni_env->FindClass("java/lang/Class"); ASSERT(klassKlass); jmethodID getName = jni_env->GetMethodID(klassKlass, "getName", "()Ljava/lang/String;"); ASSERT(getName != NULL); jstring ret = (jstring)jni_env->CallObjectMethod(obj, getName); // we tag the string as not instrumented, as we don't want it to end up in the data! g_jvmti->SetTag(ret, NativeInterface_SPECIAL_VAL_NOT_INSTRUMENTED); return toInternalForm(toStdString(jni_env, ret)); } std::string getToString(JNIEnv *jni_env, jobject obj) { jclass objKlass = jni_env->FindClass("java/lang/Object"); ASSERT(objKlass); jmethodID toString = jni_env->GetMethodID(objKlass, "toString", "()Ljava/lang/String;"); ASSERT(toString != NULL); jstring ret = (jstring)jni_env->CallObjectMethod(obj, toString); // we tag the string as not instrumented, as we don't want it to end up in the data! g_jvmti->SetTag(ret, NativeInterface_SPECIAL_VAL_NOT_INSTRUMENTED); return toStdString(jni_env, ret); } std::string getTypeForThis(JNIEnv *jni_env) { return getTypeForObj(jni_env, getThis()); } std::string getTypeForObjKind(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jobject obj, jint kind, jstring definitionKlass) { ASSERT(definitionKlass != NULL); switch (kind) { case NativeInterface_SPECIAL_VAL_NORMAL: { return getTypeForObj(jni_env, obj); } case NativeInterface_SPECIAL_VAL_THIS: { jobject _this = getThis(); if (_this == NULL) { return toStdString(jni_env, definitionKlass); } else { return getTypeForObj(jni_env, _this); } } case NativeInterface_SPECIAL_VAL_STATIC: { return toCanonicalForm(toStdString(jni_env, definitionKlass)); } default: ERR("Can't handle kind "<<kind); } } jobject getObjectForTag(JNIEnv *jni_env, jlong tag) { jint count = -1; jobject *obj_res = NULL; g_jvmti->GetObjectsWithTags(1, // Tag count &tag, &count, &obj_res, NULL); if (count == 0) { // the object does not exist or has been GCd g_jvmti->Deallocate((unsigned char*)obj_res); return NULL; } else { ASSERT_EQ(count, 1); jobject ret = *obj_res; g_jvmti->Deallocate((unsigned char*)obj_res); return ret; } } std::string getTypeForTag(JNIEnv *jni_env, jlong tag) { auto obj = getObjectForTag(jni_env, tag); if (obj != NULL) { return getTypeForObj(jni_env, obj); } else { return "N/A"; } } void tagUntaggedClasses(JNIEnv *jni); void printUntaggedClasses(JNIEnv *jni) { jclass *klasses; jint klasses_count; jvmtiError err = g_jvmti->GetLoadedClasses(&klasses_count, &klasses); ASSERT_NO_JVMTI_ERR(g_jvmti, err); for (jint i=0; i<klasses_count; ++i) { long tag; err = g_jvmti->GetTag(klasses[i], &tag); ASSERT_NO_JVMTI_ERR(g_jvmti, err); auto className = getClassName(jni, klasses[i]); if (tag == 0) { DBG("stubbornly untagged class: "<<className); } else { DBG(" tagged class: "<<className<<", tag = "<<tag); } } } std::map<const std::string, const jlong> klassReps; jlong getClassRepTag(JNIEnv *jni, const std::string &className) { DBG("getClassRepTag(.., "<<className<<")") if (klassReps.find(className) == klassReps.end()) { tagUntaggedClasses(jni); } if (klassReps.find(className) == klassReps.end()) { long tag = -1 * nextObjID.fetch_add(1); WARN("can't find class rep tag for "<<className<<", synthesizing "<<tag); klassReps.insert({ { className, tag } }); } return klassReps[className]; } long getTag(JNIEnv *jni, jint objkind, jobject jobj, std::string klass) { jlong tag = 0; switch (objkind) { case NativeInterface_SPECIAL_VAL_NORMAL: { if (jobj) { jvmtiError err = g_jvmti->GetTag(jobj, &tag); DBG("getting tag (" << klass << " @ " << tag << ") from JVMTI"); ASSERT_NO_JVMTI_ERR(g_jvmti, err); } } break; case NativeInterface_SPECIAL_VAL_THIS: { jobject obj = getThis(); if (obj == NULL) { return NativeInterface_SPECIAL_VAL_JVM; //this is emitted too often } else { return getTag(jni, NativeInterface_SPECIAL_VAL_NORMAL, obj, klass); } } case NativeInterface_SPECIAL_VAL_STATIC: { tag = getClassRepTag(jni, klass); DBG("getting tag (" << klass << " @ " << tag << ") from classRep"); break; } case NativeInterface_SPECIAL_VAL_NOT_IMPLEMENTED: { ERR("SPECIAL_VAL_NOT_IMPLEMENTED"); break; } default: ERR("Can not get tag for object with kind "<<objkind); } return tag; } std::vector<long> irregularlyTagged; long getOrDoTagNonNull(JNIEnv *jni, jint objkind, jobject jobj, std::string klass) { DBG("kind="<<kindToStr(objkind)<<", klass="<<klass<<", jobj="<<jobj); ASSERT(jobj != NULL || objkind == NativeInterface_SPECIAL_VAL_STATIC && "can't handle NULL references"); jlong tag = getTag(jni, objkind, jobj, klass); if (tag == 0) { tag = doTag(g_jvmti, jobj); if (isInLivePhase()) { // LOCK; // WARN("irregularly tagged object #"<<tag//<<" : "<<getTypeForTag(jni, tag) // <<" (as string: "<<getToString(jni, jobj)<<") in live phase"); } else { irregularlyTagged.push_back(tag); } DBG("setting tag (" << klass << " @ " << tag << ") using doTag"); ASSERT(tag != 0); } return tag; } long getOrDoTag(JNIEnv *jni, jint objkind, jobject jobj, std::string klass) { if (jobj == NULL && objkind == NativeInterface_SPECIAL_VAL_NORMAL) { return 0; } else { return getOrDoTagNonNull(jni, objkind, jobj, klass); } } struct SourceLoc { std::string file; int line; }; SourceLoc getSourceLoc(jint depth) { SourceLoc ret; if (isInLivePhase()) { jmethodID callingMethod; jlocation callsite; jvmtiError err = g_jvmti->GetFrameLocation(NULL, //use current thread depth, //get the frame above &callingMethod, &callsite); if (err == JVMTI_ERROR_NO_MORE_FRAMES) { ret.file = "<no more frames>"; ret.line = -1; } else { ASSERT_NO_JVMTI_ERR(g_jvmti, err); jvmtiLineNumberEntry *lineNumbers; jint lineNumberEntryCount; err = g_jvmti->GetLineNumberTable(callingMethod, &lineNumberEntryCount, &lineNumbers); if (err != JVMTI_ERROR_ABSENT_INFORMATION && err != JVMTI_ERROR_NATIVE_METHOD) { ASSERT_NO_JVMTI_ERR(g_jvmti, err); jint lineNumber = -1; for (int i=0; i<lineNumberEntryCount; ++i) { // DBG("is it "<<lineNumbers[i].start_location<<"?"); if (lineNumbers[i].start_location > callsite) { // DBG("it is!"); break; } else { lineNumber = lineNumbers[i].line_number; } } g_jvmti->Deallocate((unsigned char*)lineNumbers); jclass declaring_class; err = g_jvmti->GetMethodDeclaringClass(callingMethod, &declaring_class); ASSERT_NO_JVMTI_ERR(g_jvmti, err); char *callsitefile; err = g_jvmti->GetSourceFileName(declaring_class, &callsitefile); ASSERT_NO_JVMTI_ERR(g_jvmti, err); ret.file = callsitefile; g_jvmti->Deallocate((unsigned char*)callsitefile); ret.line = lineNumber; } else { ret.file = "<absent information>"; ret.line = -1; } } } else { ret.file = "<not instrumented>"; ret.line = -1; } return ret; } bool tagFreshlyInitialisedObject(JNIEnv *jni, jobject callee, std::string threadName) { DBG("tagFreshlyInitialisedObject(..., threadName = " << threadName << ")"); ASSERT(g_jvmti); ASSERT(callee); if (getTag(jni, NativeInterface_SPECIAL_VAL_NORMAL, callee, "class/unknown") != 0) { return false; } jlong tag; DBG("thread " << threadName << ": don't have an object ID"); tag = nextObjID.fetch_add(1); DBG("tagging freshly initialised object with id " << tag); jvmtiError err = g_jvmti->SetTag(callee, tag); ASSERT_NO_JVMTI_ERR(g_jvmti, err); return true; } void printStack() { for (jint i=1; i<=15; ++i) { SourceLoc loc = getSourceLoc(i); if (loc.file == "<no more frames>") { break; } std::cout << "frame #"<<i<<": "<<loc.file<<":"<<loc.line << std::endl; } } JNIEXPORT void JNICALL Java_NativeInterface_methodEnter(JNIEnv *env, jclass nativeinterfacecls, jstring name, jstring signature, jstring calleeClass, jint calleeKind, jobject callee, jobjectArray args) { #ifdef ENABLED REQUIRE_LIVE(); LOCK; DBG("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); std::string threadName = getThreadName(); std::string calleeClassStr; std::string nameStr = toStdString(env, name); calleeClassStr = toStdString(env, calleeClass); DBG("Java_NativeInterface_methodEnter: "<<calleeClassStr <<"::" << nameStr <<", thd:"<<threadName); long calleeTag; DBG("calleeclass= " << calleeClassStr); if (calleeKind == NativeInterface_SPECIAL_VAL_STATIC) { callee = NULL; calleeTag = getClassRepTag(env, calleeClassStr); calleeClassStr = toStdString(env, calleeClass); } else { calleeTag = getOrDoTagNonNull(env, calleeKind, callee, toStdString(env, calleeClass)); } DBG("callee tag = " << calleeTag); DBG("calleeKind = " << calleeKind); DBG("thread nam = " << threadName); { capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; MethodEnterEvt::Builder msgbuilder = innermessage.initRoot<MethodEnterEvt>(); msgbuilder.setName(nameStr); msgbuilder.setSignature(toStdString(env, signature)); msgbuilder.setCalleeclass(toStdString(env, calleeClass)); msgbuilder.setCalleetag(calleeTag); if (isInLivePhase()) { SourceLoc loc = getSourceLoc(2); msgbuilder.setCallsitefile(loc.file); msgbuilder.setCallsiteline(loc.line); } else { msgbuilder.setCallsitefile("<not instrumented>"); msgbuilder.setCallsiteline(-1); } msgbuilder.setThreadName(threadName); anybuilder.setMethodenter(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } } { if (args != NULL) { DBG("emitting args "<<toStdString(env, calleeClass)<<"::"<<nameStr); const jsize N_ARGS = env->GetArrayLength((jarray)args); // std::cout << "N_ARGS=" << N_ARGS << "\n"; for (jsize i = 0; i < N_ARGS; ++i) { DBG("arg #"<<(i+1)); jobject arg = env->GetObjectArrayElement(args, i); if (arg == NULL) { continue; } //FIXME: the caller must be the the object in the stackframe above us! long tag = getOrDoTag(env, NativeInterface_SPECIAL_VAL_NORMAL, arg, "java/lang/Object"); if (tag == 0) { const auto klass = getTypeForObj(env, arg); tagFreshlyInitialisedObject(env, arg, getThreadName()); tag = getTag(env, NativeInterface_SPECIAL_VAL_NORMAL, arg, klass); ASSERT(tag != 0); { capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; MethodEnterEvt::Builder msgbuilder = innermessage.initRoot<MethodEnterEvt>(); innermessage.initRoot<MethodEnterEvt>(); msgbuilder.setName("<init>"); msgbuilder.setSignature("(<unknown>)V"); msgbuilder.setCalleeclass(klass); msgbuilder.setCalleetag(tag); SourceLoc loc = getSourceLoc(2); msgbuilder.setCallsitefile(loc.file); msgbuilder.setCallsiteline(loc.line); msgbuilder.setThreadName(getThreadName().c_str()); anybuilder.setMethodenter(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } } { doFramePop("<init>", calleeClassStr); } } capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; VarStoreEvt::Builder msgbuilder = innermessage.initRoot<VarStoreEvt>(); msgbuilder.setNewval(tag); msgbuilder.setOldval((int64_t)0); msgbuilder.setVar((int8_t)i); msgbuilder.setCallermethod(nameStr); // the callee of the call is the caller of the the var store: msgbuilder.setCallerclass(calleeClassStr); msgbuilder.setCallertag(calleeTag); msgbuilder.setThreadName(getThreadName()); anybuilder.setVarstore(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } } DBG("emitting args done"); } } DBG("methodEnter done"); #endif // ifdef ENABLED } JNIEXPORT void JNICALL Java_NativeInterface_afterInitMethod(JNIEnv *env, jclass native_interface, jobject callee, jstring calleeClass) { #ifdef ENABLED REQUIRE_LIVE(); LOCK; std::string calleeClassStr = toStdString(env, calleeClass); std::string threadName = getThreadName(); DBG("afterInitMethod(..., callee="<<callee<<", calleeClass=" << calleeClassStr << ")"); tagFreshlyInitialisedObject(env, callee, threadName); DBG("afterInitMethod done") #endif // ifdef ENABLED } JNIEXPORT void JNICALL Java_NativeInterface_newObj(JNIEnv *, jclass, jobject, jstring, jstring, jstring, jobject, jobject) { #ifdef ENABLED ERR("newObj not implemented"); #endif // ifdef ENABLED } void handleStoreFieldA(JNIEnv *env, jclass native_interface, jint holderKind, jobject holder, jobject newval, jobject oldval, std::string holderClass, std::string fname, std::string type, std::string callerClass, std::string callerMethod, jint callerKind, jobject caller) { #ifdef ENABLED LOCK; DBG("Java_NativeInterface_storeFieldA "<<holderClass<<"::"<<fname); auto threadName = getThreadName(); long callerTag = getOrDoTagNonNull(env, callerKind, caller, callerClass); DBG("getting holder tag, holderKind="<<holderKind); long holderTag = getOrDoTagNonNull(env, holderKind, holder, holderClass); DBG("getting oldval tag"); long oldvaltag = getOrDoTag(env, NativeInterface_SPECIAL_VAL_NORMAL, oldval, type.c_str()); DBG("getting newval tag"); long newvaltag = getOrDoTag(env, NativeInterface_SPECIAL_VAL_NORMAL, newval, type.c_str()); DBG("callertag ="<<callerTag); DBG("holdertag ="<<holderTag); DBG("newvaltag ="<<newvaltag); DBG("oldvaltag ="<<oldvaltag); DBG("callermthd="<<callerClass<<"::"<<callerMethod); capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; FieldStoreEvt::Builder msgbuilder = innermessage.initRoot<FieldStoreEvt>(); msgbuilder.setHolderclass(holderClass); msgbuilder.setHoldertag(holderTag); msgbuilder.setFname(fname); msgbuilder.setType(type); msgbuilder.setNewval(newvaltag); msgbuilder.setOldval(oldvaltag); msgbuilder.setCallermethod(callerMethod); msgbuilder.setCallerclass(callerClass); msgbuilder.setCallertag(callerTag); msgbuilder.setThreadName(getThreadName()); anybuilder.setFieldstore(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } #endif // ifdef ENABLED } JNIEXPORT void JNICALL Java_NativeInterface_storeFieldA(JNIEnv *env, jclass native_interface, jint holderKind, jobject holder, jobject newVal, jobject oldval, jstring _holderClass, jstring _fname, jstring _type, jstring _callerClass, jstring _callerMethod, jint callerKind, jobject caller) { #ifdef ENABLED REQUIRE_LIVE(); LOCK; std::string callerClass = toStdString(env, _callerClass); std::string holderClass = toStdString(env, _holderClass); std::string fname = toStdString(env, _fname); std::string type = toStdString(env, _type); std::string callerMethod = toStdString(env, _callerMethod); handleStoreFieldA(env, native_interface, holderKind, holder, newVal, oldval, holderClass, fname, type, callerClass, callerMethod, callerKind, caller); #endif // ifdef ENABLED } JNIEXPORT void JNICALL Java_NativeInterface_storeVar(JNIEnv *env, jclass native_interface, jint newValKind, jobject newVal, jint oldValKind, jobject oldval, jint var, jstring callerClass, jstring callerMethod, jint callerKind, jobject caller) { #ifdef ENABLED REQUIRE_LIVE(); LOCK; DBG("Java_NativeInterface_storeVar"); DBG("callerKind = "<<kindToStr(callerKind)); auto threadName = getThreadName(); ASSERT(oldValKind != NativeInterface_SPECIAL_VAL_STATIC); ASSERT(newValKind != NativeInterface_SPECIAL_VAL_STATIC); capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; VarStoreEvt::Builder msgbuilder = innermessage.initRoot<VarStoreEvt>(); msgbuilder.setCallerclass(toStdString(env, callerClass)); long newValTag = getTag(env, newValKind, newVal, msgbuilder.asReader().getCallerclass().cStr()); DBG("newValtag="<<newValTag); msgbuilder.setNewval(newValTag); msgbuilder.setOldval(0 /* this feature is not used in the instrumentation*/); msgbuilder.setVar((int8_t)var); msgbuilder.setCallermethod(toStdString(env, callerMethod)); msgbuilder.setCallertag(getOrDoTagNonNull(env, callerKind, caller, msgbuilder.asReader().getCallerclass().cStr())); msgbuilder.setThreadName(getThreadName()); anybuilder.setVarstore(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } DBG("storeVar done"); #endif // ifdef ENABLED } JNIEXPORT void JNICALL Java_NativeInterface_loadVar(JNIEnv *env, jclass native_interface, jint valKind, jobject val, jint var, jstring callerClass, jstring callerMethod, jint callerKind, jobject caller) { #ifdef ENABLED REQUIRE_LIVE(); LOCK; auto threadName = getThreadName(); DBG("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); DBG("Java_NativeInterface_loadVar " << var << " in " << toStdString(env, callerClass) << "::" << toStdString(env, callerMethod)); ASSERT(valKind != NativeInterface_SPECIAL_VAL_STATIC); capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; VarLoadEvt::Builder msgbuilder = innermessage.initRoot<VarLoadEvt>(); long valTag = getTag(env, valKind, val, "no/var/class/available"); long callerTag = getOrDoTagNonNull(env, callerKind, caller, toStdString(env, callerClass)); //getTag(env, NativeInterface_SPECIAL_VAL_NORMAL, caller, // toStdString(env, callerClass)); msgbuilder.setVal(valTag); DBG("valTag = " << valTag); DBG("callerTag = " << callerTag); DBG("callerKind = " << kindToStr(callerKind)); msgbuilder.setVar((char)var); msgbuilder.setCallermethod(toStdString(env, callerMethod)); msgbuilder.setCallerclass(toStdString(env, callerClass)); msgbuilder.setCallertag(callerTag); msgbuilder.setThreadName(getThreadName()); anybuilder.setVarload(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } #endif // ifdef ENABLED } void handleModify(JNIEnv *env, jclass native_interface, jint calleeKind, jobject callee, std::string calleeClass, std::string fname, jint callerKind, jobject caller, std::string callerClass) { #ifdef ENABLED LOCK; auto threadName = getThreadName(); DBG("Java_NativeInterface_modify"); capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; ReadModifyEvt::Builder msgbuilder = innermessage.initRoot<ReadModifyEvt>(); msgbuilder.setIsModify(true); msgbuilder.setCalleeclass(calleeClass); msgbuilder.setCalleetag(getOrDoTagNonNull(env, calleeKind, callee, msgbuilder.asReader().getCalleeclass().cStr())); msgbuilder.setFname(fname); msgbuilder.setCallerclass(callerClass); msgbuilder.setCallertag(getOrDoTagNonNull(env, callerKind, caller, msgbuilder.asReader().getCallerclass().cStr())); msgbuilder.setThreadName(getThreadName()); anybuilder.setReadmodify(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } DBG("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); #endif // ifdef ENABLED } JNIEXPORT void JNICALL Java_NativeInterface_modify(JNIEnv *env, jclass native_interface, jint calleeKind, jobject callee, jstring calleeClass, jstring fname, jint callerKind, jobject caller, jstring callerClass) { #ifdef ENABLED REQUIRE_LIVE(); LOCK; handleModify(env, native_interface, calleeKind, callee, toStdString(env, calleeClass), toStdString(env, fname), callerKind, caller, toStdString(env, callerClass)); #endif // ifdef ENABLED } void handleRead(JNIEnv *env, jclass native_interface, jint calleeKind, jobject callee, std::string calleeClass, std::string fname, jint callerKind, jobject caller, std::string callerClass) { #ifdef ENABLED REQUIRE_LIVE(); LOCK; auto threadName = getThreadName(); DBG("Java_NativeInterface_read"); capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; ReadModifyEvt::Builder msgbuilder = innermessage.initRoot<ReadModifyEvt>(); msgbuilder.setIsModify(false); msgbuilder.setCalleeclass(calleeClass); msgbuilder.setCalleetag(getOrDoTagNonNull(env, calleeKind, callee, msgbuilder.asReader().getCalleeclass().cStr())); msgbuilder.setFname(fname); msgbuilder.setCallerclass(callerClass); msgbuilder.setCallertag(getOrDoTagNonNull(env, callerKind, caller, msgbuilder.asReader().getCallerclass().cStr())); msgbuilder.setThreadName(getThreadName()); anybuilder.setReadmodify(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } #endif // ifdef ENABLED } JNIEXPORT void JNICALL Java_NativeInterface_read(JNIEnv *env, jclass nativeInterface, jint calleeKind, jobject callee, jstring calleeClass, jstring fname, jint callerKind, jobject caller, jstring callerClass) { #ifdef ENABLED REQUIRE_LIVE(); LOCK; handleRead(env, nativeInterface, calleeKind, callee, toStdString(env, calleeClass), toStdString(env, fname), callerKind, caller, toStdString(env, callerClass)); #endif // ifdef ENABLED } void handleLoadFieldA(JNIEnv *env, jclass native_interface, jobject val, jint holderKind, jobject holder, std::string holderClass, std::string fname, std::string type, std::string callerClass, std::string callerMethod, jint callerKind, jobject caller) { #ifdef ENABLED DBG("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); DBG("Java_NativeInterface_loadFieldA"); DBG("callerKind = "<<kindToStr(callerKind)); auto threadName = getThreadName(); capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; FieldLoadEvt::Builder msgbuilder = innermessage.initRoot<FieldLoadEvt>(); msgbuilder.setHolderclass(holderClass); msgbuilder.setHoldertag(getOrDoTagNonNull(env, holderKind, holder, msgbuilder.asReader().getHolderclass().cStr())); msgbuilder.setFname(fname); msgbuilder.setType(type); msgbuilder.setVal(getTag(env, NativeInterface_SPECIAL_VAL_NORMAL, val, msgbuilder.asReader().getType().cStr())); msgbuilder.setCallermethod(callerMethod); msgbuilder.setCallerclass(callerClass); msgbuilder.setCallertag(getTag(env, callerKind, caller, msgbuilder.asReader().getCallerclass().cStr())); msgbuilder.setThreadName(getThreadName()); anybuilder.setFieldload(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } DBG("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); #endif // ifdef ENABLED } JNIEXPORT void JNICALL Java_NativeInterface_loadFieldA(JNIEnv *env, jclass native_interface, jobject val, jint holderKind, jobject holder, jstring _holderClass, jstring _fname, jstring _type, jstring _callerClass, jstring _callerMethod, jint callerKind, jobject caller) { #ifdef ENABLED REQUIRE_LIVE(); LOCK; std::string holderClass = toStdString(env, _holderClass); std::string fname = toStdString(env, _fname); std::string type = toStdString(env, _type); std::string callerClass = toStdString(env, _callerClass); std::string callerMethod = toStdString(env, _callerMethod); handleLoadFieldA(env, native_interface, val, holderKind, holder, holderClass, fname, type, callerClass, callerMethod, callerKind, caller); #endif // ifdef ENABLED } void JNICALL VMObjectAlloc(jvmtiEnv *jvmti_env, JNIEnv *env, jthread threadName, jobject object, jclass object_klass, jlong size) { #ifdef ENABLED ERR("not prepared for this"); #endif } /* Sent by the VM when a class is being loaded into the VM Transforms loaded classes, if the VM is initialized and if loader!=NULL */ void JNICALL ClassFileLoadHook(jvmtiEnv *jvmti_env, JNIEnv *jni, jclass class_being_redefined, jobject loader, const char *_name, jobject protection_domain, jint class_data_len, const unsigned char *class_data, jint *new_class_data_len, unsigned char **new_class_data) { #ifdef ENABLED LOCK; ASSERT(class_data); std::string name; if (_name) { name = _name; } else { // Names can be empty. Weird! // http://docs.oracle.com/javase/1.5.0/docs/guide/jvmti/jvmti.html#ClassFileLoadHook name = ""; } DBG("ClassFileLoadHook: '" << name << "'"); DBG("inserting "<<name); klassReps.insert({{name, (-1)*nextObjID.fetch_add(1)}}); if (name == "java/lang/invoke/LambdaForm") { //these classes don't really exist, so they'll never be loaded. We'll give them //IDs anyway! klassReps.insert({{ "java/lang/invoke/LambdaForm$MH", (-1)*nextObjID.fetch_add(1)}}); klassReps.insert({{ "java/lang/invoke/LambdaForm$BMH", (-1)*nextObjID.fetch_add(1)}}); klassReps.insert({{ "java/lang/invoke/LambdaForm$DMH", (-1)*nextObjID.fetch_add(1)}}); klassReps.insert({{ "java/lang/invoke/LambdaForm$LFI", (-1)*nextObjID.fetch_add(1)}}); klassReps.insert({{ "java/lang/invoke/LambdaForm$NFI", (-1)*nextObjID.fetch_add(1)}}); } if (class_being_redefined != NULL) { //this is a call from RedefineClass. The class has been transformed already; DBG("class '"<<name<<"' has been redefined -- len="<<class_data_len); return; } if (name == "NativeInterface" || name == "sun/reflect/generics/repository/ClassRepository" // http://www.docjar.com/docs/api/sun/reflect/generics/repository/ClassRepository.html: [the class] is designed to be used unchanged by at least core reflection and JDI. || name == "sun/misc/Launcher$AppClassLoader" || name == "java/lang/Object" // there seem to be objects that generate an exit in Object::<init> but don't generate a matching enter.. ) { return; } if (!isInLivePhase()) { //check whether the class is marked as 'tricky'. If so, it should not be transformed now, but //redefined later. for (auto it = onlyDuringLivePhaseMatch.begin(); it != onlyDuringLivePhaseMatch.end(); ++it) { auto res = std::mismatch(it->begin(), it->end(), name.begin()); if (true || res.first == it->end()) { DBG("postponing transformation of class "<<name<<" -- len="<<class_data_len<< ", due to match with "<<*it); // match string is a prefix of class name SpencerClassRedefinition redef; redef.name = name; redef.klassDef.klass = NULL; redef.klassDef.class_byte_count = class_data_len; ASSERT(class_data_len > 0); unsigned char *class_data_cpy = (unsigned char*)malloc((unsigned long)class_data_len); memcpy(class_data_cpy, class_data, (unsigned long)class_data_len); redef.klassDef.class_bytes = class_data_cpy; redefineDuringLivePhase.push_back(redef); return; } } } jvmtiPhase phase; if (jvmti_env->GetPhase(&phase) != JVMTI_ERROR_NONE) { ERR("can't get phase"); } DBG("phase = " << phase); DBG("loader = " << loader); DBG("g_init = " << g_init); DBG("instrumenting class " << name); transformClass(class_data, (uint32_t)class_data_len, new_class_data, (uint32_t*)new_class_data_len); int minLen = *new_class_data_len < class_data_len ? *new_class_data_len : class_data_len; ASSERT(minLen > 0) if ((class_data_len != *new_class_data_len) || (memcmp(class_data, *new_class_data, (unsigned long)minLen) != 0)) { DBG("class "<<name<<" is instrumented: got changed class back"); } else { DBG("class "<<name<<" is not instrumented: got unchanged class back"); } // unsigned char **new_class_data_ignore; // recvClass(sock, new_class_data_ignore); // */ DBG("done"); #endif // ifdef ENABLED } struct FieldDescr { std::string name; long val; }; std::vector<FieldDescr> getFieldsForTag(jvmtiEnv *env, JNIEnv *jni, long tag) { auto niKlass = jni->FindClass("NativeInterface"); //jni->ExceptionDescribe(); ASSERT(niKlass != NULL); jmethodID midGetFields = jni->GetStaticMethodID(niKlass, "getAllFieldsArrHelper", "(Ljava/lang/Object;)[Ljava/lang/Object;"); jni->ExceptionDescribe(); ASSERT(midGetFields != NULL); std::vector<FieldDescr> ret; jobjectArray fields = (jobjectArray)jni->CallStaticObjectMethod(niKlass, midGetFields, getObjectForTag(jni, tag)); if (fields != NULL) { ASSERT(fields != NULL); jsize len = jni->GetArrayLength(fields); DBG(getTypeForTag(jni, tag)<<" has "<<(len/2)<<" fields"); for (int i=0; i<len/2; ++i) { FieldDescr fd; jstring fieldName = (jstring)jni->GetObjectArrayElement(fields, (jsize)(i*2)); jobject fieldVal = (jobject)jni->GetObjectArrayElement(fields, (jsize)(i*2+1)); fd.name = toStdString(jni, fieldName); fd.val = getTag(jni, NativeInterface_SPECIAL_VAL_NORMAL, fieldVal, "java/lang/Object"); /* if (fd.val == 0 && fieldVal != NULL) { WARN("have untagged fieldVal"); } */ ret.push_back(fd); } } else { DBG("got null for "<<getTypeForTag(jni, tag)); } return ret; } jvmtiIterationControl JNICALL handleUntaggedKlass(jlong class_tag, jlong size, jlong *tag_ptr, void *user_data) { std::vector<long> *freshlyTagged = (std::vector<long>*)user_data; *tag_ptr = -1 * nextObjID.fetch_add(1); freshlyTagged->push_back(*tag_ptr); return JVMTI_ITERATION_CONTINUE; } jvmtiIterationControl JNICALL handleUntaggedObject(jlong class_tag, jlong size, jlong *tag_ptr, void *user_data) { std::vector<long> *freshlyTagged = (std::vector<long>*)user_data; *tag_ptr = nextObjID.fetch_add(1); DBG("tagging untagged obj with "<<*tag_ptr); freshlyTagged->push_back(*tag_ptr); return JVMTI_ITERATION_CONTINUE; } void tagUntaggedClasses(JNIEnv *jni) { DBG("tagging untagged classes.."); jclass *klasses; jint klasses_count; jvmtiError err = g_jvmti->GetLoadedClasses(&klasses_count, &klasses); ASSERT_NO_JVMTI_ERR(g_jvmti, err); for (jint i=0; i<klasses_count; ++i) { long tag; err = g_jvmti->GetTag(klasses[i], &tag); ASSERT_NO_JVMTI_ERR(g_jvmti, err); auto className = getClassName(jni, klasses[i]); if (tag == 0) { tag = klassReps[className]; if (tag == 0) { tag = -1 * nextObjID.fetch_add(1); klassReps.insert({ { className, tag } }); } err = g_jvmti->SetTag(klasses[i], tag); ASSERT_NO_JVMTI_ERR(g_jvmti, err); DBG("tagged class: "<<className<<" as "<<tag); } } } /* The VM initialization event signals the completion of VM initialization. */ void JNICALL VMInit(jvmtiEnv *env, JNIEnv *jni, jthread threadName) { #ifdef ENABLED LOCK; DBG("VMInit"); { // tag objects that have not been tagged yet! // We start by iterating over all untagged classes, giving them negative indices. // We then iterate over all other untagged objects and give them positive indices. tagUntaggedClasses(jni); std::vector<long> freshlyTagged; jvmtiError err = env->IterateOverHeap(JVMTI_HEAP_OBJECT_UNTAGGED, handleUntaggedObject, &freshlyTagged); ASSERT_NO_JVMTI_ERR(env, err); DBG("got "<<freshlyTagged.size()<<" untagged objects"); DBG("late initialising "<<freshlyTagged.size() <<" objects"); for (auto it = freshlyTagged.begin(); it != freshlyTagged.end(); ++it) { DBG("freshlyTagged: "<<*it); capnp::MallocMessageBuilder outermessage; AnyEvt::Builder anybuilder = outermessage.initRoot<AnyEvt>(); capnp::MallocMessageBuilder innermessage; LateInitEvt::Builder msgbuilder = innermessage.initRoot<LateInitEvt>(); msgbuilder.setCalleetag(*it); auto klass = getTypeForTag(jni, *it); if (klass == "N/A") { continue; } msgbuilder.setCalleeclass(klass); auto fields = getFieldsForTag(env, jni, *it); auto fieldsBuilder = msgbuilder.initFields((unsigned int)fields.size()); unsigned int i=0; for (auto it = fields.begin(); it != fields.end(); ++it) { fieldsBuilder[i].setName(it->name); fieldsBuilder[i].setVal(it->val); ++i; } anybuilder.setLateinit(msgbuilder.asReader()); if (traceToDisk) { capnp::writeMessageToFd(capnproto_fd, outermessage); } } DBG("late initialising "<<freshlyTagged.size() <<" objects done"); } g_init = true; { // redefine classes that we could not transform during the primordial // phase: for (auto redef = redefineDuringLivePhase.begin(); redef != redefineDuringLivePhase.end(); ++redef) { if (//redef->name == "java/lang/SystemClassLoaderAction" || redef->name == "java/lang/Class" || strstr(redef->name.c_str(), "java/lang/invoke/") // || redef->name == "sun/reflect/Reflection" ) { DBG("never instrumenting "<<redef->name); continue; } DBG("redefining klass "<<redef->name); unsigned char *new_class_data; uint32_t new_class_data_len; transformClass(redef->klassDef.class_bytes, (uint32_t)redef->klassDef.class_byte_count, &new_class_data, &new_class_data_len); free((void*)redef->klassDef.class_bytes); redef->klassDef.class_bytes = new_class_data; redef->klassDef.class_byte_count = (jint)new_class_data_len; redef->klassDef.klass = jni->FindClass(redef->name.c_str()); DBG("redefining class "<<redef->name<<" -- len="<<redef->klassDef.class_byte_count); jvmtiError err = g_jvmti->RedefineClasses(1, &redef->klassDef); if (err == JVMTI_ERROR_INVALID_CLASS) { WARN("could not redefine class "<<redef->name<<" (JVMTI_ERROR_INVALID_CLASS)"); } else { ASSERT_NO_JVMTI_ERR(g_jvmti, err); } } } #endif // ENABLED } void JNICALL VMDeath(jvmtiEnv *jvmti_env, JNIEnv *jni_env) { #ifdef ENABLED DBG("VMDeath"); g_dead = true; if (traceToDisk) { close(capnproto_fd); } for (auto const& it : klassReps) { DBG("klass "<<it.first<<" -> "<<it.second); } #endif // ifdef ENABLED } void parse_options(std::string options) { //std::cout << "options: " << options << "\n"; DBG("options="<<options); if (strstr(options.c_str(), "application_only")) { flag_application_only = true; ERR("DEPRECATED FLAG: application_only"); } size_t p1 = options.find("tracefile="); if (p1 != string::npos) { std::string rest = options.substr(p1 + std::string("tracefile=").size()); size_t p2 = rest.find(","); if (p2 != string::npos) { tracefilename = options.substr(p1, p2); } else { tracefilename = rest; } } if (tracefilename != "none") { traceToDisk = true; } } /* This method is invoked by the JVM early in it's initialization. No classes have been loaded and no objects created. Tries to set capabilities and callbacks for the agent If something goes wrong it will cause the JVM to disrupt the initialization. Return values: JNI_OK -> JVM will continue JNI_ERR -> JVM will disrupt initialization */ JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved) { DBG("Agent_OnLoad"); { // onlyDuringLivePhaseMatch.push_back("java/io/File"); // onlyDuringLivePhaseMatch.push_back("java/io/FileOutputStream"); //onlyDuringLivePhaseMatch.push_back("java/io/PrintStream"); // onlyDuringLivePhaseMatch.push_back("java/lang/AbstractStringBuilder"); { // these need to be disabled because they're used when switching to the live phase onlyDuringLivePhaseMatch.push_back("java/lang/reflect/Field"); onlyDuringLivePhaseMatch.push_back("sun/reflect/"); } onlyDuringLivePhaseMatch.push_back("java/lang/StringBuilder"); onlyDuringLivePhaseMatch.push_back("java/lang/Class"); onlyDuringLivePhaseMatch.push_back("java/lang/ClassLoader"); onlyDuringLivePhaseMatch.push_back("java/util/AbstractCollection"); onlyDuringLivePhaseMatch.push_back("java/util/AbstractList"); // onlyDuringLivePhaseMatch.push_back("java/lang/Float"); onlyDuringLivePhaseMatch.push_back("java/lang/Object"); onlyDuringLivePhaseMatch.push_back("java/lang/Shutdown"); onlyDuringLivePhaseMatch.push_back("java/lang/String"); onlyDuringLivePhaseMatch.push_back("java/lang/System"); onlyDuringLivePhaseMatch.push_back("java/lang/Thread"); onlyDuringLivePhaseMatch.push_back("java/lang/ref"); onlyDuringLivePhaseMatch.push_back("java/security/AccessControlContext"); //onlyDuringLivePhaseMatch.push_back("java/util/Arrays"); // arst arst arst onlyDuringLivePhaseMatch.push_back("java/util/HashMap"); onlyDuringLivePhaseMatch.push_back("java/util/Hashtable"); onlyDuringLivePhaseMatch.push_back("java/util/LinkedList$ListItr"); onlyDuringLivePhaseMatch.push_back("java/util/Locale/"); onlyDuringLivePhaseMatch.push_back("java/util/Vector"); onlyDuringLivePhaseMatch.push_back("sun/launcher/"); onlyDuringLivePhaseMatch.push_back("sun/reflect/"); onlyDuringLivePhaseMatch.push_back("sun/nio/cs"); onlyDuringLivePhaseMatch.push_back("sun/util/PreHashedMap"); } jvmtiError error; jint res; if (options != NULL) { parse_options(options); } if (traceToDisk) { capnproto_fd = open(tracefilename.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); if (capnproto_fd == -1) { ERR("could not open log file '" << tracefilename << "'"); } } // Get jvmti env res = vm->GetEnv((void **)&g_jvmti, JVMTI_VERSION); if (res != JNI_OK) { printf("ERROR GETTING JVMTI"); return JNI_ERR; } // Set capabilities jvmtiCapabilities capabilities; memset(&capabilities, 0, sizeof(jvmtiCapabilities)); capabilities.can_generate_all_class_hook_events = 1; capabilities.can_tag_objects = 1; capabilities.can_access_local_variables = 1; capabilities.can_generate_object_free_events = 1; capabilities.can_generate_vm_object_alloc_events = 1; capabilities.can_generate_exception_events = 1; capabilities.can_redefine_classes = 1; capabilities.can_redefine_any_class = 1; capabilities.can_get_line_numbers = 1; capabilities.can_get_source_file_name = 1; error = g_jvmti->AddCapabilities(&capabilities); ASSERT_NO_JVMTI_ERR(g_jvmti, error); // Set callbacks jvmtiEventCallbacks callbacks; memset(&callbacks, 0, sizeof(callbacks)); callbacks.VMInit = &VMInit; callbacks.VMDeath = &VMDeath; callbacks.ClassFileLoadHook = &ClassFileLoadHook; callbacks.VMObjectAlloc = &VMObjectAlloc; error = g_jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); ASSERT_NO_JVMTI_ERR(g_jvmti, error); error = g_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL); ASSERT_NO_JVMTI_ERR(g_jvmti, error); error = g_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL); ASSERT_NO_JVMTI_ERR(g_jvmti, error); error = g_jvmti->SetEventNotificationMode( JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL); ASSERT_NO_JVMTI_ERR(g_jvmti, error); error = g_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_OBJECT_FREE, NULL); ASSERT_NO_JVMTI_ERR(g_jvmti, error); error = g_jvmti->CreateRawMonitor((char *)"Callbacks Lock", &g_lock); ASSERT_NO_JVMTI_ERR(g_jvmti, error); { DBG("extending bootstrap classloader search"); //FIXME I think we don't need ./ any longer: error = g_jvmti->AddToBootstrapClassLoaderSearch("./"); ASSERT_NO_JVMTI_ERR(g_jvmti, error); // make NativeInterface.class visible char *home; if ((home = getenv("HOME")) == NULL) { home = getpwuid(getuid())->pw_dir; } //FIXME: hard coded version number std::string jar = std::string(home)+"/.m2/repository/com/github/kaeluka/spencer-tracing/0.1.3-SNAPSHOT/spencer-tracing-0.1.3-SNAPSHOT-events.jar"; error = g_jvmti->AddToBootstrapClassLoaderSearch(jar.c_str()); ASSERT_NO_JVMTI_ERR(g_jvmti, error); // make NativeInterface.class visible } DBG("extending bootstrap classloader search: done"); return JNI_OK; } /* This function is invoked by the JVM just before it unloads exports the events. */ JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) { DBG("Agent_OnUnload"); #ifdef ENABLED { // int cnt = 0; // for (auto it = instrumentedClasses.begin(); it != instrumentedClasses.end(); // ++it) { // DBG("instrumented " << ++cnt << "/" << instrumentedClasses.size() // << ": class " << *it); // } // int cnt = 0; // for (auto it = uninstrumentedClasses.begin(); // it != uninstrumentedClasses.end(); ++it) { // DBG("uninstrumented "<<++cnt<<"/"<<uninstrumentedClasses.size() // <<": class "<<*it); // } DBG("instrumented "<<instrumentedClasses.size()<<" classes, skipped "<<uninstrumentedClasses.size()); } #endif // ifdef ENABLED }
34.105769
236
0.643725
[ "object", "vector", "transform" ]
e8a4e445fd435627ffe4ea6515de810e5b6cb9b7
4,787
hpp
C++
fbmpy/include/fbmpy/fbmpy.hpp
kjetil-lye/fractional_brownian_motion
0dfd8ddd8568e72f8d1eaf1ad37280cc6733be8b
[ "MIT" ]
1
2021-06-24T12:37:03.000Z
2021-06-24T12:37:03.000Z
fbmpy/include/fbmpy/fbmpy.hpp
kjetil-lye/fractional_brownian_motion
0dfd8ddd8568e72f8d1eaf1ad37280cc6733be8b
[ "MIT" ]
null
null
null
fbmpy/include/fbmpy/fbmpy.hpp
kjetil-lye/fractional_brownian_motion
0dfd8ddd8568e72f8d1eaf1ad37280cc6733be8b
[ "MIT" ]
1
2019-06-14T15:48:05.000Z
2019-06-14T15:48:05.000Z
/* Copyright (c) 2019 Kjetil Olsen Lye, ETH Zurich * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include <boost/python.hpp> #include <boost/python/numpy.hpp> #include <fbm/fbm.hpp> namespace fbmpy { //! Adapter function for fbm::generate_fractional_brownian_bridge inline boost::python::numpy::ndarray fractional_brownian_bridge_3d( double H, int nx, const boost::python::numpy::ndarray& X) { Py_intptr_t shape[1] = {(nx + 1)* (nx + 1)* (nx + 1)}; auto bridge_data = boost::python::numpy::zeros(1, shape, boost::python::numpy::dtype::get_builtin<double>()); fbm::fractional_brownian_bridge_3d(reinterpret_cast<double*> (bridge_data.get_data()), H, nx, reinterpret_cast<const double*>(X.get_data())); return bridge_data; } //! Adapter function for fbm::generate_fractional_brownian_bridge inline boost::python::numpy::ndarray fractional_brownian_bridge_2d( double H, int nx, const boost::python::numpy::ndarray& X) { Py_intptr_t shape[1] = {(nx + 1)* (nx + 1)}; auto bridge_data = boost::python::numpy::zeros(1, shape, boost::python::numpy::dtype::get_builtin<double>()); fbm::fractional_brownian_bridge_2d(reinterpret_cast<double*> (bridge_data.get_data()), H, nx, reinterpret_cast<const double*>(X.get_data())); return bridge_data; } //! Adapter function for fbm::generate_fractional_brownian_bridge inline boost::python::numpy::ndarray fractional_brownian_bridge_1d( double H, int nx, const boost::python::numpy::ndarray& X) { Py_intptr_t shape[1] = {(nx + 1)}; auto bridge_data = boost::python::numpy::zeros(1, shape, boost::python::numpy::dtype::get_builtin<double>()); fbm::fractional_brownian_bridge_1d(reinterpret_cast<double*> (bridge_data.get_data()), H, nx, reinterpret_cast<const double*>(X.get_data())); return bridge_data; } //! Adapter function for fbm::generate_fractional_brownian_motion inline boost::python::numpy::ndarray fractional_brownian_motion_1d( double H, int nx, const boost::python::numpy::ndarray& X) { Py_intptr_t shape[1] = {(nx + 1)}; auto bridge_data = boost::python::numpy::zeros(1, shape, boost::python::numpy::dtype::get_builtin<double>()); fbm::fractional_brownian_motion_1d(reinterpret_cast<double*> (bridge_data.get_data()), H, nx, reinterpret_cast<const double*>(X.get_data())); return bridge_data; } //! Adapter function for fbm::generate_fractional_brownian_motion inline boost::python::numpy::ndarray fractional_brownian_motion_2d( double H, int nx, const boost::python::numpy::ndarray& X) { Py_intptr_t shape[1] = {(nx + 1)* (nx + 1)}; auto bridge_data = boost::python::numpy::zeros(1, shape, boost::python::numpy::dtype::get_builtin<double>()); fbm::fractional_brownian_bridge_2d(reinterpret_cast<double*> (bridge_data.get_data()), H, nx, reinterpret_cast<const double*>(X.get_data()), false); return bridge_data; } //! Adapter function for fbm::generate_fractional_brownian_motion inline boost::python::numpy::ndarray fractional_brownian_motion_3d( double H, int nx, const boost::python::numpy::ndarray& X) { Py_intptr_t shape[1] = {(nx + 1)* (nx + 1)* (nx + 1)}; auto bridge_data = boost::python::numpy::zeros(1, shape, boost::python::numpy::dtype::get_builtin<double>()); fbm::fractional_brownian_bridge_3d(reinterpret_cast<double*> (bridge_data.get_data()), H, nx, reinterpret_cast<const double*>(X.get_data()), false); return bridge_data; } }
34.941606
81
0.687696
[ "shape" ]
e8a8c516025b59e85d7fd72d7e861edc45cfff07
26,321
cpp
C++
modules/datasets/src/metrics.cpp
jpjodoin/litiv
435556bea20d60816aff492f50587b1a2d748b21
[ "BSD-3-Clause" ]
97
2015-10-16T04:32:33.000Z
2022-03-29T07:04:02.000Z
modules/datasets/src/metrics.cpp
jpjodoin/litiv
435556bea20d60816aff492f50587b1a2d748b21
[ "BSD-3-Clause" ]
19
2016-07-01T16:37:02.000Z
2020-09-10T06:09:39.000Z
modules/datasets/src/metrics.cpp
jpjodoin/litiv
435556bea20d60816aff492f50587b1a2d748b21
[ "BSD-3-Clause" ]
41
2015-11-17T05:59:23.000Z
2022-02-16T09:30:28.000Z
// This file is part of the LITIV framework; visit the original repository at // https://github.com/plstcharles/litiv for more information. // // Copyright 2015 Pierre-Luc St-Charles; pierre-luc.st-charles<at>polymtl.ca // // 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 <litiv/datasets/metrics.hpp> #include "litiv/datasets/metrics.hpp" void lv::BinClassif::accumulate(const cv::Mat& oClassif, const cv::Mat& oGT, const cv::Mat& oROI) { lvAssert_(!oClassif.empty() && oClassif.dims==2 && oClassif.isContinuous() && oClassif.type()==CV_8UC1,"binary classifier results must be non-empty and of type 8UC1"); lvAssert_(oGT.empty() || (oGT.type()==CV_8UC1 && oGT.isContinuous()),"gt mat must be empty, or of type 8UC1"); lvAssert_(oROI.empty() || (oROI.type()==CV_8UC1 && oGT.isContinuous()),"ROI mat must be empty, or of type 8UC1"); lvAssert_((oGT.empty() || oClassif.size()==oGT.size()) && (oROI.empty() || oClassif.size()==oROI.size()),"all input mat sizes must match"); if(oGT.empty()) { nDC += oClassif.size().area(); return; } const size_t step_row = oClassif.step.p[0]; for(size_t i = 0; i<(size_t)oClassif.rows; ++i) { const size_t idx_nstep = step_row*i; const uchar* input_step_ptr = oClassif.data+idx_nstep; const uchar* gt_step_ptr = oGT.data+idx_nstep; const uchar* roi_step_ptr = oROI.data+idx_nstep; for(int j = 0; j<oClassif.cols; ++j) { if(gt_step_ptr[j]!=DATASETUTILS_OUTOFSCOPE_VAL && gt_step_ptr[j]!=DATASETUTILS_UNKNOWN_VAL && (oROI.empty() || roi_step_ptr[j]!=DATASETUTILS_NEGATIVE_VAL)) { if(input_step_ptr[j]==DATASETUTILS_POSITIVE_VAL) { if(gt_step_ptr[j]==DATASETUTILS_POSITIVE_VAL) ++nTP; else // gt_step_ptr[j]==s_nSegmNegative ++nFP; } else { // input_step_ptr[j]==s_nSegmNegative if(gt_step_ptr[j]==DATASETUTILS_POSITIVE_VAL) ++nFN; else // gt_step_ptr[j]==s_nSegmNegative ++nTN; } if(gt_step_ptr[j]==DATASETUTILS_SHADOW_VAL) { if(input_step_ptr[j]==DATASETUTILS_POSITIVE_VAL) ++nSE; } } else ++nDC; } } } cv::Mat lv::BinClassif::getColoredMask(const cv::Mat& oClassif, const cv::Mat& oGT, const cv::Mat& oROI) { lvAssert_(!oClassif.empty() && oClassif.dims==2 && oClassif.isContinuous() && oClassif.type()==CV_8UC1,"binary classifier results must be non-empty and of type 8UC1"); lvAssert_(oGT.empty() || (oGT.type()==CV_8UC1 && oGT.isContinuous()),"gt mat must be empty, or of type 8UC1"); lvAssert_(oROI.empty() || (oROI.type()==CV_8UC1 && oROI.isContinuous()),"ROI mat must be empty, or of type 8UC1"); lvAssert_((oGT.empty() || oClassif.size()==oGT.size()) && (oROI.empty() || oClassif.size()==oROI.size()),"all input mat sizes must match"); if(oGT.empty()) { cv::Mat oResult; cv::cvtColor(oClassif,oResult,cv::COLOR_GRAY2BGR); return oResult; } cv::Mat oResult(oClassif.size(),CV_8UC3,cv::Scalar_<uchar>(0)); const size_t step_row = oClassif.step.p[0]; for(size_t i=0; i<(size_t)oClassif.rows; ++i) { const size_t idx_nstep = step_row*i; const uchar* input_step_ptr = oClassif.data+idx_nstep; const uchar* gt_step_ptr = oGT.data+idx_nstep; const uchar* roi_step_ptr = oROI.data+idx_nstep; uchar* res_step_ptr = oResult.data+idx_nstep*3; for(int j=0; j<oClassif.cols; ++j) { if(gt_step_ptr[j]!=DATASETUTILS_OUTOFSCOPE_VAL && gt_step_ptr[j]!=DATASETUTILS_UNKNOWN_VAL && (oROI.empty() || roi_step_ptr[j]!=DATASETUTILS_NEGATIVE_VAL)) { if(input_step_ptr[j]==DATASETUTILS_POSITIVE_VAL) { if(gt_step_ptr[j]==DATASETUTILS_POSITIVE_VAL) res_step_ptr[j*3+1] = UCHAR_MAX; else if(gt_step_ptr[j]==DATASETUTILS_NEGATIVE_VAL) res_step_ptr[j*3+2] = UCHAR_MAX; else if(gt_step_ptr[j]==DATASETUTILS_SHADOW_VAL) { res_step_ptr[j*3+1] = UCHAR_MAX/2; res_step_ptr[j*3+2] = UCHAR_MAX; } else { for(size_t c=0; c<3; ++c) res_step_ptr[j*3+c] = UCHAR_MAX/3; } } else { // input_step_ptr[j]==s_nSegmNegative if(gt_step_ptr[j]==DATASETUTILS_POSITIVE_VAL) { res_step_ptr[j*3] = UCHAR_MAX/2; res_step_ptr[j*3+2] = UCHAR_MAX; } } } else if(!oROI.empty() && roi_step_ptr[j]==DATASETUTILS_NEGATIVE_VAL) { for(size_t c=0; c<3; ++c) res_step_ptr[j*3+c] = UCHAR_MAX/2; } else { for(size_t c=0; c<3; ++c) res_step_ptr[j*3+c] = input_step_ptr[j]; } } } return oResult; } //////////////////////////////////////////////////////////////////////////////////////////////////// void lv::StereoDispErrors::accumulate(const cv::Mat& _oDispMap, const cv::Mat& _oGT, const cv::Mat& oROI) { lvAssert_(!_oDispMap.empty() && _oDispMap.dims==2 && _oDispMap.isContinuous(),"input disp map must be non-empty and 2d"); lvAssert_(_oDispMap.type()==CV_8UC1 || _oDispMap.type()==CV_8SC1 || _oDispMap.type()==CV_16UC1 || _oDispMap.type()==CV_16SC1 || _oDispMap.type()==CV_32SC1 || _oDispMap.type()==CV_32FC1,"binary classifier results must be of type 8UC1/8SC1/16UC1/16SC1/32SC1/32FC1"); lvAssert_(_oGT.empty() || (_oGT.isContinuous() && (_oGT.type()==CV_8UC1 || _oGT.type()==CV_8SC1 || _oGT.type()==CV_16UC1 || _oGT.type()==CV_16SC1 || _oGT.type()==CV_32SC1 || _oGT.type()==CV_32FC1)),"gt mat must be empty, or of type 8UC1/8SC1/16UC1/16SC1/32SC1/32FC1"); lvAssert_(oROI.empty() || (oROI.isContinuous() && oROI.type()==CV_8UC1),"ROI mat must be empty, or of type 8UC1"); lvAssert_((_oGT.empty() || _oDispMap.size()==_oGT.size()) && (oROI.empty() || _oDispMap.size()==oROI.size()),"all input mat sizes must match"); if(_oGT.empty()) { nDC += _oDispMap.size().area(); return; } cv::Mat_<float> oDispMap,oGT; if(_oDispMap.type()==CV_32FC1) oDispMap = _oDispMap; else _oDispMap.convertTo(oDispMap,CV_32F); if(_oGT.type()==CV_32FC1) oGT = _oGT; else _oGT.convertTo(oGT,CV_32F); cv::Mat_<uchar> oGTValidMask; if(_oGT.type()==CV_8UC1) oGTValidMask = (_oGT!=std::numeric_limits<uchar>::max()); else if(_oGT.type()==CV_8SC1) oGTValidMask = (_oGT!=std::numeric_limits<char>::max()) & (_oGT>=0); else if(_oGT.type()==CV_16UC1) oGTValidMask = (_oGT!=std::numeric_limits<ushort>::max()); else if(_oGT.type()==CV_16SC1) oGTValidMask = (_oGT!=std::numeric_limits<short>::max()) & (_oGT>=0); else if(_oGT.type()==CV_32SC1) oGTValidMask = (_oGT!=std::numeric_limits<int>::max()) & (_oGT>=0); else if(_oGT.type()==CV_32FC1) oGTValidMask = (_oGT!=std::numeric_limits<float>::max()) & (_oGT>=0); else lvError("unexpected gt map type"); vErrors.reserve(vErrors.size()+oDispMap.total()); for(int nRowIdx=0; nRowIdx<oDispMap.rows; ++nRowIdx) { const float* pInputDispPtr = oDispMap.ptr<float>(nRowIdx); const float* pGTDispPtr = oGT.ptr<float>(nRowIdx); const uchar* pGTValidPtr = oGTValidMask.ptr<uchar>(nRowIdx); const uchar* pROIPtr = oROI.empty()?pGTValidPtr:oROI.ptr<uchar>(nRowIdx); for(int nColIdx=0; nColIdx<oDispMap.cols; ++nColIdx) { if(pGTValidPtr[nColIdx] && pROIPtr[nColIdx]) vErrors.push_back(std::abs(pInputDispPtr[nColIdx]-pGTDispPtr[nColIdx])); else ++nDC; } } } cv::Mat lv::StereoDispErrors::getColoredMask(const cv::Mat& _oDispMap, const cv::Mat& _oGT, float fMaxError, const cv::Mat& oROI) { lvAssert_(!_oDispMap.empty() && _oDispMap.dims==2 && _oDispMap.isContinuous(),"input disp map must be non-empty and 2d"); lvAssert_(_oDispMap.type()==CV_8UC1 || _oDispMap.type()==CV_8SC1 || _oDispMap.type()==CV_16UC1 || _oDispMap.type()==CV_16SC1 || _oDispMap.type()==CV_32SC1 || _oDispMap.type()==CV_32FC1,"binary classifier results must be of type 8UC1/8SC1/16UC1/16SC1/32SC1/32FC1"); lvAssert_(_oGT.empty() || (_oGT.isContinuous() && (_oGT.type()==CV_8UC1 || _oGT.type()==CV_8SC1 || _oGT.type()==CV_16UC1 || _oGT.type()==CV_16SC1 || _oGT.type()==CV_32SC1 || _oGT.type()==CV_32FC1)),"gt mat must be empty, or of type 8UC1/8SC1/16UC1/16SC1/32SC1/32FC1"); lvAssert_(oROI.empty() || (oROI.isContinuous() && oROI.type()==CV_8UC1),"ROI mat must be empty, or of type 8UC1"); lvAssert_((_oGT.empty() || _oDispMap.size()==_oGT.size()) && (oROI.empty() || _oDispMap.size()==oROI.size()),"all input mat sizes must match"); lvAssert_(fMaxError>0.0f,"bad max disparity error value for color map scaling"); if(_oGT.empty()) return cv::Mat(_oDispMap.size(),CV_8UC3,cv::Scalar::all(92)); cv::Mat_<float> oDispMap,oGT,oErrorMap; if(_oDispMap.type()==CV_32FC1) oDispMap = _oDispMap; else _oDispMap.convertTo(oDispMap,CV_32F); if(_oGT.type()==CV_32FC1) oGT = _oGT; else _oGT.convertTo(oGT,CV_32F); cv::Mat_<uchar> oGTValidMask; if(_oGT.type()==CV_8UC1) oGTValidMask = (_oGT!=std::numeric_limits<uchar>::max()); else if(_oGT.type()==CV_8SC1) oGTValidMask = (_oGT!=std::numeric_limits<char>::max()) & (_oGT>=0); else if(_oGT.type()==CV_16UC1) oGTValidMask = (_oGT!=std::numeric_limits<ushort>::max()); else if(_oGT.type()==CV_16SC1) oGTValidMask = (_oGT!=std::numeric_limits<short>::max()) & (_oGT>=0); else if(_oGT.type()==CV_32SC1) oGTValidMask = (_oGT!=std::numeric_limits<int>::max()) & (_oGT>=0); else if(_oGT.type()==CV_32FC1) oGTValidMask = (_oGT!=std::numeric_limits<float>::max()) & (_oGT>=0); else lvError("unexpected gt map type"); oErrorMap.create(oDispMap.size()); for(int nRowIdx=0; nRowIdx<oErrorMap.rows; ++nRowIdx) { const float* pInputDispPtr = oDispMap.ptr<float>(nRowIdx); const float* pGTDispPtr = oGT.ptr<float>(nRowIdx); const uchar* pGTValidPtr = oGTValidMask.ptr<uchar>(nRowIdx); const uchar* pROIPtr = oROI.empty()?pGTValidPtr:oROI.ptr<uchar>(nRowIdx); for(int nColIdx=0; nColIdx<oErrorMap.cols; ++nColIdx) { if(pGTValidPtr[nColIdx] && pROIPtr[nColIdx]) oErrorMap(nRowIdx,nColIdx) = std::min(std::abs(pInputDispPtr[nColIdx]-pGTDispPtr[nColIdx]),fMaxError); else oErrorMap(nRowIdx,nColIdx) = 0.0f; } } const float fOldErrorMapCornerVal = oErrorMap(0,0); oErrorMap(0,0) = fMaxError; cv::Mat oOutput; cv::normalize(oErrorMap,oOutput,255,0,cv::NORM_MINMAX,CV_8U); oOutput.at<uchar>(0,0) = uchar((fOldErrorMapCornerVal/fMaxError)*255); cv::dilate(oOutput,oOutput,cv::Mat(),cv::Point(-1,-1),2); cv::applyColorMap(oOutput,oOutput,cv::COLORMAP_HOT); if(!oROI.empty()) cv::Mat(oOutput.size(),CV_8UC3,cv::Scalar_<uchar>::all(92)).copyTo(oOutput,oROI==0); return oOutput; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// bool lv::IMetricsAccumulator_<lv::DatasetEval_BinaryClassifier>::isEqual(const IIMetricsAccumulatorConstPtr& m) const { const auto& m2 = dynamic_cast<const IMetricsAccumulator_<lv::DatasetEval_BinaryClassifier>&>(*m.get()); return this->m_oCounters.isEqual(m2.m_oCounters); } lv::IIMetricsAccumulatorPtr lv::IMetricsAccumulator_<lv::DatasetEval_BinaryClassifier>::accumulate(const IIMetricsAccumulatorConstPtr& m) { const auto& m2 = dynamic_cast<const IMetricsAccumulator_<lv::DatasetEval_BinaryClassifier>&>(*m.get()); this->m_oCounters.accumulate(m2.m_oCounters); return shared_from_this(); } //////////////////////////////////////////////////////////////////////////////////////////////////// bool lv::IMetricsAccumulator_<lv::DatasetEval_BinaryClassifierArray>::isEqual(const IIMetricsAccumulatorConstPtr& m) const { const auto& m2 = dynamic_cast<const IMetricsAccumulator_<lv::DatasetEval_BinaryClassifierArray>&>(*m.get()); if(this->m_vCounters.size()!=m2.m_vCounters.size()) return false; for(size_t s=0; s<this->m_vCounters.size(); ++s) if(!this->m_vCounters[s].isEqual(m2.m_vCounters[s])) return false; return true; } lv::IIMetricsAccumulatorPtr lv::IMetricsAccumulator_<lv::DatasetEval_BinaryClassifierArray>::accumulate(const IIMetricsAccumulatorConstPtr& m) { const auto& m2 = dynamic_cast<const IMetricsAccumulator_<lv::DatasetEval_BinaryClassifierArray>&>(*m.get()); if(m_vCounters.empty()) m_vCounters.resize(m2.m_vCounters.size()); else lvAssert_(this->m_vCounters.size()==m2.m_vCounters.size(),"array size mismatch"); if(m_vsStreamNames.empty()) m_vsStreamNames = m2.m_vsStreamNames; else lvAssert_(this->m_vsStreamNames.size()==m2.m_vsStreamNames.size(),"array size mismatch"); lvAssert_(this->m_vCounters.size()==this->m_vsStreamNames.size(),"array size mismatch"); for(size_t s=0; s<this->m_vCounters.size(); ++s) { this->m_vCounters[s].accumulate(m2.m_vCounters[s]); if(this->m_vsStreamNames[s].empty()) this->m_vsStreamNames[s] = m2.m_vsStreamNames[s]; } return shared_from_this(); } lv::BinClassifMetricsAccumulatorPtr lv::IMetricsAccumulator_<lv::DatasetEval_BinaryClassifierArray>::reduce() const { BinClassifMetricsAccumulatorPtr m = IIMetricsAccumulator::create<BinClassifMetricsAccumulator>(); for(size_t s=0; s<this->m_vCounters.size(); ++s) m->m_oCounters.accumulate(this->m_vCounters[s]); return m; } lv::IMetricsAccumulator_<lv::DatasetEval_BinaryClassifierArray>::IMetricsAccumulator_(size_t nArraySize) : m_vCounters(nArraySize),m_vsStreamNames(nArraySize) {} //////////////////////////////////////////////////////////////////////////////////////////////////// bool lv::IMetricsAccumulator_<lv::DatasetEval_StereoDisparityEstim>::isEqual(const IIMetricsAccumulatorConstPtr& m) const { const auto& m2 = dynamic_cast<const IMetricsAccumulator_<lv::DatasetEval_StereoDisparityEstim>&>(*m.get()); if(this->m_vErrorLists.size()!=m2.m_vErrorLists.size()) return false; for(size_t s=0; s<this->m_vErrorLists.size(); ++s) if(!this->m_vErrorLists[s].isEqual(m2.m_vErrorLists[s])) return false; return true; } lv::IIMetricsAccumulatorPtr lv::IMetricsAccumulator_<lv::DatasetEval_StereoDisparityEstim>::accumulate(const IIMetricsAccumulatorConstPtr& m) { const auto& m2 = dynamic_cast<const IMetricsAccumulator_<lv::DatasetEval_StereoDisparityEstim>&>(*m.get()); if(m_vErrorLists.empty()) m_vErrorLists.resize(m2.m_vErrorLists.size()); else lvAssert_(this->m_vErrorLists.size()==m2.m_vErrorLists.size(),"array size mismatch"); if(m_vsStreamNames.empty()) m_vsStreamNames = m2.m_vsStreamNames; else lvAssert_(this->m_vsStreamNames.size()==m2.m_vsStreamNames.size(),"array size mismatch"); lvAssert_(this->m_vErrorLists.size()==this->m_vsStreamNames.size(),"array size mismatch"); for(size_t s=0; s<this->m_vErrorLists.size(); ++s) { this->m_vErrorLists[s].accumulate(m2.m_vErrorLists[s]); if(this->m_vsStreamNames[s].empty()) this->m_vsStreamNames[s] = m2.m_vsStreamNames[s]; } return shared_from_this(); } lv::StereoDispErrors lv::IMetricsAccumulator_<lv::DatasetEval_StereoDisparityEstim>::reduce() const { StereoDispErrors m; for(size_t s=0; s<this->m_vErrorLists.size(); ++s) m.accumulate(this->m_vErrorLists[s]); return m; } lv::IMetricsAccumulator_<lv::DatasetEval_StereoDisparityEstim>::IMetricsAccumulator_(size_t nArraySize) : m_vErrorLists(nArraySize),m_vsStreamNames(nArraySize) {} //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// lv::IIMetricsCalculatorPtr lv::IMetricsCalculator_<lv::DatasetEval_BinaryClassifier>::accumulate(const IIMetricsCalculatorConstPtr& m) { const auto& m2 = dynamic_cast<const IMetricsCalculator_<lv::DatasetEval_BinaryClassifier>&>(*m.get()); const size_t nTotWeight = this->nWeight+m2.nWeight; this->m_oMetrics.dRecall = (m2.m_oMetrics.dRecall*m2.nWeight + this->m_oMetrics.dRecall*this->nWeight)/nTotWeight; this->m_oMetrics.dSpecificity = (m2.m_oMetrics.dSpecificity*m2.nWeight + this->m_oMetrics.dSpecificity*this->nWeight)/nTotWeight; this->m_oMetrics.dFPR = (m2.m_oMetrics.dFPR*m2.nWeight + this->m_oMetrics.dFPR*this->nWeight)/nTotWeight; this->m_oMetrics.dFNR = (m2.m_oMetrics.dFNR*m2.nWeight + this->m_oMetrics.dFNR*this->nWeight)/nTotWeight; this->m_oMetrics.dPBC = (m2.m_oMetrics.dPBC*m2.nWeight + this->m_oMetrics.dPBC*this->nWeight)/nTotWeight; this->m_oMetrics.dPrecision = (m2.m_oMetrics.dPrecision*m2.nWeight + this->m_oMetrics.dPrecision*this->nWeight)/nTotWeight; this->m_oMetrics.dFMeasure = (m2.m_oMetrics.dFMeasure*m2.nWeight + this->m_oMetrics.dFMeasure*this->nWeight)/nTotWeight; this->m_oMetrics.dMCC = (m2.m_oMetrics.dMCC*m2.nWeight + this->m_oMetrics.dMCC*this->nWeight)/nTotWeight; this->nWeight = nTotWeight; return shared_from_this(); } lv::IMetricsCalculator_<lv::DatasetEval_BinaryClassifier>::IMetricsCalculator_(const IIMetricsAccumulatorConstPtr& m) : m_oMetrics(dynamic_cast<const BinClassifMetricsAccumulator&>(*m.get()).m_oCounters) {} lv::IMetricsCalculator_<lv::DatasetEval_BinaryClassifier>::IMetricsCalculator_(const BinClassifMetrics& m) : m_oMetrics(m) {} lv::IMetricsCalculator_<lv::DatasetEval_BinaryClassifier>::IMetricsCalculator_(const BinClassif& m) : m_oMetrics(m) {} //////////////////////////////////////////////////////////////////////////////////////////////////// lv::IIMetricsCalculatorPtr lv::IMetricsCalculator_<lv::DatasetEval_BinaryClassifierArray>::accumulate(const IIMetricsCalculatorConstPtr& m) { const auto& m2 = dynamic_cast<const IMetricsCalculator_<lv::DatasetEval_BinaryClassifierArray>&>(*m.get()); lvAssert_(this->m_vMetrics.size()==m2.m_vMetrics.size(),"array size mismatch"); const size_t nTotWeight = this->nWeight+m2.nWeight; for(size_t s=0; s<this->m_vMetrics.size(); ++s) { this->m_vMetrics[s].dRecall = (m2.m_vMetrics[s].dRecall*m2.nWeight + this->m_vMetrics[s].dRecall*this->nWeight)/nTotWeight; this->m_vMetrics[s].dSpecificity = (m2.m_vMetrics[s].dSpecificity*m2.nWeight + this->m_vMetrics[s].dSpecificity*this->nWeight)/nTotWeight; this->m_vMetrics[s].dFPR = (m2.m_vMetrics[s].dFPR*m2.nWeight + this->m_vMetrics[s].dFPR*this->nWeight)/nTotWeight; this->m_vMetrics[s].dFNR = (m2.m_vMetrics[s].dFNR*m2.nWeight + this->m_vMetrics[s].dFNR*this->nWeight)/nTotWeight; this->m_vMetrics[s].dPBC = (m2.m_vMetrics[s].dPBC*m2.nWeight + this->m_vMetrics[s].dPBC*this->nWeight)/nTotWeight; this->m_vMetrics[s].dPrecision = (m2.m_vMetrics[s].dPrecision*m2.nWeight + this->m_vMetrics[s].dPrecision*this->nWeight)/nTotWeight; this->m_vMetrics[s].dFMeasure = (m2.m_vMetrics[s].dFMeasure*m2.nWeight + this->m_vMetrics[s].dFMeasure*this->nWeight)/nTotWeight; this->m_vMetrics[s].dMCC = (m2.m_vMetrics[s].dMCC*m2.nWeight + this->m_vMetrics[s].dMCC*this->nWeight)/nTotWeight; } this->nWeight = nTotWeight; return shared_from_this(); } lv::BinClassifMetricsCalculatorPtr lv::IMetricsCalculator_<lv::DatasetEval_BinaryClassifierArray>::reduce() const { lvAssert_(this->m_vMetrics.size()>0,"need at least array size one"); BinClassifMetrics m(this->m_vMetrics[0]); for(size_t s=1; s<this->m_vMetrics.size(); ++s) { m.dRecall += this->m_vMetrics[s].dRecall; m.dSpecificity += this->m_vMetrics[s].dSpecificity; m.dFPR += this->m_vMetrics[s].dFPR; m.dFNR += this->m_vMetrics[s].dFNR; m.dPBC += this->m_vMetrics[s].dPBC; m.dPrecision += this->m_vMetrics[s].dPrecision; m.dFMeasure += this->m_vMetrics[s].dFMeasure; m.dMCC += this->m_vMetrics[s].dMCC; } m.dRecall /= this->m_vMetrics.size(); m.dSpecificity /= this->m_vMetrics.size(); m.dFPR /= this->m_vMetrics.size(); m.dFNR /= this->m_vMetrics.size(); m.dPBC /= this->m_vMetrics.size(); m.dPrecision /= this->m_vMetrics.size(); m.dFMeasure /= this->m_vMetrics.size(); m.dMCC /= this->m_vMetrics.size(); return IIMetricsCalculator::create<BinClassifMetricsCalculator>(m); } inline std::vector<lv::BinClassifMetrics> initMetricsArray(const lv::BinClassifMetricsArrayAccumulator& m) { std::vector<lv::BinClassifMetrics> vMetrics; for(const lv::BinClassif& m2 : m.m_vCounters) vMetrics.push_back(lv::BinClassifMetrics(m2)); return vMetrics; } lv::IMetricsCalculator_<lv::DatasetEval_BinaryClassifierArray>::IMetricsCalculator_(const IIMetricsAccumulatorConstPtr& m) : m_vMetrics(initMetricsArray(dynamic_cast<const BinClassifMetricsArrayAccumulator&>(*m.get()))), m_vsStreamNames(dynamic_cast<const BinClassifMetricsArrayAccumulator&>(*m.get()).m_vsStreamNames) { lvAssert(m_vMetrics.size()==m_vsStreamNames.size()); } lv::IMetricsCalculator_<lv::DatasetEval_BinaryClassifierArray>::IMetricsCalculator_(const std::vector<BinClassifMetrics>& vm, const std::vector<std::string>& vs) : m_vMetrics(vm),m_vsStreamNames(vs) { lvAssert(m_vMetrics.size()==m_vsStreamNames.size()); } //////////////////////////////////////////////////////////////////////////////////////////////////// lv::IIMetricsCalculatorPtr lv::IMetricsCalculator_<lv::DatasetEval_StereoDisparityEstim>::accumulate(const IIMetricsCalculatorConstPtr& m) { const auto& m2 = dynamic_cast<const IMetricsCalculator_<lv::DatasetEval_StereoDisparityEstim>&>(*m.get()); lvAssert_(this->m_vMetrics.size()==m2.m_vMetrics.size(),"array size mismatch"); const size_t nTotWeight = this->nWeight+m2.nWeight; for(size_t s=0; s<this->m_vMetrics.size(); ++s) { this->m_vMetrics[s].dBadPercent_05 = (m2.m_vMetrics[s].dBadPercent_05*m2.nWeight + this->m_vMetrics[s].dBadPercent_05*this->nWeight)/nTotWeight; this->m_vMetrics[s].dBadPercent_1 = (m2.m_vMetrics[s].dBadPercent_1*m2.nWeight + this->m_vMetrics[s].dBadPercent_1*this->nWeight)/nTotWeight; this->m_vMetrics[s].dBadPercent_2 = (m2.m_vMetrics[s].dBadPercent_2*m2.nWeight + this->m_vMetrics[s].dBadPercent_2*this->nWeight)/nTotWeight; this->m_vMetrics[s].dBadPercent_4 = (m2.m_vMetrics[s].dBadPercent_4*m2.nWeight + this->m_vMetrics[s].dBadPercent_4*this->nWeight)/nTotWeight; this->m_vMetrics[s].dAverageError = (m2.m_vMetrics[s].dAverageError*m2.nWeight + this->m_vMetrics[s].dAverageError*this->nWeight)/nTotWeight; this->m_vMetrics[s].dRMS = (m2.m_vMetrics[s].dRMS*m2.nWeight + this->m_vMetrics[s].dRMS*this->nWeight)/nTotWeight; } this->nWeight = nTotWeight; return shared_from_this(); } lv::StereoDispErrorMetrics lv::IMetricsCalculator_<lv::DatasetEval_StereoDisparityEstim>::reduce() const { lvAssert_(this->m_vMetrics.size()>0,"need at least array size one"); StereoDispErrorMetrics m(this->m_vMetrics[0]); for(size_t s=1; s<this->m_vMetrics.size(); ++s) { m.dBadPercent_05 += this->m_vMetrics[s].dBadPercent_05; m.dBadPercent_1 += this->m_vMetrics[s].dBadPercent_1; m.dBadPercent_2 += this->m_vMetrics[s].dBadPercent_2; m.dBadPercent_4 += this->m_vMetrics[s].dBadPercent_4; m.dAverageError += this->m_vMetrics[s].dAverageError; m.dRMS += this->m_vMetrics[s].dRMS; } m.dBadPercent_05 /= this->m_vMetrics.size(); m.dBadPercent_1 /= this->m_vMetrics.size(); m.dBadPercent_2 /= this->m_vMetrics.size(); m.dBadPercent_4 /= this->m_vMetrics.size(); m.dAverageError /= this->m_vMetrics.size(); m.dRMS /= this->m_vMetrics.size(); return m; } inline std::vector<lv::StereoDispErrorMetrics> initMetricsArray(const lv::StereoDispMetricsAccumulator& m) { std::vector<lv::StereoDispErrorMetrics> vMetrics; for(const lv::StereoDispErrors& m2 : m.m_vErrorLists) vMetrics.push_back(lv::StereoDispErrorMetrics(m2)); return vMetrics; } lv::IMetricsCalculator_<lv::DatasetEval_StereoDisparityEstim>::IMetricsCalculator_(const IIMetricsAccumulatorConstPtr& m) : m_vMetrics(initMetricsArray(dynamic_cast<const StereoDispMetricsAccumulator&>(*m.get()))), m_vsStreamNames(dynamic_cast<const StereoDispMetricsAccumulator&>(*m.get()).m_vsStreamNames) { lvAssert(m_vMetrics.size()==m_vsStreamNames.size()); } lv::IMetricsCalculator_<lv::DatasetEval_StereoDisparityEstim>::IMetricsCalculator_(const std::vector<StereoDispErrorMetrics>& vm, const std::vector<std::string>& vs) : m_vMetrics(vm),m_vsStreamNames(vs) { lvAssert(m_vMetrics.size()==m_vsStreamNames.size()); }
56.002128
272
0.644162
[ "vector" ]
e8b593bc4060ac6835519240d00a1a4a6647177d
1,688
cpp
C++
term7/saio/saio/dijkstras_algorithm/dijkstras_algorithm.cpp
japanese-goblinn/labs
47f5d59d28faf62c82535856e138b5cb98159fd0
[ "MIT" ]
null
null
null
term7/saio/saio/dijkstras_algorithm/dijkstras_algorithm.cpp
japanese-goblinn/labs
47f5d59d28faf62c82535856e138b5cb98159fd0
[ "MIT" ]
null
null
null
term7/saio/saio/dijkstras_algorithm/dijkstras_algorithm.cpp
japanese-goblinn/labs
47f5d59d28faf62c82535856e138b5cb98159fd0
[ "MIT" ]
1
2021-10-11T08:30:48.000Z
2021-10-11T08:30:48.000Z
// // main.cpp // saio // // Created by Kirill Gorbachyonok on 10/4/20. // #include <iostream> #include <vector> #include <queue> #include <fstream> using namespace std; #define print_with_endl(x) std::cout << x << "\n" typedef std::pair<long long, long long> cost_and_node; typedef std::pair<long long, long long> node_and_cost; typedef std::vector<std::vector<node_and_cost>> graph; auto Dijkstra(graph& g) { auto start = 0; auto destination = (long long)(g.size() - 1); vector<long long> d(g.size(), LLONG_MAX); d.at(start) = 0; priority_queue<cost_and_node> q; q.push({ 0, start }); while (!q.empty()) { auto cur_cost = -q.top().first; auto node = q.top().second; q.pop(); if (cur_cost > d.at(node)) { continue; } for (size_t i = 0; i < g.at(node).size(); ++i) { auto next_node = g.at(node).at(i).first; auto check_cost = g.at(node).at(i).second; if (d.at(node) + check_cost >= d.at(next_node)) { continue; } d.at(next_node) = d.at(node) + check_cost; q.push({ -d.at(next_node), next_node }); } } return d.at(destination); } int main(int argc, const char * argv[]) { ifstream f("input.txt"); if (!f.is_open()) { return -9; } size_t n, m; f >> n >> m; graph graph(n); long long u, v, w; for (size_t i = 0; i < m; ++i) { f >> u >> v >> w; graph.at(u - 1).push_back({ v - 1, w }); graph.at(v - 1).push_back({ u - 1, w }); } auto cost = Dijkstra(graph); ofstream o("output.txt"); o << cost; return 0; }
25.19403
61
0.527251
[ "vector" ]
e8bb9e7cc3e33e71aa16a80d8c028a38322ad7ee
5,757
cpp
C++
Tests/GeometryShop/ebgraphSingleGrid/ebgraphSG.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
1
2021-05-20T13:04:05.000Z
2021-05-20T13:04:05.000Z
Tests/GeometryShop/ebgraphSingleGrid/ebgraphSG.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
null
null
null
Tests/GeometryShop/ebgraphSingleGrid/ebgraphSG.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <cmath> #include "AMReX_GeometryShop.H" #include "AMReX_WrappedGShop.H" #include "AMReX_BoxIterator.H" #include "AMReX_ParmParse.H" #include "AMReX_RealVect.H" #include "AMReX_SphereIF.H" #include "AMReX_EBGraph.H" namespace amrex { //////////// int checkGraph(const EBGraph& a_ebgraph) { const Box& domain = a_ebgraph.getDomain(); ///account for regular and covered cells for (BoxIterator bit(domain); bit.ok(); ++bit) { IntVect iv = bit(); //check to see that there is never a regular cell next //to a covered cell for (int idir = 0; idir < SpaceDim; idir++) { for (SideIterator sit; sit.ok(); ++sit) { IntVect ivshift = BASISV(idir); ivshift[idir] *= sign(sit()); IntVect ivneigh = iv + ivshift; if (domain.contains(ivneigh)) { if((a_ebgraph.isRegular(iv) && a_ebgraph.isCovered(ivneigh) ) || (a_ebgraph.isCovered(iv) && a_ebgraph.isRegular(ivneigh))) { return -2; } if((a_ebgraph.isRegular(iv) && a_ebgraph.isMultiValued(ivneigh)) || (a_ebgraph.isRegular(ivneigh) && a_ebgraph.isMultiValued(iv) )) { return -3; } } std::vector<VolIndex> vofs = a_ebgraph.getVoFs(iv); for(int ivof = 0; ivof < vofs.size(); ivof++) { const VolIndex& vof = vofs[ivof]; if(vof.gridIndex() != iv) { return -6; } if(vof.cellIndex() < 0) { return -7; } //check to see if the vof matches the faces std::vector<FaceIndex> faces = a_ebgraph.getFaces(vof, idir, sit()); for(int iface = 0; iface < faces.size(); iface++) { const FaceIndex& face = faces[iface]; VolIndex startVoF = face.getVoF(flip(sit())); if(startVoF != vof) { return -8; } VolIndex neighVoF = face.getVoF(sit()); if(neighVoF.gridIndex() != ivneigh) { return -4; } if(domain.contains(ivneigh) && (neighVoF.cellIndex() < 0)) { return -5; } if(!domain.contains(ivneigh) && (neighVoF.cellIndex() >= 0)) { return -9; } } } } } } return 0; } //////////// int checkGraph(int whichgeom) { Real radius = 0.5; Real domlen = 1; std::vector<Real> centervec(SpaceDim); std::vector<int> ncellsvec(SpaceDim); ParmParse pp; pp.getarr( "n_cell" , ncellsvec, 0, SpaceDim); pp.get( "sphere_radius", radius); pp.getarr("sphere_center", centervec, 0, SpaceDim); pp.get("domain_length", domlen); RealVect center; for(int idir = 0; idir < SpaceDim; idir++) { center[idir] = centervec[idir]; } bool insideRegular = false; SphereIF sphere(radius, center, insideRegular); int verbosity = 0; pp.get("verbosity", verbosity); BaseFab<int> regIrregCovered; Vector<IrregNode> nodes; IntVect ivlo = IntVect::TheZeroVector(); IntVect ivhi; for(int idir = 0; idir < SpaceDim; idir++) { ivhi[idir] = ncellsvec[idir] - 1; } Box domain(ivlo, ivhi); Box validRegion = domain; Box ghostRegion = domain; //whole domain so ghosting does not matter RealVect origin = RealVect::Zero; Real dx = domlen/ncellsvec[0]; NodeMap nodemap; if(whichgeom == 0) { GeometryShop gshop(sphere, verbosity); gshop.fillGraph(regIrregCovered, nodes, nodemap, validRegion, ghostRegion, domain, origin, dx); } else { WrappedGShop gshop(sphere, verbosity); gshop.fillGraph(regIrregCovered, nodes, nodemap, validRegion, ghostRegion, domain, origin, dx); } EBGraph ebgraph(domain, 1); ebgraph.buildGraph(regIrregCovered, nodes, domain, domain); int eekflag = checkGraph(ebgraph); if(eekflag != 0) { return eekflag; } //now check coarsened versions Box testBox = domain; testBox.coarsen(2); testBox.refine(2); bool coarsenable = (testBox == domain); std::vector<EBGraph> graphsSoFar(1, ebgraph); int ilev = 0; while(coarsenable) { domain.coarsen(2); EBGraph coarGraph(domain, 1); const EBGraph& finerGraph = graphsSoFar[ilev]; coarGraph.coarsenVoFs(finerGraph, domain); coarGraph.coarsenFaces(finerGraph, domain); if(coarGraph.getDomain() != domain) { return -10; } if(coarGraph.getRegion() != domain) { return -11; } eekflag = checkGraph(ebgraph); if(eekflag != 0) { return eekflag; } graphsSoFar.push_back(coarGraph); testBox = domain; testBox.coarsen(2); testBox.refine(2); coarsenable = (testBox == domain); ilev++; } return eekflag; } } int main(int argc,char **argv) { #ifdef CH_MPI MPI_Init(&argc, &argv); #endif const char* in_file = "sphere.inputs"; //parse input file amrex::ParmParse pp; pp.Initialize(0, NULL, in_file); // check volume and surface area of approximate sphere for(int iwhichgeom =0; iwhichgeom <= 1; iwhichgeom++) { int eekflag = amrex::checkGraph(iwhichgeom); if (eekflag != 0) { cout << "non zero eek detected = " << eekflag << endl; cout << "sphere test failed" << endl; return eekflag; } } cout << "sphere test passed" << endl; return 0; }
26.287671
101
0.549939
[ "vector" ]
e8bc95ad02bb9bcccb09e6f20e656ca1405fbfee
6,271
cc
C++
src/devices/bin/driver_runtime/microbenchmarks/round_trips.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2022-02-24T16:24:29.000Z
2022-02-25T22:33:10.000Z
src/devices/bin/driver_runtime/microbenchmarks/round_trips.cc
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
src/devices/bin/driver_runtime/microbenchmarks/round_trips.cc
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/async/cpp/task.h> #include <lib/fdf/cpp/channel.h> #include <lib/fdf/cpp/channel_read.h> #include <lib/fdf/cpp/dispatcher.h> #include <lib/fdf/internal.h> #include <lib/fit/function.h> #include <lib/sync/completion.h> #include <lib/syslog/cpp/macros.h> #include <thread> #include <vector> #include "src/devices/bin/driver_runtime/microbenchmarks/assert.h" #include "src/devices/bin/driver_runtime/microbenchmarks/driver_stack_manager.h" #include "src/devices/bin/driver_runtime/microbenchmarks/test_runner.h" namespace { // Registers an asynchronous channel read handler with |dispatcher|. // The read handler will read |count| messages, re-registering the read handler if necessary. // If |reply| is true, the read messages will be written back to the channel. zx::status<std::unique_ptr<fdf::ChannelRead>> RegisterChannelReadMultiple( const fdf::Channel& channel, const fdf::Dispatcher& dispatcher, uint32_t want_num_read, bool reply, uint32_t want_msg_size, sync_completion_t* completion) { auto channel_read = std::make_unique<fdf::ChannelRead>( channel.get(), 0 /* options */, [=, num_read = 0u](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, fdf_status_t status) mutable { ASSERT_OK(status); fdf::UnownedChannel channel(channel_read->channel()); while (num_read < want_num_read) { auto read = channel->Read(0); if (read.status_value() == ZX_ERR_SHOULD_WAIT) { // Ran out of messages to read, need to register for another callback. ASSERT_OK(channel_read->Begin(dispatcher)); return; } ASSERT_OK(read.status_value()); FX_CHECK(read->num_bytes == want_msg_size); if (reply) { ASSERT_OK( channel ->Write(0, read->arena, read->data, read->num_bytes, cpp20::span<zx_handle_t>()) .status_value()); } num_read++; } FX_CHECK(num_read == want_num_read); sync_completion_signal(completion); }); fdf_status_t status = channel_read->Begin(dispatcher.get()); if (status != ZX_OK) { return zx::error(status); } return zx::ok(std::move(channel_read)); } // Test IPC round trips using fdf channels where the client and server // both use the same kind of fdf dispatchers to wait. class ChannelDispatcherTest { public: explicit ChannelDispatcherTest(uint32_t dispatcher_options, uint32_t msg_count, uint32_t msg_size) : msg_count_(msg_count), msg_size_(msg_size) { auto channel_pair = fdf::ChannelPair::Create(0); ASSERT_OK(channel_pair.status_value()); client_ = std::move(channel_pair->end0); server_ = std::move(channel_pair->end1); { DriverStackManager dsm(&client_fake_driver_); auto dispatcher = fdf::Dispatcher::Create(dispatcher_options); ASSERT_OK(dispatcher.status_value()); client_dispatcher_ = *std::move(dispatcher); } { DriverStackManager dsm(&server_fake_driver_); auto dispatcher = fdf::Dispatcher::Create(dispatcher_options); ASSERT_OK(dispatcher.status_value()); server_dispatcher_ = *std::move(dispatcher); } std::string_view tag; auto arena = fdf::Arena::Create(0, tag); ASSERT_OK(arena.status_value()); arena_ = *std::move(arena); // Create the messages to transfer. for (uint32_t i = 0; i < msg_count_; i++) { msgs_.push_back(arena_.Allocate(msg_size_)); } } void Run() { sync_completion_t client_completion; sync_completion_t server_completion; auto client_read = RegisterChannelReadMultiple( client_, client_dispatcher_, msg_count_, false /* reply */, msg_size_, &client_completion); auto server_read = RegisterChannelReadMultiple(server_, server_dispatcher_, msg_count_, true /* reply */, msg_size_, &server_completion); ASSERT_OK(client_read.status_value()); ASSERT_OK(server_read.status_value()); // Send the messages from client to server. async_dispatcher_t* async_dispatcher = client_dispatcher_.async_dispatcher(); FX_CHECK(async_dispatcher != nullptr); ASSERT_OK(async::PostTask(async_dispatcher, [&, this] { DriverStackManager dsm(&client_fake_driver_); for (const auto& msg : msgs_) { ASSERT_OK( client_.Write(0, arena_, msg, msg_size_, cpp20::span<zx_handle_t>()).status_value()); } })); ASSERT_OK(sync_completion_wait(&client_completion, ZX_TIME_INFINITE)); ASSERT_OK(sync_completion_wait(&server_completion, ZX_TIME_INFINITE)); } private: uint32_t msg_count_; uint32_t msg_size_; // Arena-allocated messages to transfer. std::vector<void*> msgs_; fdf::Channel client_; fdf::Dispatcher client_dispatcher_; fdf::Channel server_; fdf::Dispatcher server_dispatcher_; fdf::Arena arena_; uint32_t client_fake_driver_; uint32_t server_fake_driver_; }; void RegisterTests() { driver_runtime_benchmark::RegisterTest<ChannelDispatcherTest>( "RoundTrip_ChannelPort_Synchronized", /* dispatcher_options= */ 0, /* msg_count= */ 1, /* msg_size= */ 4); driver_runtime_benchmark::RegisterTest<ChannelDispatcherTest>( "RoundTrip_ChannelPort_AllowSyncCalls", /* dispatcher_options = */ FDF_DISPATCHER_OPTION_ALLOW_SYNC_CALLS, /* msg_count= */ 1, /* msg_size= */ 4); driver_runtime_benchmark::RegisterTest<ChannelDispatcherTest>( "IpcThroughput_BasicChannel_1_64kbytes", /* dispatcher_options= */ 0, /* msg_count= */ 1, /* msg_size= */ 64 * 1024); driver_runtime_benchmark::RegisterTest<ChannelDispatcherTest>( "IpcThroughput_BasicChannel_1024_4bytes", /* dispatcher_options= */ 0, /* msg_count= */ 1024, /* msg_size= */ 4); driver_runtime_benchmark::RegisterTest<ChannelDispatcherTest>( "IpcThroughput_BasicChannel_1024_64kbytes", /* dispatcher_options= */ 0, /* msg_count= */ 1024, /* msg_size= */ 64 * 1024); } PERFTEST_CTOR(RegisterTests) } // namespace
36.888235
100
0.688885
[ "vector" ]
e8bf2e880a4c802ecaaf87780efaa672476ed756
11,236
cpp
C++
project/race3d/src/GUI/GUIBitmap.cpp
maximbilan/cpp_marmalade_sdk_the_pursuit_3d
b0e42bae7ba5c47c5bf2f9db22d973f3319cdb06
[ "MIT" ]
5
2015-01-05T17:03:00.000Z
2016-04-07T07:43:32.000Z
project/race3d/src/GUI/GUIBitmap.cpp
maximbilan/cpp_marmalade_sdk_the_pursuit_3d
b0e42bae7ba5c47c5bf2f9db22d973f3319cdb06
[ "MIT" ]
null
null
null
project/race3d/src/GUI/GUIBitmap.cpp
maximbilan/cpp_marmalade_sdk_the_pursuit_3d
b0e42bae7ba5c47c5bf2f9db22d973f3319cdb06
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // GUIBitmap.cpp // Displays a bitmap on screen //----------------------------------------------------------------------------- #include "GUIBitmap.h" // Library includes #include "IwGx.h" #include "IwTextParserITX.h" // Project includes #include "GUIColour.h" #include "GUIDraw.h" #include "GUIFrame.h" #include "GUIManager.h" IW_MANAGED_IMPLEMENT_FACTORY( GUIBitmap ); //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- GUIBitmap::GUIBitmap() : m_pVertRatios( NULL ), m_pUV( NULL ), m_Angle( 0 ), m_Mirror( 0 ), m_VertexCount( 0 ) { IW_CALLSTACK( "GUIBitmap::GUIBitmap" ); m_Material.Init(); m_Material.SetColAmbient( 0xffffffff ); // Default to full colour! } //----------------------------------------------------------------------------- // Destructor //----------------------------------------------------------------------------- GUIBitmap::~GUIBitmap() { IW_CALLSTACK( "GUIBitmap::~GUIBitmap" ); delete[] m_pUV; } //----------------------------------------------------------------------------- // Serialise to/from binary file //----------------------------------------------------------------------------- void GUIBitmap::Serialise() { IW_CALLSTACK( "GUIBitmap::Serialise" ); GUIElement::Serialise(); IwSerialiseInt32( m_Angle ); IwSerialiseInt16( m_VertexCount ); IwSerialiseInt16( m_Mirror ); m_Material.Serialise(); // Have to serialise and reset the material colour since // CIwMaterial::Serialise doesn't seem to behave properly m_Colour.Serialise(); m_Material.SetColAmbient( m_Colour.GetColour() ); m_Material.SetColDiffuse( m_Colour.GetColour() ); // Do we have UVs specified? bool lHasUVs = ( m_pUV != NULL ); IwSerialiseBool( lHasUVs ); if( lHasUVs ) { // If boolean is true but pointer is null we are reading from // binary data and therefore need to allocate our UV buffer if( !m_pUV ) m_pUV = new CIwFVec2[4]; // Serialise the actual UV data for( uint32 i = 0; i < 4; i++ ) { m_pUV[i].Serialise(); } } } //----------------------------------------------------------------------------- // Lookup resource references //----------------------------------------------------------------------------- void GUIBitmap::Resolve() { IW_CALLSTACK( "GUIBitmap::Resolve" ); GUIElement::Resolve(); m_Material.Resolve(); // We need to generate some points and UVs to support mirroring CreateVertexAndUVData(); } //----------------------------------------------------------------------------- // Parse an attribute from an ITX file //----------------------------------------------------------------------------- bool GUIBitmap::ParseAttribute( CIwTextParserITX* apParser, const char* apAttrName ) { #ifdef IW_BUILD_RESOURCES IW_CALLSTACK( "GUIBitmap::ParseAttribute" ); if( !strcmp( apAttrName, "material" ) ) { CIwStringS lMaterialName; apParser->ReadString( lMaterialName ); CIwMaterial* lpMaterial = ResourceFindByName<CIwMaterial>( lMaterialName.c_str(), "CIwMaterial" ); IwAssertMsg( GUI, lpMaterial, ( "Material named %s not found", lMaterialName.c_str() ) ); // Make a copy of the material so we can tweak colours etc later m_Material.Copy( *lpMaterial ); } else if( !strcmp( apAttrName, "colour" ) ) { GUIColour::ParseColour( apParser, &m_Colour ); m_Material.SetColAmbient( m_Colour.GetColour() ); m_Material.SetColDiffuse( m_Colour.GetColour() ); } else if( !strcmp( apAttrName, "uv" ) ) { // Read in pixel UV data int16 lTexelUVData[4]; float lUVData[4]; apParser->ReadInt16Array( lTexelUVData, 4 ); // Convert pixel UV positions into fractions of width/height lUVData[0] = MakeUVValue( lTexelUVData[0], m_Material.GetTexture()->GetWidth() ); lUVData[1] = MakeUVValue( lTexelUVData[1], m_Material.GetTexture()->GetHeight() ); lUVData[2] = MakeUVValue( lTexelUVData[2], m_Material.GetTexture()->GetWidth() ); lUVData[3] = MakeUVValue( lTexelUVData[3], m_Material.GetTexture()->GetHeight() ); // See g_FullTextureUV in Draw.cpp for ordering of UV data m_VertexCount = 4; m_pUV = new CIwFVec2[m_VertexCount]; m_pUV[0].x = lUVData[0]; m_pUV[0].y = lUVData[1]; m_pUV[1].x = lUVData[0]; m_pUV[1].y = lUVData[3]; m_pUV[2].x = lUVData[2]; m_pUV[2].y = lUVData[3]; m_pUV[3].x = lUVData[2]; m_pUV[3].y = lUVData[1]; } else if( !strcmp( apAttrName, "angle" ) ) { apParser->ReadAngleDegrees( &m_Angle ); } else if( !strcmp( apAttrName, "mirrorx" ) ) { m_Mirror |= GB_MIRROR_X; } else if( !strcmp( apAttrName, "mirrory" ) ) { m_Mirror |= GB_MIRROR_Y; } else return GUIElement::ParseAttribute( apParser, apAttrName ); #endif return true; } //----------------------------------------------------------------------------- // Clone this element //----------------------------------------------------------------------------- void GUIBitmap::Clone( GUIElement* apCloneSource ) { IW_CALLSTACK( "GUIBitmap::Clone" ); GUIElement::Clone( apCloneSource ); GUIBitmap* lpCloneBitmap = reinterpret_cast<GUIBitmap*>( apCloneSource ); m_Material.Copy( lpCloneBitmap->m_Material ); m_Colour.Copy( lpCloneBitmap->m_Colour ); m_Angle = lpCloneBitmap->m_Angle; m_VertexCount = lpCloneBitmap->m_VertexCount; m_Mirror = lpCloneBitmap->m_Mirror; if( lpCloneBitmap->m_pUV ) { m_pUV = new CIwFVec2[m_VertexCount]; memcpy( m_pUV, lpCloneBitmap->m_pUV, sizeof( CIwFVec2 ) * m_VertexCount ); } } //----------------------------------------------------------------------------- // Called once per frame to render GUI element //----------------------------------------------------------------------------- void GUIBitmap::Render() { IW_CALLSTACK( "GUIBitmap::Render" ); GUIElement::Render(); // Find screen position and sine/cosine of rotation angle CIwRect lrRect = GetScreenRect(); const int32 cx = ( lrRect.x + ( lrRect.w >> 1 ) ) << 3; const int32 cy = ( lrRect.y + ( lrRect.h >> 1 ) ) << 3; const iwfixed lSine = IwGeomSin( m_Angle ); const iwfixed lCosine = IwGeomCos( m_Angle ); // Rotate and translate points CIwSVec2* lPts = IW_GX_ALLOC( CIwSVec2, m_VertexCount ); for( int16 i = 0; i < m_VertexCount; i++ ) { int32 lTmpWidth = IW_FIXED_MUL( m_pVertRatios[i].x, lrRect.w ); int32 lTmpHeight = IW_FIXED_MUL( m_pVertRatios[i].y, lrRect.h ); lPts[i].x = cx + IW_FIXED_MUL( lTmpWidth, lCosine ) - IW_FIXED_MUL( lTmpHeight, lSine ); lPts[i].y = cy + IW_FIXED_MUL( lTmpWidth, lSine ) + IW_FIXED_MUL( lTmpHeight, lCosine ); } IwGxSetMaterial( &m_Material ); IwGxSetVertStreamScreenSpaceSubPixel( lPts, m_VertexCount ); IwGxSetColStream( NULL ); IwGxSetUVStream( m_pUV ); IwGxDrawPrims( IW_GX_TRI_FAN, NULL, m_VertexCount ); } //----------------------------------------------------------------------------- // Replace the materials texture with the one represented by the // supplied hash value //----------------------------------------------------------------------------- void GUIBitmap::SetTexture( uint32 aTextureHash ) { IW_CALLSTACK( "GUIBitmap::SetTexture" ); CIwTexture* lpTexture = ResourceFindByHash<CIwTexture>( aTextureHash, "CIwTexture" ); m_Material.SetTexture( lpTexture ); } //----------------------------------------------------------------------------- // Create our vertex and UV arrays for rendering the bitmap //----------------------------------------------------------------------------- // We're using subpixel screen space coords #define GB_ONE (IW_GEOM_ONE << 2) CIwSVec2 GUIBitmap::s_VertRatios_MirrorNone[4] = { CIwSVec2( -GB_ONE, -GB_ONE ), CIwSVec2( -GB_ONE, GB_ONE ), CIwSVec2( GB_ONE, GB_ONE ), CIwSVec2( GB_ONE, -GB_ONE ) }; CIwSVec2 GUIBitmap::s_VertRatios_MirrorX[6] = { CIwSVec2( 0, -GB_ONE ), CIwSVec2( -GB_ONE, -GB_ONE ), CIwSVec2( -GB_ONE, GB_ONE ), CIwSVec2( 0, GB_ONE ), CIwSVec2( GB_ONE, GB_ONE ), CIwSVec2( GB_ONE, -GB_ONE ) }; CIwSVec2 GUIBitmap::s_VertRatios_MirrorY[6] = { CIwSVec2( GB_ONE, 0 ), CIwSVec2( GB_ONE, -GB_ONE ), CIwSVec2( -GB_ONE, -GB_ONE ), CIwSVec2( -GB_ONE, 0 ), CIwSVec2( -GB_ONE, GB_ONE ), CIwSVec2( GB_ONE, GB_ONE ) }; CIwSVec2 GUIBitmap::s_VertRatios_MirrorXY[10] = { CIwSVec2( 0, 0 ), CIwSVec2( 0, -GB_ONE ), CIwSVec2( -GB_ONE, -GB_ONE ), CIwSVec2( -GB_ONE, 0 ), CIwSVec2( -GB_ONE, GB_ONE ), CIwSVec2( 0, GB_ONE ), CIwSVec2( GB_ONE, GB_ONE ), CIwSVec2( GB_ONE, 0 ), CIwSVec2( GB_ONE, -GB_ONE ), CIwSVec2( 0, -GB_ONE ) }; void GUIBitmap::CreateVertexAndUVData() { IW_CALLSTACK( "GUIBitmap::CreateVertexAndUVData" ); // If no UVs specified, allocate a block of them and set up with // full texture defaults CIwFVec2* lpNewUV = NULL; if( !m_pUV ) { m_pUV = new CIwFVec2[4]; int32 lWidth = m_Material.GetTexture()->GetWidth(); int32 lHeight = m_Material.GetTexture()->GetHeight(); m_pUV[0].x = MakeUVValue( 0, lWidth ); m_pUV[0].y = MakeUVValue( 0, lHeight ); m_pUV[1].x = MakeUVValue( 0, lWidth ); m_pUV[1].y = MakeUVValue( lHeight, lHeight ); m_pUV[2].x = MakeUVValue( lWidth, lWidth ); m_pUV[2].y = MakeUVValue( lHeight, lHeight ); m_pUV[3].x = MakeUVValue( lWidth, lWidth ); m_pUV[3].y = MakeUVValue( 0, lHeight ); } switch( m_Mirror ) { case GB_MIRROR_X: { m_VertexCount = 6; m_pVertRatios = s_VertRatios_MirrorX; lpNewUV = new CIwFVec2[6]; lpNewUV[0].x = m_pUV[3].x; lpNewUV[0].y = m_pUV[3].y; lpNewUV[1].x = m_pUV[0].x; lpNewUV[1].y = m_pUV[0].y; lpNewUV[2].x = m_pUV[1].x; lpNewUV[2].y = m_pUV[1].y; lpNewUV[3].x = m_pUV[2].x; lpNewUV[3].y = m_pUV[2].y; lpNewUV[4].x = m_pUV[1].x; lpNewUV[4].y = m_pUV[1].y; lpNewUV[5].x = m_pUV[0].x; lpNewUV[5].y = m_pUV[0].y; break; } case GB_MIRROR_Y: { m_VertexCount = 6; m_pVertRatios = s_VertRatios_MirrorY; lpNewUV = new CIwFVec2[6]; lpNewUV[0].x = m_pUV[2].x; lpNewUV[0].y = m_pUV[2].y; lpNewUV[1].x = m_pUV[3].x; lpNewUV[1].y = m_pUV[3].y; lpNewUV[2].x = m_pUV[0].x; lpNewUV[2].y = m_pUV[0].y; lpNewUV[3].x = m_pUV[1].x; lpNewUV[3].y = m_pUV[1].y; lpNewUV[4].x = m_pUV[0].x; lpNewUV[4].y = m_pUV[0].y; lpNewUV[5].x = m_pUV[3].x; lpNewUV[5].y = m_pUV[3].y; break; } case GB_MIRROR_X + GB_MIRROR_Y: { m_VertexCount = 10; m_pVertRatios = s_VertRatios_MirrorXY; lpNewUV = new CIwFVec2[10]; lpNewUV[0].x = m_pUV[2].x; lpNewUV[0].y = m_pUV[2].y; lpNewUV[1].x = m_pUV[3].x; lpNewUV[1].y = m_pUV[3].y; lpNewUV[2].x = m_pUV[0].x; lpNewUV[2].y = m_pUV[0].y; lpNewUV[3].x = m_pUV[1].x; lpNewUV[3].y = m_pUV[1].y; lpNewUV[4].x = m_pUV[0].x; lpNewUV[4].y = m_pUV[0].y; lpNewUV[5].x = m_pUV[3].x; lpNewUV[5].y = m_pUV[3].y; lpNewUV[6].x = m_pUV[0].x; lpNewUV[6].y = m_pUV[0].y; lpNewUV[7].x = m_pUV[1].x; lpNewUV[7].y = m_pUV[1].y; lpNewUV[8].x = m_pUV[0].x; lpNewUV[8].y = m_pUV[0].y; lpNewUV[9].x = m_pUV[3].x; lpNewUV[9].y = m_pUV[3].y; break; } default: { // No mirroring m_VertexCount = 4; m_pVertRatios = s_VertRatios_MirrorNone; break; } } // If we are mirroring, set material to clamp if( m_Mirror ) m_Material.SetClamping( true ); // Replace m_pUV if necessary if( lpNewUV ) { delete[] m_pUV; m_pUV = lpNewUV; } }
32.011396
100
0.583037
[ "render" ]
e8c28fb2be247ad68a77dd47626fa03e2a3da335
2,159
cpp
C++
SourceCode/Final/Standalone/ProceduralCityGenerator/WaterData.cpp
JosephBarber96/FinalProject
60400efa64c36b7cdbc975e0df7b937cbaae1d0b
[ "MIT" ]
2
2019-05-18T21:37:17.000Z
2021-07-16T04:08:23.000Z
SourceCode/Final/Standalone/ProceduralCityGenerator/WaterData.cpp
JosephBarber96/FinalProject
60400efa64c36b7cdbc975e0df7b937cbaae1d0b
[ "MIT" ]
1
2020-04-29T05:37:48.000Z
2020-04-29T11:14:57.000Z
SourceCode/Final/Standalone/ProceduralCityGenerator/WaterData.cpp
JosephBarber96/FinalProject
60400efa64c36b7cdbc975e0df7b937cbaae1d0b
[ "MIT" ]
1
2021-07-16T04:08:31.000Z
2021-07-16T04:08:31.000Z
#include <iostream> #include "WaterData.h" #include "DiamondSquare.h" #include "Vec3.h" WaterData::WaterData(int size) { fillWaterMap(size); } WaterData::~WaterData() {} void WaterData::LoadFromTerrain(DiamondSquare* terrain, float percentage) { // First, make all of the values positive float lowest = terrain->Lowest(); float highest = terrain->Highest(); float toAdd = fabsf(lowest); for (auto &row : terrain->Points()) { for (auto &point : row) { point->z += toAdd; } } // Find the new highest and lowest values float newLowest = lowest + toAdd; float newHighest = highest + toAdd; // Find the difference float difference = newHighest - newLowest; // The bottom 20% shal be considered water float cutoffPoint = difference * (percentage / 100); std::cout << "Highest terrain point: " << newHighest << std::endl; std::cout << "Cut off point: " << cutoffPoint << std::endl; // Get the size int wid, hei; wid = terrain->getDivisions(); hei = terrain->getDivisions(); // Loop through, assign water or terrain auto points = terrain->Points(); for (int y = 0; y < hei; y++) { for (int x = 0; x < wid; x++) { // If the Z point is lower than or equal to the cut off point, set it as water. Otherwise, don't points[y][x]->z <= cutoffPoint ? SetPixeAsWater(x, y, true) : SetPixeAsWater(x, y, false); } } } bool WaterData::IsWater(int x, int y) { // OOB if (y > waterMap.size() - 1 || x > waterMap[0].size() - 1) return false; return (waterMap[x][y] == true); } bool WaterData::SectionContainsLand(int xOrigin, int width, int yOrigin, int height) { for (int y = yOrigin; y < yOrigin + height; y++) { for (int x = xOrigin; x < xOrigin + width; x++) { // If we found a section that isn't water, return true if (!IsWater(x, y)) return true; } } // Return false if none is found return false; } // Private void WaterData::SetPixeAsWater(int x, int y, bool water) { waterMap[x][y] = water; } void WaterData::fillWaterMap(int size) { for (int y = 0; y < size; y++) { waterMap.push_back(std::vector<bool>()); for (int x = 0; x < size; x++) { waterMap[y].push_back(false); } } }
22.489583
99
0.64428
[ "vector" ]
e8c49818aa6089bee4875df510ad9e7012784480
69,837
cpp
C++
Modules/SemanticRelations/src/mitkRelationStorage.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Modules/SemanticRelations/src/mitkRelationStorage.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Modules/SemanticRelations/src/mitkRelationStorage.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkRelationStorage.h" // semantic relations module #include "mitkDICOMHelper.h" // multi label module #include <mitkLabelSetImage.h> // mitk core #include <mitkIPersistenceService.h> #include <mitkVectorProperty.h> // c++ #include <algorithm> #include <iostream> namespace { std::vector<mitk::SemanticTypes::CaseID> GetCaseIDs() { PERSISTENCE_GET_SERVICE_MACRO if (nullptr == persistenceService) { MITK_DEBUG << "Persistence service could not be loaded"; return std::vector<mitk::SemanticTypes::CaseID>(); } // the property list is valid for a certain scenario and contains all the case IDs of the radiological user's MITK session std::string listIdentifier = "caseIDs"; mitk::PropertyList::Pointer propertyList = persistenceService->GetPropertyList(listIdentifier); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << listIdentifier << " for the current MITK workbench / session."; return std::vector<mitk::SemanticTypes::CaseID>(); } // retrieve a vector property that contains all case IDs mitk::VectorProperty<std::string>* caseIDsVectorProperty = dynamic_cast<mitk::VectorProperty<std::string>*>(propertyList->GetProperty(listIdentifier)); if (nullptr == caseIDsVectorProperty) { MITK_DEBUG << "Could not find the property " << listIdentifier << " for the " << listIdentifier << " property list."; return std::vector<mitk::SemanticTypes::CaseID>(); } return caseIDsVectorProperty->GetValue(); } bool CaseIDExists(const mitk::SemanticTypes::CaseID& caseID) { auto allCaseIDs = GetCaseIDs(); auto existingCase = std::find(allCaseIDs.begin(), allCaseIDs.end(), caseID); if (existingCase == allCaseIDs.end()) { return false; } return true; } mitk::PropertyList::Pointer GetStorageData(const mitk::SemanticTypes::CaseID& caseID) { // access the storage PERSISTENCE_GET_SERVICE_MACRO if (nullptr == persistenceService) { MITK_DEBUG << "Persistence service could not be loaded"; return nullptr; } // The persistence service may create a new property list with the given ID, if no property list is found. // Since we don't want to return a new property list but rather inform the user that the given case // is not a valid, stored case, we will return nullptr in that case. if (CaseIDExists(caseID)) { // the property list is valid for a whole case and contains all the properties for the current case return persistenceService->GetPropertyList(const_cast<mitk::SemanticTypes::CaseID&>(caseID)); } return nullptr; } mitk::SemanticTypes::Lesion GenerateLesion(const mitk::SemanticTypes::CaseID& caseID, const mitk::SemanticTypes::ID& lesionID) { mitk::PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return mitk::SemanticTypes::Lesion(); } mitk::VectorProperty<std::string>* lesionDataProperty = dynamic_cast<mitk::VectorProperty<std::string>*>(propertyList->GetProperty(lesionID)); if (nullptr == lesionDataProperty) { MITK_DEBUG << "Lesion " << lesionID << " not found. Lesion can not be retrieved."; return mitk::SemanticTypes::Lesion(); } std::vector<std::string> lesionData = lesionDataProperty->GetValue(); // a lesion date has to have exactly two values (the name of the lesion and the UID of the lesion class) if (lesionData.size() != 2) { MITK_DEBUG << "Incorrect lesion data storage. Not two (2) strings of the lesion name and the lesion UID are stored."; return mitk::SemanticTypes::Lesion(); } // the lesion class ID is stored as the second property std::string lesionClassID = lesionData[1]; mitk::StringProperty* lesionClassProperty = dynamic_cast<mitk::StringProperty*>(propertyList->GetProperty(lesionClassID)); if (nullptr != lesionClassProperty) { mitk::SemanticTypes::LesionClass generatedLesionClass; generatedLesionClass.UID = lesionClassID; generatedLesionClass.classType = lesionClassProperty->GetValue(); mitk::SemanticTypes::Lesion generatedLesion; generatedLesion.UID = lesionID; generatedLesion.name = lesionData[0]; generatedLesion.lesionClass = generatedLesionClass; return generatedLesion; } MITK_DEBUG << "Incorrect lesion class storage. Lesion " << lesionID << " can not be retrieved."; return mitk::SemanticTypes::Lesion(); } mitk::SemanticTypes::ControlPoint GenerateControlpoint(const mitk::SemanticTypes::CaseID& caseID, const mitk::SemanticTypes::ID& controlPointUID) { mitk::PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return mitk::SemanticTypes::ControlPoint(); } // retrieve a vector property that contains the integer values of the date of a control point (0. year 1. month 2. day) mitk::VectorProperty<int>* controlPointVectorProperty = dynamic_cast<mitk::VectorProperty<int>*>(propertyList->GetProperty(controlPointUID)); if (nullptr == controlPointVectorProperty) { MITK_DEBUG << "Could not find the control point " << controlPointUID << " in the storage."; return mitk::SemanticTypes::ControlPoint(); } std::vector<int> controlPointVectorPropertyValue = controlPointVectorProperty->GetValue(); // a control point has to have exactly three integer values (year, month and day) if (controlPointVectorPropertyValue.size() != 3) { MITK_DEBUG << "Incorrect control point storage. Not three (3) values of the date are stored."; return mitk::SemanticTypes::ControlPoint(); } // set the values of the control point mitk::SemanticTypes::ControlPoint generatedControlPoint; generatedControlPoint.UID = controlPointUID; generatedControlPoint.date = boost::gregorian::date(controlPointVectorPropertyValue[0], controlPointVectorPropertyValue[1], controlPointVectorPropertyValue[2]); return generatedControlPoint; } } mitk::SemanticTypes::LesionVector mitk::RelationStorage::GetAllLesionsOfCase(const SemanticTypes::CaseID& caseID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::LesionVector(); } // retrieve a vector property that contains the valid lesion-IDs for the current case VectorProperty<std::string>* lesionsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions")); if (nullptr == lesionsVectorProperty) { MITK_DEBUG << "Could not find any lesion in the storage."; return SemanticTypes::LesionVector(); } std::vector<std::string> lesionsVectorPropertyValue = lesionsVectorProperty->GetValue(); SemanticTypes::LesionVector allLesionsOfCase; for (const auto& lesionID : lesionsVectorPropertyValue) { SemanticTypes::Lesion generatedLesion = GenerateLesion(caseID, lesionID); if (!generatedLesion.UID.empty()) { allLesionsOfCase.push_back(generatedLesion); } } return allLesionsOfCase; } mitk::SemanticTypes::Lesion mitk::RelationStorage::GetLesionOfSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::Lesion(); } // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID) VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID)); if (nullptr == segmentationVectorProperty) { MITK_DEBUG << "Could not find the segmentation " << segmentationID << " in the storage."; return SemanticTypes::Lesion(); } std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue(); // the lesion ID of a segmentation is the second value in the vector if (segmentationVectorPropertyValue.size() != 2) { MITK_DEBUG << "Incorrect segmentation storage. Not two (2) IDs stored."; return SemanticTypes::Lesion(); } std::string lesionID = segmentationVectorPropertyValue[1]; if (lesionID.empty()) { // segmentation does not refer to any lesion; return empty lesion return SemanticTypes::Lesion(); } return GenerateLesion(caseID, lesionID); } mitk::SemanticTypes::ControlPointVector mitk::RelationStorage::GetAllControlPointsOfCase(const SemanticTypes::CaseID& caseID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::ControlPointVector(); } // retrieve a vector property that contains the valid control point-IDs for the current case VectorProperty<std::string>* controlPointsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("controlpoints")); if (nullptr == controlPointsVectorProperty) { MITK_DEBUG << "Could not find any control points in the storage."; return SemanticTypes::ControlPointVector(); } std::vector<std::string> controlPointsVectorPropertyValue = controlPointsVectorProperty->GetValue(); SemanticTypes::ControlPointVector allControlPointsOfCase; for (const auto& controlPointUID : controlPointsVectorPropertyValue) { SemanticTypes::ControlPoint generatedControlPoint = GenerateControlpoint(caseID, controlPointUID); if (!generatedControlPoint.UID.empty()) { allControlPointsOfCase.push_back(generatedControlPoint); } } return allControlPointsOfCase; } mitk::SemanticTypes::ControlPoint mitk::RelationStorage::GetControlPointOfImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::ControlPoint(); } // retrieve a vector property that contains the information type and the referenced ID of a control point (0. information type 1. control point ID) VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID)); if (nullptr == imageVectorProperty) { MITK_DEBUG << "Could not find the image " << imageID << " in the storage."; return SemanticTypes::ControlPoint(); } std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue(); SemanticTypes::ControlPoint controlPoint; // an image has to have exactly two values (the information type and the ID of the control point) if (imageVectorPropertyValue.size() != 2) { MITK_DEBUG << "Incorrect data storage. Not two (2) values stored."; return SemanticTypes::ControlPoint(); } // the second value of the image vector is the ID of the referenced control point std::string controlPointID = imageVectorPropertyValue[1]; // retrieve a vector property that contains the integer values of the date of a control point (0. year 1. month 2. day) VectorProperty<int>* controlPointVectorProperty = dynamic_cast<VectorProperty<int>*>(propertyList->GetProperty(controlPointID)); if (nullptr == controlPointVectorProperty) { MITK_DEBUG << "Could not find the control point " << controlPointID << " in the storage."; return SemanticTypes::ControlPoint(); } std::vector<int> controlPointVectorPropertyValue = controlPointVectorProperty->GetValue(); // a control point has to have exactly three integer values (year, month and day) if (controlPointVectorPropertyValue.size() != 3) { MITK_DEBUG << "Incorrect control point storage. Not three (3) values of the date are stored."; return SemanticTypes::ControlPoint(); } // set the values of the control point controlPoint.UID = controlPointID; controlPoint.date = boost::gregorian::date(controlPointVectorPropertyValue[0], controlPointVectorPropertyValue[1], controlPointVectorPropertyValue[2]); return controlPoint; } mitk::SemanticTypes::ExaminationPeriodVector mitk::RelationStorage::GetAllExaminationPeriodsOfCase(const SemanticTypes::CaseID& caseID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::ExaminationPeriodVector(); } // retrieve a vector property that contains the valid examination period UIDs for the current case VectorProperty<std::string>::Pointer examinationPeriodsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("examinationperiods")); if (nullptr == examinationPeriodsVectorProperty) { MITK_DEBUG << "Could not find any examination periods in the storage."; return SemanticTypes::ExaminationPeriodVector(); } std::vector<std::string> examinationPeriodsVectorPropertyValue = examinationPeriodsVectorProperty->GetValue(); SemanticTypes::ExaminationPeriodVector allExaminationPeriods; for (const auto& examinationPeriodID : examinationPeriodsVectorPropertyValue) { // retrieve a vector property that contains the represented control point-IDs VectorProperty<std::string>::Pointer examinationPeriodVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(examinationPeriodID)); if (nullptr == examinationPeriodVectorProperty) { MITK_DEBUG << "Could not find the examination period " << examinationPeriodID << " in the storage."; continue; } std::vector<std::string> examinationPeriodVectorPropertyValue = examinationPeriodVectorProperty->GetValue(); // an examination period has an arbitrary number of vector values (name and control point UIDs) (at least one for the name) if (examinationPeriodVectorPropertyValue.empty()) { MITK_DEBUG << "Incorrect examination period storage. At least one (1) value for the examination period name has to be stored."; continue; } else { // set the values of the name and the control points SemanticTypes::ExaminationPeriod generatedExaminationPeriod; generatedExaminationPeriod.UID = examinationPeriodID; generatedExaminationPeriod.name = examinationPeriodVectorPropertyValue[0]; for (size_t i = 1; i < examinationPeriodVectorPropertyValue.size(); ++i) { generatedExaminationPeriod.controlPointUIDs.push_back(examinationPeriodVectorPropertyValue[i]); } allExaminationPeriods.push_back(generatedExaminationPeriod); } } return allExaminationPeriods; } mitk::SemanticTypes::InformationTypeVector mitk::RelationStorage::GetAllInformationTypesOfCase(const SemanticTypes::CaseID& caseID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::InformationTypeVector(); } // retrieve a vector property that contains the valid information types of the current case VectorProperty<std::string>* informationTypesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("informationtypes")); if (nullptr == informationTypesVectorProperty) { MITK_DEBUG << "Could not find any information types in the storage."; return SemanticTypes::InformationTypeVector(); } return informationTypesVectorProperty->GetValue(); } mitk::SemanticTypes::InformationType mitk::RelationStorage::GetInformationTypeOfImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::InformationType(); } // retrieve a vector property that contains the information type and the referenced ID of an image (0. information type 1. control point ID) VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID)); if (nullptr == imageVectorProperty) { MITK_DEBUG << "Could not find the image " << imageID << " in the storage."; return SemanticTypes::InformationType(); } std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue(); // an image has to have exactly two values (the information type and the ID of the control point) if (imageVectorPropertyValue.size() != 2) { MITK_DEBUG << "Incorrect data storage. Not two (2) values stored."; return SemanticTypes::InformationType(); } // the first value of the image vector is the information type return imageVectorPropertyValue[0]; } mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllImageIDsOfCase(const SemanticTypes::CaseID& caseID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::IDVector(); } // retrieve a vector property that contains the valid image-IDs of the current case VectorProperty<std::string>* imagesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("images")); if (nullptr == imagesVectorProperty) { MITK_DEBUG << "Could not find any image in the storage."; return SemanticTypes::IDVector(); } return imagesVectorProperty->GetValue(); } mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllImageIDsOfControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::IDVector(); } // retrieve a vector property that contains the valid image-IDs of the current case VectorProperty<std::string>* imagesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("images")); if (nullptr == imagesVectorProperty) { MITK_DEBUG << "Could not find any image in the storage."; return SemanticTypes::IDVector(); } mitk::SemanticTypes::IDVector allImageIDsOfControlPoint; std::vector<std::string> imagesVectorPropertyValue = imagesVectorProperty->GetValue(); for (const auto& imageID : imagesVectorPropertyValue) { // retrieve a vector property that contains the referenced ID of an image (0. information type 1. control point ID) VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID)); if (nullptr == imageVectorProperty) { continue; } std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue(); // an image has to have exactly two values (the information type and the ID of the control point) if (imageVectorPropertyValue.size() != 2) { continue; } // the second value of the image vector is the ID of the referenced control point if (imageVectorPropertyValue[1] == controlPoint.UID) { allImageIDsOfControlPoint.push_back(imageID); } } return allImageIDsOfControlPoint; } mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllImageIDsOfInformationType(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::IDVector(); } // retrieve a vector property that contains the valid image-IDs of the current case VectorProperty<std::string>* imagesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("images")); if (nullptr == imagesVectorProperty) { MITK_DEBUG << "Could not find any image in the storage."; return SemanticTypes::IDVector(); } mitk::SemanticTypes::IDVector allImageIDsOfInformationType; std::vector<std::string> imagesVectorPropertyValue = imagesVectorProperty->GetValue(); for (const auto& imageID : imagesVectorPropertyValue) { // retrieve a vector property that contains the referenced ID of an image (0. information type 1. control point ID) VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID)); if (nullptr == imageVectorProperty) { continue; } std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue(); // an image has to have exactly two values (the information type and the ID of the control point) if (imageVectorPropertyValue.size() != 2) { continue; } // the first value of the image vector is the ID of the referenced information type if (imageVectorPropertyValue[0] == informationType) { allImageIDsOfInformationType.push_back(imageID); } } return allImageIDsOfInformationType; } mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllSegmentationIDsOfCase(const SemanticTypes::CaseID& caseID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::IDVector(); } // retrieve a vector property that contains the valid segmentation-IDs for the current case VectorProperty<std::string>* segmentationsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("segmentations")); if (nullptr == segmentationsVectorProperty) { MITK_DEBUG << "Could not find any segmentation in the storage."; return SemanticTypes::IDVector(); } return segmentationsVectorProperty->GetValue(); } mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllSegmentationIDsOfImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::IDVector(); } // retrieve a vector property that contains the valid segmentation-IDs for the current case VectorProperty<std::string>* segmentationsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("segmentations")); if (nullptr == segmentationsVectorProperty) { MITK_DEBUG << "Could not find any segmentation in the storage."; return SemanticTypes::IDVector(); } mitk::SemanticTypes::IDVector allSegmentationIDsOfImage; std::vector<std::string> segmentationsVectorPropertyValue = segmentationsVectorProperty->GetValue(); for (const auto& segmentationID : segmentationsVectorPropertyValue) { // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID) VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID)); if (nullptr == segmentationVectorProperty) { continue; } std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue(); // a segmentation has to have exactly two values (the ID of the referenced image and the ID of the referenced lesion) if (segmentationVectorPropertyValue.size() != 2) { continue; } // the first value of the segmentation vector is the ID of the referenced image if (segmentationVectorPropertyValue[0] == imageID) { allSegmentationIDsOfImage.push_back(segmentationID); } } return allSegmentationIDsOfImage; } mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllSegmentationIDsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::IDVector(); } // retrieve a vector property that contains the valid segmentation-IDs for the current case VectorProperty<std::string>* segmentationsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("segmentations")); if (nullptr == segmentationsVectorProperty) { MITK_DEBUG << "Could not find any segmentation in the storage."; return SemanticTypes::IDVector(); } mitk::SemanticTypes::IDVector allSegmentationIDsOfLesion; std::vector<std::string> segmentationsVectorPropertyValue = segmentationsVectorProperty->GetValue(); for (const auto& segmentationID : segmentationsVectorPropertyValue) { // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID) VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID)); if (nullptr == segmentationVectorProperty) { continue; } std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue(); // a segmentation has to have exactly two values (the ID of the referenced image and the ID of the referenced lesion) if (segmentationVectorPropertyValue.size() != 2) { continue; } // the second value of the segmentation vector is the ID of the referenced lesion if (segmentationVectorPropertyValue[1] == lesion.UID) { allSegmentationIDsOfLesion.push_back(segmentationID); } } return allSegmentationIDsOfLesion; } mitk::SemanticTypes::ID mitk::RelationStorage::GetImageIDOfSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return SemanticTypes::ID(); } // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID) VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID)); if (nullptr == segmentationVectorProperty) { MITK_DEBUG << "Could not find the segmentation " << segmentationID << " in the storage."; return SemanticTypes::ID(); } std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue(); // the lesion ID of a segmentation is the second value in the vector if (segmentationVectorPropertyValue.size() != 2) { MITK_DEBUG << "Incorrect segmentation storage. Not two (2) IDs stored."; return SemanticTypes::ID(); } return segmentationVectorPropertyValue[0]; } std::vector<mitk::SemanticTypes::CaseID> mitk::RelationStorage::GetAllCaseIDs() { return GetCaseIDs(); } bool mitk::RelationStorage::InstanceExists(const SemanticTypes::CaseID& caseID) { return CaseIDExists(caseID); } void mitk::RelationStorage::AddCase(const SemanticTypes::CaseID& caseID) { PERSISTENCE_GET_SERVICE_MACRO if (nullptr == persistenceService) { MITK_DEBUG << "Persistence service could not be loaded"; return; } // the property list is valid for a certain scenario and contains all the case IDs of the radiological user's MITK session std::string listIdentifier = "caseIDs"; PropertyList::Pointer propertyList = persistenceService->GetPropertyList(listIdentifier); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << listIdentifier << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains all case IDs VectorProperty<std::string>::Pointer caseIDsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(listIdentifier)); std::vector<std::string> caseIDsVectorPropertyValue; if (nullptr == caseIDsVectorProperty) { caseIDsVectorProperty = VectorProperty<std::string>::New(); } else { caseIDsVectorPropertyValue = caseIDsVectorProperty->GetValue(); } auto existingCase = std::find(caseIDsVectorPropertyValue.begin(), caseIDsVectorPropertyValue.end(), caseID); if (existingCase != caseIDsVectorPropertyValue.end()) { return; } // add case to the "caseIDs" property list caseIDsVectorPropertyValue.push_back(caseID); caseIDsVectorProperty->SetValue(caseIDsVectorPropertyValue); propertyList->SetProperty(listIdentifier, caseIDsVectorProperty); } void mitk::RelationStorage::AddImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid image-IDs for the current case VectorProperty<std::string>::Pointer imagesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("images")); std::vector<std::string> imagesVectorPropertyValue; if (nullptr == imagesVectorProperty) { imagesVectorProperty = VectorProperty<std::string>::New(); } else { imagesVectorPropertyValue = imagesVectorProperty->GetValue(); } auto existingImage = std::find(imagesVectorPropertyValue.begin(), imagesVectorPropertyValue.end(), imageID); if (existingImage != imagesVectorPropertyValue.end()) { return; } // add image to the "images" property list imagesVectorPropertyValue.push_back(imageID); imagesVectorProperty->SetValue(imagesVectorPropertyValue); propertyList->SetProperty("images", imagesVectorProperty); // add the image itself VectorProperty<std::string>::Pointer imageVectorProperty = VectorProperty<std::string>::New(); // an image has to have exactly two values (the information type and the ID of the control point) std::vector<std::string> imageVectorPropertyValue(2); imageVectorProperty->SetValue(imageVectorPropertyValue); propertyList->SetProperty(imageID, imageVectorProperty); } void mitk::RelationStorage::RemoveImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid image-IDs for the current case VectorProperty<std::string>::Pointer imagesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("images")); if (nullptr == imagesVectorProperty) { MITK_DEBUG << "Could not find any images in the storage."; return; } // remove the image reference from the list of all images of the current case std::vector<std::string> imagesVectorPropertyValue = imagesVectorProperty->GetValue(); imagesVectorPropertyValue.erase(std::remove(imagesVectorPropertyValue.begin(), imagesVectorPropertyValue.end(), imageID), imagesVectorPropertyValue.end()); if (imagesVectorPropertyValue.empty()) { // no more images stored -> remove the images property list propertyList->DeleteProperty("images"); } else { // or store the modified vector value imagesVectorProperty->SetValue(imagesVectorPropertyValue); } // remove the image instance itself propertyList->DeleteProperty(imageID); } void mitk::RelationStorage::AddSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID, const SemanticTypes::ID& parentID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid segmentation-IDs for the current case VectorProperty<std::string>::Pointer segmentationsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("segmentations")); std::vector<std::string> segmentationsVectorPropertyValue; if (nullptr == segmentationsVectorProperty) { segmentationsVectorProperty = VectorProperty<std::string>::New(); } else { segmentationsVectorPropertyValue = segmentationsVectorProperty->GetValue(); } auto existingSegmentation = std::find(segmentationsVectorPropertyValue.begin(), segmentationsVectorPropertyValue.end(), segmentationID); if (existingSegmentation != segmentationsVectorPropertyValue.end()) { return; } // add segmentation to the "segmentations" property list segmentationsVectorPropertyValue.push_back(segmentationID); segmentationsVectorProperty->SetValue(segmentationsVectorPropertyValue); propertyList->SetProperty("segmentations", segmentationsVectorProperty); // add the segmentation itself VectorProperty<std::string>::Pointer segmentationVectorProperty = VectorProperty<std::string>::New(); // a segmentation has to have exactly two values (the ID of the referenced image and the ID of the referenced lesion) std::vector<std::string> segmentationVectorPropertyValue(2); segmentationVectorPropertyValue[0] = parentID; segmentationVectorProperty->SetValue(segmentationVectorPropertyValue); propertyList->SetProperty(segmentationID, segmentationVectorProperty); } void mitk::RelationStorage::RemoveSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid segmentation-IDs for the current case VectorProperty<std::string>::Pointer segmentationsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("segmentations")); if (nullptr == segmentationsVectorProperty) { MITK_DEBUG << "Could not find any segmentation in the storage."; return; } // remove the lesion reference from the list of all lesions of the current case std::vector<std::string> segmentationsVectorPropertyValue = segmentationsVectorProperty->GetValue(); segmentationsVectorPropertyValue.erase(std::remove(segmentationsVectorPropertyValue.begin(), segmentationsVectorPropertyValue.end(), segmentationID), segmentationsVectorPropertyValue.end()); if (segmentationsVectorPropertyValue.empty()) { // no more segmentations stored -> remove the segmentations property list propertyList->DeleteProperty("segmentations"); } else { // or store the modified vector value segmentationsVectorProperty->SetValue(segmentationsVectorPropertyValue); } // remove the lesion instance itself propertyList->DeleteProperty(segmentationID); } void mitk::RelationStorage::AddLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid lesion-IDs for the current case VectorProperty<std::string>::Pointer lesionsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions")); std::vector<std::string> lesionsVectorPropertyValue; if (nullptr == lesionsVectorProperty) { lesionsVectorProperty = VectorProperty<std::string>::New(); } else { lesionsVectorPropertyValue = lesionsVectorProperty->GetValue(); } const auto& existingIndex = std::find(lesionsVectorPropertyValue.begin(), lesionsVectorPropertyValue.end(), lesion.UID); if (existingIndex != lesionsVectorPropertyValue.end()) { return; } // add the new lesion id from the given lesion to the vector of all current lesion IDs lesionsVectorPropertyValue.push_back(lesion.UID); // overwrite the current vector property with the new, extended string vector lesionsVectorProperty->SetValue(lesionsVectorPropertyValue); propertyList->SetProperty("lesions", lesionsVectorProperty); // add the lesion with the lesion UID as the key and the lesion information as value std::vector<std::string> lesionData; lesionData.push_back(lesion.name); lesionData.push_back(lesion.lesionClass.UID); VectorProperty<std::string>::Pointer newLesionVectorProperty = VectorProperty<std::string>::New(); newLesionVectorProperty->SetValue(lesionData); propertyList->SetProperty(lesion.UID, newLesionVectorProperty); // add the lesion class with the lesion class UID as key and the class type as value std::string lesionClassType = lesion.lesionClass.classType; propertyList->SetStringProperty(lesion.lesionClass.UID.c_str(), lesionClassType.c_str()); } void mitk::RelationStorage::OverwriteLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid lesion-IDs for the current case VectorProperty<std::string>* lesionVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions")); if (nullptr == lesionVectorProperty) { MITK_DEBUG << "Could not find any lesion in the storage."; return; } std::vector<std::string> lesionVectorPropertyValue = lesionVectorProperty->GetValue(); const auto existingLesion = std::find(lesionVectorPropertyValue.begin(), lesionVectorPropertyValue.end(), lesion.UID); if (existingLesion != lesionVectorPropertyValue.end()) { // overwrite the referenced lesion class UID with the new, given lesion class data std::vector<std::string> lesionData; lesionData.push_back(lesion.name); lesionData.push_back(lesion.lesionClass.UID); VectorProperty<std::string>::Pointer newLesionVectorProperty = VectorProperty<std::string>::New(); newLesionVectorProperty->SetValue(lesionData); propertyList->SetProperty(lesion.UID, newLesionVectorProperty); // overwrite the lesion class with the lesion class UID as key and the new, given class type as value std::string lesionClassType = lesion.lesionClass.classType; propertyList->SetStringProperty(lesion.lesionClass.UID.c_str(), lesionClassType.c_str()); } else { MITK_DEBUG << "Could not find lesion " << lesion.UID << " in the storage. Cannot overwrite the lesion."; } } void mitk::RelationStorage::LinkSegmentationToLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID, const SemanticTypes::Lesion& lesion) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid lesion-IDs for the current case VectorProperty<std::string>* lesionVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions")); if (nullptr == lesionVectorProperty) { MITK_DEBUG << "Could not find any lesion in the storage."; return; } std::vector<std::string> lesionVectorPropertyValue = lesionVectorProperty->GetValue(); const auto existingLesion = std::find(lesionVectorPropertyValue.begin(), lesionVectorPropertyValue.end(), lesion.UID); if (existingLesion != lesionVectorPropertyValue.end()) { // set / overwrite the lesion reference of the given segmentation // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID) VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID)); if (nullptr == segmentationVectorProperty) { MITK_DEBUG << "Could not find the segmentation " << segmentationID << " in the storage. Cannot link segmentation to lesion."; return; } std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue(); if (segmentationVectorPropertyValue.size() != 2) { MITK_DEBUG << "Incorrect segmentation storage. Not two (2) IDs stored."; return; } // the lesion ID of a segmentation is the second value in the vector segmentationVectorPropertyValue[1] = lesion.UID; segmentationVectorProperty->SetValue(segmentationVectorPropertyValue); return; } MITK_DEBUG << "Could not find lesion " << lesion.UID << " in the storage. Cannot link segmentation to lesion."; } void mitk::RelationStorage::UnlinkSegmentationFromLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID) VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID)); if (nullptr == segmentationVectorProperty) { MITK_DEBUG << "Could not find the segmentation " << segmentationID << " in the storage. Cannot unlink lesion from segmentation."; return; } std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue(); // a segmentation has to have exactly two values (the ID of the linked image and the ID of the lesion) if (segmentationVectorPropertyValue.size() != 2) { MITK_DEBUG << "Incorrect data storage. Not two (2) values stored."; return; } // the second value of the segmentation vector is the ID of the referenced lesion // set the lesion reference to an empty string for removal segmentationVectorPropertyValue[1] = ""; segmentationVectorProperty->SetValue(segmentationVectorPropertyValue); } void mitk::RelationStorage::RemoveLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid lesions of the current case VectorProperty<std::string>* lesionVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions")); if (nullptr == lesionVectorProperty) { MITK_DEBUG << "Could not find any lesion in the storage."; return; } // remove the lesion reference from the list of all lesions of the current case std::vector<std::string> lesionsVectorPropertyValue = lesionVectorProperty->GetValue(); lesionsVectorPropertyValue.erase(std::remove(lesionsVectorPropertyValue.begin(), lesionsVectorPropertyValue.end(), lesion.UID), lesionsVectorPropertyValue.end()); if (lesionsVectorPropertyValue.empty()) { // no more lesions stored -> remove the lesions property list propertyList->DeleteProperty("lesions"); } else { // or store the modified vector value lesionVectorProperty->SetValue(lesionsVectorPropertyValue); } // remove the lesion instance itself // the lesion data is stored under the lesion ID VectorProperty<std::string>* lesionDataProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(lesion.UID)); if (nullptr == lesionDataProperty) { MITK_DEBUG << "Lesion " << lesion.UID << " not found (already removed?). Cannot remove the lesion."; return; } std::vector<std::string> lesionData = lesionDataProperty->GetValue(); // a lesion date has to have exactly two values (the name of the lesion and the UID of the lesion class) if (lesionData.size() != 2) { MITK_DEBUG << "Incorrect lesion data storage. Not two (2) strings of the lesion UID and the lesion name are stored."; } else { std::string lesionClassID = lesionData[1]; RemoveLesionClass(caseID, lesionClassID); } propertyList->DeleteProperty(lesion.UID); } void mitk::RelationStorage::RemoveLesionClass(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& lesionClassID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the lesion class StringProperty* lesionClassProperty = dynamic_cast<StringProperty*>(propertyList->GetProperty(lesionClassID)); if (nullptr == lesionClassProperty) { MITK_DEBUG << "Lesion class " << lesionClassID << " not found (already removed?). Cannot remove the lesion class."; return; } // retrieve a vector property that contains the valid lesions of the current case VectorProperty<std::string>* lesionVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions")); if (nullptr == lesionVectorProperty) { return; } // check if the lesion class ID is referenced by any other lesion std::vector<std::string> lesionsVectorPropertyValue = lesionVectorProperty->GetValue(); const auto existingLesionClass = std::find_if(lesionsVectorPropertyValue.begin(), lesionsVectorPropertyValue.end(), [&propertyList, &lesionClassID](const std::string& lesionID) { VectorProperty<std::string>* lesionDataProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(lesionID)); if (nullptr == lesionDataProperty) { return false; } std::vector<std::string> lesionData = lesionDataProperty->GetValue(); // a lesion date has to have exactly two values (the name of the lesion and the UID of the lesion class) if (lesionData.size() != 2) { return false; } return lesionData[1] == lesionClassID; }); if (existingLesionClass == lesionsVectorPropertyValue.end()) { // lesion class ID not referenced; remove lesion class propertyList->DeleteProperty(lesionClassID); } } void mitk::RelationStorage::AddControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid controlPoint UIDs for the current case VectorProperty<std::string>::Pointer controlPointsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("controlpoints")); std::vector<std::string> controlPointsVectorPropertyValue; if (nullptr == controlPointsVectorProperty) { controlPointsVectorProperty = VectorProperty<std::string>::New(); } else { controlPointsVectorPropertyValue = controlPointsVectorProperty->GetValue(); } const auto existingControlPoint = std::find(controlPointsVectorPropertyValue.begin(), controlPointsVectorPropertyValue.end(), controlPoint.UID); if (existingControlPoint != controlPointsVectorPropertyValue.end()) { return; } // add the new control point UID from the given control point to the vector of all current control point UIDs controlPointsVectorPropertyValue.push_back(controlPoint.UID); // overwrite the current vector property with the new, extended string vector controlPointsVectorProperty->SetValue(controlPointsVectorPropertyValue); propertyList->SetProperty("controlpoints", controlPointsVectorProperty); // store the control point values (the three integer values of a date) std::vector<int> controlPointDate; controlPointDate.push_back(controlPoint.date.year()); controlPointDate.push_back(controlPoint.date.month()); controlPointDate.push_back(controlPoint.date.day()); VectorProperty<int>::Pointer newControlPointVectorProperty = VectorProperty<int>::New(); newControlPointVectorProperty->SetValue(controlPointDate); propertyList->SetProperty(controlPoint.UID, newControlPointVectorProperty); } void mitk::RelationStorage::LinkImageToControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID, const SemanticTypes::ControlPoint& controlPoint) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid controlPoint UIDs for the current case VectorProperty<std::string>* controlPointsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("controlpoints")); if (nullptr == controlPointsVectorProperty) { MITK_DEBUG << "Could not find any control point in the storage."; return; } std::vector<std::string> controlPointsVectorPropertyValue = controlPointsVectorProperty->GetValue(); const auto existingControlPoint = std::find(controlPointsVectorPropertyValue.begin(), controlPointsVectorPropertyValue.end(), controlPoint.UID); if (existingControlPoint != controlPointsVectorPropertyValue.end()) { // set / overwrite the control point reference of the given data // retrieve a vector property that contains the referenced ID of a image (0. information type 1. control point ID) VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID)); if (nullptr == imageVectorProperty) { MITK_DEBUG << "Could not find the image " << imageID << " in the storage. Cannot link data to control point."; return; } std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue(); // an image has to have exactly two values (the information type and the ID of the control point) if (imageVectorPropertyValue.size() != 2) { MITK_DEBUG << "Incorrect data storage. Not two (2) values stored."; return; } // the second value of the image vector is the ID of the referenced control point imageVectorPropertyValue[1] = controlPoint.UID; imageVectorProperty->SetValue(imageVectorPropertyValue); return; } MITK_DEBUG << "Could not find control point " << controlPoint.UID << " in the storage. Cannot link data to control point."; } void mitk::RelationStorage::UnlinkImageFromControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the referenced ID of a date (0. information type 1. control point ID) VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID)); if (nullptr == imageVectorProperty) { MITK_DEBUG << "Could not find the date " << imageID << " in the storage. Cannot unlink control point from date."; return; } std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue(); // an image has to have exactly two values (the information type and the ID of the control point) if (imageVectorPropertyValue.size() != 2) { MITK_DEBUG << "Incorrect data storage. Not two (2) values stored."; return; } // the second value of the image vector is the ID of the referenced control point // set the control point reference to an empty string for removal imageVectorPropertyValue[1] = ""; imageVectorProperty->SetValue(imageVectorPropertyValue); } void mitk::RelationStorage::RemoveControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid controlPoint UIDs for the current case VectorProperty<std::string>* controlPointsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("controlpoints")); if (nullptr == controlPointsVectorProperty) { MITK_DEBUG << "Could not find any control point in the storage."; return; } // remove the control point reference from the list of all control points of the current case std::vector<std::string> controlPointsVectorPropertyValue = controlPointsVectorProperty->GetValue(); controlPointsVectorPropertyValue.erase(std::remove(controlPointsVectorPropertyValue.begin(), controlPointsVectorPropertyValue.end(), controlPoint.UID), controlPointsVectorPropertyValue.end()); if (controlPointsVectorPropertyValue.empty()) { // no more control points stored -> remove the control point property list propertyList->DeleteProperty("controlpoints"); } else { // or store the modified vector value controlPointsVectorProperty->SetValue(controlPointsVectorPropertyValue); } // remove the control point instance itself propertyList->DeleteProperty(controlPoint.UID); } void mitk::RelationStorage::AddExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid examination period UIDs for the current case VectorProperty<std::string>::Pointer examinationPeriodsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("examinationperiods")); std::vector<std::string> examinationPeriodsVectorPropertyValue; if (nullptr == examinationPeriodsVectorProperty) { examinationPeriodsVectorProperty = VectorProperty<std::string>::New(); } else { examinationPeriodsVectorPropertyValue = examinationPeriodsVectorProperty->GetValue(); } const auto& existingIndex = std::find(examinationPeriodsVectorPropertyValue.begin(), examinationPeriodsVectorPropertyValue.end(), examinationPeriod.UID); if (existingIndex != examinationPeriodsVectorPropertyValue.end()) { return; } // add the new examination period id from the given examination period to the vector of all current examination period UIDs examinationPeriodsVectorPropertyValue.push_back(examinationPeriod.UID); // overwrite the current vector property with the new, extended string vector examinationPeriodsVectorProperty->SetValue(examinationPeriodsVectorPropertyValue); propertyList->SetProperty("examinationperiods", examinationPeriodsVectorProperty); // add the examination period with the UID as the key and the name as as the vector value std::vector<std::string> examinationPeriodData; examinationPeriodData.push_back(examinationPeriod.name); VectorProperty<std::string>::Pointer newExaminationPeriodVectorProperty = VectorProperty<std::string>::New(); newExaminationPeriodVectorProperty->SetValue(examinationPeriodData); propertyList->SetProperty(examinationPeriod.UID, newExaminationPeriodVectorProperty); } void mitk::RelationStorage::RenameExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the data of the given examination period VectorProperty<std::string>* examinationPeriodDataVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(examinationPeriod.UID)); if (nullptr == examinationPeriodDataVectorProperty) { MITK_DEBUG << "Could not find examination period " << examinationPeriod.UID << " in the storage. Cannot rename the examination period."; return; } std::vector<std::string> examinationPeriodDataVectorPropertyValue = examinationPeriodDataVectorProperty->GetValue(); // an examination period has an arbitrary number of vector values (name and control point UIDs) (at least one for the name) if (examinationPeriodDataVectorPropertyValue.size() < 1) { MITK_DEBUG << "Incorrect examination period storage. At least one (1) name has to be stored."; return; } else { // set the first vector value - the name examinationPeriodDataVectorPropertyValue[0] = examinationPeriod.name; // store the modified vector value examinationPeriodDataVectorProperty->SetValue(examinationPeriodDataVectorPropertyValue); } } void mitk::RelationStorage::AddControlPointToExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriod& examinationPeriod) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the represented control point UIDs of the given examination period VectorProperty<std::string>* controlPointUIDsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(examinationPeriod.UID)); if (nullptr == controlPointUIDsVectorProperty) { MITK_DEBUG << "Could not find the examination period " << examinationPeriod.UID << " in the storage. Cannot add the control point to the examination period."; return; } std::vector<std::string> controlPointUIDsVectorPropertyValue = controlPointUIDsVectorProperty->GetValue(); // store the control point UID controlPointUIDsVectorPropertyValue.push_back(controlPoint.UID); // sort the vector according to the date of the control points referenced by the UIDs auto lambda = [&caseID](const SemanticTypes::ID& leftControlPointUID, const SemanticTypes::ID& rightControlPointUID) { const auto& leftControlPoint = GenerateControlpoint(caseID, leftControlPointUID); const auto& rightControlPoint = GenerateControlpoint(caseID, rightControlPointUID); return leftControlPoint.date <= rightControlPoint.date; }; std::sort(controlPointUIDsVectorPropertyValue.begin(), controlPointUIDsVectorPropertyValue.end(), lambda); // store the modified and sorted control point UID vector of this examination period controlPointUIDsVectorProperty->SetValue(controlPointUIDsVectorPropertyValue); } void mitk::RelationStorage::RemoveControlPointFromExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriod& examinationPeriod) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the represented control point UIDs of the given examination period VectorProperty<std::string>* controlPointUIDsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(examinationPeriod.UID)); if (nullptr == controlPointUIDsVectorProperty) { MITK_DEBUG << "Could not find examination period " << examinationPeriod.UID << " in the storage. Cannot add the control point to the examination period."; return; } std::vector<std::string> controlPointUIDsVectorPropertyValue = controlPointUIDsVectorProperty->GetValue(); // an examination period has an arbitrary number of vector values (name and control point UIDs) (at least one for the name) if (controlPointUIDsVectorPropertyValue.size() < 2) { MITK_DEBUG << "Incorrect examination period storage. At least one (1) control point ID has to be stored."; return; } else { controlPointUIDsVectorPropertyValue.erase(std::remove(controlPointUIDsVectorPropertyValue.begin(), controlPointUIDsVectorPropertyValue.end(), controlPoint.UID), controlPointUIDsVectorPropertyValue.end()); if (controlPointUIDsVectorPropertyValue.size() < 2) { RemoveExaminationPeriod(caseID, examinationPeriod); } else { // store the modified vector value controlPointUIDsVectorProperty->SetValue(controlPointUIDsVectorPropertyValue); } } } void mitk::RelationStorage::RemoveExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid examination period UIDs for the current case VectorProperty<std::string>::Pointer examinationPeriodsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("examinationperiods")); if (nullptr == examinationPeriodsVectorProperty) { MITK_DEBUG << "Could not find any examination periods in the storage."; return; } std::vector<std::string> examinationPeriodsVectorPropertyValue = examinationPeriodsVectorProperty->GetValue(); examinationPeriodsVectorPropertyValue.erase(std::remove(examinationPeriodsVectorPropertyValue.begin(), examinationPeriodsVectorPropertyValue.end(), examinationPeriod.UID), examinationPeriodsVectorPropertyValue.end()); if (examinationPeriodsVectorPropertyValue.empty()) { // no more examination periods stored -> remove the examination period property list propertyList->DeleteProperty("examinationperiods"); } else { // or store the modified vector value examinationPeriodsVectorProperty->SetValue(examinationPeriodsVectorPropertyValue); } // remove the examination period instance itself propertyList->DeleteProperty(examinationPeriod.UID); } void mitk::RelationStorage::AddInformationTypeToImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID, const SemanticTypes::InformationType& informationType) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid information types of the current case VectorProperty<std::string>::Pointer informationTypesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("informationtypes")); std::vector<std::string> informationTypesVectorPropertyValue; if (nullptr == informationTypesVectorProperty) { informationTypesVectorProperty = VectorProperty<std::string>::New(); } else { informationTypesVectorPropertyValue = informationTypesVectorProperty->GetValue(); } const auto existingInformationType = std::find(informationTypesVectorPropertyValue.begin(), informationTypesVectorPropertyValue.end(), informationType); if (existingInformationType == informationTypesVectorPropertyValue.end()) { // at first: add the information type to the storage informationTypesVectorPropertyValue.push_back(informationType); informationTypesVectorProperty->SetValue(informationTypesVectorPropertyValue); propertyList->SetProperty("informationtypes", informationTypesVectorProperty); } // set / overwrite the information type of the given data // retrieve a vector property that contains the referenced ID of an image (0. information type 1. control point ID) VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID)); if (nullptr == imageVectorProperty) { MITK_DEBUG << "Could not find the image " << imageID << " in the storage. Cannot add information type to image."; return; } std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue(); // an image has to have exactly two values (the information type and the ID of the control point) if (imageVectorPropertyValue.size() != 2) { MITK_DEBUG << "Incorrect data storage. Not two (2) values stored."; return; } // the first value of the image vector is the information type imageVectorPropertyValue[0] = informationType; imageVectorProperty->SetValue(imageVectorPropertyValue); } void mitk::RelationStorage::RemoveInformationTypeFromImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the referenced ID of an image (0. information type 1. control point ID) VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID)); if (nullptr == imageVectorProperty) { MITK_DEBUG << "Could not find the image " << imageID << " in the storage. Cannot remove information type from image."; return; } std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue(); // an image has to have exactly two values (the information type and the ID of the control point) if (imageVectorPropertyValue.size() != 2) { MITK_DEBUG << "Incorrect data storage. Not two (2) values stored."; return; } // the first value of the image vector is the information type // set the information type to an empty string for removal imageVectorPropertyValue[0] = ""; imageVectorProperty->SetValue(imageVectorPropertyValue); } void mitk::RelationStorage::RemoveInformationType(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType) { PropertyList::Pointer propertyList = GetStorageData(caseID); if (nullptr == propertyList) { MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session."; return; } // retrieve a vector property that contains the valid information types of the current case VectorProperty<std::string>* informationTypesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("informationtypes")); if (nullptr == informationTypesVectorProperty) { MITK_DEBUG << "Could not find any information type in the storage."; return; } std::vector<std::string> informationTypesVectorPropertyValue = informationTypesVectorProperty->GetValue(); informationTypesVectorPropertyValue.erase(std::remove(informationTypesVectorPropertyValue.begin(), informationTypesVectorPropertyValue.end(), informationType), informationTypesVectorPropertyValue.end()); if (informationTypesVectorPropertyValue.empty()) { // no more information types stored -> remove the information types property list propertyList->DeleteProperty("informationtypes"); } else { // or store the modified vector value informationTypesVectorProperty->SetValue(informationTypesVectorPropertyValue); } }
44.538903
219
0.747254
[ "vector" ]
e8cae52ca4c0d72633cba18a8e75bc60c88ded9c
5,310
cpp
C++
plugins/mesh/src/gltf/glTFRenderTasksDataSource.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
null
null
null
plugins/mesh/src/gltf/glTFRenderTasksDataSource.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
null
null
null
plugins/mesh/src/gltf/glTFRenderTasksDataSource.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
null
null
null
#include "stdafx.h" #include "glTFRenderTasksDataSource.h" #include "tiny_gltf.h" #include "vislib/graphics/gl/IncludeAllGL.h" #include "vislib/math/Matrix.h" #include "mesh/MeshCalls.h" megamol::mesh::GlTFRenderTasksDataSource::GlTFRenderTasksDataSource() : m_glTF_callerSlot("CallGlTFData", "Connects the data source with a loaded glTF file") { this->m_glTF_callerSlot.SetCompatibleCall<CallGlTFDataDescription>(); this->MakeSlotAvailable(&this->m_glTF_callerSlot); } megamol::mesh::GlTFRenderTasksDataSource::~GlTFRenderTasksDataSource() { } bool megamol::mesh::GlTFRenderTasksDataSource::getDataCallback(core::Call & caller) { CallGPURenderTaskData* lhs_rtc = dynamic_cast<CallGPURenderTaskData*>(&caller); if (lhs_rtc == NULL) return false; std::shared_ptr<GPURenderTaskCollection> rt_collection(nullptr); if (lhs_rtc->getData() == nullptr){ rt_collection = this->m_gpu_render_tasks; } else { rt_collection = lhs_rtc->getData(); } CallGPUMaterialData* mtlc = this->m_material_slot.CallAs<CallGPUMaterialData>(); if (mtlc == NULL) return false; if (!(*mtlc)(0)) return false; CallGPUMeshData* mc = this->m_mesh_slot.CallAs<CallGPUMeshData>(); if (mc == NULL) return false; if (!(*mc)(0)) return false; CallGlTFData* gltf_call = this->m_glTF_callerSlot.CallAs<CallGlTFData>(); if (gltf_call == NULL) return false; if (!(*gltf_call)(0)) return false; auto gpu_mtl_storage = mtlc->getData(); auto gpu_mesh_storage = mc->getData(); //TODO nullptr check if (gltf_call->hasUpdate()) { ++m_version; //rt_collection->clear(); if (!m_rt_collection_indices.empty()) { // TODO delete all exisiting render task from this module for (auto& rt_idx : m_rt_collection_indices) { rt_collection->deleteSingleRenderTask(rt_idx); } m_rt_collection_indices.clear(); } auto model = gltf_call->getData(); for (size_t node_idx = 0; node_idx < model->nodes.size(); node_idx++) { if (node_idx < model->nodes.size() && model->nodes[node_idx].mesh != -1) { vislib::math::Matrix<GLfloat, 4, vislib::math::COLUMN_MAJOR> object_transform; if (model->nodes[node_idx].matrix.size() != 0) // has matrix transform { // TODO } else { auto& translation = model->nodes[node_idx].translation; auto& scale = model->nodes[node_idx].scale; auto& rotation = model->nodes[node_idx].rotation; if (translation.size() != 0) { object_transform.SetAt(0, 3, translation[0]); object_transform.SetAt(1, 3, translation[1]); object_transform.SetAt(2, 3, translation[2]); } if (scale.size() != 0) { } if (rotation.size() != 0) { } } // compute submesh offset by iterating over all meshes before the given mesh and summing up their primitive counts size_t submesh_offset = 0; for (int mesh_idx = 0; mesh_idx < model->nodes[node_idx].mesh; ++mesh_idx) { submesh_offset += model->meshes[mesh_idx].primitives.size(); } auto primitive_cnt = model->meshes[model->nodes[node_idx].mesh].primitives.size(); for (size_t primitive_idx = 0; primitive_idx < primitive_cnt; ++primitive_idx) { //auto const& sub_mesh = gpu_mesh_storage->getSubMeshData()[model->nodes[node_idx].mesh]; auto const& sub_mesh = gpu_mesh_storage->getSubMeshData()[submesh_offset + primitive_idx]; auto const& gpu_batch_mesh = gpu_mesh_storage->getMeshes()[sub_mesh.batch_index].mesh; auto const& shader = gpu_mtl_storage->getMaterials().front().shader_program; size_t rt_idx = rt_collection->addSingleRenderTask( shader, gpu_batch_mesh, sub_mesh.sub_mesh_draw_command, object_transform); m_rt_collection_indices.push_back(rt_idx); } } } // add some lights to the scene to test the per frame buffers struct LightParams { float x,y,z,intensity; }; // Place lights in icosahedron pattern float x = 0.525731112119133606f * 1000.0f; float z = 0.850650808352039932f * 1000.0f; std::vector<LightParams> lights = { {-x, 0.0f, z, 1.0f}, {x, 0.0f, z, 1.0f}, {-x, 0.0f, -z, 1.0f}, {x, 0.0f, -z, 1.0f}, {0.0f, z, x, 1.0f}, {0.0f, z, -x, 1.0f}, {0.0f, -z, x, 1.0f}, {0.0f, -z, -x, 1.0f}, {z, x, 0.0f, 1.0f}, {-z, x, 0.0f, 1.0f}, {z, -x, 0.0f, 1.0f}, {-z, -x, 0.0f, 1.0f} }; // Add a key light lights.push_back({-5000.0,5000.0,-5000.0,1000.0f}); rt_collection->addPerFrameDataBuffer(lights,1); } if (lhs_rtc->version() < m_version) { lhs_rtc->setData(rt_collection, m_version); } CallGPURenderTaskData* rhs_rtc = this->m_renderTask_rhs_slot.CallAs<CallGPURenderTaskData>(); if (rhs_rtc != NULL) { rhs_rtc->setData(rt_collection,0); (*rhs_rtc)(0); } return true; } bool megamol::mesh::GlTFRenderTasksDataSource::getMetaDataCallback(core::Call& caller) { AbstractGPURenderTaskDataSource::getMetaDataCallback(caller); auto gltf_call = m_glTF_callerSlot.CallAs<CallGlTFData>(); if (!(*gltf_call)(1)) return false; //auto gltf_meta_data = gltf_call->getMetaData(); return true; }
27.801047
118
0.649906
[ "mesh", "render", "vector", "model", "transform" ]