hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
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
float64
1
77k
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
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
d84b98c24c424c30b717045c425aeaf4f67144fc
941
cpp
C++
Leetcode/res/Binary Tree Paths/1.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
1
2022-03-04T16:06:41.000Z
2022-03-04T16:06:41.000Z
Leetcode/res/Binary Tree Paths/1.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
null
null
null
Leetcode/res/Binary Tree Paths/1.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
null
null
null
\* Author: allannozomu Runtime: 4 ms Memory: 11.5 MB*\ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void binaryTreecPathsRec(TreeNode* root, vector<string>& paths, string path){ if (root->left == NULL && root->right == NULL){ paths.push_back(path + to_string(root->val)); return; } if (root->left != NULL) binaryTreecPathsRec(root->left, paths, path + to_string(root->val) + "->"); if (root->right != NULL) binaryTreecPathsRec(root->right, paths, path + to_string(root->val) + "->"); } vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if (!root) return res; binaryTreecPathsRec(root, res, ""); return res; } };
27.676471
88
0.563231
d84e5a28b50382247dd241e3f938307d2ea248f5
2,015
cpp
C++
src/parser/expression_defs.cpp
pmenon/noisepage
73d50cdfa2e15b5d45e61b51e34672d10a851e14
[ "MIT" ]
971
2020-09-13T10:24:02.000Z
2022-03-31T07:02:51.000Z
src/parser/expression_defs.cpp
pmenon/noisepage
73d50cdfa2e15b5d45e61b51e34672d10a851e14
[ "MIT" ]
1,019
2018-07-20T23:11:10.000Z
2020-09-10T06:41:42.000Z
src/parser/expression_defs.cpp
pmenon/noisepage
73d50cdfa2e15b5d45e61b51e34672d10a851e14
[ "MIT" ]
318
2018-07-23T16:48:16.000Z
2020-09-07T09:46:31.000Z
#include "parser/expression_defs.h" #include <string> namespace noisepage::parser { std::string ExpressionTypeToShortString(ExpressionType type) { switch (type) { // clang-format off case ExpressionType::OPERATOR_PLUS: return "+"; case ExpressionType::OPERATOR_MINUS: return "-"; case ExpressionType::OPERATOR_MULTIPLY: return "*"; case ExpressionType::OPERATOR_DIVIDE: return "/"; case ExpressionType::COMPARE_EQUAL: return "="; case ExpressionType::COMPARE_NOT_EQUAL: return "!="; case ExpressionType::COMPARE_LESS_THAN: return "<"; case ExpressionType::COMPARE_GREATER_THAN: return ">"; case ExpressionType::COMPARE_LESS_THAN_OR_EQUAL_TO: return "<="; case ExpressionType::COMPARE_GREATER_THAN_OR_EQUAL_TO: return ">="; case ExpressionType::COMPARE_LIKE: return "~~"; case ExpressionType::COMPARE_NOT_LIKE: return "!~~"; case ExpressionType::COMPARE_IN: return "IN"; case ExpressionType::COMPARE_IS_DISTINCT_FROM: return "IS_DISTINCT_FROM"; case ExpressionType::CONJUNCTION_AND: return "AND"; case ExpressionType::CONJUNCTION_OR: return "OR"; case ExpressionType::AGGREGATE_COUNT: return "COUNT"; case ExpressionType::AGGREGATE_SUM: return "SUM"; case ExpressionType::AGGREGATE_MIN: return "MIN"; case ExpressionType::AGGREGATE_MAX: return "MAX"; case ExpressionType::AGGREGATE_AVG: return "AVG"; case ExpressionType::AGGREGATE_TOP_K: return "TOP_K"; case ExpressionType::AGGREGATE_HISTOGRAM: return "HISTOGRAM"; default: return ExpressionTypeToString(type); // clang-format on } } } // namespace noisepage::parser
51.666667
86
0.598015
d8509208a3026d9a17a883853aeb591c29e8bda5
12,341
cpp
C++
sourceCode/textures/imgLoaderSaver.cpp
mdecourse/CoppeliaSimLib
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
[ "RSA-MD" ]
null
null
null
sourceCode/textures/imgLoaderSaver.cpp
mdecourse/CoppeliaSimLib
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
[ "RSA-MD" ]
null
null
null
sourceCode/textures/imgLoaderSaver.cpp
mdecourse/CoppeliaSimLib
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
[ "RSA-MD" ]
null
null
null
#include "imgLoaderSaver.h" #ifdef SIM_WITH_QT #include "tGAFormat.h" #include "stb_image.h" #include "ttUtil.h" #include "vVarious.h" #include <QImage> #include <QImageWriter> #include <QColor> #include <QtCore/QBuffer> #endif unsigned char* CImageLoaderSaver::load(const char* filename,int* resX,int* resY,int* colorComponents,int desiredColorComponents,int scaleTo) { // scaleTo is 0 by default (no scaling). ScaleTo should be a power of 2! #ifdef SIM_WITH_QT std::string ext(CTTUtil::getLowerCaseString(VVarious::splitPath_fileExtension(filename).c_str())); unsigned char* data=nullptr; if ((ext.compare("tga")==0)||(ext.compare("gif")==0)) { data=stbi_load(filename,resX,resY,colorComponents,desiredColorComponents); } else { QImage image; if (image.load(filename)) { if (image.hasAlphaChannel()) colorComponents[0]=4; else colorComponents[0]=3; resX[0]=image.width(); resY[0]=image.height(); data=new unsigned char[resX[0]*resY[0]*colorComponents[0]]; for (int j=0;j<resY[0];j++) { for (int i=0;i<resX[0];i++) { QRgb pixel=image.pixel(i,j); if (colorComponents[0]==3) { data[3*(j*resX[0]+i)+0]=(unsigned char)qRed(pixel); data[3*(j*resX[0]+i)+1]=(unsigned char)qGreen(pixel); data[3*(j*resX[0]+i)+2]=(unsigned char)qBlue(pixel); } else { data[4*(j*resX[0]+i)+0]=(unsigned char)qRed(pixel); data[4*(j*resX[0]+i)+1]=(unsigned char)qGreen(pixel); data[4*(j*resX[0]+i)+2]=(unsigned char)qBlue(pixel); data[4*(j*resX[0]+i)+3]=(unsigned char)qAlpha(pixel); } } } } } if ((scaleTo!=0)&&(data!=nullptr)) { unsigned char* img=data; int s[2]; s[0]=resX[0]; s[1]=resY[0]; int ns[2]; ns[0]=resX[0]; ns[1]=resY[0]; for (int i=0;i<2;i++) { // set the side size to a power of 2 and smaller or equal to 'scaleTo': int v=s[i]; v&=(32768-1); unsigned short tmp=32768; while (tmp!=1) { if (v&tmp) { v=tmp; break; } tmp/=2; } if (v!=s[i]) v=v*2; while (v>scaleTo) v/=2; ns[i]=v; } if ((ns[0]!=s[0])||(ns[1]!=s[1])) { data=getScaledImage(img,colorComponents[0],s[0],s[1],ns[0],ns[1]); delete[] img; resX[0]=ns[0]; resY[0]=ns[1]; } } return(data); #else return(nullptr); #endif } unsigned char* CImageLoaderSaver::loadQTgaImageData(const char* fileAndPath,int& resX,int& resY,bool& rgba,unsigned char invisibleColor[3],int bitsPerPixel[1]) { #ifdef SIM_WITH_QT unsigned char* data=CTGAFormat::getQ_ImageData(fileAndPath,resX,resY,rgba,invisibleColor,bitsPerPixel); return(data); #else return(nullptr); #endif } unsigned char* CImageLoaderSaver::getScaledImage(const unsigned char* originalImg,int colorComponents,int originalX,int originalY,int newX,int newY) { #ifdef SIM_WITH_QT QImage::Format f=QImage::Format_RGB888; unsigned char* im=new unsigned char[originalX*originalY*colorComponents]; if (colorComponents==4) { f=QImage::Format_ARGB32; for (int i=0;i<originalX*originalY;i++) { // from rgba to bgra (corrected on 9/9/2914) im[4*i+0]=originalImg[4*i+2]; im[4*i+1]=originalImg[4*i+1]; im[4*i+2]=originalImg[4*i+0]; im[4*i+3]=originalImg[4*i+3]; } } else { for (int i=0;i<originalX*originalY;i++) { im[3*i+0]=originalImg[3*i+0]; im[3*i+1]=originalImg[3*i+1]; im[3*i+2]=originalImg[3*i+2]; } } QImage image(im,originalX,originalY,originalX*colorComponents,f); unsigned char* nim=new unsigned char[newX*newY*colorComponents]; QImage nimage(image.scaled(newX,newY,Qt::IgnoreAspectRatio,Qt::SmoothTransformation)); for (int j=0;j<newY;j++) { for (int i=0;i<newX;i++) { QRgb pixel=nimage.pixel(i,j); if (colorComponents==3) { nim[3*(j*newX+i)+0]=(unsigned char)qRed(pixel); nim[3*(j*newX+i)+1]=(unsigned char)qGreen(pixel); nim[3*(j*newX+i)+2]=(unsigned char)qBlue(pixel); } else { nim[4*(j*newX+i)+0]=(unsigned char)qRed(pixel); nim[4*(j*newX+i)+1]=(unsigned char)qGreen(pixel); nim[4*(j*newX+i)+2]=(unsigned char)qBlue(pixel); nim[4*(j*newX+i)+3]=(unsigned char)qAlpha(pixel); } } } delete[] im; return(nim); #else return(nullptr); #endif } bool CImageLoaderSaver::transformImage(unsigned char* img,int resX,int resY,int options) { int comp=3; if (options&1) comp=4; unsigned char* img2=new unsigned char[resX*resY*comp]; for (int i=0;i<resX*resY*comp;i++) img2[i]=img[i]; for (int x=0;x<resX;x++) { int x2=x; if (options&2) x2=resX-1-x; for (int y=0;y<resY;y++) { int y2=y; if (options&4) y2=resY-1-y; img[comp*(x+y*resX)+0]=img2[comp*(x2+y2*resX)+0]; img[comp*(x+y*resX)+1]=img2[comp*(x2+y2*resX)+1]; img[comp*(x+y*resX)+2]=img2[comp*(x2+y2*resX)+2]; if (comp==4) img[comp*(x+y*resX)+3]=img2[comp*(x2+y2*resX)+3]; } } delete[] img2; return(true); } unsigned char* CImageLoaderSaver::getScaledImage(const unsigned char* originalImg,const int resolIn[2],int resolOut[2],int options) { #ifdef SIM_WITH_QT int compIn=3; int compOut=3; if (options&1) compIn=4; if (options&2) compOut=4; QImage::Format f=QImage::Format_RGB888; unsigned char* im=new unsigned char[resolIn[0]*resolIn[1]*compIn]; if (compIn==4) { f=QImage::Format_ARGB32; for (int i=0;i<resolIn[0]*resolIn[1];i++) { // from rgba to bgra (corrected on 9/9/2914) im[4*i+0]=originalImg[4*i+2]; im[4*i+1]=originalImg[4*i+1]; im[4*i+2]=originalImg[4*i+0]; im[4*i+3]=originalImg[4*i+3]; } } else { for (int i=0;i<resolIn[0]*resolIn[1];i++) { im[3*i+0]=originalImg[3*i+0]; im[3*i+1]=originalImg[3*i+1]; im[3*i+2]=originalImg[3*i+2]; } } QImage image(im,resolIn[0],resolIn[1],resolIn[0]*compIn,f); Qt::AspectRatioMode aspectRatio=Qt::IgnoreAspectRatio; if ((options&12)==4) aspectRatio=Qt::KeepAspectRatio; if ((options&12)==8) aspectRatio=Qt::KeepAspectRatioByExpanding; Qt::TransformationMode transform=Qt::SmoothTransformation; if (options&16) transform=Qt::FastTransformation; QImage nimage(image.scaled(resolOut[0],resolOut[1],aspectRatio,transform)); resolOut[0]=nimage.width(); resolOut[1]=nimage.height(); unsigned char* nim=new unsigned char[resolOut[0]*resolOut[1]*compOut]; for (int j=0;j<resolOut[1];j++) { for (int i=0;i<resolOut[0];i++) { QRgb pixel=nimage.pixel(i,j); if (compOut==3) { nim[3*(j*resolOut[0]+i)+0]=(unsigned char)qRed(pixel); nim[3*(j*resolOut[0]+i)+1]=(unsigned char)qGreen(pixel); nim[3*(j*resolOut[0]+i)+2]=(unsigned char)qBlue(pixel); } else { nim[4*(j*resolOut[0]+i)+0]=(unsigned char)qRed(pixel); nim[4*(j*resolOut[0]+i)+1]=(unsigned char)qGreen(pixel); nim[4*(j*resolOut[0]+i)+2]=(unsigned char)qBlue(pixel); nim[4*(j*resolOut[0]+i)+3]=(unsigned char)qAlpha(pixel); } } } delete[] im; return(nim); #else return(nullptr); #endif } bool CImageLoaderSaver::save(const unsigned char* data,const int resolution[2],int options,const char* filename,int quality,std::string* buffer) { bool retVal=false; #ifdef SIM_WITH_QT unsigned char *buff=nullptr; QImage::Format format=QImage::Format_ARGB32; buff=new unsigned char[4*resolution[0]*resolution[1]]; int bytesPerPixel=4; for (int i=0;i<resolution[0];i++) { for (int j=0;j<resolution[1];j++) { if ((options&1)==0) { // input img provided as rgb if ((options&2)==0) { bytesPerPixel=3; format=QImage::Format_RGB888; buff[3*(resolution[0]*j+i)+0]=data[3*(resolution[0]*(resolution[1]-j-1)+i)+0]; buff[3*(resolution[0]*j+i)+1]=data[3*(resolution[0]*(resolution[1]-j-1)+i)+1]; buff[3*(resolution[0]*j+i)+2]=data[3*(resolution[0]*(resolution[1]-j-1)+i)+2]; } else { bytesPerPixel=1; format=QImage::Format_Grayscale8; buff[resolution[0]*j+i]=data[resolution[0]*(resolution[1]-j-1)+i]; } } else { // input img provided as rgba buff[4*(resolution[0]*j+i)+0]=data[4*(resolution[0]*(resolution[1]-j-1)+i)+2]; buff[4*(resolution[0]*j+i)+1]=data[4*(resolution[0]*(resolution[1]-j-1)+i)+1]; buff[4*(resolution[0]*j+i)+2]=data[4*(resolution[0]*(resolution[1]-j-1)+i)+0]; buff[4*(resolution[0]*j+i)+3]=data[4*(resolution[0]*(resolution[1]-j-1)+i)+3]; } } } { QImage image(buff,resolution[0],resolution[1],resolution[0]*bytesPerPixel,format); if (buffer==nullptr) retVal=image.save(filename,0,quality); else { if (filename[0]=='.') { QByteArray ba; QBuffer qbuffer(&ba); qbuffer.open(QIODevice::WriteOnly); retVal=image.save(&qbuffer,filename+1); if (retVal) buffer->assign(ba.data(),ba.data()+ba.size()); } } } delete[] buff; #endif return(retVal); } unsigned char* CImageLoaderSaver::load(int resolution[2],int options,const char* filename,void* reserved) { unsigned char* retVal=nullptr; #ifdef SIM_WITH_QT QImage image; bool loadRes=false; if (reserved!=nullptr) loadRes=image.loadFromData((const unsigned char*)filename,((int*)reserved)[0]); else loadRes=image.load(filename,0); if (loadRes) { if (options&1) retVal=new unsigned char[image.height()*image.width()*4]; else retVal=new unsigned char[image.height()*image.width()*3]; resolution[0]=image.width(); resolution[1]=image.height(); for (int x=0;x<image.width();++x) { for (int y=0;y<image.height();++y) { QColor col(image.pixel(x,y)); if (options&1) { retVal[4*(resolution[0]*(resolution[1]-y-1)+x)+0]=col.red(); retVal[4*(resolution[0]*(resolution[1]-y-1)+x)+1]=col.green(); retVal[4*(resolution[0]*(resolution[1]-y-1)+x)+2]=col.blue(); retVal[4*(resolution[0]*(resolution[1]-y-1)+x)+3]=col.alpha(); } else { retVal[3*(resolution[0]*(resolution[1]-y-1)+x)+0]=col.red(); retVal[3*(resolution[0]*(resolution[1]-y-1)+x)+1]=col.green(); retVal[3*(resolution[0]*(resolution[1]-y-1)+x)+2]=col.blue(); } } } } #endif return(retVal); }
33.444444
159
0.51333
d851b73d72148dc84f24876dd7036dca78269130
9,947
cpp
C++
ortc/services/cpp/services_DHPublicKey.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
2
2016-10-12T09:16:32.000Z
2016-10-13T03:49:47.000Z
ortc/services/cpp/services_DHPublicKey.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
2
2017-11-24T09:18:45.000Z
2017-11-24T09:20:53.000Z
ortc/services/cpp/services_DHPublicKey.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2014, Hookflash Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #include <ortc/services/internal/services_DHPublicKey.h> #include <ortc/services/internal/services_DHKeyDomain.h> #include <ortc/services/IHelper.h> #include <zsLib/XML.h> #include <zsLib/eventing/IHasher.h> namespace ortc { namespace services { ZS_DECLARE_SUBSYSTEM(ortc_services) } } namespace ortc { namespace services { namespace internal { using CryptoPP::AutoSeededRandomPool; using namespace zsLib::XML; //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark IDHPublicKeyForDHPublicKey #pragma mark //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHPublicKey #pragma mark //----------------------------------------------------------------------- DHPublicKey::DHPublicKey(const make_private &) { ZS_LOG_DEBUG(log("created")) } //----------------------------------------------------------------------- DHPublicKey::~DHPublicKey() { if(isNoop()) return; ZS_LOG_DEBUG(log("destroyed")) } //----------------------------------------------------------------------- DHPublicKeyPtr DHPublicKey::convert(IDHPublicKeyPtr publicKey) { return ZS_DYNAMIC_PTR_CAST(DHPublicKey, publicKey); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHPublicKey => IDHPublicKey #pragma mark //----------------------------------------------------------------------- ElementPtr DHPublicKey::toDebug(IDHPublicKeyPtr keyDomain) { if (!keyDomain) return ElementPtr(); return convert(keyDomain)->toDebug(); } //----------------------------------------------------------------------- DHPublicKeyPtr DHPublicKey::load( const SecureByteBlock &staticPublicKey, const SecureByteBlock &ephemeralPublicKey ) { DHPublicKeyPtr pThis(make_shared<DHPublicKey>(make_private{})); pThis->mStaticPublicKey.Assign(staticPublicKey); pThis->mEphemeralPublicKey.Assign(ephemeralPublicKey); if (ZS_IS_LOGGING(Trace)) { ZS_LOG_TRACE(pThis->debug("loaded")) } else { ZS_LOG_DEBUG(pThis->log("loaded")) } return pThis; } //----------------------------------------------------------------------- void DHPublicKey::save( SecureByteBlock *outStaticPublicKey, SecureByteBlock *outEphemeralPublicKey ) const { ZS_LOG_TRACE(log("save called")) if (outStaticPublicKey) { (*outStaticPublicKey).Assign(mStaticPublicKey); } if (outEphemeralPublicKey) { (*outEphemeralPublicKey).Assign(mEphemeralPublicKey); } } //----------------------------------------------------------------------- String DHPublicKey::getFingerprint() const { return IHelper::convertToHex(*IHasher::hash(mStaticPublicKey, IHasher::hmacSHA1(mEphemeralPublicKey))); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHPublicKey => IDHPublicKeyForDHPrivateKey #pragma mark //----------------------------------------------------------------------- const SecureByteBlock &DHPublicKey::getStaticPublicKey() const { return mStaticPublicKey; } //----------------------------------------------------------------------- const SecureByteBlock &DHPublicKey::getEphemeralPublicKey() const { return mEphemeralPublicKey; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHPublicKey => (internal) #pragma mark //----------------------------------------------------------------------- Log::Params DHPublicKey::log(const char *message) const { ElementPtr objectEl = Element::create("DHPublicKey"); IHelper::debugAppend(objectEl, "id", mID); return Log::Params(message, objectEl); } //----------------------------------------------------------------------- Log::Params DHPublicKey::debug(const char *message) const { return Log::Params(message, toDebug()); } //----------------------------------------------------------------------- ElementPtr DHPublicKey::toDebug() const { ElementPtr resultEl = Element::create("DHPublicKey"); IHelper::debugAppend(resultEl, "id", mID); IHelper::debugAppend(resultEl, "static public key", IHelper::convertToHex(mStaticPublicKey, true)); IHelper::debugAppend(resultEl, "ephemeral public key", IHelper::convertToHex(mEphemeralPublicKey, true)); return resultEl; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark IDHPublicKeyFactory #pragma mark //----------------------------------------------------------------------- IDHPublicKeyFactory &IDHPublicKeyFactory::singleton() { return DHPublicKeyFactory::singleton(); } //----------------------------------------------------------------------- DHPublicKeyPtr IDHPublicKeyFactory::load( const SecureByteBlock &staticPublicKey, const SecureByteBlock &ephemeralPublicKey ) { if (this) {} return DHPublicKey::load(staticPublicKey, ephemeralPublicKey); } } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark IDHPublicKey #pragma mark //------------------------------------------------------------------------- ElementPtr IDHPublicKey::toDebug(IDHPublicKeyPtr keyDomain) { return internal::DHPublicKey::toDebug(keyDomain); } //------------------------------------------------------------------------- IDHPublicKeyPtr IDHPublicKey::load( const SecureByteBlock &staticPublicKey, const SecureByteBlock &ephemeralPublicKey ) { return internal::IDHPublicKeyFactory::singleton().load(staticPublicKey, ephemeralPublicKey); } } }
39.472222
113
0.41701
d85306e3e2c87156f925039aeee4b27cf7bb7a15
3,509
cc
C++
test/unit/Eval/EvalSubgoalTest.cc
mnowotnik/fovris
82f692743fa6c96fef05041e686d716b03c22f07
[ "BSD-3-Clause" ]
4
2017-01-04T17:22:55.000Z
2018-12-08T02:10:18.000Z
test/unit/Eval/EvalSubgoalTest.cc
Mike-Now/fovris
82f692743fa6c96fef05041e686d716b03c22f07
[ "BSD-3-Clause" ]
null
null
null
test/unit/Eval/EvalSubgoalTest.cc
Mike-Now/fovris
82f692743fa6c96fef05041e686d716b03c22f07
[ "BSD-3-Clause" ]
1
2022-03-24T05:26:13.000Z
2022-03-24T05:26:13.000Z
#include "KB/KBHeadLiteral.h" #include "Eval/EvalSubgoal.h" #include "Eval/TestUtils.h" #include "thirdparty/Catch/include/catch.hpp" #include <string> using namespace fovris; TEST_CASE("Check subgoal evaluation result", "[EvalSubgoal]") { // given unsigned relId = 0xDEADBEEF; KBRelation relation{ relId, {TermType::Integer, TermType::Integer, TermType::Integer}}; KBGroundTerm Id1{10}, Id2{20}, Id3{30}; KBTuple tup{{Id1, Id2, Id1}, TruthValue::True}; KBTuple tup2{{Id1, Id2, Id3}, TruthValue::True}; relation.addTuple(tup); relation.addTuple(tup2); KBVarTerm X{1}, Y{2}, Z{5}; KBRuleLiteral kbr{relId, {X, Y, X}, TruthValue::True}; SECTION("Check EvalSubgoalFirst") { auto evalFirst = CreateEvalSubgoalFirst(kbr, EvalDestination{Y, X}); // then auto result = evalFirst->evaluate({}, relation.getFacts()); REQUIRE(result.size() == 1); REQUIRE(result[0].getTerms().length() == 2); REQUIRE(result[0].getTerms()[0] == Id2); REQUIRE(result[0].getTerms()[1] == Id1); } SECTION("Check EvalSubgoalNext") { KBRuleLiteral tmpKbr{relId, {X, Y, Z}, TruthValue::True}; auto evalNext = CreateEvalSubgoalNext(tmpKbr, kbr, {Y, Z}); // given // then KBTuple tmpTup = {{Id1, Id2, Id3}, TruthValue::True}; auto result = evalNext->evaluate({tmpTup}, relation.getFacts()); REQUIRE(result.size() == 1); REQUIRE(result[0].getTerms().length() == 2); REQUIRE(result[0].getTerms()[0] == Id2); REQUIRE(result[0].getTerms()[1] == Id3); } } TEST_CASE("Check subgoal with function evaluation", "[EvalSubgoal]") { unsigned relId = 0; TermMapper termMapper; KBGroundTerm foo{termMapper.internTerm("foo")}; KBGroundTerm bar{termMapper.internTerm("bar")}; KBGroundTerm baz{termMapper.internTerm("baz")}; KBRelation relation{relId, {TermType::Id, TermType::Id, TermType::Id}}; relation.addFact({foo, bar, baz}, TruthValue::True); relation.addFact({foo, foo, baz}, TruthValue::True); KBVarTerm X{1}, Y{2}, Z{5}; KBRuleLiteral kbr{relId, {X, Y, Z}, TruthValue::True}; // function predicates matche std::vector<KBRuleFunction> functions; functions.emplace_back([](const Array<Term> &terms) -> bool { return terms[0].get<std::string>() == "foo" && terms[1].get<std::string>() == "bar"; }, std::vector<KBTerm>{X, Y}, std::vector<TermType>{TermType::Id, TermType::Id}); KBRuleLiteral tmpKbr{relId, {X, Y, Z}, TruthValue::True}; auto evalNext = CreateEvalSubgoalLast(tmpKbr, kbr, {Y, Z}, functions, termMapper); KBTuple tmpTup = {{foo, bar, baz}, TruthValue::True}; auto result = evalNext->evaluate({tmpTup}, relation.getFacts()); REQUIRE(result.size() == 1); // function predicates don't match functions.emplace_back([](const Array<Term> &terms) -> bool { return terms[0].get<std::string>() == "baz"; }, std::vector<KBTerm>{X, Y}, std::vector<TermType>{TermType::Id, TermType::Id}); evalNext = CreateEvalSubgoalLast(tmpKbr, kbr, {Y, Z}, functions, termMapper); result = evalNext->evaluate({tmpTup}, relation.getFacts()); REQUIRE(result.size() == 0); }
34.401961
78
0.588487
d855695e7f9b2b5d51d12e6e80b1e1bbd4a7b389
1,362
cpp
C++
SDIZO_Graphs/my_graph.cpp
michaltkacz/SDIZO_Graphs
085a9be87ff96826ca2a6dec1f7206ebabaca341
[ "MIT" ]
null
null
null
SDIZO_Graphs/my_graph.cpp
michaltkacz/SDIZO_Graphs
085a9be87ff96826ca2a6dec1f7206ebabaca341
[ "MIT" ]
null
null
null
SDIZO_Graphs/my_graph.cpp
michaltkacz/SDIZO_Graphs
085a9be87ff96826ca2a6dec1f7206ebabaca341
[ "MIT" ]
null
null
null
#include "my_graph.h" #include "graph_exception.h" #include "my_rand.h" #include <fstream> #include <iomanip> void my_graph::random() { const int v_number = my_rand::random_int(min_vert, max_vert); const int density = my_rand::random_int(min_dens, max_dens); random(v_number, density); } void my_graph::random(int v_number, int density) { if (v_number < min_vert || v_number >= max_vert) { std::string msg = "Liczba wierzcholkow poza zakresem! ("; msg += std::to_string(min_vert); msg += "-"; msg += std::to_string(max_vert-1); msg += ")"; throw graph_exception(msg.c_str()); } if(density < min_dens || density >= max_dens) { std::string msg = "Gestosc poza zakresem! ("; msg += std::to_string(min_dens); msg += "-"; msg += std::to_string(max_dens-1); msg += ")"; throw graph_exception(msg.c_str()); } } void my_graph::load_from_file(const std::string& file_name) { std::ifstream fin(file_name); if (fin.is_open()) { int e = 0; int v = 0; int v_start = 0; int v_end = 0; int w = 0; fin >> e; fin >> v; try { init(v, e); while (!fin.eof()) { fin >> v_start; fin >> v_end; fin >> w; add_edge(v_start, v_end, w); } } catch (graph_exception& exc) { fin.close(); throw exc; } fin.close(); } else { throw graph_exception("Podany plik nie istnieje!"); } }
17.921053
62
0.61674
d858b4d2863db23ed4f62818c5eaf13a6d571930
2,115
cpp
C++
uppsrc/ide/Debuggers/GdbUtils.cpp
UltimateScript/Forgotten
ac59ad21767af9628994c0eecc91e9e0e5680d95
[ "BSD-3-Clause" ]
null
null
null
uppsrc/ide/Debuggers/GdbUtils.cpp
UltimateScript/Forgotten
ac59ad21767af9628994c0eecc91e9e0e5680d95
[ "BSD-3-Clause" ]
null
null
null
uppsrc/ide/Debuggers/GdbUtils.cpp
UltimateScript/Forgotten
ac59ad21767af9628994c0eecc91e9e0e5680d95
[ "BSD-3-Clause" ]
null
null
null
#include "GdbUtils.h" #include <memory> #include <ide/Core/Logger.h> #include <ide/Common/CommandLineOptions.h> using namespace Upp; One<IGdbUtils> GdbUtilsFactory::Create() { #if defined(PLATFORM_WIN32) return MakeOne<GdbWindowsUtils>(); #elif defined(PLATFORM_POSIX) return MakeOne<GdbPosixUtils>(); #endif } #if defined(PLATFORM_WIN32) #define METHOD_NAME UPP_METHOD_NAME("GdbWindowsUtils") using DeleteHandleFun = std::function<void(HANDLE)>; static void DeleteHandle(HANDLE handle) { if (handle) { CloseHandle(handle); } } String GdbWindowsUtils::BreakRunning(int pid) { std::unique_ptr<void, DeleteHandleFun> handle(OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid), &DeleteHandle); if(!handle) return String().Cat() << "Failed to open process associated with " << pid << " PID."; if(Is64BitIde() && !Is64BitProcess(handle.get())) { auto path = String().Cat() << GetExeFolder() << "\\" << GetExeTitle() << "32.exe"; auto cmd = String().Cat() << path << " " << COMMAND_LINE_GDB_DEBUG_BREAK_PROCESS_OPTION << " " << pid; String out; if(Sys(cmd, out) == COMMAND_LINE_GDB_DEBUG_BREAK_PROCESS_FAILURE_STATUS) { Logd() << METHOD_NAME << cmd; return String().Cat() << "Failed to interrupt process via 32-bit TheIDE. Output from command is \"" << out << "\"."; } return ""; } if (!DebugBreakProcess(handle.get())) return String().Cat() << "Failed to break process associated with " << pid << " PID."; return ""; } bool GdbWindowsUtils::Is64BitIde() const { return sizeof(void*) == 8; } bool GdbWindowsUtils::Is64BitProcess(HANDLE handle) const { BOOL is_wow_64 = FALSE; if(!IsWow64Process(handle, &is_wow_64)) { Loge() << METHOD_NAME << "Failed to check that process is under wow64 emulation layer."; } return !is_wow_64; } #undef METHOD_NAME #elif defined(PLATFORM_POSIX) String GdbPosixUtils::BreakRunning(int pid) { if(kill(pid, SIGINT) == -1) return String().Cat() << "Failed to interrupt process associated with " << pid << " PID."; return ""; } #endif
24.593023
120
0.661466
d858f20cd9418ed569a886d53eecf7466c64150e
4,141
hpp
C++
include/seqan3/core/simd/simd.hpp
FirstLoveLife/seqan3
ac2e983e0a576515c13ebb2c851c43c1eba1ece1
[ "BSD-3-Clause" ]
null
null
null
include/seqan3/core/simd/simd.hpp
FirstLoveLife/seqan3
ac2e983e0a576515c13ebb2c851c43c1eba1ece1
[ "BSD-3-Clause" ]
null
null
null
include/seqan3/core/simd/simd.hpp
FirstLoveLife/seqan3
ac2e983e0a576515c13ebb2c851c43c1eba1ece1
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================ // SeqAn - The Library for Sequence Analysis // ============================================================================ // // Copyright (c) 2006-2018, Knut Reinert & Freie Universitaet Berlin // Copyright (c) 2016-2018, Knut Reinert & MPI Molekulare Genetik // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ============================================================================ /*!\file * \brief Contains seqan3::simd::simd_type * \author Marcel Ehrhardt <marcel.ehrhardt AT fu-berlin.de> */ #pragma once #include <seqan3/core/simd/detail/default_simd_backend.hpp> namespace seqan3 { inline namespace simd { /*!\brief seqan3::simd::simd_type encapsulates simd vector types, which can be manipulated * by simd operations. * \ingroup simd * \tparam scalar_t The underlying type of a simd vector * \tparam length The number of packed values in a simd vector * \tparam simd_backend The simd backend to use, e.g. * seqan3::detail::builtin_simd * * \include test/snippet/core/simd/simd.cpp * \attention * seqan3::simd::simd_type may not support *float* types depending on the selected backend. * * All implementations support *[u]intX_t* types, e.g. *uint8_t*. * * \par Helper types * seqan3::simd::simd_type_t as a shorthand for seqan3::simd::simd_type::type * \sa https://en.wikipedia.org/wiki/SIMD What is SIMD conceptually? * \sa https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions Which SIMD architectures exist? * \sa https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html Underlying technique of *seqan3::detail::builtin_simd types*. * \sa https://github.com/edanor/umesimd Underlying library of *seqan3::detail::ume_simd* types. * \sa https://software.intel.com/sites/landingpage/IntrinsicsGuide Instruction sets and their low-level intrinsics. */ template <typename scalar_t, size_t length = detail::default_simd_length<scalar_t, detail::default_simd_backend>, typename simd_backend = detail::default_simd_backend<scalar_t, length>> struct simd_type : simd_backend { //!\brief The actual simd type. using type = typename simd_backend::type; }; //!\brief Helper type of seqan3::simd::simd_type //!\ingroup simd template <typename scalar_t, size_t length = detail::default_simd_length<scalar_t, detail::default_simd_backend>, typename simd_backend = detail::default_simd_backend<scalar_t, length>> using simd_type_t = typename simd_type<scalar_t, length, simd_backend>::type; } // inline namespace simd } // namespace seqan3
45.505495
126
0.702729
d85f4240e7e6152924206d62980c7e33f3069942
5,010
cpp
C++
src/raspberry_pi/receiver/home/vr360_view/src/main.cpp
sisinn/raspi_telexistence_vr-
09adb1160c86c2d4573d69f432790c312b4f0279
[ "MIT" ]
2
2018-10-04T05:27:11.000Z
2020-02-10T02:15:00.000Z
src/raspberry_pi/receiver/home/vr360_view/src/main.cpp
sisinn/raspi_telexistence_vr
09adb1160c86c2d4573d69f432790c312b4f0279
[ "MIT" ]
null
null
null
src/raspberry_pi/receiver/home/vr360_view/src/main.cpp
sisinn/raspi_telexistence_vr
09adb1160c86c2d4573d69f432790c312b4f0279
[ "MIT" ]
null
null
null
#include "ofMain.h" #include "ofApp.h" #include "unistd.h" int main(int argc, char *argv[]) { int opt; int qopt = 0; char qparam[128] = ""; int topt = 0; char tparam[128] = ""; int fopt = 0; char fparam[128] = ""; int ropt = 0; char rparam[128] = ""; int sopt = 0; char sparam[128] = ""; int bopt = 0; char bparam[128] = ""; int aopt = 0; char aparam[128] = ""; int sum_chk = 0; // parameter q: quatanion sort select // parameter f: focal // parameter t: theta // parameter r: radius // parameter s: smooth while ((opt = getopt(argc, argv, "q:f:t:r:s:a:b:")) != -1) { switch (opt) { case 'q': qopt = 1; if(strlen(optarg) < 128){ strcpy(qparam, optarg); } break; case 't': topt = 1; if(strlen(optarg) < 128){ strcpy(tparam, optarg); } break; case 'f': fopt = 1; if(strlen(optarg) < 128){ strcpy(fparam, optarg); } break; case 'r': ropt = 1; if(strlen(optarg) < 128){ strcpy(rparam, optarg); } break; case 's': sopt = 1; if(strlen(optarg) < 128){ strcpy(sparam, optarg); } break; case 'a': aopt = 1; if(strlen(optarg) < 128){ strcpy(aparam, optarg); } break; case 'b': bopt = 1; if(strlen(optarg) < 128){ strcpy(bparam, optarg); } break; default: printf("error! \'%c\' \'%c\'\n", opt, optopt); return 1; } } if(qopt == 1){ char *p[4]; int err_flag = 0; p[0] = strtok(qparam,","); if(p[0] == NULL){ err_flag = 1; } else{ for(int i = 1; i < 4; i++){ p[i] = strtok(NULL,","); if(p[i] == NULL){ err_flag = 1; break; } } } if(err_flag == 0){ for(int i = 0; i < 4; i++){ if(p[i][0] == 'w'){ wxyz[i] = 1; sum_chk += 1; } else if((p[i][0] == '_') && (p[i][1] == 'w')){ wxyz[i] = -1; sum_chk += 1; } else if(p[i][0] == 'x'){ wxyz[i] = 2; sum_chk += 2; } else if((p[i][0] == '_') && (p[i][1] == 'x')){ wxyz[i] = -2; sum_chk += 2; } else if(p[i][0] == 'y'){ wxyz[i] = 3; sum_chk += 4; } else if((p[i][0] == '_') && (p[i][1] == 'y')){ wxyz[i] = -3; sum_chk += 4; } else if(p[i][0] == 'z'){ wxyz[i] = 4; sum_chk += 8; } else if((p[i][0] == '_') && (p[i][1] == 'z')){ wxyz[i] = -4; sum_chk += 8; } } } } if(sum_chk != 15){ wxyz[0] = 1; wxyz[1] = 2; wxyz[2] = 3; wxyz[3] = 4; } printf("wxyz= %d %d %d %d\n", wxyz[0],wxyz[1],wxyz[2],wxyz[3]); th_max = 90; if(topt == 1){ th_max = atoi(tparam); if((th_max < 60) || (th_max > 120)){ th_max = 90; } } focal = 1.0; if(fopt == 1){ focal = atof(fparam); } r_max = 90; if(ropt == 1){ r_max = atoi(rparam); if((r_max < 60) || (r_max > 120)){ r_max = 90; } } front_tilt = 0; if(bopt == 1){ front_tilt = atoi(bparam); } back_tilt = 0; if(aopt == 1){ back_tilt = atoi(aparam); } smooth = 0.02; if(sopt == 1){ smooth = atof(sparam); if((smooth < 0.001) || (smooth > 0.1)){ smooth = 0.02; } } printf("th_max = %d, r_max = %d, focal = %f, smooth = %f, tilt = %d,%d\n", th_max, r_max, focal, smooth, front_tilt, back_tilt); circle_center_x = 0.0; circle_center_y = 0.0; printf("circle_center = %d %d\n", circle_center_x, circle_center_y); ofSetLogLevel(OF_LOG_VERBOSE); ofGLESWindowSettings settings; settings.setSize(SCREEN_WIDTH, SCREEN_HIGH); settings.setGLESVersion(2); settings.windowMode = OF_FULLSCREEN; ofCreateWindow(settings); ofRunApp( new ofApp()); }
24.679803
132
0.353493
d85f4e78725f54a82f55b1a2fa66d9ee72a4c7f3
3,978
cpp
C++
src/threads.cpp
yanmingsohu/PlayJS
2f9e015d0ec38f9613aa6915c5289a815bb5a52f
[ "Apache-2.0" ]
1
2019-09-03T19:13:54.000Z
2019-09-03T19:13:54.000Z
src/threads.cpp
yanmingsohu/PlayJS
2f9e015d0ec38f9613aa6915c5289a815bb5a52f
[ "Apache-2.0" ]
null
null
null
src/threads.cpp
yanmingsohu/PlayJS
2f9e015d0ec38f9613aa6915c5289a815bb5a52f
[ "Apache-2.0" ]
null
null
null
#include "threads.h" #include "export-js.h" #include "fs.h" #include "util.h" #include "vm.h" #include <map> #include <mutex> using std::map; using std::thread; using std::string; using std::mutex; using std::lock_guard; typedef map<threadId, thread*> ThreadMap; static volatile int nextId = 0x10; static mutex lock_map; static ThreadMap tmap; static void freeThread(threadId* _id) { lock_guard<mutex> guard(lock_map); threadId id = reinterpret_cast<threadId>(_id); tmap.erase((threadId)id); } static string& operator+(string& s, int i) { return s.append(std::to_string(i)); } void loadScript(string& filename, threadId id) { LocalResource<threadId> freeThreadHandle(reinterpret_cast<threadId*>(id), freeThread); println("Start Script '"+ filename +"'", id); std::string code; if (FAILED == readTxtFile(filename, code)) { println("Read '"+ filename +"' error", id); return; } VM vm(id); installJsLibrary(&vm); JsErrorCode r = vm.loadModule(0, filename, code); if (r) { println("Load Module '"+ filename +"' failed code: "+ r, id, LERROR); println(parseJsErrCode(r), id, LERROR); } LocalVal err = vm.checkError(); if (err.notNull()) { println("Exit on failed: "+ errorStack(err), id, LERROR); } unstallJsLIbrary(&vm); println("Script '"+ filename+ "' Exit", id); } threadId loadScriptInNewThread(string& fileName) { lock_guard<mutex> guard(lock_map); threadId id = nextId++; thread* newThread = new thread(loadScript, fileName, id); tmap.insert(ThreadMap::value_type(id, newThread)); return id; } thread* getThread(threadId i) { lock_guard<mutex> guard(lock_map); auto p = tmap.find(i); if (p == tmap.end()) { return 0; } return p->second; } void joinAll() { println(string("Running Thread: ")+ tmap.size()); lock_map.lock(); for (auto it = tmap.begin(); it != tmap.end(); ++it) { // // 当线程运行时可能会启动新的线程, 交叉锁可以防止死锁. // lock_map.unlock(); println(std::string("Wait thread [id:")+ (it->first) +"]"); it->second->join(); lock_map.lock(); } lock_map.unlock(); } static JsValueRef js_run(JsValueRef callee, JsValueRef *args, unsigned short ac, JsNativeFunctionInfo *info, void *d) { if (ac != 2) { pushException("bad arguments, run(scriptFilePath)"); return 0; } LocalVal filenameArg(args[1]); string filename = filenameArg.toString(); threadId id = loadScriptInNewThread(filename); return wrapJs(id); } static JsValueRef js_sleep(JsValueRef callee, JsValueRef *args, unsigned short ac, JsNativeFunctionInfo *info, void *d) { if (ac != 2) { pushException("bad arguments, sleep(ms)"); return 0; } int time = intValue(args[1]); if (time > 0) { std::this_thread::sleep_for( std::chrono::duration<int, std::milli>(time)); } return 0; } static JsValueRef js_running(JsValueRef callee, JsValueRef *args, unsigned short ac, JsNativeFunctionInfo *info, void *d) { if (ac != 2) { pushException("bad arguments, get(threadid)"); return 0; } int id = intValue(args[1]); return wrapJs(0 != getThread(id)); } static JsValueRef js_id(JsValueRef callee, JsValueRef *args, unsigned short ac, JsNativeFunctionInfo *info, void *id) { return wrapJs(reinterpret_cast<threadId>(id)); } void installThread(VM* vm) { LocalVal thread = vm->createObject(); vm->getGlobal().put("thread", thread); void * id = reinterpret_cast<void*>(vm->thread()); DEF_JS_FUNC(vm, id, thread, id, js_id); DEF_JS_FUNC(vm, 0, thread, run, js_run); DEF_JS_FUNC(vm, 0, thread, sleep, js_sleep); DEF_JS_FUNC(vm, 0, thread, wait, js_sleep); DEF_JS_FUNC(vm, 0, thread, running, js_running); }
25.177215
90
0.616642
d8711fe5a8b2142a73751d6580651b63e075013b
9,749
cpp
C++
src/wrappers/src/mfx_gst_frame_constructor.cpp
AntonGrishin/gstreamer-plugins
6d86897e02b525da4bf1d3f8b4bb6472cc72eb2b
[ "BSD-3-Clause" ]
20
2016-08-06T02:31:53.000Z
2022-01-24T13:29:41.000Z
src/wrappers/src/mfx_gst_frame_constructor.cpp
AntonGrishin/gstreamer-plugins
6d86897e02b525da4bf1d3f8b4bb6472cc72eb2b
[ "BSD-3-Clause" ]
5
2016-08-01T15:35:36.000Z
2021-07-15T10:33:59.000Z
src/wrappers/src/mfx_gst_frame_constructor.cpp
AntonGrishin/gstreamer-plugins
6d86897e02b525da4bf1d3f8b4bb6472cc72eb2b
[ "BSD-3-Clause" ]
14
2016-08-18T23:42:06.000Z
2021-05-16T22:06:59.000Z
/********************************************************************************** Copyright (C) 2005-2019 Intel Corporation. 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************/ #include "mfx_defs.h" #include "mfx_gst_debug.h" #include "mfx_gst_frame_constructor.h" #include "mfx_utils.h" #undef MFX_DEBUG_MODULE_NAME #define MFX_DEBUG_MODULE_NAME "mfx_gst_frame_constructor" /*------------------------------------------------------------------------------*/ IMfxGstFrameConstuctor::IMfxGstFrameConstuctor(): m_bs_state(MfxGstBS_HeaderAwaiting) { MFX_DEBUG_TRACE_FUNC; } /*------------------------------------------------------------------------------*/ IMfxGstFrameConstuctor::~IMfxGstFrameConstuctor(void) { MFX_DEBUG_TRACE_FUNC; if (buffered_bst_.Data) { MSDK_FREE(buffered_bst_.Data); } } /*------------------------------------------------------------------------------*/ mfxStatus IMfxGstFrameConstuctor::Load(std::shared_ptr<mfxGstBitstreamBufferRef> bst_ref, bool header) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = LoadToNativeFormat(bst_ref, header); if (MFX_ERR_NONE != sts) { Unload(); } MFX_DEBUG_TRACE_I32(sts); return sts; } /*------------------------------------------------------------------------------*/ mfxStatus IMfxGstFrameConstuctor::Unload(void) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = Sync(); current_bst_.reset(); MFX_DEBUG_TRACE_I32(sts); return sts; } /*------------------------------------------------------------------------------*/ mfxStatus IMfxGstFrameConstuctor::Sync(void) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = MFX_ERR_NONE; if (buffered_bst_.DataLength && buffered_bst_.DataOffset) { memmove(buffered_bst_.Data, buffered_bst_.Data + buffered_bst_.DataOffset, buffered_bst_.DataLength); } buffered_bst_.DataOffset = 0; mfxBitstream * bst = current_bst_.get() ? current_bst_->bst() : NULL; if (bst && bst->DataLength) { sts = buffered_bst_.Append(bst); } MFX_DEBUG_TRACE_I32(sts); return sts; } /*------------------------------------------------------------------------------*/ mfxStatus IMfxGstFrameConstuctor::Reset(void) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = MFX_ERR_NONE; buffered_bst_.Reset(); if (m_bs_state >= MfxGstBS_HeaderCollecting) m_bs_state = MfxGstBS_Resetting; MFX_DEBUG_TRACE_I32(sts); return sts; } /*------------------------------------------------------------------------------*/ mfxBitstream * IMfxGstFrameConstuctor::GetMfxBitstream(void) { MFX_DEBUG_TRACE_FUNC; mfxBitstream * bst = nullptr; auto loaded_bst = current_bst_ ? current_bst_->bst() : nullptr; if (buffered_bst_.Data && buffered_bst_.DataLength) { bst = &buffered_bst_; } else if (loaded_bst && loaded_bst->Data && loaded_bst->DataLength) { bst = loaded_bst; } else { bst = &buffered_bst_; } MFX_DEBUG_TRACE_P(&buffered_bst_); MFX_DEBUG_TRACE_P(&loaded_bst); MFX_DEBUG_TRACE_P(bst); return bst; } /*------------------------------------------------------------------------------*/ IMfxGstFrameConstuctor* MfxGstFrameConstuctorFactory::CreateFrameConstuctor(MfxGstFrameConstuctorType type) { IMfxGstFrameConstuctor* fc = nullptr; if (MfxGstFC_NoChange == type) { fc = new MfxGstFrameConstuctor; } else if (MfxGstFC_AVCC == type) { fc = new MfxGstAVCFrameConstuctorAVCC; } return fc; } /*------------------------------------------------------------------------------*/ mfxStatus MfxGstFrameConstuctor::LoadToNativeFormat(std::shared_ptr<mfxGstBitstreamBufferRef> bst_ref, bool /*header*/) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = MFX_ERR_NONE; auto bst = bst_ref ? bst_ref->bst() : nullptr; if (buffered_bst_.DataLength) { sts = buffered_bst_.Append(bst); current_bst_.reset(); } else { current_bst_ = bst_ref; } MFX_DEBUG_TRACE_I32(sts); return sts; } /*------------------------------------------------------------------------------*/ mfxStatus MfxGstAVCFrameConstuctorAVCC::LoadToNativeFormat(std::shared_ptr<mfxGstBitstreamBufferRef> bst_ref, bool header) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = MFX_ERR_NONE; if (header) { ConstructHeader(bst_ref); } else { auto * bst = bst_ref ? bst_ref->bst() : nullptr; convert_avcc_to_bytestream(bst); if (buffered_bst_.DataLength) { sts = buffered_bst_.Append(bst); current_bst_.reset(); } else { current_bst_ = bst_ref; } } MFX_DEBUG_TRACE_I32(sts); return sts; } mfxStatus MfxGstAVCFrameConstuctorAVCC::ConstructHeader(std::shared_ptr<mfxGstBitstreamBufferRef> bst_ref) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = MFX_ERR_NONE; mfxU8 * data = NULL; mfxU32 size = 0; mfxU32 numOfSequenceParameterSets = 0; mfxU32 numOfPictureParameterSets = 0; mfxU32 sequenceParameterSetLength = 0; mfxU32 pictureParameterSetLength = 0; static mfxU8 header[4] = {0x00, 0x00, 0x00, 0x01}; MfxBistreamBuffer bst_header; mfxBitstream * in_bst = bst_ref.get() ? bst_ref->bst() : NULL; if (!in_bst) { sts = MFX_ERR_NULL_PTR; goto _done; } if ((bst_header.Extend(1024) != MFX_ERR_NONE) || (!bst_header.Data)) { sts = MFX_ERR_MEMORY_ALLOC; goto _done; } data = in_bst->Data; size = in_bst->DataLength; /* AVCDecoderConfigurationRecord: * - mfxU8 - configurationVersion = 1 * - mfxU8 - AVCProfileIndication * - mfxU8 - profile_compatibility * - mfxU8 - AVCLevelIndication * - mfxU8 - '111111'b + lengthSizeMinusOne * - mfxU8 - '111'b + numOfSequenceParameterSets * - for (i = 0; i < numOfSequenceParameterSets; ++i) { * - mfxU16 - sequenceParameterSetLength * - mfxU8*sequenceParameterSetLength - SPS * } * - mfxU8 - numOfPictureParameterSets * - for (i = 0; i < numOfPictureParameterSets; ++i) { * - mfxU16 - pictureParameterSetLength * - mfxU8*pictureParameterSetLength - PPS * } */ if (size < 5) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } data += 5; size -= 5; if (size < 1) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } numOfSequenceParameterSets = data[0] & 0x1f; ++data; --size; for (mfxU32 i = 0; i < numOfSequenceParameterSets; ++i) { if (size < 2) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } sequenceParameterSetLength = (data[0] << 8) | data[1]; data += 2; size -= 2; if (size < sequenceParameterSetLength) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } if (bst_header.MaxLength - bst_header.DataOffset + bst_header.DataLength < 4 + sequenceParameterSetLength) { if (MFX_ERR_NONE != bst_header.Extend(4 + sequenceParameterSetLength)) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } } mfxU8 * buf = bst_header.Data + bst_header.DataOffset + bst_header.DataLength; memcpy(buf, header, sizeof(mfxU8)*4); memcpy(&(buf[4]), data, sizeof(mfxU8)*sequenceParameterSetLength); data += sequenceParameterSetLength; size -= sequenceParameterSetLength; bst_header.DataLength += 4 + sequenceParameterSetLength; } if (size < 1) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } numOfPictureParameterSets = data[0]; ++data; --size; for (mfxU32 i = 0; i < numOfPictureParameterSets; ++i) { if (size < 2) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } pictureParameterSetLength = (data[0] << 8) | data[1]; data += 2; size -= 2; if (size < pictureParameterSetLength) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } if (bst_header.MaxLength - bst_header.DataOffset + bst_header.DataLength < 4 + pictureParameterSetLength) { if (MFX_ERR_NONE != bst_header.Extend(4 + pictureParameterSetLength)) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } } mfxU8 * buf = bst_header.Data + bst_header.DataOffset + bst_header.DataLength; memcpy(buf, header, sizeof(mfxU8)*4); memcpy(&(buf[4]), data, sizeof(mfxU8)*pictureParameterSetLength); data += pictureParameterSetLength; size -= pictureParameterSetLength; bst_header.DataLength += 4 + pictureParameterSetLength; } sts = buffered_bst_.Append(bst_header); _done: return sts; }
28.673529
122
0.637296
d871c04714b3c998d4d0f8f20d2f85a9bd6f8ce3
206
cpp
C++
Object Oriented Algo Design in C++/practice/height_heap.cpp
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
Object Oriented Algo Design in C++/practice/height_heap.cpp
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
Object Oriented Algo Design in C++/practice/height_heap.cpp
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
int height(int i,int size) { int l,r; if(i>size) return 0; else { l=height(2*i,size); r=height(((2*i)+1),size); if(l>r) { l=l+1; return l; } else { r=r+1; return r; } } }
9.363636
27
0.475728
d872dad72aa20ff0381e61a47744ec79c79d5686
4,281
hpp
C++
src/nnfusion/core/kernels/cpu/eigen/softmax.hpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
src/nnfusion/core/kernels/cpu/eigen/softmax.hpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
src/nnfusion/core/kernels/cpu/eigen/softmax.hpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "../cpu_kernel_emitter.hpp" #include "nnfusion/core/operators/generic_op/generic_op.hpp" namespace nnfusion { namespace kernels { namespace cpu { template <typename ElementType> class SoftmaxEigen : public EigenKernelEmitter { public: SoftmaxEigen(shared_ptr<KernelContext> ctx) : EigenKernelEmitter(ctx) { auto pad = static_pointer_cast<nnfusion::op::Softmax>(ctx->gnode->get_op_ptr()); input_shape = nnfusion::Shape(ctx->inputs[0]->get_shape()); output_shape = nnfusion::Shape(ctx->outputs[0]->get_shape()); axes = pad->get_axes(); output_type = ctx->outputs[0]->get_element_type().c_type_string(); rank = static_cast<uint32_t>(input_shape.size()); std::stringstream tag; tag << rank << "softmax_i" << join(input_shape, "_") << "softmax_o" << join(output_shape, "_") << "_axes" << join(axes, "_"); custom_tag = tag.str(); } LanguageUnit_p emit_function_body() override { LanguageUnit_p _lu(new LanguageUnit(get_function_name())); auto& lu = *_lu; if (m_context->inputs[0]->get_element_type() == element::f32) { nnfusion::Shape rdims(rank); nnfusion::Shape bcast(rank); for (size_t i = 0; i < rank; ++i) { if (axes.count(i)) { rdims[i] = 1; } else { rdims[i] = input_shape[i]; } } for (size_t i = 0; i < rank; ++i) { bcast[i] = input_shape[i] / rdims[i]; } auto code = nnfusion::op::create_code_from_template( R"( Eigen::array<Eigen::Index, @Rank@> in_dims({@in_dims@}); Eigen::array<Eigen::Index, @Rank@> rdims({@rdims@}); Eigen::array<Eigen::Index, @Rank@> bcast({@bcast@}); Eigen::array<Eigen::Index, @AxisCount@> axes({@axes@}); Eigen::TensorMap<Eigen::Tensor<@ElementType@, @Rank@, Eigen::RowMajor>> out( static_cast<@ElementType@ *>(output0), in_dims), in(static_cast<@ElementType@ *>(input0), in_dims); out.device(*(thread_pool->GetDevice())) = (in - in.maximum(axes).eval().reshape(rdims).broadcast(bcast)).exp(); out.device(*(thread_pool->GetDevice())) = out * out.sum(axes).inverse().eval().reshape(rdims).broadcast(bcast); )", {{"Rank", rank}, {"AxisCount", axes.size()}, {"in_dims", join(input_shape)}, {"rdims", join(rdims)}, {"bcast", join(bcast)}, {"axes", join(axes)}, {"ElementType", output_type}}); lu << code; } else { return nullptr; } return _lu; } LanguageUnit_p emit_dependency() override { LanguageUnit_p _lu(new LanguageUnit(get_function_name() + "_dep")); _lu->require(header::thread); _lu->require(header::eigen_tensor); return _lu; } private: shared_ptr<KernelContext> kernel_ctx; nnfusion::Shape input_shape, output_shape; nnfusion::AxisSet axes; uint32_t rank; string output_type; }; } // namespace cpu } // namespace kernels } // namespace nnfusion
38.223214
100
0.443354
d874fed91ddb84f034e8e97d57a87d232bd6e028
2,108
hpp
C++
Core/DescriptorSet.hpp
Shmaug/vkCAVE
e502aedaf172047557f0454acb170a46b9d350f8
[ "MIT" ]
2
2019-10-01T22:55:47.000Z
2019-10-04T20:25:29.000Z
Core/DescriptorSet.hpp
Shmaug/vkCAVE
e502aedaf172047557f0454acb170a46b9d350f8
[ "MIT" ]
null
null
null
Core/DescriptorSet.hpp
Shmaug/vkCAVE
e502aedaf172047557f0454acb170a46b9d350f8
[ "MIT" ]
null
null
null
#pragma once #include <Util/Util.hpp> class Device; class Texture; class Buffer; class Sampler; class DescriptorSet { public: ENGINE_EXPORT DescriptorSet(const std::string& name, Device* device, VkDescriptorSetLayout layout); ENGINE_EXPORT ~DescriptorSet(); ENGINE_EXPORT void CreateStorageBufferDescriptor(Buffer* buffer, uint32_t index, VkDeviceSize offset, VkDeviceSize range, uint32_t binding); ENGINE_EXPORT void CreateStorageBufferDescriptor(Buffer* buffer, VkDeviceSize offset, VkDeviceSize range, uint32_t binding); ENGINE_EXPORT void CreateStorageTexelBufferDescriptor(Buffer* view, uint32_t binding); ENGINE_EXPORT void CreateUniformBufferDescriptor(Buffer* buffer, VkDeviceSize offset, VkDeviceSize range, uint32_t binding); ENGINE_EXPORT void CreateStorageTextureDescriptor(Texture* texture, uint32_t binding, VkImageLayout layout = VK_IMAGE_LAYOUT_GENERAL); ENGINE_EXPORT void CreateStorageTextureDescriptor(Texture* texture, uint32_t index, uint32_t binding, VkImageLayout layout = VK_IMAGE_LAYOUT_GENERAL); ENGINE_EXPORT void CreateSampledTextureDescriptor(Texture* texture, uint32_t binding, VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); ENGINE_EXPORT void CreateSampledTextureDescriptor(Texture* texture, uint32_t index, uint32_t binding, VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); ENGINE_EXPORT void CreateSamplerDescriptor(Sampler* sampler, uint32_t binding); ENGINE_EXPORT void FlushWrites(); inline VkDescriptorSetLayout Layout() const { return mLayout; } inline operator const VkDescriptorSet*() const { return &mDescriptorSet; } inline operator VkDescriptorSet() const { return mDescriptorSet; } private: std::unordered_map<uint64_t, VkWriteDescriptorSet> mCurrent; std::vector<VkWriteDescriptorSet> mPending; std::queue<VkDescriptorBufferInfo*> mBufferInfoPool; std::queue<VkDescriptorImageInfo*> mImageInfoPool; std::vector<VkDescriptorBufferInfo*> mPendingBuffers; std::vector<VkDescriptorImageInfo*> mPendingImages; Device* mDevice; VkDescriptorSet mDescriptorSet; VkDescriptorSetLayout mLayout; };
45.826087
168
0.833491
d875c03131f5d23004d3af46de9f475a03d9e566
2,102
cc
C++
TC-programs/STUFF/sort_excitationsa.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
TC-programs/STUFF/sort_excitationsa.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
TC-programs/STUFF/sort_excitationsa.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
# include <iostream> # include <fstream> # include <string.h> # include <stdio.h> # include <stdlib.h> # include <sstream> # include <math.h> using namespace std; void swap_line(int &froma, int &toa, double &coeffa, int &fromb, int &tob, double &coeffb){ int tempfrom, tempto; double tempcoeff; tempfrom = froma; froma = fromb; fromb = tempfrom; tempto = toa; toa = tob; tob = tempto; tempcoeff = coeffa; coeffa = coeffb; coeffb = tempcoeff; } int main(int argc, char* argv[]){ if(argc != 2){ cerr << "Usage: ./sort_excitations <infile>\n"; exit(0); } ifstream inf; inf.open(argv[1]); int nros; double gsenergy; inf >> gsenergy >> nros; double* excenergies = new double[nros]; for(int i = 0; i < nros; i++) inf >> excenergies[i]; int limit, state; double dndum; double* upcoeff = new double[500]; int* frommo = new int[500]; int* tomo = new int[500]; for(int i = 0; i < nros; i++){ inf >> limit; if(limit > 0){ for(int j = 0; j < limit; j++){ inf >> state >> frommo[j] >> tomo[j] >> upcoeff[j] >> dndum; cout << state << " " << frommo[j] << " " << tomo[j] << " " << upcoeff[j] << " " << dndum << "\n"; } for(int k = 0; k < (limit-2); k++){ if(k%2 == 0){ #pragma omp parallel for for(int j = 0; j < (limit/2); j++){ if(fabs(upcoeff[2*j]) < fabs(upcoeff[2*j+1])){ swap_line(frommo[2*j], tomo[2*j], upcoeff[2*j], frommo[2*j+1], tomo[2*j+1], upcoeff[2*j+1]); } } }else{ #pragma omp parallel for for(int j = 0; j < (nros/2-1); j++){ if(fabs(upcoeff[2*j+1]) < fabs(upcoeff[2*j+2])){ swap_line(frommo[2*j+1], tomo[2*j+1], upcoeff[2*j+1], frommo[2*j+2], tomo[2*j+2], upcoeff[2*j+2]); } } } } } cout << "State: " << i << "\n"; if(limit >= 3){ for(int j = 0; j < 3; j++) cout << frommo[j] << " " << tomo[j] << " " << upcoeff[j] << "\n"; }else if(limit > 0){ for(int j = 0; j < limit; j++) cout << frommo[j] << " " << tomo[j] << " " << upcoeff[j] << "\n"; }else{ cout << "0 0 1.00000\n"; } } }
26.607595
103
0.519029
d877e2908aa3d9ea6e7a4a3a17d62b6954741c44
1,481
cpp
C++
src/cpp/UTILS/DistilleryExceptionCode.cpp
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
10
2021-02-19T20:19:24.000Z
2021-09-16T05:11:50.000Z
src/cpp/UTILS/DistilleryExceptionCode.cpp
xguerin/openstreams
7000370b81a7f8778db283b2ba9f9ead984b7439
[ "Apache-2.0" ]
7
2021-02-20T01:17:12.000Z
2021-06-08T14:56:34.000Z
src/cpp/UTILS/DistilleryExceptionCode.cpp
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
4
2021-02-19T18:43:10.000Z
2022-02-23T14:18:16.000Z
/* * Copyright 2021 IBM Corporation * * 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 <UTILS/DistilleryExceptionCode.h> #include <UTILS/SerializationBuffer.h> UTILS_NAMESPACE_USE using namespace std; const string DistilleryExceptionCode::NO_MESSAGE_ID = "NoMessageId"; DistilleryExceptionCode::DistilleryExceptionCode(const string& messageId) : _msgId(messageId){}; DistilleryExceptionCode::DistilleryExceptionCode(const DistilleryExceptionCode& ec) : _msgId(ec._msgId){}; DistilleryExceptionCode::DistilleryExceptionCode(SerializationBuffer& data) : _msgId(data.getSTLString()){}; void DistilleryExceptionCode::serialize(SerializationBuffer& s) const { s.addSTLString(_msgId); } void DistilleryExceptionCode::print(ostream& o) const { o << _msgId; } DistilleryExceptionCode::~DistilleryExceptionCode(void) throw() {} ostream& UTILS_NAMESPACE::operator<<(ostream& o, const DistilleryExceptionCode& i) { i.print(o); return o; }
29.039216
83
0.766374
d8795b1764abefc1e1b3e6a06455b268e65532f0
522
cpp
C++
CodingInterviews/cpp/56_get_missing_number.cpp
YorkFish/git_study
6e023244daaa22e12b24e632e76a13e5066f2947
[ "MIT" ]
null
null
null
CodingInterviews/cpp/56_get_missing_number.cpp
YorkFish/git_study
6e023244daaa22e12b24e632e76a13e5066f2947
[ "MIT" ]
null
null
null
CodingInterviews/cpp/56_get_missing_number.cpp
YorkFish/git_study
6e023244daaa22e12b24e632e76a13e5066f2947
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int getMissingNumber(vector<int>& nums) { int left = 0, right = nums.size(); while (left < right) { int mid = left + (right - left) / 2; if (mid == nums[mid]) left = mid + 1; else right = mid; } return left; } }; int main() { vector<int> nums{0, 1, 2, 4}; Solution s; int ans = s.getMissingNumber(nums); cout << ans << endl; return 0; }
18.642857
49
0.519157
f21d904334a6c51d4a57974b32bc4313dfb92ad1
1,929
hpp
C++
src/pyprx/visualization/three_js_group_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
3
2021-05-31T11:28:03.000Z
2021-05-31T13:49:30.000Z
src/pyprx/visualization/three_js_group_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
1
2021-09-03T09:39:32.000Z
2021-12-10T22:17:56.000Z
src/pyprx/visualization/three_js_group_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
2
2021-09-03T09:17:45.000Z
2021-10-04T15:52:58.000Z
#include <iostream> #include <boost/python.hpp> #include "prx/visualization/three_js_group.hpp" void (prx::three_js_group_t::*update_vis_infos_1_1)(prx::info_geometry_t, const prx::trajectory_t&, std::string, prx::space_t*, std::string color) = &prx::three_js_group_t::add_vis_infos; void (prx::three_js_group_t::*update_vis_infos_2_1)(prx::info_geometry_t, std::vector<prx::vector_t>, std::string, double) = &prx::three_js_group_t::add_vis_infos; // void (prx::three_js_group_t::*update_vis_infos_2_2)(prx::info_geometry_t, std::vector<prx::vector_t>, std::string) = &prx::three_js_group_t::add_vis_infos; // void (prx::three_js_group_t::*update_vis_infos_2_3)(prx::info_geometry_t, std::vector<prx::vector_t>) = &prx::three_js_group_t::add_vis_infos; void pyprx_visualization_three_js_group_py() { enum_<prx::info_geometry_t>("info_geometry") .value("LINE", prx::info_geometry_t::LINE) .value("QUAD", prx::info_geometry_t::QUAD) .value("FULL_LINE", prx::info_geometry_t::FULL_LINE) .value("CIRCLE", prx::info_geometry_t::CIRCLE) .export_values() ; class_<prx::three_js_group_t>("three_js_group", init<std::vector<prx::system_ptr_t>, std::vector<std::shared_ptr<prx::movable_object_t>>>()) .def("output_html", &prx::three_js_group_t::output_html) .def("update_vis_infos", &prx::three_js_group_t::update_vis_infos) .def("add_vis_infos", update_vis_infos_1_1) // .def("add_vis_infos", update_vis_infos_1_2) .def("add_vis_infos", update_vis_infos_2_1) // .def("add_vis_infos", update_vis_infos_2_2) // .def("add_vis_infos", update_vis_infos_2_3) .def("add_detailed_vis_infos", &prx::three_js_group_t::add_detailed_vis_infos) .def("snapshot_state", &prx::three_js_group_t::snapshot_state) ; }
53.583333
191
0.6817
f21f1628be052c4ba093baefeb32dbf6eae4df4b
13,324
cc
C++
agp-7.1.0-alpha01/tools/base/profiler/native/perfd/profiler_service_test.cc
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
1
2020-10-04T19:30:22.000Z
2020-10-04T19:30:22.000Z
agp-7.1.0-alpha01/tools/base/profiler/native/perfd/profiler_service_test.cc
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
agp-7.1.0-alpha01/tools/base/profiler/native/perfd/profiler_service_test.cc
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
2
2020-10-04T19:30:24.000Z
2020-11-04T05:58:17.000Z
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <climits> #include <unordered_set> #include <grpc++/grpc++.h> #include "perfd/profiler_service.h" #include "perfd/sessions/sessions_manager.h" #include "proto/profiler.grpc.pb.h" #include "utils/daemon_config.h" #include "utils/fake_clock.h" #include "utils/file_cache.h" #include "utils/fs/memory_file_system.h" #include "utils/log.h" using std::unique_ptr; namespace profiler { class ProfilerServiceTest : public ::testing::Test { public: ProfilerServiceTest() : file_cache_(unique_ptr<FileSystem>(new MemoryFileSystem()), "/"), config_(proto::DaemonConfig::default_instance()), buffer_(&clock_, 10, 5), daemon_(&clock_, &config_, &file_cache_, &buffer_), service_(&daemon_) {} void SetUp() override { grpc::ServerBuilder builder; int port; builder.AddListeningPort("0.0.0.0:0", grpc::InsecureServerCredentials(), &port); builder.RegisterService(&service_); server_ = builder.BuildAndStart(); std::shared_ptr<grpc::ChannelInterface> channel = grpc::CreateChannel(std::string("0.0.0.0:") + std::to_string(port), grpc::InsecureChannelCredentials()); stub_ = proto::ProfilerService::NewStub(channel); // Create a new thread to read events on. events_thread_ = std::thread(&ProfilerServiceTest::GetEvents, this); SessionsManager::Instance()->ClearSessions(); } proto::Session BeginSession(int32_t device_id, int32_t pid) { proto::BeginSessionRequest req; req.set_device_id(device_id); req.set_pid(pid); grpc::ClientContext context; proto::BeginSessionResponse res; stub_->BeginSession(&context, req, &res); return res.session(); } proto::Session EndSession(int32_t device_id, int32_t session_id) { proto::EndSessionRequest req; req.set_device_id(device_id); req.set_session_id(session_id); grpc::ClientContext context; proto::EndSessionResponse res; stub_->EndSession(&context, req, &res); return res.session(); } proto::GetSessionsResponse GetSessions(int64_t start, int64_t end) { proto::GetSessionsRequest request; request.set_start_timestamp(start); request.set_end_timestamp(end); grpc::ClientContext context; proto::GetSessionsResponse sessions; stub_->GetSessions(&context, request, &sessions); return sessions; } void GetEvents() { proto::GetEventsRequest request; events_reader_ = stub_->GetEvents(&events_context_, request); proto::Event event; // Read is a blocking call. while (events_reader_->Read(&event)) { std::unique_lock<std::mutex> lock(events_mutex_); events_.push(event); events_cv_.notify_all(); } } std::unique_ptr<proto::Event> PopEvent() { std::unique_lock<std::mutex> lock(events_mutex_); // Check events list for elements, if no elements found block until // we timeout (returning null) or we have an event. if (events_cv_.wait_for(lock, std::chrono::milliseconds(500), [this] { return !events_.empty(); })) { proto::Event event = events_.front(); events_.pop(); return std::unique_ptr<proto::Event>(new proto::Event(event)); } return nullptr; } bool IsSessionActive(const proto::Session& session) { return session.end_timestamp() == LLONG_MAX; } void TearDown() override { // Stop client and server listeners. daemon_.InterruptWriteEvents(); events_context_.TryCancel(); events_reader_->Finish(); events_thread_.join(); server_->Shutdown(); } FakeClock clock_; FileCache file_cache_; DaemonConfig config_; EventBuffer buffer_; Daemon daemon_; ProfilerServiceImpl service_; std::mutex events_mutex_; std::condition_variable events_cv_; std::queue<proto::Event> events_; std::thread events_thread_; grpc::ClientContext events_context_; std::unique_ptr<::grpc::Server> server_; std::unique_ptr<proto::ProfilerService::Stub> stub_; std::unique_ptr<grpc::ClientReader<proto::Event>> events_reader_; }; TEST_F(ProfilerServiceTest, TestBeginSessionCommand) { // Test legacy api: // Because lagacy APIs use device ID but new APIs don't, we have to call // legacy BeginSession API at least once so profiler service knows about the // device ID. clock_.SetCurrentTime(20); proto::BeginSessionRequest begin_req; begin_req.set_device_id(100); begin_req.set_pid(1002); grpc::ClientContext begin_context; proto::BeginSessionResponse begin_res; stub_->BeginSession(&begin_context, begin_req, &begin_res); grpc::ClientContext sessions_context; proto::GetSessionsRequest sreq; sreq.set_start_timestamp(0); sreq.set_end_timestamp(20); proto::GetSessionsResponse sres; stub_->GetSessions(&sessions_context, sreq, &sres); ASSERT_EQ(3, sres.sessions_size()); // Test id generation to ensure refactoring maintains same id's. EXPECT_EQ(96, sres.sessions(0).session_id()); EXPECT_EQ(100, sres.sessions(0).stream_id()); EXPECT_EQ(1000, sres.sessions(0).pid()); EXPECT_EQ(2, sres.sessions(0).start_timestamp()); EXPECT_EQ(4, sres.sessions(0).end_timestamp()); EXPECT_EQ(108, sres.sessions(1).session_id()); EXPECT_EQ(100, sres.sessions(1).stream_id()); EXPECT_EQ(1001, sres.sessions(1).pid()); EXPECT_EQ(4, sres.sessions(1).start_timestamp()); EXPECT_EQ(20, sres.sessions(1).end_timestamp()); EXPECT_EQ(LLONG_MAX, sres.sessions(2).end_timestamp()); } TEST_F(ProfilerServiceTest, TestBufferFull) { for (int32_t i = 0; i < 5; i++) { clock_.SetCurrentTime(i); BeginSession(1234, 101); proto::GetSessionsResponse sessions = GetSessions(0, i + 1); ASSERT_EQ(i + 1, sessions.sessions_size()); } proto::GetSessionsResponse sessions = GetSessions(0, 6); ASSERT_EQ(5, sessions.sessions_size()); auto first = sessions.sessions(0).session_id(); auto second = sessions.sessions(1).session_id(); // Creating a new session would push the first one out clock_.SetCurrentTime(5); BeginSession(1234, 101); sessions = GetSessions(0, 6); ASSERT_EQ(5, sessions.sessions_size()); ASSERT_NE(first, second); ASSERT_EQ(second, sessions.sessions(0).session_id()); } TEST_F(ProfilerServiceTest, TestBeginSession) { clock_.SetCurrentTime(2); BeginSession(100, 1000); clock_.SetCurrentTime(4); BeginSession(101, 1001); proto::GetSessionsResponse sessions = GetSessions(1, 3); ASSERT_EQ(1, sessions.sessions_size()); sessions = GetSessions(1, 5); ASSERT_EQ(2, sessions.sessions_size()); sessions = GetSessions(3, 5); ASSERT_EQ(2, sessions.sessions_size()); } TEST_F(ProfilerServiceTest, CanBeginAndEndASession) { clock_.SetCurrentTime(1234); proto::Session begin = BeginSession(2222, 1); EXPECT_EQ(begin.start_timestamp(), 1234); EXPECT_EQ(begin.end_timestamp(), LONG_MAX); EXPECT_EQ(begin.stream_id(), 2222); EXPECT_EQ(begin.pid(), 1); EXPECT_TRUE(IsSessionActive(begin)); clock_.Elapse(10); // Session ended_session; proto::Session end = EndSession(2222, begin.session_id()); EXPECT_EQ(begin.session_id(), end.session_id()); // Test ids to ensure they are stable EXPECT_EQ(0x10A, end.session_id()); EXPECT_EQ(end.end_timestamp(), 1234 + 10); EXPECT_FALSE(IsSessionActive(end)); } TEST_F(ProfilerServiceTest, BeginClosesPreviousSession) { clock_.SetCurrentTime(1234); proto::Session session1 = BeginSession(-1, 1); clock_.Elapse(10); EXPECT_TRUE(IsSessionActive(session1)); EXPECT_EQ(1, session1.pid()); proto::Session session2 = BeginSession(-2, 2); clock_.Elapse(10); EXPECT_TRUE(IsSessionActive(session2)); EXPECT_EQ(2, session2.pid()); proto::Session session3 = BeginSession(-3, 3); clock_.Elapse(10); EXPECT_TRUE(IsSessionActive(session3)); EXPECT_EQ(3, session3.pid()); { proto::GetSessionsResponse sessions = GetSessions(LLONG_MIN, LLONG_MAX); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_FALSE(IsSessionActive(sessions.sessions(0))); EXPECT_FALSE(IsSessionActive(sessions.sessions(1))); EXPECT_TRUE(IsSessionActive(sessions.sessions(2))); } // End and already ended session EndSession(-1, session2.session_id()); { proto::GetSessionsResponse sessions = GetSessions(LLONG_MIN, LLONG_MAX); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_FALSE(IsSessionActive(sessions.sessions(0))); EXPECT_FALSE(IsSessionActive(sessions.sessions(1))); EXPECT_TRUE(IsSessionActive(sessions.sessions(2))); } // End the last session EndSession(-1, session3.session_id()); { proto::GetSessionsResponse sessions = GetSessions(LLONG_MIN, LLONG_MAX); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_FALSE(IsSessionActive(sessions.sessions(0))); EXPECT_FALSE(IsSessionActive(sessions.sessions(1))); EXPECT_FALSE(IsSessionActive(sessions.sessions(2))); } } TEST_F(ProfilerServiceTest, GetSessionsByTimeRangeWorks) { clock_.SetCurrentTime(1000); // Session from 1000 to 1500. proto::Session session = BeginSession(-10, 10); clock_.Elapse(500); session = EndSession(-1, session.session_id()); // Session from 2000 to 2500. clock_.Elapse(500); session = BeginSession(-20, 20); clock_.Elapse(500); session = EndSession(-1, session.session_id()); // Session from 3000 to 3500. clock_.Elapse(500); session = BeginSession(-30, 30); clock_.Elapse(500); session = EndSession(-1, session.session_id()); // Session from 4000 to 4500. clock_.Elapse(500); session = BeginSession(-40, 40); clock_.Elapse(500); session = EndSession(-1, session.session_id()); // Session from 5000 to present. clock_.Elapse(500); session = BeginSession(-50, 50); EXPECT_TRUE(IsSessionActive(session)); { // Get all auto sessions = GetSessions(LLONG_MIN, LLONG_MAX); EXPECT_EQ(5, sessions.sessions_size()); EXPECT_EQ(10, sessions.sessions(0).pid()); EXPECT_EQ(20, sessions.sessions(1).pid()); EXPECT_EQ(30, sessions.sessions(2).pid()); EXPECT_EQ(40, sessions.sessions(3).pid()); EXPECT_EQ(50, sessions.sessions(4).pid()); } { // Get all sessions ended after a time range auto sessions = GetSessions(3250, LLONG_MAX); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_EQ(30, sessions.sessions(0).pid()); EXPECT_EQ(40, sessions.sessions(1).pid()); EXPECT_EQ(50, sessions.sessions(2).pid()); } { // Get all sessions started before a time range auto sessions = GetSessions(0, 3250); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_EQ(10, sessions.sessions(0).pid()); EXPECT_EQ(20, sessions.sessions(1).pid()); EXPECT_EQ(30, sessions.sessions(2).pid()); } { // Get sessions between two time ranges auto sessions = GetSessions(2250, 3250); EXPECT_EQ(2, sessions.sessions_size()); EXPECT_EQ(20, sessions.sessions(0).pid()); EXPECT_EQ(30, sessions.sessions(1).pid()); } { // An active session has no end timestamp and, until it ends, is assumed // extend forever. auto sessions = GetSessions(clock_.GetCurrentTime() + 1000, LLONG_MAX); EXPECT_EQ(1, sessions.sessions_size()); EXPECT_EQ(50, sessions.sessions(0).pid()); } } TEST_F(ProfilerServiceTest, BeginingTwiceIsTheSameAsEndingInBetween) { clock_.SetCurrentTime(1000); proto::Session session; EXPECT_EQ(0, GetSessions(LLONG_MIN, LLONG_MAX).sessions_size()); session = BeginSession(-10, 10); clock_.Elapse(10); EXPECT_EQ(1, GetSessions(LLONG_MIN, LLONG_MAX).sessions_size()); session = BeginSession(-10, 10); clock_.Elapse(10); EXPECT_EQ(2, GetSessions(LLONG_MIN, LLONG_MAX).sessions_size()); session = EndSession(-1, session.session_id()); clock_.Elapse(10); session = BeginSession(-10, 10); clock_.Elapse(10); { auto sessions = GetSessions(LLONG_MIN, LLONG_MAX); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_EQ(10, sessions.sessions(0).pid()); EXPECT_FALSE(IsSessionActive(sessions.sessions(0))); EXPECT_EQ(10, sessions.sessions(1).pid()); EXPECT_FALSE(IsSessionActive(sessions.sessions(1))); EXPECT_EQ(10, sessions.sessions(2).pid()); EXPECT_TRUE(IsSessionActive(sessions.sessions(2))); } } TEST_F(ProfilerServiceTest, UniqueSessionIds) { clock_.SetCurrentTime(1234); std::unordered_set<int64_t> session_ids; for (int32_t device_id = 0; device_id < 100; device_id++) { for (int64_t start_time = 0; start_time < 10000; start_time += 100) { clock_.SetCurrentTime(start_time); proto::Session session = BeginSession(device_id, start_time); EXPECT_EQ(session_ids.end(), session_ids.find(session.session_id())); session_ids.insert(session.session_id()); } } } } // namespace profiler
33.31
78
0.707896
f22135104eb6c134a71fbbb52d41a9b1c7f155c1
20,275
cpp
C++
src/textnet_nextbasket.cpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
114
2017-06-14T07:05:31.000Z
2021-06-13T05:30:49.000Z
src/textnet_nextbasket.cpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
7
2017-11-17T08:16:55.000Z
2019-10-05T00:09:20.000Z
src/textnet_nextbasket.cpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
40
2017-06-15T03:21:10.000Z
2021-10-31T15:03:30.000Z
#define _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_DEPRECATE #include <iostream> #include <fstream> #include <ctime> #include <string> #include <cstring> #include <vector> #include <map> #include <climits> #include "./layer/layer.h" #include "./io/json/json.h" #include "global.h" #include <cassert> #include "./checker/checker.h" using namespace std; using namespace textnet; using namespace textnet::layer; using namespace mshadow; void PrintTensor(const char * name, Tensor<cpu, 1> x) { Shape<1> s = x.shape_; cout << name << " shape " << s[0] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { cout << x[d1] << " "; } cout << endl; } void PrintTensor(const char * name, Tensor<cpu, 2> x) { Shape<2> s = x.shape_; cout << name << " shape " << s[0] << "x" << s[1] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { for (unsigned int d2 = 0; d2 < s[1]; ++d2) { cout << x[d1][d2] << " "; } cout << endl; } cout << endl; } void PrintTensor(const char * name, Tensor<cpu, 3> x) { Shape<3> s = x.shape_; cout << name << " shape " << s[0] << "x" << s[1] << "x" << s[2] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { for (unsigned int d2 = 0; d2 < s[1]; ++d2) { for (unsigned int d3 = 0; d3 < s[2]; ++d3) { cout << x[d1][d2][d3] << " "; } cout << ";"; } cout << endl; } } void PrintTensor(const char * name, Tensor<cpu, 4> x) { Shape<4> s = x.shape_; cout << name << " shape " << s[0] << "x" << s[1] << "x" << s[2] << "x" << s[3] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { for (unsigned int d2 = 0; d2 < s[1]; ++d2) { for (unsigned int d3 = 0; d3 < s[2]; ++d3) { for (unsigned int d4 = 0; d4 < s[3]; ++d4) { cout << x[d1][d2][d3][d4] << " "; } cout << "|"; } cout << ";"; } cout << endl; } cout << endl; } struct EvalRet { float acc, loss; EvalRet(): acc(0.), loss(0.) {} void clear() { acc = 0.; loss = 0.; } }; void eval(vector<Layer<cpu> *> senti_net, vector<vector<Node<cpu> *> > &bottoms, vector<vector<Node<cpu> *> > &tops, int nBatch, EvalRet &ret) { ret.clear(); for (int i = 0; i < nBatch; ++i) { for (int j = 0; j < senti_net.size(); ++j) { senti_net[j]->SetPhrase(kTest); senti_net[j]->Forward(bottoms[j], tops[j]); } ret.loss += tops[tops.size()-2][0]->data_d1()[0]; ret.acc += tops[tops.size()-1][0]->data_d1()[0] * tops[0][0]->data.size(0); } ret.loss /= float(nBatch); // ret.acc /= float(nBatch); } int main(int argc, char *argv[]) { mshadow::Random<cpu> rnd(37); vector<Layer<cpu>*> senti_net, senti_valid, senti_test, senti_train; if (argc >= 3) { freopen(argv[2], "w", stdout); setvbuf(stdout, NULL, _IOLBF, 0); } bool no_bias = true; float l2 = 0.f; int max_session_len = 300; int context_window = 1; int min_doc_len = 1; int batch_size = 1; int word_rep_dim = 50; int num_hidden = (context_window+1) * word_rep_dim; int num_item = 7973; int num_user = 2265; int num_class = num_item; float base_lr = 0.1; float ADA_GRAD_EPS = 0.1; float decay = 0.00; int nTrain = 168933;// nValid = 7, nTest = 7; int nTrainPred = num_user;// nValid = 7, nTest = 7; int nValid = num_user;// nValid = 7, nTest = 7; int nTest = num_user; // nValid = 7, nTest = 7; int max_iter = (20*nTrain)/(batch_size); int iter_eval = (nTrain/batch_size)/20; // int ADA_GRAD_MAX_ITER = 1000000; int ADA_GRAD_MAX_ITER = (nTrain/batch_size)/3; string train_data_file = "/home/wsx/dl.shengxian/data/pengfei/tafeng_sub.textnet.train.1"; string train_pred_data_file = "/home/wsx/dl.shengxian/data/pengfei/tafeng_sub.textnet.train_pred.1"; string valid_data_file = "/home/wsx/dl.shengxian/data/pengfei/tafeng_sub.textnet.valid.1"; string test_data_file = "/home/wsx/dl.shengxian/data/pengfei/tafeng_sub.textnet.test.1"; string embedding_file = ""; // string embedding_file = "/home/pangliang/matching/data/wikicorp_50_msr.txt"; // int nTrain = 1000;// nValid = 7, nTest = 7; if (argc >= 2) { base_lr = atof(argv[1]); } map<string, SettingV> &g_updater = *(new map<string, SettingV>()); // g_updater["updater_type"] = SettingV(updater::kAdaDelta); g_updater["updater_type"] = SettingV(updater::kAdagrad); g_updater["batch_size"] = SettingV(batch_size); g_updater["l2"] = SettingV(l2); g_updater["max_iter"] = SettingV(ADA_GRAD_MAX_ITER); g_updater["eps"] = SettingV(ADA_GRAD_EPS); g_updater["lr"] = SettingV(base_lr); // g_updater["decay"] = SettingV(decay); // g_updater["momentum"] = SettingV(0.0f); senti_net.push_back(CreateLayer<cpu>(kNextBasketData)); senti_net[senti_net.size()-1]->layer_name = "data"; senti_net.push_back(CreateLayer<cpu>(kEmbedding)); senti_net[senti_net.size()-1]->layer_name = "user_embedding"; senti_net.push_back(CreateLayer<cpu>(kEmbedding)); senti_net[senti_net.size()-1]->layer_name = "item_embedding"; senti_net.push_back(CreateLayer<cpu>(kWholePooling)); senti_net[senti_net.size()-1]->layer_name = "wholepooling"; senti_net.push_back(CreateLayer<cpu>(kConcat)); senti_net[senti_net.size()-1]->layer_name = "concat"; senti_net.push_back(CreateLayer<cpu>(kFullConnect)); senti_net[senti_net.size()-1]->layer_name = "fullconnect"; senti_net.push_back(CreateLayer<cpu>(kRectifiedLinear)); senti_net[senti_net.size()-1]->layer_name = "activation"; senti_net.push_back(CreateLayer<cpu>(kDropout)); senti_net[senti_net.size()-1]->layer_name = "dropout"; senti_net.push_back(CreateLayer<cpu>(kFullConnect)); senti_net[senti_net.size()-1]->layer_name = "fullconnect"; senti_net.push_back(CreateLayer<cpu>(kSoftmax)); senti_net[senti_net.size()-1]->layer_name = "softmax"; senti_net.push_back(CreateLayer<cpu>(kAccuracy)); senti_net[senti_net.size()-1]->layer_name = "accuracy"; senti_train = senti_net; senti_test = senti_net; senti_valid = senti_net; senti_train[0] = CreateLayer<cpu>(kNextBasketData); senti_test[0] = CreateLayer<cpu>(kNextBasketData); senti_valid[0]= CreateLayer<cpu>(kNextBasketData); vector<vector<Node<cpu>*> > bottom_vecs(senti_net.size(), vector<Node<cpu>*>()); vector<vector<Node<cpu>*> > top_vecs(senti_net.size(), vector<Node<cpu>*>()); vector<Node<cpu>*> nodes; for (int i = 0; i < senti_net.size(); ++i) { // last layers are softmax layer and accuracy layers int top_node_num = 0; top_node_num = senti_net[i]->TopNodeNum(); for (int j = 0; j < top_node_num; ++j) { Node<cpu>* node = new Node<cpu>(); stringstream ss; ss << nodes.size(); node->node_name = ss.str(); nodes.push_back(node); top_vecs[i].push_back(node); senti_net[i]->top_nodes.push_back(node->node_name); } } int layerIdx = 0; // data senti_net[0]->top_nodes.push_back(nodes[0]->node_name); // label senti_net[0]->top_nodes.push_back(nodes[1]->node_name); // label set senti_net[0]->top_nodes.push_back(nodes[2]->node_name); // user senti_net[0]->top_nodes.push_back(nodes[3]->node_name); // item senti_valid[0]->top_nodes.push_back(nodes[0]->node_name); // label senti_valid[0]->top_nodes.push_back(nodes[1]->node_name); // label set senti_valid[0]->top_nodes.push_back(nodes[2]->node_name); // user senti_valid[0]->top_nodes.push_back(nodes[3]->node_name); // item ++layerIdx; // user_embedding bottom_vecs[1].push_back(top_vecs[0][2]); senti_net[1]->bottom_nodes.push_back(nodes[2]->node_name); senti_net[1]->top_nodes.push_back(nodes[4]->node_name); ++layerIdx; // item_embedding bottom_vecs[2].push_back(top_vecs[0][3]); senti_net[2]->bottom_nodes.push_back(nodes[3]->node_name); senti_net[2]->top_nodes.push_back(nodes[5]->node_name); ++layerIdx; // whole_pooling bottom_vecs[3].push_back(top_vecs[2][0]); senti_net[3]->bottom_nodes.push_back(nodes[5]->node_name); senti_net[3]->top_nodes.push_back(nodes[6]->node_name); ++layerIdx; // 4 // concat bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-3][0]); bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[4]->node_name); senti_net[layerIdx]->bottom_nodes.push_back(nodes[6]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[7]->node_name); ++layerIdx; // fullconnect bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-1]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); ++layerIdx; // activation bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-1]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); ++layerIdx; // dropout bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-1]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); ++layerIdx; // fullconnect bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-1]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); ++layerIdx; // softmax bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); bottom_vecs[layerIdx].push_back(top_vecs[0][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-1]->node_name); senti_net[layerIdx]->bottom_nodes.push_back(nodes[0]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); ++layerIdx; // hit_cnt bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-2][0]); bottom_vecs[layerIdx].push_back(top_vecs[0][1]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-2]->node_name); senti_net[layerIdx]->bottom_nodes.push_back(nodes[1]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); // Fill Settings vector vector<map<string, SettingV> > setting_vec; // kNextBasketLayer { map<string, SettingV> setting; // orc setting["data_file"] = SettingV(train_data_file); setting["batch_size"] = SettingV(batch_size); setting["max_session_len"] = SettingV(max_session_len); setting["context_window"] = SettingV(context_window); setting_vec.push_back(setting); // test setting["batch_size"] = SettingV(batch_size); setting["data_file"] = SettingV(valid_data_file); senti_valid[0]->PropAll(); senti_valid[0]->SetupLayer(setting, bottom_vecs[0], top_vecs[0], &rnd); senti_valid[0]->Reshape(bottom_vecs[0], top_vecs[0]); setting["batch_size"] = SettingV(batch_size); setting["data_file"] = SettingV(train_pred_data_file); senti_train[0]->PropAll(); senti_train[0]->SetupLayer(setting, bottom_vecs[0], top_vecs[0], &rnd); senti_train[0]->Reshape(bottom_vecs[0], top_vecs[0]); setting["batch_size"] = SettingV(batch_size); setting["data_file"] = SettingV(test_data_file); senti_test[0]->PropAll(); senti_test[0]->SetupLayer(setting, bottom_vecs[0], top_vecs[0], &rnd); senti_test[0]->Reshape(bottom_vecs[0], top_vecs[0]); } // kEmbedding user { map<string, SettingV> setting; // orc setting["embedding_file"] = SettingV(embedding_file); setting["word_count"] = SettingV(num_user); setting["feat_size"] = SettingV(word_rep_dim); setting["pad_value"] = SettingV((float)(NAN)); map<string, SettingV> &w_setting = *(new map<string, SettingV>()); w_setting["init_type"] = SettingV(initializer::kUniform); w_setting["range"] = SettingV(1.f/word_rep_dim); setting["w_filler"] = SettingV(&w_setting); map<string, SettingV> &w_updater = *(new map<string, SettingV>()); w_updater = g_updater; setting["w_updater"] = SettingV(&w_updater); setting_vec.push_back(setting); } // kEmbedding item { map<string, SettingV> setting; // orc setting["embedding_file"] = SettingV(embedding_file); setting["word_count"] = SettingV(num_item); setting["feat_size"] = SettingV(word_rep_dim); setting["pad_value"] = SettingV((float)(NAN)); map<string, SettingV> &w_setting = *(new map<string, SettingV>()); w_setting = *setting_vec[setting_vec.size()-1]["w_filler"].mVal(); setting["w_filler"] = SettingV(&w_setting); map<string, SettingV> &w_updater = *(new map<string, SettingV>()); w_updater = g_updater; setting["w_updater"]= SettingV(&w_updater); setting_vec.push_back(setting); } // kWholeMaxPooling { map<string, SettingV> setting; setting["pool_type"] = "ave"; setting_vec.push_back(setting); } // kConcat { map<string, SettingV> setting; setting["bottom_node_num"] = context_window + 1; setting_vec.push_back(setting); } // kFullConnect { map<string, SettingV> setting; setting["num_hidden"] = SettingV(num_hidden); setting["no_bias"] = SettingV(no_bias); map<string, SettingV> &w_setting = *(new map<string, SettingV>()); w_setting["init_type"] = SettingV(initializer::kUniform); w_setting["range"] = SettingV(1.f/word_rep_dim); map<string, SettingV> &b_setting = *(new map<string, SettingV>()); b_setting["init_type"] = SettingV(initializer::kZero); setting["w_filler"] = SettingV(&w_setting); setting["b_filler"] = SettingV(&b_setting); map<string, SettingV> &w_updater = *(new map<string, SettingV>()); w_updater = g_updater; map<string, SettingV> &b_updater = *(new map<string, SettingV>()); b_updater = g_updater; setting["w_updater"] = SettingV(&w_updater); setting["b_updater"] = SettingV(&b_updater); setting_vec.push_back(setting); } // kActivation { map<string, SettingV> setting; setting_vec.push_back(setting); } // kDropout { map<string, SettingV> setting; setting["rate"] = SettingV(0.5f); setting_vec.push_back(setting); } // kFullConnect { map<string, SettingV> setting; setting["num_hidden"] = SettingV(num_class); setting["no_bias"] = SettingV(no_bias); map<string, SettingV> &w_setting = *(new map<string, SettingV>()); // w_setting["init_type"] = SettingV(initializer::kZero); w_setting["init_type"] = SettingV(initializer::kUniform); w_setting["range"] = SettingV(1.f/word_rep_dim); map<string, SettingV> &b_setting = *(new map<string, SettingV>()); b_setting["init_type"] = SettingV(initializer::kZero); setting["w_filler"] = SettingV(&w_setting); setting["b_filler"] = SettingV(&b_setting); map<string, SettingV> &w_updater = *(new map<string, SettingV>()); w_updater = g_updater; map<string, SettingV> &b_updater = *(new map<string, SettingV>()); b_updater = g_updater; setting["w_updater"] = SettingV(&w_updater); setting["b_updater"] = SettingV(&b_updater); setting_vec.push_back(setting); } // kSoftmax { map<string, SettingV> setting; // map<string, SettingV> &w_setting = *(new map<string, SettingV>()); // // w_setting["init_type"] = SettingV(initializer::kZero); // w_setting["init_type"] = SettingV(initializer::kZero); // map<string, SettingV> &b_setting = *(new map<string, SettingV>()); // b_setting["init_type"] = SettingV(initializer::kZero); // setting["w_filler"] = SettingV(&w_setting); // setting["b_filler"] = SettingV(&b_setting); setting_vec.push_back(setting); } // kAccuracy { map<string, SettingV> setting; setting["topk"] = SettingV(5); setting_vec.push_back(setting); } cout << "Setting Vector Filled." << endl; // Set up Layers for (index_t i = 0; i < senti_net.size(); ++i) { cout << "Begin set up layer " << i << endl; senti_net[i]->PropAll(); cout << "\tPropAll" << endl; senti_net[i]->SetupLayer(setting_vec[i], bottom_vecs[i], top_vecs[i], &rnd); cout << "\tSetup Layer" << endl; senti_net[i]->Reshape(bottom_vecs[i], top_vecs[i]); cout << "\tReshape" << endl; } // Save Initial Model { ofstream _of("./next.basket.model"); Json::StyledWriter writer; Json::Value net_root; net_root["net_name"] = "next_basket"; Json::Value layers_root; for (index_t i = 0; i < senti_net.size(); ++i) { Json::Value layer_root; senti_net[i]->SaveModel(layer_root, false); layers_root.append(layer_root); } net_root["layers"] = layers_root; string json_file = writer.write(net_root); _of << json_file; _of.close(); } // Begin Training float maxValidAcc = 0., testAccByValid = 0.; for (int iter = 0; iter < max_iter; ++iter) { // if (iter % 100 == 0) { cout << "iter:" << iter << endl; } if (iter % iter_eval == 0) { EvalRet train_ret, valid_ret, test_ret; // eval(senti_net, bottom_vecs, top_vecs, (nTrain/batch_size), train_ret); eval(senti_train, bottom_vecs, top_vecs, (nTrainPred/batch_size), train_ret); eval(senti_valid, bottom_vecs, top_vecs, (nValid/batch_size), valid_ret); eval(senti_test, bottom_vecs, top_vecs, (nTest/batch_size), test_ret); fprintf(stdout, "****%d,%f,%f,%f,%f,%f,%f", iter, train_ret.loss, valid_ret.loss, test_ret.loss, train_ret.acc, valid_ret.acc, test_ret.acc); if (valid_ret.acc > maxValidAcc) { maxValidAcc = valid_ret.acc; testAccByValid = test_ret.acc; fprintf(stdout, "*^_^*"); } fprintf(stdout, "\n"); } // cout << "Begin iter " << iter << endl; for (index_t i = 0; i < senti_net.size(); ++i) { senti_net[i]->SetPhrase(kTrain); // cout << "Forward layer " << i << endl; senti_net[i]->Forward(bottom_vecs[i], top_vecs[i]); } #if 0 for (index_t i = 0; i < nodes.size(); ++i) { cout << "# Data " << nodes[i]->node_name << " : "; for (index_t j = 0; j < 5; ++j) { cout << nodes[i]->data[0][0][0][j] << "\t"; } cout << endl; cout << "# Diff " << nodes[i]->node_name << " : "; for (index_t j = 0; j < 5; ++j) { cout << nodes[i]->diff[0][0][0][j] << "\t"; } cout << endl; } #endif for (int i = 0; i < senti_net.size(); ++i) { senti_net[i]->ClearDiff(bottom_vecs[i], top_vecs[i]); } for (int i = senti_net.size()-2; i >= 0; --i) { // cout << "Backprop layer " << i << endl; senti_net[i]->Backprop(bottom_vecs[i], top_vecs[i]); } for (index_t i = 0; i < senti_net.size(); ++i) { for (index_t j = 0; j < senti_net[i]->ParamNodeNum(); ++j) { // cout << "Update param in layer " << i << " params " << j << endl; // cout << "param data" << i << " , " << j << ": " << senti_net[i]->GetParams()[j].data[0][0][0][0] << endl; // cout << "param diff" << i << " , " << j << ": " << senti_net[i]->GetParams()[j].diff[0][0][0][0] << endl; if (senti_net[i]->layer_name == "fullconnect" && j == 1) continue; // bias is shit if (senti_net[i]->layer_name == "lstm" && j == 2) continue; // bias is shit senti_net[i]->GetParams()[j].Update(); // cout << "param data" << i << " , " << j << ": " << senti_net[i]->GetParams()[j].data[0][0][0][0] << endl<<endl; } } // Output informations // cout << "###### Iter " << iter << ": error =\t" << nodes[nodes.size()-2]->data_d1()[0] << endl; } return 0; }
38.472486
123
0.612429
f22dfd860b4d10bf32ddef2f1593e46d9b44ea93
3,276
cpp
C++
src/util/node.cpp
markhary/ctci
eb96014b779e2a7eca1229644300bae18caf328d
[ "Unlicense" ]
1
2021-11-17T16:50:54.000Z
2021-11-17T16:50:54.000Z
src/util/node.cpp
markhary/ctci
eb96014b779e2a7eca1229644300bae18caf328d
[ "Unlicense" ]
null
null
null
src/util/node.cpp
markhary/ctci
eb96014b779e2a7eca1229644300bae18caf328d
[ "Unlicense" ]
1
2020-06-15T13:54:04.000Z
2020-06-15T13:54:04.000Z
// Node object // #include <iostream> #include <vector> #include <gtest/gtest.h> #include "args.h" #include "macros.h" #include "util/node.h" using namespace std; using namespace ctci; using namespace ctci::util; TEST(Node, Initialize) { int value = 5; Node<int> node(value); ASSERT_EQ(node.value, value); ASSERT_EQ(node.visitState, UNVISITED); } TEST(Node, Cout) { // Simple test string test = "test"; const NodeTypeEnum nodeType = DIRECTED; Node<string> node(test, nodeType); stringstream testOutput; testOutput << node; string testExpected = "test -> {}"; ASSERT_EQ(testOutput.str(), testExpected); // Complicated test string nodeOne = "a"; string nodeTwo = "b"; string nodeThree = "c"; shared_ptr<Node<string>> node1(new Node<string>(nodeOne, nodeType)); shared_ptr<Node<string>> node2(new Node<string>(nodeTwo, nodeType)); shared_ptr<Node<string>> node3(new Node<string>(nodeThree, nodeType)); vector<pair<string, shared_ptr<Node<string>>>> adjacencyList = {{nodeTwo, node2}, {nodeThree, node3}}; node1->insert(adjacencyList); string expectedOne = "a -> {b c}"; stringstream outputOne; string expectedTwo = "b -> {}"; stringstream outputTwo; string expectedThree = "c -> {}"; stringstream outputThree; outputOne << *node1; outputTwo << *node2; outputThree << *node3; ASSERT_EQ(outputOne.str(), expectedOne); ASSERT_EQ(outputTwo.str(), expectedTwo); ASSERT_EQ(outputThree.str(), expectedThree); // Make sure output was not affected outputOne.str(""); outputTwo.str(""); outputThree.str(""); outputOne << *node1; outputTwo << *node2; outputThree << *node3; ASSERT_EQ(outputOne.str(), expectedOne); ASSERT_EQ(outputTwo.str(), expectedTwo); ASSERT_EQ(outputThree.str(), expectedThree); } TEST(Node, Insert) { string nodeOne = "one"; string nodeTwo = "two"; string nodeThree = "three"; shared_ptr<Node<string>> node1(new Node<string>(nodeOne)); shared_ptr<Node<string>> node2(new Node<string>(nodeTwo)); shared_ptr<Node<string>> node3(new Node<string>(nodeThree)); vector<pair<string, shared_ptr<Node<string>>>> adjacencyList = {{nodeTwo, node2}, {nodeThree, node3}}; node1->insert(adjacencyList); ASSERT_EQ(node1->value, nodeOne); ASSERT_EQ(node2->value, nodeTwo); ASSERT_EQ(node3->value, nodeThree); // Check duplicates are not successful ASSERT_EQ(node1->insert({nodeTwo, node2}), false); auto c2 = node1->connections.find(nodeTwo); if ( c2 == node1->connections.end() ) { ASSERT_EQ(true, false); } else { ASSERT_EQ(c2->first, nodeTwo); } auto c3 = node1->connections.find(nodeThree); if ( c3 == node1->connections.end() ) { ASSERT_EQ(true, false); } else { ASSERT_EQ(c3->first, nodeThree); } } TEST(Node, Templating) { int intValue = 5; Node<int> nodeInt(intValue); ASSERT_EQ(nodeInt.value, intValue); string stringValue = "abc"; Node<string> nodeString(stringValue); ASSERT_EQ(nodeString.value, stringValue); double doubleValue = 3.14; Node<double> nodeDouble(doubleValue); ASSERT_EQ(nodeDouble.value, doubleValue); }
25.395349
106
0.654762
f23084bf6073bb48b042bc99e01b044d35f4d297
600
cpp
C++
Tau/src/core/Midi/MidiEvent.cpp
cymheart/tau
1881046c7e362451e8d4f5d4b885e9011dade319
[ "MIT" ]
7
2021-10-05T07:07:45.000Z
2022-03-01T07:28:34.000Z
Tau/src/core/Midi/MidiEvent.cpp
cymheart/tau
1881046c7e362451e8d4f5d4b885e9011dade319
[ "MIT" ]
1
2021-09-21T07:25:53.000Z
2021-10-02T02:02:10.000Z
Tau/src/core/Midi/MidiEvent.cpp
cymheart/ventrue
57219117a40077ffdde76c7183ea744c0ac2a08f
[ "MIT" ]
1
2022-02-24T21:24:27.000Z
2022-02-24T21:24:27.000Z
#include"MidiEvent.h" namespace tau { SysexEvent::~SysexEvent() { free(data); } void SysexEvent::CreateData(byte* d, size_t len) { if (len <= 0) return; try { data = (byte*)malloc(len); if (data != nullptr) memcpy(data, d, len); this->size = len; } catch (exception) { } } UnknownEvent::~UnknownEvent() { free(data); } void UnknownEvent::CreateData(byte* d, size_t len) { if (len <= 0) return; try { data = (byte*)malloc(len); if (data != nullptr) memcpy(data, d, len); this->size = len; } catch (exception) { } } }
12
51
0.558333
f23107e929ed9d288e7d9d15b2b4f334ffea79a3
3,679
cpp
C++
src/main.cpp
fixstars/cRTOS-loader
d3da5738d2511b497a56d320eafe1f3dc628347b
[ "Apache-2.0" ]
null
null
null
src/main.cpp
fixstars/cRTOS-loader
d3da5738d2511b497a56d320eafe1f3dc628347b
[ "Apache-2.0" ]
null
null
null
src/main.cpp
fixstars/cRTOS-loader
d3da5738d2511b497a56d320eafe1f3dc628347b
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2020 Yang, Chung-Fan @ Fixstars corporation * <chungfan.yang@fixstars.com> * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> #include <iostream> #include <vector> #include <stdexcept> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <signal.h> #include "MMAP.hpp" #include "IO.hpp" #include "Proxy.hpp" #include "verbose.hpp" #define __VERBOSE verbose static std::string get_filename(const std::string& s) { char sep = '/'; size_t i = s.rfind(sep, s.length()); if (i != std::string::npos) { return(s.substr(i + 1, s.length() - i)); } return(""); } std::string readenv(std::string in, std::string def) { if (std::getenv(in.c_str()) != NULL) { return std::string(std::getenv(in.c_str())); } else { return def; } return std::string("NULL"); } void print_usage() { std::cout << "Usage: loader <optional env> <elf file> ..." << std::endl; std::cout << "Environment variable APPMEM must be set to corresponding uio device" << std::endl; } int main(int argc, char *argv[], char *envp[]) { bool verbose = (readenv("VERBOSE", "0") == "1"); bool magic = (readenv("MAGIC", "0") == "1"); std::vector<std::string> llargv; std::vector<std::string> llenvv; int i; /* Early declaration for additional arguments or environs */ for (i = 1; i < argc; i++) { auto curr = std::string(argv[i]); if (curr.find('=') != std::string::npos) { // Take a string with '=' as env llenvv.push_back(curr); } else { break; } } /* Nothing left? */ if ( argc - i < 1 ) { print_usage(); exit(1); } /* Construct the argv and envv list */ std::string elf_filename(argv[i++]); llargv.push_back(elf_filename); for ( ; i < argc; i++) { llargv.push_back(std::string(argv[i])); } for (i = 0; envp[i]; i++) { llenvv.push_back(std::string(envp[i])); } /* Create the TCP/IP and Shadow channel * Test the connection and spawn the Proxy */ std::string shadow = readenv("SHADOWPROC", "/dev/shadow-process0"); auto io = IO("172.16.0.2", 42, verbose); VERBOSE("Testing Communication..."); io.ping(); auto pxy = Proxy(io, shadow, verbose); /* Reserve the Lower 1GB of the memory, used by application * to prevent libc and kernel being funky */ if (!mmap((void*)0x0, 0x40000000, PROT_NONE, MAP_SHARED, 0, 0)) { throw std::runtime_error("Unable to reserve the low memory space!"); } /* Reserve the Upper portion of the memory, used by Nuttx kernel * to prevent libc and kernel being funky */ if (!mmap((void*)KERNELMEM_VIRT_START, KERNELMEM_SIZE, PROT_NONE, MAP_SHARED, 0, 0)) { throw std::runtime_error("Unable to reserve the low memory space!"); } pxy.rexec(elf_filename, llargv, llenvv); return 0; }
25.908451
100
0.608046
f239b20b515adeda1a89ac106b609cd22e0fef40
2,474
cpp
C++
app/src/main/cpp/Feature_Extraction/RSMelFilterBank.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
1
2019-04-18T06:33:09.000Z
2019-04-18T06:33:09.000Z
app/src/main/cpp/Feature_Extraction/RSMelFilterBank.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/Feature_Extraction/RSMelFilterBank.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
null
null
null
/* * Class providing interface to renderscript implementation of mel bank filters. * * Created by Petr Flajsingr on 15/12/2017. */ #include <RSMelFilterBank.h> #include <constants.h> SpeechRecognition::Feature_Extraction::RSMelFilterBank::RSMelFilterBank(const char* cacheDir) { this->renderScriptObject = new RS(); this->renderScriptObject->init(cacheDir); this->melRSinstance = new ScriptC_RSmelfilterbank(this->renderScriptObject); this->prepareAllocations(); } void SpeechRecognition::Feature_Extraction::RSMelFilterBank::prepareAllocations() { Element::Builder* elBuilder = new Element::Builder(this->renderScriptObject); elBuilder->add(Element::F32(this->renderScriptObject), "", FFT_FRAME_LENGTH); this->fftFrameAllocation = Allocation::createTyped(this->renderScriptObject, Type::create(this->renderScriptObject, elBuilder->create(), 1, 0, 0)); this->melIterationAllocation = Allocation::createSized(this->renderScriptObject, Element::U32(this->renderScriptObject), MEL_BANK_FRAME_LENGTH); uint32_t iter[MEL_BANK_FRAME_LENGTH]; for(uint32_t i = 0; i < MEL_BANK_FRAME_LENGTH; ++i) iter[i] = i; melIterationAllocation->copy1DFrom(iter); this->melBankAllocation = Allocation::createSized(this->renderScriptObject, Element::F32(this->renderScriptObject), MEL_BANK_FRAME_LENGTH); } float *SpeechRecognition::Feature_Extraction::RSMelFilterBank::calculateMelBank(kiss_fft_cpx *fftData) { fftFrameAllocation->copy1DFrom(fftData); this->melRSinstance->set_fftFrame(fftFrameAllocation); this->melRSinstance->forEach_melBank(melIterationAllocation, melBankAllocation); renderScriptObject->finish(); float* returnMelValues = new float[MEL_BANK_FRAME_LENGTH]; this->melBankAllocation->copy1DTo(returnMelValues); return returnMelValues; } void SpeechRecognition::Feature_Extraction::RSMelFilterBank::normalise(float *data) { for(int i = 0; i < MEL_BANK_FRAME_LENGTH; i++){ meanForNormalisation[i] = (meanForNormalisation[i] * elementCount + data[i]) / (elementCount + 1); data[i] = data[i] - meanForNormalisation[i]; } elementCount++; }
38.65625
134
0.657639
f23a61df028c4bc3fb7cfed62a551939ce5ec547
634
cpp
C++
Estrutura de Dados/Sorts/SelectionSort/Source.cpp
boveloco/Puc
cbc3308fac104098b030dadebdd036fe288bbe0c
[ "MIT" ]
null
null
null
Estrutura de Dados/Sorts/SelectionSort/Source.cpp
boveloco/Puc
cbc3308fac104098b030dadebdd036fe288bbe0c
[ "MIT" ]
null
null
null
Estrutura de Dados/Sorts/SelectionSort/Source.cpp
boveloco/Puc
cbc3308fac104098b030dadebdd036fe288bbe0c
[ "MIT" ]
null
null
null
#pragma once #include "Array.h" #include "SelectionSort.h" #include "Inimigos.h" #include <iostream> int compararEnergiaInimigos(Inimigos a, Inimigos b); int main(){ Array<Inimigos> numbs(5); numbs[0].energia = 13; numbs[1].energia = 30; numbs[2].energia = 20; numbs[3].energia = 10; numbs[4].energia = 5; selectionSort<Inimigos>(numbs, compararEnergiaInimigos); for (int i = 0; i < numbs.Size(); i++){ std::cout << "Numb: " << i << " " << numbs[i].energia << std::endl; } system("PAUSE"); return 1; } int compararEnergiaInimigos(Inimigos a, Inimigos b){ if (a.energia > b.energia) return 1; else return 0; }
19.212121
69
0.657729
f2413268101c11fe61c3d43e27f20111c77f31f4
5,553
cpp
C++
04_Sample/TowerDefence/Source/Tower.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
04_Sample/TowerDefence/Source/Tower.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
04_Sample/TowerDefence/Source/Tower.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* -------------------------------------------------------------------------- * * File Tower.cpp * Description * * Ported By Young-Hwan Mun * Contact xmsoft77@gmail.com * * Created By Kirill Muzykov on 8/22/13. * * -------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft. All rights reserved. * * -------------------------------------------------------------------------- * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- */ #include "Precompiled.h" #include "Tower.h" #include "Enemy.h" #include "GameLayer.h" Tower* Tower::create ( const KDchar* szFileName ) { Tower* pRet = new Tower ( ); if ( pRet && pRet->initWithFile ( szFileName ) ) { pRet->autorelease ( ); } else { CC_SAFE_DELETE ( pRet ); } return pRet; } KDbool Tower::initWithTexture ( CCTexture2D* pTexture, const CCRect& tRect, KDbool bRotated ) { if ( !CCSprite::initWithTexture ( pTexture, tRect, bRotated ) ) { return KD_FALSE; } m_fAttackRange = 70; m_nDamage = 10; m_fFireRate = 1.0f; m_pTheGame = KD_NULL; m_pChosenEnemy = KD_NULL; this->scheduleUpdate ( ); return KD_TRUE; } KDvoid Tower::draw ( KDvoid ) { // Uncomment to draw attack range circle. For debug purpose only. CCPoint tPos = CCNode::convertToNodeSpace ( this->getPosition ( ) ); ccDrawColor4B ( 128, 0, 0, 128 ); ccDrawCircle ( tPos, m_fAttackRange, KD_DEG2RAD ( -90 ), 30, KD_TRUE ); CCSprite::draw ( ); } KDvoid Tower::update ( KDfloat fDelta ) { CCAssert ( m_pTheGame != NULL, "You should set the game for Tower" ); if ( m_pChosenEnemy ) { // Finding normalized vector enemy -> tower to calculate angle we should turn tower, CCPoint tEnemyPos = m_pChosenEnemy->getPosition ( ); CCPoint tMyPos = this->getPosition ( ); CCPoint tNormalized = ccpNormalize ( ccpSub ( tEnemyPos, tMyPos ) ); // Turning tower to face the enemy. KDfloat fAngle = CC_RADIANS_TO_DEGREES ( kdAtan2f ( tNormalized.y, -tNormalized.x ) ) + 90; this->setRotation ( fAngle ); // Checking if enemy is still in attack range. if ( !m_pTheGame->checkCirclesCollide ( this->getPosition ( ), m_fAttackRange, m_pChosenEnemy->getPosition ( ), 1.0f ) ) { this->lostSightOfEnemy ( ); } } else { // Currently we're not attaching anyone. Let's look if there are any enemies in our attack range. CCObject* pObject; CCARRAY_FOREACH ( &m_pTheGame->getEnemies ( ), pObject ) { Enemy* pEnemy = (Enemy*) pObject; if ( m_pTheGame->checkCirclesCollide ( this->getPosition ( ), m_fAttackRange, pEnemy->getPosition ( ), 1.0f ) ) { // Found enemy in range. Attacking. this->chosenEnemyForAttack ( pEnemy ); break; } } } } KDvoid Tower::chosenEnemyForAttack ( Enemy* pEnemy ) { m_pChosenEnemy = pEnemy; this->attackEnemy ( ); pEnemy->getAttacked ( this ); } KDvoid Tower::attackEnemy ( KDvoid ) { this->schedule ( schedule_selector ( Tower::shootWeapon ), m_fFireRate ); } KDvoid Tower::shootWeapon ( KDfloat fDelta ) { CCAssert ( m_pTheGame != KD_NULL, "You should set the game for Tower" ); CCSprite* pBullet = CCSprite::create ( "bullet.png" ); pBullet->setPosition ( this->getPosition ( ) ); m_pTheGame->addChild ( pBullet ); // Bullet actions: Move from turret to enemy, then make some damage to enemy, and finally remove bullet sprite. pBullet->runAction ( CCSequence::create ( CCMoveTo::create ( 0.1f, m_pChosenEnemy->getPosition ( ) ), CCCallFunc::create ( this, callfunc_selector ( Tower::damageEnemy ) ), CCCallFuncN::create ( this, callfuncN_selector ( Tower::removeBullet ) ), KD_NULL ) ); } KDvoid Tower::damageEnemy ( KDvoid ) { if ( m_pChosenEnemy ) { m_pChosenEnemy->getDamaged ( m_nDamage ); } } KDvoid Tower::removeBullet ( CCNode* pBullet ) { pBullet->removeFromParentAndCleanup ( KD_TRUE ); } KDvoid Tower::lostSightOfEnemy ( KDvoid ) { if ( m_pChosenEnemy ) { m_pChosenEnemy->gotLostSight ( this ); m_pChosenEnemy = KD_NULL; } this->unschedule ( schedule_selector ( Tower::shootWeapon ) ); } KDvoid Tower::setTheGame ( GameLayer* pGame ) { m_pTheGame = pGame; } KDvoid Tower::targetKilled ( KDvoid ) { m_pChosenEnemy = KD_NULL; this->unschedule ( schedule_selector ( Tower::shootWeapon ) ); }
29.073298
128
0.591572
f2460ca1daec1f6e64ac04dc64574fc70288c57d
2,121
hpp
C++
include/open-bo-api-crc64.hpp
sokoliko/open-bo-api
ddcad19163532543ad13a0398f0b0119e55d4c3d
[ "MIT" ]
6
2020-02-09T06:40:03.000Z
2021-09-08T09:38:19.000Z
include/open-bo-api-crc64.hpp
sokoliko/open-bo-api
ddcad19163532543ad13a0398f0b0119e55d4c3d
[ "MIT" ]
3
2020-02-28T11:30:43.000Z
2020-06-05T12:50:33.000Z
include/open-bo-api-crc64.hpp
sokoliko/open-bo-api
ddcad19163532543ad13a0398f0b0119e55d4c3d
[ "MIT" ]
7
2020-03-24T22:31:25.000Z
2021-11-24T17:13:56.000Z
/* * open-bo-api - C++ API for working with binary options brokers * * Copyright (c) 2020 Elektro Yar. Email: git.electroyar@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef OPEN_BO_API_CRC64_HPP_INCLUDED #define OPEN_BO_API_CRC64_HPP_INCLUDED namespace open_bo_api { class CRC64 { public: inline static const long long poly = 0xC96C5795D7870F42; inline static long long crc64_table[256]; inline static void generate_table(){ for(int i=0; i<256; ++i) { long long crc = i; for(int j=0; j<8; ++j) { if(crc & 1) { crc >>= 1; crc ^= poly; } else { crc >>= 1; } } crc64_table[i] = crc; } } inline static long long calc_crc64(long long crc, const unsigned char* stream, int n) { for(int i=0; i< n; ++i) { unsigned char index = stream[i] ^ crc; long long lookup = crc64_table[index]; crc >>= 8; crc ^= lookup; } return crc; } inline static long long calc_crc64(const std::string str) { return calc_crc64(0, (const unsigned char*)str.c_str(), str.size()); } }; } #endif // CRC64_HPP_INCLUDED
32.630769
89
0.704856
f2465b2f9af69a8637fdd2e79279b20b1fc4ee81
986
cpp
C++
LeetCode/23. Merge k Sorted Lists/Solution.cpp
nik3212/challenges
b127bc66ffa27bfdef87ac402dc080f933dad893
[ "MIT" ]
1
2021-06-15T12:48:47.000Z
2021-06-15T12:48:47.000Z
LeetCode/23. Merge k Sorted Lists/Solution.cpp
nik3212/challenges
b127bc66ffa27bfdef87ac402dc080f933dad893
[ "MIT" ]
null
null
null
LeetCode/23. Merge k Sorted Lists/Solution.cpp
nik3212/challenges
b127bc66ffa27bfdef87ac402dc080f933dad893
[ "MIT" ]
null
null
null
/* 23. Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { std::priority_queue<int, std::vector<int>, std::greater<int>> queue; for (auto& list: lists) { while (list) { queue.push(list->val); list = list->next; } } ListNode* result = new ListNode(0); ListNode* tmp = result; while (!queue.empty()) { int val = queue.top(); queue.pop(); tmp->next = new ListNode(val); tmp = tmp->next; } return result->next; } };
17.927273
98
0.51217
f24a6059fe50be8a4a5f21d303f9a8b110248f99
233
cpp
C++
src/caller/executor/executor.cpp
czhj/caller
1f749bc039e731478a2a2f766445b8a14ac13063
[ "MIT" ]
1
2022-03-09T01:02:25.000Z
2022-03-09T01:02:25.000Z
src/caller/executor/executor.cpp
czhj/caller
1f749bc039e731478a2a2f766445b8a14ac13063
[ "MIT" ]
null
null
null
src/caller/executor/executor.cpp
czhj/caller
1f749bc039e731478a2a2f766445b8a14ac13063
[ "MIT" ]
null
null
null
#include <caller/executor/executor.hpp> CALLER_BEGIN ExecutionContext::ExecutionContext() { } ExecutionContext::~ExecutionContext() { } Executor::Executor() { } Executor::~Executor() { } CALLER_END
8.961538
40
0.643777
f24f3f3faf0695de76ce2b2b4d575af04e5f9c12
70,427
hpp
C++
Evolutionary_Strategy_Vulkan.hpp
Harri-Renney/Survival_of_the_Synthesis-GPU_Accelerated_Frequency_Modulation_Parameter_Matcher
c70f8f2f2961148a7639fad05b3cf0d87f895c0c
[ "MIT" ]
null
null
null
Evolutionary_Strategy_Vulkan.hpp
Harri-Renney/Survival_of_the_Synthesis-GPU_Accelerated_Frequency_Modulation_Parameter_Matcher
c70f8f2f2961148a7639fad05b3cf0d87f895c0c
[ "MIT" ]
null
null
null
Evolutionary_Strategy_Vulkan.hpp
Harri-Renney/Survival_of_the_Synthesis-GPU_Accelerated_Frequency_Modulation_Parameter_Matcher
c70f8f2f2961148a7639fad05b3cf0d87f895c0c
[ "MIT" ]
null
null
null
#ifndef EVOLUTIONARY_STRATEGY_VULKAN_HPP #define EVOLUTIONARY_STRATEGY_VULKAN_HPP #include <math.h> #include <array> #include <random> #include <chrono> #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> //Graphic math types and functions// #include <glm\glm.hpp> #include "Evolutionary_Strategy.hpp" #include "Benchmarker.hpp" #include "Vulkan_Helper.hpp" //#define CL_HPP_TARGET_OPENCL_VERSION 200 //#define CL_HPP_MINIMUM_OPENCL_VERSION 200 #define CL_HPP_TARGET_OPENCL_VERSION 120 #define CL_HPP_MINIMUM_OPENCL_VERSION 120 #include <CL/cl2.hpp> #include <clFFT.h> #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; #endif struct Evolutionary_Strategy_Vulkan_Arguments { //Generic Evolutionary Strategy arguments// Evolutionary_Strategy_Arguments es_args; //Shader workgroup details// uint32_t workgroupX = 32; uint32_t workgroupY = 1; uint32_t workgroupZ = 1; uint32_t workgroupSize = workgroupX * workgroupY * workgroupZ; uint32_t numWorkgroupsPerParent; VkPhysicalDeviceType deviceType; }; struct Specialization_Constants { uint32_t workgroupX = 32; uint32_t workgroupY = 1; uint32_t workgroupZ = 1; uint32_t workgroupSize = 32; uint32_t numDimensions = 4; uint32_t populationCount = 1536; uint32_t numWorkgroupsPerParent = 1; //population->num_parents / cl->work_group_size uint32_t chunkSizeFitness = 1; uint32_t audioWaveFormSize = 1024; uint32_t fftOutSize = 1; uint32_t fftHalfSize = 1; float fftOneOverSize = 1.0; float fftOneOverWindowFactor = 1.0; float mPI = 3.14159265358979323846; float alpha = 1.4f; float oneOverAlpha = 1.f / alpha; float rootTwoOverPi = sqrtf(2.f / (float)mPI); float betaScale = 1.f / numDimensions; //1.f / (float)population->num_dimensions; float beta = sqrtf(betaScale); uint32_t chunksPerWorkgroupSynth = 2; uint32_t chunkSizeSynth = workgroupSize / chunksPerWorkgroupSynth; float OneOverSampleRateTimeTwoPi = 0.00014247573; uint32_t populationSize = 1536 * 4; } specializationData; class Evolutionary_Strategy_Vulkan : public Evolutionary_Strategy { private: //Shader workgroup details// uint32_t globalSize; uint32_t localSize; uint32_t workgroupX; uint32_t workgroupY; uint32_t workgroupZ; uint32_t workgroupSize; uint32_t numWorkgroupsX; uint32_t numWorkgroupsY; uint32_t numWorkgroupsZ; uint32_t chunks; uint32_t chunkSize; uint32_t chunkSizeFitness = 1; //@ToDo - Need this? Or just define in shader/kernel. Only important to GPU implementations so in subclass. float* populationAudioDate; float* populationFFTData; ////////// //Vulkan// //Instance// VkInstance instance_; //Physical Device// VkPhysicalDevice physicalDevice_; VkPhysicalDeviceType deviceType_; //Logical Device// VkDevice logicalDevice_; //Compute Queue// VkQueue computeQueue_; //A queue supporting compute operations. uint32_t queueFamilyIndex_; //Pipeline// //FFT comes inbetween applyWindowPopulation & fitnessPopulation// static const int numPipelines_ = 9; enum computePipelineNames_ { initPopulation = 0, recombinePopulation, mutatePopulation, synthesisePopulation, applyWindowPopulation, VulkanFFT, fitnessPopulation, sortPopulation, rotatePopulation}; std::vector<std::string> shaderNames_; VkPipeline computePipelines_[numPipelines_]; VkPipelineLayout computePipelineLayouts_[numPipelines_]; //Command Buffer// VkCommandPool commandPoolInit_; VkCommandBuffer commandBufferInit_; VkQueryPool queryPoolInit_; VkCommandPool commandPoolESOne_; VkCommandBuffer commandBufferESOne_; VkQueryPool queryPoolESOne_[5]; VkCommandPool commandPoolESTwo_; VkCommandBuffer commandBufferESTwo_; VkQueryPool queryPoolESTwo_[3]; float shaderExecuteTime_[numPipelines_]; VkCommandPool commandPoolFFT_; VkCommandBuffer commandBufferFFT_; //Descriptor// VkDescriptorPool descriptorPool_; VkDescriptorSet descriptorSet_; VkDescriptorSetLayout descriptorSetLayout_; std::vector<VkDescriptorPool> descriptorPools_; std::vector<VkDescriptorSetLayout> descriptorSetLayouts_; std::vector<VkDescriptorSet> descriptorSets_; VkDescriptorPool descriptorPoolFFT_; VkDescriptorSet descriptorSetFFT_; VkDescriptorSetLayout descriptorSetLayoutFFT_; //Constants// static const int numSpecializationConstants_ = 23; void* specializationConstantData_; std::array<VkSpecializationMapEntry, numSpecializationConstants_> specializationConstantEntries_; VkSpecializationInfo specializationConstantInfo_; //Fences// std::vector<VkFence> fences_; //Population Buffers// static const int numBuffers_ = 14; enum storageBufferNames_ { inputPopulationValueBuffer = 0, inputPopulationStepBuffer, inputPopulationFitnessBuffer, outputPopulationValueBuffer, outputPopulationStepBuffer, outputPopulationFitnessBuffer, randomStatesBuffer, paramMinBuffer, paramMaxBuffer, outputAudioBuffer, inputFFTDataBuffer, inputFFTTargetBuffer, rotationIndexBuffer, wavetableBuffer}; std::array<VkBuffer, numBuffers_> storageBuffers_; std::array<VkDeviceMemory, numBuffers_> storageBuffersMemory_; std::array<uint32_t, numBuffers_> storageBufferSizes_; //Staging Buffer// VkQueue bufferQueue; //A queue for supporting memory buffer operations. VkCommandPool commandPoolStaging_; uint32_t stagingBufferSrcSize_; VkBuffer stagingBufferSrc; VkDeviceMemory stagingBufferMemorySrc; void* stagingBufferSrcPointer; uint32_t stagingBufferDstSize_; VkBuffer stagingBufferDst; VkDeviceMemory stagingBufferMemoryDst; void* stagingBufferDstPointer; Benchmarker vkBenchmarker_; uint32_t rotationIndex_; //Validation & Debug Variables// VkDebugReportCallbackEXT debugReportCallback_; std::vector<const char *> enabledValidationLayers; static VKAPI_ATTR VkBool32 VKAPI_CALL debugReportCallbackFn( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) { printf("Debug Report: %s: %s\n", pLayerPrefix, pMessage); return VK_FALSE; } void initConstantsVK() { //Setup specialization constant entries// specializationConstantEntries_[0].constantID = 1; specializationConstantEntries_[0].size = sizeof(specializationData.workgroupX); specializationConstantEntries_[0].offset = 0; specializationConstantEntries_[1].constantID = 2; specializationConstantEntries_[1].size = sizeof(specializationData.workgroupY); specializationConstantEntries_[1].offset = offsetof(Specialization_Constants, workgroupY); specializationConstantEntries_[2].constantID = 3; specializationConstantEntries_[2].size = sizeof(specializationData.workgroupZ); specializationConstantEntries_[2].offset = offsetof(Specialization_Constants, workgroupZ); specializationConstantEntries_[3].constantID = 4; specializationConstantEntries_[3].size = sizeof(specializationData.workgroupSize); specializationConstantEntries_[3].offset = offsetof(Specialization_Constants, workgroupSize); specializationConstantEntries_[4].constantID = 5; specializationConstantEntries_[4].size = sizeof(specializationData.numDimensions); specializationConstantEntries_[4].offset = offsetof(Specialization_Constants, numDimensions); specializationConstantEntries_[5].constantID = 6; specializationConstantEntries_[5].size = sizeof(specializationData.populationCount); specializationConstantEntries_[5].offset = offsetof(Specialization_Constants, populationCount); specializationConstantEntries_[6].constantID = 7; specializationConstantEntries_[6].size = sizeof(specializationData.numWorkgroupsPerParent); specializationConstantEntries_[6].offset = offsetof(Specialization_Constants, numWorkgroupsPerParent); specializationConstantEntries_[7].constantID = 8; specializationConstantEntries_[7].size = sizeof(specializationData.chunkSizeFitness); specializationConstantEntries_[7].offset = offsetof(Specialization_Constants, chunkSizeFitness); specializationConstantEntries_[8].constantID = 9; specializationConstantEntries_[8].size = sizeof(specializationData.audioWaveFormSize); specializationConstantEntries_[8].offset = offsetof(Specialization_Constants, audioWaveFormSize); specializationConstantEntries_[9].constantID = 10; specializationConstantEntries_[9].size = sizeof(specializationData.fftOutSize); specializationConstantEntries_[9].offset = offsetof(Specialization_Constants, fftOutSize); specializationConstantEntries_[10].constantID = 11; specializationConstantEntries_[10].size = sizeof(specializationData.fftHalfSize); specializationConstantEntries_[10].offset = offsetof(Specialization_Constants, fftHalfSize); specializationConstantEntries_[11].constantID = 12; specializationConstantEntries_[11].size = sizeof(specializationData.fftOneOverSize); specializationConstantEntries_[11].offset = offsetof(Specialization_Constants, fftOneOverSize); specializationConstantEntries_[12].constantID = 13; specializationConstantEntries_[12].size = sizeof(specializationData.fftOneOverWindowFactor); specializationConstantEntries_[12].offset = offsetof(Specialization_Constants, fftOneOverWindowFactor); specializationConstantEntries_[13].constantID = 14; specializationConstantEntries_[13].size = sizeof(specializationData.mPI); specializationConstantEntries_[13].offset = offsetof(Specialization_Constants, mPI); specializationConstantEntries_[14].constantID = 15; specializationConstantEntries_[14].size = sizeof(specializationData.alpha); specializationConstantEntries_[14].offset = offsetof(Specialization_Constants, alpha); specializationConstantEntries_[15].constantID = 16; specializationConstantEntries_[15].size = sizeof(specializationData.oneOverAlpha); specializationConstantEntries_[15].offset = offsetof(Specialization_Constants, oneOverAlpha); specializationConstantEntries_[16].constantID = 17; specializationConstantEntries_[16].size = sizeof(specializationData.rootTwoOverPi); specializationConstantEntries_[16].offset = offsetof(Specialization_Constants, rootTwoOverPi); specializationConstantEntries_[17].constantID = 18; specializationConstantEntries_[17].size = sizeof(specializationData.betaScale); specializationConstantEntries_[17].offset = offsetof(Specialization_Constants, betaScale); specializationConstantEntries_[18].constantID = 19; specializationConstantEntries_[18].size = sizeof(specializationData.beta); specializationConstantEntries_[18].offset = offsetof(Specialization_Constants, beta); specializationConstantEntries_[19].constantID = 20; specializationConstantEntries_[19].size = sizeof(specializationData.chunksPerWorkgroupSynth); specializationConstantEntries_[19].offset = offsetof(Specialization_Constants, chunksPerWorkgroupSynth); specializationConstantEntries_[20].constantID = 21; specializationConstantEntries_[20].size = sizeof(specializationData.chunkSizeSynth); specializationConstantEntries_[20].offset = offsetof(Specialization_Constants, chunkSizeSynth); specializationConstantEntries_[21].constantID = 22; specializationConstantEntries_[21].size = sizeof(specializationData.OneOverSampleRateTimeTwoPi); specializationConstantEntries_[21].offset = offsetof(Specialization_Constants, OneOverSampleRateTimeTwoPi); specializationConstantEntries_[22].constantID = 23; specializationConstantEntries_[22].size = sizeof(specializationData.populationSize); specializationConstantEntries_[22].offset = offsetof(Specialization_Constants, populationSize); //Setup specialization constant data// specializationData.workgroupX = workgroupX; specializationData.workgroupY = workgroupY; specializationData.workgroupZ = workgroupZ; specializationData.workgroupSize = workgroupSize; specializationData.numDimensions = population.numDimensions; specializationData.populationCount = population.populationLength; specializationData.numWorkgroupsPerParent = population.numParents / workgroupSize; specializationData.chunkSizeFitness = workgroupSize / 2; specializationData.audioWaveFormSize = objective.audioLength; specializationData.fftOutSize = objective.fftOutSize; specializationData.fftHalfSize = objective.fftHalfSize; specializationData.fftOneOverSize = objective.fftOneOverSize; specializationData.fftOneOverWindowFactor = objective.fftOneOverWindowFactor; specializationData.mPI = mPI; specializationData.alpha = alpha; specializationData.oneOverAlpha = oneOverAlpha; specializationData.rootTwoOverPi = rootTwoOverPi; specializationData.betaScale = betaScale; specializationData.beta = beta; specializationData.chunksPerWorkgroupSynth = 2; specializationData.chunkSizeSynth = workgroupSize / specializationData.chunksPerWorkgroupSynth; specializationData.OneOverSampleRateTimeTwoPi = 0.00014247573; specializationData.populationSize = population.populationLength * population.numDimensions; } //@ToDo - Use local memory buffers correctly// void initBuffersVK() { //Creating each buffer at time// VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[inputPopulationValueBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storageBuffers_[inputPopulationValueBuffer], storageBuffersMemory_[inputPopulationValueBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[inputPopulationStepBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storageBuffers_[inputPopulationStepBuffer], storageBuffersMemory_[inputPopulationStepBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[inputPopulationFitnessBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storageBuffers_[inputPopulationFitnessBuffer], storageBuffersMemory_[inputPopulationFitnessBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[outputPopulationValueBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[outputPopulationValueBuffer], storageBuffersMemory_[outputPopulationValueBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[outputPopulationStepBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[outputPopulationStepBuffer], storageBuffersMemory_[outputPopulationStepBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[outputPopulationFitnessBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[outputPopulationFitnessBuffer], storageBuffersMemory_[outputPopulationFitnessBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[outputAudioBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storageBuffers_[outputAudioBuffer], storageBuffersMemory_[outputAudioBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[randomStatesBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[randomStatesBuffer], storageBuffersMemory_[randomStatesBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[paramMinBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[paramMinBuffer], storageBuffersMemory_[paramMinBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[paramMaxBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[paramMaxBuffer], storageBuffersMemory_[paramMaxBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[inputFFTDataBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[inputFFTDataBuffer], storageBuffersMemory_[inputFFTDataBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[inputFFTTargetBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[inputFFTTargetBuffer], storageBuffersMemory_[inputFFTTargetBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[rotationIndexBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[rotationIndexBuffer], storageBuffersMemory_[rotationIndexBuffer]); VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[wavetableBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storageBuffers_[wavetableBuffer], storageBuffersMemory_[wavetableBuffer]); //Create Staging Buffer// stagingBufferSrcSize_ = storageBufferSizes_[inputFFTDataBuffer]; stagingBufferDstSize_ = storageBufferSizes_[inputFFTDataBuffer]; VKHelper::createBuffer(physicalDevice_, logicalDevice_, stagingBufferSrcSize_, VK_BUFFER_USAGE_TRANSFER_SRC_BIT , VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBufferSrc, stagingBufferMemorySrc); VKHelper::createBuffer(physicalDevice_, logicalDevice_, stagingBufferDstSize_, VK_BUFFER_USAGE_TRANSFER_DST_BIT , VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBufferDst, stagingBufferMemoryDst); } void initRandomStateBuffer() { //Initialize random numbers in CPU buffer// unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator(seed); //std::uniform_int_distribution<int> distribution(0, 2147483647); std::uniform_int_distribution<int> distribution(0, 32767); //std::uniform_real_distribution<float> distribution(0.0, 1.0); glm::uvec2* rand_state = new glm::uvec2[population.populationLength]; for (int i = 0; i < population.populationLength; ++i) { rand_state[i].x = distribution(generator); rand_state[i].y = distribution(generator); } void* data; uint32_t cpySize = population.populationLength * sizeof(glm::uvec2); vkMapMemory(logicalDevice_, storageBuffersMemory_[randomStatesBuffer], 0, cpySize, 0, &data); memcpy(data, rand_state, static_cast<size_t>(cpySize)); vkUnmapMemory(logicalDevice_, storageBuffersMemory_[randomStatesBuffer]); } void createInstance() { std::vector<const char *> enabledExtensions; /* By enabling validation layers, Vulkan will emit warnings if the API is used incorrectly. We shall enable the layer VK_LAYER_LUNARG_standard_validation, which is basically a collection of several useful validation layers. */ if (enableValidationLayers) { //Get all supported layers with vkEnumerateInstanceLayerProperties// uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, NULL); std::vector<VkLayerProperties> layerProperties(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, layerProperties.data()); //Check if VK_LAYER_LUNARG_standard_validation is among supported layers// bool foundLayer = false; if (std::find_if(layerProperties.begin(), layerProperties.end(), [](const VkLayerProperties& m) -> bool { return strcmp(m.layerName, "VK_LAYER_KHRONOS_validation"); }) != layerProperties.end()) foundLayer = true; if (!foundLayer) { throw std::runtime_error("Layer VK_LAYER_KHRONOS_validation not supported\n"); } enabledValidationLayers.push_back("VK_LAYER_KHRONOS_validation"); /* We need to enable an extension named VK_EXT_DEBUG_REPORT_EXTENSION_NAME, in order to be able to print the warnings emitted by the validation layer. Check if the extension is among the supported extensions. */ uint32_t extensionCount; vkEnumerateInstanceExtensionProperties(NULL, &extensionCount, NULL); std::vector<VkExtensionProperties> extensionProperties(extensionCount); vkEnumerateInstanceExtensionProperties(NULL, &extensionCount, extensionProperties.data()); bool foundExtension = false; if (std::find_if(extensionProperties.begin(), extensionProperties.end(), [](const VkExtensionProperties& m) -> bool { return strcmp(m.extensionName, VK_EXT_DEBUG_REPORT_EXTENSION_NAME); }) != extensionProperties.end()) foundExtension = true; if (!foundExtension) { throw std::runtime_error("Extension VK_EXT_DEBUG_REPORT_EXTENSION_NAME not supported\n"); } enabledExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); } //Create Vulkan instance// VkApplicationInfo applicationInfo = {}; applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; applicationInfo.pApplicationName = "Hello world app"; applicationInfo.applicationVersion = 0; applicationInfo.pEngineName = "VkSoundMatch"; applicationInfo.engineVersion = 0; applicationInfo.apiVersion = VK_API_VERSION_1_2; VkInstanceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.flags = 0; createInfo.pApplicationInfo = &applicationInfo; // Give our desired layers and extensions to vulkan. createInfo.enabledLayerCount = enabledValidationLayers.size(); createInfo.ppEnabledLayerNames = enabledValidationLayers.data(); createInfo.enabledExtensionCount = enabledExtensions.size(); createInfo.ppEnabledExtensionNames = enabledExtensions.data(); /* Actually create the instance. Having created the instance, we can actually start using vulkan. */ VK_CHECK_RESULT(vkCreateInstance(&createInfo, NULL, &instance_)); /* Register a callback function for the extension VK_EXT_DEBUG_REPORT_EXTENSION_NAME, so that warnings emitted from the validation layer are actually printed. */ if (enableValidationLayers) { VkDebugReportCallbackCreateInfoEXT createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; createInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; createInfo.pfnCallback = &debugReportCallbackFn; // We have to explicitly load this function. auto vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance_, "vkCreateDebugReportCallbackEXT"); if (vkCreateDebugReportCallbackEXT == nullptr) { throw std::runtime_error("Could not load vkCreateDebugReportCallbackEXT"); } // Create and register callback. VK_CHECK_RESULT(vkCreateDebugReportCallbackEXT(instance_, &createInfo, NULL, &debugReportCallback_)); } } //@ToDo - Correctly find the AMD GPU, not use intel one.// void findPhysicalDevice() { //Collect physical devices available to VUlkan// uint32_t deviceCount; vkEnumeratePhysicalDevices(instance_, &deviceCount, NULL); if (deviceCount == 0) { throw std::runtime_error("could not find a device with vulkan support"); } std::vector<VkPhysicalDevice> devices(deviceCount); vkEnumeratePhysicalDevices(instance_, &deviceCount, devices.data()); //Iterate through and choose appropriate device// for (VkPhysicalDevice device : devices) { if (true) { // As above stated, we do no feature checks, so just accept. VkPhysicalDeviceProperties deviceProperties; VkPhysicalDeviceFeatures deviceFeatures; vkGetPhysicalDeviceProperties(device, &deviceProperties); vkGetPhysicalDeviceFeatures(device, &deviceFeatures); printf("Device found: %s\n", deviceProperties.deviceName); printf("Device maxDescriptorSetStorageBuffers: %d\n", deviceProperties.limits.maxDescriptorSetStorageBuffers); if(deviceProperties.deviceType == deviceType_) { physicalDevice_ = device; break; } } } } // Returns the index of a queue family that supports compute operations. uint32_t getComputeQueueFamilyIndex() { uint32_t queueFamilyCount; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice_, &queueFamilyCount, NULL); // Retrieve all queue families. std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice_, &queueFamilyCount, queueFamilies.data()); // Now find a family that supports compute. uint32_t i = 0; for (; i < queueFamilies.size(); ++i) { VkQueueFamilyProperties props = queueFamilies[i]; if (props.queueCount > 0 && (props.queueFlags & VK_QUEUE_COMPUTE_BIT)) { // found a queue with compute. We're done! break; } } if (i == queueFamilies.size()) { throw std::runtime_error("could not find a queue family that supports operations"); } return i; } void createDevice() { /* We create the logical device in this function. */ /* When creating the device, we also specify what queues it has. */ VkDeviceQueueCreateInfo queueCreateInfo = {}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueFamilyIndex_ = getComputeQueueFamilyIndex(); // find queue family with compute capability. queueCreateInfo.queueFamilyIndex = queueFamilyIndex_; queueCreateInfo.queueCount = 1; // create one queue in this family. We don't need more. float queuePriorities = 1.0; // we only have one queue, so this is not that imporant. queueCreateInfo.pQueuePriorities = &queuePriorities; /* Now we create the logical device. The logical device allows us to interact with the physical device. */ VkDeviceCreateInfo deviceCreateInfo = {}; // Specify any desired device features here. We do not need any for this application, though. VkPhysicalDeviceFeatures deviceFeatures = {}; deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceCreateInfo.enabledLayerCount = enabledValidationLayers.size(); // need to specify validation layers here as well. deviceCreateInfo.ppEnabledLayerNames = enabledValidationLayers.data(); deviceCreateInfo.queueCreateInfoCount = 1; deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo; // when creating the logical device, we also specify what queues it has. deviceCreateInfo.pEnabledFeatures = &deviceFeatures; VK_CHECK_RESULT(vkCreateDevice(physicalDevice_, &deviceCreateInfo, NULL, &logicalDevice_)); // create logical device. // Get a handle to the only member of the queue family. vkGetDeviceQueue(logicalDevice_, queueFamilyIndex_, 0, &computeQueue_); } // find memory type with desired properties. uint32_t findMemoryType(uint32_t memoryTypeBits, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memoryProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice_, &memoryProperties); /* How does this search work? See the documentation of VkPhysicalDeviceMemoryProperties for a detailed description. */ for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; ++i) { if ((memoryTypeBits & (1 << i)) && ((memoryProperties.memoryTypes[i].propertyFlags & properties) == properties)) return i; } return -1; } void createDescriptorSetLayout() { /* Here we specify a descriptor set layout. This allows us to bind our descriptors to resources in the shader. */ /* Here we specify a binding of type VK_DESCRIPTOR_TYPE_STORAGE_BUFFER to the binding point 0. This binds to layout(std140, binding = 0) buffer buf in the compute shader. */ VkDescriptorSetLayoutBinding populationValueLayoutBinding = {}; populationValueLayoutBinding.binding = 0; // binding = 0 populationValueLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; populationValueLayoutBinding.descriptorCount = 1; populationValueLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding populationStepLayoutBinding = {}; populationStepLayoutBinding.binding = 1; // binding = 0 populationStepLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; populationStepLayoutBinding.descriptorCount = 1; populationStepLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding populationFitnessLayoutBinding = {}; populationFitnessLayoutBinding.binding = 2; // binding = 0 populationFitnessLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; populationFitnessLayoutBinding.descriptorCount = 1; populationFitnessLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding populationValueTempLayoutBinding = {}; populationValueTempLayoutBinding.binding = 3; // binding = 0 populationValueTempLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; populationValueTempLayoutBinding.descriptorCount = 1; populationValueTempLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding populationStepTempLayoutBinding = {}; populationStepTempLayoutBinding.binding = 4; // binding = 0 populationStepTempLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; populationStepTempLayoutBinding.descriptorCount = 1; populationStepTempLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding populationFitnessTempLayoutBinding = {}; populationFitnessTempLayoutBinding.binding = 5; // binding = 0 populationFitnessTempLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; populationFitnessTempLayoutBinding.descriptorCount = 1; populationFitnessTempLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding randStateLayoutBinding = {}; randStateLayoutBinding.binding = 6; // binding = 0 randStateLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; randStateLayoutBinding.descriptorCount = 1; randStateLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding paramMinLayoutBinding = {}; paramMinLayoutBinding.binding = 7; // binding = 0 paramMinLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; paramMinLayoutBinding.descriptorCount = 1; paramMinLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding paramMaxLayoutBinding = {}; paramMaxLayoutBinding.binding = 8; // binding = 0 paramMaxLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; paramMaxLayoutBinding.descriptorCount = 1; paramMaxLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding audioWaveLayoutBinding = {}; audioWaveLayoutBinding.binding = 9; // binding = 0 audioWaveLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; audioWaveLayoutBinding.descriptorCount = 1; audioWaveLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding FFTOutputLayoutBinding = {}; FFTOutputLayoutBinding.binding = 10; // binding = 0 FFTOutputLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; FFTOutputLayoutBinding.descriptorCount = 1; FFTOutputLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding FFTTargetLayoutBinding = {}; FFTTargetLayoutBinding.binding = 11; // binding = 0 FFTTargetLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; FFTTargetLayoutBinding.descriptorCount = 1; FFTTargetLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding rotationIndexLayoutBinding = {}; rotationIndexLayoutBinding.binding = 12; // binding = 0 rotationIndexLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; rotationIndexLayoutBinding.descriptorCount = 1; rotationIndexLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding wavetableLayoutBinding = {}; wavetableLayoutBinding.binding = 13; // binding = 0 wavetableLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wavetableLayoutBinding.descriptorCount = 1; wavetableLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; //Layout create information from binding layouts// std::array<VkDescriptorSetLayoutBinding, numBuffers_> bindings = { populationValueLayoutBinding, populationStepLayoutBinding, populationFitnessLayoutBinding, populationValueTempLayoutBinding, populationStepTempLayoutBinding, populationFitnessTempLayoutBinding, randStateLayoutBinding, paramMinLayoutBinding, paramMaxLayoutBinding, audioWaveLayoutBinding, FFTOutputLayoutBinding, FFTTargetLayoutBinding, rotationIndexLayoutBinding, wavetableLayoutBinding }; VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = {}; descriptorSetLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptorSetLayoutCreateInfo.bindingCount = static_cast<uint32_t>(bindings.size()); // only a single binding in this descriptor set layout. descriptorSetLayoutCreateInfo.pBindings = bindings.data(); //Create the descriptor set layout// VK_CHECK_RESULT(vkCreateDescriptorSetLayout(logicalDevice_, &descriptorSetLayoutCreateInfo, NULL, &descriptorSetLayout_)); } void createDescriptorSet() { /* So we will allocate a descriptor set here. But we need to first create a descriptor pool to do that. */ /* Our descriptor pool can only allocate a single storage buffer. */ std::array<VkDescriptorPoolSize, numBuffers_> poolSizes = {}; poolSizes[0].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[0].descriptorCount = 1; poolSizes[1].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[1].descriptorCount = 1; poolSizes[2].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[2].descriptorCount = 1; poolSizes[3].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[3].descriptorCount = 1; poolSizes[4].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[4].descriptorCount = 1; poolSizes[5].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[5].descriptorCount = 1; poolSizes[6].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[6].descriptorCount = 1; poolSizes[7].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[7].descriptorCount = 1; poolSizes[8].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[8].descriptorCount = 1; poolSizes[9].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[9].descriptorCount = 1; poolSizes[10].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[10].descriptorCount = 1; poolSizes[11].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[11].descriptorCount = 1; poolSizes[12].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[12].descriptorCount = 1; poolSizes[13].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; poolSizes[13].descriptorCount = 1; VkDescriptorPoolCreateInfo descriptorPoolCreateInfo = {}; descriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; descriptorPoolCreateInfo.maxSets = 1; // we only need to allocate one descriptor set from the pool. descriptorPoolCreateInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size()); descriptorPoolCreateInfo.pPoolSizes = poolSizes.data(); // create descriptor pool. VK_CHECK_RESULT(vkCreateDescriptorPool(logicalDevice_, &descriptorPoolCreateInfo, NULL, &descriptorPool_)); /* With the pool allocated, we can now allocate the descriptor set. */ VkDescriptorSetAllocateInfo descriptorSetAllocateInfo = {}; descriptorSetAllocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; descriptorSetAllocateInfo.descriptorPool = descriptorPool_; // pool to allocate from. descriptorSetAllocateInfo.descriptorSetCount = 1; // allocate a single descriptor set. descriptorSetAllocateInfo.pSetLayouts = &descriptorSetLayout_; // allocate descriptor set. VK_CHECK_RESULT(vkAllocateDescriptorSets(logicalDevice_, &descriptorSetAllocateInfo, &descriptorSet_)); /* Next, we need to connect our actual storage buffer with the descrptor. We use vkUpdateDescriptorSets() to update the descriptor set. */ std::array<VkDescriptorBufferInfo, numBuffers_> descriptorBuffersInfo; std::array<VkWriteDescriptorSet, numBuffers_> descriptorWrites = {}; for (uint32_t i = 0; i != numBuffers_; ++i) { descriptorBuffersInfo[i].buffer = storageBuffers_[i]; descriptorBuffersInfo[i].offset = 0; descriptorBuffersInfo[i].range = storageBufferSizes_[i]; descriptorWrites[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[i].dstSet = descriptorSet_; descriptorWrites[i].dstBinding = i; descriptorWrites[i].dstArrayElement = 0; descriptorWrites[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; descriptorWrites[i].descriptorCount = 1; //@ToDo - May need higher count. descriptorWrites[i].pBufferInfo = &(descriptorBuffersInfo[i]); } // perform the update of the descriptor set. vkUpdateDescriptorSets(logicalDevice_, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, NULL); } void createComputePipelines() //create pipelines { VkSpecializationInfo specializationInfo{}; specializationInfo.dataSize = sizeof(specializationData); specializationInfo.mapEntryCount = static_cast<uint32_t>(specializationConstantEntries_.size()); specializationInfo.pMapEntries = specializationConstantEntries_.data(); specializationInfo.pData = &specializationData; VkPushConstantRange pushConstantRange[1] = {}; pushConstantRange[0].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; pushConstantRange[0].offset = 0; pushConstantRange[0].size = sizeof(uint32_t); for (uint8_t i = 0; i != numPipelines_; ++i) { /* Now let us actually create the compute pipeline. A compute pipeline is very simple compared to a graphics pipeline. It only consists of a single stage with a compute shader. So first we specify the compute shader stage, and it's entry point(main). */ uint32_t filelength; std::string fileName = "shaders/" + shaderNames_[i]; std::vector<char> code = VKHelper::readFile(fileName); VkShaderModule shaderModule = VKHelper::createShaderModule(logicalDevice_, code); VkPipelineShaderStageCreateInfo shaderStageCreateInfo = {}; shaderStageCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; shaderStageCreateInfo.stage = VK_SHADER_STAGE_COMPUTE_BIT; shaderStageCreateInfo.module = shaderModule; shaderStageCreateInfo.pName = "main"; shaderStageCreateInfo.pSpecializationInfo = &specializationInfo; /* The pipeline layout allows the pipeline to access descriptor sets. So we just specify the descriptor set layout we created earlier. All pipelines are going to access the same descriptors to start with. */ VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = {}; pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutCreateInfo.setLayoutCount = 1; pipelineLayoutCreateInfo.pSetLayouts = &descriptorSetLayout_; pipelineLayoutCreateInfo.pushConstantRangeCount = 1; pipelineLayoutCreateInfo.pPushConstantRanges = pushConstantRange; VK_CHECK_RESULT(vkCreatePipelineLayout(logicalDevice_, &pipelineLayoutCreateInfo, NULL, &(computePipelineLayouts_[i]))); VkComputePipelineCreateInfo pipelineCreateInfo = {}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; pipelineCreateInfo.stage = shaderStageCreateInfo; pipelineCreateInfo.layout = (computePipelineLayouts_[i]); VK_CHECK_RESULT(vkCreateComputePipelines(logicalDevice_, VK_NULL_HANDLE, 1, &pipelineCreateInfo, NULL, &(computePipelines_[i]))); vkDestroyShaderModule(logicalDevice_, shaderModule, NULL); std::cout << "Created shader: " << fileName.c_str() << std::endl; } } void createCopyCommandPool() { VkCommandPoolCreateInfo commandPoolCreateInfo = {}; commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; commandPoolCreateInfo.flags = 0; // the queue family of this command pool. All command buffers allocated from this command pool, // must be submitted to queues of this family ONLY. commandPoolCreateInfo.queueFamilyIndex = queueFamilyIndex_; VK_CHECK_RESULT(vkCreateCommandPool(logicalDevice_, &commandPoolCreateInfo, NULL, &commandPoolStaging_)); } void calculateAudioFFT() { //int counter = 0; //for (uint32_t i = 0; i != population.populationSize * objective.audioLength; i += objective.audioLength) //{ // objective.calculateFFTSpecial(&populationAudioDate[i], &populationFFTData[counter]); // counter += objective.fftHalfSize; //} executeOpenCLFFT(); } //@ToDo - Right now pick platform. Can extend to pick best available. int errorStatus_ = 0; cl_uint num_platforms, num_devices; cl::Platform platform_; cl::Context context_; cl::Device device_; cl::CommandQueue commandQueue_; cl::Program kernelProgram_; std::string kernelSourcePath_; cl::NDRange globalws_; cl::NDRange localws_; clfftPlanHandle planHandle; void initContextCL(uint8_t aPlatform, uint8_t aDevice) { //Discover platforms// std::vector <cl::Platform> platforms; cl::Platform::get(&platforms); //Create contex properties for first platform// cl_context_properties contextProperties[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[aPlatform])(), 0 }; //Need to specify platform 3 for dedicated graphics - Harri Laptop. //Create context context using platform for GPU device// context_ = cl::Context(CL_DEVICE_TYPE_ALL, contextProperties); //Get device list from context// std::vector<cl::Device> devices = context_.getInfo<CL_CONTEXT_DEVICES>(); //Create command queue for first device - Profiling enabled// commandQueue_ = cl::CommandQueue(context_, devices[aDevice], CL_QUEUE_PROFILING_ENABLE, &errorStatus_); //Need to specify device 1[0] of platform 3[2] for dedicated graphics - Harri Laptop. if (errorStatus_) std::cout << "ERROR creating command queue for device. Status code: " << errorStatus_ << std::endl; globalws_ = cl::NDRange(globalSize); localws_ = cl::NDRange(workgroupX, workgroupY, workgroupZ); /* FFT library realted declarations */ clfftDim dim = CLFFT_1D; size_t clLengths[1] = { objective.audioLength }; /* Setup clFFT. */ clfftSetupData fftSetup; errorStatus_ = clfftInitSetupData(&fftSetup); errorStatus_ = clfftSetup(&fftSetup); /* Create a default plan for a complex FFT. */ errorStatus_ = clfftCreateDefaultPlan(&planHandle, context_(), dim, clLengths); /* Set plan parameters. */ errorStatus_ = clfftSetPlanPrecision(planHandle, CLFFT_SINGLE); errorStatus_ = clfftSetLayout(planHandle, CLFFT_REAL, CLFFT_HERMITIAN_INTERLEAVED); errorStatus_ = clfftSetResultLocation(planHandle, CLFFT_OUTOFPLACE); errorStatus_ = clfftSetPlanBatchSize(planHandle, (size_t)population.populationLength); size_t in_strides[1] = { 1 }; size_t out_strides[1] = { 1 }; size_t in_dist = (size_t)objective.audioLength; size_t out_dist = (size_t)objective.audioLength / 2 + 4; objective.fftOutSize = out_dist * 2; objective.fftHalfSize = 1 << (objective.audioLengthLog2 - 1); storageBufferSizes_[inputFFTDataBuffer] = population.populationLength * objective.fftOutSize * sizeof(float); storageBufferSizes_[inputFFTTargetBuffer] = objective.fftHalfSize * sizeof(float); //objective.fftSizeHalf clfftSetPlanInStride(planHandle, dim, in_strides); clfftSetPlanOutStride(planHandle, dim, out_strides); clfftSetPlanDistance(planHandle, in_dist, out_dist); /* Bake the plan. */ errorStatus_ = clfftBakePlan(planHandle, 1, &commandQueue_(), NULL, NULL); } cl::Buffer inputBuffer; cl::Buffer outputBuffer; void initBuffersCL() { inputBuffer = cl::Buffer(context_, CL_MEM_READ_WRITE, storageBufferSizes_[outputAudioBuffer]); outputBuffer = cl::Buffer(context_, CL_MEM_READ_WRITE, storageBufferSizes_[inputFFTDataBuffer]); } public: Evolutionary_Strategy_Vulkan(uint32_t aNumGenerations, uint32_t aNumParents, uint32_t aNumOffspring, uint32_t aNumDimensions, const std::vector<float> aParamMin, const std::vector<float> aParamMax, uint32_t aAudioLengthLog2) : Evolutionary_Strategy(aNumGenerations, aNumParents, aNumOffspring, aNumDimensions, aParamMin, aParamMax, aAudioLengthLog2), vkBenchmarker_("vulkanlog.csv", { "Test_Name", "Total_Time", "Average_Time", "Max_Time", "Min_Time", "Max_Difference", "Average_Difference" }), shaderNames_({ "initPopulation.spv", "recombinePopulation.spv", "mutatePopulation.spv", "SynthesisePopulation.spv", "applyWindowPopulation.spv", "VulkanFFT.spv", "fitnessPopulation.spv", "sortPopulation.spv", "rotatePopulation.spv" }) { } Evolutionary_Strategy_Vulkan(Evolutionary_Strategy_Vulkan_Arguments args) : Evolutionary_Strategy(args.es_args.numGenerations, args.es_args.pop.numParents, args.es_args.pop.numOffspring, args.es_args.pop.numDimensions, args.es_args.paramMin, args.es_args.paramMax, args.es_args.audioLengthLog2), vkBenchmarker_("vulkanlog.csv", { "Test_Name", "Total_Time", "Average_Time", "Max_Time", "Min_Time", "Max_Difference", "Average_Difference" }), shaderNames_({ "initPopulation.spv", "recombinePopulation.spv", "mutatePopulation.spv", "SynthesisePopulation.spv", "applyWindowPopulation.spv", "VulkanFFT.spv", "fitnessPopulation.spv", "sortPopulation.spv", "rotatePopulation.spv" }), workgroupX(args.workgroupX), workgroupY(args.workgroupY), workgroupZ(args.workgroupZ), workgroupSize(args.workgroupX*args.workgroupY*args.workgroupZ), globalSize(population.populationLength), numWorkgroupsX(globalSize / workgroupX), numWorkgroupsY(1), numWorkgroupsZ(1), chunkSizeFitness(workgroupSize / 2), deviceType_(args.deviceType) { for (int i = 0; i != randomStatesBuffer; ++i) storageBufferSizes_[i] = (population.numParents + population.numOffspring) * population.numDimensions * sizeof(float) * 2; storageBufferSizes_[randomStatesBuffer] = (population.numParents + population.numOffspring) * sizeof(glm::vec2); storageBufferSizes_[inputPopulationFitnessBuffer] = (population.numParents + population.numOffspring) * sizeof(float) * 2; storageBufferSizes_[outputPopulationFitnessBuffer] = (population.numParents + population.numOffspring) * sizeof(float) * 2; storageBufferSizes_[paramMinBuffer] = population.numDimensions * sizeof(float); storageBufferSizes_[paramMaxBuffer] = population.numDimensions * sizeof(float); storageBufferSizes_[outputAudioBuffer] = population.populationLength * objective.audioLength * sizeof(float); storageBufferSizes_[rotationIndexBuffer] = sizeof(uint32_t); storageBufferSizes_[wavetableBuffer] = objective.wavetableSize * sizeof(float); rotationIndex_ = 0; initContextCL(0, 0); initBuffersCL(); initCLFFT(); populationAudioDate = new float[population.populationLength * objective.audioLength]; populationFFTData = new float[population.populationLength * objective.fftOutSize]; createInstance(); findPhysicalDevice(); createDevice(); initBuffersVK(); createDescriptorSetLayout(); createDescriptorSet(); initConstantsVK(); createComputePipelines(); createCopyCommandPool(); std::vector<VkPipelineLayout> pipelineLayoutsTemp = { computePipelineLayouts_[initPopulation] }; std::vector<VkPipeline> pipelinesTemp = { computePipelines_[initPopulation] }; createCommandBuffer(commandPoolInit_, commandBufferInit_, pipelineLayoutsTemp, pipelinesTemp, &queryPoolInit_); pipelineLayoutsTemp = { computePipelineLayouts_[recombinePopulation], computePipelineLayouts_[mutatePopulation], computePipelineLayouts_[synthesisePopulation], computePipelineLayouts_[applyWindowPopulation] }; pipelinesTemp = { computePipelines_[recombinePopulation], computePipelines_[mutatePopulation], computePipelines_[synthesisePopulation], computePipelines_[applyWindowPopulation] }; createCommandBuffer(commandPoolESOne_, commandBufferESOne_, pipelineLayoutsTemp, pipelinesTemp, queryPoolESOne_); pipelineLayoutsTemp = { computePipelineLayouts_[fitnessPopulation], computePipelineLayouts_[sortPopulation] }; pipelinesTemp = { computePipelines_[fitnessPopulation], computePipelines_[sortPopulation] }; createCommandBuffer(commandPoolESTwo_, commandBufferESTwo_, pipelineLayoutsTemp, pipelinesTemp, queryPoolESTwo_); //createPopulationInitialiseCommandBuffer(); //createESCommandBufferOne(); //createESCommandBufferTwo(); initRandomStateBuffer(); writeLocalBuffer(storageBuffers_[paramMinBuffer], 4 * sizeof(float), (void*)objective.paramMins.data()); writeLocalBuffer(storageBuffers_[paramMaxBuffer], 4 * sizeof(float), (void*)objective.paramMaxs.data()); VKHelper::writeBuffer(logicalDevice_, storageBufferSizes_[wavetableBuffer], stagingBufferMemorySrc, objective.wavetable); copyBuffer(stagingBufferSrc, storageBuffers_[wavetableBuffer], storageBufferSizes_[wavetableBuffer]); } void initCLFFT() { //clFFT Variables// clfftDim dim = CLFFT_1D; size_t clLengths[1] = { objective.audioLength }; size_t in_strides[1] = { 1 }; size_t out_strides[1] = { 1 }; size_t in_dist = (size_t)objective.audioLength; size_t out_dist = (size_t)objective.audioLength / 2 + 4; //Update member variables with new information// objective.fftOutSize = out_dist * 2; storageBufferSizes_[inputFFTDataBuffer] = population.populationLength * objective.fftOutSize * sizeof(float); storageBufferSizes_[inputFFTTargetBuffer] = objective.fftHalfSize * sizeof(float); //Setup clFFT// clfftSetupData fftSetup; errorStatus_ = clfftInitSetupData(&fftSetup); errorStatus_ = clfftSetup(&fftSetup); //Create a default plan for a complex FFT// errorStatus_ = clfftCreateDefaultPlan(&planHandle, context_(), dim, clLengths); //Set plan parameters// errorStatus_ = clfftSetPlanPrecision(planHandle, CLFFT_SINGLE); errorStatus_ = clfftSetLayout(planHandle, CLFFT_REAL, CLFFT_HERMITIAN_INTERLEAVED); errorStatus_ = clfftSetResultLocation(planHandle, CLFFT_OUTOFPLACE); errorStatus_ = clfftSetPlanBatchSize(planHandle, (size_t)population.populationLength); clfftSetPlanInStride(planHandle, dim, in_strides); clfftSetPlanOutStride(planHandle, dim, out_strides); clfftSetPlanDistance(planHandle, in_dist, out_dist); //Bake clFFT plan// errorStatus_ = clfftBakePlan(planHandle, 1, &commandQueue_(), NULL, NULL); if (errorStatus_) std::cout << "ERROR creating clFFT plan. Status code: " << errorStatus_ << std::endl; } void writePopulationData() { } void readTestingData(void* aTestingData, size_t aTestingDataSize) { copyBuffer(storageBuffers_[inputPopulationValueBuffer], stagingBufferDst, aTestingDataSize); VKHelper::readBuffer(logicalDevice_, aTestingDataSize, stagingBufferMemoryDst, aTestingData); } void readPopulationData(void* aInputPopulationValueData, void* aOutputPopulationValueData, uint32_t aPopulationValueSize, void* aInputPopulationStepData, void* aOutputPopulationStepData, uint32_t aPopulationStepSize, void* aInputPopulationFitnessData, void* aOutputPopulationFitnessData, uint32_t aPopulationFitnessSize) { copyBuffer(storageBuffers_[inputPopulationValueBuffer], stagingBufferDst, aPopulationValueSize); VKHelper::readBuffer(logicalDevice_, aPopulationValueSize, stagingBufferMemoryDst, aInputPopulationValueData); copyBuffer(storageBuffers_[inputPopulationStepBuffer], stagingBufferDst, aPopulationStepSize); VKHelper::readBuffer(logicalDevice_, aPopulationStepSize, stagingBufferMemoryDst, aInputPopulationStepData); copyBuffer(storageBuffers_[inputPopulationFitnessBuffer], stagingBufferDst, aPopulationFitnessSize); VKHelper::readBuffer(logicalDevice_, aPopulationFitnessSize, stagingBufferMemoryDst, aInputPopulationFitnessData); } void writeSynthesizerData(void* aOutputAudioBuffer, uint32_t aOutputAudioSize, void* aInputFFTDataBuffer, void* aInputFFTTargetBuffer, uint32_t aInputFFTSize) { } void readSynthesizerData(void* aOutputAudioBuffer, uint32_t aOutputAudioSize, void* aInputFFTDataBuffer, void* aInputFFTTargetBuffer, uint32_t aInputFFTSize) { VKHelper::readBuffer(logicalDevice_, aOutputAudioSize, storageBuffersMemory_[outputAudioBuffer], aOutputAudioBuffer); VKHelper::readBuffer(logicalDevice_, aInputFFTSize, storageBuffersMemory_[inputFFTDataBuffer], aInputFFTDataBuffer); VKHelper::readBuffer(logicalDevice_, aInputFFTSize/2, storageBuffersMemory_[inputFFTTargetBuffer], aInputFFTTargetBuffer); } void readParamData() { } void writeParamData(void* aParamMinBuffer, void* aParamMaxBuffer) { VKHelper::writeBuffer(logicalDevice_, population.numDimensions*sizeof(float), storageBuffersMemory_[paramMinBuffer], aParamMinBuffer); VKHelper::writeBuffer(logicalDevice_, population.numDimensions*sizeof(float), storageBuffersMemory_[paramMaxBuffer], aParamMaxBuffer); } void executeMutate() { //commandQueue_.enqueueNDRangeKernel(kernels_[mutatePopulation], cl::NullRange/*globaloffset*/, globalws_, localws_, NULL); //commandQueue_.finish(); } void executeFitness() { //commandQueue_.enqueueNDRangeKernel(kernels_[fitnessPopulation], cl::NullRange/*globaloffset*/, globalws_, localws_, NULL); //commandQueue_.finish(); } void executeSynthesise() { //commandQueue_.enqueueNDRangeKernel(kernels_[synthesisePopulation], cl::NullRange/*globaloffset*/, globalws_, localws_, NULL); //commandQueue_.finish(); } void executeGeneration() { VKHelper::runCommandBuffer(logicalDevice_, computeQueue_, commandBufferESOne_); //VKHelper::readBuffer(logicalDevice_, storageBufferSizes_[outputAudioBuffer], storageBuffersMemory_[outputAudioBuffer], populationAudioDate); //copyBuffer(storageBuffers_[outputAudioBuffer], stagingBufferDst, storageBufferSizes_[outputAudioBuffer]); //VKHelper::readBuffer(logicalDevice_, storageBufferSizes_[outputAudioBuffer], stagingBufferMemoryDst, populationAudioDate); std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::steady_clock::now(); readLocalBuffer(storageBuffers_[outputAudioBuffer], storageBufferSizes_[outputAudioBuffer], populationAudioDate); calculateAudioFFT(); //@ToDo - Work out how to calculate FFT for GPU acceptable format. writeLocalBuffer(storageBuffers_[inputFFTDataBuffer], storageBufferSizes_[inputFFTDataBuffer], populationFFTData); auto end = std::chrono::steady_clock::now(); auto diff = end - start; shaderExecuteTime_[5] += diff.count() / (float)1e6; //VKHelper::writeBuffer(logicalDevice_, storageBufferSizes_[outputAudioBuffer], stagingBufferMemorySrc, populationAudioDate); //copyBuffer(stagingBufferSrc, storageBuffers_[outputAudioBuffer], storageBufferSizes_[outputAudioBuffer]); //VKHelper::writeBuffer(logicalDevice_, storageBufferSizes_[inputFFTDataBuffer], storageBuffersMemory_[inputFFTDataBuffer], populationFFTData); VKHelper::runCommandBuffer(logicalDevice_, computeQueue_, commandBufferESTwo_); vkBenchmarker_.startTimer(shaderNames_[8]); rotationIndex_ = (rotationIndex_ == 0 ? 1 : 0); VKHelper::writeBuffer(logicalDevice_, sizeof(uint32_t), storageBuffersMemory_[rotationIndexBuffer], &rotationIndex_); vkBenchmarker_.pauseTimer(shaderNames_[8]); } void executeAllGenerations() { rotationIndex_ = 0; for (uint32_t i = 0; i != numGenerations; ++i) { executeGeneration(); //*rotationIndex_ = (*rotationIndex_ == 0 ? 1 : 0); // //VkCommandBuffer commandBuffer = beginSingleTimeCommands(); //for(uint32_t i = 0; i != numPipelines_; ++i) // vkCmdPushConstants(commandBuffer, computePipelineLayouts_[i], VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t), rotationIndex_); ////VkCmdPushConstants(commandBufferESOne_, computePipelineLayouts_[0], VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t), rotationIndex_); //endSingleTimeCommands(commandBuffer); uint64_t timestamp[2]; vkGetQueryPoolResults(logicalDevice_, queryPoolInit_, 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); vkGetQueryPoolResults(logicalDevice_, queryPoolInit_, 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); uint64_t diff = timestamp[1] - timestamp[0]; shaderExecuteTime_[0] += diff / (float)1e6; vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[0], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[0], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); diff = timestamp[1] - timestamp[0]; shaderExecuteTime_[1] += diff / (float)1e6; vkBenchmarker_.addTimer(shaderNames_[1], diff / (float)1e6); vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[1], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[1], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); diff = timestamp[1] - timestamp[0]; shaderExecuteTime_[2] += diff / (float)1e6; vkBenchmarker_.addTimer(shaderNames_[2], diff / (float)1e6); vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[2], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[2], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); diff = timestamp[1] - timestamp[0]; shaderExecuteTime_[3] += diff / (float)1e6; vkBenchmarker_.addTimer(shaderNames_[3], diff / (float)1e6); vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[3], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[3], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); diff = timestamp[1] - timestamp[0]; shaderExecuteTime_[4] += diff / (float)1e6; vkBenchmarker_.addTimer(shaderNames_[4], diff / (float)1e6); vkGetQueryPoolResults(logicalDevice_, queryPoolESTwo_[0], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); vkGetQueryPoolResults(logicalDevice_, queryPoolESTwo_[0], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); diff = timestamp[1] - timestamp[0]; shaderExecuteTime_[6] += diff / (float)1e6; vkBenchmarker_.addTimer(shaderNames_[6], diff / (float)1e6); vkGetQueryPoolResults(logicalDevice_, queryPoolESTwo_[1], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); vkGetQueryPoolResults(logicalDevice_, queryPoolESTwo_[1], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); diff = timestamp[1] - timestamp[0]; shaderExecuteTime_[7] += diff / (float)1e6; vkBenchmarker_.addTimer(shaderNames_[7], diff / (float)1e6); } float totalKernelRunTime = 0.0; for (uint32_t i = 0; i != numPipelines_; ++i) { //executeTime = executeTime / numGenerations; std::cout << "Time to complete kernel " << i << ": " << shaderExecuteTime_[i] << "ms\n"; totalKernelRunTime += shaderExecuteTime_[i]; } std::cout << "Time to complete all kernels for this run: " << totalKernelRunTime << "ms\n"; } void parameterMatchAudio(float* aTargetAudio, uint32_t aTargetAudioLength) { chunkSize = objective.audioLength; chunks = aTargetAudioLength / chunkSize; for (int i = 0; i < chunks; i++) { setTargetAudio(&aTargetAudio[i*chunkSize], chunkSize); initPopulationVK(); uint32_t rI = 0; VKHelper::writeBuffer(logicalDevice_, sizeof(uint32_t), storageBuffersMemory_[rotationIndexBuffer], &rI); //Need this? executeAllGenerations(); uint32_t tempSize = 4 * sizeof(float); float* tempData = new float[4]; float tempFitness; copyBuffer(storageBuffers_[inputPopulationValueBuffer], stagingBufferDst, tempSize); VKHelper::readBuffer(logicalDevice_, tempSize, stagingBufferMemoryDst, tempData); //VKHelper::readBuffer(logicalDevice_, tempSize, storageBuffersMemory_[inputPopulationValueBuffer], tempData); copyBuffer(storageBuffers_[inputPopulationFitnessBuffer], stagingBufferDst, sizeof(float)); VKHelper::readBuffer(logicalDevice_, sizeof(float), stagingBufferMemoryDst, &tempFitness); //VKHelper::readBuffer(logicalDevice_, sizeof(float), storageBuffersMemory_[inputPopulationFitnessBuffer], &tempFitness); printf("Generation %d parameters:\n Param0 = %f\n Param1 = %f\n Param2 = %f\n Param3 = %f\nFitness=%f\n\n\n", i, tempData[0] * 3520.0, tempData[1] * 8.0, tempData[2] * 3520.0, tempData[3] * 1.0, tempFitness); } vkBenchmarker_.elapsedTimer(shaderNames_[1]); vkBenchmarker_.elapsedTimer(shaderNames_[2]); vkBenchmarker_.elapsedTimer(shaderNames_[3]); vkBenchmarker_.elapsedTimer(shaderNames_[4]); vkBenchmarker_.elapsedTimer(shaderNames_[5]); vkBenchmarker_.elapsedTimer(shaderNames_[6]); vkBenchmarker_.elapsedTimer(shaderNames_[7]); vkBenchmarker_.elapsedTimer(shaderNames_[8]); } void executeOpenCLFFT() { commandQueue_.enqueueWriteBuffer(inputBuffer, CL_TRUE, 0, storageBufferSizes_[outputAudioBuffer], populationAudioDate); /* Execute the plan. */ errorStatus_ = clfftEnqueueTransform(planHandle, CLFFT_FORWARD, 1, &commandQueue_(), 0, NULL, NULL, &inputBuffer(), &outputBuffer(), NULL); commandQueue_.finish(); commandQueue_.enqueueReadBuffer(outputBuffer, CL_TRUE, 0, storageBufferSizes_[inputFFTDataBuffer], populationFFTData); } void setTargetAudio(float* aTargetAudio, uint32_t aTargetAudioLength) { float* targetFFT = new float[objective.fftHalfSize]; objective.calculateFFT(aTargetAudio, targetFFT); //@ToDo - Check this works. Not any problems with passing as values// VKHelper::writeBuffer(logicalDevice_, objective.fftHalfSize * sizeof(float), storageBuffersMemory_[inputFFTTargetBuffer], targetFFT); delete(targetFFT); } void initPopulationVK() { VKHelper::runCommandBuffer(logicalDevice_, computeQueue_, commandBufferInit_); } //Command execution functions// VkCommandBuffer beginSingleTimeCommands() { //Memory transfer executed like drawing commands// VkCommandBufferAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPoolStaging_; //@ToDo - Is this okay to be renderCommandPool only? Or need one for each?? allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(logicalDevice_, &allocInfo, &commandBuffer); //Start recording command buffer// VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); return commandBuffer; } void endSingleTimeCommands(VkCommandBuffer aCommandBuffer) { vkEndCommandBuffer(aCommandBuffer); //Execute command buffer to complete transfer - Can use fences for synchronized, simultaneous execution// VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &aCommandBuffer; vkQueueSubmit(computeQueue_, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(computeQueue_); //Cleanup used comand pool// vkFreeCommandBuffers(logicalDevice_, commandPoolStaging_, 1, &aCommandBuffer); //@ToDo - Is this okay to be renderCommandPool only? Or need one for each?? } void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { VkCommandBufferAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPoolStaging_; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(logicalDevice_, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferCopy copyRegion = {}; copyRegion.srcOffset = 0; // Optional copyRegion.dstOffset = 0; // Optional copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion); vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; vkQueueSubmit(computeQueue_, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(computeQueue_); vkFreeCommandBuffers(logicalDevice_, commandPoolStaging_, 1, &commandBuffer); } void readLocalBuffer(VkBuffer aBuffer, uint32_t aSize, void* aOutput) { copyBuffer(aBuffer, stagingBufferDst, aSize); VKHelper::readBuffer(logicalDevice_, aSize, stagingBufferMemoryDst, aOutput); } void writeLocalBuffer(VkBuffer aBuffer, uint32_t aSize, void* aInput) { VKHelper::writeBuffer(logicalDevice_, aSize, stagingBufferMemorySrc, aInput); copyBuffer(stagingBufferSrc, aBuffer, aSize); } void createCommandBuffer(VkCommandPool& aCommandPool, VkCommandBuffer& aCommandBuffer, std::vector<VkPipelineLayout>& aPipelineLayouts, std::vector<VkPipeline>& aPipelines, /*std::vector<VkQueryPool>&*/ VkQueryPool aQueryPools[]) { //Timestamp initilize// VkQueryPoolCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; createInfo.pNext = nullptr; createInfo.queryType = VK_QUERY_TYPE_TIMESTAMP; createInfo.queryCount = 2; for (uint32_t i = 0; i != aPipelineLayouts.size(); ++i) { VkResult res = vkCreateQueryPool(logicalDevice_, &createInfo, nullptr, &(aQueryPools[i])); assert(res == VK_SUCCESS); } /* We are getting closer to the end. In order to send commands to the device(GPU), we must first record commands into a command buffer. To allocate a command buffer, we must first create a command pool. So let us do that. */ VkCommandPoolCreateInfo commandPoolCreateInfo = {}; commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; commandPoolCreateInfo.flags = 0; // the queue family of this command pool. All command buffers allocated from this command pool, // must be submitted to queues of this family ONLY. commandPoolCreateInfo.queueFamilyIndex = queueFamilyIndex_; VK_CHECK_RESULT(vkCreateCommandPool(logicalDevice_, &commandPoolCreateInfo, NULL, &aCommandPool)); /* Now allocate a command buffer from the command pool. */ VkCommandBufferAllocateInfo commandBufferAllocateInfo = {}; commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; commandBufferAllocateInfo.commandPool = aCommandPool; // specify the command pool to allocate from. // if the command buffer is primary, it can be directly submitted to queues. // A secondary buffer has to be called from some primary command buffer, and cannot be directly // submitted to a queue. To keep things simple, we use a primary command buffer. commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; commandBufferAllocateInfo.commandBufferCount = 1; // allocate a single command buffer. VK_CHECK_RESULT(vkAllocateCommandBuffers(logicalDevice_, &commandBufferAllocateInfo, &aCommandBuffer)); // allocate command buffer. /* Now we shall start recording commands into the newly allocated command buffer. */ VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; // the buffer is only submitted and used once in this application. VK_CHECK_RESULT(vkBeginCommandBuffer(aCommandBuffer, &beginInfo)); // start recording commands. for (uint32_t i = 0; i != aPipelineLayouts.size(); ++i) { vkCmdResetQueryPool(aCommandBuffer, aQueryPools[i], 0, 2); /* We need to bind a pipeline, AND a descriptor set before we dispatch. The validation layer will NOT give warnings if you forget these, so be very careful not to forget them. */ vkCmdBindDescriptorSets(aCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, aPipelineLayouts[i], 0, 1, &descriptorSet_, 0, NULL); vkCmdBindPipeline(aCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, aPipelines[i]); //Include loop and update push constants every iteration// //vkCmdPushConstants(commandBufferInit_, computePipelineLayouts_[initPopulation], VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t), rotationIndex_); vkCmdWriteTimestamp(aCommandBuffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, aQueryPools[i], 0); /* Calling vkCmdDispatch basically starts the compute pipeline, and executes the compute shader. The number of workgroups is specified in the arguments. If you are already familiar with compute shaders from OpenGL, this should be nothing new to you. */ vkCmdDispatch(aCommandBuffer, numWorkgroupsX, numWorkgroupsY, numWorkgroupsZ); vkCmdPipelineBarrier(aCommandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, NULL, 0, NULL, 0, NULL, 0, NULL); vkCmdWriteTimestamp(aCommandBuffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, aQueryPools[i], 1); } VK_CHECK_RESULT(vkEndCommandBuffer(aCommandBuffer)); // end recording commands. } }; #endif
48.738408
458
0.799906
f25211b062c96bd4607d269177d7eee4e4c09c4a
7,227
cpp
C++
Final/Dataset/B2016_Z2_Z3/student4982.cpp
Team-PyRated/PyRated
1df171c8a5a98977b7a96ee298a288314d1b1b96
[ "MIT" ]
null
null
null
Final/Dataset/B2016_Z2_Z3/student4982.cpp
Team-PyRated/PyRated
1df171c8a5a98977b7a96ee298a288314d1b1b96
[ "MIT" ]
null
null
null
Final/Dataset/B2016_Z2_Z3/student4982.cpp
Team-PyRated/PyRated
1df171c8a5a98977b7a96ee298a288314d1b1b96
[ "MIT" ]
null
null
null
#include <iostream> #include <stdexcept> #include <vector> #include <deque> #include <type_traits> #include <cmath> #include <algorithm> #include <iomanip> int SumaCifara(long long int x) { int suma=0; while(x!=0) { suma+=std::abs(x%10); x=x/10; } return suma; } int SumaDjelilaca(long long int x) { int suma=0; if(x<0) x=-x; for(long long int i=1;i<=x;i++) { if(x%i==0) suma+=i; } return suma; } bool DaLiJeProst(long long int x) { if(x<=1) return false; long long int i=0; for(i=2;i<=(int)sqrt(x);i++) { if(x%i==0) return false; } if(i==(int)sqrt(x)+1) return true; } int BrojProstihFaktora(long long int x) { if(x<=1) return 0; if(DaLiJeProst(x)==true) return 1; int i=2, suma=0, n=x; while(1) { if(i==x) break; if(DaLiJeProst(i)==false) i++; if(DaLiJeProst(i)==true) { if(n==1) break; if(n%i==0) { n=n/i; suma++; } else i++; } } return suma; } bool DaLiJeSavrsen(long long int x) { int suma=0; for(long long int i=1;i<x;i++) if(x%i==0) suma+=i; if(suma==x) return true; else return false; } int BrojSavrsenihDjelilaca(long long int x) { if(x<0) x=-x; int broj=0; for(long long int i=1;i<=x;i++) if(x%i==0 && DaLiJeSavrsen(i)==true) broj++; return broj; } template <typename Tip1, typename Tip2, typename Tip3, typename Tip4> auto UvrnutiPresjek(Tip1 p1, Tip1 p2, Tip2 p3, Tip2 p4, Tip3 fun(Tip4)) -> std::vector<std::vector<typename std::remove_reference<decltype((*p1)+(*p3))>::type>> { typedef typename std::remove_reference<decltype((*p1)+(*p3))>::type Tip; std::vector<std::vector<Tip>> matrica; Tip2 poc2=p3; while(p1!=p2) { while(p3!=p4) { if(fun(*p1)==fun(*p3)) { std::vector<Tip> v; v.push_back(*p1); v.push_back(*p3); v.push_back(fun(*p1)); matrica.push_back(v); } p3++; } p3=poc2; p1++; } std::sort(matrica.begin(), matrica.end(), [](std::vector<Tip> x, std::vector<Tip> y) { return x[2]<y[2]; } ); if(matrica.size()>1) { for(int i=0;i<matrica.size()-1;i++) { for(int j=i+1;j<matrica.size();j++) { if(matrica[i][2]==matrica[j][2]) std::sort(matrica.begin()+i,matrica.begin()+j+1, [](std::vector<Tip> x, std::vector<Tip> y) { return x[0]<y[0];}); } } for(int i=0;i<matrica.size()-1;i++) { for(int j=i+1;j<matrica.size();j++) { if(matrica[i][0]==matrica[j][0]) std::sort(matrica.begin()+i,matrica.begin()+j+1, [](std::vector<Tip> x, std::vector<Tip> y) { return x[1]<y[1];}); } } } return matrica; } template <typename Tip1, typename Tip2> auto UvrnutiPresjek(Tip1 p1, Tip1 p2, Tip2 p3, Tip2 p4) -> std::vector<std::vector<typename std::remove_reference<decltype((*p1)+(*p3))>::type>> { typedef typename std::remove_reference<decltype((*p1)+(*p3))>::type Tip; std::vector<std::vector<Tip>> matrica; Tip2 poc=p3; while(p1!=p2) { while(p3!=p4) { if(*p1==*p3) { std::vector<Tip> v1; v1.push_back(*p1); v1.push_back(0); v1.push_back(0); matrica.push_back(v1); } p3++; } p3=poc; p1++; } std::sort(matrica.begin(), matrica.end(), [] (std::vector<Tip> x, std::vector<Tip> y) { return x[0]<y[0]; }); return matrica; } template<typename Tip1, typename Tip2, typename Tip3, typename Tip4> auto UvrnutaRazlika(Tip1 p1, Tip1 p2, Tip2 p3, Tip2 p4, Tip3 fun(Tip4)) -> std::vector<std::vector<typename std::remove_reference<decltype((*p1)+(*p3))>::type>> { typedef typename std::remove_reference<decltype((*p1)+(*p3))>::type Tip; std::vector<std::vector<Tip>> matrica; Tip1 poc=p1; Tip2 poc2=p3; while(p1!=p2) { bool par=false; while(p3!=p4) { if(fun(*p1)==fun(*p3)) par=true; p3++; } p3=poc2; if(par==false) { std::vector<Tip> v; v.push_back(*p1); v.push_back(fun(*p1)); matrica.push_back(v); } p1++; } p1=poc; p3=poc2; while(p3!=p4) { bool par=false; while(p1!=p2) { if(fun(*p3)==fun(*p1)) par=true; p1++; } p1=poc; if(par==false) { std::vector<Tip> v; v.push_back(*p3); v.push_back(fun(*p3)); matrica.push_back(v); } p3++; } std::sort(matrica.begin(),matrica.end(),[] (std::vector<Tip> x, std::vector<Tip> y) {return x[0]>y[0];} ); if(matrica.size()>1) { for(int i=0;i<matrica.size()-1;i++) { for(int j=i+1;j<matrica.size();j++) { if(matrica[i][0]==matrica[j][0]) std::sort(matrica.begin()+i,matrica.begin()+j+1, [] (std::vector<Tip> x, std::vector<Tip> y) {return x[1]>y[1];} ); } } } return matrica; } template<typename Tip1, typename Tip2> auto UvrnutaRazlika(Tip1 p1, Tip1 p2, Tip2 p3, Tip2 p4) -> std::vector<std::vector<typename std::remove_reference<decltype((*p1)+(*p3))>::type>> { typedef typename std::remove_reference<decltype((*p1)+(*p3))>::type Tip; std::vector<std::vector<Tip>> matrica; Tip1 poc=p1; Tip2 poc2=p3; while(p1!=p2) { bool par=false; while(p3!=p4) { if(*p1==*p3) par=true; p3++; } p3=poc2; if(par==false) { std::vector<Tip> v; v.push_back(*p1); v.push_back(0); matrica.push_back(v); } p1++; } p1=poc; p3=poc2; while(p3!=p4) { bool par=false; while(p1!=p2) { if(*p3==*p1) par=true; p1++; } p1=poc; if(par==false) { std::vector<Tip> v; v.push_back(*p3); v.push_back(0); matrica.push_back(v); } p3++; } std::sort(matrica.begin(),matrica.end(),[](std::vector<Tip> x, std::vector<Tip> y){return x[0]>y[0];}); return matrica; } int main () { try { std::cout<<"Unesite broj elemenata prvog kontejnera: "; int n; std::cin>>n; std::deque<int> d1; std::cout<<"Unesite elemente prvog kontejnera: "; while(d1.size()<n) { int x; std::cin>>x; if(d1.size()==0) d1.push_back(x); else { bool ponavlja_se=false; for(int i=0;i<d1.size();i++) { if(d1[i]==x) { ponavlja_se=true; break; } } if(ponavlja_se==false) d1.push_back(x); } } std::cout<<"Unesite broj elemenata drugog kontejnera: "; std::deque<int> d2; int k; std::cin>>k; std::cout<<"Unesite elemente drugog kontejnera: "; while(d2.size()<k) { int x; std::cin>>x; if(d2.size()==0) d2.push_back(x); else { bool ponavlja_se=false; for(int i=0;i<d2.size();i++) { if(d2[i]==x) { ponavlja_se=true; break; } } if(ponavlja_se==false) d2.push_back(x); } } std::vector<std::vector<int>> matrica=UvrnutiPresjek(d1.begin(),d1.end(),d2.begin(),d2.end(),SumaCifara); std::vector<std::vector<int>> matrica2=UvrnutaRazlika(d1.begin(),d1.end(),d2.begin(),d2.end(),BrojProstihFaktora); std::cout<<"Uvrnuti presjek kontejnera:"<<std::endl; for(std::vector<int> red: matrica) { for(int x: red) std::cout<<std::setw(6)<<x<<" "; std::cout<<std::endl; } std::cout<<"Uvrnuta razlika kontejnera:"<<std::endl; for(std::vector<int> red: matrica2) { for(int x: red) std::cout<<std::setw(6)<<x<<" "; std::cout<<std::endl; } std::cout<<"Dovidjenja!"; return 0; } catch(...) { std::cout<<"Izuzetak: nedovoljno memorije"; } }
22.100917
164
0.5705
f255aecf55b084a234b0747fedf0e3de15bf4980
7,619
cpp
C++
Necromancer/Terrain.cpp
myffx36/RenderingEngine
38df29966b3126744fb40c2a97775ae44cea92f9
[ "MIT" ]
null
null
null
Necromancer/Terrain.cpp
myffx36/RenderingEngine
38df29966b3126744fb40c2a97775ae44cea92f9
[ "MIT" ]
null
null
null
Necromancer/Terrain.cpp
myffx36/RenderingEngine
38df29966b3126744fb40c2a97775ae44cea92f9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Terrain.h" const float height_base = 200.0f; namespace Necromancer { Terrain::Terrain(const char* file_name, ID3D11Device* device) { std::fstream terrain_file; terrain_file.open(file_name, std::ios::binary | std::ios::in); terrain_file.seekg(0, std::ios::beg); auto start_point = terrain_file.tellg(); terrain_file.seekg(0, std::ios::end); auto end_point = terrain_file.tellg(); unsigned long file_size = end_point; m_terrain_size = sqrt(file_size / sizeof(float)); unsigned long data_size = file_size / sizeof(float); m_data = new float[data_size]; terrain_file.seekg(0, std::ios::beg); terrain_file.read(reinterpret_cast<char*>(m_data), file_size); terrain_file.close(); //CImage image; //const size_t cSize = strlen(file_name) + 1; //wchar_t* wc = new wchar_t[cSize]; //mbstowcs(wc, file_name, cSize); //image.Load(wc); //delete[] wc; //m_terrain_size = image.GetHeight(); //m_data = new float[image.GetHeight() * image.GetWidth()]; //for (int i = 0; i < image.GetWidth(); ++i) { // for (int j = 0; j < image.GetHeight(); ++j) { // int index = i * image.GetHeight() + j; // m_data[index] = (GetRValue(image.GetPixel(i, j))) / 255.0f; // } //} m_position = nullptr; m_normal = nullptr; m_indices = nullptr; generate_position(); generate_indices(); generate_normal(); generate_vb_ib(device); } Terrain::~Terrain() { delete[] m_data; if (m_position) delete[] m_position; if (m_normal) delete[] m_normal; if (m_indices) delete[] m_indices; } void Terrain::generate_position() { m_position = new Vec3[m_terrain_size * m_terrain_size]; for (unsigned long i = 0; i < m_terrain_size; ++i) { for (unsigned long j = 0; j < m_terrain_size; ++j) { unsigned long offset = (i * m_terrain_size + j); m_position[offset][0] = static_cast<float>(i); m_position[offset][1] = height_base * m_data[i * m_terrain_size + j]; m_position[offset][2] = static_cast<float>(j); } } } void Terrain::generate_normal() { m_normal = new Vec3[m_terrain_size * m_terrain_size]; for (unsigned long i = 0; i < m_terrain_size * m_terrain_size; ++i) { m_normal[i] = Vec3(0.0f, 0.0f, 0.0f); } unsigned long triangle_num = (m_terrain_size - 1) * (m_terrain_size - 1) * 2; for (unsigned long i = 0; i < triangle_num; ++i) { unsigned long index_offset = i * 3; unsigned long i1 = m_indices[index_offset]; unsigned long i2 = m_indices[index_offset + 1]; unsigned long i3 = m_indices[index_offset + 2]; Vec3 p1 = m_position[i1]; Vec3 p2 = m_position[i2]; Vec3 p3 = m_position[i3]; Vec3 l1 = p2 - p1; Vec3 l2 = p3 - p2; Vec3 normal = normalize(cross(l2, l1)); m_normal[i1] = m_normal[i1] + normal; m_normal[i2] = m_normal[i2] + normal; m_normal[i3] = m_normal[i3] + normal; } for (unsigned long i = 0; i < m_terrain_size * m_terrain_size; ++i) { m_normal[i] = normalize(m_normal[i]); } } void Terrain::generate_indices() { unsigned long triangle_num = (m_terrain_size - 1) * (m_terrain_size - 1) * 2; m_index_number = triangle_num * 3; m_indices = new unsigned long[m_index_number]; for (unsigned long i = 0; i < m_terrain_size - 1; ++i) { for (unsigned long j = 0; j < m_terrain_size - 1; ++j) { unsigned long offset = (i * (m_terrain_size - 1) + j) * 6; unsigned long left_bottom_index = i * m_terrain_size + j; unsigned long left_top_index = left_bottom_index + 1; unsigned long right_bottom_index = left_bottom_index + m_terrain_size; unsigned long right_top_index = right_bottom_index + 1; m_indices[offset + 0] = left_bottom_index; m_indices[offset + 1] = right_bottom_index; m_indices[offset + 2] = left_top_index; m_indices[offset + 3] = left_top_index; m_indices[offset + 4] = right_bottom_index; m_indices[offset + 5] = right_top_index; } } } void Terrain::generate_vb_ib(ID3D11Device* d3d_device) { float *vertices = new float[8 * m_terrain_size * m_terrain_size]; for (unsigned long i = 0; i < m_terrain_size * m_terrain_size; ++i) { unsigned long vertices_offset = i * 8; vertices[vertices_offset + 0] = m_position[i].x; vertices[vertices_offset + 1] = m_position[i].y; vertices[vertices_offset + 2] = m_position[i].z; vertices[vertices_offset + 3] = m_normal[i].x; vertices[vertices_offset + 4] = m_normal[i].y; vertices[vertices_offset + 5] = m_normal[i].z; vertices[vertices_offset + 6] = 0.0f; vertices[vertices_offset + 7] = 0.0f; } D3D11_BUFFER_DESC vb_desc; ZeroMemory(&vb_desc, sizeof(vb_desc)); vb_desc.ByteWidth = 8 * m_terrain_size * m_terrain_size * sizeof(float); vb_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vb_desc.CPUAccessFlags = 0; vb_desc.Usage = D3D11_USAGE_DEFAULT; vb_desc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vb_init_data; vb_init_data.pSysMem = vertices; vb_init_data.SysMemPitch = 0; vb_init_data.SysMemSlicePitch = 0; HRESULT hr = d3d_device->CreateBuffer(&vb_desc, &vb_init_data, &m_vertex_buffer); delete[]vertices; D3D11_BUFFER_DESC ib_desc; ZeroMemory(&vb_desc, sizeof(ib_desc)); ib_desc.ByteWidth = m_index_number * sizeof(unsigned long); ib_desc.BindFlags = D3D11_BIND_INDEX_BUFFER; ib_desc.CPUAccessFlags = 0; ib_desc.Usage = D3D11_USAGE_DEFAULT; ib_desc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA ib_init_data; ib_init_data.pSysMem = m_indices; ib_init_data.SysMemPitch = 0; ib_init_data.SysMemSlicePitch = 0; hr = d3d_device->CreateBuffer(&ib_desc, &ib_init_data, &m_index_buffer); char* vs_data; unsigned long vs_data_size; std::ifstream vs_file("VertexShader.cso", std::ios::binary | std::ios::ate); vs_data_size = static_cast<unsigned long>(vs_file.tellg()); vs_file.seekg(std::ios::beg); vs_data = new char[vs_data_size]; vs_file.read(vs_data, vs_data_size); vs_file.close(); hr = d3d_device->CreateVertexShader(vs_data, vs_data_size, nullptr, &m_vertex_shader); char* ps_data; unsigned long ps_data_size; std::ifstream ps_file("PixelShader.cso", std::ios::binary | std::ios::ate); ps_data_size = static_cast<unsigned long>(ps_file.tellg()); ps_file.seekg(std::ios::beg); ps_data = new char[ps_data_size]; ps_file.read(ps_data, ps_data_size); ps_file.close(); hr = d3d_device->CreatePixelShader(ps_data, ps_data_size, nullptr, &m_pixel_shader); D3D11_INPUT_ELEMENT_DESC input_layout_desc[3]; input_layout_desc[0].SemanticName = "POSITION"; input_layout_desc[0].SemanticIndex = 0; input_layout_desc[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; input_layout_desc[0].InputSlot = 0; input_layout_desc[0].AlignedByteOffset = 0; input_layout_desc[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; input_layout_desc[0].InstanceDataStepRate = 0; input_layout_desc[1].SemanticName = "NORMAL"; input_layout_desc[1].SemanticIndex = 0; input_layout_desc[1].Format = DXGI_FORMAT_R32G32B32_FLOAT; input_layout_desc[1].InputSlot = 0; input_layout_desc[1].AlignedByteOffset = 3 * sizeof(float); input_layout_desc[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; input_layout_desc[1].InstanceDataStepRate = 0; input_layout_desc[2].SemanticName = "TEXCOORD"; input_layout_desc[2].SemanticIndex = 0; input_layout_desc[2].Format = DXGI_FORMAT_R32G32_FLOAT; input_layout_desc[2].InputSlot = 0; input_layout_desc[2].AlignedByteOffset = 6 * sizeof(float); input_layout_desc[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; input_layout_desc[2].InstanceDataStepRate = 0; hr = d3d_device->CreateInputLayout(input_layout_desc, 3, vs_data, vs_data_size, &m_input_layout); } }
35.110599
88
0.708229
f25c4187bd60703c16fbcb4709293a8ec00f1145
101
cpp
C++
code/code-complete/test.cpp
peter-can-talk/cpp-london
e232bf98f28b1d8b56af3af23d43a3f565221ab0
[ "MIT" ]
3
2017-02-20T23:24:47.000Z
2019-09-09T19:15:07.000Z
code/code-complete/test.cpp
peter-can-talk/cpp-london-2017
e232bf98f28b1d8b56af3af23d43a3f565221ab0
[ "MIT" ]
null
null
null
code/code-complete/test.cpp
peter-can-talk/cpp-london-2017
e232bf98f28b1d8b56af3af23d43a3f565221ab0
[ "MIT" ]
null
null
null
struct X { /** * foo does things. */ void foo(int x) { } }; int main() { X x; x. }
7.214286
21
0.405941
f2609badd8ff348904efaae8ae92b3112507f4fc
8,628
cpp
C++
PersonDetection/PersonDetector.cpp
vohoaiviet/Human-Detection
e34acdab5af81fc2e99d686ada470a114ae3de63
[ "MIT" ]
28
2015-04-28T08:45:43.000Z
2021-11-15T12:10:12.000Z
PersonDetection/PersonDetector.cpp
vohoaiviet/Human-Detection
e34acdab5af81fc2e99d686ada470a114ae3de63
[ "MIT" ]
null
null
null
PersonDetection/PersonDetector.cpp
vohoaiviet/Human-Detection
e34acdab5af81fc2e99d686ada470a114ae3de63
[ "MIT" ]
28
2015-04-07T04:02:07.000Z
2019-03-31T17:55:42.000Z
#include "StdAfx.h" #include "PersonDetector.h" #include <math.h> PersonDetector::PersonDetector() { m_cell = cvSize(8, 8); m_block = cvSize(2, 2); m_winSize = cvSize(64, 128); m_stepOverlap = 1; classifier.SetParams(m_cell, m_block , m_stepOverlap); startScale = 1; scaleStep = 1.5; m_widthStep = 8; m_heigthStep = 8; svmTrainPath = "Dataset/small train/TrainSVM.xml"; } void PersonDetector::setParams(CvSize cell, CvSize block, float stepOverLap) { m_cell = cell; m_block = block; m_stepOverlap = stepOverLap; classifier.SetParams(cell, block , stepOverLap); } void PersonDetector::setSVMTrainPath(char* path) { svmTrainPath = path; classifier.loadTrainSVM(path); } int PersonDetector::DetectPosWindows(IplImage* img) { int nWins = 0; return nWins; } /// Ham detect people multiscale // Params: srcImgPath: Duong dan toi file anh test // Return value: so luong nguoi detect duoc IplImage* PersonDetector::DetectMultiScale(char* srcImgPath) { int count = 0; IplImage* srcImg = cvLoadImage(srcImgPath, 1); CvSize size = cvGetSize(srcImg); // vector<IntegralScale*> integralsScale; // if (size.width > 400) { //IplImage* dst = cvCreateImage(cvSize((int)(srcImg->width / 2), (int)(srcImg->height / 2)), // srcImg->depth, srcImg->nChannels); //cvResize(srcImg, dst); //cvReleaseImage(&srcImg); //srcImg = cvCloneImage(dst); startScale = 2.5; } else if (size.width > 300) { startScale = 2; } // Tinh toan so buoc scale anh endScale = min((float)size.width / m_winSize.width, (float)size.height / m_winSize.height); nScaleStep = floor(log(endScale / startScale) / log(scaleStep) + 1); // Khoi tao kich thuoc scale ban dau float scale = startScale; // Duyet qua tat ca cac muc scale for (int k = 0; k <= nScaleStep; k++) { IplImage* input = NULL; if (k == nScaleStep) { // Kiem tra neu buoc scale truoc do da cho ti le anh input bang ti le cua so thi if ((int)(srcImg->width / scale) == m_winSize.width && (int)(srcImg->height / scale) == m_winSize.height) break; else // Nguoc lai thuc hien them 1 lan test voi kich thuoc anh scale bang dung kich thuoc cua so input = cvCreateImage(cvSize((int)(m_winSize.width), (int)(m_winSize.height)), srcImg->depth, srcImg->nChannels); } else { input = cvCreateImage(cvSize((int)(srcImg->width / scale), (int)(srcImg->height / scale)), srcImg->depth, srcImg->nChannels); } cvResize(srcImg, input); int x = 0; int y = 0; int nBins = classifier.hog.NumOfBins; IplImage** integrals = classifier.calcIntegralHOG(input); // add integral image + scale vao list IntegralScale *integralScaleImage = new IntegralScale(integrals, scale); integralsScale.push_back(integralScaleImage); // IplImage** integralsInput = (IplImage**)malloc(nBins * sizeof(IplImage*)); while(y + m_winSize.height <= integrals[0]->height) { x = 0; while (x + m_winSize.width <= integrals[0]->width) { // set region of interest for (int i = 0; i < nBins; i++) { cvSetImageROI(integrals[i], cvRect(x, y, m_winSize.width + 1, m_winSize.height + 1)); integralsInput[i] = cvCreateImage(cvGetSize(integrals[i]),integrals[i]->depth, integrals[i]->nChannels); cvCopy(integrals[i], integralsInput[i], NULL); } //IplImage *img = cvCreateImage(cvGetSize(input),input->depth, input->nChannels); // copy subimage //cvCopy(input, img, NULL); float weight = classifier.testSVM(svmTrainPath, integralsInput, NULL); if (weight != 2) // -2.4115036f) { ScanWindow *window = new ScanWindow(x, y, scale, 64, 128); // changed 3rd parameter from 1 to scale window->setWeight(weight); m_detectedWindows.push_back(window); } for (int i = 0; i < nBins; i++) cvResetImageROI(integrals[i]); x += m_widthStep; //cvReleaseImage(&img); for (int i = 0; i < nBins; i++) cvReleaseImage(&integralsInput[i]); } y += m_heigthStep; } for (int i = 0; i < nBins; i++) cvReleaseImage(&integrals[i]); free(integrals); free(integralsInput); cvReleaseImage(&input); scale *= scaleStep; } // PHAN LOCALIZATION // Input: tap cac cua so o cac muc scale da detect duoc tren anh test input // Output: tra ra tap cac cua so da HOI TU int numberWindows = -1; OverlappingDetection *overlapDetector; vector<CvMat*> boundaryList; while (true) { overlapDetector = new OverlappingDetection(&m_detectedWindows); // cluster nhung cum cua so overlap len nhau overlapDetector->clusterWindows(); for (int i = 0; i < overlapDetector->_clusteredWindows.size(); i++) { // doi voi moi cum, tao ra mot doi tuong localization de localize ScanWindow** listOverlapped = new ScanWindow*[overlapDetector->_clusteredWindows[i].size()]; for (int j = 0; j < overlapDetector->_clusteredWindows[i].size(); j++) { listOverlapped[j] = m_detectedWindows[overlapDetector->_clusteredWindows[i][j]]; } //Localisation *localize = new Localisation(overlapDetector->_clusteredWindows[i], m_widthStep, m_heigthStep, log(1.03), scaleStep, &classifier, svmTrainPath, srcImg, integralsScale); Localisation *localize = new Localisation(listOverlapped, m_widthStep, m_heigthStep, log(1.03), scaleStep, &classifier, svmTrainPath, srcImg, integralsScale); //localize->_detectedWindows = overlapDetector->_clusteredWindows[i]; // tinh toan cua so cuoi cung de tim boundary localize->localize2(overlapDetector->_clusteredWindows[i].size()); // lay ra boundary boundaryList.push_back(localize->_finalLocalisationWindow); for (int j = 0; j < overlapDetector->_clusteredWindows[i].size(); j++) { delete listOverlapped[j]; } delete listOverlapped; delete localize; } if (boundaryList.size() == numberWindows) { break; } else { numberWindows = boundaryList.size(); // huy vung nho m_detectedWindows.clear(); for (int i = 0; i < boundaryList.size(); i++) { float scaleWindow = cvGetReal2D(boundaryList[i], 2, 0); int x = (int) cvGetReal2D(boundaryList[i], 0, 0); int y = (int) cvGetReal2D(boundaryList[i], 1, 0); x = (int) x / scaleWindow; y = (int) y/ scaleWindow; ScanWindow* window = new ScanWindow(x, y, scaleWindow, 64, 128); m_detectedWindows.push_back(window); } // for (int i = 0; i < boundaryList.size(); i++) { cvReleaseMat(&boundaryList[i]); } free(overlapDetector); boundaryList.clear(); } } // ket thuc phan localization // Ve Bounding box o day, su dung danh sach boundaryList // Trong do, cua so thu i bao gom // x = cvGetReal2D(boundaryList[i], 0, 0) // y = cvGetReal2D(boundaryList[i], 1, 0) // scale = cvGetReal2D(boundaryList[i], 2, 0) IplImage* resultImage = cvCloneImage(srcImg); float scaleWindow; int x, y; float width, height; for (int i = 0; i < boundaryList.size(); i++) { //scaleWindow = pow(10, (float) cvGetReal2D(boundaryList[i], 2, 0)); //scaleWindow = exp((float) cvGetReal2D(boundaryList[i], 2, 0)); scaleWindow = cvGetReal2D(boundaryList[i], 2, 0); x = (int) cvGetReal2D(boundaryList[i], 0, 0); y = (int) cvGetReal2D(boundaryList[i], 1, 0); // // width = 64 * scaleWindow; height = 128 * scaleWindow; cvRectangle(resultImage, cvPoint(x, y), cvPoint(x + (int) width, y + (int) height), cvScalar(0, 255, 255, 0), 2, 8, 0); } //float scaleWindow; //int x, y; //int width, height; //for (int i = 0; i < m_detectedWindows.size(); i++) //{ // //scaleWindow = pow(10, (float) cvGetReal2D(boundaryList[i], 2, 0)); // scaleWindow = m_detectedWindows[i]->getScale(); // x = (int) m_detectedWindows[i]->getXCoordinate(); // y = (int) m_detectedWindows[i]->getYCoordinate(); // width = 64 * scaleWindow; // height = 128 * scaleWindow; // cvRectangle(resultImage, cvPoint(x, y), cvPoint(x + (int) width, y + (int) height), cvScalar(0, 255, 255, 0), 2, 8, 0); // //} /*string sFile(srcImgPath); int pos = sFile.find_last_of('/'); string sFileOut = sFile.substr(pos + 1, sFile.length() - pos - 1); sFileOut = "Result/neg/" + sFileOut; cvSaveImage(sFileOut.c_str(), resultImage, 0); cvReleaseImage(&resultImage);*/ // ket thuc ve bounding box //count = m_detectedWindows.size(); count = boundaryList.size(); // huy vung nho for (int i = 0; i < boundaryList.size(); i++) { cvReleaseMat(&boundaryList[i]); } if (srcImg != NULL) cvReleaseImage(&srcImg); // free vung nho free(overlapDetector); boundaryList.clear(); integralsScale.clear(); m_detectedWindows.clear(); return resultImage; }
28.104235
186
0.663421
f260cce44c1ea4cd63b4a99908bfd536b9922ccb
618
cpp
C++
src/game/LevelListLoader.cpp
ArthurSonzogni/InTheCube
c4a35096d962d23f6211802970ee44f77d29e38a
[ "MIT" ]
4
2019-12-31T07:58:54.000Z
2021-09-07T18:16:51.000Z
src/game/LevelListLoader.cpp
ArthurSonzogni/InTheCube
c4a35096d962d23f6211802970ee44f77d29e38a
[ "MIT" ]
null
null
null
src/game/LevelListLoader.cpp
ArthurSonzogni/InTheCube
c4a35096d962d23f6211802970ee44f77d29e38a
[ "MIT" ]
2
2020-02-17T12:47:33.000Z
2021-09-07T18:16:52.000Z
// Copyright 2020 Arthur Sonzogni. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file. #include "game/LevelListLoader.hpp" #include <fstream> #include <iostream> #include "game/Resource.hpp" std::vector<std::string> LevelListLoader() { std::ifstream file(ResourcePath() + "/lvl/LevelList"); if (!file) { std::cerr << "No level list file" << std::endl; return {}; } std::vector<std::string> result; std::string line; while (getline(file, line)) { result.push_back(ResourcePath() + "/lvl/" + line); } return result; }
23.769231
78
0.669903
f26663b27836b964aeaa957327dbff9365075dc0
12,757
cpp
C++
bin/windows/cpp/obj/src/openfl/display/Tilesheet.cpp
DrSkipper/twogames
916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b
[ "MIT" ]
null
null
null
bin/windows/cpp/obj/src/openfl/display/Tilesheet.cpp
DrSkipper/twogames
916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b
[ "MIT" ]
null
null
null
bin/windows/cpp/obj/src/openfl/display/Tilesheet.cpp
DrSkipper/twogames
916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b
[ "MIT" ]
null
null
null
#include <hxcpp.h> #ifndef INCLUDED_flash_Lib #include <flash/Lib.h> #endif #ifndef INCLUDED_flash_display_BitmapData #include <flash/display/BitmapData.h> #endif #ifndef INCLUDED_flash_display_Graphics #include <flash/display/Graphics.h> #endif #ifndef INCLUDED_flash_display_IBitmapDrawable #include <flash/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_flash_geom_Point #include <flash/geom/Point.h> #endif #ifndef INCLUDED_flash_geom_Rectangle #include <flash/geom/Rectangle.h> #endif #ifndef INCLUDED_openfl_display_Tilesheet #include <openfl/display/Tilesheet.h> #endif namespace openfl{ namespace display{ Void Tilesheet_obj::__construct(::flash::display::BitmapData image) { HX_STACK_PUSH("Tilesheet::new","openfl/display/Tilesheet.hx",36); { HX_STACK_LINE(38) this->__bitmap = image; HX_STACK_LINE(39) this->__handle = ::openfl::display::Tilesheet_obj::lime_tilesheet_create(image->__handle); HX_STACK_LINE(41) this->_bitmapWidth = this->__bitmap->get_width(); HX_STACK_LINE(42) this->_bitmapHeight = this->__bitmap->get_height(); HX_STACK_LINE(44) this->_tilePoints = Array_obj< ::Dynamic >::__new(); HX_STACK_LINE(45) this->_tiles = Array_obj< ::Dynamic >::__new(); HX_STACK_LINE(46) this->_tileUVs = Array_obj< ::Dynamic >::__new(); } ; return null(); } Tilesheet_obj::~Tilesheet_obj() { } Dynamic Tilesheet_obj::__CreateEmpty() { return new Tilesheet_obj; } hx::ObjectPtr< Tilesheet_obj > Tilesheet_obj::__new(::flash::display::BitmapData image) { hx::ObjectPtr< Tilesheet_obj > result = new Tilesheet_obj(); result->__construct(image); return result;} Dynamic Tilesheet_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Tilesheet_obj > result = new Tilesheet_obj(); result->__construct(inArgs[0]); return result;} ::flash::geom::Rectangle Tilesheet_obj::getTileUVs( int index){ HX_STACK_PUSH("Tilesheet::getTileUVs","openfl/display/Tilesheet.hx",77); HX_STACK_THIS(this); HX_STACK_ARG(index,"index"); HX_STACK_LINE(77) return this->_tileUVs->__get(index).StaticCast< ::flash::geom::Rectangle >(); } HX_DEFINE_DYNAMIC_FUNC1(Tilesheet_obj,getTileUVs,return ) ::flash::geom::Rectangle Tilesheet_obj::getTileRect( int index){ HX_STACK_PUSH("Tilesheet::getTileRect","openfl/display/Tilesheet.hx",73); HX_STACK_THIS(this); HX_STACK_ARG(index,"index"); HX_STACK_LINE(73) return this->_tiles->__get(index).StaticCast< ::flash::geom::Rectangle >(); } HX_DEFINE_DYNAMIC_FUNC1(Tilesheet_obj,getTileRect,return ) ::flash::geom::Point Tilesheet_obj::getTileCenter( int index){ HX_STACK_PUSH("Tilesheet::getTileCenter","openfl/display/Tilesheet.hx",69); HX_STACK_THIS(this); HX_STACK_ARG(index,"index"); HX_STACK_LINE(69) return this->_tilePoints->__get(index).StaticCast< ::flash::geom::Point >(); } HX_DEFINE_DYNAMIC_FUNC1(Tilesheet_obj,getTileCenter,return ) Void Tilesheet_obj::drawTiles( ::flash::display::Graphics graphics,Array< Float > tileData,hx::Null< bool > __o_smooth,hx::Null< int > __o_flags){ bool smooth = __o_smooth.Default(false); int flags = __o_flags.Default(0); HX_STACK_PUSH("Tilesheet::drawTiles","openfl/display/Tilesheet.hx",62); HX_STACK_THIS(this); HX_STACK_ARG(graphics,"graphics"); HX_STACK_ARG(tileData,"tileData"); HX_STACK_ARG(smooth,"smooth"); HX_STACK_ARG(flags,"flags"); { HX_STACK_LINE(62) graphics->drawTiles(hx::ObjectPtr<OBJ_>(this),tileData,smooth,flags); } return null(); } HX_DEFINE_DYNAMIC_FUNC4(Tilesheet_obj,drawTiles,(void)) int Tilesheet_obj::addTileRect( ::flash::geom::Rectangle rectangle,::flash::geom::Point centerPoint){ HX_STACK_PUSH("Tilesheet::addTileRect","openfl/display/Tilesheet.hx",51); HX_STACK_THIS(this); HX_STACK_ARG(rectangle,"rectangle"); HX_STACK_ARG(centerPoint,"centerPoint"); HX_STACK_LINE(53) this->_tiles->push(rectangle); HX_STACK_LINE(54) if (((centerPoint == null()))){ HX_STACK_LINE(54) this->_tilePoints->push(::openfl::display::Tilesheet_obj::defaultRatio); } else{ HX_STACK_LINE(55) this->_tilePoints->push(::flash::geom::Point_obj::__new((Float(centerPoint->x) / Float(rectangle->width)),(Float(centerPoint->y) / Float(rectangle->height)))); } HX_STACK_LINE(56) this->_tileUVs->push(::flash::geom::Rectangle_obj::__new((Float(rectangle->get_left()) / Float(this->_bitmapWidth)),(Float(rectangle->get_top()) / Float(this->_bitmapHeight)),(Float(rectangle->get_right()) / Float(this->_bitmapWidth)),(Float(rectangle->get_bottom()) / Float(this->_bitmapHeight)))); HX_STACK_LINE(57) return ::openfl::display::Tilesheet_obj::lime_tilesheet_add_rect(this->__handle,rectangle,centerPoint); } HX_DEFINE_DYNAMIC_FUNC2(Tilesheet_obj,addTileRect,return ) int Tilesheet_obj::TILE_SCALE; int Tilesheet_obj::TILE_ROTATION; int Tilesheet_obj::TILE_RGB; int Tilesheet_obj::TILE_ALPHA; int Tilesheet_obj::TILE_TRANS_2x2; int Tilesheet_obj::TILE_BLEND_NORMAL; int Tilesheet_obj::TILE_BLEND_ADD; int Tilesheet_obj::TILE_BLEND_MULTIPLY; int Tilesheet_obj::TILE_BLEND_SCREEN; ::flash::geom::Point Tilesheet_obj::defaultRatio; Dynamic Tilesheet_obj::lime_tilesheet_create; Dynamic Tilesheet_obj::lime_tilesheet_add_rect; Tilesheet_obj::Tilesheet_obj() { } void Tilesheet_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Tilesheet); HX_MARK_MEMBER_NAME(_tileUVs,"_tileUVs"); HX_MARK_MEMBER_NAME(_tiles,"_tiles"); HX_MARK_MEMBER_NAME(_tilePoints,"_tilePoints"); HX_MARK_MEMBER_NAME(_bitmapWidth,"_bitmapWidth"); HX_MARK_MEMBER_NAME(_bitmapHeight,"_bitmapHeight"); HX_MARK_MEMBER_NAME(__handle,"__handle"); HX_MARK_MEMBER_NAME(__bitmap,"__bitmap"); HX_MARK_END_CLASS(); } void Tilesheet_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(_tileUVs,"_tileUVs"); HX_VISIT_MEMBER_NAME(_tiles,"_tiles"); HX_VISIT_MEMBER_NAME(_tilePoints,"_tilePoints"); HX_VISIT_MEMBER_NAME(_bitmapWidth,"_bitmapWidth"); HX_VISIT_MEMBER_NAME(_bitmapHeight,"_bitmapHeight"); HX_VISIT_MEMBER_NAME(__handle,"__handle"); HX_VISIT_MEMBER_NAME(__bitmap,"__bitmap"); } Dynamic Tilesheet_obj::__Field(const ::String &inName,bool inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"_tiles") ) { return _tiles; } break; case 8: if (HX_FIELD_EQ(inName,"_tileUVs") ) { return _tileUVs; } if (HX_FIELD_EQ(inName,"__handle") ) { return __handle; } if (HX_FIELD_EQ(inName,"__bitmap") ) { return __bitmap; } break; case 9: if (HX_FIELD_EQ(inName,"drawTiles") ) { return drawTiles_dyn(); } break; case 10: if (HX_FIELD_EQ(inName,"getTileUVs") ) { return getTileUVs_dyn(); } break; case 11: if (HX_FIELD_EQ(inName,"getTileRect") ) { return getTileRect_dyn(); } if (HX_FIELD_EQ(inName,"addTileRect") ) { return addTileRect_dyn(); } if (HX_FIELD_EQ(inName,"_tilePoints") ) { return _tilePoints; } break; case 12: if (HX_FIELD_EQ(inName,"defaultRatio") ) { return defaultRatio; } if (HX_FIELD_EQ(inName,"_bitmapWidth") ) { return _bitmapWidth; } break; case 13: if (HX_FIELD_EQ(inName,"getTileCenter") ) { return getTileCenter_dyn(); } if (HX_FIELD_EQ(inName,"_bitmapHeight") ) { return _bitmapHeight; } break; case 21: if (HX_FIELD_EQ(inName,"lime_tilesheet_create") ) { return lime_tilesheet_create; } break; case 23: if (HX_FIELD_EQ(inName,"lime_tilesheet_add_rect") ) { return lime_tilesheet_add_rect; } } return super::__Field(inName,inCallProp); } Dynamic Tilesheet_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"_tiles") ) { _tiles=inValue.Cast< Array< ::Dynamic > >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"_tileUVs") ) { _tileUVs=inValue.Cast< Array< ::Dynamic > >(); return inValue; } if (HX_FIELD_EQ(inName,"__handle") ) { __handle=inValue.Cast< Dynamic >(); return inValue; } if (HX_FIELD_EQ(inName,"__bitmap") ) { __bitmap=inValue.Cast< ::flash::display::BitmapData >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"_tilePoints") ) { _tilePoints=inValue.Cast< Array< ::Dynamic > >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"defaultRatio") ) { defaultRatio=inValue.Cast< ::flash::geom::Point >(); return inValue; } if (HX_FIELD_EQ(inName,"_bitmapWidth") ) { _bitmapWidth=inValue.Cast< int >(); return inValue; } break; case 13: if (HX_FIELD_EQ(inName,"_bitmapHeight") ) { _bitmapHeight=inValue.Cast< int >(); return inValue; } break; case 21: if (HX_FIELD_EQ(inName,"lime_tilesheet_create") ) { lime_tilesheet_create=inValue.Cast< Dynamic >(); return inValue; } break; case 23: if (HX_FIELD_EQ(inName,"lime_tilesheet_add_rect") ) { lime_tilesheet_add_rect=inValue.Cast< Dynamic >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void Tilesheet_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_CSTRING("_tileUVs")); outFields->push(HX_CSTRING("_tiles")); outFields->push(HX_CSTRING("_tilePoints")); outFields->push(HX_CSTRING("_bitmapWidth")); outFields->push(HX_CSTRING("_bitmapHeight")); outFields->push(HX_CSTRING("__handle")); outFields->push(HX_CSTRING("__bitmap")); super::__GetFields(outFields); }; static ::String sStaticFields[] = { HX_CSTRING("TILE_SCALE"), HX_CSTRING("TILE_ROTATION"), HX_CSTRING("TILE_RGB"), HX_CSTRING("TILE_ALPHA"), HX_CSTRING("TILE_TRANS_2x2"), HX_CSTRING("TILE_BLEND_NORMAL"), HX_CSTRING("TILE_BLEND_ADD"), HX_CSTRING("TILE_BLEND_MULTIPLY"), HX_CSTRING("TILE_BLEND_SCREEN"), HX_CSTRING("defaultRatio"), HX_CSTRING("lime_tilesheet_create"), HX_CSTRING("lime_tilesheet_add_rect"), String(null()) }; static ::String sMemberFields[] = { HX_CSTRING("getTileUVs"), HX_CSTRING("getTileRect"), HX_CSTRING("getTileCenter"), HX_CSTRING("drawTiles"), HX_CSTRING("addTileRect"), HX_CSTRING("_tileUVs"), HX_CSTRING("_tiles"), HX_CSTRING("_tilePoints"), HX_CSTRING("_bitmapWidth"), HX_CSTRING("_bitmapHeight"), HX_CSTRING("__handle"), HX_CSTRING("__bitmap"), String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Tilesheet_obj::__mClass,"__mClass"); HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_SCALE,"TILE_SCALE"); HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_ROTATION,"TILE_ROTATION"); HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_RGB,"TILE_RGB"); HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_ALPHA,"TILE_ALPHA"); HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_TRANS_2x2,"TILE_TRANS_2x2"); HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_NORMAL,"TILE_BLEND_NORMAL"); HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_ADD,"TILE_BLEND_ADD"); HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_MULTIPLY,"TILE_BLEND_MULTIPLY"); HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_SCREEN,"TILE_BLEND_SCREEN"); HX_MARK_MEMBER_NAME(Tilesheet_obj::defaultRatio,"defaultRatio"); HX_MARK_MEMBER_NAME(Tilesheet_obj::lime_tilesheet_create,"lime_tilesheet_create"); HX_MARK_MEMBER_NAME(Tilesheet_obj::lime_tilesheet_add_rect,"lime_tilesheet_add_rect"); }; static void sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Tilesheet_obj::__mClass,"__mClass"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_SCALE,"TILE_SCALE"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_ROTATION,"TILE_ROTATION"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_RGB,"TILE_RGB"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_ALPHA,"TILE_ALPHA"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_TRANS_2x2,"TILE_TRANS_2x2"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_NORMAL,"TILE_BLEND_NORMAL"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_ADD,"TILE_BLEND_ADD"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_MULTIPLY,"TILE_BLEND_MULTIPLY"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_SCREEN,"TILE_BLEND_SCREEN"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::defaultRatio,"defaultRatio"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::lime_tilesheet_create,"lime_tilesheet_create"); HX_VISIT_MEMBER_NAME(Tilesheet_obj::lime_tilesheet_add_rect,"lime_tilesheet_add_rect"); }; Class Tilesheet_obj::__mClass; void Tilesheet_obj::__register() { hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("openfl.display.Tilesheet"), hx::TCanCast< Tilesheet_obj> ,sStaticFields,sMemberFields, &__CreateEmpty, &__Create, &super::__SGetClass(), 0, sMarkStatics, sVisitStatics); } void Tilesheet_obj::__boot() { TILE_SCALE= (int)1; TILE_ROTATION= (int)2; TILE_RGB= (int)4; TILE_ALPHA= (int)8; TILE_TRANS_2x2= (int)16; TILE_BLEND_NORMAL= (int)0; TILE_BLEND_ADD= (int)65536; TILE_BLEND_MULTIPLY= (int)131072; TILE_BLEND_SCREEN= (int)262144; defaultRatio= ::flash::geom::Point_obj::__new((int)0,(int)0); lime_tilesheet_create= ::flash::Lib_obj::load(HX_CSTRING("lime"),HX_CSTRING("lime_tilesheet_create"),(int)1); lime_tilesheet_add_rect= ::flash::Lib_obj::load(HX_CSTRING("lime"),HX_CSTRING("lime_tilesheet_add_rect"),(int)3); } } // end namespace openfl } // end namespace display
35.143251
300
0.767108
f26798529f0a2c0bbae58fdf5292113f7510975c
431
cpp
C++
src/mesh/mesh.cpp
ycjungSubhuman/Kinect-Face
b582bd8572e998617b5a0d197b4ac9bd4a9b42be
[ "CNRI-Python" ]
7
2018-08-12T22:05:26.000Z
2021-05-14T08:39:32.000Z
src/mesh/mesh.cpp
ycjungSubhuman/Kinect-Face
b582bd8572e998617b5a0d197b4ac9bd4a9b42be
[ "CNRI-Python" ]
null
null
null
src/mesh/mesh.cpp
ycjungSubhuman/Kinect-Face
b582bd8572e998617b5a0d197b4ac9bd4a9b42be
[ "CNRI-Python" ]
2
2019-02-14T08:29:16.000Z
2019-03-01T07:11:17.000Z
#include <Eigen/Core> #include <Eigen/Geometry> #include "mesh/mesh.h" namespace telef::mesh { void ColorMesh::applyTransform(Eigen::MatrixXf transform) { Eigen::Map<Eigen::Matrix3Xf> v(position.data(), 3, position.size() / 3); Eigen::Matrix3Xf result = (transform * v.colwise().homogeneous()).colwise().hnormalized(); position = Eigen::Map<Eigen::VectorXf>{result.data(), result.size()}; } } // namespace telef::mesh
33.153846
74
0.698376
f26b97db07cd2c2457a94eb2ed16d8becd085010
963
cpp
C++
package/statistics/statistics_gateway/deprecated/btp_deprecated_gateway_multiton.cpp
mambaru/wfc_core
0c3e7fba82a9bb1580582968efae02ef7fabc87a
[ "MIT" ]
null
null
null
package/statistics/statistics_gateway/deprecated/btp_deprecated_gateway_multiton.cpp
mambaru/wfc_core
0c3e7fba82a9bb1580582968efae02ef7fabc87a
[ "MIT" ]
5
2019-12-06T01:01:01.000Z
2021-04-20T21:16:34.000Z
package/statistics/statistics_gateway/deprecated/btp_deprecated_gateway_multiton.cpp
mambaru/wfc_core
0c3e7fba82a9bb1580582968efae02ef7fabc87a
[ "MIT" ]
null
null
null
// // Author: Vladimir Migashko <migashko@gmail.com>, (C) 2013-2015 // // Copyright: See COPYING file that comes with this distribution // #include "btp_deprecated_gateway_multiton.hpp" #include "btp_deprecated_gateway.hpp" #include <wfc/module/multiton.hpp> #include <wfc/module/instance.hpp> #include <wfc/name.hpp> namespace wfc{ namespace core{ namespace { WFC_NAME2(component_name, "btp-deprecated-gateway") class impl : public ::wfc::jsonrpc::gateway_multiton< component_name, gateway::btp_deprecated_method_list, gateway::btp_deprecated_interface > { public: virtual std::string interface_name() const override { return std::string("wfc::btp::ibtp"); } virtual std::string description() const override { return "Gateway for BTP system"; } }; } btp_deprecated_gateway_multiton::btp_deprecated_gateway_multiton() : wfc::component( std::make_shared<impl>() ) { } }}
20.934783
66
0.695742
f26c536c9a9135d1e2875932cd0d32332bcb451f
3,571
cpp
C++
game-emu-common/src/binarytreememorymap.cpp
Dudejoe870/game-emu
153b7f9b7bc56042cc6d41187688aa1d9a612830
[ "MIT" ]
1
2022-03-28T21:03:10.000Z
2022-03-28T21:03:10.000Z
game-emu-common/src/binarytreememorymap.cpp
Dudejoe870/game-emu
153b7f9b7bc56042cc6d41187688aa1d9a612830
[ "MIT" ]
null
null
null
game-emu-common/src/binarytreememorymap.cpp
Dudejoe870/game-emu
153b7f9b7bc56042cc6d41187688aa1d9a612830
[ "MIT" ]
null
null
null
#include <game-emu/common/physicalmemorymap.h> namespace GameEmu::Common { PhysicalMemoryMap::Entry* BinaryTreeMemoryMap::Map(u8* hostReadMemory, u8* hostWriteMemory, u64 size, u64 baseAddress, Entry::ReadEventFunction readEvent, Entry::WriteEventFunction writeEvent) { entries.push_back(Entry(baseAddress &addressMask, hostReadMemory, hostWriteMemory, size, readEvent, writeEvent)); return &entries[entries.size() - 1]; } void BinaryTreeMemoryMap::Unmap(const Entry* entry) { std::vector<Entry>::iterator entryIndex = std::find(entries.begin(), entries.end(), *entry); if (entryIndex == entries.end()) return; entries.erase(entryIndex); } std::shared_ptr<BinaryTreeMemoryMap::BinaryTree::Node> BinaryTreeMemoryMap::sortedVectorToBinaryTree(std::vector<Entry>& entries, s64 start, s64 end) { if (start > end) return nullptr; else if (start == end) return std::make_shared<BinaryTree::Node>(entries[start]); s64 mid = (start + end) / 2; std::shared_ptr<BinaryTree::Node> root = std::make_shared<BinaryTree::Node>(entries[mid]); root->left = sortedVectorToBinaryTree(entries, start, mid - 1); root->right = sortedVectorToBinaryTree(entries, mid + 1, end); return root; } void BinaryTreeMemoryMap::Update() { if (!entries.empty()) { std::sort(entries.begin(), entries.end()); // Rebalance the Binary Search Tree tree.root = sortedVectorToBinaryTree(entries, 0, entries.size() - 1); } } /* 8-bit Write */ void BinaryTreeMemoryMap::WriteU8(u8 value, u64 address) { WriteImpl<u8, std::endian::native>(static_cast<u64>(value), address); } /* 8-bit Read */ u8 BinaryTreeMemoryMap::ReadU8(u64 address) { return static_cast<u8>(ReadImpl<u8, std::endian::native>(address)); } /* 16-bit Write */ void BinaryTreeMemoryMap::WriteU16BigEndianImpl(u16 value, u64 address) { WriteImpl<u16, std::endian::big>(static_cast<u64>(value), address); } void BinaryTreeMemoryMap::WriteU16LittleEndianImpl(u16 value, u64 address) { WriteImpl<u16, std::endian::little>(static_cast<u64>(value), address); } /* 16-bit Read */ u16 BinaryTreeMemoryMap::ReadU16BigEndianImpl(u64 address) { return static_cast<u16>(ReadImpl<u16, std::endian::big>(address)); } u16 BinaryTreeMemoryMap::ReadU16LittleEndianImpl(u64 address) { return static_cast<u16>(ReadImpl<u16, std::endian::little>(address)); } /* 32-bit Write */ void BinaryTreeMemoryMap::WriteU32BigEndianImpl(u32 value, u64 address) { WriteImpl<u32, std::endian::big>(static_cast<u64>(value), address); } void BinaryTreeMemoryMap::WriteU32LittleEndianImpl(u32 value, u64 address) { WriteImpl<u32, std::endian::little>(static_cast<u64>(value), address); } /* 32-bit Read */ u32 BinaryTreeMemoryMap::ReadU32BigEndianImpl(u64 address) { return static_cast<u32>(ReadImpl<u32, std::endian::big>(address)); } u32 BinaryTreeMemoryMap::ReadU32LittleEndianImpl(u64 address) { return static_cast<u32>(ReadImpl<u32, std::endian::little>(address)); } /* 64-bit Write */ void BinaryTreeMemoryMap::WriteU64BigEndianImpl(u64 value, u64 address) { WriteImpl<u64, std::endian::big>(value, address); } void BinaryTreeMemoryMap::WriteU64LittleEndianImpl(u64 value, u64 address) { WriteImpl<u64, std::endian::little>(value, address); } /* 64-bit Read */ u64 BinaryTreeMemoryMap::ReadU64BigEndianImpl(u64 address) { return ReadImpl<u64, std::endian::big>(address); } u64 BinaryTreeMemoryMap::ReadU64LittleEndianImpl(u64 address) { return ReadImpl<u64, std::endian::little>(address); } }
25.147887
150
0.720806
f26e1bf69404f9ff4878ce369c1a86cdd8c60546
5,364
hpp
C++
patterns/2020_10_19/prefab/include/prefab/IEntity.hpp
liff-engineer/articles
ad3386ef9cda5083793f485e309a9f85ab36f664
[ "MIT" ]
2
2020-12-01T06:44:41.000Z
2021-11-22T06:07:52.000Z
patterns/2020_10_19/prefab/include/prefab/IEntity.hpp
liff-engineer/articles
ad3386ef9cda5083793f485e309a9f85ab36f664
[ "MIT" ]
null
null
null
patterns/2020_10_19/prefab/include/prefab/IEntity.hpp
liff-engineer/articles
ad3386ef9cda5083793f485e309a9f85ab36f664
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <tuple> #include <memory> #include "IComponent.hpp" namespace prefab { //用来操作tuple的foreach算法 template <typename Tuple, typename F, std::size_t ...Indices> void for_each_impl(Tuple&& tuple, F&& f, std::index_sequence<Indices...>) { using swallow = int[]; (void)swallow { 1, (f(std::get<Indices>(std::forward<Tuple>(tuple))), void(), int{})... }; } template <typename Tuple, typename F> void for_each(Tuple&& tuple, F&& f) { constexpr std::size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value; for_each_impl(std::forward<Tuple>(tuple), std::forward<F>(f), std::make_index_sequence<N>{}); } //实体基类 class IEntity { public: virtual ~IEntity() = default; //实现类型Code virtual HashedStringLiteral implTypeCode() const noexcept = 0; //根据类型获取数据组件 virtual IComponentBase* component(HashedStringLiteral typeCode) noexcept = 0; }; //实体集合基类 class IEntitys { public: virtual ~IEntitys() = default; //实现类型Code virtual HashedStringLiteral implTypeCode() const noexcept = 0; //包含的实体(实体生命周期由集合类管理) virtual std::vector<IEntity*> entitys() noexcept = 0; }; //引用语义的实体类,不管理实体生命周期 template<typename... Ts> class EntityView { std::tuple<IComponent<Ts>* ...> m_components; private: //从实体中获取并设置组件接口 template<typename T> void setComponentOf(IEntity* entity, IComponent<T>*& component) { auto typeCode = HashedTypeNameOf<T>(); auto componentBase = entity->component(typeCode); if (componentBase == nullptr || componentBase->typeCode() != typeCode) { component = nullptr; return; } component = static_cast<IComponent<T>*>(componentBase); } public: EntityView() = default; explicit EntityView(IEntity* entity) { if (!entity) return; for_each(m_components, [&](auto& component) { this->setComponentOf(entity, component); }); } //判断是否所有组件都存在且有效 explicit operator bool() const noexcept { bool result = true; for_each(m_components, [&](auto component) { result &= (component != nullptr); }); return result; } template<typename T> decltype(auto) component() const noexcept { return std::get<IComponent<T>*>(m_components); } template<typename T> decltype(auto) component() noexcept { return std::get<IComponent<T>*>(m_components); } template<typename T> decltype(auto) exist() const noexcept { return component<T>()->exist(); } template<typename T> decltype(auto) view() const { return component<T>()->view(); } template<typename T> decltype(auto) remove() noexcept { return component<T>()->remove(); } template<typename T> decltype(auto) assign(T const& v) noexcept { return component<T>()->assign(v); } template<typename T> decltype(auto) replace(T const& v) noexcept { return component<T>()->replace(v); } }; class IRepository; //值语义的实体类,使用智能指针管理实体的生命周期 template<typename... Ts> class Entity :public EntityView<Ts...> { friend class IRepository; std::unique_ptr<IEntity> m_impl; public: Entity() = default; explicit Entity(std::unique_ptr<IEntity>&& entity) :EntityView(entity.get()), m_impl(std::move(entity)) {}; }; //实体容器 template<typename... Ts> class Entitys { friend class IRepository; using entity_t = EntityView<Ts...>; std::vector<entity_t> m_entitys; std::unique_ptr<IEntitys> m_impl; public: Entitys() = default; explicit Entitys(std::unique_ptr<IEntitys>&& entitys) :m_impl(std::move(entitys)) { if (m_impl == nullptr) return; auto items = m_impl->entitys(); m_entitys.reserve(items.size()); for (auto e : items) { m_entitys.emplace_back(entity_t{ e }); } } decltype(auto) empty() const noexcept { return m_entitys.empty(); } decltype(auto) size() const noexcept { return m_entitys.size(); } decltype(auto) at(std::size_t i) const { return m_entitys.at(i); } decltype(auto) operator[](std::size_t i) const noexcept { return m_entitys[i]; } decltype(auto) begin() const noexcept { return m_entitys.begin(); } decltype(auto) end() const noexcept { return m_entitys.end(); } decltype(auto) begin() noexcept { return m_entitys.begin(); } decltype(auto) end() noexcept { return m_entitys.end(); } explicit operator bool() const noexcept { return (m_impl != nullptr); } }; }
27.228426
89
0.543624
f271842da1c802a66058f6006e2a868b865d0c12
2,388
hpp
C++
include/Network/Session.hpp
Lisoph/MORL
f1c4f9a1c16df236495666fd46d76da6ac9a32af
[ "MIT" ]
1
2015-05-24T17:20:06.000Z
2015-05-24T17:20:06.000Z
include/Network/Session.hpp
Lisoph/MORL
f1c4f9a1c16df236495666fd46d76da6ac9a32af
[ "MIT" ]
1
2015-05-15T20:29:58.000Z
2015-05-15T20:29:58.000Z
include/Network/Session.hpp
Lisoph/MORL
f1c4f9a1c16df236495666fd46d76da6ac9a32af
[ "MIT" ]
null
null
null
#pragma once #include "UdpSocket.hpp" #include "IPEndpoint.hpp" #include "Network/SessionState.hpp" #include <cstdint> #include <functional> #include <stack> namespace MORL { class Game; namespace Network { class Session; class StateNotRunning : public SessionState { public: StateNotRunning(Session &session) : SessionState(session) {} void Update() override {} }; class Session { public: static constexpr uint16_t ServerSocketPort = 5666; using OwnedSessionState = std::unique_ptr<SessionState>; using SessionStateStack = std::stack<OwnedSessionState>; Session(MORL::Game &game); Session(Session const &) = delete; Session(Session && other); ~Session(); inline UdpSocket &Socket() { return mSocket; } inline MORL::Game &Game() { return mGame; } inline bool IsConnectedToServer() const { return mConnectedToServer; } inline void ConnectedToServer(IPEndpoint const &server) { mConnectedToServer = true; mServer = server; } inline IPEndpoint const &Server() const { return mServer; } template <typename S> inline void PushState(S const &state) { mStates.push(MakeUnique<S>(state)); } template <typename S> inline void PushState(S && state) { mStates.push(MakeUnique<S>(std::move(state))); } template <typename S> inline void ReplaceState(S const &state) { if(mStates.size() >= 1) { mStates.pop(); } mStates.push(MakeUnique<S>(state)); } template <typename S> inline void ReplaceState(S && state) { if(mStates.size() >= 1) { mStates.pop(); } mStates.push(MakeUnique<S>(std::move(state))); } void GoBack(); /** * Update internal stuff, call this once a frame */ void Update(); private: inline SessionState &CurrentState() { return *(mStates.top().get()); } private: // How this socket is used varies from server to client side UdpSocket mSocket; MORL::Game &mGame; SessionStateStack mStates; // Only used by client IPEndpoint mServer; // Only used by client bool mConnectedToServer = false; }; } }
22.528302
66
0.588358
f275bc1ce15ec5440151d3e7013dd7a10fdc3923
152
cpp
C++
12_Sorting/HighScoreEntry.cpp
alyoshenka/CodeDesign
beb8bbf79b14cbf1cad26b1e8f58fd47c417ccdd
[ "MIT" ]
null
null
null
12_Sorting/HighScoreEntry.cpp
alyoshenka/CodeDesign
beb8bbf79b14cbf1cad26b1e8f58fd47c417ccdd
[ "MIT" ]
null
null
null
12_Sorting/HighScoreEntry.cpp
alyoshenka/CodeDesign
beb8bbf79b14cbf1cad26b1e8f58fd47c417ccdd
[ "MIT" ]
null
null
null
#include "HighScoreEntry.h" HighScoreEntry::HighScoreEntry() { name = "noName"; score = -1; level = -1; } HighScoreEntry::~HighScoreEntry() { }
9.5
33
0.657895
f27a190e89511dc1e7eaf4ac352322b7f0cc9244
9,108
cpp
C++
src/Player.cpp
osbixaodaunb/RGBender-2.0
9c5e33cba50541b8288e29f56562820b3d7b0e55
[ "MIT" ]
4
2017-05-15T19:33:28.000Z
2017-05-15T23:33:04.000Z
src/Player.cpp
osbixaodaunb/RGBender-2.0
9c5e33cba50541b8288e29f56562820b3d7b0e55
[ "MIT" ]
4
2017-10-04T14:29:18.000Z
2017-10-04T14:43:52.000Z
src/Player.cpp
unbgames/RGBender
9c5e33cba50541b8288e29f56562820b3d7b0e55
[ "MIT" ]
4
2017-05-15T19:33:37.000Z
2017-08-18T14:12:41.000Z
#include "Player.h" #include "SDLGameObject.h" #include "LoaderParams.h" #include "InputHandler.h" #include "Bullet.h" #include "Game.h" #include "Log.h" #include "Enemy.h" #include "PlayState.h" #include "Physics.h" #include "AudioManager.h" #include "GameOverState.h" #include "Childmaiden.h" #include "Timer.h" #include <string> #include <SDL2/SDL.h> #include <iostream> #include <cmath> using namespace std; using namespace engine; Player::Player() : SDLGameObject(){ m_fireRate = 500; m_isShieldActive = false; m_bulletVenemous = false; for(int i=1; i<7; i++){ TextureManager::Instance().load("assets/player_health" + to_string(i) + ".png", "health" + to_string(i), Game::Instance().getRenderer()); } TextureManager::Instance().load("assets/ataque_protagonista_preto.png", "bullet", Game::Instance().getRenderer()); TextureManager::Instance().load("assets/health.png", "health", Game::Instance().getRenderer()); TextureManager::Instance().load("assets/circle.png", "instance", Game::Instance().getRenderer()); TextureManager::Instance().load("assets/Cadeira_frente.png", "chairBullet", Game::Instance().getRenderer()); INFO("Player inicializado"); m_life = 6; canMove = true; } void Player::load(const LoaderParams* pParams){ SDLGameObject::load(pParams); } void Player::draw(){ TextureManager::Instance().draw("instance", 100, 600, 100, 100, Game::Instance().getRenderer()); if(m_isShieldActive){ TextureManager::Instance().draw("shield", getPosition().getX()-17, getPosition().getY()-10, 110, 110, Game::Instance().getRenderer()); TextureManager::Instance().draw("brownskill", 110, 610, 80, 80, Game::Instance().getRenderer()); } if(m_fireRate != 500){ TextureManager::Instance().draw("redskill", 110, 610, 80, 80, Game::Instance().getRenderer()); } if(bullet!= NULL && bullet->getVenemous() == true){ TextureManager::Instance().draw("greenskill", 110, 610, 80, 80, Game::Instance().getRenderer()); } TextureManager::Instance().draw("health" +to_string(m_life), 1000, 620, 180, 80, Game::Instance().getRenderer()); SDLGameObject::draw(); } void Player::update(){ //std::cout << "Player top: " << getPosition().getX() << std::endl; if(m_life <= 0){ Game::Instance().getStateMachine()->changeState(new GameOverState()); } if(Game::Instance().getStateMachine()->currentState()->getStateID() == "PLAY"){ PlayState *playState = dynamic_cast<PlayState*>(Game::Instance().getStateMachine()->currentState()); if(playState->getLevel() != NULL && m_boss == NULL){ INFO("Xuxa is set"); m_boss = playState->getLevel()->getXuxa(); } } if(!canMove){ int time = Timer::Instance().step() - getStunTime(); if(time >= 700){ canMove = true; } rotateTowards(); } if(shieldHits > 5 && m_isShieldActive){ TextureManager::Instance().clearFromTextureMap("shield"); shieldHits = 0; m_isShieldActive = false; } setPoison(); if(canMove){ handleInput(); } // if(m_bulletVenemous == true) // INFO("FOI"); SDLGameObject::update(); } void Player::setBulletVenemous(bool isVenemous){ m_bulletVenemous = isVenemous; bullet->setVenemous(isVenemous); if(isVenemous == false){ uint8_t* pixels = new uint8_t[3]; pixels[0] = 255; pixels[1] = 255; pixels[2] = 255; TheTextureManager::Instance().changeColorPixels(pixels, "RAG"); } } void Player::setPoison(){ if(bullet != NULL && bullet->getVenemous() && bullet->isActive()){ if(Timer::Instance().step() <= m_boss->getEnemyTime() && bullet->m_collided){ m_boss->takeDamage(1); int score = Game::Instance().getScore(); Game::Instance().setScore(score + 5); TextureManager::Instance().loadText(std::to_string(Game::Instance().getScore()), "assets/fonts/Lato-Regular.ttf", "score", {255,255,255}, 50, Game::Instance().getRenderer()); INFO(m_boss->getHealth()); }else if(Timer::Instance().step() >= m_boss->getEnemyTime()){ //bullet->m_collided = false; //bullet->setVenemous(false); } } } void Player::clean(){ SDLGameObject::clean(); } void Player::handleInput(){ move(); m_numFrames = 4; m_currentFrame = 1; if(m_velocity == Vector2D(0, 0)){ rotateTowards(); } else { Vector2D vec[] = {Vector2D(0,-1), Vector2D(1, -1).norm(), Vector2D(1, 0), Vector2D(1, 1).norm(), Vector2D(0, 1), Vector2D(-1, 1).norm(), Vector2D(-1, 0), Vector2D(-1, -1).norm()}; for(int i=0; i<8; i++){ if(m_velocity.norm() == vec[i]){ changeSprite(i); } } int tmp = m_currentFrame; m_currentFrame = 1 + int(((SDL_GetTicks() / 100) % (m_numFrames-1))); } useSkill(); if(InputHandler::Instance().getMouseButtonState(LEFT, m_fireRate)){ count = Timer::Instance().step() + 300; AudioManager::Instance().playChunk("assets/sounds/spray.wav"); INFO("FIRE RATE: " + m_fireRate); Vector2D pivot = Vector2D(m_width/2+m_position.getX(), m_height/2 + m_position.getY()); Vector2D target = InputHandler::Instance().getMousePosition() - pivot; target = target.norm(); bullet = bulletCreator.create(m_boss); //bullet->setVenemous(m_bulletVenemous); bullet->load(target, Vector2D(m_width/2+m_position.getX(), m_height/2 + m_position.getY())); Game::Instance().getStateMachine()->currentState()->addGameObject(bullet); } } bool inside(double angle, double value){ return value > angle - 22.5 && value < angle + 22.5; } void Player::changeSprite(int index){ m_flip = false; switch(index){ case 0: // UP m_textureID = "up"; break; case 1: // UP-RIGHT m_textureID = "upright"; break; case 2: // RIGHT m_flip = true; m_textureID = "left"; break; case 3: // DOWN-RIGHT m_flip = true; m_textureID = "downleft"; break; case 4: // DOWN m_textureID = "down"; break; case 5: // DOWN-LEFT m_textureID = "downleft"; break; case 6: // LEFT m_textureID = "left"; break; case 7: // UP-LEFT m_flip = true; m_textureID = "upright"; break; } if(!canMove){ m_textureID += "stun"; } else if(Timer::Instance().step() < count){ m_textureID += "attack"; } } void Player::rotateTowards(){ m_numFrames = 1; m_currentFrame = 0; Vector2D pivot = Vector2D(m_width/2+m_position.getX(), m_height/2 + m_position.getY()); Vector2D target = InputHandler::Instance().getMousePosition() - pivot; target = target.norm(); double angle = Vector2D::angle(target, Vector2D(0, 1)); for(int i=0; i<8; i++){ if(inside(45 * i, angle)){ changeSprite(i); break; } } } void Player::move(){ Vector2D movement(0, 0); if(InputHandler::Instance().isKeyDown("w")){ movement += Vector2D(0, -1); } if(InputHandler::Instance().isKeyDown("s")){ movement += Vector2D(0, +1); } if(InputHandler::Instance().isKeyDown("d")){ movement += Vector2D(1, 0); } if(InputHandler::Instance().isKeyDown("a")){ movement += Vector2D(-1, 0); } movement = movement.norm(); if(!m_isDashing){ m_velocity = movement * 2; } dash(); if(getPosition().getY() + getHeight() >= 705){ if(m_velocity.getY() > 0) m_velocity.setY(0); } else if(getPosition().getY() <= 20){ if(m_velocity.getY() < 0) m_velocity.setY(0); } if(getPosition().getX() + getWidth() >= 1365){ if(m_velocity.getX() > 0) m_velocity.setX(0); } else if(getPosition().getX() <= -6){ if(m_velocity.getX() < 0) m_velocity.setX(0); } m_position += m_velocity; if(Physics::Instance().checkCollision(this, m_boss)){ m_position -= m_velocity; setLife(m_life - 1); } for(auto x: engine::Game::Instance().getStateMachine()->currentState()->getShieldObjects()){ if(Physics::Instance().checkCollision(this, x)){ if(dynamic_cast<Childmaiden*>(x)->getVisibility()) m_position -= m_velocity; //setLife(m_life - 1); } } } void Player::useSkill(){ if(InputHandler::Instance().isKeyDown("1", 200)){ m_skillManager.setSkillPair(&m_pSkills, RED, &isFirstSkill); } if(InputHandler::Instance().isKeyDown("2", 200)){ m_skillManager.setSkillPair(&m_pSkills, GREEN, &isFirstSkill); } if(InputHandler::Instance().isKeyDown("3", 200)){ m_skillManager.setSkillPair(&m_pSkills, BLUE, &isFirstSkill); } if(InputHandler::Instance().isKeyDown("r", 100)){ std::map<std::pair<default_inks, default_inks>, bool>::iterator it = m_skillManager.getCoolDownMap()->find(m_pSkills); if(it != m_skillManager.getCoolDownMap()->end()){ if(it->second == false){ m_skillManager.setCoolDownTrigger(m_pSkills); if(m_pSkills.first != BLANK and m_pSkills.second != BLANK){ pixelColors = m_skillManager.getSkill(m_pSkills)(); TheTextureManager::Instance().changeColorPixels(pixelColors, "bullet"); //TheTextureManager::Instance().changeColorPixels(pixelColors, "instance"); } } else INFO("TA EM CD"); m_pSkills.first = BLANK; m_pSkills.second = BLANK; isFirstSkill = true; } } } void Player::dash(){ if(InputHandler::Instance().isKeyDown("space", 1000)){ m_dashTime = Timer::Instance().step(); m_velocity = (m_velocity.norm() * 15); m_isDashing = true; } if(m_isDashing && Timer::Instance().step() >= m_dashTime + 100){ m_isDashing = false; } } void Player::setPlayerMoves(bool value){ canMove = value; }
26.553936
181
0.664361
f27b60e26acb014e0db888dda596bbfd2c3c660b
6,813
cpp
C++
tester/main-db-tester.cpp
hihi-dev/linphone
45814404943a0c8a4e341dbebf5da71fc6e44b67
[ "BSD-2-Clause" ]
null
null
null
tester/main-db-tester.cpp
hihi-dev/linphone
45814404943a0c8a4e341dbebf5da71fc6e44b67
[ "BSD-2-Clause" ]
null
null
null
tester/main-db-tester.cpp
hihi-dev/linphone
45814404943a0c8a4e341dbebf5da71fc6e44b67
[ "BSD-2-Clause" ]
null
null
null
/* * main-db-tester.cpp * Copyright (C) 2017 Belledonne Communications SARL * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "address/address.h" #include "core/core-p.h" #include "db/main-db.h" #include "event-log/events.h" // TODO: Remove me. <3 #include "private.h" #include "liblinphone_tester.h" #include "tools/tester.h" // ============================================================================= using namespace std; using namespace LinphonePrivate; // ----------------------------------------------------------------------------- class MainDbProvider { public: MainDbProvider () { mCoreManager = linphone_core_manager_create("marie_rc"); char *dbPath = bc_tester_res("db/linphone.db"); linphone_config_set_string(linphone_core_get_config(mCoreManager->lc), "storage", "uri", dbPath); bctbx_free(dbPath); linphone_core_manager_start(mCoreManager, false); } ~MainDbProvider () { linphone_core_manager_destroy(mCoreManager); } const MainDb &getMainDb () { return *L_GET_PRIVATE(mCoreManager->lc->cppPtr)->mainDb; } private: LinphoneCoreManager *mCoreManager; }; // ----------------------------------------------------------------------------- static void get_events_count () { MainDbProvider provider; const MainDb &mainDb = provider.getMainDb(); BC_ASSERT_EQUAL(mainDb.getEventCount(), 5175, int, "%d"); BC_ASSERT_EQUAL(mainDb.getEventCount(MainDb::ConferenceCallFilter), 0, int, "%d"); BC_ASSERT_EQUAL(mainDb.getEventCount(MainDb::ConferenceInfoFilter), 18, int, "%d"); BC_ASSERT_EQUAL(mainDb.getEventCount(MainDb::ConferenceChatMessageFilter), 5157, int, "%d"); BC_ASSERT_EQUAL(mainDb.getEventCount(MainDb::NoFilter), 5175, int, "%d"); } static void get_messages_count () { MainDbProvider provider; const MainDb &mainDb = provider.getMainDb(); BC_ASSERT_EQUAL(mainDb.getChatMessageCount(), 5157, int, "%d"); BC_ASSERT_EQUAL( mainDb.getChatMessageCount( ChatRoomId(IdentityAddress("sip:test-3@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org")) ), 861, int, "%d" ); } static void get_unread_messages_count () { MainDbProvider provider; const MainDb &mainDb = provider.getMainDb(); BC_ASSERT_EQUAL(mainDb.getUnreadChatMessageCount(), 2, int, "%d"); BC_ASSERT_EQUAL( mainDb.getUnreadChatMessageCount( ChatRoomId(IdentityAddress("sip:test-3@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org")) ), 0, int, "%d" ); } static void get_history () { MainDbProvider provider; const MainDb &mainDb = provider.getMainDb(); BC_ASSERT_EQUAL( mainDb.getHistoryRange( ChatRoomId(IdentityAddress("sip:test-4@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org")), 0, -1, MainDb::Filter::ConferenceChatMessageFilter ).size(), 54, int, "%d" ); BC_ASSERT_EQUAL( mainDb.getHistoryRange( ChatRoomId(IdentityAddress("sip:test-7@sip.linphone.org"), IdentityAddress("sip:test-7@sip.linphone.org")), 0, -1, MainDb::Filter::ConferenceCallFilter ).size(), 0, int, "%d" ); BC_ASSERT_EQUAL( mainDb.getHistoryRange( ChatRoomId(IdentityAddress("sip:test-1@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org")), 0, -1, MainDb::Filter::ConferenceChatMessageFilter ).size(), 804, int, "%d" ); BC_ASSERT_EQUAL( mainDb.getHistory( ChatRoomId(IdentityAddress("sip:test-1@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org")), 100, MainDb::Filter::ConferenceChatMessageFilter ).size(), 100, int, "%d" ); } static void get_conference_notified_events () { MainDbProvider provider; const MainDb &mainDb = provider.getMainDb(); list<shared_ptr<EventLog>> events = mainDb.getConferenceNotifiedEvents( ChatRoomId(IdentityAddress("sip:test-44@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org")), 1 ); BC_ASSERT_EQUAL(events.size(), 3, int, "%d"); if (events.size() != 3) return; shared_ptr<EventLog> event; auto it = events.cbegin(); event = *it; if (!BC_ASSERT_TRUE(event->getType() == EventLog::Type::ConferenceParticipantRemoved)) return; { shared_ptr<ConferenceParticipantEvent> participantEvent = static_pointer_cast<ConferenceParticipantEvent>(event); BC_ASSERT_TRUE(participantEvent->getChatRoomId().getPeerAddress().asString() == "sip:test-44@sip.linphone.org"); BC_ASSERT_TRUE(participantEvent->getParticipantAddress().asString() == "sip:test-11@sip.linphone.org"); BC_ASSERT_TRUE(participantEvent->getNotifyId() == 2); } event = *++it; if (!BC_ASSERT_TRUE(event->getType() == EventLog::Type::ConferenceParticipantDeviceAdded)) return; { shared_ptr<ConferenceParticipantDeviceEvent> deviceEvent = static_pointer_cast< ConferenceParticipantDeviceEvent >(event); BC_ASSERT_TRUE(deviceEvent->getChatRoomId().getPeerAddress().asString() == "sip:test-44@sip.linphone.org"); BC_ASSERT_TRUE(deviceEvent->getParticipantAddress().asString() == "sip:test-11@sip.linphone.org"); BC_ASSERT_TRUE(deviceEvent->getNotifyId() == 3); BC_ASSERT_TRUE(deviceEvent->getDeviceAddress().asString() == "sip:test-47@sip.linphone.org"); } event = *++it; if (!BC_ASSERT_TRUE(event->getType() == EventLog::Type::ConferenceParticipantDeviceRemoved)) return; { shared_ptr<ConferenceParticipantDeviceEvent> deviceEvent = static_pointer_cast< ConferenceParticipantDeviceEvent >(event); BC_ASSERT_TRUE(deviceEvent->getChatRoomId().getPeerAddress().asString() == "sip:test-44@sip.linphone.org"); BC_ASSERT_TRUE(deviceEvent->getParticipantAddress().asString() == "sip:test-11@sip.linphone.org"); BC_ASSERT_TRUE(deviceEvent->getNotifyId() == 4); BC_ASSERT_TRUE(deviceEvent->getDeviceAddress().asString() == "sip:test-47@sip.linphone.org"); } } test_t main_db_tests[] = { TEST_NO_TAG("Get events count", get_events_count), TEST_NO_TAG("Get messages count", get_messages_count), TEST_NO_TAG("Get unread messages count", get_unread_messages_count), TEST_NO_TAG("Get history", get_history), TEST_NO_TAG("Get conference events", get_conference_notified_events) }; test_suite_t main_db_test_suite = { "MainDb", NULL, NULL, liblinphone_tester_before_each, liblinphone_tester_after_each, sizeof(main_db_tests) / sizeof(main_db_tests[0]), main_db_tests };
34.583756
115
0.719507
f27b70324b23c204b5ef974c72beaadd47255450
414
cpp
C++
lecture5/task_6.cpp
zaneta-skiba/cpp
b02ce4252f9cf894370358fded7cfbfa3a317ead
[ "MIT" ]
null
null
null
lecture5/task_6.cpp
zaneta-skiba/cpp
b02ce4252f9cf894370358fded7cfbfa3a317ead
[ "MIT" ]
null
null
null
lecture5/task_6.cpp
zaneta-skiba/cpp
b02ce4252f9cf894370358fded7cfbfa3a317ead
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main() { string names[4]; cout << "Enter 4 names:" << endl; for (int i = 0; i < 4; i++) // user enters the names { cout << "name " << i+1 <<": "; cin >> names[i]; } for (int i = 0; i < 4; i++) { cout << names[i] << endl; // display names on the screen } return 0; }
15.923077
79
0.417874
f27b75f9a9f11ae8ad2f1dd03714e6a1cfdb2357
132
cpp
C++
flower_equals_win/logic/Minus.cpp
Garoli/flower-equals-win-game
c6965b9dfa38de124e3e8991a0d92509a54365df
[ "Unlicense", "MIT" ]
null
null
null
flower_equals_win/logic/Minus.cpp
Garoli/flower-equals-win-game
c6965b9dfa38de124e3e8991a0d92509a54365df
[ "Unlicense", "MIT" ]
null
null
null
flower_equals_win/logic/Minus.cpp
Garoli/flower-equals-win-game
c6965b9dfa38de124e3e8991a0d92509a54365df
[ "Unlicense", "MIT" ]
null
null
null
#include "Minus.h" Minus::Minus(char s) : Operator(s) { setImage("../flower_equals_win/meshes/textures/blocks/block_minus.png"); }
26.4
74
0.727273
f27b977245640cf13e6e45289e2901f7b0c05bd8
4,087
cpp
C++
Libs/DICOM/Core/Testing/Cpp/ctkDICOMTesterTest1.cpp
ntoussaint/CTK
fc7a5f78fff4c4394ee5ede2f21975c6a44dfea4
[ "Apache-2.0" ]
515
2015-01-13T05:42:10.000Z
2022-03-29T03:10:01.000Z
Libs/DICOM/Core/Testing/Cpp/ctkDICOMTesterTest1.cpp
ntoussaint/CTK
fc7a5f78fff4c4394ee5ede2f21975c6a44dfea4
[ "Apache-2.0" ]
425
2015-01-06T05:28:38.000Z
2022-03-08T19:42:18.000Z
Libs/DICOM/Core/Testing/Cpp/ctkDICOMTesterTest1.cpp
ntoussaint/CTK
fc7a5f78fff4c4394ee5ede2f21975c6a44dfea4
[ "Apache-2.0" ]
341
2015-01-08T06:18:17.000Z
2022-03-29T21:47:49.000Z
/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt 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. =========================================================================*/ // Qt includes #include <QCoreApplication> #include <QFileInfo> // ctkDICOMCore includes #include "ctkDICOMTester.h" // STD includes #include <iostream> #include <cstdlib> void printUsage() { std::cout << " ctkDICOMTesterTest1 [<dcmqrscp>] [<configfile>]" << std::endl; } int ctkDICOMTesterTest1(int argc, char * argv []) { QCoreApplication app(argc, argv); ctkDICOMTester tester; if (argc > 1) { tester.setDCMQRSCPExecutable(argv[1]); if (tester.dcmqrscpExecutable() != argv[1]) { std::cerr << __LINE__ << ": Failed to set dcmqrscp: " << argv[1] << " value:" << qPrintable(tester.dcmqrscpExecutable()) << std::endl; return EXIT_FAILURE; } } if (argc > 2) { tester.setDCMQRSCPConfigFile(argv[2]); if (tester.dcmqrscpConfigFile() != argv[2]) { std::cerr << __LINE__ << ": Failed to set dcmqrscp config file: " << argv[2] << " value:" << qPrintable(tester.dcmqrscpConfigFile()) << std::endl; return EXIT_FAILURE; } } QString dcmqrscp(tester.dcmqrscpExecutable()); QString dcmqrscpConf(tester.dcmqrscpConfigFile()); if (!QFileInfo(dcmqrscp).exists() || !QFileInfo(dcmqrscp).isExecutable()) { std::cerr << __LINE__ << ": Wrong dcmqrscp executable: " << qPrintable(dcmqrscp) << std::endl; } if (!QFileInfo(dcmqrscpConf).exists() || !QFileInfo(dcmqrscpConf).isReadable()) { std::cerr << __LINE__ << ": Wrong dcmqrscp executable: " << qPrintable(dcmqrscp) << std::endl; } QProcess* process = tester.startDCMQRSCP(); if (!process) { std::cerr << __LINE__ << ": Failed to start dcmqrscp: " << qPrintable(dcmqrscp) << " with config file:" << qPrintable(dcmqrscpConf) << std::endl; return EXIT_FAILURE; } bool res = tester.stopDCMQRSCP(); if (!res) { std::cerr << __LINE__ << ": Failed to stop dcmqrscp: " << qPrintable(dcmqrscp) << " with config file:" << qPrintable(dcmqrscpConf) << std::endl; return EXIT_FAILURE; } process = tester.startDCMQRSCP(); if (!process) { std::cerr << __LINE__ << ": Failed to start dcmqrscp: " << qPrintable(dcmqrscp) << " with config file:" << qPrintable(dcmqrscpConf) << std::endl; return EXIT_FAILURE; } process = tester.startDCMQRSCP(); if (process) { std::cerr << __LINE__ << ": Failed to start dcmqrscp: " << qPrintable(dcmqrscp) << " with config file:"<< qPrintable(dcmqrscpConf) << std::endl; return EXIT_FAILURE; } res = tester.stopDCMQRSCP(); if (!res) { std::cerr << __LINE__ << ": Failed to stop dcmqrscp: " << qPrintable(dcmqrscp) << " with config file:" << qPrintable(dcmqrscpConf) << std::endl; return EXIT_FAILURE; } // there should be no process to stop res = tester.stopDCMQRSCP(); if (res) { std::cerr << __LINE__ << ": Failed to stop dcmqrscp: " << qPrintable(dcmqrscp) << " with config file:" << qPrintable(dcmqrscpConf) << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
28.985816
79
0.571324
f27be8659b0b452d8f4a3c58fde153b08c488f8c
101
hpp
C++
source/windows.hpp
phwitti/elevate
00e4718bcfbf2d5490a3059451d850d17c30d9b0
[ "Unlicense" ]
4
2021-02-24T23:50:18.000Z
2021-08-08T11:56:49.000Z
src/shared/windows.hpp
phwitti/cmdhere
a8e7635780b043efb3e220c65366255d8529b615
[ "Unlicense" ]
null
null
null
src/shared/windows.hpp
phwitti/cmdhere
a8e7635780b043efb3e220c65366255d8529b615
[ "Unlicense" ]
null
null
null
#ifndef __PW_WINDOWS_HPP__ #define __PW_WINDOWS_HPP__ #define NOMINMAX #include <Windows.h> #endif
12.625
26
0.811881
f27f8336710722dff65995ed0278c5e1a93f3a07
926
cpp
C++
ITK19_Summer_Training _2021/PreQNOI/21_08_21/e.cpp
hoanghai1803/CP_Training
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
[ "MIT" ]
4
2021-08-25T10:53:32.000Z
2021-09-30T03:25:50.000Z
ITK19_Summer_Training _2021/PreQNOI/21_08_21/e.cpp
hoanghai1803/CP_Training
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
[ "MIT" ]
null
null
null
ITK19_Summer_Training _2021/PreQNOI/21_08_21/e.cpp
hoanghai1803/CP_Training
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { long long x, y, l, r; cin >> x >> y >> l >> r; long long powX = 1, powY = 1; vector<long long> vecX, vecY, vecSum; while (1) { vecX.push_back(powX); if (r / x < powX) break; powX *= x; } while (1) { vecY.push_back(powY); if (r / y < powY) break; powY *= y; } for (auto _x: vecX) for (auto _y: vecY) vecSum.push_back(_x + _y); sort(vecSum.begin(), vecSum.end()); auto it = vecSum.begin(); while (*it < l) it++; if (*it >= r) { cout << (r - l + (*it > r)); return 0; } long long res = *it - l; it++; for (; it < vecSum.end() && *it < r; it++) res = max(res, *it - *(it - 1) - 1); cout << max(res, r - *(it - 1) - (it != vecSum.end() && r == *it)) << "\n"; }
21.045455
79
0.413607
f28194fb10280e78290c1e8fd063a8815c6bae80
209
cpp
C++
src/stream/DirectStream.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
45
2018-08-24T12:57:38.000Z
2021-11-12T11:21:49.000Z
src/stream/DirectStream.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
null
null
null
src/stream/DirectStream.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
4
2019-09-16T02:48:42.000Z
2020-07-10T03:50:31.000Z
#include "DirectStream.h" #include "../container/Buffer.h" using namespace L; Buffer DirectStream::read_into_buffer() { Buffer buffer(size()); seek(0); read(buffer, buffer.size()); return buffer; }
16.076923
41
0.69378
f28b6c86a411b6fa3e1472f751d8e4235d6aa694
1,294
cpp
C++
src/Editor/Dynamic/Fields/TexturePathEditor.cpp
Tristeon/Tristeon
9052e87b743f1122ed4c81952f2bffda96599447
[ "MIT" ]
32
2018-06-16T20:50:15.000Z
2022-03-26T16:57:15.000Z
src/Editor/Dynamic/Fields/TexturePathEditor.cpp
Tristeon/Tristeon2D
9052e87b743f1122ed4c81952f2bffda96599447
[ "MIT" ]
2
2018-10-07T17:41:39.000Z
2021-01-08T03:14:19.000Z
src/Editor/Dynamic/Fields/TexturePathEditor.cpp
Tristeon/Tristeon2D
9052e87b743f1122ed4c81952f2bffda96599447
[ "MIT" ]
9
2018-06-12T21:00:58.000Z
2021-01-08T02:18:30.000Z
#include "TexturePathEditor.h" #include <qboxlayout.h> #include <qdir.h> #include <qfiledialog.h> #include <Settings.h> #include <AssetManagement/AssetDatabase.h> namespace TristeonEditor { TexturePathEditor::TexturePathEditor(const nlohmann::json& pValue, const std::function<void(nlohmann::json)>& pCallback) : AbstractJsonEditor(pValue, pCallback) { const uint32_t guid = _value.value("guid", 0); _button = new QPushButton(QString(std::to_string(guid).c_str())); _widget = _button; QWidget::connect(_button, &QPushButton::clicked, [=]() { QDir const baseDir(Tristeon::Settings::assetPath().c_str()); auto const path = QFileDialog::getOpenFileName(nullptr, QWidget::tr("Find Texture"), Tristeon::Settings::assetPath().c_str(), QWidget::tr("Image Files (*.png *.jpg *.bmp)")); if (!path.isEmpty()) { auto const localPath = baseDir.relativeFilePath(path); auto const fileName = QFileInfo(path).baseName(); _value["guid"] = Tristeon::AssetDatabase::guid("assets://" + localPath.toStdString()); _button->setText(fileName); _callback(_value); } }); } void TexturePathEditor::setValue(const nlohmann::json& pValue) { _value = pValue; _button->setText(Tristeon::AssetDatabase::path(pValue.value("guid", 0)).c_str()); } }
31.560976
178
0.697836
f290e9b9e1dfe6750502d56b139da0c12d11eefb
2,707
cpp
C++
competitive_programming_3/2_data_structures_and_libraries/2.3_Non-Linear_DS_with_Built-in_Libraries/map(treemap)/978_Lemmings_Battle.cpp
FranciscoPigretti/onlinejudge_solutions
ec9368ade1faa403d0d26ad9321b030e128ae099
[ "MIT" ]
null
null
null
competitive_programming_3/2_data_structures_and_libraries/2.3_Non-Linear_DS_with_Built-in_Libraries/map(treemap)/978_Lemmings_Battle.cpp
FranciscoPigretti/onlinejudge_solutions
ec9368ade1faa403d0d26ad9321b030e128ae099
[ "MIT" ]
null
null
null
competitive_programming_3/2_data_structures_and_libraries/2.3_Non-Linear_DS_with_Built-in_Libraries/map(treemap)/978_Lemmings_Battle.cpp
FranciscoPigretti/onlinejudge_solutions
ec9368ade1faa403d0d26ad9321b030e128ae099
[ "MIT" ]
null
null
null
#include <iostream> // cin, cout #include <set> #include <iterator> using namespace std; int main() { int test_cases; scanf("%d", &test_cases); int B, SG, SB, current; multiset <int, greater <int> > greens, blues; multiset <int, greater <int> > temp_greens, temp_blues; multiset <int, greater <int> >::iterator g_it, b_it; while(test_cases--) { int number_of_snowflakes; scanf("%d %d %d", &B, &SG, &SB); greens.clear(); blues.clear(); while(SG--) { scanf("%d", &current); greens.insert(current); } while(SB--) { scanf("%d", &current); blues.insert(current); } while(true) { for (int i = 0; i < B; i++) { // saco de cada uno si hay en ambos if (greens.size() > 0 && blues.size() > 0) { g_it = greens.begin(); b_it = blues.begin(); int g = *g_it; int b = *b_it; greens.erase(g_it); blues.erase(b_it); int res = g - b; if (res > 0) { temp_greens.insert(res); } else if (res < 0) { temp_blues.insert(-res); } else { // empate } } else { break; } } // vuelvo a insertar los ganadores for (auto x : temp_greens) { greens.insert(x); } for (auto x : temp_blues) { blues.insert(x); } temp_greens.clear(); temp_blues.clear(); // si hay en ambos sigo, sino devuelvo el ganador o empate if (greens.size() == 0 && blues.size() == 0) { cout << "green and blue died" << endl << endl; break; } else if (greens.size() == 0) { cout << "blue wins" << endl; for (auto x : blues) { cout << x << endl; } if (test_cases != 0) { cout << endl; } break; } else if (blues.size() == 0) { cout << "green wins" << endl; for (auto x : greens) { cout << x << endl; } if (test_cases != 0) { cout << endl; } break; } } } }
27.907216
70
0.362763
f294481ff7e6dc8c20b6e4ea9d130ef1c07a09a1
12,105
cpp
C++
runtests.cpp
fguitton/mdipp
a79d207daa3bf6b2b730653d39cd270cf6295859
[ "BSD-3-Clause" ]
2
2017-11-01T16:45:16.000Z
2021-02-24T08:29:14.000Z
runtests.cpp
fguitton/mdipp
a79d207daa3bf6b2b730653d39cd270cf6295859
[ "BSD-3-Clause" ]
null
null
null
runtests.cpp
fguitton/mdipp
a79d207daa3bf6b2b730653d39cd270cf6295859
[ "BSD-3-Clause" ]
2
2018-03-22T16:40:51.000Z
2018-07-16T13:05:10.000Z
#include <fstream> #include <iostream> #include <memory> #include <Eigen/Dense> #include "datatypes.hpp" #include "utility.hpp" std::default_random_engine generator; template<typename T> void writeCsvMatrix (std::ostream &fd, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &data, const Eigen::VectorXi &alloc) { fd << "cluster"; for (int i = 0; i < data.cols(); i++) { fd << ",f" << i+1; } fd << "\n"; for (int i = 0; i < data.rows(); i++) { fd << "c" << alloc(i)+1; for (int j = 0; j < data.cols(); j++) { fd << "," << data(i,j); } fd << "\n"; } } template<typename T> void checkEqualTemplate (T a, T b, const std::string &msg) { if (a == b) return; std::cerr << "Error: " << msg << " (expecting " << a << " == " << b << ")" << std::endl; } void checkEqual(int a, int b, const std::string &msg) { return checkEqualTemplate(a, b, msg); } template<typename T> void checkApproxEqual(const T &a, const T &b, const std::string &msg, typename T::Scalar epsilon = 1e-6) { // Eigen::Array<bool, T::RowsAtCompileTime, T::ColsAtCompileTime> // em = (a - b).array() <= a.array().abs().min(b.array().abs()) * epsilon; if (a.isApprox(b, epsilon)) return; std::cerr << "Error: " << msg << " (matrix equality check failed at epsilon=" << epsilon << ")" << " differences observed: " << std::endl << (a-b).array().abs() << std::endl << std::endl; } void checkApproxEqual(const double a, const double b, const std::string &msg, double epsilon = 1e-6) { using std::abs; using std::min; epsilon *= min(abs(a),abs(b)); if(abs(a-b) <= epsilon) return; std::cerr << "Error: " << msg << " (expecting ||" << a << " - " << b << "|| <= " << epsilon << ")" << std::endl; } template<typename T> void checkProbItemMassGt(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &prob, int item, T mass, const std::string &msg) { // normalise, nans and infinities will propagate! auto probnorm = prob.array() / prob.sum(); // check all positive if ((probnorm < 0).any()) { std::cerr << "Error: " << msg << " (some probabilities are not positive)\n"; } if (probnorm(item) < mass) { std::cerr << "Error: " << msg << " (mass of item " << item << " is " << probnorm(item) << ", i.e. < " << mass << ")\n"; } } double nuConditionalAlphaOracle(const Eigen::MatrixXi &alloc) { return alloc.rows(); } double phiConditionalAlphaOracle(const Eigen::MatrixXi &alloc, int m, int p) { int sum = 0; for (int i = 0; i < alloc.rows(); i++) { sum += alloc(i,m) == alloc(i,p); } return 1 + sum; } double gammaConditionalAlphaOracle(const Eigen::MatrixXi &alloc, int m, int jm) { int sum = 0; for (int i = 0; i < alloc.rows(); i++) { sum += alloc(i,m) == jm; } return 1 + sum; } /* the following set of functions work by having an @outer function * that works "down" through the files, setting $j_i$ to the * appropriate value and then calling the next @outer function. Once * $j$ has been set for all $K$ files (i.e. @{i == K}), @outer defers * to @inner and the product for the given $j$ is evaluated. */ // See Equation 2 in section "A.2 Normalising Constant" of Kirk et.al 2012 double nuConditionalBetaOracle(const mdisampler &mdi) { const int N = mdi.nclus(), K = mdi.nfiles(); std::vector<int> j(mdi.nfiles()); auto inner = [K,&mdi,&j]() { long double prod = 1; for (int k = 0; k < K; k++) { prod *= mdi.weight(j[k], k); } for (int k = 0; k < K-1; k++) { for (int l = k+1; l < K; l++) { prod *= 1 + mdi.phi(k, l) * (j[k] == j[l]); } } return prod; }; std::function<long double(int)> outer = [&outer, &inner, &j, N, K](int i) { if (i == K) return inner(); long double sum = 0; for (j[i] = 0; j[i] < N; j[i]++) sum += outer(i+1); return sum; }; return outer(0); } // See Kirk et.al 2012 $b_\phi$ from "Conditional for $\phi_{mp}$" double phiConditionalBetaOracle(const mdisampler &mdi, int m, int p) { const int N = mdi.nclus(), K = mdi.nfiles(); std::vector<int> j(mdi.nfiles()); auto inner = [K,&mdi,&j,m,p]() { long double prod = 1; for (int k = 0; k < K; k++) { prod *= mdi.weight(j[k], k); } for (int k = 0; k < K-1; k++) { for (int l = k+1; l < K; l++) { if (l != p) prod *= 1 + mdi.phi(k, l) * (j[k] == j[l]); } } for (int k = 0; k < p; k++) { if (k != m) prod *= 1 + mdi.phi(k, p) * (j[k] == j[p]); } return prod; }; std::function<long double(int)> outer = [&outer,&inner,&j,N,K,m,p](int i) { if (i == K) return inner(); // $j_m$ and $j_p$ are set outside this iteration if (i == m || i == p) return outer(i+1); long double sum = 0; for (j[i] = 0; j[i] < N; j[i]++) sum += outer(i+1); return sum; }; // iterate over $\sum_{j_m = j_p = 1}^N$ long double sum = 0; for (int i = 0; i < N; i++) { j[m] = j[p] = i; sum += outer(0); } return mdi.nu() * sum; } // See Kirk et.al 2012 $b_\gamma$ from "Conditional for $\gamma_{j_m m}$" double gammaConditionalBetaOracle (const mdisampler &mdi, const int m, const int jm) { const int N = mdi.nclus(), K = mdi.nfiles(); std::vector<int> j(mdi.nfiles()); // within data @m we are interested in cluster @jm j[m] = jm; auto inner = [K,m,&mdi,&j]() { long double prod = 1; for (int k = 0; k < K; k++) { if(k != m) prod *= mdi.weight(j[k], k); } for (int k = 0; k < K-1; k++) { for (int l = k+1; l < K; l++) { prod *= 1 + mdi.phi(k, l) * (j[k] == j[l]); } } return prod; }; std::function<long double(int)> outer = [&outer, &inner, &j, N, K, m](int i) { if (i == K) return inner(); if (i == m) return outer(i+1); long double sum = 0; for (j[i] = 0; j[i] < N; j[i]++) sum += outer(i+1); return sum; }; return mdi.nu() * outer(0); } int main() { /* datatypes * * * loading data (CPU) * * * summarising data given cluster allocations (CPU GPU) * * * sampling cluster parameters given above summary (CPU GPU) * * * sampling cluster allocations given cluster parameters (CPU GPU) * * MDI prior * * * Sampling Nu given [weights and allocations]? * * * Sampling weights given [lots!] * * * Sampling DPs given weights and nu */ generator.seed(1); // given a single "file" for each datatype, load it in define // allocations (same for all four files), weights, nu, DP // concentration const int nfiles = 4, nitems = 5, nclus = 10, ngaussfeatures = 3; // 5 items, cluster allocations [0 0 1 1 2]. one file for each // datatype Eigen::MatrixXi alloc(nitems, nfiles); for (int i = 0; i < nfiles; i++) alloc.col(i) << 0, 0, 1, 1, 2; Eigen::MatrixXf weights = alloc.cast<float>(); Eigen::VectorXf dpmass = Eigen::VectorXf::Ones(nfiles); Eigen::MatrixXf data_gaussian(nitems, ngaussfeatures); data_gaussian << -2.1, -2.1, -2.1, -1.9, -1.9, -1.9, 1.9, 1.9, 1.9, 2.1, 2.1, 2.1, 5.0, 5.0, 5.0; // write dummy data out, load it back in and make sure it's the same // as the original data { std::ofstream out("data_gauss.txt"); writeCsvMatrix (out, data_gaussian, alloc.col(0)); } gaussianDatatype dt_gauss("data_gauss.txt"); checkEqual(nitems, dt_gauss.items().size(), "number of items read from gaussian dataset"); checkEqual(ngaussfeatures, dt_gauss.features().size(), "number of features read from gaussian dataset"); checkApproxEqual<Eigen::MatrixXf>(data_gaussian.transpose(), dt_gauss.rawdata(), "gaussian data from file"); // given weights, allocations, nu: shared shared(nfiles, nclus, nitems); interdataset inter(nfiles); mdisampler mdi(inter, nclus); shared.sampleFromPrior(); mdi.sampleFromPrior(); shared.setAlloc(alloc); cuda::sampler cuda(nfiles, nitems, nclus, inter.getPhiOrd(), inter.getWeightOrd()); cuda.setNu(mdi.nu()); cuda.setDpMass(eigenMatrixToStdVector(mdi.dpmass())); cuda.setAlloc(eigenMatrixToStdVector(alloc)); cuda.setPhis(eigenMatrixToStdVector(mdi.phis())); cuda.setWeights(eigenMatrixToStdVector(mdi.weights())); gaussianSampler * gauss_sampler = dt_gauss.newSampler(nclus, &cuda); // given known allocations, calculate Gaussian summaries { gauss_sampler->cudaSampleParameters(alloc.col(0)); gauss_sampler->cudaAccumAllocProbs(); const std::vector<runningstats<> > state(gauss_sampler->accumState(alloc.col(0))); checkEqual(nclus * ngaussfeatures, state.size(), "number of accumulated gaussian stats"); // check Gaussian summaries are OK const runningstats<> rs[nclus] = {{2,-2,0.02},{2,2,0.02},{1,5,0}}; bool ok = true; for (int j = 0; j < nclus; j++) { for (int i = 0; i < ngaussfeatures; i++) { const runningstats<> &a = state[j * ngaussfeatures + i], &b = rs[j]; ok &= a.isApprox(b); } } if (!ok) { std::cout << "Error: some of the accumulated gaussian stats are incorrect\n"; } } // given known cluster parameters, ... { Eigen::MatrixXf mu(ngaussfeatures, nclus), tau(ngaussfeatures,nclus); mu.fill(0); tau.fill(20); mu.col(0).fill(-2); mu.col(1).fill( 2); mu.col(2).fill( 5); gauss_sampler->debug_setMuTau(mu, tau); } // ... sample Gaussian cluster association probabilities { std::unique_ptr<sampler::item> is(gauss_sampler->newItemSampler()); for (int i = 0; i < nitems; i++) { Eigen::VectorXf prob((*is)(i)); prob = (prob.array() - prob.maxCoeff()).exp(); checkProbItemMassGt<float>(prob, alloc(i,0), 0.5, "gaussian cluster allocations"); } } { double oracle = nuConditionalBetaOracle(mdi); checkApproxEqual(oracle, mdi.nuConditionalBeta(), "MDI nu beta conditional, CPU code"); checkApproxEqual(oracle, cuda.collectNuConditionalBeta(), "MDI nu beta conditional, GPU code"); oracle = nuConditionalAlphaOracle(alloc); checkApproxEqual(oracle, shared.nuConditionalAlpha(), "MDI nu alpha conditional, CPU code"); } { Eigen::MatrixXf oracle, cpu, gpu; oracle = cpu = gpu = Eigen::MatrixXf::Zero(nfiles, nfiles); std::vector<float> gpuv = cuda.collectPhiConditionalsBeta(); for (int k = 0, i = 0; k < nfiles; k++) { for (int l = k+1; l < nfiles; l++) { oracle(k,l) = phiConditionalBetaOracle(mdi, k, l); cpu(k,l) = mdi.phiConditionalBeta(k, l); gpu(k,l) = gpuv[i++]; } } checkApproxEqual(oracle, cpu, "MDI phi beta conditionals, CPU code"); checkApproxEqual(oracle, gpu, "MDI phi beta conditionals, GPU code"); gpuv = cuda.collectPhiConditionalsAlpha(); for (int k = 0, i = 0; k < nfiles; k++) { for (int l = k+1; l < nfiles; l++) { oracle(k,l) = phiConditionalAlphaOracle(alloc, k, l); cpu(k,l) = shared.phiConditionalAlpha(k, l) + 1; // what to do about prior? gpu(k,l) = gpuv[i++]; } } checkApproxEqual(oracle, cpu, "MDI phi alpha conditionals, CPU code"); checkApproxEqual(oracle, gpu, "MDI phi alpha conditionals, GPU code"); } { Eigen::MatrixXf oracle, cpu, gpu; oracle = cpu = Eigen::MatrixXf::Zero(nclus, nfiles); gpu = stdVectorToEigenMatrix(cuda.collectGammaConditionalsBeta(), nclus, nfiles); // take out the prior, not sure what to do about this. I think I // should be checking priors as well, but conflating it in the // test unnecessarily seems to make things more difficult to debug // than it could... hum! gpu.array() -= 1; for (int k = 0; k < nfiles; k++) { for (int j = 0; j < nclus; j++) { oracle(j,k) = gammaConditionalBetaOracle(mdi, k, j); cpu(j,k) = mdi.gammaConditionalBeta(k, j); } } checkApproxEqual(oracle, cpu, "MDI gamma beta conditionals, CPU code"); checkApproxEqual(oracle, gpu, "MDI gamma beta conditionals, GPU code"); } return 0; }
26.546053
86
0.585378
f295975d8918914e50a1a1e82b5b1f9a728aa1ff
254
cpp
C++
ImportantExample/QIconEditorDemo/main.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
ImportantExample/QIconEditorDemo/main.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
ImportantExample/QIconEditorDemo/main.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
#include "iconeditor.h" #include <QIcon> #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QImage icon(":/images/mouse.png"); IconEditor w; w.setIconImage(icon); w.show(); return a.exec(); }
16.933333
38
0.629921
f29fee79be5f44a0dd5e04a95fd2201638ea63c1
4,862
cpp
C++
src/ECS/Systems/UpdateEntityPositionSystem.cpp
novuscore/NovusCore-World
4c0639e251cac9ae0cef601b814c575a1bfb4f2e
[ "MIT" ]
null
null
null
src/ECS/Systems/UpdateEntityPositionSystem.cpp
novuscore/NovusCore-World
4c0639e251cac9ae0cef601b814c575a1bfb4f2e
[ "MIT" ]
null
null
null
src/ECS/Systems/UpdateEntityPositionSystem.cpp
novuscore/NovusCore-World
4c0639e251cac9ae0cef601b814c575a1bfb4f2e
[ "MIT" ]
2
2021-12-20T22:16:11.000Z
2022-03-10T20:59:10.000Z
#include "UpdateEntityPositionSystem.h" #include <entt.hpp> #include <tracy/Tracy.hpp> #include <Utils/DebugHandler.h> #include "../../Utils/ServiceLocator.h" #include "../Components/Singletons/MapSingleton.h" #include "../Components/Network/ConnectionComponent.h" #include <Gameplay/Network/PacketWriter.h> #include <Gameplay/ECS/Components/Transform.h> #include <Gameplay/ECS/Components/GameEntity.h> void UpdateEntityPositionSystem::Update(entt::registry& registry) { auto modelView = registry.view<Transform, GameEntity>(); if (modelView.size_hint() == 0) return; MapSingleton& mapSingleton = registry.ctx<MapSingleton>(); modelView.each([&](const auto entity, Transform& transform, GameEntity& gameEntity) { if (gameEntity.type != GameEntity::Type::Player) return; std::vector<Point2D> playersWithinDistance; Tree2D& entityTress = mapSingleton.GetPlayerTree(); if (!entityTress.GetWithinDistance({transform.position.x, transform.position.y}, 500.f, entity, playersWithinDistance)) return; std::vector<entt::entity>& seenEntities = gameEntity.seenEntities; if (seenEntities.size() == 0 && playersWithinDistance.size() == 0) return; std::vector<entt::entity> newlySeenEntities(playersWithinDistance.size()); for (u32 i = 0; i < playersWithinDistance.size(); i++) { newlySeenEntities[i] = playersWithinDistance[i].GetPayload(); } ConnectionComponent& connection = registry.get<ConnectionComponent>(entity); // Send Delete Updates to no longer seen entites { for (auto it = seenEntities.begin(); it != seenEntities.end();) { entt::entity seenEntity = *it; auto itr = std::find(newlySeenEntities.begin(), newlySeenEntities.end(), seenEntity); if (itr != newlySeenEntities.end()) { newlySeenEntities.erase(itr); it++; continue; } // Remove SeenEntity { it = seenEntities.erase(it); std::shared_ptr<Bytebuffer> packetBuffer = nullptr; if (PacketWriter::SMSG_DELETE_ENTITY(packetBuffer, seenEntity)) { connection.AddPacket(packetBuffer, PacketPriority::IMMEDIATE); } else { DebugHandler::PrintError("Failed to build SMSG_DELETE_ENTITY"); } } } } // Send Movement Updates to seenEntities if (seenEntities.size() > 0 && registry.all_of<TransformIsDirty>(entity)) { std::shared_ptr<Bytebuffer> packetBuffer = nullptr; if (PacketWriter::SMSG_UPDATE_ENTITY(packetBuffer, entity, transform)) { for (u32 i = 0; i < seenEntities.size(); i++) { entt::entity& seenEntity = seenEntities[i]; if (!registry.valid(seenEntity)) continue; const GameEntity& seenGameEntity = registry.get<GameEntity>(seenEntity); if (seenGameEntity.type != GameEntity::Type::Player) continue; ConnectionComponent& seenConnection = registry.get<ConnectionComponent>(seenEntity); seenConnection.AddPacket(packetBuffer, PacketPriority::IMMEDIATE); } } } // Check if there are any new entities if (newlySeenEntities.size() == 0) return; // List of new entities within range if (newlySeenEntities.size() > 0) { //DebugHandler::PrintSuccess("Preparing Data for Player (%u)", entt::to_integral(entity)); for (u32 i = 0; i < newlySeenEntities.size(); i++) { entt::entity newEntity = newlySeenEntities[i]; if (!registry.valid(newEntity)) continue; const Transform& newTransform = registry.get<Transform>(newEntity); const GameEntity& newGameEntity = registry.get<GameEntity>(newEntity); std::shared_ptr<Bytebuffer> packetBuffer = nullptr; if (PacketWriter::SMSG_CREATE_ENTITY(packetBuffer, newEntity, newGameEntity, newTransform)) { connection.AddPacket(packetBuffer, PacketPriority::IMMEDIATE); } seenEntities.push_back(newEntity); } //DebugHandler::PrintSuccess("Finished Preparing Data for Player (%u)", entt::to_integral(entity)); } }); }
37.4
127
0.567668
f29feff2635c02f4971e24e5d2cf9f452cda5ce7
4,298
cc
C++
gpu/command_buffer/tests/gl_unallocated_texture_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
gpu/command_buffer/tests/gl_unallocated_texture_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
gpu/command_buffer/tests/gl_unallocated_texture_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 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 <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <stddef.h> #include <stdint.h> #include "gpu/GLES2/gl2extchromium.h" #include "gpu/command_buffer/client/gles2_implementation.h" #include "gpu/command_buffer/client/gles2_lib.h" #include "gpu/command_buffer/service/gles2_cmd_decoder.h" #include "gpu/command_buffer/tests/gl_manager.h" #include "gpu/command_buffer/tests/gl_test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gl/gl_share_group.h" namespace gpu { class GLUnallocatedTextureTest : public testing::Test { protected: void SetUp() override { gl_.Initialize(GLManager::Options()); } void TearDown() override { gl_.Destroy(); } GLuint MakeProgram(const char* fragment_shader) { constexpr const char kVertexShader[] = "void main() { gl_Position = vec4(0.0, 0.0, 0.0, 1.0); }"; GLuint program = GLTestHelper::LoadProgram(kVertexShader, fragment_shader); if (!program) return 0; glUseProgram(program); GLint location_sampler = glGetUniformLocation(program, "sampler"); glUniform1i(location_sampler, 0); return program; } // Creates a texture on target, setting up filters but without setting any // level image. GLuint MakeUninitializedTexture(GLenum target) { GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(target, texture); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); return texture; } GLManager gl_; }; // Test that we can render with GL_TEXTURE_2D textures that are unallocated. // This should not generate errors or assert. TEST_F(GLUnallocatedTextureTest, RenderUnallocatedTexture2D) { constexpr const char kFragmentShader[] = "uniform sampler2D sampler;\n" "void main() { gl_FragColor = texture2D(sampler, vec2(0.0, 0.0)); }\n"; GLuint program = MakeProgram(kFragmentShader); ASSERT_TRUE(program); GLuint texture = MakeUninitializedTexture(GL_TEXTURE_2D); glDrawArrays(GL_TRIANGLES, 0, 3); EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glDeleteTextures(1, &texture); glDeleteProgram(program); } // Test that we can render with GL_TEXTURE_EXTERNAL_OES textures that are // unallocated. This should not generate errors or assert. TEST_F(GLUnallocatedTextureTest, RenderUnallocatedTextureExternal) { if (!gl_.GetCapabilities().egl_image_external) { LOG(INFO) << "GL_OES_EGL_image_external not supported, skipping test"; return; } constexpr const char kFragmentShader[] = "#extension GL_OES_EGL_image_external : enable\n" "uniform samplerExternalOES sampler;\n" "void main() { gl_FragColor = texture2D(sampler, vec2(0.0, 0.0)); }\n"; GLuint program = MakeProgram(kFragmentShader); ASSERT_TRUE(program); GLuint texture = MakeUninitializedTexture(GL_TEXTURE_EXTERNAL_OES); glDrawArrays(GL_TRIANGLES, 0, 3); EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glDeleteTextures(1, &texture); glDeleteProgram(program); } // Test that we can render with GL_TEXTURE_RECTANGLE_ARB textures that are // unallocated. This should not generate errors or assert. TEST_F(GLUnallocatedTextureTest, RenderUnallocatedTextureRectange) { if (!gl_.GetCapabilities().texture_rectangle) { LOG(INFO) << "GL_ARB_texture_rectangle not supported, skipping test"; return; } constexpr const char kFragmentShader[] = "#extension GL_ARB_texture_rectangle : enable\n" "uniform sampler2DRect sampler;\n" "void main() {\n" " gl_FragColor = texture2DRect(sampler, vec2(0.0, 0.0));\n" "}\n"; GLuint program = MakeProgram(kFragmentShader); ASSERT_TRUE(program); GLuint texture = MakeUninitializedTexture(GL_TEXTURE_RECTANGLE_ARB); glDrawArrays(GL_TRIANGLES, 0, 3); EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glDeleteTextures(1, &texture); glDeleteProgram(program); } } // namespace gpu
35.520661
79
0.744067
f2a21670e5d0d880491c390727879e089abf1476
7,027
cpp
C++
Operations/albaOpImporterLandmark.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
9
2018-11-19T10:15:29.000Z
2021-08-30T11:52:07.000Z
Operations/albaOpImporterLandmark.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Operations/albaOpImporterLandmark.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-10T22:56:29.000Z
2019-12-12T06:22:56.000Z
/*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: albaOpImporterLandmark Authors: Daniele Giunchi, Simone Brazzale Copyright (c) BIC All rights reserved. See Copyright.txt or This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "albaDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "albaOpImporterLandmark.h" #include <wx/busyinfo.h> #include "albaDecl.h" #include "albaEvent.h" #include "albaGUI.h" #include "albaVME.h" #include "albaVMELandmarkCloud.h" #include "albaVMELandmark.h" #include "albaTagArray.h" #include "albaSmartPointer.h" #include <fstream> #include "albaProgressBarHelper.h" const bool DEBUG_MODE = true; //---------------------------------------------------------------------------- albaOpImporterLandmark::albaOpImporterLandmark(wxString label) : albaOp(label) { m_OpType = OPTYPE_IMPORTER; m_Canundo = false; m_TypeSeparation = 0; m_VmeCloud = NULL; m_OnlyCoordinates = false; } //---------------------------------------------------------------------------- albaOpImporterLandmark::~albaOpImporterLandmark( ) { albaDEL(m_VmeCloud); } //---------------------------------------------------------------------------- albaOp* albaOpImporterLandmark::Copy() { albaOpImporterLandmark *cp = new albaOpImporterLandmark(m_Label); cp->m_Canundo = m_Canundo; cp->m_OpType = m_OpType; cp->m_Listener = m_Listener; cp->m_Next = NULL; cp->m_OnlyCoordinates = m_OnlyCoordinates; cp->m_VmeCloud = m_VmeCloud; cp->m_TypeSeparation = m_TypeSeparation; return cp; } //---------------------------------------------------------------------------- void albaOpImporterLandmark::OpRun() { wxString fileDir; m_File = ""; wxString pgd_wildc = "Landmark (*.*)|*.*"; fileDir = albaGetLastUserFolder().c_str(); albaString f = albaGetOpenFile(fileDir,pgd_wildc).c_str(); if(f != "") { m_File = f; if (!m_TestMode) { m_Gui = new albaGUI(this); wxString choices[4] = { _("Comma"),_("Space"),_("Semicolon"),_("Tab") }; m_Gui->Radio(ID_TYPE_SEPARATION,"Separator",&m_TypeSeparation,4,choices,1,""); m_Gui->Divider(); m_Gui->Bool(ID_TYPE_FILE,"Coordinates only",&m_OnlyCoordinates,true,"Check if the format is \"x y z\""); m_Gui->Divider(); m_Gui->Label(""); m_Gui->Divider(1); m_Gui->OkCancel(); ShowGui(); } } else { albaEventMacro(albaEvent(this, OP_RUN_CANCEL)); } } //---------------------------------------------------------------------------- void albaOpImporterLandmark:: OnEvent(albaEventBase *alba_event) { if (albaEvent *e = albaEvent::SafeDownCast(alba_event)) { switch (e->GetId()) { case wxOK: OpStop(OP_RUN_OK); break; case wxCANCEL: OpStop(OP_RUN_CANCEL); break; case ID_TYPE_FILE: case ID_TYPE_SEPARATION: break; default: albaEventMacro(*e); } } } //---------------------------------------------------------------------------- void albaOpImporterLandmark::OpDo() { Read(); wxString path, name, ext; wxSplitPath(m_File.c_str(),&path,&name,&ext); m_VmeCloud->SetName(name); albaTagItem tag_Nature; tag_Nature.SetName("VME_NATURE"); tag_Nature.SetValue("NATURAL"); m_VmeCloud->GetTagArray()->SetTag(tag_Nature); GetLogicManager()->VmeAdd(m_VmeCloud); } //---------------------------------------------------------------------------- void albaOpImporterLandmark::OpStop(int result) { HideGui(); albaEventMacro(albaEvent(this,result)); } //---------------------------------------------------------------------------- void albaOpImporterLandmark::Read() { // need the number of landmarks for the progress bar std::ifstream landmarkNumberPromptFileStream(m_File); int numberOfLines = 0; char line[512], separator; double x = 0, y = 0, z = 0, t = 0; long counter = 0, linesReaded = 0; wxString name; while(!landmarkNumberPromptFileStream.fail()) { landmarkNumberPromptFileStream.getline(line,512); numberOfLines++; } landmarkNumberPromptFileStream.close(); albaNEW(m_VmeCloud); if (m_TestMode == true) { m_VmeCloud->TestModeOn(); } std::ifstream landmarkFileStream(m_File); albaProgressBarHelper progressHelper(m_Listener); progressHelper.SetTextMode(m_TestMode); progressHelper.InitProgressBar("Reading Landmark Cloud"); switch (m_TypeSeparation) //_("Comma"),_("Space"),_("Semicolon"),_("Tab") { case 0: separator = ','; break; case 1: separator = ' '; break; case 2: separator = ';'; case 3: separator = '\t'; break; } while(!landmarkFileStream.fail()) { landmarkFileStream.getline(line, 512); if(line[0] == '#' || albaString(line) == "") { //skip comments and empty lines linesReaded++; continue; } else if(strncmp(line, "Time",4)==0) { char *time = line + 5; t = atof(time); counter = 0; linesReaded++; continue; } else { ConvertLine(line, counter, separator, name, x, y, z); if (m_VmeCloud->GetLandmarkIndex(name.c_str()) == -1) { //New Landmark m_VmeCloud->AppendLandmark(x, y, z, name); if (t != 0) { //this landmark is present only int idx = m_VmeCloud->GetLandmarkIndex(name); m_VmeCloud->SetLandmarkVisibility(idx, false, 0); } } else { //Set an existing landmark m_VmeCloud->SetLandmark(name, x, y, z, t); } bool visibility = !(x == -9999 && y == -9999 && z == -9999); m_VmeCloud->SetLandmarkVisibility(counter, visibility, t); counter++; linesReaded++; progressHelper.UpdateProgressBar(linesReaded * 100 / numberOfLines); } } m_VmeCloud->Modified(); m_VmeCloud->ReparentTo(m_Input); landmarkFileStream.close(); m_Output = m_VmeCloud; } void albaOpImporterLandmark::ConvertLine(char *line, int count, char separator, wxString &name, double &x, double &y, double &z) { wxString str = wxString(line); if (m_OnlyCoordinates) { name = "LM "; name << count; } else { name = str.BeforeFirst(separator); str = str.After(separator); } wxString xStr = str.BeforeFirst(separator); str = str.AfterFirst(separator); wxString yStr = str.BeforeFirst(separator); wxString zStr = str.AfterFirst(separator); xStr.ToDouble(&x); yStr.ToDouble(&y); zStr.ToDouble(&z); }
25.18638
128
0.588587
f2a38d65b98167a68d5ffc9639eab636bee17c11
324
cpp
C++
cpp/example/src/ContainerWithMostH2O/containerWithMostH2O.cpp
zcemycl/algoTest
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
[ "MIT" ]
1
2022-01-26T16:33:45.000Z
2022-01-26T16:33:45.000Z
cpp/example/src/ContainerWithMostH2O/containerWithMostH2O.cpp
zcemycl/algoTest
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
[ "MIT" ]
null
null
null
cpp/example/src/ContainerWithMostH2O/containerWithMostH2O.cpp
zcemycl/algoTest
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
[ "MIT" ]
1
2022-01-26T16:35:44.000Z
2022-01-26T16:35:44.000Z
#include "containerWithMostH2O.h" int containerWithMostH2O::naive(vector<int>& height){ int l=0;int r=height.size()-1; int maxV = min(height[l],height[r])*r; while (l<r){ if (height[l]>=height[r])r-=1; else l+=1; maxV = max(maxV,min(height[l],height[r])*(r-l)); } return maxV; }
24.923077
56
0.57716
f2a96756f9c5581c82820de3bde9780e0eaad7de
3,500
cpp
C++
09/smoke_basin.t.cpp
ComicSansMS/AdventOfCode2021
60902d14c356c3375266703e85aca991241afc84
[ "Unlicense" ]
null
null
null
09/smoke_basin.t.cpp
ComicSansMS/AdventOfCode2021
60902d14c356c3375266703e85aca991241afc84
[ "Unlicense" ]
null
null
null
09/smoke_basin.t.cpp
ComicSansMS/AdventOfCode2021
60902d14c356c3375266703e85aca991241afc84
[ "Unlicense" ]
null
null
null
#include <smoke_basin.hpp> #include <catch.hpp> #include <sstream> TEST_CASE("Smoke Basin") { char const sample_input[] = "2199943210" "\n" "3987894921" "\n" "9856789892" "\n" "8767896789" "\n" "9899965678" "\n"; Heightmap const map = parseInput(sample_input); SECTION("Parse Input") { CHECK(map.width == 10); CHECK(map.height == 5); CHECK(map.map.size() == 50); CHECK(fmt::format("{}", map) == sample_input); } SECTION("Lowest in Neighbourhood") { CHECK(!isLowerThan4Neighbourhood(map, 0, 0)); CHECK(isLowerThan4Neighbourhood(map, 1, 0)); CHECK(isLowerThan4Neighbourhood(map, 9, 0)); CHECK(!isLowerThan4Neighbourhood(map, 0, 4)); CHECK(!isLowerThan4Neighbourhood(map, 9, 4)); } SECTION("Point Equality") { CHECK(Point{ .x = 1, .y = 2 } == Point{ .x = 1, .y = 2 }); CHECK(!(Point{ .x = 0, .y = 2 } == Point{ .x = 1, .y = 2 })); CHECK(!(Point{ .x = 1, .y = 0 } == Point{ .x = 1, .y = 2 })); CHECK(!(Point{ .x = 5, .y = 5 } == Point{ .x = 1, .y = 2 })); } SECTION("Get Low Points") { auto points = getLowPoints(map); REQUIRE(points.size() == 4); CHECK(points[0] == Point{ .x = 1, .y = 0 }); CHECK(points[1] == Point{ .x = 9, .y = 0 }); CHECK(points[2] == Point{ .x = 2, .y = 2 }); CHECK(points[3] == Point{ .x = 6, .y = 4 }); } SECTION("Result 1") { CHECK(result1(map) == 15); } SECTION("Partition Basins") { auto basins = partitionBasins(map); REQUIRE(basins.size() == 4); CHECK(basins[0].points == std::vector{ Point{ .x = 0, .y = 0 }, Point{ .x = 1, .y = 0 }, Point{ .x = 0, .y = 1 }, }); CHECK(basins[1].points == std::vector{ Point{.x = 5, .y = 0 }, Point{.x = 6, .y = 0 }, Point{.x = 7, .y = 0 }, Point{.x = 8, .y = 0 }, Point{.x = 9, .y = 0 }, Point{.x = 6, .y = 1 }, Point{.x = 8, .y = 1 }, Point{.x = 9, .y = 1 }, Point{.x = 9, .y = 2 }, }); CHECK(basins[2].points == std::vector{ Point{.x = 2, .y = 1 }, Point{.x = 3, .y = 1 }, Point{.x = 4, .y = 1 }, Point{.x = 1, .y = 2 }, Point{.x = 2, .y = 2 }, Point{.x = 3, .y = 2 }, Point{.x = 4, .y = 2 }, Point{.x = 5, .y = 2 }, Point{.x = 0, .y = 3 }, Point{.x = 1, .y = 3 }, Point{.x = 2, .y = 3 }, Point{.x = 3, .y = 3 }, Point{.x = 4, .y = 3 }, Point{.x = 1, .y = 4 }, }); CHECK(basins[3].points == std::vector{ Point{.x = 7, .y = 2 }, Point{.x = 6, .y = 3 }, Point{.x = 7, .y = 3 }, Point{.x = 8, .y = 3 }, Point{.x = 5, .y = 4 }, Point{.x = 6, .y = 4 }, Point{.x = 7, .y = 4 }, Point{.x = 8, .y = 4 }, Point{.x = 9, .y = 4 }, }); } SECTION("Result 2") { CHECK(result2(map) == 1134); } }
31.25
69
0.369429
f2ae2ff61ab14da82b661a799256e159355fbb26
1,054
cpp
C++
Source/PracticeVeter/Characters/Animations/BaseCharacterAnimInstance.cpp
mile634/ExperimentalUE
20a7b13af43c79e7b53920b25b451da9212429e3
[ "MIT" ]
null
null
null
Source/PracticeVeter/Characters/Animations/BaseCharacterAnimInstance.cpp
mile634/ExperimentalUE
20a7b13af43c79e7b53920b25b451da9212429e3
[ "MIT" ]
null
null
null
Source/PracticeVeter/Characters/Animations/BaseCharacterAnimInstance.cpp
mile634/ExperimentalUE
20a7b13af43c79e7b53920b25b451da9212429e3
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "BaseCharacterAnimInstance.h" #include "PracticeVeter/Characters/BaseCharacter.h" #include "PracticeVeter/Components/MovementComponents/MyBaseCharacterMovementComponent.h" void UBaseCharacterAnimInstance::NativeBeginPlay() { Super::NativeBeginPlay(); checkf(TryGetPawnOwner()->IsA<ABaseCharacter>(), TEXT("UBaseCharacterAnimInstance::NativeBeginPlay() can be used only with BaseCharacter")); CachedBaseCharacter = StaticCast<ABaseCharacter*>(TryGetPawnOwner()); } void UBaseCharacterAnimInstance::NativeUpdateAnimation(float DeltaSeconds) { Super::NativeUpdateAnimation(DeltaSeconds); if (!CachedBaseCharacter.IsValid()) { return; } UMyBaseCharacterMovementComponent* CharacterMovement = CachedBaseCharacter->GetBaseCharacterMovementComponent(); Speed = CharacterMovement->Velocity.Size(); bIsFalling = CharacterMovement->IsFalling(); bIsCrouching = CharacterMovement->IsCrouching(); bIsSprinting = CharacterMovement->IsSprinting(); }
31.939394
113
0.805503
f2b21addfdadd2d17c3507ad5a4b634ba8889390
741
cpp
C++
DataStructure/c++/Linked-list/Remove loop in Linked List.cpp
Sauradip07/DataStructures-and-Algorithm
d782e2e5cf2caedce7202c4aac43ee0ca3a0c285
[ "MIT" ]
17
2021-09-13T14:50:29.000Z
2022-01-07T10:53:35.000Z
DataStructure/c++/Linked-list/Remove loop in Linked List.cpp
Manish4Kumar/DataStructures-and-Algorithm
7f3b156af8b380a0a2785782e6437a6cc5835448
[ "MIT" ]
15
2021-10-01T04:13:32.000Z
2021-11-05T07:49:55.000Z
DataStructure/c++/Linked-list/Remove loop in Linked List.cpp
Manish4Kumar/DataStructures-and-Algorithm
7f3b156af8b380a0a2785782e6437a6cc5835448
[ "MIT" ]
11
2021-09-23T14:37:03.000Z
2021-11-04T13:22:17.000Z
Remove loop in Linked List : https://practice.geeksforgeeks.org/problems/remove-loop-in-linked-list/1# solution: void removeLoop(Node* head) { Node* low=head; Node* high=head; while(low!=NULL and high!=NULL and high->next!=NULL){ low=low->next; high=high->next->next; if(low==high) break; } if(low==head){ while(high->next!=low){ high=high->next; } high->next=NULL; } else if(low==high){ low=head; while(low->next!=high->next){ low=low->next; high=high->next; } high->next=NULL; } }
25.551724
102
0.453441
f2b290c54fb16b4f60d60b2c9d8596e02023abc1
2,542
cxx
C++
periphery/gpio.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
periphery/gpio.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
periphery/gpio.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
/* * gpio.cxx * * Created on: 30 июля 2014 г. * Author: root */ #include "gpio.h" eErrorTp GpioInInit(u8 gpio) { string str; str= "echo \"" + intToString(gpio) + "\"> /sys/class/gpio/export"; printf("%s\n",str.c_str()); system(str.c_str()); str= "echo \"in\" > /sys/class/gpio/gpio"+intToString(gpio)+"/direction"; printf("%s\n",str.c_str()); system(str.c_str()); return NO_ERROR; } eErrorTp GpioOutInit(u8 gpio, u8 defval) { string str; str= "echo \"" + intToString(gpio) + "\"> /sys/class/gpio/export"; system(str.c_str()); str= "echo \""+ intToString(defval) +"\" > /sys/class/gpio/gpio"+intToString(gpio)+"/value"; system(str.c_str()); str= "echo \"out\" > /sys/class/gpio/gpio"+intToString(gpio)+"/direction"; system(str.c_str()); return NO_ERROR; } u8 GpioInRead(u8 gpio) { string res=ExecResult("cat",(char*)string("/sys/class/gpio/gpio"+intToString(gpio)+"/value").c_str()); //printf("res %s\n",res.c_str()); if (res=="1\n") return 1; else return 0; } eErrorTp GpioOnOff(u8 gpio,u8 val) { string str; //if (val) //val=(~val)&0x1; str= "echo "+ intToString(val) +" > /sys/class/gpio/gpio"+intToString(gpio)+"/value"; system(str.c_str()); printf("%s\n",str.c_str()); return NO_ERROR; } gpio::gpio(string num,string direct,string value){ ngpio=num; int fd = open("/sys/class/gpio/export", O_WRONLY); write(fd, num.c_str(), num.size()); close(fd); access=O_RDONLY; if (direct=="out"){ access=O_WRONLY; } fd_val = open(string_format("/sys/class/gpio/gpio%s/value",num.c_str()).c_str(), access); //write(fd_val, value.c_str(), value.size()); printf("open %s\n",string_format("/sys/class/gpio/gpio%s/value",num.c_str()).c_str()); //printf("Write %s size %d\n",value.c_str(),value.size()); fd_dir = open(string_format("/sys/class/gpio/gpio%s/direction",num.c_str()).c_str(), O_WRONLY); write(fd_dir, direct.c_str(), direct.size()); if (direct=="out") set((char*)value.c_str()); //set("1"); //printf("Write %s size %d\n",value.c_str(),value.size()); //sleep(5); //int fd = open("/sys/class/gpio/gpio23/value", O_WRONLY); } gpio::~gpio(void){ close(fd_val); close(fd_dir); } eErrorTp gpio::set(char * val){ write(fd_val, val, 1); return NO_ERROR; } u32 gpio::get(void){ char buf[2]={0}; u32 len=read(fd_val, buf, 1); //printf("get %d %d len %d\n",buf[0],buf[1],len); close(fd_val); fd_val = open(string_format("/sys/class/gpio/gpio%s/value",ngpio.c_str()).c_str(), access); return atoi(buf); }
21.542373
103
0.623131
f2b2de4d4bf075da5c949471babdd2fb1f2affed
96
cpp
C++
Hololens_Demos/SpatialSoundPlayer/SpatialAudioPlayer.cpp
dvroegop/hololens_helpers
1d3f4cca336758e6a1a1e66739da770c9d936b59
[ "MIT" ]
null
null
null
Hololens_Demos/SpatialSoundPlayer/SpatialAudioPlayer.cpp
dvroegop/hololens_helpers
1d3f4cca336758e6a1a1e66739da770c9d936b59
[ "MIT" ]
null
null
null
Hololens_Demos/SpatialSoundPlayer/SpatialAudioPlayer.cpp
dvroegop/hololens_helpers
1d3f4cca336758e6a1a1e66739da770c9d936b59
[ "MIT" ]
null
null
null
#include "pch.h" #include "SpatialAudioPlayer.h" SpatialAudioPlayer::SpatialAudioPlayer() { }
12
40
0.760417
f2b73aff2628270efc7aad6f35bc915ff0db6efe
791
cpp
C++
test_storage.cpp
squeek502/sol2
f4434393ce820dca0bcbc3a5e74bd3100dbe51b9
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
test_storage.cpp
squeek502/sol2
f4434393ce820dca0bcbc3a5e74bd3100dbe51b9
[ "MIT" ]
null
null
null
test_storage.cpp
squeek502/sol2
f4434393ce820dca0bcbc3a5e74bd3100dbe51b9
[ "MIT" ]
null
null
null
#define SOL_CHECK_ARGUMENTS #include <catch.hpp> #include <sol.hpp> TEST_CASE("storage/registry=construction", "ensure entries from the registry can be retrieved") { const auto& script = R"( function f() return 2 end )"; sol::state lua; sol::function f = lua["f"]; sol::reference r = lua["f"]; sol::function regf(lua, f); sol::reference regr(lua, sol::ref_index(f.registry_index())); bool isequal = f == r; REQUIRE(isequal); isequal = f == regf; REQUIRE(isequal); isequal = f == regr; REQUIRE(isequal); } TEST_CASE("storage/main-thread", "ensure round-tripping and pulling out thread data even on 5.1 with a backup works") { sol::state lua; { sol::stack_guard g(lua); lua_State* orig = lua; lua_State* ts = sol::main_thread(lua, lua); REQUIRE(ts == orig); } }
22.6
119
0.676359
f2bb6efe0f31897af8c8c46b56d5e298bf6d645d
385
hpp
C++
library/ATF/tagLITEM.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/tagLITEM.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/tagLITEM.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE struct tagLITEM { unsigned int mask; int iLink; unsigned int state; unsigned int stateMask; wchar_t szID[48]; wchar_t szUrl[2084]; }; END_ATF_NAMESPACE
20.263158
108
0.657143
f2bcb1eb081756a5c394ddceead203a6b2b9a8fe
515
hpp
C++
Engine/Code/Engine/Math/Ray2.hpp
tonyatpeking/SmuSpecialTopic
b61d44e4efacb3c504847deb4d00234601bca49c
[ "MIT" ]
null
null
null
Engine/Code/Engine/Math/Ray2.hpp
tonyatpeking/SmuSpecialTopic
b61d44e4efacb3c504847deb4d00234601bca49c
[ "MIT" ]
null
null
null
Engine/Code/Engine/Math/Ray2.hpp
tonyatpeking/SmuSpecialTopic
b61d44e4efacb3c504847deb4d00234601bca49c
[ "MIT" ]
1
2019-10-02T01:48:54.000Z
2019-10-02T01:48:54.000Z
#pragma once #include "Engine/Math/Vec2.hpp" class Ray3; class Ray2 { public: // This is not normalized so that the Evaluate T will match with the 3D version static Ray2 FromRay3XZ( const Ray3& ray3 ); Ray2() {}; Ray2( const Vec2& point, const Vec2& dir ); ~Ray2() {}; void SetStartEnd( const Vec2& start, const Vec2& end ); void Normalzie(); Vec2 Evaluate( float t ) const; bool IsValid() { return direction != Vec2::ZEROS; }; public: Vec2 start; Vec2 direction; };
21.458333
83
0.642718
f2bec613e0307a903f3c93b54430727aa51028ac
583
cpp
C++
src/actions/ActionableObject.cpp
MiKlTA/Lust_The_Game
aabe4a951ffd7305526466d378ba8b6769c555e8
[ "MIT" ]
null
null
null
src/actions/ActionableObject.cpp
MiKlTA/Lust_The_Game
aabe4a951ffd7305526466d378ba8b6769c555e8
[ "MIT" ]
null
null
null
src/actions/ActionableObject.cpp
MiKlTA/Lust_The_Game
aabe4a951ffd7305526466d378ba8b6769c555e8
[ "MIT" ]
null
null
null
#include "Action.h" #include "ActionableObject.h" namespace lust { void ActionableObject::addAction(Action *action) { m_dependentActions.insert(action); } void ActionableObject::removeAction(const Action *action) { auto found = std::find( m_dependentActions.begin(), m_dependentActions.end(), action ); if (found != m_dependentActions.end()) { m_dependentActions.erase(found); } } void ActionableObject::invalidate() { for (auto da : m_dependentActions) { da->invalidate(); } } }
15.342105
76
0.620926
f2c02db8e7fd5f2bcfd0e65349df14eaf893ed56
13,140
cpp
C++
src/parser/parser.cpp
toebsen/angreal
772f0b2499ef9b121322f80f2dacdb8754180c38
[ "MIT" ]
4
2020-08-30T21:10:47.000Z
2021-12-28T13:13:21.000Z
src/parser/parser.cpp
toebsen/angreal
772f0b2499ef9b121322f80f2dacdb8754180c38
[ "MIT" ]
12
2020-05-14T12:25:54.000Z
2021-08-01T11:01:23.000Z
src/parser/parser.cpp
toebsen/angreal
772f0b2499ef9b121322f80f2dacdb8754180c38
[ "MIT" ]
null
null
null
// // Created by bichlmaier on 07.02.2020. // #include "parser.h" namespace angreal::parser { Parser::Parser(const error_handler_t& error_handler) : error_handler_(error_handler) {} template <typename Type, typename... Args> std::shared_ptr<Type> Parser::MakeASTNode(Args&&... args) { { auto node = std::make_shared<Type>(std::forward<Args>(args)...); node->SetLine(current_line_number); return node; } } std::shared_ptr<AST::Program> Parser::parseProgram( const std::vector<Token>& tokens) { AST::statements_t statements; current_token = tokens.begin(); next_token = tokens.begin() + 1; while (current_token->type() != Token::Type::EndOfProgram && current_token != tokens.end()) { if (auto stmt = parseStatement()) { statements.push_back(stmt.value()); } } return MakeASTNode<AST::Program>(statements); } expression_t Parser::parseExpression(const std::vector<Token>& tokens) { current_token = tokens.begin(); next_token = tokens.begin() + 1; return parseRelational(); } void Parser::consume() { // std::cout << "consuming: " << *next_token << std::endl; current_token = next_token; next_token = current_token + 1; if (current_token->type() == Token::Type::NewLine) { ++current_line_number; consume(); } } void Parser::expectToken(Token::Type t) const { if (current_token->type() != t) { std::stringstream ss; ss << "Expected " << Token::type2str(t) << ", but got: " << Token::type2str(current_token->type()); error_handler_->ParserError(ss.str(), *current_token); } } expression_t Parser::parseRelational() { expression_t expr = parseAdditive(); if (current_token->type() == Token::Type::RelationalOp) { auto opType = current_token->value(); consume(); auto rhs = parseAdditive(); return MakeASTNode<AST::BinaryOperation>(opType, expr, rhs); } return expr; } expression_t Parser::parseAdditive() { expression_t expr = parseMultiplicative(); if (current_token->type() == Token::Type::AdditiveOp || current_token->type() == Token::Type::AndStatement) { auto opType = current_token->value(); consume(); auto rhs = parseMultiplicative(); return MakeASTNode<AST::BinaryOperation>(opType, expr, rhs); } return expr; } expression_t Parser::parseMultiplicative() { expression_t expr = parseUnary(); if (current_token->type() == Token::Type::MulOp || current_token->type() == Token::Type::DivOp || current_token->type() == Token::Type::OrStatement) { auto opType = current_token->value(); consume(); auto rhs = parsePrimary(); return MakeASTNode<AST::BinaryOperation>(opType, expr, rhs); } return expr; } expression_t Parser::parseUnary() { if (current_token->type() == Token::Type::AdditiveOp || current_token->type() == Token::Type::Exclamation) { auto opType = current_token->value(); consume(); AST::expression_t expression = parseRelational(); return MakeASTNode<AST::UnaryOperation>(opType, expression); } return parseFunctionCall(); } AST::expressions_t Parser::parseActualParams() { AST::expressions_t params; params.push_back(parseRelational()); while (current_token->type() == Token::Type::Comma) { consume(); params.push_back(parseRelational()); } return params; } expression_t Parser::parseFunctionCall() { auto expression = parsePrimary(); while (true) { if (current_token->type() == Token::Type::LeftBracket) { consume(); //( AST::expressions_t args; if (current_token->type() != Token::Type::RightBracket) { args = parseActualParams(); } expectToken(Token::Type::RightBracket); consume(); expression = MakeASTNode<AST::FunctionCall>(expression, args); } else if (current_token->type() == Token::Type::Dot) { consume(); expectToken(Token::Type::Identifier); auto identifier = current_token->value(); consume(); expression = MakeASTNode<AST::Get>(expression, identifier); } else { break; } } return expression; } expression_t Parser::parsePrimary() { if (current_token->type() == Token::Type::Boolean || current_token->type() == Token::Type::Integer || current_token->type() == Token::Type::Float || current_token->type() == Token::Type::String) { TypeHelper::Type decl = TypeHelper::mapTokenToLiteralType(current_token->type()); auto value = current_token->value(); consume(); return TypeHelper::mapTypeToLiteral(decl, value); } if (current_token->type() == Token::Type::SelfStatement) { consume(); return MakeASTNode<AST::Self>(); } if (current_token->type() == Token::Type::Identifier) { auto value = current_token->value(); consume(); if (value == "super") { expectToken(Token::Type::Dot); consume(); expectToken(Token::Type::Identifier); auto ident = current_token->value(); consume(); return MakeASTNode<AST::Super>(ident); } return MakeASTNode<AST::IdentifierLiteral>(value); } if (current_token->type() == Token::Type::LeftBracket) { consume(); auto expression = parseRelational(); expectToken(Token::Type::RightBracket); consume(); return expression; } return nullptr; } statement_t Parser::parseVariableDeclaration() { std::string identifier; AST::expression_t expression; consume(); expectToken(Token::Type::Identifier); identifier = current_token->value(); consume(); expectToken(Token::Type::Equal); consume(); expression = parseRelational(); return MakeASTNode<AST::Declaration>(identifier, expression); } expression_t Parser::parseAssignment(const expression_t& expression) { expectToken(Token::Type::Equal); consume(); auto value = parseRelational(); if (auto ident = std::dynamic_pointer_cast<IdentifierLiteral>(expression)) { return MakeASTNode<AST::Assignment>(ident->name, value); } if (auto get = std::dynamic_pointer_cast<Get>(expression)) { return MakeASTNode<AST::Set>(get->expression, get->identifier, value); } return nullptr; } AST::formal_parameters Parser::parseFormalParameters() { AST::formal_parameters parameters; expectToken(Token::Type::LeftBracket); consume(); if (current_token->type() != Token::Type::RightBracket) { while (current_token->type() != Token::Type::RightBracket) { auto param = parseFormalParameter(); parameters.push_back(param); if (current_token->type() != Token::Type::RightBracket) { expectToken(Token::Type::Comma); consume(); } } } expectToken(Token::Type::RightBracket); consume(); return parameters; } std::shared_ptr<AST::FormalParameter> Parser::parseFormalParameter() { expectToken(Token::Type::Identifier); std::string identifier = current_token->value(); consume(); return MakeASTNode<AST::FormalParameter>(identifier); } statement_t Parser::parseFunctionDeclaration() { std::string identifier; consume(); expectToken(Token::Type::Identifier); identifier = current_token->value(); consume(); auto parameters = parseFormalParameters(); auto block = std::dynamic_pointer_cast<Block>(parseBlock()); return MakeASTNode<AST::FunctionDeclaration>(identifier, parameters, block->statements); } statement_t Parser::parseBlock() { AST::statements_t statements; expectToken(Token::Type::LeftCurlyBracket); consume(); if (current_token->type() == Token::Type::RightCurlyBracket) { // don't parse empty block consume(); return MakeASTNode<AST::Block>(statements); } do { if (auto stmt = parseStatement()) { statements.push_back(stmt.value()); } } while (!(current_token->type() == Token::Type::RightCurlyBracket || current_token->type() == Token::Type::EndOfProgram)); expectToken(Token::Type::RightCurlyBracket); consume(); return MakeASTNode<AST::Block>(statements); } statement_t Parser::parseReturnDeclaration() { AST::expression_t expression; consume(); expression = parseRelational(); return MakeASTNode<AST::Return>(expression); } statement_t Parser::parsePrintStatement() { AST::expressions_t args; consume(); // identifier consume(); //( if (current_token->type() != Token::Type::RightBracket) { args = parseActualParams(); } expectToken(Token::Type::RightBracket); consume(); return MakeASTNode<AST::Print>(args); } std::optional<statement_t> Parser::parseStatement() { current_line_number = current_token->position().line; if (current_token->type() == Token::Type::VarStatement) { return parseVariableDeclaration(); } if (current_token->type() == Token::Type::DefStatement) { return parseFunctionDeclaration(); } if (current_token->type() == Token::Type::ClassStatement) { return parseClassDeclaration(); } if (current_token->type() == Token::Type::PrintStatement) { return parsePrintStatement(); } if (current_token->type() == Token::Type::LeftCurlyBracket) { return parseBlock(); } if (current_token->type() == Token::Type::ReturnStatement) { return parseReturnDeclaration(); } if (current_token->type() == Token::Type::IfStatement) { return parseIfStatement(); } if (current_token->type() == Token::Type::WhileStatement) { return parseWhileStatement(); } if (current_token->type() == Token::Type::EndOfProgram) { return std::nullopt; } if (current_token->type() == Token::Type::Comment) { consume(); return std::nullopt; } auto expr = parseRelational(); if (current_token->type() == Token::Type::Equal) { expr = parseAssignment(expr); } if (expr) { return MakeASTNode<ExpressionStatement>(expr); } consume(); return std::nullopt; } statement_t Parser::parseIfStatement() { consume(); expression_t condition = parseRelational(); block_t if_branch = std::dynamic_pointer_cast<Block>(parseBlock()); block_t else_branch; if (current_token->type() == Token::Type::Identifier && current_token->value() == "else") { consume(); else_branch = std::dynamic_pointer_cast<Block>(parseBlock()); } return MakeASTNode<AST::IfStatement>(condition, if_branch, else_branch); } statement_t Parser::parseWhileStatement() { consume(); expression_t condition = parseRelational(); block_t block = std::dynamic_pointer_cast<Block>(parseBlock()); return MakeASTNode<AST::WhileStatement>(condition, block); } statement_t Parser::parseClassDeclaration() { consume(); // class expectToken(Token::Type::Identifier); auto identifier = *current_token; consume(); std::optional<identifier_t> superclass; if (current_token->type() == Token::Type::LeftBracket) { // optional superclass consume(); expectToken(Token::Type::Identifier); superclass = MakeASTNode<IdentifierLiteral>(current_token->value()); consume(); expectToken(Token::Type::RightBracket); consume(); } expectToken(Token::Type::LeftCurlyBracket); consume(); functions_t methods; while (true) { if (current_token->type() == Token::Type::RightCurlyBracket) { break; } if (current_token->type() == Token::Type::DefStatement) { methods.push_back(std::dynamic_pointer_cast<FunctionDeclaration>( parseFunctionDeclaration())); } else { error_handler_->ParserError( "Only function declarations are allowed inside declaration of " "class !", identifier); break; } } expectToken(Token::Type::RightCurlyBracket); consume(); return MakeASTNode<AST::ClassDeclaration>(identifier.value(), methods, superclass); } } // namespace angreal::parser
31.211401
81
0.59863
f2c03315b9f772048e9285a63a30d5021f782a3e
1,800
cpp
C++
client/src/user_interface/game_over.cpp
dima1997/PORTAL_2D_copy
7618d970feded3fc05fda0c422a5d76a1d3056c7
[ "MIT" ]
null
null
null
client/src/user_interface/game_over.cpp
dima1997/PORTAL_2D_copy
7618d970feded3fc05fda0c422a5d76a1d3056c7
[ "MIT" ]
null
null
null
client/src/user_interface/game_over.cpp
dima1997/PORTAL_2D_copy
7618d970feded3fc05fda0c422a5d76a1d3056c7
[ "MIT" ]
null
null
null
#include "../../includes/user_interface/game_over.h" #include "ui_GameOver.h" #include "../../includes/threads/play_result.h" #include <QWidget> #include <QDesktopWidget> #include <string> #define WINDOW_WIDTH 640 #define WINDOW_HEIGHT 480 /* PRE: Recibe un resultado de juego. POST:Iniicaliza una ventana de fin de juego. */ GameOver::GameOver(PlayResult & playResult, QWidget *parent) : QWidget(parent) { Ui::GameOver gameOver; gameOver.setupUi(this); this->setFixedSize(WINDOW_WIDTH, WINDOW_HEIGHT); this->hide(); this->move( QApplication::desktop()->screen()->rect().center() - (this->rect()).center() ); this->set_game_status(playResult); this->set_players_status(playResult); } /* PRE: Recibe el resultado de un juego. POST: Setea la etiqueta de estado del juego. */ void GameOver::set_game_status(PlayResult & playResult){ QLabel* gameStatusLabel = findChild<QLabel*>("gameStatusLabel"); GameStatus gameStatus = playResult.get_game_status(); if (gameStatus == GAME_STATUS_WON){ gameStatusLabel->setText("WON"); } else if (gameStatus == GAME_STATUS_LOST){ gameStatusLabel->setText("LOST"); } else { gameStatusLabel->setText("NOT_FINISHED"); } gameStatusLabel->setStyleSheet("QLabel { color : white; font-size: 20pt }"); } /* PRE: Recibe el resultado de un juego. POST: Setea el estado de los jugadores en el text browser. */ void GameOver::set_players_status(PlayResult & playResult){ QTextBrowser* playersStatusTextBrowser = findChild<QTextBrowser*>("playersStatusTextBrowser"); std::string playersStatusStr = playResult.get_players_status(); playersStatusTextBrowser->append(playersStatusStr.c_str()); } /*Destruye ventantana.*/ GameOver::~GameOver() = default;
28.571429
80
0.707778
f2c0b8fb27d8d25f924b9a57f850141d94ee4687
9,663
cp
C++
MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Account_Panels/Authentication_Panels/CPrefsAccountAuth.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
12
2015-04-21T16:10:43.000Z
2021-11-05T13:41:46.000Z
MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Account_Panels/Authentication_Panels/CPrefsAccountAuth.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
2
2015-11-02T13:32:11.000Z
2019-07-10T21:11:21.000Z
MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Account_Panels/Authentication_Panels/CPrefsAccountAuth.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
6
2015-01-12T08:49:12.000Z
2021-03-27T09:11:10.000Z
/* Copyright (c) 2007 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Source for CPrefsAccountAuth class #include "CPrefsAccountAuth.h" #include "CAuthPlugin.h" #include "CCertificateManager.h" #include "CINETAccount.h" #include "CMulberryCommon.h" #include "CPluginManager.h" #include "CPreferences.h" #include "CPreferencesDialog.h" #include "CPrefsAuthPanel.h" #include "CPrefsAuthPlainText.h" #include "CPrefsAuthKerberos.h" #include "CPrefsAuthAnonymous.h" #include <LCheckBox.h> #include <LPopupButton.h> // C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S // Default constructor CPrefsAccountAuth::CPrefsAccountAuth() { mCurrentPanel = nil; mCurrentPanelNum = 0; } // Constructor from stream CPrefsAccountAuth::CPrefsAccountAuth(LStream *inStream) : CPrefsTabSubPanel(inStream) { mCurrentPanel = nil; mCurrentPanelNum = 0; } // Default destructor CPrefsAccountAuth::~CPrefsAccountAuth() { } // O T H E R M E T H O D S ____________________________________________________________________________ // Get details of sub-panes void CPrefsAccountAuth::FinishCreateSelf(void) { // Do inherited CPrefsTabSubPanel::FinishCreateSelf(); // Get controls mAuthPopup = (LPopupButton*) FindPaneByID(paneid_AccountAuthPopup); mAuthSubPanel = (LView*) FindPaneByID(paneid_AccountAuthPanel); mTLSPopup = (LPopupButton*) FindPaneByID(paneid_AccountTLSPopup); mUseTLSClientCert = (LCheckBox*) FindPaneByID(paneid_AccountUseTLSClientCert); mTLSClientCert = (LPopupButton*) FindPaneByID(paneid_AccountTLSClientCert); BuildCertPopup(); // Link controls to this window UReanimator::LinkListenerToBroadcasters(this,this,RidL_CPrefsAccountAuthBtns); // Start with first panel SetAuthPanel(cdstring::null_str); } // Handle buttons void CPrefsAccountAuth::ListenToMessage( MessageT inMessage, void *ioParam) { switch (inMessage) { case msg_MailAccountAuth: { cdstring temp = ::GetPopupMenuItemTextUTF8(mAuthPopup); SetAuthPanel(temp); break; } case msg_AccountTLSPopup: TLSItemsState(); break; case msg_AccountUseTLSClientCert: TLSItemsState(); break; } } // Toggle display of IC void CPrefsAccountAuth::ToggleICDisplay(bool IC_on) { if (mCurrentPanel) mCurrentPanel->ToggleICDisplay(IC_on); } // Set prefs void CPrefsAccountAuth::SetData(void* data) { CINETAccount* account = (CINETAccount*) data; // Build popup from panel BuildAuthPopup(account); if (mCurrentPanel) mCurrentPanel->SetAuth(account->GetAuthenticator().GetAuthenticator()); InitTLSItems(account); mTLSPopup->SetValue(account->GetTLSType() + 1); mUseTLSClientCert->SetValue(account->GetUseTLSClientCert()); // Match fingerprint in list for(cdstrvect::const_iterator iter = mCertFingerprints.begin(); iter != mCertFingerprints.end(); iter++) { if (account->GetTLSClientCert() == *iter) { ::SetPopupByName(mTLSClientCert, mCertSubjects.at(iter - mCertFingerprints.begin())); break; } } TLSItemsState(); } // Force update of prefs void CPrefsAccountAuth::UpdateData(void* data) { CINETAccount* account = (CINETAccount*) data; // Copy info from panel into prefs cdstring temp = ::GetPopupMenuItemTextUTF8(mAuthPopup); // Special for anonymous if (mAuthPopup->GetValue() == ::CountMenuItems(mAuthPopup->GetMacMenuH()) - 1) temp = "None"; account->GetAuthenticator().SetDescriptor(temp); if (mCurrentPanel) mCurrentPanel->UpdateAuth(account->GetAuthenticator().GetAuthenticator()); int popup = mTLSPopup->GetValue() - 1; account->SetTLSType((CINETAccount::ETLSType) (mTLSPopup->GetValue() - 1)); account->SetUseTLSClientCert(mUseTLSClientCert->GetValue()); if (account->GetUseTLSClientCert() && ::CountMenuItems(mTLSClientCert->GetMacMenuH())) account->SetTLSClientCert(mCertFingerprints.at(mTLSClientCert->GetValue() - 1)); else account->SetTLSClientCert(cdstring::null_str); } // Set auth panel void CPrefsAccountAuth::SetAuthPanel(const cdstring& auth_type) { // Find matching auth plugin CAuthPlugin* plugin = CPluginManager::sPluginManager.GetAuthPlugin(auth_type); CAuthPlugin::EAuthPluginUIType ui_type = plugin ? plugin->GetAuthUIType() : (auth_type == "Plain Text" ? CAuthPlugin::eAuthUserPswd : CAuthPlugin::eAuthAnonymous); ResIDT panel; switch(ui_type) { case CAuthPlugin::eAuthUserPswd: panel = paneid_PrefsAuthPlainText; break; case CAuthPlugin::eAuthKerberos: panel = paneid_PrefsAuthKerberos; break; case CAuthPlugin::eAuthAnonymous: panel = paneid_PrefsAuthAnonymous; break; } if (mAuthType != auth_type) { mAuthType = auth_type; // First remove and update any existing panel mAuthSubPanel->DeleteAllSubPanes(); // Update to new panel id mCurrentPanelNum = panel; // Make panel area default so new panel is automatically added to it if (panel) { SetDefaultView(mAuthSubPanel); mAuthSubPanel->Hide(); CPreferencesDialog* prefs_dlog = (CPreferencesDialog*) mSuperView; while(prefs_dlog->GetPaneID() != paneid_PreferencesDialog) prefs_dlog = (CPreferencesDialog*) prefs_dlog->GetSuperView(); LCommander* defCommander; prefs_dlog->GetSubCommanders().FetchItemAt(1, defCommander); prefs_dlog->SetDefaultCommander(defCommander); mCurrentPanel = (CPrefsAuthPanel*) UReanimator::ReadObjects('PPob', mCurrentPanelNum); mCurrentPanel->FinishCreate(); mAuthSubPanel->Show(); } else { mAuthSubPanel->Refresh(); mCurrentPanel = nil; } } } void CPrefsAccountAuth::BuildAuthPopup(CINETAccount* account) { // Copy info cdstring set_name; short set_value = -1; switch(account->GetAuthenticatorType()) { case CAuthenticator::eNone: set_value = -1; break; case CAuthenticator::ePlainText: set_value = 1; break; case CAuthenticator::eSSL: set_value = 0; break; case CAuthenticator::ePlugin: set_name = account->GetAuthenticator().GetDescriptor(); break; } // Remove any existing plugin items from main menu MenuHandle menuH = mAuthPopup->GetMacMenuH(); short num_remove = ::CountMenuItems(menuH) - 4; for(short i = 0; i < num_remove; i++) ::DeleteMenuItem(menuH, 2); cdstrvect plugin_names; CPluginManager::sPluginManager.GetAuthPlugins(plugin_names); std::sort(plugin_names.begin(), plugin_names.end()); short index = 1; for(cdstrvect::const_iterator iter = plugin_names.begin(); iter != plugin_names.end(); iter++, index++) { ::InsertMenuItem(menuH, "\p?", index); ::SetMenuItemTextUTF8(menuH, index + 1, *iter); if (*iter == set_name) set_value = index + 1; } // Force max/min update mAuthPopup->SetMenuMinMax(); // Set value StopListening(); mAuthPopup->SetValue((set_value > 0) ? set_value : index + 3 + set_value); StartListening(); cdstring temp = ::GetPopupMenuItemTextUTF8(mAuthPopup); SetAuthPanel(temp); } void CPrefsAccountAuth::InitTLSItems(CINETAccount* account) { // Enable each item based on what the protocol supports bool enabled = false; for(int i = CINETAccount::eNoTLS; i <= CINETAccount::eTLSTypeMax; i++) { if (account->SupportsTLSType(static_cast<CINETAccount::ETLSType>(i))) { ::EnableItem(mTLSPopup->GetMacMenuH(), i + 1); enabled = true; } else ::DisableItem(mTLSPopup->GetMacMenuH(), i + 1); } // Hide if no plugin present or none enabled if (enabled && CPluginManager::sPluginManager.HasSSL()) { mTLSPopup->Show(); FindPaneByID(paneid_AccountTLSGroup)->Show(); //mUseTLSClientCert->Show(); //mTLSClientCert->Show(); } else { mTLSPopup->Hide(); FindPaneByID(paneid_AccountTLSGroup)->Hide(); //mUseTLSClientCert->Hide(); //mTLSClientCert->Hide(); // Disable the auth item ::DisableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue()); } } void CPrefsAccountAuth::BuildCertPopup() { // Only if certs are available if (CCertificateManager::HasCertificateManager()) { // Get list of private certificates CCertificateManager::sCertificateManager->GetPrivateCertificates(mCertSubjects, mCertFingerprints); // Remove any existing items from main menu MenuHandle menuH = mTLSClientCert->GetMacMenuH(); while(::CountMenuItems(menuH)) ::DeleteMenuItem(menuH, 1); short index = 1; for(cdstrvect::const_iterator iter = mCertSubjects.begin(); iter != mCertSubjects.end(); iter++, index++) ::AppendItemToMenu(menuH, index, (*iter).c_str()); // Force max/min update mTLSClientCert->SetMenuMinMax(); } } void CPrefsAccountAuth::TLSItemsState() { // TLS popup if (mTLSPopup->GetValue() - 1 == CINETAccount::eNoTLS) { mUseTLSClientCert->Disable(); mTLSClientCert->Disable(); if (mAuthPopup->GetValue() == mAuthPopup->GetMaxValue()) mAuthPopup->SetValue(1); ::DisableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue()); } else { mUseTLSClientCert->Enable(); if (mUseTLSClientCert->GetValue()) { mTLSClientCert->Enable(); ::EnableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue()); } else { mTLSClientCert->Disable(); if (mAuthPopup->GetValue() == mAuthPopup->GetMaxValue()) mAuthPopup->SetValue(1); ::DisableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue()); } } }
26.841667
107
0.732381
f2c10f99fbebf3fd599e1bcd8fd28bbbfa8ac15a
676
cpp
C++
binary-tree/check-if-subtree.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
binary-tree/check-if-subtree.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
binary-tree/check-if-subtree.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct Node { int data; Node *left; Node *right; Node(int x) { data = x; left = nullptr; right = nullptr; } }; bool isIdentical(Node* T, Node* S) { if (!T && !S) return true; if (!T || !S) return false; return T->data == S->data && isIdentical(T->left, S->left) && isIdentical(T->right, S->right); } bool isSubTree(Node* T, Node* S) { if (!S) return true; if (!T) return false; if (isIdentical(T, S)) return true; return isSubTree(T->left, S) || isSubTree(T->right, S); }
18.27027
99
0.486686
f2c43230a7babcb209a2c7b93636ad6da4111bc2
755
cpp
C++
ReeeEngine/src/ReeeEngine/Rendering/Context/SampleState.cpp
Lewisscrivens/ReeeEngine
abb31ef7e1adb553fafe02c4f9bd60ceb520acbf
[ "MIT" ]
null
null
null
ReeeEngine/src/ReeeEngine/Rendering/Context/SampleState.cpp
Lewisscrivens/ReeeEngine
abb31ef7e1adb553fafe02c4f9bd60ceb520acbf
[ "MIT" ]
null
null
null
ReeeEngine/src/ReeeEngine/Rendering/Context/SampleState.cpp
Lewisscrivens/ReeeEngine
abb31ef7e1adb553fafe02c4f9bd60ceb520acbf
[ "MIT" ]
null
null
null
#include "SampleState.h" namespace ReeeEngine { SampleState::SampleState(Graphics& graphics) { // Create sampler default options for UV read type. D3D11_SAMPLER_DESC samplerOptions = {}; samplerOptions.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerOptions.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerOptions.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerOptions.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; // Create sampler state and check/log errors. HRESULT result = GetDevice(graphics)->CreateSamplerState(&samplerOptions, &sampler); LOG_DX_ERROR(result); } void SampleState::Add(Graphics& graphics) noexcept { // Add sampler to rendering pipeline. GetContext(graphics)->PSSetSamplers(0, 1, sampler.GetAddressOf()); } }
31.458333
86
0.778808
f2c4b177991326df24f69a82d0f92a72c44a23c9
3,632
cpp
C++
03/minik/src/target_x86/x86_conv.cpp
nokia-wroclaw/nokia-book
dd397958b5db039a2f53e555c2becfc419065264
[ "MIT" ]
104
2015-06-30T07:41:42.000Z
2022-02-28T08:56:37.000Z
03/minik/src/target_x86/x86_conv.cpp
nokia-wroclaw/nokia-book
dd397958b5db039a2f53e555c2becfc419065264
[ "MIT" ]
null
null
null
03/minik/src/target_x86/x86_conv.cpp
nokia-wroclaw/nokia-book
dd397958b5db039a2f53e555c2becfc419065264
[ "MIT" ]
22
2015-06-11T14:40:49.000Z
2021-12-27T19:13:11.000Z
#include "analysis/control_flow_graph.hpp" #include "analysis/live_variables.hpp" #include "ir/ir_printer.hpp" #include "x86_assembler.hpp" #include "x86_conv.hpp" #include "utils/headers.hpp" #include <list> #include <iostream> namespace { Ir::Block rewrite_block(SymbolTable &st, const Ir::Block &_block) { Ir::Block result = _block; step("live variables"); auto cfg = buildControlFlowGraph(result); auto lv = LiveVariablesDataFlowAnalysis::analyse(cfg); LiveVariablesDataFlowAnalysis::dump(std::cerr, cfg, lv); auto it = result.begin(); std::set<int> visited; step("input"); std::cerr << to_string(result) << "\n"; step("transformation"); while (it != result.end()) { if (it->type == Ir::InstructionType::Call and visited.find(it->extra) == visited.end()) { auto v = it->extra; auto lv_in = lv.entry[v]; const auto &fdef = st.getFunction(it->arguments[0]); visited.insert(v); auto orig_it = it; std::cerr << "found call: " << to_string(*it) << "\n"; std::cerr << "live variables at entry: " << LiveVariablesDataFlowAnalysis::to_string(lv.entry.at(v)) << "\n"; std::string ret; for (auto r : fdef.modifiedRegs) { ret += " "; ret += to_string(r); } std::cerr << "function modifies: " << ret << "\n"; bool hasArguments = false; do { --it; hasArguments |= it->type == Ir::InstructionType::Push; } while (it->type == Ir::InstructionType::Push); ++it; std::list<Ir::Argument> saved; for (auto r : lv_in) { if (r.is(Ir::ArgumentType::PinnedHardRegister) and fdef.modifiedRegs.find(r) != fdef.modifiedRegs.end()) { auto helper = Ir::Instruction{Ir::InstructionType::Push, {r}, 0}; result.insert(it, helper); saved.push_front(r); } } if (saved.size() > 0) { it = orig_it; ++it; if (hasArguments) ++it; for (auto r : saved) { auto helper = Ir::Instruction{Ir::InstructionType::Pop, {r}, 0}; result.insert(it, helper); } } } // TODO: temporary remove of Meta instructions CallerSave/CallerRestore if (it->type == Ir::InstructionType::Meta) { if (it->arguments[0].content == int(Ir::MetaTag::CallerSave) or it->arguments[0].content == int(Ir::MetaTag::CallerRestore)) { it = result.erase(it); } } else { ++it; } } step("output"); std::cerr << to_string(result) << "\n"; return result; } } // end of anonymous namespace std::set<Ir::Argument> getAllGeneralPurposeHardRegisters() { std::set<Ir::Argument> ir; for (int i = 0; i < 6; i++) { ir.insert(Ir::Argument::PinnedHardRegister(i)); } return ir; } void x86_conv(SymbolTable &st) { for (auto &p : st.functionsMap) { if (p.second.predefined) { p.second.modifiedRegs = getAllGeneralPurposeHardRegisters(); } else { p.second.modifiedRegs = computeModifiedRegisters(p.second.body); } } for (auto &p : st.functionsMap) { if (not p.second.predefined) { subpass("fuction " + p.second.name); p.second.body = rewrite_block(st, p.second.body); } } }
27.725191
122
0.528359
f2c4dc83ec8d1f9807509068206be97a0cce3eb0
407
cc
C++
examples/Example3/main.cc
stognini/AdePT
9a106b83f421938ad8f4d8567d199c84f339e6c9
[ "Apache-2.0" ]
null
null
null
examples/Example3/main.cc
stognini/AdePT
9a106b83f421938ad8f4d8567d199c84f339e6c9
[ "Apache-2.0" ]
null
null
null
examples/Example3/main.cc
stognini/AdePT
9a106b83f421938ad8f4d8567d199c84f339e6c9
[ "Apache-2.0" ]
null
null
null
// SPDX-FileCopyrightText: 2020 CERN // SPDX-License-Identifier: Apache-2.0 #include "common.h" #include "loop.h" #include <iostream> int main(int argc, char **argv) { if (argc != 2) { std::cout << "Usage: " << argv[0] << " nparticles" << std::endl; return 0; } int nparticles = std::atoi(argv[1]); #ifndef __CUDACC__ simulate(nparticles); #else simulate_all(nparticles); #endif return 0; }
15.653846
66
0.653563
f2d318974ca25caa783bfda28c4121b7d15a1c02
354
cpp
C++
src/L/L1226.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
src/L/L1226.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
src/L/L1226.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; string s; string o; main(){ long long a; bool first=true; cin>>a; s+=to_string(a); sort(s.begin(),s.end()); for(int i=2;i<=9;i++){ o.clear(); o+=to_string(a*i); sort(o.begin(),o.end()); if(s==o){ if(!first) cout<<" "; cout<<i; first=false; } } if(first) cout<<"NO"; cout<<endl; }
14.16
26
0.553672
f2d7680e1d2d38fcd1f235c4d44731acfc3b1834
11,285
hpp
C++
src/core/TChem_KineticModelGasConstData.hpp
sandialabs/TChem
c9d00d7d283c8687a5aa4549161e29a08d3d39d6
[ "BSD-2-Clause" ]
30
2020-10-28T08:07:36.000Z
2022-03-29T15:22:30.000Z
src/core/TChem_KineticModelGasConstData.hpp
sandialabs/TChem
c9d00d7d283c8687a5aa4549161e29a08d3d39d6
[ "BSD-2-Clause" ]
2
2021-02-22T21:47:47.000Z
2022-03-16T16:38:07.000Z
src/core/TChem_KineticModelGasConstData.hpp
sandialabs/TChem
c9d00d7d283c8687a5aa4549161e29a08d3d39d6
[ "BSD-2-Clause" ]
10
2020-10-28T01:11:41.000Z
2021-06-16T08:15:28.000Z
/* ===================================================================================== TChem version 2.0 Copyright (2020) NTESS https://github.com/sandialabs/TChem Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software. This file is part of TChem. TChem is open source software: you can redistribute it and/or modify it under the terms of BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause). A copy of the licese is also provided under the main directory Questions? Contact Cosmin Safta at <csafta@sandia.gov>, or Kyungjoo Kim at <kyukim@sandia.gov>, or Oscar Diaz-Ibarra at <odiazib@sandia.gov> Sandia National Laboratories, Livermore, CA, USA ===================================================================================== */ #ifndef __TCHEM_KINETIC_MODEL_GAS_CONST_DATA_HPP__ #define __TCHEM_KINETIC_MODEL_GAS_CONST_DATA_HPP__ #include "TChem_Util.hpp" #include "TChem_KineticModelData.hpp" namespace TChem { template<typename DeviceType> struct KineticModelGasConstData { public: using device_type = DeviceType; using exec_space_type = typename device_type::execution_space; /// non const using real_type_0d_view_type = Tines::value_type_0d_view<real_type,device_type>; using real_type_1d_view_type = Tines::value_type_1d_view<real_type,device_type>; using real_type_2d_view_type = Tines::value_type_2d_view<real_type,device_type>; using real_type_3d_view_type = Tines::value_type_3d_view<real_type,device_type>; using ordinal_type_1d_view = Tines::value_type_1d_view<ordinal_type,device_type>; using ordinal_type_2d_view = Tines::value_type_2d_view<ordinal_type,device_type>; using string_type_1d_view_type = Tines::value_type_1d_view<char [LENGTHOFSPECNAME + 1],device_type>; //// const views using kmcd_ordinal_type_1d_view = ConstUnmanaged<ordinal_type_1d_view>; using kmcd_ordinal_type_2d_view = ConstUnmanaged<ordinal_type_2d_view>; using kmcd_real_type_1d_view = ConstUnmanaged<real_type_1d_view_type>; using kmcd_real_type_2d_view = ConstUnmanaged<real_type_2d_view_type>; using kmcd_real_type_3d_view = ConstUnmanaged<real_type_3d_view_type>; using kmcd_string_type_1d_view =ConstUnmanaged<string_type_1d_view_type>; real_type rho; kmcd_string_type_1d_view speciesNames; // ordinal_type nNASAinter; // ordinal_type nCpCoef; // ordinal_type nArhPar; // ordinal_type nLtPar; // ordinal_type nJanPar; // ordinal_type nFit1Par; // ordinal_type nIonSpec; // ordinal_type electrIndx; // ordinal_type nIonEspec; ordinal_type nElem; // this include all elements from chem.inp ordinal_type NumberofElementsGas; // this only include elements present in gas species ordinal_type nSpec; ordinal_type nReac; // ordinal_type nNASA9coef; ordinal_type nThbReac; // ordinal_type maxTbInReac; ordinal_type nFallReac; ordinal_type nFallPar; // ordinal_type maxSpecInReac; ordinal_type maxOrdPar; ordinal_type nRealNuReac; ordinal_type nRevReac; ordinal_type nOrdReac; ordinal_type nPlogReac; ordinal_type jacDim; bool enableRealReacScoef; real_type Runiv; real_type Rcal; real_type Rcgs; real_type TthrmMin; real_type TthrmMax; // kmcd_string_type_1d_view<LENGTHOFSPECNAME+1> sNames ; // kmcd_ordinal_type_1d_view spec9t; // kmcd_ordinal_type_1d_view spec9nrng; // kmcd_ordinal_type_1d_view sigNu; kmcd_ordinal_type_1d_view reacTbdy; kmcd_ordinal_type_1d_view reacTbno; // kmcd_ordinal_type_1d_view reac_to_Tbdy_index; kmcd_ordinal_type_1d_view reacPfal; kmcd_ordinal_type_1d_view reacPtype; kmcd_ordinal_type_1d_view reacPlohi; kmcd_ordinal_type_1d_view reacPspec; kmcd_ordinal_type_1d_view isRev; // kmcd_ordinal_type_1d_view isDup; kmcd_ordinal_type_1d_view reacAOrd; // kmcd_ordinal_type_1d_view reacNrp; kmcd_ordinal_type_1d_view reacNreac; kmcd_ordinal_type_1d_view reacNprod; kmcd_ordinal_type_1d_view reacScoef; kmcd_ordinal_type_1d_view reacRnu; kmcd_ordinal_type_1d_view reacRev; kmcd_ordinal_type_1d_view reacHvIdx; kmcd_ordinal_type_1d_view reacPlogIdx; kmcd_ordinal_type_1d_view reacPlogPno; // kmcd_ordinal_type_1d_view sNion; // kmcd_ordinal_type_1d_view sCharge; // kmcd_ordinal_type_1d_view sTfit; // kmcd_ordinal_type_1d_view sPhase; kmcd_real_type_2d_view NuIJ; kmcd_ordinal_type_2d_view specTbdIdx; kmcd_real_type_2d_view reacNuki; kmcd_ordinal_type_2d_view reacSidx; kmcd_ordinal_type_2d_view specAOidx; // kmcd_ordinal_type_2d_view elemCount; kmcd_real_type_1d_view sMass; // kmcd_real_type_1d_view Tlo; kmcd_real_type_1d_view Tmi; // kmcd_real_type_1d_view Thi; // kmcd_real_type_1d_view sigRealNu; // kmcd_real_type_1d_view reacHvPar; kmcd_real_type_1d_view kc_coeff; // kmcd_real_type_1d_view eMass; kmcd_real_type_2d_view RealNuIJ; kmcd_real_type_2d_view reacArhenFor; kmcd_real_type_2d_view reacArhenRev; kmcd_real_type_2d_view specTbdEff; kmcd_real_type_2d_view reacPpar; kmcd_real_type_2d_view reacRealNuki; kmcd_real_type_2d_view specAOval; kmcd_real_type_2d_view reacPlogPars; kmcd_real_type_3d_view cppol; kmcd_real_type_2d_view stoiCoefMatrix; // kmcd_real_type_3d_view spec9trng; // kmcd_real_type_3d_view spec9coefs; }; template<typename DT> KineticModelGasConstData<DT> createGasKineticModelConstData(const KineticModelData & kmd) { KineticModelGasConstData<DT> data; // using DT = typename DeviceType::execution_space; /// given from non-const kinetic model data data.rho = real_type(-1); /// there is no minus density if this is minus, rhoset = 0 data.speciesNames = kmd.sNames_.template view<DT>(); // data.nNASAinter = kmd.nNASAinter_; // data.nCpCoef = kmd.nCpCoef_; // data.nArhPar = kmd.nArhPar_; // data.nLtPar = kmd.nLtPar_; // data.nJanPar = kmd.nJanPar_; // data.nFit1Par = kmd.nFit1Par_; // data.nIonSpec = kmd.nIonSpec_; // data.electrIndx = kmd.electrIndx_; // data.nIonEspec = kmd.nIonEspec_; data.nElem = kmd.nElem_; // includes all elements from chem.inp data.NumberofElementsGas = kmd.NumberofElementsGas_; // only includes elments present in gas phase data.nSpec = kmd.nSpec_; data.nReac = kmd.nReac_; // data.nNASA9coef = kmd.nNASA9coef_; data.nThbReac = kmd.nThbReac_; // data.maxTbInReac = kmd.maxTbInReac_; data.nFallReac = kmd.nFallReac_; data.nFallPar = kmd.nFallPar_; // data.maxSpecInReac = kmd.maxSpecInReac_; data.maxOrdPar = kmd.maxOrdPar_; data.nRealNuReac = kmd.nRealNuReac_; data.nRevReac = kmd.nRevReac_; data.nOrdReac = kmd.nOrdReac_; data.nPlogReac = kmd.nPlogReac_; data.jacDim = kmd.nSpec_ + 3; /// rho, temperature and pressure data.enableRealReacScoef = true; { const auto tmp = kmd.reacScoef_.template view<host_exec_space>(); for (ordinal_type i = 0; i < kmd.nReac_; ++i) { const bool flag = (tmp(i) != -1); data.enableRealReacScoef &= flag; } } data.Runiv = kmd.Runiv_; data.Rcal = kmd.Rcal_; data.Rcgs = kmd.Rcgs_; data.TthrmMin = kmd.TthrmMin_; data.TthrmMax = kmd.TthrmMax_; // data.spec9t = kmd.spec9t_.template view<DT>(); // data.spec9nrng = kmd.spec9nrng_.template view<DT>(); // data.sigNu = kmd.sigNu_.template view<DT>(); data.reacTbdy = kmd.reacTbdy_.template view<DT>(); data.reacTbno = kmd.reacTbno_.template view<DT>(); // data.reac_to_Tbdy_index = kmd.reac_to_Tbdy_index_.template view<DT>(); data.reacPfal = kmd.reacPfal_.template view<DT>(); data.reacPtype = kmd.reacPtype_.template view<DT>(); data.reacPlohi = kmd.reacPlohi_.template view<DT>(); data.reacPspec = kmd.reacPspec_.template view<DT>(); data.isRev = kmd.isRev_.template view<DT>(); // data.isDup = kmd.isDup_.template view<DT>(); data.reacAOrd = kmd.reacAOrd_.template view<DT>(); // data.reacNrp = kmd.reacNrp_.template view<DT>(); data.reacNreac = kmd.reacNreac_.template view<DT>(); data.reacNprod = kmd.reacNprod_.template view<DT>(); data.reacScoef = kmd.reacScoef_.template view<DT>(); data.reacRnu = kmd.reacRnu_.template view<DT>(); data.reacRev = kmd.reacRev_.template view<DT>(); data.reacHvIdx = kmd.reacHvIdx_.template view<DT>(); data.reacPlogIdx = kmd.reacPlogIdx_.template view<DT>(); data.reacPlogPno = kmd.reacPlogPno_.template view<DT>(); // data.sNion = kmd.sNion_.template view<DT>(); // data.sCharge = kmd.sCharge_.template view<DT>(); // data.sTfit = kmd.sTfit_.template view<DT>(); // data.sPhase = kmd.sPhase_.template view<DT>(); data.NuIJ = kmd.NuIJ_.template view<DT>(); data.specTbdIdx = kmd.specTbdIdx_.template view<DT>(); data.reacNuki = kmd.reacNuki_.template view<DT>(); data.reacSidx = kmd.reacSidx_.template view<DT>(); data.specAOidx = kmd.specAOidx_.template view<DT>(); // data.elemCount = kmd.elemCount_.template view<DT>(); // (nSpec_, nElem_) data.sMass = kmd.sMass_.template view<DT>(); // data.Tlo = kmd.Tlo_.template view<DT>(); data.Tmi = kmd.Tmi_.template view<DT>(); // data.Thi = kmd.Thi_.template view<DT>(); // data.sigRealNu = kmd.sigRealNu_.template view<DT>(); // data.reacHvPar = kmd.reacHvPar_.template view<DT>(); data.kc_coeff = kmd.kc_coeff_.template view<DT>(); // data.eMass = kmd.eMass_.template view<DT>(); data.RealNuIJ = kmd.RealNuIJ_.template view<DT>(); data.reacArhenFor = kmd.reacArhenFor_.template view<DT>(); data.reacArhenRev = kmd.reacArhenRev_.template view<DT>(); data.specTbdEff = kmd.specTbdEff_.template view<DT>(); data.reacPpar = kmd.reacPpar_.template view<DT>(); data.reacRealNuki = kmd.reacRealNuki_.template view<DT>(); data.specAOval = kmd.specAOval_.template view<DT>(); data.reacPlogPars = kmd.reacPlogPars_.template view<DT>(); data.cppol = kmd.cppol_.template view<DT>(); // data.spec9trng = kmd.spec9trng_.template view<DT>(); // data.spec9coefs = kmd.spec9coefs_.template view<DT>(); // data.sNames = kmd.sNames_.template view<DT>(); data.stoiCoefMatrix = kmd.stoiCoefMatrix_.template view<DT>(); return data; } template<typename DT> static inline Kokkos::View<KineticModelGasConstData<DT>*,DT> createGasKineticModelConstData(const kmd_type_1d_view_host kmds) { Kokkos::View<KineticModelGasConstData<DT>*,DT> r_val(do_not_init_tag("KMCD::gas phase const data objects"), kmds.extent(0)); auto r_val_host = Kokkos::create_mirror_view(r_val); Kokkos::parallel_for (Kokkos::RangePolicy<host_exec_space>(0, kmds.extent(0)), KOKKOS_LAMBDA(const int i) { r_val_host(i) = createGasKineticModelConstData<DT>(kmds(i)); }); Kokkos::deep_copy(r_val, r_val_host); return r_val; } /// KK: once code is working, it will be deprecated template<typename DT> using KineticModelConstData = KineticModelGasConstData<DT>; } // namespace TChem #endif
38.780069
104
0.718121
f2dddfbc6249d58b917232fc7819daa05d380ca0
1,276
hpp
C++
include/tdc/util/lcp.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
1
2021-05-06T13:39:22.000Z
2021-05-06T13:39:22.000Z
include/tdc/util/lcp.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
1
2020-03-07T08:05:20.000Z
2020-03-07T08:05:20.000Z
include/tdc/util/lcp.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
2
2020-05-27T07:54:43.000Z
2021-11-18T13:29:14.000Z
#pragma once namespace tdc { /// \brief Computes the LCP array from the suffix array using Kasai's algorithm. /// \tparam char_t the character type /// \tparam idx_t the suffix/LCP array entry type /// \param text the input text, assuming to be zero-terminated /// \param n the length of the input text including the zero-terminator /// \param sa the suffix array for the text /// \param lcp the output LCP array /// \param plcp an array of size n used as working space -- contains the permuted LCP array after the operation template<typename char_t, typename idx_t> static void lcp_kasai(const char_t* text, const size_t n, const idx_t* sa, idx_t* lcp, idx_t* plcp) { // compute phi array { for(size_t i = 1, prev = sa[0]; i < n; i++) { plcp[sa[i]] = prev; prev = sa[i]; } plcp[sa[0]] = sa[n-1]; } // compute PLCP array { for(size_t i = 0, l = 0; i < n - 1; ++i) { const auto phi_i = plcp[i]; while(text[i + l] == text[phi_i + l]) ++l; plcp[i] = l; if(l) --l; } } // compute LCP array { lcp[0] = 0; for(size_t i = 1; i < n; i++) { lcp[i] = plcp[sa[i]]; } } } } // namespace tdc
29
111
0.554859
f2de2cd3f4565129763b927dfd000cad5c946085
58
hpp
C++
src/boost_mpl_aux__preprocessed_no_ctps_vector.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_mpl_aux__preprocessed_no_ctps_vector.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_mpl_aux__preprocessed_no_ctps_vector.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/mpl/aux_/preprocessed/no_ctps/vector.hpp>
29
57
0.810345
f2deba7cbaf90053e5c47ad9cee572e1fc63afc3
18,693
cpp
C++
src/lua/state.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/lua/state.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/lua/state.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
#include "lcv.hpp" #include "lvalue.hpp" #include "../sdl/rw.hpp" #include "../apppath.hpp" #include "rewindtop.hpp" #include "lubee/src/freelist.hpp" extern "C" { #include <lauxlib.h> #include <lualib.h> } namespace rev { // ----------------- LuaState::Exceptions ----------------- LuaState::EBase::EBase(const std::string& typ_msg, const std::string& msg): std::runtime_error("") { std::stringstream ss; ss << "Error in LuaState:\nCause: " << typ_msg << std::endl << msg; reinterpret_cast<std::runtime_error&>(*this) = std::runtime_error(ss.str()); } LuaState::ERun::ERun(const std::string& s): EBase("Runtime", s) {} LuaState::ESyntax::ESyntax(const std::string& s): EBase("Syntax", s) {} LuaState::EMem::EMem(const std::string& s): EBase("Memory", s) {} LuaState::EError::EError(const std::string& s): EBase("ErrorHandler", s) {} LuaState::EGC::EGC(const std::string& s): EBase("GC", s) {} LuaState::EType::EType(lua_State* ls, const LuaType expect, const LuaType actual): EBase( "InvalidType", std::string("[") + STypeName(ls, actual) + "] to [" + STypeName(ls, expect) + "]" ), expect(expect), actual(actual) {} // ----------------- LuaState ----------------- const std::string LuaState::cs_fromCpp("FromCpp"), LuaState::cs_fromLua("FromLua"), LuaState::cs_mainThreadPtr("MainThreadPtr"), LuaState::cs_mainThread("MainThread"); void LuaState::Nothing(lua_State* /*ls*/) {} const LuaState::Deleter LuaState::s_deleter = [](lua_State* ls){ // これが呼ばれる時はメインスレッドなどが全て削除された時なのでlua_closeを呼ぶ lua_close(ls); }; LuaState::Deleter LuaState::_MakeCoDeleter(LuaState* lsp) { #ifdef DEBUG return [lsp](lua_State* ls) { D_Assert0(lsp->getLS() == ls); #else return [lsp](lua_State*) { #endif lsp->_unregisterCpp(); }; } void LuaState::_initMainThread() { const CheckTop ct(getLS()); // メインスレッドの登録 -> global[cs_mainThreadPtr] push(static_cast<void*>(this)); setGlobal(cs_mainThreadPtr); pushSelf(); setGlobal(cs_mainThread); // fromCpp newTable(); setGlobal(cs_fromCpp); // fromLua newTable(); // FromLuaの方は弱参照テーブルにする newTable(); setField(-1, "__mode", "k"); // [fromLua][mode] setMetatable(-2); setGlobal(cs_fromLua); } void LuaState::_getThreadTable() { getGlobal(cs_fromCpp); getGlobal(cs_fromLua); D_Assert0(type(-2)==LuaType::Table && type(-1)==LuaType::Table); } void LuaState::_registerLua() { D_Assert0(!_bWrap); const CheckTop ct(getLS()); getGlobal(cs_fromLua); pushSelf(); getTable(-2); if(type(-1) == LuaType::Nil) { pop(1); MakeUserdataWithDtor(*this, Lua_WP(shared_from_this())); // [fromLua][Lua_SP] pushSelf(); pushValue(-2); // [fromLua][Lua_SP][Thread][Lua_SP] setTable(-4); pop(2); } else { // [fromLua][Lua_SP] D_Assert0(type(-1) == LuaType::Userdata); pop(2); } } void LuaState::_registerCpp() { D_Assert0(!_bWrap); const RewindTop rt(getLS()); pushSelf(); getGlobal(cs_fromCpp); // [Thread][fromCpp] push(reinterpret_cast<void*>(this)); pushValue(rt.getBase()+1); // [Thread][fromCpp][LuaState*][Thread] D_Assert0(type(-1) == LuaType::Thread); setTable(-3); } void LuaState::_unregisterCpp() { D_Assert0(!_bWrap); const RewindTop rt(getLS()); getGlobal(cs_fromCpp); // [fromCpp] push(reinterpret_cast<void*>(this)); push(LuaNil{}); // [fromCpp][LuaState*][Nil] setTable(-3); } bool LuaState::isLibraryLoaded() { getGlobal(luaNS::system::Package); const bool res = type(-1) == LuaType::Table; pop(1); return res; } bool LuaState::isMainThread() const { return !static_cast<bool>(_base); } void LuaState::addResourcePath(const std::string& path) { loadLibraries(); const CheckTop ct(getLS()); // パッケージのロードパスにアプリケーションリソースパスを追加 getGlobal(luaNS::system::Package); getField(-1, luaNS::system::Path); push(";"); push(path); // [package][path-str][;][path] concat(3); // [package][path-str(new)] push(luaNS::system::Path); pushValue(-2); // [package][path-str(new)][path][path-str(new)] setTable(-4); pop(2); } LuaState::LuaState(const Lua_SP& spLua) { _bWrap = false; lua_State* ls = spLua->getLS(); const CheckTop ct(ls); _base = spLua->getMainLS_SP(); _lua = ILua_SP(lua_newthread(ls), _MakeCoDeleter(this)); _registerCpp(); D_Assert0(getTop() == 0); spLua->pop(1); } LuaState::LuaState(lua_State* ls, const bool bCheckTop): _lua(ls, Nothing) { _bWrap = true; if(bCheckTop) _opCt = spi::construct(ls); } LuaState::LuaState(const lua_Alloc f, void* ud) { _bWrap = false; _lua = ILua_SP(f ? lua_newstate(f, ud) : luaL_newstate(), s_deleter); const CheckTop ct(_lua.get()); _initMainThread(); } LuaState::Reader::Reader(const HRW& hRW): ops(hRW), size(ops->size()) {} Lua_SP LuaState::NewState(const lua_Alloc f, void* ud) { Lua_SP ret(new LuaState(f, ud)); // スレッドリストにも加える ret->_registerCpp(); ret->_registerLua(); return ret; } // --------------- LuaState::Reader --------------- void LuaState::Reader::Read(lua_State* ls, const HRW& hRW, const char* chunkName, const char* mode) { Reader reader(hRW); const int res = lua_load( ls, &Reader::Proc, &reader, (chunkName ? chunkName : "(no name present)"), mode ); LuaState::CheckError(ls, res); } const char* LuaState::Reader::Proc(lua_State* /*ls*/, void* data, std::size_t* size) { auto* self = reinterpret_cast<Reader*>(data); auto remain = self->size; if(remain > 0) { constexpr decltype(remain) BLOCKSIZE = 2048, MAX_BLOCK = 4; int nb, blocksize; if(remain <= BLOCKSIZE) { nb = 1; blocksize = *size = remain; self->size = 0; } else { nb = std::min(MAX_BLOCK, remain / BLOCKSIZE); blocksize = BLOCKSIZE; *size = BLOCKSIZE * nb; self->size -= *size; } self->buff.resize(*size); self->ops->read(self->buff.data(), blocksize, nb); return reinterpret_cast<const char*>(self->buff.data()); } *size = 0; return nullptr; } const char* LuaState::cs_defaultmode = "bt"; int LuaState::load(const HRW& hRW, const char* chunkName, const char* mode, const bool bExec) { Reader::Read(getLS(), hRW, chunkName, mode); if(bExec) { // Loadされたチャンクを実行 return call(0, LUA_MULTRET); } return 0; } int LuaState::loadFromSource(const HRW& hRW, const char* chunkName, const bool bExec) { return load(hRW, chunkName, "t", bExec); } int LuaState::loadFromBinary(const HRW& hRW, const char* chunkName, const bool bExec) { return load(hRW, chunkName, "b", bExec); } int LuaState::loadModule(const std::string& name) { std::string s("require(\""); s.append(name); s.append("\")"); HRW hRW = mgr_rw.fromConstTemporal(s.data(), s.length()); return loadFromSource(hRW, name.c_str(), true); } void LuaState::pushSelf() { lua_pushthread(getLS()); } void LuaState::loadLibraries() { if(!isLibraryLoaded()) luaL_openlibs(getLS()); } void LuaState::push(const LCValue& v) { v.push(getLS()); } void LuaState::pushCClosure(const lua_CFunction func, const int nvalue) { lua_pushcclosure(getLS(), func, nvalue); } void LuaState::pushValue(const int idx) { lua_pushvalue(getLS(), idx); } void LuaState::pop(const int n) { lua_pop(getLS(), n); } namespace { #ifdef DEBUG bool IsRegistryIndex(const int idx) noexcept { return idx==LUA_REGISTRYINDEX; } #endif } int LuaState::absIndex(int idx) const { idx = lua_absindex(getLS(), idx); D_Assert0(IsRegistryIndex(idx) || idx>=0); return idx; } void LuaState::arith(const OP op) { lua_arith(getLS(), static_cast<int>(op)); } lua_CFunction LuaState::atPanic(const lua_CFunction panicf) { return lua_atpanic(getLS(), panicf); } int LuaState::call(const int nargs, const int nresults) { D_Scope(call) const int top = getTop() - 1; // 1は関数の分 const int err = lua_pcall(getLS(), nargs, nresults, 0); checkError(err); return getTop() - top; D_ScopeEnd() } int LuaState::callk(const int nargs, const int nresults, lua_KContext ctx, lua_KFunction k) { D_Scope(callk) const int top = getTop() - 1; // 1は関数の分 const int err = lua_pcallk(getLS(), nargs, nresults, 0, ctx, k); checkError(err); return getTop() - top; D_ScopeEnd() } bool LuaState::checkStack(const int extra) { return lua_checkstack(getLS(), extra) != 0; } bool LuaState::compare(const int idx0, const int idx1, CMP cmp) const { return lua_compare(getLS(), idx0, idx1, static_cast<int>(cmp)) != 0; } void LuaState::concat(const int n) { lua_concat(getLS(), n); } void LuaState::copy(const int from, const int to) { lua_copy(getLS(), from, to); } void LuaState::dump(lua_Writer writer, void* data) { lua_dump(getLS(), writer, data, 0); } void LuaState::error() { lua_error(getLS()); } int LuaState::gc(GC what, const int data) { return lua_gc(getLS(), static_cast<int>(what), data); } lua_Alloc LuaState::getAllocf(void** ud) const { return lua_getallocf(getLS(), ud); } void LuaState::getField(int idx, const LCValue& key) { idx = absIndex(idx); push(key); getTable(idx); } void LuaState::getGlobal(const LCValue& key) { pushGlobal(); push(key); // [Global][key] getTable(-2); remove(-2); } const char* LuaState::getUpvalue(const int idx, const int n) { return lua_getupvalue(getLS(), idx, n); } void LuaState::getTable(const int idx) { lua_gettable(getLS(), idx); } int LuaState::getTop() const { return lua_gettop(getLS()); } void LuaState::getUserValue(const int idx) { lua_getuservalue(getLS(), idx); } void LuaState::getMetatable(const int idx) { lua_getmetatable(getLS(), idx); } void LuaState::insert(const int idx) { lua_insert(getLS(), idx); } bool LuaState::isBoolean(const int idx) const { return lua_isboolean(getLS(), idx) != 0; } bool LuaState::isCFunction(const int idx) const { return lua_iscfunction(getLS(), idx) != 0; } bool LuaState::isLightUserdata(const int idx) const { return lua_islightuserdata(getLS(), idx) != 0; } bool LuaState::isNil(const int idx) const { return lua_isnil(getLS(), idx) != 0; } bool LuaState::isNone(const int idx) const { return lua_isnone(getLS(), idx) != 0; } bool LuaState::isNoneOrNil(const int idx) const { return lua_isnoneornil(getLS(), idx) != 0; } bool LuaState::isNumber(const int idx) const { return lua_isnumber(getLS(), idx) != 0; } bool LuaState::isString(const int idx) const { return lua_isstring(getLS(), idx) != 0; } bool LuaState::isTable(const int idx) const { return lua_istable(getLS(), idx) != 0; } bool LuaState::isThread(const int idx) const { return lua_isthread(getLS(), idx) != 0; } bool LuaState::isUserdata(const int idx) const { return lua_isuserdata(getLS(), idx) != 0; } void LuaState::length(const int idx) { lua_len(getLS(), idx); } int LuaState::getLength(const int idx) { length(idx); const int ret = toInteger(-1); pop(1); return ret; } void LuaState::newTable(const int narr, const int nrec) { lua_createtable(getLS(), narr, nrec); } Lua_SP LuaState::newThread() { return Lua_SP(new LuaState(shared_from_this())); } void* LuaState::newUserData(const std::size_t sz) { return lua_newuserdata(getLS(), sz); } int LuaState::next(const int idx) { return lua_next(getLS(), idx); } bool LuaState::rawEqual(const int idx0, const int idx1) { return lua_rawequal(getLS(), idx0, idx1) != 0; } void LuaState::rawGet(const int idx) { lua_rawget(getLS(), idx); } void LuaState::rawGetField(int idx, const LCValue& key) { if(idx < 0) idx = lua_absindex(getLS(), idx); D_Assert0(idx >= 0); push(key); rawGet(idx); } std::size_t LuaState::rawLen(const int idx) const { return lua_rawlen(getLS(), idx); } void LuaState::rawSet(const int idx) { lua_rawset(getLS(), idx); } void LuaState::rawSetField(int idx, const LCValue& key, const LCValue& val) { if(idx < 0) idx = lua_absindex(getLS(), idx); D_Assert0(idx >= 0); push(key); push(val); rawSet(idx); } void LuaState::remove(const int idx) { lua_remove(getLS(), idx); } void LuaState::replace(const int idx) { lua_replace(getLS(), idx); } std::pair<bool,int> LuaState::resume(const Lua_SP& from, const int narg) { lua_State *const ls = from ? from->getLS() : nullptr; const int res = lua_resume(getLS(), ls, narg); checkError(res); return std::make_pair(res==LUA_YIELD, getTop()); } void LuaState::setAllocf(lua_Alloc f, void* ud) { lua_setallocf(getLS(), f, ud); } void LuaState::setField(int idx, const LCValue& key, const LCValue& val) { idx = absIndex(idx); push(key); push(val); setTable(idx); } void LuaState::setGlobal(const LCValue& key) { pushGlobal(); push(key); pushValue(-3); // [value][Global][key][value] setTable(-3); pop(2); } void LuaState::setMetatable(const int idx) { lua_setmetatable(getLS(), idx); } void LuaState::pushGlobal() { pushValue(LUA_REGISTRYINDEX); getField(-1, LUA_RIDX_GLOBALS); // [Registry][Global] remove(-2); } void LuaState::setTable(const int idx) { lua_settable(getLS(), idx); } void LuaState::setTop(const int idx) { lua_settop(getLS(), idx); } void LuaState::setUservalue(const int idx) { lua_setuservalue(getLS(), idx); } const char* LuaState::setUpvalue(const int funcidx, const int n) { return lua_setupvalue(getLS(), funcidx, n); } void* LuaState::upvalueId(const int funcidx, const int n) { return lua_upvalueid(getLS(), funcidx, n); } void LuaState::upvalueJoin(const int funcidx0, const int n0, const int funcidx1, const int n1) { lua_upvaluejoin(getLS(), funcidx0, n0, funcidx1, n1); } bool LuaState::status() const { const int res = lua_status(getLS()); checkError(res); return res != 0; } void LuaState::checkType(const int idx, const LuaType typ) const { const LuaType t = type(idx); if(t != typ) throw EType(getLS(), typ, t); } void LuaState::CheckType(lua_State* ls, const int idx, const LuaType typ) { LuaState lsc(ls, true); lsc.checkType(idx, typ); } bool LuaState::toBoolean(const int idx) const { return LCV<bool>()(idx, getLS(), nullptr); } lua_CFunction LuaState::toCFunction(const int idx) const { return LCV<lua_CFunction>()(idx, getLS(), nullptr); } lua_Integer LuaState::toInteger(const int idx) const { return LCV<lua_Integer>()(idx, getLS(), nullptr); } std::string LuaState::toString(const int idx) const { return LCV<std::string>()(idx, getLS(), nullptr); } std::string LuaState::cnvString(int idx) { idx = absIndex(idx); getGlobal(luaNS::ToString); pushValue(idx); call(1,1); std::string ret = toString(-1); pop(1); return ret; } lua_Number LuaState::toNumber(const int idx) const { return LCV<lua_Number>()(idx, getLS(), nullptr); } const void* LuaState::toPointer(const int idx) const { return lua_topointer(getLS(), idx); } Lua_SP LuaState::toThread(const int idx) const { return LCV<Lua_SP>()(idx, getLS(), nullptr); } void* LuaState::toUserData(const int idx) const { return LCV<void*>()(idx, getLS(), nullptr); } LCTable_SP LuaState::toTable(const int idx, LPointerSP* spm) const { return LCV<LCTable_SP>()(idx, getLS(), spm); } LCValue LuaState::toLCValue(const int idx, LPointerSP* spm) const { return LCV<LCValue>()(idx, getLS(), spm); } LuaType LuaState::type(const int idx) const { return SType(getLS(), idx); } LuaType LuaState::SType(lua_State* ls, const int idx) { const int typ = lua_type(ls, idx); return static_cast<LuaType::e>(typ); } const char* LuaState::typeName(const LuaType typ) const { return STypeName(getLS(), typ); } const char* LuaState::STypeName(lua_State* ls, const LuaType typ) { return lua_typename(ls, static_cast<int>(typ)); } const lua_Number* LuaState::version() const { return lua_version(getLS()); } void LuaState::xmove(const Lua_SP& to, const int n) { lua_xmove(getLS(), to->getLS(), n); } int LuaState::yield(const int nresults) { return lua_yield(getLS(), nresults); } int LuaState::yieldk(const int nresults, lua_KContext ctx, lua_KFunction k) { return lua_yieldk(getLS(), nresults, ctx, k); } bool LuaState::prepareTable(const int idx, const LCValue& key) { getField(idx, key); if(type(-1) != LuaType::Table) { // テーブルを作成 pop(1); newTable(); push(key); pushValue(-2); // [Target][NewTable][key][NewTable] setTable(-4); return true; } return false; } bool LuaState::prepareTableGlobal(const LCValue& key) { pushGlobal(); const bool b = prepareTable(-1, key); remove(-2); return b; } bool LuaState::prepareTableRegistry(const LCValue& key) { pushValue(LUA_REGISTRYINDEX); const bool b = prepareTable(-1, key); remove(-2); return b; } lua_State* LuaState::getLS() const { return _lua.get(); } Lua_SP LuaState::GetLS_SP(lua_State* ls) { Lua_SP ret; const RewindTop rt(ls); LuaState lsc(ls, false); lsc.getGlobal(cs_fromLua); lsc.pushSelf(); lsc.getTable(-2); if(lsc.type(-1) == LuaType::Userdata) { // [fromLua][LuaState*] return reinterpret_cast<Lua_WP*>(lsc.toUserData(-1))->lock(); } lsc.pop(2); // Cppでのみ生きているスレッド lsc.getGlobal(cs_fromCpp); const int idx = lsc.getTop(); // [fromCpp] lsc.push(LuaNil{}); while(lsc.next(idx) != 0) { // key=-2 value=-1 D_Assert0(lsc.type(-1) == LuaType::Thread); if(lua_tothread(ls, -1) == ls) return reinterpret_cast<LuaState*>(lsc.toUserData(-2))->shared_from_this(); lsc.pop(1); } return Lua_SP(); } Lua_SP LuaState::getLS_SP() { return shared_from_this(); } Lua_SP LuaState::getMainLS_SP() { if(_base) return _base->getMainLS_SP(); return shared_from_this(); } Lua_SP LuaState::GetMainLS_SP(lua_State* ls) { const RewindTop rt(ls); lua_getglobal(ls, cs_mainThreadPtr.c_str()); void* ptr = lua_touserdata(ls, -1); return reinterpret_cast<LuaState*>(ptr)->shared_from_this(); } void LuaState::checkError(const int code) const { CheckError(getLS(), code); } void LuaState::CheckError(lua_State* ls, const int code) { const CheckTop ct(ls); if(code!=LUA_OK && code!=LUA_YIELD) { const char* msg = LCV<const char*>()(-1, ls, nullptr); switch(code) { case LUA_ERRRUN: throw ERun(msg); case LUA_ERRMEM: throw EMem(msg); case LUA_ERRERR: throw EError(msg); case LUA_ERRSYNTAX: throw ESyntax(msg); case LUA_ERRGCMM: throw EGC(msg); } throw EBase("unknown error-code", msg); } } std::ostream& operator << (std::ostream& os, const LuaState& ls) { // スタックの値を表示する const int n = ls.getTop(); for(int i=1 ; i<=n ; i++) os << "[" << i << "]: " << ls.toLCValue(i) << " (" << ls.type(i).toStr() << ")" << std::endl; return os; } }
27.530191
102
0.658375
f2e0665b349d0a8c37d7175641a280c3b4fb2069
4,199
cpp
C++
runChip-8/main.cpp
badlydrawnrod/Chip-8
a31b30af5eb6a3948831a951c230c1b967cc3a7e
[ "Apache-2.0" ]
null
null
null
runChip-8/main.cpp
badlydrawnrod/Chip-8
a31b30af5eb6a3948831a951c230c1b967cc3a7e
[ "Apache-2.0" ]
null
null
null
runChip-8/main.cpp
badlydrawnrod/Chip-8
a31b30af5eb6a3948831a951c230c1b967cc3a7e
[ "Apache-2.0" ]
null
null
null
#include <fstream> #include <iostream> #include <memory> #include <SDL.h> #include <libChip-8/include/chip8vm.hpp> using namespace std; // Screen dimensions. const int SCALING = 16; const int SCREEN_WIDTH = Chip8VM::SCREEN_WIDTH * SCALING; const int SCREEN_HEIGHT = Chip8VM::SCREEN_HEIGHT * SCALING; enum { SUCCEEDED, FAILED, USAGE }; // A unique pointer with a custom destructor, used as a handle for SDL objects. template<typename C> using handle = std::unique_ptr<C, void(*)(C*)>; void load_rom(Chip8VM& vm, string filename) { // Load the ROM file into a buffer. ifstream is(filename, ifstream::binary | ios::ate); size_t len = static_cast<size_t>(is.tellg()); auto buffer = make_unique<Chip8VM::Byte[]>(len); is.seekg(0, is.beg); is.read((char*)buffer.get(), len); is.close(); // Supply the buffer to the Chip-8 VM. vm.load(buffer.get(), len); } Chip8VM::Key convert_scancode(SDL_Scancode scancode) { switch (scancode) { case SDL_SCANCODE_1: return Chip8VM::Key::KEY_1; case SDL_SCANCODE_2: return Chip8VM::Key::KEY_2; case SDL_SCANCODE_3: return Chip8VM::Key::KEY_3; case SDL_SCANCODE_4: return Chip8VM::Key::KEY_C; case SDL_SCANCODE_Q: return Chip8VM::Key::KEY_4; case SDL_SCANCODE_W: return Chip8VM::Key::KEY_5; case SDL_SCANCODE_E: return Chip8VM::Key::KEY_6; case SDL_SCANCODE_R: return Chip8VM::Key::KEY_D; case SDL_SCANCODE_A: return Chip8VM::Key::KEY_7; case SDL_SCANCODE_S: return Chip8VM::Key::KEY_8; case SDL_SCANCODE_D: return Chip8VM::Key::KEY_9; case SDL_SCANCODE_F: return Chip8VM::Key::KEY_E; case SDL_SCANCODE_Z: return Chip8VM::Key::KEY_A; case SDL_SCANCODE_X: return Chip8VM::Key::KEY_0; case SDL_SCANCODE_C: return Chip8VM::Key::KEY_B; case SDL_SCANCODE_V: return Chip8VM::Key::KEY_F; default: return Chip8VM::Key::NO_KEY; } } int main(int argc, char* argv[]) { if (argc != 2) { cerr << "Usage: " << argv[0] << " <filename>\n"; return USAGE; } auto vm_handle = make_unique<Chip8VM>(); Chip8VM& vm = *vm_handle; load_rom(vm, argv[1]); // Initialise SDL. if (SDL_Init(SDL_INIT_VIDEO) != 0) { cerr << "SDL_Init: Error: " << SDL_GetError() << endl; return FAILED; } // Create an SDL window, wrapping it in a handle to clear it up automatically. handle<SDL_Window> window_handle{ SDL_CreateWindow("CHIP-8 in C++", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN), SDL_DestroyWindow }; SDL_Window* window = window_handle.get(); if (window == nullptr) { cerr << "SDL_CreateWindow: Error: " << SDL_GetError() << endl; SDL_Quit(); return FAILED; } // Create an SDL renderer, wrapping it in a handle to clear it up automatically. handle<SDL_Renderer> rh( SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC), SDL_DestroyRenderer); SDL_Renderer* renderer = rh.get(); if (renderer == nullptr) { cerr << "SDL_CreateRenderer: Error: " << SDL_GetError() << endl; SDL_Quit(); return FAILED; } SDL_Event event; bool quit = false; while (!quit) { // Process events. while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = true; break; case SDL_KEYDOWN: vm.key_pressed(convert_scancode(event.key.keysym.scancode)); break; case SDL_KEYUP: vm.key_released(convert_scancode(event.key.keysym.scancode)); break; } } // Tick the delay timer (based on the not necessarily true assumption that we're refreshing at 60Hz). vm.tick(); // Bump the VM on by a few instructions. vm.step(10); // Clear the screen in dark grey. SDL_SetRenderDrawColor(renderer, 0x0f, 0x0f, 0x0f, 0xff); SDL_RenderClear(renderer); // Draw the VM's screen in green. SDL_SetRenderDrawColor(renderer, 0x00, 0xff, 0x00, 0xff); for (auto y = 0; y < Chip8VM::SCREEN_HEIGHT; y++) { for (auto x = 0; x < Chip8VM::SCREEN_WIDTH; x++) { if (vm.io.screen.test(x + Chip8VM::SCREEN_WIDTH * y)) { SDL_Rect rect{ x * SCALING, y * SCALING, SCALING, SCALING }; SDL_RenderFillRect(renderer, &rect); } } } SDL_RenderPresent(renderer); } // Clean up and quit. SDL_Quit(); return SUCCEEDED; }
23.327778
133
0.69326
f2e7dfd0dc05993a7fe9ccf12d63dcea44e78dc0
412
cc
C++
src/code_complete_cache.cc
Gei0r/cquery
6ff8273e8b8624016f9363f444acfee30c4bbf64
[ "MIT" ]
null
null
null
src/code_complete_cache.cc
Gei0r/cquery
6ff8273e8b8624016f9363f444acfee30c4bbf64
[ "MIT" ]
null
null
null
src/code_complete_cache.cc
Gei0r/cquery
6ff8273e8b8624016f9363f444acfee30c4bbf64
[ "MIT" ]
null
null
null
#include "code_complete_cache.h" void CodeCompleteCache::WithLock(std::function<void()> action) { std::lock_guard<std::mutex> lock(mutex_); action(); } bool CodeCompleteCache::IsCacheValid(lsTextDocumentPositionParams position) { std::lock_guard<std::mutex> lock(mutex_); return cached_path_ == position.textDocument.uri.GetAbsolutePath() && cached_completion_position_ == position.position; }
34.333333
77
0.759709
f2e9881742fc1b942ac3a60416ebf51b41d9dfbe
829
cpp
C++
Olamundo/freq_0502/main.cpp
tosantos1/LIP
7dbc045afa02729f4e2f2f1d3b29baebf5be72ad
[ "MIT" ]
null
null
null
Olamundo/freq_0502/main.cpp
tosantos1/LIP
7dbc045afa02729f4e2f2f1d3b29baebf5be72ad
[ "MIT" ]
null
null
null
Olamundo/freq_0502/main.cpp
tosantos1/LIP
7dbc045afa02729f4e2f2f1d3b29baebf5be72ad
[ "MIT" ]
null
null
null
#include <iostream> /*Ordenação por referência  Complete o programa dado para que com apenas uma chamada para o procedimento ordenarTres, os valores das variáveis a, b e c sejam colocados em ordem crescente. Note que nenhuma alteração da função main nem do procedimento ordenarTres é necessária.*/ using namespace std; int oQueEuFaco (int x, int y ); void oQueEuFaco(int &x, int &y); void ordenarTres(int &x, int &y, int &z); int main() { int a, b, c; cin >> a >> b >> c; ordenarTres(a, b, c); cout << a << " " << b << " " << c << endl; return 0; } //Este procedimento arranja os valores de x, y e z em ordem crescente void ordenarTres(int &x, int &y, int &z) { oQueEuFaco(x, y); oQueEuFaco(x, z); oQueEuFaco(y, z); } int oQueEuFaco (int x, int y){ int a; if ( x>y){ a=x; x=y; y=a; } }
18.840909
102
0.640531
f2e9b05f3c16a26d7f319ac7e9a8750d8943d941
8,390
cpp
C++
Testbeds/GTests/twEventTest.cpp
microqq/TwinkleGraphics
e3975dc6dad5b6b8d5db1d54e30e815072db162e
[ "MIT" ]
null
null
null
Testbeds/GTests/twEventTest.cpp
microqq/TwinkleGraphics
e3975dc6dad5b6b8d5db1d54e30e815072db162e
[ "MIT" ]
1
2020-07-03T03:13:39.000Z
2020-07-03T03:13:39.000Z
Testbeds/GTests/twEventTest.cpp
microqq/TwinkleGraphics
e3975dc6dad5b6b8d5db1d54e30e815072db162e
[ "MIT" ]
null
null
null
#include <functional> #include <string> #include <gtest/gtest.h> #include "twEventHandler.h" #include "twEventManager.h" #include "twConsoleLog.h" using namespace TwinkleGraphics; class SampleListener { public: SampleListener(){} ~SampleListener(){} void OnBaseEvent(Object::Ptr sender, BaseEventArgs::Ptr e) const { Console::LogGTestInfo("Add SampleListener OnBaseEvent EventHandler.\n"); } }; DefMemFuncType(SampleListener); class SampleEventArgs : public BaseEventArgs { public: typedef std::shared_ptr<SampleEventArgs> Ptr; static EventId ID; SampleEventArgs() : BaseEventArgs() { } virtual ~SampleEventArgs() {} virtual EventId GetEventId() override { return SampleEventArgs::ID; } }; EventId SampleEventArgs::ID = std::hash<std::string>{}("SampleEventArgs"); class SampleEventArgsA : public BaseEventArgs { public: typedef std::shared_ptr<SampleEventArgsA> Ptr; static EventId ID; SampleEventArgsA() : BaseEventArgs() { } virtual ~SampleEventArgsA() {} virtual EventId GetEventId() override { return SampleEventArgsA::ID; } }; EventId SampleEventArgsA::ID = std::hash<std::string>{}("SampleEventArgsA"); // en.cppreference.com/w/cpp/utility/functional/function/target.html void f(Object::Ptr, BaseEventArgs::Ptr) { Console::LogGTestInfo("Initialise Global f(******) EventHandler.\n"); } void g(Object::Ptr, BaseEventArgs::Ptr) { } void test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)> arg) { typedef void (*FPTR)(Object::Ptr, BaseEventArgs::Ptr); // void (*const* ptr)(Object::Ptr, BaseEventArgs::Ptr) = // arg.target<void(*)(Object::Ptr, BaseEventArgs::Ptr)>(); FPTR* ptr= arg.target<FPTR>(); if (ptr && *ptr == f) { Console::LogGTestInfo("it is the function f\n"); } else if (ptr && *ptr == g) { Console::LogGTestInfo("it is the function g\n"); } else if(ptr) { Console::LogGTestInfo("it is not nullptr\n"); } } // en.cppreference.com/w/cpp/utility/functional/function.html struct Foo { Foo(int num) : num_(num) {} void print_add(int i) const { Console::LogGTestInfo("Foo: ", num_+i, '\n'); } int num_; }; TEST(EventTests, AddEventHandler) { //EventHandler(const HandlerFunc& func) EventHandler handler( EventHandler::HandlerFunc( [](Object::Ptr sender, BaseEventArgs::Ptr args) { Console::LogGTestInfo("Initialise EventHandler.\n"); } ) ); //Lambda handler function EventHandler::HandlerFuncPointer lambda = [](Object::Ptr sender, BaseEventArgs::Ptr args) { Console::LogGTestInfo("Add Lambda Num(1) EventHandler.\n"); }; EventHandler::HandlerFunc lambdaFunc(lambda); //EventHandler::operator+= handler += lambdaFunc; ASSERT_EQ(handler[1] != nullptr, true); //EventHandler::operator-= handler -= lambdaFunc; ASSERT_EQ(handler.GetHandlerFuncSize(), 1); // We won't use std::bind binding class member function SampleListener listener; // EventHandler::HandlerFunc baseFunc = // std::bind(&SampleListener::OnBaseEvent, &listener, std::placeholders::_1, std::placeholders::_2); // handlerRef += baseFunc; Object::Ptr objectPtr = std::make_shared<Object>(); SampleEventArgs::Ptr sampleEvent1 = std::make_shared<SampleEventArgs>(); SampleEventArgs::Ptr sampleEvent2 = std::make_shared<SampleEventArgs>(); SampleEventArgsA::Ptr sampleEventA = std::make_shared<SampleEventArgsA>(); ASSERT_EQ(sampleEvent1->GetEventId() != -1, true); ASSERT_EQ(sampleEvent2->GetEventId() != -1, true); ASSERT_EQ(sampleEventA->GetEventId() != -1, true); ASSERT_EQ(sampleEventA->GetEventId() != sampleEvent1->GetEventId(), true); ASSERT_EQ(sampleEvent2->GetEventId() != sampleEvent1->GetEventId(), false); Console::LogGTestInfo("SampleEvent Instance 1 EventId: ", sampleEvent1->GetEventId(), "\n"); Console::LogGTestInfo("SampleEvent Instance 2 EventId: ", sampleEvent2->GetEventId(), "\n"); Console::LogGTestInfo("SampleEventA EventId: ", sampleEventA->GetEventId(), "\n"); handler.Invoke(objectPtr, sampleEvent1); }; TEST(EventTests, FireEvent) { EventManagerInst eventMgrInst; SampleEventArgsA::Ptr sampleEventA = std::make_shared<SampleEventArgsA>(); //EventHandler(const HandlerFunc& func) EventHandler handler( EventHandler::HandlerFunc( [](Object::Ptr sender, BaseEventArgs::Ptr args) { Console::LogGTestInfo("Initialise EventHandler.\n"); } ) ); //Lambda handler function EventHandler::HandlerFuncPointer lambda = [](Object::Ptr sender, BaseEventArgs::Ptr args) { Console::LogGTestInfo("Add Lambda Num(1) EventHandler.\n"); }; Console::LogGTestInfo("Lambda function address: ", size_t(lambda), "\n"); EventHandler::HandlerFunc lambdaFunc(lambda); //EventHandler::operator+= handler += lambdaFunc; ASSERT_EQ(handler[1] != nullptr, true); handler += lambdaFunc; ASSERT_EQ(handler.GetHandlerFuncSize(), 2); eventMgrInst->Subscribe(SampleEventArgsA::ID, handler); Console::LogGTestInfo("Fire SampleEventArgsA--------1\n"); eventMgrInst->FireImmediately(nullptr, sampleEventA); //EventHandler::operator-= handler -= lambdaFunc; ASSERT_EQ(handler.GetHandlerFuncSize(), 1); // handler updated, so first unsubscribe and then subscribe again eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler); eventMgrInst->Subscribe(SampleEventArgsA::ID, handler); eventMgrInst->Subscribe(SampleEventArgsA::ID, handler); eventMgrInst->Subscribe(SampleEventArgsA::ID, handler); Console::LogGTestInfo("Fire SampleEventArgsA--------2\n"); eventMgrInst->FireImmediately(nullptr, sampleEventA); handler.Remove(0); handler += lambdaFunc; ASSERT_EQ(handler.GetHandlerFuncSize(), 1); eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler); eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler); eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler); eventMgrInst->Subscribe(SampleEventArgsA::ID, handler); Console::LogGTestInfo("Fire SampleEventArgsA--------3\n"); eventMgrInst->FireImmediately(nullptr, sampleEventA); //Bind class member function // SampleListener listener; // EventHandler::HandlerFunc sampleListenerHFunc = std::bind(&SampleListener::OnBaseEvent, &listener, std::placeholders::_1, std::placeholders::_2); EventHandler::HandlerFuncPointer lambda2 = [](Object::Ptr sender, BaseEventArgs::Ptr args){ SampleListener* listener = dynamic_cast<SampleListener*>(sender.get()); listener->OnBaseEvent(sender, args); }; EventHandler::HandlerFunc lambda2Func(lambda2); handler += lambda2Func; handler += lambda2Func; handler += lambda2Func; handler -= lambda2Func; EventHandlerCallBack(lambda3, SampleListener, OnBaseEvent); RegisterEventHandlerCallBack(handler, lambda3); UnRegisterEventHandlerCallBack(handler, lambda3); RegisterEventHandlerCallBack(handler, lambda3); EventHandler::HandlerFunc lambda3Func(f); handler += lambda3Func; handler += lambda3Func; handler += lambda3Func; eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler); eventMgrInst->Subscribe(SampleEventArgsA::ID, handler); eventMgrInst->Subscribe(SampleEventArgsA::ID, handler); eventMgrInst->Subscribe(SampleEventArgsA::ID, handler); Console::LogGTestInfo("Fire SampleEventArgsA--------4\n"); eventMgrInst->FireImmediately(nullptr, sampleEventA); // en.cppreference.com/w/cpp/utility/functional/function.html // std::function<void(const SampleListener&, Object::Ptr, BaseEventArgs::Ptr)> fffFunc = &SampleListener::OnBaseEvent; std::function<void(const Foo&, int)> f_add_display = &Foo::print_add; const Foo foo(314159); f_add_display(foo, 1); f_add_display(314159, 1); // en.cppreference.com/w/cpp/utility/functional/function/target.html test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)>(f)); test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)>(g)); test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)>(lambda3)); }
33.031496
152
0.682956
f2eb90d197927bf0fca32e905d2d4bdd65d653b2
10,624
cpp
C++
src/pyscal/atom.cpp
srmnitc/SteinhardtTools
b73865bbc35e88773126a952be653e382e5fbf3c
[ "BSD-3-Clause" ]
22
2019-10-17T13:21:19.000Z
2021-07-06T12:11:21.000Z
src/pyscal/atom.cpp
aazocar/pyscal
d0a393fc0462fdc6d23599a9e2bcc85ac9b212b2
[ "BSD-3-Clause" ]
68
2019-09-07T22:28:06.000Z
2021-10-17T15:24:23.000Z
src/pyscal/atom.cpp
aazocar/pyscal
d0a393fc0462fdc6d23599a9e2bcc85ac9b212b2
[ "BSD-3-Clause" ]
10
2019-11-01T20:29:07.000Z
2021-10-04T19:09:29.000Z
#include "atom.h" #include <iostream> #include <iomanip> #include <algorithm> #include <stdio.h> #include "string.h" #include <chrono> #include <pybind11/stl.h> #include <complex> //------------------------------------------------------- // Constructor, Destructor //------------------------------------------------------- Atom::Atom( vector<double> pos, int idd, int typ){ posx = pos[0]; posy = pos[1]; posz = pos[2]; id = idd; type = typ; ghost = 0; //assign other values - the default ones belongsto = -1; issolid = 0; issurface = 0; loc = 0; isneighborset = 0; n_neighbors = 0; lcluster = 0; head = -1; entropy = 0; avg_entropy = 0; energy = 0; avg_energy = 0; for (int tn = 0; tn<MAXNUMBEROFNEIGHBORS; tn++){ neighbors[tn] = -1; neighbordist[tn] = -1.0; neighborweight[tn] = -1.0; facevertices[tn] = -1; faceverticenumbers[tn] = -1; faceperimeters[tn] = -1.0; sij[tn] = -1.0; masks[tn] = -1; //edgelengths[tn] = -1.0; } for (int tn = 0; tn<11; tn++){ q[tn] = -1; aq[tn] = -1; for (int tnn =0; tnn<25; tnn++){ realq[tn][tnn] = -1; imgq[tn][tnn] = -1; arealq[tn][tnn] = -1; aimgq[tn][tnn] = -1; } } } Atom::~Atom(){ } //------------------------------------------------------- // Basic Atom properties //------------------------------------------------------- //aceesss funcs vector<double> Atom::gx(){ vector<double> pos; pos.emplace_back(posx); pos.emplace_back(posy); pos.emplace_back(posz); return pos; } void Atom::sx(vector<double> rls){ posx = rls[0]; posy = rls[1]; posz = rls[2]; } //------------------------------------------------------- // Neighbor related properties //------------------------------------------------------- vector<int> Atom::gneighbors(){ vector<int> nn; nn.reserve(n_neighbors); for(int i=0;i<n_neighbors;i++){ nn.emplace_back(neighbors[i]); } return nn; } void Atom::sneighdist(vector<double> dd){ } vector<double> Atom::gneighdist(){ vector<double> neighdist; for(int i=0; i<n_neighbors; i++){ neighdist.emplace_back(neighbordist[i]); } return neighdist; } void Atom::sneighbors(vector<int> nns){ //first reset all neighbors for (int i = 0;i<MAXNUMBEROFNEIGHBORS;i++){ neighbors[i] = NILVALUE; neighbordist[i] = -1.0; } //now assign the neighbors for(int i=0; i<nns.size(); i++){ neighbors[i] = nns[i]; //auto assign weight to 1 neighborweight[i] = 1.00; } n_neighbors = nns.size(); isneighborset = 1; } void Atom::sneighborweights(vector<double> nss){ for(int i=0; i<nss.size(); i++){ neighborweight[i] = nss[i]; } } vector<double> Atom::gneighborweights(){ vector <double> rqlms; for(int i=0; i<n_neighbors; i++){ rqlms.emplace_back(neighborweight[i]); } return rqlms; } void Atom::sdistvecs(vector<vector<double>> nss){ } vector<vector<double>> Atom::gdistvecs(){ vector<vector<double>> m1; vector <double> m2; for(int i=0; i<n_neighbors; i++){ m2.clear(); m2.emplace_back(n_diffx[i]); m2.emplace_back(n_diffy[i]); m2.emplace_back(n_diffz[i]); m1.emplace_back(m2); } return m1; } void Atom::slocalangles(vector<vector<double>> nss){ } vector<vector<double>> Atom::glocalangles(){ vector<vector<double>> m1; vector <double> m2; for(int i=0; i<n_neighbors; i++){ m2.clear(); m2.emplace_back(n_phi[i]); m2.emplace_back(n_theta[i]); m1.emplace_back(m2); } return m1; } //------------------------------------------------------- // Q parameter properties //------------------------------------------------------- void Atom::ssij(vector<double> dd){ } vector<double> Atom::gsij(){ vector<double> ss; for(int i=0; i<n_neighbors; i++){ ss.emplace_back(sij[i]); } return ss; } vector<double> Atom::gallq(){ vector<double> allq; for(int i=0; i<11; i++){ allq.emplace_back(q[i]); } return allq; } vector<double> Atom::gallaq(){ vector<double> allq; for(int i=0; i<11; i++){ allq.emplace_back(aq[i]); } return allq; } void Atom::sallq(vector<double> allq){ for(int i=0; i<11; i++){ q[i] = allq[i]; } } void Atom::sallaq(vector<double> allaq){ for(int i=0; i<11; i++){ aq[i] = allaq[i]; } } double Atom::gq(int qq){ return q[qq-2]; } void Atom::sq(int qq, double qval){ q[qq-2] = qval; } double Atom::gaq(int qq){ return aq[qq-2]; } void Atom::saq(int qq, double qval){ aq[qq-2] = qval; } double Atom::gq_big(int qval, bool averaged){ if ((qval < 2) || (qval > 12)){ throw invalid_argument("q value should be between 2-12"); } if(averaged == true) { return gaq(qval);} else {return gq(qval);} } void Atom::sq_big(int qval, double val, bool averaged){ if ((qval < 2) || (qval > 12)){ throw invalid_argument("q value should be between 2-12"); } if(averaged == true) { saq(qval, val);} else { sq(qval, val);} } //overloaded version which takes a vector vector<double> Atom::gq_big(vector<int> qval, bool averaged ){ int d; if(averaged == true) { vector<double> retvals; for(int i=0; i<qval.size(); i++){ if ((qval[i] < 2) || (qval[i] > 12)){ throw invalid_argument("q value should be between 2-12"); } retvals.push_back(gaq(qval[i])); } return retvals; } else { vector<double> retvals; for(int i=0; i<qval.size(); i++){ if ((qval[i] < 2) || (qval[i] > 12)){ throw invalid_argument("q value should be between 2-12"); } retvals.push_back(gq(qval[i])); } return retvals; } } //overloaded version which takes a vector void Atom::sq_big(vector<int> qval, vector<double> setvals, bool averaged){ if(averaged == true) { for(int i=0; i<qval.size(); i++){ if ((qval[i] < 2) || (qval[i] > 12)){ throw invalid_argument("q value should be between 2-12"); } saq(qval[i], setvals[i]); } } else { for(int i=0; i<qval.size(); i++){ if ((qval[i] < 2) || (qval[i] > 12)){ throw invalid_argument("q value should be between 2-12"); } sq(qval[i], setvals[i]); } } } vector<complex<double>> Atom::get_qcomps(int qq, bool averaged){ vector<complex<double>> qlms; qlms.reserve(2*qq+1); if (!averaged){ for(int i=0;i<(2*qq+1);i++){ complex<double> lmval(realq[qq-2][i], imgq[qq-2][i]); qlms.emplace_back(lmval); } } else{ for(int i=0;i<(2*qq+1);i++){ complex<double> lmval(arealq[qq-2][i], aimgq[qq-2][i]); qlms.emplace_back(lmval); } } return qlms; } //------------------------------------------------------- // Solid related properties //------------------------------------------------------- //------------------------------------------------------- // Voronoi related properties //------------------------------------------------------- void Atom::sfacevertices(vector<int> nss){ for(int i=0; i<nss.size(); i++){ facevertices[i] = nss[i]; } } vector<int> Atom::gfacevertices(){ vector <int> rqlms; for(int i=0; i<n_neighbors; i++){ rqlms.emplace_back(facevertices[i]); } return rqlms; } void Atom::sfaceperimeters(vector<double> nss){ for(int i=0; i<nss.size(); i++){ faceperimeters[i] = nss[i]; } } vector<double> Atom::gfaceperimeters(){ vector <double> rqlms; for(int i=0; i<n_neighbors; i++){ rqlms.emplace_back(faceperimeters[i]); } return rqlms; } void Atom::sedgelengths(vector<vector<double>> nss){ edgelengths.clear(); edgelengths = nss; } vector<vector<double>> Atom::gedgelengths(){ return edgelengths; } void Atom::svertexpositions(vector<vector<double>> nss){ vertex_positions.clear(); vertex_positions = nss; } vector<vector<double>> Atom::gvertexpositions(){ return vertex_positions; } vector<int> Atom::gvorovector(){ vector<int> voro; voro.emplace_back(n3); voro.emplace_back(n4); voro.emplace_back(n5); voro.emplace_back(n6); return voro; } void Atom::svorovector(vector<int> voro){ n3 = voro[0]; n4 = voro[1]; n5 = voro[2]; n6 = voro[3]; } //------------------------------------------------------- // Angle related properties //------------------------------------------------------- //------------------------------------------------------- // Other order parameters //------------------------------------------------------- double Atom::gmr(double r) { double g = 0.00; double rij,r2; double sigma2 = sigma*sigma; double frho = 4.00*PI*rho*r*r; double fsigma = sqrt(2.00*PI*sigma2); double factor = (1.00/frho)*(1.00/fsigma); for(int i=0; i<n_neighbors; i++) { rij = neighbordist[i]; r2 = (r-rij)*(r-rij); g+=exp((-1.00*r2)/(2.00*sigma2)); } return factor*g; } //function which is to be integrated double Atom::entropy_integrand(double r) { double g = gmr(r); return ((g*log(g)-g +1.00)*r*r); } void Atom::trapezoid_integration() { int nsteps = (rstop - rstart)/h; double summ; double xstart, xend; summ=0.00; double rloop; double integral; xstart = entropy_integrand(rstart); for(int j=1; j<nsteps-1; j++) { rloop = rstart + j*h; summ += entropy_integrand(rloop); } xend = entropy_integrand(rstart + nsteps*h); integral = (h/2.00)*(xstart + 2.00*summ + xend); //cout<<xstart<<endl; integral = -1.*rho*kb*integral; entropy = integral; }
23.400881
76
0.483622
f2edbea3f6ac2b4c696a67227a8cf853d76b3482
4,716
cpp
C++
src/vi/vi_db.cpp
liulixinkerry/ripple
330522a61bcf1cf290c100ce4686ed62dcdc5cab
[ "Unlicense" ]
7
2021-01-25T04:28:38.000Z
2021-11-20T04:14:14.000Z
src/vi/vi_db.cpp
Xingquan-Li/ripple
330522a61bcf1cf290c100ce4686ed62dcdc5cab
[ "Unlicense" ]
3
2021-02-25T08:13:41.000Z
2022-02-25T16:37:16.000Z
src/vi/vi_db.cpp
Xingquan-Li/ripple
330522a61bcf1cf290c100ce4686ed62dcdc5cab
[ "Unlicense" ]
8
2021-02-27T13:52:25.000Z
2021-11-15T08:01:02.000Z
#include "../db/db.h" using namespace db; #include "vi.h" using namespace vi; #include "../ut/utils.h" void Geometry::draw(Visualizer* v, const Layer& L) const { if ((L.rIndex >= 0 || L.cIndex >= 0) && layer != L) { return; } if (layer.rIndex >= 0) { v->setFillColor(v->scheme.metalFill[layer.rIndex]); v->setLineColor(v->scheme.metalLine[layer.rIndex]); } else if (layer.cIndex >= 0) { v->setFillColor(v->scheme.metalFill[layer.cIndex]); v->setLineColor(v->scheme.metalLine[layer.cIndex]); } const int lx = globalX(); const int ly = globalY(); const int hx = globalX() + boundR(); const int hy = globalY() + boundT(); v->drawRect(lx, ly, hx, hy, true, true); } void Cell::draw(Visualizer* v) const { if (!(region->id)) { v->setFillColor(v->scheme.instanceFill); v->setLineColor(v->scheme.instanceLine); } else { int r = (region->id * 100) % 256; int g = (region->id * 200) % 256; v->setFillColor(Color(r, g, 255)); v->setLineColor(Color(r / 2, g / 2, 128)); } int lx = globalX(); int ly = globalY(); int hx = globalX() + boundR(); int hy = globalY() + boundT(); // printlog(LOG_INFO, "cell : %d %d %d %d", lx, ly, hx, hy); v->drawRect(lx, ly, hx, hy, true, true); } void IOPin::draw(Visualizer* v, Layer& L) const { type->shapes[0].draw(v, L); } void Pin::draw(Visualizer* v, const Layer& L) const { for (const Geometry& shape : type->shapes) { shape.draw(v, L); } } void Net::draw(Visualizer* v, const Layer& L) const { for (const Pin* pin : pins) { pin->draw(v, L); } } void SNet::draw(Visualizer* v, Layer& L) const { for (const Geometry& shape : shapes) { shape.draw(v, L); } for (const Via& via : vias) { via.draw(v, L); } } void Row::draw(Visualizer* v) const { v->setFillColor(v->scheme.rowFill); v->setLineColor(v->scheme.rowLine); v->drawRect(_x, _y, _x + _xStep * _xNum, _y + _yStep * _yNum, true, true); } void Via::draw(Visualizer* v, Layer& L) const { for (const Geometry& rect : type->rects) { rect.draw(v); } } void Region::draw(Visualizer* v) const { int nRects = rects.size(); for (int i = 0; i < nRects; i++) { v->setFillColor(v->scheme.regionFill); v->setLineColor(Color(0, 0, 0)); v->drawRect(rects[i].lx, rects[i].ly, rects[i].hx, rects[i].hy, true, true); } } void SiteMap::draw(Visualizer* v) const { int lx, ly, hx, hy; for (int x = 0; x < siteNX; x++) { for (int y = 0; y < siteNY; y++) { unsigned char regionID = getRegion(x, y); bool blocked = getSiteMap(x, y, SiteMap::SiteBlocked); if (blocked) { v->setFillColor(Color(0, 0, 0)); getSiteBound(x, y, lx, ly, hx, hy); v->drawRect(lx, ly, hx, hy, true, false); } else if (regionID == Region::InvalidRegion) { v->setFillColor(Color(255, 0, 0)); getSiteBound(x, y, lx, ly, hx, hy); v->drawRect(lx, ly, hx, hy, true, false); } else if (regionID > 0) { v->setFillColor(v->scheme.regionFill); getSiteBound(x, y, lx, ly, hx, hy); v->drawRect(lx, ly, hx, hy, true, false); } } } } void Database::draw(Visualizer* v) const { v->reset(v->scheme.background); int nRows = rows.size(); for (int i = 0; i < nRows; i++) { rows[i]->draw(v); } int nCells = cells.size(); for (int i = 0; i < nCells; i++) { cells[i]->draw(v); } /* int nRegions = regions.size(); for(int i=1; i<nRegions; i++){ regions[i]->draw(v); } */ // siteMap.draw(v); /* draw metal objects */ unsigned nLayers = layers.size(); for (unsigned i = 0; i != nLayers; ++i) { const Layer* layer = nullptr; if (i % 2) { layer = database.getCLayer(i / 2); } else { layer = database.getRLayer(i / 2); } if (!layer) { continue; } // printlog(LOG_INFO, "draw layer %s", layer->name.c_str()); for (const Net* net : nets) { net->draw(v, *layer); } } /* v->setFillColor(Color(255,0,0)); for(int x=0; x<grGrid.trackNX; x++){ for(int y=0; y<grGrid.trackNY; y++){ int dx = grGrid.trackL + x * grGrid.trackStepX; int dy = grGrid.trackB + y * grGrid.trackStepY; if(grGrid.getRGrid(x, y, 2) == (char)1){ v->drawPoint(dx, dy, 1); } } } */ }
28.756098
84
0.516327
f2ef082ffdb2d2c0b7d783d0c5183936fe35c4aa
543
hpp
C++
OptionsState.hpp
nathiss/ticTacToe
e51866b66dda3fe92e82450a7732ad175eb1c96c
[ "MIT" ]
null
null
null
OptionsState.hpp
nathiss/ticTacToe
e51866b66dda3fe92e82450a7732ad175eb1c96c
[ "MIT" ]
null
null
null
OptionsState.hpp
nathiss/ticTacToe
e51866b66dda3fe92e82450a7732ad175eb1c96c
[ "MIT" ]
null
null
null
#pragma once #include <array> #include <SFML/Graphics.hpp> #include "State.hpp" #include "SettingsBag.hpp" #include "MapCell.hpp" class OptionsState : public State { public: OptionsState(std::shared_ptr<sf::RenderWindow>); ~OptionsState(); static uint8_t player; static uint8_t computer; virtual void pollEvent() override; virtual void update() override; virtual void draw() override; private: std::array<sf::Text, 3> orderOption; std::array<sf::Text, 3> characterOption; uint8_t optionIdx; };
20.884615
52
0.694291
f2f3834523da7253561a9831549f255536882d88
4,689
inl
C++
include/quadtree.inl
MaxAlzner/libtree
80501e15fdec77e1f1824b46ebd3ae1c1cedd7f8
[ "MIT" ]
null
null
null
include/quadtree.inl
MaxAlzner/libtree
80501e15fdec77e1f1824b46ebd3ae1c1cedd7f8
[ "MIT" ]
null
null
null
include/quadtree.inl
MaxAlzner/libtree
80501e15fdec77e1f1824b46ebd3ae1c1cedd7f8
[ "MIT" ]
null
null
null
#pragma once template <typename T> inline bool quadnode_t<T>::empty() const { return this->_tree == 0 || this->_ring < 0 || this->_branch < 0; } template <typename T> inline size_t quadnode_t<T>::index() const { return tree_index(this->_ring, this->_branch, 4); } template <typename T> inline quaditerator_t<T> quaditerator_t<T>::child(const int32_t quadrant) { if (this->_node != 0) { switch (quadrant) { case 0: return quaditerator_t<T>(this->_node->_q0); case 1: return quaditerator_t<T>(this->_node->_q1); case 2: return quaditerator_t<T>(this->_node->_q2); case 3: return quaditerator_t<T>(this->_node->_q3); default: break; } } return quaditerator_t<T>(); } template <typename T> inline quaditerator_t<T> quaditerator_t<T>::parent() { return this->_node != 0 && this->_node->_up != 0 ? quaditerator_t<T>(this->_node->_up) : quaditerator_t<T>(); } template <typename T> inline quaditerator_t<T> quaditerator_t<T>::remove() { if (this->_node != 0) { treereference_t<quadnode_t<T> > prev = this->_node; if (prev->_up != 0) { if (prev->_up->_q0 == prev) { prev->_up->_q0 = -1; } else if (prev->_up->_q1 == prev) { prev->_up->_q1 = -1; } else if (prev->_up->_q2 == prev) { prev->_up->_q2 = -1; } else if (prev->_up->_q3 == prev) { prev->_up->_q3 = -1; } } this->_node = prev->_up; prev->_tree->_registry.remove(prev->index()); if (this->_node != 0) { return quaditerator_t<T>(this->_node); } } return quaditerator_t<T>(); } template <typename T> inline bool quaditerator_t<T>::root() const { return this->_node != 0 && this->_node->_parent == 0; } template <typename T> inline bool quaditerator_t<T>::leaf() const { return this->_node != 0 && this->_node->_left == 0 && this->_node->_right == 0; } template <typename T> inline bool quaditerator_t<T>::empty() const { return this->_node == 0; } template <typename T> inline T& quaditerator_t<T>::operator*() const { return *(this->_node->_data); } template <typename T> inline quaditerator_t<T> quaditerator_t<T>::operator[](const int32_t quadrant) { return this->child(quadrant); } template <typename T> inline bool quaditerator_t<T>::operator==(const quaditerator_t<T>& other) const { return this->_node == other._node; } template <typename T> inline bool quaditerator_t<T>::operator!=(const quaditerator_t<T>& other) const { return this->_node != other._node; } #include <stdio.h> template <typename T> inline quaditerator_t<T> quadtree_t<T>::set_root(const T& item) { this->_registry.zero(); this->_registry[0] = quadnode_t<T>(*this, 0, 0, item); return quaditerator_t<T>(treereference_t<quadnode_t<T> >(this->_registry, 0)); } template <typename T> inline quaditerator_t<T> quadtree_t<T>::search(const T& item) { for (size_t i = 0; i < this->_registry.capacity(); i++) { treereference_t<quadnode_t<T> > node(this->_registry, i); if (!node.empty() && !node->empty() && memcmp(&(node->_data), &item, sizeof(T)) == 0) { return quaditerator_t<T>(node); } } return quaditerator_t<T>(); } template <typename T> inline quaditerator_t<T> quadtree_t<T>::root() { return quaditerator_t<T>(treereference_t<quadnode_t<T> >(this->_registry, 0)); } template <typename T> inline quaditerator_t<T> quadtree_t<T>::end() const { return quaditerator_t<T>(); } template <typename T> inline void quadtree_t<T>::each(iterationfunc callback) { execute_each(treereference_t<quadnode_t<T> >(this->_registry, 0), callback); } template <typename T> inline void quadtree_t<T>::path(iterationfunc callback) { execute_path(treereference_t<quadnode_t<T> >(this->_registry, 0), callback); } template <typename T> inline void quadtree_t<T>::clear() { this->_registry.clear(); } template <typename T> int32_t quadtree_t<T>::execute_each(const treereference_t<quadnode_t<T> >& node, iterationfunc callback) { int32_t result = 1; if (node != 0 && !node.empty() && !node->empty() && callback != 0) { result = callback(node, node->_data); // if (result != 0) // { // result = execute_each(node->_left, callback); // if (result != 0) // { // result = execute_each(node->_right, callback); // } // } } return result; } template <typename T> int32_t quadtree_t<T>::execute_path(const treereference_t<quadnode_t<T> >& node, iterationfunc callback) { int32_t result = 0; if (node != 0 && !node.empty() && !node->empty() && callback != 0) { result = callback(node, node->_data); // if (result != 0) // { // if (result > 0) // { // return execute_path(node->_left, callback); // } // else // { // return execute_path(node->_right, callback); // } // } } return result; }
26.342697
126
0.656856
f2f99b32899966a08f5aa199583f70adc9ac009d
3,575
tcc
C++
src/utils/json/parser.tcc
unbornchikken/reflect-cpp
1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f
[ "BSD-2-Clause" ]
45
2015-03-24T09:35:46.000Z
2021-05-06T11:50:34.000Z
src/utils/json/parser.tcc
unbornchikken/reflect-cpp
1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f
[ "BSD-2-Clause" ]
null
null
null
src/utils/json/parser.tcc
unbornchikken/reflect-cpp
1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f
[ "BSD-2-Clause" ]
11
2015-01-27T12:08:21.000Z
2020-08-29T16:34:13.000Z
/* parser.tcc -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 12 Apr 2015 FreeBSD-style copyright and disclaimer apply */ #include "json.h" #pragma once namespace reflect { namespace json { /******************************************************************************/ /* GENERIC PARSER */ /******************************************************************************/ void parseNull(Reader& reader) { reader.expectToken(Token::Null); } bool parseBool(Reader& reader) { return reader.expectToken(Token::Bool).asBool(); } int64_t parseInt(Reader& reader) { return reader.expectToken(Token::Int).asInt(); } double parseFloat(Reader& reader) { Token token = reader.nextToken(); if (token.type() == Token::Int); else reader.assertToken(token, Token::Float); return token.asFloat(); } std::string parseString(Reader& reader) { return reader.expectToken(Token::String).asString(); } template<typename Fn> void parseObject(Reader& reader, const Fn& fn) { Token token = reader.nextToken(); if (token.type() == Token::Null) return; reader.assertToken(token, Token::ObjectStart); token = reader.peekToken(); if (token.type() == Token::ObjectEnd) { reader.expectToken(Token::ObjectEnd); return; } while (reader) { token = reader.expectToken(Token::String); const std::string& key = token.asString(); token = reader.expectToken(Token::KeySeparator); fn(key); token = reader.nextToken(); if (token.type() == Token::ObjectEnd) return; reader.assertToken(token, Token::Separator); } } template<typename Fn> void parseArray(Reader& reader, const Fn& fn) { Token token = reader.nextToken(); if (token.type() == Token::Null) return; reader.assertToken(token, Token::ArrayStart); token = reader.peekToken(); if (token.type() == Token::ArrayEnd) { reader.expectToken(Token::ArrayEnd); return; } for (size_t i = 0; reader; ++i) { fn(i); token = reader.nextToken(); if (token.type() == Token::ArrayEnd) return; reader.assertToken(token, Token::Separator); } } void skip(Reader& reader) { Token token = reader.peekToken(); if (!reader) return; switch (token.type()) { case Token::Null: case Token::Bool: case Token::Int: case Token::Float: case Token::String: (void) reader.nextToken(); break; case Token::ArrayStart: parseArray(reader, [&] (size_t) { skip(reader); }); break; case Token::ObjectStart: parseObject(reader, [&] (const std::string&) { skip(reader); }); break; default: reader.error("unable to skip token %s", token); break; } } /******************************************************************************/ /* VALUE PARSER */ /******************************************************************************/ template<typename T> void parse(Reader& reader, T& value) { Value v = cast<Value>(value); parse(reader, v); } template<typename T> Error parse(std::istream& stream, T& value) { Reader reader(stream); parse(reader, value); return reader.error(); } template<typename T> Error parse(const std::string& str, T& value) { std::istringstream stream(str); return parse(stream, value); } } // namespace json } // namespace reflect
23.064516
80
0.53958
f2f9f2b8b37680de67e251215bbab012254aa65a
290
hpp
C++
src/Game.hpp
ara159/snake
c65b25ab50a4b867f941c0a5406a11071ff80b78
[ "MIT" ]
null
null
null
src/Game.hpp
ara159/snake
c65b25ab50a4b867f941c0a5406a11071ff80b78
[ "MIT" ]
null
null
null
src/Game.hpp
ara159/snake
c65b25ab50a4b867f941c0a5406a11071ff80b78
[ "MIT" ]
null
null
null
#ifndef GAME_H #define GAME_H 1 #include "SFML/Graphics.hpp" #include "Snake.hpp" using namespace sf; class Game { private: RenderWindow * window; void run(); void event_handler(); void draw(); Snake snake; public: Game(); ~Game(); void start(); }; #endif
13.181818
28
0.627586
f2fa9b0bf14591422adab530b477db47bd3dab0a
14,020
cpp
C++
Source/Native/MouriOptimizationPlugin/MoManageCompactOS.cpp
bryanwills/NSudo
54ebd8092c3b2d4a89576d669ed123e23651ae77
[ "MIT" ]
1,363
2016-06-30T07:16:09.000Z
2022-03-30T09:50:08.000Z
Source/Native/MouriOptimizationPlugin/MoManageCompactOS.cpp
bryanwills/NSudo
54ebd8092c3b2d4a89576d669ed123e23651ae77
[ "MIT" ]
70
2017-04-29T11:17:33.000Z
2022-03-26T06:31:11.000Z
Source/Native/MouriOptimizationPlugin/MoManageCompactOS.cpp
bryanwills/NSudo
54ebd8092c3b2d4a89576d669ed123e23651ae77
[ "MIT" ]
206
2016-07-03T02:22:05.000Z
2022-03-25T02:47:24.000Z
/* * PROJECT: Mouri Optimization Plugin * FILE: MoManageCompactOS.cpp * PURPOSE: Implementation for Manage Compact OS * * LICENSE: The MIT License * * DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com) */ #include "MouriOptimizationPlugin.h" #include <string> #include <vector> namespace { static void CompressFileWorker( _In_ PNSUDO_CONTEXT Context, _In_ LPCWSTR RootPath) { HANDLE RootHandle = ::MoPrivateCreateFile( RootPath, SYNCHRONIZE | FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); if (RootHandle != INVALID_HANDLE_VALUE) { Mile::HResult hr = S_OK; hr = Mile::EnumerateFile( RootHandle, [&]( _In_ Mile::PFILE_ENUMERATE_INFORMATION Information) -> BOOL { if (Mile::IsDotsName(Information->FileName)) { return TRUE; } { DWORD& FileAttributes = Information->FileAttributes; if (FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { return TRUE; } if (FileAttributes & FILE_ATTRIBUTE_EA) { return TRUE; } if (FileAttributes & FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS) { return TRUE; } } std::wstring CurrentPath = Mile::FormatUtf16String( L"%s\\%s", RootPath, Information->FileName); if (S_OK == ::PathMatchSpecExW( CurrentPath.c_str(), L"*\\WinSxS\\Backup;" L"*\\WinSxS\\ManifestCache;" L"*\\WinSxS\\Manifests;" L"*\\ntldr;" L"*\\cmldr;" L"*\\BootMgr;" L"*\\aow.wim;" L"*\\boot\\bcd;" L"*\\boot\\bcd.*;" L"*\\boot\\bootstat.dat;" L"*\\config\\drivers;" L"*\\config\\drivers.*;" L"*\\config\\system;" L"*\\config\\system.*;" L"*\\windows\\bootstat.dat;" L"*\\winload.e??*;" L"*\\winresume.e??*;", PMSF_MULTIPLE)) { ::MoPrivateWriteLine( Context, Context->GetTranslation( Context, "SkippedText"), CurrentPath.c_str()); return TRUE; } if (Information->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) { ::CompressFileWorker( Context, CurrentPath.c_str()); return TRUE; } HANDLE CurrentHandle = ::MoPrivateCreateFile( CurrentPath.c_str(), FILE_READ_DATA | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); if (CurrentHandle == INVALID_HANDLE_VALUE) { ::MoPrivateWriteErrorMessage( Context, Mile::HResultFromLastError(FALSE), L"%s(%s)", L"CreateFileW", CurrentPath.c_str()); return TRUE; } DWORD CompressionAlgorithm = 0; hr = Mile::GetWofCompressionAttribute( CurrentHandle, &CompressionAlgorithm); if (hr.IsFailed() || CompressionAlgorithm != FILE_PROVIDER_COMPRESSION_XPRESS4K) { hr = Mile::SetWofCompressionAttribute( CurrentHandle, FILE_PROVIDER_COMPRESSION_XPRESS4K); if (hr.IsSucceeded()) { ::MoPrivateWriteLine( Context, Context->GetTranslation( Context, "CompressedText"), CurrentPath.c_str()); } else { ::MoPrivateWriteErrorMessage( Context, hr, L"%s(%s)", L"Mile::SetWofCompressionAttribute", CurrentPath.c_str()); } } else { ::MoPrivateWriteLine( Context, Context->GetTranslation( Context, "SkippedText"), CurrentPath.c_str()); } ::CloseHandle(CurrentHandle); return TRUE; }); if (hr.IsFailed()) { ::MoPrivateWriteErrorMessage( Context, hr, L"%s(%s)", L"Mile::EnumerateFile", RootPath); } ::CloseHandle(RootHandle); } else { ::MoPrivateWriteErrorMessage( Context, Mile::HResultFromLastError(FALSE), L"%s(%s)", L"CreateFileW", RootPath); } } static void UncompressFileWorker( _In_ PNSUDO_CONTEXT Context, _In_ LPCWSTR RootPath) { HANDLE RootHandle = ::MoPrivateCreateFile( RootPath, SYNCHRONIZE | FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); if (RootHandle != INVALID_HANDLE_VALUE) { Mile::HResult hr = S_OK; hr = Mile::EnumerateFile( RootHandle, [&]( _In_ Mile::PFILE_ENUMERATE_INFORMATION Information) -> BOOL { if (Mile::IsDotsName(Information->FileName)) { return TRUE; } std::wstring CurrentPath = Mile::FormatUtf16String( L"%s\\%s", RootPath, Information->FileName); { DWORD& FileAttributes = Information->FileAttributes; if (FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { return TRUE; } if (FileAttributes & FILE_ATTRIBUTE_EA) { return TRUE; } if (FileAttributes & FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS) { return TRUE; } } if (Information->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) { ::UncompressFileWorker( Context, CurrentPath.c_str()); return TRUE; } HANDLE CurrentHandle = ::MoPrivateCreateFile( CurrentPath.c_str(), FILE_READ_DATA | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); if (CurrentHandle == INVALID_HANDLE_VALUE) { ::MoPrivateWriteErrorMessage( Context, Mile::HResultFromLastError(FALSE), L"%s(%s)", L"CreateFileW", CurrentPath.c_str()); return TRUE; } DWORD CompressionAlgorithm = 0; hr = Mile::GetWofCompressionAttribute( CurrentHandle, &CompressionAlgorithm); if (hr.IsSucceeded()) { hr = Mile::RemoveWofCompressionAttribute(CurrentHandle); if (hr.IsSucceeded()) { ::MoPrivateWriteLine( Context, Context->GetTranslation( Context, "UncompressedText"), CurrentPath.c_str()); } else { ::MoPrivateWriteErrorMessage( Context, hr, L"%s(%s)", L"Mile::RemoveWofCompressionAttribute", CurrentPath.c_str()); } } else { ::MoPrivateWriteLine( Context, Context->GetTranslation( Context, "SkippedText"), CurrentPath.c_str()); } ::CloseHandle(CurrentHandle); return TRUE; }); if (hr.IsFailed()) { ::MoPrivateWriteErrorMessage( Context, hr, L"%s(%s)", L"Mile::EnumerateFile", RootPath); } ::CloseHandle(RootHandle); } else { ::MoPrivateWriteErrorMessage( Context, Mile::HResultFromLastError(FALSE), L"%s(%s)", L"CreateFileW", RootPath); } } } EXTERN_C HRESULT WINAPI MoManageCompactOS( _In_ PNSUDO_CONTEXT Context) { Mile::HResult hr = S_OK; HANDLE PreviousContextTokenHandle = INVALID_HANDLE_VALUE; do { if (!::IsWindows10OrGreater()) { hr = E_NOINTERFACE; break; } DWORD PurgeMode = ::MoPrivateParsePurgeMode(Context); if (PurgeMode == 0) { hr = Mile::HResult::FromWin32(ERROR_CANCELLED); break; } if (PurgeMode != MO_PRIVATE_PURGE_MODE_QUERY && PurgeMode != MO_PRIVATE_PURGE_MODE_ENABLE && PurgeMode != MO_PRIVATE_PURGE_MODE_DISABLE) { hr = E_NOINTERFACE; break; } hr = ::MoPrivateEnableBackupRestorePrivilege( &PreviousContextTokenHandle); if (hr.IsFailed()) { ::MoPrivateWriteErrorMessage( Context, hr, L"MoPrivateEnableBackupRestorePrivilege"); break; } if (PurgeMode == MO_PRIVATE_PURGE_MODE_QUERY) { DWORD DeploymentState = 0; ::MoPrivateWriteLine( Context, Context->GetTranslation( Context, (Mile::GetCompactOsDeploymentState( &DeploymentState).IsSucceeded() && DeploymentState != FALSE) ? "MoManageCompactOS_EnabledText" : "MoManageCompactOS_DisabledText")); } else if (PurgeMode == MO_PRIVATE_PURGE_MODE_ENABLE) { hr = Mile::SetCompactOsDeploymentState(TRUE); if (hr.IsFailed()) { ::MoPrivateWriteErrorMessage( Context, hr, L"Mile::SetCompactOsDeploymentState"); break; } ::CompressFileWorker( Context, Mile::ExpandEnvironmentStringsW(L"%SystemDrive%\\").c_str()); } else if (PurgeMode == MO_PRIVATE_PURGE_MODE_DISABLE) { ::UncompressFileWorker( Context, Mile::ExpandEnvironmentStringsW(L"%SystemDrive%\\").c_str()); DWORD DeploymentState = 0; if (Mile::GetCompactOsDeploymentState( &DeploymentState).IsSucceeded() && DeploymentState != FALSE) { hr = Mile::SetCompactOsDeploymentState(FALSE); if (hr.IsFailed()) { ::MoPrivateWriteErrorMessage( Context, hr, L"Mile::SetCompactOsDeploymentState"); break; } } } } while (false); if (PreviousContextTokenHandle != INVALID_HANDLE_VALUE) { ::SetThreadToken(nullptr, PreviousContextTokenHandle); ::CloseHandle(PreviousContextTokenHandle); } ::MoPrivateWriteFinalResult(Context, hr); return hr; }
32.155963
79
0.414194
f2ffc7cc13c60374f92699e9abddec3f51196fdc
3,184
cpp
C++
dynamic programming/dp3-27 gfg-leetcode/dp3 - 300. Longest Increasing Subsequence.cpp
ankithans/dsa
32aeeff1b4eeebcc8c18fdb1b95ee1dd123f8443
[ "MIT" ]
1
2021-09-16T07:01:46.000Z
2021-09-16T07:01:46.000Z
dynamic programming/dp3-27 gfg-leetcode/dp3 - 300. Longest Increasing Subsequence.cpp
ankithans/dsa
32aeeff1b4eeebcc8c18fdb1b95ee1dd123f8443
[ "MIT" ]
null
null
null
dynamic programming/dp3-27 gfg-leetcode/dp3 - 300. Longest Increasing Subsequence.cpp
ankithans/dsa
32aeeff1b4eeebcc8c18fdb1b95ee1dd123f8443
[ "MIT" ]
1
2021-10-19T06:48:48.000Z
2021-10-19T06:48:48.000Z
// 0 1 2 3 4 5 6 7 // [10,9,2,5,3,7,101,18] // o/p = 4 [2,3,7,101] // idx -> f -> LIS // (0, []) // 2 (1, [10]) (1, []) // (2,[10]) (2,[9]) (2,[]) // (3,[10]) (3,[9]) // (4,[10]) (4,[9]) // (5,[10]) // (6,[10,101]) (6,[10]) // (7,[10,101]) (7,[10,18]) (7,[10]) // 22 / 54 test cases passed. // TLE class Solution { public: int LIShelper(int idx, int lastMax, vector<int> &nums) { if(idx >= nums.size()) return 0; int pick = INT_MIN; if(nums[idx] > lastMax) { pick = 1 + LIShelper(idx+1, nums[idx], nums); } int not_pick = LIShelper(idx+1, lastMax, nums); return max(pick, not_pick); } int lengthOfLIS(vector<int>& nums) { return LIShelper(0, INT_MIN, nums); } }; class Solution { public: int LIShelper(vector<int> &nums, int idx, int lastMax, vector<int> &dp) { if(idx >= nums.size()) return 0; int pick = INT_MIN; if(nums[idx] > lastMax) { if(dp[idx] != -1) pick = dp[idx]; else dp[idx] = pick = 1 + LIShelper(nums, idx+1, nums[idx], dp); } int not_pick = LIShelper(nums, idx+1, lastMax, dp); return max(pick, not_pick); } int lengthOfLIS(vector<int>& nums) { vector<int> dp(nums.size()+1, -1); return LIShelper(nums, 0, INT_MIN, dp); } }; // https://leetcode.com/problems/longest-increasing-subsequence/discuss/1326552/Optimization-From-Brute-Force-to-Dynamic-Programming-Explained! class Solution { public: vector<vector<int>> dp; int LIShelper(vector<int> &nums, int idx, int lastMaxInd) { if(idx >= nums.size()) return 0; if(dp[idx][lastMaxInd+1] != -1) return dp[idx][lastMaxInd+1]; int pick = INT_MIN; if(lastMaxInd == -1 || nums[idx] > nums[lastMaxInd]) { pick = 1 + LIShelper(nums, idx+1, idx); } int not_pick = LIShelper(nums, idx+1, lastMaxInd); return dp[idx][lastMaxInd+1] = max(pick, not_pick); } int lengthOfLIS(vector<int>& nums) { dp.resize(size(nums), vector<int>(1+size(nums), -1)); return LIShelper(nums, 0, -1); } }; class Solution { public: vector<int> dp; int LIShelper(vector<int> &nums, int idx, int lastMaxInd) { if(idx >= nums.size()) return 0; if(dp[lastMaxInd+1] != -1) return dp[lastMaxInd+1]; int pick = INT_MIN; if(lastMaxInd == -1 || nums[idx] > nums[lastMaxInd]) { pick = 1 + LIShelper(nums, idx+1, idx); } int not_pick = LIShelper(nums, idx+1, lastMaxInd); return dp[lastMaxInd+1] = max(pick, not_pick); } int lengthOfLIS(vector<int>& nums) { dp.resize(size(nums)+1, -1); return LIShelper(nums, 0, -1); } };
26.983051
143
0.47142
f2ffca4a66451085ebad8884a6f3a40914c630c0
759
cpp
C++
src/506.cpp
MoRunChang2015/LeetCode
d046083b952811dfbf5f8fb646060836a3e937ce
[ "Apache-2.0" ]
null
null
null
src/506.cpp
MoRunChang2015/LeetCode
d046083b952811dfbf5f8fb646060836a3e937ce
[ "Apache-2.0" ]
null
null
null
src/506.cpp
MoRunChang2015/LeetCode
d046083b952811dfbf5f8fb646060836a3e937ce
[ "Apache-2.0" ]
null
null
null
class Solution { public: vector<string> findRelativeRanks(vector<int>& nums) { vector<pair<int, int>> v; for (int i = 0; i < nums.size(); ++i) { v.push_back({nums[i], i}); } sort(v.begin(), v.end()); vector<string> ans(nums.size()); for (int i = 0; i < nums.size(); ++i) { if (i == nums.size() - 1) { ans[v[i].second] = "Gold Medal"; } else if (i == nums.size() - 2) { ans[v[i].second] = "Silver Medal"; } else if (i == nums.size() - 3) { ans[v[i].second] = "Bronze Medal"; } else { ans[v[i].second] = to_string(nums.size() - i); } } return ans; } };
31.625
62
0.417655
8402cf8233496ce59dc4677557df3e787ed7dc5c
7,948
cc
C++
src/comm/communicator_collective.cc
akkaze/rdc
76e85e3fe441e3ba968a190d9496f467b9d4d2e6
[ "BSD-3-Clause" ]
52
2018-10-08T01:56:15.000Z
2021-03-14T12:19:51.000Z
src/comm/communicator_collective.cc
akkaze/rdc
76e85e3fe441e3ba968a190d9496f467b9d4d2e6
[ "BSD-3-Clause" ]
null
null
null
src/comm/communicator_collective.cc
akkaze/rdc
76e85e3fe441e3ba968a190d9496f467b9d4d2e6
[ "BSD-3-Clause" ]
3
2019-01-02T05:17:28.000Z
2020-01-06T03:53:12.000Z
#include "comm/communicator_base.h" #include "comm/communicator_manager.h" namespace rdc { namespace comm { void Communicator::TryAllreduce(Buffer sendrecvbuf, ReduceFunction reducer) { if (sendrecvbuf.size_in_bytes() > CommunicatorManager::Get()->reduce_ring_mincount()) { return this->TryAllreduceRing(sendrecvbuf, reducer); } else { return this->TryAllreduceTree(sendrecvbuf, reducer); } } void Communicator::TryReduceTree(Buffer sendrecvbuf, Buffer reducebuf, ReduceFunction reducer, int root) { auto dists_from_root = tree_map_.ShortestDist(root); auto dist_from_root = dists_from_root[GetRank()]; auto neighbors = tree_map_.GetNeighbors(GetRank()); std::unordered_set<int> recv_from_nodes; int send_to_node = -1; for (const auto& neighbor : neighbors) { if (dists_from_root[neighbor] == dist_from_root + 1) { recv_from_nodes.insert(neighbor); } else if (dists_from_root[neighbor] == dist_from_root - 1) { send_to_node = neighbor; } } for (const auto& recv_from_node : recv_from_nodes) { auto wc = all_links_[recv_from_node]->IRecv(reducebuf); wc->Wait(); reducer(reducebuf, sendrecvbuf); WorkCompletion::Delete(wc); } auto chain_wc = ChainWorkCompletion::New(); if (send_to_node != -1) { auto wc = all_links_[send_to_node]->ISend(sendrecvbuf); chain_wc->Add(wc); } chain_wc->Wait(); ChainWorkCompletion::Delete(chain_wc); return; } void Communicator::TryBroadcast(Buffer sendrecvbuf, int root) { auto dists_from_root = tree_map_.ShortestDist(root); auto dist_from_root = dists_from_root[GetRank()]; auto neighbors = tree_map_.GetNeighbors(GetRank()); std::unordered_set<int> send_to_nodes; int recv_from_node = -1; for (const auto& neighbor : neighbors) { if (dists_from_root[neighbor] == dist_from_root + 1) { send_to_nodes.insert(neighbor); } else if (dists_from_root[neighbor] == dist_from_root - 1) { recv_from_node = neighbor; } } auto chain_wc = ChainWorkCompletion::New(); if (recv_from_node != -1) { auto wc = all_links_[recv_from_node]->IRecv(sendrecvbuf); chain_wc->Add(wc); } for (const auto& send_to_node : send_to_nodes) { auto wc = all_links_[send_to_node]->ISend(sendrecvbuf); chain_wc->Add(wc); } chain_wc->Wait(); ChainWorkCompletion::Delete(chain_wc); return; } void Communicator::TryAllreduceTree(Buffer sendrecvbuf, ReduceFunction reducer) { Buffer reducebuf(sendrecvbuf.size_in_bytes()); reducebuf.AllocTemp(utils::AllocTemp); TryReduceTree(sendrecvbuf, reducebuf, reducer, 0); reducebuf.FreeTemp(utils::Free); TryBroadcast(sendrecvbuf, 0); } void Communicator::TryAllgatherRing(std::vector<Buffer> sendrecvbufs) { // read from next link and send to prev one auto &prev = ring_prev_, &next = ring_next_; const size_t count_bufs = GetWorldSize(); const size_t stop_write_idx = count_bufs + GetRank() - 1; const size_t stop_read_idx = count_bufs + GetRank(); size_t write_idx = GetRank(); size_t read_idx = GetRank() + 1; while (true) { bool finished = true; if (read_idx != stop_read_idx) { finished = false; } if (write_idx != stop_write_idx) { finished = false; } if (finished) break; auto chain_wc = ChainWorkCompletion::New(); if (write_idx < read_idx && write_idx != stop_write_idx) { size_t start = write_idx % count_bufs; auto wc = prev->ISend(sendrecvbufs[start]); chain_wc->Add(wc); write_idx++; } if (read_idx != stop_read_idx) { size_t start = read_idx % count_bufs; auto wc = next->IRecv(sendrecvbufs[start]); chain_wc->Add(wc); // wc.Wait(); read_idx++; } chain_wc->Wait(); ChainWorkCompletion::Delete(chain_wc); } } void Communicator::TryReduceScatterRing(Buffer sendrecvbuf, Buffer reducebuf, ReduceFunction reducer) { // read from next link and send to prev one auto &&prev = ring_prev_, &&next = ring_next_; uint64_t n = static_cast<uint64_t>(GetWorldSize()); const auto& ranges = utils::Split(0, sendrecvbuf.Count(), n); uint64_t write_idx = GetNextRank(); uint64_t read_idx = GetNextRank() + 1; uint64_t reduce_idx = read_idx; // position to stop reading const uint64_t stop_read_idx = n + GetNextRank(); // position to stop writing size_t stop_write_idx = n + GetRank(); ; const auto& item_size = sendrecvbuf.item_size(); if (stop_write_idx > stop_read_idx) { stop_write_idx -= n; CHECK_F(write_idx <= stop_write_idx, "write ptr boundary check"); } while (true) { bool finished = true; if (read_idx != stop_read_idx) { finished = false; } if (write_idx != stop_write_idx) { finished = false; } if (finished) break; auto chain_wc = ChainWorkCompletion::New(); if (write_idx < reduce_idx && write_idx != stop_write_idx) { uint64_t write_pos = write_idx % n; uint64_t write_size = (ranges[write_pos].second - ranges[write_pos].first) * item_size; uint64_t write_start = ranges[write_pos].first * item_size; auto wc = prev->ISend( sendrecvbuf.Slice(write_start, write_start + write_size)); chain_wc->Add(wc); write_idx++; } if (read_idx != stop_read_idx) { uint64_t read_pos = read_idx % n; uint64_t read_start = ranges[read_pos].first * item_size; uint64_t read_size = (ranges[read_pos].second - ranges[read_pos].first) * item_size; auto wc = next->IRecv( reducebuf.Slice(read_start, read_start + read_size)); chain_wc->Add(wc); chain_wc->Wait(); CHECK_F(read_idx <= stop_read_idx, "[%d] read_ptr boundary check", GetRank()); read_idx++; size_t reduce_pos = reduce_idx % n; size_t reduce_start = ranges[reduce_pos].first * item_size; size_t reduce_size = (ranges[reduce_pos].second - ranges[reduce_pos].first) * item_size; reducer( reducebuf.Slice(reduce_start, reduce_start + reduce_size), sendrecvbuf.Slice(reduce_start, reduce_start + reduce_size)); reduce_idx++; } ChainWorkCompletion::Delete(chain_wc); } return; } void Communicator::TryAllreduceRing(Buffer sendrecvbuf, ReduceFunction reducer) { Buffer reducebuf(sendrecvbuf.size_in_bytes()); reducebuf.AllocTemp(utils::AllocTemp); reducebuf.set_item_size(sendrecvbuf.item_size()); TryReduceScatterRing(sendrecvbuf, reducebuf, reducer); reducebuf.FreeTemp(utils::Free); uint64_t n = static_cast<uint64_t>(GetWorldSize()); const auto& ranges = utils::Split(0, sendrecvbuf.Count(), n); // get rank of previous std::vector<Buffer> sendrecvbufs(n); for (auto i = 0U; i < n; i++) { uint64_t begin = ranges[i].first; uint64_t end = ranges[i].second; uint64_t size = (end - begin) * sendrecvbuf.item_size(); sendrecvbufs[i].set_size_in_bytes(size); sendrecvbufs[i].set_addr(utils::IncrVoidPtr( sendrecvbuf.addr(), begin * sendrecvbuf.item_size())); } return TryAllgatherRing(sendrecvbufs); } } // namespace comm } // namespace rdc
38.582524
78
0.612355
8404279ffd536f25360485833c7e0df1f9a555f5
2,249
cpp
C++
src/minhook_api.cpp
MG4vQIs7Fv/PerformanceOverhaulCyberpunk
4fb6e34752ce7c286357cf148d0b4096d4ca32ea
[ "MIT" ]
26
2019-10-28T00:14:18.000Z
2022-03-05T22:26:46.000Z
src/minhook_api.cpp
MG4vQIs7Fv/PerformanceOverhaulCyberpunk
4fb6e34752ce7c286357cf148d0b4096d4ca32ea
[ "MIT" ]
null
null
null
src/minhook_api.cpp
MG4vQIs7Fv/PerformanceOverhaulCyberpunk
4fb6e34752ce7c286357cf148d0b4096d4ca32ea
[ "MIT" ]
7
2019-10-28T03:21:19.000Z
2022-03-25T11:05:43.000Z
#include "common.hpp" #include "minhook_api.hpp" #include "minhook.h" namespace minhook_api { #if defined(USE_MINHOOK) && (USE_MINHOOK == 1) void init() { if(MH_Initialize() != MH_OK) { DEBUG_TRACE("MH_Initialize : failed\n"); } } void cleanup() { MH_Uninitialize(); } #else void init() {} void cleanup() {} #endif } // namespace minhook #if defined(USE_MINHOOK) && (USE_MINHOOK == 1) #define D(funcname, ...) \ return funcname(__VA_ARGS__); \ __pragma(comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)) extern "C" MH_STATUS WINAPI MH_Initialize_(void) { D(MH_Initialize) } extern "C" MH_STATUS WINAPI MH_Uninitialize_(void) { D(MH_Uninitialize); } extern "C" MH_STATUS WINAPI MH_CreateHook_(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal) { D(MH_CreateHook, pTarget, pDetour, ppOriginal); } extern "C" MH_STATUS WINAPI MH_CreateHookApi_(LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal) { D(MH_CreateHookApi, pszModule, pszProcName, pDetour, ppOriginal); } extern "C" MH_STATUS WINAPI MH_CreateHookApiEx_(LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget) { D(MH_CreateHookApiEx, pszModule, pszProcName, pDetour, ppOriginal, ppTarget); } extern "C" MH_STATUS WINAPI MH_RemoveHook_(LPVOID pTarget) { D(MH_RemoveHook, pTarget); } extern "C" MH_STATUS WINAPI MH_EnableHook_(LPVOID pTarget) { D(MH_EnableHook, pTarget); } extern "C" MH_STATUS WINAPI MH_DisableHook_(LPVOID pTarget) { D(MH_DisableHook, pTarget); } extern "C" MH_STATUS WINAPI MH_QueueEnableHook_(LPVOID pTarget) { D(MH_QueueEnableHook, pTarget); } extern "C" MH_STATUS WINAPI MH_QueueDisableHook_(LPVOID pTarget) { D(MH_QueueDisableHook, pTarget); } extern "C" MH_STATUS WINAPI MH_ApplyQueued_(void) { D(MH_ApplyQueued); } extern "C" const char * WINAPI MH_StatusToString_(MH_STATUS status) { D(MH_StatusToString, status); } #endif
28.833333
142
0.638061
8405943d2334623503f09655d041c70e5d8bc794
483
cpp
C++
C++ STL Programming/C++_STL_Programming/Operator_Overloading/06_PlusOperatorFuncion.cpp
devgunho/Cpp_AtoZ
4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc
[ "MIT" ]
1
2022-03-25T06:11:06.000Z
2022-03-25T06:11:06.000Z
C++ STL Programming/C++_STL_Programming/Operator_Overloading/06_PlusOperatorFuncion.cpp
devgunho/Cpp_AtoZ
4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc
[ "MIT" ]
null
null
null
C++ STL Programming/C++_STL_Programming/Operator_Overloading/06_PlusOperatorFuncion.cpp
devgunho/Cpp_AtoZ
4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Point { int x; int y; public: Point(int _x = 0, int _y = 0) :x(_x), y(_y) {} void Print() const { cout << x << ',' << y << endl; } const Point operator+(const Point& arg) const { Point pt; pt.x = this->x + arg.x; pt.y = this->y + arg.y; return pt; } }; int main() { Point p1(2, 3), p2(5, 5); Point p3; p3 = p1 + p2; // = p1.operator+(p2) p3.Print(); p3 = p1.operator+(p2); // Direct call p3.Print(); return 0; }
16.1
54
0.554865
8406a1d0255cf5abbe189d3c0beeb27a9a93973a
389
hpp
C++
src/firmware/src/websocket/socket_server.hpp
geaz/tableDisco
1f081a0372da835150881da245dc69d97dcaabe3
[ "MIT" ]
1
2020-05-26T01:45:04.000Z
2020-05-26T01:45:04.000Z
src/firmware/src/websocket/socket_server.hpp
geaz/tableDisco
1f081a0372da835150881da245dc69d97dcaabe3
[ "MIT" ]
null
null
null
src/firmware/src/websocket/socket_server.hpp
geaz/tableDisco
1f081a0372da835150881da245dc69d97dcaabe3
[ "MIT" ]
null
null
null
#pragma once #ifndef SOCKETSERVER_H #define SOCKETSERVER_H #include <WebSocketsServer.h> namespace TableDisco { class SocketServer { public: SocketServer(); void loop(); void broadcast(String data); private: WebSocketsServer webSocket = WebSocketsServer(81); }; } #endif // SOCKETSERVER_H
17.681818
62
0.586118
8406dca80a0a5d0c040e297255c6eae5b07d4f27
2,391
cpp
C++
src/index_handler/index_file_handler.cpp
robinren03/database2021
50074b6fdab2bcd5d4c95870f247cfb430804081
[ "Apache-2.0" ]
null
null
null
src/index_handler/index_file_handler.cpp
robinren03/database2021
50074b6fdab2bcd5d4c95870f247cfb430804081
[ "Apache-2.0" ]
null
null
null
src/index_handler/index_file_handler.cpp
robinren03/database2021
50074b6fdab2bcd5d4c95870f247cfb430804081
[ "Apache-2.0" ]
1
2022-01-11T08:20:41.000Z
2022-01-11T08:20:41.000Z
#include "index_file_handler.h" #include <assert.h> IndexFileHandler::IndexFileHandler(BufManager* _bm){ bm = _bm; header = new IndexFileHeader; } void IndexFileHandler::openFile(const char* fileName){ fileID = bm->openFile(fileName); int headerIndex; if (fileID == -1){ bm->createFile(fileName); fileID = bm->openFile(fileName); /*IndexFileHeader* tempHeader = (IndexFileHeader*)*/bm->allocPage(fileID, 0, headerIndex); headerChanged = true; header->rootPageId = 1; header->pageCount = 1; header->firstLeaf = 1; header->lastLeaf = 1; header->sum = 0; int index; BPlusNode* root = (BPlusNode*)bm->allocPage(fileID, 1, index); root->nextPage = 0; root->prevPage = 0; root->nodeType = ix::LEAF; root->pageId = 1; root->recs = 0; bm->markDirty(index); } else { IndexFileHeader* tempHeader = (IndexFileHeader*)bm->getPage(fileID, 0, headerIndex); memcpy(header, tempHeader, sizeof(IndexFileHeader)); } } IndexFileHandler::~IndexFileHandler(){ delete header; closeFile(); } void IndexFileHandler::access(int index){ bm->access(index); } char* IndexFileHandler::newPage(int &index, bool isOvrflowPage){ // std::cout << "Apply for a new page" << std::endl; header->pageCount++; /*if (header->pageCount == 342) { cout << "Hello World!" << endl; } std::cout << "Apply for a new page" << header->pageCount << std::endl;*/ char* res = bm->getPage(fileID, header->pageCount, index); if(isOvrflowPage) ((BPlusOverflowPage*)res)->pageId = header->pageCount; else ((BPlusNode*)res)->pageId = header->pageCount; markPageDirty(index); markHeaderPageDirty(); return res; } char* IndexFileHandler::getPage(int pageID, int& index){ return bm->getPage(fileID, pageID, index); } void IndexFileHandler::markHeaderPageDirty(){ headerChanged = true; } void IndexFileHandler::markPageDirty(int index){ bm->markDirty(index); } void IndexFileHandler::closeFile(){ if (bm != nullptr){ int headerIndex; IndexFileHeader* tempHeader = (IndexFileHeader*)bm->getPage(fileID, 0, headerIndex); memcpy(tempHeader, header, sizeof(IndexFileHeader)); this->markPageDirty(headerIndex); bm->closeFile(fileID); } }
29.158537
98
0.634044
840c144708b1a8d9abcb758af72c07ae85187df7
2,833
cpp
C++
misc/fexcept/execdump/xxlib/Std/mu_case.cpp
MKadaner/FarManager
c99a14c12e3481dd25ce71451ecd264656f631bb
[ "BSD-3-Clause" ]
1,256
2015-07-07T12:19:17.000Z
2022-03-31T18:41:41.000Z
misc/fexcept/execdump/xxlib/Std/mu_case.cpp
MKadaner/FarManager
c99a14c12e3481dd25ce71451ecd264656f631bb
[ "BSD-3-Clause" ]
305
2017-11-01T18:58:50.000Z
2022-03-22T11:07:23.000Z
misc/fexcept/execdump/xxlib/Std/mu_case.cpp
MKadaner/FarManager
c99a14c12e3481dd25ce71451ecd264656f631bb
[ "BSD-3-Clause" ]
183
2017-10-28T11:31:14.000Z
2022-03-30T16:46:24.000Z
#include <all_lib.h> #pragma hdrstop #if defined(__MYPACKAGE__) #pragma package(smart_init) #endif #if !defined(__HWIN__) static char *lwrChars = "йцукенгшщзхъфывапролджэячсмитьбю"; static char *uprChars = "ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ"; char MYRTLEXP ToUpper( char ch ) { if ( ch >= 'A' && ch <= 'Z' ) return ch; if ( ch >= 'a' && ch <= 'z' ) return (char)(ch-'a'+'A'); for( int n = 0; lwrChars[n]; n++ ) if ( lwrChars[n] == ch ) return uprChars[n]; return ch; } char MYRTLEXP ToLower( char ch ) { if ( ch >= 'a' && ch <= 'z' ) return ch; if ( ch >= 'A' && ch <= 'Z' ) return (char)(ch-'A'+'a'); for( int n = 0; uprChars[n]; n++ ) if ( uprChars[n] == ch ) return lwrChars[n]; return ch; } BOOL MYRTLEXP isLower( char ch ) { if ( ch >= 'a' && ch <= 'z' ) return TRUE; return StrChr(lwrChars,ch) != NULL; } BOOL MYRTLEXP isUpper( char ch ) { if ( ch >= 'A' && ch <= 'Z' ) return TRUE; return StrChr(uprChars,ch) != NULL; } void MYRTLEXP StrLwr( char *str ) { for ( int n = 0; str[n]; n++ ) str[n] = ToLower( str[n] ); } void MYRTLEXP StrUpr( char *str ) { for ( int n = 0; str[n]; n++ ) str[n] = ToUpper( str[n] ); } #endif static const char* sysSpaces= " \t"; BOOL MYRTLEXP isSpace( char ch ) { return StrChr( sysSpaces,ch ) != NULL; } char *MYRTLEXP StrCase( char *str,msCaseTypes type ) { int n; if ( !str || *str == 0 ) return str; switch( type ){ case mscLower: StrLwr( str ); break; case mscUpper: StrUpr( str ); break; case mscCapitalize: StrLwr( str ); str[0] = ToUpper(str[0]); break; case mscUpLower: for ( n = 0; str[n]; n++ ) if ( isLower(str[n]) ) return str; return StrCase( str,mscLower ); case mscLoUpper: for ( n = 0; str[n]; n++ ) if ( isUpper(str[n]) ) return str; return StrCase( str,mscUpper ); case mscInvert: for ( n = 0; str[n]; n++ ) if ( isUpper(str[n]) ) str[n] = ToLower(str[n]); else str[n] = ToUpper(str[n]); break; } return str; } #if defined(__GNUC__) static int memicmp(const void *s1, const void *s2, size_t n) { LPCBYTE b1 = (LPCBYTE)s1, b2 = (LPCBYTE)s2; for( ; n > 0; n--, b1++, b2++ ) { BYTE ch = *b1 - *b2; if ( ch ) return (int)(ch); } return 0; } #endif BOOL MYRTLEXP BuffCmp( LPBYTE b, LPBYTE b1, DWORD count, BOOL Case ) { if ( Case ) return memcmp( b,b1,count ) == 0; else return memicmp( b,b1,count ) == 0; }
24.850877
68
0.491705
840cc9b4774d397c3f63b506e10cd5e32c5a3893
655
cpp
C++
test.cpp
ZaMaZaN4iK/iex_example
57717f34f39ceadf1407bdd6b925f6b8c894533c
[ "MIT" ]
1
2020-04-25T14:16:03.000Z
2020-04-25T14:16:03.000Z
test.cpp
ZaMaZaN4iK/iex_example
57717f34f39ceadf1407bdd6b925f6b8c894533c
[ "MIT" ]
null
null
null
test.cpp
ZaMaZaN4iK/iex_example
57717f34f39ceadf1407bdd6b925f6b8c894533c
[ "MIT" ]
1
2020-04-25T14:17:49.000Z
2020-04-25T14:17:49.000Z
#define CATCH_CONFIG_MAIN #include <catch.hpp> #include "CompanyPriceDataStorage.h" /* That's a sample test case */ TEST_CASE( "Company price data is stored and selecte3d", "[storage]" ) { CompanyPriceData etalonData{0, "1", "2", "3", "4"} CompanyPriceDataStorage storage("test.db"); const int id = storage.store(etalonData); const CompanyPriceData storedData = storage.read(id); CHECK_THAT(etalonData.symbol, Equals(storedData.symbol)); CHECK_THAT(etalonData.companyName, Equals(storedData.companyName)); CHECK_THAT(etalonData.logo, Equals(storedData.logo)); CHECK_THAT(etalonData.price, Equals(storedData.price)); }
32.75
72
0.732824
8411ec0587bd6d49d94bee2f8e3e0d32ae5148d6
5,231
cpp
C++
source/options/OptionDialog.cpp
Mauzerov/wxPacman
9fe599b1588d6143ff563ae8a3e5c2f31f69a5c3
[ "Unlicense" ]
1
2021-05-02T10:38:03.000Z
2021-05-02T10:38:03.000Z
source/options/OptionDialog.cpp
Mauzerov/wxPacman
9fe599b1588d6143ff563ae8a3e5c2f31f69a5c3
[ "Unlicense" ]
null
null
null
source/options/OptionDialog.cpp
Mauzerov/wxPacman
9fe599b1588d6143ff563ae8a3e5c2f31f69a5c3
[ "Unlicense" ]
null
null
null
#include "OptionDialog.h" #include <iostream> //(*InternalHeaders(OptionDialog) #include <wx/font.h> #include <wx/intl.h> #include <wx/settings.h> #include <wx/string.h> //*) //(*IdInit(OptionDialog) const long OptionDialog::ID_BUTTONSAVE = wxNewId(); const long OptionDialog::ID_KEYCHOICE = wxNewId(); const long OptionDialog::ID_LANGCHOICE = wxNewId(); //*) BEGIN_EVENT_TABLE(OptionDialog,wxDialog) //(*EventTable(OptionDialog) //*) END_EVENT_TABLE() OptionDialog::OptionDialog(wxWindow* parent, wxWindowID id, std::string movement, std::string language) { //(*Initialize(OptionDialog) Create(parent, id, _("Options"), wxDefaultPosition, wxDefaultSize, wxCAPTION|wxSYSTEM_MENU, _T("id")); SetClientSize(wxSize(400,200)); SetForegroundColour(wxColour(255,255,255)); SetBackgroundColour(wxColour(0,0,0)); wxFont thisFont(11,wxFONTFAMILY_MODERN,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL,false,_T("Consolas"),wxFONTENCODING_DEFAULT); SetFont(thisFont); GamePausePanel = new wxPanel(this, wxID_ANY, wxPoint(0,0), wxSize(400,30), 0, _T("wxID_ANY")); GamePauseLabel = new wxStaticText(GamePausePanel, wxID_ANY, _("GAME PAUSED"), wxPoint(0,0), wxSize(400,50), wxALIGN_CENTRE, _T("wxID_ANY")); GamePauseLabel->SetForegroundColour(wxColour(243,156,18)); GamePauseLabel->SetBackgroundColour(wxColour(16,16,16)); wxFont GamePauseLabelFont(20,wxFONTFAMILY_MODERN,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL,false,_T("Consolas"),wxFONTENCODING_DEFAULT); GamePauseLabel->SetFont(GamePauseLabelFont); GamePauseUnderLine = new wxStaticLine(this, wxID_ANY, wxPoint(0,30), wxSize(400,2), wxLI_HORIZONTAL, _T("wxID_ANY")); GamePauseUnderLine->SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME)); GamePauseUnderLine->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME)); SaveOptionBtn = new wxButton(this, ID_BUTTONSAVE, _("Save Options"), wxPoint(100,175), wxSize(200,25), wxBORDER_NONE|wxTRANSPARENT_WINDOW, wxDefaultValidator, _T("ID_BUTTONSAVE")); SaveOptionBtn->SetForegroundColour(wxColour(255,255,255)); SaveOptionBtn->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME)); KeyBindsPanel = new wxPanel(this, wxID_ANY, wxPoint(0,40), wxSize(200,50), wxBORDER_SIMPLE, _T("wxID_ANY")); KeyBindsMoveChoice = new wxChoice(KeyBindsPanel, ID_KEYCHOICE, wxPoint(8,8), wxDefaultSize, 0, 0, 0, wxDefaultValidator, _T("ID_KEYCHOICE")); KeyBindsMoveChoice->Append(_("Arrows")); KeyBindsMoveChoice->Append(_("WSAD")); KeyBindsMoveLabel = new wxStaticText(KeyBindsPanel, wxID_ANY, _("Movement\nKeys"), wxPoint(120,4), wxSize(70,40), wxALIGN_CENTRE, _T("wxID_ANY")); KeyBindsMoveLabel->SetForegroundColour(wxColour(255,255,255)); GameLangPanel = new wxPanel(this, wxID_ANY, wxPoint(200,40), wxSize(200,50), wxBORDER_SIMPLE, _T("wxID_ANY")); GameLangChoise = new wxChoice(GameLangPanel, ID_LANGCHOICE, wxPoint(8,8), wxDefaultSize, 0, 0, 0, wxDefaultValidator, _T("ID_LANGCHOICE")); GameLangChoise->Append(_("Polski")); GameLangChoise->Append(_("English")); GameLangLabel = new wxStaticText(GameLangPanel, wxID_ANY, _("Language"), wxPoint(120,12), wxSize(70,40), wxALIGN_CENTRE, _T("wxID_ANY")); GameLangLabel->SetForegroundColour(wxColour(255,255,255)); SpaceShootLabel = new wxStaticText(this, wxID_ANY, _("Label"), wxPoint(10,100), wxSize(380,20), wxALIGN_CENTRE, _T("wxID_ANY")); wxFont SpaceShootLabelFont(12,wxFONTFAMILY_MODERN,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL,false,_T("Consolas"),wxFONTENCODING_DEFAULT); SpaceShootLabel->SetFont(SpaceShootLabelFont); Center(); Connect(ID_BUTTONSAVE,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&OptionDialog::OnSaveOptionBtnClick); Connect(wxID_ANY,wxEVT_CLOSE_WINDOW,(wxObjectEventFunction)&OptionDialog::OnDialogClose); //*) ///TODO Options uising int indexes this->KeyBindsMoveChoice->Select(this->KeyBindsMoveChoice->FindString(movement)); // Set Current Move Option this->GameLangChoise->Select(this->GameLangChoise->FindString(language)); // Set Current Language Option this->GameLangLabel->SetLabel(lang::lang.at(language).at("language_pick")); // Translated Language this->KeyBindsMoveLabel->SetLabel(lang::lang.at(language).at("movement_pick")); // Translated Movement this->SaveOptionBtn->SetLabel(lang::lang.at(language).at("save_options")); // Translated Saving Options this->GamePauseLabel->SetLabel(lang::lang.at(language).at("game_paused")); // Translated Game Paused Label this->SpaceShootLabel->SetLabel(lang::lang.at(language).at("space_button")); // Translated Game Paused Label this->movement = movement; this->language = language; } OptionDialog::~OptionDialog( void ) { //(*Destroy(OptionDialog) //*) } void OptionDialog::OnDialogClose(wxCloseEvent& event) { this->Destroy(); } void OptionDialog::SaveOptions( void ) { this->movement = std::string(this->KeyBindsMoveChoice->GetStringSelection().mb_str()); // Changing Movement Method this->language = std::string(this->GameLangChoise->GetStringSelection().mb_str()); // Changing Language } void OptionDialog::OnSaveOptionBtnClick(wxCommandEvent& event) { this->SaveOptions(); this->Destroy(); }
52.31
182
0.761422