hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
f0c3c448ae36049015e4ee6600dd6f8106476b5c
3,980
cpp
C++
HamurEngine/Hamur/src/game/hamurObject.cpp
ttesla/hamur
02a31b4fec9bb3527289a38cdde842a93772be41
[ "MIT" ]
null
null
null
HamurEngine/Hamur/src/game/hamurObject.cpp
ttesla/hamur
02a31b4fec9bb3527289a38cdde842a93772be41
[ "MIT" ]
null
null
null
HamurEngine/Hamur/src/game/hamurObject.cpp
ttesla/hamur
02a31b4fec9bb3527289a38cdde842a93772be41
[ "MIT" ]
null
null
null
#include "hamurObject.h" #include "../hamurTextureManager.h" #include "../helper/hamurMath.h" #include "../helper/hamurLog.h" #include "../hamurDefinitions.h" #include "../helper/hamurColor.h" #include "hamurAnimation.h" namespace hamur { HamurObject::HamurObject(const string& name) :mName(name), mVisible(true), mActive(true), mRotation(0.0f), mTransparency(1.0f), mCurrentAnimation(NULL) { mPos.SetZero(); mScale.SetAll(1.0f); HAMURLOG->WriteLogln("Object created: " + mName); } HamurObject::HamurObject(const string& name, const string& spritePath) :mName(name), mVisible(true), mActive(true), mRotation(0.0f), mTransparency(1.0f), mCurrentAnimation(NULL) { mPos.SetZero(); mScale.SetAll(1.0f); SetSprite(spritePath); HAMURLOG->WriteLogln("Object created: " + mName + ", " + spritePath); } HamurObject::HamurObject(const string& name, const string& spritePath, const HamurColorRGB& colorkey) :mName(name), mVisible(true), mActive(true), mRotation(0.0f), mTransparency(1.0f), mCurrentAnimation(NULL) { mPos.SetZero(); mScale.SetAll(1.0f); SetSprite(spritePath, colorkey); HAMURLOG->WriteLogln("Object created: " + mName + ", " + spritePath); } HamurObject::~HamurObject() { mAnimations.clear(); HAMURLOG->WriteLogln("Object deleted: " + mName); } void HamurObject::Update() { // Update animation if(mCurrentAnimation) mCurrentAnimation->Update(); } void HamurObject::Draw() { HAMURTEXMR->BlitTexture(mSpriteID, mPos, mScale, mRotation, mTransparency); } void HamurObject::RotateDegree(float rotationAngle) { mRotation = rotationAngle; } void HamurObject::RotateRadian(float rotationRadian) { mRotation = HamurMath::Converter::RadianToDegree(rotationRadian); } // GETTERS & SETTERS string HamurObject::GetName() const { return mName; } HamurVec3 HamurObject::GetPosition() const { return mPos; } float HamurObject::GetRotation() const { return mRotation; } bool HamurObject::IsVisible() const { return mVisible; } bool HamurObject::IsActive() const { return mActive; } unsigned HamurObject::GetSpriteID() const { return mSpriteID; } float HamurObject::GetWidth() const { return mWidth;} float HamurObject::GetHeight() const { return mHeight;} void HamurObject::SetName(const string& name) { mName = name; } void HamurObject::SetWidth(float width) { mWidth = width; } void HamurObject::SetHeight(float height) { mHeight = height;} void HamurObject::SetPosition(const HamurVec3& pos) { mPos = pos; } void HamurObject::SetPosition(const HamurVec2& pos) { mPos.x = pos.x; mPos.y = pos.y; mPos.z = 0; } void HamurObject::SetPosition(float x, float y, float z) { mPos.x = x; mPos.y = y; mPos.z = z; } void HamurObject::SetVisible(bool visible) { mVisible = visible; } void HamurObject::SetActive(bool active) { mActive = active; } void HamurObject::SetSprite(const string& path) { mSpriteID = HAMURTEXMR->AddTexture(path); } void HamurObject::SetSprite(const string& path, const HamurColorRGB& colorkey) { mSpriteID = HAMURTEXMR->AddTexture(path, colorkey.R, colorkey.G, colorkey.B); } void HamurObject::SetSprite(const string& path, int redKey, int greenKey, int blueKey) { mSpriteID = HAMURTEXMR->AddTexture(path, redKey, greenKey, blueKey); } void HamurObject::ScaleSprite(const HamurVec2& scale) { mScale = scale; } void HamurObject::ScaleSprite(float scaleX, float scaleY) { mScale.x = scaleX; mScale.y = scaleY; } void HamurObject::ScaleSpriteUniform(float scale) { mScale.x = scale; mScale.y = scale; } void HamurObject::SetTransparency(float transparency) { mTransparency = transparency; } } // namespace hamur
25.512821
111
0.661558
ttesla
f0ca1e07c5a7a1fc9f53bccc831b79b8de6de891
827
hpp
C++
src/lib/sampling/sampler_primitives.hpp
idangerichter/CryptoWorkshop
c8d5e202fe3d02c85e58c8c01978db013a81eccd
[ "WTFPL" ]
null
null
null
src/lib/sampling/sampler_primitives.hpp
idangerichter/CryptoWorkshop
c8d5e202fe3d02c85e58c8c01978db013a81eccd
[ "WTFPL" ]
null
null
null
src/lib/sampling/sampler_primitives.hpp
idangerichter/CryptoWorkshop
c8d5e202fe3d02c85e58c8c01978db013a81eccd
[ "WTFPL" ]
null
null
null
#pragma once #include "sampler_primitive.hpp" //------------------------------------------------------------------------ // This file contains implementation of several useful sampler primitives. //------------------------------------------------------------------------ // Simple sampler primitive. Preparation is no-op. class SimpleSamplerPrimitive : public SamplerPrimitive { }; // Sampler primitive for flush-reload. Preparation is to flush the given index. class FlushSamplerPrimitive : public SamplerPrimitive { public: void Prepare(const MemoryWrapper& memory, size_t index) const override; }; // Sampler primitive for Prime-Probe. Preparation is to access the given index. class LoadSamplerPrimitive : public SamplerPrimitive { public: void Prepare(const MemoryWrapper& memory, size_t index) const override; };
31.807692
79
0.650544
idangerichter
f0cd3f7de6c7d5dd50a62402017a28cf814709dc
493
cpp
C++
lib/strmm.cpp
langou/latl
df838fb44a1ef5c77b57bf60bd46eaeff8db3492
[ "BSD-3-Clause-Open-MPI" ]
6
2015-12-13T09:10:11.000Z
2022-02-09T23:18:22.000Z
lib/strmm.cpp
langou/latl
df838fb44a1ef5c77b57bf60bd46eaeff8db3492
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
lib/strmm.cpp
langou/latl
df838fb44a1ef5c77b57bf60bd46eaeff8db3492
[ "BSD-3-Clause-Open-MPI" ]
2
2019-02-01T06:46:36.000Z
2022-02-09T23:18:24.000Z
// // strmm.cpp // Linear Algebra Template Library // // Created by Rodney James on 1/1/13. // Copyright (c) 2013 University of Colorado Denver. All rights reserved. // #include "blas.h" #include "trmm.h" using LATL::TRMM; int strmm_(char& side, char& uplo, char& trans, char& diag, int &m, int &n, float& alpha, float *A, int &ldA, float *B, int &ldB) { int info=-TRMM<float>(side,uplo,trans,diag,m,n,alpha,A,ldA,B,ldB); if(info!=0) xerbla_("STRMM ",info); return 0; }
22.409091
129
0.64503
langou
f0d689720d417ebda71d44526c4debbef0b702a6
1,922
cpp
C++
glhelper/utils/pathutils.cpp
Wumpf/glhelper
de4658f4918533dfac25acf99fc3e5802743210b
[ "MIT" ]
14
2015-01-18T21:13:21.000Z
2021-12-21T01:03:16.000Z
glhelper/utils/pathutils.cpp
Jojendersie/glhelper
7e59fcb09bb7332cf48c1831db1ff5f59de0af81
[ "MIT" ]
7
2015-06-15T19:09:13.000Z
2015-11-26T09:22:10.000Z
glhelper/utils/pathutils.cpp
Wumpf/glhelper
de4658f4918533dfac25acf99fc3e5802743210b
[ "MIT" ]
5
2015-06-15T13:22:18.000Z
2021-10-31T00:26:01.000Z
#include "pathutils.hpp" #include <glhelperconfig.hpp> namespace PathUtils { /// Concats to paths. std::string AppendPath(const std::string& _leftPath, const std::string& _rightPath) { return CanonicalizePath(_leftPath + "/" + _rightPath); } std::string CanonicalizePath(const std::string& _path) { std::string canonicalizedPath(_path); size_t searchResult = 0; while ((searchResult = canonicalizedPath.find('\\', searchResult)) != std::string::npos) { canonicalizedPath[searchResult] = '/'; } searchResult = 0; while ((searchResult = canonicalizedPath.find("//", searchResult)) != std::string::npos) { canonicalizedPath.erase(searchResult, 1); --searchResult; } searchResult = 1; while ((searchResult = canonicalizedPath.find("..", searchResult)) != std::string::npos) { if (searchResult > 2 && canonicalizedPath[searchResult - 1] == '/') { size_t slashBefore = searchResult - 2; for (; slashBefore > 0; --slashBefore) { if (canonicalizedPath[slashBefore-1] == '/') break; } --slashBefore; canonicalizedPath.erase(slashBefore, searchResult - slashBefore + 2); searchResult -= searchResult - slashBefore; } } return canonicalizedPath; } size_t GetFilenameStart(const std::string& _path) { GLHELPER_ASSERT(_path == CanonicalizePath(_path), "Given path was expected to be canonicalized: \'" + _path + "\'"); return _path.find_last_of('/'); } std::string GetFilename(const std::string& _path) { GLHELPER_ASSERT(_path == CanonicalizePath(_path), "Given path was expected to be canonicalized: \'" + _path + "\'"); return _path.substr(_path.find_last_of('/') + 1); } std::string GetDirectory(const std::string& _path) { GLHELPER_ASSERT(_path == CanonicalizePath(_path), "Given path was expected to be canonicalized: \'" + _path + "\'"); return _path.substr(0, _path.find_last_of('/')); } } // PathUtils
28.264706
118
0.676899
Wumpf
f0d7a552dab581c95d8235232326542d50d3acde
1,168
cpp
C++
Cpp_AcceleratedRT03/src/Lights/CuboidLight.cpp
afritz1/CppRayTracer
0b69c7713680e7d9540478a6d743908fe794bdba
[ "MIT" ]
1
2020-11-28T22:10:16.000Z
2020-11-28T22:10:16.000Z
Cpp_AcceleratedRT03/src/Lights/CuboidLight.cpp
afritz1/CppRayTracer
0b69c7713680e7d9540478a6d743908fe794bdba
[ "MIT" ]
null
null
null
Cpp_AcceleratedRT03/src/Lights/CuboidLight.cpp
afritz1/CppRayTracer
0b69c7713680e7d9540478a6d743908fe794bdba
[ "MIT" ]
null
null
null
#include "CuboidLight.h" #include "../Accelerators/BoundingBox.h" #include "../Intersections/Intersection.h" #include "../Materials/Flat.h" #include "../Materials/Material.h" #include "../Rays/Ray.h" CuboidLight::CuboidLight(const Vector3 &point) : CuboidLight(point, 0.5 + Utility::rand0To1(), 0.5 + Utility::rand0To1(), 0.5 + Utility::rand0To1(), Vector3::randomColor()) { } CuboidLight::CuboidLight(const Vector3 &point, double width, double height, double depth, const Vector3 &color) : Light(), Cuboid(point, width, height, depth, new Flat(color)) { } const Vector3 &CuboidLight::getCentroid() const { return Cuboid::getCentroid(); } BoundingBox CuboidLight::getBoundingBox() const { return Cuboid::getBoundingBox(); } const Material &CuboidLight::getMaterial() const { return Cuboid::getMaterial(); } Vector3 CuboidLight::randomPoint() const { return Vector3::randomPointInCuboid(this->getCentroid(), this->width, this->height, this->depth); } void CuboidLight::moveTo(const Vector3 &point) { Cuboid::moveTo(point); } Intersection CuboidLight::hit(const Ray &ray) const { return Cuboid::hit(ray); }
25.955556
90
0.700342
afritz1
f0eeac6b3152ddb0d56933f796865fd99b9053b6
221
cpp
C++
Workshop4-Inheritence/task4/rectangle.cpp
mathewsjoyy/c-Practise-Files
4367555c3f4aa2b2d084b57791eae853f47ad36c
[ "MIT" ]
null
null
null
Workshop4-Inheritence/task4/rectangle.cpp
mathewsjoyy/c-Practise-Files
4367555c3f4aa2b2d084b57791eae853f47ad36c
[ "MIT" ]
null
null
null
Workshop4-Inheritence/task4/rectangle.cpp
mathewsjoyy/c-Practise-Files
4367555c3f4aa2b2d084b57791eae853f47ad36c
[ "MIT" ]
null
null
null
#include "rectangle.h" double Rectangle::area() const { return width * height; } Rectangle Rectangle::operator+(const Rectangle& r) const { return Rectangle(this -> width + r.width, this -> height + r.height); }
22.1
73
0.683258
mathewsjoyy
e7c4039ff960d41dca343bf3dd3d2c2a439e95b9
35,271
cc
C++
src/Distributed/RedistributeNodes.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Distributed/RedistributeNodes.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Distributed/RedistributeNodes.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // RedistributeNodes -- An abstract base class for methods that repartition // the Spheral++ NodeLists among domains. // // Created by JMO, Tue Feb 4 14:23:11 PST 2003 //----------------------------------------------------------------------------// #include "RedistributeNodes.hh" #include "Utilities/DomainNode.hh" #include "DataBase/DataBase.hh" #include "NodeList/NodeList.hh" #include "Field/Field.hh" #include "Field/FieldList.hh" #include "Field/NodeIterators.hh" #include "Utilities/globalNodeIDs.hh" #include "Utilities/packElement.hh" #include "Neighbor/ConnectivityMap.hh" #include "Utilities/RedistributionRegistrar.hh" #include "Communicator.hh" #include "Utilities/DBC.hh" #include <mpi.h> #include <algorithm> #include <vector> #include <list> #include <sstream> using std::vector; using std::list; using std::string; using std::pair; using std::make_pair; using std::cout; using std::cerr; using std::endl; using std::min; using std::max; using std::abs; namespace Spheral { //------------------------------------------------------------------------------ // Default constructor //------------------------------------------------------------------------------ template<typename Dimension> RedistributeNodes<Dimension>:: RedistributeNodes(): mComputeWork(false) { } //------------------------------------------------------------------------------ // Destructor //------------------------------------------------------------------------------ template<typename Dimension> RedistributeNodes<Dimension>:: ~RedistributeNodes() { } //------------------------------------------------------------------------------ // Get the total number of nodes in the given DataBase. //------------------------------------------------------------------------------ template<typename Dimension> int RedistributeNodes<Dimension>:: numGlobalNodes(const DataBase<Dimension>& dataBase) const { typedef typename DataBase<Dimension>::ConstNodeListIterator ItrType; int result = 0; for (ItrType itr = dataBase.nodeListBegin(); itr < dataBase.nodeListEnd(); ++itr) { result += Spheral::numGlobalNodes(**itr); } return result; } //------------------------------------------------------------------------------ // Calculate the current domain decomposition, and return it as a set of // DomainNode identifiers. //------------------------------------------------------------------------------ template<typename Dimension> vector<DomainNode<Dimension> > RedistributeNodes<Dimension>:: currentDomainDecomposition(const DataBase<Dimension>& dataBase, const FieldList<Dimension, int>& globalNodeIDs) const { FieldList<Dimension, Scalar> dummyWork = dataBase.newGlobalFieldList(Scalar()); return currentDomainDecomposition(dataBase, globalNodeIDs, dummyWork); } //------------------------------------------------------------------------------ // Calculate the current domain decomposition, and return it as a set of // DomainNode identifiers. //------------------------------------------------------------------------------ template<typename Dimension> vector<DomainNode<Dimension> > RedistributeNodes<Dimension>:: currentDomainDecomposition(const DataBase<Dimension>& dataBase, const FieldList<Dimension, int>& globalNodeIDs, const FieldList<Dimension, Scalar>& workPerNode) const { // Pre-conditions. BEGIN_CONTRACT_SCOPE REQUIRE(dataBase.numNodeLists() == globalNodeIDs.numFields()); REQUIRE(dataBase.numNodeLists() == workPerNode.numFields()); for (typename FieldList<Dimension, int>::const_iterator itr = globalNodeIDs.begin(); itr != globalNodeIDs.end(); ++itr) REQUIRE(dataBase.haveNodeList((*itr)->nodeList())); for (typename FieldList<Dimension, Scalar>::const_iterator itr = workPerNode.begin(); itr != workPerNode.end(); ++itr) REQUIRE(dataBase.haveNodeList((*itr)->nodeList())); END_CONTRACT_SCOPE // Prepare the result. vector<DomainNode<Dimension> > result; // Loop over each NodeList in the DataBase. int nodeListID = 0; const int proc = domainID(); int offset = 0; for (typename DataBase<Dimension>::ConstNodeListIterator itr = dataBase.nodeListBegin(); itr != dataBase.nodeListEnd(); ++itr, ++nodeListID) { const NodeList<Dimension>& nodeList = **itr; const Field<Dimension, int>& globalNodeListIDs = **(globalNodeIDs.fieldForNodeList(nodeList)); const Field<Dimension, Scalar>& work = **(workPerNode.fieldForNodeList(nodeList)); // Loop over the nodes in the NodeList, and add their info to the // result. result.reserve(result.size() + nodeList.numInternalNodes()); for (auto localID = 0u; localID != nodeList.numInternalNodes(); ++localID) { result.push_back(DomainNode<Dimension>()); result.back().localNodeID = localID; result.back().uniqueLocalNodeID = localID + offset; result.back().globalNodeID = globalNodeListIDs(localID); result.back().nodeListID = nodeListID; result.back().domainID = proc; result.back().work = work(localID); result.back().position = nodeList.positions()(localID); } offset += nodeList.numInternalNodes(); } CHECK(nodeListID == (int)dataBase.numNodeLists()); ENSURE(validDomainDecomposition(result, dataBase)); return result; } //------------------------------------------------------------------------------ // Given a desired domain decomposition, reassign the nodes across domains and // create it! //------------------------------------------------------------------------------ template<typename Dimension> void RedistributeNodes<Dimension>:: enforceDomainDecomposition(const vector<DomainNode<Dimension> >& nodeDistribution, DataBase<Dimension>& dataBase) const { // Notify everyone before we start redistributing. RedistributionRegistrar::instance().preRedistributionNotifications(); REQUIRE(validDomainDecomposition(nodeDistribution, dataBase)); typedef typename DataBase<Dimension>::ConstNodeListIterator NodeListIterator; const int numNodeLists = dataBase.numNodeLists(); const int proc = domainID(); const int numProcs = numDomains(); // Post receives for how many nodes we're getting from each domain. vector< vector<int> > numRecvNodes; numRecvNodes.reserve(numProcs); for (int i = 0; i != numProcs; ++i) numRecvNodes.push_back(vector<int>(numNodeLists, 0)); CHECK((int)numRecvNodes.size() == numProcs); vector<MPI_Request> numRecvNodeRequests; numRecvNodeRequests.reserve(numProcs - 1); for (int recvProc = 0; recvProc != numProcs; ++recvProc) { CHECK(recvProc < (int)numRecvNodes.size()); if (recvProc != proc) { numRecvNodeRequests.push_back(MPI_Request()); MPI_Irecv(&(*numRecvNodes[recvProc].begin()), numNodeLists, MPI_INT, recvProc, 0, Communicator::communicator(), &(numRecvNodeRequests.back())); } } CHECK((int)numRecvNodeRequests.size() == numProcs - 1); // Find the nodes on this domain that have to be reassigned to new domains. vector< vector< vector<int> > > sendNodes(numProcs); // [sendDomain][nodeList][node] for (int i = 0; i != numProcs; ++i) sendNodes[i].resize(numNodeLists); for (typename vector<DomainNode<Dimension> >::const_iterator distItr = nodeDistribution.begin(); distItr != nodeDistribution.end(); ++distItr) { if (distItr->domainID != proc) { CHECK(distItr->domainID >= 0 && distItr->domainID < numProcs); CHECK(distItr->nodeListID < numNodeLists); CHECK(distItr->domainID < (int)sendNodes.size()); CHECK(distItr->nodeListID < (int)sendNodes[distItr->domainID].size()); sendNodes[distItr->domainID][distItr->nodeListID].push_back(distItr->localNodeID); } } // Tell everyone the number of nodes we're sending them. int numSendDomains = 0; list< vector<int> > numSendNodes; vector<MPI_Request> numSendNodeRequests; numSendNodeRequests.reserve(numProcs - 1); vector<int> totalNumSendNodes(numProcs, 0); for (int sendProc = 0; sendProc != numProcs; ++sendProc) { if (sendProc != proc) { numSendNodes.push_back(vector<int>()); vector<int>& x = numSendNodes.back(); x.reserve(numNodeLists); for (int nodeListID = 0; nodeListID != numNodeLists; ++nodeListID) { x.push_back(sendNodes[sendProc][nodeListID].size()); totalNumSendNodes[sendProc] += x.back(); } CHECK((int)x.size() == numNodeLists); numSendNodeRequests.push_back(MPI_Request()); MPI_Isend(&(*x.begin()), numNodeLists, MPI_INT, sendProc, 0, Communicator::communicator(), &(numSendNodeRequests.back())); if (totalNumSendNodes[sendProc] > 0) ++numSendDomains; } } CHECK((int)numSendNodes.size() == numProcs - 1) CHECK((int)numSendNodeRequests.size() == numProcs - 1); CHECK(numSendDomains <= numProcs - 1); CHECK(totalNumSendNodes[proc] == 0); // Pack up the field info for the nodes we're sending. vector< vector< list< vector<char> > > > sendBuffers(numProcs); for (int sendProc = 0; sendProc != numProcs; ++sendProc) { CHECK(sendProc < (int)sendBuffers.size()); sendBuffers[sendProc].resize(numNodeLists); int nodeListID = 0; for (NodeListIterator nodeListItr = dataBase.nodeListBegin(); nodeListItr != dataBase.nodeListEnd(); ++nodeListItr, ++nodeListID) { const NodeList<Dimension>& nodeList = **nodeListItr; CHECK(sendProc < (int)sendNodes.size()); CHECK(nodeListID < (int)sendNodes[sendProc].size()); const int numSendNodes = sendNodes[sendProc][nodeListID].size(); if (numSendNodes > 0) { CHECK(sendProc < (int)sendBuffers.size()); CHECK(nodeListID < (int)sendBuffers[sendProc].size()); sendBuffers[sendProc][nodeListID] = nodeList.packNodeFieldValues(sendNodes[sendProc][nodeListID]); } } CHECK(nodeListID == numNodeLists); } // Wait until we know who is sending us nodes. if (not numRecvNodeRequests.empty()) { vector<MPI_Status> recvStatus(numRecvNodeRequests.size()); MPI_Waitall(numRecvNodeRequests.size(), &(*numRecvNodeRequests.begin()), &(*recvStatus.begin())); } // Sum the total nodes we're receiving from each domain. int numRecvDomains = 0; vector<int> totalNumRecvNodes(numProcs, 0); for (int recvProc = 0; recvProc != numProcs; ++recvProc) { if (recvProc != proc) { CHECK(recvProc < (int)totalNumRecvNodes.size()); CHECK(recvProc < (int)numRecvNodes.size()); CHECK((int)numRecvNodes[recvProc].size() == numNodeLists); for (vector<int>::const_iterator itr = numRecvNodes[recvProc].begin(); itr != numRecvNodes[recvProc].end(); ++itr) totalNumRecvNodes[recvProc] += *itr; if (totalNumRecvNodes[recvProc] > 0) ++numRecvDomains; } } CHECK(numRecvDomains >= 0); CHECK(totalNumRecvNodes[proc] == 0); // Post receives for the sizes of the encoded field buffers we'll be receiving. int numRecvBuffers = 0; list< list< vector<int> > > recvBufferSizes; vector<MPI_Request> recvBufSizeRequests; recvBufSizeRequests.reserve(numRecvDomains*numNodeLists); for (int recvProc = 0; recvProc != numProcs; ++recvProc) { if (totalNumRecvNodes[recvProc] > 0) { recvBufferSizes.push_back(list< vector<int> >()); list< vector<int> >& x = recvBufferSizes.back(); int nodeListID = 0; for (NodeListIterator itr = dataBase.nodeListBegin(); itr != dataBase.nodeListEnd(); ++itr, ++nodeListID) { if (numRecvNodes[recvProc][nodeListID] > 0) { const int numFields = (*itr)->numFields(); x.push_back(vector<int>(numFields)); recvBufSizeRequests.push_back(MPI_Request()); MPI_Irecv(&(*x.back().begin()), numFields, MPI_INT, recvProc, 1 + nodeListID, Communicator::communicator(), &(recvBufSizeRequests.back())); numRecvBuffers += numFields; } } CHECK((int)x.size() <= numNodeLists); CHECK(nodeListID == numNodeLists); } } CHECK((int)recvBufferSizes.size() == numRecvDomains); CHECK((int)recvBufSizeRequests.size() <= numRecvDomains*numNodeLists); CHECK(numRecvBuffers >= numRecvDomains); // Send the sizes of the our encoded field buffers. int numSendBuffers = 0; list< list< vector<int> > > sendBufferSizes; vector<MPI_Request> sendBufSizeRequests; sendBufSizeRequests.reserve(numSendDomains*numNodeLists); for (int sendProc = 0; sendProc != numProcs; ++sendProc) { if (totalNumSendNodes[sendProc] > 0) { sendBufferSizes.push_back(list< vector<int> >()); list< vector<int> >& x = sendBufferSizes.back(); for (int nodeListID = 0; nodeListID != numNodeLists; ++nodeListID) { if (sendNodes[sendProc][nodeListID].size() > 0) { const list< vector<char> >& sendBufs = sendBuffers[sendProc][nodeListID]; x.push_back(vector<int>()); for (list< vector<char> >::const_iterator itr = sendBufs.begin(); itr != sendBufs.end(); ++itr) { x.back().push_back(itr->size()); } numSendBuffers += sendBufs.size(); CHECK(x.back().size() == sendBufs.size()); sendBufSizeRequests.push_back(MPI_Request()); MPI_Isend(&(*x.back().begin()), x.back().size(), MPI_INT, sendProc, 1 + nodeListID, Communicator::communicator(), &(sendBufSizeRequests.back())); } } CHECK((int)x.size() <= numNodeLists); } } CHECK((int)sendBufferSizes.size() == numSendDomains); CHECK((int)sendBufSizeRequests.size() <= numSendDomains*numNodeLists); CHECK(numSendBuffers >= numSendDomains); // Determine the maximum number of fields defined on a NodeList. int maxNumFields = 0; for (NodeListIterator nodeListItr = dataBase.nodeListBegin(); nodeListItr != dataBase.nodeListEnd(); ++nodeListItr) { maxNumFields = max(maxNumFields, (**nodeListItr).numFields()); // This is a somewhat expensive contract because of the all reduce, // but it is critical all processors agree about the fields defined // on each NodeList. BEGIN_CONTRACT_SCOPE { int localNumFields = (**nodeListItr).numFields(); int globalNumFields; MPI_Allreduce(&localNumFields, &globalNumFields, 1, MPI_INT, MPI_MAX, Communicator::communicator()); CHECK(localNumFields == globalNumFields); } END_CONTRACT_SCOPE } // Wait until we know the sizes of the encoded field buffers we're receiving. if (not recvBufSizeRequests.empty()) { vector<MPI_Status> recvStatus(recvBufSizeRequests.size()); MPI_Waitall(recvBufSizeRequests.size(), &(*recvBufSizeRequests.begin()), &(*recvStatus.begin())); } // Prepare to receive the encoded field buffers. list< list< list< vector<char> > > > fieldBuffers; list< list< vector<int> > >::const_iterator outerBufSizeItr = recvBufferSizes.begin(); vector<MPI_Request> recvBufferRequests; recvBufferRequests.reserve(numRecvBuffers); for (int recvProc = 0; recvProc != numProcs; ++recvProc) { if (totalNumRecvNodes[recvProc] > 0) { fieldBuffers.push_back(list< list< vector<char> > >()); CHECK(outerBufSizeItr != recvBufferSizes.end()); CHECK((int)outerBufSizeItr->size() <= numNodeLists); list< vector<int> >::const_iterator bufSizeItr = outerBufSizeItr->begin(); for (int nodeListID = 0; nodeListID != numNodeLists; ++nodeListID) { if (numRecvNodes[recvProc][nodeListID] > 0) { CHECK(bufSizeItr != outerBufSizeItr->end()); fieldBuffers.back().push_back(list< vector<char> >()); list< vector<char> >& bufs = fieldBuffers.back().back(); const vector<int>& bufSizes = *bufSizeItr; size_t i = 0; for (vector<int>::const_iterator itr = bufSizes.begin(); itr != bufSizes.end(); ++itr, ++i) { bufs.push_back(vector<char>(*itr)); recvBufferRequests.push_back(MPI_Request()); MPI_Irecv(&(*bufs.back().begin()), *itr, MPI_CHAR, recvProc, (2 + numNodeLists) + maxNumFields*nodeListID + i, Communicator::communicator(), &(recvBufferRequests.back())); } ++bufSizeItr; CHECK((int)i <= maxNumFields); } } CHECK(bufSizeItr == outerBufSizeItr->end()); ++outerBufSizeItr; } } CHECK((int)fieldBuffers.size() == numRecvDomains); CHECK(outerBufSizeItr == recvBufferSizes.end()); CHECK((int)recvBufferRequests.size() == numRecvBuffers); // Send our encoded buffers. vector<MPI_Request> sendBufferRequests; sendBufferRequests.reserve(numSendBuffers); for (int sendProc = 0; sendProc != numProcs; ++sendProc) { if (totalNumSendNodes[sendProc] > 0) { CHECK(sendProc < (int)sendBuffers.size()); CHECK((int)sendBuffers[sendProc].size() == numNodeLists); for (int nodeListID = 0; nodeListID != numNodeLists; ++nodeListID) { if (sendNodes[sendProc][nodeListID].size() > 0) { list< vector<char> >& bufs = sendBuffers[sendProc][nodeListID]; size_t i = 0; for (list< vector<char> >::iterator itr = bufs.begin(); itr != bufs.end(); ++itr, ++i) { vector<char>& buf = *itr; sendBufferRequests.push_back(MPI_Request()); MPI_Isend(&(*buf.begin()), buf.size(), MPI_CHAR, sendProc, (2 + numNodeLists) + maxNumFields*nodeListID + i, Communicator::communicator(), &(sendBufferRequests.back())); } CHECK((int)i <= maxNumFields); } } } } CHECK((int)sendBufferRequests.size() == numSendBuffers); // Wait until we've received the packed field buffers. if (not recvBufferRequests.empty()) { vector<MPI_Status> recvStatus(recvBufferRequests.size()); MPI_Waitall(recvBufferRequests.size(), &(*recvBufferRequests.begin()), &(*recvStatus.begin())); } // OK, now we're done with the communication part of this scheme. Next we need to // delete the nodes (and their associated Field elements) that we've transferred // to other domains. { int nodeListID = 0; for (NodeListIterator nodeListItr = dataBase.nodeListBegin(); nodeListItr != dataBase.nodeListEnd(); ++nodeListItr, ++nodeListID) { NodeList<Dimension>& nodeList = **nodeListItr; // Build the complete list of local IDs we're removing from this NodeList. // You have to do this, 'cause if you delete just some nodes from the // NodeList, then the remaining sendNode localIDs are not valid. vector<int> deleteNodes; for (int sendProc = 0; sendProc != numProcs; ++sendProc) { CHECK(sendProc < (int)sendNodes.size()); CHECK(nodeListID < (int)sendNodes[sendProc].size()); deleteNodes.reserve(deleteNodes.size() + sendNodes[sendProc][nodeListID].size()); for (vector<int>::const_iterator itr = sendNodes[sendProc][nodeListID].begin(); itr < sendNodes[sendProc][nodeListID].end(); ++itr) deleteNodes.push_back(*itr); } // Delete these nodes from the NodeList. nodeList.deleteNodes(deleteNodes); } CHECK(nodeListID == numNodeLists); } // Now unpack the new nodes and Field values. list< list< list< vector<char> > > >::const_iterator procBufItr = fieldBuffers.begin(); for (int recvProc = 0; recvProc != numProcs; ++recvProc) { CHECK(recvProc < (int)totalNumRecvNodes.size()); if (totalNumRecvNodes[recvProc] > 0) { CHECK(procBufItr != fieldBuffers.end()); int nodeListID = 0; list< list< vector<char> > >::const_iterator nodeListBufItr = procBufItr->begin(); for (NodeListIterator nodeListItr = dataBase.nodeListBegin(); nodeListItr != dataBase.nodeListEnd(); ++nodeListItr, ++nodeListID) { const int numNewNodes = numRecvNodes[recvProc][nodeListID]; if (numNewNodes > 0) { CHECK(nodeListBufItr != procBufItr->end()); const list< vector<char> >& bufs = *nodeListBufItr; (*nodeListItr)->appendInternalNodes(numNewNodes, bufs); (*nodeListItr)->neighbor().updateNodes(); ++nodeListBufItr; } } CHECK(nodeListBufItr == procBufItr->end()); ++procBufItr; } } CHECK(procBufItr == fieldBuffers.end()); // Wait until all our sends are completed. if (not numSendNodeRequests.empty()) { vector<MPI_Status> sendStatus(numSendNodeRequests.size()); MPI_Waitall(numSendNodeRequests.size(), &(*numSendNodeRequests.begin()), &(*sendStatus.begin())); } if (not sendBufSizeRequests.empty()) { vector<MPI_Status> sendStatus(sendBufSizeRequests.size()); MPI_Waitall(sendBufSizeRequests.size(), &(*sendBufSizeRequests.begin()), &(*sendStatus.begin())); } if (not sendBufferRequests.empty()) { vector<MPI_Status> sendStatus(sendBufferRequests.size()); MPI_Waitall(sendBufferRequests.size(), &(*sendBufferRequests.begin()), &(*sendStatus.begin())); } // Notify everyone that the nodes have just been shuffled around. RedistributionRegistrar::instance().broadcastRedistributionNotifications(); } //------------------------------------------------------------------------------ // Test that the given domain decomposition is valid (all nodes accounted // for, once and only once, etc.). //------------------------------------------------------------------------------ template<typename Dimension> bool RedistributeNodes<Dimension>:: validDomainDecomposition(const vector<DomainNode<Dimension> >& nodeDistribution, const DataBase<Dimension>& dataBase) const { // Parallel domain info. const int proc = domainID(); const int numProcs = numDomains(); // Data structure for checking the local node IDs. const int numNodeLists = dataBase.numNodeLists(); vector< vector<bool> > localIDtaken(numNodeLists); int nodeListID = 0; for (typename DataBase<Dimension>::ConstNodeListIterator nodeListItr = dataBase.nodeListBegin(); nodeListItr < dataBase.nodeListEnd(); ++nodeListItr, ++nodeListID) { CHECK(nodeListID >= 0 && nodeListID < (int)localIDtaken.size()); localIDtaken[nodeListID].resize((*nodeListItr)->numInternalNodes(), false); } // Get the maximum allowed value for global IDs. const int maxGlobalNodeID = numGlobalNodes(dataBase); // We'll build up a vector of just the global node ID assignments. vector<int> globalNodeIDs; globalNodeIDs.reserve(nodeDistribution.size()); // Go over every domain node assignment. bool valid = true; typename vector<DomainNode<Dimension> >::const_iterator nodeDistItr = nodeDistribution.begin(); while (nodeDistItr < nodeDistribution.end() && valid) { const DomainNode<Dimension>& domainNode = *nodeDistItr; const int localNodeID = domainNode.localNodeID; const int globalNodeID = domainNode.globalNodeID; const int nodeListID = domainNode.nodeListID; const int domain = domainNode.domainID; // Check that the nodeListID is sensible. if (!(nodeListID >= 0 && nodeListID < numNodeLists)) valid = false; CHECK(valid); // Check that this local ID is not already used. CHECK(nodeListID >= 0 && nodeListID < numNodeLists); CHECK(localNodeID >= 0 && localNodeID < (int)localIDtaken[nodeListID].size()); if (localIDtaken[nodeListID][localNodeID] == true) { valid = false; } else { localIDtaken[nodeListID][localNodeID] = true; } CHECK(valid); // Check if this global node ID is already allocated on this domain, // and insert it into the list of global node IDs for this domain. CHECK(globalNodeID >= 0 && globalNodeID < maxGlobalNodeID); valid = valid && globalNodeID >= 0 && globalNodeID < maxGlobalNodeID; CHECK(valid); if (count(globalNodeIDs.begin(), globalNodeIDs.end(), globalNodeID) > 0) valid = false; globalNodeIDs.push_back(globalNodeID); if (!valid) { cerr << globalNodeID << " : "; for (vector<int>::const_iterator itr = globalNodeIDs.begin(); itr < globalNodeIDs.end(); ++itr) cerr << *itr << " "; cerr << endl; } CHECK(valid); // Check that the assigned domain is valid. valid = valid && (domain >= 0 && domain < numProcs); CHECK(valid); ++nodeDistItr; } // Check that all local IDs are accounted for. for (vector< vector<bool> >::const_iterator itr = localIDtaken.begin(); itr < localIDtaken.end(); ++itr) { valid = valid && (count(itr->begin(), itr->end(), false) == 0); } CHECK(valid); // Have all processors agree if we're valid at this point. If not, go ahead // and exit. int iValid = 0; if (valid) iValid = 1; int globalValid; MPI_Allreduce(&iValid, &globalValid, 1, MPI_INT, MPI_MIN, Communicator::communicator()); if (globalValid == 0) { return false; } // Now for the really expensive check. Make sure that the global IDs // are unique across all processors. for (int checkProc = 0; checkProc < numProcs - 1; ++checkProc) { if (proc == checkProc) { // If we're the processor being checked, then send our list of global // Ids to each of the higher processors. int numNodes = globalNodeIDs.size(); for (int sendProc = checkProc + 1; sendProc < numProcs; ++sendProc) { MPI_Send(&numNodes, 1, MPI_INT, sendProc, 5, Communicator::communicator()); MPI_Send(&(*globalNodeIDs.begin()), numNodes, MPI_INT, sendProc, 6, Communicator::communicator()); } // Now wait for the responses from each higher processor. for (int recvProc = checkProc + 1; recvProc < numProcs; ++recvProc) { MPI_Status status; int iValid; MPI_Recv(&iValid, 1, MPI_INT, recvProc, 7, Communicator::communicator(), &status); valid = valid && iValid == 1; } CHECK(valid); } else if (proc > checkProc) { // If we're one of the processors greater than the processor being // checked, we'll receive the set of global nodes from the check // processor. MPI_Status status; int numCheckNodes; MPI_Recv(&numCheckNodes, 1, MPI_INT, checkProc, 5, Communicator::communicator(), &status); CHECK(numCheckNodes >= 0); vector<int> checkGlobalNodeIDs(numCheckNodes); MPI_Recv(&(*checkGlobalNodeIDs.begin()), numCheckNodes, MPI_INT, checkProc, 6, Communicator::communicator(), &status); // Check to see if any of the global IDs assigned to the processor // we're checking is also assigned to this one. vector<int>::const_iterator globalCheckItr = checkGlobalNodeIDs.begin(); while (globalCheckItr < checkGlobalNodeIDs.end() && valid) { valid = find(globalNodeIDs.begin(), globalNodeIDs.end(), *globalCheckItr) == globalNodeIDs.end(); ++globalCheckItr; } CHECK(valid); // Send the verdict back to the check processor. int iValid = 0; if (valid) iValid = 1; MPI_Send(&iValid, 1, MPI_INT, checkProc, 7, Communicator::communicator()); CHECK(valid); } // Now the check processor broadcasts the result of it's check back // to everyone. int iValid = 0; if (valid) iValid = 1; MPI_Bcast(&iValid, 1, MPI_INT, checkProc, Communicator::communicator()); if (iValid == 1) { valid = true; } else { valid = false; } // If we not valid, then finish and return false. if (!valid) return false; } // If we got all the way here, it must be valid. CHECK(valid); return valid; } //------------------------------------------------------------------------------ // Assign unique global integer IDs to each node on every domain in the given // DataBase. We assign globalIDs so that they are consecutive on a domain, // increasing with domain. // Note this is different than what the globalNodeIDs function produces only // because that one does unique IDs by NodeList. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Compute the work per node on the local processor. //------------------------------------------------------------------------------ template<typename Dimension> FieldList<Dimension, typename Dimension::Scalar> RedistributeNodes<Dimension>:: workPerNode(const DataBase<Dimension>& dataBase, const double /*Hextent*/) const { // Prepare the result. FieldList<Dimension, Scalar> result = dataBase.newGlobalFieldList(Scalar(), "work per node"); // We have two choices for the work: we can use the estimate computed during // the last integration step, or simply use the number of neighbors. if (mComputeWork) { // The work per node is just the number of neighbors. dataBase.updateConnectivityMap(false, false, false); const ConnectivityMap<Dimension>& connectivityMap = dataBase.connectivityMap(); const vector<const NodeList<Dimension>*>& nodeLists = connectivityMap.nodeLists(); for (auto iNodeList = 0u; iNodeList != nodeLists.size(); ++iNodeList) { const NodeList<Dimension>* nodeListPtr = nodeLists[iNodeList]; for (auto i = 0u; i != nodeListPtr->numInternalNodes(); ++i) { result(iNodeList, i) = connectivityMap.numNeighborsForNode(nodeListPtr, i); } } } else { // Use the work estimate from the last integration cycle. result = dataBase.globalWork(); } // We don't allow zeros for work, so if there are any reset them to be the minimum // work for a node in the NodeList in question. const double globalMax = result.max(); if (globalMax == 0.0) { result = 1.0; } else { for (auto iNodeList = 0u; iNodeList != result.size(); ++iNodeList) { Field<Dimension, Scalar>& worki = *(result[iNodeList]); if (worki.max() == 0.0) { worki = globalMax; } else { if (worki.min() == 0.0) { double localMin = std::numeric_limits<double>::max(); for (auto i = 0u; i != worki.numInternalElements(); ++i) { if (worki(i) > 0.0) localMin = std::min(localMin, worki(i)); } double globalMin; MPI_Allreduce(&localMin, &globalMin, 1, MPI_DOUBLE, MPI_MIN, Communicator::communicator()); worki.applyMin(globalMin); } } } } // Output some statistics. const Scalar minWeight = result.min(); const Scalar maxWeight = result.max(); if (Process::getRank() == 0) cerr << "RedistributeNodes::workPerNode: min/max work : " << minWeight << " " << maxWeight << endl; // Return the result. return result; } //------------------------------------------------------------------------------ // Pack a vector<DomainNode> into vector<char>. //------------------------------------------------------------------------------ template<typename Dimension> vector<char> RedistributeNodes<Dimension>:: packDomainNodes(const vector<DomainNode<Dimension> >& domainNodes) const { vector<char> result; const int bufsize = (4*sizeof(int) + Dimension::nDim*sizeof(double))*domainNodes.size(); result.reserve(bufsize); for (typename vector<DomainNode<Dimension> >::const_iterator domainNodeItr = domainNodes.begin(); domainNodeItr != domainNodes.end(); ++domainNodeItr) { packElement(domainNodeItr->localNodeID, result); packElement(domainNodeItr->globalNodeID, result); packElement(domainNodeItr->nodeListID, result); packElement(domainNodeItr->domainID, result); for (int i = 0; i != Dimension::nDim; ++i) packElement(domainNodeItr->position(i), result); } ENSURE((int)result.size() == bufsize); return result; } //------------------------------------------------------------------------------ // Unpack a vector<char> to a vector<DomainNode>. //------------------------------------------------------------------------------ template<typename Dimension> vector<DomainNode<Dimension> > RedistributeNodes<Dimension>:: unpackDomainNodes(const vector<char>& packedDomainNodes) const { const int sizeOfDomainNode = 4*sizeof(int) + Dimension::nDim*sizeof(double); const int size = packedDomainNodes.size()/sizeOfDomainNode; CHECK(packedDomainNodes.size() - size*sizeOfDomainNode == 0); vector<DomainNode<Dimension> > result; result.reserve(size); vector<char>::const_iterator itr = packedDomainNodes.begin(); const vector<char>::const_iterator endItr = packedDomainNodes.end(); while (itr < packedDomainNodes.end()) { result.push_back(DomainNode<Dimension>()); unpackElement(result.back().localNodeID, itr, endItr); unpackElement(result.back().globalNodeID, itr, endItr); unpackElement(result.back().nodeListID, itr, endItr); unpackElement(result.back().domainID, itr, endItr); for (int i = 0; i < Dimension::nDim; ++i) unpackElement(result.back().position(i), itr, endItr); } ENSURE(itr == packedDomainNodes.end()); return result; } //------------------------------------------------------------------------------ // Gather statistics about the work distribution, returning a string with the // result. //------------------------------------------------------------------------------ template<typename Dimension> string RedistributeNodes<Dimension>:: gatherDomainDistributionStatistics(const FieldList<Dimension, typename Dimension::Scalar>& work) const { // Each domain computes it's total work and number of nodes. int localNumNodes = 0; Scalar localWork = 0.0; for (InternalNodeIterator<Dimension> nodeItr = work.internalNodeBegin(); nodeItr != work.internalNodeEnd(); ++nodeItr) { ++localNumNodes; localWork += work(nodeItr); } // Now gather up some statistics about the distribution. const int numProcs = this->numDomains(); CHECK(numProcs > 0); int globalMinNodes, globalMaxNodes, globalAvgNodes; MPI_Allreduce(&localNumNodes, &globalMinNodes, 1, MPI_INT, MPI_MIN, Communicator::communicator()); MPI_Allreduce(&localNumNodes, &globalMaxNodes, 1, MPI_INT, MPI_MAX, Communicator::communicator()); MPI_Allreduce(&localNumNodes, &globalAvgNodes, 1, MPI_INT, MPI_SUM, Communicator::communicator()); globalAvgNodes /= numProcs; Scalar globalMinWork, globalMaxWork, globalAvgWork; MPI_Allreduce(&localWork, &globalMinWork, 1, MPI_DOUBLE, MPI_MIN, Communicator::communicator()); MPI_Allreduce(&localWork, &globalMaxWork, 1, MPI_DOUBLE, MPI_MAX, Communicator::communicator()); MPI_Allreduce(&localWork, &globalAvgWork, 1, MPI_DOUBLE, MPI_SUM, Communicator::communicator()); globalAvgWork /= numProcs; // Build a string with the result. std::stringstream result; result << " (min, max, avg) nodes per domain: (" << globalMinNodes << ", " << globalMaxNodes << ", " << globalAvgNodes << ")" << endl << " (min, max, avg) work per domain : (" << globalMinWork << ", " << globalMaxWork << ", " << globalAvgWork << ")" << std::endl; return result.str(); } }
41.59316
183
0.631454
jmikeowen
e7c62bd17fb0219b69e0cea3be5ff7e18e9587a9
4,630
cpp
C++
src/CPluginWeatherSystem.cpp
omggomb/Plugin_WeatherSystem
c616ebb42101f8aacc2abae4f45c50918baf281b
[ "BSD-2-Clause" ]
4
2016-03-16T21:16:47.000Z
2021-04-13T22:22:47.000Z
src/CPluginWeatherSystem.cpp
omggomb/Plugin_WeatherSystem
c616ebb42101f8aacc2abae4f45c50918baf281b
[ "BSD-2-Clause" ]
1
2017-11-12T21:09:21.000Z
2017-12-16T06:18:46.000Z
src/CPluginWeatherSystem.cpp
omggomb/Plugin_WeatherSystem
c616ebb42101f8aacc2abae4f45c50918baf281b
[ "BSD-2-Clause" ]
2
2019-03-07T21:11:08.000Z
2021-04-13T22:22:50.000Z
/* WeatherSystem_Plugin - for licensing and copyright see license.txt */ #include <StdAfx.h> #include "CPluginWeatherSystem.h" namespace WeatherSystemPlugin { CPluginWeatherSystem *gPlugin = NULL; CPluginWeatherSystem::CPluginWeatherSystem() { gPlugin = this; m_pWeatherSystem = new CWeatherSystem(); } CPluginWeatherSystem::~CPluginWeatherSystem() { Release(true); gPlugin = NULL; } bool CPluginWeatherSystem::Release(bool bForce) { bool bRet = true; bool bWasInitialized = m_bIsFullyInitialized; // Will be reset by base class so backup if (!m_bCanUnload) { // Note: Type Unregistration will be automatically done by the Base class (Through RegisterTypes) // Should be called while Game is still active otherwise there might be leaks/problems bRet = CPluginBase::Release(bForce); if (bRet) { if (bWasInitialized) { // TODO: Cleanup stuff that can only be cleaned up if the plugin was initialized } // Cleanup like this always (since the class is static its cleaned up when the dll is unloaded) gPluginManager->UnloadPlugin(GetName()); // Allow Plugin Manager garbage collector to unload this plugin AllowDllUnload(); } } return bRet; }; bool CPluginWeatherSystem::Init(SSystemGlobalEnvironment &env, SSystemInitParams &startupParams, IPluginBase *pPluginManager, const char *sPluginDirectory) { gPluginManager = (PluginManager::IPluginManager *)pPluginManager->GetConcreteInterface(NULL); CPluginBase::Init(env, startupParams, pPluginManager, sPluginDirectory); gEnv->pSystem->GetISystemEventDispatcher()->RegisterListener(this); return true; } bool CPluginWeatherSystem::RegisterTypes(int nFactoryType, bool bUnregister) { // Note: Autoregister Flownodes will be automatically registered by the Base class bool bRet = CPluginBase::RegisterTypes(nFactoryType, bUnregister); using namespace PluginManager; eFactoryType enFactoryType = eFactoryType(nFactoryType); if (bRet) { if (gEnv && gEnv->pSystem && !gEnv->pSystem->IsQuitting()) { // UIEvents if (gEnv->pConsole && (enFactoryType == FT_All || enFactoryType == FT_UIEvent)) { if (!bUnregister) { // TODO: Register CVars here if you have some // ... } else { // TODO: Unregister CVars here if you have some // ... } } // CVars if (gEnv->pConsole && (enFactoryType == FT_All || enFactoryType == FT_CVar)) { if (!bUnregister) { // TODO: Register CVars here if you have some // ... } else { // TODO: Unregister CVars here if you have some // ... } } // CVars Commands if (gEnv->pConsole && (enFactoryType == FT_All || enFactoryType == FT_CVarCommand)) { if (!bUnregister) { // TODO: Register CVar Commands here if you have some // ... } else { // TODO: Unregister CVar Commands here if you have some // ... } } // Game Objects if (gEnv->pGame && gEnv->pGame->GetIGameFramework() && (enFactoryType == FT_All || enFactoryType == FT_GameObjectExtension)) { if (!bUnregister) { // TODO: Register Game Object Extensions here if you have some // ... } } if (enFactoryType == FT_Flownode) { } } } return bRet; } const char *CPluginWeatherSystem::ListCVars() const { return "..."; // TODO: Enter CVARs/Commands here if you have some } const char *CPluginWeatherSystem::GetStatus() const { return "OK"; } int CPluginWeatherSystem::GetInitializationMode() const { return int(PluginManager::IM_Default); }; const char *CPluginWeatherSystem::GetVersion() const { return "0.1"; }; const char *CPluginWeatherSystem::GetName() const { return PLUGIN_NAME; }; const char *CPluginWeatherSystem::GetCategory() const { return "Visual"; }; const char *CPluginWeatherSystem::ListAuthors() const { return "omggomb <omggomb at gmx dot net>"; }; const char *CPluginWeatherSystem::GetCurrentConcreteInterfaceVersion() const { return "1.0"; }; void *CPluginWeatherSystem::GetConcreteInterface(const char *sInterfaceVersion) { return static_cast <IPluginWeatherSystem *>(this); }; // IPluginWeatherSystem CPluginWeatherSystem::IPluginBase *CPluginWeatherSystem::GetBase() { return static_cast<IPluginBase *>(this); }; void CPluginWeatherSystem::OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) { if (event == ESystemEvent::ESYSTEM_EVENT_GAME_POST_INIT) { if (!m_pWeatherSystem->Init()) { WEATHERSSYSTEM_ERROR("Failed to initialize weather system!"); SAFE_DELETE(m_pWeatherSystem); } } } // TODO: Add your plugin concrete interface implementation }
22.259615
155
0.700864
omggomb
e7c926cadff767d9424c88a77fecbb729ce4dfd4
551
cpp
C++
impl/gui/sdl/src/gui_sdl.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
50
2015-01-15T10:00:31.000Z
2022-02-04T20:45:25.000Z
impl/gui/sdl/src/gui_sdl.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
88
2020-03-15T17:40:04.000Z
2022-03-15T08:21:44.000Z
impl/gui/sdl/src/gui_sdl.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
19
2017-03-11T04:32:01.000Z
2022-01-12T22:47:12.000Z
#include "lxgui/impl/gui_sdl.hpp" #include <lxgui/impl/input_sdl_source.hpp> #include <lxgui/gui_manager.hpp> namespace lxgui { namespace gui { namespace sdl { utils::owner_ptr<gui::manager> create_manager(SDL_Window* pWindow, SDL_Renderer* pRenderer, bool bInitialiseSDLImage) { return utils::make_owned<gui::manager>( std::unique_ptr<input::source>(new input::sdl::source(pWindow, pRenderer, bInitialiseSDLImage)), std::unique_ptr<gui::renderer>(new gui::sdl::renderer(pRenderer, false)) ); } } } }
26.238095
105
0.700544
cschreib
e7d8d85e290d7bf18b8c1a9aaa17ad2d8fb5ab8d
567
cpp
C++
arrays&string/question9.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
arrays&string/question9.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
arrays&string/question9.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
//question 9 CTCI arrays & strings #include<bits/stdc++.h> //is s2 a rotation of s1? //best way is to check if s2 is subset if s1s1 bool isRotation(std::string s1, std::string s2){ int len = s1.length(); /*check if length of s1 and s2 aer same or not */ if(len = s2.length() && len >0){ std::string s1s1 = s1 + s1; if ( s1s1.find(s2) != std::string::npos ) { return true; } } return false; } int main(){ std::string s1 ="hello"; std::string s2 ="lohel"; std::cout <<std::boolalpha<<isRotation(s2,s1); return 0; }
23.625
53
0.592593
kgajwan1
e7d9dac005ed735e751f3f9027de9281fcf03156
29,676
cpp
C++
server/lineardb.cpp
Valaras/OneLife
0f83ffb8edf8362ff3bf0ca87a73bba21be20446
[ "Linux-OpenIB" ]
69
2018-10-05T23:29:10.000Z
2022-03-29T22:34:24.000Z
server/lineardb.cpp
Valaras/OneLife
0f83ffb8edf8362ff3bf0ca87a73bba21be20446
[ "Linux-OpenIB" ]
62
2018-11-08T14:14:40.000Z
2022-03-01T20:38:01.000Z
server/lineardb.cpp
Valaras/OneLife
0f83ffb8edf8362ff3bf0ca87a73bba21be20446
[ "Linux-OpenIB" ]
24
2018-10-11T09:20:27.000Z
2021-11-06T19:23:17.000Z
#define _FILE_OFFSET_BITS 64 #include "lineardb.h" #include <string.h> #include <stdlib.h> #include <math.h> #ifdef _WIN32 #define fseeko fseeko64 #define ftello ftello64 #endif #define DEFAULT_MAX_LOAD 0.5 #include "murmurhash2_64.cpp" /* // djb2 hash function static uint64_t djb2( const void *inB, unsigned int inLen ) { uint64_t hash = 5381; for( unsigned int i=0; i<inLen; i++ ) { hash = ((hash << 5) + hash) + (uint64_t)(((const uint8_t *)inB)[i]); } return hash; } */ // function used here must have the following signature: // static uint64_t LINEARDB_hash( const void *inB, unsigned int inLen ); // murmur2 seems to have equal performance on real world data // and it just feels safer than djb2, which must have done well on test // data for a weird reson #define LINEARDB_hash(inB, inLen) MurmurHash64( inB, inLen, 0xb9115a39 ) // djb2 is resulting in way fewer collisions in test data //#define LINEARDB_hash(inB, inLen) djb2( inB, inLen ) /* // computes 8-bit hashing using different method from LINEARDB_hash static uint8_t byteHash( const void *inB, unsigned int inLen ) { // use different seed uint64_t bigHash = MurmurHash64( inB, inLen, 0x202a025d ); // xor all 8 bytes together uint8_t smallHash = bigHash & 0xFF; smallHash = smallHash ^ ( ( bigHash >> 8 ) & 0xFF ); smallHash = smallHash ^ ( ( bigHash >> 16 ) & 0xFF ); smallHash = smallHash ^ ( ( bigHash >> 24 ) & 0xFF ); smallHash = smallHash ^ ( ( bigHash >> 32 ) & 0xFF ); smallHash = smallHash ^ ( ( bigHash >> 40 ) & 0xFF ); smallHash = smallHash ^ ( ( bigHash >> 48 ) & 0xFF ); smallHash = smallHash ^ ( ( bigHash >> 56 ) & 0xFF ); return smallHash; } */ // computes 16-bit hashing using different method from LINEARDB_hash static uint16_t shortHash( const void *inB, unsigned int inLen ) { // use different seed uint64_t bigHash = MurmurHash64( inB, inLen, 0x202a025d ); // xor all 2-byte chunks together uint16_t smallHash = bigHash & 0xFFFF; smallHash = smallHash ^ ( ( bigHash >> 16 ) & 0xFFFF ); smallHash = smallHash ^ ( ( bigHash >> 32 ) & 0xFFFF ); smallHash = smallHash ^ ( ( bigHash >> 48 ) & 0xFFFF ); return smallHash; } static const char *magicString = "Ldb"; // Ldb magic characters plus // four 32-bit ints #define LINEARDB_HEADER_SIZE 19 static unsigned int getExistenceMapSize( unsigned int inHashTableSizeA ) { return ( ( inHashTableSizeA * 2 ) / 8 ) + 1; } static void recreateMaps( LINEARDB *inDB, unsigned int inOldTableSizeA = 0 ) { uint8_t *oldExistenceMap = inDB->existenceMap; inDB->existenceMap = new uint8_t[ getExistenceMapSize( inDB->hashTableSizeA ) ]; memset( inDB->existenceMap, 0, getExistenceMapSize( inDB->hashTableSizeA ) ); if( oldExistenceMap != NULL ) { if( inOldTableSizeA > 0 ) { memcpy( inDB->existenceMap, oldExistenceMap, getExistenceMapSize( inOldTableSizeA ) * sizeof( uint8_t ) ); } delete [] oldExistenceMap; } uint16_t *oldFingerprintMap = inDB->fingerprintMap; inDB->fingerprintMap = new uint16_t[ inDB->hashTableSizeA * 2 ]; memset( inDB->fingerprintMap, 0, inDB->hashTableSizeA * 2 * sizeof( uint16_t ) ); if( oldFingerprintMap != NULL ) { if( inOldTableSizeA > 0 ) { memcpy( inDB->fingerprintMap, oldFingerprintMap, inOldTableSizeA * 2 * sizeof( uint16_t ) ); } delete [] oldFingerprintMap; } } static char exists( LINEARDB *inDB, uint64_t inBinNumber ) { return ( inDB->existenceMap[ inBinNumber / 8 ] >> ( inBinNumber % 8 ) ) & 0x01; } static void setExists( LINEARDB *inDB, uint64_t inBinNumber ) { uint8_t presentFlag = 1 << ( inBinNumber % 8 ); inDB->existenceMap[ inBinNumber / 8 ] |= presentFlag; } static void setNotExists( LINEARDB *inDB, uint64_t inBinNumber ) { // bitwise inversion uint8_t presentFlag = ~( 1 << ( inBinNumber % 8 ) ); inDB->existenceMap[ inBinNumber / 8 ] &= presentFlag; } static uint64_t getBinLoc( LINEARDB *inDB, uint64_t inBinNumber ) { return inBinNumber * inDB->recordSizeBytes + LINEARDB_HEADER_SIZE; } // returns 0 on success, -1 on error static int writeHeader( LINEARDB *inDB ) { if( fseeko( inDB->file, 0, SEEK_SET ) ) { return -1; } int numWritten; numWritten = fwrite( magicString, strlen( magicString ), 1, inDB->file ); if( numWritten != 1 ) { return -1; } uint32_t val32; val32 = inDB->hashTableSizeA; numWritten = fwrite( &val32, sizeof(uint32_t), 1, inDB->file ); if( numWritten != 1 ) { return -1; } val32 = inDB->hashTableSizeB; numWritten = fwrite( &val32, sizeof(uint32_t), 1, inDB->file ); if( numWritten != 1 ) { return -1; } val32 = inDB->keySize; numWritten = fwrite( &val32, sizeof(uint32_t), 1, inDB->file ); if( numWritten != 1 ) { return -1; } val32 = inDB->valueSize; numWritten = fwrite( &val32, sizeof(uint32_t), 1, inDB->file ); if( numWritten != 1 ) { return -1; } return 0; } int LINEARDB_open( LINEARDB *inDB, const char *inPath, int inMode, unsigned int inHashTableStartSize, unsigned int inKeySize, unsigned int inValueSize ) { inDB->recordBuffer = NULL; inDB->existenceMap = NULL; inDB->fingerprintMap = NULL; inDB->maxProbeDepth = 0; inDB->numRecords = 0; inDB->maxLoad = DEFAULT_MAX_LOAD; if( inPath != NULL ) { inDB->file = fopen( inPath, "r+b" ); if( inDB->file == NULL ) { // doesn't exist yet inDB->file = fopen( inPath, "w+b" ); } if( inDB->file == NULL ) { return 1; } } // else file already set by forceFile inDB->hashTableSizeA = inHashTableStartSize; inDB->hashTableSizeB = inHashTableStartSize; inDB->keySize = inKeySize; inDB->valueSize = inValueSize; // first byte in record is present flag inDB->recordSizeBytes = 1 + inKeySize + inValueSize; inDB->recordBuffer = new uint8_t[ inDB->recordSizeBytes ]; // does the file already contain a header // seek to the end to find out file size if( fseeko( inDB->file, 0, SEEK_END ) ) { fclose( inDB->file ); inDB->file = NULL; return 1; } if( inPath == NULL || ftello( inDB->file ) < LINEARDB_HEADER_SIZE ) { // file that doesn't even contain the header // or it's a forced file (which is forced to be empty) // write fresh header and hash table // rewrite header if( writeHeader( inDB ) != 0 ) { fclose( inDB->file ); inDB->file = NULL; return 1; } inDB->tableSizeBytes = (uint64_t)( inDB->recordSizeBytes ) * (uint64_t)( inDB->hashTableSizeB ); // now write empty hash table, full of 0 values unsigned char buff[ 4096 ]; memset( buff, 0, 4096 ); uint64_t i = 0; if( inDB->tableSizeBytes > 4096 ) { for( i=0; i < inDB->tableSizeBytes-4096; i += 4096 ) { int numWritten = fwrite( buff, 4096, 1, inDB->file ); if( numWritten != 1 ) { fclose( inDB->file ); inDB->file = NULL; return 1; } } } if( i < inDB->tableSizeBytes ) { // last partial buffer int numWritten = fwrite( buff, inDB->tableSizeBytes - i, 1, inDB->file ); if( numWritten != 1 ) { fclose( inDB->file ); inDB->file = NULL; return 1; } } // empty existence and fingerprint map recreateMaps( inDB ); } else { // read header if( fseeko( inDB->file, 0, SEEK_SET ) ) { fclose( inDB->file ); inDB->file = NULL; return 1; } int numRead; char magicBuffer[ 4 ]; numRead = fread( magicBuffer, 3, 1, inDB->file ); if( numRead != 1 ) { fclose( inDB->file ); inDB->file = NULL; return 1; } magicBuffer[3] = '\0'; if( strcmp( magicBuffer, magicString ) != 0 ) { printf( "lineardb magic string '%s' not found at start of " "file header\n", magicString ); fclose( inDB->file ); inDB->file = NULL; return 1; } uint32_t val32; numRead = fread( &val32, sizeof(uint32_t), 1, inDB->file ); if( numRead != 1 ) { fclose( inDB->file ); inDB->file = NULL; return 1; } // can vary in size from what's been requested inDB->hashTableSizeA = val32; // now read sizeB numRead = fread( &val32, sizeof(uint32_t), 1, inDB->file ); if( numRead != 1 ) { fclose( inDB->file ); inDB->file = NULL; return 1; } if( val32 < inDB->hashTableSizeA ) { printf( "lineardb hash table base size of %u is larger than " "expanded size of %u in file header\n", inDB->hashTableSizeA, val32 ); fclose( inDB->file ); inDB->file = NULL; return 1; } if( val32 >= inDB->hashTableSizeA * 2 ) { printf( "lineardb hash table expanded size of %u is 2x or more " "larger than base size of %u in file header\n", val32, inDB->hashTableSizeA ); fclose( inDB->file ); inDB->file = NULL; return 1; } // can vary in size from what's been requested inDB->hashTableSizeB = val32; numRead = fread( &val32, sizeof(uint32_t), 1, inDB->file ); if( numRead != 1 ) { fclose( inDB->file ); inDB->file = NULL; return 1; } if( val32 != inKeySize ) { printf( "Requested lineardb key size of %u does not match " "size of %u in file header\n", inKeySize, val32 ); fclose( inDB->file ); inDB->file = NULL; return 1; } numRead = fread( &val32, sizeof(uint32_t), 1, inDB->file ); if( numRead != 1 ) { fclose( inDB->file ); inDB->file = NULL; return 1; } if( val32 != inValueSize ) { printf( "Requested lineardb value size of %u does not match " "size of %u in file header\n", inValueSize, val32 ); fclose( inDB->file ); inDB->file = NULL; return 1; } // got here, header matches inDB->tableSizeBytes = (uint64_t)( inDB->recordSizeBytes ) * (uint64_t)( inDB->hashTableSizeB ); // make sure hash table exists in file if( fseeko( inDB->file, 0, SEEK_END ) ) { fclose( inDB->file ); inDB->file = NULL; return 1; } if( ftello( inDB->file ) < (int64_t)( LINEARDB_HEADER_SIZE + inDB->tableSizeBytes ) ) { printf( "lineardb file contains correct header but is missing " "hash table.\n" ); fclose( inDB->file ); inDB->file = NULL; return 1; } recreateMaps( inDB ); // now populate existence map and fingerprint map if( fseeko( inDB->file, LINEARDB_HEADER_SIZE, SEEK_SET ) ) { fclose( inDB->file ); inDB->file = NULL; return 1; } for( unsigned int i=0; i<inDB->hashTableSizeB; i++ ) { if( fseeko( inDB->file, LINEARDB_HEADER_SIZE + i * inDB->recordSizeBytes, SEEK_SET ) ) { fclose( inDB->file ); inDB->file = NULL; return 1; } char present = 0; int numRead = fread( &present, 1, 1, inDB->file ); if( numRead != 1 ) { printf( "Failed to scan hash table from lineardb file\n" ); fclose( inDB->file ); inDB->file = NULL; return 1; } if( present ) { inDB->numRecords ++; setExists( inDB, i ); // now read key numRead = fread( inDB->recordBuffer, inDB->keySize, 1, inDB->file ); if( numRead != 1 ) { printf( "Failed to scan hash table from lineardb file\n" ); fclose( inDB->file ); inDB->file = NULL; return 1; } inDB->fingerprintMap[ i ] = shortHash( inDB->recordBuffer, inDB->keySize ); } } } return 0; } void LINEARDB_close( LINEARDB *inDB ) { if( inDB->recordBuffer != NULL ) { delete [] inDB->recordBuffer; inDB->recordBuffer = NULL; } if( inDB->existenceMap != NULL ) { delete [] inDB->existenceMap; inDB->existenceMap = NULL; } if( inDB->fingerprintMap != NULL ) { delete [] inDB->fingerprintMap; inDB->fingerprintMap = NULL; } if( inDB->file != NULL ) { fclose( inDB->file ); inDB->file = NULL; } } void LINEARDB_setMaxLoad( LINEARDB *inDB, double inMaxLoad ) { inDB->maxLoad = inMaxLoad; } inline char keyComp( int inKeySize, const void *inKeyA, const void *inKeyB ) { uint8_t *a = (uint8_t*)inKeyA; uint8_t *b = (uint8_t*)inKeyB; for( int i=0; i<inKeySize; i++ ) { if( a[i] != b[i] ) { return false; } } return true; } // removes a coniguous segment of cells from the table, one by one, // from left to right, // starting at inFirstBinNumber, and reinserts them // examines at least inMinCellCount cells, but maybe more, if there // is a long run with no empty spots // returns 0 on success, -1 on failure static int reinsertCellSegment( LINEARDB *inDB, uint64_t inFirstBinNumber, uint64_t inMinCellCount ) { uint64_t c = inFirstBinNumber; // don't infinite loop if table is 100% full uint64_t numCellsTouched = 0; while( numCellsTouched < inDB->hashTableSizeB && ( numCellsTouched < inMinCellCount || exists( inDB, c ) ) ) { if( exists( inDB, c ) ) { // a full cell is here uint64_t binLoc = getBinLoc( inDB, c ); if( fseeko( inDB->file, binLoc, SEEK_SET ) ) { return -1; } int numRead = fread( inDB->recordBuffer, inDB->recordSizeBytes, 1, inDB->file ); if( numRead != 1 ) { return -1; } // now clear present byte if( fseeko( inDB->file, binLoc, SEEK_SET ) ) { return -1; } // write not present flag unsigned char presentFlag = 0; int numWritten = fwrite( &presentFlag, 1, 1, inDB->file ); if( numWritten != 1 ) { return -1; } setNotExists( inDB, c ); // decrease count before reinsert, which will increment count inDB->numRecords --; int putResult = LINEARDB_put( inDB, // key &( inDB->recordBuffer[ 1 ] ), // value &( inDB->recordBuffer[ 1 + inDB->keySize ] ) ); if( putResult != 0 ) { return -1; } } c++; if( c >= inDB->hashTableSizeB ) { c -= inDB->hashTableSizeB; } numCellsTouched++; } return 0; } // uses method described here: // https://en.wikipedia.org/wiki/Linear_hashing // But adds support for linear probing by potentially rehashing // all cells hit by a linear probe from the split point // returns 0 on success, -1 on failure // // This call may expand the table by more than one cell, until the table // is big enough that it's at or below the maxLoad static int expandTable( LINEARDB *inDB ) { unsigned int oldSplitPoint = inDB->hashTableSizeB - inDB->hashTableSizeA; // expand table until we are back at or below maxLoad int numExpanded = 0; while( (double)( inDB->numRecords ) / (double)( inDB->hashTableSizeB ) > inDB->maxLoad ) { inDB->hashTableSizeB ++; numExpanded++; if( inDB->hashTableSizeB == inDB->hashTableSizeA * 2 ) { // full round of expansion is done. unsigned int oldTableSizeA = inDB->hashTableSizeA; inDB->hashTableSizeA = inDB->hashTableSizeB; recreateMaps( inDB, oldTableSizeA ); } } // add extra cells at end of the file if( fseeko( inDB->file, 0, SEEK_END ) ) { return -1; } memset( inDB->recordBuffer, 0, inDB->recordSizeBytes ); for( int c=0; c<numExpanded; c++ ) { int numWritten = fwrite( inDB->recordBuffer, inDB->recordSizeBytes, 1, inDB->file ); if( numWritten != 1 ) { return -1; } } // existence and fingerprint maps already 0 for these extra cells // (they are big enough already to have room for it at the end) // remove and re-insert all contiguous cells from the region // between the old and new split point // we need to ensure there are no holes for future linear probes int result = reinsertCellSegment( inDB, oldSplitPoint, numExpanded ); if( result == -1 ) { return -1; } // do the same for first cell of table, which might have wraped-around // cells in it due to linear probing, and there might be an empty cell // at the end of the table now that we've expanded it // there is no minimum number we must examine, if first cell is empty // looking at just that cell is enough result = reinsertCellSegment( inDB, 0, 1 ); if( result == -1 ) { return -1; } inDB->tableSizeBytes = (uint64_t)( inDB->recordSizeBytes ) * (uint64_t)( inDB->hashTableSizeB ); // write latest sizes into header return writeHeader( inDB ); } // returns 0 if found or 1 if not found, -1 on error // if inPut, it will create a new location for inKey and and write // the contents of inOutValue into that spot, or overwrite // existing value. // if inPut is false, it will read the contents of the value into // inOutValue. static int locateValue( LINEARDB *inDB, const void *inKey, void *inOutValue, char inPut = false ) { unsigned int probeDepth = 0; // hash to find first possible bin for inKey uint64_t hashVal = LINEARDB_hash( inKey, inDB->keySize ); uint64_t binNumberA = hashVal % (uint64_t)( inDB->hashTableSizeA ); uint64_t binNumberB = binNumberA; unsigned int splitPoint = inDB->hashTableSizeB - inDB->hashTableSizeA; if( binNumberA < splitPoint ) { // points before split can be mod'ed with double base table size // binNumberB will always fit in hashTableSizeB, the expanded table binNumberB = hashVal % (uint64_t)( inDB->hashTableSizeA * 2 ); } uint16_t fingerprint = shortHash( inKey, inDB->keySize ); // linear prob after that while( true ) { uint64_t binLoc = getBinLoc( inDB, binNumberB ); char present = exists( inDB, binNumberB ); if( present ) { if( fingerprint == inDB->fingerprintMap[ binNumberB ] ) { // match in fingerprint, but might be false positive // check full key on disk too // skip present flag to key if( fseeko( inDB->file, binLoc + 1, SEEK_SET ) ) { return -1; } int numRead = fread( inDB->recordBuffer, inDB->keySize, 1, inDB->file ); if( numRead != 1 ) { return -1; } if( keyComp( inDB->keySize, inKey, inDB->recordBuffer ) ) { // key match! if( inPut ) { // replace value // C99 standard says we must seek after reading // before writing // we're already at the right spot fseeko( inDB->file, 0, SEEK_CUR ); int numWritten = fwrite( inOutValue, inDB->valueSize, 1, inDB->file ); if( numWritten != 1 ) { return -1; } // present flag and fingerprint already set return 0; } else { // read value numRead = fread( inOutValue, inDB->valueSize, 1, inDB->file ); if( numRead != 1 ) { return -1; } return 0; } } } // no key match, collision in this bin // go on to next bin binNumberB++; probeDepth ++; if( probeDepth > inDB->maxProbeDepth ) { inDB->maxProbeDepth = probeDepth; } // wrap around if( binNumberB >= inDB->hashTableSizeB ) { binNumberB -= inDB->hashTableSizeB; } } else if( inPut ) { // empty bin, insert mode if( fseeko( inDB->file, binLoc, SEEK_SET ) ) { return -1; } // write present flag unsigned char presentFlag = 1; int numWritten = fwrite( &presentFlag, 1, 1, inDB->file ); if( numWritten != 1 ) { return -1; } // write key numWritten = fwrite( inKey, inDB->keySize, 1, inDB->file ); if( numWritten != 1 ) { return -1; } // write value numWritten = fwrite( inOutValue, inDB->valueSize, 1, inDB->file ); if( numWritten != 1 ) { return -1; } setExists( inDB, binNumberB ); inDB->fingerprintMap[ binNumberB ] = fingerprint; inDB->numRecords++; if( (double)( inDB->numRecords ) / (double)( inDB->hashTableSizeB ) > inDB->maxLoad ) { return expandTable( inDB ); } return 0; } else { // empty bin hit, not insert mode return 1; } } } int LINEARDB_get( LINEARDB *inDB, const void *inKey, void *outValue ) { return locateValue( inDB, inKey, outValue, false ); } int LINEARDB_put( LINEARDB *inDB, const void *inKey, const void *inValue ) { return locateValue( inDB, inKey, (void*)inValue, true ); } void LINEARDB_Iterator_init( LINEARDB *inDB, LINEARDB_Iterator *inDBi ) { inDBi->db = inDB; inDBi->nextRecordLoc = LINEARDB_HEADER_SIZE; inDBi->currentRunLength = 0; inDB->maxProbeDepth = 0; } int LINEARDB_Iterator_next( LINEARDB_Iterator *inDBi, void *outKey, void *outValue ) { LINEARDB *db = inDBi->db; while( true ) { if( inDBi->nextRecordLoc > db->tableSizeBytes + LINEARDB_HEADER_SIZE ) { return 0; } // fseek is needed here to make iterator safe to interleave // with other calls // If iterator calls are not interleaved, this seek should have // little impact on performance (seek to current location between // reads). if( fseeko( db->file, inDBi->nextRecordLoc, SEEK_SET ) ) { return -1; } int numRead = fread( db->recordBuffer, db->recordSizeBytes, 1, db->file ); if( numRead != 1 ) { return -1; } inDBi->nextRecordLoc += db->recordSizeBytes; if( db->recordBuffer[0] ) { inDBi->currentRunLength++; if( inDBi->currentRunLength > db->maxProbeDepth ) { db->maxProbeDepth = inDBi->currentRunLength; } // present memcpy( outKey, &( db->recordBuffer[1] ), db->keySize ); memcpy( outValue, &( db->recordBuffer[1 + db->keySize] ), db->valueSize ); return 1; } else { // empty table cell, run broken inDBi->currentRunLength = 0; } } } unsigned int LINEARDB_getCurrentSize( LINEARDB *inDB ) { return inDB->hashTableSizeB; } unsigned int LINEARDB_getNumRecords( LINEARDB *inDB ) { return inDB->numRecords; } unsigned int LINEARDB_getShrinkSize( LINEARDB *inDB, unsigned int inNewNumRecords ) { unsigned int curSize = inDB->hashTableSizeA; if( inDB->hashTableSizeA != inDB->hashTableSizeB ) { // use doubled size as cur size // it's big enough to contain current record load without // violating max load factor curSize *= 2; } if( inNewNumRecords >= curSize ) { // can't shrink return curSize; } unsigned int minSize = lrint( ceil( inNewNumRecords / inDB->maxLoad ) ); // power of 2 that divides curSize and produces new size that is // large enough for minSize unsigned int divisor = 1; while( true ) { unsigned int newDivisor = divisor * 2; if( curSize % newDivisor == 0 && curSize / newDivisor >= minSize ) { divisor = newDivisor; } else { // divisor as large as it can be break; } } return curSize / divisor; } uint64_t LINEARDB_getMaxFileSize( unsigned int inTableStartSize, unsigned int inKeySize, unsigned int inValueSize, uint64_t inNumRecords, double inMaxLoad ) { if( inMaxLoad == 0 ) { inMaxLoad = DEFAULT_MAX_LOAD; } uint64_t recordSize = 1 + inKeySize + inValueSize; double load = (double)inNumRecords / (double)inTableStartSize; uint64_t tableSize = inTableStartSize; if( load > inMaxLoad ) { // too big for original table tableSize = (uint64_t)( ceil( ( inNumRecords / inMaxLoad ) ) ); } return LINEARDB_HEADER_SIZE + tableSize * recordSize; } void LINEARDB_forceFile( LINEARDB *inDB, FILE *inFile ) { inDB->file = inFile; }
26.615247
80
0.490194
Valaras
e7e64a1e3b3e19cb93bafee7a75209a3390350cc
280
cpp
C++
src/range_based_for_loop.cpp
mwerlberger/cpp11_tutorial
e02e7a1fb61b029681060db97ff16e1b8be53ad1
[ "BSD-3-Clause" ]
null
null
null
src/range_based_for_loop.cpp
mwerlberger/cpp11_tutorial
e02e7a1fb61b029681060db97ff16e1b8be53ad1
[ "BSD-3-Clause" ]
null
null
null
src/range_based_for_loop.cpp
mwerlberger/cpp11_tutorial
e02e7a1fb61b029681060db97ff16e1b8be53ad1
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <vector> int main() { std::vector<int> ivec = {0, 1, 2, 3, 4, 5}; for (auto i : ivec) { std::cout << i << ", "; } std::cout << std::endl; for(auto j : {0,2,4,6,8,10}) { std::cout << j << ", "; } std::cout << std::endl; }
13.333333
45
0.457143
mwerlberger
e7e7d00961663b3da155a1b0d6692c1f5ef3e367
3,547
cpp
C++
src/IntroductionLevel.cpp
dantehemerson/Arkanoid-Returns
478ae8df92f978dce95fd227a9047e83dea9a855
[ "MIT" ]
3
2018-09-25T07:59:06.000Z
2019-08-24T09:35:43.000Z
src/IntroductionLevel.cpp
dantehemerson/Arkanoid-Returns
478ae8df92f978dce95fd227a9047e83dea9a855
[ "MIT" ]
1
2018-05-08T11:34:05.000Z
2018-05-08T11:34:05.000Z
src/IntroductionLevel.cpp
dantehemerson/Arkanoid-Returns
478ae8df92f978dce95fd227a9047e83dea9a855
[ "MIT" ]
1
2020-06-07T21:23:24.000Z
2020-06-07T21:23:24.000Z
#include "IntroductionLevel.hpp" #include <allegro5/allegro_font.h> #include <allegro5/allegro_primitives.h> #include "Gallery.hpp" #include "R.hpp" #include "Level.hpp" const int IntroductionLevel::waitTime = 85; const int IntroductionLevel::animationStart = 310; IntroductionLevel::IntroductionLevel(Level* level) : level(level), velocity(9), counterStart(0) { isStart = true; velocityAnimationAlpha = 2; reinit(); } void IntroductionLevel::draw() const { if (isStart) { al_draw_filled_rectangle(0, 0, 800, 600, al_map_rgba(0, 0, 0, alpha)); } al_draw_filled_rectangle(rectPos.X() - 1, rectPos.Y(), rectPos.X() + 800, rectPos.Y() + 240, al_map_rgba(50, 50, 50, 150)); al_draw_scaled_bitmap(Gallery::getSingleton().getImage(R::Image::SHADOW_TOP), 0, 0, 64, 33, rectPos.X(), 200, 800, 15, NULL); al_draw_scaled_bitmap(Gallery::getSingleton().getImage(R::Image::SHADOW_BOTTOM), 0, 0, 64, 33, rectPos.X(), 425, 800, 15, NULL); al_draw_scaled_bitmap(Gallery::getSingleton().getImage(R::Image::SHADOW_LEFT), 0, 0, 33, 64, rectPos.X(), 200, 15, 200, NULL); al_draw_scaled_bitmap(Gallery::getSingleton().getImage(R::Image::SHADOW_RIGHT), 0, 0, 33, 64, rectPos.X() + 785, 200, 15, 200, NULL); al_draw_textf(Gallery::getSingleton().getFont(R::Font::VENUS_INTRO), R::Color::GREEN, titlePos.X() + 4, titlePos.Y() + 4, ALLEGRO_ALIGN_CENTER, "LEVEL %i", level->getLevel()); al_draw_textf(Gallery::getSingleton().getFont(R::Font::VENUS_INTRO), R::Color::WHITE, titlePos.X(), titlePos.Y(), ALLEGRO_ALIGN_CENTER, "LEVEL %i", level->getLevel()); if (isStart) { al_draw_textf(Gallery::getSingleton().getFont(R::Font::VENUS_BIG), R::Color::GREEN, titlePos.X() + 4, 364, ALLEGRO_ALIGN_CENTER, "START"); al_draw_textf(Gallery::getSingleton().getFont(R::Font::VENUS_BIG), R::Color::WHITE, titlePos.X(), 360, ALLEGRO_ALIGN_CENTER, "START"); } } void IntroductionLevel::update() { if (counterStart < animationStart) { if (!isStart) { counterStart = animationStart; } else { if (initLLC) { loadLevelCounter++; if (loadLevelCounter > 50) { initLLC = false; } } else { alpha += velocityAnimationAlpha; } if (alpha >= 255) { level->show(); alpha = 254; velocityAnimationAlpha = 2; velocityAnimationAlpha *= -1; // Para que ahora disminuya initLLC = true; } else if (alpha <= 0) { alpha = 0; } counterStart++; } if (counterStart == animationStart) { isStart = false; } } if (counterStart >= animationStart) { if (titlePos.X() > (400 - velocity / 2) && titlePos.X() <= (400 + velocity / 2)) { counter = (counter + 1) % 100000; if (counter > waitTime) { titlePos.setX(titlePos.X() - velocity); } } else { rectPos.setX(rectPos.X() + velocity + velocity / 3.73); titlePos.setX(titlePos.X() - velocity); } /* Es /2 */ if (titlePos.X() < -al_get_text_width(Gallery::getSingleton().getFont(R::Font::VENUS_INTRO), "NIVEL 0")) { finish = true; } } } bool IntroductionLevel::animationFinish() const { return finish; } void IntroductionLevel::setStart(bool value) { isStart = value; } void IntroductionLevel::reinit(bool initGame) { counter = 0; counterStart = 0; loadLevelCounter = 0; alpha = (initGame ? 255 : 0); initLLC = false; finish = false; velocityAnimationAlpha = 2; rectPos.setPosition(-800 - velocity, 200); titlePos.setPosition(800 + al_get_text_width(Gallery::getSingleton().getFont(R::Font::VENUS_INTRO), "NIVEL 00") / 2 + velocity, 250); } IntroductionLevel::~IntroductionLevel() { }
29.31405
176
0.674373
dantehemerson
e7eaa66765589fa41db55d729629e7030c75eb31
2,258
cc
C++
src/Rtsp.cc
philberty/overflow
7370cd4d145f290c32a8c020ae849241ac9b1082
[ "MIT" ]
4
2020-03-27T21:17:06.000Z
2022-02-11T15:20:17.000Z
src/Rtsp.cc
philberty/overflow
7370cd4d145f290c32a8c020ae849241ac9b1082
[ "MIT" ]
null
null
null
src/Rtsp.cc
philberty/overflow
7370cd4d145f290c32a8c020ae849241ac9b1082
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Philip Herron. // // 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 "Rtsp.h" #include "Helpers.h" Overflow::Rtsp::Rtsp(const std::string& method, const std::string& path, int seqNum) : mMethod(method), mPath(path) { addHeader("CSeq", Helper::intToString(seqNum)); } const Overflow::ByteBuffer& Overflow::Rtsp::getBuffer() { mBuffer.reset(); mBuffer.append(mMethod + " " + mPath + " RTSP/1.0\r\n"); for (auto it = mHeaders.begin(); it != mHeaders.end(); ++it) { mBuffer.append(it->first + ": " + it->second + "\r\n"); } mBuffer.append("\r\n\r\n"); // TODO: // add content return mBuffer; } void Overflow::Rtsp::addAuth(const std::string& encoded) { addHeader("Authorization", "Basic " + encoded); } const std::string& Overflow::Rtsp::getMethod() const { return mMethod; } std::string Overflow::Rtsp::toString() { std::string buf; buf += mMethod + ":" + mPath; return buf; } void Overflow::Rtsp::addHeader(const std::string& key, const std::string& value) { mHeaders.insert(std::pair<std::string,std::string>(key, value)); }
28.582278
80
0.666076
philberty
e7ef2ea6b47ffd901a7f1941bb904ee11833a8f1
2,523
cpp
C++
sys/dev/arm/armv7m-systick/armv7m-systick.cpp
apexrtos/apex
9538ab2f5b974035ca30ca8750479bdefe153047
[ "0BSD" ]
15
2020-05-08T06:21:58.000Z
2021-12-11T18:10:43.000Z
sys/dev/arm/armv7m-systick/armv7m-systick.cpp
apexrtos/apex
9538ab2f5b974035ca30ca8750479bdefe153047
[ "0BSD" ]
11
2020-05-08T06:46:37.000Z
2021-03-30T05:46:03.000Z
sys/dev/arm/armv7m-systick/armv7m-systick.cpp
apexrtos/apex
9538ab2f5b974035ca30ca8750479bdefe153047
[ "0BSD" ]
5
2020-08-31T17:05:03.000Z
2021-12-08T07:09:00.000Z
#include "init.h" #include <arch/mmio.h> #include <atomic> #include <cpu.h> #include <debug.h> #include <irq.h> #include <sections.h> #include <timer.h> #include <v7m/bitfield.h> namespace { /* * SysTick registers */ struct syst { union csr { using S = uint32_t; struct { S r; }; bitfield::armbit<S, bool, 16> COUNTFLAG; bitfield::armbit<S, bool, 2> CLKSOURCE; bitfield::armbit<S, bool, 1> TICKINT; bitfield::armbit<S, bool, 0> ENABLE; } CSR; uint32_t RVR; uint32_t CVR; union calib { using S = uint32_t; struct { S r; }; bitfield::armbit<S, bool, 31> NOREF; bitfield::armbit<S, bool, 30> SKEW; bitfield::armbits<S, unsigned, 23, 0> TENMS; } CALIB; }; static_assert(sizeof(syst) == 16, "Bad SYST size"); static syst *const SYST = (syst*)0xe000e010; __fast_bss uint64_t scale; __fast_bss std::atomic<uint64_t> monotonic; constexpr uint32_t tick_ns = 1000000000 / CONFIG_HZ; /* * Compute how many nanoseconds we are through the current tick * * Must be called with SysTick interrupt disabled */ uint32_t ns_since_tick() { if (!read32(&SYST->CSR).ENABLE) return 0; /* get CVR, making sure that we handle rollovers */ uint32_t cvr = read32(&SYST->CVR); bool tick_pending = read32(&SCB->ICSR).PENDSTSET; if (tick_pending) cvr = read32(&SYST->CVR); /* convert count to nanoseconds */ uint32_t ns = cvr ? ((read32(&SYST->RVR) + 1 - cvr) * scale) >> 32 : 0; if (tick_pending) ns += tick_ns; return ns; } } /* * Initialise */ void arm_armv7m_systick_init(const arm_armv7m_systick_desc *d) { /* do not configure twice */ assert(!read32(&SYST->CSR).ENABLE); /* set systick timer to interrupt us at CONFIG_HZ */ write32(&SYST->RVR, static_cast<uint32_t>(d->clock / CONFIG_HZ - 1)); write32(&SYST->CVR, 0u); /* enable timer & interrupts */ write32(&SYST->CSR, [&]{ syst::csr r{}; r.ENABLE = 1; r.TICKINT = 1; r.CLKSOURCE = d->clksource; return r; }()); /* scaling factor from count to ns * 2^32 */ scale = 1000000000ull * 0x100000000 / d->clock; dbg("ARMv7-M SysTick initialised, RVR=%u\n", read32(&SYST->RVR)); } /* * SysTick exception */ extern "C" __fast_text void exc_SysTick() { timer_tick(monotonic += tick_ns, tick_ns); } /* * Get monotonic time */ uint_fast64_t timer_monotonic() { const int s = irq_disable(); const uint_fast64_t r = monotonic + ns_since_tick(); irq_restore(s); return r; } /* * Get monotonic time (coarse, fast version), 1/CONFIG_HZ resolution. */ uint_fast64_t timer_monotonic_coarse() { return monotonic; }
20.02381
72
0.673405
apexrtos
e7f4aa77455816c3abbe4c34adbf962e940377f5
6,411
cpp
C++
source/backend/cpu/CPUGridSample.cpp
zhangzan1997/MNN
2860411058fcd5f5d4848b92b571276bda00e12b
[ "Apache-2.0" ]
1
2021-06-01T03:02:29.000Z
2021-06-01T03:02:29.000Z
source/backend/cpu/CPUGridSample.cpp
zhangzan1997/MNN
2860411058fcd5f5d4848b92b571276bda00e12b
[ "Apache-2.0" ]
null
null
null
source/backend/cpu/CPUGridSample.cpp
zhangzan1997/MNN
2860411058fcd5f5d4848b92b571276bda00e12b
[ "Apache-2.0" ]
null
null
null
// // CPUGridSample.cpp // MNN // // Created by MNN on 2021/03/24. // Copyright © 2018, Alibaba Group Holding Limited // #include "backend/cpu/CPUGridSample.hpp" #include <math.h> #include <string.h> #include "core/Concurrency.h" #include <algorithm> #include "backend/cpu/CPUBackend.hpp" #include "backend/cpu/compute/CommonOptFunction.h" #include "backend/cpu/compute/ConvOpt.h" #include "core/Macro.h" #include <math/Vec.hpp> using Vec4 = MNN::Math::Vec<float, 4>; namespace MNN { CPUGridSample::CPUGridSample(Backend *b, SampleMode mode, BorderMode paddingMode, bool alignCorners) : Execution(b) { mMode = mode; mPaddingMode = paddingMode; mAlignCorners = alignCorners; } static float getPosition(float x, int range, bool alignCorners) { float a = alignCorners ? 1.0f : 0.0f; float b = alignCorners ? 0.0f : 1.0f; return ((1 + x) * (range - a) - b) / 2.0f; } static int CLAMP(int v, int min, int max) { if ((v) < min) { (v) = min; } else if ((v) > max) { (v) = max; } return v; } static Vec4 sample(int h, int w, const float *buffer, int height, int width, BorderMode padMode) { if (h < 0 || h >= height || w < 0 || w >= width) { if(padMode == BorderMode_ZEROS) { return 0.0f; } // Clearly, CLAMP is the right way to go for GridSamplePaddingMode_BORDER // For GridSamplePaddingMode_REFLECTION, since we have reflected the values into (-1, 1), // the leftover reflections degrade to GridSamplePaddingMode_BORDER h = CLAMP(h, 0, height - 1); w = CLAMP(w, 0, width - 1); } return Vec4::load(buffer + h * width * 4 + w * 4); } static Vec4 interpolate(float h, float w, const float *buffer, int height, int width, SampleMode mode, BorderMode padMode) { if (mode == SampleMode_NEAREST) { int nh = ::floor(h+0.5f); int nw = ::floor(w+0.5f); return sample(nh, nw, buffer, height, width, padMode); } // mode == GridSampleMode_BILINEAR int w0_h = ::floor(h); int w0_w = ::floor(w); int w1_h = ::ceil(h); int w1_w = ::ceil(w); auto oneV = Vec4(1.0f); Vec4 i00 = sample(w0_h, w0_w, buffer, height, width, padMode); Vec4 i01 = sample(w0_h, w1_w, buffer, height, width, padMode); Vec4 i10 = sample(w1_h, w0_w, buffer, height, width, padMode); Vec4 i11 = sample(w1_h, w1_w, buffer, height, width, padMode); auto f0 = Vec4((float)w1_w - w); auto f1 = oneV - f0; auto h0 = Vec4((float)w1_h - h); auto h1 = oneV - h0; Vec4 i0 = i00 * f0 + i01 * f1; Vec4 i1 = i10 * f0 + i11 * f1; return i0 * h0 + i1 * h1; } ErrorCode CPUGridSample::onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) { int numberThread = static_cast<CPUBackend*>(backend())->threadNumber(); auto outputTensor = outputs[0]; auto outH = outputTensor->buffer().dim[2].extent; auto outW = outputTensor->buffer().dim[3].extent; mTempCordBuffer.reset(Tensor::createDevice<float>({1, outH * outW * 2})); auto res = backend()->onAcquireBuffer(mTempCordBuffer.get(), Backend::DYNAMIC); if (!res) { return OUT_OF_MEMORY; } backend()->onReleaseBuffer(mTempCordBuffer.get(), Backend::DYNAMIC); return NO_ERROR; } ErrorCode CPUGridSample::onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) { auto inputTensor = inputs[0]; auto gridTensor = inputs[1]; auto outputTensor = outputs[0]; float *inputPtr = inputTensor->host<float>(); float *gridPtr = gridTensor->host<float>(); auto *outputPtr = outputTensor->host<float>(); auto batches = inputTensor->buffer().dim[0].extent; auto channels = inputTensor->buffer().dim[1].extent; auto channelC4 = UP_DIV(channels, 4); auto inH = inputTensor->buffer().dim[2].extent; auto inW = inputTensor->buffer().dim[3].extent; auto outH = outputTensor->buffer().dim[2].extent; auto outW = outputTensor->buffer().dim[3].extent; auto cordPtr = mTempCordBuffer->host<float>(); auto threadCount = static_cast<CPUBackend*>(backend())->threadNumber(); auto tileCount = channelC4 * outH; for (auto b = 0; b < batches; ++b) { const float *_inputPtr = inputPtr + b * inputTensor->buffer().dim[0].stride; const float *_gridPtr = gridPtr + b * gridTensor->buffer().dim[0].stride; float *_outputPtr = outputPtr + b * outputTensor->buffer().dim[0].stride; // Compute cord for (auto h = 0; h < outH; ++h) { auto __gridPtr = _gridPtr + h * gridTensor->buffer().dim[1].stride; auto cordH = cordPtr + h * outW * 2; for (auto w = 0; w < outW; ++w) { auto x = getPosition(__gridPtr[2 * w + 0], inW, mAlignCorners); auto y = getPosition(__gridPtr[2 * w + 1], inH, mAlignCorners); cordH[2 * w + 0] = x; cordH[2 * w + 1] = y; } } MNN_CONCURRENCY_BEGIN(tId, threadCount) { for (int index=tId; index < tileCount; index += threadCount) { auto c = index / outH; auto h = index % outH; auto inpC = _inputPtr + c * inW * inH * 4; auto outC = _outputPtr + c * outW * outH * 4; auto cordH = cordPtr + h * outW * 2; auto outH = outC + h * outW * 4; for (auto w = 0; w < outW; ++w) { auto x = cordH[2 * w + 0]; auto y = cordH[2 * w + 1]; Vec4::save(outH + 4 * w, interpolate(y, x, inpC, inH, inW, mMode, mPaddingMode)); } } } MNN_CONCURRENCY_END(); } return NO_ERROR; } class CPUGridSampleCreator : public CPUBackend::Creator { public: virtual Execution *onCreate(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs, const MNN::Op *op, Backend *backend) const { auto gridSampleParam = op->main_as_GridSample(); auto mode = gridSampleParam->mode(); auto paddingMode = gridSampleParam->paddingMode(); auto alignCorners = gridSampleParam->alignCorners(); return new CPUGridSample(backend, mode, paddingMode, alignCorners); } }; REGISTER_CPU_OP_CREATOR(CPUGridSampleCreator, OpType_GridSample); } // namespace MNN
37.057803
124
0.599282
zhangzan1997
e7f92df8112aa20a087be331e4f1abdf21c18529
2,000
cpp
C++
src/diskFile.cpp
Rocik/btree-file-index
04cb787c903a18e606b2f03f0cce345d879086f5
[ "MIT" ]
null
null
null
src/diskFile.cpp
Rocik/btree-file-index
04cb787c903a18e606b2f03f0cce345d879086f5
[ "MIT" ]
null
null
null
src/diskFile.cpp
Rocik/btree-file-index
04cb787c903a18e606b2f03f0cce345d879086f5
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <cassert> #include <cstring> #include "diskFile.h" int DiskFile::statRead = 0; int DiskFile::statWrite = 0; DiskFile::DiskFile(string filename, int pageSize) : filename(filename), pageSizeInBytes(pageSize) { binaryInOut = fstream::in | fstream::out | fstream::binary; binaryAppend = fstream::out | fstream::binary | ifstream::app; ifstream infile(filename); newlyCreated = !infile.good(); resetStats(); } bool DiskFile::existed() { return !newlyCreated; } bool DiskFile::readPage(int pageNumber, char* page) { unique_ptr<ifstream> file = make_unique<ifstream>(filename, ifstream::binary); file->seekg(pageNumber * pageSizeInBytes, ios::beg); file->read(page, pageSizeInBytes); file->close(); DiskFile::statRead++; return true; } void DiskFile::savePage(int pageNumber, const char* page) { unique_ptr<fstream> file; // This is retarded design of C++ streams: // If you want to replace bytes you HAVE to open in fstream binaryInOut // but it will not create new file and when you append data the file is erased // When you use binaryAppend your data will ALWAYS be written at the end // This will still not work when skipping some pages at the creation of file int totalPages = getPagesCount(); if (pageNumber == totalPages) file = make_unique<fstream>(filename, binaryAppend); else { file = make_unique<fstream>(filename, binaryInOut); file->seekp(pageNumber * pageSizeInBytes, ios::beg); } file->write(page, pageSizeInBytes); file->flush(); file->close(); DiskFile::statWrite++; } int DiskFile::getPagesCount() { ifstream in(filename, ifstream::binary | ifstream::ate); return in.tellg() / pageSizeInBytes; } void DiskFile::dispose() { ::remove(filename.c_str()); } int DiskFile::getStatReads() { return DiskFile::statRead; } int DiskFile::getStatWrites() { return DiskFile::statWrite; } void DiskFile::resetStats() { DiskFile::statRead = 0; DiskFile::statWrite = 0; }
21.73913
79
0.7145
Rocik
e7fef3d6df5d8d706514527c0023aa049decc9c9
6,986
cpp
C++
storage/tests/EvictionPolicy_unittest.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
storage/tests/EvictionPolicy_unittest.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
storage/tests/EvictionPolicy_unittest.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #include <algorithm> #include <array> #include <chrono> #include <memory> #include <thread> // NOLINT(build/c++11) #include <unordered_set> #include "gtest/gtest.h" #include "storage/EvictionPolicy.hpp" #include "storage/StorageBlockInfo.hpp" namespace quickstep { class EvictionPolicyTest : public ::testing::Test { protected: enum class Config : unsigned char { kUniformRandom = 0, kLRU1, kLRU2, kLRU3, kEvictAnyBlock, kEnd }; Config current_config_ = Config::kUniformRandom; std::unique_ptr<EvictionPolicy> eviction_policy_; void initEvictionPolicy() { switch (current_config_) { case Config::kUniformRandom: eviction_policy_.reset(new UniformRandomEvictionPolicy); break; case Config::kLRU1: eviction_policy_.reset(LRUKEvictionPolicyFactory::ConstructLRUKEvictionPolicy(1, std::chrono::seconds(100))); break; case Config::kLRU2: eviction_policy_.reset(LRUKEvictionPolicyFactory::ConstructLRUKEvictionPolicy(2, std::chrono::seconds(100))); break; case Config::kLRU3: eviction_policy_.reset(LRUKEvictionPolicyFactory::ConstructLRUKEvictionPolicy(3, std::chrono::seconds(100))); break; case Config::kEvictAnyBlock: eviction_policy_.reset(new EvictAnyBlockEvictionPolicy); break; case Config::kEnd: ASSERT_TRUE(false); break; } } public: EvictionPolicyTest() : ::testing::Test() { initEvictionPolicy(); } protected: bool nextConfig() { current_config_ = static_cast<Config>(static_cast<unsigned char>(current_config_) + 1); if (current_config_ == Config::kEnd) { current_config_ = Config::kUniformRandom; return false; } initEvictionPolicy(); return true; } }; TEST_F(EvictionPolicyTest, DoesNotEvictReferencedBlocks) { EvictionPolicy::Status status; block_id block; do { // Simulate some access patterns std::unordered_set<block_id> blocks; for (int i = 0; i < 1000; ++i) { blocks.insert(BlockIdUtil::GetBlockId(0 /* domain */, i)); } status = eviction_policy_->chooseBlockToEvict(&block); ASSERT_EQ(EvictionPolicy::Status::kBlockNotFound, status); // Make all blocks known to eviction_policy_ for (int i = 0; i < 1000; ++i) { eviction_policy_->blockReferenced(BlockIdUtil::GetBlockId(0 /* domain */, i)); eviction_policy_->blockUnreferenced(BlockIdUtil::GetBlockId(0 /* domain */, i)); } // Reference every 10th one for (int i = 0; i < 1000; i += 10) { eviction_policy_->blockReferenced(BlockIdUtil::GetBlockId(0 /* domain */, i)); } // Make sure they don't get chosen for eviction for (int i = 0; i < 900; ++i) { status = eviction_policy_->chooseBlockToEvict(&block); // Expect that status is okay and that it didn't evict a referenced block ASSERT_EQ(EvictionPolicy::Status::kOk, status); ASSERT_NE(0u, BlockIdUtil::Counter(block) % 10); blocks.erase(block); } // Make sure that we now always get an error. We just try 10 times. for (int i = 0; i < 10; ++i) { status = eviction_policy_->chooseBlockToEvict(&block); ASSERT_EQ(EvictionPolicy::Status::kBlockNotFound, status); } // Now unreference and evict the rest of the blocks for (int i = 0; i < 1000; i += 10) { eviction_policy_->blockUnreferenced(BlockIdUtil::GetBlockId(0 /* domain */, i)); status = eviction_policy_->chooseBlockToEvict(&block); ASSERT_EQ(EvictionPolicy::Status::kOk, status); blocks.erase(block); ASSERT_EQ(static_cast<block_id_counter>(i), BlockIdUtil::Counter(block)); } // Finally, ensure that EvictionPolicy doesn't believe in any non-existent blocks for (int i = 0; i < 10; ++i) { status = eviction_policy_->chooseBlockToEvict(&block); ASSERT_EQ(EvictionPolicy::Status::kBlockNotFound, status); } } while (nextConfig()); } TEST(LRUKEvictionPolicyTest, LRU2IsCorrect) { std::array<std::chrono::milliseconds, 3> corrl_reference_periods = {{ std::chrono::milliseconds(0), std::chrono::milliseconds(100), std::chrono::milliseconds(300) }}; for (std::chrono::milliseconds corrl_reference_period : corrl_reference_periods) { // Create an array of block IDs from [1, 100] and shuffle it. std::array<block_id, 100> blocks; int n = 1; std::generate(blocks.begin(), blocks.end(), [&n]{ return BlockIdUtil::GetBlockId(0 /* domain */, n++); }); std::random_shuffle(blocks.begin(), blocks.end()); // Create an LRU-2 EvictionPolicy std::unique_ptr<EvictionPolicy> eviction_policy( LRUKEvictionPolicyFactory::ConstructLRUKEvictionPolicy( 2, corrl_reference_period)); // Reference all the blocks for (const block_id block : blocks) { eviction_policy->blockReferenced(block); eviction_policy->blockUnreferenced(block); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } // Shuffle them again std::array<block_id, 100> shuffled_blocks = blocks; std::random_shuffle(shuffled_blocks.begin(), shuffled_blocks.end()); // Ensure that the next set of references is at least corrl_reference_period after the first set. std::this_thread::sleep_for(corrl_reference_period); // Reference each block again in a random order for (const block_id block : shuffled_blocks) { eviction_policy->blockReferenced(block); eviction_policy->blockUnreferenced(block); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } // Ensure that no block has been referenced in the last corrl_reference_period. std::this_thread::sleep_for(corrl_reference_period + std::chrono::milliseconds(500)); // Assure that the blocks are evicted in descending order for (const block_id block : blocks) { block_id evicted_block; EvictionPolicy::Status status = eviction_policy->chooseBlockToEvict(&evicted_block); ASSERT_EQ(EvictionPolicy::Status::kOk, status); ASSERT_EQ(block, evicted_block); } } } } // namespace quickstep
34.245098
110
0.68623
Hacker0912
f0023820823cf54a5a0e857940730910d797df64
4,136
cpp
C++
tool/procedural/distributedsquaregenerator.cpp
monadgroup/sy17
2901438fcca6be69d30ff9c316097deb37a85613
[ "MIT" ]
18
2021-10-04T14:05:28.000Z
2021-12-26T21:18:06.000Z
tool/procedural/distributedsquaregenerator.cpp
monadgroup/sy17
2901438fcca6be69d30ff9c316097deb37a85613
[ "MIT" ]
null
null
null
tool/procedural/distributedsquaregenerator.cpp
monadgroup/sy17
2901438fcca6be69d30ff9c316097deb37a85613
[ "MIT" ]
null
null
null
#include "distributedsquaregenerator.h" #include "util.h" using namespace monad; DistributedSquareGenerator::DistributedSquareGenerator(ivec2 size) : size(size) { cells = new bool*[size.y]; for (auto y = 0; y < size.y; y++) { cells[y] = new bool[size.x]; } maxSize = size.x > size.y ? size.x : size.y; maxSize /= 2; } bool DistributedSquareGenerator::inBounds(ivec2 p) { return p.x >= 0 && p.x < size.x && p.y >= 0 && p.y < size.y; } bool DistributedSquareGenerator::isUsed(ivec2 p) { if (!inBounds(p)) return true; return cells[p.y][p.x]; } void DistributedSquareGenerator::spawnRay(ivec2 p, ivec2 d) { auto nextP = p + d; if (isUsed(nextP + ivec2(d.y, d.x)) || isUsed(nextP - ivec2(d.y, d.x))) return; if (inBounds(nextP) && !cells[nextP.y][nextP.x]) { auto newRayDist = (int)random(5, maxSize * distMultiplier); newRays.push_back({p, d, newRayDist}); } } void DistributedSquareGenerator::updateRay(Ray &ray) { ray.p = ray.p + ray.d; if (!inBounds(ray.p)) return; cells[ray.p.y][ray.p.x] = true; ray.distance--; if (ray.distance <= 0) { spawnRay(ray.p, ivec2(ray.d.y, ray.d.x)); spawnRay(ray.p, -ivec2(ray.d.y, ray.d.x)); if (random(0, 1) < 0.5) spawnRay(ray.p, ray.d); } else { auto nextP = ray.p + ray.d; if (inBounds(nextP) && !cells[nextP.y][nextP.x]) newRays.push_back(ray); } } void DistributedSquareGenerator::fixCorners() { for (auto y = 0; y < size.y; y++) { for (auto x = 0; x < size.x; x++) { if (!cells[y][x]) continue; auto usedLeft = isUsed({x - 1, y}); auto usedRight = isUsed({x + 1, y}); auto usedAbove = isUsed({x, y - 1}); auto usedBelow = isUsed({x, y + 1}); auto hFlag = usedLeft ^ usedRight; auto vFlag = usedAbove ^ usedBelow; if (hFlag && vFlag) { ivec2 direction; if (random(0, 1) < 0.5) direction = {usedLeft ? 1 : -1, 0}; else direction = {0, usedAbove ? 1 : -1}; auto startPoint = ivec2(x, y) + direction; while (!isUsed(startPoint)) { cells[startPoint.y][startPoint.x] = true; startPoint = startPoint + direction; } } } } } void DistributedSquareGenerator::floodfill(List<ivec4> &boxes) { for (auto y = 0; y < size.y; y++) { for (auto x = 0; x < size.x; x++) { if (cells[y][x]) continue; auto usedLeft = isUsed({x - 1, y}); auto usedTop = isUsed({x, y - 1}); if (!usedLeft || !usedTop) continue; auto boundX = x + 1; while (!isUsed({boundX, y})) boundX++; if (boundX == x) continue; auto boundY = y + 1; while (!isUsed({x, boundY})) boundY++; if (boundY == y) continue; boxes.push_back({x, y, boundX - x, boundY - y}); } } } void DistributedSquareGenerator::generate(List<ivec4> &boxes) { distMultiplier = 1; for (auto y = 0; y < size.y; y++) { for (auto x = 0; x < size.x; x++) { cells[y][x] = false; } } ivec2 startRayP = {(int)random(0, size.x), (int)random(0, size.y)}; ivec2 rayDirection; int startDist1, startDist2; if (random(0, 1) < 0.5) { rayDirection = {1, 0}; startDist1 = (int)random(5, size.x - startRayP.x - 5); startDist2 = (int)random(5, size.x - startRayP.x - 5); } else { rayDirection = {0, 1}; startDist1 = (int)random(5, size.y - startRayP.y - 5); startDist2 = (int)random(5, size.y - startRayP.y - 5); } rays = List<Ray>(2); rays.push_back({startRayP, rayDirection, startDist1}); rays.push_back({startRayP, -rayDirection, startDist2}); while (rays.size()) { for (auto &ray : rays) { updateRay(ray); } rays = newRays; newRays = List<Ray>(); distMultiplier *= 0.99; } fixCorners(); floodfill(boxes); }
29.126761
83
0.525145
monadgroup
f006e32d05ab5161b8d32f645e442589754ef14a
4,233
cc
C++
google/cloud/bigquery/samples/read.cc
orinem/google-cloud-cpp
c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1
[ "Apache-2.0" ]
5
2019-10-24T04:58:21.000Z
2021-06-04T06:15:38.000Z
google/cloud/bigquery/samples/read.cc
orinem/google-cloud-cpp
c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1
[ "Apache-2.0" ]
24
2019-10-14T12:33:41.000Z
2020-04-16T19:17:34.000Z
google/cloud/bigquery/samples/read.cc
orinem/google-cloud-cpp
c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1
[ "Apache-2.0" ]
10
2019-10-12T00:35:55.000Z
2021-10-07T21:31:13.000Z
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/bigquery/client.h" namespace { using google::cloud::StatusOr; using google::cloud::bigquery::Client; using google::cloud::bigquery::ConnectionOptions; using google::cloud::bigquery::DeserializeReadStream; using google::cloud::bigquery::MakeConnection; using google::cloud::bigquery::ReadResult; using google::cloud::bigquery::ReadStream; using google::cloud::bigquery::Row; using google::cloud::bigquery::SerializeReadStream; // The following are some temporary examples of how I envision the Read() // functions will be used. Once we settle on the design and implementation, // we'll restructure these samples, so users can actually run them. void SimpleRead() { ConnectionOptions options; Client client(MakeConnection(options)); ReadResult result = client.Read("my-parent-project", "bigquery-public-data:samples.shakespeare", /* columns = */ {"c1", "c2", "c3"}); for (StatusOr<Row> const& row : result.Rows()) { if (row.ok()) { // Do something with row.value(); } } } void ParallelRead() { // From coordinating job: ConnectionOptions options; Client client(MakeConnection(options)); StatusOr<std::vector<ReadStream>> read_session = client.ParallelRead( "my-parent-project", "bigquery-public-data:samples.shakespeare", /* columns = */ {"c1", "c2", "c3"}); if (!read_session.ok()) { // Handle error; } for (ReadStream const& stream : read_session.value()) { std::string bits = SerializeReadStream(stream); // Send bits to worker job. } // From a worker job: std::string bits; // Sent by coordinating job. ReadStream stream = DeserializeReadStream(bits).value(); ReadResult result = client.Read(stream); for (StatusOr<Row> const& row : result.Rows()) { if (row.ok()) { // Do something with row.value(); } } } int CreateSession(std::string const& project_id) { google::cloud::bigquery::ConnectionOptions options; google::cloud::bigquery::Client client( google::cloud::bigquery::MakeConnection(options)); google::cloud::StatusOr<std::vector<ReadStream>> res = client.ParallelRead( project_id, "bigquery-public-data:samples.shakespeare"); if (!res.ok()) { std::cerr << "Session creation failed with error: " << res.status() << "\n"; return EXIT_FAILURE; } for (ReadStream const& stream : res.value()) { std::cout << "Starting stream: " << stream.stream_name() << "\n"; ReadResult read_result = client.Read(stream); for (StatusOr<Row> const& row : read_result.Rows()) { if (!row.ok()) { std::cerr << "Error at row offset " << read_result.CurrentOffset() << ": " << row.status() << "\n"; return EXIT_FAILURE; } std::cout << " Current offset: " << read_result.CurrentOffset() << "; fraction consumed: " << read_result.FractionConsumed() << "\n"; } std::cout << "Done with stream: " << stream.stream_name() << "\n\n"; } return EXIT_SUCCESS; } } // namespace int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "You must provide a command and project ID as positional" << " arguments.\n"; return EXIT_FAILURE; } std::string cmd = argv[1]; std::string project_id = argv[2]; if (cmd == "SimpleRead") { SimpleRead(); } else if (cmd == "ParallelRead") { ParallelRead(); } else if (cmd == "PrintProgress") { return CreateSession(project_id); } else { std::cerr << "Unknown command: " << cmd << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
33.330709
80
0.649894
orinem
f01007c18ea7a7a5e19d354b4ac5cb158829bab5
1,725
hpp
C++
tau/TauEngine/include/dx/dx10/DX10GraphicsAccelerator.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
1
2020-04-22T04:07:01.000Z
2020-04-22T04:07:01.000Z
tau/TauEngine/include/dx/dx10/DX10GraphicsAccelerator.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
null
null
null
tau/TauEngine/include/dx/dx10/DX10GraphicsAccelerator.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
null
null
null
#pragma once #include "system/GraphicsAccelerator.hpp" #ifdef _WIN32 #include <dxgi.h> class TAU_DLL DX10GraphicsAccelerator final : public IGraphicsAccelerator { DELETE_CM(DX10GraphicsAccelerator); private: IDXGIAdapter* _dxgiAdapter; public: DX10GraphicsAccelerator(const DynString& vendor, const DynString& deviceName, const u64 videoMemory, const u64 systemMemory, const u64 sharedMemory, IDXGIAdapter* const dxgiAdapter) noexcept : IGraphicsAccelerator(vendor, deviceName, videoMemory, systemMemory, sharedMemory) , _dxgiAdapter(dxgiAdapter) { dxgiAdapter->AddRef(); } ~DX10GraphicsAccelerator() noexcept override { _dxgiAdapter->Release(); } [[nodiscard]] bool hasTessellationShaders() noexcept override { return false; } [[nodiscard]] bool hasGeometryShaders() noexcept override { return true; } [[nodiscard]] bool has64BitFloat() noexcept override { return false; } [[nodiscard]] bool has64BitInt() noexcept override { return false; } [[nodiscard]] bool has16BitInt() noexcept override { return false; } [[nodiscard]] RefDynArray<NullableRef<IGraphicsDisplay>> graphicsDisplays() noexcept override; }; class TAU_DLL DX10GraphicsAcceleratorBuilder final { DEFAULT_CONSTRUCT_PU(DX10GraphicsAcceleratorBuilder); DEFAULT_DESTRUCT(DX10GraphicsAcceleratorBuilder); DEFAULT_CM_PU(DX10GraphicsAcceleratorBuilder); private: IDXGIAdapter* _dxgiAdapter; public: void setAdapter(IDXGIAdapter* dxgiAdapter) noexcept { _dxgiAdapter = dxgiAdapter; } [[nodiscard]] NullableRef<DX10GraphicsAccelerator> build() const noexcept; }; #endif
37.5
99
0.721159
hyfloac
f016ad41b6a8146fca7c4e0b999da41d1706fa97
1,233
cpp
C++
src/ImageView/line_reader.cpp
miere43/imageview
a264fa44ba0140a8171913be763abdddbc531b4a
[ "Unlicense" ]
1
2021-06-24T12:19:41.000Z
2021-06-24T12:19:41.000Z
src/ImageView/line_reader.cpp
miere43/imageview
a264fa44ba0140a8171913be763abdddbc531b4a
[ "Unlicense" ]
null
null
null
src/ImageView/line_reader.cpp
miere43/imageview
a264fa44ba0140a8171913be763abdddbc531b4a
[ "Unlicense" ]
null
null
null
#include "line_reader.hpp" #include "error.hpp" void Line_Reader::set_string_builder(String_Builder* sb) { this->line = sb; } void Line_Reader::set_source(const char* source, int source_count) { this->source = source; this->source_count = source_count; this->index = 0; } bool Line_Reader::next_line() { E_VERIFY_NULL_R(source, false); E_VERIFY_R(source_count >= 0, false); E_VERIFY_NULL_R(line, false); E_VERIFY_R(index >= 0, false); if (index >= source_count) return false; for (int i = index; i < source_count; ++i) { char c = source[i]; if (c == '\r' && i + 1 < source_count && source[i + 1] == '\n') return set_line(i, 2); else if (c == '\n') return set_line(i, 1); else continue; } return set_line(source_count, 0); } bool Line_Reader::set_line(int i, int skip) { int base_index = index; int line_count = i - base_index; index = i + skip; if (!line->reserve(line_count + 1)) return false; for (int j = 0; j < line_count; ++j) line->buffer[j] = static_cast<wchar_t>(source[base_index + j]); line->buffer[line_count] = L'\0'; return true; }
22.017857
71
0.583942
miere43
f018339a65f00e68a0847433e3d5c05c6a368f41
6,596
cpp
C++
Source/Modules/MMOEngine/Scenario/ScLoginClient_SlaveImpl.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
27
2015-01-08T08:26:29.000Z
2019-02-10T03:18:05.000Z
Source/Modules/MMOEngine/Scenario/ScLoginClient_SlaveImpl.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
1
2017-04-05T02:02:14.000Z
2017-04-05T02:02:14.000Z
Source/Modules/MMOEngine/Scenario/ScLoginClient_SlaveImpl.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
17
2015-01-18T02:50:01.000Z
2019-02-08T21:00:53.000Z
/* Author: Gudakov Ramil Sergeevich a.k.a. Gauss Гудаков Рамиль Сергеевич Contacts: [ramil2085@mail.ru, ramil2085@gmail.com] See for more information LICENSE.md. */ #include "ScLoginClient_SlaveImpl.h" #include "ContextScLoginClient.h" #include "SessionManager.h" #include "Base.h" #include "Logger.h" #include "Events.h" #include "EnumMMO.h" #include "SrcEvent_ex.h" using namespace nsMMOEngine; using namespace nsLoginClientStruct; TScLoginClient_SlaveImpl::TScLoginClient_SlaveImpl( IScenario* pSc ) : TBaseScLoginClient( pSc ) { } //----------------------------------------------------------------------------- void TScLoginClient_SlaveImpl::RecvInherit( TDescRecvSession* pDesc ) { // защита от хака if( pDesc->dataSize < sizeof( THeader ) ) return; //======================================= THeader* pHeader = (THeader*) pDesc->data; switch( pHeader->from ) { case eClient: RecvFromClient( pDesc ); break; case eMaster: RecvFromMaster( pDesc ); break; default:BL_FIX_BUG(); } } //----------------------------------------------------------------------------- void TScLoginClient_SlaveImpl::Work( unsigned int time_ms ) { if( Context()->IsStateTimeExpired( time_ms ) == false ) return; auto errorType = Context()->GetCurrentStateErrorCode(); // ошибка на той стороне // непонятно в чем дело, но клиент сдох TErrorEvent event; event.code = (nsMMOEngine::ErrorCode)errorType; Context()->GetSE()->AddEventCopy( &event, sizeof( event ) ); End(); } //----------------------------------------------------------------------------- void TScLoginClient_SlaveImpl::RecvFromClient( TDescRecvSession* pDesc ) { THeader* pHeader = (THeader*) pDesc->data; switch( pHeader->subType ) { case eConnectToSlaveC2S: ConnectToSlaveC2S( pDesc ); break; default:BL_FIX_BUG(); } } //-------------------------------------------------------------- void TScLoginClient_SlaveImpl::RecvFromMaster( TDescRecvSession* pDesc ) { THeader* pHeader = (THeader*) pDesc->data; switch( pHeader->subType ) { case eInfoClientM2S: InfoClientM2S( pDesc ); break; case eCheckClientConnectM2S: CheckClientConnectM2S( pDesc ); break; case eDisconnectClientM2S: DisconnectClientM2S( pDesc ); break; default:BL_FIX_BUG(); } } //-------------------------------------------------------------- void TScLoginClient_SlaveImpl::ConnectToSlaveC2S( TDescRecvSession* pDesc ) { // защита от хака if( pDesc->dataSize < sizeof( THeaderConnectToSlaveC2S ) ) return; THeaderConnectToSlaveC2S* pHeader = (THeaderConnectToSlaveC2S*) pDesc->data; // существует ли вообще клиент с данным ключом, // то есть был ли добавлен на ожидание от Мастера данный Клиент // загрузить контекст для работы NeedContextByClientSessionByClientKey( pDesc->sessionID, pHeader->clientKey ); if( Context() == nullptr ) { // генерация ошибки GetLogger( STR_NAME_MMO_ENGINE )-> WriteF_time( "TScLoginClient_SlaveImpl::SetIsExistClientID() id client is not exist.\n" ); BL_FIX_BUG(); return; } // запомнить сессию Клиента SetID_SessionClientSlave( pDesc->sessionID ); // уведомить Мастера о запросе от клиента THeaderClientConnectS2M h; h.clientKey = Context()->GetClientKey();// указать какой клиент захотел соединиться mBP.Reset(); mBP.PushFront( (char*) &h, sizeof( h ) ); Context()->GetMS()->Send( GetID_SessionMasterSlave(), mBP ); Context()->SetCurrentStateWait( TContextScLoginClient::SlaveWaitMaster ); } //-------------------------------------------------------------- void TScLoginClient_SlaveImpl::InfoClientM2S( TDescRecvSession* pDesc ) { THeaderInfoClientM2S* pHeader = (THeaderInfoClientM2S*) pDesc->data; NeedContextByClientKey( pHeader->clientKey ); if( Context() == nullptr ) { BL_FIX_BUG(); return; } //-------------------------------------------- // начало сценария if( Context()->WasBegin() == false ) { // стартовали впервые Context()->SetWasBegin(); if( Begin() == false ) { // генерация ошибки GetLogger( STR_NAME_MMO_ENGINE )-> WriteF_time( "TScLoginClient_SlaveImpl::InfoClientM2S() scenario is not active.\n" ); BL_FIX_BUG(); return; } } // Если WasBegin==true - старт уже был, Мастер не дождался, Клиент остановил у себя сценарий // потом Клиент еще раз попытался авторизоваться, а Slave еще его ждет, т.е. это уже // вторая попытка войти. Что ж продолжим авторизацию. // запомнить сессию SetID_SessionMasterSlave( pDesc->sessionID ); Context()->SetClientKey( pHeader->clientKey ); // сформировать квитанцию mBP.Reset(); THeaderCheckInfoClientS2M h; h.clientKey = Context()->GetClientKey(); mBP.PushFront( (char*) &h, sizeof( h ) ); Context()->GetMS()->Send( GetID_SessionMasterSlave(), mBP ); Context()->SetCurrentStateWait( TContextScLoginClient::SlaveWaitClient ); } //-------------------------------------------------------------- void TScLoginClient_SlaveImpl::CheckClientConnectM2S( TDescRecvSession* pDesc ) { THeaderCheckClientConnectM2S* pHeader = (THeaderCheckClientConnectM2S*) pDesc->data; NeedContextByClientKey_SecondCallSlave( pHeader->clientKey ); if( Context() == nullptr ) return; //-------------------------------------------- // отсылка уведомления Developer Slave события Connect TConnectDownEvent* pEvent = new TConnectDownEvent; pEvent->sessionID = GetID_SessionClientSlave(); Context()->GetSE()->AddEventWithoutCopy<TConnectDownEvent>( pEvent ); // отослать клиенту уведомление THeaderCheckConnectToSlaveS2C h; mBP.Reset(); mBP.PushFront( (char*) &h, sizeof( h ) ); Context()->GetMS()->Send( GetID_SessionClientSlave(), mBP ); Context()->Accept(); Context()->SetCurrentStateWait( TContextScLoginClient::NoWait ); End(); } //-------------------------------------------------------------- void TScLoginClient_SlaveImpl::DisconnectClientM2S( TDescRecvSession* pDesc ) { THeaderDisconnectClientM2S* pH = (THeaderDisconnectClientM2S*) pDesc->data; NeedContextByClientKey( pH->clientKey ); if( Context() == nullptr ) { BL_FIX_BUG(); return; } Context()->Reject(); Context()->GetMS()->CloseSession( Context()->GetID_SessionClientSlave() ); End(); } //--------------------------------------------------------------
31.864734
97
0.604457
RamilGauss
f01aca7fa6f0bb169b4c16a05a9389286c367568
6,249
cpp
C++
library/src/blas1/rocblas_rotmg.cpp
rosenrodt/rocBLAS
e24058b09239814bea61b74bd736bcb6659d0915
[ "MIT" ]
null
null
null
library/src/blas1/rocblas_rotmg.cpp
rosenrodt/rocBLAS
e24058b09239814bea61b74bd736bcb6659d0915
[ "MIT" ]
1
2019-09-26T01:51:09.000Z
2019-09-26T18:09:56.000Z
library/src/blas1/rocblas_rotmg.cpp
mahmoodw/rocBLAS
53b1271e4881ef7473b78e8783e4d55740e9b933
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright 2016-2019 Advanced Micro Devices, Inc. * ************************************************************************ */ #include "handle.h" #include "logging.h" #include "rocblas.h" #include "utility.h" namespace { template <typename T> __device__ __host__ void rotmg_calc(T& d1, T& d2, T& x1, const T& y1, T* param) { const T gam = 4096; const T gamsq = gam * gam; const T rgamsq = 1 / gamsq; T flag = -1; T h11 = 0, h21 = 0, h12 = 0, h22 = 0; if(d1 < 0) { d1 = d2 = x1 = 0; } else { T p2 = d2 * y1; if(p2 == 0) { flag = -2; param[0] = flag; return; } T p1 = d1 * x1; T q2 = p2 * y1; T q1 = p1 * x1; if(rocblas_abs(q1) > rocblas_abs(q2)) { h21 = -y1 / x1; h12 = p2 / p1; T u = 1 - h12 * h21; if(u > 0) { flag = 0; d1 /= u; d2 /= u; x1 *= u; } } else { if(q2 < 0) { d1 = d2 = x1 = 0; } else { flag = 1; h11 = p1 / p2; h22 = x1 / y1; T u = 1 + h11 * h22; T temp = d2 / u; d2 = d1 / u; d1 = temp; x1 = y1 * u; } } if(d1 != 0) { while((d1 <= rgamsq) || (d1 >= gamsq)) { if(flag == 0) { h11 = h22 = 1; flag = -1; } else { h21 = -1; h12 = 1; flag = -1; } if(d1 <= rgamsq) { d1 *= gamsq; x1 /= gam; h11 /= gam; h12 /= gam; } else { d1 /= gamsq; x1 *= gam; h11 *= gam; h12 *= gam; } } } if(d2 != 0) { while((rocblas_abs(d2) <= rgamsq) || (rocblas_abs(d2) >= gamsq)) { if(flag == 0) { h11 = h22 = 1; flag = -1; } else { h21 = -1; h12 = 1; flag = -1; } if(rocblas_abs(d2) <= rgamsq) { d2 *= gamsq; h21 /= gam; h22 /= gam; } else { d2 /= gamsq; h21 *= gam; h22 *= gam; } } } } if(flag < 0) { param[1] = h11; param[2] = h21; param[3] = h12; param[4] = h22; } else if(flag == 0) { param[2] = h21; param[3] = h12; } else { param[1] = h11; param[4] = h22; } param[0] = flag; } template <typename T> __global__ void rotmg_kernel(T* d1, T* d2, T* x1, const T* y1, T* param) { rotmg_calc(*d1, *d2, *x1, *y1, param); } template <typename> constexpr char rocblas_rotmg_name[] = "unknown"; template <> constexpr char rocblas_rotmg_name<float>[] = "rocblas_srotmg"; template <> constexpr char rocblas_rotmg_name<double>[] = "rocblas_drotmg"; template <class T> rocblas_status rocblas_rotmg(rocblas_handle handle, T* d1, T* d2, T* x1, const T* y1, T* param) { if(!handle) return rocblas_status_invalid_handle; auto layer_mode = handle->layer_mode; if(layer_mode & rocblas_layer_mode_log_trace) log_trace(handle, rocblas_rotmg_name<T>, d1, d2, x1, y1, param); if(layer_mode & rocblas_layer_mode_log_bench) log_trace(handle, "./rocblas-bench -f rotmg -r", rocblas_precision_string<T>); if(layer_mode & rocblas_layer_mode_log_profile) log_profile(handle, rocblas_rotmg_name<T>); if(!d1 || !d2 || !x1 || !y1 || !param) return rocblas_status_invalid_pointer; RETURN_ZERO_DEVICE_MEMORY_SIZE_IF_QUERIED(handle); hipStream_t rocblas_stream = handle->rocblas_stream; if(rocblas_pointer_mode_device == handle->pointer_mode) { hipLaunchKernelGGL(rotmg_kernel, 1, 1, 0, rocblas_stream, d1, d2, x1, y1, param); } else { RETURN_IF_HIP_ERROR(hipStreamSynchronize(rocblas_stream)); rotmg_calc(*d1, *d2, *x1, *y1, param); } return rocblas_status_success; } } // namespace /* * =========================================================================== * C wrapper * =========================================================================== */ extern "C" { ROCBLAS_EXPORT rocblas_status rocblas_srotmg( rocblas_handle handle, float* d1, float* d2, float* x1, const float* y1, float* param) { return rocblas_rotmg(handle, d1, d2, x1, y1, param); } ROCBLAS_EXPORT rocblas_status rocblas_drotmg( rocblas_handle handle, double* d1, double* d2, double* x1, const double* y1, double* param) { return rocblas_rotmg(handle, d1, d2, x1, y1, param); } } // extern "C"
28.148649
99
0.351416
rosenrodt
f021a2c5758d89932548211b571059623e22f2ee
511
hpp
C++
src/event_handler/event_thread.hpp
Morilli/LeagueModel
a364206a9115ffe7eea31bbddf94a646d13552da
[ "MIT" ]
26
2018-12-09T15:35:02.000Z
2021-05-02T11:36:19.000Z
src/event_handler/event_thread.hpp
Morilli/LeagueModel
a364206a9115ffe7eea31bbddf94a646d13552da
[ "MIT" ]
19
2018-12-09T20:14:36.000Z
2021-11-10T07:04:52.000Z
src/event_handler/event_thread.hpp
Morilli/LeagueModel
a364206a9115ffe7eea31bbddf94a646d13552da
[ "MIT" ]
5
2018-11-14T10:41:56.000Z
2022-02-19T22:22:32.000Z
#pragma once #include <thread> #define MAX_EVENT_THREAD_EVENT_COUNT 64 class EventHandler; class Event; class EventThread { private: enum StateType { NoState, Idle, Running, ForceQuit, ThreadEnded }; friend class EventHandler; protected: EventThread(); ~EventThread(); void Detach(); void Join(); void AddToQueue(Event* a_Event); Event* m_Queue[MAX_EVENT_THREAD_EVENT_COUNT]; size_t m_QueuePlaceIterator = 0; std::thread* m_Thread; StateType m_State; private: void Thread(); };
12.775
46
0.733855
Morilli
f02b5ddb7270d9ce2b5d296d808c47dee529bbf8
40,026
cpp
C++
scripts/DBScripts.cpp
mpforums/RenSharp
5b3fb8bff2a1772a82a4148bcf3e1265a11aa097
[ "Apache-2.0" ]
1
2021-10-04T02:34:33.000Z
2021-10-04T02:34:33.000Z
scripts/DBScripts.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
9
2019-07-03T19:19:59.000Z
2020-03-02T22:00:21.000Z
scripts/DBScripts.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
2
2019-08-14T08:37:36.000Z
2020-09-29T06:44:26.000Z
#include "General.h" #include "engine_tt.h" #include "engine_def.h" #include "VehicleGameObjDef.h" #include "BeaconGameObjDef.h" #include "TeamPurchaseSettingsDefClass.h" #include "PurchaseSettingsDefClass.h" #include "PowerupGameObj.h" #include "PowerupGameObjDef.h" #include "SoldierGameObj.h" #include "VehicleGameObj.h" #include "BuildingGameObj.h" #include "CommandLineParser.h" #include "WeaponClass.h" #include "BeaconGameObj.h" #include "weaponmgr.h" #include "GameObjManager.h" #include "MoveablePhysClass.h" #include "DB_General.h" #include "engine_tdb.h" #include "engine_obj.h" #include "engine_script.h" #include "engine_player.h" #include "engine_phys.h" #include "engine_game.h" #include "engine_obj2.h" #include "engine_dmg.h" class DB_Captureable_Silo : public ScriptImpClass { bool Play_Damage; bool Play_Killed; bool Upgraded; const char *Building; float amount; int UpgradeID; void Created(GameObject *obj) { Upgraded=false; Building = Get_Translated_Preset_Name(obj); Play_Damage = false; Play_Killed = false; Set_Object_Type(obj, Get_Int_Parameter("Team")); amount = Get_Float_Parameter("Amount"); UpgradeID=Get_Int_Parameter("UpgradeID"); if(!UpgradeID) UpgradeID=1; Attach_Script_Once(obj,"DB_Research_Listener",""); if(UpgradeComplete.Exists(UpgradeID)) { amount = Get_Float_Parameter("UpgradeAmount"); Upgraded=true; } if(Get_Object_Type(obj)!=-2) { Attach_Script_Once_V(obj,"dp88_buildingScripts_functionMoneyTrickle","%f",amount); Play_Killed = true; Play_Damage = true; } } void Custom(GameObject *obj, int message, int param, GameObject *sender) { if (!Upgraded && message == Research_Technology::UPGRADE_INFANTRY_ARMOR_CUSTOM && param==UpgradeID) { Upgraded=true; amount=Get_Float_Parameter("UpgradeAmount"); if(Is_Script_Attached(obj,"dp88_buildingScripts_functionMoneyTrickle")) { Remove_Script(obj,"dp88_buildingScripts_functionMoneyTrickle"); Attach_Script_V(obj,"dp88_buildingScripts_functionMoneyTrickle","%f",amount); } } } void Detach(GameObject *obj) { if (Exe != 4) { delete[] this->Building; this->Building = 0; } } void Damaged(GameObject *obj, GameObject *damager, float damage) { if (damage < 0.0f) { if (Get_Object_Type(obj) == -2) { if (Commands->Get_Health(obj) == Commands->Get_Max_Health(obj)) { Set_Object_Type(obj,Get_Object_Type(damager)); if (Get_Object_Type(obj) == 0) { Send_Message_Team(0,255,0,0,StringClass::getFormattedString("Nod has captured the %s!", Building)); Attach_Script_Once_V(obj,"dp88_buildingScripts_functionMoneyTrickle","%f",amount); } else if (Get_Object_Type(obj) == 1) { Send_Message_Team(1,255,201,0,StringClass::getFormattedString("GDI has captured the %s!", Building)); Attach_Script_Once_V(obj,"dp88_buildingScripts_functionMoneyTrickle","%f",amount); } Play_Killed = true; Play_Damage = true; } } } if (damage > Commands->Get_Health(obj)) { if (Get_Object_Type(obj) == 0) { if (Play_Killed) { Send_Message(255,255,255,StringClass::getFormattedString("The %s was destroyed by %s (%s)", Building, Get_Player_Name(damager), Get_Team_Name(Get_Object_Type(damager)))); Play_Killed = false; Play_Damage = false; Remove_Script(obj,"dp88_buildingScripts_functionMoneyTrickle"); } } else if (Get_Object_Type(obj) == 1) { if (Play_Killed) { Send_Message(255,255,255,StringClass::getFormattedString("The %s was destroyed by %s (%s)", Building, Get_Player_Name(damager), Get_Team_Name(Get_Object_Type(damager)))); Play_Killed = false; Play_Damage = false; Remove_Script(obj,"dp88_buildingScripts_functionMoneyTrickle"); } } Set_Object_Type(obj,-2); Commands->Set_Health(obj,1.0f); } } }; class DB_Helipad_Captureable : public ScriptImpClass { bool Play_Damage; bool Play_Killed; const char *Building; void Created(GameObject *obj) { Commands->Start_Timer(obj,this,5.0f,333); Building = Get_Translated_Preset_Name(obj); Play_Damage = false; Play_Killed = false; Commands->Set_Animation_Frame(obj,Get_Model(obj),0); Set_Object_Type(obj, Get_Int_Parameter("Team")); if(Get_Object_Type(obj)!=-2) { Play_Killed = true; Play_Damage = true; } if(!obj->As_VehicleGameObj()) Attach_Script_Once(obj,"SH_CustomCollisionGroup","15"); } void Custom(GameObject* obj, int type, int param, GameObject* sender) { if(type == 826455) { if(!Has_Timer(obj,this,123)) { if(param == 0) { Commands->Set_Animation_Frame(obj,Get_Model(obj),2); } else if(param == 1) { Commands->Set_Animation_Frame(obj,Get_Model(obj),4); } } else Stop_Timer2(obj,this,123); Commands->Start_Timer(obj,this,2.1f,123); } } void Timer_Expired(GameObject *obj, int number) { if(number == 123) { if(Get_Object_Type(obj) == 0) Commands->Set_Animation_Frame(obj,Get_Model(obj),1); else if(Get_Object_Type(obj) == 1) Commands->Set_Animation_Frame(obj,Get_Model(obj),3); else Commands->Set_Animation_Frame(obj,Get_Model(obj),0); } } void Damaged(GameObject *obj, GameObject *damager, float damage) { if (damage > Commands->Get_Health(obj)) { if (Get_Object_Type(obj) == 0) { if (Play_Killed) { Send_Message(255,255,255,StringClass::getFormattedString("The %s was destroyed by %s (%s)", Building, Get_Player_Name(damager), Get_Team_Name(Get_Object_Type(damager)))); Play_Killed = false; Play_Damage = false; Commands->Set_Animation_Frame(obj,Get_Model(obj),0); } } else if (Get_Object_Type(obj) == 1) { if (Play_Killed) { Send_Message(255,255,255,StringClass::getFormattedString("The %s was destroyed by %s (%s)", Building, Get_Player_Name(damager), Get_Team_Name(Get_Object_Type(damager)))); Play_Killed = false; Play_Damage = false; Commands->Set_Animation_Frame(obj,Get_Model(obj),0); } } Set_Object_Type(obj,-2); Commands->Set_Health(obj,1.0f); } if (damage < 0.0f) { if (Get_Object_Type(obj) == -2) { if (Commands->Get_Health(obj) == Commands->Get_Max_Health(obj)) { Set_Object_Type(obj,Get_Object_Type(damager)); if (Get_Object_Type(obj) == 0) { Send_Message_Team(0,255,0,0,StringClass::getFormattedString("Nod has captured the %s!",Building)); Commands->Set_Animation_Frame(obj,Get_Model(obj),1); } else if (Get_Object_Type(obj) == 1) { Send_Message_Team(1,255,201,0,StringClass::getFormattedString("GDI has captured the %s!",Building)); Commands->Set_Animation_Frame(obj,Get_Model(obj),3); } Play_Killed = true; Play_Damage = true; } } } } void Detach(GameObject *obj) { if (Exe != 4) { delete[] this->Building; this->Building = 0; } } }; class DB_Capturable_repairpad : public ScriptImpClass { bool Play_Damage; bool Play_Killed; const char *Building; int zoneid; void Created(GameObject *obj) { zoneid = Get_Int_Parameter("RepairZoneID"); Commands->Start_Timer(obj,this,5.0f,333); Play_Damage = false; Play_Killed = false; Commands->Set_Animation_Frame(obj,Get_Model(obj),0); Set_Object_Type(obj, Get_Int_Parameter("Team")); if(Get_Object_Type(obj)!=-2) { Commands->Set_Health(obj, Commands->Get_Max_Health(obj)); Commands->Set_Shield_Strength(obj, Commands->Get_Max_Shield_Strength(obj)); Play_Killed = true; Play_Damage = true; Attach_Script_Once_V(Commands->Find_Object(zoneid), "JFW_Sell_Zone", "%i",Get_Object_Type(obj)); } if(!obj->As_VehicleGameObj()) Attach_Script_Once(obj,"SH_CustomCollisionGroup","15"); Building = Get_Translated_Preset_Name(obj); } void Custom(GameObject* obj, int type, int param, GameObject* sender) { if(type == 826455) { if(!Has_Timer(obj,this,123)) { if(param == 0) { Commands->Set_Animation_Frame(obj,Get_Model(obj),2); } else if(param == 1) { Commands->Set_Animation_Frame(obj,Get_Model(obj),4); } } else Stop_Timer2(obj,this,123); Commands->Start_Timer(obj,this,1.1f,123); } } void Timer_Expired(GameObject *obj, int number) { if(number == 123) { if(Get_Object_Type(obj) == 0) Commands->Set_Animation_Frame(obj,Get_Model(obj),1); else if(Get_Object_Type(obj) == 1) Commands->Set_Animation_Frame(obj,Get_Model(obj),3); else Commands->Set_Animation_Frame(obj,Get_Model(obj),0); } } void Damaged(GameObject *obj, GameObject *damager, float damage) { if (damage > Commands->Get_Health(obj)) { if (Get_Object_Type(obj) == 0) { if (Play_Killed) { Send_Message(255,255,255,StringClass::getFormattedString("The %s was destroyed by %s (%s)", Building, Get_Player_Name(damager), Get_Team_Name(Get_Object_Type(damager)))); Play_Killed = false; Play_Damage = false; Remove_Script(Commands->Find_Object(zoneid), "JFW_Sell_Zone"); Commands->Set_Animation_Frame(obj,Get_Model(obj),0); } } else if (Get_Object_Type(obj) == 1) { if (Play_Killed) { Send_Message(255,255,255,StringClass::getFormattedString("The %s was destroyed by %s (%s)", Building, Get_Player_Name(damager), Get_Team_Name(Get_Object_Type(damager)))); Play_Killed = false; Play_Damage = false; Remove_Script(Commands->Find_Object(zoneid), "JFW_Sell_Zone"); Commands->Set_Animation_Frame(obj,Get_Model(obj),0); } } Set_Object_Type(obj,-2); Commands->Set_Health(obj,1.0f); } if (damage < 0.0f) { if (Get_Object_Type(obj) == -2) { if (Commands->Get_Health(obj) == Commands->Get_Max_Health(obj)) { Set_Object_Type(obj,Get_Object_Type(damager)); if (Get_Object_Type(obj) == 0) { Send_Message_Team(0,255,0,0,StringClass::getFormattedString("Nod has captured the %s!", Building)); Attach_Script_Once(Commands->Find_Object(zoneid), "JFW_Sell_Zone", "0"); Commands->Set_Animation_Frame(obj,Get_Model(obj),1); } else if (Get_Object_Type(obj) == 1) { Send_Message_Team(1,255,201,0,StringClass::getFormattedString("GDI has captured the %s!", Building)); Attach_Script_Once(Commands->Find_Object(zoneid), "JFW_Sell_Zone", "1"); Commands->Set_Animation_Frame(obj,Get_Model(obj),3); } Play_Killed = true; Play_Damage = true; } } } } void Detach(GameObject *obj) { if (Exe != 4) { delete[] this->Building; this->Building = 0; } } }; class DB_Capturable_object : public ScriptImpClass { bool Play_Damage; bool Play_Killed; const char *Building; void Created(GameObject *obj) { Commands->Start_Timer(obj,this,5.0f,333); Set_Object_Type(obj, Get_Int_Parameter("Owner")); Building = Get_Translated_Preset_Name(obj); Play_Damage = false; Play_Killed = false; if(Get_Object_Type(obj)!=-2) { Play_Killed = true; Play_Damage = true; } if(!obj->As_VehicleGameObj()) Attach_Script_Once(obj,"SH_CustomCollisionGroup","15"); } void Damaged(GameObject *obj, GameObject *damager, float damage) { if (damage > Commands->Get_Health(obj)) { if (Get_Object_Type(obj) == 0) { if (Play_Killed) { if(Commands->Is_A_Star(damager)) { Send_Message(255,255,255,StringClass::getFormattedString("The Nod %s was destroyed by %s (%s)", Building, Get_Player_Name(damager), Get_Team_Name(Get_Object_Type(damager)))); //DALogManager::Write_Log("_INFO","The Nod %s was destroyed by %s (%s)", Building, Get_Player_Name(damager), Get_Team_Name(Get_Object_Type(damager))); } else { Send_Message(255,255,255,StringClass::getFormattedString("The Nod %s was destroyed by a %s (%s)", Building, Get_Translated_Preset_Name(damager), Get_Team_Name(Get_Object_Type(damager)))); //DALogManager::Write_Log("_INFO","The Nod %s was destroyed by a %s", Building, DATranslationManager::Translate_With_Team_Name(damager)); } Play_Killed = false; Play_Damage = false; Commands->Action_Reset(obj,200); } } else if (Get_Object_Type(obj) == 1) { if (Play_Killed) { if(Commands->Is_A_Star(damager)) { Send_Message(255,255,255,StringClass::getFormattedString("The GDI %s was destroyed by %s (%s)", Building, Get_Player_Name(damager), Get_Team_Name(Get_Object_Type(damager)))); //DALogManager::Write_Log("_INFO","The GDI %s was destroyed by %s (%s)", Building, Get_Player_Name(damager), Get_Team_Name(Get_Object_Type(damager))); } else { Send_Message(255,255,255,StringClass::getFormattedString("The GDI %s was destroyed by a %s (%s)", Building, Get_Translated_Preset_Name(damager), Get_Team_Name(Get_Object_Type(damager)))); //DALogManager::Write_Log("_INFO","The GDI %s was destroyed by a %s", Building, DATranslationManager::Translate_With_Team_Name(damager)); } Play_Killed = false; Play_Damage = false; Commands->Action_Reset(obj,200); } } Set_Object_Type(obj,-2); Commands->Set_Health(obj,1.0f); } if (damage < 0.0f) { if (Get_Object_Type(obj) == -2) { if (Commands->Get_Health(obj) == Commands->Get_Max_Health(obj)) { Set_Object_Type(obj,Get_Object_Type(damager)); if (Get_Object_Type(obj) == 0) { Send_Message_Team(0,255,0,0,StringClass::getFormattedString("Nod has captured the %s!",Building)); //DALogManager::Write_Log("_INFO","Nod has captured the %s!",Building); } else if (Get_Object_Type(obj) == 1) { Send_Message_Team(1,255,201,0,StringClass::getFormattedString("GDI has captured the %s!",Building)); //DALogManager::Write_Log("_INFO","GDI has captured the %s!",Building); } Play_Killed = true; Play_Damage = true; } } } } void Detach(GameObject *obj) { if (Exe != 4) { delete[] this->Building; this->Building = 0; } } }; class DB_Powerup_Buy_Poke_Sound : public ScriptImpClass { bool Do_Poke_Stuff; void DB_Powerup_Buy_Poke_Sound::Created(GameObject *obj) { Do_Poke_Stuff = true; Commands->Enable_HUD_Pokable_Indicator(obj, true); } void DB_Powerup_Buy_Poke_Sound::Poked(GameObject *obj,GameObject *poker) { if (Do_Poke_Stuff) { Do_Poke_Stuff = false; Commands->Start_Timer(obj,this,5.0f,12345); if (!Is_Building_Dead(Commands->Find_Object(Get_Int_Parameter("BuildingID")))) { const char *preset; int x; int cost; x = Get_Int_Parameter("Team"); if (Get_Object_Type(poker) != x) { Send_Message_Player(poker,255,255,255,"Access Denied!"); Create_2D_WAV_Sound_Player(poker,Get_Parameter("SoundDenied")); return; } preset = Get_Parameter("Preset"); cost = Get_Int_Parameter("Cost"); if (cost <= Commands->Get_Money(poker)) { cost = -cost; Commands->Give_Money(poker,(float)cost,0); Grant_Powerup(poker,preset); Create_2D_WAV_Sound_Player(poker,Get_Parameter("SoundGranted")); Send_Message_Player(poker,255,255,255,"Purchase request granted!"); } else { Create_2D_WAV_Sound_Player(poker,Get_Parameter("SoundDenied")); Send_Message_Player(poker,255,255,255,"Access Denied! Insufficient Funds!"); } } else { const char *Building = Get_Translated_Preset_Name(Commands->Find_Object(Get_Int_Parameter("BuildingID"))); Send_Message_Player(poker,255,255,255,StringClass::getFormattedString("Sorry the %s is dead. Purchase denied.",Building)); Create_2D_WAV_Sound_Player(poker,Get_Parameter("SoundDenied")); } Commands->Enable_HUD_Pokable_Indicator(obj, false); } } void DB_Powerup_Buy_Poke_Sound::Timer_Expired(GameObject *obj, int number) { if (number == 12345) { Do_Poke_Stuff = true; Commands->Enable_HUD_Pokable_Indicator(obj, true); } } }; void PlayInsufficientFunds(GameObject *obj) { if(Get_Player_Type(obj)==0) Create_2D_WAV_Sound_Player (obj, "m00evan_dsgn0024i1evan_snd.wav"); if(Get_Player_Type(obj)==1) Create_2D_WAV_Sound_Player (obj, "m00evag_dsgn0028i1evag_snd.wav"); } class DB_capturable_Helipad_Terminal : public ScriptImpClass { bool Do_Poke_Stuff; ReferencerClass building; void DB_capturable_Helipad_Terminal::Created(GameObject *obj) { Do_Poke_Stuff = true; Commands->Enable_HUD_Pokable_Indicator(obj, true); Commands->Set_Animation_Frame(obj,Get_Model(obj),0); Commands->Start_Timer(obj,this,0.5f,1); building = Commands->Find_Object(Get_Int_Parameter("BuildingID")); } void DB_capturable_Helipad_Terminal::Poked(GameObject *obj,GameObject *poker) { if (Do_Poke_Stuff) { Do_Poke_Stuff = false; Commands->Start_Timer(obj,this,5.0f,12345); if (Get_Object_Type(building)==Get_Object_Type(poker)) { const char *preset; float cost; int spawnlocation; Vector3 location; bool powered=true; cost=Get_Float_Parameter("Cost"); preset = Get_Parameter("Preset"); spawnlocation = Get_Int_Parameter("SpawnLocation"); location = Commands->Get_Position(Commands->Find_Object(spawnlocation)); if(!Is_Base_Powered(Get_Object_Type(poker))) { powered=false; cost=cost*1.5f; } if (cost <= Commands->Get_Money(poker)) { cost = -cost; Commands->Give_Money(poker,(float)cost,0); GameObject *Purchase = Commands->Create_Object(preset, location); if(Purchase) Commands->Set_Facing(Purchase, Commands->Get_Facing(Commands->Find_Object(spawnlocation))); if(Purchase && Purchase->As_VehicleGameObj()) { Set_Object_Type(Purchase,Get_Object_Type(poker)); Purchase->As_VehicleGameObj()->Lock_Vehicle(poker,45.0f); } Send_Message_Team(Get_Object_Type(poker),160,160,255,StringClass::getFormattedString("Building: %s - %s",Get_Translated_Definition_Name(preset),Get_Player_Name(poker))); Send_Message_Player(poker,178,178,178,"Purchase request granted!"); Stop_Timer2(obj,this,1); DB_capturable_Helipad_Terminal::Timer_Expired(obj, 1); } else { PlayInsufficientFunds(poker); if(!powered) Send_Message_Player(poker,255,255,255,"Access Denied! Insufficient Funds! (Power Down - Cost x 1.5)"); else Send_Message_Player(poker,255,255,255,"Access Denied! Insufficient Funds!"); } } else { const char *Building = Get_Translated_Preset_Name(building); Send_Message_Player(poker,255,255,255,StringClass::getFormattedString("Sorry, the %s is not captured. Purchase denied.",Building)); } Commands->Enable_HUD_Pokable_Indicator(obj, false); } } void DB_capturable_Helipad_Terminal::Timer_Expired(GameObject *obj, int number) { if(number == 1) { int team = Get_Object_Type(building); int frame = 0; if(team == 1) { if(Do_Poke_Stuff) { if(Is_Base_Powered(1)) frame=7; else frame=5; } else { if(Is_Base_Powered(1)) frame=8; else frame=6; } if(Get_Object_Type(obj) != -2) { Set_Object_Type(obj,1); } } else if (team == 0) { if(Do_Poke_Stuff) { if(Is_Base_Powered(0)) frame=3; else frame=1; } else { if(Is_Base_Powered(0)) frame=4; else frame=2; } if(Get_Object_Type(obj) != 0) { Set_Object_Type(obj,0); } } else { frame=0; if(Get_Object_Type(obj) != -2) { Set_Object_Type(obj,-2); } } if(Get_Animation_Frame(obj) != frame) { Commands->Set_Animation_Frame(obj,Get_Model(obj),frame); } Commands->Start_Timer(obj,this,0.5f,1); } else if (number == 12345) { Do_Poke_Stuff = true; Commands->Enable_HUD_Pokable_Indicator(obj, true); } } }; class DB_capturable_WF_Terminal : public ScriptImpClass { bool Do_Poke_Stuff; void DB_capturable_WF_Terminal::Created(GameObject *obj) { Do_Poke_Stuff = true; Commands->Enable_HUD_Pokable_Indicator(obj, true); } void DB_capturable_WF_Terminal::Poked(GameObject *obj,GameObject *poker) { if (Do_Poke_Stuff) { Do_Poke_Stuff = false; Commands->Start_Timer(obj,this,5.0f,12345); if (Get_Object_Type(Commands->Find_Object(Get_Int_Parameter("BuildingID")))==Get_Object_Type(poker)) { const char *preset; int cost; int spawnlocation; Vector3 location; cost=Get_Int_Parameter("Cost"); preset = Get_Parameter("Preset"); spawnlocation = Get_Int_Parameter("SpawnLocation"); location = Commands->Get_Position(Commands->Find_Object(spawnlocation)); if (cost <= Commands->Get_Money(poker)) { cost = -cost; Commands->Give_Money(poker,(float)cost,0); GameObject *vehicle = Commands->Create_Object(preset, location); if(vehicle) Commands->Set_Facing(vehicle, Commands->Get_Facing(Commands->Find_Object(spawnlocation))); if(vehicle->As_VehicleGameObj()) { Set_Object_Type(vehicle,Get_Object_Type(poker)); vehicle->As_VehicleGameObj()->Lock_Vehicle(poker,45.0f); //if(!vehicle->As_PhysicalGameObj()->Peek_Physical_Object()->As_MoveablePhysClass()->Can_Teleport(vehicle->As_PhysicalGameObj()->Get_Transform())) //Fix_Stuck_Object(vehicle->As_VehicleGameObj(),15); } Send_Message_Player(poker,255,255,255,"Purchase request granted!"); } else { PlayInsufficientFunds(poker); Send_Message_Player(poker,255,255,255,"Access Denied! Insufficient Funds!"); } } else { const char *Building = Get_Translated_Preset_Name(Commands->Find_Object(Get_Int_Parameter("BuildingID"))); Send_Message_Player(poker,255,255,255,StringClass::getFormattedString("Sorry the %s is not captured. Purchase denied.",Building)); } Commands->Enable_HUD_Pokable_Indicator(obj, false); } } void DB_capturable_WF_Terminal::Timer_Expired(GameObject *obj, int number) { if (number == 12345) { Do_Poke_Stuff = true; Commands->Enable_HUD_Pokable_Indicator(obj, true); } } }; class DB_capturable_helipadzone_reload : public ScriptImpClass { void DB_capturable_helipadzone_reload::Entered(GameObject *obj, GameObject *enterer) { if(Commands->Find_Object(Get_Int_Parameter("BuildingID"))) if (Get_Object_Type(enterer) == Get_Object_Type(Commands->Find_Object(Get_Int_Parameter("BuildingID"))) && enterer->As_VehicleGameObj() && Is_VTOL(enterer)) { if(!Has_Timer(obj,this,enterer->Get_ID())) Commands->Start_Timer(obj, this, 1, Commands->Get_ID(enterer)); Commands->Send_Custom_Event(obj,Commands->Find_Object(Get_Int_Parameter("BuildingID")),826455,Get_Object_Type(enterer),0); } } void DB_capturable_helipadzone_reload::Timer_Expired(GameObject *obj, int number) { Vector3 pos1; Vector3 pos2; float distance; pos1 = Commands->Get_Position(obj); pos2 = Commands->Get_Position(Commands->Find_Object(number)); distance = Commands->Get_Distance(pos1,pos2); if ((distance <= 10.0) && (Get_Vehicle_Driver(Commands->Find_Object(number)))) //reloads vehicle up to 10m from zone center { GameObject *Aircraft = Commands->Find_Object(number); if(Aircraft && Is_VTOL(Aircraft)) { Commands->Give_PowerUp(Commands->Find_Object(number),Get_Parameter("ReloadPreset"),false); //WeaponClass *weapon = Aircraft->As_VehicleGameObj()->Get_Weapon_Bag()->Get_Weapon(); if(Get_Vehicle_Driver(Aircraft)) { Create_2D_WAV_Sound_Player(Get_Vehicle_Driver(Aircraft),"powerup_ammo.wav"); } /* if(weapon) { weapon->Set_Clip_Rounds(weapon->Get_Definition()->ClipSize); } */ Commands->Send_Custom_Event(obj,Commands->Find_Object(Get_Int_Parameter("BuildingID")),826455,Get_Object_Type(Aircraft),0); } Commands->Start_Timer(obj, this, 2, number); } } }; class DB_capturable_Repairzone : public ScriptImpClass { void DB_capturable_Repairzone::Entered(GameObject *obj,GameObject *enterer) { int Player_Type = Get_Object_Type(Commands->Find_Object(Get_Int_Parameter("BuildingID"))); if (CheckPlayerType(enterer,Player_Type) || Commands->Find_Object(Get_Int_Parameter("BuildingID"))==enterer || Player_Type==-2) { return; } if (enterer->As_VehicleGameObj() && !enterer->As_VehicleGameObj()->Is_Turret()) { if(Get_Vehicle_Driver(enterer)) { if(Player_Type==0) Create_2D_WAV_Sound_Player(Get_Vehicle_Driver(enterer),"m00evan_dsgn0015i1evan_snd.wav"); else Create_2D_WAV_Sound_Player(Get_Vehicle_Driver(enterer),"m00evag_dsgn0018i1evag_snd.wav"); unsigned int Red = 0,Blue = 0,Green = 0; Get_Team_Color(Get_Object_Type(Get_Vehicle_Driver(enterer)),&Red,&Green,&Blue); Send_Message_Player(Get_Vehicle_Driver(enterer),Red,Green,Blue,"Repairing..."); } if(Get_Hitpoints(enterer)!=Get_Max_Hitpoints(enterer)) Commands->Send_Custom_Event(obj,Commands->Find_Object(Get_Int_Parameter("BuildingID")),826455,Player_Type,0); if(!Has_Timer(obj,this,enterer->Get_ID())) Commands->Start_Timer(obj,this,1.0,Commands->Get_ID(enterer)); } } void DB_capturable_Repairzone::Timer_Expired(GameObject *obj,int number) { Vector3 pos1; Vector3 pos2; float distance; GameObject *repairunit = Commands->Find_Object(number); if(repairunit) { pos1 = Commands->Get_Position(obj); pos2 = Commands->Get_Position(repairunit); distance = Commands->Get_Distance(pos1,pos2); int Player_Type = Get_Object_Type(Commands->Find_Object(Get_Int_Parameter("BuildingID"))); if (distance <= 10 && Player_Type!=-2) { if(Get_Hitpoints(repairunit)!=Get_Max_Hitpoints(repairunit)) Commands->Send_Custom_Event(obj,Commands->Find_Object(Get_Int_Parameter("BuildingID")),826455,Player_Type,0); Commands->Apply_Damage(repairunit,-50,"None",NULL); Commands->Start_Timer(obj,this,1.0,number); } } } }; class DB_Capturable_Infantry_Terminal : public ScriptImpClass { void Created(GameObject *obj); void Poked(GameObject *obj, GameObject *poker); void Timer_Expired(GameObject *obj, int number); int InfantryFactoryID; int Team; bool Allowpoke; float Cost; const char *Preset; }; void DB_Capturable_Infantry_Terminal::Created(GameObject *obj) { Commands->Enable_HUD_Pokable_Indicator(obj, true); InfantryFactoryID = Get_Int_Parameter("InfantryFactoryID"); Cost = Get_Float_Parameter("Cost"); Preset = Get_Parameter("Preset"); Team = Get_Object_Type(Commands->Find_Object(InfantryFactoryID)); Allowpoke = true; Set_Object_Type(obj, Team); Commands->Start_Timer(obj, this, 10.0f, 102031);//set the team of the console to that of the associated helipad } void DB_Capturable_Infantry_Terminal::Poked(GameObject *obj, GameObject *poker) { if (Allowpoke) { Commands->Enable_HUD_Pokable_Indicator(obj, false); Team = Get_Object_Type(Commands->Find_Object(InfantryFactoryID));//request the helipad team again and check it against poker Allowpoke = false; Commands->Start_Timer(obj, this, 3.0f, 102030);//No poking for 5s if (Get_Object_Type(poker) == Team) { if (Is_Base_Powered(Team)) { if (Commands->Get_Money(poker) >= Cost) { Commands->Give_Money(poker, -Cost, false); //DALogManager::Write_Log("_PURCHASE","%s - %s",Get_Player_Name(poker),DATranslationManager::Translate(Preset)); Send_Message_Player(poker,255,255,255,"Purchase request granted!"); Change_Character(poker, Preset); } else { if (Team == 0) { Create_2D_Wave_Sound_Dialog_Player(poker, "m00evan_dsgn0024i1evan_snd.wav"); } else if (Team == 1) { Create_2D_Wave_Sound_Dialog_Player(poker, "m00evag_dsgn0028i1evag_snd.wav"); } Send_Message_Player(poker, 255, 255, 255, "Insufficient Funds"); } } else if (!Is_Base_Powered(Team)) { if (Commands->Get_Money(poker) >= Cost * 1.5f) { Commands->Give_Money(poker, -Cost * 1.5f, false); //DALogManager::Write_Log("_PURCHASE","%s - %s",Get_Player_Name(poker),DATranslationManager::Translate(Preset)); Send_Message_Player(poker,255,255,255,"Purchase request granted!"); Change_Character(poker, Preset); } else { if (Team == 0) { Create_2D_Wave_Sound_Dialog_Player(poker, "m00evan_dsgn0024i1evan_snd.wav"); } else if (Team == 1) { Create_2D_Wave_Sound_Dialog_Player(poker, "m00evag_dsgn0028i1evag_snd.wav"); } Send_Message_Player(poker, 255, 255, 255, "Insufficient Funds: Power is Down = 1.5x Cost"); } } } else { const char *Building = Get_Translated_Preset_Name(Commands->Find_Object(InfantryFactoryID)); Send_Message_Player(poker,255,255,255,StringClass::getFormattedString("Sorry, the %s is not captured. Purchase denied.",Building)); } } } void DB_Capturable_Infantry_Terminal::Timer_Expired(GameObject *obj, int number) { if (number == 102030) { Allowpoke = true; Commands->Enable_HUD_Pokable_Indicator(obj, true); } else if (number == 102031) { Team = Get_Object_Type(Commands->Find_Object(InfantryFactoryID)); Set_Object_Type(obj, Team); Commands->Start_Timer(obj, this, 10.0f, 102031);//re-set the team of the console to that of the associated helipad } } ScriptRegistrant<DB_Capturable_Infantry_Terminal> DB_Capturable_Infantry_Terminal_Registrant("DB_Capturable_Infantry_Terminal", "InfantryFactoryID=0:int,Preset=bla:string,Cost=10000:float"); class DB_Capturable_Powerup_Terminal : public ScriptImpClass { void Created(GameObject *obj); void Poked(GameObject *obj, GameObject *poker); void Timer_Expired(GameObject *obj, int number); int CheckObjectID; int Team; bool Allowpoke; float Cost; const char *Preset; }; void DB_Capturable_Powerup_Terminal::Created(GameObject *obj) { Commands->Enable_HUD_Pokable_Indicator(obj, true); CheckObjectID = Get_Int_Parameter("CheckObjectID"); Cost = Get_Float_Parameter("Cost"); Preset = Get_Parameter("Powerup"); Team = Get_Object_Type(Commands->Find_Object(CheckObjectID)); Allowpoke = true; Set_Object_Type(obj, Team); Commands->Start_Timer(obj, this, 10.0f, 102031);//set the team of the console to that of the associated helipad } void DB_Capturable_Powerup_Terminal::Poked(GameObject *obj, GameObject *poker) { if (Allowpoke) { Commands->Enable_HUD_Pokable_Indicator(obj, false); Team = Get_Object_Type(Commands->Find_Object(CheckObjectID));//request the helipad team again and check it against poker Allowpoke = false; Commands->Start_Timer(obj, this, 3.0f, 102030);//No poking for 5s if (Get_Object_Type(poker) == Team) { if (Is_Base_Powered(Team)) { if (Commands->Get_Money(poker) >= Cost) { Commands->Give_Money(poker, -Cost, false); Grant_Powerup(poker, Preset); } else { if (Team == 0) { Create_2D_WAV_Sound_Player(poker, "m00evan_dsgn0024i1evan_snd.wav"); } else if (Team == 1) { Create_2D_WAV_Sound_Player(poker, "m00evag_dsgn0028i1evag_snd.wav"); } Send_Message_Player(poker, 255, 255, 255, "Insufficient Funds"); } } else if (!Is_Base_Powered(Team)) { if (Commands->Get_Money(poker) >= Cost * 1.5f) { Commands->Give_Money(poker, -Cost * 1.5f, false); Grant_Powerup(poker, Preset); } else { if (Team == 0) { Create_2D_WAV_Sound_Player(poker, "m00evan_dsgn0024i1evan_snd.wav"); } else if (Team == 1) { Create_2D_WAV_Sound_Player(poker, "m00evag_dsgn0028i1evag_snd.wav"); } Send_Message_Player(poker, 255, 255, 255, "Insufficient Funds: Power is Down = Double Cost"); } } } else { const char *Building = Get_Translated_Preset_Name(Commands->Find_Object(CheckObjectID)); Send_Message_Player(poker,255,255,255,StringClass::getFormattedString("Sorry, the %s is not captured. Purchase denied.",Building)); } } } void DB_Capturable_Powerup_Terminal::Timer_Expired(GameObject *obj, int number) { if (number == 102030) { Allowpoke = true; Commands->Enable_HUD_Pokable_Indicator(obj, true); } else if (number == 102031) { Team = Get_Object_Type(Commands->Find_Object(CheckObjectID)); Set_Object_Type(obj, Team); Commands->Start_Timer(obj, this, 10.0f, 102031);//re-set the team of the console to that of the associated helipad } } ScriptRegistrant<DB_Capturable_Powerup_Terminal> DB_Capturable_Powerup_Terminal_Registrant("DB_Capturable_Powerup_Terminal", "CheckObjectID=0:int,Powerup=bla:string,Cost=10000:float"); class Nod_Turret_DeathSound : public ScriptImpClass { int team; void Nod_Turret_DeathSound::Created(GameObject *obj) { team=Get_Object_Type(obj); } void Nod_Turret_DeathSound::Killed(GameObject *obj, GameObject *killer) { team=Get_Object_Type(obj); if(team==0) Create_2D_WAV_Sound_Team("m00bntu_kill0001i1evan_snd.wav",team); else if(team==1) Create_2D_WAV_Sound_Team("m00bgtu_kill0002i1evag_snd.wav",team); } }; class GDI_Guard_Tower_DeathSound : public ScriptImpClass { int team; void GDI_Guard_Tower_DeathSound::Created(GameObject *obj) { team=Get_Object_Type(obj); } void GDI_Guard_Tower_DeathSound::Killed(GameObject *obj, GameObject *killer) { team=Get_Object_Type(obj); if(team==1) Create_2D_WAV_Sound_Team("m00bggt_kill0001i1evag_snd.wav",team); else if(team==0) Create_2D_WAV_Sound_Team("m00bngt_kill0001i1evan_snd.wav",team); } }; class Nod_SamSite_DeathSound : public ScriptImpClass { int team; void Nod_SamSite_DeathSound::Created(GameObject *obj) { team=Get_Object_Type(obj); } void Nod_SamSite_DeathSound::Killed(GameObject *obj, GameObject *killer) { team=Get_Object_Type(obj); if(team==0) Create_2D_WAV_Sound_Team("m00bnss_kill0001i1evan_snd.wav",team); else if(team==1) Create_2D_WAV_Sound_Team("m00bgss_kill0002i1evag_snd.wav",team); } }; class DB_Power_Plant_fix : public ScriptImpClass { int team; void DB_Power_Plant_fix::Created(GameObject *obj) { team=Get_Object_Type(obj); } void DB_Power_Plant_fix::Killed(GameObject *obj, GameObject *killer) { Commands->Start_Timer(obj,this,3,8); } void DB_Power_Plant_fix::Timer_Expired(GameObject *obj,int number) { if(obj->As_BuildingGameObj()->Get_Player_Type()==0) { if(!Is_Base_Powered(0)) { Create_2D_WAV_Sound_Team("m00evag_dsgn0065i1evag_snd2.wav",1); Create_2D_WAV_Sound_Team("m00evan_dsgn0069i1evan_snd2.wav",0); } } else if(obj->As_BuildingGameObj()->Get_Player_Type()==1) { if(!Is_Base_Powered(1)) { Create_2D_WAV_Sound_Team("m00evag_dsgn0064i1evag_snd2.wav",1); Create_2D_WAV_Sound_Team("m00evan_dsgn0068i1evan_snd2.wav",0); } } } }; class DB_Enter_Teleport_Random : public ScriptImpClass { void Entered(GameObject *obj, GameObject *enter) { int random = Commands->Get_Random_Int(1,5); { if (random == 1) { int x = Get_Int_Parameter("Object_ID1"); if (x) { GameObject *gotoObject = Commands->Find_Object(x); Vector3 gotoLocation = Commands->Get_Position(gotoObject); Commands->Set_Position(enter,gotoLocation); } } else if (random == 2) { int x = Get_Int_Parameter("Object_ID2"); if (x) { GameObject *gotoObject = Commands->Find_Object(x); Vector3 gotoLocation = Commands->Get_Position(gotoObject); Commands->Set_Position(enter,gotoLocation); } } else if (random == 3) { int x = Get_Int_Parameter("Object_ID3"); if (x) { GameObject *gotoObject = Commands->Find_Object(x); Vector3 gotoLocation = Commands->Get_Position(gotoObject); Commands->Set_Position(enter,gotoLocation); } } else if (random == 4) { int x = Get_Int_Parameter("Object_ID4"); if (x) { GameObject *gotoObject = Commands->Find_Object(x); Vector3 gotoLocation = Commands->Get_Position(gotoObject); Commands->Set_Position(enter,gotoLocation); } } else { int x = Get_Int_Parameter("Object_ID5"); if (x) { GameObject *gotoObject = Commands->Find_Object(x); Vector3 gotoLocation = Commands->Get_Position(gotoObject); Commands->Set_Position(enter,gotoLocation); } } } } }; class DB_Face_Forward: public ScriptImpClass { Vector3 DefaultPos; float Duration; void DB_Face_Forward::Created(GameObject *obj) { Duration = Get_Float_Parameter("Duration"); Vector3 pos = Commands->Get_Bone_Position(obj,"barrel"); Vector3 target_direction = obj->As_PhysicalGameObj()->Peek_Model()->Get_Bone_Transform( obj->As_PhysicalGameObj()->Peek_Model()->Get_Bone_Index("Barrel")).Get_X_Vector(); DefaultPos = pos + target_direction * 100; if(stristr(Commands->Get_Preset_Name(obj),"Sam") || stristr(Commands->Get_Preset_Name(obj),"AA_Gun")) { DefaultPos.Z+=36; } ActionParamsStruct var; var.Priority=10; var.Set_Face_Location(DefaultPos,0,Duration); Commands->Action_Face_Location(obj,var); } void DB_Face_Forward::Custom(GameObject *obj,int type,int param,GameObject *sender) { if(type==8765) { GameObject *target = Commands->Find_Object(param); if(obj->As_VehicleGameObj() && obj->As_VehicleGameObj()->Is_Turret()) { ActionParamsStruct var; var.Priority=71; var.Set_Attack(target,1000,0,true); Commands->Action_Attack(obj,var); } } else if(type==5432) { ActionParamsStruct var; var.Priority=71; var.Set_Face_Location(DefaultPos,0,Duration); Commands->Action_Face_Location(obj,var); } else if(type==7654) { GameObject *target = Commands->Find_Object(param); if(target) { if(Get_Object_Type(target)!=Get_Object_Type(obj)) { Vector3 TargetPos = Commands->Get_Position(target); ActionParamsStruct var; var.Priority=71; var.Set_Face_Location(TargetPos,0,Duration); Commands->Action_Face_Location(obj,var); } } } } }; ScriptRegistrant<DB_Face_Forward> DB_Face_Forward_Registrant("DB_Face_Forward", "Duration=1:float"); ScriptRegistrant<DB_Captureable_Silo>DB_Captureable_Silo_Registrant("DB_Captureable_Silo","Team=-2:int,Amount=2:float,UpgradeAmount=3:float,UpgradeID=0:int"); ScriptRegistrant<DB_Helipad_Captureable> DB_Capturable_Helipad_Registrant("DB_Capturable_Helipad","Team=-2:int,ReloadZoneID=0:int"); ScriptRegistrant<DB_Powerup_Buy_Poke_Sound> DB_Powerup_Buy_Poke_Sound_Registrant("DB_Powerup_Buy_Poke_Sound", "Team=0:int,BuildingID=0:int,Preset=bla:string,Cost=10000:float,SoundGranted=bla:string,SoundDenied=bla:string"); ScriptRegistrant<DB_capturable_Helipad_Terminal> DB_capturable_Helipad_Terminal_Registrant("DB_capturable_Helipad_Terminal", "BuildingID=0:int,Preset=bla:string,Cost=10000:float,SpawnLocation=0:int"); ScriptRegistrant<DB_capturable_WF_Terminal> DB_capturable_WF_Terminal_Registrant("DB_capturable_WF_Terminal", "BuildingID=0:int,Preset=bla:string,Cost=10000:float,SpawnLocation=0:int,WaypathID=0:int"); ScriptRegistrant<DB_capturable_helipadzone_reload> DB_capturable_helipad_zone_reload_Registrant("DB_capturable_helipadzone_reload", "BuildingID=0:int,ReloadPreset=bla:string"); ScriptRegistrant<DB_Capturable_repairpad> DB_capturable_repairpad_Registrant("DB_capturable_repairpad", "Team=-2:int,RepairZoneID=0:int"); ScriptRegistrant<DB_Capturable_object> DB_capturable_object_Registrant("DB_capturable_object", "Owner=-2:int"); ScriptRegistrant<DB_Capturable_object> DB_Capturable_Object_2_Registrant("DB_Capturable_Object_2", "Owner=0:int,Audio_Captured_GDI_GDI=asdf:string,Audio_Captured_GDI_Nod=asdf:string,Audio_Captured_Nod_GDI=asdf:string,Audio_Captured_Nod_Nod=asdf:string,Audio_Killed_GDI_GDI=asdf:string,Audio_Killed_GDI_Nod=asdf:string,Audio_Killed_Nod_GDI=asdf:string,Audio_Killed_Nod_Nod=asdf:string"); ScriptRegistrant<DB_capturable_Repairzone> DB_capturable_Repairzone_Registrant("DB_capturable_Repairzone", "BuildingID=0:int"); ScriptRegistrant<DB_capturable_Repairzone> DB_capturable_Helipad_Repairzone_Registrant("DB_capturable_Helipad_Repairzone", "BuildingID=0:int"); ScriptRegistrant<Nod_Turret_DeathSound> Nod_Turret_DeathSound_Registrant("Nod_Turret_DeathSound", ""); ScriptRegistrant<GDI_Guard_Tower_DeathSound> GDI_Guard_Tower_DeathSound_Registrant("GDI_Guard_Tower_DeathSound", ""); ScriptRegistrant<Nod_SamSite_DeathSound> Nod_SamSite_DeathSound_Registrant("Nod_SamSite_DeathSound", ""); ScriptRegistrant<DB_Power_Plant_fix> DB_Power_Plant_fix_Registrant("DB_Power_Plant_fix", ""); ScriptRegistrant<DB_Enter_Teleport_Random> DB_Enter_Teleport_Random_Registrant("DB_Enter_Teleport_Random","Object_ID1=1:int,Object_ID2=1:int,Object_ID3=1:int,Object_ID4=1:int,Object_ID5=1:int");
30.741935
386
0.717908
mpforums
f02c708484649ea53ac11744c812b003f91e0706
12,931
cpp
C++
lib/src/gtoplus/serialize.cpp
theodelrieu/prc
199942ed8365f6e49a7e9667d587d1ae06f14999
[ "BSL-1.0" ]
1
2022-01-04T22:37:00.000Z
2022-01-04T22:37:00.000Z
lib/src/gtoplus/serialize.cpp
theodelrieu/prc
199942ed8365f6e49a7e9667d587d1ae06f14999
[ "BSL-1.0" ]
null
null
null
lib/src/gtoplus/serialize.cpp
theodelrieu/prc
199942ed8365f6e49a7e9667d587d1ae06f14999
[ "BSL-1.0" ]
null
null
null
#include <prc/gtoplus/serialize.hpp> #include <prc/detail/unicode.hpp> #include <prc/range_elem.hpp> #include <cstring> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <optional> #include <sstream> namespace prc::gtoplus { namespace { struct group_name_rgb { std::string name; int rgb; }; struct hand_info { std::vector<std::pair<int, double>> index_to_ratio; }; // TODO avoid copy pasting :D class hand_range_expander { public: hand_range_expander(std::back_insert_iterator<std::vector<prc::hand>> out) : _out(out) { } void operator()(paired_hand const& from, paired_hand const& to) const { auto from_int = static_cast<int>(from.rank()); auto const to_int = static_cast<int>(to.rank()); while (from_int != to_int) *_out = hand{paired_hand{static_cast<rank>(from_int++)}}; *_out = hand{paired_hand{static_cast<rank>(to_int)}}; } void operator()(unpaired_hand const& from, unpaired_hand const& to) const { auto from_high_int = static_cast<int>(from.high()); auto from_low_int = static_cast<int>(from.low()); auto to_high_int = static_cast<int>(to.high()); auto to_low_int = static_cast<int>(to.low()); if (from_high_int == to_high_int) { while (from_low_int != to_low_int) { *_out = hand{unpaired_hand{from.high(), static_cast<rank>(from_low_int++), static_cast<suitedness>(from.suited())}}; } *_out = hand{unpaired_hand{from.high(), static_cast<rank>(from_low_int), static_cast<suitedness>(from.suited())}}; } // 98s+ type of hands else { while (from_high_int != to_high_int) { *_out = hand{unpaired_hand{static_cast<rank>(from_high_int++), static_cast<rank>(from_low_int++), static_cast<suitedness>(from.suited())}}; } *_out = hand{unpaired_hand{static_cast<rank>(from_high_int), static_cast<rank>(from_low_int), static_cast<suitedness>(from.suited())}}; } } void operator()(hand const& from, hand const& to) const { if (auto f = from.get_if<paired_hand>()) (*this)(*f, to.get<paired_hand>()); else (*this)(from.get<unpaired_hand>(), to.get<unpaired_hand>()); } private: std::back_insert_iterator<std::vector<prc::hand>> mutable _out; }; class range_elem_expander { public: range_elem_expander(std::back_insert_iterator<std::vector<range_elem>> out) : _out{out} { } void operator()(combo const& c) const { throw std::runtime_error("combos are not supported here"); } void operator()(hand const& h) const { *_out = prc::range_elem{h}; } void operator()(hand_range const& hr) const { std::vector<hand> hands; hand_range_expander{std::back_inserter(hands)}(hr.from(), hr.to()); for (auto const& h : hands) ((*this)(h)); } private: std::back_insert_iterator<std::vector<range_elem>> mutable _out; }; std::string rgb_to_string(int rgb) { char buf[12]; auto const r = (rgb >> 16) & 0xFF; auto const g = (rgb >> 8) & 0xFF; auto const b = rgb & 0xFF; std::snprintf(&buf[0], 12, "%03d %03d %03d", r, g, b); return buf; } void percents_to_ratios(hand_info& info) { auto it = std::min_element( info.index_to_ratio.begin(), info.index_to_ratio.end(), [](auto& lhs, auto& rhs) { return lhs.second < rhs.second; }); assert(it != info.index_to_ratio.end()); hand_info tmp; for (auto const& [idx, weight] : info.index_to_ratio) tmp.index_to_ratio.emplace_back(idx, weight / it->second); info = std::move(tmp); } std::optional<hand_info> get_hand_info( prc::hand const& h, std::vector<prc::range> const& subranges, std::vector<group_name_rgb> const& group_names_rgbs) { hand_info ret; for (auto const& sub : subranges) { for (auto const& [w, e] : sub.elems()) { auto const hands = expand_hands(e); auto const it = std::find(hands.begin(), hands.end(), h); if (it != hands.end()) { auto const group_name_it = std::find_if( group_names_rgbs.begin(), group_names_rgbs.end(), [&](auto& g) { return g.rgb == sub.rgb(); }); if (group_name_it == group_names_rgbs.end()) { throw std::runtime_error{ "cannot find group name, should not happen!"}; } ret.index_to_ratio.emplace_back( std::distance(group_names_rgbs.begin(), group_name_it), w); break; } } } if (ret.index_to_ratio.empty()) return std::nullopt; percents_to_ratios(ret); return ret; } auto const& sorted_hands() { using namespace prc::literals; static auto const ret = []() { // clang-format off std::vector const hands{ "AA"_re, "AKs"_re, "AQs"_re, "AJs"_re, "ATs"_re, "A9s"_re, "A8s"_re, "A7s"_re, "A6s"_re, "A5s"_re, "A4s"_re, "A3s"_re, "A2s"_re, "AKo"_re, "KK"_re, "KQs"_re, "KJs"_re, "KTs"_re, "K9s"_re, "K8s"_re, "K7s"_re, "K6s"_re, "K5s"_re, "K4s"_re, "K3s"_re, "K2s"_re, "AQo"_re, "KQo"_re, "QQ"_re, "QJs"_re, "QTs"_re, "Q9s"_re, "Q8s"_re, "Q7s"_re, "Q6s"_re, "Q5s"_re, "Q4s"_re, "Q3s"_re, "Q2s"_re, "AJo"_re, "KJo"_re, "QJo"_re, "JJ"_re, "JTs"_re, "J9s"_re, "J8s"_re, "J7s"_re, "J6s"_re, "J5s"_re, "J4s"_re, "J3s"_re, "J2s"_re, "ATo"_re, "KTo"_re, "QTo"_re, "JTo"_re, "TT"_re, "T9s"_re, "T8s"_re, "T7s"_re, "T6s"_re, "T5s"_re, "T4s"_re, "T3s"_re, "T2s"_re, "A9o"_re, "K9o"_re, "Q9o"_re, "J9o"_re, "T9o"_re, "99"_re, "98s"_re, "97s"_re, "96s"_re, "95s"_re, "94s"_re, "93s"_re, "92s"_re, "A8o"_re, "K8o"_re, "Q8o"_re, "J8o"_re, "T8o"_re, "98o"_re, "88"_re, "87s"_re, "86s"_re, "85s"_re, "84s"_re, "83s"_re, "82s"_re, "A7o"_re, "K7o"_re, "Q7o"_re, "J7o"_re, "T7o"_re, "97o"_re, "87o"_re, "77"_re, "76s"_re, "75s"_re, "74s"_re, "73s"_re, "72s"_re, "A6o"_re, "K6o"_re, "Q6o"_re, "J6o"_re, "T6o"_re, "96o"_re, "86o"_re, "76o"_re, "66"_re, "65s"_re, "64s"_re, "63s"_re, "62s"_re, "A5o"_re, "K5o"_re, "Q5o"_re, "J5o"_re, "T5o"_re, "95o"_re, "85o"_re, "75o"_re, "65o"_re, "55"_re, "54s"_re, "53s"_re, "52s"_re, "A4o"_re, "K4o"_re, "Q4o"_re, "J4o"_re, "T4o"_re, "94o"_re, "84o"_re, "74o"_re, "64o"_re, "54o"_re, "44"_re, "43s"_re, "42s"_re, "A3o"_re, "K3o"_re, "Q3o"_re, "J3o"_re, "T3o"_re, "93o"_re, "83o"_re, "73o"_re, "63o"_re, "53o"_re, "43o"_re, "33"_re, "32s"_re, "A2o"_re, "K2o"_re, "Q2o"_re, "J2o"_re, "T2o"_re, "92o"_re, "82o"_re, "72o"_re, "62o"_re, "52o"_re, "42o"_re, "32o"_re, "22"_re, }; // clang-format on std::vector<prc::hand> ret; for (auto& h : hands) ret.push_back(h.get<prc::hand>()); return ret; }(); return ret; } std::string to_little_word(std::uint16_t n) { std::string ret(2, '\0'); std::memcpy( ret.data(), reinterpret_cast<char const*>(&n), sizeof(std::uint16_t)); return ret; } std::string to_little_dword(int n) { std::string ret(4, '\0'); std::memcpy(ret.data(), reinterpret_cast<char const*>(&n), sizeof(int)); return ret; } std::string to_radix_double(double d) { std::string ret(8, '\0'); std::memcpy(ret.data(), reinterpret_cast<char const*>(&d), sizeof(double)); return ret; } std::string to_utf16_string(std::string const& utf8) { auto ret = to_little_dword(0x65) + '\xff' + '\xfe'; auto const utf16 = detail::utf8_to_utf16le(utf8); auto const nb_code_units = utf16.size(); if (nb_code_units > 30'000) throw std::runtime_error("utf16 size must be <= 60 000"); ret += "\xff"; // 255 must be encoded on two bytes, else you get two 0xff which breaks the // format if (nb_code_units >= 0xff) { ret += "\xff"; ret += to_little_word(nb_code_units); } else { ret += static_cast<char>(nb_code_units); } ret += std::string(reinterpret_cast<char const*>(utf16.data()), utf16.size() * 2); return ret; } std::string to_category(prc::folder const& f) { auto ret = to_little_dword(0x00003039); if (f.name() == "/") ret += to_utf16_string("default_name"); else ret += to_utf16_string(f.name()); ret += to_little_dword(0); ret += static_cast<char>(1) + to_little_dword(0) + to_little_dword(0) + to_little_dword(f.entries().size()); return ret; } std::string to_range_content( std::vector<prc::range::weighted_elems> const& elems) { std::stringstream ss; for (auto const& [w, e] : elems) { ss << '[' << w << ']'; for (auto i = 0; i < e.size(); ++i) { // GTO+ doesn't like when hand ranges are low-high, must be high-low if (auto hr = e[i].get_if<prc::hand_range>()) ss << hr->to() << '-' << hr->from(); else ss << e[i]; if (i != e.size() - 1) ss << ','; } ss << "[/" << w << "],"; } auto utf8 = ss.str(); if (!utf8.empty()) utf8.pop_back(); return to_utf16_string(utf8); } std::string to_group_info(std::vector<prc::range> const& subranges, std::vector<group_name_rgb>& group_names_rgbs) { std::string ret; for (auto const& sub : subranges) { auto const group_it = std::find_if( group_names_rgbs.begin(), group_names_rgbs.end(), [&](auto& g) { return g.rgb == sub.rgb(); }); auto const idx = std::distance(group_names_rgbs.begin(), group_it); if (group_it == group_names_rgbs.end()) group_names_rgbs.push_back({sub.name(), sub.rgb()}); ret += to_little_dword(0x00003039) + to_utf16_string(sub.name()) + to_little_dword(0) + '\x01' + to_little_dword(2) + to_little_dword(idx) + to_little_dword(0); } return ret; } std::string to_hand_info(std::vector<prc::range> const& subranges, std::vector<group_name_rgb> const& group_names_rgbs) { std::string ret; auto const& all_hands = sorted_hands(); std::vector<hand_info> info; for (auto i = 0; i < all_hands.size(); ++i) { auto const opt_info = get_hand_info(all_hands[i], subranges, group_names_rgbs); if (opt_info) info.push_back(*opt_info); else info.push_back(hand_info{{{0, 1.0}}}); } for (auto const& elem : info) { ret += to_little_dword(0x84) + to_little_dword(elem.index_to_ratio.size()); for (auto const& [idx, ratio] : elem.index_to_ratio) ret += to_little_dword(idx); for (auto const& [idx, ratio] : elem.index_to_ratio) ret += to_radix_double(ratio); } return ret; } std::string to_range(prc::range const& r, std::vector<group_name_rgb>& group_names_rgbs) { auto ret = to_little_dword(0x00003039); ret += to_utf16_string(r.name()) + to_little_dword(0); if (r.subranges().empty()) ret += '\x00'; else ret += '\x01'; ret += to_little_dword(1) + to_little_dword(0) + to_little_dword(r.subranges().size()); ret += to_group_info(r.subranges(), group_names_rgbs); ret += to_range_content(r.elems()); ret += to_hand_info(r.subranges(), group_names_rgbs); ret += to_little_dword(r.subranges().size()); for (auto const& sub : r.subranges()) { auto const group_it = std::find_if( group_names_rgbs.begin(), group_names_rgbs.end(), [&](auto& g) { return g.rgb == sub.rgb(); }); auto const idx = std::distance(group_names_rgbs.begin(), group_it); if (group_it == group_names_rgbs.end()) throw std::runtime_error{"cannot find group name, should not happen!"}; ret += to_little_dword(idx); } return ret; } std::string serialize_impl(prc::folder const& parent_folder, std::vector<group_name_rgb>& group_names_rgbs) { auto ret = to_category(parent_folder); for (auto const& entry : parent_folder.entries()) { if (auto f = boost::variant2::get_if<prc::folder>(&entry)) ret += serialize_impl(*f, group_names_rgbs); else ret += to_range(boost::variant2::get<prc::range>(entry), group_names_rgbs); } return ret; } std::string serialize_settings( std::vector<group_name_rgb> const& group_names_rgbs) { using namespace std::string_literals; auto ret = R"-([ACTION COLORS] 1) 225 68 68 2) 114 191 68 3) 0 130 202 4) 225 0 225 5) 0 225 225 6) 255 183 71 7) 0 191 255 8) 255 105 180 [HEATMAP COLORS] 1) 255 0 0 2) 255 230 0 3) 0 200 0 [PREFLOP GROUP COLORS] )-"s; for (auto i = 0; i < group_names_rgbs.size(); ++i) { ret += std::to_string(i + 1) + ") " + rgb_to_string(group_names_rgbs[i].rgb) + '\n'; } return ret; } } serialized_content serialize(prc::folder const& f) { serialized_content ret; std::vector<group_name_rgb> group_names_rgbs; ret.newdefs3 = serialize_impl(f, group_names_rgbs); ret.settings = serialize_settings(group_names_rgbs); return ret; } }
30.283372
134
0.607996
theodelrieu
f02d4b30a4d7e005ddb192d575ccb0b02eb80c96
29,715
cpp
C++
src/types.cpp
Javyre/wf-config
c9603754c650c2121582735c469e9cb9117e309e
[ "MIT" ]
10
2019-02-20T08:52:26.000Z
2022-03-27T00:23:52.000Z
src/types.cpp
Javyre/wf-config
c9603754c650c2121582735c469e9cb9117e309e
[ "MIT" ]
43
2018-09-05T18:03:58.000Z
2022-03-31T15:18:46.000Z
src/types.cpp
Javyre/wf-config
c9603754c650c2121582735c469e9cb9117e309e
[ "MIT" ]
14
2019-02-13T12:54:26.000Z
2021-07-16T21:23:12.000Z
#include <wayfire/config/types.hpp> #include <vector> #include <map> #include <cmath> #include <algorithm> #include <libevdev/libevdev.h> #include <sstream> /* --------------------------- Primitive types ------------------------------ */ template<> stdx::optional<bool> wf::option_type::from_string(const std::string& value) { std::string lowercase = value; for (auto& c : lowercase) { c = std::tolower(c); } if ((lowercase == "true") || (lowercase == "1")) { return true; } if ((lowercase == "false") || (lowercase == "0")) { return false; } return {}; } template<> stdx::optional<int> wf::option_type::from_string(const std::string& value) { std::istringstream in{value}; int result; in >> result; if (value != std::to_string(result)) { return {}; } return result; } /** Attempt to parse a string as an double value */ template<> stdx::optional<double> wf::option_type::from_string(const std::string& value) { auto old = std::locale::global(std::locale::classic()); std::istringstream in{value}; double result; in >> result; std::locale::global(old); if (!in.eof() || in.fail() || value.empty()) { /* XXX: is the check above enough??? Overflow? Underflow? */ return {}; } return result; } template<> stdx::optional<std::string> wf::option_type::from_string(const std::string& value) { return value; } template<> std::string wf::option_type::to_string( const bool& value) { return value ? "true" : "false"; } template<> std::string wf::option_type::to_string( const int& value) { return std::to_string(value); } template<> std::string wf::option_type::to_string( const double& value) { return std::to_string(value); } template<> std::string wf::option_type::to_string( const std::string& value) { return value; } /* ----------------------------- wf::color_t -------------------------------- */ wf::color_t::color_t() : color_t(0.0, 0.0, 0.0, 0.0) {} wf::color_t::color_t(double r, double g, double b, double a) { this->r = r; this->g = g; this->b = b; this->a = a; } wf::color_t::color_t(const glm::vec4& value) : color_t(value.r, value.g, value.b, value.a) {} static double hex_to_double(std::string value) { char *dummy; return std::strtol(value.c_str(), &dummy, 16); } static stdx::optional<wf::color_t> try_parse_rgba(const std::string& value) { wf::color_t parsed = {0, 0, 0, 0}; std::stringstream ss(value); auto old = std::locale::global(std::locale::classic()); bool valid_color = (bool)(ss >> parsed.r >> parsed.g >> parsed.b >> parsed.a); /* Check nothing else after that */ std::string dummy; valid_color &= !(bool)(ss >> dummy); std::locale::global(old); return valid_color ? parsed : stdx::optional<wf::color_t>{}; } #include <iostream> static const std::string hex_digits = "0123456789ABCDEF"; template<> stdx::optional<wf::color_t> wf::option_type::from_string( const std::string& param_value) { auto value = param_value; for (auto& ch : value) { ch = std::toupper(ch); } auto as_rgba = try_parse_rgba(value); if (as_rgba) { return as_rgba; } /* Either #RGBA or #RRGGBBAA */ if ((value.size() != 5) && (value.size() != 9)) { return {}; } if (value[0] != '#') { return {}; } if (value.find_first_not_of(hex_digits, 1) != std::string::npos) { return {}; } double r, g, b, a; /* #RRGGBBAA case */ if (value.size() == 9) { r = hex_to_double(value.substr(1, 2)) / 255.0; g = hex_to_double(value.substr(3, 2)) / 255.0; b = hex_to_double(value.substr(5, 2)) / 255.0; a = hex_to_double(value.substr(7, 2)) / 255.0; } else { assert(value.size() == 5); r = hex_to_double(value.substr(1, 1)) / 15.0; g = hex_to_double(value.substr(2, 1)) / 15.0; b = hex_to_double(value.substr(3, 1)) / 15.0; a = hex_to_double(value.substr(4, 1)) / 15.0; } return wf::color_t{r, g, b, a}; } template<> std::string wf::option_type::to_string(const color_t& value) { const int max_byte = 255; const int min_byte = 0; auto to_hex = [=] (double number_d) { int number = std::round(number_d); /* Clamp */ number = std::min(number, max_byte); number = std::max(number, min_byte); std::string result; result += hex_digits[number / 16]; result += hex_digits[number % 16]; return result; }; return "#" + to_hex(value.r * max_byte) + to_hex(value.g * max_byte) + to_hex(value.b * max_byte) + to_hex(value.a * max_byte); } bool wf::color_t::operator ==(const color_t& other) const { constexpr double epsilon = 1e-6; bool equal = true; equal &= std::abs(this->r - other.r) < epsilon; equal &= std::abs(this->g - other.g) < epsilon; equal &= std::abs(this->b - other.b) < epsilon; equal &= std::abs(this->a - other.a) < epsilon; return equal; } /* ------------------------- wf::keybinding_t ------------------------------- */ struct general_binding_t { bool enabled; uint32_t mods; uint32_t value; }; /** * Split @value at non-empty tokens when encountering any of the characters * in @at */ static std::vector<std::string> split_at(std::string value, std::string at, bool allow_empty = false) { /* Trick: add a delimiter at position 0 and at the end * to avoid special casing */ value = at[0] + value + at[0]; size_t current = 0; std::vector<size_t> split_positions = {0}; while (current < value.size() - 1) { size_t next_split = value.find_first_of(at, current + 1); split_positions.push_back(next_split); current = next_split; } assert(split_positions.size() >= 2); std::vector<std::string> tokens; for (size_t i = 1; i < split_positions.size(); i++) { if ((split_positions[i] == split_positions[i - 1] + 1) && !allow_empty) { continue; // skip empty tokens } tokens.push_back(value.substr(split_positions[i - 1] + 1, split_positions[i] - split_positions[i - 1] - 1)); } return tokens; } static std::map<std::string, wf::keyboard_modifier_t> modifier_names = { {"ctrl", wf::KEYBOARD_MODIFIER_CTRL}, {"alt", wf::KEYBOARD_MODIFIER_ALT}, {"shift", wf::KEYBOARD_MODIFIER_SHIFT}, {"super", wf::KEYBOARD_MODIFIER_LOGO}, }; static std::string binding_to_string(general_binding_t binding) { std::string result = ""; for (auto& pair : modifier_names) { if (binding.mods & pair.second) { result += "<" + pair.first + "> "; } } if (binding.value > 0) { auto evdev_name = libevdev_event_code_get_name(EV_KEY, binding.value); result += evdev_name ?: "NULL"; } return result; } /** * @return A string which consists of the characters of value, but without * those contained in filter. */ static std::string filter_out(std::string value, std::string filter) { std::string result; for (auto& c : value) { if (filter.find(c) != std::string::npos) { continue; } result += c; } return result; } static const std::string whitespace_chars = " \t\n\r\v\b"; static stdx::optional<general_binding_t> parse_binding( std::string binding_description) { /* Handle disabled bindings */ auto binding_descr_no_whitespace = filter_out(binding_description, whitespace_chars); if ((binding_descr_no_whitespace == "none") || (binding_descr_no_whitespace == "disabled")) { return general_binding_t{false, 0, 0}; } /* Strategy: split the binding at modifier begin/end markings and spaces, * and then drop empty tokens. The tokens that are left should be either a * binding or something recognizable by evdev. */ static const std::string delims = "<>" + whitespace_chars; auto tokens = split_at(binding_description, delims); if (tokens.empty()) { return {}; } general_binding_t result = {true, 0, 0}; for (size_t i = 0; i < tokens.size() - 1; i++) { if (modifier_names.count(tokens[i])) { result.mods |= modifier_names[tokens[i]]; } else { return {}; // invalid modifier } } int code = libevdev_event_code_from_name(EV_KEY, tokens.back().c_str()); if (code == -1) { /* Last token might either be yet another modifier (in case of modifier * bindings) or it may be KEY_*. If neither, we have invalid binding */ if (modifier_names.count(tokens.back())) { result.mods |= modifier_names[tokens.back()]; code = 0; } else { return {}; // not found } } result.value = code; /* Do one last check: if we remove whitespaces, and add a whitespace after * each > character, then the resulting string should be almost equal to the * minimal description, generated by binding_to_string(). * * Since we have already checked all identifiers and they are valid * modifiers, it is enough to check just that the lengths are matching. * Note we can't directly compare because the order may be different. */ auto filtered_descr = filter_out(binding_description, whitespace_chars); std::string filtered_with_spaces; for (auto c : filtered_descr) { filtered_with_spaces += c; if (c == '>') { filtered_with_spaces += " "; } } auto minimal_descr = binding_to_string(result); if (filtered_with_spaces.length() == minimal_descr.length()) { return result; } return {}; } wf::keybinding_t::keybinding_t(uint32_t modifier, uint32_t keyval) { this->mod = modifier; this->keyval = keyval; } template<> stdx::optional<wf::keybinding_t> wf::option_type::from_string( const std::string& description) { auto parsed_opt = parse_binding(description); if (!parsed_opt) { return {}; } auto parsed = parsed_opt.value(); /* Disallow buttons, because evdev treats buttons and keys the same */ if (parsed.enabled && (parsed.value > 0) && (description.find("KEY") == std::string::npos)) { return {}; } if (parsed.enabled && (parsed.mods == 0) && (parsed.value == 0)) { return {}; } return wf::keybinding_t{parsed.mods, parsed.value}; } template<> std::string wf::option_type::to_string(const wf::keybinding_t& value) { if ((value.get_modifiers() == 0) && (value.get_key() == 0)) { return "none"; } return binding_to_string({true, value.get_modifiers(), value.get_key()}); } bool wf::keybinding_t::operator ==(const keybinding_t& other) const { return this->mod == other.mod && this->keyval == other.keyval; } /** @return The modifiers of the keybinding */ uint32_t wf::keybinding_t::get_modifiers() const { return this->mod; } /** @return The key of the keybinding */ uint32_t wf::keybinding_t::get_key() const { return this->keyval; } /* -------------------------- wf::buttonbinding_t --------------------------- */ wf::buttonbinding_t::buttonbinding_t(uint32_t modifier, uint32_t buttonval) { this->mod = modifier; this->button = buttonval; } template<> stdx::optional<wf::buttonbinding_t> wf::option_type::from_string( const std::string& description) { auto parsed_opt = parse_binding(description); if (!parsed_opt) { return {}; } auto parsed = parsed_opt.value(); if (!parsed.enabled) { return wf::buttonbinding_t{0, 0}; } /* Disallow keys, because evdev treats buttons and keys the same */ if (description.find("BTN") == std::string::npos) { return {}; } if (parsed.value == 0) { return {}; } return wf::buttonbinding_t{parsed.mods, parsed.value}; } template<> std::string wf::option_type::to_string( const wf::buttonbinding_t& value) { if ((value.get_modifiers() == 0) && (value.get_button() == 0)) { return "none"; } return binding_to_string({true, value.get_modifiers(), value.get_button()}); } bool wf::buttonbinding_t::operator ==(const buttonbinding_t& other) const { return this->mod == other.mod && this->button == other.button; } uint32_t wf::buttonbinding_t::get_modifiers() const { return this->mod; } uint32_t wf::buttonbinding_t::get_button() const { return this->button; } wf::touchgesture_t::touchgesture_t(touch_gesture_type_t type, uint32_t direction, int finger_count) { this->type = type; this->direction = direction; this->finger_count = finger_count; } static const std::map<std::string, wf::touch_gesture_direction_t> touch_gesture_direction_string_map = { {"up", wf::GESTURE_DIRECTION_UP}, {"down", wf::GESTURE_DIRECTION_DOWN}, {"left", wf::GESTURE_DIRECTION_LEFT}, {"right", wf::GESTURE_DIRECTION_RIGHT} }; static wf::touch_gesture_direction_t parse_single_direction( const std::string& direction) { if (touch_gesture_direction_string_map.count(direction)) { return touch_gesture_direction_string_map.at(direction); } throw std::domain_error("invalid swipe direction"); } uint32_t parse_direction(const std::string& direction) { size_t hyphen = direction.find("-"); if (hyphen == std::string::npos) { return parse_single_direction(direction); } else { /* we support up to 2 directions, because >= 3 will be invalid anyway */ auto first = direction.substr(0, hyphen); auto second = direction.substr(hyphen + 1); uint32_t mask = parse_single_direction(first) | parse_single_direction(second); const uint32_t both_horiz = wf::GESTURE_DIRECTION_LEFT | wf::GESTURE_DIRECTION_RIGHT; const uint32_t both_vert = wf::GESTURE_DIRECTION_UP | wf::GESTURE_DIRECTION_DOWN; if (((mask & both_horiz) == both_horiz) || ((mask & both_vert) == both_vert)) { throw std::domain_error("Cannot have two opposing directions in the" "same gesture"); } return mask; } } wf::touchgesture_t parse_gesture(const std::string& value) { if (value.empty()) { return {wf::GESTURE_TYPE_NONE, 0, 0}; } auto tokens = split_at(value, " \t\v\b\n\r"); assert(!tokens.empty()); if (tokens.size() != 3) { return {wf::GESTURE_TYPE_NONE, 0, 0}; } try { wf::touch_gesture_type_t type; uint32_t direction = 0; int32_t finger_count; if (tokens[0] == "pinch") { type = wf::GESTURE_TYPE_PINCH; if (tokens[1] == "in") { direction = wf::GESTURE_DIRECTION_IN; } else if (tokens[1] == "out") { direction = wf::GESTURE_DIRECTION_OUT; } else { throw std::domain_error("Invalid pinch direction: " + tokens[1]); } } else if (tokens[0] == "swipe") { type = wf::GESTURE_TYPE_SWIPE; direction = parse_direction(tokens[1]); } else if (tokens[0] == "edge-swipe") { type = wf::GESTURE_TYPE_EDGE_SWIPE; direction = parse_direction(tokens[1]); } else { throw std::domain_error("Invalid gesture type:" + tokens[0]); } // TODO: instead of atoi, check properly finger_count = std::atoi(tokens[2].c_str()); return wf::touchgesture_t{type, direction, finger_count}; } catch (std::exception& e) { // XXX: show error? // ignore it, will return GESTURE_NONE } return wf::touchgesture_t{wf::GESTURE_TYPE_NONE, 0, 0}; } template<> stdx::optional<wf::touchgesture_t> wf::option_type::from_string( const std::string& description) { auto as_binding = parse_binding(description); if (as_binding && !as_binding.value().enabled) { return touchgesture_t{GESTURE_TYPE_NONE, 0, 0}; } auto gesture = parse_gesture(description); if (gesture.get_type() == GESTURE_TYPE_NONE) { return {}; } return gesture; } static std::string direction_to_string(uint32_t direction) { std::string result = ""; for (auto& pair : touch_gesture_direction_string_map) { if (direction & pair.second) { result += pair.first + "-"; } } if (result.size() > 0) { /* Remove trailing - */ result.pop_back(); } return result; } template<> std::string wf::option_type::to_string(const touchgesture_t& value) { std::string result; switch (value.get_type()) { case GESTURE_TYPE_NONE: return ""; case GESTURE_TYPE_EDGE_SWIPE: result += "edge-"; // fallthrough case GESTURE_TYPE_SWIPE: result += "swipe "; result += direction_to_string(value.get_direction()) + " "; break; case GESTURE_TYPE_PINCH: result += "pinch "; if (value.get_direction() == GESTURE_DIRECTION_IN) { result += "in "; } if (value.get_direction() == GESTURE_DIRECTION_OUT) { result += "out "; } break; } result += std::to_string(value.get_finger_count()); return result; } wf::touch_gesture_type_t wf::touchgesture_t::get_type() const { return this->type; } int wf::touchgesture_t::get_finger_count() const { return this->finger_count; } uint32_t wf::touchgesture_t::get_direction() const { return this->direction; } bool wf::touchgesture_t::operator ==(const touchgesture_t& other) const { return type == other.type && finger_count == other.finger_count && (direction == 0 || other.direction == 0 || direction == other.direction); } /* --------------------------- activatorbinding_t --------------------------- */ struct wf::activatorbinding_t::impl { std::vector<keybinding_t> keys; std::vector<buttonbinding_t> buttons; std::vector<touchgesture_t> gestures; std::vector<hotspot_binding_t> hotspots; }; wf::activatorbinding_t::activatorbinding_t() { this->priv = std::make_unique<impl>(); } wf::activatorbinding_t::~activatorbinding_t() = default; wf::activatorbinding_t::activatorbinding_t(const activatorbinding_t& other) { this->priv = std::make_unique<impl>(*other.priv); } wf::activatorbinding_t& wf::activatorbinding_t::operator =( const activatorbinding_t& other) { if (&other != this) { this->priv = std::make_unique<impl>(*other.priv); } return *this; } template<class Type> bool try_add_binding( std::vector<Type>& to, const std::string& value) { auto binding = wf::option_type::from_string<Type>(value); if (binding) { to.push_back(binding.value()); return true; } return false; } template<> stdx::optional<wf::activatorbinding_t> wf::option_type::from_string( const std::string& string) { activatorbinding_t binding; if (filter_out(string, whitespace_chars) == "") { return binding; // empty binding } auto tokens = split_at(string, "|", true); for (auto& token : tokens) { bool is_valid_binding = try_add_binding(binding.priv->keys, token) || try_add_binding(binding.priv->buttons, token) || try_add_binding(binding.priv->gestures, token) || try_add_binding(binding.priv->hotspots, token); if (!is_valid_binding) { return {}; } } return binding; } template<class Type> static std::string concatenate_bindings(const std::vector<Type>& bindings) { std::string repr = ""; for (auto& b : bindings) { repr += wf::option_type::to_string<Type>(b); repr += " | "; } return repr; } template<> std::string wf::option_type::to_string( const activatorbinding_t& value) { std::string repr = concatenate_bindings(value.priv->keys) + concatenate_bindings(value.priv->buttons) + concatenate_bindings(value.priv->gestures) + concatenate_bindings(value.priv->hotspots); /* Remove trailing " | " */ if (repr.size() >= 3) { repr.erase(repr.size() - 3); } return repr; } template<class Type> bool find_in_container(const std::vector<Type>& haystack, Type needle) { return std::find(haystack.begin(), haystack.end(), needle) != haystack.end(); } bool wf::activatorbinding_t::has_match(const keybinding_t& key) const { return find_in_container(priv->keys, key); } bool wf::activatorbinding_t::has_match(const buttonbinding_t& button) const { return find_in_container(priv->buttons, button); } bool wf::activatorbinding_t::has_match(const touchgesture_t& gesture) const { return find_in_container(priv->gestures, gesture); } bool wf::activatorbinding_t::operator ==(const activatorbinding_t& other) const { return priv->keys == other.priv->keys && priv->buttons == other.priv->buttons && priv->gestures == other.priv->gestures && priv->hotspots == other.priv->hotspots; } const std::vector<wf::hotspot_binding_t>& wf::activatorbinding_t::get_hotspots() const { return priv->hotspots; } wf::hotspot_binding_t::hotspot_binding_t(uint32_t edges, int32_t along_edge, int32_t away_from_edge, int32_t timeout) { this->edges = edges; this->along = along_edge; this->away = away_from_edge; this->timeout = timeout; } bool wf::hotspot_binding_t::operator ==(const hotspot_binding_t& other) const { return edges == other.edges && along == other.along && away == other.away && timeout == other.timeout; } int32_t wf::hotspot_binding_t::get_timeout() const { return timeout; } int32_t wf::hotspot_binding_t::get_size_away_from_edge() const { return away; } int32_t wf::hotspot_binding_t::get_size_along_edge() const { return along; } uint32_t wf::hotspot_binding_t::get_edges() const { return edges; } static std::map<std::string, wf::output_edge_t> hotspot_edges = { {"top", wf::OUTPUT_EDGE_TOP}, {"bottom", wf::OUTPUT_EDGE_BOTTOM}, {"left", wf::OUTPUT_EDGE_LEFT}, {"right", wf::OUTPUT_EDGE_RIGHT}, }; template<> stdx::optional<wf::hotspot_binding_t> wf::option_type::from_string( const std::string& description) { std::istringstream stream{description}; std::string token; stream >> token; // "hotspot" if (token != "hotspot") { return {}; } stream >> token; // direction uint32_t edges = 0; size_t hyphen = token.find("-"); if (hyphen == token.npos) { if (hotspot_edges.count(token) == 0) { return {}; } edges = hotspot_edges[token]; } else { std::string first_direction = token.substr(0, hyphen); std::string second_direction = token.substr(hyphen + 1); if ((hotspot_edges.count(first_direction) == 0) || (hotspot_edges.count(second_direction) == 0)) { return {}; } edges = hotspot_edges[first_direction] | hotspot_edges[second_direction]; } stream >> token; int32_t along, away; if (2 != sscanf(token.c_str(), "%dx%d", &along, &away)) { return {}; } stream >> token; auto timeout = wf::option_type::from_string<int>(token); if (!timeout || stream >> token) // check for trailing characters { return {}; } return wf::hotspot_binding_t(edges, along, away, timeout.value()); } template<> std::string wf::option_type::to_string( const wf::hotspot_binding_t& value) { std::ostringstream out; out << "hotspot "; uint32_t remaining_edges = value.get_edges(); const auto& find_edge = [&] (bool need_hyphen) { for (const auto& edge : hotspot_edges) { if (remaining_edges & edge.second) { remaining_edges &= ~edge.second; if (need_hyphen) { out << "-"; } out << edge.first; break; } } }; find_edge(false); find_edge(true); out << " " << value.get_size_along_edge() << "x" << value.get_size_away_from_edge() << " " << value.get_timeout(); return out.str(); } /* ------------------------- Output config types ---------------------------- */ wf::output_config::mode_t::mode_t(bool auto_on) { this->type = auto_on ? MODE_AUTO : MODE_OFF; } wf::output_config::mode_t::mode_t(int32_t width, int32_t height, int32_t refresh) { this->type = MODE_RESOLUTION; this->width = width; this->height = height; this->refresh = refresh; } /** * Initialize a mirror mode. */ wf::output_config::mode_t::mode_t(const std::string& mirror_from) { this->type = MODE_MIRROR; this->mirror_from = mirror_from; } /** @return The type of this mode. */ wf::output_config::mode_type_t wf::output_config::mode_t::get_type() const { return type; } int32_t wf::output_config::mode_t::get_width() const { return width; } int32_t wf::output_config::mode_t::get_height() const { return height; } int32_t wf::output_config::mode_t::get_refresh() const { return refresh; } std::string wf::output_config::mode_t::get_mirror_from() const { return mirror_from; } bool wf::output_config::mode_t::operator ==(const mode_t& other) const { if (type != other.get_type()) { return false; } switch (type) { case MODE_RESOLUTION: return width == other.width && height == other.height && refresh == other.refresh; case MODE_MIRROR: return mirror_from == other.mirror_from; case MODE_AUTO: case MODE_OFF: return true; } return false; } template<> stdx::optional<wf::output_config::mode_t> wf::option_type::from_string( const std::string& string) { if (string == "off") { return wf::output_config::mode_t{false}; } if ((string == "auto") || (string == "default")) { return wf::output_config::mode_t{true}; } if (string.substr(0, 6) == "mirror") { std::stringstream ss(string); std::string from, dummy; ss >> from; // the mirror word if (!(ss >> from)) { return {}; } // trailing garbage if (ss >> dummy) { return {}; } return wf::output_config::mode_t{from}; } int w, h, rr = 0; char next; int read = std::sscanf(string.c_str(), "%d x %d @ %d%c", &w, &h, &rr, &next); if ((read < 2) || (read > 3)) { return {}; } if ((w < 0) || (h < 0) || (rr < 0)) { return {}; } // Ensure refresh rate in mHz if (rr < 1000) { rr *= 1000; } return wf::output_config::mode_t{w, h, rr}; } /** Represent the activator binding as a string. */ template<> std::string wf::option_type::to_string(const output_config::mode_t& value) { switch (value.get_type()) { case output_config::MODE_AUTO: return "auto"; case output_config::MODE_OFF: return "off"; case output_config::MODE_RESOLUTION: if (value.get_refresh() <= 0) { return to_string(value.get_width()) + "x" + to_string(value.get_height()); } else { return to_string(value.get_width()) + "x" + to_string(value.get_height()) + "@" + to_string( value.get_refresh()); } case output_config::MODE_MIRROR: return "mirror " + value.get_mirror_from(); } return {}; } wf::output_config::position_t::position_t() { this->automatic = true; } wf::output_config::position_t::position_t(int32_t x, int32_t y) { this->automatic = false; this->x = x; this->y = y; } int32_t wf::output_config::position_t::get_x() const { return x; } int32_t wf::output_config::position_t::get_y() const { return y; } bool wf::output_config::position_t::is_automatic_position() const { return automatic; } bool wf::output_config::position_t::operator ==(const position_t& other) const { if (is_automatic_position() != other.is_automatic_position()) { return false; } if (is_automatic_position()) { return true; } return x == other.x && y == other.y; } template<> stdx::optional<wf::output_config::position_t> wf::option_type::from_string( const std::string& string) { if ((string == "auto") || (string == "default")) { return wf::output_config::position_t(); } int x, y; char r; if (sscanf(string.c_str(), "%d , %d%c", &x, &y, &r) != 2) { return {}; } return wf::output_config::position_t(x, y); } /** Represent the activator binding as a string. */ template<> std::string wf::option_type::to_string(const output_config::position_t& value) { if (value.is_automatic_position()) { return "auto"; } return to_string(value.get_x()) + ", " + to_string(value.get_y()); }
23.658439
84
0.592798
Javyre
f0394df5f58e67b770fa28fc4b739da94b2752d6
1,756
cpp
C++
Practice/2017/2017.8.17/HDU4289.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2017/2017.8.17/HDU4289.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2017/2017.8.17/HDU4289.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; const int maxN=600; const int maxM=20001*20; const int inf=2147483647; class Edge { public: int u,v,flow; }; int n,m; int S,T; int cnt=-1; int Head[maxN]; int Next[maxM]; Edge E[maxM]; int depth[maxN]; int Q[maxM]; int cur[maxN]; void Add_Edge(int u,int v,int flow); bool bfs(); int dfs(int u,int flow); int main() { while (cin>>n>>m) { cnt=-1; memset(Head,-1,sizeof(Head)); scanf("%d%d",&S,&T); T=T+n; for (int i=1;i<=n;i++) { int cost; scanf("%d",&cost); Add_Edge(i,i+n,cost); } for (int i=1;i<=m;i++) { int u,v; scanf("%d%d",&u,&v); Add_Edge(u+n,v,inf); Add_Edge(v+n,u,inf); } int Ans=0; while (bfs()) { for (int i=1;i<=2*n;i++) cur[i]=Head[i]; while (int di=dfs(S,inf)) Ans+=di; } printf("%d\n",Ans); } return 0; } void Add_Edge(int u,int v,int flow) { cnt++; Next[cnt]=Head[u]; Head[u]=cnt; E[cnt].u=u; E[cnt].v=v; E[cnt].flow=flow; cnt++; Next[cnt]=Head[v]; Head[v]=cnt; E[cnt].u=v; E[cnt].v=u; E[cnt].flow=0; return; } bool bfs() { memset(depth,-1,sizeof(depth)); int h=1,t=0; Q[1]=S; depth[S]=1; do { t++; int u=Q[t]; for (int i=Head[u];i!=-1;i=Next[i]) { int v=E[i].v; if ((depth[v]==-1)&&(E[i].flow>0)) { depth[v]=depth[u]+1; h++; Q[h]=v; } } } while (t!=h); if (depth[T]==-1) return 0; return 1; } int dfs(int u,int flow) { if (u==T) return flow; for (int &i=cur[u];i!=-1;i=Next[i]) { int v=E[i].v; if ((depth[v]==depth[u]+1)&&(E[i].flow>0)) { int di=dfs(v,min(flow,E[i].flow)); if (di>0) { E[i].flow-=di; E[i^1].flow+=di; return di; } } } return 0; }
13.40458
44
0.530182
SYCstudio
f03bd8d993f42592cc5cff9722b46427abb9ea62
11,077
cpp
C++
Source/Engine/SDLEngine.cpp
gabr1e11/cornerstone
bc696e22af350b867219ef3ac99840b3e8a3f20a
[ "MIT" ]
null
null
null
Source/Engine/SDLEngine.cpp
gabr1e11/cornerstone
bc696e22af350b867219ef3ac99840b3e8a3f20a
[ "MIT" ]
null
null
null
Source/Engine/SDLEngine.cpp
gabr1e11/cornerstone
bc696e22af350b867219ef3ac99840b3e8a3f20a
[ "MIT" ]
null
null
null
// // SDLEngine.cpp // // @author Roberto Cano // #include "SDLEngine.hpp" #include "Framework/Core/GameObject.hpp" #include <stdexcept> #include <algorithm> #define GLM_FORCE_RADIANS #include <glm/gtc/matrix_transform.hpp> #include <glew/glew.h> #include <glm/glm.hpp> #include <sdl/Sdl.h> #include <sdl/SDL_image.h> using namespace SDL; namespace SDLEngineConstants { const float MaxFrameTicks = 300.0f; } EngineOwner Engine::Create(const Settings& settings) { return std::make_shared<Engine>(settings); } Engine::Engine(const Settings& settings) : _assetsDirectoryPath(settings.assetsDirectoryPath) , _lastFrameSeconds(1.0f / 60.0f) , _windowSize(settings.windowSize) , _mousePosition(settings.windowSize.width * 0.5f, settings.windowSize.height * 0.5f) , _isMouseButtonDown(false) , _isLoopRunning(false) , _updater(nullptr) , _elapsedTicks(static_cast<float>(SDL_GetTicks())) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_NOPARACHUTE) != 0) { throw std::runtime_error("Failed to init SDL"); } _window = SDL_CreateWindow("SDLEngine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, _windowSize.width, _windowSize.height, SDL_WINDOW_HIDDEN | SDL_WINDOW_OPENGL); if (_window == nullptr) { throw std::runtime_error(std::string("Error creating window: ") + SDL_GetError()); } _GLContext = SDL_GL_CreateContext(_window); const char* error = SDL_GetError(); if (*error != '\0') { throw std::runtime_error(std::string("Error initialising OpenGL context: ") + error); } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetSwapInterval(1); glEnable(GL_TEXTURE_2D); glClearColor(0.0, 0.0, 0.0, 1.0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0f, settings.windowSize.width, settings.windowSize.height, 0.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); _fontSurfaceTextureId = registerTexture(settings.fontFileName); } void Engine::start(Framework::Types::GameObject::PtrType updater) { assert(updater); _updater = updater; _updater->setEngine(shared_from_this()); callStart(_updater); SDL_ShowWindow(_window); while (!_isLoopRunning) { SDL_GL_SwapWindow(_window); glClear(GL_COLOR_BUFFER_BIT); handleMouseEvents(); float currentTicks = static_cast<float>(SDL_GetTicks()); float lastFrameTicks = currentTicks - _elapsedTicks; _elapsedTicks = currentTicks; lastFrameTicks = std::min(lastFrameTicks, SDLEngineConstants::MaxFrameTicks); _lastFrameSeconds = lastFrameTicks * 0.001f; callUpdate(updater, _lastFrameSeconds); renderCommandList(); } } void Engine::stop() { _isLoopRunning = true; _updater.reset(); } float Engine::getElapsedTime() const { return _lastFrameSeconds; } Engine::Point2D Engine::getMousePosition() const { return _mousePosition; } bool Engine::isMouseButtonDown() const { return _isMouseButtonDown; } std::string Engine::getFullPathFromAssetName(const std::string& assetName) const { return _assetsDirectoryPath + assetName; } Engine::TextureId Engine::registerTexture(const std::string& assetPath) { const std::string assetFullPath = getFullPathFromAssetName(assetPath); std::optional<TextureId> textureIdOpt = findTextureByAsset(assetFullPath); if (textureIdOpt != std::nullopt) { return textureIdOpt.value(); } SDL_Surface* texture = IMG_Load(assetFullPath.c_str()); if (texture == nullptr) { throw std::runtime_error(std::string("Unable to load texture ") + assetFullPath); } GLuint textureId; glGenTextures(1, &textureId); glBindTexture(GL_TEXTURE_2D, textureId); int mode; switch (texture->format->BytesPerPixel) { case 4: mode = GL_RGBA; break; case 3: mode = GL_RGB; break; case 1: mode = GL_LUMINANCE_ALPHA; break; default: throw std::runtime_error("Image with unknown channel profile"); break; } glTexImage2D(GL_TEXTURE_2D, 0, mode, texture->w, texture->h, 0, mode, GL_UNSIGNED_BYTE, texture->pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); _textureMapById.emplace(textureId, texture); return static_cast<TextureId>(textureId); } Engine::Size Engine::getTextureSize(TextureId textureId) const { SDL_Surface& texture = getTexture(textureId); return Size(texture.w, texture.h); } Engine::Size Engine::getScreenSize() const { return _windowSize; } Engine::Size2D Engine::getTextSize(const std::string& text, float scale) const { Size2D textSize; int maxHeight = 0; int advance = 0; for (char letter : text) { Glyph& g = findGlyph(letter); advance += g.advance + InterLetterAdvance; maxHeight = std::max(maxHeight, g.height); } return Size2D(advance, maxHeight) * scale; } void Engine::render(TextureId textureId, const Point2D& position, int zIndex, const Color3D& color, float rotation, float scale, float opacity) { _renderCommands.emplace(zIndex, RenderCommand(textureId, position, color, rotation, scale, opacity)); } void Engine::renderText(const std::string& text, const Point2D& position, int zIndex, const Color3D& color, float rotation, float scale, float opacity) { _renderCommands.emplace(zIndex, RenderCommand(text, position, color, rotation, scale, opacity)); } void Engine::renderText(const std::string& text, const Point2D& position, const std::vector<float>& yOffsets, int zIndex, const Color3D& color, float rotation, float scale, float opacity) { _renderCommands.emplace(zIndex, RenderCommand(text, position, yOffsets, color, rotation, scale, opacity)); } void Engine::renderCommandList() { for (const auto& cmdIter : _renderCommands) { const RenderCommand& cmd = cmdIter.second; if (cmd.textureId != std::nullopt) { render(cmd.textureId.value(), cmd.position.x, cmd.position.y, cmd.color, cmd.rotation, cmd.scale, cmd.opacity); } else if (cmd.text != std::nullopt) { renderText(cmd.text.value().c_str(), cmd.position.x, cmd.position.y, cmd.yOffsets, cmd.color, cmd.rotation, cmd.scale, cmd.opacity); } } _renderCommands.clear(); } void Engine::render(TextureId textureId, float x, float y, const glm::vec3& color, float rotation, float scale, float opacity) { glm::mat4 transformation; transformation = glm::translate(transformation, glm::vec3(x, y, 0.0f)); if (rotation) { transformation = glm::rotate(transformation, rotation, glm::vec3(0.0f, 0.0f, 1.0f)); } if (scale) { transformation = glm::scale(transformation, glm::vec3(scale)); } render(textureId, transformation, color, opacity); } void Engine::render(TextureId textureId, const glm::mat4& transform, const glm::vec3& color, float opacity) { glLoadMatrixf(reinterpret_cast<const float*>(&transform)); SDL_Surface& surface = getTexture(textureId); glBindTexture(GL_TEXTURE_2D, textureId); GLint halfWidth = surface.w / 2; GLint halfHeight = surface.h / 2; // Alpha blending glColor4f(color.r, color.g, color.b, opacity); glBegin(GL_QUADS); glTexCoord2i(0, 1); glVertex2i(-halfWidth, halfHeight); glTexCoord2i(1, 1); glVertex2i(halfWidth, halfHeight); glTexCoord2i(1, 0); glVertex2i(halfWidth, -halfHeight); glTexCoord2i(0, 0); glVertex2i(-halfWidth, -halfHeight); glEnd(); } void Engine::renderText(const char* text, const glm::mat4& transform, const std::vector<float>& yOffsets, const glm::vec3& color, float opacity) { glLoadMatrixf(reinterpret_cast<const float*>(&transform)); int advance = 0; int offsetIndex = 0; SDL_Surface& fontSurface = getTexture(_fontSurfaceTextureId); for (; *text; ++text) { Glyph& g = findGlyph(*text); float yOffset = 0.0f; if (!yOffsets.empty()) { yOffset = yOffsets.at(offsetIndex++); } float fontTexWidth = static_cast<float>(fontSurface.w); float fontTexHeight = static_cast<float>(fontSurface.h); float uvLeft = static_cast<float>(g.x) / fontTexWidth; float uvRight = static_cast<float>(g.x + g.width) / fontTexWidth; float uvBottom = static_cast<float>(g.y) / fontTexHeight; float uvTop = static_cast<float>(g.y + g.height) / fontTexHeight; float worldLeft = static_cast<float>(g.xoffset + advance); float worldRight = static_cast<float>(g.xoffset + g.width + advance); float worldBottom = static_cast<float>(g.yoffset + yOffset); float worldTop = static_cast<float>(g.yoffset + g.height + yOffset); glBindTexture(GL_TEXTURE_2D, _fontSurfaceTextureId); // Alpha blending glColor4f(color.r, color.g, color.b, opacity); glBegin(GL_QUADS); glTexCoord2f(uvLeft, uvTop); glVertex2f(worldLeft, worldTop); glTexCoord2f(uvRight, uvTop); glVertex2f(worldRight, worldTop); glTexCoord2f(uvRight, uvBottom); glVertex2f(worldRight, worldBottom); glTexCoord2f(uvLeft, uvBottom); glVertex2f(worldLeft, worldBottom); glEnd(); advance += g.advance + InterLetterAdvance; } } void Engine::renderText(const char* text, float x, float y, const std::vector<float>& yOffsets, const glm::vec3& color, float rotation, float scale, float opacity) { Size2D textSize = getTextSize(text, scale); float xPos = x - textSize.x / 2.0f; float yPos = y - textSize.y / 2.0f; glm::mat4 transformation; transformation = glm::translate(transformation, glm::vec3(xPos, yPos, 0.0f)); if (rotation) { transformation = glm::rotate(transformation, rotation, glm::vec3(0.0f, 0.0f, 1.0f)); } if (scale) { transformation = glm::scale(transformation, glm::vec3(scale)); } renderText(text, transformation, yOffsets, color, opacity); } void Engine::handleMouseEvents() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: case SDL_KEYDOWN: _isLoopRunning = true; break; case SDL_MOUSEBUTTONDOWN: _isMouseButtonDown = true; break; case SDL_MOUSEBUTTONUP: _isMouseButtonDown = false; break; case SDL_MOUSEMOTION: _mousePosition = Size2D(static_cast<float>(event.motion.x), static_cast<float>(event.motion.y)); break; default: break; } } } SDL_Surface& Engine::getTexture(TextureId textureId) const { auto& textureIter = _textureMapById.find(textureId); assert(textureIter != _textureMapById.end()); return *(textureIter->second); } void Engine::destroyTexture(SDL_Surface* texture) { SDL_FreeSurface(texture); } std::optional<Engine::TextureId> Engine::findTextureByAsset(const std::string& assetPath) { const std::string assetFullPath = getFullPathFromAssetName(assetPath); const auto &assetTextureIdIter = _textureMapByAssetName.find(assetFullPath); if (assetTextureIdIter != _textureMapByAssetName.end()) { return assetTextureIdIter->second; } return std::nullopt; } float Engine::getCharacterAdvance(char character, float scale) const { Glyph& g = findGlyph(character); return static_cast<float>(g.advance + InterLetterAdvance) * scale; } Glyph& Engine::findGlyph(char c) const { auto found = std::lower_bound(std::begin(Font), std::end(Font), c); if (found == std::end(Font) || c < *found) { found = std::lower_bound(std::begin(Font), std::end(Font), static_cast<int>('_')); } return *found; }
28.257653
187
0.737384
gabr1e11
f03e9404d821b0d336e0128af0599b751ac4b67d
953
hpp
C++
drivers/LightDriver.hpp
jpmorris33/syntheyes3
36b0312616145e8da44868897f231cbe7702a64f
[ "BSD-3-Clause" ]
2
2022-01-24T23:00:43.000Z
2022-03-01T01:39:08.000Z
drivers/LightDriver.hpp
jpmorris33/syntheyes3
36b0312616145e8da44868897f231cbe7702a64f
[ "BSD-3-Clause" ]
null
null
null
drivers/LightDriver.hpp
jpmorris33/syntheyes3
36b0312616145e8da44868897f231cbe7702a64f
[ "BSD-3-Clause" ]
null
null
null
#ifndef __LIGHTDRIVER_HPP__ #define __LIGHTDRIVER_HPP__ #include <stdint.h> #include "../gpio.hpp" #define LIGHTMODE_NORMAL 0 #define LIGHTMODE_UNISON 1 #define LIGHTMODE_STOP 2 class LightDriver { public: virtual void init(int ledcount, const char *param); virtual void draw(); void update(); void force(int percentage); void setPattern(unsigned char pattern[16]); void setColour(uint32_t rgb); void setBrightness(int percentage); void setMode(int mode); protected: int leds; int ledpos; unsigned char r,g,b; int brightness; unsigned char bright256; int lightmode; unsigned char *framebuffer; unsigned char oldpattern[16]; unsigned char curpattern[16]; private: void update_normal(); void update_unison(unsigned char bright); }; extern const char *getDriverParam(const char *string, const char *cmd); extern int getDriverInt(const char *param); extern const char *getDriverStr(const char *param); #endif
23.243902
71
0.749213
jpmorris33
f03ffe50c467b584222e8654ef6121c1798d50b0
1,037
cpp
C++
MetalTrainer/src/WorkoutThread.cpp
eperiod-software/metal-trainer
9a9307d15eda4c071357a0259069d2ddd6358d89
[ "BSD-3-Clause" ]
null
null
null
MetalTrainer/src/WorkoutThread.cpp
eperiod-software/metal-trainer
9a9307d15eda4c071357a0259069d2ddd6358d89
[ "BSD-3-Clause" ]
null
null
null
MetalTrainer/src/WorkoutThread.cpp
eperiod-software/metal-trainer
9a9307d15eda4c071357a0259069d2ddd6358d89
[ "BSD-3-Clause" ]
null
null
null
/* * WorkoutThread.cpp * * Created on: Jul 9, 2013 * Author: Vaughn Friesen */ #include <QThread> #include <iostream> #include "WorkoutThread.h" #include "interval/IntervalManager.h" using namespace std; WorkoutThread::WorkoutThread(int workout) { this->workout = workout; } WorkoutThread::~WorkoutThread() { } WorkoutThread *WorkoutThread::startThread(int workout) { QThread *thread = new QThread(); WorkoutThread *worker = new WorkoutThread(workout); worker->moveToThread(thread); connect(thread, SIGNAL(started()), worker, SLOT(process())); connect(worker, SIGNAL(finished()), thread, SLOT(quit())); connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); return worker; } void WorkoutThread::process() { IntervalManager *mgr = IntervalManager::getInstance(); if (!mgr->launchWorkout(workout)) cout << "Launching workout failed" << endl; cout << "Finishing launcher thread" << endl; emit finished(); }
22.06383
66
0.708775
eperiod-software
f0440fd02aa633860690289c79634eadccb8c151
6,026
cpp
C++
ledger/environment.cpp
michealbrownm/phantom
a1a41a6f9317c26e621952637c7e331c8dacf79d
[ "Apache-2.0" ]
27
2020-09-24T03:14:13.000Z
2021-11-29T14:00:36.000Z
ledger/environment.cpp
david2011dzha/phantom
eff76713e03966eb44e20a07806b8d47ec73ad09
[ "Apache-2.0" ]
null
null
null
ledger/environment.cpp
david2011dzha/phantom
eff76713e03966eb44e20a07806b8d47ec73ad09
[ "Apache-2.0" ]
10
2020-09-24T14:34:30.000Z
2021-02-22T06:50:31.000Z
/* phantom is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. phantom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with phantom. If not, see <http://www.gnu.org/licenses/>. */ #include <common/storage.h> #include "ledger_manager.h" #include "environment.h" namespace phantom{ Environment::Environment(mapKV* data, settingKV* settings) : AtomMap<std::string, AccountFrm>(data), settings_(settings) { useAtomMap_ = Configure::Instance().ledger_configure_.use_atom_map_; parent_ = nullptr; } Environment::Environment(Environment* parent){ useAtomMap_ = Configure::Instance().ledger_configure_.use_atom_map_; if (useAtomMap_) { parent_ = nullptr; return; } parent_ = parent; if (parent_){ for (auto it = parent_->entries_.begin(); it != parent_->entries_.end(); it++){ entries_[it->first] = std::make_shared<AccountFrm>(it->second); } settings_ = parent->settings_; } } bool Environment::GetEntry(const std::string &key, AccountFrm::pointer &frm){ if (useAtomMap_) return Get(key, frm); if (entries_.find(key) == entries_.end()){ if (AccountFromDB(key, frm)){ entries_[key] = frm; return true; } else{ return false; } } else{ frm = entries_[key]; return true; } } bool Environment::Commit(){ if (useAtomMap_){ return settings_.Commit() && AtomMap<std::string, AccountFrm>::Commit(); } parent_->entries_ = entries_; parent_->settings_ = settings_; return true; } void Environment::ClearChangeBuf() { if (useAtomMap_){ settings_.ClearChangeBuf(); AtomMap<std::string, AccountFrm>::ClearChangeBuf(); } } bool Environment::AddEntry(const std::string& key, AccountFrm::pointer frm){ if (useAtomMap_ == true) return Set(key, frm); entries_[key] = frm; return true; } bool Environment::GetFromDB(const std::string &address, AccountFrm::pointer &account_ptr) { return AccountFromDB(address, account_ptr); } bool Environment::AccountFromDB(const std::string &address, AccountFrm::pointer &account_ptr){ auto db = Storage::Instance().account_db(); std::string index = DecodeAddress(address); std::string buff; if (!LedgerManager::Instance().tree_->Get(index, buff)){ return false; } protocol::Account account; if (!account.ParseFromString(buff)){ PROCESS_EXIT("fatal error, account(%s) ParseFromString failed", address.c_str()); } account_ptr = std::make_shared<AccountFrm>(account); return true; } std::shared_ptr<Environment> Environment::NewStackFrameEnv() { mapKV& data = GetActionBuf(); settingKV& settings = settings_.GetActionBuf(); std::shared_ptr<Environment> next = std::make_shared<Environment>(&data, &settings); return next; } bool Environment::UpdateFeeConfig(const Json::Value &feeConfig) { std::shared_ptr<Json::Value> fees; settings_.Get(feesKey, fees); if (!fees){ fees = std::make_shared<Json::Value>(feeConfig); settings_.Set(feesKey, fees); } else{ for (auto it = feeConfig.begin(); it != feeConfig.end(); it++) { (*fees)[it.memberName()] = feeConfig[it.memberName()]; } } return true; } bool Environment::GetVotedFee(const protocol::FeeConfig &old_fee, protocol::FeeConfig& new_fee) { bool change = false; new_fee = old_fee; std::shared_ptr<Json::Value> fees; settings_.Get(feesKey, fees); if (!fees) return false; for (auto it = fees->begin(); it != fees->end(); it++) { int32_t fee_type = (protocol::FeeConfig_Type)utils::String::Stoi(it.memberName()); int64_t price = (*fees)[it.memberName()].asInt64(); switch ((protocol::FeeConfig_Type)fee_type) { case protocol::FeeConfig_Type_UNKNOWN: LOG_ERROR("FeeConfig type error"); break; case protocol::FeeConfig_Type_GAS_PRICE: if (new_fee.gas_price() != price) { new_fee.set_gas_price(price); change = true; } break; case protocol::FeeConfig_Type_BASE_RESERVE: if (new_fee.base_reserve() != price) { new_fee.set_base_reserve(price); change = true; } break; default: LOG_ERROR("Fee config type(%d) error", fee_type); break; } } return change; } Json::Value& Environment::GetValidators(){ std::shared_ptr<Json::Value> validators; settings_.Get(validatorsKey, validators); if (!validators){ validators = std::make_shared<Json::Value>(); auto sets = LedgerManager::Instance().Validators(); for (int i = 0; i < sets.validators_size(); i++){ auto validator = sets.mutable_validators(i); Json::Value value; value.append(validator->address()); value.append(utils::String::ToString(validator->pledge_coin_amount())); validators->append(value); } settings_.Set(validatorsKey, validators); } return *validators; } bool Environment::UpdateNewValidators(const Json::Value& validators) { return settings_.Set(validatorsKey, std::make_shared<Json::Value>(validators)); } bool Environment::GetVotedValidators(const protocol::ValidatorSet &old_validator, protocol::ValidatorSet& new_validator){ std::shared_ptr<Json::Value> validators; bool ret = settings_.Get(validatorsKey, validators); if (!validators){ new_validator = old_validator; return false; } for (Json::Value::UInt i = 0; i < validators->size(); i++){ std::string address = (*validators)[i][(Json::Value::UInt)0].asString(); int64_t pledge_amount = utils::String::Stoi64( (*validators)[i][1].asString() ); auto validator = new_validator.add_validators(); validator->set_address(address); validator->set_pledge_coin_amount(pledge_amount); } return true; } }
27.022422
122
0.694656
michealbrownm
f047a96fd00fb9d967cd4ca6b208e1a7f20b78e3
1,208
cpp
C++
sources/systems/transform.cpp
wonderwombatgames/hydrogine
c44c113090a7a3e9357775c69b3e94adb9d6569d
[ "MIT" ]
null
null
null
sources/systems/transform.cpp
wonderwombatgames/hydrogine
c44c113090a7a3e9357775c69b3e94adb9d6569d
[ "MIT" ]
null
null
null
sources/systems/transform.cpp
wonderwombatgames/hydrogine
c44c113090a7a3e9357775c69b3e94adb9d6569d
[ "MIT" ]
null
null
null
/** * */ #include "systems/transform.hpp" namespace W2E { namespace System { Transform::Transform() : SystemsInterface{"Transform"} , components_{} { } Transform::Transform(const char* name) : SystemsInterface{name} , components_{} { } Transform::~Transform() {} void Transform::insert(Component::EntityPod& entity) { Component::TransformPod pod; this->components_.emplace(entity.entityId, pod); entity.transform = &(this->components_[entity.entityId]); entity.transform->position = {{0.0f, 0.0f, 0.0f}}; entity.transform->rotation = {{0.0f, 0.0f, 0.0f}}; entity.transform->scale = {{1.0f, 1.0f, 1.0f}}; } void Transform::remove(const Component::EntityPod& entity) { auto it = this->components_.find(entity.entityId); if(it != this->components_.end()) { this->components_.erase(it); } } void Transform::tick(TimeDim delta) {} ComponentBinderPtr Transform::getComponentBinder(ResourceID resourceId) { using TransformComponentBinder = ComponentBinder< void, TransformComponents >; ComponentBinderPtr retVal; retVal.reset(new TransformComponentBinder(this, nullptr, &components_)); return retVal; } } // end namespace System; } // end namespace W2E
21.192982
80
0.70447
wonderwombatgames
f04dc3b81b1621fa408dc81c34f342db99e6091b
7,504
cpp
C++
SummedAreaTable.cpp
xkong/envtools
682eeac42a7f173e24333ec4e94f87251ce6d579
[ "MIT" ]
68
2015-01-22T14:26:42.000Z
2022-02-17T23:39:20.000Z
SummedAreaTable.cpp
xkong/envtools
682eeac42a7f173e24333ec4e94f87251ce6d579
[ "MIT" ]
10
2015-03-15T19:34:25.000Z
2019-01-29T09:46:02.000Z
SummedAreaTable.cpp
xkong/envtools
682eeac42a7f173e24333ec4e94f87251ce6d579
[ "MIT" ]
11
2016-06-03T16:20:23.000Z
2020-07-13T11:29:42.000Z
#include <cassert> #include "SummedAreaTable" void SummedAreaTable::createLum(float* rgb, const uint width, const uint height, const uint nc) { assert(nc > 2); _width = width; _height = height; const uint imgSize = width * height; _sat.clear(); _sat.resize(imgSize); _sat1.clear(); _sat1.resize(imgSize); _sat2.clear(); _sat2.resize(imgSize); _sat3.clear(); _sat3.resize(imgSize); _sat4.clear(); _sat4.resize(imgSize); _sat5.clear(); _sat5.resize(imgSize); _r.clear(); _r.resize(imgSize); _g.clear(); _g.resize(imgSize); _b.clear(); _b.resize(imgSize); _sat[0] = 0.0; _sat1[0] = 0.0; _sat2[0] = 0.0; _sat3[0] = 0.0; _sat4[0] = 0.0; _sat5[0] = 0.0; _r[0] = 0.0; _g[0] = 0.0; _b[0] = 0.0; double weightAccum = 0.0; // solid angle for 1 pixel on equi map double weight = (4.0 * PI) / ((double)(imgSize)); Vec3f d; uint faceIdx; float aU, aV; _minLum = DBL_MAX; _maxLum = DBL_MIN; _minPonderedLum = DBL_MAX; _maxPonderedLum = DBL_MIN; _minR = DBL_MAX; _maxR = DBL_MIN; _minB = DBL_MAX; _maxG = DBL_MIN; _minB = DBL_MAX; _maxB = DBL_MIN; _sum = 0.0; for (uint y = 0; y < height; ++y) { const double posY = (double)(y+1.0) / (double)(height+1.0); // the latitude-longitude format overrepresents the area of regions near the poles. // To compensate for this, the pixels of the probe image // should first be scaled by cosφ. // (φ == 0 at middle height of image input) const double solidAngle = cos(PI* (posY - 0.5)) * weight; for (uint x = 0; x < width; ++x) { const uint i = y*width + x; double r = rgb[i*nc + 0]; double g = rgb[i*nc + 1]; double b = rgb[i*nc + 2]; double ixy = luminance(r,g,b); // update Min/Max before pondering _minLum = std::min(ixy, _minLum); _maxLum = std::max(ixy, _maxLum); _minR = std::min(r, _minR); _maxR = std::max(r, _maxR); _minG = std::min(g, _minG); _maxG = std::max(g, _maxG); _minB = std::min(b, _minB); _maxB = std::max(b, _maxB); #define _PONDER_REAL #ifdef _PONDER_REAL r *= solidAngle* imgSize; g *= solidAngle* imgSize; b *= solidAngle* imgSize; // ixy = luminance(r,g,b); // pondering luminance for unpondered colors makes more sense ixy *= solidAngle; #else // complex approx going through cubemap conversion // convert panorama to direction x,y,z //https://www.shadertoy.com/view/4dsGD2 double theta = (1.0 - posY) * PI; double phi = (double) x / (double)width * TAU; // Equation from http://graphicscodex.com [sphry] d[0] = sin(theta) * sin(phi); d[1] = cos(theta); d[2] = sin(theta) * cos(phi); d.normalize(); vectToTexelCoordPanorama(d, width, height, aU, aV ) ; const double solidAngle = texelPixelSolidAnglePanorama(aU, aV, width, height); // Then compute the solid Angle of that thing //const double solidAngle = texelPixelSolidAngle(x, y, width, height); ixy *= solidAngle; //r *= solidAngle; //g *= solidAngle; //b *= solidAngle; #endif _sat[i] = ixy; _r[i] = r; _g[i] = g; _b[i] = b; //weightAccum += weight; //weightAccum += 1.0; weightAccum += solidAngle; _sum += ixy; } } // store for later use. _weightAccum = weightAccum; bool normalize = true; if (normalize){ // normalize in order our image Accumulation exactly match 4 PI. const double normalizer = (4.0 * PI) / weightAccum; _sum *= normalizer; for (uint i = 0; i < imgSize; ++i) { _sat[i] *= normalizer; _minPonderedLum = std::min(_sat[i], _minPonderedLum); _maxPonderedLum = std::max(_sat[i], _maxPonderedLum); } } #define ENHANCE_PRECISION 1 #ifdef ENHANCE_PRECISION // enhances precision of SAT // make values be around [0.0, 0.5] // https://developer.amd.com/wordpress/media/2012/10/SATsketch-siggraph05.pdf const double rangeLum = _maxLum - _minLum; const double rangePonderedLum = _maxPonderedLum -_minPonderedLum; const double rangeR = _maxR - _minR; const double rangeG = _maxG - _minG; const double rangeB = _maxB - _minB; for (uint i = 0; i< imgSize; ++i) { _sat[i] = ((_sat[i] - _minPonderedLum) / rangePonderedLum) * 0.5; _r[i] = ((_r[i] - _minR) / rangeR) * 0.5; _g[i] = ((_g[i] - _minG) / rangeG) * 0.5; _b[i] = ((_b[i] - _minB) / rangeB) * 0.5; } #endif // now we sum for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x) { const uint i = y*width + x; // https://en.wikipedia.org/wiki/Summed_area_table _sat[i] = _sat[i] + I(x-1, y) + I(x, y-1) - I(x-1, y-1); _r[i] = _r[i] + R(x-1, y) + R(x, y-1) - R(x-1, y-1); _g[i] = _g[i] + G(x-1, y) + G(x, y-1) - G(x-1, y-1); _b[i] = _b[i] + B(x-1, y) + B(x, y-1) - B(x-1, y-1); } } // integral log for (uint y = 0; y < _height; ++y) { for (uint x = 0; x < _width; ++x) { const uint i = y*width + x; double sum = I(x, y); if (sum > 0) sum = log(I(x, y)); _sat1[i] = sum + I1(x-1, y) + I1(x, y-1) - I1(x-1, y-1); } } // Integral image of higher power // http://vision.okstate.edu/pubs/ssiai_tp_1.pdf // integral 2 for (uint y = 0; y < _height; ++y) { for (uint x = 0; x < _width; ++x) { const uint i = y*width + x; _sat2[i] = I(x, y)*I(x, y) + I2(x-1, y) + I2(x, y-1) - I2(x-1, y-1); } } // integral 3 for (uint y = 0; y < _height; ++y) { for (uint x = 0; x < _width; ++x) { const uint i = y*width + x; _sat3[i] = I(x, y)*I(x, y)*I(x, y) + I3(x-1, y) + I3(x, y-1) - I3(x-1, y-1); } } // integral 4 for (uint y = 0; y < _height; ++y) { for (uint x = 0; x < _width; ++x) { const uint i = y*width + x; _sat4[i] = I(x, y)*I(x, y)*I(x, y)*I(x, y) + I4(x-1, y) + I4(x, y-1) - I4(x-1, y-1); } } // integral 5 for (uint y = 0; y < _height; ++y) { for (uint x = 0; x < _width; ++x) { const uint i = y*width + x; _sat5[i] = I(x, y)*I(x, y)*I(x, y)*I(x, y) + I5(x-1, y) + I5(x, y-1) - I5(x-1, y-1); } } }
28.861538
100
0.457756
xkong
f05441f5e8f1416f9568bf4e879cfae1229eab01
5,153
hpp
C++
include/lvr2/geometry/BoundingBox.hpp
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
38
2019-06-19T15:10:35.000Z
2022-02-16T03:08:24.000Z
include/lvr2/geometry/BoundingBox.hpp
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
9
2019-06-19T16:19:51.000Z
2021-09-17T08:31:25.000Z
include/lvr2/geometry/BoundingBox.hpp
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
13
2019-04-16T11:50:32.000Z
2020-11-26T07:47:44.000Z
/** * Copyright (c) 2018, University Osnabrück * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University Osnabrück 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 University Osnabrück 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. */ /* * BoundingBox.hpp * * @date 22.10.2008 * @author Thomas Wiemann (twiemann@uos.de) */ #pragma once #include <cmath> #include <ostream> #include "lvr2/io/LineReader.hpp" namespace lvr2 { /** * @brief A dynamic bounding box class. */ template<typename BaseVecT> class BoundingBox { public: using VectorType = BaseVecT; /** * @brief Default constructor */ BoundingBox(); /** * @brief Constructs a bounding box with from the given vertices * * @param v1 Lower left corner of the BoundingBox * @param v2 Upper right corner of the BoundingBox * @return */ template<typename T> BoundingBox(T v1, T v2); /** * * @brief Constructs a bounding box for a given point cloud * * @param plyPath path of the point cloud */ BoundingBox(std::string plyPath); /** * @brief Expands the bounding box if the given Vector \ref{v} is * outside the current volume * * @param v A 3d Vector */ template<typename T> inline void expand(T v); /** * @brief Calculates the surrounding bounding box of the current * volume and the other given bounding box * * @param bb Another bounding box */ inline void expand(const BoundingBox<BaseVecT>& bb); /** * @brief Returns the radius of the current volume, i.e. the distance * between the centroid and the most distant corner from this * Vector. */ typename BaseVecT::CoordType getRadius() const; /** * @brief Returns true if the bounding box has been expanded before or * was initialized with a preset size. */ bool isValid() const; /** * @brief Returns the center Vector of the bounding box. */ BaseVecT getCentroid() const; /** * @brief check if current volume overlap with a given bounding box * * @param bb Another bounding box * @return true if both boxes overlap */ bool overlap(const BoundingBox<BaseVecT>& bb); /** * @brief Returns the longest side of the bounding box */ typename BaseVecT::CoordType getLongestSide() const; /** * @brief Returns the x-size of the bounding box */ typename BaseVecT::CoordType getXSize() const; /** * @brief Returns the y-size of the bounding box */ typename BaseVecT::CoordType getYSize() const; /** * @brief Returns the z-size of the bounding box */ typename BaseVecT::CoordType getZSize() const; /** * @brief Returns the volume of the bounding box * @return */ typename BaseVecT::CoordType getVolume() const; /** * @brief Returns the upper right coordinates */ BaseVecT getMax() const; /** * @brief Returns the lower left coordinates */ BaseVecT getMin() const; private: /// The lower left Vector of the bounding box BaseVecT m_min; /// The upper right Vector of the bounding box BaseVecT m_max; /// The center Vector of the bounding box BaseVecT m_centroid; }; template<typename BaseVecT> inline std::ostream& operator<<(std::ostream& os, const BoundingBox<BaseVecT>& bb) { os << "Bounding Box[min: " << bb.getMin() << " max: " << bb.getMax(); os << " dimension: " << bb.getXSize() << ", " << bb.getYSize() << ", " << bb.getZSize() << "]" << std::endl; return os; } } // namespace lvr2 #include "lvr2/geometry/BoundingBox.tcc"
28.469613
86
0.649525
uos
f05b735b9fe46ff40ef491d8f7af6364ad43db50
3,643
cpp
C++
src/ofApp.cpp
carlesgutierrez/ofxVjMatics
8f7d1f3e7ef9a3b9db899f0f8549525303771f90
[ "MIT" ]
null
null
null
src/ofApp.cpp
carlesgutierrez/ofxVjMatics
8f7d1f3e7ef9a3b9db899f0f8549525303771f90
[ "MIT" ]
null
null
null
src/ofApp.cpp
carlesgutierrez/ofxVjMatics
8f7d1f3e7ef9a3b9db899f0f8549525303771f90
[ "MIT" ]
null
null
null
#include "ofApp.h" #include "ofxPublishScreen.h" ofxPublishScreen::FboPublisher myPublishScreen; //-------------------------------------------------------------- void ofApp::setup(){ ofSetFrameRate(30); ofBackground(0, 255, 0); //Load oll examples myRandomVideosPlayers.setup(); myParticles.setup(); myAnimatedBoxes.setup(); guiManager::getInstance()->setup(); #ifdef USE_SYPHON mainOutputSyphonServer.setName("OF_syphon"); // 1syphon #endif #ifdef USE_MTL_MAPPING _mapping = new ofxMtlMapping2D(); _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/shapes.xml", "mapping/controls/mapping.xml"); #endif #ifdef USE_PUBLISHSCREEN myPublishScreen.setup(20000, ofGetWidth(), ofGetHeight()); #endif } //-------------------------------------------------------------- void ofApp::update(){ #ifdef USE_MTL_MAPPING _mapping->update(); #endif if(guiManager::getInstance()->bBailongos)myRandomVideosPlayers.update(modeLocation,0,spaceVideos, false); if(guiManager::getInstance()->bParticles)myParticles.update(); myAnimatedBoxes.update(); #ifdef USE_PUBLISHSCREEN myPublishScreen.begin(); drawVisuals(); myPublishScreen.end(); #endif guiManager::getInstance()->update(); // udpate receiving OSC data frmom mobiles } //-------------------------------------------------------------- void ofApp::drawVisuals(){ if(guiManager::getInstance()->bBailongos)myRandomVideosPlayers.draw(); if(guiManager::getInstance()->bParticles)myParticles.draw(); myAnimatedBoxes.draw(); } //-------------------------------------------------------------- void ofApp::draw(){ ofSetWindowTitle("ApoloMatics - FrameRate = "+ ofToString(ofGetFrameRate(), 2)); // ---- #ifdef USE_MTL_MAPPING _mapping->bind(); #endif #ifdef USE_PUBLISHSCREEN ofSetColor(ofColor::white); myPublishScreen.draw(); #else drawVisuals(); #endif #ifdef USE_MTL_MAPPING _mapping->unbind(); //-------- mapping of the towers/shapes _mapping->draw(); #endif #ifdef USE_SYPHON mainOutputSyphonServer.publishScreen(); #endif } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ if(key == '8'){ myModeVisual = videosInLineArea; } else if(key == '9'){ myModeVisual = particlesArea; } else if(key == '0'){ myModeVisual = ribbonsArea; } } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ //myRandomVideosPlayers.mouseDragged(x,y,button); } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ //myRandomVideosPlayers.mousePressed(x,y,button); } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ //myRandomVideosPlayers.mouseReleased(x,y,button); } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } //-------------------------------------------------------------- void ofApp::audioReceived(float* input, int bufferSize, int nChannels) { //soundManager::getInstance()->audioReceived( input , bufferSize, nChannels ) ; }
21.556213
106
0.534999
carlesgutierrez
f05bbb4e23acf2d31bf9fcacecffd1054fbbf995
6,216
hpp
C++
Source/AllProjects/DataUtils/CIDXML/CIDXML_Attr.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/DataUtils/CIDXML/CIDXML_Attr.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/DataUtils/CIDXML/CIDXML_Attr.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDXML_Attr.hpp // // AUTHOR: Dean Roddey // // CREATED: 10/10/1999 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header file for the CIDXML_Attr.Cpp file, which implements // The TXMLAttr class. When a start tag is parsed and it contains attributes, // the start tag even must pass these out via the event callback. A list of // these objects is used to pass that data out. It just needs to hold the // key/value information and a little other data about the attribute. // // In order to support canonical XML foramatting, which requires that attrs // be sorted, we provide a comparator method for this class. This allows // a sorted collection to manipulate them. // // CAVEATS/GOTCHAS: // // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TXMLAttr // PREFIX: xattr // --------------------------------------------------------------------------- class CIDXMLEXP TXMLAttr : public TObject { public : // ------------------------------------------------------------------- // Public, static methods // ------------------------------------------------------------------- static tCIDLib::ESortComps eComp ( const TXMLAttr& xad1 , const TXMLAttr& xad2 ); // ------------------------------------------------------------------- // Public Constructors and Destructor // ------------------------------------------------------------------- TXMLAttr(); TXMLAttr ( const tCIDLib::TCh* const pszBaseName , const tCIDLib::TCh* const pszPrefix , const tCIDLib::TCh* const pszURI , const tCIDLib::TCh* const pszValue , const tCIDXML::EAttrTypes eType , const tCIDLib::TBoolean bExplicit ); TXMLAttr ( const TString& strBaseName , const TString& strPrefix , const TString& strURI , const TString& strValue , const tCIDXML::EAttrTypes eType , const tCIDLib::TBoolean bExplicit ); TXMLAttr(const TXMLAttr&) = default; TXMLAttr(TXMLAttr&&) = default; ~TXMLAttr(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TXMLAttr& operator=(const TXMLAttr&) = default; TXMLAttr& operator=(TXMLAttr&&) = default; tCIDLib::TBoolean operator== ( const TXMLAttr& xattrSrc ); tCIDLib::TBoolean operator!= ( const TXMLAttr& xattrSrc ); // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TBoolean bExplicit() const; tCIDXML::EAttrTypes eType() const; const TString& strBaseName() const; const TString& strPrefix() const; const TString& strQName() const; const TString& strURI() const; const TString& strValue() const; tCIDLib::TVoid Set ( const tCIDLib::TCh* const pszBaseName , const tCIDLib::TCh* const pszPrefix , const tCIDLib::TCh* const pszURI , const tCIDLib::TCh* const pszValue , const tCIDXML::EAttrTypes eType , const tCIDLib::TBoolean bExplicit ); tCIDLib::TVoid Set ( const TString& strBaseName , const TString& strPrefix , const TString& strURI , const TString& strValue , const tCIDXML::EAttrTypes eType , const tCIDLib::TBoolean bExplicit ); private : // ------------------------------------------------------------------- // Private data members // // m_bExplicit // This flag indicates whether the attribute was explicitly // provided or defaulted in. // // m_eType // The type of the attribute. // // m_strBaseName // This is the base name of the attribute, which is always // required. // // m_strPrefix // This is the prefix part of the name, if any. Regardless of // whether namespaces are enabled, this can be empty. // // m_strQName // This is the QName, which is built from the base name and // prefix. Because of the common need to access it, we don't want // to force client code to build it up themselves over and over. // // m_strURI // This is the URI the prefix maps to, empty if namespace // processing is not enabled. // // m_strValue // The value of this attribute. // ------------------------------------------------------------------- tCIDLib::TBoolean m_bExplicit; tCIDXML::EAttrTypes m_eType; TString m_strBaseName; TString m_strPrefix; TString m_strQName; TString m_strURI; TString m_strValue; // ------------------------------------------------------------------- // Magic macros // ------------------------------------------------------------------- RTTIDefs(TXMLAttr,TObject) }; #pragma CIDLIB_POPPACK
31.876923
78
0.444981
MarkStega
f05edfab1e8a1275eee582e969793b1adac692aa
53,865
cpp
C++
bench/ml2cpp-demo/BaggingRegressor_Pipeline/freidman3/ml2cpp-demo_BaggingRegressor_Pipeline_freidman3.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
null
null
null
bench/ml2cpp-demo/BaggingRegressor_Pipeline/freidman3/ml2cpp-demo_BaggingRegressor_Pipeline_freidman3.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
33
2020-09-13T09:55:01.000Z
2022-01-06T11:53:55.000Z
bench/ml2cpp-demo/BaggingRegressor_Pipeline/freidman3/ml2cpp-demo_BaggingRegressor_Pipeline_freidman3.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
1
2021-01-26T14:41:58.000Z
2021-01-26T14:41:58.000Z
// ******************************************************** // This C++ code was automatically generated by ml2cpp (development version). // Copyright 2020 // https://github.com/antoinecarme/ml2cpp // Model : BaggingRegressor_Pipeline // Dataset : freidman3 // This CPP code can be compiled using any C++-17 compiler. // g++ -Wall -Wno-unused-function -std=c++17 -g -o ml2cpp-demo_BaggingRegressor_Pipeline_freidman3.exe ml2cpp-demo_BaggingRegressor_Pipeline_freidman3.cpp // Model deployment code // ******************************************************** #include "../../Generic.i" namespace { namespace imputer { std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "imputer_output_2", "imputer_output_3", "imputer_output_4", "imputer_output_5" }; return lOutputs; } tTable compute_features(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3) { tTable lTable; lTable["imputer_output_2"] = { ((Feature_0 == std::any()) ? ( 43.79128122207401 ) : ( Feature_0)) }; lTable["imputer_output_3"] = { ((Feature_1 == std::any()) ? ( 945.9672833084396 ) : ( Feature_1)) }; lTable["imputer_output_4"] = { ((Feature_2 == std::any()) ? ( 0.5310009099975209 ) : ( Feature_2)) }; lTable["imputer_output_5"] = { ((Feature_3 == std::any()) ? ( 6.139967152050499 ) : ( Feature_3)) }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_features(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0]); return lTable; } } // eof namespace imputer namespace scaler { std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "imputer_output_2", "imputer_output_3", "imputer_output_4", "imputer_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lOutputs; } tTable compute_features(std::any imputer_output_2, std::any imputer_output_3, std::any imputer_output_4, std::any imputer_output_5) { tTable lTable; lTable["scaler_output_2"] = { ( ( imputer_output_2 - 43.79128122207401 ) / 26.03562357622511 ) }; lTable["scaler_output_3"] = { ( ( imputer_output_3 - 945.9672833084396 ) / 461.4552766146446 ) }; lTable["scaler_output_4"] = { ( ( imputer_output_4 - 0.5310009099975209 ) / 0.2901863282144786 ) }; lTable["scaler_output_5"] = { ( ( imputer_output_5 - 6.139967152050499 ) / 3.072917242564058 ) }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_features(iTable.at("imputer_output_2")[0], iTable.at("imputer_output_3")[0], iTable.at("imputer_output_4")[0], iTable.at("imputer_output_5")[0]); return lTable; } } // eof namespace scaler namespace model { namespace SubModel_0 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 3 , {0.48486692 }} , { 4 , {0.38342473 }} , { 5 , {0.61001684 }} , { 9 , {1.55432885 }} , { 11 , {1.40929984 }} , { 12 , {1.35633395 }} , { 14 , {0.70507147 }} , { 16 , {1.13749386 }} , { 17 , {1.33034355 }} , { 21 , {1.16100714 }} , { 22 , {1.14405643 }} , { 23 , {1.27887759 }} , { 26 , {1.49715235 }} , { 27 , {1.32892492 }} , { 29 , {1.53631304 }} , { 30 , {1.48947205 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.6865600943565369) ? ( (scaler_output_3 <= 1.0818820148706436) ? ( (scaler_output_3 <= -0.19290710985660553) ? ( 3 ) : ( 4 ) ) : ( 5 ) ) : ( (scaler_output_4 <= -0.37393590807914734) ? ( (scaler_output_2 <= 0.19635166227817535) ? ( (scaler_output_2 <= -1.346356213092804) ? ( 9 ) : ( (scaler_output_4 <= -1.660830020904541) ? ( 11 ) : ( 12 ) ) ) : ( (scaler_output_4 <= -1.3605417609214783) ? ( 14 ) : ( (scaler_output_3 <= 0.32986392825841904) ? ( 16 ) : ( 17 ) ) ) ) : ( (scaler_output_3 <= -1.495688259601593) ? ( (scaler_output_3 <= -1.5442689657211304) ? ( (scaler_output_5 <= -0.5514519065618515) ? ( 21 ) : ( 22 ) ) : ( 23 ) ) : ( (scaler_output_3 <= -0.9236918985843658) ? ( (scaler_output_2 <= 0.17494834959506989) ? ( 26 ) : ( 27 ) ) : ( (scaler_output_2 <= 0.18584853038191795) ? ( 29 ) : ( 30 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_0 namespace SubModel_1 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.61001684 }} , { 3 , {0.38342473 }} , { 7 , {0.80791092 }} , { 8 , {0.70507147 }} , { 11 , {1.26879448 }} , { 12 , {1.1030161 }} , { 14 , {1.40929984 }} , { 15 , {1.34636148 }} , { 19 , {1.53596709 }} , { 20 , {1.43130244 }} , { 22 , {1.46088901 }} , { 23 , {1.18648202 }} , { 26 , {1.42518022 }} , { 27 , {1.35886857 }} , { 29 , {1.53022139 }} , { 30 , {1.49648065 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.7298851609230042) ? ( (scaler_output_2 <= -0.6579667255282402) ? ( 2 ) : ( 3 ) ) : ( (scaler_output_4 <= -0.7780995666980743) ? ( (scaler_output_3 <= -0.9540339708328247) ? ( (scaler_output_4 <= -1.4776207208633423) ? ( 7 ) : ( 8 ) ) : ( (scaler_output_3 <= 0.32986392825841904) ? ( (scaler_output_2 <= 0.8264346718788147) ? ( 11 ) : ( 12 ) ) : ( (scaler_output_5 <= -0.8546210080385208) ? ( 14 ) : ( 15 ) ) ) ) : ( (scaler_output_3 <= -0.9236918985843658) ? ( (scaler_output_2 <= -0.5679637044668198) ? ( (scaler_output_3 <= -1.717117726802826) ? ( 19 ) : ( 20 ) ) : ( (scaler_output_5 <= -1.3738551139831543) ? ( 22 ) : ( 23 ) ) ) : ( (scaler_output_4 <= -0.4938385933637619) ? ( (scaler_output_2 <= 0.07024127151817083) ? ( 26 ) : ( 27 ) ) : ( (scaler_output_2 <= 0.2522202655673027) ? ( 29 ) : ( 30 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_1 namespace SubModel_2 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 3 , {0.38342473 }} , { 4 , {0.48486692 }} , { 5 , {0.70507147 }} , { 9 , {1.53596709 }} , { 11 , {1.45085999 }} , { 12 , {1.16100714 }} , { 15 , {1.14405643 }} , { 16 , {1.11561476 }} , { 18 , {1.38449452 }} , { 19 , {1.27221806 }} , { 23 , {1.53671123 }} , { 24 , {1.34984299 }} , { 26 , {1.10634412 }} , { 27 , {1.081892 }} , { 30 , {1.567781 }} , { 31 , {1.53249386 }} , { 33 , {1.27948723 }} , { 34 , {1.49009524 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.3343552350997925) ? ( (scaler_output_2 <= 0.06683275103569031) ? ( (scaler_output_2 <= -0.15695498138666153) ? ( 3 ) : ( 4 ) ) : ( 5 ) ) : ( (scaler_output_3 <= -1.0727011263370514) ? ( (scaler_output_2 <= 0.040250442922115326) ? ( (scaler_output_4 <= -0.4686051160097122) ? ( 9 ) : ( (scaler_output_5 <= -1.3401830196380615) ? ( 11 ) : ( 12 ) ) ) : ( (scaler_output_3 <= -1.5181928873062134) ? ( (scaler_output_3 <= -1.5474199056625366) ? ( 15 ) : ( 16 ) ) : ( (scaler_output_2 <= 0.7340636104345322) ? ( 18 ) : ( 19 ) ) ) ) : ( (scaler_output_4 <= -0.5216203033924103) ? ( (scaler_output_2 <= 1.2749183773994446) ? ( (scaler_output_4 <= -0.8660534620285034) ? ( 23 ) : ( 24 ) ) : ( (scaler_output_2 <= 1.673033356666565) ? ( 26 ) : ( 27 ) ) ) : ( (scaler_output_2 <= 0.26149413734674454) ? ( (scaler_output_2 <= -1.3878793120384216) ? ( 30 ) : ( 31 ) ) : ( (scaler_output_3 <= -0.615314394235611) ? ( 33 ) : ( 34 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_2 namespace SubModel_3 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 3 , {0.38342473 }} , { 4 , {0.61001684 }} , { 7 , {0.80791092 }} , { 8 , {0.70507147 }} , { 11 , {1.40929984 }} , { 12 , {1.35009011 }} , { 13 , {1.14091625 }} , { 18 , {1.53596709 }} , { 19 , {1.45186094 }} , { 21 , {1.13377171 }} , { 22 , {1.27887759 }} , { 25 , {1.31432562 }} , { 26 , {1.34636148 }} , { 28 , {1.52863669 }} , { 29 , {1.48020213 }} , { 33 , {1.081892 }} , { 34 , {1.02748435 }} , { 35 , {1.15778604 }} , { 37 , {1.27948723 }} , { 38 , {1.49496626 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.3605417609214783) ? ( (scaler_output_4 <= -1.7298851609230042) ? ( (scaler_output_3 <= 1.0818820148706436) ? ( 3 ) : ( 4 ) ) : ( (scaler_output_3 <= -0.9296590089797974) ? ( (scaler_output_4 <= -1.4776207208633423) ? ( 7 ) : ( 8 ) ) : ( (scaler_output_5 <= 0.6717203818261623) ? ( (scaler_output_5 <= -0.6441354788839817) ? ( 11 ) : ( 12 ) ) : ( 13 ) ) ) ) : ( (scaler_output_2 <= 1.2387755811214447) ? ( (scaler_output_3 <= -1.495688259601593) ? ( (scaler_output_2 <= -0.6530774086713791) ? ( (scaler_output_3 <= -1.717117726802826) ? ( 18 ) : ( 19 ) ) : ( (scaler_output_4 <= 0.8984425663948059) ? ( 21 ) : ( 22 ) ) ) : ( (scaler_output_4 <= -0.9403093159198761) ? ( (scaler_output_4 <= -1.108010083436966) ? ( 25 ) : ( 26 ) ) : ( (scaler_output_2 <= -0.15516800433397293) ? ( 28 ) : ( 29 ) ) ) ) : ( (scaler_output_5 <= -0.606260135769844) ? ( (scaler_output_5 <= -1.0919035375118256) ? ( (scaler_output_5 <= -1.5203047394752502) ? ( 33 ) : ( 34 ) ) : ( 35 ) ) : ( (scaler_output_4 <= 0.5518082813359797) ? ( 37 ) : ( 38 ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_3 namespace SubModel_4 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {1.40929984 }} , { 5 , {0.61001684 }} , { 7 , {0.48486692 }} , { 8 , {0.37929615 }} , { 10 , {1.36871758 }} , { 11 , {0.70507147 }} , { 15 , {1.16100714 }} , { 16 , {1.53596709 }} , { 18 , {1.3413442 }} , { 20 , {1.46483828 }} , { 21 , {1.52332753 }} , { 25 , {1.07654708 }} , { 26 , {1.02748435 }} , { 28 , {1.15841469 }} , { 29 , {1.27887759 }} , { 31 , {1.34636148 }} , { 33 , {1.47832813 }} , { 34 , {1.50754127 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.4309000372886658) ? ( (scaler_output_5 <= -1.2066214084625244) ? ( 2 ) : ( (scaler_output_4 <= -1.5602660179138184) ? ( (scaler_output_4 <= -1.7965635061264038) ? ( 5 ) : ( (scaler_output_5 <= -0.14987096190452576) ? ( 7 ) : ( 8 ) ) ) : ( (scaler_output_2 <= -0.3636448532342911) ? ( 10 ) : ( 11 ) ) ) ) : ( (scaler_output_2 <= 0.6816338896751404) ? ( (scaler_output_3 <= -1.6158922910690308) ? ( (scaler_output_5 <= -0.046768903732299805) ? ( 15 ) : ( 16 ) ) : ( (scaler_output_4 <= -1.1599440574645996) ? ( 18 ) : ( (scaler_output_5 <= -1.2838689684867859) ? ( 20 ) : ( 21 ) ) ) ) : ( (scaler_output_3 <= -0.13757695525418967) ? ( (scaler_output_5 <= -0.7887826561927795) ? ( (scaler_output_4 <= 0.49538497254252434) ? ( 25 ) : ( 26 ) ) : ( (scaler_output_4 <= 1.1004490554332733) ? ( 28 ) : ( 29 ) ) ) : ( (scaler_output_2 <= 0.9817717373371124) ? ( 31 ) : ( (scaler_output_3 <= 0.18995892733801156) ? ( 33 ) : ( 34 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_4 namespace SubModel_5 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 3 , {1.14091625 }} , { 5 , {1.36871758 }} , { 6 , {1.40929984 }} , { 9 , {0.80791092 }} , { 10 , {0.70507147 }} , { 12 , {0.48486692 }} , { 14 , {0.37516757 }} , { 15 , {0.38342473 }} , { 20 , {1.53596709 }} , { 21 , {1.41074394 }} , { 23 , {1.11561476 }} , { 24 , {1.38449452 }} , { 26 , {1.31432562 }} , { 28 , {1.55172203 }} , { 29 , {1.50101215 }} , { 33 , {1.34752198 }} , { 34 , {1.26722342 }} , { 36 , {1.1360622 }} , { 37 , {1.05468818 }} , { 39 , {1.27887759 }} , { 41 , {1.46708262 }} , { 42 , {1.50181409 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.3605417609214783) ? ( (scaler_output_2 <= -0.5874325856566429) ? ( (scaler_output_3 <= -0.4679744988679886) ? ( 3 ) : ( (scaler_output_3 <= 0.6646461933851242) ? ( 5 ) : ( 6 ) ) ) : ( (scaler_output_5 <= -0.7836979031562805) ? ( (scaler_output_5 <= -1.1247649788856506) ? ( 9 ) : ( 10 ) ) : ( (scaler_output_5 <= -0.14987096190452576) ? ( 12 ) : ( (scaler_output_3 <= -0.2956656664609909) ? ( 14 ) : ( 15 ) ) ) ) ) : ( (scaler_output_2 <= 0.8440569937229156) ? ( (scaler_output_3 <= -1.2677711248397827) ? ( (scaler_output_2 <= -0.35382256656885147) ? ( (scaler_output_3 <= -1.6177831292152405) ? ( 20 ) : ( 21 ) ) : ( (scaler_output_4 <= 0.3329373747110367) ? ( 23 ) : ( 24 ) ) ) : ( (scaler_output_4 <= -1.1697484254837036) ? ( 26 ) : ( (scaler_output_2 <= -0.7974012792110443) ? ( 28 ) : ( 29 ) ) ) ) : ( (scaler_output_4 <= 1.0049840807914734) ? ( (scaler_output_2 <= 1.241290807723999) ? ( (scaler_output_4 <= -0.253071166574955) ? ( 33 ) : ( 34 ) ) : ( (scaler_output_2 <= 1.8500051498413086) ? ( 36 ) : ( 37 ) ) ) : ( (scaler_output_3 <= -0.8243342787027359) ? ( 39 ) : ( (scaler_output_3 <= 0.026924937963485718) ? ( 41 ) : ( 42 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_5 namespace SubModel_6 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 4 , {1.14091625 }} , { 5 , {1.36871758 }} , { 6 , {0.61001684 }} , { 9 , {0.37516757 }} , { 10 , {0.38342473 }} , { 12 , {0.80791092 }} , { 13 , {0.70507147 }} , { 18 , {1.41074394 }} , { 19 , {1.46071017 }} , { 21 , {1.14587635 }} , { 22 , {1.32935424 }} , { 25 , {1.12520028 }} , { 26 , {1.19835311 }} , { 28 , {1.07654708 }} , { 29 , {1.02748435 }} , { 32 , {1.31432562 }} , { 33 , {1.081892 }} , { 36 , {1.55559363 }} , { 37 , {1.53370949 }} , { 39 , {1.46679899 }} , { 40 , {1.49524974 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.3605417609214783) ? ( (scaler_output_2 <= -0.5874325856566429) ? ( (scaler_output_3 <= 0.7551565617322922) ? ( (scaler_output_2 <= -1.028288573026657) ? ( 4 ) : ( 5 ) ) : ( 6 ) ) : ( (scaler_output_4 <= -1.5640677213668823) ? ( (scaler_output_3 <= -0.2956656664609909) ? ( 9 ) : ( 10 ) ) : ( (scaler_output_5 <= -1.1247649788856506) ? ( 12 ) : ( 13 ) ) ) ) : ( (scaler_output_3 <= -0.34917865693569183) ? ( (scaler_output_2 <= 1.1800363659858704) ? ( (scaler_output_2 <= -0.2754115164279938) ? ( (scaler_output_5 <= -0.13076937198638916) ? ( 18 ) : ( 19 ) ) : ( (scaler_output_3 <= -1.5181928873062134) ? ( 21 ) : ( 22 ) ) ) : ( (scaler_output_2 <= 1.7521882057189941) ? ( (scaler_output_2 <= 1.4051255583763123) ? ( 25 ) : ( 26 ) ) : ( (scaler_output_4 <= 0.49538497254252434) ? ( 28 ) : ( 29 ) ) ) ) : ( (scaler_output_4 <= -1.1435618996620178) ? ( (scaler_output_4 <= -1.225070297718048) ? ( 32 ) : ( 33 ) ) : ( (scaler_output_2 <= 0.17194722779095173) ? ( (scaler_output_2 <= -1.19354248046875) ? ( 36 ) : ( 37 ) ) : ( (scaler_output_3 <= 0.025099143385887146) ? ( 39 ) : ( 40 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_6 namespace SubModel_7 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.38342473 }} , { 3 , {0.37516757 }} , { 8 , {0.70507147 }} , { 9 , {1.081892 }} , { 11 , {1.13828483 }} , { 12 , {1.36871758 }} , { 15 , {1.54552004 }} , { 16 , {1.47795145 }} , { 18 , {1.32783491 }} , { 19 , {1.34636148 }} , { 23 , {1.54877679 }} , { 24 , {1.43815527 }} , { 26 , {1.11649954 }} , { 27 , {1.33419435 }} , { 30 , {1.55364397 }} , { 31 , {1.52190806 }} , { 33 , {1.46424873 }} , { 34 , {1.49524786 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.6357912421226501) ? ( (scaler_output_5 <= 0.7462165057659149) ? ( 2 ) : ( 3 ) ) : ( (scaler_output_4 <= -0.4017176181077957) ? ( (scaler_output_3 <= 0.28764166682958603) ? ( (scaler_output_5 <= -0.9156729280948639) ? ( (scaler_output_4 <= -1.3343552350997925) ? ( 8 ) : ( 9 ) ) : ( (scaler_output_3 <= -0.2286939173936844) ? ( 11 ) : ( 12 ) ) ) : ( (scaler_output_2 <= -0.16294515877962112) ? ( (scaler_output_2 <= -0.9280877113342285) ? ( 15 ) : ( 16 ) ) : ( (scaler_output_2 <= 0.7302617281675339) ? ( 18 ) : ( 19 ) ) ) ) : ( (scaler_output_3 <= -0.8848086297512054) ? ( (scaler_output_2 <= -0.5679637044668198) ? ( (scaler_output_2 <= -1.2143871784210205) ? ( 23 ) : ( 24 ) ) : ( (scaler_output_3 <= -1.555534303188324) ? ( 26 ) : ( 27 ) ) ) : ( (scaler_output_2 <= 0.26149413734674454) ? ( (scaler_output_2 <= -0.5963975787162781) ? ( 30 ) : ( 31 ) ) : ( (scaler_output_3 <= -0.2016371637582779) ? ( 33 ) : ( 34 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_7 namespace SubModel_8 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {1.35009011 }} , { 4 , {0.80791092 }} , { 6 , {0.38342473 }} , { 7 , {0.37516757 }} , { 12 , {1.41074394 }} , { 13 , {1.36789414 }} , { 15 , {1.52208363 }} , { 16 , {1.46088901 }} , { 18 , {1.36871758 }} , { 20 , {1.5558566 }} , { 21 , {1.51412624 }} , { 25 , {1.11195258 }} , { 26 , {1.1610368 }} , { 27 , {1.38449452 }} , { 30 , {1.3214291 }} , { 31 , {1.081892 }} , { 33 , {1.46665718 }} , { 34 , {1.48912378 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.481613039970398) ? ( (scaler_output_2 <= -0.590480200946331) ? ( 2 ) : ( (scaler_output_3 <= -1.0840756297111511) ? ( 4 ) : ( (scaler_output_2 <= 0.2745603397488594) ? ( 6 ) : ( 7 ) ) ) ) : ( (scaler_output_2 <= 0.20899805426597595) ? ( (scaler_output_5 <= -1.3374958038330078) ? ( (scaler_output_4 <= 0.23203356564044952) ? ( (scaler_output_2 <= -0.3779405727982521) ? ( 12 ) : ( 13 ) ) : ( (scaler_output_5 <= -1.4630562663078308) ? ( 15 ) : ( 16 ) ) ) : ( (scaler_output_4 <= -1.2830256819725037) ? ( 18 ) : ( (scaler_output_2 <= -0.8880466222763062) ? ( 20 ) : ( 21 ) ) ) ) : ( (scaler_output_3 <= -0.5494245290756226) ? ( (scaler_output_4 <= 0.9384577572345734) ? ( (scaler_output_4 <= -0.19714802643284202) ? ( 25 ) : ( 26 ) ) : ( 27 ) ) : ( (scaler_output_4 <= -0.26058902591466904) ? ( (scaler_output_2 <= 1.6245991587638855) ? ( 30 ) : ( 31 ) ) : ( (scaler_output_3 <= -0.1196240484714508) ? ( 33 ) : ( 34 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_8 namespace SubModel_9 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.61001684 }} , { 4 , {0.48486692 }} , { 5 , {0.38342473 }} , { 9 , {1.1968265 }} , { 11 , {1.40929984 }} , { 12 , {1.3575411 }} , { 15 , {1.56030668 }} , { 16 , {1.53549644 }} , { 18 , {1.27887759 }} , { 19 , {1.4856347 }} , { 23 , {1.07921954 }} , { 24 , {1.02748435 }} , { 26 , {1.12349143 }} , { 27 , {1.23229966 }} , { 29 , {1.46708262 }} , { 30 , {1.49322332 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.6865600943565369) ? ( (scaler_output_2 <= -0.6579667255282402) ? ( 2 ) : ( (scaler_output_3 <= -0.19290710985660553) ? ( 4 ) : ( 5 ) ) ) : ( (scaler_output_2 <= 1.1021127700805664) ? ( (scaler_output_4 <= -1.0424461364746094) ? ( (scaler_output_3 <= -0.2286939173936844) ? ( 9 ) : ( (scaler_output_5 <= -0.6441354788839817) ? ( 11 ) : ( 12 ) ) ) : ( (scaler_output_2 <= -0.3589157611131668) ? ( (scaler_output_2 <= -1.3878793120384216) ? ( 15 ) : ( 16 ) ) : ( (scaler_output_3 <= -1.3856977820396423) ? ( 18 ) : ( 19 ) ) ) ) : ( (scaler_output_4 <= 1.0049840807914734) ? ( (scaler_output_5 <= -0.7887826561927795) ? ( (scaler_output_4 <= 0.49538497254252434) ? ( 23 ) : ( 24 ) ) : ( (scaler_output_4 <= -0.3880885704420507) ? ( 26 ) : ( 27 ) ) ) : ( (scaler_output_4 <= 1.3188034296035767) ? ( 29 ) : ( 30 ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_9 namespace SubModel_10 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.38342473 }} , { 3 , {0.37516757 }} , { 8 , {1.53192082 }} , { 9 , {1.57013152 }} , { 10 , {1.45186094 }} , { 13 , {1.15253179 }} , { 14 , {1.11561476 }} , { 16 , {1.13649067 }} , { 17 , {1.35048948 }} , { 21 , {1.55929544 }} , { 22 , {1.52804718 }} , { 24 , {1.34385284 }} , { 25 , {1.47263588 }} , { 26 , {1.081892 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.6357912421226501) ? ( (scaler_output_4 <= -1.7129992842674255) ? ( 2 ) : ( 3 ) ) : ( (scaler_output_3 <= -0.34917865693569183) ? ( (scaler_output_2 <= -1.0801426768302917) ? ( (scaler_output_2 <= -1.2143871784210205) ? ( (scaler_output_4 <= -0.2431742437183857) ? ( 8 ) : ( 9 ) ) : ( 10 ) ) : ( (scaler_output_3 <= -1.5181928873062134) ? ( (scaler_output_3 <= -1.5474199056625366) ? ( 13 ) : ( 14 ) ) : ( (scaler_output_4 <= -0.7780995666980743) ? ( 16 ) : ( 17 ) ) ) ) : ( (scaler_output_2 <= 1.6818326115608215) ? ( (scaler_output_2 <= 0.12355757132172585) ? ( (scaler_output_2 <= -1.0938920080661774) ? ( 21 ) : ( 22 ) ) : ( (scaler_output_4 <= -0.8606774806976318) ? ( 24 ) : ( 25 ) ) ) : ( 26 ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_10 namespace SubModel_11 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.38342473 }} , { 3 , {0.48486692 }} , { 7 , {0.80791092 }} , { 8 , {0.70507147 }} , { 11 , {1.11340366 }} , { 12 , {1.1968265 }} , { 14 , {1.36048096 }} , { 15 , {1.53671123 }} , { 19 , {1.55693496 }} , { 20 , {1.5285057 }} , { 22 , {1.45014868 }} , { 23 , {1.50824867 }} , { 26 , {1.21505182 }} , { 27 , {1.05201572 }} , { 29 , {1.34636148 }} , { 30 , {1.48282415 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.6865600943565369) ? ( (scaler_output_2 <= -0.15695498138666153) ? ( 2 ) : ( 3 ) ) : ( (scaler_output_4 <= -0.9838692843914032) ? ( (scaler_output_3 <= -0.9540339708328247) ? ( (scaler_output_4 <= -1.4776207208633423) ? ( 7 ) : ( 8 ) ) : ( (scaler_output_3 <= -0.2286939173936844) ? ( (scaler_output_3 <= -0.3915177583694458) ? ( 11 ) : ( 12 ) ) : ( (scaler_output_4 <= -1.1697484254837036) ? ( 14 ) : ( 15 ) ) ) ) : ( (scaler_output_2 <= 0.7946660220623016) ? ( (scaler_output_2 <= -0.3589157611131668) ? ( (scaler_output_2 <= -0.767800509929657) ? ( 19 ) : ( 20 ) ) : ( (scaler_output_3 <= 0.17564557399600744) ? ( 22 ) : ( 23 ) ) ) : ( (scaler_output_3 <= -0.37791891396045685) ? ( (scaler_output_2 <= 1.7521882057189941) ? ( 26 ) : ( 27 ) ) : ( (scaler_output_2 <= 0.9817717373371124) ? ( 29 ) : ( 30 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_11 namespace SubModel_12 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 4 , {0.48486692 }} , { 5 , {0.37516757 }} , { 6 , {0.80791092 }} , { 8 , {1.14091625 }} , { 9 , {1.40929984 }} , { 14 , {1.16100714 }} , { 15 , {1.11561476 }} , { 17 , {1.47989632 }} , { 18 , {1.38449452 }} , { 21 , {1.36871758 }} , { 22 , {1.33233801 }} , { 24 , {1.53673512 }} , { 25 , {1.48696741 }} , { 29 , {1.07921954 }} , { 30 , {1.21710895 }} , { 31 , {1.46708262 }} , { 33 , {1.34636148 }} , { 35 , {1.49230328 }} , { 36 , {1.50990015 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.481613039970398) ? ( (scaler_output_3 <= -0.80410435795784) ? ( (scaler_output_4 <= -1.5640677213668823) ? ( (scaler_output_2 <= 0.3028857856988907) ? ( 4 ) : ( 5 ) ) : ( 6 ) ) : ( (scaler_output_3 <= 0.3801743984222412) ? ( 8 ) : ( 9 ) ) ) : ( (scaler_output_2 <= 0.6816338896751404) ? ( (scaler_output_3 <= -1.2677711248397827) ? ( (scaler_output_5 <= 0.5453606434166431) ? ( (scaler_output_3 <= -1.6383969187736511) ? ( 14 ) : ( 15 ) ) : ( (scaler_output_4 <= 0.8441102802753448) ? ( 17 ) : ( 18 ) ) ) : ( (scaler_output_4 <= -1.089585781097412) ? ( (scaler_output_3 <= 0.2732888013124466) ? ( 21 ) : ( 22 ) ) : ( (scaler_output_2 <= -0.2323714792728424) ? ( 24 ) : ( 25 ) ) ) ) : ( (scaler_output_3 <= 0.1398674175143242) ? ( (scaler_output_5 <= 0.8137871325016022) ? ( (scaler_output_5 <= -0.7887826561927795) ? ( 29 ) : ( 30 ) ) : ( 31 ) ) : ( (scaler_output_4 <= -0.1691150963306427) ? ( 33 ) : ( (scaler_output_4 <= 1.545040786266327) ? ( 35 ) : ( 36 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_12 namespace SubModel_13 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 3 , {0.80791092 }} , { 5 , {0.48486692 }} , { 6 , {0.37516757 }} , { 8 , {0.61001684 }} , { 11 , {1.40929984 }} , { 12 , {1.35009011 }} , { 14 , {1.081892 }} , { 15 , {1.14091625 }} , { 20 , {1.53621514 }} , { 21 , {1.42518022 }} , { 23 , {1.11044163 }} , { 24 , {1.34636148 }} , { 26 , {1.16100714 }} , { 28 , {1.47039493 }} , { 29 , {1.52384973 }} , { 31 , {1.02748435 }} , { 32 , {1.07654708 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.1435618996620178) ? ( (scaler_output_3 <= -0.80410435795784) ? ( (scaler_output_5 <= -0.8493432998657227) ? ( 3 ) : ( (scaler_output_2 <= 0.3028857856988907) ? ( 5 ) : ( 6 ) ) ) : ( (scaler_output_4 <= -1.7431707978248596) ? ( 8 ) : ( (scaler_output_4 <= -1.6370146870613098) ? ( (scaler_output_2 <= -1.1099023222923279) ? ( 11 ) : ( 12 ) ) : ( (scaler_output_5 <= -0.17572009563446045) ? ( 14 ) : ( 15 ) ) ) ) ) : ( (scaler_output_2 <= 1.7969666719436646) ? ( (scaler_output_4 <= -0.4017176181077957) ? ( (scaler_output_2 <= 0.09435927774757147) ? ( (scaler_output_2 <= -0.6898520225659013) ? ( 20 ) : ( 21 ) ) : ( (scaler_output_3 <= 0.027333766222000122) ? ( 23 ) : ( 24 ) ) ) : ( (scaler_output_3 <= -1.7070884108543396) ? ( 26 ) : ( (scaler_output_3 <= -0.28210045397281647) ? ( 28 ) : ( 29 ) ) ) ) : ( (scaler_output_3 <= -1.494538426399231) ? ( 31 ) : ( 32 ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_13 namespace SubModel_14 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 3 , {1.14091625 }} , { 4 , {1.40929984 }} , { 7 , {0.80791092 }} , { 8 , {0.70507147 }} , { 10 , {0.48486692 }} , { 12 , {0.38342473 }} , { 13 , {0.37516757 }} , { 18 , {1.11561476 }} , { 19 , {1.16100714 }} , { 20 , {1.53596709 }} , { 22 , {1.31432562 }} , { 24 , {1.36789414 }} , { 25 , {1.51357611 }} , { 29 , {1.24737362 }} , { 30 , {1.07654708 }} , { 31 , {1.1082904 }} , { 33 , {1.34636148 }} , { 35 , {1.49889488 }} , { 36 , {1.47193903 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.3605417609214783) ? ( (scaler_output_2 <= -0.626136414706707) ? ( (scaler_output_3 <= 0.3801743984222412) ? ( 3 ) : ( 4 ) ) : ( (scaler_output_3 <= -1.0840756297111511) ? ( (scaler_output_2 <= 0.0887349471449852) ? ( 7 ) : ( 8 ) ) : ( (scaler_output_5 <= -0.14987096190452576) ? ( 10 ) : ( (scaler_output_5 <= 0.7462165057659149) ? ( 12 ) : ( 13 ) ) ) ) ) : ( (scaler_output_2 <= 0.84055495262146) ? ( (scaler_output_3 <= -1.4988391995429993) ? ( (scaler_output_5 <= 0.5780204124748707) ? ( (scaler_output_4 <= -0.0005476325750350952) ? ( 18 ) : ( 19 ) ) : ( 20 ) ) : ( (scaler_output_4 <= -1.1697484254837036) ? ( 22 ) : ( (scaler_output_5 <= -1.5956872701644897) ? ( 24 ) : ( 25 ) ) ) ) : ( (scaler_output_3 <= -0.2100047916173935) ? ( (scaler_output_3 <= -0.8670860826969147) ? ( (scaler_output_2 <= 1.6569893956184387) ? ( 29 ) : ( 30 ) ) : ( 31 ) ) : ( (scaler_output_5 <= -0.13076972588896751) ? ( 33 ) : ( (scaler_output_3 <= 1.2354365587234497) ? ( 35 ) : ( 36 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_14 namespace SubModel_15 { typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.61001684 }} , { 3 , {0.48486692 }} , { 7 , {0.70507147 }} , { 9 , {1.1509548 }} , { 10 , {1.081892 }} , { 12 , {1.53671123 }} , { 14 , {1.40929984 }} , { 15 , {1.34636148 }} , { 19 , {1.56316862 }} , { 20 , {1.52263693 }} , { 22 , {1.33168605 }} , { 23 , {1.47807992 }} , { 26 , {1.26722342 }} , { 27 , {1.09803608 }} , { 29 , {1.34984299 }} , { 30 , {1.48058871 }} }; int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = (scaler_output_4 <= -1.6865600943565369) ? ( (scaler_output_5 <= -0.680695652961731) ? ( 2 ) : ( 3 ) ) : ( (scaler_output_4 <= -0.7780995666980743) ? ( (scaler_output_3 <= 0.28764166682958603) ? ( (scaler_output_3 <= -0.9788162112236023) ? ( 7 ) : ( (scaler_output_2 <= 1.8500051498413086) ? ( 9 ) : ( 10 ) ) ) : ( (scaler_output_2 <= -1.2885634303092957) ? ( 12 ) : ( (scaler_output_4 <= -1.320627897977829) ? ( 14 ) : ( 15 ) ) ) ) : ( (scaler_output_2 <= 1.1021127700805664) ? ( (scaler_output_2 <= -0.15516800433397293) ? ( (scaler_output_2 <= -1.1985815167427063) ? ( 19 ) : ( 20 ) ) : ( (scaler_output_3 <= -1.2677711248397827) ? ( 22 ) : ( 23 ) ) ) : ( (scaler_output_3 <= -0.6523826867341995) ? ( (scaler_output_2 <= 1.1800363659858704) ? ( 26 ) : ( 27 ) ) : ( (scaler_output_4 <= 0.22499209642410278) ? ( 29 ) : ( 30 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; std::any lEstimator = lNodeValue [ 0 ]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace SubModel_15 std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) { std::vector<tTable> lTreeScores = { SubModel_0::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_1::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_2::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_3::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_4::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_5::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_6::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_7::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_8::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_9::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_10::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_11::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_12::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_13::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_14::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5), SubModel_15::compute_regression(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5) }; tTable lAggregatedTable = aggregate_bag_scores(lTreeScores, {"Estimator"}); tTable lTable; std::any lEstimator = lAggregatedTable["Estimator"][0]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]); return lTable; } } // eof namespace model std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3) { tTable lTable_imputer = imputer::compute_features(Feature_0, Feature_1, Feature_2, Feature_3); tTable lTable_scaler = scaler::compute_model_outputs_from_table( lTable_imputer ); tTable lTable_model = model::compute_model_outputs_from_table( lTable_scaler ); tTable lTable; std::any lEstimator = lTable_model[ "Estimator" ][0]; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0]); return lTable; } } // eof namespace int main() { score_csv_file("outputs/ml2cpp-demo/datasets/freidman3.csv"); return 0; }
42.954545
1,191
0.619605
antoinecarme
f06c3df9f58062bc9129e3c3c1e6fda77bb6108c
266
hpp
C++
include/mpp.hpp
tbs1980/mpp
5a704b48d5ab2386588c71987a7616a276380a99
[ "MIT" ]
null
null
null
include/mpp.hpp
tbs1980/mpp
5a704b48d5ab2386588c71987a7616a276380a99
[ "MIT" ]
null
null
null
include/mpp.hpp
tbs1980/mpp
5a704b48d5ab2386588c71987a7616a276380a99
[ "MIT" ]
null
null
null
#ifndef MPP_MPP_HPP #define MPP_MPP_HPP #include "mpp/version.hpp" #include "mpp/config.hpp" #include "mpp/chains/mcmc_chain.hpp" #include "mpp/hamiltonian/kinetic_energy_multivar_normal.hpp" #include "mpp/hamiltonian/classic_hamiltonian.hpp" #endif //MPP_MPP_HPP
24.181818
61
0.808271
tbs1980
f06efdd728a5ec5bea585997bf77a2bfcc579fc3
4,472
cpp
C++
build/cpp_test/src/massive/munit/async/AsyncTimeoutException.cpp
TomBebb/hxecs
80620512df7b32d70f1b59facdf8f6349192a166
[ "BSD-3-Clause" ]
null
null
null
build/cpp_test/src/massive/munit/async/AsyncTimeoutException.cpp
TomBebb/hxecs
80620512df7b32d70f1b59facdf8f6349192a166
[ "BSD-3-Clause" ]
null
null
null
build/cpp_test/src/massive/munit/async/AsyncTimeoutException.cpp
TomBebb/hxecs
80620512df7b32d70f1b59facdf8f6349192a166
[ "BSD-3-Clause" ]
null
null
null
// Generated by Haxe 3.4.7 #include <hxcpp.h> #ifndef INCLUDED_massive_haxe_Exception #include <massive/haxe/Exception.h> #endif #ifndef INCLUDED_massive_haxe_util_ReflectUtil #include <massive/haxe/util/ReflectUtil.h> #endif #ifndef INCLUDED_massive_munit_MUnitException #include <massive/munit/MUnitException.h> #endif #ifndef INCLUDED_massive_munit_async_AsyncTimeoutException #include <massive/munit/async/AsyncTimeoutException.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_3cb19e0e4e5633da_47_new,"massive.munit.async.AsyncTimeoutException","new",0x38cd2b63,"massive.munit.async.AsyncTimeoutException.new","massive/munit/async/AsyncTimeoutException.hx",47,0x266cf6b0) namespace massive{ namespace munit{ namespace async{ void AsyncTimeoutException_obj::__construct(::String message, ::Dynamic info){ HX_STACKFRAME(&_hx_pos_3cb19e0e4e5633da_47_new) HXLINE( 48) super::__construct(message,info); HXLINE( 49) this->type = ( (::String)(::massive::haxe::util::ReflectUtil_obj::here(hx::SourceInfo(HX_("AsyncTimeoutException.hx",54,cc,f7,06),49,HX_("massive.munit.async.AsyncTimeoutException",f1,3d,9d,d2),HX_("new",60,d0,53,00)))->__Field(HX_("className",a3,92,3d,dc),hx::paccDynamic)) ); } Dynamic AsyncTimeoutException_obj::__CreateEmpty() { return new AsyncTimeoutException_obj; } void *AsyncTimeoutException_obj::_hx_vtable = 0; Dynamic AsyncTimeoutException_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< AsyncTimeoutException_obj > _hx_result = new AsyncTimeoutException_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool AsyncTimeoutException_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x6b60f4c9) { if (inClassId<=(int)0x1e96a5df) { return inClassId==(int)0x00000001 || inClassId==(int)0x1e96a5df; } else { return inClassId==(int)0x6b60f4c9; } } else { return inClassId==(int)0x7ce6b12b; } } hx::ObjectPtr< AsyncTimeoutException_obj > AsyncTimeoutException_obj::__new(::String message, ::Dynamic info) { hx::ObjectPtr< AsyncTimeoutException_obj > __this = new AsyncTimeoutException_obj(); __this->__construct(message,info); return __this; } hx::ObjectPtr< AsyncTimeoutException_obj > AsyncTimeoutException_obj::__alloc(hx::Ctx *_hx_ctx,::String message, ::Dynamic info) { AsyncTimeoutException_obj *__this = (AsyncTimeoutException_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(AsyncTimeoutException_obj), true, "massive.munit.async.AsyncTimeoutException")); *(void **)__this = AsyncTimeoutException_obj::_hx_vtable; __this->__construct(message,info); return __this; } AsyncTimeoutException_obj::AsyncTimeoutException_obj() { } #if HXCPP_SCRIPTABLE static hx::StorageInfo *AsyncTimeoutException_obj_sMemberStorageInfo = 0; static hx::StaticInfo *AsyncTimeoutException_obj_sStaticStorageInfo = 0; #endif static void AsyncTimeoutException_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(AsyncTimeoutException_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void AsyncTimeoutException_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(AsyncTimeoutException_obj::__mClass,"__mClass"); }; #endif hx::Class AsyncTimeoutException_obj::__mClass; void AsyncTimeoutException_obj::__register() { hx::Object *dummy = new AsyncTimeoutException_obj; AsyncTimeoutException_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("massive.munit.async.AsyncTimeoutException","\xf1","\x3d","\x9d","\xd2"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = AsyncTimeoutException_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< AsyncTimeoutException_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = AsyncTimeoutException_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = AsyncTimeoutException_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = AsyncTimeoutException_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace massive } // end namespace munit } // end namespace async
38.222222
291
0.792039
TomBebb
f07126828164706da3c5200aa5f5be8bc01b76ba
1,219
cpp
C++
bellmanFord.cpp
PAlexcom/Algorithms
02cc55ad9b6975ebd1305a82cd9dbcf4ab4caa4d
[ "MIT" ]
1
2019-03-09T05:51:45.000Z
2019-03-09T05:51:45.000Z
bellmanFord.cpp
PAlexcom/Algorithms
02cc55ad9b6975ebd1305a82cd9dbcf4ab4caa4d
[ "MIT" ]
null
null
null
bellmanFord.cpp
PAlexcom/Algorithms
02cc55ad9b6975ebd1305a82cd9dbcf4ab4caa4d
[ "MIT" ]
1
2020-05-20T19:31:07.000Z
2020-05-20T19:31:07.000Z
#include <vector> using namespace std; void relax(vector<int> &parent, vector<int> &pathCost, vector<vector<int>> &matrix, int a, int b) { if (pathCost[b] > (pathCost[a] + matrix[a][b])) { pathCost[b] = pathCost[a] + matrix[a][b]; parent[b] = a; } } pair<vector<int>, vector<int>> bellmanFord(vector<LinkedList *> &adjacency, vector<vector<int>> &matrix, int root) { vector<pair<int, int>> result; vector<int> parent(adjacency.size(), -1); vector<int> pathCost(adjacency.size(), INT_MAX); parent[root] = 0; pathCost[root] = 0; for (int i = 0; i < adjacency.size(); i++) { for (int j = 0; j < adjacency.size(); j++) { LinkedListNode *tmp = adjacency[j]->head; while (tmp != NULL) { relax(parent, pathCost, matrix, j, tmp->data); tmp = tmp->next; } } } // Control if there is a negative cycle for (int i = 0; i < adjacency.size(); i++) { LinkedListNode *tmp = adjacency[i]->head; while (tmp != NULL) { if (pathCost[tmp->data] > (pathCost[i] + matrix[i][tmp->data])) { vector<int> a; a.push_back(-1); return make_pair(a, a); } tmp = tmp->next; } } return make_pair(parent, pathCost); }
27.704545
116
0.578343
PAlexcom
7eb6e9d2647a5ecb9b3c2fc578ec3d64c81209a2
554
cpp
C++
Motor2D/DynamicLabel.cpp
kistofe/Ramona-Flowers-vs-The-Code
dc87262279583b21fcb7de7231d7e16cfe6d477e
[ "MIT" ]
null
null
null
Motor2D/DynamicLabel.cpp
kistofe/Ramona-Flowers-vs-The-Code
dc87262279583b21fcb7de7231d7e16cfe6d477e
[ "MIT" ]
7
2017-11-13T13:24:15.000Z
2017-12-10T20:45:08.000Z
Motor2D/DynamicLabel.cpp
kistofe/Basic-Platformer
dc87262279583b21fcb7de7231d7e16cfe6d477e
[ "MIT" ]
null
null
null
#include "j1App.h" #include "DynamicLabel.h" #include "j1Fonts.h" #include "j1Textures.h" DynamicLabel::DynamicLabel(iPoint pos, j1Module* callback) : Label(pos, callback) {} DynamicLabel::~DynamicLabel() { } void DynamicLabel::ChangeContent(const char* new_content) { if (text_texture != nullptr) App->tex->UnLoad(text_texture); text_texture = App->font->Print(new_content); int w, h; SDL_QueryTexture(text_texture, NULL, NULL, &w, &h); SetArea(w, h); } void DynamicLabel::SetArea(uint w, uint h) { world_area.w = w; world_area.h = h; }
17.870968
81
0.709386
kistofe
7eba4f91f4f594fbc273bc7d1f8e8ce79b52e930
5,628
cpp
C++
examples/detectnet/utility.cpp
nFeus/reverse_detectnet
c25db99943763864398d08aa2ab69b8343d85db1
[ "MIT" ]
null
null
null
examples/detectnet/utility.cpp
nFeus/reverse_detectnet
c25db99943763864398d08aa2ab69b8343d85db1
[ "MIT" ]
null
null
null
examples/detectnet/utility.cpp
nFeus/reverse_detectnet
c25db99943763864398d08aa2ab69b8343d85db1
[ "MIT" ]
null
null
null
#include "function.hpp" std::vector <cv::Point> RoiVtx; extern int number_frame; extern int foggy_or_storm_frame; extern int normal_frame; std::chrono::system_clock::time_point start; std::chrono::system_clock::time_point end; bool reverse_detected = 0; bool on_timer = 0; int cnt_sec_tracking = 0; void stddev_modify(const std::string &std, int &stddev) { if (fileExists(std)) { std::ifstream std("/home/user/jetson-inference/dbict/control/stddev.txt"); std::string get_std; getline(std, get_std); stddev = stoi(get_std); system("rmdir /home/user/jetson-inference/dbict/control/std"); } } int get_stddev(const std::string &std_file) { std::ifstream std_num(std_file); std::string get_std; getline(std_num, get_std); return stoi(get_std); } void save_nextvideo(cv::VideoWriter &video, const std::string &record_video_file, const std::string &record_dir_by_date) { if (fileExists(record_video_file)) { char fName[100]; char gName[100]; char sys_rm[100]; // check video file size FILE *f; FILE *g; strcpy(fName, record_video_file.c_str()); f = fopen(fName, "r"); fseek(f, 0, SEEK_END); int fileLength = ftell(f); fclose(f); if (fileLength < 100) { std::string remove_cli = "rm " + record_video_file; strcpy(sys_rm, remove_cli.c_str()); system(sys_rm); video.open(record_video_file, VideoWriter::fourcc('a', 'v', 'c', '1'), save_video_fps, cv::Size(det_width, det_height), true); } else { for (int i = 1; i < 10; ++i) { std::string next_video_file = record_dir_by_date + "/" + to_hour() + "_" + to_string(i) + ".mp4"; if (fileExists(next_video_file)) { strcpy(gName, next_video_file.c_str()); g = fopen(gName, "r"); fseek(g, 0, SEEK_END); int fileLengths = ftell(g); fclose(g); if (fileLength < 100) { std::string remove_cli = "rm " + next_video_file; strcpy(sys_rm, remove_cli.c_str()); system(sys_rm); video.open(next_video_file, VideoWriter::fourcc('a', 'v', 'c', '1'), save_video_fps, cv::Size(det_width, det_height), true); break; } } else { video.open(next_video_file, VideoWriter::fourcc('a', 'v', 'c', '1'), save_video_fps, cv::Size(det_width, det_height), true); break; } } } } } void c_region(const std::string &region, const std::string &std_file) { if (fileExists(std_file)) { char poly[100]; std::ifstream c_region(region); if (c_region.is_open()) { RoiVtx.clear(); while (!c_region.eof()) { std::string position; getline(c_region, position); string *points = new string[256]; points = StringSplit(position, " "); for (int i = 0; i <= 30; i++) { poly[i * 2] = atoi(points[i * 2].c_str()); poly[i * 2 + 1] = atoi(points[i * 2 + 1].c_str()); if (poly[i * 2] != 0 && poly[i * 2 + 1] != 0) { RoiVtx.push_back(Point(poly[i * 2], poly[i * 2 + 1])); } } } } std::string rmdir_cli = "rmdir " + std_file; system(rmdir_cli.c_str()); } } bool check_bad_weather(int img_stddev, int get_cfg_stddev, std::ofstream &log_file) { if (img_stddev < get_cfg_stddev) { foggy_or_storm_frame++; normal_frame = 0; if (foggy_or_storm_frame >= one_second * 2) { normal_frame = 0; if (foggy_or_storm_frame == one_second * 2) { std::cout << "start bad weather:\t" << return_current_time_and_date() << "\tStdDev:\t" << img_stddev << endl; log_file << "start bad weather:\t" << return_current_time_and_date() << "\tStdDev:\t" << img_stddev << endl; } return 1; } } else { normal_frame++; return 0; } if (foggy_or_storm_frame > one_second * 2 && normal_frame > one_second * 3) { foggy_or_storm_frame = 0; std::cout << "stop bad weather:\t" << return_current_time_and_date() << "\tStdDev:\t" << img_stddev << endl; log_file << "stop bad weather:\t" << return_current_time_and_date() << "\tStdDev:\t" << img_stddev << endl; } if (foggy_or_storm_frame < one_second * 2 && normal_frame > one_second * 3) foggy_or_storm_frame = 0; return 0; } int tracking_clocks(const bool &is_reverse, std::ostringstream &out){ if(is_reverse) { out << " reverse : O" ; reverse_detected = true; if(!on_timer) { start = std::chrono::system_clock::now(); on_timer = true; } std::chrono::duration<double> sec = std::chrono::system_clock::now() - start; cnt_sec_tracking = static_cast<int>(sec.count()); }else{ out << " reverse : X" ; if(reverse_detected){ reverse_detected = false; on_timer = false; } } return cnt_sec_tracking; }
31.617978
117
0.519545
nFeus
7eba769cca233e0de7f8a103dd42f2d98f2ac856
739
hpp
C++
source/include/FlopTexturePuzzle.hpp
jane8384/seven-monkeys
119cb7312f25d54e88f212a8710a512b893b046d
[ "MIT" ]
3
2017-11-16T01:54:09.000Z
2018-05-20T15:33:21.000Z
include/FlopTexturePuzzle.hpp
aitorfernandez/seven-monkeys
8f2440fd5ae7a9e86bb71dba800efe9424f3792e
[ "MIT" ]
null
null
null
include/FlopTexturePuzzle.hpp
aitorfernandez/seven-monkeys
8f2440fd5ae7a9e86bb71dba800efe9424f3792e
[ "MIT" ]
3
2017-09-18T11:44:41.000Z
2019-12-25T11:30:26.000Z
// // FlopTexturePuzzle.hpp // SevenMonkeys // #ifndef FlopTexturePuzzle_hpp #define FlopTexturePuzzle_hpp #include "SevenMonkeys.hpp" #include "Deck.hpp" #include "FlopEvaluator.hpp" #include "PuzzleLayer.hpp" class FlopTexturePuzzle : public PuzzleLayer { public: FlopTexturePuzzle(); virtual ~FlopTexturePuzzle(); virtual bool init(); CREATE_FUNC(FlopTexturePuzzle); void update(float dt); private: void deal(); void addCommunityCards(); void addTokens(); void showPlayerMessage(); sevenmonkeys::Deck *mvpDeck; sevenmonkeys::FlopEvaluator *mvpFlopEval; std::vector<int> mvCards; int mvSuit; int mvMatch; int mvConnect; }; #endif /* FlopTexturePuzzle_hpp */
15.081633
45
0.699594
jane8384
7ec12a41a69692ef9d415572ae101b41adbf8280
13,036
cc
C++
wrappers/8.1.1/vtkDelimitedTextWriterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkDelimitedTextWriterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkDelimitedTextWriterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkWriterWrap.h" #include "vtkDelimitedTextWriterWrap.h" #include "vtkObjectBaseWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkDelimitedTextWriterWrap::ptpl; VtkDelimitedTextWriterWrap::VtkDelimitedTextWriterWrap() { } VtkDelimitedTextWriterWrap::VtkDelimitedTextWriterWrap(vtkSmartPointer<vtkDelimitedTextWriter> _native) { native = _native; } VtkDelimitedTextWriterWrap::~VtkDelimitedTextWriterWrap() { } void VtkDelimitedTextWriterWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkDelimitedTextWriter").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("DelimitedTextWriter").ToLocalChecked(), ConstructorGetter); } void VtkDelimitedTextWriterWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkDelimitedTextWriterWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkWriterWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkWriterWrap::ptpl)); tpl->SetClassName(Nan::New("VtkDelimitedTextWriterWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetFieldDelimiter", GetFieldDelimiter); Nan::SetPrototypeMethod(tpl, "getFieldDelimiter", GetFieldDelimiter); Nan::SetPrototypeMethod(tpl, "GetFileName", GetFileName); Nan::SetPrototypeMethod(tpl, "getFileName", GetFileName); Nan::SetPrototypeMethod(tpl, "GetStringDelimiter", GetStringDelimiter); Nan::SetPrototypeMethod(tpl, "getStringDelimiter", GetStringDelimiter); Nan::SetPrototypeMethod(tpl, "GetUseStringDelimiter", GetUseStringDelimiter); Nan::SetPrototypeMethod(tpl, "getUseStringDelimiter", GetUseStringDelimiter); Nan::SetPrototypeMethod(tpl, "GetWriteToOutputString", GetWriteToOutputString); Nan::SetPrototypeMethod(tpl, "getWriteToOutputString", GetWriteToOutputString); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "RegisterAndGetOutputString", RegisterAndGetOutputString); Nan::SetPrototypeMethod(tpl, "registerAndGetOutputString", RegisterAndGetOutputString); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetFieldDelimiter", SetFieldDelimiter); Nan::SetPrototypeMethod(tpl, "setFieldDelimiter", SetFieldDelimiter); Nan::SetPrototypeMethod(tpl, "SetFileName", SetFileName); Nan::SetPrototypeMethod(tpl, "setFileName", SetFileName); Nan::SetPrototypeMethod(tpl, "SetStringDelimiter", SetStringDelimiter); Nan::SetPrototypeMethod(tpl, "setStringDelimiter", SetStringDelimiter); Nan::SetPrototypeMethod(tpl, "SetUseStringDelimiter", SetUseStringDelimiter); Nan::SetPrototypeMethod(tpl, "setUseStringDelimiter", SetUseStringDelimiter); Nan::SetPrototypeMethod(tpl, "SetWriteToOutputString", SetWriteToOutputString); Nan::SetPrototypeMethod(tpl, "setWriteToOutputString", SetWriteToOutputString); Nan::SetPrototypeMethod(tpl, "WriteToOutputStringOff", WriteToOutputStringOff); Nan::SetPrototypeMethod(tpl, "writeToOutputStringOff", WriteToOutputStringOff); Nan::SetPrototypeMethod(tpl, "WriteToOutputStringOn", WriteToOutputStringOn); Nan::SetPrototypeMethod(tpl, "writeToOutputStringOn", WriteToOutputStringOn); #ifdef VTK_NODE_PLUS_VTKDELIMITEDTEXTWRITERWRAP_INITPTPL VTK_NODE_PLUS_VTKDELIMITEDTEXTWRITERWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkDelimitedTextWriterWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkDelimitedTextWriter> native = vtkSmartPointer<vtkDelimitedTextWriter>::New(); VtkDelimitedTextWriterWrap* obj = new VtkDelimitedTextWriterWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkDelimitedTextWriterWrap::GetFieldDelimiter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetFieldDelimiter(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkDelimitedTextWriterWrap::GetFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetFileName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkDelimitedTextWriterWrap::GetStringDelimiter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetStringDelimiter(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkDelimitedTextWriterWrap::GetUseStringDelimiter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetUseStringDelimiter(); info.GetReturnValue().Set(Nan::New(r)); } void VtkDelimitedTextWriterWrap::GetWriteToOutputString(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetWriteToOutputString(); info.GetReturnValue().Set(Nan::New(r)); } void VtkDelimitedTextWriterWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); vtkDelimitedTextWriter * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkDelimitedTextWriterWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDelimitedTextWriterWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDelimitedTextWriterWrap *w = new VtkDelimitedTextWriterWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkDelimitedTextWriterWrap::RegisterAndGetOutputString(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->RegisterAndGetOutputString(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkDelimitedTextWriterWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkDelimitedTextWriter * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkDelimitedTextWriterWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDelimitedTextWriterWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDelimitedTextWriterWrap *w = new VtkDelimitedTextWriterWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDelimitedTextWriterWrap::SetFieldDelimiter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetFieldDelimiter( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDelimitedTextWriterWrap::SetFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetFileName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDelimitedTextWriterWrap::SetStringDelimiter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetStringDelimiter( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDelimitedTextWriterWrap::SetUseStringDelimiter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetUseStringDelimiter( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDelimitedTextWriterWrap::SetWriteToOutputString(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetWriteToOutputString( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDelimitedTextWriterWrap::WriteToOutputStringOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->WriteToOutputStringOff(); } void VtkDelimitedTextWriterWrap::WriteToOutputStringOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDelimitedTextWriterWrap *wrapper = ObjectWrap::Unwrap<VtkDelimitedTextWriterWrap>(info.Holder()); vtkDelimitedTextWriter *native = (vtkDelimitedTextWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->WriteToOutputStringOn(); }
33.684755
109
0.755216
axkibe
7ec62584c94a09d90f485e85bf04f805f968e887
4,776
cpp
C++
Widget/MagnifierWidget.cpp
devonchenc/NovaImage
3d17166f9705ba23b89f1aefd31ac2db97385b1c
[ "MIT" ]
null
null
null
Widget/MagnifierWidget.cpp
devonchenc/NovaImage
3d17166f9705ba23b89f1aefd31ac2db97385b1c
[ "MIT" ]
null
null
null
Widget/MagnifierWidget.cpp
devonchenc/NovaImage
3d17166f9705ba23b89f1aefd31ac2db97385b1c
[ "MIT" ]
null
null
null
#include "MagnifierWidget.h" #include <QApplication> #include <QDesktopWidget> #include <QPainter> #include <QCursor> #include <QWindow> #include <QScreen> #include <QTimer> #include <QMouseEvent> const int grabInterval = 50; const int sizeOfMouseIcon = 20; MagnifierWidget::MagnifierWidget(QWidget* parent) : QWidget(parent) , _displayDirection(TopLeft) , _magnifyAeraSize(41, 41) , _magnifyTimes(8) , _magnifierSize((_magnifyAeraSize - QSize(2, 2)) * _magnifyTimes) , _totalSize(_magnifyAeraSize + _magnifierSize) , _timer(new QTimer(this)) { setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); setAttribute(Qt::WA_TranslucentBackground); setFixedSize(_totalSize); setMouseTracking(true); _timer->setInterval(grabInterval); connect(_timer, &QTimer::timeout, this, &MagnifierWidget::updatePosition); _timer->start(); } MagnifierWidget::~MagnifierWidget() { delete _timer; } void MagnifierWidget::setMagnifyArea(QSize size) { _magnifyAeraSize = size; update(); } void MagnifierWidget::setMagnifyTimes(int times) { _magnifyTimes = times; update(); } void MagnifierWidget::paintEvent(QPaintEvent*) { QWindow* window = QApplication::desktop()->windowHandle(); QPixmap grab = window->screen()->grabWindow(QApplication::desktop()->winId()); grab = grab.copy(QCursor::pos().x() - _magnifyAeraSize.width() / 2 + 1, QCursor::pos().y() - _magnifyAeraSize.height() / 2 + 1, _magnifyAeraSize.width() - 2, _magnifyAeraSize.height() - 2); QPainter painter(this); QPixmap centerPixel = grab.copy(_magnifyAeraSize.width() / 2 - 1, _magnifyAeraSize.height() / 2 - 1, 1, 1); QColor color = centerPixel.toImage().pixel(0, 0); if (color.red() > 100 && color.blue() > 100 && color.green() > 100) painter.setPen(QColor(0, 0, 0)); else painter.setPen(QColor(255, 255, 255)); QPoint magnifyAeraPoint, magnifierPoint; if (_displayDirection == TopLeft) { magnifyAeraPoint = QPoint(0, 0); magnifierPoint = QPoint(_magnifyAeraSize.width(), _magnifyAeraSize.height()); } else if(_displayDirection == TopRight) { magnifyAeraPoint = QPoint(_magnifierSize.width(), 0); magnifierPoint = QPoint(0, _magnifyAeraSize.height()); } else if (_displayDirection == BottomLeft) { magnifyAeraPoint = QPoint(0, _magnifierSize.height()); magnifierPoint = QPoint(_magnifyAeraSize.width(), 0); } else if (_displayDirection == BottomRight) { magnifyAeraPoint = QPoint(_magnifierSize.width(), _magnifierSize.height()); magnifierPoint = QPoint(0, 0); } painter.drawRect(magnifyAeraPoint.x(), magnifyAeraPoint.y(), _magnifyAeraSize.width() - 1, _magnifyAeraSize.height() - 1); painter.drawRect(magnifierPoint.x(), magnifierPoint.y(), _magnifierSize.width() - 1, _magnifierSize.height() - 1); painter.drawPixmap(magnifierPoint.x(), magnifierPoint.y(), _magnifierSize.width(), _magnifierSize.height(), grab); static int change = 0; change++; if (change > 3) { painter.setPen(QColor(0, 0, 0)); if (change >= 6) change = 0; } else { painter.setPen(QColor(255, 255, 255)); } QPoint leftop(magnifierPoint.x() + _magnifierSize.width() / 2 - _magnifyTimes / 2, magnifierPoint.y() + _magnifierSize.height() / 2 - _magnifyTimes / 2); painter.drawRect(leftop.x(), leftop.y(), _magnifyTimes, _magnifyTimes); } void MagnifierWidget::mousePressEvent(QMouseEvent*) { if (parentWidget()) { parentWidget()->setCursor(Qt::ArrowCursor); } close(); } void MagnifierWidget::mouseReleaseEvent(QMouseEvent*) { if (parentWidget()) { parentWidget()->setCursor(Qt::ArrowCursor); } close(); } void MagnifierWidget::updatePosition() { QPoint position = QCursor::pos() - QPoint(_magnifyAeraSize.width() / 2, _magnifyAeraSize.height() / 2); bool right = position.x() + _totalSize.width() > QApplication::desktop()->width() ? true : false; bool bottom = position.y() + _totalSize.height() > QApplication::desktop()->height() ? true : false; if (right && bottom) { _displayDirection = BottomRight; position.setX(position.x() - _magnifierSize.width()); position.setY(position.y() - _magnifierSize.height()); } else if (right) { _displayDirection = TopRight; position.setX(position.x() - _magnifierSize.width()); } else if (bottom) { _displayDirection = BottomLeft; position.setY(position.y() - _magnifierSize.height()); } else { _displayDirection = TopLeft; } move(position); update(); }
31.215686
157
0.65557
devonchenc
7ec70cbc87ab3664aa68f470b0b5f1d05a620657
6,654
hpp
C++
detail/utility.hpp
storm-ptr/bark
e4cd481183aba72ec6cf996eff3ac144c88b79b6
[ "MIT" ]
3
2019-11-05T10:27:35.000Z
2019-12-02T06:25:53.000Z
detail/utility.hpp
storm-ptr/bark
e4cd481183aba72ec6cf996eff3ac144c88b79b6
[ "MIT" ]
null
null
null
detail/utility.hpp
storm-ptr/bark
e4cd481183aba72ec6cf996eff3ac144c88b79b6
[ "MIT" ]
2
2019-12-01T18:01:02.000Z
2021-04-07T08:34:04.000Z
// Andrew Naplavkov #ifndef BARK_UTILITY_HPP #define BARK_UTILITY_HPP #include <algorithm> #include <chrono> #include <condition_variable> #include <cstddef> #include <functional> #include <initializer_list> #include <iterator> #include <mutex> #include <random> #include <sstream> #include <stdexcept> #include <string_view> #include <type_traits> #include <unordered_set> #include <utility> #include <variant> namespace bark { constexpr std::chrono::seconds DbTimeout(60); constexpr std::chrono::milliseconds UiTimeout(250); /// @see https://en.cppreference.com/w/cpp/utility/variant/visit template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template <class... Ts> overloaded(Ts...) -> overloaded<Ts...>; /// @see https://en.cppreference.com/w/cpp/iterator/iter_t template <class It> using iter_value_t = typename std::iterator_traits<It>::value_type; /// @see https://en.cppreference.com/w/cpp/ranges/iterator_t template <class Rng> using iterator_t = decltype(std::begin(std::declval<Rng&>())); template <class Rng> using range_value_t = iter_value_t<iterator_t<Rng>>; template <class T, class Result = void> using if_arithmetic_t = std::enable_if_t<std::is_arithmetic_v<T> || std::is_enum_v<T>, Result>; template <class T> if_arithmetic_t<T, T> reversed(T val) { if constexpr (sizeof(T) > 1) { auto first = reinterpret_cast<std::byte*>(&val); auto last = first + sizeof(T); std::reverse(first, last); } return val; } inline auto within(std::string_view rhs) { return [rhs](std::string_view lhs) { return rhs.find(lhs) != std::string_view::npos; }; } /// @see https://youtu.be/qL6zUn7iiLg?t=477 template <class T> auto equals(const T& lhs) { return [lhs](const auto& rhs) { return lhs == rhs; }; } template <class T, class Predicate> bool any_of(std::initializer_list<T> rng, Predicate p) { return std::any_of(rng.begin(), rng.end(), p); } template <class T, class Predicate> bool all_of(std::initializer_list<T> rng, Predicate p) { return std::all_of(rng.begin(), rng.end(), p); } template <class Container, class Item> void resize_and_assign(Container& container, size_t pos, Item&& item) { if (container.size() <= pos) container.resize(pos + 1); container[pos] = std::forward<Item>(item); } template <class... Args> std::string concat(const Args&... args) { std::ostringstream os; ((os << args), ...); return os.str(); } /// @see https://en.cppreference.com/w/cpp/utility/functional/identity struct identity { template <class T> constexpr decltype(auto) operator()(T&& val) const noexcept { return std::forward<T>(val); } }; template <class Result, class Rng, class Operation = identity> auto as(const Rng& rng, Operation op = {}) { Result res; std::transform(std::begin(rng), std::end(rng), std::back_inserter(res), op); return res; } template <class V, class T, size_t I = 0> constexpr size_t variant_index() { if constexpr (I == std::variant_size_v<V> || std::is_same_v<std::variant_alternative_t<I, V>, T>) return I; else return variant_index<V, T, I + 1>(); } /// Synchronous std::future<T> analogue. /// expected<T> is either a T or the exception preventing its creation. template <class T> class expected { std::variant<std::exception_ptr, T> val_; public: template <class F, class... Args> static expected result_of(F&& f, Args&&... args) noexcept { expected res; try { res.val_ = std::invoke(std::forward<F>(f), std::forward<Args>(args)...); } catch (...) { res.val_ = std::current_exception(); } return res; } T get() && { return std::visit( overloaded{ [](std::exception_ptr e) -> T { std::rethrow_exception(e); }, [](T&& val) -> T { return std::move(val); }}, std::move(val_)); } }; /// Joins 'items' by adding user defined separator. /// @code std::cout << list{{"Hello", "World!"}, ", "}; @endcode template <class Rng, class Separator, class Operation = identity> struct list { const Rng& rng; const Separator& sep; Operation op; template <class OStream> friend OStream& operator<<(OStream& os, const list& that) { auto first = std::begin(that.rng); auto last = std::end(that.rng); if (first != last) os << that.op(*first++); while (first != last) os << that.sep << that.op(*first++); return os; } }; template <class... Ts> list(Ts...) -> list<Ts...>; class random_index { public: using generator_type = std::mt19937; using value_type = generator_type::result_type; explicit random_index(value_type size) : gen_(std::random_device()()), dist_(0, size - 1) { } value_type operator()() { auto lock = std::lock_guard{guard_}; return dist_(gen_); } private: std::mutex guard_; generator_type gen_; std::uniform_int_distribution<value_type> dist_; }; template <class Type> struct same { Type type; template <class T> bool operator()(const T& val) const { return type == val.type; } }; template <class T> same(T) -> same<T>; template <class Functor> struct streamable : Functor { explicit streamable(Functor&& f) : Functor{std::move(f)} {} template <class OStream> friend OStream& operator<<(OStream& os, const streamable& that) { that(os); return os; } }; template <class T> streamable(T) -> streamable<T>; /// Synchronization primitive for value semantics. /// @see https://en.cppreference.com/w/cpp/named_req/TimedLockable template <class T, class Hash = std::hash<T>, class Equal = std::equal_to<T>> class timed_lockable { T val_; inline static std::mutex guard_; inline static std::condition_variable notifier_; inline static std::unordered_set<T, Hash, Equal> locked_; public: explicit timed_lockable(const T& val) : val_{val} {} template <class Rep, class Period> bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) { auto lock = std::unique_lock{guard_}; return notifier_.wait_for(lock, duration, [&] { return !locked_.count(val_); }) && locked_.insert(val_).second; } void unlock() { { auto lock = std::unique_lock{guard_}; locked_.erase(val_); } notifier_.notify_all(); } }; } // namespace bark #endif // BARK_UTILITY_HPP
24.463235
80
0.627142
storm-ptr
7eca43f0de1cb1001ca82d483f9dc2efd86bf72b
28,630
cpp
C++
src/app/ext/com/ux/ux.cpp
indigoabstract/techno-globe
1f01b231bece534282344fa660d5f9a8cc07262e
[ "MIT" ]
null
null
null
src/app/ext/com/ux/ux.cpp
indigoabstract/techno-globe
1f01b231bece534282344fa660d5f9a8cc07262e
[ "MIT" ]
null
null
null
src/app/ext/com/ux/ux.cpp
indigoabstract/techno-globe
1f01b231bece534282344fa660d5f9a8cc07262e
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "appplex-conf.hpp" #if defined MOD_UX #include "ux.hpp" #include "ux-camera.hpp" #include "ux-font.hpp" #include "gfx.hpp" #include "gfx-tex.hpp" #include "unit.hpp" #include "com/unit/transitions.hpp" #include <algorithm> using std::string; using std::vector; slide_scrolling::scroll_dir get_scroll_dir(touch_sym_evt::touch_sym_evt_types swipe_type) { switch (swipe_type) { case touch_sym_evt::TS_BACKWARD_SWIPE: return slide_scrolling::SD_LEFT_RIGHT; case touch_sym_evt::TS_FORWARD_SWIPE: return slide_scrolling::SD_RIGHT_LEFT; case touch_sym_evt::TS_UPWARD_SWIPE: return slide_scrolling::SD_DOWN_UP; case touch_sym_evt::TS_DOWNWARD_SWIPE: return slide_scrolling::SD_UP_DOWN; } throw ia_exception("not a swipe type"); } shared_ptr<ux_model> ux_model::get_instance() { return shared_from_this(); } void ux_model::receive(shared_ptr<iadp> idp) { } void ux_model::set_view(shared_ptr<ux> iview) { view = iview; notify_update(); } void ux_model::notify_update() { if (get_view()) { send(get_view(), iadp::new_instance(UX_EVT_MODEL_UPDATE)); } } shared_ptr<ux> ux_model::get_view() { return view.lock(); } shared_ptr<ia_sender> ux_model::sender_inst() { return get_instance(); } ux::ux() // for rootless / parentless ux inst { enabled = true; is_opaque = true; } ux::ux(shared_ptr<ux> iparent) { enabled = true; is_opaque = true; parent = iparent; if (!iparent) { throw ia_exception("init error. parent must not be null"); } root = iparent->root; if (root.expired()) { throw ia_exception("init error. parent's root must be null"); } } shared_ptr<ux> ux::get_instance() { return shared_from_this(); } void ux::set_visible(bool iis_visible) { enabled = iis_visible; } bool ux::is_visible()const { return enabled; } void ux::set_id(string iid) { id = iid; } const string& ux::get_id() { return id; } shared_ptr<ux> ux::find_by_id(const string& iid) { return root.lock()->contains_id(iid); } shared_ptr<ux> ux::contains_id(const string& iid) { if (iid == id) { return get_instance(); } return shared_ptr<ux>(); } bool ux::contains_ux(const shared_ptr<ux> iux) { return iux == get_instance(); } shared_ptr<ux> ux::get_parent() { return parent.lock(); } shared_ptr<ux_page_tab> ux::get_root() { return root.lock(); } shared_ptr<unit> ux::get_unit() { return static_pointer_cast<unit>(root.lock()->get_unit()); } void ux::receive(shared_ptr<iadp> idp) {} void ux::update_state() {} void ux::update_view(shared_ptr<ux_camera> g) {} ux_rect ux::get_pos() { return uxr; } bool ux::is_hit(float x, float y) { return is_inside_box(x, y, uxr.x, uxr.y, uxr.w, uxr.h); } shared_ptr<ia_sender> ux::sender_inst() { return get_instance(); } shared_ptr<ux_page_transition> ux_page_transition::new_instance(shared_ptr<ux_page> ipage) { return shared_ptr<ux_page_transition>(new ux_page_transition(ipage)); } shared_ptr<ux_page_transition> ux_page_transition::new_instance(shared_ptr<ux_page_tab> iuxroot, string iid) { return shared_ptr<ux_page_transition>(new ux_page_transition(iuxroot, iid)); } ux_page_transition::ux_page_transition(shared_ptr<ux_page> ipage) : iadp(UX_EVT_PAGE_TRANSITION) { page = ipage; dir = slide_scrolling::SD_RIGHT_LEFT; pt_type = REPLACE_CURRENT_PAGE; pj_type = HISTORY_ADD_PAGE; } ux_page_transition::ux_page_transition(shared_ptr<ux_page_tab> iuxroot, string iid) : iadp(UX_EVT_PAGE_TRANSITION) { uxroot = iuxroot; id = iid; dir = slide_scrolling::SD_RIGHT_LEFT; pt_type = REPLACE_CURRENT_PAGE; pj_type = HISTORY_ADD_PAGE; } shared_ptr<ux_page> ux_page_transition::get_target_page() { if (!page.expired()) { return page.lock(); } else { shared_ptr<ux> u = uxroot.lock()->contains_id(id); if (u) { return static_pointer_cast<ux_page>(u); } } vprint("target page with id [%s] is not available\n", id.c_str()); return ux_page::PAGE_NONE; } slide_scrolling::scroll_dir ux_page_transition::get_scroll_dir() { return dir; } ux_page_transition::page_transition_types ux_page_transition::get_transition_type() { return pt_type; } ux_page_transition::page_jump_types ux_page_transition::get_jump_type() { return pj_type; } shared_ptr<ux_page_transition> ux_page_transition::set_scroll_dir(slide_scrolling::scroll_dir idir) { dir = idir; return get_instance(); } shared_ptr<ux_page_transition> ux_page_transition::set_transition_type(page_transition_types iptType) { pt_type = iptType; return get_instance(); } shared_ptr<ux_page_transition> ux_page_transition::set_jump_type(page_jump_types ipjType) { pj_type = ipjType; return get_instance(); } shared_ptr<ux_page_transition> ux_page_transition::get_instance() { return shared_from_this(); } static shared_ptr<gfx_tex> keyboardImg; class uxpagetab_vkeyboard_page : public ux_page { public: uxpagetab_vkeyboard_page(shared_ptr<ux_page_tab> iparent, string iid) : ux_page(iparent) { set_id(iid); tmap[touch_sym_evt::TS_BACKWARD_SWIPE] = ux_page_transition::new_instance(ux_page::PREV_PAGE) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_BACKWARD_SWIPE)) ->set_transition_type(ux_page_transition::POP_CURRENT_PAGE); tmap.erase(touch_sym_evt::TS_FORWARD_SWIPE); } virtual void receive(shared_ptr<iadp> idp) { if (idp->is_type(touch_sym_evt::TOUCHSYM_EVT_TYPE)) { shared_ptr<touch_sym_evt> ts = touch_sym_evt::as_touch_sym_evt(idp); if (ts->get_type() == touch_sym_evt::TS_FIRST_TAP) { float x = ts->pressed.te->points[0].x; float y = ts->pressed.te->points[0].y; if (is_inside_box(x, y, uxr.x, uxr.h - 40, uxr.w, uxr.h)) { shared_ptr<ux_page_transition> upt = ux_page_transition::new_instance(ux_page::PREV_PAGE) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_DOWNWARD_SWIPE)) ->set_transition_type(ux_page_transition::POP_CURRENT_PAGE); send(get_parent(), upt); } } } ux_page::receive(idp); } virtual void update_view(shared_ptr<ux_camera> g) { ux_page::update_view(g); if (keyboardImg) { g->push_transform_state(); g->scale((float)pfm::screen::get_width() / keyboardImg->get_width(), (float)pfm::screen::get_height() / keyboardImg->get_height()); g->drawImage(keyboardImg, 0, 0); g->pop_transform_state(); } else { //keyboardImg = vg_image::load_image("voronoi/voronoi-vkb3.png"); } g->drawText(get_id(), 10, 10); } }; const string ux_page_tab::VKEYBOARD_MAIN_PAGE = "vkeyboard-main-page"; const string ux_page_tab::VKEYBOARD_UP_PAGE = "vkeyboard-up-page"; const string ux_page_tab::VKEYBOARD_RIGHT_PAGE = "vkeyboard-right-page"; const string ux_page_tab::VKEYBOARD_DOWN_PAGE = "vkeyboard-down-page"; ux_page_tab::ux_page_tab(shared_ptr<unit> iu) : ux(), ss(550) { if (!iu) { throw ia_exception("unit cannot be null"); } u = iu; uxr.set(0, 0, (float)iu->get_width(), (float)iu->get_height()); } shared_ptr<ux_page_tab> ux_page_tab::new_instance(shared_ptr<unit> iu) { shared_ptr<ux_page_tab> pt(new ux_page_tab(iu)); pt->new_instance_helper(); return pt; } shared_ptr<ux_page_tab> ux_page_tab::new_shared_instance(ux_page_tab* inew_page_tab_class_instance) { shared_ptr<ux_page_tab> pt(inew_page_tab_class_instance); pt->new_instance_helper(); return pt; } void ux_page_tab::init() { root = get_ux_page_tab_instance(); ss.get_transition()->add_receiver(get_instance()); if (!is_empty()) { current_page = pages[4]; page_history.push_back(current_page); page_stack.push_back(current_page); } for(auto p : pages) { p->init(); } } void ux_page_tab::on_destroy() { for(auto p : pages) { p->on_destroy(); } } shared_ptr<ux> ux_page_tab::contains_id(const string& iid) { if (iid.length() > 0) { if (iid == get_id()) { return get_instance(); } for(auto p : pages) { shared_ptr<ux> u = p->contains_id(iid); if (u) { return u; } } } return shared_ptr<ux>(); } bool ux_page_tab::contains_ux(const shared_ptr<ux> iux) { for(auto p : pages) { if (iux == p || p->contains_ux(iux)) { return true; } } return false; } shared_ptr<ux_page_tab> ux_page_tab::get_ux_page_tab_instance() { return static_pointer_cast<ux_page_tab>(get_instance()); } shared_ptr<unit> ux_page_tab::get_unit() { return static_pointer_cast<unit>(u.lock()); } bool ux_page_tab::is_empty() { return pages.size() <= 4; } void ux_page_tab::receive(shared_ptr<iadp> idp) { if (idp->is_type(touch_sym_evt::TOUCHSYM_EVT_TYPE)) { shared_ptr<touch_sym_evt> ts = touch_sym_evt::as_touch_sym_evt(idp); auto pa = ts->crt_state.te; //trx("_mt1 %1% tt %2%") % pa->is_multitouch() % pa->type; } if (idp->is_processed()) { return; } shared_ptr<ia_sender> source = idp->source(); shared_ptr<ms_linear_transition> mst = ss.get_transition(); if (idp->is_type(UX_EVT_PAGE_TRANSITION)) { current_transition = static_pointer_cast<ux_page_transition>(idp); shared_ptr<ux_page> targetPage = current_transition->get_target_page(); switch (current_transition->get_transition_type()) { case ux_page_transition::REPLACE_CURRENT_PAGE: //current_page->on_visibility_changed(false); //current_page = current_transition->get_target_page(); //page_stack.back() = current_page; break; case ux_page_transition::PUSH_CURRENT_PAGE: current_page->on_visibility_changed(false); current_page = current_transition->get_target_page(); page_stack.push_back(current_page); break; case ux_page_transition::POP_CURRENT_PAGE: current_page->on_visibility_changed(false); page_stack.erase(page_stack.end() - 1); current_page = page_stack.back(); break; case ux_page_transition::CLEAR_PAGE_STACK: break; } //mst->start(); //ss.set_scroll_dir(current_transition->get_scroll_dir()); //ss.start(); current_page->on_visibility_changed(true); } else if (!is_empty()) { send(current_page, idp); } return; //-------------------- old code. inactivated. //if (source == mst) //{ // last_page->on_hide_transition(mst); // current_page->on_show_transition(mst); //} //else if (idp->is_type(UX_EVT_PAGE_TRANSITION)) //{ // current_transition = static_pointer_cast<ux_page_transition>(idp); // shared_ptr<ux_page> targetPage = current_transition->get_target_page(); // bool startTransition = false; // if (targetPage == ux_page::PAGE_NONE) // { // } // else if (targetPage == ux_page::PREV_PAGE) // { // if (page_history.size() > 1) // { // page_history.erase(page_history.end() - 1); // last_page = current_page; // current_page = page_history.back(); // startTransition = true; // } // else // { // //get_unit()->back(); // } // } // else if (targetPage == ux_page::NEXT_PAGE) // { // int idx = get_page_index(current_page); // if (idx < pages.size() - 1) // { // last_page = current_page; // current_page = pages[idx + 1]; // page_history.push_back(current_page); // startTransition = true; // } // } // else // { // int idx = get_page_index(targetPage); // if (idx < 0) // { // throw ia_exception("target page cannot be found"); // } // last_page = current_page; // current_page = pages[idx]; // switch (current_transition->get_jump_type()) // { // case ux_page_transition::HISTORY_ADD_PAGE: // page_history.push_back(current_page); // break; // case ux_page_transition::HISTORY_REWIND_TO_PAGE: // { // vector<shared_ptr<ux_page> >::reverse_iterator it = std::find(page_history.rbegin(), page_history.rend(), targetPage); // if (it != page_history.rend()) // { // page_history.erase(it.base(), page_history.end()); // } // else // { // page_history.clear(); // page_history.push_back(targetPage); // } // break; // } // case ux_page_transition::HISTORY_IGNORE_PAGE: // break; // } // startTransition = true; // } // if (startTransition) // { // switch (current_transition->get_transition_type()) // { // case ux_page_transition::REPLACE_CURRENT_PAGE: // page_stack.back() = current_page; // break; // case ux_page_transition::PUSH_CURRENT_PAGE: // page_stack.push_back(current_page); // break; // case ux_page_transition::POP_CURRENT_PAGE: // page_stack.erase(page_stack.end() - 1); // page_stack.back() = current_page; // break; // case ux_page_transition::CLEAR_PAGE_STACK: // break; // } // mst->start(); // ss.set_scroll_dir(current_transition->get_scroll_dir()); // ss.start(); // current_page->on_visibility_changed(true); // } //} //else if (!is_empty()) //{ // send(current_page, idp); //} } void ux_page_tab::update_state() { if (!is_empty()) { if (!ss.is_finished()) { ss.update(); switch (current_transition->get_transition_type()) { case ux_page_transition::REPLACE_CURRENT_PAGE: last_page->update_state(); for(auto p : page_stack) { p->update_state(); } break; case ux_page_transition::PUSH_CURRENT_PAGE: for(auto p : page_stack) { p->update_state(); } break; case ux_page_transition::POP_CURRENT_PAGE: last_page->update_state(); for(auto p : page_stack) { p->update_state(); } break; case ux_page_transition::CLEAR_PAGE_STACK: current_page->update_state(); for(auto p : page_stack) { p->update_state(); } break; } if (ss.is_finished()) { last_page->on_visibility_changed(false); if (current_transition->get_transition_type() == ux_page_transition::CLEAR_PAGE_STACK) { page_stack.clear(); page_stack.push_back(current_page); } current_transition.reset(); } } else { for(auto p : page_stack) { p->update_state(); } } } } void ux_page_tab::update_view(shared_ptr<ux_camera> g) { if (!is_empty()) { int size = page_stack.size(); int c = 0; for (int k = size - 1; k >= 0; k--) { if (page_stack[k]->is_opaque) { c = k; break; } } for (int k = c; k < size; k++) { shared_ptr<ux_page> p = page_stack[k]; g->push_transform_state(); g->translate(p->uxr.x, p->uxr.y); p->update_view(g); g->pop_transform_state(); } } return; //-------------------- old code. inactivated. //if (!is_empty()) //{ // if (!ss.is_finished()) // { // float sx = ss.srcpos.x * get_unit()->get_width(); // float sy = ss.srcpos.y * get_unit()->get_height(); // float dx = ss.dstpos.x * get_unit()->get_width(); // float dy = ss.dstpos.y * get_unit()->get_height(); // switch (current_transition->get_transition_type()) // { // case ux_page_transition::REPLACE_CURRENT_PAGE: // { // int size = page_stack.size() - 1; // for (int k = 0; k < size; k++) // { // shared_ptr<ux_page> p = page_stack[k]; // g->push_transform_state(); // g->translate(p->uxr.x, p->uxr.y); // p->update_view(g); // g->pop_transform_state(); // } // g->push_transform_state(); // g->translate(sx, sy); // g->push_transform_state(); // g->translate(last_page->uxr.x, last_page->uxr.y); // last_page->update_view(g); // g->pop_transform_state(); // g->pop_transform_state(); // g->push_transform_state(); // g->translate(dx, dy); // g->push_transform_state(); // g->translate(current_page->uxr.x, current_page->uxr.y); // current_page->update_view(g); // g->pop_transform_state(); // g->pop_transform_state(); // break; // } // case ux_page_transition::PUSH_CURRENT_PAGE: // { // int size = page_stack.size() - 1; // for (int k = 0; k < size; k++) // { // shared_ptr<ux_page> p = page_stack[k]; // g->push_transform_state(); // g->translate(p->uxr.x, p->uxr.y); // p->update_view(g); // g->pop_transform_state(); // } // g->push_transform_state(); // g->translate(dx, dy); // g->push_transform_state(); // g->translate(current_page->uxr.x, current_page->uxr.y); // current_page->update_view(g); // g->pop_transform_state(); // g->pop_transform_state(); // break; // } // case ux_page_transition::POP_CURRENT_PAGE: // { // int size = page_stack.size(); // for (int k = 0; k < size; k++) // { // shared_ptr<ux_page> p = page_stack[k]; // g->push_transform_state(); // g->translate(p->uxr.x, p->uxr.y); // p->update_view(g); // g->pop_transform_state(); // } // g->push_transform_state(); // g->translate(sx, sy); // g->push_transform_state(); // g->translate(last_page->uxr.x, last_page->uxr.y); // last_page->update_view(g); // g->pop_transform_state(); // g->pop_transform_state(); // break; // } // case ux_page_transition::CLEAR_PAGE_STACK: // { // int size = page_stack.size(); // for (int k = 0; k < size; k++) // { // shared_ptr<ux_page> p = page_stack[k]; // g->push_transform_state(); // g->translate(sx, sy); // g->push_transform_state(); // g->translate(p->uxr.x, p->uxr.y); // p->update_view(g); // g->pop_transform_state(); // g->pop_transform_state(); // } // g->push_transform_state(); // g->translate(dx, dy); // g->push_transform_state(); // g->translate(current_page->uxr.x, current_page->uxr.y); // current_page->update_view(g); // g->pop_transform_state(); // g->pop_transform_state(); // break; // } // } // } // else // { // int c = 0; // for (int k = page_stack.size() - 1; k >= 0; k--) // { // if (page_stack[k]->is_opaque) // { // c = k; // break; // } // } // for (int k = c; k < page_stack.size(); k++) // { // shared_ptr<ux_page> p = page_stack[k]; // g->push_transform_state(); // g->translate(p->uxr.x, p->uxr.y); // p->update_view(g); // g->pop_transform_state(); // } // } //} } shared_ptr<ux_page> ux_page_tab::get_page_at(int idx) { return pages[idx + 4]; } void ux_page_tab::set_first_page(shared_ptr<ux_page> up) { int idx = get_page_index(up); if (idx > 0) { shared_ptr<ux_page> swp = pages[idx]; pages.erase(pages.begin() + idx); pages.insert(pages.begin() + 4, swp); } else if (idx == -1) { throw ia_exception("page is not a member of this container"); } } void ux_page_tab::show_vkeyboard() { shared_ptr<ux_page_transition> upt = ux_page_transition::new_instance(get_ux_page_tab_instance(), VKEYBOARD_MAIN_PAGE) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_UPWARD_SWIPE)) ->set_transition_type(ux_page_transition::PUSH_CURRENT_PAGE); send(get_instance(), upt); } void ux_page_tab::on_resize() { uxr.w = (float)u.lock()->get_width(); uxr.h = (float)u.lock()->get_height(); for(auto p : pages) { p->on_resize(); } } void ux_page_tab::add(shared_ptr<ux_page> p) { if (contains_ux(p)) { throw ia_exception();//trs("page with id [%1%] already exists") % p->get_id()); } pages.push_back(p); } int ux_page_tab::get_page_index(shared_ptr<ux_page> ipage) { int k = 0; for(auto p : pages) { if (ipage == p) { return k; } k++; } return -1; } void ux_page_tab::new_instance_helper() { shared_ptr<ux_page_tab> uxroot = get_ux_page_tab_instance(); root = uxroot; shared_ptr<ux_page> vkmainpage = ux_page::new_shared_instance(new uxpagetab_vkeyboard_page(uxroot, VKEYBOARD_MAIN_PAGE)); shared_ptr<ux_page> vkuppage = ux_page::new_shared_instance(new uxpagetab_vkeyboard_page(uxroot, VKEYBOARD_UP_PAGE)); shared_ptr<ux_page> vkrightpage = ux_page::new_shared_instance(new uxpagetab_vkeyboard_page(uxroot, VKEYBOARD_RIGHT_PAGE)); shared_ptr<ux_page> vkdownpage = ux_page::new_shared_instance(new uxpagetab_vkeyboard_page(uxroot, VKEYBOARD_DOWN_PAGE)); vkmainpage->tmap[touch_sym_evt::TS_UPWARD_SWIPE] = ux_page_transition::new_instance(vkdownpage) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_UPWARD_SWIPE)) ->set_jump_type(ux_page_transition::HISTORY_IGNORE_PAGE); vkmainpage->tmap[touch_sym_evt::TS_FORWARD_SWIPE] = ux_page_transition::new_instance(vkrightpage) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_FORWARD_SWIPE)) ->set_jump_type(ux_page_transition::HISTORY_IGNORE_PAGE); vkmainpage->tmap[touch_sym_evt::TS_DOWNWARD_SWIPE] = ux_page_transition::new_instance(vkuppage) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_DOWNWARD_SWIPE)) ->set_jump_type(ux_page_transition::HISTORY_IGNORE_PAGE); vkuppage->tmap[touch_sym_evt::TS_DOWNWARD_SWIPE] = ux_page_transition::new_instance(vkdownpage) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_DOWNWARD_SWIPE)) ->set_jump_type(ux_page_transition::HISTORY_IGNORE_PAGE); vkuppage->tmap[touch_sym_evt::TS_UPWARD_SWIPE] = ux_page_transition::new_instance(vkmainpage) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_UPWARD_SWIPE)) ->set_jump_type(ux_page_transition::HISTORY_IGNORE_PAGE); vkrightpage->tmap[touch_sym_evt::TS_BACKWARD_SWIPE] = ux_page_transition::new_instance(vkmainpage) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_BACKWARD_SWIPE)) ->set_jump_type(ux_page_transition::HISTORY_IGNORE_PAGE); vkdownpage->tmap[touch_sym_evt::TS_UPWARD_SWIPE] = ux_page_transition::new_instance(vkuppage) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_UPWARD_SWIPE)) ->set_jump_type(ux_page_transition::HISTORY_IGNORE_PAGE); vkdownpage->tmap[touch_sym_evt::TS_DOWNWARD_SWIPE] = ux_page_transition::new_instance(vkmainpage) ->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_DOWNWARD_SWIPE)) ->set_jump_type(ux_page_transition::HISTORY_IGNORE_PAGE); } const shared_ptr<ux_page> ux_page::PAGE_NONE = ux_page::new_standalone_instance(); const shared_ptr<ux_page> ux_page::PREV_PAGE = ux_page::new_standalone_instance(); const shared_ptr<ux_page> ux_page::NEXT_PAGE = ux_page::new_standalone_instance(); ux_page::ux_page() : ux() { } ux_page::ux_page(shared_ptr<ux_page_tab> iparent) : ux(iparent) { shared_ptr<unit> tu = iparent->get_unit(); uxr.set(0, 0, (float)tu->get_width(), (float)tu->get_height()); tmap[touch_sym_evt::TS_BACKWARD_SWIPE] = ux_page_transition::new_instance(PREV_PAGE)->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_BACKWARD_SWIPE)); tmap[touch_sym_evt::TS_FORWARD_SWIPE] = ux_page_transition::new_instance(NEXT_PAGE)->set_scroll_dir(get_scroll_dir(touch_sym_evt::TS_FORWARD_SWIPE)); } shared_ptr<ux_page> ux_page::new_instance(shared_ptr<ux_page_tab> iparent) { shared_ptr<ux_page> u(new ux_page(iparent)); iparent->add(u); return u; } shared_ptr<ux_page> ux_page::new_shared_instance(ux_page* inew_page_class_instance) { shared_ptr<ux_page> u(inew_page_class_instance); shared_ptr<ux_page_tab> pt = static_pointer_cast<ux_page_tab>(u->get_parent()); pt->add(u); return u; } void ux_page::init() {} void ux_page::on_destroy() { for(auto p : mlist) { p->on_destroy(); } } shared_ptr<ux> ux_page::contains_id(const string& iid) { if (iid.length() > 0) { if (iid == get_id()) { return get_instance(); } for(auto p : mlist) { shared_ptr<ux> u = p->contains_id(iid); if (u) { return u; } } } return shared_ptr<ux>(); } bool ux_page::contains_ux(const shared_ptr<ux> iux) { for(auto p : mlist) { if (iux == p) { return true; } } return false; } shared_ptr<ux_page> ux_page::get_ux_page_instance() { return static_pointer_cast<ux_page>(get_instance()); } shared_ptr<ux_page_tab> ux_page::get_ux_page_parent() { return static_pointer_cast<ux_page_tab>(get_parent()); } void ux_page::on_visibility_changed(bool iis_visible) {} void ux_page::on_show_transition(const shared_ptr<linear_transition> itransition) {} void ux_page::on_hide_transition(const shared_ptr<linear_transition> itransition) {} void ux_page::receive(shared_ptr<iadp> idp) { update_input_subux(idp); update_input_std_behaviour(idp); } void ux_page::update_input_subux(shared_ptr<iadp> idp) { if (idp->is_processed()) { return; } if (idp->is_type(touch_sym_evt::TOUCHSYM_EVT_TYPE)) { shared_ptr<touch_sym_evt> ts = touch_sym_evt::as_touch_sym_evt(idp); float x = ts->crt_state.te->points[0].x; float y = ts->crt_state.te->points[0].y; for(auto b : mlist) { if (b->is_hit(x, y)) { send(b, idp); if (idp->is_processed()) { break; } } } } } void ux_page::update_input_std_behaviour(shared_ptr<iadp> idp) { if (idp->is_processed()) { return; } if (idp->is_type(touch_sym_evt::TOUCHSYM_EVT_TYPE)) { shared_ptr<touch_sym_evt> ts = touch_sym_evt::as_touch_sym_evt(idp); switch (ts->get_type()) { case touch_sym_evt::TS_PRESSED: { float x = ts->pressed.te->points[0].x; float y = ts->pressed.te->points[0].y; if (ts->tap_count == 1) { ks.grab(x, y); ts->process(); } break; } case touch_sym_evt::TS_PRESS_AND_DRAG: { float x = ts->crt_state.te->points[0].x; float y = ts->crt_state.te->points[0].y; switch (ts->tap_count) { case 1: { if (ts->is_finished) { ks.start_slowdown(); } else { ks.begin(ts->crt_state.te->points[0].x, ts->crt_state.te->points[0].y); } uxr.x += ts->crt_state.te->points[0].x - ts->prev_state.te->points[0].x; uxr.y += ts->crt_state.te->points[0].y - ts->prev_state.te->points[0].y; if (uxr.x > 0) { uxr.x = 0; } else if (uxr.x < -uxr.w + pfm::screen::get_width()) { uxr.x = -uxr.w + pfm::screen::get_width(); } if (uxr.y > 0) { uxr.y = 0; } else if (uxr.y < -uxr.h + pfm::screen::get_height()) { uxr.y = -uxr.h + pfm::screen::get_height(); } ts->process(); } } break; } case touch_sym_evt::TS_MOUSE_WHEEL: { shared_ptr<mouse_wheel_evt> mw = static_pointer_cast<mouse_wheel_evt>(ts); uxr.y += float(mw->wheel_delta) * 50.f; if (uxr.y > 0) { uxr.y = 0; } else if (uxr.y < -uxr.h + pfm::screen::get_height()) { uxr.y = -uxr.h + pfm::screen::get_height(); } ts->process(); break; } case touch_sym_evt::TS_BACKWARD_SWIPE: { if (uxr.x < 0) { ts->process(); } else if (tmap.find(touch_sym_evt::TS_BACKWARD_SWIPE) != tmap.end()) { send(get_ux_page_parent(), tmap[touch_sym_evt::TS_BACKWARD_SWIPE]); ts->process(); } break; } case touch_sym_evt::TS_FORWARD_SWIPE: { if (uxr.x > -uxr.w + pfm::screen::get_width()) { ts->process(); } else if (tmap.find(touch_sym_evt::TS_FORWARD_SWIPE) != tmap.end()) { send(get_ux_page_parent(), tmap[touch_sym_evt::TS_FORWARD_SWIPE]); ts->process(); } break; } case touch_sym_evt::TS_UPWARD_SWIPE: { if (uxr.y < 0) { ts->process(); } else if (tmap.find(touch_sym_evt::TS_UPWARD_SWIPE) != tmap.end()) { send(get_ux_page_parent(), tmap[touch_sym_evt::TS_UPWARD_SWIPE]); ts->process(); } break; } case touch_sym_evt::TS_DOWNWARD_SWIPE: { if (uxr.y > -uxr.h + pfm::screen::get_height()) { ts->process(); } else if (tmap.find(touch_sym_evt::TS_DOWNWARD_SWIPE) != tmap.end()) { send(get_ux_page_parent(), tmap[touch_sym_evt::TS_DOWNWARD_SWIPE]); ts->process(); } break; } } } } void ux_page::update_state() { point2d p = ks.update(); uxr.x += p.x; uxr.y += p.y; for(auto b : mlist) { uxr.w = std::max(uxr.w, b->get_pos().w); uxr.h = std::max(uxr.h, b->get_pos().h); } if (uxr.x > 0) { uxr.x = 0; } else if (uxr.x < -uxr.w + pfm::screen::get_width()) { uxr.x = -uxr.w + pfm::screen::get_width(); } if (uxr.y > 0) { uxr.y = 0; } else if (uxr.y < -uxr.h + pfm::screen::get_height()) { uxr.y = -uxr.h + pfm::screen::get_height(); } for(auto b : mlist) { b->update_state(); } } void ux_page::update_view(shared_ptr<ux_camera> g) { for(auto b : mlist) { b->update_view(g); } } shared_ptr<ux> ux_page::get_ux_at(int idx) { return mlist[idx]; } void ux_page::on_resize() { shared_ptr<ux_page_tab> parent = get_ux_page_parent(); uxr.x = 0; uxr.y = 0; uxr.w = parent->uxr.w; uxr.h = parent->uxr.h; } shared_ptr<ux_page> ux_page::new_standalone_instance() { return shared_ptr<ux_page>(new ux_page()); } void ux_page::add(shared_ptr<ux_page_item> b) { if (contains_ux(b)) { throw ia_exception();//trs("uxpageitem with id [%1%] already exists") % b->get_id()); } mlist.push_back(b); } ux_page_item::ux_page_item(shared_ptr<ux_page> iparent) : ux(iparent) { } shared_ptr<ux_page> ux_page_item::get_ux_page_item_parent() { return static_pointer_cast<ux_page>(get_parent()); } void ux_page_item::add_to_page() { shared_ptr<ux_page> page = static_pointer_cast<ux_page>(get_parent()); shared_ptr<ux_page_item> inst = static_pointer_cast<ux_page_item>(get_instance()); page->add(inst); } #endif
20.989736
152
0.673175
indigoabstract
7ed3ce21721bf726f2d4ce746416c72d1ffb44fd
1,784
cpp
C++
native/ui/ui_slider.cpp
49View/event_horizon
9b78c9318e1a785384ab01eb4d90e79f0192c6ad
[ "BSD-3-Clause" ]
null
null
null
native/ui/ui_slider.cpp
49View/event_horizon
9b78c9318e1a785384ab01eb4d90e79f0192c6ad
[ "BSD-3-Clause" ]
7
2021-09-02T05:58:24.000Z
2022-02-27T07:06:43.000Z
native/ui/ui_slider.cpp
49View/event_horizon
9b78c9318e1a785384ab01eb4d90e79f0192c6ad
[ "BSD-3-Clause" ]
2
2020-02-06T02:05:15.000Z
2021-11-25T11:35:14.000Z
#include "ui_slider.h" void UiSlider::initImpl() { mIsClickable = true; mAcceptInputs = true; mStartValue = 0; mEndValue = 1; } void UiSlider::setValuesRange( const int _vstart, const int _vend, const int _curr ) { mStartValue = _vstart; mEndValue = _vend; mCurrValue = _curr; } //TouchResult UiSlider::onTouchDown( const Vector2f& pos, ModifiersKey mod ) { // UiControl::onTouchDown( pos, mod ); // // if ( mTouchDownResult == TOUCH_RESULT_HIT ) { // AcceptInputs( false ); // Vector3f baric = BaricentricHit( pos ); // if ( isbetween( baric.x(), 0.0f, 1.0f ) ) { // onValueChanged( lerp( baric.x(), mStartValue, mEndValue ) ); // } // } // return mTouchDownResult; //} // //bool UiSlider::onTouchUp( const Vector2f& /*pos*/, ModifiersKey /*mod*/ ) { // if ( !mEnabled ) return false; // // if ( mTouchDownResult == TOUCH_RESULT_HIT ) { // AcceptInputs( true ); // animateTo( mScale, V2fc::ONE, 0.05f, 0.0f ); // mTouchDownResult = TOUCH_RESULT_NOT_HIT; // if ( mCallbackOnClickAction ) mCallbackOnClickAction(); // return true; // } // return false; //} // //bool UiSlider::onTouchMove( const Vector2f& pos, ModifiersKey /*mod*/ ) { // Vector3f baric = BaricentricHit( pos ); // if ( isbetween( baric.x(), 0.0f, 1.0f ) ) { // onValueChanged( lerp( baric.x(), mStartValue, mEndValue ) ); // } // // // Text(text); // return false; //} void UiSlider::setValue( int value ) { onValueChanged( value ); // if ( mCallbackOnClickAction ) mCallbackOnClickAction(); } void UiSlider::onValueChanged( int value ) { if ( value == mCurrValue ) return; mCurrValue = value; // setSliderBarTo( lerpInv( static_cast<float>( value ), static_cast<float>( mStartValue ), static_cast<float>( mEndValue ) ) ); // if ( mCallbackValueChanged ) mCallbackValueChanged( value ); }
27.875
128
0.670404
49View
7ed96885c6be588b5422c1ea2e46acccdbde89af
11,884
cpp
C++
pkg/Bfdp/source/Lexer/Symbolizer.cpp
dpkristensen/bfdm
1fdbdb89263b35b5ecd3bd7e24bce700910b38f9
[ "BSD-3-Clause" ]
1
2018-07-27T17:20:59.000Z
2018-07-27T17:20:59.000Z
pkg/Bfdp/source/Lexer/Symbolizer.cpp
dpkristensen/bfdm
1fdbdb89263b35b5ecd3bd7e24bce700910b38f9
[ "BSD-3-Clause" ]
10
2018-07-28T03:21:05.000Z
2019-02-21T07:09:36.000Z
pkg/Bfdp/source/Lexer/Symbolizer.cpp
dpkristensen/bfdm
1fdbdb89263b35b5ecd3bd7e24bce700910b38f9
[ "BSD-3-Clause" ]
null
null
null
/** BFDP Lexer Symbolizer Definition Copyright 2016-2019, Daniel Kristensen, Garmin Ltd, or its subsidiaries. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Base types #include "Bfdp/Lexer/Symbolizer.hpp" // External includes #include <algorithm> #include <cstdlib> #include <sstream> // Internal includes #include "Bfdp/Common.hpp" #include "Bfdp/Data/ByteBuffer.hpp" #include "Bfdp/ErrorReporter/Functions.hpp" #include "Bfdp/Lexer/CategoryBase.hpp" #include "Bfdp/Unicode/Utf8Converter.hpp" #define BFDP_MODULE "Lexer::Symbolizer" namespace Bfdp { namespace Lexer { Symbolizer::Symbolizer ( ISymbolObserver& aObserver, ISymbolBuffer& aSymbolBuffer, Unicode::IConverter& aByteConverter ) : mObserver( aObserver ) , mSymbolBuffer( aSymbolBuffer ) , mSavedCategory( CategoryBase::NoCategory ) , mByteConverter( aByteConverter ) , mLastMapEntry( mSymbolMap.cend() ) { } bool Symbolizer::AddCategory ( ISymbolCategory const* const aCategory ) { if( aCategory->GetCategory() < 0 ) { BFDP_MISUSE_ERROR( "Bad category in AddCategory" ); return false; } bool success = true; SymbolCategoryMap::const_iterator newEntry = mSymbolMap.cend(); try { newEntry = mSymbolMap.insert( mSymbolMap.end(), aCategory ); } catch( std::exception const& /* exception */ ) { BFDP_RUNTIME_ERROR( "Failed to add symbol category" ); success = false; } if( success && ( mLastMapEntry == mSymbolMap.cend() ) ) { mLastMapEntry = newEntry; } return success; } void Symbolizer::EndParsing() { // If any data was left in the buffer, report it to mark it as complete. if( !mSymbolBuffer.IsEmpty() ) { // Ignore the return value when reporting since this is the end ReportSymbolFound( mSavedCategory ); } Reset(); } bool Symbolizer::Parse ( Byte const* const aBytes, size_t const aNumBytes, size_t& aBytesRead ) { aBytesRead = 0; if( ( aBytes == NULL ) || ( aNumBytes == 0 ) ) { BFDP_MISUSE_ERROR( "Bad input to Parse()" ); return false; } size_t curPos = 0; while( curPos < aNumBytes ) { /* Treat bytes as a multi-byte sequence and convert to a symbol */ Unicode::CodePoint symbol; size_t const bytesToConvert = std::min< size_t >( ( aNumBytes - curPos ), mByteConverter.GetMaxBytes() ); size_t bytesRead = mByteConverter.ConvertBytes( &aBytes[curPos], bytesToConvert, symbol ); if( bytesRead == -2 ) // TODO: Magic number { // Incomplete MB sequence if( ( curPos + bytesToConvert ) >= aNumBytes ) { // This is at the end of the the buffer; so allow parsing to continue aBytesRead = aNumBytes; return true; } else { // This is in the middle of the buffer BFDP_RUNTIME_ERROR( "Incomplete multi-byte character sequence" ); aBytesRead = curPos; return false; } } else if( bytesRead == -1 ) // TODO: Magic number { // Invalid MB sequence BFDP_RUNTIME_ERROR( "Invalid multi-byte character sequence" ); aBytesRead = curPos; return false; } else if( bytesRead == 0 ) { BFDP_RUNTIME_ERROR( "Invalid multi-byte character sequence" ); aBytesRead = curPos; return false; } /* Categorize the symbol */ int category = CategoryBase::Unknown; bool shouldConcatenate = true; LookupCategory( symbol, category, shouldConcatenate ); /* Detect category boundary and send cached data */ // See if the previous category is complete if( mSavedCategory != CategoryBase::NoCategory ) { // Report the symbol when changing categories if( category != mSavedCategory ) { if( ( !mSymbolBuffer.IsEmpty() ) && ( !ReportSymbolFound( mSavedCategory ) ) ) { aBytesRead = curPos; return true; } } } /* Save/track categorized data */ mSavedCategory = category; bool saved = mSymbolBuffer.Add( symbol ); if( ( !saved ) && ( category == CategoryBase::Unknown ) ) { // For uncategorized data which does not fit in the buffer, send the result and // add it again; this isn't an error since this data could be anything. if( !ReportSymbolFound( category ) ) { aBytesRead = curPos; return true; } saved = mSymbolBuffer.Add( symbol ); } if( !saved ) { BFDP_RUNTIME_ERROR( "Symbol too big" ); aBytesRead = curPos; return false; } else if( !shouldConcatenate ) { // If concatenation should not occur, go ahead and report the symbol right now if( !ReportSymbolFound( category ) ) { aBytesRead = curPos; return true; } } curPos += bytesRead; } // end while // Save the final count of bytes parsed aBytesRead = curPos; // If the final section of data was uncategorized, treat it as complete and fire the // event. Categorized data may span multiple Parse() calls. if( mSavedCategory == CategoryBase::Unknown ) { // Report the data, but ignore the return value since Parse() is done anyway ReportSymbolFound( mSavedCategory ); } return true; } void Symbolizer::Reset() { mSymbolBuffer.Clear(); mSavedCategory = CategoryBase::NoCategory; // There is no need to reset the last map entry; it may or may not help the next parsing // operation. } void Symbolizer::LookupCategory ( Unicode::CodePoint const aSymbol, int& aCategory, bool& aShouldConcatenate ) { if( mSymbolMap.empty() ) { return; } // Perform a lookup if one of the following is true: // * No previous category was found // * The last category does not contains the symbol (it is likely the next character // will be in the same category as the last one) if( ( mLastMapEntry == mSymbolMap.cend() ) || ( !(*mLastMapEntry)->Contains( aSymbol ) ) ) { // Look for a new category for mLastMapEntry mLastMapEntry = mSymbolMap.cend(); for( SymbolCategoryMap::const_iterator iter = mSymbolMap.cbegin(); iter != mSymbolMap.cend(); ++iter ) { if( (*iter)->Contains( aSymbol ) ) { mLastMapEntry = iter; break; } } } // If a category was found, update output parameters if( mLastMapEntry != mSymbolMap.cend() ) { aCategory = (*mLastMapEntry)->GetCategory(); aShouldConcatenate = (*mLastMapEntry)->ShouldConcatenate(); } } bool Symbolizer::ReportSymbolFound ( int const aCategory ) { std::ostringstream utf8String; Unicode::Utf8Converter utf8Conv; size_t const numBytes = utf8Conv.GetMaxBytes(); Data::ByteBuffer buf; if( !buf.Allocate( numBytes ) ) { BFDP_RUNTIME_ERROR( "Out of memory while converting sequence to UTF-8" ); return false; } for( size_t i = 0; i < mSymbolBuffer.GetSize(); ++i ) { size_t bytesConverted = utf8Conv.ConvertSymbol ( mSymbolBuffer.GetSymbolAt( i ), buf.GetPtr(), numBytes ); if( 0 == bytesConverted ) { BFDP_RUNTIME_ERROR( "Invalid symbol while converting to UTF-8" ); return false; } utf8String << buf.GetString( bytesConverted ); } bool keepParsing = ( aCategory == CategoryBase::Unknown ) ? mObserver.OnUnmappedSymbols( utf8String.str(), mSymbolBuffer.GetSize() ) : mObserver.OnMappedSymbols( aCategory, utf8String.str(), mSymbolBuffer.GetSize() ); mSymbolBuffer.Clear(); return keepParsing; } } // namespace Lexer } // namespace Bfdp
35.903323
121
0.507826
dpkristensen
7edd4785ac326e0efbc18768ea04fa9c3d3dea86
3,087
hpp
C++
tests/tdd/generator.hpp
tjahn/mbedcrypto
23ea27d1d7602e0f2c4e8c8c148b73ca7b4f1425
[ "MIT" ]
40
2016-04-01T15:20:24.000Z
2022-03-24T08:38:12.000Z
tests/tdd/generator.hpp
tjahn/mbedcrypto
23ea27d1d7602e0f2c4e8c8c148b73ca7b4f1425
[ "MIT" ]
4
2017-12-12T09:04:38.000Z
2021-01-30T04:19:05.000Z
tests/tdd/generator.hpp
tjahn/mbedcrypto
23ea27d1d7602e0f2c4e8c8c148b73ca7b4f1425
[ "MIT" ]
15
2016-07-22T02:46:23.000Z
2020-12-23T15:57:37.000Z
/** @file generator.hpp * * @copyright (C) 2016 * @date 2016.03.06 * @version 1.0.0 * @author amir zamani <azadkuh@live.com> * */ #ifndef TESTS_GENERATOR_HPP #define TESTS_GENERATOR_HPP #include "mbedcrypto/types.hpp" /////////////////////////////////////////////////////////////////////////////// namespace mbedcrypto { namespace test { /////////////////////////////////////////////////////////////////////////////// // following functions return some sample data for various test units. const char* short_text(); const char* long_text(); buffer_t short_binary(); buffer_t long_binary(); /// a sample RSA, 2048bit key in pem format /// generated by: /// @code /// $> openssl genrsa -out mprivate.pem 2048 /// @endcode buffer_t rsa_private_key(); /// same as above key, encrypted by AES256. password is: mbedcrypto1234 /// generated by: /// @code /// $> openssl rsa -aes256 -in mprivate.pem -out mprivate_encrypted.pem /// @endcode buffer_t rsa_private_key_password(); /// the public pair of the above key /// generated by: /// @code /// $> openssl rsa -in mprivate.pem -pubout -out mpublic.pem /// @endcode buffer_t rsa_public_key(); /// with the above private key and long text /// $> openssl dgst -sha1 -sign private.pem -out signature.bin long.txt /// verification: /// $> openssl dgst -sha1 -verify public.pem -signature signature.bin long.txt buffer_t long_text_signature(); /////////////////////////////////////////////////////////////////////////////// /// utility function for reading a buffer in chunks /// used by test units to test start()/update().../finish() sequences. template <class BufferT, class Func, class... Args> void chunker(size_t chunk_size, const BufferT& src, Func&& func, Args&&... args) { const auto* data = reinterpret_cast<const uint8_t*>(src.data()); for (size_t i = 0; (i + chunk_size) <= src.size(); i += chunk_size) { func(data + i, chunk_size, std::forward<Args&&>(args)...); } size_t residue = src.size() % chunk_size; if (residue) { func( data + src.size() - residue, residue, std::forward<Args&&>(args)...); } } /// dumps content of data as binary to filename void dump_to_file(const buffer_t& data, const char* filename); /////////////////////////////////////////////////////////////////////////////// inline bool icompare(const char* a, const char* b) { return std::strncmp(a, b, std::strlen(b)) == 0; } /////////////////////////////////////////////////////////////////////////////// } // namespace test /////////////////////////////////////////////////////////////////////////////// #if defined(QT_CORE_LIB) inline bool operator==(const QByteArray& ba, const std::string& ss) { if ((size_t)ba.size() != ss.size()) return false; return std::memcmp(ba.data(), ss.data(), ss.size()) == 0; } #endif // QT_CORE_LIB /////////////////////////////////////////////////////////////////////////////// } // namespace mbedcrypto /////////////////////////////////////////////////////////////////////////////// #endif // TESTS_GENERATOR_HPP
31.5
79
0.530936
tjahn
7ede1883cfc96480d622e9052c04a386389c3f2c
3,258
hpp
C++
inc/Fluke8050A.hpp
farlepet/8050a-display
0df434816bc371ca80c2757c99ae97aa326d3894
[ "MIT" ]
1
2020-12-24T03:55:45.000Z
2020-12-24T03:55:45.000Z
inc/Fluke8050A.hpp
farlepet/8050a-display
0df434816bc371ca80c2757c99ae97aa326d3894
[ "MIT" ]
null
null
null
inc/Fluke8050A.hpp
farlepet/8050a-display
0df434816bc371ca80c2757c99ae97aa326d3894
[ "MIT" ]
null
null
null
#ifndef FLUKE8050A_HPP #define FLUKE8080A_HPP #include <stdint.h> typedef struct { uint8_t dp; /*!< Decimal point / relative */ uint8_t hv; /*!< High Voltage */ uint8_t w; /*!< BCD 0 / - */ uint8_t x; /*!< BCD 1 / + */ uint8_t y; /*!< BCD 2 / dB */ uint8_t z; /*!< BCD 3 / 1 */ uint8_t st0; /*!< Strobe 0 */ uint8_t st1; /*!< Strobe 1 */ uint8_t st2; /*!< Strobe 2 */ uint8_t st3; /*!< Strobe 3 */ uint8_t st4; /*!< Strobe 4 */ } fluke_8050a_pins_t; typedef enum { FLUKE8050A_STATUS_ONE = (1U << 0), /* Extra 1 */ FLUKE8050A_STATUS_NEG = (1U << 1), /* Negative sign */ FLUKE8050A_STATUS_POS = (1U << 2), /* Positive sign */ FLUKE8050A_STATUS_DB = (1U << 3), /* Decibels */ FLUKE8050A_STATUS_REL = (1U << 4), /* Relative */ FLUKE8050A_STATUS_BT = (1U << 5), /* Battery */ FLUKE8050A_STATUS_HV = (1U << 6), /* High Voltage */ } fluke_8050a_status_e; class Fluke8050A { private: fluke_8050a_pins_t pins; /*!< GPIOHS pins */ uint8_t bcd[4]; /*!< BCD value of display. Left-most ones digit in status. */ uint8_t status; /*!< Status bits, see fluke_8050a_statue_e. */ uint8_t statusPend; /*!< Pending status, used to prevent short glitches from messing up stored relative value. */ uint8_t decimal; /*!< Position of decimal point, 0xFF in non-existant */ float value; /*!< Last displayed numberical value */ float relaPend; /*!< Pending relative value */ float relative; /*!< Last recorded value when relative mode was enabled */ /** * Convert received and stored data into numerical value. * * @return 0 on success, else non-zero */ int convert(void); /** * Strobe 0 interrupt handler. * * Called when strobe 0 line goes high. Reads and stores status information. */ int st0Interrupt(void); /** * Strobe 1-4 interrupt handler * * Called when strobe 1-4 lines go high. Stores current digit, and updates * decimal point position if applicable. */ int st1Interrupt(void); /** * Set status bit, taking pending status into account. * * @param mask Mask with bit to set */ void statusSet(uint8_t mask); /** * Clear status bit, taking pending status into account. * * @param mask Mask with bit to clear */ void statusClear(uint8_t mask); public: /** * Constructor * * @param pins Set of pins to use to communicate with the 8050A */ Fluke8050A(fluke_8050a_pins_t *pins); /** * Initialize GPIO used to receive data from the 8050A */ void init(void); /** * Get the last seen value * * @return Last seen value */ float getValue(void); /** * Get the current relative value, if applicable. * * @return NAN if not in relative mode, else value seen when relative mode * was first detected. */ float getRelative(void); /** * Print some internal state to the serial port for debugging purposes. */ void debug(void); }; #endif
28.330435
129
0.574893
farlepet
7ee5d172003adc97d26066b70635b0d7c922db19
35,859
cpp
C++
source/plugin/PluginVst2x.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
404
2015-01-02T18:37:30.000Z
2022-03-31T17:38:39.000Z
source/plugin/PluginVst2x.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
101
2015-01-12T08:14:13.000Z
2021-03-16T12:36:19.000Z
source/plugin/PluginVst2x.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
96
2015-01-06T08:05:12.000Z
2022-03-08T16:18:49.000Z
// // PluginVst2x.cpp - MrsWatson // Copyright (c) 2016 Teragon Audio. 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // C++ includes #include "PluginVst2xHostCallback.h" #define VST_FORCE_DEPRECATED 0 #include "aeffectx.h" // C includes extern "C" { #include "PluginVst2x.h" #include "audio/AudioSettings.h" #include "base/File.h" #include "base/PlatformInfo.h" #include "base/Types.h" #include "logging/EventLogger.h" #include "midi/MidiEvent.h" #include "plugin/Plugin.h" #include "plugin/PluginVst2xId.h" extern LinkedList getVst2xPluginLocations(CharString currentDirectory); extern LibraryHandle getLibraryHandleForPlugin(const CharString pluginAbsolutePath); extern void showVst2xEditor(AEffect *effect, const CharString pluginName, PluginWindowSize *rect); extern AEffect *loadVst2xPlugin(LibraryHandle libraryHandle); extern void closeLibraryHandle(LibraryHandle libraryHandle); } // Opaque struct must be declared here rather than in the header, otherwise many // other files in this project must be compiled as C++ code. =/ typedef struct { AEffect *pluginHandle; PluginVst2xId pluginId; Vst2xPluginDispatcherFunc dispatcher; LibraryHandle libraryHandle; boolByte isPluginShell; VstInt32 shellPluginId; // Must be retained until processReplacing() is called, so best to keep a // reference in the plugin's data storage. struct VstEvents *vstEvents; } PluginVst2xDataMembers; typedef PluginVst2xDataMembers *PluginVst2xData; // Implementation body starts here extern "C" { // Current plugin ID, which is mostly used by shell plugins during // initialization. To support VST shell plugins, we must provide them with a // unique ID of a sub-plugin which they will ask for from the host (opcode // audioMasterCurrentId). The problem is that this host callback is made when // the plugin's main() function is called for the first time, in // loadVst2xPlugin(). While the AEffect struct provides a void* user member for // storing a pointer to an arbitrary object which could be used to store this // value, that struct is not fully constructed when the callback is made to the // host (in fact, calling the plugin's main() *returns* the AEffect* which we // save in our extraData struct). Therefore it is not possible to have the // plugin reach our host callback with some custom data, and we must keep a // global variable to the current effect ID. That said, this prevents // initializing plugins in multiple threads in the future, as as we must set // this to the correct ID before calling the plugin's main() function when // setting up the effect chain. VstInt32 currentPluginUniqueId; const char *_getVst2xPlatformExtension(void); const char *_getVst2xPlatformExtension(void) { PlatformInfo platform = newPlatformInfo(); PlatformType platformType = platform->type; freePlatformInfo(platform); switch (platformType) { case PLATFORM_MACOSX: return ".vst"; case PLATFORM_WINDOWS: return ".dll"; case PLATFORM_LINUX: return ".so"; default: return EMPTY_STRING; } } static void _logPluginVst2xInLocation(void *item, void *userData) { File itemFile = (File)item; CharString itemPath = newCharStringWithCString(itemFile->absolutePath->data); boolByte *pluginsFound = (boolByte *)userData; char *dot; logDebug("Checking item '%s'", itemPath->data); dot = strrchr(itemPath->data, '.'); if (dot != NULL) { if (!strncmp(dot, _getVst2xPlatformExtension(), 3)) { *dot = '\0'; logInfo(" %s", itemPath->data); *pluginsFound = true; } } freeCharString(itemPath); } static void _logPluginLocation(const CharString location) { logInfo("Location '%s', type VST 2.x:", location->data); } static void _listPluginsVst2xInLocation(void *item, void *userData) { CharString locationString; File location = NULL; LinkedList locationItems; boolByte pluginsFound = false; locationString = (CharString)item; _logPluginLocation(locationString); location = newFileWithPath(locationString); locationItems = fileListDirectory(location); if (linkedListLength(locationItems) == 0) { // Empty or does not exist, return logInfo(" (Empty or non-existent directory)"); freeLinkedList(locationItems); freeFile(location); return; } linkedListForeach(locationItems, _logPluginVst2xInLocation, &pluginsFound); if (!pluginsFound) { logInfo(" (No plugins found)"); } freeFile(location); freeLinkedListAndItems(locationItems, (LinkedListFreeItemFunc)freeFile); } void listAvailablePluginsVst2x(const CharString pluginRoot) { if (!charStringIsEmpty(pluginRoot)) { _listPluginsVst2xInLocation(pluginRoot, NULL); } LinkedList pluginLocations = getVst2xPluginLocations(fileGetCurrentDirectory()); linkedListForeach(pluginLocations, _listPluginsVst2xInLocation, NULL); freeLinkedListAndItems(pluginLocations, (LinkedListFreeItemFunc)freeCharString); } static boolByte _doesVst2xPluginExistAtLocation(const CharString pluginName, const CharString locationName) { boolByte result = false; const char *subpluginSeparator = NULL; CharString pluginSearchName = NULL; CharString pluginSearchExtension = NULL; File location = NULL; File pluginSearchPath = NULL; subpluginSeparator = strrchr(pluginName->data, kPluginVst2xSubpluginSeparator); if (subpluginSeparator != NULL) { pluginSearchName = newCharString(); strncpy(pluginSearchName->data, pluginName->data, subpluginSeparator - pluginName->data); result = _doesVst2xPluginExistAtLocation(pluginSearchName, locationName); freeCharString(pluginSearchName); return result; } logDebug("Looking for plugin '%s' in '%s'", pluginName->data, locationName->data); location = newFileWithPath(locationName); if (location == NULL || !fileExists(location) || location->fileType != kFileTypeDirectory) { logWarn("Location '%s' is not a valid directory", locationName->data); freeFile(location); return result; } pluginSearchName = newCharStringWithCString(pluginName->data); pluginSearchPath = newFileWithParent(location, pluginSearchName); if (pluginSearchPath == NULL) { freeFile(location); return result; } // Get the file extension of the plugin name given by the user, but also // check that the extension is what we expect it to be on this platform. // Otherwise, plugin names which contain a dot may give us an incorrect // file extension. pluginSearchExtension = fileGetExtension(pluginSearchPath); if (pluginSearchExtension == NULL || !charStringIsEqualToCString(pluginSearchExtension, _getVst2xPlatformExtension(), true)) { freeFile(pluginSearchPath); charStringAppendCString(pluginSearchName, _getVst2xPlatformExtension()); pluginSearchPath = newFileWithParent(location, pluginSearchName); } if (fileExists(pluginSearchPath)) { result = true; } freeCharString(pluginSearchExtension); freeCharString(pluginSearchName); freeFile(pluginSearchPath); freeFile(location); return result; } static CharString _getVst2xPluginLocation(const CharString pluginName, const CharString pluginRoot) { File pluginAbsolutePath = newFileWithPath(pluginName); if (fileExists(pluginAbsolutePath)) { File pluginParentDir = fileGetParent(pluginAbsolutePath); CharString result = newCharStringWithCString(pluginParentDir->absolutePath->data); freeFile(pluginParentDir); freeFile(pluginAbsolutePath); return result; } else { freeFile(pluginAbsolutePath); } // Then search the path given to --plugin-root, if given if (!charStringIsEmpty(pluginRoot)) { if (_doesVst2xPluginExistAtLocation(pluginName, pluginRoot)) { return newCharStringWithCString(pluginRoot->data); } } // If the plugin wasn't found in the user's plugin root, then try searching // the default locations for the platform, starting with the current // directory. LinkedList pluginLocations = getVst2xPluginLocations(fileGetCurrentDirectory()); if (pluginLocations->item == NULL) { freeLinkedListAndItems(pluginLocations, (LinkedListFreeItemFunc)freeCharString); return NULL; } LinkedListIterator iterator = pluginLocations; while (iterator != NULL) { CharString searchLocation = (CharString)(iterator->item); if (_doesVst2xPluginExistAtLocation(pluginName, searchLocation)) { CharString result = newCharStringWithCString(searchLocation->data); freeLinkedListAndItems(pluginLocations, (LinkedListFreeItemFunc)freeCharString); return result; } iterator = (LinkedListIterator)iterator->nextItem; } freeLinkedListAndItems(pluginLocations, (LinkedListFreeItemFunc)freeCharString); return NULL; } boolByte pluginVst2xExists(const CharString pluginName, const CharString pluginRoot) { CharString pluginLocation = _getVst2xPluginLocation(pluginName, pluginRoot); boolByte result = (boolByte)((pluginLocation != NULL) && !charStringIsEmpty(pluginLocation)); freeCharString(pluginLocation); return result; } static short _canPluginDo(Plugin plugin, const char *canDoString) { PluginVst2xData data = (PluginVst2xData)plugin->extraData; VstIntPtr result = data->dispatcher(data->pluginHandle, effCanDo, 0, 0, (void *)canDoString, 0.0f); return (short)result; } static void _resumePlugin(Plugin plugin) { logDebug("Resuming plugin '%s'", plugin->pluginName->data); PluginVst2xData data = (PluginVst2xData)plugin->extraData; if (data->isPluginShell && data->shellPluginId == 0) { logError("'%s' is a shell plugin, but no sub-plugin ID was given, run with " "--help plugin", plugin->pluginName->data); } data->dispatcher(data->pluginHandle, effMainsChanged, 0, 1, NULL, 0.0f); data->dispatcher(data->pluginHandle, effStartProcess, 0, 0, NULL, 0.0f); } static void _suspendPlugin(Plugin plugin) { logDebug("Suspending plugin '%s'", plugin->pluginName->data); PluginVst2xData data = (PluginVst2xData)plugin->extraData; data->dispatcher(data->pluginHandle, effMainsChanged, 0, 0, NULL, 0.0f); data->dispatcher(data->pluginHandle, effStopProcess, 0, 0, NULL, 0.0f); } static void _setSpeakers(struct VstSpeakerArrangement *speakerArrangement, int channels) { memset(speakerArrangement, 0, sizeof(struct VstSpeakerArrangement)); speakerArrangement->numChannels = channels; if (channels <= 8) { speakerArrangement->numChannels = channels; } else { logInfo("Number of channels = %d. Will only arrange 8 speakers.", channels); speakerArrangement->numChannels = 8; } switch (speakerArrangement->numChannels) { case 0: speakerArrangement->type = kSpeakerArrEmpty; break; case 1: speakerArrangement->type = kSpeakerArrMono; break; case 2: speakerArrangement->type = kSpeakerArrStereo; break; case 3: speakerArrangement->type = kSpeakerArr30Music; break; case 4: speakerArrangement->type = kSpeakerArr40Music; break; case 5: speakerArrangement->type = kSpeakerArr50; break; case 6: speakerArrangement->type = kSpeakerArr60Music; break; case 7: speakerArrangement->type = kSpeakerArr70Music; break; case 8: speakerArrangement->type = kSpeakerArr80Music; break; default: logInternalError("Cannot arrange more than 8 speakers."); break; } for (int i = 0; i < speakerArrangement->numChannels; i++) { speakerArrangement->speakers[i].azimuth = 0.0f; speakerArrangement->speakers[i].elevation = 0.0f; speakerArrangement->speakers[i].radius = 0.0f; speakerArrangement->speakers[i].reserved = 0.0f; speakerArrangement->speakers[i].name[0] = '\0'; speakerArrangement->speakers[i].type = kSpeakerUndefined; } } static boolByte _initVst2xPlugin(Plugin plugin) { PluginVst2xData data = (PluginVst2xData)plugin->extraData; PluginVst2xId subpluginId; logDebug("Initializing VST2.x plugin '%s'", plugin->pluginName->data); if (data->pluginHandle->flags & effFlagsIsSynth) { plugin->pluginType = PLUGIN_TYPE_INSTRUMENT; } else { plugin->pluginType = PLUGIN_TYPE_EFFECT; } if (data->pluginHandle->dispatcher(data->pluginHandle, effGetPlugCategory, 0, 0, NULL, 0.0f) == kPlugCategShell) { subpluginId = newPluginVst2xIdWithId((unsigned long)data->shellPluginId); logDebug("VST is a shell plugin, sub-plugin ID '%s'", subpluginId->idString->data); freePluginVst2xId(subpluginId); data->isPluginShell = true; } data->dispatcher(data->pluginHandle, effOpen, 0, 0, NULL, 0.0f); data->dispatcher(data->pluginHandle, effSetSampleRate, 0, 0, NULL, (float)getSampleRate()); data->dispatcher(data->pluginHandle, effSetBlockSize, 0, (VstIntPtr)getBlocksize(), NULL, 0.0f); struct VstSpeakerArrangement inSpeakers; _setSpeakers(&inSpeakers, data->pluginHandle->numInputs); struct VstSpeakerArrangement outSpeakers; _setSpeakers(&outSpeakers, data->pluginHandle->numOutputs); data->dispatcher(data->pluginHandle, effSetSpeakerArrangement, 0, (VstIntPtr)&inSpeakers, &outSpeakers, 0.0f); return true; } unsigned long pluginVst2xGetUniqueId(const Plugin self) { if (self->interfaceType == PLUGIN_TYPE_VST_2X) { PluginVst2xData data = (PluginVst2xData)self->extraData; return (unsigned long)data->pluginHandle->uniqueID; } return 0; } unsigned long pluginVst2xGetVersion(const Plugin self) { if (self->interfaceType == PLUGIN_TYPE_VST_2X) { PluginVst2xData data = (PluginVst2xData)self->extraData; return (unsigned long)data->pluginHandle->version; } return 0; } void pluginVst2xAudioMasterIOChanged(const Plugin self, AEffect const *const newValues) { PluginVst2xData data = (PluginVst2xData)(self->extraData); data->pluginHandle->initialDelay = newValues->initialDelay; if (newValues->numInputs != data->pluginHandle->numInputs || newValues->numOutputs != data->pluginHandle->numOutputs) { data->pluginHandle->numInputs = newValues->numInputs; struct VstSpeakerArrangement inSpeakers; _setSpeakers(&inSpeakers, data->pluginHandle->numInputs); data->pluginHandle->numOutputs = newValues->numOutputs; struct VstSpeakerArrangement outSpeakers; _setSpeakers(&outSpeakers, data->pluginHandle->numOutputs); data->dispatcher(data->pluginHandle, effSetSpeakerArrangement, 0, (VstIntPtr)&inSpeakers, &outSpeakers, 0.0f); } } static boolByte _openVst2xPlugin(void *pluginPtr) { boolByte result = false; AEffect *pluginHandle; Plugin plugin = (Plugin)pluginPtr; PluginVst2xData data = (PluginVst2xData)plugin->extraData; char *subpluginSeparator = strrchr(plugin->pluginName->data, kPluginVst2xSubpluginSeparator); CharString subpluginIdString = NULL; // Check to see if a sub-plugin has been given, which would indicate that a // shell plugin is being used. However, we must also make sure that the // separator is past the 2nd character position, since otherwise it may // conflict with absolute paths on Windows. It was a bad idea to use colon // as the sub-plugin separator character. :( size_t separatorPosition = subpluginSeparator - plugin->pluginName->data; if (subpluginSeparator != NULL && separatorPosition > 1) { *subpluginSeparator = '\0'; subpluginIdString = newCharStringWithCapacity(kCharStringLengthShort); strncpy(subpluginIdString->data, subpluginSeparator + 1, 4); PluginVst2xId subpluginId = newPluginVst2xIdWithStringId(subpluginIdString); data->shellPluginId = (VstInt32)subpluginId->id; currentPluginUniqueId = data->shellPluginId; freePluginVst2xId(subpluginId); } File pluginPath = newFileWithPath(plugin->pluginName); CharString pluginBasename = fileGetBasename(pluginPath); logInfo("Opening VST2.x plugin '%s'", plugin->pluginName->data); if (fileExists(pluginPath)) { charStringCopy(plugin->pluginAbsolutePath, pluginPath->absolutePath); } else { File pluginLocationPath = newFileWithPath(plugin->pluginLocation); CharString pluginNameWithExtension = newCharString(); charStringCopy(pluginNameWithExtension, plugin->pluginName); charStringAppendCString(pluginNameWithExtension, _getVst2xPlatformExtension()); // Reset pluginPath so that we can check if the file exists below freeFile(pluginPath); pluginPath = newFileWithParent(pluginLocationPath, pluginNameWithExtension); charStringCopy(plugin->pluginAbsolutePath, pluginPath->absolutePath); freeFile(pluginLocationPath); freeCharString(pluginNameWithExtension); } if (!fileExists(pluginPath)) { logError("Plugin file '%s' does not exist", pluginPath->absolutePath->data); freeFile(pluginPath); return false; } else { logDebug("Plugin location is '%s'", pluginPath->absolutePath->data); freeFile(pluginPath); } data->libraryHandle = getLibraryHandleForPlugin(plugin->pluginAbsolutePath); if (data->libraryHandle == NULL) { return false; } pluginHandle = loadVst2xPlugin(data->libraryHandle); if (pluginHandle == NULL) { logError("Could not load VST2.x plugin '%s'", plugin->pluginAbsolutePath->data); return false; } // The plugin name which is passed into this function is basically just used // to find the actual location. Now that the plugin has been loaded, we can // set a friendlier name. CharString temp = plugin->pluginName; plugin->pluginName = newCharStringWithCString(pluginBasename->data); freeCharString(pluginBasename); freeCharString(temp); if (data->shellPluginId && subpluginIdString != NULL) { charStringAppendCString(plugin->pluginName, " ("); charStringAppend(plugin->pluginName, subpluginIdString); charStringAppendCString(plugin->pluginName, ")"); } // Check plugin's magic number. If incorrect, then the file either was not // loaded properly, is not a real VST plugin, or is otherwise corrupt. if (pluginHandle->magic != kEffectMagic) { logError("Plugin '%s' has bad magic number, possibly corrupt", plugin->pluginName->data); } else { data->dispatcher = (Vst2xPluginDispatcherFunc)(pluginHandle->dispatcher); data->pluginHandle = pluginHandle; result = _initVst2xPlugin(plugin); if (result) { data->pluginId = newPluginVst2xIdWithId((unsigned long)data->pluginHandle->uniqueID); } } freeCharString(subpluginIdString); return result; } static LinkedList _getCommonCanDos(void) { LinkedList result = newLinkedList(); linkedListAppend(result, (char *)"sendVstEvents"); linkedListAppend(result, (char *)"sendVstMidiEvent"); linkedListAppend(result, (char *)"receiveVstEvents"); linkedListAppend(result, (char *)"receiveVstMidiEvent"); linkedListAppend(result, (char *)"receiveVstTimeInfo"); linkedListAppend(result, (char *)"offline"); linkedListAppend(result, (char *)"midiProgramNames"); linkedListAppend(result, (char *)"bypass"); return result; } static const char *_prettyTextForCanDoResult(int result) { if (result == -1) { return "No"; } else if (result == 0) { return "Don't know"; } else if (result == 1) { return "Yes"; } else { return "Undefined response"; } } static void _displayVst2xPluginCanDo(void *item, void *userData) { char *canDoString = (char *)item; short result = _canPluginDo((Plugin)userData, canDoString); logInfo(" %s: %s", canDoString, _prettyTextForCanDoResult(result)); } static void _displayVst2xPluginInfo(void *pluginPtr) { Plugin plugin = (Plugin)pluginPtr; PluginVst2xData data = (PluginVst2xData)plugin->extraData; CharString nameBuffer = newCharString(); logInfo("Information for VST2.x plugin '%s'", plugin->pluginName->data); data->dispatcher(data->pluginHandle, effGetVendorString, 0, 0, nameBuffer->data, 0.0f); logInfo("Vendor: %s", nameBuffer->data); VstInt32 vendorVersion = (VstInt32)data->dispatcher( data->pluginHandle, effGetVendorVersion, 0, 0, NULL, 0.0f); logInfo("Version: %d", vendorVersion); charStringClear(nameBuffer); logInfo("Unique ID: %s", data->pluginId->idString->data); freeCharString(nameBuffer); VstInt32 pluginCategory = (VstInt32)data->dispatcher( data->pluginHandle, effGetPlugCategory, 0, 0, NULL, 0.0f); switch (plugin->pluginType) { case PLUGIN_TYPE_EFFECT: logInfo("Plugin type: effect, category %d", pluginCategory); break; case PLUGIN_TYPE_INSTRUMENT: logInfo("Plugin type: instrument, category %d", pluginCategory); break; default: logInfo("Plugin type: other, category %d", pluginCategory); break; } logInfo("Version: %d", data->pluginHandle->version); logInfo("I/O: %d/%d", data->pluginHandle->numInputs, data->pluginHandle->numOutputs); logInfo("InitialDelay: %d frames", data->pluginHandle->initialDelay); logInfo("GUI Editor: %s", data->pluginHandle->flags & effFlagsHasEditor ? "yes" : "no"); if (data->isPluginShell && data->shellPluginId == 0) { logInfo("Sub-plugins:"); nameBuffer = newCharStringWithCapacity(kCharStringLengthShort); while (true) { charStringClear(nameBuffer); VstInt32 shellPluginId = (VstInt32)data->dispatcher(data->pluginHandle, effShellGetNextPlugin, 0, 0, nameBuffer->data, 0.0f); if (shellPluginId == 0 || charStringIsEmpty(nameBuffer)) { break; } else { PluginVst2xId subpluginId = newPluginVst2xIdWithId((unsigned long)shellPluginId); logInfo(" '%s' (%s)", subpluginId->idString->data, nameBuffer->data); freePluginVst2xId(subpluginId); } } freeCharString(nameBuffer); } else { nameBuffer = newCharStringWithCapacity(kCharStringLengthShort); logInfo("Parameters (%d total):", data->pluginHandle->numParams); for (VstInt32 i = 0; i < data->pluginHandle->numParams; i++) { float value = data->pluginHandle->getParameter(data->pluginHandle, i); charStringClear(nameBuffer); data->dispatcher(data->pluginHandle, effGetParamName, i, 0, nameBuffer->data, 0.0f); logInfo(" %d: '%s' (%f)", i, nameBuffer->data, value); if (isLogLevelAtLeast(LOG_DEBUG)) { logDebug(" Displaying common values for parameter:"); for (unsigned int j = 0; j < 128; j++) { const float midiValue = (float)j / 127.0f; // Don't use the other setParameter function, or else that will log // like crazy to a different log level. data->pluginHandle->setParameter(data->pluginHandle, i, midiValue); charStringClear(nameBuffer); data->dispatcher(data->pluginHandle, effGetParamDisplay, i, 0, nameBuffer->data, 0.0f); logDebug(" %0.3f/MIDI value %d (0x%02x): %s", midiValue, j, j, nameBuffer->data); } } } logInfo("Programs (%d total):", data->pluginHandle->numPrograms); for (int i = 0; i < data->pluginHandle->numPrograms; i++) { charStringClear(nameBuffer); data->dispatcher(data->pluginHandle, effGetProgramNameIndexed, i, 0, nameBuffer->data, 0.0f); logInfo(" %d: '%s'", i, nameBuffer->data); } charStringClear(nameBuffer); data->dispatcher(data->pluginHandle, effGetProgramName, 0, 0, nameBuffer->data, 0.0f); logInfo("Current program: '%s'", nameBuffer->data); freeCharString(nameBuffer); logInfo("Common canDo's:"); LinkedList commonCanDos = _getCommonCanDos(); linkedListForeach(commonCanDos, _displayVst2xPluginCanDo, plugin); freeLinkedList(commonCanDos); } } static int _getVst2xPluginSetting(void *pluginPtr, PluginSetting pluginSetting) { Plugin plugin = (Plugin)pluginPtr; PluginVst2xData data = (PluginVst2xData)plugin->extraData; switch (pluginSetting) { case PLUGIN_SETTING_TAIL_TIME_IN_MS: { VstInt32 tailSize = (VstInt32)data->dispatcher( data->pluginHandle, effGetTailSize, 0, 0, NULL, 0.0f); // For some reason, the VST SDK says that plugins return a 1 here for no // tail. if (tailSize == 1 || tailSize == 0) { return 0; } else { // If tailSize is not 0 or 1, then it is assumed to be in samples return (int)((double)tailSize * getSampleRate() / 1000.0f); } } case PLUGIN_NUM_INPUTS: return data->pluginHandle->numInputs; case PLUGIN_NUM_OUTPUTS: return data->pluginHandle->numOutputs; case PLUGIN_INITIAL_DELAY: return data->pluginHandle->initialDelay; default: logUnsupportedFeature("Plugin setting for VST2.x"); return 0; } } void pluginVst2xSetProgramChunk(Plugin plugin, char *chunk, size_t chunkSize) { PluginVst2xData data = (PluginVst2xData)plugin->extraData; data->dispatcher(data->pluginHandle, effSetChunk, 1, (VstIntPtr)chunkSize, chunk, 0.0f); } static void _processAudioVst2xPlugin(void *pluginPtr, SampleBuffer inputs, SampleBuffer outputs) { Plugin plugin = (Plugin)pluginPtr; PluginVst2xData data = (PluginVst2xData)plugin->extraData; data->pluginHandle->processReplacing(data->pluginHandle, inputs->samples, outputs->samples, (VstInt32)outputs->blocksize); } static void _fillVstMidiEvent(const MidiEvent midiEvent, VstMidiEvent *vstMidiEvent) { switch (midiEvent->eventType) { case MIDI_TYPE_REGULAR: vstMidiEvent->type = kVstMidiType; vstMidiEvent->byteSize = sizeof(VstMidiEvent); vstMidiEvent->deltaFrames = (VstInt32)midiEvent->deltaFrames; vstMidiEvent->midiData[0] = midiEvent->status; vstMidiEvent->midiData[1] = midiEvent->data1; vstMidiEvent->midiData[2] = midiEvent->data2; vstMidiEvent->flags = 0; vstMidiEvent->reserved1 = 0; vstMidiEvent->reserved2 = 0; break; case MIDI_TYPE_SYSEX: logUnsupportedFeature("VST2.x plugin sysex messages"); break; case MIDI_TYPE_META: // Ignore, don't care break; default: logInternalError("Cannot convert MIDI event type '%d' to VstMidiEvent", midiEvent->eventType); break; } } static void _processMidiEventsVst2xPlugin(void *pluginPtr, LinkedList midiEvents) { Plugin plugin = (Plugin)pluginPtr; PluginVst2xData data = (PluginVst2xData)(plugin->extraData); int numEvents = linkedListLength(midiEvents); // Free events from the previous call if (data->vstEvents != NULL) { for (int i = 0; i < data->vstEvents->numEvents; i++) { free(data->vstEvents->events[i]); } free(data->vstEvents); } data->vstEvents = (struct VstEvents *)malloc( sizeof(struct VstEvent) + (numEvents * sizeof(struct VstEvent *))); data->vstEvents->numEvents = numEvents; // Some monophonic instruments have problems dealing with the order of MIDI // events, so send them all note off events *first* followed by any other // event types. LinkedListIterator iterator = midiEvents; int outIndex = 0; while (iterator != NULL && outIndex < numEvents) { MidiEvent midiEvent = (MidiEvent)(iterator->item); if (midiEvent != NULL && (midiEvent->status >> 4) == 0x08) { VstMidiEvent *vstMidiEvent = (VstMidiEvent *)malloc(sizeof(VstMidiEvent)); _fillVstMidiEvent(midiEvent, vstMidiEvent); data->vstEvents->events[outIndex] = (VstEvent *)vstMidiEvent; outIndex++; } iterator = (LinkedListIterator)(iterator->nextItem); } iterator = midiEvents; while (iterator != NULL && outIndex < numEvents) { MidiEvent midiEvent = (MidiEvent)(iterator->item); if (midiEvent != NULL && (midiEvent->status >> 4) != 0x08) { VstMidiEvent *vstMidiEvent = (VstMidiEvent *)malloc(sizeof(VstMidiEvent)); _fillVstMidiEvent(midiEvent, vstMidiEvent); data->vstEvents->events[outIndex] = (VstEvent *)vstMidiEvent; outIndex++; } iterator = (LinkedListIterator)(iterator->nextItem); } data->dispatcher(data->pluginHandle, effProcessEvents, 0, 0, data->vstEvents, 0.0f); } boolByte pluginVst2xSetProgram(Plugin plugin, const int programNumber) { PluginVst2xData data = (PluginVst2xData)plugin->extraData; CharString currentProgram; VstInt32 result; if (programNumber < data->pluginHandle->numPrograms) { result = (VstInt32)data->pluginHandle->dispatcher( data->pluginHandle, effSetProgram, 0, programNumber, NULL, 0.0f); if (result != 0) { logError("Plugin '%s' failed to load program number %d", plugin->pluginName->data, programNumber); return false; } else { result = (VstInt32)data->pluginHandle->dispatcher( data->pluginHandle, effGetProgram, 0, 0, NULL, 0.0f); if (result != programNumber) { logError("Plugin '%s' claimed to load program %d successfully, but " "current program is %d", plugin->pluginName->data, programNumber, result); return false; } else { currentProgram = newCharStringWithCapacity(kVstMaxProgNameLen + 1); data->dispatcher(data->pluginHandle, effGetProgramName, 0, 0, currentProgram->data, 0.0f); logDebug("Current program is now '%s'", currentProgram->data); freeCharString(currentProgram); return true; } } } else { logError("Cannot load program, plugin '%s' only has %d programs", plugin->pluginName->data, data->pluginHandle->numPrograms - 1); return false; } } static boolByte _setParameterVst2xPlugin(void *pluginPtr, unsigned int index, float value) { Plugin plugin = (Plugin)pluginPtr; PluginVst2xData data = (PluginVst2xData)(plugin->extraData); if (index < (unsigned int)data->pluginHandle->numParams) { CharString valueBuffer = newCharStringWithCapacity(kCharStringLengthShort); data->pluginHandle->setParameter(data->pluginHandle, index, value); data->dispatcher(data->pluginHandle, effGetParamDisplay, index, 0, valueBuffer->data, 0.0f); logInfo("Set parameter %d on plugin '%s' to %f (%s)", index, plugin->pluginName->data, value, valueBuffer->data); freeCharString(valueBuffer); return true; } else { logError("Cannot set parameter %d on plugin '%s', invalid index", index, plugin->pluginName->data); return false; } } static void _prepareForProcessingVst2xPlugin(void *pluginPtr) { Plugin plugin = (Plugin)pluginPtr; _resumePlugin(plugin); } static boolByte _pluginVst2xGetWindowRect(Plugin self, PluginWindowSize *outRect) { PluginVst2xData data = (PluginVst2xData)(self->extraData); ERect *editorRect = 0; logDebug("Getting editor window size from plugin"); data->pluginHandle->dispatcher(data->pluginHandle, effEditGetRect, 0, 0, &editorRect, 0); if (editorRect != NULL) { outRect->width = editorRect->right - editorRect->left; outRect->height = editorRect->bottom - editorRect->top; logDebug("Plugin window should be %dx%d pixels", outRect->width, outRect->height); return true; } else { logError("Plugin did not return GUI window size"); return false; } } static void _showVst2xEditor(void *pluginPtr) { Plugin plugin = (Plugin)pluginPtr; PluginVst2xData data = (PluginVst2xData)(plugin->extraData); PluginWindowSize windowSize; if ((data->pluginHandle->flags & effFlagsHasEditor) != 0) { logDebug("Attempting to open editor for plugin '%s'", plugin->pluginName->data); if (_pluginVst2xGetWindowRect(plugin, &windowSize)) { showVst2xEditor(data->pluginHandle, plugin->pluginName, &windowSize); } } else { logError("Plugin '%s' does not have a GUI editor", plugin->pluginName->data); } } static void _closeVst2xPlugin(void *pluginPtr) { Plugin plugin = (Plugin)pluginPtr; _suspendPlugin(plugin); } static void _freeVst2xPluginData(void *pluginDataPtr) { PluginVst2xData data = (PluginVst2xData)(pluginDataPtr); data->dispatcher(data->pluginHandle, effClose, 0, 0, NULL, 0.0f); data->dispatcher = NULL; data->pluginHandle = NULL; freePluginVst2xId(data->pluginId); closeLibraryHandle(data->libraryHandle); if (data->vstEvents != NULL) { for (int i = 0; i < data->vstEvents->numEvents; i++) { free(data->vstEvents->events[i]); } free(data->vstEvents); } } Plugin newPluginVst2x(const CharString pluginName, const CharString pluginRoot) { Plugin plugin = _newPlugin(PLUGIN_TYPE_VST_2X, PLUGIN_TYPE_UNKNOWN); charStringCopy(plugin->pluginName, pluginName); freeCharString(plugin->pluginLocation); plugin->pluginLocation = _getVst2xPluginLocation(pluginName, pluginRoot); plugin->openPlugin = _openVst2xPlugin; plugin->displayInfo = _displayVst2xPluginInfo; plugin->getSetting = _getVst2xPluginSetting; plugin->processAudio = _processAudioVst2xPlugin; plugin->processMidiEvents = _processMidiEventsVst2xPlugin; plugin->setParameter = _setParameterVst2xPlugin; plugin->prepareForProcessing = _prepareForProcessingVst2xPlugin; plugin->showEditor = _showVst2xEditor; plugin->closePlugin = _closeVst2xPlugin; plugin->freePluginData = _freeVst2xPluginData; PluginVst2xData extraData = (PluginVst2xData)malloc(sizeof(PluginVst2xDataMembers)); extraData->pluginHandle = NULL; extraData->pluginId = NULL; extraData->dispatcher = NULL; extraData->libraryHandle = NULL; const char *shellPluginDelimiter = strchr(pluginName->data, kPluginVst2xSubpluginSeparator); extraData->isPluginShell = (boolByte)(shellPluginDelimiter != NULL); extraData->shellPluginId = 0; extraData->vstEvents = NULL; plugin->extraData = extraData; return plugin; } }
35.680597
80
0.698569
jagilley
7eea21d243efcfab044d4cf893569701dd9eb485
1,046
cpp
C++
dp_coin_change.cpp
DeeptanshuM/Algorithms
48f91e952b71370127db33fa42d642062690f9d9
[ "MIT" ]
null
null
null
dp_coin_change.cpp
DeeptanshuM/Algorithms
48f91e952b71370127db33fa42d642062690f9d9
[ "MIT" ]
null
null
null
dp_coin_change.cpp
DeeptanshuM/Algorithms
48f91e952b71370127db33fa42d642062690f9d9
[ "MIT" ]
null
null
null
/* My dynammic programming approach to the coin change problem. int amount is the change to be obtained using as few coins as possible given in the coins vector if it's not possible to get change for amount with the coins given (for eg, trying to get change for 30 cents with only quarters available) then -1 must be returned to indicate that. */ class Solution { public: int coinChange(vector<int>& coins, int amount) { vector<int> MinNumCoins (amount + 1, amount + 1); //amount + 1 represents infinity in this solution int coin_i, numCoins; MinNumCoins[0] = 0; for(int m = 1; m <= amount; m++){ for(int i = 0; i < coins.size(); i++){ coin_i = coins[i]; if(m >= coin_i){ numCoins = MinNumCoins[m - coin_i] + 1; if(numCoins < MinNumCoins[m]) MinNumCoins[m] = numCoins; } } } //if given coins can't be used to make change for given amount if(MinNumCoins[amount] == amount + 1) return -1; return MinNumCoins[amount]; } };
30.764706
103
0.630019
DeeptanshuM
7eebd511517291d25c8dac2c2a1be7a9d118db2b
2,162
cpp
C++
Source/Modules/SampleAndHoldModule.cpp
JanMalitschek/ParkerSynth
ff9e14ff8b806350667ff7236e5065cc66651260
[ "MIT" ]
1
2020-03-03T23:41:21.000Z
2020-03-03T23:41:21.000Z
Source/Modules/SampleAndHoldModule.cpp
JanMalitschek/ParkerSynth
ff9e14ff8b806350667ff7236e5065cc66651260
[ "MIT" ]
null
null
null
Source/Modules/SampleAndHoldModule.cpp
JanMalitschek/ParkerSynth
ff9e14ff8b806350667ff7236e5065cc66651260
[ "MIT" ]
null
null
null
#include "SampleAndHoldModule.hpp" #include "..\LookAndFeel\Colors.hpp" #include "..\NodeGraphEditor.h" #include "..\NodeGraphProcessor.h" SampleAndHoldModule::SampleAndHoldModule() : Module(ModuleColorScheme::Grey, "SaH", 2, 1, 0, Point<int>(4, 4), 0) { inputSocketButtons[0]->button.setTooltip("Signal"); inputSocketButtons[1]->button.setTooltip("Trigger Value"); inputSocketButtons[1]->SetValueType(ValueType::SimpleValue); outputSocketButtons[0]->button.setTooltip("Held Value"); outputSocketButtons[0]->SetValueType(ValueType::SimpleValue); holding = false; heldValue = 0.0f; } SampleAndHoldModule::~SampleAndHoldModule(){ removeAllChildren(); } void SampleAndHoldModule::PaintGUI(Graphics &g) { } void SampleAndHoldModule::ResizeGUI() { } void SampleAndHoldModule::sliderValueChanged(Slider* slider) { } void SampleAndHoldModule::sliderDragStarted(Slider* slider) { } void SampleAndHoldModule::sliderDragEnded(Slider* slider) { } float SampleAndHoldModule::GetParameter(int id) { return 0.0f; } void SampleAndHoldModule::SetParameter(int id, float value) { } double SampleAndHoldModule::GetResult(int midiNote, float velocity, int outputID, int voiceID) { if (canBeEvaluated) { double signal = 0.0f; float triggerValue = 0.0f; if (inputs[0].connectedModule >= 0) { signal = ngp->modules[inputs[0].connectedModule]->GetResult(midiNote, velocity, inputs[0].connectedOutput, voiceID); } if (inputs[1].connectedModule >= 0) { triggerValue = ngp->modules[inputs[1].connectedModule]->GetResult(midiNote, velocity, inputs[1].connectedOutput, voiceID); } if (triggerValue > 0.0f && !holding) { holding = true; heldValue = signal; } if (triggerValue <= 0.0f) { holding = false; heldValue = 0.0f; } outputs[0] = heldValue; canBeEvaluated = false; } return outputs[outputID]; } void SampleAndHoldModule::GetResultIteratively(int midiNote, float velocity, int voiceID) { READ_INPUT(signal, 0) READ_INPUT(triggerValue, 1) if (triggerValue > 0.0 && !holding) { holding = true; heldValue = signal; } if (triggerValue <= 0.0) { holding = false; heldValue = 0.0; } outputs[0] = heldValue; }
26.691358
125
0.725717
JanMalitschek
7ef47b215909eead2a7c407b20c70c6520a74b6e
3,674
hpp
C++
include/bytes_reader.hpp
gwisp2/BytesIO
6ebf97073648e2ab38f890429faad0a0d1a35732
[ "Unlicense" ]
2
2021-07-07T04:37:22.000Z
2021-07-08T17:06:25.000Z
include/bytes_reader.hpp
gwisp2/BytesIO
6ebf97073648e2ab38f890429faad0a0d1a35732
[ "Unlicense" ]
null
null
null
include/bytes_reader.hpp
gwisp2/BytesIO
6ebf97073648e2ab38f890429faad0a0d1a35732
[ "Unlicense" ]
null
null
null
#pragma once #include "bytes_io_common.hpp" #include <assert.h> #include <boost/endian/conversion.hpp> #include <cstdint> #include <cstring> #include <stdexcept> #include <type_traits> namespace BytesIO { class BytesReaderError : public std::runtime_error { public: BytesReaderError(const char *what) : std::runtime_error(what) {} }; class BytesReaderEndOfDataError : public BytesReaderError { public: BytesReaderEndOfDataError() : BytesReaderError("End of byte buffer reached") {} }; enum class ReaderSafetyMode { // No capacity checks, BytesReader may read after the end of buffer Unsafe, // Capacity checks are made, variables are not set on reading data in case of end of data. // Special flag is set. SetFlag, // Throw BytesReaderEndOfDataError ThrowException }; template <ByteOrder byteOrder, ReaderSafetyMode safetyMode> class BytesReader { public: BytesReader(const uint8_t *buffer, size_t capacity) : buffer_(buffer), capacity_(capacity), bytesRead_(0), endOfDataErrorFlag_(false) {} void readBytes(uint8_t *dest, size_t len) { if (!checkCapacity(len)) { return; } std::memcpy(dest, buffer_ + bytesRead_, len); bytesRead_ += len; } void readChars(char *dest, size_t len) { if (!checkCapacity(len)) { return; } std::memcpy(dest, buffer_ + bytesRead_, len); bytesRead_ += len; } void setPosition(size_t position) { assert(position <= capacity_); bytesRead_ = position; } size_t position() { return bytesRead_; } template <typename Enum, typename = std::enable_if_t<std::is_enum<Enum>::value>> BytesReader &operator>>(Enum &value) { std::underlying_type_t<Enum> tmp; *this >> tmp; value = Enum(tmp); return *this; } BytesReader &operator>>(uint8_t &u) { return read(u); } BytesReader &operator>>(int8_t &u) { return read(u); } BytesReader &operator>>(char &u) { return read(u); } BytesReader &operator>>(uint16_t &u) { return read(u); } BytesReader &operator>>(int16_t &u) { return read(u); } BytesReader &operator>>(uint32_t &u) { return read(u); } BytesReader &operator>>(int32_t &u) { return read(u); } BytesReader &operator>>(uint64_t &u) { return read(u); } BytesReader &operator>>(int64_t &u) { return read(u); } BytesReader &skipBytes(size_t bytes) { checkCapacity(bytes); bytesRead_ += bytes; return *this; } size_t bytesAvailable() { return capacity_ - bytesRead_; } bool isEndOfDataError() const { return endOfDataErrorFlag_; } private: const uint8_t *buffer_; const size_t capacity_; size_t bytesRead_; // Flag is set in SetFlag safety mode if read occurs when not enough data is present bool endOfDataErrorFlag_; template <class Integer> BytesReader &read(Integer &value) { if (!checkCapacity(sizeof(Integer))) { return *this; } memcpy(&value, buffer_ + bytesRead_, sizeof(Integer)); bytesRead_ += sizeof(Integer); if (byteOrder == ByteOrder::BigEndian) { boost::endian::big_to_native_inplace(value); } else if (byteOrder == ByteOrder::LittleEndian) { boost::endian::little_to_native_inplace(value); } return *this; } bool checkCapacity(size_t sizeToRead) { if (safetyMode == ReaderSafetyMode::Unsafe) { return true; } else if (safetyMode == ReaderSafetyMode::SetFlag) { if (bytesRead_ + sizeToRead > capacity_) { bytesRead_ = capacity_; endOfDataErrorFlag_ = true; return false; } return true; } else { if (bytesRead_ + sizeToRead > capacity_) { throw BytesReaderEndOfDataError(); } return true; } } }; }; // namespace BytesIO
27.214815
138
0.677735
gwisp2
7efa2880554ac0ece50e37588a9c57d5022c2c31
1,228
hpp
C++
cpp_module_02/ex00/Fixed.hpp
AbderrSfa/cpp_modules
2465e31853af87f9bf9faba57ac0470b43918607
[ "Apache-2.0" ]
1
2021-11-05T13:46:36.000Z
2021-11-05T13:46:36.000Z
cpp_module_02/ex00/Fixed.hpp
AbderrSfa/cpp_modules
2465e31853af87f9bf9faba57ac0470b43918607
[ "Apache-2.0" ]
null
null
null
cpp_module_02/ex00/Fixed.hpp
AbderrSfa/cpp_modules
2465e31853af87f9bf9faba57ac0470b43918607
[ "Apache-2.0" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Fixed.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: asfaihi <asfaihi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/28 14:39:01 by asfaihi #+# #+# */ /* Updated: 2021/10/28 15:03:44 by asfaihi ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FIXED_HPP # define FIXED_HPP # include <iostream> class Fixed { private: int _FixedPointVal; static const int _Bits = 0; public: Fixed( void ); Fixed( Fixed const & src ); ~Fixed(); Fixed & operator=( Fixed const & rhs ); int getRawBits( void ) const; void setRawBits( int const raw ); }; #endif
36.117647
80
0.254072
AbderrSfa
7efb240527b0eeba7eb8dcfbc45f65e1311f6132
120
cpp
C++
test/example_greaterthanequals.cpp
patelh63/gtest-demo
6feca30d05cd3a81c99baccd9f17f2a6a0628a97
[ "BSD-3-Clause" ]
null
null
null
test/example_greaterthanequals.cpp
patelh63/gtest-demo
6feca30d05cd3a81c99baccd9f17f2a6a0628a97
[ "BSD-3-Clause" ]
null
null
null
test/example_greaterthanequals.cpp
patelh63/gtest-demo
6feca30d05cd3a81c99baccd9f17f2a6a0628a97
[ "BSD-3-Clause" ]
1
2021-11-20T18:48:23.000Z
2021-11-20T18:48:23.000Z
#include <gtest/gtest.h> #include "example.h" TEST(example, greaterthanequals) { ASSERT_TRUE(greaterthanequals()); }
15
35
0.741667
patelh63
7efcd78208bb4caf682b8979ca673cb4bf49a2d9
7,853
cpp
C++
SDK/Galil PlugIn/MachDevImplementation.cpp
mariusl/step2mach
3ac7ff6c3b29a25f4520e4325e7922f2d34c547a
[ "MIT" ]
6
2019-05-22T03:18:38.000Z
2022-02-07T20:54:38.000Z
SDK/Galil PlugIn/MachDevImplementation.cpp
mariusl/step2mach
3ac7ff6c3b29a25f4520e4325e7922f2d34c547a
[ "MIT" ]
1
2019-11-10T05:57:09.000Z
2020-07-01T05:50:49.000Z
SDK/Galil PlugIn/MachDevImplementation.cpp
mariusl/step2mach
3ac7ff6c3b29a25f4520e4325e7922f2d34c547a
[ "MIT" ]
9
2019-05-20T06:03:55.000Z
2022-02-01T10:16:41.000Z
// MachDevImplementation.cpp // This is the place where the implementor puts his/her code to actually implement the plugin // // ----------------------------------------------------------------------------------------------------- // Revision History: // 7 June 2006 - Separated from MachDevice by JAP // ----------------------------------------------------------------------------------------------------- // Blank Device #include "stdafx.h" #include "resource.h" #include "TrajectoryControl.h" #include "Mach4View.h" #include "Engine.h" #include "rs274ngc.h" #include "XMLProfile.h" #include "dmcwin.h" #include "MachDevImplementation.h" #include "GalilStructs.h" #include "GalilControl.h" #include "GalilConfig.h" // --------------------------------------->>>>>>> See this file for the Mach functions that can be // called and the pointers to the variable blocks. //#include "xxxxxxxx.h" // add includes for code you call here #include <mmsystem.h> #include <math.h> extern GalilStruct State; // ================================================================================================== // // Global variables for this code // // =================================================================================================== extern CMach4View *MachView; bool ShutDown = false; CString DefDir,Profile; GalilStruct Galil; GalilControl *GUnit; //Templates of control routines. // ================================================================================================== // // Declare helper routines for your code - more obvious here than in your header // //==================================================================================================== // Routines. CString myProfileInit (CString name, CXMLProfile *DevProf) // initial access to Mach profile when enumerating available plugins // Returns the second half on the "pluging id" for the list in Operator // MachDevice adds the file name at the start of the string { //this gets the default directory DefDir in which Mach3 is located. and the profile name ex. "Mach3Mill" DefDir = DevProf->GetProfileString("Preferences","DefDir","C:\\Mach3\\"); Profile = DevProf->GetProfileString("Preferences","Profile","Mach3Mill"); //initial load of program vars. m_UseRefPostion = DevProf->GetProfileInt("Preferences","RefPos",1) == 1; m_UseCalcSpeed = DevProf->GetProfileInt("Preferences","CalcSpeed",1) == 1; //set the default motor types.. State.motortype[0] = DevProf->GetProfileInt("Galil","MotorType1",3); State.motortype[1] = DevProf->GetProfileInt("Galil","MotorType2",3); State.motortype[2] = DevProf->GetProfileInt("Galil","MotorType3",3); State.motortype[3] = DevProf->GetProfileInt("Galil","MotorType4",3); State.motortype[4] = DevProf->GetProfileInt("Galil","MotorType5",3); State.motortype[5] = DevProf->GetProfileInt("Galil","MotorType6",3); State.nSpindle = DevProf->GetProfileInt("Galil","Spindle_Axis",-1); m_UseVectorDecel = DevProf->GetProfileInt("Galil","VectorDecel",300000); m_UseVectorTimeConst = atof(DevProf->GetProfileString("Galil","UseVectorDecel","1")); State.HomeData.UseIndex[0] = DevProf->GetProfileInt("Galil", "X_Index", 0); State.HomeData.UseIndex[1] = DevProf->GetProfileInt("Galil", "Y_Index", 0); State.HomeData.UseIndex[2] = DevProf->GetProfileInt("Galil", "Z_Index", 0); State.HomeData.UseIndex[3] = DevProf->GetProfileInt("Galil", "A_Index", 0); State.HomeData.UseIndex[4] = DevProf->GetProfileInt("Galil", "B_Index", 0); State.HomeData.UseIndex[5] = DevProf->GetProfileInt("Galil", "C_Index", 0); return " Galil PlugIn - A.Fenerty B.Barker Ver .1a"; } // myProfileInit //====================================================================================================== // // Here are the routines which are called by Mach3 via MachDevice. They are the "meat" of every plugin // //==================================================================================================== void myCleanUp() //used for destrcution of variables prior to exit.. Called as MAch3 shuts down. { ShutDown = true; // GUnit->CloseWindow(); delete GUnit; } void myReset() //used for destrcution of variables prior to exit.. Called as MAch3 shuts down. { if( GUnit != NULL )GUnit->ResetControl(); } void myInitControl () // called during Mach initialisation. You can influence subsequent init by actions here // **** Not used in typical device plugin { MachView->m_PrinterOn = false; // Tell Mach3 we are a movement plugin. ShutDown = false; //this will be set to true as we shut down. GUnit = new GalilControl(); //create a new window just for Galil's. return; } //myInitControl void myPostInitControl () // called when mach fully set up so all data can be used but initialization outcomes not affected { //In the case of a MotionControl plugin, this rouine is only called to tell us to // take over. We HAVE been selected and are now commanded to do whatever it takes // to OWN the IO and movement of this run. // If you wish for example, to zero all IO at this point, your free to do so.. GUnit->Create( NULL, "Galil", WS_DISABLED , CRect(0,0,0,0), MachView, 55555); GUnit->ShowWindow( SW_HIDE ); GUnit->Connect(); return; } //myPostInitControl //This is called by Mach3 when homing is commanded. Relevent axis are in the Engine.Axis status //word to indicate they should be homed.. void myHome( short axis) { GUnit->HomeAxis(axis); } //Called to add a homing axis.. "axis" is the one to add to current homing if applicable.. void myProbe(){ }; //OK, we have a probe command. So we need to activate the Halt mask, check to see its on, then do the move.. void myConfig (CXMLProfile *DevProf) { GalilConfig *fig = new GalilConfig(); fig->DoModal(); delete fig; CString NumOut; //restore globals here.. DevProf->WriteProfileInt("Preferences","RefPos",m_UseRefPostion); DevProf->WriteProfileInt("Preferences","CalcSpeed", m_UseCalcSpeed); DevProf->WriteProfileInt("Galil","MotorType1",State.motortype[0]); DevProf->WriteProfileInt("Galil","MotorType2",State.motortype[1]); DevProf->WriteProfileInt("Galil","MotorType3",State.motortype[2]); DevProf->WriteProfileInt("Galil","MotorType4",State.motortype[3]); DevProf->WriteProfileInt("Galil","MotorType5",State.motortype[4]); DevProf->WriteProfileInt("Galil","MotorType6",State.motortype[5]); DevProf->WriteProfileInt("Galil","Spindle_Axis",State.nSpindle); DevProf->WriteProfileInt("Galil","VectorDecel",m_UseVectorDecel); _gcvt( m_UseVectorTimeConst, 4 , NumOut.GetBuffer(20) ); DevProf->WriteProfileString("Galil","UseVectorDecel", NumOut); DevProf->WriteProfileInt("Galil", "X_Index", State.HomeData.UseIndex[0]); DevProf->WriteProfileInt("Galil", "Y_Index", State.HomeData.UseIndex[1]); DevProf->WriteProfileInt("Galil", "Z_Index", State.HomeData.UseIndex[2]); DevProf->WriteProfileInt("Galil", "A_Index", State.HomeData.UseIndex[3]); DevProf->WriteProfileInt("Galil", "B_Index", State.HomeData.UseIndex[4]); DevProf->WriteProfileInt("Galil", "C_Index", State.HomeData.UseIndex[5]); }; //this will open the Config Dialogs. void myUpdate () // 10Hz update loop //Updates the G100 10 times a second. { } // myUpdate void myNotify(int message) { if( message == -1 ) { if( State.Connected) GUnit->Stop( ); } } void myHighSpeedUpdate () { if( !ShutDown && State.Connected ) GUnit->Update(); }; // myHighSpeed Update void MyJogOn( short axis, short dir, double speed) { if( State.Connected) GUnit->JogOn( axis, dir, speed ); }; //Routines to start and stop Jogging.. void MyJogOff(short axis) { if( State.Connected) GUnit->JogOff( axis ); }; void myDwell( double time){ }; void myPurge( short flags){ };
34.594714
128
0.632752
mariusl
7d02df629091e704ddce2d51ac38ff9da4e948af
626
cpp
C++
games.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
264
2015-01-08T10:07:01.000Z
2022-03-26T04:11:51.000Z
games.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
17
2016-04-15T03:38:07.000Z
2020-10-30T00:33:57.000Z
games.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
127
2015-01-08T04:56:44.000Z
2022-02-25T18:40:37.000Z
// 2014-09-22 #include <iostream> #include <string> #include <sstream> using namespace std; int gcd(int x, int y) { if (x == 0) return y; else return gcd(y%x, x); } int main() { ios::sync_with_stdio(false); int t; cin >> t; while (t--) { string s; cin >> s; int p = s.find("."); if (p == string::npos) { cout << "1\n"; } else { string f = s.substr(p+1); while (f.size() < 4) f += "0"; istringstream iss(f); int frac; iss >> frac; cout << 10000/gcd(10000, frac) << "\n"; } } return 0; }
22.357143
51
0.453674
ohmyjons
7d044f13ccff48af4ba264949deb4cfb96d9acc5
677
cpp
C++
ch19-Class_&_Objects/19.3_box.cpp
theoryofcpp/CppTheory-Codes
d7ed8732890ab77444a93c7d3c04bcab4e36370b
[ "MIT" ]
null
null
null
ch19-Class_&_Objects/19.3_box.cpp
theoryofcpp/CppTheory-Codes
d7ed8732890ab77444a93c7d3c04bcab4e36370b
[ "MIT" ]
null
null
null
ch19-Class_&_Objects/19.3_box.cpp
theoryofcpp/CppTheory-Codes
d7ed8732890ab77444a93c7d3c04bcab4e36370b
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Box { public: double length; double breadth; double height; }; int main() { Box box1; Box box2; double volume = 0.0; // box1 specs box1.length = 3.0; box1.breadth = 5.0; box1.height = 7.0; // box2 specs box2.length = 6.0; box2.breadth = 8.0; box2.height = 10.0; // volume of box1 volume = box1.length * box1.breadth * box1.height; cout << "volume of box1: " << volume << endl; // volume of box2 volume = box2.length * box2.breadth * box2.height; cout << "volume of box2: " << volume << endl; return 0; }
19.342857
54
0.543575
theoryofcpp
7d05f4e5aca7e2d1e83dc37c1763321fcb5c5533
10,434
hh
C++
packages/Alea/mc_solvers/AdjointMcParallelFor.i.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
19
2015-06-04T09:02:41.000Z
2021-04-27T19:32:55.000Z
packages/Alea/mc_solvers/AdjointMcParallelFor.i.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
null
null
null
packages/Alea/mc_solvers/AdjointMcParallelFor.i.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
5
2016-10-05T20:48:28.000Z
2021-06-21T12:00:54.000Z
//----------------------------------*-C++-*----------------------------------// /*! * \file Alea/mc_solvers/AdjointMcParallelFor.i.hh * \author Steven Hamilton * \brief Perform single history of adjoint MC */ //---------------------------------------------------------------------------// #ifndef Alea_mc_solvers_AdjointMcParallelFor_i_hh #define Alea_mc_solvers_AdjointMcParallelFor_i_hh #include <iterator> #include <random> #include <cmath> #include "AdjointMcParallelFor.hh" #include "MC_Components.hh" #include "utils/String_Functions.hh" #include "harness/Warnings.hh" namespace alea { //---------------------------------------------------------------------------// /*! * \brief Constructor * * \param P Views into entries of probability matrix * \param W Views into entries of weight matrix * \param inds Views into nonzeros indices * \param offsets Starting indices for each matrix row * \param coeffs Polynomial coefficients * \param pl Problem parameters */ //---------------------------------------------------------------------------// AdjointMcParallelFor::AdjointMcParallelFor( const MC_Data_View &mc_data, const const_scalar_view coeffs, Teuchos::RCP<Teuchos::ParameterList> pl) : d_N(mc_data.offsets.size()-1) , d_mc_data(mc_data) , d_coeffs(coeffs) , d_start_cdf("start_cdf",d_N) , d_start_wt("start_wt",d_N) , d_rand_pool(pl->get("random_seed",31891)) , d_max_history_length(d_coeffs.size()-1) { d_num_histories = pl->get("num_histories",1000); // Determine type of tally std::string estimator = pl->get<std::string>("estimator", "expected_value"); VALIDATE(estimator == "collision" || estimator == "expected_value", "Only collision and expected_value estimators are available."); d_use_expected_value = (estimator == "expected_value"); // Power factor for initial probability distribution d_start_wt_factor = pl->get<SCALAR>("start_weight_factor",1.0); // Should we print anything to screen std::string verb = profugus::lower(pl->get("verbosity","low")); d_print = (verb == "high"); } //---------------------------------------------------------------------------// // Solve problem using Monte Carlo //---------------------------------------------------------------------------// void AdjointMcParallelFor::solve(const MV &x, MV &y) { range_policy policy(0,d_num_histories); // Build initial probability and weight distributions build_initial_distribution(x); // Need to get Kokkos view directly, this is silly Teuchos::ArrayRCP<SCALAR> y_data = y.getDataNonConst(0); const scalar_view y_device("result",d_N); const scalar_host_mirror y_mirror = Kokkos::create_mirror_view(y_device); d_y = y_device; // Execute functor Kokkos::parallel_for(policy,*this); // Copy data back to host Kokkos::deep_copy(y_mirror,y_device); DEVICE::fence(); // Apply scale factor SCALAR scale_factor = 1.0 / static_cast<SCALAR>(d_num_histories); for( LO i=0; i<d_N; ++i ) { y_data[i] = scale_factor*y_mirror(i); } // Add rhs for expected value if( d_use_expected_value ) { scalar_host_mirror coeffs_mirror = Kokkos::create_mirror_view(d_coeffs); Kokkos::deep_copy(coeffs_mirror,d_coeffs); y.update(coeffs_mirror(0),x,1.0); } } //---------------------------------------------------------------------------// /*! * \brief Perform adjoint Monte Carlo process */ //---------------------------------------------------------------------------// void AdjointMcParallelFor::operator()(const policy_member &member) const { LO index; LO state; LO row_length; SCALAR weight; generator_type rand_gen = d_rand_pool.get_state(); // Get starting position and weight bool valid = initHistory(d_start_cdf,state,index,row_length,weight,rand_gen); if( !valid ) { d_rand_pool.free_state(rand_gen); return; } if( std::abs(weight) == 0.0 ) { d_rand_pool.free_state(rand_gen); return; } SCALAR initial_weight = weight; if( d_print ) { printf("Thread %i starting history in state %i with initial weight %6.2e\n", member,state,initial_weight); } // Collision estimator starts tallying on zeroth order term // Expected value estimator gets this added explicitly at the end int stage = 0; if( d_use_expected_value ) stage++; // Get data and add to tally tallyContribution(state,d_coeffs(stage)*weight); // Transport particle until done for( ; stage<d_max_history_length; ++stage ) { // Get new state index valid = transition(d_mc_data.P,state,index,row_length,weight,rand_gen); if( !valid ) { d_rand_pool.free_state(rand_gen); return; } if( d_print ) { printf("Thread %i transitioning to state %i with new weight %6.2e\n", member,state,weight); } // Get data and add to tally tallyContribution(state,d_coeffs(stage)*weight); } // while d_rand_pool.free_state(rand_gen); } //---------------------------------------------------------------------------// // PRIVATE FUNCTIONS //---------------------------------------------------------------------------// //---------------------------------------------------------------------------// /*! * \brief Tally contribution into vector */ //---------------------------------------------------------------------------// void AdjointMcParallelFor::tallyContribution( const LO state, const SCALAR wt ) const { if( d_use_expected_value ) { int start = d_mc_data.offsets(state); int row_length = d_mc_data.offsets(state+1)-start; if( row_length > 0 ) { for( LO i=0; i<row_length; ++i ) { // P is cdf, we want value of pdf //y[inds[i]] += wt*H[i]; Kokkos::atomic_add(&d_y(d_mc_data.inds[start+i]), wt*d_mc_data.H[start+i]); } } } else { //y[state] += wt; Kokkos::atomic_add(&d_y(state),wt); } } //---------------------------------------------------------------------------// /*! * \brief Initialize a history */ //---------------------------------------------------------------------------// template <class view_type> bool AdjointMcParallelFor::initHistory(const view_type &cdf, LO &state, LO &cdf_start, LO &cdf_length, SCALAR &weight, generator_type &gen) const { // Generate random number SCALAR rand = Kokkos::rand<generator_type,SCALAR>::draw(gen); // Sample cdf to get new state // Use local lower_bound implementation, not std library version // This allows calling from device state = lower_bound(cdf,0,d_N,rand); if( state == d_N ) return false; // Get initial state weight = d_start_wt(state); // Get row info cdf_start = d_mc_data.offsets(state); cdf_length = d_mc_data.offsets(state+1)-cdf_start; return true; } //---------------------------------------------------------------------------// /*! * \brief Get new state by sampling from cdf */ //---------------------------------------------------------------------------// template <class view_type> bool AdjointMcParallelFor::transition(const view_type &cdf, LO &state, LO &cdf_start, LO &cdf_length, SCALAR &weight, generator_type &gen) const { // Generate random number SCALAR rand = Kokkos::rand<generator_type,SCALAR>::draw(gen); // Sample cdf to get new state // Use local lower_bound implementation, not std library version // This allows calling from device LO elem = lower_bound(cdf,cdf_start,cdf_length,rand); if( elem == cdf_start+cdf_length ) return false; // Modify weight and update state state = d_mc_data.inds(elem); weight *= d_mc_data.W(elem); // Update current row info cdf_start = d_mc_data.offsets(state); cdf_length = d_mc_data.offsets(state+1)-cdf_start; return true; } //---------------------------------------------------------------------------// // Build initial cdf and weights //---------------------------------------------------------------------------// void AdjointMcParallelFor::build_initial_distribution(const MV &x) { // Build data on host, then explicitly copy to device // In future, convert this to a new Kernel to allow building // distributions directly on device if x is allocated there scalar_host_mirror start_cdf_host = Kokkos::create_mirror_view(d_start_cdf); scalar_host_mirror start_wt_host = Kokkos::create_mirror_view(d_start_wt); Teuchos::ArrayRCP<const SCALAR> x_data = x.getData(0); for( LO i=0; i<d_N; ++i ) { start_cdf_host(i) = SCALAR_TRAITS::pow(SCALAR_TRAITS::magnitude(x_data[i]), d_start_wt_factor); } SCALAR pdf_sum = std::accumulate(&start_cdf_host(0),&start_cdf_host(d_N-1)+1,0.0); ENSURE( pdf_sum > 0.0 ); std::transform(&start_cdf_host(0),&start_cdf_host(d_N-1)+1,&start_cdf_host(0), [pdf_sum](SCALAR x){return x/pdf_sum;}); std::transform(x_data.begin(),x_data.end(),&start_cdf_host(0), &start_wt_host(0), [](SCALAR x, SCALAR y){return y==0.0 ? 0.0 : x/y;}); std::partial_sum(&start_cdf_host(0),&start_cdf_host(d_N-1)+1,&start_cdf_host(0)); Kokkos::deep_copy(d_start_cdf,start_cdf_host); Kokkos::deep_copy(d_start_wt, start_wt_host); } } // namespace alea #endif // Alea_mc_solvers_AdjointMcParallelFor_i_hh
32.811321
86
0.523002
GCZhang
7d103e521ff8c7706bf0333674aa732e9e74c175
1,597
hpp
C++
misc/hardware/headers/FunnyOS/Hardware/GFX/VGA.hpp
LetsPlaySomeUbuntu/XitongOS-test-1
792d0c76f9aa4bb2b579d47c2c728394a3acf9f9
[ "MIT" ]
null
null
null
misc/hardware/headers/FunnyOS/Hardware/GFX/VGA.hpp
LetsPlaySomeUbuntu/XitongOS-test-1
792d0c76f9aa4bb2b579d47c2c728394a3acf9f9
[ "MIT" ]
null
null
null
misc/hardware/headers/FunnyOS/Hardware/GFX/VGA.hpp
LetsPlaySomeUbuntu/XitongOS-test-1
792d0c76f9aa4bb2b579d47c2c728394a3acf9f9
[ "MIT" ]
null
null
null
#ifndef FUNNYOS_BOOTLOADER_COMMONS_HEADERS_FUNNYOS_BOOTLOADERCOMMONS_GFX_VGAINTERFACE_HPP #define FUNNYOS_BOOTLOADER_COMMONS_HEADERS_FUNNYOS_BOOTLOADERCOMMONS_GFX_VGAINTERFACE_HPP #include <FunnyOS/Misc/TerminalManager/ITerminalInterface.hpp> namespace FunnyOS::HW { /** * Implementation of ITerminalInterface that operates directly on the VGA hardware. */ class VGAInterface : public Misc::TerminalManager::ITerminalInterface { public: using CursorPosition = Misc::TerminalManager::CursorPosition; using CharacterData = Misc::TerminalManager::CharacterData; public: [[nodiscard]] Stdlib::Memory::SizedBuffer<uint8_t> SaveScreenData() const noexcept override; void RestoreScreenData(Stdlib::Memory::SizedBuffer<uint8_t>& buffer) noexcept override; [[nodiscard]] uint16_t GetScreenWidth() const noexcept override; [[nodiscard]] uint16_t GetScreenHeight() const noexcept override; [[nodiscard]] CursorPosition GetCursorPosition() const noexcept override; bool SetCursorPosition(const CursorPosition& position) noexcept override; void WriteCharacter(const CursorPosition& position, const CharacterData& data) noexcept override; [[nodiscard]] CharacterData ReadCharacter(const CursorPosition& position) noexcept override; void Move(const CursorPosition& from, const CursorPosition& to) noexcept override; void Submit() override; }; } // namespace FunnyOS::HW #endif // FUNNYOS_BOOTLOADER_COMMONS_HEADERS_FUNNYOS_BOOTLOADERCOMMONS_GFX_VGAINTERFACE_HPP
38.95122
105
0.76268
LetsPlaySomeUbuntu
7d148641d320c570b1e5a53221756b7cc059922c
79
hxx
C++
ovalsidingControl_nucleo_io/targets/freertos.armv7m.st-stm32f303re-nucleo-dev-board/NODEID.hxx
RobertPHeller/RPi-RRCircuits
19aff23e20eebdbd028c0407d68eef77cc6ee0ec
[ "CC-BY-4.0" ]
10
2018-09-04T02:12:39.000Z
2022-03-17T20:29:32.000Z
ovalsidingControl_nucleo_io/targets/freertos.armv7m.st-stm32f303re-nucleo-dev-board/NODEID.hxx
RobertPHeller/RPi-RRCircuits
19aff23e20eebdbd028c0407d68eef77cc6ee0ec
[ "CC-BY-4.0" ]
null
null
null
ovalsidingControl_nucleo_io/targets/freertos.armv7m.st-stm32f303re-nucleo-dev-board/NODEID.hxx
RobertPHeller/RPi-RRCircuits
19aff23e20eebdbd028c0407d68eef77cc6ee0ec
[ "CC-BY-4.0" ]
1
2018-12-26T00:32:27.000Z
2018-12-26T00:32:27.000Z
extern const openlcb::NodeID NODE_ID = 0x050101012291ULL; // 05 01 01 01 22 91
39.5
78
0.759494
RobertPHeller
7d17cfa805b2f91dd6c988034df6db6db54ecad1
3,043
cpp
C++
serveur/Youcef/fuelgauge.cpp
de-souza/car-dashboard
ba3a6658887710a91d2d7095c9f2bb8e5f35b314
[ "Apache-2.0" ]
1
2020-02-23T04:34:05.000Z
2020-02-23T04:34:05.000Z
serveur/Youcef/fuelgauge.cpp
de-souza/car-dashboard
ba3a6658887710a91d2d7095c9f2bb8e5f35b314
[ "Apache-2.0" ]
1
2019-11-12T14:18:19.000Z
2019-11-12T14:27:52.000Z
serveur/Youcef/fuelgauge.cpp
de-souza/car-dashboard
ba3a6658887710a91d2d7095c9f2bb8e5f35b314
[ "Apache-2.0" ]
2
2019-11-12T14:15:09.000Z
2021-04-12T05:10:35.000Z
#include "fuelgauge.h" #include <QtMath> #include <QGraphicsTextItem> #include <QStringList> FuelGauge::FuelGauge(objet_virtuel *) { value=0; valueMax =100; } QRectF FuelGauge::boundingRect() const { return QRectF(-600, -400, 1200, 800); } void FuelGauge::paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget *) { painter->setRenderHint(QPainter::Antialiasing); { QRect RectSpeed (100,-300, 405, 405); painter->setPen(QPen(QBrush("red"), 4, Qt::SolidLine,Qt::RoundCap,Qt::BevelJoin)); QPolygonF polygon; QPainterPath rectPath; rectPath.moveTo(102,-64); rectPath.lineTo(20,-64); rectPath.lineTo(20, 85); rectPath.lineTo(212,85); rectPath.arcTo(RectSpeed,244, -50); rectPath.closeSubpath(); rectPath.addPolygon(polygon); QRadialGradient gradient(119, -4.5, 200); gradient.setColorAt(0, QColor(0,0,0,0)); gradient.setColorAt(0.5, QColor("dark blue")); gradient.setColorAt(1, QColor("dark")); QBrush brush(gradient); painter->setBrush(brush); painter->drawPath(rectPath); } { QPen pen ; pen.setWidth(2); pen.setColor("#DF3A01"); painter->setPen(pen); QBrush NeedleColor("white",Qt::SolidPattern); painter->setBrush(NeedleColor); for (int i=0;i<=9;i++) { if((i+1)>getValue()/10) { QBrush NeedleColor("#DF3A01",Qt::SolidPattern); painter->setBrush(NeedleColor); } float x1,y1;int r=15; x1=260+195*(cos((170-(i*4.8))*pi/180)); y1=-90+195*(sin((170-(i*4.8))*pi/180)); painter->drawRoundedRect(x1,y1,2*r,r/2,2,2); } } { QRect RectSpeed (53,-350, 505, 505); double startAngle= 222*16; double spanAngle= -32.5*16; double spanAngle1 = -7.5*16; painter->setPen(QPen(QBrush("dark"), 5, Qt::SolidLine,Qt::FlatCap,Qt::BevelJoin)); painter->drawArc(RectSpeed,startAngle,spanAngle); painter->drawLine(QPoint(40,-53),QPoint(55,-53)); painter->drawLine(QPoint(60,16),QPoint(80,16)); painter->drawLine(QPoint(53,-17),QPoint(65,-17)); painter->setPen(QPen(QBrush("red"), 5, Qt::SolidLine,Qt::FlatCap,Qt::BevelJoin)); painter->drawLine(QPoint(85,45),QPoint(99,45)); painter->drawArc(RectSpeed,startAngle,spanAngle1); painter->drawLine(QPoint(95,70),QPoint(115,70)); painter->setFont(QFont("ariel", 15, QFont::Bold, false)); painter->setPen(QPen(QBrush("dark") ,10, Qt::SolidLine,Qt::FlatCap)); painter->drawText(25,-45, "F"); painter->setPen(QPen(QBrush("red") ,10, Qt::SolidLine,Qt::FlatCap)); painter->drawText(75, 75, "E"); } { QPixmap img1(":/new/logos/Icones/fuelWhiteIcone.gif"); QPixmap img2=img1.scaled(30,30); painter->setOpacity(1); painter->drawPixmap(15,-10,50,50,img2); } }
28.439252
91
0.586592
de-souza
7d1a97b08c6e29abb0d14916751d499dfd8d433d
640
cpp
C++
Chapter 2/2.1_myfirst.cpp
Reavolt/Cpp-Primer-Plus
491876ca0808d55cb688d575ec4688b087387810
[ "Unlicense" ]
3
2021-10-04T11:59:10.000Z
2022-01-05T22:26:12.000Z
Chapter 2/2.1_myfirst.cpp
Hitoku/Cpp-Primer-Plus
491876ca0808d55cb688d575ec4688b087387810
[ "Unlicense" ]
null
null
null
Chapter 2/2.1_myfirst.cpp
Hitoku/Cpp-Primer-Plus
491876ca0808d55cb688d575ec4688b087387810
[ "Unlicense" ]
3
2018-11-22T17:34:42.000Z
2020-09-19T09:39:19.000Z
//myfirst.срр -- выводит сообщение на экран //#include "stdafx.h" --- Visual Studio --- precompiled headers #include <iostream> using namespace std; //------------------------------------------------------------------------------------------------- int main() { cout << "Come up and C++ me some time."; cout << endl; cout << "You won't regret it!" << endl; std::cin.get(); std::cin.get(); return 0; } //-------------------------------------------------------------------------------------------------
33.684211
99
0.30625
Reavolt
7d1d43912662d8b3cb8c77c6f4fa52ffcf555527
3,451
cpp
C++
Library/Sources/Stroika/Foundation/IO/FileSystem/ThroughTmpFileWriter.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Library/Sources/Stroika/Foundation/IO/FileSystem/ThroughTmpFileWriter.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Library/Sources/Stroika/Foundation/IO/FileSystem/ThroughTmpFileWriter.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../../StroikaPreComp.h" #include <cstdio> #if qPlatform_Windows #include <windows.h> #elif qPlatform_POSIX #include <unistd.h> #endif #include "../../Characters/Format.h" #include "../../Characters/ToString.h" #include "../../Containers/Common.h" #include "../../Execution/Activity.h" #include "../../Execution/Exceptions.h" #include "../../Execution/Throw.h" #if qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #endif #include "../../Debug/Trace.h" #include "../../IO/FileSystem/PathName.h" #include "Exception.h" #include "ThroughTmpFileWriter.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfZeroGetLastError; #endif /* ******************************************************************************** ************************ FileSystem::ThroughTmpFileWriter ********************** ******************************************************************************** */ ThroughTmpFileWriter::ThroughTmpFileWriter (const filesystem::path& realFileName, const String& tmpSuffix) : fRealFilePath_{realFileName} , fTmpFilePath_{realFileName / ToPath (tmpSuffix)} { Require (not realFileName.empty ()); Require (not tmpSuffix.empty ()); } ThroughTmpFileWriter::~ThroughTmpFileWriter () { if (not fTmpFilePath_.empty ()) { DbgTrace (L"ThroughTmpFileWriter::DTOR - tmpfile not successfully commited to %s", Characters::ToString (fRealFilePath_).c_str ()); // ignore errors on unlink, cuz nothing to be done in DTOR anyhow...(@todo perhaps should at least tracelog) #if qPlatform_POSIX (void)::unlink (fTmpFilePath_.c_str ()); #elif qPlatform_Windows (void)::DeleteFileW (fTmpFilePath_.c_str ()); #else AssertNotImplemented (); #endif } } void ThroughTmpFileWriter::Commit () { Require (not fTmpFilePath_.empty ()); // cannot Commit more than once // Also - NOTE - you MUST close fTmpFilePath (any file descriptors that have opened it) BEFORE the Commit! auto activity = LazyEvalActivity ([&] () -> String { return Characters::Format (L"committing temporary file %s to %s", Characters::ToString (fTmpFilePath_).c_str (), Characters::ToString (fRealFilePath_).c_str ()); }); DeclareActivity currentActivity{&activity}; #if qPlatform_POSIX FileSystem::Exception::ThrowPOSIXErrNoIfNegative (::rename (fTmpFilePath_.c_str (), fRealFilePath_.c_str ()), fTmpFilePath_, fRealFilePath_); #elif qPlatform_Windows try { ThrowIfZeroGetLastError (::MoveFileExW (fTmpFilePath_.c_str (), fRealFilePath_.c_str (), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)); } catch (const system_error& we) { // On Win9x - this fails cuz OS not impl... if (we.code () == error_code{ERROR_CALL_NOT_IMPLEMENTED, system_category ()}) { ::DeleteFileW (fRealFilePath_.c_str ()); ThrowIfZeroGetLastError (::MoveFileW (fTmpFilePath_.c_str (), fRealFilePath_.c_str ())); } else { ReThrow (); } } #else AssertNotImplemented (); #endif fTmpFilePath_.clear (); }
35.57732
233
0.661547
SophistSolutions
7d1f960459ef009a467713317fd909660060ad23
6,323
hpp
C++
src/database/src/Index.hpp
maciejjablonsky/indexed-sequential-file
50898dbe0c1864dd0a86aed6cac4ed56bf4abd33
[ "MIT" ]
null
null
null
src/database/src/Index.hpp
maciejjablonsky/indexed-sequential-file
50898dbe0c1864dd0a86aed6cac4ed56bf4abd33
[ "MIT" ]
null
null
null
src/database/src/Index.hpp
maciejjablonsky/indexed-sequential-file
50898dbe0c1864dd0a86aed6cac4ed56bf4abd33
[ "MIT" ]
null
null
null
#pragma once #include "Link.hpp" #include "Memory.hpp" #include "PageDispositor.hpp" #include <algorithm> #include <concepts/comparable.hpp> #include <map> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> namespace index { struct IndexHeader { size_t links; size_t primary_entries; size_t overflow_entries; }; static_assert(std::is_trivial_v<IndexHeader>); template <typename T> inline const std::byte *to_byte_ptr(const T *o) { return reinterpret_cast<const std::byte *>(o); } template <typename T> inline std::byte *to_byte_ptr(T *o) { return reinterpret_cast<std::byte *>(o); } template <typename Key> concept index_concept = requires { comparable<Key>; }; template <typename Key> requires index_concept<Key> class Index { private: static constexpr size_t index_entry_size = sizeof(Key) + sizeof(link::PrimaryPageLink); page::PageDispositor<page::PageMemory<>> page_dispositor_; std::map<Key, link::PrimaryPageLink> page_links_; public: [[nodiscard]] std::tuple<size_t, size_t> Setup(const std::string &file_path) { if (!page_dispositor_.AttachFile(file_path)) { throw std::runtime_error( "Failed to setup page_dispositor for database index."); } if (page_dispositor_.PagesInFile() > 0) { return Deserialize(file_path); } else { key::Key dummy_key = {-1}; page_links_[dummy_key] = {0}; return {0, 0}; } } [[nodiscard]] link::PrimaryPageLink LookUp(Key key) const { auto it = std::adjacent_find(page_links_.begin(), page_links_.end(), [&](const auto &lhs, const auto &rhs) { return lhs.first <= key && key < rhs.first; }); if (it == page_links_.cend()) { --it; } return it->second; } inline void Add(Key key, link::PrimaryPageLink link) { page_links_.insert_or_assign(key, link); } inline size_t Size() const { return page_links_.size(); } [[nodiscard]] std::tuple<size_t, size_t> Deserialize(const std::string &file_path) { auto current_page = *page_dispositor_.Request(0); IndexHeader header; std::copy_n(current_page.begin(), sizeof(header), to_byte_ptr(&header)); auto entries_read = std::min((current_page.size - sizeof(header)) / index_entry_size, header.links); auto current_byte = current_page.begin() + sizeof(header); auto read_n_entries = [&](size_t n) { Key key; link::PrimaryPageLink link; for (auto i = 0; i < n; ++i) { std::copy_n(current_byte, sizeof(key), to_byte_ptr(&key)); std::copy_n(current_byte + sizeof(Key), sizeof(link), to_byte_ptr(&link)); current_byte += index_entry_size; page_links_[key] = link; } }; read_n_entries(entries_read); for (auto page_no = 1; entries_read < header.links; ++page_no) { current_page = *page_dispositor_.Request(page_no); current_byte = current_page.begin(); auto entries_to_read = std::min(current_page.size / index_entry_size, header.links - entries_read); read_n_entries(entries_to_read); entries_read += entries_to_read; } return {header.primary_entries, header.overflow_entries}; } void Serialize(size_t primary_entries, size_t overflow_entries) { page_dispositor_.ClearFile(); IndexHeader header = {.links = page_links_.size(), .primary_entries = primary_entries, .overflow_entries = overflow_entries}; auto current_page = *page_dispositor_.Request(0); std::copy_n(to_byte_ptr(&header), sizeof(header), current_page.begin()); // copy header auto entries_saved = (current_page.size - sizeof(header)) / index_entry_size; auto current_byte = current_page.begin() + sizeof(header); auto page_link_it = page_links_.begin(); // prepare first page std::for_each_n( page_links_.begin(), std::min(page_links_.size(), entries_saved), [&](const auto &index_entry) { current_byte = std::copy_n(to_byte_ptr(&index_entry.first), sizeof(index_entry.first), current_byte); current_byte = std::copy_n(to_byte_ptr(&index_entry.second), sizeof(index_entry.second), current_byte); ++page_link_it; }); page_dispositor_.Write(current_page); for (auto page_no = 1; entries_saved < page_links_.size(); ++page_no) { auto current_page = *page_dispositor_.Request(page_no); current_byte = current_page.begin(); auto entries_to_save = std::min(current_page.size / index_entry_size, page_links_.size() - entries_saved); std::for_each_n( page_link_it, entries_to_save, [&](const auto &index_entry) { current_byte = std::copy_n(to_byte_ptr(&index_entry.first), sizeof(index_entry.first), current_byte); current_byte = std::copy_n(to_byte_ptr(&index_entry.second), sizeof(index_entry.second), current_byte); ++page_link_it; }); page_dispositor_.Write(current_page); entries_saved += entries_to_save; } } void Show() { fmt::print("[{:^91}]\n", "INDEX"); for (const auto &[key, link] : page_links_) { fmt::print("[key: {:>4}, page: {:>4}]\n", static_cast<std::string>(key), link); } fmt::print("\n"); } void Clear() { page_links_.clear(); page_dispositor_.ClearFile(); } }; } // namespace index
38.554878
84
0.564922
maciejjablonsky
7d22c09eaef73e1615a9168ad52bda1a0d99fbac
3,403
cpp
C++
src/StatsWindow.cpp
whitearsenic/Kdd99-Feature-Extractor-Prebuilt
a6128bdbc81a1fbfd9bdf76586e70c562b59fa3a
[ "MIT" ]
99
2017-03-07T08:56:15.000Z
2022-03-29T05:29:43.000Z
src/StatsWindow.cpp
cainsmile/kdd99_feature_extractor
f3d40e3f8df78a3ed7ccdbfabb1b763e9e4d87c0
[ "MIT" ]
19
2017-04-08T08:22:44.000Z
2021-11-09T03:05:28.000Z
src/StatsWindow.cpp
cainsmile/kdd99_feature_extractor
f3d40e3f8df78a3ed7ccdbfabb1b763e9e4d87c0
[ "MIT" ]
46
2016-07-07T15:49:49.000Z
2022-03-15T21:57:28.000Z
#include "StatsWindow.h" #include "StatsPerHost.h" #include "StatsPerService.h" #include "StatsPerServiceWithSrcPort.h" #include <assert.h> namespace FeatureExtractor { template<class TStatsPerHost, class TStatsPerService> StatsWindow<TStatsPerHost, TStatsPerService>::StatsWindow(FeatureUpdater *feature_updater) : feature_updater(feature_updater) { // Initialize stats per service for (int i = 0; i < NUMBER_OF_SERVICES; i++) { per_service[i] = TStatsPerService(feature_updater); } } template<class TStatsPerHost, class TStatsPerService> StatsWindow<TStatsPerHost, TStatsPerService>::~StatsWindow() { // Deallocate leftover conversations in the queue while (!finished_convs.empty()) { Conversation *conv = finished_convs.front(); finished_convs.pop(); // Object commits suicide if no more references to it conv->deregister_reference(); } // per_host map<> should automatically be deallocated } template<class TStatsPerHost, class TStatsPerService> TStatsPerHost *StatsWindow<TStatsPerHost, TStatsPerService>::find_or_insert_host_stats(uint32_t dst_ip) { TStatsPerHost *stats = nullptr; // Find or insert with single lookup: // http://stackoverflow.com/a/101980/3503528 typename map<uint32_t, TStatsPerHost>::iterator it = per_host.lower_bound(dst_ip); if (it != per_host.end() && !(per_host.key_comp()(dst_ip, it->first))) { // Found stats = &it->second; } else { // The key does not exist in the map // Add it to the map + update iterator to point to new item it = per_host.insert(it, typename map<uint32_t, TStatsPerHost>::value_type(dst_ip, TStatsPerHost(feature_updater))); stats = &it->second; } return stats; } template<class TStatsPerHost, class TStatsPerService> void StatsWindow<TStatsPerHost, TStatsPerService>::report_conversation_removal(const Conversation *conv) { uint32_t dst_ip = conv->get_five_tuple_ptr()->get_dst_ip(); service_t service = conv->get_service(); // Forward to per host stats typename map<uint32_t, TStatsPerHost>::iterator it = per_host.find(dst_ip); assert(it != per_host.end() && "Reporting removal of convesation not in queue: no such dst. IP record"); TStatsPerHost *this_host = &it->second; this_host->report_conversation_removal(conv); // Remove per-host stats for this host if it's "empty" for this window if (this_host->is_empty()) per_host.erase(it); // Forward to per service stats per_service[service].report_conversation_removal(conv); } template<class TStatsPerHost, class TStatsPerService> void StatsWindow<TStatsPerHost, TStatsPerService>::add_conversation(ConversationFeatures *cf) { Conversation *conv = cf->get_conversation(); uint32_t dst_ip = conv->get_five_tuple_ptr()->get_dst_ip(); service_t service = conv->get_service(); // Per host statitics TStatsPerHost *this_host = find_or_insert_host_stats(dst_ip); this_host->report_new_conversation(cf); // Per service statitics per_service[service].report_new_conversation(cf); // Add new connection to window queue (+ register reference) conv->register_reference(); finished_convs.push(conv); perform_window_maintenance(conv); } // Explicit template specialisation http://stackoverflow.com/q/115703/3503528 template class StatsWindow<StatsPerHost, StatsPerService>; template class StatsWindow<StatsPerHost, StatsPerServiceWithSrcPort>; }
33.362745
119
0.752571
whitearsenic
7d250d55e815e84233ca30041068460805ebf9aa
2,633
cpp
C++
MaterialLib/MPL/Properties/LinearProperty.cpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
1
2020-03-24T13:33:52.000Z
2020-03-24T13:33:52.000Z
MaterialLib/MPL/Properties/LinearProperty.cpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
null
null
null
MaterialLib/MPL/Properties/LinearProperty.cpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
1
2020-07-15T05:55:55.000Z
2020-07-15T05:55:55.000Z
/** * \file * * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license */ #include <numeric> #include "MaterialLib/MPL/Properties/LinearProperty.h" namespace MaterialPropertyLib { LinearProperty::LinearProperty(PropertyDataType const& property_reference_value, std::vector<IndependentVariable> const& vs) : _independent_variables(vs) { _value = property_reference_value; } PropertyDataType LinearProperty::value( VariableArray const& variable_array, ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/, double const /*dt*/) const { auto calculate_linearized_ratio = [&variable_array]( double const initial_linearized_ratio, auto const& iv) { return initial_linearized_ratio + std::get<double>(iv.slope) * (std::get<double>( variable_array[static_cast<int>(iv.type)]) - std::get<double>(iv.reference_condition)); }; double const linearized_ratio_to_reference_value = std::accumulate(_independent_variables.begin(), _independent_variables.end(), 1.0, calculate_linearized_ratio); return std::get<double>(_value) * linearized_ratio_to_reference_value; } PropertyDataType LinearProperty::dValue( VariableArray const& /*variable_array*/, Variable const primary_variable, ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/, double const /*dt*/) const { auto const independent_variable = std::find_if(_independent_variables.begin(), _independent_variables.end(), [&primary_variable](auto const& iv) -> bool { return iv.type == primary_variable; }); return independent_variable != _independent_variables.end() ? std::get<double>(_value) * std::get<double>(independent_variable->slope) : decltype(_value){}; } PropertyDataType LinearProperty::d2Value( VariableArray const& /*variable_array*/, Variable const /*pv1*/, Variable const /*pv2*/, ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/, double const /*dt*/) const { return decltype(_value){}; } } // namespace MaterialPropertyLib
35.106667
80
0.612989
OlafKolditz
7d2525ef5e6735a00d7300e326023226fec7c289
1,795
cpp
C++
oli/viii2013puncte/main.cpp
rockoanna/nirvana
81fadbe66b0a24244feec312c6f7fe5c8effccaa
[ "MIT" ]
null
null
null
oli/viii2013puncte/main.cpp
rockoanna/nirvana
81fadbe66b0a24244feec312c6f7fe5c8effccaa
[ "MIT" ]
12
2019-09-04T10:38:24.000Z
2019-12-08T18:09:41.000Z
oli/viii2013puncte/main.cpp
rockoanna/nirvana
81fadbe66b0a24244feec312c6f7fe5c8effccaa
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef int64_t i64; typedef int32_t i32; typedef uint64_t u64; typedef uint32_t u32; typedef string st; typedef stringstream ss; typedef double db; typedef vector<i64> vl; typedef vector<i32> vi; typedef vector<char> vc; typedef vector<db> vd; typedef vector<st> vs; typedef map<st,i32> st2i; typedef map<st,i64> st2l; typedef map<st,db> st2d; typedef map<i64,i64> l2l; typedef map<i64,i32> l2i; typedef map<i32,i32> i2i; typedef map<i32,i64> i2l; i64 solve2(set<tuple<i64, i64>>& s) { i64 res = 0; for(auto it0 = s.begin(); it0 != s.end(); it0++) { // cout << "it0 :" << get<0>(*it0) << " " << get<1>(*it0) << endl; set<double> slopes; for(auto it = s.begin(); it != s.end(); it++) { if(it == it0) { continue; } double slope =(get<1>(*it) - get<1>(*it0)) / double(get<0>(*it) - get<0>(*it0)); auto f = slopes.find(slope); if(f == slopes.end()) { res += 1; // cout << setprecision(10); /// cout << get<0>(*it) << " " << get<1>(*it) << " slooooope :" << slope << endl; } slopes.insert(slope); } } return res / 2; } int main() { u64 n; cin >> n; map<i64, i64> x; map<i64, i64> y; i64 mx = 0; set<tuple<i64, i64>> s; for(int i = 0; i < n; i++) { i64 a; cin >> a; i64 b; cin >> b; x[a] += 1; y[b] += 1; mx = max(x[a], mx); mx = max(y[b], mx); if(a == b || a + b == 0) { s.insert({a, b}); } } cout << mx << endl; cout << solve2(s) << endl; return 0; }
18.316327
96
0.458496
rockoanna
7d2574a973d349b7ada6b51a8df73b9c76cf880d
3,317
cpp
C++
Source/Voxel/Private/Octree.cpp
nwiswakarma/Voxel
cd53ef8c85c84c465ad771efefeeb539258c6b02
[ "MIT" ]
5
2020-05-28T00:29:22.000Z
2021-04-15T11:14:39.000Z
Source/Voxel/Private/Octree.cpp
nwiswakarma/Voxel
cd53ef8c85c84c465ad771efefeeb539258c6b02
[ "MIT" ]
null
null
null
Source/Voxel/Private/Octree.cpp
nwiswakarma/Voxel
cd53ef8c85c84c465ad771efefeeb539258c6b02
[ "MIT" ]
1
2020-05-28T00:32:25.000Z
2020-05-28T00:32:25.000Z
// Copyright 2017 Phyronnaz #include "Octree.h" FOctree::FOctree(FIntVector Position, uint8 Depth, uint64 Id /*= -1*/) : Position(Position), Depth(Depth), Id(Id), bHasChilds(false) { // Max for Id check(Depth <= 19); } bool FOctree::operator==(const FOctree& Other) const { check((Id == Other.Id) == (Position == Other.Position && Depth == Other.Depth)); return Id == Other.Id; } bool FOctree::operator<(const FOctree& Other) const { return Id < Other.Id; } bool FOctree::operator>(const FOctree& Other) const { return Id > Other.Id; } int FOctree::Size() const { return 16 << Depth; } FIntVector FOctree::GetMinimalCornerPosition() const { return Position - FIntVector(Size() / 2, Size() / 2, Size() / 2); } FIntVector FOctree::GetMaximalCornerPosition() const { return Position + FIntVector(Size() / 2, Size() / 2, Size() / 2); } bool FOctree::IsLeaf() const { return !bHasChilds; } bool FOctree::IsInOctree(int X, int Y, int Z) const { return Position.X - Size() / 2 <= X && X < Position.X + Size() / 2 && Position.Y - Size() / 2 <= Y && Y < Position.Y + Size() / 2 && Position.Z - Size() / 2 <= Z && Z < Position.Z + Size() / 2; } void FOctree::LocalToGlobal(int X, int Y, int Z, int& OutX, int& OutY, int& OutZ) const { OutX = X + (Position.X - Size() / 2); OutY = Y + (Position.Y - Size() / 2); OutZ = Z + (Position.Z - Size() / 2); } void FOctree::GlobalToLocal(int X, int Y, int Z, int& OutX, int& OutY, int& OutZ) const { OutX = X - (Position.X - Size() / 2); OutY = Y - (Position.Y - Size() / 2); OutZ = Z - (Position.Z - Size() / 2); } uint64 FOctree::GetTopIdFromDepth(int8 Depth) { return IntPow9(Depth); } void FOctree::GetIDsAt(uint64 ID, uint8 LOD, uint64 IDs[8]) { const uint64 Pow = IntPow9(LOD); IDs[0] = ID+1*Pow; IDs[1] = ID+2*Pow; IDs[2] = ID+3*Pow; IDs[3] = ID+4*Pow; IDs[4] = ID+5*Pow; IDs[5] = ID+6*Pow; IDs[6] = ID+7*Pow; IDs[7] = ID+8*Pow; } void FOctree::GetIDsAt(uint64 ID, uint8 LOD, TArray<uint64>& IDs) { const uint64 Pow = IntPow9(LOD); IDs.Emplace(ID+1*Pow); IDs.Emplace(ID+2*Pow); IDs.Emplace(ID+3*Pow); IDs.Emplace(ID+4*Pow); IDs.Emplace(ID+5*Pow); IDs.Emplace(ID+6*Pow); IDs.Emplace(ID+7*Pow); IDs.Emplace(ID+8*Pow); } void FOctree::GetIDsAt(uint64 ID, uint8 Depth, uint8 EndDepth, TArray<uint64>& OutIDs) { if (Depth > EndDepth) { // Next depth const uint8 LOD = Depth-1; if (LOD == EndDepth) { // At the specified depth, write result ids GetIDsAt(ID, LOD, OutIDs); } else { // Get child ids uint64 IDs[8]; FOctree::GetIDsAt(ID, LOD, IDs); // Recursively gather ids GetIDsAt(IDs[0], LOD, EndDepth, OutIDs); GetIDsAt(IDs[1], LOD, EndDepth, OutIDs); GetIDsAt(IDs[2], LOD, EndDepth, OutIDs); GetIDsAt(IDs[3], LOD, EndDepth, OutIDs); GetIDsAt(IDs[4], LOD, EndDepth, OutIDs); GetIDsAt(IDs[5], LOD, EndDepth, OutIDs); GetIDsAt(IDs[6], LOD, EndDepth, OutIDs); GetIDsAt(IDs[7], LOD, EndDepth, OutIDs); } } // Specified start depth equals end depth, simply adds starting id as result else { OutIDs.Emplace(ID); } }
24.93985
132
0.586675
nwiswakarma
7d27607a13e8632c8903d331bd2035453881ea2d
1,876
cpp
C++
plugins/cmd-command/cmd_command.cpp
pozitiffcat/build-disp
73727e17e2eba8f488a749a6daa412362a426613
[ "MIT" ]
null
null
null
plugins/cmd-command/cmd_command.cpp
pozitiffcat/build-disp
73727e17e2eba8f488a749a6daa412362a426613
[ "MIT" ]
null
null
null
plugins/cmd-command/cmd_command.cpp
pozitiffcat/build-disp
73727e17e2eba8f488a749a6daa412362a426613
[ "MIT" ]
null
null
null
#include <boost/process.hpp> #include "plugins_manager_api.hpp" class cmd_command : public command { public: cmd_command(boost::asio::io_service &service, const std::string &command) : _service(service), _command(command) { } void execute(const boost::filesystem::path &workspace_path, params_map &context_params, command_finish_handler finish_handler) { namespace bp = boost::process; _log_buf.consume(_log_buf.size()); bp::environment env = boost::this_process::environment(); const auto &params = context_params.get_map(); for (const auto &p : params) env[p.first] = p.second; // todo: if windows? _child = boost::process::child("/bin/bash -c \"" + _command + "\"", _service, (bp::std_out & bp::std_err) > _log_buf, bp::env(env), bp::on_exit([finish_handler](auto res, auto err){ finish_handler(res == EXIT_SUCCESS ? SOURCE_FINISH_SUCCESS : SOURCE_FINISH_FAILURE); })); } std::string get_log() const { auto bufs = _log_buf.data(); size_t buf_size = _log_buf.size(); return std::move(std::string(boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + buf_size)); } private: boost::asio::io_service &_service; std::string _command; boost::process::child _child; boost::asio::streambuf _log_buf; }; class cmd_command_builder : public command_builder { public: command_ptr build(boost::asio::io_service &service, const params_map &params) const { return std::make_shared<cmd_command> ( service, params.get_param("command") ); } }; void connect_plugin(plugins_manager_api *api) noexcept { api->register_command_builder("cmd", std::make_shared<cmd_command_builder>()); }
30.258065
130
0.633795
pozitiffcat
7d2ab9ea11b4d640d50dd1bcbb313739c87f8650
53,944
cxx
C++
osprey/ipa/common/ipc_compile.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/ipa/common/ipc_compile.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/ipa/common/ipc_compile.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* Copyright 2014 University of Houston. All Rights Reserved. */ /* Copyright UT-Battelle, LLC. All Rights Reserved. 2014 Oak Ridge National Laboratory */ /* * Copyright (C) 2010 Advanced Micro Devices, Inc. All Rights Reserved. */ /* * Copyright 2003, 2004, 2005, 2006 PathScale, Inc. All Rights Reserved. */ /* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. UT-BATTELLE, LLC AND THE GOVERNMENT MAKE NO REPRESENTATIONS AND DISCLAIM ALL WARRANTIES, BOTH EXPRESSED AND IMPLIED. THERE ARE NO EXPRESS OR IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY PATENT, COPYRIGHT, TRADEMARK, OR OTHER PROPRIETARY RIGHTS, OR THAT THE SOFTWARE WILL ACCOMPLISH THE INTENDED RESULTS OR THAT THE SOFTWARE OR ITS USE WILL NOT RESULT IN INJURY OR DAMAGE. THE USER ASSUMES RESPONSIBILITY FOR ALL LIABILITIES, PENALTIES, FINES, CLAIMS, CAUSES OF ACTION, AND COSTS AND EXPENSES, CAUSED BY, RESULTING FROM OR ARISING OUT OF, IN WHOLE OR IN PART THE USE, STORAGE OR DISPOSAL OF THE SOFTWARE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ #undef DRAGON #include <stdint.h> #include <limits.h> // for PATH_MAX #include <unistd.h> // for read(2)/write(2) #include <fcntl.h> // for open(2) #include <sys/types.h> #include <sys/stat.h> // for chmod(2) #include <string.h> #include <errno.h> // for sys_errlist #include <vector> // for STL vector container #include <ext/hash_map> // for STL hash_map container #include <libgen.h> // for basename() #include <time.h> // for time() #include <sys/param.h> // for MAXPATHLEN #include "linker.h" // std. linker's headers #include "process.h" // for tmpdir, etc. #include "main.h" // for arg_vectors #include "ipc_weak.h" #include "defs.h" // std. mongoose definitions #include "errors.h" // for ErrMsg #include "erglob.h" // error code #include "glob.h" // for Tlog_File_Name #include "tracing.h" // for Set_Trace_File #include "cxx_memory.h" // for CXX_NEW #include "opcode.h" // needed by wn_core.h #include "wn_core.h" // needed by ir_bread.h #include "pu_info.h" // needed by ir_bread.h #include "ir_bread.h" // for WN_get_section_base () #include "dwarf_DST_mem.h" // needed by ipc_file.h #include "ipc_file.h" // for IP_FILE_HDR #include "ipa_option.h" // ipa option flags #include "ipc_link.h" // for ipa_link_link_argv #include "lib_phase_dir.h" // for BINDIR etc #ifdef KEY #include "ipc_defs.h" // for IPA_Target_Type #endif #pragma weak tos_string #pragma weak outfilename using std::vector; using __gnu_cxx::hash_map; #if defined(__linux__) || defined(BUILD_OS_DARWIN) #define _USE_GNU_MAKE_ #endif #ifdef _USE_GNU_MAKE_ #define TARGET_DELIMITER " : " #else #define TARGET_DELIMITER " ! " #endif #ifdef KEY extern char *psclp_arg; #endif // To create an executable, we have to // -- Compile the symtab file to a .o file (an elf symtab) // -- Compile the symtab to a .G file // -- Using the .G file, compile each of the regular whirl files // (each file that contains a pu) to an elf .o file // -- Link all of the .o files. // For each of the regular whirl files, we keep track of // -- its name // -- the command line we'll use to compile it // -- a list of zero of more lines that will be added to the makefile // as comments. Normally these will be the pu's contained in the file. // How to use these functions: // (1) Initialize with ipa_compile_init. // (2) Call ipacom_process_symtab, where the argument is the symtab file // name. (e.g. "symtab.I") // (3) For each other whirl file: // (a) call ipacom_process_file // (b) call ipacom_add_comment zero or more times, using the // index that ipacom_process_file returned. // (4) call ipacom_doit. ipacom_doit never returns. // -------------------------------------------------------------------------- // File-local variables // makefile_name is a full pathname, as is outfiles_fullpath, // all of the others are basename only. extern int Epilog_Flag; static char* makefile_name = 0; // name of the makefile #ifndef OPENSHMEM_ANALYZER static FILE* makefile = 0; #else FILE* makefile = 0; #endif static vector<const char*>* infiles = 0; static vector<const char*>* outfiles = 0; static vector<const char*>* outfiles_fullpath = 0; static vector<const char*>* commands = 0; static vector<UINT32>* ProMP_Idx = 0; static vector<vector<const char*> >* comments = 0; // Name of the symtab file as written by the ipa. (e.g. symtab.I) static char input_symtab_name[PATH_MAX] = ""; // Name of the symtab file that will be used to compile other whirl // files. (e.g. symtab.G) static char whirl_symtab_name[PATH_MAX] = ""; // Name of the elf symtab file. (e.g. symtab.o) static char elf_symtab_name[PATH_MAX] = ""; // Command line for producing the whirl and elf symtab files. static const char* symtab_command_line = 0; static const char* symtab_extra_args = 0; // Map from short forms of command names (e.g. "cc") to full // forms (e.g. "/usr/bin/cc"). namespace { struct eqstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) == 0; } }; typedef __gnu_cxx::hash_map<const char*, const char*, __gnu_cxx::hash<const char*>, eqstr> COMMAND_MAP_TYPE; } static COMMAND_MAP_TYPE* command_map; // -------------------------------------------------------------------------- // Overview of what happens post-ipa. We create a makefile in the // tmpdir. We spawn a shell to invoke make. Make will compile each // of the .I files in tmpdir, and will then do the final link in the // current working directory. After make terminates, the shell // deletes all of the in the tmp_file_list, including the makefile // itself and the shell script itself, moves all of the other files in // tmpdir into the current working directory, and delete the tmpdir. // Upon interrupt (using sh's builtin trap command), it does the same // thing. static const char* get_extra_args(const char* ipaa_filename); static const char* get_extra_symtab_args(const ARGV&); static void exec_smake(char* cmdfile_name); /* This is here because the gnu basename() doesn't strip off multiple slashes. */ static const char*ipa_basename(char *name){ const char *bname = basename(name); while (*bname == '/') bname++; return bname; } /* This is here because the result from ipa_basename may contain illegal character '-', which should be changed to '_' */ static char* proper_name(char *name){ for(char *i = name; *i; i++) { if ( !isalnum(*i) ) *i = '_'; } return name; } static const char* abi() { #if defined(TARG_MIPS) || defined(TARG_LOONGSON) // 12343: Use IPA_Target_Type instead of ld_ipa_opt[LD_IPA_TARGOS].flag // to distinguish between n32 and 64 in IPA return IPA_Target_Type == IP_64_bit_ABI ? "-64" : "-n32"; #endif #ifdef TARG_IA64 return "-i64"; #endif #ifdef TARG_IA32 return "-i32"; #endif #ifdef TARG_X8664 return IPA_Target_Type == IP_64_bit_ABI ? "-m64" : "-m32"; #endif return "-n32"; // This line is never reached. } namespace { // Returns true if path refers to an ordinary file. bool file_exists(const char* path) { if (!path || strlen(path) == 0) return false; struct stat buf; return stat(path, &buf) == 0 && S_ISREG(buf.st_mode); } } // Close unnamed namespace #ifdef KEY static inline bool looks_like(const char *path, const char *base) { int p = strlen(path), b = strlen(base); return (strcmp(path + p - b, base) == 0 && (path[p - b - 1] == '-' || path[p - b - 1] == '/')); } #endif extern "C" void ipa_compile_init () { Is_True(tmpdir, ("no IPA temp. directory")); Is_True(infiles == 0 && outfiles == 0 && commands == 0 && comments == 0 && makefile_name == 0 && makefile == 0 && command_map == 0, ("ipa_compile_init already initialized")); infiles = CXX_NEW (vector<const char*>, Malloc_Mem_Pool); outfiles = CXX_NEW (vector<const char*>, Malloc_Mem_Pool); outfiles_fullpath = CXX_NEW (vector<const char*>, Malloc_Mem_Pool); commands = CXX_NEW (vector<const char*>, Malloc_Mem_Pool); comments = CXX_NEW (vector<vector<const char*> >, Malloc_Mem_Pool); if (infiles == 0 || outfiles == 0 || outfiles_fullpath == 0 || commands == 0 || comments == 0) ErrMsg (EC_No_Mem, "ipa_compile_init"); if (ProMP_Listing) ProMP_Idx = CXX_NEW (vector<UINT32>, Malloc_Mem_Pool); char name_buffer[256]; sprintf(name_buffer, "makefile.ipa%ld", (long) getpid()); makefile_name = create_unique_file(name_buffer, 0); add_to_tmp_file_list (makefile_name); makefile = fopen(makefile_name, "w"); if (makefile == 0) ErrMsg (EC_Ipa_Open, makefile_name, strerror(errno)); chmod(makefile_name, 0644); command_map = CXX_NEW(COMMAND_MAP_TYPE, Malloc_Mem_Pool); if (command_map == 0) ErrMsg (EC_No_Mem, "ipa_compile_init"); const char* toolroot = getenv("TOOLROOT"); #if defined(TARG_IA64) || defined(TARG_X8664) || defined(TARG_MIPS) || defined(TARG_SL) || defined(TARG_LOONGSON) static char* smake_base = ALTBINPATH "/usr/bin/make"; #if defined(VENDOR_PSC) #include "pathscale_defs.h" static const char* tmp_cc_name_base = PSC_INSTALL_PREFIX "/bin/" PSC_NAME_PREFIX "cc"; #elif defined(VENDOR_OSP) static const char* tmp_cc_name_base = "/usr/ia64-sgi-linux/bin/sgicc"; #else static const char* tmp_cc_name_base; #endif static const char* cc_name_base = tmp_cc_name_base; static const char* cord_name_base= "/usr/bin/gen_cord"; static char my_cc[MAXPATHLEN]; char *where_am_i = getenv("COMPILER_BIN"); int retval; if (where_am_i) { tmp_cc_name_base = where_am_i; cc_name_base = where_am_i; } if (my_cc[0] == '\0' && (retval = readlink ("/proc/self/exe", my_cc, sizeof(my_cc))) >= 0) { my_cc[retval] = '\0'; // readlink doesn't append NULL #if !defined(TARG_SL) && !defined(TARG_MIPS) if (looks_like (my_cc, OPEN64_NAME_PREFIX "cc") || looks_like (my_cc, OPEN64_NAME_PREFIX "CC") || looks_like (my_cc, OPEN64_NAME_PREFIX "f90")) { #else #define SLCC_NAME_PREFIX "sl" if (looks_like (my_cc, SLCC_NAME_PREFIX "cc") || looks_like (my_cc, SLCC_NAME_PREFIX "CC") || looks_like (my_cc, SLCC_NAME_PREFIX "f90")) { #endif tmp_cc_name_base = my_cc; cc_name_base = my_cc; } else if (looks_like (my_cc, "ipa_link")) { char *s = strrchr(my_cc, '/'); if (s) { #ifndef TARG_SL *s = '\0'; // remove "/ipa_link" s = strrchr(my_cc, '/'); (s) ? *s = '\0' : 0; // remove version number, e.g. "/2.3.99" s = strrchr(my_cc, '/'); (s) ? *s = '\0' : 0; // remove the 'targ_open64_linux' s = strrchr(my_cc, '/'); (s) ? *s = '\0' : 0; // remove the 'gcc-lib' s = strrchr(my_cc, '/'); #endif if (s) { // Invoke the C/C++/Fortran compiler depending on the source // language. Bug 8620. const char *compiler_name_suffix; if (!strcmp(IPA_lang, "F77") || !strcmp(IPA_lang, "F90")) { compiler_name_suffix = "f95"; } else if (!strcmp(IPA_lang, "C")) { compiler_name_suffix = "cc"; } else if (!strcmp(IPA_lang, "CC")) { compiler_name_suffix = "CC"; } else { Fail_FmtAssertion ("ipa: unknown language"); } #if defined(VENDOR_PSC) strcpy(++s, "bin/" PSC_NAME_PREFIX); s += strlen("bin/" PSC_NAME_PREFIX); #elif defined(VENDOR_SL) strcpy(++s, SLCC_NAME_PREFIX); s += strlen(SLCC_NAME_PREFIX); #elif !defined(TARG_MIPS) strcpy(++s, "bin/" OPEN64_NAME_PREFIX); s += strlen("bin/" OPEN64_NAME_PREFIX); #endif strcpy(s, compiler_name_suffix); if (file_exists (my_cc)) { tmp_cc_name_base = my_cc; cc_name_base = my_cc; } } } } } #define MAKE_STRING "make" #else static char* smake_base = "/usr/sbin/smake"; static char* tmp_cc_name_base = "/usr/bin/cc"; static char* cc_name_base = "/usr/bin/cc"; static char* cord_name_base= "/usr/bin/gen_cord"; #define MAKE_STRING "smake" #endif (*command_map)["cord"] = cord_name_base; if (toolroot) { static char* new_cc_name_base = concat_names((const string)toolroot, (const string)tmp_cc_name_base); if (file_exists(new_cc_name_base)) (*command_map)["cc"] = new_cc_name_base; else (*command_map)["cc"] = cc_name_base; } else (*command_map)["cc"] = cc_name_base; // For smake we first try $TOOLROOT/usr/sbin/smake. If that doesn't // exist then we try /usr/sbin/smake, and finally if *that* doesn't // exist we just use smake and hope that the user's search path // contains something sensible. static const char* smake_name = 0; { if (toolroot != 0) { const char* tmp = concat_names((const string)toolroot, (const string)smake_base); if (file_exists(tmp)) smake_name = tmp; } if (smake_name == 0) { if (file_exists(smake_base)) smake_name = smake_base; else smake_name = MAKE_STRING; } } (*command_map)[MAKE_STRING] = smake_name; #ifdef TODO if (IPA_Enable_Cord) { cord_output_file_name = create_tmp_file ("cord_script"); call_graph_file_name = create_tmp_file ("ipa_cg"); add_to_tmp_file_list (call_graph_file_name); Call_graph_file = FOPEN (call_graph_file_name, "w"); if (Call_graph_file == 0) #ifdef TARG_IA64 { perror(call_graph_file_name); exit(1); } #else msg (ER_FATAL, ERN_IO_FATAL, call_graph_file_name, strerror(errno)); #endif } #else DevWarn ("TODO: support ipa-cord"); #endif } // ipa_compile_init // Generate a command line to compile an ordinary whirl file into an object // file. static void get_command_line (const IP_FILE_HDR& hdr, ARGV& argv, const char* inpath, const char* outpath) { char* base_addr = (char*) WN_get_section_base (IP_FILE_HDR_input_map_addr (hdr), WT_COMP_FLAGS); if (base_addr == (char*) -1) ErrMsg (EC_IR_Scn_Read, "command line", IP_FILE_HDR_file_name (hdr)); Elf64_Word argc = *((Elf64_Word *) base_addr); Elf64_Word* args = (Elf64_Word *) (base_addr + sizeof(Elf64_Word)); // args[0] is the command, so we need to treat it specially. If // TOOLROOT is set, and if args[0] isn't already an absolute pathname, // we need to construct an absolute pathname using TOOLROOT. Is_True(command_map != 0 && command_map->find("cc") != command_map->end() && (*command_map)["cc"] != 0 && strlen((*command_map)["cc"]) != 0, ("Full pathname for cc not set up")); if (argc > 0) { argv.push_back((*command_map)["cc"]); for (INT i = 1; i < argc; ++i) { argv.push_back (base_addr + args[i]); } } else { argv.push_back ((*command_map)["cc"]); argv.push_back ("-c"); } argv.push_back(abi()); argv.push_back (inpath); argv.push_back ("-o"); argv.push_back (outpath); argv.push_back ("-c"); if (ld_ipa_opt[LD_IPA_KEEP_TEMPS].flag) argv.push_back ("-keep"); } // get_command_line // temp. kludge: ipacom_process_file should really take // const IP_FILE_HDR& as argument instead of const PU_Info * #include "ipc_symtab_merge.h" static const IP_FILE_HDR& get_ip_file_hdr (const PU_Info *pu) { ST_IDX st_idx = PU_Info_proc_sym (pu); PU_IDX pu_idx = ST_pu (St_Table[st_idx]); return *AUX_PU_file_hdr (Aux_Pu_Table[pu_idx]); } extern "C" void ipacom_process_symtab (char* symtab_file) { Is_True(infiles != 0 && outfiles != 0 && outfiles_fullpath != 0 && commands != 0 && comments != 0, ("ipacom_process_symtab: ipacom not yet initialized")); Is_True(strlen(input_symtab_name) == 0 && strlen(whirl_symtab_name) == 0 && strlen(elf_symtab_name) == 0 && symtab_command_line == 0, ("ipacom_process_symtab: symtab already initialized")); char* output_file = create_unique_file (symtab_file, 'o'); add_to_tmp_file_list (output_file); #ifdef _USE_GNU_MAKE_ unlink (output_file); #endif const char* input_base = ipa_basename(symtab_file); const char* output_base = ipa_basename(output_file); // Save the three symtab file names in global variables. strcpy(input_symtab_name, input_base); strcpy(elf_symtab_name, output_base); strcpy(whirl_symtab_name, output_base); whirl_symtab_name[strlen(whirl_symtab_name) - 1] = 'G'; // Generate a command line to create the .G and .o files. char buf[3*PATH_MAX + 64]; Is_True(command_map != 0 && command_map->find("cc") != command_map->end() && (*command_map)["cc"] != 0 && strlen((*command_map)["cc"]) != 0, ("Full pathname for cc not set up")); char* toolroot = getenv("TOOLROOT"); #if defined(VENDOR_OSP) || defined(VENDOR_SL) sprintf(buf, "%s -c %s %s -o %s %s -TENV:emit_global_data=%s %s", #else sprintf(buf, "%s%s -c %s %s -o %s %s -TENV:emit_global_data=%s %s", (toolroot != 0) ? toolroot : "", #endif (*command_map)["cc"], abi(), input_symtab_name, elf_symtab_name, ld_ipa_opt[LD_IPA_KEEP_TEMPS].flag ? "-keep":"", whirl_symtab_name, IPA_Enable_AutoGnum?"-Gspace 0":""); char* cmd = static_cast<char*>(malloc(strlen(buf) + 1)); if (!cmd) ErrMsg (EC_No_Mem, "ipacom_process_symtab"); strcpy(cmd, buf); symtab_command_line = cmd; Is_True(strlen(input_symtab_name) != 0 && strlen(whirl_symtab_name) != 0 && strlen(elf_symtab_name) != 0 && symtab_command_line != 0, ("ipacom_process_symtab: initialization failed")); } // ipacom_process_symtab // The return value is the index of this file in the vectors. extern "C" size_t ipacom_process_file (char* input_file, const PU_Info* pu, UINT32 ProMP_id) { Is_True(infiles != 0 && outfiles_fullpath != 0 && commands != 0 && comments != 0, ("ipacom_process_file: ipacom not initialized")); Is_True(strlen(input_symtab_name) != 0 && strlen(whirl_symtab_name) != 0 && strlen(elf_symtab_name) != 0 && symtab_command_line != 0, ("ipacom_process_file: symtab not initialized")); if (ProMP_Listing) { Is_True (ProMP_Idx != 0, ("ipacom_process_file: ipacom not initialized")); ProMP_Idx->push_back (ProMP_id); } char* output_file = create_unique_file (input_file, 'o'); add_to_tmp_file_list (output_file); const char* input_base = ipa_basename (input_file); const char* output_base = ipa_basename (output_file); infiles->push_back(input_base); outfiles->push_back(output_base); outfiles_fullpath->push_back(output_file); // Assemble the command line. ARGV argv; // vector<const char*> get_command_line (get_ip_file_hdr (pu), argv, input_base, output_base); char* str = (char*) malloc(2 * PATH_MAX + 64); sprintf(str, "-TENV:ipa_ident=%ld -TENV:read_global_data=%s %s", time(0), whirl_symtab_name, IPA_Enable_AutoGnum?"-Gspace 0":""); argv.push_back(str); #ifdef KEY // Add "-psclp filename". if (psclp_arg != NULL) { char* str = static_cast<char*>(strdup(psclp_arg)); argv.push_back(str); } #endif if (ProMP_Listing) { char* str = static_cast<char*>(malloc(64)); sprintf(str, "-PROMP:=ON -PROMP:next_id=%lu", (unsigned long) ProMP_id); argv.push_back(str); } //char* gspace = (char*) malloc(2 * PATH_MAX + 64); //strcpy(gspace, "-Gspace 0"); //argv.push_back(gspace); #ifdef TODO if (gspace_size) { WRITE_STRING("-Gspace", argv->argv[i]); sprintf(str, "%d", gspace_size); WRITE_STRING(str, argv->argv[++i]); } #else static bool reported = false; if (!reported) { reported = true; DevWarn ("TODO: implement gspace_size command file"); } if (IPA_Enable_Array_Sections) argv.push_back("-LNO:ipa"); #endif // Piece the command line together and push it onto the list. size_t cmdline_length = 0; ARGV::const_iterator i; for (i = argv.begin(); i != argv.end(); ++i) cmdline_length += strlen(*i) + 1; char* cmdline = static_cast<char*>(malloc(cmdline_length + 1)); if (!cmdline) ErrMsg (EC_No_Mem, "ipacom_process_file"); cmdline[0] = '\0'; for (i = argv.begin(); i != argv.end(); ++i) { strcat(cmdline, *i); strcat(cmdline, " "); } commands->push_back(cmdline); // Add an empty vector for this file's comments. #ifdef KEY // porting to GNU 3.* vector<const char*>* emptyvector = CXX_NEW(vector<const char*>, Malloc_Mem_Pool); comments->push_back(*emptyvector); #else comments->push_back(); #endif Is_True (infiles->size() > 0 && infiles->size() == outfiles->size() && infiles->size() == outfiles_fullpath->size() && infiles->size() == commands->size() && infiles->size() == comments->size(), ("ipacom_process_file: inconsistent vector sizes")); // Set up extra args for compiling symtab, if necessary. if (!symtab_extra_args) symtab_extra_args = get_extra_symtab_args(argv); return infiles->size() - 1; } // ipacom_process_file // Each file has a list of zero or more comments that will appear in the // makefile. (Usually, each comment will be the name of a pu.) // This function adds a comment to the n'th file's list. extern "C" void ipacom_add_comment(size_t n, const char* comment) { Is_True(infiles != 0 && outfiles != 0 && outfiles_fullpath != 0 && commands != 0 && comments != 0, ("ipacom_add_comment: ipacom not initialized")); Is_True(comments->size() >= n + 1, ("ipacom_add_comment: invalid index %ld, max is %ld", n, comments->size())); Is_True(comment != 0, ("ipacom_add_comment: argument is a null pointer")); char* tmp = static_cast<char*>(malloc(strlen(comment) + 1)); if (!tmp) ErrMsg (EC_No_Mem, "ipacom_add_commend"); strcpy(tmp, comment); (*comments)[n].push_back(tmp); } namespace { char* ipc_copy_of (char *str) { register int len; register char *p; len = strlen(str) + 1; p = (char *) MALLOC (len); MALLOC_ASSERT (p); BCOPY (str, p, len); return p; } /* ipc_copy_of */ void print_obj_listfiles(const char* dirname, FILE* listfile) { for (vector<const char*>::iterator i = outfiles->begin(); i != outfiles->end(); ++i) fprintf(listfile, "%s/%s \n", dirname, *i); if (strlen(elf_symtab_name) != 0) fprintf(listfile, "%s/%s \n", dirname, elf_symtab_name); } void print_all_outfiles(const char* dirname) { for (vector<const char*>::iterator i = outfiles->begin(); i != outfiles->end(); ++i) fprintf(makefile, "%s%s/%s \\\n", " ", dirname, *i); if (strlen(elf_symtab_name) != 0) fprintf(makefile, "%s%s/%s \n", " ", dirname, elf_symtab_name); } } // Close unnamed namespace static const char* Get_Annotation_Filename_With_Path (void) { static char buf[MAXPATHLEN]; if (!Annotation_Filename) { buf[0] = '\0'; } else if (*Annotation_Filename == '/') { strcpy (buf, Annotation_Filename); }else { #ifdef KEY strcpy (buf, "$$dir/"); // bug 11686 #else strcpy (buf, "../"); #endif strcat (buf, Annotation_Filename); } return &buf[0]; } extern "C" void ipacom_doit (const char* ipaa_filename) { Is_True(infiles != 0 && outfiles != 0 && outfiles_fullpath != 0 && commands != 0 && comments != 0 && makefile != 0, ("ipacom_doit: ipacom not yet initialized")); Is_True(infiles->size() == outfiles->size() && infiles->size() == outfiles_fullpath->size() && infiles->size() == commands->size() && infiles->size() == comments->size(), ("ipacom_doit: vectors are inconsistent")); if (infiles->size() > 0) { Is_True(strlen(input_symtab_name) != 0 && strlen(whirl_symtab_name) != 0 && strlen(elf_symtab_name) != 0 && symtab_command_line != 0, ("ipacom_doit: symtab not initialized")); } #ifdef TODO if (IPA_Enable_Cord) { FCLOSE (Call_graph_file); if (IPA_Enable_final_link) process_cord_cmd (); } #endif // These are used when compiling each .I file. const char* extra_args = get_extra_args(ipaa_filename); const char* tmpdir_macro_name = "IPA_TMPDIR"; const char* tmpdir_macro = "$(IPA_TMPDIR)"; fprintf(makefile, "%s = %s\n\n", tmpdir_macro_name, tmpdir); char* link_cmdfile_name = 0; // The default target: either the executable, or all of the // elf object files. if (IPA_Enable_final_link) { // Path (possibly relative to cwd) of the executable we're creating. const char* executable = outfilename; const char* executable_macro_name = "IPA_OUTFILENAME"; const char* executable_macro = "$(IPA_OUTFILENAME)"; fprintf(makefile, "%s = %s\n\n", executable_macro_name, executable); fprintf(makefile, ".PHONY: default\n"); fprintf(makefile, "default: %s\n\n", executable_macro); #ifdef KEY // bug 2487 // bug 3594: emit backslash if there is only symtab.o fprintf(makefile, "%s%s%s\n", executable_macro, TARGET_DELIMITER, outfiles->size() || strlen(elf_symtab_name) ? "\\" : ""); #else fprintf(makefile, "%s%s\\\n", executable_macro, TARGET_DELIMITER); #endif #ifdef TODO if (IPA_Enable_Cord) fprintf(makefile, "%s%s \\\n", " ", cord_output_file_name); #endif print_all_outfiles(tmpdir_macro); // The final link command is just ld -from <cmdfile>. Everything else // goes into cmdfile. // Create a temporary file for cmdfile. char cmdfile_buf[256]; sprintf(cmdfile_buf, "linkopt.%ld", (long) getpid()); link_cmdfile_name = create_unique_file(cmdfile_buf, 0); FILE* cmdfile = fopen(link_cmdfile_name, "w"); if (cmdfile == 0) ErrMsg (EC_Ipa_Open, link_cmdfile_name, strerror(errno)); chmod(link_cmdfile_name, 0644); // Get the link command line. const ARGV* link_line = ipa_link_line_argv (outfiles_fullpath, tmpdir, elf_symtab_name); Is_True(link_line->size() > 1, ("Invalid link line ARGV vector")); // Print all but link_line[0] into cmdfile. ARGV::const_iterator i = link_line->begin(); // see whether we use ld/collect or gcc/g++ to link objects, if // we use gcc/g++ to link the object, we should ignore the CRTs. const char* linker = strrchr(*i, '/'); BOOL no_crt = TRUE; if (linker && (!strcmp (linker, "/ld") || !strcmp (linker, "/collect")) || !linker && (!strcmp (*i, "ld") || !strcmp (*i, "collect"))) { no_crt = FALSE; } for (++i; i != link_line->end(); ++i) { #ifdef KEY // Since we are using GCC to link, don't print out the run-time support // files. const char *p; #ifndef TARG_SL // jczhang: use slcc specific crt*.o if (((p = strstr(*i, "/crt1.o")) && p[7] == '\0') || ((p = strstr(*i, "/Scrt1.o")) && p[8] == '\0') || ((p = strstr(*i, "/crti.o")) && p[7] == '\0') || ((p = strstr(*i, "/crtbegin.o")) && p[11] == '\0') || ((p = strstr(*i, "/crtbeginS.o")) && p[12] == '\0') || ((p = strstr(*i, "/crtend.o")) && p[9] == '\0') || ((p = strstr(*i, "/crtendS.o")) && p[10] == '\0') || ((p = strstr(*i, "/crtn.o")) && p[7] == '\0')) { continue; } if (strcmp(*i,"-lgcc")==0) { if(Feedback_Filename!=NULL) { /* need to enabled the feedback for ther faces via flags */ if (!Epilog_Flag) { fputs("-linstr", cmdfile); fputs(" \n", cmdfile); fputs("-lstdc++", cmdfile); fputs(" \n", cmdfile); } } } #endif #endif // Since we're using gcc to link, we must mangle linker // directives that we know about so they are acceptable to it, // and passed properly to its linker. if (strcmp(*i, "-rpath") == 0) { fputs("-Wl,-rpath,", cmdfile); ++i; } if (strcmp(*i, "-rpath-link") == 0) { fputs("-Wl,-rpath-link,", cmdfile); ++i; } if (strcmp(*i, "-whole-archive") == 0) { fputs("-Wl,-whole-archive", cmdfile); fputs(" \n", cmdfile); continue; } if (strcmp(*i, "-no-whole-archive") == 0) { fputs("-Wl,-no-whole-archive", cmdfile); fputs(" \n", cmdfile); continue; } if (strncmp(*i, "-soname=", 8) == 0) { fputs("-Wl,", cmdfile); fputs(*i, cmdfile); fputs(" \n", cmdfile); continue; } fputs(*i, cmdfile); fputs(" \n", cmdfile); } #ifdef TODO if (IPA_Enable_Cord) { fputs("-T", cmdfile); fprintf(cmdfile, " %s\n", cord_output_file_name); } #endif fputs("\n", cmdfile); fclose(cmdfile); // If we're compiling with -show, make sure we see the link line. if (ld_ipa_opt[LD_IPA_SHOW].flag) { fprintf(makefile, "\techo -n %s ' ' ; cat %s\n", link_line->front(), link_cmdfile_name); #ifndef _USE_GNU_MAKE_ fprintf(makefile, "\t...\n"); #endif } // Print the final link command into the makefile. #if defined(TARG_IA64) || defined(TARG_X8664) || defined(TARG_MIPS) || defined(TARG_SL) // Create a dir in /tmp and create symbolic links inside it to point to the // IPA .o files in the IPA tmpdir. In the link command file, refer to // these symbolic links instead of the IPA tmpdir .o files, in order to // shorten the args in the link command file. For example, // /home/blah/very/long/path/1.o becomes /tmp/symlinksdir/1.o. Fixes bugs // 5876 (very long path), and 7801/7866 (must link in current dir). // Create symbolic links dir in /tmp. const char *outfile_basename = ipa_basename(outfilename); char *symlinksdir = (char *) alloca(20 + strlen(outfile_basename)); sprintf(symlinksdir, "/tmp/%s.ipaXXXXXX", outfile_basename); symlinksdir = mktemp(symlinksdir); // In the makefile, set up the symbolic links and modify the link command // to reference these links: // mkdir symlinksdir // for i in `grep ^tmpdir/.\*.o link_cmdfile`; do // ln -s $i symlinksdir // done // gcc `sed 's:tmpdir:symlinksdir:' link_cmdfile` // rm -r symlinksdir fprintf(makefile, "\tmkdir %s\n", symlinksdir); fprintf(makefile, "\td=`pwd` ; \\\n"); fprintf(makefile, "\tfor i in `grep ^%s/.\\*.o %s`; do ln -s %s$$i %s; done\n", tmpdir, link_cmdfile_name, tmpdir[0] == '/' ? "" : "$$d/", symlinksdir); #ifdef TARG_SL //jczhang: link with SL's ld instead of gcc char *toolroot = getenv("TOOLROOT"); fprintf(makefile, "\t%s%s `sed 's:%s:%s:' %s`\n", toolroot, BINPATH"/ld", tmpdir, symlinksdir, link_cmdfile_name); #else fprintf(makefile, "\t%s `sed 's:%s:%s:' %s`\n", link_line->front(), tmpdir, symlinksdir, link_cmdfile_name); #endif // TARG_SL fprintf(makefile, "\trm -r %s\n", symlinksdir); #ifdef OPENSHMEM_ANALYZER if (OSA_Flag) { fprintf(makefile, "\trm -r %s\n", outfile_basename); } #endif #elif defined(TARG_LOONGSON) fprintf(makefile, "\t%s `cat %s `\n", link_line->front(), link_cmdfile_name); #else fprintf(makefile, "\t%s -from %s\n", link_line->front(), link_cmdfile_name); #endif //For ProMP we need to run a Perl script after doing the final link. if (ProMP_Listing) { const char* toolroot = getenv("TOOLROOT"); static const char* script_base = "/usr/lib32/cmplrs/pfa_reshuffle"; const char* script_name = toolroot ? concat_names((const string)toolroot, (const string)script_base) : script_base; struct stat dummy; if (stat("/bin/perl5", &dummy) == 0 && stat(script_name, &dummy) == 0) { fprintf(makefile, "\t/bin/perl5 %s", script_name); vector<const char*>::const_iterator i = outfiles_fullpath->begin(); for ( ; i != outfiles_fullpath->end(); ++i) fprintf(makefile, " %s", *i); fprintf(makefile, "\n"); } else { if (stat("/bin/perl5", &dummy) != 0) { DevWarn("Can't find perl5 to run the ProMP reshuffle script"); } if (stat(script_name, &dummy) != 0) { DevWarn("Can't find the ProMP reshuffle script"); } } // For ProMP we also need to concatenate all of the .list files into // a file in the same directory as the excecutable. The file is // named <executable>.list fprintf(makefile, "\tif [ -f %s.list ] ; then 'rm' -f %s.list ; fi\n", executable_macro, executable_macro); fprintf(makefile, "\t'cat' %s/*.list > %s.list\n", tmpdir_macro, executable_macro); } // Do the same thing with .t and .tlog files (if they exist) as // with .list files. bool tlogs_enabled = Get_Trace(TP_PTRACE1, 0xffffffff) || Get_Trace(TP_PTRACE2, 0xffffffff); bool t_enabled = TFile != stdout; if (tlogs_enabled) { fprintf(makefile, "\tif 'ls' -f %s/*.tlog > /dev/null 2>&1 ; then ", tmpdir); // Beforehand the output of cat was appended to // <executable>.<log>, but this requires the user to remove // <executable>.t before invocation when there is no // <executable>.<suffix> source file. But we don't want to just // truncate <executable>.<log> before writing, since // <executable>.<log> might be created during input WHIRL // generation. So we truncate and write to <tmpdir>.log // instead. fprintf(makefile, "'cat' %s/*.tlog > %s.tlog ; true ; fi\n", tmpdir, tmpdir); } if (t_enabled) { fprintf(makefile, "\tif 'ls' -f %s/*.t > /dev/null 2>&1 ; then ", tmpdir); fprintf(makefile, "'cat' %s/*.t > %s.t ; true ; fi\n", tmpdir, tmpdir); } } else { fprintf(makefile, ".PHONY: default\n"); fprintf(makefile, "\ndefault: \\\n"); print_all_outfiles(tmpdir_macro); } fputs("\n", makefile); // This generates both the .o symtab and the .G symtab. if (strlen(elf_symtab_name) != 0) { char* toolroot = getenv("TOOLROOT"); Is_True(strlen(input_symtab_name) != 0 && strlen(whirl_symtab_name) != 0 && symtab_command_line != 0 && strlen(symtab_command_line) != 0, ("ipacom_doit: symtab not initialized")); if (!symtab_extra_args) symtab_extra_args = get_extra_args(0); #if defined(TARG_IA64) || defined(TARG_X8664) || defined(TARG_MIPS) || defined(TARG_SL) || defined(TARG_LOONGSON) if (IPA_Enable_Cord) { const char * obj_listfile_name = create_tmp_file((const string)"obj_file_list"); FILE* listfile = fopen(obj_listfile_name, "w"); print_obj_listfiles(tmpdir, listfile); fclose(listfile); fprintf(makefile, "%s%s \\\n", cord_output_file_name, TARGET_DELIMITER); print_all_outfiles(tmpdir_macro); fprintf(makefile, "\t%s%s -o %s %s %s\n",(toolroot != 0) ? toolroot : "",(*command_map)["cord"], cord_output_file_name, call_graph_file_name, obj_listfile_name);//gen_cord } fprintf(makefile, "%s/%s" TARGET_DELIMITER "\n", tmpdir_macro, "dummy"); char *tmpname = (char *) malloc (strlen (outfilename) + 1); strcpy (tmpname, outfilename); if (Feedback_Filename) { fprintf(makefile, "\tcd %s; %s -Wb,-OPT:procedure_reorder=on -fb_create %s %s -Wb,-CG:enable_feedback=off -TENV:object_name=_%s\n\n", tmpdir_macro, symtab_command_line, Feedback_Filename, symtab_extra_args, proper_name((const string)ipa_basename(tmpname))); } else if (Annotation_Filename) { fprintf (makefile, "\t" #ifdef KEY "dir=`pwd`; " // for calculating feedback prefix #endif "cd %s; %s -Wb,-OPT:procedure_reorder=on -fb_opt %s %s -TENV:object_name=_%s " #ifdef KEY "-Wb,-CG:enable_feedback=on\n\n", // enable feedback for cg #else "-Wb,-CG:enable_feedback=off\n\n", #endif tmpdir_macro, symtab_command_line, Get_Annotation_Filename_With_Path (), symtab_extra_args, proper_name((const string)ipa_basename(tmpname))); } else { fprintf(makefile, "\tcd %s; %s -Wb,-OPT:procedure_reorder=on %s -Wb,-CG:enable_feedback=off -TENV:object_name=_%s\n\n", tmpdir_macro, symtab_command_line, symtab_extra_args, proper_name((const string)ipa_basename(tmpname))); } fprintf(makefile, "%s/%s" TARGET_DELIMITER "%s/%s %s/%s\n\n", tmpdir_macro, elf_symtab_name, tmpdir_macro, input_symtab_name, tmpdir_macro, "dummy"); fprintf(makefile, "%s/%s" TARGET_DELIMITER "%s/%s %s/%s\n\n", tmpdir_macro, whirl_symtab_name, tmpdir_macro, elf_symtab_name, tmpdir_macro, "dummy"); #endif #ifdef _TARG_MIPS fprintf(makefile, "%s/%s" TARGET_DELIMITER "%s/%s\n", tmpdir_macro, elf_symtab_name, tmpdir_macro, input_symtab_name); fprintf(makefile, "\tcd -P %s; %s %s\n\n", tmpdir_macro, symtab_command_line, symtab_extra_args); fprintf(makefile, "%s/%s" TARGET_DELIMITER "%s/%s\n\n", tmpdir_macro, whirl_symtab_name, tmpdir_macro, elf_symtab_name); #endif } // For each whirl file, tell how to create the corresponding elf file. for (size_t i = 0; i < infiles->size(); ++i) { fprintf(makefile, "%s/%s" TARGET_DELIMITER "%s/%s %s/%s %s/%s\n", tmpdir_macro, (*outfiles)[i], tmpdir_macro, elf_symtab_name, tmpdir_macro, whirl_symtab_name, tmpdir_macro, (*infiles)[i]); #if defined(TARG_IA64) || defined(TARG_X8664) || defined(TARG_MIPS) || defined(TARG_SL) || defined(TARG_LOONGSON) if (Feedback_Filename) { fprintf(makefile, "\tcd %s; %s -Wb,-OPT:procedure_reorder=on -fb_create %s %s -Wb,-CG:enable_feedback=off\n", tmpdir_macro, (*commands)[i], Feedback_Filename, extra_args); } else if (Annotation_Filename) { fprintf(makefile, "\t" #ifdef KEY "dir=`pwd`; " #endif "cd %s; %s -Wb,-OPT:procedure_reorder=on -fb_opt %s %s " #ifdef KEY "-Wb,-CG:enable_feedback=on\n", // enable feedback for cg #else "-Wb,-CG:enable_feedback=off\n", #endif tmpdir_macro, (*commands)[i], Get_Annotation_Filename_With_Path () , extra_args); } else { fprintf(makefile, "\tcd %s; %s -Wb,-OPT:procedure_reorder=on %s -Wb,-CG:enable_feedback=off\n", tmpdir_macro, (*commands)[i], extra_args); } #else if (Feedback_Filename) { fprintf(makefile, "\tcd %s; %s -Wb,-OPT:procedure_reorder=on -fb_create %s %s -Wb,-CG:enable_feedback=off\n", tmpdir_macro, (*commands)[i], Feedback_Filename, extra_args); } else if (Annotation_Filename) { fprintf(makefile, "\tcd %s; " #ifdef KEY "dir=`pwd`; " #endif "%s -Wb,-OPT:procedure_reorder=on -fb_opt %s %s -Wb,-CG:enable_feedback=off \n", tmpdir_macro, (*commands)[i], Get_Annotation_Filename_With_Path (),extra_args); } else { fprintf(makefile, "\tcd -P %s; %s -Wb,-OPT:procedure_reorder=on %s -Wb,-CG:enable_feedback=off\n", tmpdir_macro, (*commands)[i], extra_args); } #endif const vector<const char*>& com = (*comments)[i]; for (vector<const char*>::const_iterator it = com.begin(); it != com.end(); ++it) fprintf(makefile, "## %s\n", *it); fputs("\n", makefile); } fclose(makefile); if (Tlog_File_Name) { fclose (Tlog_File); } // We don't call make directly. Instead we call sh, and have it // call sh. This makes cleanup simpler. char sh_cmdfile_buf[256]; sprintf(sh_cmdfile_buf, "cmdfile.%ld", (long) getpid()); char* sh_cmdfile_name = create_unique_file(sh_cmdfile_buf, 0); FILE* sh_cmdfile = fopen(sh_cmdfile_name, "w"); if (sh_cmdfile == 0) ErrMsg (EC_Ipa_Open, sh_cmdfile_name, strerror(errno)); chmod(sh_cmdfile_name, 0644); // Define a shell function for the cleanup. if (!ld_ipa_opt[LD_IPA_KEEP_TEMPS].flag) { fprintf(sh_cmdfile, "cleanup() {\n"); // Remove each temporary file that we know about. vector<const char*>::iterator i; for (i = infiles->begin(); i != infiles->end(); ++i) fprintf(sh_cmdfile, "if [ -f %s/%s ] ; then 'rm' -f %s/%s ; fi\n", tmpdir, *i, tmpdir, *i); for (i = outfiles->begin(); i != outfiles->end(); ++i) fprintf(sh_cmdfile, "if [ -f %s/%s ] ; then 'rm' -f %s/%s ; fi\n", tmpdir, *i, tmpdir, *i); if (strlen(input_symtab_name) != 0) { Is_True(strlen(whirl_symtab_name) != 0 && strlen(elf_symtab_name) != 0, ("Inconsistent symtab names: input, whirl, elf = %d %d %d\n", strlen(input_symtab_name), strlen(whirl_symtab_name), strlen(elf_symtab_name))); fprintf(sh_cmdfile, "if [ -f %s/%s ] ; then 'rm' -f %s/%s ; fi\n", tmpdir, input_symtab_name, tmpdir, input_symtab_name); fprintf(sh_cmdfile, "if [ -f %s/%s ] ; then 'rm' -f %s/%s ; fi\n", tmpdir, whirl_symtab_name, tmpdir, whirl_symtab_name); fprintf(sh_cmdfile, "if [ -f %s/%s ] ; then 'rm' -f %s/%s ; fi\n", tmpdir, elf_symtab_name, tmpdir, elf_symtab_name); } if (link_cmdfile_name) fprintf(sh_cmdfile, "if [ -f %s ] ; then 'rm' -f %s ; fi\n", link_cmdfile_name, link_cmdfile_name); fprintf(sh_cmdfile, "'rm' %s > /dev/null 2>&1 ; true\n", makefile_name); #ifndef KEY fprintf(sh_cmdfile, "'rm' %s > /dev/null 2>&1 ; true\n", sh_cmdfile_name); #endif // Move any files that we don't know about to cwd. We use a // complicated shell command because, if no such files exist, we // don't want the user to see any diagnostics. fprintf(sh_cmdfile, "'mv' %s/* . > /dev/null 2>&1 ; true\n", tmpdir); // Remove the directory. fprintf(sh_cmdfile, "'rm' -rf %s > /dev/null 2>&1 ; true\n", tmpdir); #ifdef KEY // fix for bug 254 fprintf(sh_cmdfile, "'rm' %s > /dev/null 2>&1 ; true\n", sh_cmdfile_buf); #endif fprintf(sh_cmdfile, "}\n\n"); // End of cleanup function. // Establish a signal handler so that cleanup always gets called. // SEGV should be here too; we're leaving it out because 6.2 sh doesn't // like it. fprintf(sh_cmdfile, "trap 'cleanup; exit 2' "); #if !defined(TARG_IA64) && !defined(TARG_X8664) && !defined(TARG_MIPS) && !defined(TARG_SL) && !defined(TARG_LOONGSON) fprintf(sh_cmdfile, "ABRT EMT SYS POLL "); #endif fprintf(sh_cmdfile, "HUP INT QUIT ILL TRAP FPE "); fprintf(sh_cmdfile, "KILL BUS PIPE ALRM TERM "); fprintf(sh_cmdfile, "USR1 USR2 IO VTALRM PROF XCPU XFSZ\n\n\n"); } // ensure MAKEFLAGS is not passed to smake(or make). // MAKEFLAGS can only cause trouble if passed in, // and gmake passes CCTYPE= information into // MAKEFLAGS. A problem // for smake if CCTYPE=-Ofast is used, as the 't' // is interpreted as the MAKEFLAGS 'touch only' // option of smake. // Using the simplest, most universal env var reset // command format, that of plain old sh. fprintf(sh_cmdfile,"#! /bin/sh -f \n"); fprintf(sh_cmdfile,"MAKEFLAGS=\nexport MAKEFLAGS\n"); // Call smake. Is_True(command_map != 0 && command_map->find(MAKE_STRING) != command_map->end() && (*command_map)[MAKE_STRING] != 0 && strlen((*command_map)[MAKE_STRING]) != 0, ("Full pathname for smake not set up")); const char* smake_name = (*command_map)[MAKE_STRING]; #ifdef KEY // bug 2487 fprintf(sh_cmdfile, "rm -f %s\n", outfilename); #endif fprintf(sh_cmdfile, "%s -f %s ", smake_name, makefile_name); if (!ld_ipa_opt[LD_IPA_SHOW].flag) fprintf(sh_cmdfile, "-s "); #ifdef KEY if (IPA_Max_Jobs > 1) fprintf(sh_cmdfile, "-j %u ", IPA_Max_Jobs); #else if (IPA_Max_Jobs_Set) fprintf(sh_cmdfile, "-J %u ", IPA_Max_Jobs); #endif fprintf(sh_cmdfile, "\nretval=$?\n"); // Do cleanup, and return. if (!ld_ipa_opt[LD_IPA_KEEP_TEMPS].flag) { fprintf(sh_cmdfile, "cleanup; "); } fprintf(sh_cmdfile, "exit $retval\n"); fclose(sh_cmdfile); #ifdef KEY // Restore the LD_LIBRARY_PATH that was in effect before the compiler was run. if (IPA_old_ld_library_path != NULL) { int i; int path_len = strlen(IPA_old_ld_library_path); // Change ";" back to ":". for (i=0; i<path_len; i++) if (IPA_old_ld_library_path[i] == ';') IPA_old_ld_library_path[i] = ':'; char *env = (char *) alloca (path_len + strlen("LD_LIBRARY_PATH=") + 5); sprintf (env, "LD_LIBRARY_PATH=%s", IPA_old_ld_library_path); putenv (env); } #endif exec_smake(sh_cmdfile_name); } // ipacom_doit // Helper function for get_extra_args. static void escape_char (char *str) { char *p = str + 1; do { *str++ = *p++; } while (*str != 0); } /* escape_char */ // Collect any extra arguments that we will tack onto the command line. // First collect them as a vector of strings, then concatenate them all // together into a single string. static const char* get_extra_args(const char* ipaa_filename) { vector<const char*> args; args.reserve(16); switch (ld_ipa_opt[LD_IPA_SHARABLE].flag) { case F_MAKE_SHARABLE: #ifdef KEY args.push_back("-TENV:PIC"); #else args.push_back("-pic2"); #endif break; case F_CALL_SHARED: case F_CALL_SHARED_RELOC: #ifndef TARG_MIPS #if !defined(TARG_SL) args.push_back("-pic1"); #endif #endif break; case F_NON_SHARED: args.push_back("-non_shared"); break; case F_RELOCATABLE: if (IPA_Enable_Relocatable_Opt == TRUE) args.push_back("-pic1"); break; } // -IPA:keeplight:=ON, which is the default, means that we keep only // the .I files, not the .s files. if (ld_ipa_opt[LD_IPA_KEEP_TEMPS].flag && !IPA_Enable_Keeplight) args.push_back("-keep"); if (ld_ipa_opt[LD_IPA_SHOW].flag) args.push_back("-show"); /* If there's an IPAA intermediate file, let WOPT know: */ if (ipaa_filename) { char* buf = (char*) malloc(strlen(ipaa_filename) + 32); if (!buf) ErrMsg (EC_No_Mem, "extra_args"); sprintf(buf, "-WOPT:ipaa:ipaa_file=%s", ipaa_filename ); args.push_back(buf); } /* If there are -WB,... options, pull them out and add them to the * list. Strip the '-WB,', and treat non-doubled internal commas * as delimiters for new arguments (undoubling the doubled ones): */ if (WB_flags) { string p = ipc_copy_of (WB_flags); while (*p) { args.push_back(p); while (*p) { if (*p == ',') { if (p[1] != ',') { *p++ = 0; break; } else escape_char(p); } else if (p[0] == '\\' && p[1] != 0) escape_char (p); p++; } } } /* If there are -Yx,... options, pull them out and add them to the * list. Several may be catenated with space delimiters: */ vector<char*> space_ptr; // for restoring spaces overwritten by zero if (Y_flags) { char* p = Y_flags; while (*p) { args.push_back(p); while (*p) { if (*p == ' ') { space_ptr.push_back(p); *p++ = 0; break; } else if (p[0] == '\\') escape_char (p); p++; } } } #ifdef _TARG_MIPS /* If there is a -mips[34] option, add it. */ if (ld_ipa_opt[LD_IPA_ISA].set) { switch(ld_ipa_opt[LD_IPA_ISA].flag) { case 3: args.push_back("-mips3"); break; case 4: args.push_back("-mips4"); break; default: break; } } #endif #ifdef TARG_LOONGSON switch(ld_ipa_opt[LD_IPA_ISA].flag) { case TOS_LOONGSON_2e: args.push_back("-loongson2e"); break; case TOS_LOONGSON_2f: args.push_back("-loongson2f"); break; case TOS_LOONGSON_3: args.push_back("-loongson2f"); break; default: // loongson2e break; } #endif size_t len = 0; vector<const char*>::const_iterator i; for (i = args.begin(); i != args.end(); ++i) len += strlen(*i) + 1; char* result = (char*) malloc(len + 1); if (!result) ErrMsg (EC_No_Mem, "extra_args"); result[0] = '\0'; for (i = args.begin(); i != args.end(); ++i) { strcat(result, *i); strcat(result, " "); } // now restore spaces in Y_flags that were overwritten by zeros for (size_t idx = 0; idx < space_ptr.size(); idx++) { Is_True(*space_ptr[idx] == 0, ("space_ptr must point to 0")); *space_ptr[idx] = ' '; } return result; } /* get_extra_args */ static const char* get_extra_symtab_args(const ARGV& argv) { const char* result = get_extra_args(0); for (ARGV::const_iterator i = argv.begin(); i != argv.end(); ++i) { const char* const debug_flag = "-DEBUG"; const char* const G_flag = "-G"; const char* const TARG_flag = "-TARG"; const char* const OPT_flag = "-OPT"; const int debug_len = 6; const int G_len = 2; const int TARG_len = 5; const int OPT_len = 4; bool flag_found = false; // The link line contains -r. That means we don't have enough information // from the link line alone to determine whether the symtab should be // compiled shared or nonshared. We have to look at how one of the other // files was compiled. if (ld_ipa_opt[LD_IPA_SHARABLE].flag == F_RELOCATABLE && IPA_Enable_Relocatable_Opt != TRUE) { const char* const non_shared_flag = "-non_shared"; if (strcmp(*i, non_shared_flag) == 0) flag_found = true; } if ((strncmp(*i, debug_flag, debug_len) == 0) || (strncmp(*i, G_flag, G_len) == 0) || (strncmp(*i, OPT_flag, OPT_len) == 0) || (strncmp(*i, TARG_flag, TARG_len) == 0)) flag_found = true; if (flag_found == true) { char* buf = static_cast<char*>(malloc(strlen(result) + strlen(*i) + 2)); if (!buf) ErrMsg (EC_No_Mem, "extra_symtab_args"); strcpy(buf, result); strcat(buf, " "); strcat(buf, *i); free(const_cast<char*>(result)); result = buf; } } return result; } static void exec_smake (char* sh_cmdfile_name) { /* Clear the trace file: */ Set_Trace_File ( NULL ); #ifdef _OPENMP /* The exec process will cause mp slaves, if any, to be killed. They will in turn send a signal to the master process, which is the new process. This process in turn has a signal handler that dies when it finds out that its slaves die. This way, if we ever compile -mp, we kill the child processes before doing the exec */ mp_destroy_(); #endif // Call the shell. const char* sh_name = "/bin/sh"; const int argc = 2; char* argv[argc+1]; argv[0] = const_cast<char*>(sh_name); argv[1] = sh_cmdfile_name; argv[2] = 0; execve (sh_name, argv, environ_vars); // if the first try fails, use the user's search path execvp ("sh", argv); Fail_FmtAssertion ("ipa: exec sh failed"); } #ifdef KEY extern "C" { // Allow ipa_link to call the error routines. void Ipalink_Set_Error_Phase (char *name) { Set_Error_Phase (name); } void Ipalink_ErrMsg_EC_infile (char *name) { ErrMsg(EC_Ipa_Infile, name); } void Ipalink_ErrMsg_EC_outfile (char *name) { ErrMsg(EC_Ipa_Outfile, name); } } // extern "C" #endif
32.186158
176
0.6146
sharugupta
7d2b0085f8e752aed06ec9875eaf646db8b653cd
6,702
cpp
C++
FSE/Input.cpp
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
17
2017-04-02T00:17:47.000Z
2021-11-23T21:42:48.000Z
FSE/Input.cpp
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
null
null
null
FSE/Input.cpp
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
5
2017-08-06T12:47:18.000Z
2020-08-14T14:16:22.000Z
#include "Input.h" #include <SFML/Window/Keyboard.hpp> #include <iostream> #include <fstream> #include <codecvt> #include <imgui.h> #ifdef _WIN32 #include <Windows.h> #endif namespace fse { Input::Input() { } Input::~Input() { } void Input::init() { KeyMap m = { { L"ShowMenu", sf::Keyboard::Key::Escape }, { L"Jump", sf::Keyboard::Key::Space }, { L"Left", sf::Keyboard::Key::A }, { L"Right", sf::Keyboard::Key::D }, { L"TogglePhysDebug", sf::Keyboard::Key::F5}, { L"TogglePhysDebugAABBs", sf::Keyboard::Key::F6}, { L"ToggleConsole0", sf::Keyboard::Key::Tab}, { L"ToggleConsole1", sf::Keyboard::Key::LControl} }; key_map_ = m; MouseButtonMap mm = { { L"Shoot", sf::Mouse::Button::Left }, { L"Select", sf::Mouse::Button::Left }, { L"RightClick", sf::Mouse::Button::Right }, }; mouse_button_map_ = mm; JoyStickButtonMap mj = { { L"Jump", 0 } }; joy_stick_button_map_ = mj; } void Input::init(KeyMap map) { key_map_ = map; } void Input::init(std::string keymap_path) { KeyMap km; MouseButtonMap mm; std::string keymapString; std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> conv; auto it = priv::key_names_.end(); std::ifstream file; file.open("./config/" + keymap_path); if (file.is_open()) { int pos; std::wstring actionName; std::string keyName; while (std::getline(file, keymapString)) { keymapString.erase(std::remove_if(keymapString.begin(), keymapString.end(), [](char x) { return std::isspace(x); }), keymapString.end()); keymapString.erase(std::remove_if(keymapString.begin(), keymapString.end(), [](char x) { return (x == '"'); }), keymapString.end()); if ((pos = keymapString.find("="), pos) != std::wstring::npos) { actionName = conv.from_bytes(keymapString.substr(0, pos)); keyName = keymapString.substr(pos + 1); if (keyName.find("Key") != std::string::npos) { it = priv::key_names_.find(keyName); if (it != priv::key_names_.end()) km[actionName] = static_cast<sf::Keyboard::Key>(it->second); else km[actionName] = sf::Keyboard::Key::Unknown; } else if (keyName.find("Mouse_Button") != std::string::npos) { it = priv::mouse_names_.find(keyName); if (it != priv::mouse_names_.end()) mm[actionName] = static_cast<sf::Mouse::Button>(it->second); } } } file.close(); } else return; key_map_ = km; mouse_button_map_ = mm; } void Input::updateEvents(sf::Event event) { if (event.type == sf::Event::GainedFocus) has_focus_ = true; else if (event.type == sf::Event::LostFocus) has_focus_ = false; else if (event.type == sf::Event::KeyReleased) { if (was_pressed_map_.count(event.key.code)) { was_pressed_map_[event.key.code] = false; } } else if (event.type == sf::Event::MouseButtonReleased) { if (was_mouse_pressed_map_.count(event.mouseButton.button)) { was_mouse_pressed_map_[event.mouseButton.button] = false; } } else if (event.type == sf::Event::JoystickButtonReleased) { if (was_joy_stick_button_pressed_map_.count(event.joystickButton.button)) { was_joy_stick_button_pressed_map_[event.joystickButton.button] = false; } } else if (text_input_enabled_ && event.type == sf::Event::TextEntered) { if (event.text.unicode == L'\b') { if (entered_text_.length() > 0) entered_text_.erase(entered_text_.end() - 1); } else { #ifdef _WIN32 if (event.text.unicode == L'\x16') //windows Clipboard support! YAY! { if (OpenClipboard(nullptr)) { HANDLE hData = GetClipboardData(CF_TEXT); if (hData != nullptr) { char * pszText = static_cast<char*>(GlobalLock(hData)); if (pszText != nullptr) { std::string text(pszText); entered_text_ += std::wstring(text.begin(), text.end()); std::wcout << entered_text_ << "\n"; } } GlobalUnlock(hData); } CloseClipboard(); } #endif if (event.text.unicode == L'\r' || event.text.unicode == L'\n') { if (!single_line_text_) entered_text_ += L"\n"; } else { if (std::isprint(static_cast<wchar_t>(event.text.unicode))) entered_text_ += static_cast<wchar_t>(event.text.unicode); } } } } bool Input::isKeyPressed(std::wstring key) { if (has_focus_) { if (key_map_.count(key) && !text_input_enabled_ && !ImGui::IsAnyItemActive()) return sf::Keyboard::isKeyPressed(key_map_[key]); if (mouse_button_map_.count(key) && !ImGui::IsMouseHoveringAnyWindow()) return sf::Mouse::isButtonPressed(mouse_button_map_[key]); if (joy_stick_button_map_.count(key)) { if (sf::Joystick::isConnected(0)) //TODO: Overlaod for multiple Players if (sf::Joystick::getButtonCount(0) > joy_stick_button_map_[key]) return sf::Joystick::isButtonPressed(0, joy_stick_button_map_[key]); } } return false; } bool Input::wasKeyPressed(std::wstring key) { if (has_focus_) { if (key_map_.count(key) && !text_input_enabled_ && !ImGui::IsAnyItemActive()) { bool isPressed = sf::Keyboard::isKeyPressed(key_map_[key]); bool wasPressed = was_pressed_map_[key_map_[key]]; if (isPressed && !wasPressed) { was_pressed_map_[key_map_[key]] = true; return true; } } if (mouse_button_map_.count(key) && !ImGui::IsMouseHoveringAnyWindow()) { bool isPressed = sf::Mouse::isButtonPressed(mouse_button_map_[key]); bool wasPressed = was_mouse_pressed_map_[mouse_button_map_[key]]; if (isPressed && !wasPressed) { was_mouse_pressed_map_[mouse_button_map_[key]] = true; return true; } } if (joy_stick_button_map_.count(key)) { if (sf::Joystick::isConnected(0)) //TODO: Overlaod for multiple Players if (sf::Joystick::getButtonCount(0) > joy_stick_button_map_[key]) { bool isPressed = sf::Joystick::isButtonPressed(0, joy_stick_button_map_[key]); bool wasPressed = was_joy_stick_button_pressed_map_[joy_stick_button_map_[key]]; if (isPressed && !wasPressed) { was_joy_stick_button_pressed_map_[joy_stick_button_map_[key]] = true; return true; } } } } return false; } Input::KeyMap Input::getKeyMap() const { return key_map_; } void Input::setTextInput(bool enabled, bool singleLine) { text_input_enabled_ = enabled; single_line_text_ = singleLine; entered_text_ = L""; } std::wstring Input::getEnteredText() const { return entered_text_; } void Input::setEnteredText(std::wstring str) { entered_text_ = str; } }
24.370909
90
0.633542
Alia5
7d2dac22b74d9f442ae84a5f73042b2226741b58
3,457
cc
C++
MassRecoCompare/bin/CompareMethods.cc
NTUHEP-Tstar/TstarAnalysis
d3bcdf6f0fd19b9a34bbacb1052143856917bea7
[ "MIT" ]
null
null
null
MassRecoCompare/bin/CompareMethods.cc
NTUHEP-Tstar/TstarAnalysis
d3bcdf6f0fd19b9a34bbacb1052143856917bea7
[ "MIT" ]
null
null
null
MassRecoCompare/bin/CompareMethods.cc
NTUHEP-Tstar/TstarAnalysis
d3bcdf6f0fd19b9a34bbacb1052143856917bea7
[ "MIT" ]
null
null
null
/******************************************************************************* * * Filename : CompareMethods * Description : Make Plots for Comparision of reconstruction methods * Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ] * *******************************************************************************/ #include "ManagerUtils/SampleMgr/interface/MultiFile.hpp" #include "ManagerUtils/SysUtils/interface/PathUtils.hpp" #include "TstarAnalysis/MassRecoCompare/interface/Common.hpp" #include "TstarAnalysis/MassRecoCompare/interface/CompareHistMgr.hpp" #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <boost/program_options.hpp> #include <iostream> #include <string> #include <vector> #include "TFile.h" using namespace std; namespace opt = boost::program_options; int main( int argc, char* argv[] ) { /******************************************************************************* * Option parsing *******************************************************************************/ opt::options_description desc( "Options for Method comparison" ); desc.add_options() ( "mass,m", opt::value<int>(), "Masspoint to run" ) ( "outputtag,o", opt::value<string>(), "What output string to add" ) ( "compare,x", opt::value<vector<string> >()->multitoken(), "Which reconstruction methods to compare" ) ; reconamer.AddOptions( desc ); reconamer.SetNamingOptions( "mass" ); const int run = reconamer.ParseOptions( argc, argv ); if( run == mgr::OptNamer::PARSE_ERROR ){ return 1; } if( run == mgr::OptNamer::PARSE_HELP ){ return 0; } if( !reconamer.CheckInput( "compare" ) ){ cerr << "Error! No comparison tokens specified!" << endl; return 1; } /******************************************************************************* * Making objects *******************************************************************************/ vector<CompareHistMgr*> complist; for( const auto& tag : reconamer.GetInputList<string>( "compare" ) ){ const string taglatex = reconamer.ExtQuery<string>( "reco", tag, "Root Name" ); complist.push_back( new CompareHistMgr( tag, taglatex ) ); } /******************************************************************************* * Filling from file *******************************************************************************/ boost::format globformat( "/wk_cms2/yichen/TstarAnalysis/EDMStore_New/recocomp/%s/*%d*.root" ); const std::string globq = boost::str( globformat % reconamer.GetInput<string>( "channel" ) % reconamer.GetInput<int>( "mass" ) ); cout << "Opening file(s): " << endl; for( const auto& file : mgr::Glob(globq) ){ cout << "\t> " << file << endl; } mgr::MultiFileEvent myevent( mgr::Glob( globq ) ); boost::format reportformat( "\rAt Event [%u|%u]" ); unsigned i = 0; for( myevent.toBegin(); !myevent.atEnd(); ++myevent, ++i ){ cout << reportformat % i % myevent.size() << flush; for( const auto& mgr : complist ){ mgr->AddEvent( myevent.Base() ); } } cout << "Done" << endl; /******************************************************************************* * Making compare plots *******************************************************************************/ for( const auto& mgr : complist ){ MatchPlot( mgr ); } ComparePlot( reconamer.GetInput<string>( "outputtag" ), complist ); return 0; }
34.919192
107
0.505062
NTUHEP-Tstar
7d2e36069972f82849c757cc5fa65fac9363f7dd
1,283
cpp
C++
msvc/libnature_staticreg.cpp
GarethNelson/ares
fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e
[ "MIT" ]
null
null
null
msvc/libnature_staticreg.cpp
GarethNelson/ares
fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e
[ "MIT" ]
null
null
null
msvc/libnature_staticreg.cpp
GarethNelson/ares
fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e
[ "MIT" ]
null
null
null
// This file is automatically generated. #include "cssysdef.h" #include "csutil/scf.h" // Put static linking stuff into own section. // The idea is that this allows the section to be swapped out but not // swapped in again b/c something else in it was needed. #if !defined(CS_DEBUG) && defined(CS_COMPILER_MSVC) #pragma const_seg(".CSmetai") #pragma comment(linker, "/section:.CSmetai,r") #pragma code_seg(".CSmeta") #pragma comment(linker, "/section:.CSmeta,er") #pragma comment(linker, "/merge:.CSmetai=.CSmeta") #endif namespace csStaticPluginInit { static char const metainfo_nature[] = "<?xml version=\"1.0\"?>" "<!-- nature.csplugin -->" "<plugin>" " <scf>" " <classes>" " <class>" " <name>utility.nature</name>" " <implementation>Nature</implementation>" " <description>Nature Plugin</description>" " </class>" " </classes>" " </scf>" "</plugin>" ; #ifndef Nature_FACTORY_REGISTER_DEFINED #define Nature_FACTORY_REGISTER_DEFINED SCF_DEFINE_FACTORY_FUNC_REGISTRATION(Nature) #endif class nature { SCF_REGISTER_STATIC_LIBRARY(nature,metainfo_nature) #ifndef Nature_FACTORY_REGISTERED #define Nature_FACTORY_REGISTERED Nature_StaticInit Nature_static_init__; #endif public: nature(); }; nature::nature() {} }
25.156863
69
0.708496
GarethNelson
7d3371311b9488a2f769aa811a8b358a23d9da30
7,207
hpp
C++
SW4STM32/ssd1306/SSD1306/Inc/SSD1306.hpp
ironiron/ssd1306-stm32HAL
468d3ae1335cf7f41f3ec703ed3abbfa4bdbb15b
[ "MIT" ]
null
null
null
SW4STM32/ssd1306/SSD1306/Inc/SSD1306.hpp
ironiron/ssd1306-stm32HAL
468d3ae1335cf7f41f3ec703ed3abbfa4bdbb15b
[ "MIT" ]
null
null
null
SW4STM32/ssd1306/SSD1306/Inc/SSD1306.hpp
ironiron/ssd1306-stm32HAL
468d3ae1335cf7f41f3ec703ed3abbfa4bdbb15b
[ "MIT" ]
null
null
null
/** ****************************************************************************** * @file SSD1306.hpp * @author Olivier Van den Eede - ovde.be * @author Rafał Mazurkiewicz * @date 13.08.2019 * @brief Library for OLED display ****************************************************************************** * <h2><center>&copy; * Original work COPYRIGHT (c) 2016 Olivier Van den Eede - ovde.be * Modified w work COPYRIGHT(c) 2019 Rafał Mazurkiewicz * </center></h2> * *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. ******************************************************************************* */ /** * @mainpage * Library for controlling OLED displays based on SSD1306 drivers. * =============================================================== * It Is intended to use with I2C interface * */ ////////////////////// EDITABLE CONTENT ///////////////////// #define USE_STANDARD_HAL #ifdef USE_STANDARD_HAL #include "stm32f1xx_hal.h" #define SSD1306_CONNECTION_INTERFACE I2C_HandleTypeDef #else #include "I2C.hpp" #define SSD1306_CONNECTION_INTERFACE I2C #endif /////////////////////END OF EDITABLE CONTENT//////////////// #ifndef SSD1306_HPP_ #define SSD1306_HPP_ #include <array> #include <stdint.h> #include "fonts.h" /*! @class SSD1306 * @brief This class is controlling display. */ class SSD1306 { public: /// This enum is for setting hardware configuration. Devices from diffrent vendors can have /// OLED segments mapped to different SSD1306 pins. Use ALT_NOREMAP for 128x64, and SEQ_NOREMAP for 128x32. enum HardwareConf : uint8_t { SEQ_NOREMAP = 0x02, SEQ_REMAP = 0x22, ALT_NOREMAP = 0x12, ALT_REMAP = 0x32 }; /// Enum for colors. White means pixel is ON. enum Color : uint8_t { BLACK = 0, WHITE = 0xff }; /**@brief Constructor configure class. If height>64 last error=0xff;. * @param connection_port: I2C class object for HW connection. * @param screen_height: height in pixels. * @param hardware_configuration: Can be a value of SSD1306::HardwareConf. * @param device_address: address of device on I2C line. usually 0x78 is OK. */ SSD1306 (SSD1306_CONNECTION_INTERFACE *connection_port, const uint8_t screen_height, HardwareConf hardware_configuration = ALT_NOREMAP, uint8_t device_address = 0x78) : conn (connection_port), height (screen_height), hard_conf ( hardware_configuration), address (device_address) { if (screen_height > 64) { last_error = 0xff; } } /**@brief Initialize device, cleans display * @retval True if initialized without errors. */ bool Initialize (void); /**@brief Initialize device, cleans display * @warning This function have to be called to refresh screen with new data */ void Update_Screen (void); /**@brief cleans display */ void Clean (void); /**@brief Fill whole display with one color (turn on or off pixels) * @param color: Black means display is OFF. */ void Fill (SSD1306::Color color); /**@brief set cursor to given coordinates * @param x: X Coordinate * @param y: Y Coordinate */ void Set_Cursor (uint8_t x, uint8_t y); /**@brief Writes normal string at coordinates set in SSD1306::Set_Cursor. * @param str: string to be written */ void Write_String (char const * str); /**@brief Similar function to Write_String but fills the background with color. * @param str: string to be written */ void Write_String_Inverted (char const *str); /**@brief Turns ON single pixel at given coordinate. * @param x: X Coordinate * @param y: Y Coordinate * @param c: Color to draw */ void Draw_Pixel (uint8_t x, uint8_t y, SSD1306::Color c); /**@brief Copy Image to internal buffer. * @param image: array of size 128*64=1024(buffer_size) containing image */ void Draw_Image (const uint8_t *image); /**@brief Put displays in Sleep mode. */ void Display_Off (void); /**@brief Wake up display. */ void Display_On (void); /**@brief Sets brightness of display. * @param brightness: brightness- 0xff means full lit. */ void Set_Brightness (uint8_t brightness); /**@brief Function for inverting colors. * @param inverted: TRUE- colors are inverted. */ void Invert_Colors (bool inverted); /**@brief Function for flip upside down display. * @param flipped: TRUE- display is flipped. */ void Flip_Screen (bool flipped); /**@brief Function for mirroring (left- right) display. * @param mirrored: TRUE- display is mirrored. */ void Mirror_Screen (bool mirrored); /**@brief Sets size of font. * @param font: Can be a value of Fonts::FontDef. */ void Set_Font_size (Fonts::FontDef font); /**@brief Informs if device is initialized * @retval True if initialized without errors. */ bool IsInitialized (void) const; /**@brief Returns error of I2C interface * @retval 0 if none error occured since last SSD1306::Clean_Errors call. */ int Get_Last_Error (void) const; /**@brief Clean errors */ void Clean_Errors (void); private: SSD1306_CONNECTION_INTERFACE *conn; const uint8_t height; const uint8_t width = 128; const uint8_t hard_conf; const uint8_t address; Fonts::FontDef font = Fonts::font_7x10; ///<font size const static uint32_t buffer_size = 64 / 8 * 128; ///< size of internal buffer. Can be lower if used ONLY with 128x32 std::array<uint8_t, buffer_size> buffer; ///<internal buffer used for displaying data bool isinitialized = false; int last_error = 0; int temp = 0; const uint8_t control_b_command = 0x00; ///<required for I2C communication const uint8_t control_b_data = 0x40; ///<required for I2C communication struct { uint8_t X; uint8_t Y; } Coordinates; /**@brief HW related sends command thru I2C interface. * @param command: byte to send. */ void Write_Command (uint8_t command); /**@brief HW related sends command thru I2C interface. * @param data: byte array size of SSD1306::buffer_size to send. */ void Write_Data (std::array<uint8_t, buffer_size> &data); void Write_Char (char str, SSD1306::Color color); }; #endif /* SSD1306_HPP_ */
30.668085
119
0.669488
ironiron
7d39cb3dcb628c85a33d22af45d7af4c0ab1af99
957
cpp
C++
cpp/11reference.cpp
yaswanthsaivendra/CP
742ba2f89180f79837fb8b32ce43df215f7b7fa1
[ "MIT" ]
null
null
null
cpp/11reference.cpp
yaswanthsaivendra/CP
742ba2f89180f79837fb8b32ce43df215f7b7fa1
[ "MIT" ]
null
null
null
cpp/11reference.cpp
yaswanthsaivendra/CP
742ba2f89180f79837fb8b32ce43df215f7b7fa1
[ "MIT" ]
null
null
null
// //Reference variables // //these can be used to call a single variable with different names. // //reference is a alias of variable // //it must be intialised when declared. // //it cannot be modified to refer other variable. // #include<iostream> // using namespace std; // int main(){ // int x = 45; // int &y = x; //here y points to the same variable. // //here y is not consuming any extra memory, here we are using the two different names for a single variable. // cout << x << endl; // cout << y << endl; // return 0; // } #include<bits/stdc++.h> using namespace std; int func(int arr1[], int n){ for (int i = 0; i <n; i++) { cout << ++arr1[i]; } return 0; } int main(){ ios::sync_with_stdio(0); cin.tie(0); int n=10; int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; func(arr, n); for (int i = 0; i < n; i++) { cout << arr[i]<<""; } return 0; }
20.361702
115
0.547544
yaswanthsaivendra
7d3ecf4e7084f243e00b9e9e2addab111d3b09b0
6,019
cpp
C++
Saturn/src/Saturn/Vulkan/VulkanDebugMessenger.cpp
BEASTSM96/Sparky-Engine
234afce5572a1b0240cb8b59d0b25a9259c5572a
[ "MIT" ]
null
null
null
Saturn/src/Saturn/Vulkan/VulkanDebugMessenger.cpp
BEASTSM96/Sparky-Engine
234afce5572a1b0240cb8b59d0b25a9259c5572a
[ "MIT" ]
3
2020-08-14T17:09:06.000Z
2020-08-14T17:10:10.000Z
Saturn/src/Saturn/Vulkan/VulkanDebugMessenger.cpp
BEASTSM96/Sparky-Engine
234afce5572a1b0240cb8b59d0b25a9259c5572a
[ "MIT" ]
null
null
null
/******************************************************************************************** * * * * * * * MIT License * * * * Copyright (c) 2020 - 2022 BEAST * * * * 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 "sppch.h" #include "VulkanDebugMessenger.h" // Vulkan Message callback static VKAPI_ATTR VkBool32 VKAPI_CALL vkDebugCB( VkDebugUtilsMessageSeverityFlagBitsEXT MessageSeverity, VkDebugUtilsMessageTypeFlagsEXT MessageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData ) { if( MessageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT ) SAT_CORE_ERROR( "{0}", pCallbackData->pMessage ); else if( MessageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT ) SAT_CORE_WARN( "{0}", pCallbackData->pMessage ); return VK_FALSE; } namespace Saturn { VulkanDebugMessenger::VulkanDebugMessenger( VkInstance& rInstance ) { VkDebugUtilsMessengerCreateInfoEXT CreateInfo; CreateDebugMessengerInfo( &CreateInfo ); _intrl_vkCreateDebugUtilsMessenger( rInstance, &CreateInfo, nullptr, &m_DebugMessenger ); } VulkanDebugMessenger::~VulkanDebugMessenger() { _intrl_vkDestroyDebugUtilsMessenger( VulkanContext::Get().GetInstance(), m_DebugMessenger, nullptr ); } void VulkanDebugMessenger::CreateDebugMessengerInfo( VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo ) { VkDebugUtilsMessengerCreateInfoEXT TempCreateInfo ={ VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT }; TempCreateInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; TempCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; TempCreateInfo.pfnUserCallback = vkDebugCB; TempCreateInfo.pUserData = nullptr; *pCreateInfo = TempCreateInfo; } VkResult VulkanDebugMessenger::_intrl_vkCreateDebugUtilsMessenger( VkInstance Instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger ) { // Find and load the "vkCreateDebugUtilsMessengerEXT" function ptr. auto func = ( PFN_vkCreateDebugUtilsMessengerEXT )vkGetInstanceProcAddr( Instance, "vkCreateDebugUtilsMessengerEXT" ); if( func != nullptr ) { // Call vkCreateDebugUtilsMessengerEXT return func( Instance, pCreateInfo, pAllocator, pDebugMessenger ); } else return VK_ERROR_EXTENSION_NOT_PRESENT; } void VulkanDebugMessenger::_intrl_vkDestroyDebugUtilsMessenger( VkInstance Instance, VkDebugUtilsMessengerEXT DebugMessenger, const VkAllocationCallbacks* pAllocator ) { auto func = ( PFN_vkDestroyDebugUtilsMessengerEXT )vkGetInstanceProcAddr( Instance, "vkDestroyDebugUtilsMessengerEXT" ); if( func ) { func( Instance, DebugMessenger, pAllocator ); } } ////////////////////////////////////////////////////////////////////////// void Helpers::CreateDebugMessengerInfo( VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo ) { VkDebugUtilsMessengerCreateInfoEXT TempCreateInfo ={ VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT }; TempCreateInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; TempCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; TempCreateInfo.pfnUserCallback = vkDebugCB; TempCreateInfo.pUserData = nullptr; *pCreateInfo = TempCreateInfo; } }
53.265487
228
0.617212
BEASTSM96
7d481e65c34703fb68f36e222813ad37fc593bb3
462
cpp
C++
src/Replacement.cpp
lingnand/Helium
d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816
[ "BSD-3-Clause" ]
8
2021-04-16T02:05:54.000Z
2022-03-16T13:56:23.000Z
src/Replacement.cpp
lingnand/Helium
d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816
[ "BSD-3-Clause" ]
null
null
null
src/Replacement.cpp
lingnand/Helium
d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816
[ "BSD-3-Clause" ]
2
2021-04-17T10:49:58.000Z
2021-07-21T20:39:52.000Z
/* * * Created on: Apr 4, 2015 * Author: lingnan */ #include <Replacement.h> QDebug operator<<(QDebug dbg, const TextSelection &selection) { dbg.nospace() << "TextSelection(" << selection.start << "," << selection.end << ")"; return dbg.space(); } QDebug operator<<(QDebug dbg, const Replacement &replacement) { dbg.nospace() << "Replacement(" << replacement.selection << ", " << replacement.replacement << ")"; return dbg.space(); }
24.315789
103
0.625541
lingnand
7d4ca9c1801db5e3ca43836a69097d892f41dc28
3,973
cpp
C++
Lab4/RSA.cpp
Gnomus042/crypto
eaea809886c99234484170376c8c20bf11436807
[ "MIT" ]
null
null
null
Lab4/RSA.cpp
Gnomus042/crypto
eaea809886c99234484170376c8c20bf11436807
[ "MIT" ]
null
null
null
Lab4/RSA.cpp
Gnomus042/crypto
eaea809886c99234484170376c8c20bf11436807
[ "MIT" ]
null
null
null
// // Created by anast on 11/14/2020. // #include <cassert> #include "RSA.h" #include "../Lab3/Kupyna.h" #include "../Lab3/SHA256.h" const int RSA_SIZE = 1024; pair<Key, Key> RSA::keygen(int prime_size) { std::cout << "Generating primes" << std::endl; BigInt p = get_prime(prime_size); std::cout << "Prime p generated." << std::endl; BigInt q = get_prime(prime_size); std::cout << "Prime q generated." << std::endl; BigInt N = p * q; BigInt phi = (p - 1) * (q - 1); BigInt e = BigInt::rand(BigInt::pow(2, RSA_SIZE - 1), BigInt::pow(2, RSA_SIZE)); while (BigInt::gcd(e, phi) != 1) e = BigInt::rand(BigInt::pow(2, RSA_SIZE - 1), BigInt::pow(2, RSA_SIZE)); BigInt d = BigInt::inverseModulo(e, phi); Key pk = {N, e}; Key sk = {N, d}; return {pk, sk}; } BigInt RSA::get_prime(int prime_size) { BigInt x = BigInt::rand(BigInt::pow(2, prime_size - 1), BigInt::pow(2, prime_size)); if (x % 2 == 0) x += 1; while (!MillerRabin::test(x, 10)) { x += 2; } return x; } vector<uint8_t> RSA::encrypt(const vector<uint8_t> &m, const Key &pk) { vector<uint8_t> encrypted = BigInt::mpow(m, pk.val, pk.mod).tou8(); while(encrypted.size() < m.size()) encrypted.push_back(0); return encrypted; } vector<uint8_t> RSA::decrypt(const vector<uint8_t> &c, const Key &sk) { return BigInt::mpow(c, sk.val, sk.mod).tou8(); } vector<uint8_t> hashG(const vector<uint8_t> m, int size) { vector<uint8_t> res; vector<uint8_t> hashm = SHA256::hash(m); res.insert(res.end(), hashm.begin(), hashm.end()); res.insert(res.end(), hashm.begin(), hashm.end()); res.insert(res.end(), hashm.begin(), hashm.end()); res.insert(res.end(), hashm.begin(), hashm.end()); res.resize(size); return res; } vector<uint8_t> RSA::decrypt_oaep(const vector<uint8_t> &m, const Key &sk, int block_size) { int k0 = 32; int k1 = 32; Kupyna kupyna(256); vector<uint8_t> mes = m; vector<uint8_t> res; for (int k = 0; k < mes.size() / block_size / 2; k++) { vector<uint8_t> block(mes.begin() + k * block_size * 2, mes.begin() + (k + 1) * block_size * 2); block = RSA::decrypt(block, sk); while (block.size() < block_size) block.push_back(0); vector<uint8_t> Y(block.end()-k0, block.end()); vector<uint8_t> X(block.begin(), block.end()-k0); vector<uint8_t> HX = kupyna.hash(X); vector<uint8_t> r = Y; assert(r.size() == HX.size()); for (int i = 0; i < r.size(); i++) r[i] = r[i] ^ HX[i]; vector<uint8_t> Gr = hashG(r, block_size-k0); assert(Gr.size() == X.size()); for (int i = 0; i < r.size(); i++) Gr[i] = Gr[i] ^ X[i]; res.insert(res.end(), Gr.begin(), Gr.end()-k1); } return res; } vector<uint8_t> RSA::encrypt_oaep(const vector<uint8_t> &m, const Key &pk, int block_size) { int k0 = 32; int k1 = 32; vector<uint8_t> mes = m; while (mes.size() % (block_size-k0-k1) != 0) { mes.push_back(0); } vector<uint8_t> c; Kupyna kupyna(256); for (int k = 0; k < mes.size() / (block_size-k0-k1); k++) { vector<uint8_t> r(k0); vector<uint8_t> block(mes.begin() + k * (block_size-k0-k1), mes.begin() + (k + 1) * (block_size-k0-k1)); for (int i = 0; i < k1; i++) block.push_back(0); for (int i = 0; i < k0; i++) r[i] = rand() % 256; vector<uint8_t> Gr = hashG(r, block_size-k0); vector<uint8_t> X = block; assert(X.size() == Gr.size()); for (int i = 0; i < Gr.size(); i++) X[i] = X[i] ^ Gr[i]; vector<uint8_t> HX = kupyna.hash(X); vector<uint8_t> Y = r; assert(Y.size() == HX.size()); for (int i = 0; i < Y.size(); i++) Y[i] = Y[i] ^ HX[i]; X.insert(X.end(), Y.begin(), Y.end()); vector<uint8_t> encrypted = RSA::encrypt(X, pk); c.insert(c.cend(), encrypted.begin(), encrypted.end()); } return c; }
35.792793
112
0.559779
Gnomus042
7d503e73c944bffbffb3a94b31da9a2ec2a3a98a
6,968
cpp
C++
sources/Database.cpp
eubrunomiguel/garuna
e18d54213b561fbc7075eaf2acb131b2084a6434
[ "MIT" ]
57
2018-05-16T17:04:01.000Z
2022-03-22T00:18:42.000Z
sources/Database.cpp
eubrunomiguel/garuna
e18d54213b561fbc7075eaf2acb131b2084a6434
[ "MIT" ]
null
null
null
sources/Database.cpp
eubrunomiguel/garuna
e18d54213b561fbc7075eaf2acb131b2084a6434
[ "MIT" ]
17
2019-01-25T04:04:59.000Z
2022-03-13T11:54:08.000Z
// // Database.cpp // server // // Created by Bruno Macedo Miguel on 3/23/17. // Copyright © 2017 d2server. All rights reserved. // #include "Database.hpp" uint8_t DatabaseIO::numinstantiated = 0; bool DatabaseIO::loadPlayer(const uint32_t& databaseid, Player& player) { if (players_cache.count(databaseid) == 1) { Player* cache_player = &players_cache[databaseid]; if (!cache_player->isConnected()){ cache_player->connect(); player = *cache_player; std::cerr << "Loaded player " << player.getPlayerBody().getName() << " from cache." << std::endl; return true; } else { std::cerr << "Player " << player.getPlayerBody().getName() << " is already connected." << std::endl; return false; } } std::string query = "SELECT * FROM players WHERE account_id = " + std::to_string(databaseid); int state = mysql_query(connection, query.c_str()); if (state !=0) { std::cout << mysql_error(connection) << std::endl; return false; } result = mysql_store_result(connection); if (mysql_num_rows(result) == 0) { std::cerr << "Player from account " << databaseid << " not found." << std::endl; return false; } if (mysql_num_rows(result) > 1) { std::cerr << "More than one player occurence for database " << databaseid << "." << std::endl; return false; } while ( ( row=mysql_fetch_row(result)) != NULL ) { Player newplayer; newplayer.load(databaseid, OnlineStatus::ONLINE); Body& newplayerBody = newplayer.getPlayerBody(); newplayerBody.setName(row[1]); newplayerBody.setLevel(std::atoi(row[2])); newplayerBody.setExperience(std::atoi(row[3])); newplayerBody.setHealth(std::atoi(row[4])); newplayerBody.setMaxHealth(std::atoi(row[5])); newplayerBody.setStamina(std::atoi(row[6])); newplayerBody.setMaxStamina(std::atoi(row[7])); newplayerBody.setAttack(std::atoi(row[8])); newplayerBody.setArmor(std::atoi(row[9])); newplayerBody.setDefense(std::atoi(row[10])); newplayerBody.setSpeed(std::atoi(row[11])); newplayerBody.setBodyColor(static_cast<BodyColor>(std::atoi(row[12]))); players_cache.insert(std::make_pair(databaseid, newplayer)); player = newplayer; std::cerr << "Loaded player " << player.getPlayerBody().getName() << " from database." << std::endl; return true; } mysql_free_result(result); return false; } bool DatabaseIO::loadAccount(const uint32_t& databaseid, const uint32_t password, Account& account) { if (accounts_cache.count(databaseid) == 1) { Account* cache_account = &accounts_cache[databaseid]; if (cache_account->getPassword() == password && !cache_account->isConnected()){ cache_account->connect(); account = *cache_account;; std::cerr << "Loaded account " << account.getAccountID() << " from cache." << std::endl; return true; } else { if (cache_account->getPassword() != password) std::cerr << "Password incorrect" << std::endl; if (cache_account->isConnected()) std::cerr << "Account already connected" << std::endl; return false; } } std::string query = "SELECT * FROM accounts WHERE id = " + std::to_string(databaseid) + " and password = " + std::to_string(password); int state = mysql_query(connection, query.c_str()); if (state !=0) { std::cout << mysql_error(connection) << std::endl; return false; } result = mysql_store_result(connection); if (mysql_num_rows(result) == 0) { std::cerr << "Account " << databaseid << " not found, or password incorrect " << password << "." << std::endl; return false; } if (mysql_num_rows(result) > 1) { std::cerr << "More than one account occurence [" << databaseid << "]." << std::endl; return false; } while ( ( row=mysql_fetch_row(result)) != NULL ) { Account newaccount; newaccount.load(databaseid, password, std::atoi(row[2]), OnlineStatus::ONLINE); accounts_cache.insert(std::make_pair(databaseid, newaccount)); account = newaccount; std::cerr << "Loaded account " << account.getAccountID() << " from database." << std::endl; return true; } mysql_free_result(result); return false; } bool DatabaseIO::save(const Account& account) { if (accounts_cache.count(account.getAccountID()) == 1) accounts_cache[account.getAccountID()] = account; std::string query = "UPDATE `accounts` SET `id`= " + std::to_string(account.getAccountID()) + ",`password`= " + std::to_string(account.getPassword()) + ",`premium_days`= " + std::to_string(account.getPremiumDays()) + " WHERE id = " + std::to_string(account.getAccountID()); int state = mysql_query(connection, query.c_str()); if (state !=0) { std::cout << mysql_error(connection) << std::endl; return false; } std::cerr << "Account " << account.getAccountID() << " saved!" << std::endl; return true; } bool DatabaseIO::save(const Player& player) { if (players_cache.count(player.getAccountID()) == 1) players_cache[player.getAccountID()] = player; const Body& body = player.getPlayerBody(); std::string query = "UPDATE `players` SET "; query += "`name`='" + body.getName() + "',"; query += "`level`='" + std::to_string(body.getLevel()) + "',"; query += "`experience`='" + std::to_string(body.getExperience()) + "',"; query += "`health`='" + std::to_string(body.getHealth()) + "',"; query += "`max_health`='" + std::to_string(body.getMaxHealth()) + "',"; query += "`stamina`='" + std::to_string(body.getStamina()) + "',"; query += "`max_stamina`='" + std::to_string(body.getMaxStamina()) + "',"; query += "`attack`='" + std::to_string(body.getAttack()) + "',"; query += "`armor`='" + std::to_string(body.getArmor()) + "',"; query += "`defense`='" + std::to_string(body.getDefense()) + "',"; query += "`movement`='" + std::to_string(body.getMovementSpeed()) + "',"; query += "`body_color`='" + std::to_string(static_cast<int>(body.getBodyColor())) + "'"; query += " WHERE account_id = " + std::to_string(player.getAccountID()); int state = mysql_query(connection, query.c_str()); if (state !=0) { std::cout << mysql_error(connection) << std::endl; return false; } std::cerr << "Player " << body.getName() << " saved!" << std::endl; return true; }
34.156863
278
0.575918
eubrunomiguel
7d53dc2aa3fc66807c88a01077ede4b0ada3f338
3,741
cc
C++
shell/platform/darwin/common/platform_service_provider.cc
smallZh/flutter_engine
166f44c0f7a84f221df8af66637e3672edbf143c
[ "BSD-3-Clause" ]
1
2021-06-12T00:46:41.000Z
2021-06-12T00:46:41.000Z
shell/platform/darwin/common/platform_service_provider.cc
smallZh/flutter_engine
166f44c0f7a84f221df8af66637e3672edbf143c
[ "BSD-3-Clause" ]
null
null
null
shell/platform/darwin/common/platform_service_provider.cc
smallZh/flutter_engine
166f44c0f7a84f221df8af66637e3672edbf143c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/darwin/common/platform_service_provider.h" #if TARGET_OS_IPHONE #include "flutter/services/activity/ios/activity_impl.h" #include "flutter/services/editing/ios/clipboard_impl.h" #include "flutter/services/media/ios/media_player_impl.h" #include "flutter/services/media/ios/media_service_impl.h" #include "flutter/services/platform/ios/haptic_feedback_impl.h" #include "flutter/services/platform/ios/path_provider_impl.h" #include "flutter/services/platform/ios/system_chrome_impl.h" #include "flutter/services/platform/ios/system_sound_impl.h" #include "flutter/services/platform/ios/url_launcher_impl.h" #include "flutter/services/vsync/ios/vsync_provider_ios_impl.h" #else #include "flutter/services/vsync/mac/vsync_provider_mac_impl.h" #endif // TARGET_OS_IPHONE namespace shell { PlatformServiceProvider::PlatformServiceProvider( mojo::InterfaceRequest<mojo::ServiceProvider> request) : binding_(this, request.Pass()) {} PlatformServiceProvider::~PlatformServiceProvider() {} void PlatformServiceProvider::ConnectToService( const mojo::String& service_name, mojo::ScopedMessagePipeHandle client_handle) { #if TARGET_OS_IPHONE if (service_name == ::media::MediaPlayer::Name_) { new sky::services::media::MediaPlayerImpl( mojo::InterfaceRequest<::media::MediaPlayer>(client_handle.Pass())); return; } if (service_name == ::media::MediaService::Name_) { new sky::services::media::MediaServiceImpl( mojo::InterfaceRequest<::media::MediaService>(client_handle.Pass())); return; } if (service_name == ::activity::Activity::Name_) { new sky::services::activity::ActivityImpl( mojo::InterfaceRequest<::activity::Activity>(client_handle.Pass())); return; } if (service_name == ::editing::Clipboard::Name_) { new sky::services::editing::ClipboardImpl( mojo::InterfaceRequest<::editing::Clipboard>(client_handle.Pass())); return; } if (service_name == flutter::platform::HapticFeedback::Name_) { new flutter::platform::HapticFeedbackImpl( mojo::InterfaceRequest<flutter::platform::HapticFeedback>( client_handle.Pass())); return; } if (service_name == flutter::platform::PathProvider::Name_) { new flutter::platform::PathProviderImpl( mojo::InterfaceRequest<flutter::platform::PathProvider>( client_handle.Pass())); return; } if (service_name == flutter::platform::SystemChrome::Name_) { new flutter::platform::SystemChromeImpl( mojo::InterfaceRequest<flutter::platform::SystemChrome>( client_handle.Pass())); return; } if (service_name == flutter::platform::SystemSound::Name_) { new flutter::platform::SystemSoundImpl( mojo::InterfaceRequest<flutter::platform::SystemSound>( client_handle.Pass())); return; } if (service_name == flutter::platform::URLLauncher::Name_) { new flutter::platform::URLLauncherImpl( mojo::InterfaceRequest<flutter::platform::URLLauncher>( client_handle.Pass())); return; } if (service_name == ::vsync::VSyncProvider::Name_) { new sky::services::vsync::VsyncProviderIOSImpl( mojo::InterfaceRequest<::vsync::VSyncProvider>(client_handle.Pass())); return; } #else // TARGET_OS_IPHONE if (service_name == ::vsync::VSyncProvider::Name_) { new sky::services::vsync::VsyncProviderMacImpl( mojo::InterfaceRequest<::vsync::VSyncProvider>(client_handle.Pass())); return; } #endif // TARGET_OS_IPHONE } } // namespace shell
37.787879
78
0.718792
smallZh
7d563fd3e8a01543274231520fe053ab68adfddc
1,030
cpp
C++
core/src/core/algebra/util.cpp
fionser/CODA
db234a1e9761d379fb96ae17eef3b77254f8781c
[ "MIT" ]
12
2017-02-24T19:28:07.000Z
2021-02-05T04:40:47.000Z
core/src/core/algebra/util.cpp
fionser/CODA
db234a1e9761d379fb96ae17eef3b77254f8781c
[ "MIT" ]
1
2017-04-15T03:41:18.000Z
2017-04-24T09:06:15.000Z
core/src/core/algebra/util.cpp
fionser/CODA
db234a1e9761d379fb96ae17eef3b77254f8781c
[ "MIT" ]
6
2017-05-14T10:12:50.000Z
2021-02-07T03:50:56.000Z
// // Created by Lu WJ on 14/02/2017. // #include "core/algebra/util.hpp" #include <cassert> namespace algebra { NTL::ZZ _InvMod(NTL::ZZ a, NTL::ZZ p) { NTL::ZZ p0(p), t, q; NTL::ZZ x0(0), x1(1); if (p == 1) return NTL::to_ZZ(1); while (a > 1) { q = a / p; t = p; p = a % p; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += p0; return x1; } NTL::ZZ apply_crt(const std::vector<NTL::ZZ> &alphas, const std::vector<NTL::ZZ> &primes, const bool negate) { NTL::ZZ product(1), sum(0); size_t size = alphas.size(); assert(size <= primes.size()); for (auto &prime : primes) { product *= prime; } NTL::ZZ half = product >> 1; for (size_t i = 0; i < size; i++) { NTL::ZZ p = product / primes[i]; sum += (alphas[i] * _InvMod(p, primes[i]) * p); } NTL::ZZ ret = sum % product; if (negate) return ret > half ? ret - product : ret; else return ret; } }
22.391304
55
0.485437
fionser
7d5e138701f9720ebfbba9b72a8051a9d1e89eb5
5,639
cpp
C++
src/model/AddressBookModel.cpp
Midar/feather
ac9693077c338527a4b31ca6b2d85514f8fe739a
[ "BSD-3-Clause" ]
22
2022-02-03T16:22:35.000Z
2022-03-27T14:06:38.000Z
src/model/AddressBookModel.cpp
Midar/feather
ac9693077c338527a4b31ca6b2d85514f8fe739a
[ "BSD-3-Clause" ]
9
2022-02-11T06:23:59.000Z
2022-03-25T03:42:02.000Z
src/model/AddressBookModel.cpp
Midar/feather
ac9693077c338527a4b31ca6b2d85514f8fe739a
[ "BSD-3-Clause" ]
8
2022-02-06T06:57:49.000Z
2022-03-24T11:58:30.000Z
// SPDX-License-Identifier: BSD-3-Clause // SPDX-FileCopyrightText: 2014-2022 The Monero Project #include "AddressBookModel.h" #include "AddressBook.h" #include "ModelUtils.h" #include "utils/Utils.h" #include "utils/Icons.h" AddressBookModel::AddressBookModel(QObject *parent, AddressBook *addressBook) : QAbstractTableModel(parent) , m_addressBook(addressBook) , m_showFullAddresses(false) { connect(m_addressBook, &AddressBook::refreshStarted, this, &AddressBookModel::startReset); connect(m_addressBook, &AddressBook::refreshFinished, this, &AddressBookModel::endReset); m_contactIcon = icons()->icon("person.svg"); } void AddressBookModel::startReset(){ beginResetModel(); } void AddressBookModel::endReset(){ endResetModel(); } int AddressBookModel::rowCount(const QModelIndex &) const { return m_addressBook->count(); } int AddressBookModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) { return 0; } return COUNT; } bool AddressBookModel::isShowFullAddresses() const { return m_showFullAddresses; } void AddressBookModel::setShowFullAddresses(bool show) { m_showFullAddresses = show; emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1)); } bool AddressBookModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && role == Qt::EditRole) { const int row = index.row(); switch (index.column()) { case Description: m_addressBook->setDescription(row, value.toString()); break; default: return false; } emit dataChanged(index, index, {Qt::DisplayRole, Qt::EditRole}); return true; } return false; } QVariant AddressBookModel::data(const QModelIndex &index, int role) const { QVariant result; bool found = m_addressBook->getRow(index.row(), [this, &result, &role, &index](const AddressBookInfo &row) { if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole) { switch (index.column()) { case Address: { QString address = row.address(); if (!m_showFullAddresses && role != Qt::UserRole) { address = ModelUtils::displayAddress(address); } result = address; break; } case Description: result = row.description(); break; default: qCritical() << "Invalid column" << index.column(); } } else if (role == Qt::FontRole) { switch (index.column()) { case Address: result = ModelUtils::getMonospaceFont(); } } else if (role == Qt::DecorationRole) { switch (index.column()) { case Description: { return QVariant(m_contactIcon); // @TODO: does not actually work } default: { return QVariant(); } } } return QVariant(); }); if (!found) { qCritical("%s: internal error: invalid index %d", __FUNCTION__, index.row()); } return result; } Qt::ItemFlags AddressBookModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::ItemIsEnabled; if (index.column() == Description) return QAbstractTableModel::flags(index) | Qt::ItemIsEditable; return QAbstractTableModel::flags(index); } QVariant AddressBookModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) { return QVariant(); } if (orientation == Qt::Horizontal) { switch(section) { case Address: return QString("Address"); case Description: return QString("Name"); default: return QVariant(); } } return QVariant(); } bool AddressBookModel::deleteRow(int row) { return m_addressBook->deleteRow(row); } bool AddressBookModel::writeCSV(const QString &path) { QString csv = ""; for(int i = 0; i < this->rowCount(); i++) { QModelIndex index = this->index(i, 0); const auto description = this->data(index.siblingAtColumn(AddressBookModel::Description), Qt::UserRole).toString().replace("\"", ""); const auto address = this->data(index.siblingAtColumn(AddressBookModel::Address), Qt::UserRole).toString(); if(address.isEmpty()) continue; csv += QString("%1,\"%2\"\n").arg(address).arg(description); } if(csv.isEmpty()) return false; csv = QString("address,description\n%1").arg(csv); return Utils::fileWrite(path, csv); } QMap<QString, QString> AddressBookModel::readCSV(const QString &path) { if(!Utils::fileExists(path)) { return QMap<QString, QString>(); } QString csv = Utils::barrayToString(Utils::fileOpen(path)); QTextStream stream(&csv); QMap<QString, QString> map; while(!stream.atEnd()) { QStringList line = stream.readLine().split(","); if(line.length() != 2) { continue; } QString address = line.at(0); QString description = line.at(1); description = description.replace("\"", ""); if(!description.isEmpty() && !address.isEmpty()) { map[description] = address; } } return map; }
29.678947
141
0.583259
Midar
7d5e35ce46eb1eb3b51c53e4a32e23080707f448
2,199
cc
C++
vision/fiducial_detection_balsaq.cc
sentree/hover-jet
7c0f03e57ecfd07a7a167b3ae509700fb48b8764
[ "MIT" ]
null
null
null
vision/fiducial_detection_balsaq.cc
sentree/hover-jet
7c0f03e57ecfd07a7a167b3ae509700fb48b8764
[ "MIT" ]
null
null
null
vision/fiducial_detection_balsaq.cc
sentree/hover-jet
7c0f03e57ecfd07a7a167b3ae509700fb48b8764
[ "MIT" ]
null
null
null
//%bin(fiducial_detection_balsaq_main) //%deps(balsa_queue) #include "vision/fiducial_detection_balsaq.hh" #include "camera/camera_image_message.hh" #include "config/fiducial_map/read_fiducial_map.hh" #include "infrastructure/balsa_queue/bq_main_macro.hh" #include "infrastructure/comms/mqtt_comms_factory.hh" #include "infrastructure/time/duration.hh" #include <iostream> namespace jet { void FidicualDetectionBq::init(const Config& config) { subscriber_ = make_subscriber("camera_image_channel"); publisher_ = make_publisher("fiducial_detection_channel"); } void FidicualDetectionBq::loop() { CameraImageMessage image_message; // Wait until we have the latest image_message bool got_msg = false; while (subscriber_->read(image_message, 1)) { got_msg = true; } if (got_msg) { gonogo().go(); last_msg_recvd_timestamp_ = get_current_time(); const Calibration camera_calibration = camera_manager_.get_calibration(image_message.camera_serial_number); const cv::Mat camera_frame = get_image_mat(image_message); std::optional<FiducialDetectionMessage> detection_message = create_fiducial_detection_message(camera_frame, camera_calibration, image_message.header.timestamp_ns); if (detection_message) { publisher_->publish(*detection_message); } // The third and fourth parameters are the marker length and the marker separation // respectively. They can be provided in any unit, having in mind that the estimated // pose for this board will be measured in the same units (in general, meters are // used). if (OPEN_DEBUG_WINDOWS) { cv::Mat board_image; get_aruco_board()->draw(cv::Size(900, 900), board_image, 50, 1); cv::imshow("board image", board_image); cv::waitKey(1); cv::imshow("camera image", camera_frame); cv::waitKey(1); } } if (last_msg_recvd_timestamp_ < get_current_time() - Duration::from_seconds(1)) { gonogo().nogo("More than 1 second since last image message"); } } void FidicualDetectionBq::shutdown() { std::cout << "fiducal detection BQ shutting down." << std::endl; } } // namespace jet BALSA_QUEUE_MAIN_FUNCTION(jet::FidicualDetectionBq)
34.359375
111
0.738518
sentree
7d6720b2ea7aa3c176dc47f30f94a7dcb720e4b1
31,757
cpp
C++
FastImplementation-BilateralFilter/color.cpp
yoshihiromaed/FastImplementation-BilateralFilter
d81d0cec1ef2304dfa12297c63b59357def04d0f
[ "MIT" ]
16
2018-10-25T11:51:46.000Z
2021-08-02T08:09:34.000Z
FastImplementation-BilateralFilter/color.cpp
yoshihiromaed/FastImplementation-BilateralFilter
d81d0cec1ef2304dfa12297c63b59357def04d0f
[ "MIT" ]
null
null
null
FastImplementation-BilateralFilter/color.cpp
yoshihiromaed/FastImplementation-BilateralFilter
d81d0cec1ef2304dfa12297c63b59357def04d0f
[ "MIT" ]
3
2018-10-25T12:48:33.000Z
2019-09-09T10:08:45.000Z
#include "color.h" #pragma warning(disable:4309) using namespace std; using namespace cv; void mergeLineInterleaveBGRAVX_8u(const Mat& src, Mat& dest) { const int sstep = src.cols * 3; const int dstep = dest.cols * 3; const uchar* bptr = src.ptr<uchar>(0); const uchar* gptr = src.ptr<uchar>(1); const uchar* rptr = src.ptr<uchar>(2); uchar* dptr = dest.ptr<uchar>(0); static const __m256i mask1 = _mm256_set_epi8(5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11, 0); static const __m256i mask2 = _mm256_set_epi8(10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11, 0, 5); static const __m256i mask3 = _mm256_set_epi8(15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11, 0, 5, 10); static const __m256i bmask1 = _mm256_set_epi8 (255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0); static const __m256i bmask2 = _mm256_set_epi8 (255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255); __m256i a, b, c; for (int j = 0; j < dest.rows; j++) { for (int i = 0; i < dest.cols; i += 32) { a = _mm256_load_si256((__m256i*)(bptr + i)); b = _mm256_load_si256((__m256i*)(gptr + i)); c = _mm256_load_si256((__m256i*)(rptr + i)); a = _mm256_shuffle_epi8(a, mask1); b = _mm256_shuffle_epi8(b, mask2); c = _mm256_shuffle_epi8(c, mask3); __m256i aa = _mm256_permute2x128_si256(a, a, 0x00); __m256i bb = _mm256_permute2x128_si256(b, b, 0x00); __m256i cc = _mm256_permute2x128_si256(c, c, 0x00); uchar* dptri = dptr + 3 * i; _mm256_stream_si256((__m256i*)(dptri), _mm256_blendv_epi8(cc, _mm256_blendv_epi8(aa, bb, bmask1), bmask2)); _mm256_stream_si256((__m256i*)(dptri + 32), _mm256_blendv_epi8(c, _mm256_blendv_epi8(b, a, bmask2), bmask1)); aa = _mm256_permute2x128_si256(a, a, 0x11); bb = _mm256_permute2x128_si256(b, b, 0x11); cc = _mm256_permute2x128_si256(c, c, 0x11); _mm256_stream_si256((__m256i*)(dptri + 64), _mm256_blendv_epi8(aa, _mm256_blendv_epi8(bb, cc, bmask1), bmask2)); } bptr += sstep; gptr += sstep; rptr += sstep; dptr += dstep; } } void mergeLineInterleaveBGRAVX_32f(const Mat& src, Mat& dest) { const int sstep = src.cols * 3; const int dstep = dest.cols * 3; const float* bptr = src.ptr<float>(0); const float* gptr = src.ptr<float>(1); const float* rptr = src.ptr<float>(2); float* dptr = dest.ptr<float>(0); __m256 a, b, c; for (int j = 0; j < dest.rows; j++) { for (int i = 0; i < dest.cols; i += 8) { a = _mm256_load_ps(bptr + i); b = _mm256_load_ps(gptr + i); c = _mm256_load_ps(rptr + i); const __m256 aa = _mm256_shuffle_ps(a, a, _MM_SHUFFLE(1, 2, 3, 0)); const __m256 bb = _mm256_shuffle_ps(b, b, _MM_SHUFFLE(2, 3, 0, 1)); const __m256 cc = _mm256_shuffle_ps(c, c, _MM_SHUFFLE(3, 0, 1, 2)); a = _mm256_blend_ps(_mm256_blend_ps(aa, cc, 0x44), bb, 0x22); b = _mm256_blend_ps(_mm256_blend_ps(cc, bb, 0x44), aa, 0x22); c = _mm256_blend_ps(_mm256_blend_ps(bb, aa, 0x44), cc, 0x22); float* dptri = dptr + 3 * i; _mm256_stream_ps(dptri, _mm256_permute2f128_ps(a, c, 0x20)); _mm256_stream_ps(dptri + 8, _mm256_permute2f128_ps(b, a, 0x30)); _mm256_stream_ps(dptri + 16, _mm256_permute2f128_ps(c, b, 0x31)); } bptr += sstep; gptr += sstep; rptr += sstep; dptr += dstep; } } void mergeLineInterleaveBGRAVX_32fcast(const Mat& src, Mat& dest) { Mat a, b; src.convertTo(a, CV_32F); mergeLineInterleaveBGRAVX_32f(a, b); b.convertTo(dest, src.type()); } void mergeLineInterleaveBGRAVX(cv::InputArray src_, cv::OutputArray dest_) { int pad; if (src_.depth() == CV_8U) pad = (32 - src_.size().width % 32) % 32; else pad = (8 - src_.size().width % 8) % 8; dest_.create(Size(src_.size().width + pad, src_.size().height / 3), CV_MAKETYPE(src_.depth(), 3)); Mat src = src_.getMat(); Mat dest = dest_.getMat(); copyMakeBorder(src, src, 0, 0, 0, pad, BORDER_REPLICATE); if (src.depth() == CV_8U) { mergeLineInterleaveBGRAVX_8u(src, dest); } else if (src.depth() == CV_32F) { mergeLineInterleaveBGRAVX_32f(src, dest); } else { mergeLineInterleaveBGRAVX_32fcast(src, dest); } } void splitBGRLineInterleaveAVX_8u(const Mat& src, Mat& dest) { const int sstep = src.cols * 3; const int dstep = dest.cols * 3; const uchar* s = src.ptr<uchar>(0); uchar* B = dest.ptr<uchar>(0);//line by line interleave uchar* G = dest.ptr<uchar>(1); uchar* R = dest.ptr<uchar>(2); //BGR BGR BGR BGR BGR B x2 //GR BGR BGR BGR BGR BG x2 //R BGR BGR BGR BGR BGR x2 //BBBBBBGGGGGRRRRR shuffle static const __m256i mask1 = _mm256_setr_epi8(0, 3, 6, 9, 12, 15, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14, 0, 3, 6, 9, 12, 15, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14); //GGGGGBBBBBBRRRRR shuffle static const __m256i smask1 = _mm256_setr_epi8(6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 15); static const __m256i ssmask1 = _mm256_setr_epi8(11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //GGGGGGBBBBBRRRRR shuffle static const __m256i mask2 = _mm256_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13); static const __m256i ssmask2 = _mm256_setr_epi8(0, 1, 2, 3, 4, 11, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 11, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10); static const __m256i bmask1 = _mm256_setr_epi8 (255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); static const __m256i bmask2 = _mm256_setr_epi8 (255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0); static const __m256i bmask3 = _mm256_setr_epi8 (255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); static const __m256i bmask4 = _mm256_setr_epi8 (255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0); __m256i a, b, c; for (int j = 0; j < src.rows; j++) { int i = 0; for (; i < src.cols; i += 32) { const __m256i _a = _mm256_load_si256((__m256i*)(s + 3 * i + 0)); const __m256i _b = _mm256_load_si256((__m256i*)(s + 3 * i + 32)); const __m256i _c = _mm256_load_si256((__m256i*)(s + 3 * i + 64)); a = _mm256_permute2x128_si256(_a, _b, 0x30); b = _mm256_permute2x128_si256(_a, _c, 0x21); c = _mm256_permute2x128_si256(_b, _c, 0x30); a = _mm256_shuffle_epi8(a, mask1); b = _mm256_shuffle_epi8(b, mask2); c = _mm256_shuffle_epi8(c, mask2); _mm256_stream_si256((__m256i*)(B + i), _mm256_blendv_epi8(c, _mm256_blendv_epi8(b, a, bmask1), bmask2)); a = _mm256_shuffle_epi8(a, smask1); b = _mm256_shuffle_epi8(b, smask1); c = _mm256_shuffle_epi8(c, ssmask1); _mm256_stream_si256((__m256i*)(G + i), _mm256_blendv_epi8(c, _mm256_blendv_epi8(b, a, bmask3), bmask2)); a = _mm256_shuffle_epi8(a, ssmask1); b = _mm256_shuffle_epi8(b, ssmask2); c = _mm256_shuffle_epi8(c, ssmask1); _mm256_stream_si256((__m256i*)(R + i), _mm256_blendv_epi8(c, _mm256_blendv_epi8(b, a, bmask3), bmask4)); } R += dstep; G += dstep; B += dstep; s += sstep; } } void splitBGRLineInterleaveAVX_32f(const Mat& src, Mat& dest) { const int size = src.size().area(); const int dstep = src.cols * 3; const int sstep = src.cols * 3; const float* s = src.ptr<float>(0); float* B = dest.ptr<float>(0);//line by line interleave float* G = dest.ptr<float>(1); float* R = dest.ptr<float>(2); for (int j = 0; j < src.rows; j++) { int i = 0; for (; i < src.cols; i += 8) { __m256 aa = _mm256_load_ps((s + 3 * i)); __m256 bb = _mm256_load_ps((s + 3 * i + 8)); __m256 cc = _mm256_load_ps((s + 3 * i + 16)); const __m256 a = _mm256_permute2f128_ps(aa, bb, 0x30); const __m256 b = _mm256_permute2f128_ps(aa, cc, 0x21); const __m256 c = _mm256_permute2f128_ps(bb, cc, 0x30); aa = _mm256_shuffle_ps(a, a, _MM_SHUFFLE(1, 2, 3, 0)); aa = _mm256_blend_ps(aa, b, 0x44); cc = _mm256_shuffle_ps(c, c, _MM_SHUFFLE(1, 3, 2, 0)); aa = _mm256_blend_ps(aa, cc, 0x88); _mm256_stream_ps((B + i), aa); aa = _mm256_shuffle_ps(a, a, _MM_SHUFFLE(3, 2, 0, 1)); bb = _mm256_shuffle_ps(b, b, _MM_SHUFFLE(2, 3, 0, 1)); bb = _mm256_blend_ps(bb, aa, 0x11); cc = _mm256_shuffle_ps(c, c, _MM_SHUFFLE(2, 3, 1, 0)); bb = _mm256_blend_ps(bb, cc, 0x88); _mm256_stream_ps((G + i), bb); aa = _mm256_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 0, 2)); bb = _mm256_blend_ps(aa, b, 0x22); cc = _mm256_shuffle_ps(c, c, _MM_SHUFFLE(3, 0, 1, 2)); cc = _mm256_blend_ps(bb, cc, 0xcc); _mm256_stream_ps((R + i), cc); } R += dstep; G += dstep; B += dstep; s += sstep; } } void splitBGRLineInterleaveAVX_64f(const Mat& src, Mat& dest) { const int size = src.size().area(); const int dstep = src.cols * 3; const int sstep = src.cols * 3; const double* s = src.ptr<double>(0); double* B = dest.ptr<double>(0);//line by line interleave double* G = dest.ptr<double>(1); double* R = dest.ptr<double>(2); for (int j = 0; j < src.rows; j++) { int i = 0; for (; i < src.cols; i += 4) { const __m256d aa = _mm256_load_pd((s + 3 * i)); const __m256d bb = _mm256_load_pd((s + 3 * i + 4)); const __m256d cc = _mm256_load_pd((s + 3 * i + 8)); #if CV_AVX2 __m256d a = _mm256_blend_pd(aa, bb, 0b0110); __m256d b = _mm256_blend_pd(a, cc, 0b0010); __m256d c = _mm256_permute4x64_pd(b, 0b01101100); _mm256_stream_pd((B + i), c); a = _mm256_blend_pd(aa, bb, 0b1001); b = _mm256_blend_pd(a, cc, 0b0100); c = _mm256_permute4x64_pd(b, 0b10110001); _mm256_stream_pd((G + i), c); a = _mm256_blend_pd(aa, bb, 0b1011); b = _mm256_blend_pd(a, cc, 0b1001); c = _mm256_permute4x64_pd(b, 0b11000110); _mm256_stream_pd((R + i), c); #else __m256d a = _mm256_blend_pd(_mm256_permute2f128_pd(aa, aa, 0b00000001), aa, 0b0001); __m256d b = _mm256_blend_pd(_mm256_permute2f128_pd(cc, cc, 0b00000000), bb, 0b0100); __m256d c = _mm256_blend_pd(a, b, 0b1100); _mm256_stream_pd((B + i), c); a = _mm256_blend_pd(aa, bb, 0b1001); b = _mm256_blend_pd(a, cc, 0b0100); c = _mm256_permute_pd(b, 0b0101); _mm256_stream_pd((G + i), c); a = _mm256_blend_pd(_mm256_permute2f128_pd(aa, aa, 0b0001), bb, 0b0010); b = _mm256_blend_pd(_mm256_permute2f128_pd(cc, cc, 0b0001), cc, 0b1000); c = _mm256_blend_pd(a, b, 0b1100); _mm256_stream_pd((R + i), c); #endif } R += dstep; G += dstep; B += dstep; s += sstep; } } void splitBGRLineInterleaveAVX_32fcast(const Mat& src, Mat& dest) { Mat a, b; src.convertTo(a, CV_32F); dest.convertTo(b, CV_32F); splitBGRLineInterleaveAVX_32f(a, b); b.convertTo(dest, src.type()); } void splitBGRLineInterleaveAVX(cv::InputArray src_, cv::OutputArray dest_) { dest_.create(Size(src_.size().width, src_.size().height * 3), src_.depth()); Mat src = src_.getMat(); Mat dest = dest_.getMat(); if (src.type() == CV_MAKE_TYPE(CV_8U, 3)) { CV_Assert(src.cols % 32 == 0); splitBGRLineInterleaveAVX_8u(src, dest); } else if (src.type() == CV_MAKE_TYPE(CV_32F, 3)) { CV_Assert(src.cols % 8 == 0); splitBGRLineInterleaveAVX_32f(src, dest); } else if (src.type() == CV_MAKE_TYPE(CV_64F, 3)) { CV_Assert(src.cols % 4 == 0); splitBGRLineInterleaveAVX_64f(src, dest); } else { CV_Assert(src.cols % 8 == 0); splitBGRLineInterleaveAVX_32fcast(src, dest); } } void splitBGRUnitInterleaveAVX_8u(const Mat& src, Mat& dest) { // for 32bit unit interleave const int sstep = src.cols * 3; const int dstep = dest.cols; const uchar* sp = src.ptr<uchar>(0); uchar* dp = dest.ptr<uchar>(0);//32bit unit interleave //BGR BGR BGR BGR BGR B x2 //GR BGR BGR BGR BGR BG x2 //R BGR BGR BGR BGR BGR x2 //BBBBBBGGGGGRRRRR shuffle static const __m256i mask1 = _mm256_setr_epi8(0, 3, 6, 9, 12, 15, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14, 0, 3, 6, 9, 12, 15, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14); //GGGGGBBBBBBRRRRR shuffle static const __m256i smask1 = _mm256_setr_epi8(6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 15); static const __m256i ssmask1 = _mm256_setr_epi8(11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //GGGGGGBBBBBRRRRR shuffle static const __m256i mask2 = _mm256_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13); static const __m256i ssmask2 = _mm256_setr_epi8(0, 1, 2, 3, 4, 11, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 11, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10); //const __m256i mask3 = _mm256_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31); static const __m256i bmask1 = _mm256_setr_epi8 (255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); static const __m256i bmask2 = _mm256_setr_epi8 (255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0); static const __m256i bmask3 = _mm256_setr_epi8 (255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); static const __m256i bmask4 = _mm256_setr_epi8 (255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0); __m256i a, b, c; for (int j = 0; j < src.rows; j++) { int i = 0; for (; i < src.cols; i += 32) { a = _mm256_shuffle_epi8(_mm256_loadu2_m128i((__m128i*)(sp + 3 * i + 48), (__m128i*)(sp + 3 * i + 0)), mask1); b = _mm256_shuffle_epi8(_mm256_loadu2_m128i((__m128i*)(sp + 3 * i + 64), (__m128i*)(sp + 3 * i + 16)), mask2); c = _mm256_shuffle_epi8(_mm256_loadu2_m128i((__m128i*)(sp + 3 * i + 80), (__m128i*)(sp + 3 * i + 32)), mask2); _mm256_stream_si256((__m256i*)(dp + 3 * i + 0), _mm256_blendv_epi8(c, _mm256_blendv_epi8(b, a, bmask1), bmask2)); a = _mm256_shuffle_epi8(a, smask1); b = _mm256_shuffle_epi8(b, smask1); c = _mm256_shuffle_epi8(c, ssmask1); _mm256_stream_si256((__m256i*)(dp + 3 * i + 32), _mm256_blendv_epi8(c, _mm256_blendv_epi8(b, a, bmask3), bmask2)); a = _mm256_shuffle_epi8(a, ssmask1); b = _mm256_shuffle_epi8(b, ssmask2); c = _mm256_shuffle_epi8(c, ssmask1); _mm256_stream_si256((__m256i*)(dp + 3 * i + 64), _mm256_blendv_epi8(c, _mm256_blendv_epi8(b, a, bmask3), bmask4)); } sp += sstep; dp += dstep; } } void splitBGRUnitInterleaveAVX_32f(const Mat& src, Mat& dest) { /* const int size = src.size().area(); const int dstep = src.cols * 3; const int sstep = src.cols * 3; const float* s = src.ptr<float>(0); float* B = dest.ptr<float>(0);//line by line interleave float* G = dest.ptr<float>(1); float* R = dest.ptr<float>(2); for (int j = 0; j < src.rows; j++) { int i = 0; for (; i < src.cols; i += 8) { __m256 aa = _mm256_load_ps((s + 3 * i)); __m256 bb = _mm256_load_ps((s + 3 * i + 8)); __m256 cc = _mm256_load_ps((s + 3 * i + 16)); __m256 a = _mm256_permute2f128_ps(aa, bb, 0x30); __m256 b = _mm256_permute2f128_ps(aa, cc, 0x21); __m256 c = _mm256_permute2f128_ps(bb, cc, 0x30); aa = _mm256_shuffle_ps(a, a, _MM_SHUFFLE(1, 2, 3, 0)); aa = _mm256_blend_ps(aa, b, 0x44); cc = _mm256_shuffle_ps(c, c, _MM_SHUFFLE(1, 3, 2, 0)); aa = _mm256_blend_ps(aa, cc, 0x88); _mm256_stream_ps((B + i), aa); aa = _mm256_shuffle_ps(a, a, _MM_SHUFFLE(3, 2, 0, 1)); bb = _mm256_shuffle_ps(b, b, _MM_SHUFFLE(2, 3, 0, 1)); bb = _mm256_blend_ps(bb, aa, 0x11); cc = _mm256_shuffle_ps(c, c, _MM_SHUFFLE(2, 3, 1, 0)); bb = _mm256_blend_ps(bb, cc, 0x88); _mm256_stream_ps((G + i), bb); aa = _mm256_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 0, 2)); bb = _mm256_blend_ps(aa, b, 0x22); cc = _mm256_shuffle_ps(c, c, _MM_SHUFFLE(3, 0, 1, 2)); cc = _mm256_blend_ps(bb, cc, 0xcc); _mm256_stream_ps((R + i), cc); } R += dstep; G += dstep; B += dstep; s += sstep; } */ } void splitBGRUnitInterleaveAVX_32fcast(const Mat& src, Mat& dest) { Mat a, b; src.convertTo(a, CV_32F); splitBGRLineInterleaveAVX_32f(a, b); b.convertTo(dest, src.type()); } void splitBGRUnitInterleaveAVX(cv::InputArray src_, cv::OutputArray dest_) { dest_.create(Size(src_.size().width * 3, src_.size().height), src_.depth()); Mat src = src_.getMat(); Mat dest = dest_.getMat(); if (src.type() == CV_MAKE_TYPE(CV_8U, 3)) { CV_Assert(src.cols % 32 == 0); splitBGRUnitInterleaveAVX_8u(src, dest); } else if (src.type() == CV_MAKE_TYPE(CV_32F, 3)) { //CV_Assert(src.cols % 8 == 0); //splitBGRUnitInterleaveAVX_32f(src, dest); } else { //CV_Assert(src.cols % 8 == 0); //splitBGRUnitInterleaveAVX_32fcast(src, dest); } } void splitBGRLineInterleaveSSE_8u(const Mat& src, Mat& dest) { const int size = src.size().area(); const int dstep = src.cols * 3; const int sstep = src.cols * 3; const uchar* s = src.ptr<uchar>(0); uchar* B = dest.ptr<uchar>(0);//line by line interleave uchar* G = dest.ptr<uchar>(1); uchar* R = dest.ptr<uchar>(2); //BGR BGR BGR BGR BGR B //GR BGR BGR BGR BGR BG //R BGR BGR BGR BGR BGR //BBBBBBGGGGGRRRRR shuffle static const __m128i mask1 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14); //GGGGGBBBBBBRRRRR shuffle static const __m128i smask1 = _mm_setr_epi8(6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 15); static const __m128i ssmask1 = _mm_setr_epi8(11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //GGGGGGBBBBBRRRRR shuffle static const __m128i mask2 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13); static const __m128i ssmask2 = _mm_setr_epi8(0, 1, 2, 3, 4, 11, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10); static const __m128i bmask1 = _mm_setr_epi8 (255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); static const __m128i bmask2 = _mm_setr_epi8 (255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0); static const __m128i bmask3 = _mm_setr_epi8 (255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); static const __m128i bmask4 = _mm_setr_epi8 (255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0); __m128i a, b, c; for (int j = 0; j < src.rows; j++) { int i = 0; for (; i < src.cols; i += 16) { a = _mm_shuffle_epi8(_mm_load_si128((__m128i*)(s + 3 * i)), mask1); b = _mm_shuffle_epi8(_mm_load_si128((__m128i*)(s + 3 * i + 16)), mask2); c = _mm_shuffle_epi8(_mm_load_si128((__m128i*)(s + 3 * i + 32)), mask2); _mm_stream_si128((__m128i*)(B + i), _mm_blendv_epi8(c, _mm_blendv_epi8(b, a, bmask1), bmask2)); a = _mm_shuffle_epi8(a, smask1); b = _mm_shuffle_epi8(b, smask1); c = _mm_shuffle_epi8(c, ssmask1); _mm_stream_si128((__m128i*)(G + i), _mm_blendv_epi8(c, _mm_blendv_epi8(b, a, bmask3), bmask2)); a = _mm_shuffle_epi8(a, ssmask1); c = _mm_shuffle_epi8(c, ssmask1); b = _mm_shuffle_epi8(b, ssmask2); _mm_stream_si128((__m128i*)(R + i), _mm_blendv_epi8(c, _mm_blendv_epi8(b, a, bmask3), bmask4)); } R += dstep; G += dstep; B += dstep; s += sstep; } } void splitBGRLineInterleaveSSE_32f(const Mat& src, Mat& dest) { const int size = src.size().area(); const int dstep = src.cols * 3; const int sstep = src.cols * 3; const float* s = src.ptr<float>(0); float* B = dest.ptr<float>(0);//line by line interleave float* G = dest.ptr<float>(1); float* R = dest.ptr<float>(2); for (int j = 0; j < src.rows; j++) { int i = 0; for (; i < src.cols; i += 4) { const __m128 a = _mm_load_ps((s + 3 * i)); const __m128 b = _mm_load_ps((s + 3 * i + 4)); const __m128 c = _mm_load_ps((s + 3 * i + 8)); __m128 aa = _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 2, 3, 0)); aa = _mm_blend_ps(aa, b, 4); __m128 cc = _mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 3, 2, 0)); aa = _mm_blend_ps(aa, cc, 8); _mm_stream_ps((B + i), aa); aa = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 2, 0, 1)); __m128 bb = _mm_shuffle_ps(b, b, _MM_SHUFFLE(2, 3, 0, 1)); bb = _mm_blend_ps(bb, aa, 1); cc = _mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 3, 1, 0)); bb = _mm_blend_ps(bb, cc, 8); _mm_stream_ps((G + i), bb); aa = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 0, 2)); bb = _mm_blend_ps(aa, b, 2); cc = _mm_shuffle_ps(c, c, _MM_SHUFFLE(3, 0, 1, 2)); cc = _mm_blend_ps(bb, cc, 12); _mm_stream_ps((R + i), cc); } R += dstep; G += dstep; B += dstep; s += sstep; } } void splitBGRLineInterleaveSSE_64f(const Mat& src, Mat& dest) { const int size = src.size().area(); const int dstep = src.cols * 3; const int sstep = src.cols * 3; const double* s = src.ptr<double>(0); double* B = dest.ptr<double>(0);//line by line interleave double* G = dest.ptr<double>(1); double* R = dest.ptr<double>(2); for (int j = 0; j < src.rows; j++) { int i = 0; for (; i < src.cols; i += 2) { const __m128d a = _mm_load_pd((s + 3 * i)); const __m128d b = _mm_load_pd((s + 3 * i + 2)); const __m128d c = _mm_load_pd((s + 3 * i + 4)); __m128d aa = _mm_blend_pd(a, b, 0b10); _mm_stream_pd((B + i), aa); aa = _mm_shuffle_pd(a, a, 0b01); const __m128d bb = _mm_shuffle_pd(c, c, 0b01); aa = _mm_blend_pd(aa, bb, 0b10); _mm_stream_pd((G + i), aa); aa = _mm_blend_pd(b, c, 0b10); _mm_stream_pd((R + i), aa); } R += dstep; G += dstep; B += dstep; s += sstep; } } void splitBGRLineInterleaveSSE_32fcast(const Mat& src, Mat& dest) { Mat a, b; src.convertTo(a, CV_32F); splitBGRLineInterleaveSSE_32f(a, b); b.convertTo(dest, src.type()); } void splitBGRLineInterleaveSSE(cv::InputArray src_, cv::OutputArray dest_) { dest_.create(Size(src_.size().width, src_.size().height * 3), src_.depth()); Mat src = src_.getMat(); Mat dest = dest_.getMat(); if (src.type() == CV_MAKE_TYPE(CV_8U, 3)) { CV_Assert(src.cols % 16 == 0); splitBGRLineInterleaveSSE_8u(src, dest); } else if (src.type() == CV_MAKE_TYPE(CV_32F, 3)) { CV_Assert(src.cols % 4 == 0); splitBGRLineInterleaveSSE_32f(src, dest); } else if (src.type() == CV_MAKE_TYPE(CV_64F, 3)) { CV_Assert(src.cols % 2 == 0); splitBGRLineInterleaveSSE_64f(src, dest); } else { CV_Assert(src.cols % 4 == 0); splitBGRLineInterleaveSSE_32fcast(src, dest); } } void cvtColorBGR2PLANE_8u(const Mat& src, Mat& dest) { dest.create(Size(src.cols, src.rows * 3), CV_8U); const int size = src.size().area(); const int ssesize = 3 * size - ((48 - (3 * size) % 48) % 48); const int ssecount = ssesize / 48; const uchar* s = src.ptr<uchar>(0); uchar* B = dest.ptr<uchar>(0);//line by line interleave uchar* G = dest.ptr<uchar>(src.rows); uchar* R = dest.ptr<uchar>(2 * src.rows); //BGR BGR BGR BGR BGR B -> GGGGG RRRRR BBBBBB //GR BGR BGR BGR BGR BG -> GGGGGG RRRRR BBBBB //R BGR BGR BGR BGR BGR -> BBBBB GGGGG RRRRR static const __m128i mask0 = _mm_setr_epi8(1, 4, 7, 10, 13, 2, 5, 8, 11, 14, 0, 3, 6, 9, 12, 15); static const __m128i mask1 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14); __m128i a, b, c, d, e; for (int i = 0; i < ssecount; i++) { a = _mm_shuffle_epi8(_mm_load_si128((__m128i*)(s + 0)), mask0); b = _mm_shuffle_epi8(_mm_load_si128((__m128i*)(s + 16)), mask1); c = _mm_shuffle_epi8(_mm_load_si128((__m128i*)(s + 32)), mask0); d = _mm_alignr_epi8(c, b, 11); e = _mm_alignr_epi8(d, a, 10); _mm_storeu_si128((__m128i*)(B), e); d = _mm_alignr_epi8(_mm_srli_si128(c, 5), _mm_slli_si128(b, 10), 10); e = _mm_alignr_epi8(d, _mm_slli_si128(a, 11), 11); _mm_storeu_si128((__m128i*)(G), e); d = _mm_alignr_epi8(_mm_srli_si128(c, 10), _mm_slli_si128(b, 5), 11); e = _mm_alignr_epi8(d, _mm_slli_si128(a, 6), 11); _mm_storeu_si128((__m128i*)(R), e); s += 48; R += 16; G += 16; B += 16; } for (int i = ssesize; i < 3 * size; i += 3) { B[0] = s[0]; G[0] = s[1]; R[0] = s[2]; s += 3, R++, G++, B++; } } void cvtColorBGR2PLANE_32f(const Mat& src, Mat& dest) { const int size = src.size().area(); const int ssesize = 3 * size - ((12 - (3 * size) % 12) % 12); const int ssecount = ssesize / 12; const float* s = src.ptr<float>(0); float* B = dest.ptr<float>(0);//line by line interleave float* G = dest.ptr<float>(src.rows); float* R = dest.ptr<float>(2 * src.rows); for (int i = 0; i < ssecount; i++) { const __m128 a = _mm_load_ps(s); const __m128 b = _mm_load_ps(s + 4); const __m128 c = _mm_load_ps(s + 8); __m128 aa = _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 2, 3, 0)); aa = _mm_blend_ps(aa, b, 4); __m128 cc = _mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 3, 2, 0)); aa = _mm_blend_ps(aa, cc, 8); _mm_storeu_ps((B), aa); aa = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 2, 0, 1)); __m128 bb = _mm_shuffle_ps(b, b, _MM_SHUFFLE(2, 3, 0, 1)); bb = _mm_blend_ps(bb, aa, 1); cc = _mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 3, 1, 0)); bb = _mm_blend_ps(bb, cc, 8); _mm_storeu_ps((G), bb); aa = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 0, 2)); bb = _mm_blend_ps(aa, b, 2); cc = _mm_shuffle_ps(c, c, _MM_SHUFFLE(3, 0, 1, 2)); cc = _mm_blend_ps(bb, cc, 12); _mm_storeu_ps((R), cc); s += 12; R += 4; G += 4; B += 4; } for (int i = ssesize; i < 3 * size; i += 3) { B[0] = s[0]; G[0] = s[1]; R[0] = s[2]; s += 3, R++, G++, B++; } } template <class T> void cvtColorBGR2PLANE_(const Mat& src, Mat& dest, int depth) { vector<Mat> v(3); split(src, v); dest.create(Size(src.cols, src.rows * 3), depth); memcpy(dest.data, v[0].data, src.size().area() * sizeof(T)); memcpy(dest.data + src.size().area() * sizeof(T), v[1].data, src.size().area() * sizeof(T)); memcpy(dest.data + 2 * src.size().area() * sizeof(T), v[2].data, src.size().area() * sizeof(T)); } void cvtColorBGR2PLANE(cv::InputArray src_, cv::OutputArray dest_) { CV_Assert(src_.channels() == 3); Mat src = src_.getMat(); dest_.create(Size(src.cols, src.rows * 3), src.depth()); Mat dest = dest_.getMat(); if (src.depth() == CV_8U) { //cvtColorBGR2PLANE_<uchar>(src, dest, CV_8U); cvtColorBGR2PLANE_8u(src, dest); } else if (src.depth() == CV_16U) { cvtColorBGR2PLANE_<ushort>(src, dest, CV_16U); } if (src.depth() == CV_16S) { cvtColorBGR2PLANE_<short>(src, dest, CV_16S); } if (src.depth() == CV_32S) { cvtColorBGR2PLANE_<int>(src, dest, CV_32S); } if (src.depth() == CV_32F) { //cvtColorBGR2PLANE_<float>(src, dest, CV_32F); cvtColorBGR2PLANE_32f(src, dest); } if (src.depth() == CV_64F) { cvtColorBGR2PLANE_<double>(src, dest, CV_64F); } } template <class T> void cvtColorPLANE2BGR_(const Mat& src, Mat& dest, int depth) { const int width = src.cols; const int height = src.rows / 3; T* b = (T*)src.ptr<T>(0); T* g = (T*)src.ptr<T>(height); T* r = (T*)src.ptr<T>(2 * height); Mat B(height, width, src.type(), b); Mat G(height, width, src.type(), g); Mat R(height, width, src.type(), r); vector<Mat> v(3); v[0] = B; v[1] = G; v[2] = R; merge(v, dest); } void cvtColorPLANE2BGR_8u_align(const Mat& src, Mat& dest) { const int width = src.cols; const int height = src.rows / 3; if (dest.empty()) dest.create(Size(width, height), CV_8UC3); else if (width != dest.cols || height != dest.rows) dest.create(Size(width, height), CV_8UC3); else if (dest.type() != CV_8UC3) dest.create(Size(width, height), CV_8UC3); uchar* B = (uchar*)src.ptr<uchar>(0); uchar* G = (uchar*)src.ptr<uchar>(height); uchar* R = (uchar*)src.ptr<uchar>(2 * height); uchar* D = (uchar*)dest.ptr<uchar>(0); const int ssecount = width * height * 3 / 48; static const __m128i mask1 = _mm_setr_epi8(0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); static const __m128i mask2 = _mm_setr_epi8(5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); static const __m128i mask3 = _mm_setr_epi8(10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); static const __m128i bmask1 = _mm_setr_epi8(0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0); static const __m128i bmask2 = _mm_setr_epi8(255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255); for (int i = ssecount; i--;) { __m128i a = _mm_load_si128((const __m128i*)B); __m128i b = _mm_load_si128((const __m128i*)G); __m128i c = _mm_load_si128((const __m128i*)R); a = _mm_shuffle_epi8(a, mask1); b = _mm_shuffle_epi8(b, mask2); c = _mm_shuffle_epi8(c, mask3); _mm_stream_si128((__m128i*)(D), _mm_blendv_epi8(c, _mm_blendv_epi8(a, b, bmask1), bmask2)); _mm_stream_si128((__m128i*)(D + 16), _mm_blendv_epi8(b, _mm_blendv_epi8(a, c, bmask2), bmask1)); _mm_stream_si128((__m128i*)(D + 32), _mm_blendv_epi8(c, _mm_blendv_epi8(b, a, bmask2), bmask1)); D += 48; B += 16; G += 16; R += 16; } } void cvtColorPLANE2BGR_8u(const Mat& src, Mat& dest) { const int width = src.cols; const int height = src.rows / 3; if (dest.empty()) dest.create(Size(width, height), CV_8UC3); else if (width != dest.cols || height != dest.rows) dest.create(Size(width, height), CV_8UC3); else if (dest.type() != CV_8UC3) dest.create(Size(width, height), CV_8UC3); uchar* B = (uchar*)src.ptr<uchar>(0); uchar* G = (uchar*)src.ptr<uchar>(height); uchar* R = (uchar*)src.ptr<uchar>(2 * height); uchar* D = (uchar*)dest.ptr<uchar>(0); const int ssecount = width * height * 3 / 48; const int rem = width * height * 3 - ssecount * 48; const __m128i mask1 = _mm_setr_epi8(0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); const __m128i mask2 = _mm_setr_epi8(5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); const __m128i mask3 = _mm_setr_epi8(10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); const __m128i bmask1 = _mm_setr_epi8(0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0); const __m128i bmask2 = _mm_setr_epi8(255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255); for (int i = ssecount; i--;) { __m128i a = _mm_loadu_si128((const __m128i*)B); __m128i b = _mm_loadu_si128((const __m128i*)G); __m128i c = _mm_loadu_si128((const __m128i*)R); a = _mm_shuffle_epi8(a, mask1); b = _mm_shuffle_epi8(b, mask2); c = _mm_shuffle_epi8(c, mask3); _mm_storeu_si128((__m128i*)(D), _mm_blendv_epi8(c, _mm_blendv_epi8(a, b, bmask1), bmask2)); _mm_storeu_si128((__m128i*)(D + 16), _mm_blendv_epi8(b, _mm_blendv_epi8(a, c, bmask2), bmask1)); _mm_storeu_si128((__m128i*)(D + 32), _mm_blendv_epi8(c, _mm_blendv_epi8(b, a, bmask2), bmask1)); D += 48; B += 16; G += 16; R += 16; } for (int i = rem; i--;) { D[0] = *B; D[1] = *G; D[2] = *R; D += 3; B++, G++, R++; } } void cvtColorPLANE2BGR(cv::InputArray src_, cv::OutputArray dest_) { CV_Assert(src_.channels() == 1); Mat src = src_.getMat(); if (dest_.empty())dest_.create(Size(src.cols, src.rows), CV_MAKETYPE(src.depth(), 3)); Mat dest = dest_.getMat(); if (src.depth() == CV_8U) { //cvtColorPLANE2BGR_<uchar>(src, dest, CV_8U); if (src.cols % 16 == 0) cvtColorPLANE2BGR_8u_align(src, dest); else cvtColorPLANE2BGR_8u(src, dest); } else if (src.depth() == CV_16U) { cvtColorPLANE2BGR_<ushort>(src, dest, CV_16U); } if (src.depth() == CV_16S) { cvtColorPLANE2BGR_<short>(src, dest, CV_16S); } if (src.depth() == CV_32S) { cvtColorPLANE2BGR_<int>(src, dest, CV_32S); } if (src.depth() == CV_32F) { cvtColorPLANE2BGR_<float>(src, dest, CV_32F); } if (src.depth() == CV_64F) { cvtColorPLANE2BGR_<double>(src, dest, CV_64F); } }
31.980866
160
0.623642
yoshihiromaed
7d676898e08ff703577bf9b32b4270822f4c2ad1
586
cpp
C++
test/geometry/geometry.05.test.cpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
1
2021-12-26T14:17:29.000Z
2021-12-26T14:17:29.000Z
test/geometry/geometry.05.test.cpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
3
2020-07-13T06:23:02.000Z
2022-02-16T08:54:26.000Z
test/geometry/geometry.05.test.cpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
null
null
null
/* * @brief 計算幾何学/計算幾何学 (平行 / 垂直) */ #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A" #include <iostream> #include "../../geometry/geometry.hpp" int main() { int q; std::cin >> q; while (q--) { geometry::Point p0, p1, p2, p3; std::cin >> p0 >> p1 >> p2 >> p3; geometry::Line s1(p0, p1), s2(p2, p3); if (geometry::is_parallel(s1, s2)) { std::cout << "2\n"; } else if (geometry::is_orthogonal(s1, s2)) { std::cout << "1\n"; } else { std::cout << "0\n"; } } return 0; }
22.538462
83
0.515358
emthrm
de102716c61d2982fb162cebeecb7ede7fb07993
1,738
cpp
C++
aws-cpp-sdk-sagemaker-edge/source/model/SendHeartbeatRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-sagemaker-edge/source/model/SendHeartbeatRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-sagemaker-edge/source/model/SendHeartbeatRequest.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/sagemaker-edge/model/SendHeartbeatRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::SagemakerEdgeManager::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; SendHeartbeatRequest::SendHeartbeatRequest() : m_agentMetricsHasBeenSet(false), m_modelsHasBeenSet(false), m_agentVersionHasBeenSet(false), m_deviceNameHasBeenSet(false), m_deviceFleetNameHasBeenSet(false) { } Aws::String SendHeartbeatRequest::SerializePayload() const { JsonValue payload; if(m_agentMetricsHasBeenSet) { Array<JsonValue> agentMetricsJsonList(m_agentMetrics.size()); for(unsigned agentMetricsIndex = 0; agentMetricsIndex < agentMetricsJsonList.GetLength(); ++agentMetricsIndex) { agentMetricsJsonList[agentMetricsIndex].AsObject(m_agentMetrics[agentMetricsIndex].Jsonize()); } payload.WithArray("AgentMetrics", std::move(agentMetricsJsonList)); } if(m_modelsHasBeenSet) { Array<JsonValue> modelsJsonList(m_models.size()); for(unsigned modelsIndex = 0; modelsIndex < modelsJsonList.GetLength(); ++modelsIndex) { modelsJsonList[modelsIndex].AsObject(m_models[modelsIndex].Jsonize()); } payload.WithArray("Models", std::move(modelsJsonList)); } if(m_agentVersionHasBeenSet) { payload.WithString("AgentVersion", m_agentVersion); } if(m_deviceNameHasBeenSet) { payload.WithString("DeviceName", m_deviceName); } if(m_deviceFleetNameHasBeenSet) { payload.WithString("DeviceFleetName", m_deviceFleetName); } return payload.View().WriteReadable(); }
23.486486
113
0.74626
perfectrecall
de116c4ff6fb4bf9ae831be22c03d5b3e5cbe3c0
252
cpp
C++
Advance Recursion/tiling.cpp
Mythical-stack/C-Crash-Course
323b7f5b1e0b270138e54a1a18fb1e81015a1763
[ "Apache-2.0" ]
1
2021-08-10T11:45:13.000Z
2021-08-10T11:45:13.000Z
Advance Recursion/tiling.cpp
jkbells/C-Crash-Course
323b7f5b1e0b270138e54a1a18fb1e81015a1763
[ "Apache-2.0" ]
null
null
null
Advance Recursion/tiling.cpp
jkbells/C-Crash-Course
323b7f5b1e0b270138e54a1a18fb1e81015a1763
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; int tilingways(int n){ if(n==0){ return 0; } if(n==1){ return 1; } return tilingways(n-1) + tilingways(n-2); } int main() { cout << tilingways(4) << endl; return 0; }
14
45
0.531746
Mythical-stack
de135c7f40ad0a4a983c9c4a12446592e669ab99
34,216
cpp
C++
WRK-V1.2/palrt/src/crypt.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/palrt/src/crypt.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/palrt/src/crypt.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== // =========================================================================== // File: crypt.cpp // // PAL RT Crypto APIs // =========================================================================== #include "rotor_palrt.h" #include "crypt.h" /***************** Crypto base class ****************************/ class CryptProvider; class CryptKey; class CryptHash; #define ADDREF(x) ((CryptBase*)x)->AddRef() #define RELEASE(x) ((CryptBase*)x)->Release() class CryptBase { LONG m_RefCount; CryptProvider* m_pProvider; public: CryptBase() { m_RefCount = 1; m_pProvider = NULL; } virtual ~CryptBase() { if (m_pProvider != NULL) RELEASE(m_pProvider); } void AddRef() { m_RefCount++; } void Release() { if (--m_RefCount == 0) delete this; } CryptProvider* GetProvider() { _ASSERTE(m_pProvider != NULL); return m_pProvider; } void SetProvider(CryptProvider* pProvider) { _ASSERTE(m_pProvider == NULL); m_pProvider = pProvider; ADDREF(m_pProvider); } }; /***************** Crypto provider ******************************/ class CryptProvider : public CryptBase { CryptKey* m_pSignatureKey; public: CryptProvider() { m_pSignatureKey = NULL; } virtual ~CryptProvider() { if (m_pSignatureKey != NULL) RELEASE(m_pSignatureKey); } CryptKey* GetSignatureKey() { return m_pSignatureKey; } void SetSignatureKey(CryptKey *pKey) { CryptKey* pOldKey; if (pKey != NULL) ADDREF(pKey); pOldKey = m_pSignatureKey; m_pSignatureKey = pKey; if (pOldKey != NULL) RELEASE(pOldKey); } }; /***************** virtual Hash base ****************************/ class CryptHash : public CryptBase { public: CryptHash() { } virtual ~CryptHash() { } virtual BOOL Initialize() = 0; virtual BOOL HashData( CONST BYTE *pbData, DWORD dwDataLen, DWORD dwFlags) = 0; virtual BOOL GetHashParam( DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags) = 0; virtual BOOL GetSignatureMagic( BYTE *pbData, DWORD *pdwDataLen) = 0; }; /***************** SHA-1 message digest *************************/ class SHA1Hash : public CryptHash { SHA1_CTX m_Context; BYTE m_Value[SHA1DIGESTLEN]; bool m_fFinalized; public: SHA1Hash() { } virtual ~SHA1Hash() { } virtual BOOL Initialize(); virtual BOOL HashData( CONST BYTE *pbData, DWORD dwDataLen, DWORD dwFlags); virtual BOOL GetHashParam( DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags); virtual BOOL GetSignatureMagic( BYTE *pbData, DWORD *pdwDataLen); }; ///////////////////////////////// SHA1Hash methods ///////////////////////////// BOOL SHA1Hash::Initialize() { m_fFinalized = false; return SHA1Init(&m_Context); } BOOL SHA1Hash::HashData( CONST BYTE *pbData, DWORD dwDataLen, DWORD dwFlags) { return SHA1Update(&m_Context, pbData, dwDataLen); } BOOL SHA1Hash::GetHashParam( DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags) { DWORD dwDataLen = (pbData != NULL) ? *pdwDataLen : NULL; switch (dwParam) { case HP_ALGID: *pdwDataLen = sizeof(ALG_ID); if (dwDataLen < *pdwDataLen) goto MoreData; *(ALG_ID*)pbData = CALG_SHA1; return TRUE; case HP_HASHSIZE: *pdwDataLen = sizeof(DWORD); if (dwDataLen < *pdwDataLen) goto MoreData; *(DWORD*)pbData = SHA1DIGESTLEN; return TRUE; case HP_HASHVAL: *pdwDataLen = SHA1DIGESTLEN; if (dwDataLen < *pdwDataLen) goto MoreData; if (!m_fFinalized) { if (!SHA1Final(&m_Context, m_Value)) return FALSE; m_fFinalized = true; } memcpy(pbData, m_Value, SHA1DIGESTLEN); return TRUE; default: SetLastError(NTE_BAD_TYPE); return FALSE; } MoreData: if (pbData != NULL) { SetLastError(ERROR_MORE_DATA); return FALSE; } return TRUE; } BOOL SHA1Hash::GetSignatureMagic( BYTE *pbData, DWORD *pdwDataLen) { // OID: 1.3.14.3.2.26 static const BYTE data[] = {0x30,0x21,0x30,0x09,0x06,0x05,0x2b,0x0e, 0x03,0x02,0x1a,0x05,0x00,0x04,0x14}; DWORD dwDataLen = *pdwDataLen; *pdwDataLen = sizeof(data); if (dwDataLen < *pdwDataLen) return FALSE; memcpy(pbData, data, sizeof(data)); return TRUE; } /***************** MD5 message digest ***************************/ class MD5Hash : public CryptHash { MD5_CTX m_Context; BYTE m_Value[MD5DIGESTLEN]; bool m_fFinalized; public: MD5Hash() { } virtual ~MD5Hash() { } virtual BOOL Initialize(); virtual BOOL HashData( CONST BYTE *pbData, DWORD dwDataLen, DWORD dwFlags); virtual BOOL GetHashParam( DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags); virtual BOOL GetSignatureMagic( BYTE *pbData, DWORD *pdwDataLen); }; ///////////////////////// MD5Hash methods /////////////////////////// // See comment inside SHA1Hash to understand why function definitions // must be outside class deifinition BOOL MD5Hash::Initialize() { m_fFinalized = false; return MD5Init(&m_Context); } BOOL MD5Hash::HashData( CONST BYTE *pbData, DWORD dwDataLen, DWORD dwFlags) { return MD5Update(&m_Context, pbData, dwDataLen); } BOOL MD5Hash::GetHashParam( DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags) { DWORD dwDataLen = (pbData != NULL) ? *pdwDataLen : NULL; switch (dwParam) { case HP_ALGID: *pdwDataLen = sizeof(ALG_ID); if (dwDataLen < *pdwDataLen) goto MoreData; *(ALG_ID*)pbData = CALG_MD5; return TRUE; case HP_HASHSIZE: *pdwDataLen = sizeof(DWORD); if (dwDataLen < *pdwDataLen) goto MoreData; *(DWORD*)pbData = MD5DIGESTLEN; return TRUE; case HP_HASHVAL: *pdwDataLen = MD5DIGESTLEN; if (dwDataLen < *pdwDataLen) goto MoreData; if (!m_fFinalized) { if (!MD5Final(&m_Context, m_Value)) return FALSE; m_fFinalized = true; } memcpy(pbData, m_Value, MD5DIGESTLEN); return TRUE; default: SetLastError(NTE_BAD_TYPE); return FALSE; } MoreData: if (pbData != NULL) { SetLastError(ERROR_MORE_DATA); return FALSE; } return TRUE; } BOOL MD5Hash::GetSignatureMagic( BYTE *pbData, DWORD *pdwDataLen) { // OID: 1.2.840.0113549.2.5 static const BYTE data[] = {0x30,0x20,0x30,0x0c,0x06,0x08,0x2a,0x86, 0x48,0x86,0xf7,0x0d,0x02,0x05,0x05,0x00,0x04,0x10}; DWORD dwDataLen = *pdwDataLen; *pdwDataLen = sizeof(data); if (dwDataLen < *pdwDataLen) return FALSE; memcpy(pbData, data, sizeof(data)); return TRUE; } /***************** virtual Key base *****************************/ struct BLOBHEADER { BYTE bType; BYTE bVersion; WORD reserved; ALG_ID aiKeyAlg; }; class CryptKey : public CryptBase { DWORD m_dwFlags; // only CRYPT_EXPORTABLE for now public: CryptKey() { m_dwFlags = 0; } virtual ~CryptKey() { } virtual BOOL GenKey(DWORD dwFlags) = 0; virtual BOOL ImportKey(DWORD dwFlags, CONST BYTE *pbData, DWORD dwDataLen) = 0; virtual BOOL ExportKey(DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen) = 0; virtual BOOL GetKeyParam(DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags) = 0; virtual DWORD GetSignatureLength() = 0; virtual BOOL EncryptSignature(CONST BYTE *pbSrc, BYTE *pbDest) = 0; virtual BOOL DecryptSignature(CONST BYTE *pbSrc, BYTE *pbDest) = 0; void SetFlags(DWORD dwFlags) { m_dwFlags = dwFlags; } inline DWORD GetFlags() { return m_dwFlags; } }; /***************** RSA crypt key ********************************/ struct RSAPUBKEY { DWORD magic; DWORD bitlen; DWORD pubexp; }; class RSAKey : public CryptKey { PVOID m_pBlob; DWORD m_dwSize; DWORD m_dwBitLen; BigNum* m_pExponent; // The exponent. BigNum* m_pModulus; // The modulus. This has a value of "prime1 * prime2" and is often known as "n". // private-only fields BigNum* m_pPrime1; // Prime number 1, often known as "p". BigNum* m_pPrime2; // Prime number 2, often known as "q". BigNum* m_pExponent1; // Exponent 1. This has a numeric value of "d mod (p - 1)". BigNum* m_pExponent2; // Exponent 2. This has a numeric value of "d mod (q - 1)". BigNum* m_pCoefficient; // Coefficient. This has a numeric value of "(inverse of q) mod p". BigNum* m_pPrivateExponent; // Private exponent, often known as "d". BOOL CheckKey(); BOOL GenerateKey(); void ClearStack(); public: RSAKey(); virtual ~RSAKey(); virtual BOOL GenKey(DWORD dwFlags); virtual BOOL ImportKey(DWORD dwFlags, CONST BYTE *pbData, DWORD dwDataLen); virtual BOOL ExportKey(DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen); virtual BOOL GetKeyParam(DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags); virtual DWORD GetSignatureLength(); virtual BOOL EncryptSignature(CONST BYTE *pbSrc, BYTE *pbDest); virtual BOOL DecryptSignature(CONST BYTE *pbSrc, BYTE *pbDest); }; //////////////// RSAKey private methods //////////////// // See comment inside SHA1Hash to understand why function definitions // must be outside class deifinition BOOL RSAKey::CheckKey() { DWORD dwBufLen; BigNum* pTmp1; BigNum* pTmp2; BigNum* pTmp3; #ifdef _DEBUG // check the bit lengths _ASSERTE(BigNum::GetBitSize(m_pExponent) <= 32); _ASSERTE(BigNum::GetBitSize(m_pModulus) <= m_dwBitLen); _ASSERTE(BigNum::GetBitSize(m_pPrime1) == m_dwBitLen/2); _ASSERTE(BigNum::GetBitSize(m_pPrime2) == m_dwBitLen/2); _ASSERTE(BigNum::GetBitSize(m_pExponent1) <= m_dwBitLen/2); _ASSERTE(BigNum::GetBitSize(m_pExponent2) <= m_dwBitLen/2); _ASSERTE(BigNum::GetBitSize(m_pCoefficient) <= m_dwBitLen/2); _ASSERTE(BigNum::GetBitSize(m_pPrivateExponent) <= m_dwBitLen); #endif dwBufLen = BigNum::GetBufferSizeFromBits(2 * m_dwBitLen); pTmp1 = (BigNum*)alloca(dwBufLen); pTmp2 = (BigNum*)alloca(dwBufLen); pTmp3 = (BigNum*)alloca(dwBufLen); // m_pModulus == m_pPrime1 * m_pPrime2 BigNum::Mul(pTmp1, m_pPrime1, m_pPrime2); if (BigNum::Cmp(pTmp1, m_pModulus) != 0) return FALSE; // m_pExponent1 == m_pPrivateExponent % (m_pPrime1 - 1) BigNum::Sub(pTmp1, m_pPrime1, BigNum::One()); BigNum::Set(pTmp2, m_pPrivateExponent); BigNum::Modulize(pTmp2, pTmp1); if (BigNum::Cmp(pTmp2, m_pExponent1) != 0) return FALSE; // m_pExponent2 == m_pPrivateExponent % (m_pPrime2 - 1) BigNum::Sub(pTmp1, m_pPrime2, BigNum::One()); BigNum::Set(pTmp2, m_pPrivateExponent); BigNum::Modulize(pTmp2, pTmp1); if (BigNum::Cmp(pTmp2, m_pExponent2) != 0) return FALSE; // 1 == (m_pCoefficient * m_pPrime2) % m_pPrime1 BigNum::Mul(pTmp1, m_pCoefficient, m_pPrime2); BigNum::Modulize(pTmp1, m_pPrime1); if (!BigNum::IsOne(pTmp1)) return FALSE; // 1 == (m_pExponent * m_pPrivateExponent) % ((m_pPrime1 - 1) * (m_pPrime2 - 1)) BigNum::Sub(pTmp1, m_pPrime1, BigNum::One()); BigNum::Sub(pTmp2, m_pPrime2, BigNum::One()); BigNum::Mul(pTmp3, pTmp1, pTmp2); BigNum::Mul(pTmp1, m_pExponent, m_pPrivateExponent); BigNum::Modulize(pTmp1, pTmp3); if (!BigNum::IsOne(pTmp1)) return FALSE; #ifdef _DEBUG // Roundtrip check: 123 = (123 ^ m_pPrivateExponent) ^ m_pExponent BigNum::SetSimple(pTmp1, 123); BigNum::Set(pTmp2, pTmp1); BigNum::PowMod(pTmp1, pTmp1, m_pExponent, m_pModulus); BigNum::PowMod(pTmp1, pTmp1, m_pPrivateExponent, m_pModulus); _ASSERTE(BigNum::Cmp(pTmp1, pTmp2) == 0); #endif return TRUE; } BOOL RSAKey::GenerateKey() { DWORD dwBufferSize; DWORD dwBufferSize2; BigNum* pTmp1; BigNum* pTmp2; BigNum* pTmp3; dwBufferSize = BigNum::GetBufferSizeFromBits(m_dwBitLen); dwBufferSize2 = BigNum::GetBufferSizeFromBits(m_dwBitLen/2); pTmp1 = (BigNum*)alloca(dwBufferSize2); pTmp2 = (BigNum*)alloca(dwBufferSize2); pTmp3 = (BigNum*)alloca(dwBufferSize); again: if (!BigNum::GenPrime(m_pPrime1, m_dwBitLen/2, TRUE)) return FALSE; if (!BigNum::GenPrime(m_pPrime2, m_dwBitLen/2, TRUE)) return FALSE; // m_pModulus = m_pPrime1 * m_pPrime2 BigNum::Mul(m_pModulus, m_pPrime1, m_pPrime2); // m_pCoeffiecient = 1/m_pPrime2 % m_pPrime1 if (!BigNum::InvMod(m_pCoefficient, m_pPrime2, m_pPrime1)) goto again; BigNum::Sub(pTmp1, m_pPrime1, BigNum::One()); BigNum::Sub(pTmp2, m_pPrime2, BigNum::One()); // m_pPrivateExponent = 1/m_pExponent % ((m_pPrime1-1)*(m_pPrime2-1)) BigNum::Mul(pTmp3, pTmp1, pTmp2); if (!BigNum::InvMod(m_pPrivateExponent, m_pExponent, pTmp3)) goto again; // m_pExponent1 = m_pPrivateExponent % (m_pPrime1-1) BigNum::Set(pTmp3, m_pPrivateExponent); BigNum::Modulize(pTmp3, pTmp1); BigNum::Set(m_pExponent1, pTmp3); // m_pExponent2 = m_pPrivateExponent % (m_pPrime2-1) BigNum::Set(pTmp3, m_pPrivateExponent); BigNum::Modulize(pTmp3, pTmp2); BigNum::Set(m_pExponent2, pTmp3); return TRUE; } void RSAKey::ClearStack() { DWORD dwSize = 8 * BigNum::GetBufferSizeFromBits(2 * m_dwBitLen) + 256 * sizeof(void*); void* ptr = alloca(dwSize); memset(ptr, 0, dwSize); } ////////////////// RSAKey public methods /////////////////////////// RSAKey::RSAKey() { m_pBlob = NULL; m_pExponent = NULL; m_pModulus = NULL; m_pPrime1 = NULL; m_pPrime2 = NULL; m_pExponent1 = NULL; m_pExponent2 = NULL; m_pCoefficient = NULL; m_pPrivateExponent = NULL; } RSAKey::~RSAKey() { if (m_pBlob != NULL) { // clear the blob to avoid potential exposure of sensitive bits memset(m_pBlob, 0, m_dwSize); free(m_pBlob); } } BOOL RSAKey::GenKey(DWORD dwFlags) { DWORD dwBitLen; DWORD dwByteLen1; DWORD dwByteLen2; DWORD dwBufferSize1; DWORD dwBufferSize2; BYTE *pb; dwBitLen = dwFlags >> 16; // use the default if not specified if (dwBitLen == 0) dwBitLen = 1024; if ((dwBitLen % 16 != 0) || (dwBitLen > 16384)) { SetLastError(NTE_BAD_FLAGS); return FALSE; } m_dwBitLen = dwBitLen; dwByteLen1 = dwBitLen / 8; dwByteLen2 = dwByteLen1 / 2; dwBufferSize1 = BigNum::GetBufferSize(dwByteLen1); dwBufferSize2 = BigNum::GetBufferSize(dwByteLen2); m_dwSize = BigNum::GetBufferSize(sizeof(DWORD)) + (2 * dwBufferSize1 + 5 * dwBufferSize2); pb = (BYTE*)malloc(m_dwSize); if (pb == NULL) { SetLastError(ERROR_OUTOFMEMORY); return FALSE; } m_pBlob = pb; m_pExponent = (BigNum*)pb; pb += BigNum::GetBufferSize(sizeof(DWORD)); static const BYTE c_DefaultExponent[4] = { 1, 0, 1, 0 }; BigNum::SetBytes(m_pExponent, c_DefaultExponent, sizeof(DWORD)); #define HELPER(m_pMember, size) \ m_pMember = (BigNum*)pb; \ pb += dwBufferSize##size; HELPER(m_pModulus, 1); HELPER(m_pPrime1, 2); HELPER(m_pPrime2, 2); HELPER(m_pExponent1, 2); HELPER(m_pExponent2, 2); HELPER(m_pCoefficient, 2); HELPER(m_pPrivateExponent, 1); #undef HELPER if (!GenerateKey()) { ClearStack(); return FALSE; } if (!CheckKey()) { SetLastError(E_UNEXPECTED); _ASSERTE(false); ClearStack(); return FALSE; } GetProvider()->SetSignatureKey(this); return TRUE; } BOOL RSAKey::ImportKey(DWORD dwFlags, CONST BYTE *pbData, DWORD dwDataLen) { BOOL bPrivate; DWORD dwBitLen; DWORD dwByteLen1; DWORD dwByteLen2; DWORD dwBufferSize1; DWORD dwBufferSize2; BYTE *pb; BLOBHEADER *pBlobHeader; RSAPUBKEY* pRSAPubKey; _ASSERTE(dwDataLen >= sizeof(BLOBHEADER)); pBlobHeader = (BLOBHEADER*)pbData; pbData += sizeof(BLOBHEADER); dwDataLen -= sizeof(BLOBHEADER); switch (pBlobHeader->bType) { case PUBLICKEYBLOB: bPrivate = FALSE; break; case PRIVATEKEYBLOB: bPrivate = TRUE; break; default: goto BadKey; } if (dwDataLen < sizeof(RSAPUBKEY)) { goto BadKey; } pRSAPubKey = (RSAPUBKEY*)pbData; pbData += sizeof(RSAPUBKEY); dwDataLen -= sizeof(RSAPUBKEY); if (GET_UNALIGNED_VAL32(&pRSAPubKey->magic) != (bPrivate ? 0x32415352U : 0x31415352U)) // 'RSA2' : 'RSA1' { goto BadKey; } dwBitLen = GET_UNALIGNED_VAL32(&pRSAPubKey->bitlen); if ((dwBitLen == 0) || (dwBitLen % 16 != 0) || (dwBitLen > 16384)) { goto BadKey; } m_dwBitLen = dwBitLen; dwByteLen1 = dwBitLen / 8; dwByteLen2 = dwByteLen1 / 2; if (dwDataLen != (bPrivate ? (9 * dwByteLen2) : dwByteLen1)) { goto BadKey; } dwBufferSize1 = BigNum::GetBufferSize(dwByteLen1); dwBufferSize2 = BigNum::GetBufferSize(dwByteLen2); m_dwSize = BigNum::GetBufferSize(sizeof(DWORD)) + (bPrivate ? (2 * dwBufferSize1 + 5 * dwBufferSize2) : dwBufferSize1); pb = (BYTE*)malloc(m_dwSize); if (pb == NULL) { SetLastError(ERROR_OUTOFMEMORY); return FALSE; } m_pBlob = pb; m_pExponent = (BigNum*)pb; pb += BigNum::GetBufferSize(sizeof(DWORD)); BigNum::SetBytes(m_pExponent, (BYTE*)&pRSAPubKey->pubexp, sizeof(DWORD)); #define HELPER(m_pMember, size) \ m_pMember = (BigNum*)pb; \ pb += dwBufferSize##size; \ BigNum::SetBytes(m_pMember, pbData, dwByteLen##size); \ pbData += dwByteLen##size; HELPER(m_pModulus, 1); if (!bPrivate) return TRUE; HELPER(m_pPrime1, 2); HELPER(m_pPrime2, 2); HELPER(m_pExponent1, 2); HELPER(m_pExponent2, 2); HELPER(m_pCoefficient, 2); HELPER(m_pPrivateExponent, 1); #undef HELPER if (!CheckKey()) { ClearStack(); goto BadKey; } ClearStack(); GetProvider()->SetSignatureKey(this); return TRUE; BadKey: SetLastError(NTE_BAD_KEY); return FALSE; } BOOL RSAKey::ExportKey(DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen) { DWORD dwByteLen1; DWORD dwByteLen2; DWORD dwDataLen; BOOL bPrivate; BLOBHEADER *pBlobHeader; RSAPUBKEY* pRSAPubKey; if ((dwBlobType != PUBLICKEYBLOB) && ((dwBlobType != PRIVATEKEYBLOB) || (m_pPrivateExponent == NULL))) { SetLastError(NTE_BAD_TYPE); return FALSE; } bPrivate = (dwBlobType != PUBLICKEYBLOB); if (dwFlags != 0) { SetLastError(NTE_BAD_FLAGS); return FALSE; } dwByteLen1 = m_dwBitLen / 8; dwByteLen2 = dwByteLen1 / 2; dwDataLen = (pbData != NULL) ? *pdwDataLen : 0; *pdwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (bPrivate ? (2 * dwByteLen1 + 5 * dwByteLen2) : dwByteLen1); if (dwDataLen < *pdwDataLen) { if (pbData != NULL) { SetLastError(ERROR_MORE_DATA); return FALSE; } return TRUE; } pBlobHeader = (BLOBHEADER *)pbData; pbData += sizeof(BLOBHEADER); pBlobHeader->bType = (BYTE)dwBlobType; pBlobHeader->bVersion = 0x02; SET_UNALIGNED_VAL16(&pBlobHeader->reserved, 0x0000); SET_UNALIGNED_VAL32(&pBlobHeader->aiKeyAlg, CALG_RSA_SIGN); pRSAPubKey = (RSAPUBKEY*)pbData; pbData += sizeof(RSAPUBKEY); SET_UNALIGNED_VAL32(&pRSAPubKey->magic, bPrivate ? 0x32415352 : 0x31415352); // 'RSA2' : 'RSA1' SET_UNALIGNED_VAL32(&pRSAPubKey->bitlen, m_dwBitLen); BigNum::GetBytes(m_pExponent, (BYTE*)&pRSAPubKey->pubexp, sizeof(DWORD)); #define HELPER(m_pMember, size) \ BigNum::GetBytes(m_pMember, pbData, dwByteLen##size); \ pbData += dwByteLen##size; HELPER(m_pModulus, 1); if (dwBlobType == PUBLICKEYBLOB) return TRUE; HELPER(m_pPrime1, 2); HELPER(m_pPrime2, 2); HELPER(m_pExponent1, 2); HELPER(m_pExponent2, 2); HELPER(m_pCoefficient, 2); HELPER(m_pPrivateExponent, 1); #undef HELPER return TRUE; } BOOL RSAKey::GetKeyParam(DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags) { DWORD dwDataLen = (pbData != NULL) ? *pdwDataLen : NULL; switch (dwParam) { case KP_ALGID: *pdwDataLen = sizeof(ALG_ID); if (dwDataLen < *pdwDataLen) goto MoreData; *(ALG_ID*)pbData = CALG_RSA_SIGN; return TRUE; case KP_KEYLEN: *pdwDataLen = sizeof(DWORD); if (dwDataLen < *pdwDataLen) goto MoreData; *(DWORD*)pbData = m_dwBitLen; return TRUE; default: SetLastError(NTE_BAD_TYPE); return FALSE; } MoreData: if (pbData != NULL) { SetLastError(ERROR_MORE_DATA); return FALSE; } return TRUE; } DWORD RSAKey::GetSignatureLength() { return m_dwBitLen / 8; } BOOL RSAKey::EncryptSignature(CONST BYTE *pbSrc, BYTE *pbDest) { DWORD dwBufferSize; BigNum * pResult; DWORD dwLen; _ASSERTE(m_pPrivateExponent != NULL); dwBufferSize = BigNum::GetBufferSizeFromBits(m_dwBitLen); pResult = (BigNum*)alloca(dwBufferSize); dwLen = GetSignatureLength(); BigNum::SetBytes(pResult, pbSrc, dwLen); BigNum::PowMod(pResult, pResult, m_pPrivateExponent, m_pModulus); BigNum::GetBytes(pResult, pbDest, dwLen); return TRUE; } BOOL RSAKey::DecryptSignature(CONST BYTE *pbSrc, BYTE *pbDest) { DWORD dwBufferSize; BigNum * pResult; DWORD dwLen; dwBufferSize = BigNum::GetBufferSizeFromBits(m_dwBitLen); pResult = (BigNum*)alloca(dwBufferSize); dwLen = GetSignatureLength(); BigNum::SetBytes(pResult, pbSrc, dwLen); BigNum::PowMod(pResult, pResult, m_pExponent, m_pModulus); BigNum::GetBytes(pResult, pbDest, dwLen); return TRUE; } /***************** Crypto APIs **********************************/ EXTERN_C BOOL PALAPI CryptAcquireContextA( HCRYPTPROV *phProv, LPCSTR szContainer, LPCSTR szProvider, DWORD dwProvType, DWORD dwFlags) { _ASSERTE(szContainer == NULL); _ASSERTE(szProvider == NULL); return CryptAcquireContextW(phProv, NULL, NULL, dwProvType, dwFlags); } EXTERN_C BOOL PALAPI CryptAcquireContextW( HCRYPTPROV *phProv, LPCWSTR szContainer, LPCWSTR szProvider, DWORD dwProvType, DWORD dwFlags) { CryptProvider* pProvider; _ASSERTE(szContainer == NULL); _ASSERTE(szProvider == NULL); pProvider = new CryptProvider(); if (pProvider == NULL) { SetLastError(ERROR_OUTOFMEMORY); return FALSE; } *phProv = (HCRYPTPROV)pProvider; return TRUE; } EXTERN_C BOOL PALAPI CryptReleaseContext( HCRYPTPROV hProv, DWORD dwFlags) { if (hProv == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } RELEASE(hProv); return TRUE; } EXTERN_C BOOL PALAPI CryptCreateHash( HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, HCRYPTHASH *phHash) { CryptHash * pHash; if (hProv == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } if (hKey != NULL) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } if (dwFlags != 0) { SetLastError(NTE_BAD_FLAGS); return FALSE; } switch (Algid) { case CALG_MD5: pHash = new MD5Hash(); break; case CALG_SHA1: pHash = new SHA1Hash(); break; default: SetLastError(NTE_BAD_ALGID); return FALSE; } if (pHash == NULL) { SetLastError(ERROR_OUTOFMEMORY); return FALSE; } pHash->SetProvider((CryptProvider*)hProv); if (!pHash->Initialize()) { RELEASE(pHash); return FALSE; } *phHash = (HCRYPTHASH)pHash; return TRUE; } EXTERN_C BOOL PALAPI CryptDestroyHash( HCRYPTHASH hHash) { if (hHash == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } RELEASE(hHash); return TRUE; } EXTERN_C BOOL PALAPI CryptHashData( HCRYPTHASH hHash, CONST BYTE *pbData, DWORD dwDataLen, DWORD dwFlags) { if (hHash == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } return ((CryptHash*)hHash)->HashData(pbData, dwDataLen, dwFlags); } EXTERN_C BOOL PALAPI CryptGetHashParam( HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags) { if (hHash == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } return ((CryptHash*)hHash)->GetHashParam(dwParam, pbData, pdwDataLen, dwFlags); } static BOOL CreateKeyObject(HCRYPTPROV hProv, ALG_ID Algid, CryptKey** ppKey) { CryptKey* pKey = NULL; switch (Algid) { case CALG_RSA_SIGN: pKey = new RSAKey(); break; default: SetLastError(NTE_BAD_ALGID); return FALSE; } if (pKey == NULL) { SetLastError(ERROR_OUTOFMEMORY); return FALSE; } pKey->SetProvider((CryptProvider*)hProv); *ppKey = pKey; return TRUE; } EXTERN_C BOOL PALAPI CryptGenKey( HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey) { CryptKey* pKey; if (hProv == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } // substitute the default algorithm if (Algid == AT_SIGNATURE) Algid = CALG_RSA_SIGN; if (!CreateKeyObject(hProv, Algid, &pKey)) { return FALSE; } pKey->SetFlags(dwFlags & CRYPT_EXPORTABLE); if (!pKey->GenKey(dwFlags)) { RELEASE(pKey); return FALSE; } *phKey = (HCRYPTKEY)pKey; return TRUE; } EXTERN_C BOOL PALAPI CryptDestroyKey( HCRYPTKEY hKey) { if (hKey == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } RELEASE(hKey); return TRUE; } EXTERN_C BOOL PALAPI CryptImportKey( HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen, HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey) { CryptKey* pKey; BLOBHEADER *pBlobHeader; if (hProv == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } if (hPubKey != NULL) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } if (dwDataLen < sizeof(BLOBHEADER)) { goto BadKey; } pBlobHeader = (BLOBHEADER*)pbData; if ((pBlobHeader->bVersion != 0x02) || GET_UNALIGNED_VAL16(&pBlobHeader->reserved) != 0x0000) { goto BadKey; } if (!CreateKeyObject(hProv, GET_UNALIGNED_VAL32(&pBlobHeader->aiKeyAlg), &pKey)) { return FALSE; } pKey->SetFlags(dwFlags & CRYPT_EXPORTABLE); if (!pKey->ImportKey(dwFlags, pbData, dwDataLen)) { RELEASE(pKey); return FALSE; } *phKey = (HCRYPTKEY)pKey; return TRUE; BadKey: SetLastError(NTE_BAD_KEY); return FALSE; } EXTERN_C BOOL PALAPI CryptExportKey( HCRYPTKEY hKey, HCRYPTKEY hExpKey, DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen) { if (hKey == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } if (hExpKey != NULL) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } if ((dwBlobType == PRIVATEKEYBLOB) && !(((CryptKey*)hKey)->GetFlags() & CRYPT_EXPORTABLE)) { SetLastError(NTE_BAD_KEY_STATE); return FALSE; } return ((CryptKey*)hKey)->ExportKey(dwBlobType, dwFlags, pbData, pdwDataLen); } EXTERN_C BOOL PALAPI CryptGetKeyParam( HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags) { if (hKey == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } return ((CryptKey*)hKey)->GetKeyParam(dwParam, pbData, pdwDataLen, dwFlags); } static void meminv(void* p, size_t len) { BYTE* p1 = (BYTE*)p; BYTE* p2 = (BYTE*)p + (len-1); while (p1 < p2) { BYTE t = *p1; *p1 = *p2; *p2 = t; p1++; p2--; } } static BOOL GetSignature(HCRYPTHASH hHash, BYTE *pbSignature, DWORD dwSize) { DWORD dwHashLen; DWORD dwOIDLen; dwHashLen = dwSize; if (!((CryptHash*)hHash)->GetHashParam(HP_HASHVAL, pbSignature, &dwHashLen, 0)) { return FALSE; } meminv(pbSignature, dwHashLen); dwSize -= dwHashLen; pbSignature += dwHashLen; if (dwSize <= 3) { SetLastError(NTE_BAD_SIGNATURE); return FALSE; } dwOIDLen = dwSize - 3; if (!((CryptHash*)hHash)->GetSignatureMagic(pbSignature, &dwOIDLen)) { SetLastError(NTE_BAD_SIGNATURE); return FALSE; } meminv(pbSignature, dwOIDLen); pbSignature += dwOIDLen; dwSize -= dwOIDLen; *pbSignature++ = 0x00; // reserved dwSize--; while (dwSize > 2) { *pbSignature++ = 0xFF; // padding dwSize--; } *pbSignature++ = 0x01; // block type dwSize--; *pbSignature++ = 0x00; // reserved dwSize--; _ASSERTE(dwSize == 0); return TRUE; } EXTERN_C BOOL PALAPI CryptVerifySignatureA( HCRYPTHASH hHash, CONST BYTE *pbSignature, DWORD dwSigLen, HCRYPTKEY hPubKey, LPCSTR szDescription, DWORD dwFlags) { _ASSERTE(szDescription == NULL); return CryptVerifySignatureW(hHash, pbSignature, dwSigLen, hPubKey, NULL, dwFlags); } EXTERN_C BOOL PALAPI CryptVerifySignatureW( HCRYPTHASH hHash, CONST BYTE *pbSignature, DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR szDescription, DWORD dwFlags) { BYTE *pbDecryptedSignature; BYTE *pbMasterSignature; CryptKey *pKey; if ((hHash == NULL) || (hPubKey == NULL)) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } if (dwFlags != 0) { SetLastError(NTE_BAD_FLAGS); return FALSE; } _ASSERTE(szDescription == NULL); pKey = (CryptKey*)hPubKey; if (dwSigLen != pKey->GetSignatureLength()) { SetLastError(NTE_SIGNATURE_FILE_BAD); return FALSE; } pbDecryptedSignature = (BYTE*)alloca(dwSigLen); if (!pKey->DecryptSignature(pbSignature, pbDecryptedSignature)) { return FALSE; } pbMasterSignature = (BYTE*)alloca(dwSigLen); if (!GetSignature(hHash, pbMasterSignature, dwSigLen)) { return FALSE; } if (memcmp(pbMasterSignature, pbDecryptedSignature, dwSigLen) != 0) { SetLastError(NTE_BAD_SIGNATURE); return FALSE; } return TRUE; } EXTERN_C BOOL PALAPI CryptSignHashA( HCRYPTHASH hHash, DWORD dwKeySpec, LPCSTR szDescription, DWORD dwFlags, BYTE *pbSignature, DWORD *pdwSigLen) { _ASSERTE(szDescription == NULL); return CryptSignHashW(hHash, dwKeySpec, NULL, dwFlags, pbSignature, pdwSigLen); } EXTERN_C BOOL PALAPI CryptSignHashW( HCRYPTHASH hHash, DWORD dwKeySpec, LPCWSTR szDescription, DWORD dwFlags, BYTE *pbSignature, DWORD *pdwSigLen) { CryptKey* pKey; BYTE* pbMasterSignature; BYTE* pbDecryptedSignature; DWORD dwSigLen; DWORD dwDataLen; if (hHash == NULL) { SetLastError(ERROR_INVALID_HANDLE); return FALSE; } if (dwKeySpec != AT_SIGNATURE) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } _ASSERTE(szDescription == NULL); if (dwFlags != 0) { SetLastError(NTE_BAD_FLAGS); return FALSE; } pKey = ((CryptHash*)hHash)->GetProvider()->GetSignatureKey(); if (pKey == NULL) { SetLastError(NTE_NO_KEY); return FALSE; } dwSigLen = pKey->GetSignatureLength(); dwDataLen = (pbSignature != NULL) ? *pdwSigLen : 0; *pdwSigLen = dwSigLen; if (dwDataLen < *pdwSigLen) { if (pbSignature != NULL) { SetLastError(ERROR_MORE_DATA); return FALSE; } return TRUE; } pbMasterSignature = (BYTE*)alloca(dwSigLen); if (!GetSignature(hHash, pbMasterSignature, dwSigLen)) { return FALSE; } if (!pKey->EncryptSignature(pbMasterSignature, pbSignature)) { return FALSE; } // check the roundtrip pbDecryptedSignature = (BYTE*)alloca(dwSigLen); if (!pKey->DecryptSignature(pbSignature, pbDecryptedSignature)) { return FALSE; } if (memcmp(pbMasterSignature, pbDecryptedSignature, dwSigLen) != 0) { _ASSERTE(false); SetLastError(NTE_FAIL); return FALSE; } return TRUE; }
21.425172
105
0.603168
intj-t
de14006aadce629e04f053adafdb5bc6394c0d07
11,306
cpp
C++
SimTest/geoTest.cpp
doplusplus/Physics_Simulator
f562b07fe7c3e245c0ebc9d5618fe0c09114126c
[ "MIT" ]
null
null
null
SimTest/geoTest.cpp
doplusplus/Physics_Simulator
f562b07fe7c3e245c0ebc9d5618fe0c09114126c
[ "MIT" ]
1
2015-09-03T08:03:12.000Z
2015-10-06T20:11:48.000Z
SimTest/geoTest.cpp
doplusplus/PointSimulator
f562b07fe7c3e245c0ebc9d5618fe0c09114126c
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "CppUnitTest.h" #include "..\SimModule\Geo.h" #include <limits> #include <iostream> //#include <functional> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTesting { const double accuracy = double(1e-10); //approximately the diameter of an hydrogen atom in meter const double rangeOfInterest = 12742000; //earth diameter const double LOWEST = std::numeric_limits<double>::lowest(); const double MIN = std::numeric_limits<double>::min(); const double MAX = std::numeric_limits<double>::max(); TEST_CLASS(CartesianTest) { public: TEST_METHOD(ParameterlessCartesian) { CartesianElement C; Assert::IsTrue(C == CartesianElement(0, 0, 0)); } TEST_METHOD(CopyConstructor) { CartesianElement C(1234142.124214, 2411.24, 45.4500000000787); CartesianElement Copied(C); Assert::IsTrue(C == Copied); } //Operators tests-------------------------------------------------- TEST_METHOD(AdditionTest_integers) { CartesianElement A(1000000, -2000000, 0); CartesianElement B(1, 1, 1); Assert::IsTrue(A + B == CartesianElement(1000001, -1999999, 1)); } TEST_METHOD(AdditionTest_Doublelimits_suitableInterger) { CartesianElement A(1000000, -2000000, 0); CartesianElement B(LOWEST, MAX, MIN); Assert::IsTrue(A + B == CartesianElement(LOWEST + 1000000.0, MAX - 2000000.0, MIN ) ); } TEST_METHOD(AdditionTest_integerfraction) //assumes compiler performs integer division { CartesianElement A(1000000 / 2, -2000001 / 2, 3); CartesianElement B(1000000 / 2, -2000001 / 2, 0); Assert::IsTrue(A + B == CartesianElement(1000000, -2000000, 3)); } TEST_METHOD(multiplication_integersZero) { CartesianElement A(1000000, -2000000, 2); Assert::IsTrue(A * 0 == CartesianElement(0, 0, 0)); } TEST_METHOD(multiplication_doubleZero) { CartesianElement A(1000.04400, -2000.0300, 2.1); Assert::IsTrue(A * 0 == CartesianElement(0, 0, 0)); } TEST_METHOD(multiplication_integerLimits_Zero) { CartesianElement A(std::numeric_limits<int>::lowest(), std::numeric_limits<int>::max(), std::numeric_limits<int>::min()); Assert::IsTrue(A * 0 == CartesianElement(0, 0, 0)); } TEST_METHOD(multiplication_doubleLimits_Zero) { CartesianElement A(LOWEST, MAX, MIN); Assert::IsTrue(A * 0 == CartesianElement(0, 0, 0)); } TEST_METHOD(multiplication_doublelimit_One) { CartesianElement A(LOWEST, MAX, MIN); Assert::IsTrue(A * 1 == CartesianElement(LOWEST, MAX, MIN ) ); } TEST_METHOD(multiplication_by2) { CartesianElement A(0.5, 0.555, 555555.55555); Assert::IsTrue(A * 2 == CartesianElement(1, 1.11, 1111111.1111)); } TEST_METHOD(divide_doubleatlimit_byOne) { CartesianElement A(LOWEST, MAX, MIN); Assert::IsTrue(A / 1 == CartesianElement(LOWEST, MAX, MIN ) ); } TEST_METHOD(divide_doubleatlimit_by0) //Checks how division by zero is handled { auto func = []() { CartesianElement A(LOWEST, MAX, MIN); A / 0; }; Assert::ExpectException<const char[13]>(func); } }; //============================================================================================ TEST_CLASS(PointTests) { public: TEST_METHOD(ParameterlessPoint) { Point C; Assert::IsTrue(C == Point(0, 0, 0)); } TEST_METHOD(PointCopyConstructor) { CartesianElement C(1234142.124214, 2411.24, 45.4500000000787); Point Copied(C); Assert::IsTrue(Point(1234142.124214, 2411.24, 45.4500000000787) == Copied); } //SPECIFIC TO POINT CLASS INTERFACE================================ TEST_METHOD(VectToPoint) { Vect V(2, 352, .5643566); Point P(V); Assert::IsTrue(P == Point(2, 352, .5643566)); } TEST_METHOD(ImagePoint) { Vect V(2, 352, .5643566); Point A(-35353, 342, 4); Point P(A, V); Assert::IsTrue(P == Point(-35351, 694, 4.5643566)); } //=============================================================================== // Element Creation tests-------------------------------------------- //Operators tests-------------------------------------------------- TEST_METHOD(AdditionTest_integers_Point) { Point A(1000000, -2000000, 0); Point B(1, 1, 1); Assert::IsTrue(A + B == Point(1000001, -1999999, 1)); } TEST_METHOD(AdditionTest_Doublelimits_suitableInterger) { Point A(1000000, -2000000, 0); Point B(LOWEST, MAX, MIN); Assert::IsTrue(A + B == Point(LOWEST + 1000000.0, MAX - 2000000.0, MIN ) ); } TEST_METHOD(AdditionTest_integerfraction_Point) //assumes compiler performs integer division { Point A(1000000 / 2, -2000001 / 2, 3); Point B(1000000 / 2, -2000001 / 2, 0); Assert::IsTrue(A + B == Point(1000000, -2000000, 3)); } TEST_METHOD(multiplication_integersZero_Point) { Point A(1000000, -2000000, 2); Assert::IsTrue(A * 0 == Point(0, 0, 0)); } TEST_METHOD(multiplication_doubleZero_Point) { Point A(1000.04400, -2000.0300, 2.1); Assert::IsTrue(A * 0 == Point(0, 0, 0)); } TEST_METHOD(multiplication_integerLimits_Zero_Point) { Point A(std::numeric_limits<int>::lowest(), std::numeric_limits<int>::max(), std::numeric_limits<int>::min()); Assert::IsTrue(A * 0 == Point(0, 0, 0)); } TEST_METHOD(multiplication_doubleLimits_Zero_Point) { Point A(LOWEST, MAX, MIN); Assert::IsTrue(A * 0 == Point(0, 0, 0)); } TEST_METHOD(multiplication_doublelimit_One_Point) { Point A(LOWEST, MAX, MIN); Assert::IsTrue(A * 1 == Point(LOWEST, MAX, MIN ) ); } TEST_METHOD(multiplication_by2_Point) { Point A(0.5, 0.555, 555555.55555); Assert::IsTrue(A * 2 == Point(1, 1.11, 1111111.1111)); } TEST_METHOD(divide_doubleatlimit_byOne_Point) { Point A(LOWEST, MAX, MIN); Assert::IsTrue(A / 1 == Point(LOWEST, MAX, MIN ) ); } TEST_METHOD(divide_doubleatlimit_by0_Point) //Checks how division by zero is handled { auto func = []() { Point A(LOWEST, MAX, MIN); A / 0; }; Assert::ExpectException<const char[13]>(func); } }; //============================================================================================ TEST_CLASS(VectTests) { public: TEST_METHOD(ParameterlessVect) { Vect C; Assert::IsTrue(C == Vect(0, 0, 0)); } TEST_METHOD(VectCopyConstructor) { CartesianElement C(1234142.124214, 2411.24, 45.4500000000787); Vect Copied(C); Assert::IsTrue(Vect(1234142.124214, 2411.24, 45.4500000000787) == Copied); } TEST_METHOD(VectFromPoints) { Point C(1234142.124214, 2411.24, 45.4500000000787); Point D(.34234, 23423, 45634563.346); Assert::IsTrue(Vect(C, D) == Vect(.34234 - 1234142.124214, 23423 - 2411.24, 45634563.346 - 45.4500000000787)); } //==============================FROM BASE CLASS================================================= //Operators tests-------------------------------------------------- TEST_METHOD(AdditionTest_integers_Vect) { Vect A(1000000, -2000000, 0); Vect B(1, 1, 1); Assert::IsTrue(A + B == Vect(1000001, -1999999, 1)); } TEST_METHOD(AdditionTest_Doublelimits_suitableInterger) { Vect A(1000000, -2000000, 0); Vect B(LOWEST, MAX, MIN); Assert::IsTrue(A + B == Vect(LOWEST + 1000000.0, MAX - 2000000.0, MIN ) ); } TEST_METHOD(AdditionTest_integerfraction_Vect) { Vect A(1000000 / 2, -2000001 / 2, 3); Vect B(1000000 / 2, -2000001 / 2, 0); Assert::IsTrue(A + B == Vect(1000000, -2000000, 3)); } TEST_METHOD(divide_doubleatlimit_byOne_Vect) { Vect A(LOWEST, MAX, MIN); Assert::IsTrue(A / 1 == Vect(LOWEST, MAX, MIN ) ); } TEST_METHOD(divideBy0_doubleatlimit_Vect) { auto func = []() { Vect A(LOWEST, MAX, MIN); A / 0; }; Assert::ExpectException<const char[13]>(func); } //========================VECT CLASS SPECIFIC============================================================ TEST_METHOD(VectEquality) { Vect A(LOWEST, MAX, MIN); Vect B(LOWEST, MAX, MIN); Assert::IsTrue(A == B); } TEST_METHOD(VectInequality) //FAIL -- Precision lost for big numbers -- { Vect A(-rangeOfInterest, rangeOfInterest, accuracy); Vect B(1 - rangeOfInterest, rangeOfInterest, accuracy); Assert::IsFalse(A == B); } TEST_METHOD(CanonicVectorialProducts) { Vect x(1, 0, 0), y(0, 1, 0), z(0, 0, 1); Assert::IsTrue((x^y) == z); Assert::IsTrue((y^z) == x); Assert::IsTrue((z^x) == y); Assert::IsTrue((y^x) == -z); Assert::IsTrue((z^y) == -x); Assert::IsTrue((x^z) == -y); } TEST_METHOD(LimitsVectorialProducts) { Vect v(-rangeOfInterest, accuracy, rangeOfInterest), u(1, 1, 1); Assert::IsTrue((v^u) == Vect(accuracy-rangeOfInterest, 2*rangeOfInterest, -accuracy - rangeOfInterest)); } TEST_METHOD(ScalarProductLimits) { Vect a(MIN, MAX, 1), b(LOWEST, LOWEST, 1); Assert::IsTrue(a*b == MIN*LOWEST + MAX*LOWEST + 1); } TEST_METHOD(CanonicScalarlProducts) { Vect x(1, 0, 0), y(0, 1, 0), z(0, 0, 1); Assert::IsTrue((x*y) == 0); Assert::IsTrue((y*z) == 0); Assert::IsTrue((z*x) == 0); } TEST_METHOD(NormalityTest) { Vect l(234, 0, 0); Vect mn(0, 453415.451454, 0); Vect mx(0, 0, .001000262434); Assert::IsTrue(l.norm() == 234); Assert::IsTrue(mn.norm() == 453415.451454); Assert::IsTrue(mx.norm() == .001000262434); } TEST_METHOD(limitNormalityTest) { Vect l(-rangeOfInterest, 0, 0); Vect mn(0, accuracy, 0); Vect mx(0, 0, rangeOfInterest); Assert::IsTrue(l.norm() == rangeOfInterest); Assert::IsTrue(mn.norm() == accuracy); Assert::IsTrue(mx.norm() == rangeOfInterest); } TEST_METHOD(limitNormOfVectorialProduct) { Vect l(-rangeOfInterest, 0, 0); Vect mn(0, accuracy, 0); Vect mx(0, rangeOfInterest, 0); Assert::IsTrue(((l^mn) ^ mx).norm() == rangeOfInterest*rangeOfInterest*accuracy); } TEST_METHOD(NormOfVectorialProduct) { Vect l(234, 0, 0); Vect mn(0, 453415.451454, 0); Vect mx(0, .001000262434, 0); Assert::IsTrue(((l^mn) ^ mx).norm() == 234 * 453415.451454*.001000262434); } TEST_METHOD(UnityVectNormAndDirection) { Vect l(2, 978.98, 78989); Assert::IsTrue(l.unitVector().norm() == 1); Assert::IsTrue(l.unitVector() * l == l.norm()); } TEST_METHOD(UnityVectorialLow) { Vect l(2, 9, 9); Assert::IsTrue((l.unitVector() ^ l) == Vect(0, 0, 0)); } TEST_METHOD(UnityVectorialHigh) { Vect l(2, 978.98, 78989); Assert::IsTrue((l.unitVector() ^ l) < Vect(accuracy, accuracy, accuracy)); } TEST_METHOD(LimitsUnitNorm) { Vect l(-rangeOfInterest, accuracy, rangeOfInterest); Assert::IsTrue(l.unitVector().norm() == 1); } TEST_METHOD(LimitsUnitScalar) //rounding error in e-6 { Vect l(-rangeOfInterest, accuracy, rangeOfInterest); Assert::IsTrue(abs(l.unitVector() * l - l.norm()) < accuracy); } TEST_METHOD(VectFunctionAddition_Null) { std::function<Vect(Vect, double)> a = Vect::constant; std::function<Vect(Vect, double)> b = Vect::linear; std::function<Vect(Vect, double)> s = a +b; Assert::IsTrue(s(Vect(0,0,0),0)== Vect(0, 0, 0)); } }; }
22.748491
124
0.600566
doplusplus
de225012c6fd445c0e43e312708646c96b1afeeb
1,212
hpp
C++
FPSWidget.hpp
karol57/HBreakout
edbae192dc8e8dfe564c2e011d9090703b3b0ab0
[ "MIT" ]
null
null
null
FPSWidget.hpp
karol57/HBreakout
edbae192dc8e8dfe564c2e011d9090703b3b0ab0
[ "MIT" ]
null
null
null
FPSWidget.hpp
karol57/HBreakout
edbae192dc8e8dfe564c2e011d9090703b3b0ab0
[ "MIT" ]
null
null
null
// // Created by Karol on 03.09.2016. // #ifndef SDLTEST_FPSWIDGET_HPP #define SDLTEST_FPSWIDGET_HPP #include <SDL_render.h> #include "FontMenager.hpp" #include "SDL_memory.hpp" #include "BasicDTMenager.hpp" class FPSWidget { public: FPSWidget(); ~FPSWidget(); bool init(SDL_Renderer * render) noexcept; void deinit() noexcept; void update(double dt) noexcept; void updateTexture(SDL_Renderer * renderer, FontMenager& fnt_mgr, unsigned fid) noexcept; SDL_Texture * texture() { return m_buffer.get(); } unsigned width() const noexcept { return m_width; } unsigned height() const noexcept { return m_height; } private: BasicDTMenager<double, 1024u> m_dt_mgr; double m_currMaxDT{1.0}; // Maximum delta time (ms) shown on graph double m_destMaxDT{1.0}; // Maximum delta time (ms) that should'be shown on graph double m_maxDTVel{0.0}; // Velcoty (ms/ms) - how fast m_currMaxDT will be going to m_destMaxDT unsigned m_width{256u+128u}; // Width of the widget unsigned m_height{128u}; // Height of the widget SDL_Texture_uptr m_buffer; }; #endif // !SDLTEST_FPSWIDGET_HPP
30.3
103
0.670792
karol57
de22b7f8bd845ae18bf0fcfa8ce2484254f8c5c8
8,187
cpp
C++
LJ2/City.cpp
huwlloyd-mmu/LockdownEngine
34a6c3a797173cfc2ce98b01643c64d4ec3bcec2
[ "MIT" ]
null
null
null
LJ2/City.cpp
huwlloyd-mmu/LockdownEngine
34a6c3a797173cfc2ce98b01643c64d4ec3bcec2
[ "MIT" ]
null
null
null
LJ2/City.cpp
huwlloyd-mmu/LockdownEngine
34a6c3a797173cfc2ce98b01643c64d4ec3bcec2
[ "MIT" ]
null
null
null
#include "City.h" #include "LockdownEngine.h" #include "IsoMap.h" #include "Walkways.h" #include "roads.h" #include "AnimatedSprite.h" #include "DbgPosition.h" #include "Vehicle.h" void CityUpdater::Update(float dt) { city->Update(dt); } int City::GetTextureForTile( int i, int j) { // used for building the base map, to figure out the road textures etc. bool here, above, below, left, right; here = tiles[i][j] == 1 || tiles[i][j] == 2; below = j > 0 && tiles[i][j - 1] == 1; above = j < ny - 1 && tiles[i][j + 1] == 1; left = i > 0 && tiles[i - 1][j] == 1; right = i < nx - 1 && tiles[i + 1][j] == 1; if (!here) { // not a road tile, but maybe a pavement tile if (below) { if (!right && !left) return 2; else if (right) return 12; else return 4; } if (above) { if (!right && !left) return 2; else if (right) return 27; else return 20; } return 2; } else { // is this a junction tile? if (tiles[i][j] == 2) return 8; // figure out what sort of road tile // first check junctions bool jbelow = j > 0 && tiles[i][j - 1] == 2; bool jabove = j < ny - 1 && tiles[i][j + 1] == 2; bool jleft = i > 0 && tiles[i - 1][j] == 2; bool jright = i < nx - 1 && tiles[i + 1][j] == 2; if (jabove && !left) return 22; if (jabove && !right) return 14; if (jbelow && !left ) return 23; if (jbelow && !right) return 15; if (jleft && !above) return 30; if (jleft && !below) return 7; if (jright && !above) return 29; if (jright && !below) return 6; if (below && !above) return 16; if (above && !below) return 24; if (left && !right) return 1; if (right && !left) return 9; } } City::City() { // initialize the tiles for (int i = 0; i < nx; i++) { std::vector<unsigned int> column; for (int j = 0; j < ny; j++) { column.push_back(0); } tiles.push_back(column); } // make some roads for (int i = 0; i < nx; i++) { for (int j = 0; j < ny; j++) { if ( ((i % blockSizeX) < roadWidth) || ((j % blockSizeY) < roadWidth) ) { tiles[i][j] = 1; // regular road } if ( ((i % blockSizeX) < roadWidth) && ((j % blockSizeY) < roadWidth)) { tiles[i][j] = 2; // junction } } } // now make the tilemap LE::GameObject* obj = new LE::GameObject(); //new DebugPosition(this); isoMap = new LE::IsoMapComponent(nx, ny, 1.0f); for (int i = 0; i < 4; i++) { for (int j = 0; j < 8; j++) { LE::Texture tex("data/econU_tiles.png", LE::Vec2(i * 0.25f, j * 0.125f), LE::Vec2(0.25f, 0.125f)); isoMap->AddTile(tex); } } for (int i = 0; i < nx; i++) { for (int j = 0; j < ny; j++) { isoMap->SetCell(i, j, GetTextureForTile(i, j)); } } isoMap->CreateSprites(); obj->AddComponent(isoMap); LE::Game::AddToLevel(obj); roads = new Roads(this); walkways = new Walkways(this); // add some pedestrians MakePedProtos(); for (int i = 0; i < 500; i++) { peds.push_back(new Pedestrian(this)); } // add some vehicles MakeVehicleProtos(); for (int i = 0; i < 200; i++) { vehicles.push_back(new Vehicle(this)); } // add the updater game object updater = new LE::GameObject(); updater->AddComponent(new CityUpdater(this)); LE::Game::AddToLevel(updater); // add buildings PlaceBuildings(); } void City::Update(float dt) { for (auto p : peds) p->Update(dt); for (auto v : vehicles) v->Update(dt); } void City::MakeVehicleProtos() { std::string texFiles[6] = { "data/black_vehicles.png","data/blue_vehicles.png", "data/white_vehicles.png", "data/grey_vehicles.png", "data/red_vehicles.png", "data/yellow_vehicles.png" }; int count = 0; for (int i = 0; i < 6; i++) { for (int j = 0; j < 8; j++) { LE::Texture* frames[4]; for (int k = 0; k < 4; k++) { frames[k] = new LE::Texture(texFiles[i], LE::Vec2(k * 0.25f, j * 0.125f), LE::Vec2(0.125f, 0.125f)); } LE::AnimatedSpriteComponent* sc = new LE::AnimatedSpriteComponent(vehicleSpriteSize); std::vector<LE::Texture*> mode; std::string names[4] = { "up", "left", "down", "right" }; sc->SetClip(); sc->SetSort(); for (int k = 0; k < 4; k++) { mode.clear(); mode.push_back(frames[k]); LE::Animation* anim = new LE::Animation(mode, 100.0f, false); sc->AddMode(names[k], anim); } vehicleProtos[count] = new LE::GameObject(); vehicleProtos[count]->AddComponent(sc); ++count; } } } void City::MakePedProtos() { for (int j = 0; j < 25; j++) { // load the textures LE::Texture* animFrames[36]; for (int i = 0; i < 36; i++) { int xOffset = i + i / 9; // i/9 is to skip the sitting animation animFrames[i] = new LE::Texture("data/people.png", LE::Vec2((float)xOffset * (32.0f / 1376.0f), j*(1.0f/25.0f)), LE::Vec2(32.0f / 1376.0f, 1.0f / 25.0f)); } LE::AnimatedSpriteComponent* sc = new LE::AnimatedSpriteComponent(1.0f); sc->SetClip(); sc->SetSort(); std::vector<LE::Texture*> mode; std::string names[8] = { "stand_up", "stand_right", "stand_left", "stand_down", "walk_up", "walk_right", "walk_left", "walk_down" }; for (int i = 0; i < 4; i++) { // add the stand mode mode.push_back(animFrames[i * 9]); LE::Animation* anim = new LE::Animation(mode, 15.0f, true); sc->AddMode(names[i], anim); mode.clear(); for (int j = 0; j < 8; j++) mode.push_back(animFrames[i * 9 + j]); anim = new LE::Animation(mode, 15.0f, true); sc->AddMode(names[i + 4], anim); } pedProto[j] = new LE::GameObject(); pedProto[j]->AddComponent(sc); } } void City::PlaceBuildings() { // for now, we'll have one building type struct buildingtex { float x0 = 256; float x1 = 512; float y0 = 0; float y1 = 160; }; float yoffs0[] = { 0,160,320,480,704,837,1024,1277 }; float yoffs1[] = { 0,160,320,480,640,800,992,1127 }; std::vector<LE::Texture*> textures; std::vector<buildingtex> tile_data; for (int i = 1; i < 8; i++) { buildingtex details; details.x0 = 256; details.x1 = 512; details.y0 = yoffs1[i - 1]; details.y1 = yoffs1[i]; LE::Texture* tile = new LE::Texture("data/econU_buildings_1.png", LE::Vec2(details.x0 / 1280.0, details.y0 / 1280.0), LE::Vec2(256.0 / 1280.0, (details.y1 - details.y0) / 1280.0f)); textures.push_back(tile); tile_data.push_back(details); } for (int i = 1; i < 8; i++) { buildingtex details; details.x0 = 0; details.x1 = 256; details.y0 = yoffs0[i - 1]; details.y1 = yoffs0[i]; LE::Texture* tile = new LE::Texture("data/econU_buildings_1.png", LE::Vec2(details.x0 / 1280.0, details.y0 / 1280.0), LE::Vec2(256.0 / 1280.0, (details.y1 - details.y0) / 1280.0f)); textures.push_back(tile); tile_data.push_back(details); } std::mt19937 rng = std::mt19937(std::random_device()()); std::uniform_int_distribution<int> dist(0, size(tile_data) - 1); int buildingSize = blockSizeY - 4; for (int x = 3; x < nx-blockSizeX; x += blockSizeX) { for (int y = 3; y < ny-blockSizeY ; y += blockSizeY) { for (int xo = 0; xo < 2; xo++) { float x0, x1, y0, y1; LE::Texture* tex; // pick a random building int ib = dist(rng); x0 = tile_data[ib].x0; x1 = tile_data[ib].x1; y0 = tile_data[ib].y0; y1 = tile_data[ib].y1; // place a building Vec2 centre = Vec2(x+xo*(buildingSize+2), y) + Vec2(buildingSize, buildingSize) * 0.5f; Vec2 isoPos = isoMap->MapToIso(centre); float width = buildingSize * 2.0f; float height = width * (y1 - y0) / (x1 - x0); float yOffset = ((y1 - y0) / (x1 - x0) - 0.5f) * buildingSize; Vec2 spriteCentre = isoPos - Vec2(0, yOffset); spriteCentre -= Vec2(width * 0.5, height * 0.5); SpriteComponent* sc = new SpriteComponent(*textures[ib], width); sc->SetClip(); sc->SetSort(); sc->SetZ(isoPos.y); GameObject* obj = new GameObject(); obj->SetPosition(spriteCentre); obj->AddComponent(sc); Game::AddToLevel(obj); } } } } int City::FindNearestPedestrian(const LE::Vec2& pos) { float minDist = 1e20f; int nearest = -1; for (int i = 0; i < peds.size(); i++) { float dist = (peds[i]->GetPos() - pos).magnsqrd(); if (dist < minDist) { minDist = dist; nearest = i; } } return nearest; }
23.938596
183
0.58654
huwlloyd-mmu
de2a411bfc13f4b4ade1f457efb6cbed9069cb98
862
cpp
C++
tutorial/int-vector-tutorial.cpp
qPCR4vir/sdsl-lite
3ae7ac30c3837553cf20243cc3df8ee658b9f00f
[ "BSD-3-Clause" ]
20
2017-12-26T16:04:18.000Z
2022-02-09T03:30:13.000Z
tutorial/int-vector-tutorial.cpp
Irallia/sdsl-lite
9a0d5676fd09fb8b52af214eca2d5809c9a32dbe
[ "BSD-3-Clause" ]
6
2018-11-12T15:14:24.000Z
2021-04-29T14:07:13.000Z
tutorial/int-vector-tutorial.cpp
Irallia/sdsl-lite
9a0d5676fd09fb8b52af214eca2d5809c9a32dbe
[ "BSD-3-Clause" ]
4
2018-11-12T14:36:34.000Z
2021-01-26T22:16:32.000Z
#include <sdsl/vectors.hpp> #include <iostream> using namespace sdsl; using namespace std; int main() { std::string tmp_file = "tmp_file.sdsl"; { // generate int_vector and store to a file int_vector<> v = {1,3,5,7,2,3,4,9,8,7,10,1}; store_to_file(v, tmp_file); } { // use int_vector_buffer to open the file int_vector_buffer<> ivb(tmp_file); // output elements and assign 42 to each of them for (auto x : ivb) { cout << x << endl; x = 42; } // int_vector_buffer is destroy at the end of the // scope and all value are written to disk } { // read vector from file and output it int_vector<> v; load_from_file(v, tmp_file); cout << v << endl; } // delete temporary file sdsl::remove(tmp_file); }
24.628571
57
0.564965
qPCR4vir
de3453ed179287a0898b8d9239d2962527ed96f8
475
cpp
C++
2018/2018020401-delta/main.cpp
maku693/daily-snippets
53e3a516eeb293b3c11055db1b87d54284e6ac52
[ "MIT" ]
null
null
null
2018/2018020401-delta/main.cpp
maku693/daily-snippets
53e3a516eeb293b3c11055db1b87d54284e6ac52
[ "MIT" ]
null
null
null
2018/2018020401-delta/main.cpp
maku693/daily-snippets
53e3a516eeb293b3c11055db1b87d54284e6ac52
[ "MIT" ]
null
null
null
#include <iostream> #include <chrono> template <class T> void put_delta(const T& delta) { std::cout << "delta: " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " msec\n"; } int main() { auto last_time = std::chrono::high_resolution_clock::now(); while(std::cin.get()) { const auto now = std::chrono::high_resolution_clock::now(); put_delta(now - last_time); last_time = now; } }
21.590909
79
0.591579
maku693
de37e23b404644f88403c2cdf810f7fd060d7492
5,186
cpp
C++
samples/SpeechRecognition/src/Main.cpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
856
2018-03-09T17:26:23.000Z
2022-03-24T21:31:33.000Z
samples/SpeechRecognition/src/Main.cpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
623
2018-03-13T04:40:42.000Z
2022-03-31T09:45:17.000Z
samples/SpeechRecognition/src/Main.cpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
284
2018-03-09T23:05:28.000Z
2022-03-29T14:42:28.000Z
// // Copyright © 2020 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include <iostream> #include <map> #include <vector> #include <algorithm> #include <cmath> #include "CmdArgsParser.hpp" #include "ArmnnNetworkExecutor.hpp" #include "AudioCapture.hpp" #include "Preprocess.hpp" #include "Decoder.hpp" #include "SpeechRecognitionPipeline.hpp" using InferenceResult = std::vector<int8_t>; using InferenceResults = std::vector<InferenceResult>; const std::string AUDIO_FILE_PATH = "--audio-file-path"; const std::string MODEL_FILE_PATH = "--model-file-path"; const std::string LABEL_PATH = "--label-path"; const std::string PREFERRED_BACKENDS = "--preferred-backends"; const std::string HELP = "--help"; std::map<int, std::string> labels = { {0, "a" }, {1, "b" }, {2, "c" }, {3, "d" }, {4, "e" }, {5, "f" }, {6, "g" }, {7, "h" }, {8, "i" }, {9, "j" }, {10,"k" }, {11,"l" }, {12,"m" }, {13,"n" }, {14,"o" }, {15,"p" }, {16,"q" }, {17,"r" }, {18,"s" }, {19,"t" }, {20,"u" }, {21,"v" }, {22,"w" }, {23,"x" }, {24,"y" }, {25,"z" }, {26, "\'" }, {27, " "}, {28,"$" } }; /* * The accepted options for this Speech Recognition executable */ static std::map<std::string, std::string> CMD_OPTIONS = { {AUDIO_FILE_PATH, "[REQUIRED] Path to the Audio file to run speech recognition on"}, {MODEL_FILE_PATH, "[REQUIRED] Path to the Speech Recognition model to use"}, {PREFERRED_BACKENDS, "[OPTIONAL] Takes the preferred backends in preference order, separated by comma." " For example: CpuAcc,GpuAcc,CpuRef. Accepted options: [CpuAcc, CpuRef, GpuAcc]." " Defaults to CpuAcc,CpuRef"} }; /* * Reads the user supplied backend preference, splits it by comma, and returns an ordered vector */ std::vector<armnn::BackendId> GetPreferredBackendList(const std::string& preferredBackends) { std::vector<armnn::BackendId> backends; std::stringstream ss(preferredBackends); while(ss.good()) { std::string backend; std::getline( ss, backend, ',' ); backends.emplace_back(backend); } return backends; } int main(int argc, char *argv[]) { // Wav2Letter ASR SETTINGS int SAMP_FREQ = 16000; int FRAME_LEN_MS = 32; int FRAME_LEN_SAMPLES = SAMP_FREQ * FRAME_LEN_MS * 0.001; int NUM_MFCC_FEATS = 13; int MFCC_WINDOW_LEN = 512; int MFCC_WINDOW_STRIDE = 160; const int NUM_MFCC_VECTORS = 296; int SAMPLES_PER_INFERENCE = MFCC_WINDOW_LEN + ((NUM_MFCC_VECTORS -1) * MFCC_WINDOW_STRIDE); int MEL_LO_FREQ = 0; int MEL_HI_FREQ = 8000; int NUM_FBANK_BIN = 128; int INPUT_WINDOW_LEFT_CONTEXT = 98; int INPUT_WINDOW_RIGHT_CONTEXT = 98; int INPUT_WINDOW_INNER_CONTEXT = NUM_MFCC_VECTORS - (INPUT_WINDOW_LEFT_CONTEXT + INPUT_WINDOW_RIGHT_CONTEXT); int SLIDING_WINDOW_OFFSET = INPUT_WINDOW_INNER_CONTEXT * MFCC_WINDOW_STRIDE; MfccParams mfccParams(SAMP_FREQ, NUM_FBANK_BIN, MEL_LO_FREQ, MEL_HI_FREQ, NUM_MFCC_FEATS, FRAME_LEN_SAMPLES, false, NUM_MFCC_VECTORS); MFCC mfccInst = MFCC(mfccParams); Preprocess preprocessor(MFCC_WINDOW_LEN, MFCC_WINDOW_STRIDE, mfccInst); bool isFirstWindow = true; std::string currentRContext = ""; std::map <std::string, std::string> options; int result = ParseOptions(options, CMD_OPTIONS, argv, argc); if (result != 0) { return result; } // Create the network options common::PipelineOptions pipelineOptions; pipelineOptions.m_ModelFilePath = GetSpecifiedOption(options, MODEL_FILE_PATH); if (CheckOptionSpecified(options, PREFERRED_BACKENDS)) { pipelineOptions.m_backends = GetPreferredBackendList((GetSpecifiedOption(options, PREFERRED_BACKENDS))); } else { pipelineOptions.m_backends = {"CpuAcc", "CpuRef"}; } asr::IPipelinePtr asrPipeline = asr::CreatePipeline(pipelineOptions, labels); asr::AudioCapture capture; std::vector<float> audioData = capture.LoadAudioFile(GetSpecifiedOption(options, AUDIO_FILE_PATH)); capture.InitSlidingWindow(audioData.data(), audioData.size(), SAMPLES_PER_INFERENCE, SLIDING_WINDOW_OFFSET); while (capture.HasNext()) { std::vector<float> audioBlock = capture.Next(); InferenceResults results; std::vector<int8_t> preprocessedData = asrPipeline->PreProcessing<float, int8_t>(audioBlock, preprocessor); asrPipeline->Inference<int8_t>(preprocessedData, results); asrPipeline->PostProcessing<int8_t>(results, isFirstWindow, !capture.HasNext(), currentRContext); } return 0; }
33.031847
115
0.60297
sahilbandar
de3947086780d2058509bfee647d1b3d1cb5fa2a
192
cpp
C++
Tests/TestProjects/VS2010/C++/DynamicallyLinkedLibrary/App/main.cpp
veganaize/make-it-so
e1f8a0c6c372891dfda3a807e80f3797efdc4a99
[ "MIT" ]
null
null
null
Tests/TestProjects/VS2010/C++/DynamicallyLinkedLibrary/App/main.cpp
veganaize/make-it-so
e1f8a0c6c372891dfda3a807e80f3797efdc4a99
[ "MIT" ]
null
null
null
Tests/TestProjects/VS2010/C++/DynamicallyLinkedLibrary/App/main.cpp
veganaize/make-it-so
e1f8a0c6c372891dfda3a807e80f3797efdc4a99
[ "MIT" ]
null
null
null
#include <TextUtils.h> #include <stdio.h> int main(int argc, char** argv) { std::string message = TextUtils::getHello() + ", " + TextUtils::getWorld(); printf(message.c_str()); }
19.2
77
0.625
veganaize