blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
5c9ad6e5dbe3600caa4548be1f61390df805b33b
C++
sogapalag/problems
/codeforces/601b.cpp
UTF-8
1,859
2.96875
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; using ll=long long; // should hold transitivity. using PartialOrd = function<bool(int,int)>; // f(x, i): x by(<) i vector<int> get_dominating_left(int n, PartialOrd f) { assert(n > 0); vector<int> L(n); vector<int> stk; for (int i = 0; i < n; i++) { // some case might need check dominating itself here // if not dominating itself, L[i] = i + 1; while (!stk.empty() && f(stk.back(), i)) { stk.pop_back(); } L[i] = stk.empty() ? 0 : stk.back() + 1; stk.push_back(i); } return L; } vector<int> get_dominating_right(int n, PartialOrd f) { assert(n > 0); vector<int> R(n); vector<int> stk; for (int i = n-1; i >= 0; i--) { // if not dominating itself, R[i] = i - 1; while (!stk.empty() && f(stk.back(), i)) { stk.pop_back(); } R[i] = stk.empty() ? n-1 : stk.back() - 1; stk.push_back(i); } return R; } ll calc(vector<int>& a) { int n = a.size(); auto L = get_dominating_left(n, [&](int l, int i){ return a[l]<a[i]; }); auto R = get_dominating_right(n, [&](int r, int i){ return a[r]<=a[i]; }); ll res = 0; for (int i = 0; i < n; i++) { res += a[i] * 1ll * (i-L[i]+1) * (R[i]-i+1); } return res; } // key: max Lipshitz must be some adj-index // brute-force each query, since q~100. Bonus q~1e5? void solve() { int n,q; cin >> n >> q; vector<int> a(n); for (auto& x: a) { cin >> x; } while (q--) { int l,r; cin >> l >> r; vector<int> b; for (int i = l; i < r; i++) { b.push_back(abs(a[i] - a[i-1])); } cout << calc(b) << '\n'; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
true
c29264bf6a41d0f8a926f90b490a34dcd7bf184f
C++
raghavaggarwal99/Competitive
/Graphs/Interviewbit/steppingnumbers.cpp
UTF-8
874
3.015625
3
[]
no_license
void dfs(int A, int B, vector<int> &ans, int num){ if( num>B){ return ; } if(num==0 && num>=A && num<=B){ ans.push_back(0); return ; } else if(num==0){ return; } if(num>=A && num<=B){ ans.push_back(num); } int lastdigit= num%10; int step1= num*10+lastdigit-1; int step2= num*10+lastdigit+1; if(lastdigit==0){ dfs(A,B,ans,step2); } else if(lastdigit==9){ dfs(A,B,ans,step1); } else{ dfs(A,B,ans,step1); dfs(A,B,ans,step2); } } vector<int> Solution::stepnum(int A, int B) { vector<int> ans; for(int i=0; i<=9; i++){ dfs(A, B, ans, i); } sort(ans.begin(), ans.end()); return ans; }
true
0f15818a3c71d08dca3b66ae90b1f513532ea6dc
C++
gauthamip/MissionRnD-C-Strings-Worksheet
/src/StrWordsinRev.cpp
UTF-8
721
3.4375
3
[]
no_license
/* OVERVIEW: Given a string, reverse all the words not the string. E.g.: Input: "i like coding". Output: "coding like i" INPUTS: A string. OUTPUT: Modify the string according to the logic. NOTES: Don't create new string. */ #include <Stdio.h> #include <string.h> void str_words_in_rev(char *input, int len){ int i = len - 1; int k = len - 1; int p = 0; char ip[40]; while (input[i] > 0) { if (input[i] == ' ') { for (int j = i + 1; j <= k; j++) { ip[p] = input[j]; p++; } ip[p] = ' '; p++; k = i - 1; } if (i == 0) { for (int j = i; j <= k; j++) { ip[p] = input[j]; p++; } } i--; } ip[p] = '\0'; for (i = 0; i < len; i++) { input[i] = ip[i]; } }
true
693c41fb2be0aea5f605205388b4d05a773f9e52
C++
petrenko-alex/array-range-analyzer
/ArrayRangeAnalyzer/main.cpp
UTF-8
3,372
2.921875
3
[ "BSD-3-Clause" ]
permissive
/*! *\file *\brief Файл основной функции программы. *\author Александр Петренко gafk555@gmail.com. * * Данный файл содержит в себе функцию main - осовную функцию, вполняющую программу. */ #include <QtCore/QCoreApplication> #include "input.h" #include "analyzer.h" #include "output.h" #include "operations.h" #include "index.h" #include "array.h" #include "exceeding.h" int main(int argc, char *argv[]) { printf("********** Array Range Analyzer **********\n"); Input input; Output out; Analyzer analyze; Operations ops; QStringList inputFileNames; QVector<Index> vars; QVector<Array> arrs; QVector<Exceeding> exceedings; QStringList expr; bool correctInputData = false; /* Проверка аргументов командной строки */ if (argc == 1) { out.writeError(QString("Additional arguments of command line are not set.Please, set required arguments.")); printf("\nError!!!\nAdditional arguments of command line are not set.\nPlease, set required arguments.\n"); return 1; } else if (argc == 2) { out.writeError(QString("Not enough arguments of command line. The file with array's info is not set.")); printf("\nError!!!\nNot enough arguments of command line.\nThe file with array's info is not set.\n"); return 1; } else if (argc == 3) { out.writeError(QString("Not enough arguments of command line. The file with variable's info is not set.")); printf("\nError!!!\nNot enough arguments of command line.\nThe file with variable's info is not set.\n"); return 1; } else if (argc > 3) { printf("\nArguments of command line are set correctly...\n"); inputFileNames << argv[3] << argv[2] << argv[1]; } /* Считывание входных данных */ correctInputData = input.readData(inputFileNames, vars, arrs, expr); /* Установка счетчика зацикливания по дополнительному аргументу командной строки */ if (correctInputData && argc > 4) { QString argument(argv[4]); int loop = 10; if (ops.isNumber(argument)) { loop = argument.toInt(); for (auto &var : vars) { var.looped = loop; } printf("\nInfinite loop counter is set to %s...\n", argv[4]); } } /* Проверка выражения на наличие выходов за пределы массива */ if (correctInputData) { analyze.checkExpression(vars, arrs, expr, exceedings); } else { printf("\nError!!!\nInput data reading failed.\nPlease, check \"ArrayRangeAnalyzer-Errors.txt\" file for more info.\n"); return 1; } /* Вывод результатов работы прогаммы */ out.makeOutputFile(exceedings, arrs, inputFileNames); /* Если в процессе анализа выражения ошибок не произошло */ if (out.isErrorOccured()) { printf("\nAnalyzing completed.\nSome errors were detected.\nPlease, check \"ArrayRangeAnalyzer-Errors.txt\" file for errors info\nAnd \"ArrayRangeAnalyzer-Results.txt\" file for results.\n"); } /* Если в процессе анализа выражения произошли ошибки */ else { printf("\nAnalyzing completed.\nNo errors were detected.\nPlease, check \"ArrayRangeAnalyzer-Results.txt\" file for results.\n"); } return 0; }
true
02ab96358733ec3b6764466120654e297955ebac
C++
goffrie/grapher
/dynamic_unique_cast.h
UTF-8
700
3.28125
3
[]
no_license
#ifndef _DYNAMIC_UNIQUE_CAST_H_ #define _DYNAMIC_UNIQUE_CAST_H_ template<typename B, typename A> std::unique_ptr<B> dynamic_unique_cast(std::unique_ptr<A> a) { B* b = dynamic_cast<B*>(a.get()); if (b != NULL) { a.release(); // let go of a's pointer; b holds it now } // otherwise, let a's destructor take care of destroying it return std::unique_ptr<B>(b); } template<typename B, typename A> std::unique_ptr<B> dynamic_maybe_unique_cast(std::unique_ptr<A>& a) { B* b = dynamic_cast<B*>(a.get()); if (b != NULL) { a.release(); // let go of a's pointer; b holds it now } // otherwise, let a keep holding on to it return std::unique_ptr<B>(b); } #endif
true
8d909afc2c48f8d709b9c078400045374b0f0e07
C++
vinicassol/poo
/JogoDaVelha/Jogador.hpp
UTF-8
221
2.578125
3
[]
no_license
#include <iostream> using namespace std; class Jogador { public: void SetPlayer(string nome, char simbolo); string GetNome(); char GetSimbolo(); private: char simbolo; // se eh X ou O string nome; };
true
6e5271ad4adab28ef3b17284d186cb19aea4fbff
C++
moejoe95/theConspiracy
/src/managers/Renderer.cpp
UTF-8
4,277
2.609375
3
[]
no_license
#include "Renderer.hpp" #include "../utils/Constants.hpp" #include "../utils/SDLException.hpp" #include "../utils/Utils.hpp" #include <SDL_image.h> #include <spdlog/spdlog.h> Renderer::Renderer() { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) throw SDLException("SDL_Init failed."); window = SDL_CreateWindow("the conspiracy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (!window) throw SDLException("SDL_CreateWindow failed."); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!renderer) throw SDLException("SDL_CreateRenderer failed."); if (TTF_Init() < 0) throw SDLException("TTF_Init failed"); std::string fontName = getResourcePath("") + "Hack-Regular.ttf"; TTF_Init(); fontMenu = TTF_OpenFont(fontName.c_str(), 38); if (!fontMenu) throw SDLException("Failed to load font " + fontName); font = TTF_OpenFont(fontName.c_str(), 20); if (!font) throw SDLException("Failed to load font " + fontName); } Renderer::~Renderer() { TTF_CloseFont(font); TTF_CloseFont(fontMenu); TTF_Quit(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } void Renderer::clear() { SDL_RenderClear(renderer); } void Renderer::update() { SDL_RenderPresent(renderer); } void Renderer::drawText(TTF_Font *font, const std::string &text, SDL_Rect rect) { SDL_Surface *surfaceMessage = TTF_RenderText_Solid(font, text.c_str(), {255, 255, 255}); SDL_Texture *message = SDL_CreateTextureFromSurface(renderer, surfaceMessage); SDL_RenderCopy(renderer, message, NULL, &rect); SDL_DestroyTexture(message); SDL_FreeSurface(surfaceMessage); } SDL_Rect Renderer::drawText(TTF_Font *font, const std::string &text, int x, int y) { int w, h; TTF_SizeText(font, text.c_str(), &w, &h); SDL_Rect rect; rect.x = x; rect.y = y; rect.w = w; rect.h = h; drawText(font, text, rect); return rect; } SDL_Rect Renderer::drawText(const std::string &text, int x, int y) { return drawText(font, text, x, y); } SDL_Rect Renderer::drawText(TTF_Font *font, const std::string &text, int y) { int w, h; TTF_SizeText(font, text.c_str(), &w, &h); SDL_Rect rect; rect.x = SCREEN_WIDTH / 2 - w / 2; rect.y = y; rect.w = w; rect.h = h; drawText(font, text, rect); return rect; } void Renderer::drawRect(SDL_Rect rect) { SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderDrawRect(renderer, &rect); } void Renderer::drawTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int w, int h) { // Setup the destination rectangle to be at the position we want SDL_Rect dst; dst.x = x + xOffset; dst.y = y; dst.w = w; dst.h = h; SDL_RenderCopy(ren, tex, NULL, &dst); } void Renderer::drawTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y) { int w, h; SDL_QueryTexture(tex, NULL, NULL, &w, &h); drawTexture(tex, ren, x, y, w, h); } void Renderer::drawTexture(SDL_Texture *tex, SDL_Rect rect) { drawTexture(tex, rect, SDL_FLIP_NONE); } void Renderer::drawTexture(SDL_Texture *tex, SDL_Rect rect, SDL_RendererFlip flip) { rect.x += xOffset; SDL_RenderCopyEx(renderer, tex, NULL, &rect, 0, NULL, flip); } void Renderer::drawTexture(SDL_Texture *tex, SDL_Rect rect, SDL_Rect offset, SDL_RendererFlip flip) { rect.x += xOffset; rect.w += offset.w; rect.h += offset.h; rect.x += offset.x; rect.y += offset.y; SDL_RenderCopyEx(renderer, tex, NULL, &rect, 0, NULL, flip); } SDL_Texture *Renderer::loadTexture(const std::string &file) { SDL_Texture *texture = IMG_LoadTexture(renderer, file.c_str()); if (!texture) { spdlog::error("loading textures " + file + " failed"); throw SDLException("loadTexture failed."); } return texture; } void Renderer::setXOffset(int offset) { xOffset = offset; } std::vector<SDL_Rect> Renderer::drawMenu() { SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); std::vector<SDL_Rect> buttons; buttons.push_back(drawText(fontMenu, "continue", 200)); buttons.push_back(drawText(fontMenu, "new game", 275)); buttons.push_back(drawText(fontMenu, "exit", 400)); return buttons; } void Renderer::drawGameOverScreen() { SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); drawText(fontMenu, "game over", 350); }
true
9d5056b3b7865d53d6dbdd8699716f08fbcb5945
C++
lordplatypus/Rhythm_Game_Remake
/Enemy/GlobalEnemyManager.cpp
UTF-8
1,352
2.953125
3
[]
no_license
#include "GlobalEnemyManager.h" GlobalEnemyManager::GlobalEnemyManager() { SetAtkModifier(0); SetMaxHPModifier(0); SetRangeModifier(0); SetHealModifier(true); SetMoneyModifier(0); } GlobalEnemyManager::~GlobalEnemyManager() { Clear(); } void GlobalEnemyManager::SetAtkModifier(const int atkModifier) { atkModifier_ = atkModifier; } int GlobalEnemyManager::GetAtkModifier() const { return atkModifier_; } void GlobalEnemyManager::SetMaxHPModifier(const int maxHPModifier) { maxHPModifier_ = maxHPModifier; } int GlobalEnemyManager::GetMaxHPModifier() const { return maxHPModifier_; } void GlobalEnemyManager::SetRangeModifier(const int rangeModifier) { rangeModifier_ = rangeModifier; } int GlobalEnemyManager::GetRangeModifier() const { return rangeModifier_; } void GlobalEnemyManager::SetHealModifier(const bool healModifier) { healModifier_ = healModifier; } bool GlobalEnemyManager::GetHealModifier() const { return healModifier_; } void GlobalEnemyManager::SetMoneyModifier(const int moneyDropRate) { moneyDropRate_ = moneyDropRate; } int GlobalEnemyManager::GetMoneyModifer() const { return moneyDropRate_ + 2; } void GlobalEnemyManager::Clear() { atkModifier_ = 0; maxHPModifier_ = 0; rangeModifier_ = 0; healModifier_ = true; moneyDropRate_ = 0; }
true
a202a284350ae9247d8f5e0f6df417cc7233d790
C++
MrJookie/AGE
/Plugins/Physics/PhysX/PhysXMaterial.cpp
UTF-8
1,485
2.671875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#include "PhysXMaterial.hpp" #include "PhysXWorld.hpp" namespace AGE { namespace Physics { // Constructors PhysXMaterial::PhysXMaterial(PhysXWorld *world, const std::string &name) : MaterialInterface(name), material(static_cast<PhysXPhysics *>(world->getPhysics())->getPhysics()->createMaterial(GetDefaultStaticFriction(), GetDefaultDynamicFriction(), GetDefaultRestitution())) { assert(material != nullptr && "Impossible to create material"); } // Destructor PhysXMaterial::~PhysXMaterial(void) { if (material != nullptr) { material->release(); material = nullptr; } } // Methods physx::PxMaterial *PhysXMaterial::getMaterial(void) { return material; } const physx::PxMaterial *PhysXMaterial::getMaterial(void) const { return material; } // Inherited Methods void PhysXMaterial::setStaticFriction(float staticFriction) { material->setStaticFriction(staticFriction); } float PhysXMaterial::getStaticFriction(void) const { return material->getStaticFriction(); } void PhysXMaterial::setDynamicFriction(float dynamicFriction) { material->setDynamicFriction(dynamicFriction); } float PhysXMaterial::getDynamicFriction(void) const { return material->getDynamicFriction(); } void PhysXMaterial::setRestitution(float restitution) { material->setRestitution(restitution); } float PhysXMaterial::getRestitution(void) const { return material->getRestitution(); } } }
true
542908e6bb0d034812c7921039794092b5eaf1e3
C++
ngc92/stargame
/src/game/detail/CGameObject.h
UTF-8
3,700
2.828125
3
[]
no_license
#ifndef CGAMEOBJECT_H_INCLUDED #define CGAMEOBJECT_H_INCLUDED #include "../IGameObject.h" #include "property/CPropertyObject.h" #include "../physics/body.h" #include "property/TypedProperty.h" namespace game { /*! \class CGameObject \brief default implementation for IGameObject. \details .... */ class CGameObject : public IGameObject, public property::CPropertyObject, ObjectCounter<CGameObject> { public: CGameObject(uint64_t ID, std::string type, ObjectCategory cateogry, b2Body* body = nullptr, std::string name = "object"); virtual ~CGameObject(); /// called just after the object is constructed and added to the world. void onInit(IGameWorld& world) override; void step(const IGameWorld& world, WorldActionQueue& push_action) override; void onStep(const IGameWorld& world) const override; void onImpact(IGameObject& other, const ImpactInfo& info) override; void dealDamage( const Damage& damage, const b2Vec2& pos, const b2Vec2& dir ) override; /// gets the current position of the game object b2Vec2 position() const final; /// gets the current rotation angle. float angle() const final; /// gets the current velocity. b2Vec2 velocity() const final; /// gets the current angular velocity. float angular_velocity() const final; /// gets an ID for object identification. uint64_t id() const final; /// gets the object type. This is the type that /// was used to get the spawn data for the object. const std::string& type() const final; /// the category of this object. ObjectCategory category() const final; /// collision filter data. This is currently very specialised, so maybe a more general /// interface would be nice. However, we need to ensure that this does not cost performance for objects /// that do not require special collision handling. /// Right now, we can set one specific body with which this object shall not collide. const b2Body* ignoreCollisionTarget() const final; /// sets the body which shall be ignored upon collision checks void setIgnoreCollisionTarget( const b2Body* ignore ) final; /// adds a module to this game object. void addModule( std::shared_ptr<IGameObjectModule> ) final; /// adds a listener that is called every step for this game object. ListenerRef addStepListener( std::function<void(const IGameObjectView&)> lst ) final; /// adds a listener that is called when this object is hit by another game object. ListenerRef addImpactListener( std::function<void(IGameObjectView&, const ImpactInfo&)> lst ) final; /// adds a listener that is called when the object is removed ListenerRef addRemoveListener( std::function<void(const IGameObjectView&)> lst ) final; /// get a pointer to the internal body, if any const Body& body() const final; /// get a pointer to the internal body, if any Body& getBody() final; /// marks this body for deletion. void remove() final; /// return whether the game object is considered to be alive, or marked for deletion. bool isAlive() const final; private: Body mBody; const b2Body* mIgnoreBody = nullptr; // status bool mIsAlive; bool mInitialized = false; // id const uint64_t mID; property::TypedProperty<std::string> mType; property::TypedProperty<int> mCategory; ListenerList<const IGameObjectView&> mStepListeners; ListenerList<const IGameObjectView&> mRemoveListeners; ListenerList<IGameObject&, const ImpactInfo&> mImpactListeners; // modules module_vec& getModules() final { return mModules; }; std::vector<std::shared_ptr<IGameObjectModule>> mModules; }; } #endif // CGAMEOBJECT_H_INCLUDED
true
8c957589dd4640367bd49e3faf88554c12db3a82
C++
SyojiTakahiro/GamePerformance
/吉田学園情報ビジネス専門学校 荘司雄大/2年次作品/02 C++ 16Dayチーム制作/ソースコード/01_プロジェクトファイル/timer.h
SHIFT_JIS
1,606
2.6875
3
[]
no_license
//***************************************************************************** // // ^C}[̏[timer.h] // Auther:Hodaka Niwa // //***************************************************************************** #ifndef _TIMER_H_ #define _TIMER_H_ //***************************************************************************** // CN[ht@C //***************************************************************************** #include "main.h" #include "scene.h" //***************************************************************************** // }N` //***************************************************************************** #define TIMER_NUMBER_MAX (3) // ^C}[̌ //***************************************************************************** // O錾 //***************************************************************************** class CNumber; //***************************************************************************** // ^C}[NX̒` //***************************************************************************** class CTimer : public CScene { public: // NłANZX”\ CTimer(int nPriority = 3, OBJTYPE objType = OBJTYPE_TIMER); ~CTimer(); HRESULT Init(void); void Uninit(void); void Update(void); void Draw(void); static CTimer *Create(void); private: // ̃NXANZX”\ CNumber *m_apNumber[TIMER_NUMBER_MAX]; // |SNX^̃|C^ int m_nTimer; // ^C}[ }; #endif
true
e8d7763c0eb241fca9698f1a330f15f5fcb76164
C++
Daniiil06/CppLab_and_other
/OLD/6.cpp
UTF-8
1,132
2.796875
3
[]
no_license
#include <iostream> #include <cmath> #include <iomanip> #include <string.h> #include <string> #include <cctype> #include <cstring> #include <stdio.h> #include <cctype> #include <cstdio> using namespace std; #pragma warning(disable:4996) int main() { setlocale(LC_ALL, "Russian"); printf("\033c"); cout << "\033]2;6 лаба\007"; int a, b, c, k, d, n, r; // cout << "Длина строки = "; // cin >> n; // char str[n]; cout << "Длина строки = "; cin >> r; cout << endl; char str[r]; fgets(str, sizeof( str ), stdin); cout << "Строка = "; n = strlen(str); a = b = c = k = d = 0; str[ std::strcspn( str, "\n" ) ] = '\0'; // for (int i = 0; i < n; ++i) // { // cin >> str[i]; // } while (a < n) { if (str[a] == '1') { b = a; k = 0; while (str[b] == '1') { k++; b++; } if (k % 2 == 1) d += k; a = b; } a++; } cout << "Ответ: " << d << endl; cout << "\033[34m _________________ \033[0m\n" << endl; printf("\033[32m Всё (= \033[0m\n"); cout << "\033[34m _________________ \033[0m\n" << endl << endl; return 0; }
true
63fcd3422d1a923f1200a3f6b585d6ae10dea54b
C++
stumped2/school
/CS475/Project5/first.cpp
UTF-8
7,904
2.546875
3
[ "Apache-2.0" ]
permissive
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <omp.h> #include "errorcodes.h" #include <CL/cl.h> #include <CL/cl_platform.h> #ifndef GLOBAL #define GLOBAL 8192 #endif #ifndef LOCAL #define LOCAL 32 #endif const int NUM_ELEMENTS = GLOBAL*1024; const int LOCAL_SIZE = LOCAL; const char * CL_FILE_NAME = { "first.cl" }; const float TOL = 0.50f; int main( int argc, char *argv[ ] ) { // see if we can even open the opencl kernel program // (no point going on if we can't): FILE *fp; #ifdef WIN32 errno_t err = fopen_s( &fp, CL_FILE_NAME, "r" ); if( err != 0 ) #else fp = fopen( CL_FILE_NAME, "r" ); if( fp == NULL ) #endif { fprintf( stderr, "Cannot open OpenCL source file '%s'\n", CL_FILE_NAME ); return 1; } // 2. allocate the host memory buffers: size_t numWorkGroups = NUM_ELEMENTS / LOCAL_SIZE; float *hA = new float[ NUM_ELEMENTS ]; float *hB = new float[ NUM_ELEMENTS ]; float *hC = new float[ numWorkGroups ]; size_t abSize = NUM_ELEMENTS * sizeof(float); size_t csize = numWorkGroups * sizeof(float); // fill the host memory buffers: for( int i = 0; i < NUM_ELEMENTS; i++ ) { hA[i] = hB[i] = sqrt( (float)i ); } size_t dataSize = NUM_ELEMENTS * sizeof(float); cl_int status; // returned status from opencl calls // test against CL_SUCCESS // get the platform id: cl_platform_id platform; status = clGetPlatformIDs( 1, &platform, NULL ); if( status != CL_SUCCESS ){ fprintf( stderr, "clGetPlatformIDs failed (2)\n" ); PrintCLError(status); } // get the device id: cl_device_id device; status = clGetDeviceIDs( platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL ); if( status != CL_SUCCESS ){ fprintf( stderr, "clGetDeviceIDs failed (2)\n" ); PrintCLError(status); } // 3. create an opencl context: cl_context context = clCreateContext( NULL, 1, &device, NULL, NULL, &status ); if( status != CL_SUCCESS ){ fprintf( stderr, "clCreateContext failed\n" ); PrintCLError(status); } // 4. create an opencl command queue: cl_command_queue cmdQueue = clCreateCommandQueue( context, device, 0, &status ); if( status != CL_SUCCESS ){ fprintf( stderr, "clCreateCommandQueue failed\n" ); PrintCLError(status); } // 5. allocate the device memory buffers: cl_mem dA = clCreateBuffer( context, CL_MEM_READ_ONLY, abSize, NULL, &status ); if( status != CL_SUCCESS ){ fprintf( stderr, "clCreateBuffer failed (1)\n" ); PrintCLError(status); } cl_mem dB = clCreateBuffer( context, CL_MEM_READ_ONLY, abSize, NULL, &status ); if( status != CL_SUCCESS ){ fprintf( stderr, "clCreateBuffer failed (2)\n" ); PrintCLError(status); } cl_mem dC = clCreateBuffer( context, CL_MEM_WRITE_ONLY, csize, NULL, &status ); if( status != CL_SUCCESS ){ fprintf( stderr, "clCreateBuffer failed (3)\n" ); PrintCLError(status); } // 6. enqueue the 2 commands to write the data from the host buffers to the device buffers: status = clEnqueueWriteBuffer( cmdQueue, dA, CL_FALSE, 0, abSize, hA, 0, NULL, NULL ); if( status != CL_SUCCESS ){ fprintf( stderr, "clEnqueueWriteBuffer failed (1)\n" ); PrintCLError(status); } status = clEnqueueWriteBuffer( cmdQueue, dB, CL_FALSE, 0, abSize, hB, 0, NULL, NULL ); if( status != CL_SUCCESS ){ fprintf( stderr, "clEnqueueWriteBuffer failed (2)\n" ); PrintCLError(status); } // 7. read the kernel code from a file: fseek( fp, 0, SEEK_END ); size_t fileSize = ftell( fp ); fseek( fp, 0, SEEK_SET ); char *clProgramText = new char[ fileSize+1 ]; // leave room for '\0' size_t n = fread( clProgramText, 1, fileSize, fp ); clProgramText[fileSize] = '\0'; fclose( fp ); if( n != fileSize ) fprintf( stderr, "Expected to read %lu bytes read from '%s' -- actually read %lu.\n", fileSize, CL_FILE_NAME, n ); // create the text for the kernel program: char *strings[1]; strings[0] = clProgramText; cl_program program = clCreateProgramWithSource( context, 1, (const char **)strings, NULL, &status ); if( status != CL_SUCCESS ){ fprintf( stderr, "clCreateProgramWithSource failed\n" ); PrintCLError(status); } delete [ ] clProgramText; // 8. compile and link the kernel code: char *options = { "" }; status = clBuildProgram( program, 1, &device, options, NULL, NULL ); if( status != CL_SUCCESS ) { size_t size; clGetProgramBuildInfo( program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &size ); cl_char *log = new cl_char[ size ]; clGetProgramBuildInfo( program, device, CL_PROGRAM_BUILD_LOG, size, log, NULL ); fprintf( stderr, "clBuildProgram failed:\n%s\n", log ); delete [ ] log; } // 9. create the kernel object: cl_kernel kernel = clCreateKernel( program, "ArrayMultReduce", &status ); if( status != CL_SUCCESS ){ fprintf( stderr, "clCreateKernel failed\n" ); PrintCLError(status); } // 10. setup the arguments to the kernel object: status = clSetKernelArg( kernel, 0, sizeof(cl_mem), &dA ); if( status != CL_SUCCESS ){ fprintf( stderr, "clSetKernelArg failed (1) %d\n", status); PrintCLError(status); } status = clSetKernelArg( kernel, 1, sizeof(cl_mem), &dB ); if( status != CL_SUCCESS ){ fprintf( stderr, "clSetKernelArg failed (2) %d\n", status); PrintCLError(status); } status = clSetKernelArg( kernel, 2, sizeof(float), NULL ); if( status != CL_SUCCESS ){ fprintf( stderr, "clSetKernelArg failed (3) %d\n", status); PrintCLError(status); } status = clSetKernelArg( kernel, 3, sizeof(cl_mem), &dC); if( status != CL_SUCCESS ){ fprintf(stderr, "clSetKernelArg failed (4) %d\n", status); PrintCLError(status); } // 11. enqueue the kernel object for execution: size_t globalWorkSize[3] = { NUM_ELEMENTS, 1, 1 }; size_t localWorkSize[3] = { LOCAL_SIZE, 1, 1 }; status = clEnqueueBarrier( cmdQueue ); if( status != CL_SUCCESS ) fprintf( stderr, "clEnqueueBarrier (1) failed: %d\n", status ); double time0 = omp_get_wtime( ); status = clEnqueueNDRangeKernel( cmdQueue, kernel, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL ); if( status != CL_SUCCESS ) fprintf( stderr, "clEnqueueNDRangeKernel failed: %d\n", status ); status = clEnqueueBarrier( cmdQueue ); if( status != CL_SUCCESS ) fprintf( stderr, "clEnqueueBarrier (2) failed: %d\n", status ); double time1 = omp_get_wtime( ); // 12. read the results buffer back from the device to the host: status = clEnqueueReadBuffer( cmdQueue, dC, CL_TRUE, 0, csize, hC, 0, NULL, NULL ); if( status != CL_SUCCESS ) fprintf( stderr, "clEnqueueReadBuffer failed\n" ); // did it work? float sum = 0; for(int i = 0; i < LOCAL_SIZE; i++){ sum += hC[i]; } /*for( int i = 0; i < NUM_ELEMENTS; i++ ) { if( fabs( hC[i] - (float)i ) > TOL ) { fprintf( stderr, "%4d: %12.4f * %12.4f wrongly produced %12.4f (%12.4f)\n", i, hA[i], hB[i], hC[i], (float)i ); } } */ fprintf( stderr, "%8d\t%4d\t%10.3f GigaMultsPerSecond\n", NUM_ELEMENTS, LOCAL_SIZE, (float)NUM_ELEMENTS/(time1-time0)/1000000000. ); // 13. clean everything up: clReleaseKernel( kernel ); clReleaseProgram( program ); clReleaseCommandQueue( cmdQueue ); clReleaseMemObject( dA ); clReleaseMemObject( dB ); clReleaseMemObject( dC ); delete [ ] hA; delete [ ] hB; delete [ ] hC; return 0; } void PrintCLError( cl_int status) { if( status == CL_SUCCESS ) return; const int numErrorCodes = sizeof( ErrorCodes ) / sizeof( struct errorcode ); char * meaning = ""; for( int i = 0; i < numErrorCodes; i++ ) { if( status == ErrorCodes[i].statusCode ) { meaning = ErrorCodes[i].meaning; break; } } fprintf( stderr, "%s\n", meaning ); }
true
d981db58b455d5ce315408a45d05314e84eca667
C++
AR2A/imu-minimu-arduino
/process_imu_data/src/Sensor3DCalibration.cpp
UTF-8
4,728
2.53125
3
[ "BSD-3-Clause" ]
permissive
/** * \author CB * \brief Main file for calibrating the Pololu MinIMU-9. * \file Sensor3DCalibration.cpp * \license BSD-3-License */ /************************************************************************************** * INCLUDES **************************************************************************************/ #include <math.h> #include <sstream> #include <boost/filesystem.hpp> #include "Sensor3DCalibration.h" using namespace arma; /************************************************************************************** * GLOBAL VARIABLES **************************************************************************************/ /************************************************************************************** * PUBLIC FUNCTIONS **************************************************************************************/ Sensor3DCalibration::Sensor3DCalibration(std::string const & path, std::string const & prefix) { m_Filename=path+std::string("/")+prefix+std::string("_"); boost::filesystem::create_directories(path); //Load or init alignement if(!m_AlignementMatrix.load(m_Filename+"alignement.mat",raw_ascii)) { m_AlignementMatrix=mat(3,3,fill::eye); m_AlignementMatrix.save(m_Filename+"alignement.mat",raw_ascii); } //Load or init orthogonalisation if(!m_OrthogonalisationMatrix.load(m_Filename+"orthogonalisation.mat",raw_ascii)) { m_OrthogonalisationMatrix=mat(3,3,fill::eye); m_OrthogonalisationMatrix.save(m_Filename+"orthogonalisation.mat",raw_ascii); } //Load or init sensitivity if(!m_SensitivityMatrix.load(m_Filename+"sensitivity.mat",raw_ascii)) { m_SensitivityMatrix=mat(3,3,fill::eye); m_SensitivityMatrix.save(m_Filename+"sensitivity.mat",raw_ascii); } //Load or init bias if(!m_BiasVector.load(m_Filename+"bias.mat",raw_ascii)) { m_BiasVector=vec(3,fill::zeros); m_BiasVector.save(m_Filename+"bias.mat",raw_ascii); } updateCombinedMatrix(); } //------------------------------------------------------------------------------------// Sensor3DCalibration::~Sensor3DCalibration() { } //------------------------------------------------------------------------------------// vec Sensor3DCalibration::operator()(vec const & input) { return m_CombinedMatrix*(input-m_BiasVector); } //------------------------------------------------------------------------------------// void Sensor3DCalibration::SetBiasValues(arma::vec const & bias) { m_BiasVector=bias; m_BiasVector.save(m_Filename+"bias.mat",raw_ascii); } //------------------------------------------------------------------------------------// void Sensor3DCalibration::SetSensitivityValues(arma::vec const & sensitivity) { m_SensitivityMatrix(0,0)=sensitivity(0); m_SensitivityMatrix(1,1)=sensitivity(1); m_SensitivityMatrix(2,2)=sensitivity(2); m_SensitivityMatrix.save(m_Filename+"sensitivity.mat",raw_ascii); updateCombinedMatrix(); } //------------------------------------------------------------------------------------// void Sensor3DCalibration::SetOrthogonalisationValues(arma::vec const & orthogonalisation) { m_OrthogonalisationMatrix=mat(3,3,fill::eye); m_OrthogonalisationMatrix(1,0)=cos(orthogonalisation(0)); m_OrthogonalisationMatrix(2,0)=cos(orthogonalisation(1)); m_OrthogonalisationMatrix(2,1)=cos(orthogonalisation(2)); m_OrthogonalisationMatrix.save(m_Filename+"orthogonalisation.mat",raw_ascii); updateCombinedMatrix(); } //------------------------------------------------------------------------------------// void Sensor3DCalibration::SetAlignementValues(arma::vec const & alignement) { mat rotRoll(3,3,fill::eye); mat rotPitch(3,3,fill::eye); mat rotYaw(3,3,fill::eye); rotRoll(1,1)=cos(alignement(0)); rotRoll(1,2)=sin(alignement(0)); rotRoll(2,1)=-rotRoll(1,2); rotRoll(2,2)=rotRoll(1,1); rotPitch(0,0)=cos(alignement(1)); rotPitch(2,0)=sin(alignement(1)); rotPitch(0,2)=-rotPitch(2,0); rotPitch(2,2)=rotPitch(0,0); rotYaw(0,0)=cos(alignement(2)); rotYaw(0,1)=sin(alignement(2)); rotYaw(1,0)=-rotYaw(0,1); rotYaw(1,1)=rotYaw(0,0); m_AlignementMatrix=rotRoll*rotPitch*rotYaw; m_AlignementMatrix.save(m_Filename+"alignement.mat",raw_ascii); updateCombinedMatrix(); } /************************************************************************************** * PRIVATE FUNCTIONS **************************************************************************************/ void Sensor3DCalibration::updateCombinedMatrix() { m_CombinedMatrix=m_AlignementMatrix.i()*m_OrthogonalisationMatrix.i()*m_SensitivityMatrix.i(); }
true
2f9c2a2da51259e80ffada90e5e2eb807395fa09
C++
binbin3828/rmserx
/com/common1.h
GB18030
1,107
2.6875
3
[]
no_license
#ifndef _COMMON1_H_ #define _COMMON1_H_ #include <pthread.h> // class CMutexLock { public: CMutexLock() { pthread_mutex_init(&m_MutexLock,NULL); } ~CMutexLock() { pthread_mutex_destroy(&m_MutexLock); } int Lock() { return pthread_mutex_lock(&m_MutexLock); } int Unlock() { return pthread_mutex_unlock(&m_MutexLock); } int Trylock() { return pthread_mutex_trylock(&m_MutexLock); } private: pthread_mutex_t m_MutexLock; }; struct MUTEXLOCK { private: CMutexLock *m_lpLock; public: MUTEXLOCK(CMutexLock *lpLock):m_lpLock(lpLock) { m_lpLock->Lock(); } ~MUTEXLOCK() { m_lpLock->Unlock(); } }; typedef char int8; typedef unsigned char uint8; typedef short int16; typedef unsigned short uint16; typedef int int32; typedef unsigned int uint32; typedef long long int64; typedef unsigned long long uint64; typedef void *funcall (void *lpPa); //funcallǷΪvoidָĺָ //#define ntohll(x) __bswap_64 (x) //#define htonll(x) __bswap_64 (x) #endif
true
743b10de101c0ca1fa5015e7767b567374247c7f
C++
Oleh0293/lab_3.3
/Lab_03_4.cpp
UTF-8
1,149
3.625
4
[]
no_license
// Lab_03_3.cpp // кулик олег // Лабораторна робота № 3.3 // Розгалуження, задане графіком функції. // Варіант 8 #include <iostream> #include <cmath> using namespace std; int main() { double x; //вхідний аргумент double R; //вхідний параметр double y; //результат обчислення cout << "R="; cin >> R; cout << "x="; cin >> x; if (x <= -8) y = -R; else if (x > (-8 - R) && x <=(-8 + R)) y = sqrt((R * R) - (x * x)); else if (x > (-8 + R) && x <= 2) y = -sqrt((R * R) - (x * x)); else if (x > 2 && x <= 6) y = 0; else if(x>6) y = (x - 6) * (x - 6); cout << endl; cout << "y=" << y << endl; // 2 спосіб if (x <= -8) y = -R; if (x > (-8 - R) && x <= (-8 + R)) y = sqrt((R * R) - (x * x)); if (x > (-8 + R) && x <= 2) y = -sqrt((R * R) - (x * x)); if (x > 2 && x <= 6) y = 0; if (x>6) y = (x - 6) * (x - 6); cout << endl; cout << "y=" << y << endl; cin.get(); return 0; }
true
1b9cb8723ed305a1a75b758b98b9737eeb10494b
C++
ytz12345/2019_ICPC_Trainings
/Opentrains_Contest/1038/A.cpp
UTF-8
921
2.796875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct node { int x, y, z; }; vector <node> a[4]; int sqr(int x) {return x * x;} int main() { srand(time(NULL)); for (int x, y, z, t = 0; t < 4; t ++) { x = rand() % 1000, y = rand() % 1000; while (x <= 100 || y <= 100) x = rand() % 1000, y = rand() % 1000; printf("Q %d %d\n", x, y); fflush(stdout); cin >> z; for (int i = 0; i <= 100; i ++) for (int j = 0; j <= 100; j ++) if (sqr(x - i) + sqr(y - j) == z) a[t].push_back((node){i, j, t == 3}); } for (int t = 3; t > 0; t --) { for (int i = 0, s1 = a[t].size(); i < s1; i ++) { if (!a[t][i].z) continue; for (int j = 0, s2 = a[t - 1].size(); j < s2; j ++) if (abs(a[t][i].x - a[t - 1][j].x) + abs(a[t][i].y - a[t - 1][j].y) == 1) a[t - 1][j].z = 1; } } for (auto i : a[0]) if (i.z == 1) { printf("A %d %d\n", i.x, i.y); fflush(stdout); return 0; } }
true
6fdc9aba5074745cd1c3e748382f1914e0e4f5c8
C++
axrdiv/USACO
/Chapter_2/Section_2.4/Fractions_to_Decimals/Fractions_to_Decimals.cpp
UTF-8
1,111
2.65625
3
[]
no_license
/* ID: axrdiv1 PROG: fracdec LANG: C++ */ #include<iostream> #include<fstream> #include<vector> #include<string> #include<cstring> using namespace std; const int maxn = 100000*10+10; ofstream fout("fracdec.out"); ifstream fin("fracdec.in"); int N, D, vis[maxn]; vector<int> dig; char line[maxn]; int divi(int n, int d) { int cnt = 1; while(n > 0) { if(vis[n]) return vis[n]; vis[n] = cnt++; dig.push_back(n/d); // cout << n/d << endl; n = n-(n/d)*d; n = n * 10; } return 0; } int main() { fin >> N >> D; string ans; sprintf(line, "%d.", N/D); ans += line; int cnt = divi((N-(N/D)*D)*10, D); for(int i = 0; i < (int)dig.size(); i++) { if(i == cnt-1) ans += "("; sprintf(line, "%d", dig[i]); ans += line; } if(cnt) ans += ")"; if(!dig.size()) ans += "0"; // print '\n' per 76 character int nchar = 0; for(int i = 0; i < ans.size(); i++) { fout << ans[i]; if(++nchar % 76 == 0) fout << endl; } if(ans.size() % 76 != 0) fout << endl; return 0; }
true
b645d04863e1686540f205c56071a63866e1d7f2
C++
jahid-coder/competitive-programming
/LeetCode/N-Queens II/main.cpp
UTF-8
1,222
3.234375
3
[ "MIT" ]
permissive
class Solution { private: vector<vector<string>> ans; bool isSafe(const vector<string> &board, int row, int col, int n) { for (int i = 0; i < row; ++i) { if (board[i][col] == 'Q') { return false; } } int i = row - 1, j = col - 1; while (i >= 0 && j >= 0) { if (board[i][j] == 'Q') return false; --i; --j; } i = row - 1, j = col + 1; while (i >= 0 && j < n) { if (board[i][j] == 'Q') return false; --i; ++j; } return true; } void solve(vector<string> &board, int row, int n) { if (row == n) { ans.push_back(board); return; } for (int col = 0; col < n; ++col) { if (isSafe(board, row, col, n)) { board[row][col] = 'Q'; solve(board, row + 1, n); board[row][col] = '.'; } } } public: int totalNQueens(int n) { string s(n, '.'); vector<string> board(n, s); solve(board, 0, n); return ans.size(); } };
true
5e291c97c714d9be06dbddcbae2ae494924377a3
C++
susu/goodies
/include/goodies/enforce.hpp
UTF-8
1,085
2.984375
3
[ "MIT" ]
permissive
#ifndef GOODIES_ENFORCE_HPP_INC #define GOODIES_ENFORCE_HPP_INC #include <stdexcept> #include <goodies/MakeString.hpp> namespace goodies { class EnforceFailedError : public std::runtime_error { public: EnforceFailedError(const char* conditionStr, const char* file, int line, const std::string & msg) : std::runtime_error(goodies::MakeString()<< "ENFORCE '"<<conditionStr<<"'" << " failed in file: " << file << ":" << line << ": " << msg) {} }; template<typename E, typename... Arg> inline void enforce(bool condition, Arg&&... arg) { if (!condition) throw E(std::forward<Arg&&>(arg)...); } } #ifndef GOODIES_ENFORCE_FAILURE_EXCEPTION #define GOODIES_ENFORCE_FAILURE_EXCEPTION goodies::EnforceFailedError #endif #define ENFORCE(cond,msg) \ goodies::enforce<GOODIES_ENFORCE_FAILURE_EXCEPTION>((cond), #cond,__FILE__,__LINE__,goodies::MakeString()<<msg) #endif
true
17d037e9d5b264939d755fc35f09ca6b4273d5d6
C++
jackmcguire1/Multi-Threaded-Audio-Streaming-Server-
/client/WebClient/ClientSocket.cpp
UTF-8
1,977
2.796875
3
[]
no_license
#include "Client.h" using namespace std; ClientSocket::ClientSocket(Settings settings) { clientSocket = -1; serverIpAddress = settings.Hostname; port = (unsigned short)strtoul(settings.Port.c_str(), NULL, 0); } ClientSocket::~ClientSocket() { WSACleanup(); closesocket(clientSocket); } int ClientSocket::connectToServer() { WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION, WINSOCK_MINOR_VERSION), &wsaData); serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(port); serverAddress.sin_addr.s_addr = inet_addr(serverIpAddress.c_str()); clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); if (connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR) { return 0; } return 1; } PacketContents ClientSocket::receive(int size) { std::vector<char> recvData(size); int bytesReceived = 0; if (this != NULL) { while ((bytesReceived = recv(clientSocket, recvData.data(), recvData.size(), 0)) != recvData.size()) { if (bytesReceived == -1) { if (WSAGetLastError() == WSAEMSGSIZE) // server has more data to send than the buffer can get in one call { continue; // iterate again to get more data } } else { // if iResult is numeric then it has retrieved what it needed and no more is currently available so if we call recv() again it will block. //printf("Bytes received: %d\n", bytesReceived); break; } } PacketContents data; data.content = recvData; data.byteSize = bytesReceived; return data; } } int ClientSocket::sendData(const char * writeBuffer, int writeLength) { if (clientSocket != SOCKET_ERROR) { int bytesSent = 0; while (bytesSent = send(clientSocket, writeBuffer, writeLength, 0) != writeLength) { } return bytesSent; } return 0; } void ClientSocket::close() { shutdown(clientSocket, SD_SEND); closesocket(clientSocket); }
true
5d17e0c47de43df9486f384f94f5509a03d1186d
C++
brighton36/cpp-slim
/tests/types/Time.cpp
UTF-8
17,544
2.8125
3
[ "MIT" ]
permissive
#include <boost/test/unit_test.hpp> #include "expression/Parser.hpp" #include "expression/Ast.hpp" #include "expression/Lexer.hpp" #include "expression/Scope.hpp" #include "types/Time.hpp" namespace { boost::test_tools::predicate_result time_eq(time_t lhs, time_t rhs) { boost::test_tools::predicate_result result = true; if (lhs < rhs - 1 || lhs > rhs + 1) { result = false; result.message() << "within a 1 second delta has failed" << " [" << lhs << "!=" << rhs << "]"; } return result; } } #define CHECK_TIME_EQUAL(lhs, rhs) BOOST_TEST(time_eq(lhs, rhs)) using namespace slim; using namespace slim::expr; BOOST_AUTO_TEST_SUITE(TestTime) Ptr<Object> eval_o(const std::string &str) { Lexer lexer(str); expr::LocalVarNames vars; Parser parser(vars, lexer); auto expr = parser.full_expression(); auto model = create_view_model(); model->add_constant("Time", create_object<TimeType>()); Scope scope(model); return expr->eval(scope); } std::string eval(const std::string &str) { return eval_o(str)->inspect(); } time_t eval_time(const std::string &str) { return coerce<Time>(eval_o(str))->get_value(); } long long eval_i(const std::string &str) { return (long long)coerce<Number>(eval_o(str))->get_value(); } std::string time_str() { return std::to_string(time(nullptr)); } BOOST_AUTO_TEST_CASE(creation) { CHECK_TIME_EQUAL(time(nullptr), eval_time("Time.now")); CHECK_TIME_EQUAL(time(nullptr), eval_time("Time.new")); CHECK_TIME_EQUAL(100, eval_time("Time.at(100)")); } BOOST_AUTO_TEST_CASE(create_utc) { CHECK_TIME_EQUAL(1484484256, eval_time("Time.utc(2017, 'jan', 15, 12, 44, 16)")); CHECK_TIME_EQUAL(1451606400, eval_time("Time.utc(2016, 'jan', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1454284800, eval_time("Time.utc(2016, 'feb', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1456790400, eval_time("Time.utc(2016, 'mar', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1459468800, eval_time("Time.utc(2016, 'apr', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1462060800, eval_time("Time.utc(2016, 'may', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1464739200, eval_time("Time.utc(2016, 'jun', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1467331200, eval_time("Time.utc(2016, 'jul', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1470009600, eval_time("Time.utc(2016, 'aug', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1472688000, eval_time("Time.utc(2016, 'sep', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1475280000, eval_time("Time.utc(2016, 'oct', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1477958400, eval_time("Time.utc(2016, 'nov', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1480550400, eval_time("Time.utc(2016, 'dec', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1480550400, eval_time("Time.gm(2016, 'dec', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1451606400, eval_time("Time.utc(2016, 1, 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1451606400, eval_time("Time.utc(2016)")); CHECK_TIME_EQUAL(1451606400, eval_time("Time.utc(2016, nil, nil, nil, nil, nil)")); CHECK_TIME_EQUAL(1462060800, eval_time("Time.utc(2016, 5, 1, 0, 0, 0)")); BOOST_CHECK_THROW(eval("Time.utc(2016, 'unknown')"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(1899)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(3001)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(2016, 0)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(2016, 13)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(2016, 'jan', 0)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(2016, 'jan', 32)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(2016, 'jan', 1, -1)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(2016, 'jan', 1, 25)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(2016, 'jan', 1, 1, -1)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(2016, 'jan', 1, 1, 61)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(2016, 'jan', 1, 1, 1, -1)"), ArgumentError); BOOST_CHECK_THROW(eval("Time.utc(2016, 'jan', 1, 1, 1, 62)"), ArgumentError); } BOOST_AUTO_TEST_CASE(create_new_with_offset) { // Year, month, day, hour, minute, second is same as Time.utc CHECK_TIME_EQUAL(1451606400, eval_time("Time.new(2016, 'jan', 1, 0, 0, 0)")); CHECK_TIME_EQUAL(1451606400, eval_time("Time.new(2016, 'jan', 1, 0, 0, 0, '+00:00')")); CHECK_TIME_EQUAL(1451606400, eval_time("Time.new(2016, 'jan', 1, 0, 0, 0, '-00:00')")); CHECK_TIME_EQUAL(1451606400 - 60*60*4, eval_time("Time.new(2016, 'jan', 1, 0, 0, 0, '+04:00')")); CHECK_TIME_EQUAL(1451606400 + 60*60*4, eval_time("Time.new(2016, 'jan', 1, 0, 0, 0, '-04:00')")); BOOST_CHECK_THROW(eval("Time.new(2016, 'jan', 1, 0, 0, 0, '04:00')"), ArgumentError); BOOST_CHECK_THROW(eval("Time.new(2016, 'jan', 1, 0, 0, 0, '')"), ArgumentError); BOOST_CHECK_THROW(eval("Time.new(2016, 'jan', 1, 0, 0, 0, '+XX:00')"), ArgumentError); BOOST_CHECK_THROW(eval("Time.new(2016, 'jan', 1, 0, 0, 0, '+00-00')"), ArgumentError); BOOST_CHECK_THROW(eval("Time.new(2016, 'jan', 1, 0, 0, 0, '+00')"), ArgumentError); } BOOST_AUTO_TEST_CASE(cmp) { BOOST_CHECK_EQUAL("true", eval("Time.at(1000) == Time.at(1000)")); BOOST_CHECK_EQUAL("false", eval("Time.at(1000) == Time.at(1200)")); BOOST_CHECK_EQUAL("0", eval("Time.at(1000) <=> Time.at(1000)")); BOOST_CHECK_EQUAL("-1", eval("Time.at(900) <=> Time.at(1000)")); BOOST_CHECK_EQUAL("1", eval("Time.at(1000) <=> Time.at(900)")); } BOOST_AUTO_TEST_CASE(arithmetic) { BOOST_CHECK_EQUAL(1500, eval_time("Time.at(1000) + 500")); BOOST_CHECK_EQUAL(500, eval_time("Time.at(1000) - 500")); BOOST_CHECK_EQUAL("500", eval("Time.at(1000) - Time.at(500)")); BOOST_CHECK_EQUAL("-500", eval("Time.at(500) - Time.at(1000)")); } BOOST_AUTO_TEST_CASE(no_timezones) { BOOST_CHECK_EQUAL("false", eval("Time.now.dst?")); BOOST_CHECK_EQUAL("false", eval("Time.now.isdst")); BOOST_CHECK_EQUAL("true", eval("Time.now.gmt?")); BOOST_CHECK_EQUAL("true", eval("Time.now.utc?")); BOOST_CHECK_EQUAL("0", eval("Time.now.gmt_offset")); BOOST_CHECK_EQUAL("0", eval("Time.now.utc_offset")); BOOST_CHECK_EQUAL("0", eval("Time.now.gmtoff")); BOOST_CHECK_EQUAL("\"UTC\"", eval("Time.now.zone")); } BOOST_AUTO_TEST_CASE(accessors) { BOOST_CHECK_EQUAL("2017", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).year")); BOOST_CHECK_EQUAL("1", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).mon")); BOOST_CHECK_EQUAL("1", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).month")); BOOST_CHECK_EQUAL("15", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).day")); BOOST_CHECK_EQUAL("15", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).mday")); BOOST_CHECK_EQUAL("15", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).yday")); BOOST_CHECK_EQUAL("0", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).wday")); BOOST_CHECK_EQUAL("12", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).hour")); BOOST_CHECK_EQUAL("44", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).min")); BOOST_CHECK_EQUAL("16", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).sec")); BOOST_CHECK_EQUAL("16", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).tv_sec")); BOOST_CHECK_EQUAL("0", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).nsec")); BOOST_CHECK_EQUAL("0", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).tv_nsec")); BOOST_CHECK_EQUAL("0", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).usec")); BOOST_CHECK_EQUAL("0", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).tv_usec")); BOOST_CHECK_EQUAL("0", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).subsec")); BOOST_CHECK_EQUAL("true", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).sunday?")); BOOST_CHECK_EQUAL("false", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).monday?")); BOOST_CHECK_EQUAL("true", eval("Time.utc(2017, 'jan', 16, 12, 44, 16).monday?")); BOOST_CHECK_EQUAL("true", eval("Time.utc(2017, 'jan', 17, 12, 44, 16).tuesday?")); BOOST_CHECK_EQUAL("true", eval("Time.utc(2017, 'jan', 18, 12, 44, 16).wednesday?")); BOOST_CHECK_EQUAL("true", eval("Time.utc(2017, 'jan', 19, 12, 44, 16).thursday?")); BOOST_CHECK_EQUAL("true", eval("Time.utc(2017, 'jan', 20, 12, 44, 16).friday?")); BOOST_CHECK_EQUAL("true", eval("Time.utc(2017, 'jan', 21, 12, 44, 16).saturday?")); BOOST_CHECK_EQUAL("[16, 44, 12, 15, 1, 2017, 0, 15, false, \"UTC\"]", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).to_a")); } BOOST_AUTO_TEST_CASE(format) { BOOST_CHECK_EQUAL( "\"Sun Jan 15 12:44:16 2017\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).asctime")); BOOST_CHECK_EQUAL( "\"Sun Jan 15 12:44:16 2017\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).ctime")); BOOST_CHECK_EQUAL( "2017-01-15 12:44:16 +0000", eval("Time.utc(2017, 'jan', 15, 12, 44, 16)")); // Year BOOST_CHECK_EQUAL("\"2017\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%Y'")); BOOST_CHECK_EQUAL("\"20\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%C'")); BOOST_CHECK_EQUAL("\"17\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%y'")); // Month BOOST_CHECK_EQUAL("\"01\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%m'")); BOOST_CHECK_EQUAL("\"12\"", eval("Time.utc(2017, 'dec', 15, 12, 44, 16).strftime '%m'")); BOOST_CHECK_EQUAL("\"January\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%B'")); BOOST_CHECK_EQUAL("\"Jan\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%b'")); BOOST_CHECK_EQUAL("\"Jan\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%h'")); // Day BOOST_CHECK_EQUAL("\"01\"", eval("Time.utc(2017, 'jan', 1, 12, 44, 16).strftime '%d'")); BOOST_CHECK_EQUAL("\"15\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%d'")); BOOST_CHECK_EQUAL("\" 1\"", eval("Time.utc(2017, 'jan', 1, 12, 44, 16).strftime '%e'")); BOOST_CHECK_EQUAL("\"015\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%j'")); BOOST_CHECK_EQUAL("\"365\"", eval("Time.utc(2017, 'dec', 31, 12, 44, 16).strftime '%j'")); BOOST_CHECK_EQUAL("\"Sunday\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%A'")); BOOST_CHECK_EQUAL("\"Sun\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%a'")); BOOST_CHECK_EQUAL("\"7\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%u'")); BOOST_CHECK_EQUAL("\"0\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%w'")); // Hour BOOST_CHECK_EQUAL("\"12\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%H'")); BOOST_CHECK_EQUAL("\"05\"", eval("Time.utc(2017, 'jan', 15, 5, 44, 16).strftime '%H'")); BOOST_CHECK_EQUAL("\"12\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%k'")); BOOST_CHECK_EQUAL("\" 5\"", eval("Time.utc(2017, 'jan', 15, 5, 44, 16).strftime '%k'")); BOOST_CHECK_EQUAL("\"12\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%I'")); BOOST_CHECK_EQUAL("\"12\"", eval("Time.utc(2017, 'jan', 15, 24, 44, 16).strftime '%I'")); BOOST_CHECK_EQUAL("\"03\"", eval("Time.utc(2017, 'jan', 15, 15, 44, 16).strftime '%I'")); BOOST_CHECK_EQUAL("\"12\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%l'")); BOOST_CHECK_EQUAL("\"12\"", eval("Time.utc(2017, 'jan', 15, 0, 44, 16).strftime '%l'")); BOOST_CHECK_EQUAL("\" 3\"", eval("Time.utc(2017, 'jan', 15, 15, 44, 16).strftime '%l'")); BOOST_CHECK_EQUAL("\"pm\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%P'")); BOOST_CHECK_EQUAL("\"am\"", eval("Time.utc(2017, 'jan', 15, 0, 44, 16).strftime '%P'")); BOOST_CHECK_EQUAL("\"PM\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%p'")); BOOST_CHECK_EQUAL("\"AM\"", eval("Time.utc(2017, 'jan', 15, 0, 44, 16).strftime '%p'")); // Minute BOOST_CHECK_EQUAL("\"44\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%M'")); BOOST_CHECK_EQUAL("\"05\"", eval("Time.utc(2017, 'jan', 15, 12, 5, 16).strftime '%M'")); // Second BOOST_CHECK_EQUAL("\"16\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%S'")); BOOST_CHECK_EQUAL("\"04\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 4).strftime '%S'")); // Millisecond BOOST_CHECK_EQUAL("\"000\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%L'")); // Fractional seconds BOOST_CHECK_EQUAL("\"000000000\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%N'")); // Time zone BOOST_CHECK_EQUAL("\"+0000\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%z'")); BOOST_CHECK_EQUAL("\"+00:00\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%:z'")); BOOST_CHECK_EQUAL("\"UTC\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%Z'")); // Literal BOOST_CHECK_EQUAL("\"%\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%'")); BOOST_CHECK_EQUAL("\"%\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%%'")); BOOST_CHECK_EQUAL("\"%Q\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%Q'")); BOOST_CHECK_EQUAL("\"\\t\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%t'")); BOOST_CHECK_EQUAL("\"\\n\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%n'")); // Flags BOOST_CHECK_EQUAL("\"6\"", eval("Time.utc(2017, 'jan', 15, 6, 44, 16).strftime '%-H'")); BOOST_CHECK_EQUAL("\" 6\"", eval("Time.utc(2017, 'jan', 15, 6, 44, 16).strftime '%_H'")); BOOST_CHECK_EQUAL("\"06\"", eval("Time.utc(2017, 'jan', 15, 6, 44, 16).strftime '%0H'")); BOOST_CHECK_EQUAL("\"006\"", eval("Time.utc(2017, 'jan', 15, 6, 44, 16).strftime '%3H'")); BOOST_CHECK_EQUAL("\" 6\"", eval("Time.utc(2017, 'jan', 15, 6, 44, 16).strftime '%_3H'")); BOOST_CHECK_EQUAL("\"06\"", eval("Time.utc(2017, 'jan', 15, 6, 44, 16).strftime '%_0H'")); BOOST_CHECK_EQUAL("\"000\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%3N'")); BOOST_CHECK_EQUAL("\"SUNDAY\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%^A'")); BOOST_CHECK_EQUAL("\" SUNDAY\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%^8A'")); BOOST_CHECK_EQUAL("\"00SUNDAY\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%0^8A'")); BOOST_CHECK_EQUAL("\" Sunday\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%-8A'")); BOOST_CHECK_EQUAL("\"06\"", eval("Time.utc(2017, 'jan', 15, 6, 44, 16).strftime '%EH'")); BOOST_CHECK_EQUAL("\"06\"", eval("Time.utc(2017, 'jan', 15, 6, 44, 16).strftime '%OH'")); // Specials BOOST_CHECK_EQUAL("\"Sun Jan 15 12:44:16 2017\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%c'")); BOOST_CHECK_EQUAL("\" Sun Jan 15 12:44:16 2017\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%30c'")); BOOST_CHECK_EQUAL("\"01/15/17\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%D'")); BOOST_CHECK_EQUAL("\"01/15/17\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%x'")); BOOST_CHECK_EQUAL("\" 01/15/17\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%10D'")); BOOST_CHECK_EQUAL("\"2017-01-15\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%F'")); BOOST_CHECK_EQUAL("\" 2017-01-15\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%14F'")); BOOST_CHECK_EQUAL("\"15-JAN-2017\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%v'")); BOOST_CHECK_EQUAL("\" 15-JAN-2017\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%14v'")); BOOST_CHECK_EQUAL("\"12:44:16 PM\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%r'")); BOOST_CHECK_EQUAL("\"03:44:16 PM\"", eval("Time.utc(2017, 'jan', 15, 15, 44, 16).strftime '%r'")); BOOST_CHECK_EQUAL("\" 12:44:16 PM\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%14r'")); BOOST_CHECK_EQUAL("\"12:44\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%R'")); BOOST_CHECK_EQUAL("\" 12:44\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%14R'")); BOOST_CHECK_EQUAL("\"12:44:16\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%T'")); BOOST_CHECK_EQUAL("\"12:44:16\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%X'")); BOOST_CHECK_EQUAL("\" 12:44:16\"", eval("Time.utc(2017, 'jan', 15, 12, 44, 16).strftime '%14T'")); } BOOST_AUTO_TEST_CASE(number_ext) { BOOST_CHECK_EQUAL( 1, eval_i("1.second")); BOOST_CHECK_EQUAL( 2, eval_i("2.seconds")); BOOST_CHECK_EQUAL( 60, eval_i("1.minute")); BOOST_CHECK_EQUAL( 120, eval_i("2.minutes")); BOOST_CHECK_EQUAL( 3600, eval_i("1.hour")); BOOST_CHECK_EQUAL( 7200, eval_i("2.hours")); BOOST_CHECK_EQUAL( 86400, eval_i("1.day")); BOOST_CHECK_EQUAL( 172800, eval_i("2.days")); BOOST_CHECK_EQUAL( 604800, eval_i("1.week")); BOOST_CHECK_EQUAL(1209600, eval_i("2.weeks")); BOOST_CHECK_EQUAL(1209600, eval_i("1.fortnight")); BOOST_CHECK_EQUAL(2419200, eval_i("2.fortnights")); CHECK_TIME_EQUAL(time(nullptr), eval_time("0.ago")); CHECK_TIME_EQUAL(time(nullptr) - 120, eval_time("120.ago")); CHECK_TIME_EQUAL(time(nullptr) - 120, eval_time("120.until")); CHECK_TIME_EQUAL(400, eval_time("100.until Time.at(500)")); CHECK_TIME_EQUAL(time(nullptr), eval_time("0.from_now")); CHECK_TIME_EQUAL(time(nullptr) + 120, eval_time("120.from_now")); CHECK_TIME_EQUAL(time(nullptr) + 120, eval_time("120.since")); CHECK_TIME_EQUAL(120, eval_time("120.since Time.at(0)")); } BOOST_AUTO_TEST_SUITE_END()
true
45444944e6a64089bcffd589b3fe68d9b7d4d6ff
C++
EmmaSteinman/hash
/testclass.cpp
UTF-8
3,992
3.5625
4
[]
no_license
#include <iostream> #include <sstream> #include <cassert> using namespace std; #include <math.h> #include <string> #include "HashTable.h" /* * test class * this is a class to test our hash table */ class test { public: int key; test(void){key = 0;}; //default constructor test(int k){key = k;}; //specified int constructor ~test(void){}; //destructor string toString(void) //toString { return to_string(key); }; int hash ( int slots ) const //lame hash table { int hval = (key*3)%slots; return hval; } bool operator< ( test& a) const //overloaded operators { return this->key < a.key; }; bool operator> (const test& a) //overloading comparison operators { //to compare key specifically return this->key > a.key; }; bool operator== (const test& a) { return this->key == a.key; }; bool operator!= (const test& a) { return this->key != a.key; }; friend ostream& operator<<(ostream& os, const test& m) //cout { os << m.key; return os; } }; //testing default constructor void testDefaultConstructor() { HashTable<test> t1; assert(t1.Empty()==1); } //test specified slots constructor void testConstructor() { HashTable<test> t1(10); assert(t1.Empty()==0); //not empty because it has 10 slots } //testing the copy constructor void testCopyConstructor() { HashTable<test> t1(10); HashTable<test> t2(t1); assert(t2.Empty()==0); //same as previous test } //testing insert method void testInsert1() { HashTable<test> t1(100); test *t = new test; t->key = 5; t1.insert(t); assert((t1.toString(t->hash(100))=="5 ")); } //testing many inserts void testInsert2() { HashTable<test> t1=HashTable<test>(10); test *a = new test; a->key = 5; test *b = new test; b->key = 20; test *c = new test; c->key = 9; test *d = new test; d->key = 2; test *e = new test; e->key = 8; test *f = new test; f->key = 10; test *g = new test; g->key = 22; t1.insert(a); t1.insert(b); t1.insert(c); t1.insert(d); t1.insert(e); t1.insert(f); t1.insert(g); assert((t1.toString(d->hash(10))=="22 2 ")); } //testing get void testGet() { HashTable<test> t1(100); test *t = new test; t->key = 5; t1.insert(t); //cout << t->key << endl; test *s = t1.get(t->key); assert(s->key==5); } //testing get on something that is not in the HT void testGetNotThere() { HashTable<test> t1=HashTable<test>(10); test *a = new test; a->key = 5; test *b = new test; b->key = 20; test *c = new test; c->key = 9; test *d = new test; d->key = 2; test *e = new test; e->key = 8; t1.insert(a); t1.insert(b); test *f = new test; f->key = 10; test *g = new test; g->key = 22; t1.insert(a); t1.insert(b); t1.insert(c); t1.insert(d); t1.insert(e); t1.insert(f); //t1.insert(g); test* x = t1.get(g->key); assert(x == 0); } //testing assignment operator void testAsst() { HashTable<test> t1 = HashTable<test>(10); test *a = new test; a->key = 5; test *b = new test; b->key = 20; t1.insert(a); t1.insert(b); HashTable<test> t2 = t1; test* t1a = t1.get(a->key); test* t2a = t2.get(a->key); assert(t1a->key == t2a->key); } //testing removal of something that is not there void isItThere() { HashTable<test> t1 = HashTable<test>(10); test *a = new test; a->key = 5; test *b = new test; b->key = 20; t1.insert(a); t1.remove(b->key); } //testing regular removal void testRemove() { HashTable<test> t1 = HashTable<test>(10); test *a = new test; a->key = 5; test *b = new test; b->key = 20; t1.insert(a); t1.insert(b); t1.remove(b->key); test* x = t1.get(b->key); assert(x == 0); } int main ( void ) { testConstructor(); testCopyConstructor(); testInsert1(); testInsert2(); testGet(); testGetNotThere(); testAsst(); isItThere(); testRemove(); return 0; }
true
67247694d68710515c1702cb21e769fec6aa549f
C++
anujrawatcode/7_Sem_Placement_Classes
/G3/4_Week_19July21/4_23July21/Reshape the Matrix.cc
UTF-8
1,726
3.015625
3
[]
no_license
// #include<bits/stdc++.h> using namespace std; // Brute force method vector<vector<int>>reshapeBF(vector<vector<int>>& a, int r, int c) { int m=a.size(); int n=a[0].size(); if(m*n != r*c) return a; else { int k=0; vector<vector<int>> ans; vector<int> temp; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { temp.push_back(a[i][j]); } } for(int i=0;i<r;i++) { vector<int> t; for(int j=0;j<c;j++) { t.push_back(a[i][j]); } ans.push_back(t); } } return ans; } // Optimized One vector<vector<int>> rehapeOPT(vector<vector<int>>& a, int r, int c) { int m=a.size(); int n=a[0].size(); if(m*n != r*c) return a; else { int k=0; vector<vector<int>> ans; vector<int> temp; for(int i=0;i<m*n;i++) { ans[i/r][i%c] = a[i/n][i%n]; } for(int i=0;i<r;i++) { vector<int> t; for(int j=0;j<c;j++) { t.push_back(a[i][j]); } ans.push_back(t); } } return ans; } int main() { int m,n;cin>>m>>n; vector<vector<int>> a; for(int i=0;i<m;i++) { vector<int> temp; int t; for(int j=0;j<n;j++) { cin>>t; temp.push_back(t); } a.push_back(temp); } int r,c;cin>>r>>c; vector<vector<int>> ans = reshapeBF(a,r,c); //optimized one vector<vector<int>> ans = reshapeOPT(a,r,c); return 0; }
true
2bf1501f9048d23b01dd210bc48aa8aff05780a8
C++
imjkdutta/Important_Training
/Training/c++/Assignment/Third_Assignment/Third_Assignment/source/template_smallest.cpp
UTF-8
1,535
4.21875
4
[]
no_license
#include<iostream> using namespace std; template <typename Type> Type find_min(Type* ptr,int num) /*template function definition*/ { for( int i = 0; i < num; i++) { for(int j = 0 ; j < num - 1; j++) { if(ptr[i] < ptr[j]) { Type temp = ptr[i]; /*toSwapping*/ ptr[i] = ptr[j]; ptr[j] = temp; } } } return ptr[0]; } #define MAX 10 int main() { int integer_arr[MAX]; /*Integer Array*/ char ch_arr[MAX]; /*character Array*/ double d_arr[MAX]; /*Double Array*/ cout <<"Enter the elements :"<<endl; /* User Input*/ for(int i = 0 ; i < MAX ; i++){ cin >>integer_arr[i]; } cout <<"Enter the chararcters :"<<endl;/* User Input*/ for(int i = 0 ; i < MAX ; i++){ cin >>ch_arr[i]; } cout <<"Enter the Double elements :"<<endl;/* User Input*/ for(int i = 0 ; i < MAX ; i++){ cin >>d_arr[i]; } cout<<"Integer Elements are:"<<endl; /*To display*/ for(int i = 0 ; i < MAX ; i++){ cout << integer_arr[i] <<" "; } cout <<endl; cout<<"Character Elements are:"<<endl;/*To display*/ for(int i = 0 ; i < MAX ; i++){ cout << ch_arr[i] <<" "; } cout <<endl; cout<<"Double Elements are:"<<endl;/*To display*/ for(int i = 0 ; i < MAX ; i++){ cout << d_arr[i] <<" "; } cout <<endl; cout << "Smallest Element in Integer array: "<< find_min(integer_arr,MAX) <<endl; /*template function call to find min*/ cout << "Smallest Element in character array: "<< find_min(ch_arr,MAX) <<endl; cout << "Smallest Element in Double array: "<< find_min(d_arr,MAX) <<endl; return 0 ; }
true
42c8227d3b31284d05d448daa794a83fc38998b0
C++
Zhangeaky/DataStructure
/BinaryTree/inorder/inorderStack.cc
UTF-8
874
2.765625
3
[]
no_license
#include<iostream> #include<stack> #include<vector> #include"Treenode.hpp" using namespace std; vector<int> container; void inorder(Treenode* root){ stack<Treenode*> ss; //ss.push(root); while( !ss.empty() || root != nullptr ){ if( root == nullptr ){ container.push_back(ss.top()->value); root = ss.top(); }else{ ss.push(root); root = root->left; continue; } if( root->right ==nullptr ){ ss.pop(); }else { container.push_back(root->right->value); } } } void inorder(Treenode& node){ } int main(){ cout<<(nullptr == 0)<<endl; Treenode n1(1); Treenode n2(2); Treenode n3(3); Treenode n4(4); Treenode n5(5); Treenode n6(6); Treenode n7(7); }
true
1cf5c5508751c9aee5c258fe4f814eca80d64934
C++
minusminus/codechef
/median/main.cpp
UTF-8
7,816
3.03125
3
[]
no_license
/* MEDIAN https://www.codechef.com/problems/MEDIAN pomysl (PD): - tabela enkodowana do liczby binarnej, gdzie 1 - max, 0 - pozostale wartosci - w kazdym kroku analizujemy wszystkie mozliwe kombincje rozszerzania 1, dla kazdej kombinacji generujemy maksymalna tablice 1 jaka mozna z niej utowrzyc: kazda maska podzielona na bloki 1 i 0 kazdy blok rozszerzany w obie strony (obejmujemy tym wszystkie przypadki) jezeli osiagniemy same 1 w tablicy to mamy rozwiazanie w biezacym kroku - dodatkowo tablica asocjacyjna (map) kombinacji juz sprawdzonych - tych nie analizujemy ponownie (nie dodajemy ich do listy dla nastepnego kroku) - z kazdego kroku wynikowo wychodzi tablica z maskami o maksymalnej liczbie 1 (n masek o liczbie 1 np 20) */ #include <iostream> #include <vector> #include <map> using namespace std; struct status{ public: status() : bits(0), ones(0) {}; status(unsigned int i1, int i2) : bits(i1), ones(i2) {}; unsigned int bits; //encoded table int ones; //count of ones }; int t; int n; vector<int> tbl; vector<status> states, states2; map<unsigned int, bool> checkedstates; void encodetable(status& r){ int vmax = -1; //find max for(int i=0; i<n; i++) if( tbl[i] > vmax) vmax=tbl[i]; //encode r.bits = 0; r.ones = 0; unsigned int mask = 1; for( int i=0; i<n; i++ ){ if(tbl[i] == vmax){ r.bits |= mask; r.ones++; } mask = mask << 1; } } void bitstoblocks(vector< pair<int, int> >& blocks, unsigned int bits){ blocks.resize(0); unsigned int mask = 1; for(int i=0; i<n; i++){ int val = 0; if( (bits & mask) != 0) val = 1; if( (blocks.size()==0) || (blocks[blocks.size()-1].first != val) ){ blocks.push_back( make_pair(val, 1) ); } else { blocks[blocks.size()-1].second++; } mask = mask << 1; } } unsigned int blockstobits(vector< pair<int, int> >& blocks, int& totalonescnt){ unsigned int res = 0; unsigned int mask = 1; totalonescnt = 0; for(int k=0; k<blocks.size(); k++){ if( blocks[k].first == 0 ) //0 - shift mask mask = mask << blocks[k].second; else{ //1 - set bits in result for(int i=0; i<blocks[k].second; i++){ res |= mask; mask = mask << 1; } totalonescnt += blocks[k].second; } } return res; } void coverblocksingle(vector< pair<int, int> >& blocks, int iones, int icovered, int& onesleft){ if( blocks[icovered].second > onesleft ){ blocks[icovered].second -= onesleft; blocks[iones].second += onesleft; onesleft = 0; } else { blocks[iones].second += blocks[icovered].second; onesleft -= blocks[icovered].second; blocks[icovered].second = 0; } } void coverblockwithnext(vector< pair<int, int> >& blocks, int iones, int icovered, int icoverednext, int& onesleft){ onesleft = (onesleft + blocks[icoverednext].second) - blocks[icovered].second; blocks[iones].second += blocks[icovered].second + blocks[icoverednext].second; blocks[icovered].second = 0; blocks[icoverednext].second = 0; } int scanfornonempty0(vector< pair<int, int> >& blocks, int ifrom, int dir){ int i = ifrom;// + dir; while( (i>=0) && (i<blocks.size()) ){ if( (blocks[i].first == 0) && (blocks[i].second > 0) ) return i; else i += dir; } return -1; } void printblock(vector< pair<int, int> >& blocks){ for(int i=0; i<blocks.size(); i++){ cout << "(" << blocks[i].first << "," << blocks[i].second << "),"; } cout << endl; } unsigned int enlargeblock(vector< pair<int, int> >& blocks, int index, int& curronescovered){ //boundary cases // if( index - 1 < 0 ) return 0; //left bound // if( index + 1 >= blocks.size() ) return 0; //right bound // cout << index << ":" << endl; // printblock(blocks); vector< pair<int, int> > work; work = blocks; int onesleft = work[index].second; int ileft, iright; ileft = iright = index; while( (onesleft>0) && (work[index].second<n) ) { //check left block only, left + next with ones, the same for right block //choose one option that gives highest coverage, or leaves smallest gap int bestcover = -1; int covercnt = 0; ileft = scanfornonempty0(work, ileft, -1); iright = scanfornonempty0(work, iright, 1); if( (ileft == -1) && (iright == -1 )) break; //no zeroes left if( (iright > -1) && (iright + 1 < work.size()) ) if(work[iright + 1].second + onesleft >= work[iright].second) {bestcover = 3; covercnt = work[iright + 1].second + work[iright].second;} if( (ileft > -1) && (ileft - 1 >=0) ) if( (work[ileft - 1].second + onesleft >= work[ileft].second) && (work[ileft].second + work[ileft - 1].second > covercnt) ) {bestcover = 1; covercnt = work[ileft].second + work[ileft - 1].second;} if(bestcover == -1){ if(iright == -1) bestcover = 0; else if(ileft == -1) bestcover = 2; else if(work[iright].second > work[ileft].second) bestcover = 2; else bestcover = 0; // covercnt = onesleft; } switch( bestcover ){ case 0 : //left only coverblocksingle(work, index, ileft, onesleft); break; case 1 : //left + next coverblockwithnext(work, index, ileft, ileft - 1, onesleft); break; case 2 : //right only coverblocksingle(work, index, iright, onesleft); break; case 3 : //right + next coverblockwithnext(work, index, iright, iright + 1, onesleft); break; } // printblock(work); } return blockstobits(work, curronescovered); } void analyzeblocks(vector< pair<int, int> >& blocks, vector<status>& snext, int& maxones){ for(int i=0; i<blocks.size(); i++){ if( blocks[i].first == 0 ) continue; //analysis only for block of 1 unsigned int newbits; int onescovered; newbits = enlargeblock(blocks, i, onescovered); if( onescovered >= maxones ){ //only greater or equal to current max if(checkedstates.find(newbits) == checkedstates.end()){ //not analyzed yet snext.push_back( status(newbits, onescovered) ); checkedstates[newbits] = true; } maxones = onescovered; } if( maxones == n ) return; } } int processtoend(int initialmaxones){ if( initialmaxones == n ) return 0; int currmaxones = initialmaxones; int maxones; int steps=1; vector<status>& scurr = states; vector<status>& snext = states2; vector< pair<int, int> > blocks; //blocks: first - 0 or 1, second - count of elements for(int x=0; x<5; x++){ //no more than 5 steps for 30 bits number // cout << "step: " << steps << endl; maxones = currmaxones; checkedstates.clear(); for(int i=0; i<scurr.size(); i++){ if(scurr[i].ones != currmaxones) continue; //only max //bits to blocks bitstoblocks(blocks, scurr[i].bits); //analyze blocks analyzeblocks(blocks, snext, maxones); if( maxones == n ) return steps; //if found setup with all 1 return steps } //swap status tables vector<status>& t = scurr; scurr = snext; snext = t; snext.resize(0); snext.reserve(n*n); currmaxones = maxones; steps++; } return -1; //some error occurred in analysis } int resolve(){ states.reserve(n*n); states2.reserve(n*n); //initial state status r; encodetable(r); states.push_back(r); // checkedstates[r.bits] = true; //process int res = processtoend(r.ones); return res; } int main() { // //speedup cin // ios::sync_with_stdio(false); // cin.tie(0); cin >> t; while(t>0){ cin >> n; tbl.resize(n); // states.resize(n*n); for(int i=0; i<n; i++) cin >> tbl[i]; int res; res = resolve(); cout << res << endl; checkedstates.clear(); states.resize(0); states2.resize(0); tbl.resize(0); t--; } return 0; }
true
aed9475b73306b8101b0b1f18bc408e97c7efe63
C++
AleksievAleksandar/Cpp-Advanced
/Exam (12 September 2020)/02. Scientists/Scientist.h
UTF-8
487
3.015625
3
[]
no_license
#pragma once enum Fields { Chemistry, Physics, Linguistics, Philosophy }; class Scientist { private: char* name; int discoveriesCount; public: Scientist(); Scientist(char* name, int discoveriesCount); Scientist(const Scientist& other); Scientist& operator=(const Scientist& other); ~Scientist(); char* getName() const; int getDiscoveriesCount() const; void setName(const char* name); void setDiscoveriesCount(int count); void Print() const; };
true
ab4199890d5113bd2503f115ba9bbaa2c23625eb
C++
ConnectionMaster/AL-Engine
/AL-Engine/Renderer.cpp
UTF-8
762
2.6875
3
[]
no_license
#include "Core.h" #include "Renderer.h" namespace AL { void Renderer::Render() { Sort(); RenderTargets(); } void Renderer::Sort() { _renderTargets.sort([=](Node* node1, Node* node2) {return node1->GetLocalDepth() < node2->GetLocalDepth(); }); _renderTargets.sort([=](Node* node1, Node* node2) {return node1->GetGlobalDepth() < node2->GetGlobalDepth(); }); } void Renderer::RenderTargets() { for (Node* node : _renderTargets) { node->Draw(); } } void Renderer::AddRenderTarget(Node * node) { if (std::find(_renderTargets.begin(), _renderTargets.end(), node) != _renderTargets.end()) return; _renderTargets.push_back(node); Sort(); } void Renderer::RemoveRenderTarget(Node * node) { _renderTargets.remove(node); } }
true
68fb48a9f03182c0601fc554da3bc1ef4d6efd31
C++
animeshkarmakarAK/Computer-Programming
/Algorithm course/jbs.cpp
UTF-8
1,404
3.125
3
[]
no_license
#include<iostream> #include<algorithm> #include<cstdio> using namespace std; struct job{ char id; int dead; int profit; }; bool comparison(job a,job b) { return (a.profit>b.profit); } void printfJobSe(job arr[],int n) { sort(arr,arr+n,comparison); for(int i=1;i<=n;++i){ cout<<arr[i].id<<" "<<arr[i].dead<<" "<<arr[i].profit<<endl; } int result[n]; int slot[n]; for(int i=0;i<n;i++){ slot[i]=false; } for(int i=0;i<n;i++) { for(int j=min(n,arr[i].dead)-1;j>=0;j--) { cout<<"\n\n\nminmmmmm:"<<min(n,arr[i].dead)<<endl; if(slot[j]==false) { result[j]=i; slot[j]=true; break; } } } int sum=0,max; for(int i=0;i<n;i++) { if(slot[i]) { cout<<arr[result[i]].id<<" "; sum=sum+arr[result[i]].profit; } } cout<<endl; cout<<"maximum weight: "<<sum; } int main() { job arr[10]; char ch; int d; int p; int n=5; int t=1; for(int i=0;i<n;i++) { printf("Enter job %d: --id--time--profit--:",t++); cin>>ch>>d>>p; arr[i].id=ch; arr[i].dead=d; arr[i].profit=p; } printfJobSe(arr,n); }
true
fb86f7c51b077681c24690961553c43dddad4ab3
C++
ttyang/sandbox
/sandbox/explore/boost/explore/manipulators.hpp
UTF-8
14,801
2.5625
3
[]
no_license
// // manipulators.hpp - stream manipulators for modifying how containers stream // // Copyright (C) 2007-2009, Jeffrey Faust // Copyright (C) 2008-2009, Jared McIntyre // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/explore for library home page. #ifndef MANIPULATOR_INCLUDED #define MANIPULATOR_INCLUDED #include <boost/explore/stream_value.hpp> #include <boost/explore/stream_state.hpp> #include <boost/explore/container_stream_state.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/remove_pointer.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/remove_const.hpp> #include <iostream> namespace boost { namespace explore { namespace detail { struct increment_depth { increment_depth(container_common_stream_state* state) : m_state(state) { m_prev_level = m_state->set_level(m_state->m_depth++); } ~increment_depth() { --m_state->m_depth; m_state->set_level(m_prev_level); } private: container_common_stream_state* m_state; size_t m_prev_level; }; // manipulator function wrapper for 1 char/wchar_t argument. When // streamed, will run manipulator function with argument. template<typename T> struct manipfunc { manipfunc(void (*fun)(std::ios_base&, T), T val) : pfun(fun), arg(val) { } void (*pfun)(std::ios_base&, T); T arg; }; // stream manipfunc template<typename Elem, typename Tr, typename T> std::basic_ostream<Elem, Tr>& operator<<( std::basic_ostream<Elem, Tr>& ostr, const manipfunc<T>& manip) { typedef typename boost::remove_const< typename boost::remove_reference< typename boost::remove_pointer<T>::type >::type >::type char_type; BOOST_STATIC_ASSERT(( boost::is_same<Elem, char_type>::value )); (*manip.pfun)(ostr, manip.arg); return ostr; } template<typename Elem, typename Tr> std::basic_ostream<Elem, Tr>& operator<<( std::basic_ostream<Elem, Tr>& ostr, const manipfunc<std::size_t>& manip) { (*manip.pfun)(ostr, manip.arg); return ostr; } template<typename Elem, typename Tr> std::basic_ostream<Elem, Tr>& operator<<( std::basic_ostream<Elem, Tr>& ostr, const manipfunc<bool>& manip) { (*manip.pfun)(ostr, manip.arg); return ostr; } struct handle_custom_stream { handle_custom_stream() : m_state(0) { } ~handle_custom_stream() { if( m_state && m_state->depth() > 0 ) // only needed if nested { m_state->level_down(); } } mutable container_common_stream_state* m_state; }; template<typename Elem, typename Tr> std::basic_ostream<Elem, Tr>& operator<<( std::basic_ostream<Elem, Tr>& ostr, const handle_custom_stream& cs) { container_common_stream_state* state = explore::get_stream_state<container_common_stream_state>(ostr); cs.m_state = state; if( state->depth() > 0 ) // only needed if nested { state->level_up(); } return ostr; } // function ptr for separator manipulator template<typename Elem> void separatorFn(std::ios_base& ostr, const Elem* sep) { explore::get_stream_state<container_stream_state<Elem> >(ostr) ->set_separator(sep); } // function ptr for start manipulator template<typename Elem> void startFn(std::ios_base& ostr, const Elem* start) { explore::get_stream_state<container_stream_state<Elem> >(ostr) ->set_start(start); } // function ptr for end manipulator template<typename Elem> void endFn(std::ios_base& ostr, const Elem* end) { explore::get_stream_state<container_stream_state<Elem> >(ostr) ->set_end(end); } // function ptr for associative separator manipulator template<typename Elem> void assoc_item_separatorFn(std::ios_base& ostr, const Elem* sep) { explore::get_stream_state<container_stream_state<Elem> >(ostr) ->set_assoc_item_separator(sep); } // function ptr for associative start manipulator template<typename Elem> void assoc_item_startFn(std::ios_base& ostr, const Elem* start) { explore::get_stream_state<container_stream_state<Elem> >(ostr) ->set_assoc_item_start(start); } // function ptr for associative end manipulator template<typename Elem> void assoc_item_endFn(std::ios_base& ostr, const Elem* end) { explore::get_stream_state<container_stream_state<Elem> >(ostr) ->set_assoc_item_end(end); } void levelFn(std::ios_base& ostr, std::size_t l) { explore::get_stream_state<container_common_stream_state>(ostr) ->set_level(l); } // function ptr object for cols void setcolsFn(std::ios_base& ostr, std::size_t sz) { explore::get_stream_state<container_common_stream_state>(ostr) ->set_cols(sz); } // function ptr object for item_width void setitemwidthFn(std::ios_base& ostr, std::size_t sz) { explore::get_stream_state<container_common_stream_state>(ostr) ->set_item_width(sz); } } template<typename Elem> detail::manipfunc<const Elem*> separator(const Elem* sep) { return detail::manipfunc<const Elem*>(&detail::separatorFn, sep); } template<typename Elem, typename Tr> const std::basic_string<Elem>& get_separator( std::basic_ostream<Elem, Tr>& ostr) { return explore::get_stream_state<container_stream_state<Elem> >(ostr) ->separator(); } template<typename Elem> detail::manipfunc<const Elem*> start(const Elem* s) { return detail::manipfunc<const Elem*>(&detail::startFn, s); } template<typename Elem, typename Tr> const std::basic_string<Elem>& get_start( std::basic_ostream<Elem, Tr>& ostr) { return explore::get_stream_state<container_stream_state<Elem> >(ostr) ->start(); } template<typename Elem> detail::manipfunc<const Elem*> end(const Elem* e) { return detail::manipfunc<const Elem*>(&detail::endFn, e); } template<typename Elem, typename Tr> const std::basic_string<Elem>& get_end(std::basic_ostream<Elem, Tr>& ostr) { return explore::get_stream_state<container_stream_state<Elem> >(ostr) ->end(); } template<typename Elem> detail::manipfunc<const Elem*> assoc_item_separator(const Elem* sep) { return detail::manipfunc<const Elem*>( &detail::assoc_item_separatorFn, sep); } template<typename Elem, typename Tr> const std::basic_string<Elem>& get_assoc_item_separator( std::basic_ostream<Elem, Tr>& ostr) { return explore::get_stream_state<container_stream_state<Elem> >(ostr) ->assoc_item_separator(); } template<typename Elem> detail::manipfunc<const Elem*> assoc_item_start(const Elem* start) { return detail::manipfunc<const Elem*>( &detail::assoc_item_startFn, start); } template<typename Elem, typename Tr> const std::basic_string<Elem>& get_assoc_item_start( std::basic_ostream<Elem, Tr>& ostr) { return explore::get_stream_state<container_stream_state<Elem> >(ostr) ->assoc_item_start(); } template<typename Elem> detail::manipfunc<const Elem*> assoc_item_end(const Elem* end) { return detail::manipfunc<const Elem*>(&detail::assoc_item_endFn, end); } template<typename Elem, typename Tr> const std::basic_string<Elem>& get_assoc_item_end( std::basic_ostream<Elem, Tr>& ostr) { return explore::get_stream_state<container_stream_state<Elem> >(ostr) ->assoc_item_end(); } detail::manipfunc<std::size_t> level(std::size_t l) { return detail::manipfunc<std::size_t>(&detail::levelFn, l); } detail::manipfunc<std::size_t> cols(std::size_t sz) { return detail::manipfunc<std::size_t>(detail::setcolsFn, sz); } template<typename Elem, typename Tr> std::size_t get_cols(std::basic_ostream<Elem, Tr>& ostr) { return explore::get_stream_state<container_common_stream_state>(ostr) ->cols(); } detail::manipfunc<std::size_t> item_width(std::size_t sz) { return detail::manipfunc<std::size_t>(detail::setitemwidthFn, sz); } template<typename Elem, typename Tr> std::size_t get_item_width(std::basic_ostream<Elem, Tr>& ostr) { return explore::get_stream_state<container_common_stream_state>(ostr) ->item_width(); } std::ios_base& quote_strings(std::ios_base& ios) { get_stream_state<container_common_stream_state>(ios) ->set_quote_strings(true); return ios; } std::ios_base& no_quote_strings(std::ios_base& ios) { get_stream_state<container_common_stream_state>(ios) ->set_quote_strings(false); return ios; } template<typename Elem, typename Tr> bool get_quote_strings(std::basic_ostream<Elem, Tr>& ostr) { return explore::get_stream_state<container_common_stream_state>(ostr) ->quote_strings(); } template<typename Elem, typename Tr> std::basic_ostream<Elem, Tr>& format_normal( std::basic_ostream<Elem, Tr>& ostr) { get_stream_state<container_stream_state<Elem> >(ostr) ->template init<Elem>(); return ostr; } detail::handle_custom_stream custom() { return detail::handle_custom_stream(); } namespace detail { struct standard_tag; struct assoc_tag; // begin_end manipulator template<typename Tag, typename T> struct begin_end_manipulator { begin_end_manipulator(T& startVal, T& endVal) :startVal_(startVal), endVal_(endVal) { } T startVal_; T endVal_; }; template<typename Elem, typename Tr, typename T> std::basic_ostream<Elem, Tr>& operator<<( std::basic_ostream<Elem, Tr>& ostr, const begin_end_manipulator<standard_tag,T>& manip) { startFn(ostr, manip.startVal_); endFn(ostr, manip.endVal_); return ostr; } template<typename Elem, typename Tr, typename T> std::basic_ostream<Elem, Tr>& operator<<( std::basic_ostream<Elem, Tr>& ostr, const begin_end_manipulator<assoc_tag,T>& manip) { assoc_item_startFn(ostr, manip.startVal_); assoc_item_endFn(ostr, manip.endVal_); return ostr; } } template<typename Elem> detail::begin_end_manipulator<detail::standard_tag,const Elem*> begin_end( const Elem* start, const Elem* end) { // todo: just use delimiters function and fetch seperator? return detail::begin_end_manipulator<detail::standard_tag,const Elem*>( start, end); } template<typename Elem> detail::begin_end_manipulator<detail::assoc_tag,const Elem*> assoc_item_begin_end(const Elem* start, const Elem* end) { // todo: just use delimiters function and fetch seperator? return detail::begin_end_manipulator<detail::assoc_tag,const Elem*>( start, end); } namespace detail { template<typename Tag, typename T> struct delimiters_manipulator { delimiters_manipulator(T& startVal, T& seperatorVal, T& endVal) :startVal_(startVal), seperatorVal_(seperatorVal), endVal_(endVal) { } T startVal_; T seperatorVal_; T endVal_; }; template<typename Elem, typename Tr, typename T> std::basic_ostream<Elem, Tr>& operator<<( std::basic_ostream<Elem, Tr>& ostr, const delimiters_manipulator<standard_tag,T>& manip) { startFn(ostr, manip.startVal_); separatorFn(ostr, manip.seperatorVal_); endFn(ostr, manip.endVal_); return ostr; } template<typename Elem, typename Tr, typename T> std::basic_ostream<Elem, Tr>& operator<<( std::basic_ostream<Elem, Tr>& ostr, const delimiters_manipulator<assoc_tag,T>& manip) { assoc_item_startFn(ostr, manip.startVal_); assoc_item_separatorFn(ostr, manip.seperatorVal_); assoc_item_endFn(ostr, manip.endVal_); return ostr; } } template<typename Elem> detail::delimiters_manipulator<detail::standard_tag,const Elem*> delimiters( const Elem* start, const Elem* seperator, const Elem* end) { return detail::delimiters_manipulator< detail::standard_tag, const Elem*>(start, seperator, end); } template<typename Elem> detail::delimiters_manipulator<detail::assoc_tag,const Elem*> assoc_item_delimiters( const Elem* start, const Elem* seperator, const Elem* end) { return detail::delimiters_manipulator< detail::assoc_tag,const Elem*>(start, seperator, end); } }} #endif
true
4da2b2129a793ad58d88def7ad3514a6bf141639
C++
gssm-cs201/gRayT
/src/Triangle.cpp
UTF-8
7,558
2.765625
3
[]
no_license
#include "gssmraytracer/geometry/Triangle.h" using namespace gssmraytracer::math; namespace gssmraytracer { namespace geometry { class Triangle::Impl { public: Impl(const TriangleMesh *m, const int n) : mesh(m), v() { v = mesh->getVertexIndex(n*3); } const TriangleMesh *mesh; int *v; }; void CoordinateSystem(const Vector &v1, Vector *v2, Vector *v3) { if (fabs(v1.x() > fabs(v1.y()))) { float invLen = 1.f/sqrt(v1.y() * v1.y() + v1.z() * v1.z()); *v2 = Vector(0.f, v1.z() * invLen, -v1.y() * invLen); } else { float invLen = 1.f / sqrtf(v1.y() * v1.y() + v1.z() * v1.z()); *v2 = Vector(0.f, v1.z() * invLen, -v1.y() * invLen); } *v3 = v1.cross(*v2); } bool SolveLinearSystem2x2(const float A[2][2], const float B[2], float *x0, float *x1) { float det = A[0][0] * A[1][1] - A[0][1]*A[1][0]; if (fabsf(det) < 1e-10f) return false; *x0 = (A[1][1] * B[0] - A[0][1] * B[1])/ det; *x1 = (A[0][0] * B[1] - A[1][0] * B[0])/ det; if (isnan(*x0) || isnan(*x1)) return false; return true; } Triangle::Triangle(const Transform &transform, const bool reverseOrientation, const TriangleMesh *mesh, const int n) : Shape(transform, reverseOrientation), mImpl(new Impl(mesh, n)) {} bool Triangle::hit(const utils::Ray &ws_ray, float &tHit) const { std::shared_ptr<DifferentialGeometry> dg; return hit(ws_ray, tHit, dg); } bool Triangle::hit(const utils::Ray &ws_ray, float &tHit, std::shared_ptr<DifferentialGeometry> &dg) const { const Point &p1 = mImpl->mesh->getVertexPositionArray(mImpl->v[0]); const Point &p2 = mImpl->mesh->getVertexPositionArray(mImpl->v[1]); const Point &p3 = mImpl->mesh->getVertexPositionArray(mImpl->v[2]); // get triangle vertices in p1, p2, and p3 Vector e1 = p2 - p1; Vector e2 = p3 - p1; Vector s1 = ws_ray.dir().cross(e2); float divisor = s1.dot(e1); if (divisor == 0.) return false; float invDivisor = 1.f / divisor; // compute first barycentric coordinate Vector d = ws_ray.origin() - p1; float b1 = d.dot(s1) * invDivisor; if (b1 < 0. || b1 > 1.) return false; // compute second barycentric coordinate Vector s2 = d.cross(e1); float b2 = ws_ray.dir().dot(s2) * invDivisor; if (b2 < 0. || b1 + b2 > 1.) return false; // Compute t to intersection point float t = e2.dot(s2) * invDivisor; if (t < ws_ray.mint() || t > ws_ray.maxt()) return false; // compute triangle partial derivative Vector dpdu, dpdv; float uvs[3][2]; getUVs(uvs); // compute deltas for triangle partial derivatives float du1 = uvs[0][0] - uvs[2][0]; float du2 = uvs[1][0] - uvs[2][0]; float dv1 = uvs[0][1] - uvs[2][1]; float dv2 = uvs[1][1] - uvs[2][1]; Vector dp1 = p1 - p3, dp2 = p2 - p3; float determinant = du1 * dv2 - dv1 * du2; if (determinant == 0.f) { // handle zero determinants for triangle partial derivative matrix CoordinateSystem(e2.cross(e1).normalized(), &dpdu, &dpdv); } else { float invdet = 1.f/determinant; dpdu = (dv2 * dp1 - dv1 * dp2) * invdet; dpdv = (-du2 * dp1 + du1 * dp2) * invdet; } // interpolate (u,v) triangle parametric coordinates float b0 = 1 - b1 - b2; float tu = b0 * uvs[0][0] + b1*uvs[1][0] + b2*uvs[2][0]; float tv = b0 * uvs[0][1] + b1*uvs[1][1] + b2*uvs[2][1]; tHit = t; std::shared_ptr<DifferentialGeometry> dg_temp(new DifferentialGeometry(ws_ray(t-1e-3), dpdu, dpdv, Normal(0,0,0), Normal(0,0,0), tu, tv, this)); getShadingGeometry(dg_temp, dg); return true; } void Triangle::getUVs(float uv[3][2]) const { if (mImpl->mesh->getUVs()) { uv[0][0] = mImpl->mesh->getUVs()[2 * mImpl->v[0]]; uv[0][1] = mImpl->mesh->getUVs()[2 * mImpl->v[0] + 1]; uv[1][0] = mImpl->mesh->getUVs()[2 * mImpl->v[1]]; uv[1][1] = mImpl->mesh->getUVs()[2 * mImpl->v[1] + 1]; uv[2][0] = mImpl->mesh->getUVs()[2 * mImpl->v[2]]; uv[2][1] = mImpl->mesh->getUVs()[2 * mImpl->v[2] + 1]; } else { uv[0][0] = 0.; uv[0][1] = 0.; uv[1][0] = 1.; uv[1][1] = 0.; uv[2][0] = 1.; uv[2][1] = 1.; } } //! returns the bounding box of the shape in world space const BBox Triangle::worldBB() const { const Point &p1 = mImpl->mesh->getVertexPositionArray(mImpl->v[0]); const Point &p2 = mImpl->mesh->getVertexPositionArray(mImpl->v[1]); const Point &p3 = mImpl->mesh->getVertexPositionArray(mImpl->v[2]); BBox bbox(p1, p3); bbox = bbox.combine(BBox(p2)); return bbox; } //! returns the bounding box of the shape in object space const BBox Triangle::objectBB() const { const Point &p1 = mImpl->mesh->getVertexPositionArray(mImpl->v[0]); const Point &p2 = mImpl->mesh->getVertexPositionArray(mImpl->v[1]); const Point &p3 = mImpl->mesh->getVertexPositionArray(mImpl->v[2]); BBox bbox(worldToObjectSpace()(p1), worldToObjectSpace()(p2)); bbox = bbox.combine(worldToObjectSpace()(p3)); return bbox; } const bool Triangle::canIntersect() const { return true; } void Triangle::getShadingGeometry(const std::shared_ptr<DifferentialGeometry> &dg, std::shared_ptr<DifferentialGeometry> &dgShading) const { if (!mImpl->mesh->n() && !mImpl->mesh->s()) { dgShading = dg; return; } // initialize Triangle shading geometry with n and s //compute barycentric coordinates for point float b[3]; //initialize A and C matrices for barycentrics float uv[3][2]; getUVs(uv); float A[2][2] = { { uv[1][0] - uv[0][0], uv[2][0] - uv[0][0]}, { uv[1][1] - uv[0][1], uv[2][1] - uv[0][1]} }; float C[2] = {dg->u - uv[0][0], dg->v - uv[0][1] }; if (!SolveLinearSystem2x2(A, C, &b[1], &b[2])) { //handle degenerate parametric mapping b[0] = b[1] = b[2] = 1.f/3.f; } else { b[0] = 1.f - b[1] - b[2]; } //use n and s to compute shading tangents for triangle, ss and ts Normal ns; Vector ss, ts; if (mImpl->mesh->n()) { ns = objectToWorldSpace()(b[0] * mImpl->mesh->n()[mImpl->v[0]] + b[1] * mImpl->mesh->n()[mImpl->v[1]] + b[2] * mImpl->mesh->n()[mImpl->v[2]]).normalized(); } else ns = dg->nn; if (mImpl->mesh->s()) { ss = objectToWorldSpace()(b[0] * mImpl->mesh->s()[mImpl->v[0]] + b[1] * mImpl->mesh->s()[mImpl->v[1]] + b[2] * mImpl->mesh->s()[mImpl->v[2]]).normalized(); } else ss = dg->dpdu.normalized(); ts = ss.cross((Vector)ns); if (ts.lengthSquared() > 0.f) { ts.normalize(); ss = ts.cross(Vector(ns)); } else CoordinateSystem(Vector(ns), &ss, &ts); Normal dndu, dndv; //compute partial dn/du and partial dn/dv for triangle shading geometry dgShading = std::shared_ptr<DifferentialGeometry>(new DifferentialGeometry(dg->p, ss, ts, objectToWorldSpace()(dndu), objectToWorldSpace()(dndv), dg->u, dg->v, dg->shape)); } } }
true
be8ef99ac2491ae39650a5a851a37d7e4d7f7d18
C++
eecs275/minimal_turtlebot
/turtlebot_controller.cpp
UTF-8
1,617
2.53125
3
[]
no_license
#include "minimal_turtlebot/turtlebot_controller.h" void turtlebot_controller(turtlebotInputs turtlebot_inputs, uint8_t *soundValue, float *vel, float *ang_vel) { //turtlebot_inputs.centerBumperPressed; //turtlebot_inputs.rightBumperPressed; //turtlebot_inputs.leftBumperPressed; //turtlebot_inputs.nanoSecs; bool bumper_flag=false; if (turtlebot_inputs.centerBumperPressed && bumper_flag==false){ uint64_t time = turtlebot_inputs.nanoSecs; bumper_flag = true; } if (bumper_flag){ if (turtlebot_inputs.nanoSecs -time < 10000000000.0){ *vel = -0.2;} else if (turtlebot_inputs.nanoSecs -time < 20000000000.0){ *vel = 0; *ang_vel = 0.2;} else bumper_flag = false; } /*if (turtlebot_inputs.leftBumperPressed){ float time = turtlebot_inputs.nanoSecs; *vel = -*vel; if (turtlebot_inputs.nanoSecs == time + 1){ *vel = 0; *ang_vel = 0.2;} if (turtlebot_inputs.nanoSecs == time + 4.93){ *ang_vel = 0; *vel = 0.2;} } if (turtlebot_inputs.rightBumperPressed){ float time = turtlebot_inputs.nanoSecs; *vel = -*vel; if (turtlebot_inputs.nanoSecs == time + 1){ *vel = 0; *ang_vel = -0.2;} if (turtlebot_inputs.nanoSecs == time + 4.93){ *ang_vel = 0; *vel = 0.2;} } */ *vel = 0.2; // Robot forward velocity in m/s //0.7 is max and is a lot *ang_vel = 0; // Robot angular velocity in rad/s //0.7 is max and is a lot *soundValue = 0; //here are the various sound value enumeration options //soundValue.OFF //soundValue.RECHARGE //soundValue.BUTTON //soundValue.ERROR //soundValue.CLEANINGSTART //soundValue.CLEANINGEND }
true
2021cb7bba484a47189d9dd97d0594b89d566378
C++
Toocanzs/4coder-non-source
/test_data/lots_of_files/4ed_math.cpp
UTF-8
13,801
2.875
3
[]
no_license
/* * Mr. 4th Dimention - Allen Webster * * 15.05.2015 * * Math functions for 4coder * */ // TOP /* * Scalar operators */ #define C_MATH 1 #define DEG_TO_RAD 0.0174533f #if C_MATH #include <math.h> #endif inline f32 ABS(f32 x){ if (x < 0) x = -x; return x; } inline f32 MOD(f32 x, i32 m){ #if C_MATH f32 whole, frac; frac = modff(x, &whole); return ((i32)(whole) % m) + frac; #endif } inline f32 SQRT(f32 x){ #if C_MATH return sqrt(x); #endif } inline f32 SIN(f32 x_degrees){ #if C_MATH return sinf(x_degrees * DEG_TO_RAD); #endif } inline f32 COS(f32 x_degrees){ #if C_MATH return cosf(x_degrees * DEG_TO_RAD); #endif } /* * Rounding */ inline i32 TRUNC32(real32 x) { return (i32)x; } inline i32 FLOOR32(real32 x) { return (i32)(x)-((x!=(i32)(x) && x<0)?1:0); } inline i32 CEIL32(real32 x) { return (i32)(x)+((x!=(i32)(x) && x>0)?1:0); } inline i32 ROUND32(real32 x) { return FLOOR32(x + .5f); } inline i32 DIVCEIL32(i32 n, i32 d) { i32 q = (n/d); return q + (q*d < n); } inline real32 FRACPART32(real32 x) { return x - (i32)x; } inline u32 ROUNDPOT32(u32 v){ v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } /* * Rectangles */ struct i32_Rect{ i32 x0, y0; i32 x1, y1; }; struct f32_Rect{ f32 x0, y0; f32 x1, y1; }; inline i32_Rect i32R(i32 l, i32 t, i32 r, i32 b){ i32_Rect rect; rect.x0 = l; rect.y0 = t; rect.x1 = r; rect.y1 = b; return rect; } inline i32_Rect i32R(f32_Rect r){ i32_Rect rect; rect.x0 = (i32)r.x0; rect.y0 = (i32)r.y0; rect.x1 = (i32)r.x1; rect.y1 = (i32)r.y1; return rect; } inline i32_Rect i32XYWH(i32 x, i32 y, i32 w, i32 h){ i32_Rect rect; rect.x0 = x; rect.y0 = y; rect.x1 = x+w; rect.y1 = y+h; return rect; } inline f32_Rect f32R(f32 l, f32 t, f32 r, f32 b){ f32_Rect rect; rect.x0 = l; rect.y0 = t; rect.x1 = r; rect.y1 = b; return rect; } inline f32_Rect f32R(i32_Rect r){ f32_Rect rect; rect.x0 = (f32)r.x0; rect.y0 = (f32)r.y0; rect.x1 = (f32)r.x1; rect.y1 = (f32)r.y1; return rect; } inline f32_Rect f32XYWH(f32 x, f32 y, f32 w, f32 h){ f32_Rect rect; rect.x0 = x; rect.y0 = y; rect.x1 = x+w; rect.y1 = y+h; return rect; } inline b32 hit_check(i32 x, i32 y, i32 x0, i32 y0, i32 x1, i32 y1){ return (x >= x0 && x < x1 && y >= y0 && y < y1); } inline b32 hit_check(i32 x, i32 y, i32_Rect rect){ return (hit_check(x, y, rect.x0, rect.y0, rect.x1, rect.y1)); } inline b32 hit_check(i32 x, i32 y, f32 x0, f32 y0, f32 x1, f32 y1){ return (x >= x0 && x < x1 && y >= y0 && y < y1); } inline b32 hit_check(i32 x, i32 y, f32_Rect rect){ return (hit_check(x, y, rect.x0, rect.y0, rect.x1, rect.y1)); } inline b32 positive_area(i32_Rect rect){ return (rect.x0 < rect.x1 && rect.y0 < rect.y1); } inline i32_Rect get_inner_rect(i32_Rect outer, i32 margin){ i32_Rect r; r.x0 = outer.x0 + margin; r.y0 = outer.y0 + margin; r.x1 = outer.x1 - margin; r.y1 = outer.y1 - margin; return r; } inline b32 fits_inside(i32_Rect rect, i32_Rect outer){ return (rect.x0 >= outer.x0 && rect.x1 <= outer.x1 && rect.y0 >= outer.y0 && rect.y1 <= outer.y1); } inline i32_Rect rect_clamp_to_rect(i32_Rect rect, i32_Rect clamp_box){ if (rect.x0 < clamp_box.x0) rect.x0 = clamp_box.x0; if (rect.y0 < clamp_box.y0) rect.y0 = clamp_box.y0; if (rect.x1 > clamp_box.x1) rect.x1 = clamp_box.x1; if (rect.y1 > clamp_box.y1) rect.y1 = clamp_box.y1; return rect; } inline i32_Rect rect_clamp_to_rect(i32 left, i32 top, i32 right, i32 bottom, i32_Rect clamp_box){ return rect_clamp_to_rect(i32R(left, top, right, bottom), clamp_box); } /* * Vectors */ struct Vec2{ union{ struct{ real32 x, y; }; struct{ real32 v[2]; }; }; }; struct Vec3{ union{ struct{ real32 x, y, z; }; struct{ real32 r, g, b; }; struct{ Vec2 xy; real32 _z; }; struct{ real32 _x; Vec2 yz; }; struct{ real32 v[3]; }; }; }; struct Vec4{ union{ struct{ real32 r, g, b, a; }; struct{ real32 h, s, l, __a; }; struct{ real32 x, y, z, w; }; struct{ Vec3 rgb; real32 _a; }; struct{ Vec3 xyz; real32 _w; }; struct{ real32 _x; Vec3 yzw; }; struct{ real32 v[4]; }; }; }; inline internal Vec2 V2(real32 x, real32 y){ Vec2 result; result.x = x; result.y = y; return result; } inline internal Vec3 V3(real32 x, real32 y, real32 z){ Vec3 result; result.x = x; result.y = y; result.z = z; return result; } inline internal Vec4 V4(real32 x, real32 y, real32 z, real32 w){ Vec4 result; result.x = x; result.y = y; result.z = z; result.w = w; return result; } inline internal Vec2 operator+(Vec2 a, Vec2 b){ Vec2 result; result.x = a.x + b.x; result.y = a.y + b.y; return result; } inline internal Vec3 operator+(Vec3 a, Vec3 b){ Vec3 result; result.x = a.x + b.x; result.y = a.y + b.y; result.z = a.z + b.z; return result; } inline internal Vec4 operator+(Vec4 a, Vec4 b){ Vec4 result; result.x = a.x + b.x; result.y = a.y + b.y; result.z = a.z + b.z; result.w = a.w + b.w; return result; } inline internal Vec2 operator-(Vec2 a, Vec2 b){ Vec2 result; result.x = a.x - b.x; result.y = a.y - b.y; return result; } inline internal Vec3 operator-(Vec3 a, Vec3 b){ Vec3 result; result.x = a.x - b.x; result.y = a.y - b.y; result.z = a.z - b.z; return result; } inline internal Vec4 operator-(Vec4 a, Vec4 b){ Vec4 result; result.x = a.x - b.x; result.y = a.y - b.y; result.z = a.z - b.z; result.w = a.w - b.w; return result; } inline internal Vec2 operator*(Vec2 a, real32 k){ Vec2 result; result.x = a.x * k; result.y = a.y * k; return result; } inline internal Vec3 operator*(Vec3 a, real32 k){ Vec3 result; result.x = a.x * k; result.y = a.y * k; result.z = a.z * k; return result; } inline internal Vec4 operator*(Vec4 a, real32 k){ Vec4 result; result.x = a.x * k; result.y = a.y * k; result.z = a.z * k; result.w = a.w * k; return result; } inline internal Vec2 operator*(real32 k, Vec2 a){ Vec2 result; result.x = a.x * k; result.y = a.y * k; return result; } inline internal Vec3 operator*(real32 k, Vec3 a){ Vec3 result; result.x = a.x * k; result.y = a.y * k; result.z = a.z * k; return result; } inline internal Vec4 operator*(real32 k, Vec4 a){ Vec4 result; result.x = a.x * k; result.y = a.y * k; result.z = a.z * k; result.w = a.w * k; return result; } inline internal Vec2& operator+=(Vec2 &a, Vec2 b){ a = (a + b); return a; } inline internal Vec3& operator+=(Vec3 &a, Vec3 b){ a = (a + b); return a; } inline internal Vec4& operator+=(Vec4 &a, Vec4 b){ a = (a + b); return a; } inline internal Vec2& operator-=(Vec2 &a, Vec2 b){ a = (a - b); return a; } inline internal Vec3& operator-=(Vec3 &a, Vec3 b){ a = (a - b); return a; } inline internal Vec4& operator-=(Vec4 &a, Vec4 b){ a = (a - b); return a; } inline internal Vec2& operator*=(Vec2 &a, real32 k){ a = (a * k); return a; } inline internal Vec3& operator*=(Vec3 &a, real32 k){ a = (a * k); return a; } inline internal Vec4& operator*=(Vec4 &a, real32 k){ a = (a * k); return a; } inline internal real32 dot(Vec2 a, Vec2 b){ real32 result; result = a.x*b.x + a.y*b.y; return result; } inline internal real32 dot(Vec3 a, Vec3 b){ real32 result; result = a.x*b.x + a.y*b.y + a.z*b.z; return result; } inline internal real32 dot(Vec4 a, Vec4 b){ real32 result; result = a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w; return result; } inline internal Vec3 cross(Vec3 a, Vec3 b){ Vec3 result; result.x = a.y*b.z - b.y*a.z; result.y = a.z*b.x - b.z*a.x; result.z = a.x*b.y - b.x*a.y; return result; } inline internal Vec2 hadamard(Vec2 a, Vec2 b){ Vec2 result; result.x = a.x*b.x; result.y = a.y*b.y; return result; } inline internal Vec3 hadamard(Vec3 a, Vec3 b){ Vec3 result; result.x = a.x*b.x; result.y = a.y*b.y; result.z = a.z*b.z; return result; } inline internal Vec4 hadamard(Vec4 a, Vec4 b){ Vec4 result; result.x = a.x*b.x; result.y = a.y*b.y; result.z = a.z*b.z; result.w = a.w*b.w; return result; } inline internal Vec2 perp(Vec2 v){ Vec2 result; result.x = -v.y; result.y = v.x; return result; } inline Vec2 polar_to_cartesian(real32 theta_degrees, real32 length){ Vec2 result; result.x = COS(theta_degrees)*length; result.y = SIN(theta_degrees)*length; return result; } inline Vec2 rotate(Vec2 v, real32 theta_degrees){ Vec2 result; real32 c, s; c = COS(theta_degrees); s = SIN(theta_degrees); result.x = v.x*c - v.y*s; result.y = v.x*s + v.y*c; return result; } /* * Coordinates */ struct Matrix2{ Vec2 x_axis; Vec2 y_axis; }; internal Matrix2 invert(Vec2 x_axis, Vec2 y_axis){ Matrix2 result = {}; real32 det = 1.f / (x_axis.x*y_axis.y - x_axis.y*y_axis.x); result.x_axis.x = y_axis.y*det; result.y_axis.x = -y_axis.x*det; result.x_axis.y = -x_axis.y*det; result.y_axis.y = x_axis.x*det; return result; } internal Matrix2 invert(Matrix2 m){ Matrix2 result = {}; real32 det = 1.f / (m.x_axis.x*m.y_axis.y - m.x_axis.y*m.y_axis.x); result.x_axis.x = m.y_axis.y*det; result.y_axis.x = -m.y_axis.x*det; result.x_axis.y = -m.x_axis.y*det; result.y_axis.y = m.x_axis.x*det; return result; } /* * Lerps, Clamps, Thresholds, Etc */ inline real32 lerp(real32 a, real32 t, real32 b){ return a + (b-a)*t; } inline Vec2 lerp(Vec2 a, real32 t, Vec2 b){ return a + (b-a)*t; } inline Vec3 lerp(Vec3 a, real32 t, Vec3 b){ return a + (b-a)*t; } inline Vec4 lerp(Vec4 a, real32 t, Vec4 b){ return a + (b-a)*t; } inline real32 unlerp(real32 a, real32 x, real32 b){ return (x - a) / (b - a); } inline real32 clamp(real32 a, real32 n, real32 z){ return (n<a)?(a):((n>z)?(z):n); } /* * Color */ // TODO(allen): Convert colors to Vec4 inline internal u32 color_blend(u32 a, real32 t, u32 b){ union{ u8 byte[4]; u32 comp; } A, B, R; A.comp = a; B.comp = b; R.byte[0] = (u8)lerp(A.byte[0], t, B.byte[0]); R.byte[1] = (u8)lerp(A.byte[1], t, B.byte[1]); R.byte[2] = (u8)lerp(A.byte[2], t, B.byte[2]); R.byte[3] = (u8)lerp(A.byte[3], t, B.byte[3]); return R.comp; } internal Vec3 unpack_color3(u32 color){ Vec3 result; result.r = ((color >> 16) & 0xFF) / 255.f; result.g = ((color >> 8) & 0xFF) / 255.f; result.b = ((color >> 0) & 0xFF) / 255.f; return result; } internal Vec4 unpack_color4(u32 color){ Vec4 result; result.a = ((color >> 24) & 0xFF) / 255.f; result.r = ((color >> 16) & 0xFF) / 255.f; result.g = ((color >> 8) & 0xFF) / 255.f; result.b = ((color >> 0) & 0xFF) / 255.f; return result; } internal u32 pack_color4(Vec4 color){ u32 result = ((u8)(color.a * 255) << 24) | ((u8)(color.r * 255) << 16) | ((u8)(color.g * 255) << 8) | ((u8)(color.b * 255) << 0); return result; } internal Vec4 rgba_to_hsla(Vec4 rgba){ Vec4 hsla = {}; real32 max, min, delta; i32 maxc; hsla.a = rgba.a; max = rgba.r; min = rgba.r; maxc = 0; if (rgba.r < rgba.g){ max = rgba.g; maxc = 1; } if (rgba.b > max){ max = rgba.b; maxc = 2; } if (rgba.r > rgba.g){ min = rgba.g; } if (rgba.b < min){ min = rgba.b; } delta = max - min; hsla.z = (max + min) * .5f; if (delta == 0){ hsla.x = 0.f; hsla.y = 0.f; } else{ switch (maxc){ case 0: { hsla.x = (rgba.g - rgba.b) / delta; hsla.x += (rgba.g < rgba.b) * 6.f; }break; case 1: { hsla.x = (rgba.b - rgba.r) / delta; hsla.x += 2.f; }break; case 2: { hsla.x = (rgba.r - rgba.g) / delta; hsla.x += 4.f; }break; } hsla.x *= (1/6.f); // * 60 / 360 hsla.y = delta / (1.f - ABS(2.f*hsla.z - 1.f)); } return hsla; } internal Vec4 hsla_to_rgba(Vec4 hsla){ if (hsla.h >= 1.f) hsla.h = 0.f; Vec4 rgba = {}; real32 C, X, m; i32 H; rgba.a = hsla.a; C = (1.f - ABS(2*hsla.z - 1.f)) * hsla.y; X = C * (1.f-ABS(MOD(hsla.x*6.f, 2)-1.f)); m = hsla.z - C*.5f; H = FLOOR32(hsla.x * 6.f); switch (H){ case 0: rgba.r = C; rgba.g = X; rgba.b = 0; break; case 1: rgba.r = X; rgba.g = C; rgba.b = 0; break; case 2: rgba.r = 0; rgba.g = C; rgba.b = X; break; case 3: rgba.r = 0; rgba.g = X; rgba.b = C; break; case 4: rgba.r = X; rgba.g = 0; rgba.b = C; break; case 5: rgba.r = C; rgba.g = 0; rgba.b = X; break; } rgba.r += m; rgba.g += m; rgba.b += m; return rgba; } // BOTTOM
true
39171c0021d0319895e589033cb1aceca8e1ea2c
C++
zzmicer/Computer-Architecture-Labs
/Lab2/Lab2/Lab2_2.cpp
UTF-8
1,844
3.453125
3
[]
no_license
#include <iostream> #include <thread> #include <chrono> #include <algorithm> #include <mutex> #include <vector> #include <atomic> #include "windows.h" #include <queue> using namespace std; using namespace std::chrono; static const int TaskNum = 4 * 1024 * 1024; static const int ProducerNum = 4; static const int ConsumerNum = 4; int globalSum = 0; // Thread safe queue implemented on std::queue class ThreadSafeDynamicQueue { public: void push(uint8_t val) { std::lock_guard<std::mutex> lock(qmutex); data.push(val); } bool pop(uint8_t& val) { unique_lock<mutex> ulock(qmutex); if (data.empty()) { ulock.unlock(); this_thread::sleep_for(milliseconds(1)); if (data.empty()) { return false; } } val = data.front(); data.pop(); return true; } private: std::queue<uint8_t> data; std::mutex qmutex; }; static ThreadSafeDynamicQueue dynamicQueue; // Push TaskNum/ConsumerNum ones to queue. void producer() { for (int i = 0; i < TaskNum/ConsumerNum; i++) { dynamicQueue.push(1); } } /** * Pop elem from queue and add to global sum. * * Using atomic counter to track number of pop operations * If queue is empty counter is not updated. */ void consumer() { int localSum = 0; uint8_t elem; atomic<int> i{ 0 }; while (i < TaskNum / ConsumerNum) { if (dynamicQueue.pop(elem)) { localSum += elem; i += 1; } } globalSum += localSum; } bool check_sum() { return TaskNum == globalSum; } int main() { thread consumers[ConsumerNum]; thread producers[ProducerNum]; for (int i = 0; i < ConsumerNum; i++) { consumers[i] = thread(consumer); producers[i] = thread(producer); } for (int i = 0; i < ConsumerNum; i++) { consumers[i].join(); producers[i].join(); } cout << "Sum: " << globalSum<<endl; check_sum() ? cout << "Succeded!" : cout << "Failed"; return 0; }
true
1f9c594e5a0b5a06deb56a49ba661b91f179daef
C++
mdqyy/go2012
/player/src/lib/vision/ImageInput.cpp
UTF-8
2,000
3.1875
3
[]
no_license
/* * Name: ImageInput.cpp * @Author: Carlos Agüero (caguero@gsyc.es) * * Description: Class that stores the parameters of an image and implements some utilities. * * Copyright (C) 2008-2009 Universidad Rey Juan Carlos * All Rights Reserved. */ #include "ImageInput.h" /** * Class constructor that sets the parameters of the image. * * @param width Sets the width of the image. * @param height Sets the height of the image. * @param channels Sets the number of the channels of the image. */ ImageInput::ImageInput() { this->width = ImageInput::IMG_WIDTH; this->height = ImageInput::IMG_HEIGHT; this->channels = ImageInput::IMG_CHANNELS; } /** * Class destructor. **/ ImageInput::~ImageInput() { } /** * getImageParams. Method that allows to read the current image parameteres. * @param width Pointer to the width of the next image to filter. * @param height Pointer to the height of the next image to filter. * @param channels Pointer to the number of channels of the next image to filter. **/ void ImageInput::getImageParams(unsigned short& width, unsigned short& height, unsigned char& channels) { width = this->width; height = this->height; channels = this->channels; } /** * setImageParams. Method that updates the image parameteres. * @param width The new width of the next image to filter. * @param height The new height of the next image to filter. * @param channels The new number of channels of the next image to filter. **/ void ImageInput::setImageParams(unsigned short width, unsigned short height, unsigned char channels) { this->width = width; this->height = height; this->channels = channels; } /** * saveImage. Method that saves to disk an image. * @param data Sets the image. * @param file Sets the name of the file. **/ void ImageInput::saveImage(const char* data, const char *file) { IplImage* img = cvCreateImage( cvSize( width, height ), 8, channels ); img->imageData = ( char* ) data; cvSaveImage( file, img ); cvReleaseImage(&img); }
true
bbbe2b965df5d68a023eedd57df211efc33c9be1
C++
webserver3315/Desktop_PS_BOJ
/PS_BOJ/BOJ2529.cpp
WINDOWS-1252
2,369
3.078125
3
[]
no_license
/* εȣ */ #include <iostream> #include <vector> #include <string> #include <cstring> #define endl '\n' using namespace std; int N; string futougo; vector<int> answer_max; bool ended_max; vector<int> answer_min; bool ended_min; bool visit[13]; void min_dfs(int now) { if (ended_min) return; if (now == N) { ended_min = true; for (int tmp : answer_min) cout << tmp; cout << endl; return; } if (answer_min.empty()) { for (int i = 0; i < 10 && !ended_min; i++) { visit[i] = true; answer_min.push_back(i); min_dfs(now); visit[i] = false; answer_min.pop_back(); } } if (futougo[now] == '<') { for (int i = 0; i < 10 && !ended_min; i++) { if (visit[i] || (!answer_min.empty() && answer_min.back() >= i)) continue; visit[i] = true; answer_min.push_back(i); min_dfs(now + 1); visit[i] = false; answer_min.pop_back(); } } else if (futougo[now] == '>') { for (int i = 0; i < 10 && !ended_min; i++) { if (visit[i] || (!answer_min.empty() && answer_min.back() <= i)) continue; visit[i] = true; answer_min.push_back(i); min_dfs(now + 1); visit[i] = false; answer_min.pop_back(); } } /*else cout << "ERROR" << endl;*/ } void max_dfs(int now) { if (ended_max) return; if (now == N) { ended_max = true; for (int tmp : answer_max) cout << tmp; cout << endl; } if (answer_max.empty()) { for (int i = 9; i >= 0 && !ended_max; i--) { visit[i] = true; answer_max.push_back(i); max_dfs(now); visit[i] = false; answer_max.pop_back(); } } else if (futougo[now] == '<') { for (int i = 9; i >= 0 && !ended_max; i--) { if (visit[i] || (!answer_max.empty() && answer_max.back() >= i)) continue; visit[i] = true; answer_max.push_back(i); max_dfs(now + 1); visit[i] = false; answer_max.pop_back(); } } else if (futougo[now] == '>') { for (int i = 9; i >= 0 && !ended_max; i--) { if (visit[i] || answer_max.back() <= i) continue; visit[i] = true; answer_max.push_back(i); max_dfs(now + 1); visit[i] = false; answer_max.pop_back(); } } /*else cout << "ERROR" << endl;*/ } int main() { ios::sync_with_stdio(false); //cin.tie(NULL); cin >> N; for (int i = 0; i < N; i++) { string tmp; cin >> tmp; futougo.append(tmp); } max_dfs(0); memset(visit, false, N); min_dfs(0); return 0; }
true
765b305d25ae277b1ba9c02ae4e2e1f67c56f2b3
C++
hijarian/KSU-algorithmization-courses
/c1/s2/The Last Step/srcCore_datalayer.cpp
WINDOWS-1251
3,819
2.875
3
[]
no_license
// 13 " ++" // , , // . // 5.2.2 9 // ----------------------------------- // srcCore_datalayer // , . // srcCore_menuitems, // // ----------------------------------- // () .. . . , 2007 #include "srcCore_datalayer.h" ptNode listConstruct(size_t size) {// () .. size_t i; ptNode pN, plist(0); if (size) // size != 0. { pN = plist = new TNode; // . for (i = 1; i < size; ++i) // . pN = pN->link = new TNode; pN->link = 0; // . } return plist; } void listDestroy(ptNode plist) {// () .. ptNode pN(plist); while (plist) // . { pN = plist->link; delete plist; // . plist = pN; } } ptNode listInverse(ptNode plist) {// () .. ptNode ptemp, pnrev(plist), prev(0); while (pnrev) { ptemp = pnrev->link; pnrev->link = prev; prev = pnrev; pnrev = ptemp; } return prev; } ptNode listGetElem(ptNode pStart, size_t nmb) { ptNode pN=pStart; for (size_t i=1; i<nmb; ++i) if(pN) pN=pN->link; else return NULL; return pN; } size_t listGetSize(ptNode pStart) { size_t count=0; ptNode pN=pStart; while(pN) { pN=pN->link; ++count; } return count; } int listAddNode(ptNode pStart, size_t nmb, TKey key, TVal val) { ptNode pN=listGetElem(pStart, nmb); if(pN) { // - , ptNode pT=new TNode; // pT->link=pN->link; // // , pN->link=pT; // // pT->name=key; pT->number=val; } else // - , =) return 1; return 0; } ptNode listAdd1st(ptNode plist, TKey key, TVal val) { ptNode pT=new TNode; pT->name=key; pT->number=val; pT->link=plist; return pT; } int listRemoveNode(ptNode pStart, size_t nmb) { ptNode pN=pStart; if(nmb==1) return -1; pN=listGetElem(pStart, nmb-1); if(pN) { ptNode pT=pN->link; pN->link=pT->link; delete pT; } else return 1; return 0; } ptNode listRemove1st(ptNode pFirst) { pFirst=pFirst->link; return pFirst; } int listSave(ptNode pList, const char* sPath) { ofstream flSave(sPath); ptNode pN=pList; while(pN) { flSave << pN->name << endl; flSave << pN->number << endl; pN=pN->link; } return 0; } ptNode listLoad(const char* sPath) { ifstream flLoad(sPath); ptNode plist = new TNode; ptNode pN=plist; pN->link=pN; string t; while(flLoad >> t) { pN=pN->link; pN->link = new TNode; pN->name=t; flLoad >> t; pN->number=t; } delete pN->link; pN->link=NULL; return plist; }
true
6b1034ee113ef3942c6ab2c890f6e09fa092ddc3
C++
annerose/mempool
/mempool/newoperator.cpp
UTF-8
901
2.5625
3
[]
no_license
 #include "kmempool.h" KMemoryPool pool; void* operator new(size_t size, char* pszFileName) { //char szMsg[256] = {0}; //sprintf(szMsg, "%d,%s", line, file); return pool.Malloc(size, pszFileName); } void* operator new[](size_t nSize, char* pszFileName ) { //char szMsg[256] = {0}; //sprintf(szMsg, "%d,%s", nLineNum, pszFileName); return pool.Malloc(nSize, pszFileName); } void FreePool(void* ptr) { pool.Free(ptr); } //void operator delete(void* ptr) //{ // pool.Free(ptr); // //{ // // ::operator delete(ptr); // //} //} // // //void operator delete[](void* ptr) //{ // pool.Free(ptr); // //{ // // ::operator delete(ptr); // //} //} // 不会调用 void operator delete(void* p, char* pszFileName ) { //pool.Free(p); printf("operator delete\n"); } // 不会调用 void operator delete[](void* ptr, char* pszFileName ) { //pool.Free(ptr); printf("operator delete [] \n"); }
true
10acc14f1db1ee565dbaa81fcfe4542a54e9154d
C++
Shalinor/Artificial-Intelligence-for-games
/GraphTraversalExercises/GraphTraversalExercises/source/Graph.cpp
UTF-8
3,593
3.109375
3
[]
no_license
#include "Graph.h" //Searches the graph starting from the "start" node until one of the // "potential end node's" are found. // The resulting path is added to the "outPath" list. void Graph::FindDijkstrasPath(Node* start_, const std::list<Node*> &potentialEndNodes_)// , std::list<Node*> &outPath_) { //Reset the lists openList.clear(); closedList.clear(); //Reset the nodes for (auto iterator = nodes.begin(); iterator != nodes.end(); ++iterator) { (*iterator)->ClearDijkstrasValues(); } Node* endNode = NULL; Node* currentNode = NULL; openList.push_back(start_); while (!openList.empty()) { //Sort openList by Node.gScore openList.sort([](const Node* nodeA, const Node* nodeB){return nodeA->gScore < nodeB->gScore; }); currentNode = openList.front(); openList.pop_front(); //Process Node... for (auto iterator = potentialEndNodes_.begin(); iterator != potentialEndNodes_.end(); ++iterator) { endNode = (*iterator); break; //Only breaks out of for?? may just clear openList??? or after for, if(endNode){break;}??? } closedList.push_back(currentNode); for (auto iterator = currentNode->connections.begin(); iterator != currentNode->connections.end(); ++iterator) { bool inClosedList = false; bool inOpenList = false; //Test for presence within closedList for (auto cLIterator = closedList.begin(); cLIterator != closedList.end(); ++cLIterator) { if ((iterator->connection) == (*cLIterator)) { inClosedList = true; break; } } /* Taken out as other paths involving the same node are not nescesarily invalid <and I can't spell>??? Though the nodes gScore will get screwy... */ ////Test for presence within openList //for (auto oLIterator = openList.begin(); oLIterator != openList.end(); ++oLIterator) //{ // if ((iterator->connection) == (*oLIterator)) // { // inOpenList = true; // break; // } //} if (!inClosedList && !inOpenList) { iterator->connection->gScore = currentNode->gScore + iterator->cost; iterator->connection->parent = currentNode; openList.push_back(iterator->connection); } } } //Calculate Path std::list<Vector2> path; currentNode = endNode; while (currentNode != NULL) { path.push_front(currentNode->pos); currentNode = currentNode->parent; } for (auto iterator = path.begin(); iterator != path.end(); ++iterator) { printf("%f, %f\n", (*iterator).x, (*iterator).y); } /* Procedure FindPathDijkstras(startNode, List of potentialEndNodes) Let openList be a List of Nodes Let closedList be a List of Nodes Let endNode be a Node set to NULL Add startNode to openList While openList is not empty Sort openList by Node.gScore Let currentNode = first item in openList // Process the node, do what you want with it. EG: if currentNode is one of the potentialEnd endNode = currentNode break out of loop remove currentNode from openList Add currentNode to closedList for all connections c in currentNode Add c.connection to openList if not in closedList c.connection.gScore = currentNode.gScore + c.cost c.connection.parent = currentNode // Calculate Path Let path be a List of Vector2 Let currentNode = endNode; While currentNode != NULL Add currentNode.position to path currentNode = currentNode.parent */ } //Helper function, populates "outNodes" with nodes that are within a // circular area (xPos, yPos, radius) void Graph::FindNodesInRange(std::vector<Node*> &outNodes_, float xPos_, float yPos_, float radius_) { }
true
e4a8f9a1c08cdde4dbcfd1d736d184d0e6d028e2
C++
Maks-s/panzer-toy
/src/bullet.cpp
UTF-8
3,411
2.953125
3
[ "MIT" ]
permissive
#include "game.hpp" #include <memory> #include <vector> #include <glm/glm.hpp> #include <glm/gtc/constants.hpp> #include "bullet.hpp" #include "log.hpp" #include "map.hpp" #include "model.hpp" #include "shader.hpp" #include "enemy.hpp" namespace { Model bullet_mdl; std::vector<Bullet> bullets; } bool BulletManager::create(const glm::vec3& pos, float angle, const Game& game) { if (bullet_mdl.is_empty()) { bullet_mdl.load("models/bullet.dae"); } if (game.collision_check(pos) != MapCollision::none) { Log::error("Invalid bullet position"); return false; } const float speed = 12.0f; Bullet bullet = {}; bullet.velocity = glm::vec3(glm::sin(angle) * speed, 0.0f, glm::cos(angle) * speed); bullet.position = pos; bullet.angle = angle; bullet.remaining_hit = 3; bullets.push_back(bullet); return true; } namespace { /** * @brief Get bullet angle relative to wall's origin * * @return Angle at which the bullet is, relative to the center of the wall * @retval -100.0f If there's no collision */ float get_collision_angle( const Game& game, const glm::vec3& new_pos, const glm::vec3& old_pos ) { MapCollision collision = game.collision_check(new_pos); if (collision == MapCollision::none) { return -100.0f; } if (collision == MapCollision::right_or_left) { return 0.0f; } else if (collision == MapCollision::up_or_down) { return glm::pi<float>(); } float x, y; if (collision == MapCollision::upper_left || collision == MapCollision::bottom_left) { x = round(new_pos.z - 0.35f); } else { x = round(new_pos.z + 0.35f); } if (collision == MapCollision::upper_left || collision == MapCollision::upper_right) { y = round(new_pos.x - 0.35f); } else { y = round(new_pos.x + 0.35f); } x = old_pos.z - x; y = old_pos.x - y; return glm::atan(y, x); } void draw(const Bullet& bullet, const Shader& shader, const glm::mat4& VP) { bullet_mdl.set_angle(bullet.angle); bullet_mdl.set_pos(bullet.position); bullet_mdl.draw(shader, VP); } } /** @brief Function called each frame */ void BulletManager::frame(Game& game, const Shader& shader, const glm::mat4& VP) { for (auto bullet = bullets.begin(); bullet != bullets.end(); ++bullet) { glm::vec3 new_pos = bullet->position + bullet->velocity * game.get_delta_time(); if (game.player_bullet_collision(new_pos)) { return; // Game has been reset, return } if (EnemyManager::bullet_collision(game, new_pos)) { if (bullets.empty()) { return; // No bullets, game has been reset } bullet = bullets.erase(bullet) - 1; continue; } float angle = get_collision_angle(game, new_pos, bullet->position); if (angle == -100.0f) { bullet->position = new_pos; draw(*bullet, shader, VP); continue; } if (bullet->remaining_hit-- <= 0) { bullet = bullets.erase(bullet) - 1; continue; } // Check if the bullet hit the wall right/left or up/down const float pi = glm::pi<float>(); const float pi_4 = glm::quarter_pi<float>(); if ( (angle > -pi_4 && angle < pi_4) || (angle > -pi && angle < pi_4-pi) || (angle > pi-pi_4 && angle < pi) ) { bullet->velocity.z *= -1.0f; // right/left } else { bullet->velocity.x *= -1.0f; // up/down } bullet->angle = glm::atan(bullet->velocity.x, bullet->velocity.z); draw(*bullet, shader, VP); } } void BulletManager::clear() { bullets.clear(); }
true
2e4f40e02912f8c91eba4ebf5a60df70e47815e7
C++
willmoon/CPP_Primer
/Chapter_1/ifcount.cpp
UTF-8
742
3.9375
4
[]
no_license
/* *从窗口读入整数,计算整数出现的次数(相同数必须出现在一起。。。。) */ #include <iostream> int main(int argc, char const *argv[]) { //currval是正在统计的数;新读入的值将存放在val int currval = 0, val = 0; //读取第一个数 if (std::cin >> currval) { int cnt = 1; //记录当前值得个数 while (std::cin >> val) //读取剩余的数 { if (val == currval) { ++ cnt; } else { std::cout << currval << " occurs " << cnt << " times " <<std:: endl; currval = val; //重新记值 cnt = 1; } } //打印最后一个值的个数 std::cout << currval << " occurs " << cnt << " times " << std::endl; } return 0; }
true
b4fdf5391485262ea7266fedd02061a90ad98516
C++
baocvcv/thu-oop-exercises
/week5/Problem1/Edge.h
UTF-8
1,853
3.984375
4
[]
no_license
#pragma once /** * Edge class. * Stores an edge and supports basic operations. */ class Edge{ /// One vertex of the edge. int v; /// Another vertec of the edge. int w; /// Weight of the edge. double weight; /// Constant used in compare() static const double mu; public: /** * @brief Construct a new Edge object * * @param _v a vertex * @param _w another vertex * @param _weight weight of the edge */ Edge(int _v, int _w, double _weight = -1.0): v(_v), w(_w), weight(_weight) {}; /** * @brief Set the v object * * @param _v */ void set_v(int _v) { v = _v; } /** * @brief Set the w object * * @param _w */ void set_w(int _w) { w = _w; } /** * @brief Set the weight object * * @param _weight */ void set_weight(double _weight) { weight = _weight; } /** * @brief Get the v object * * @return int */ int get_v() const { return v; } /** * @brief Get the w object * * @return int */ int get_w() const { return w; } /** * @brief Get the weight object * * @return double */ double get_weight() const { return weight; } /** * @brief Get the other vertex * * @param vertex * @return int the id of the other vertex */ int get_other(int vertex){ if (vertex == v) return w; else return v; }; /** * @brief Compare with another edge. * * @param f * @return true weight is smaller * @return false */ bool compare_to(Edge f); /** * @brief Compare two edges. * * @param e * @param f * @return true * @return false */ static bool compare(Edge e, Edge f); };
true
2e328211dab95d2dc02501d1baec85de1dbc3802
C++
sajal243/DataStructures
/count_sort.cpp
UTF-8
699
3.265625
3
[]
no_license
#include<iostream> using namespace std; void countSort(int a[], int n){ int k = a[0]; for(int i=0; i<n; i++){ k = max(k, a[i]); } cout << k << endl; int count[10] = {0}; for(int i=0; i<n; i++){ count[a[i]]++; } for(int i=1; i<=k; i++){ count[i] += count[i-1] ; //cout << count[i] << endl; } int b[n]; for(int i = n-1; i>=0; i--){ b[--count[a[i]]] = a[i]; } for(int i =0; i<n; i++){ a[i] = b[i]; } } int main(){ int a[] = {1,3,2,3,4,1,6,4,3}; countSort(a,9); for(int i=0; i<9; i++){ cout << a[i] << " "; } return 0; }
true
0268ca96ffe5f0c77178ae1f44152123dd102004
C++
CarlBye/LeetCode
/src/0001_Two_Sum/two_sum.cpp
UTF-8
420
3.046875
3
[]
no_license
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int size = nums.size(); vector<int> s(2,0); for(int i = 0;i < size;i++) { for(int j = i+1;j < size;j++) { if(nums[i] + nums[j] == target){ s[0] = i; s[1] = j; } } } return s; } };
true
158820ddd0469c031a9a9c87116aa332c9e9f8bc
C++
lzw3232/car
/framework/src/window/Window.cpp
UTF-8
2,764
2.65625
3
[]
no_license
#include "../../include/window/Window.h" #include "../../include/log/Log.h" #include <iostream> using namespace lzw; Window::Window() { } Window::Window(int windowWidth,int windowHeight,const char *windowName){ this->windowWidth=windowWidth; this->windowHeight=windowHeight; this->windowName=(char *)windowName; } void Window::OnEvent(SDL_Event* Event) { } bool Window::Init() { if(SDL_Init(SDL_INIT_VIDEO) < 0) { Log("Unable to Init SDL: %s", SDL_GetError()); return false; } if(!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) { Log("Unable to Init hinting: %s", SDL_GetError()); } if((window = SDL_CreateWindow(windowName, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, SDL_WINDOW_SHOWN)) == NULL) { Log("Unable to create SDL Window: %s", SDL_GetError()); return false; } primarySurface = SDL_GetWindowSurface(window); if((renderer = SDL_GetRenderer(window)) == NULL) { Log("Unable to create renderer"); return false; } SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); return true; } void Window::Loop() { } void Window::Render() { SDL_RenderClear(renderer); // GAME RENDER AREA for(int i = 0; i< this->pixelMtrix->getHeight(); i++){ for(int j = 0; j<this->pixelMtrix->getWidth(); j++){ SDL_SetRenderDrawColor(renderer, pixelMtrix->getPixel()[i][j].getColor()->getR(), pixelMtrix->getPixel()[i][j].getColor()->getG(), pixelMtrix->getPixel()[i][j].getColor()->getB(), 255); SDL_RenderDrawPoint(renderer, j, i); } } SDL_RenderPresent(renderer); } void Window::Cleanup() { if(renderer) { SDL_DestroyRenderer(renderer); renderer = NULL; } if(window) { SDL_DestroyWindow(window); window = NULL; } SDL_Quit(); } int Window::Execute() { if(!Init()) return 0; SDL_Event Event; while(running) { while(SDL_PollEvent(&Event) != 0) { OnEvent(&Event); if(Event.type == SDL_QUIT) running = false; } Loop(); Render(); // SDL_Delay(1); // Breath } Cleanup(); return 1; } void Window::Run(){ this->Execute(); } int Window::GetWindowWidth() { return windowWidth; } int Window::GetWindowHeight() { return windowHeight; }
true
a4fa4dbc8bad59c2c8791b310d28c886476a167c
C++
hyrise/hyrise
/src/lib/expression/in_expression.hpp
UTF-8
873
2.75
3
[ "MIT" ]
permissive
#pragma once #include "abstract_predicate_expression.hpp" namespace hyrise { /** * SQL's IN */ class InExpression : public AbstractPredicateExpression { public: InExpression(const PredicateCondition init_predicate_condition, const std::shared_ptr<AbstractExpression>& operand, const std::shared_ptr<AbstractExpression>& set); /** * Utility for better readability * @return predicate_condition == PredicateCondition::NotIn */ bool is_negated() const; const std::shared_ptr<AbstractExpression>& operand() const; const std::shared_ptr<AbstractExpression>& set() const; std::shared_ptr<AbstractExpression> _on_deep_copy( std::unordered_map<const AbstractOperator*, std::shared_ptr<AbstractOperator>>& copied_ops) const override; std::string description(const DescriptionMode mode) const override; }; } // namespace hyrise
true
da9f1f360c1887c3a375836aa1b3c23eacb2543d
C++
STEllAR-GROUP/hpx
/libs/core/algorithms/include/hpx/parallel/container_algorithms/merge.hpp
UTF-8
55,450
3.109375
3
[ "BSL-1.0", "LicenseRef-scancode-free-unknown" ]
permissive
// Copyright (c) 2017 Taeguk Kwon // Copyright (c) 2022 Dimitra Karatza // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /// \file parallel/container_algorithms/merge.hpp #pragma once #if defined(DOXYGEN) namespace hpx { namespace ranges { // clang-format off /// Merges two sorted ranges [first1, last1) and [first2, last2) /// into one sorted range beginning at \a dest. The order of /// equivalent elements in the each of original two ranges is preserved. /// For equivalent elements in the original two ranges, the elements from /// the first range precede the elements from the second range. /// The destination range cannot overlap with either of the input ranges. /// /// \note Complexity: Performs /// O(std::distance(first1, last1) + std::distance(first2, last2)) /// applications of the comparison \a comp and the each projection. /// /// \tparam ExPolicy The type of the execution policy to use (deduced). /// It describes the manner in which the execution /// of the algorithm may be parallelized and the manner /// in which it executes the assignments. /// \tparam Rng1 The type of the first source range used (deduced). /// The iterators extracted from this range type must /// meet the requirements of an random access iterator. /// \tparam Rng2 The type of the second source range used (deduced). /// The iterators extracted from this range type must /// meet the requirements of an random access iterator. /// \tparam Iter3 The type of the iterator representing the /// destination range (deduced). /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Comp The type of the function/function object to use /// (deduced). Unlike its sequential form, the parallel /// overload of \a merge requires \a Comp to meet the /// requirements of \a CopyConstructible. This defaults /// to std::less<> /// \tparam Proj1 The type of an optional projection function to be /// used for elements of the first range. This defaults /// to \a hpx::identity /// \tparam Proj2 The type of an optional projection function to be /// used for elements of the second range. This defaults /// to \a hpx::identity /// /// \param policy The execution policy to use for the scheduling of /// the iterations. /// \param rng1 Refers to the first range of elements the algorithm /// will be applied to. /// \param rng2 Refers to the second range of elements the algorithm /// will be applied to. /// \param dest Refers to the beginning of the destination range. /// \param comp \a comp is a callable object which returns true if /// the first argument is less than the second, /// and false otherwise. The signature of this /// comparison should be equivalent to: /// \code /// bool comp(const Type1 &a, const Type2 &b); /// \endcode \n /// The signature does not need to have const&, but /// the function must not modify the objects passed to /// it. The types \a Type1 and \a Type2 must be such that /// objects of types \a Iter1 and \a Iter2 can be /// dereferenced and then implicitly converted to /// both \a Type1 and \a Type2 /// \param proj1 Specifies the function (or function object) which /// will be invoked for each of the elements of the /// first range as a projection operation before the /// actual comparison \a comp is invoked. /// \param proj2 Specifies the function (or function object) which /// will be invoked for each of the elements of the /// second range as a projection operation before the /// actual comparison \a comp is invoked. /// /// The assignments in the parallel \a merge algorithm invoked with /// an execution policy object of type \a sequenced_policy /// execute in sequential order in the calling thread. /// /// The assignments in the parallel \a merge algorithm invoked with /// an execution policy object of type \a parallel_policy or /// \a parallel_task_policy are permitted to execute in an unordered /// fashion in unspecified threads, and indeterminately sequenced /// within each thread. /// /// \returns The \a merge algorithm returns a /// \a hpx::future<merge_result<Iter1, Iter2, Iter3>> /// if the execution policy is of type /// \a sequenced_task_policy or /// \a parallel_task_policy and returns /// \a merge_result<Iter1, Iter2, Iter3> otherwise. /// The \a merge algorithm returns the tuple of /// the source iterator \a last1, /// the source iterator \a last2, /// the destination iterator to the end of the \a dest range. /// template <typename ExPolicy, typename Rng1, typename Rng2, typename Iter3, typename Comp = hpx::ranges::less, typename Proj1 = hpx::identity, typename Proj2 = hpx::identity> typename hpx::parallel::util::detail::algorithm_result<ExPolicy, hpx::ranges::merge_result< hpx::traits::range_iterator_t<Rng1>, hpx::traits::range_iterator_t<Rng2>, Iter3>> merge(ExPolicy&& policy, Rng1&& rng1, Rng2&& rng2, Iter3 dest, Comp&& comp = Comp(), Proj1&& proj1 = Proj1(), Proj2&& proj2 = Proj2()); /// Merges two sorted ranges [first1, last1) and [first2, last2) /// into one sorted range beginning at \a dest. The order of /// equivalent elements in the each of original two ranges is preserved. /// For equivalent elements in the original two ranges, the elements from /// the first range precede the elements from the second range. /// The destination range cannot overlap with either of the input ranges. /// /// \note Complexity: Performs /// O(std::distance(first1, last1) + std::distance(first2, last2)) /// applications of the comparison \a comp and the each projection. /// /// \tparam ExPolicy The type of the execution policy to use (deduced). /// It describes the manner in which the execution /// of the algorithm may be parallelized and the manner /// in which it executes the assignments. /// \tparam Iter1 The type of the source iterators used (deduced) /// representing the first sequence. /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Sent1 The type of the end source iterators used (deduced). /// This iterator type must meet the requirements of an /// sentinel for Iter1. /// \tparam Iter2 The type of the source iterators used (deduced) /// representing the second sequence. /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Sent2 The type of the end source iterators used (deduced) /// representing the second sequence. /// This iterator type must meet the requirements of an /// sentinel for Iter2. /// \tparam Iter3 The type of the iterator representing the /// destination range (deduced). /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Comp The type of the function/function object to use /// (deduced). Unlike its sequential form, the parallel /// overload of \a merge requires \a Comp to meet the /// requirements of \a CopyConstructible. This defaults /// to std::less<> /// \tparam Proj1 The type of an optional projection function to be /// used for elements of the first range. This defaults /// to \a hpx::identity /// \tparam Proj2 The type of an optional projection function to be /// used for elements of the second range. This defaults /// to \a hpx::identity /// /// \param policy The execution policy to use for the scheduling of /// the iterations. /// \param first1 Refers to the beginning of the sequence of elements /// of the first range the algorithm will be applied to. /// \param last1 Refers to the end of the sequence of elements of /// the first range the algorithm will be applied to. /// \param first2 Refers to the beginning of the sequence of elements /// of the second range the algorithm will be applied to. /// \param last2 Refers to the end of the sequence of elements of /// the second range the algorithm will be applied to. /// \param dest Refers to the beginning of the destination range. /// \param comp \a comp is a callable object which returns true if /// the first argument is less than the second, /// and false otherwise. The signature of this /// comparison should be equivalent to: /// \code /// bool comp(const Type1 &a, const Type2 &b); /// \endcode \n /// The signature does not need to have const&, but /// the function must not modify the objects passed to /// it. The types \a Type1 and \a Type2 must be such that /// objects of types \a Iter1 and \a Iter2 can be /// dereferenced and then implicitly converted to /// both \a Type1 and \a Type2 /// \param proj1 Specifies the function (or function object) which /// will be invoked for each of the elements of the /// first range as a projection operation before the /// actual comparison \a comp is invoked. /// \param proj2 Specifies the function (or function object) which /// will be invoked for each of the elements of the /// second range as a projection operation before the /// actual comparison \a comp is invoked. /// /// The assignments in the parallel \a merge algorithm invoked with /// an execution policy object of type \a sequenced_policy /// execute in sequential order in the calling thread. /// /// The assignments in the parallel \a merge algorithm invoked with /// an execution policy object of type \a parallel_policy or /// \a parallel_task_policy are permitted to execute in an unordered /// fashion in unspecified threads, and indeterminately sequenced /// within each thread. /// /// \returns The \a merge algorithm returns a /// \a hpx::future<merge_result<Iter1, Iter2, Iter3>> /// if the execution policy is of type /// \a sequenced_task_policy or /// \a parallel_task_policy and returns /// \a merge_result<Iter1, Iter2, Iter3> otherwise. /// The \a merge algorithm returns the tuple of /// the source iterator \a last1, /// the source iterator \a last2, /// the destination iterator to the end of the \a dest range. /// template <typename ExPolicy, typename Iter1, typename Sent1, typename Iter2, typename Sent2, typename Iter3, typename Comp = hpx::ranges::less, typename Proj1 = hpx::identity, typename Proj2 = hpx::identity> typename hpx::parallel::util::detail::algorithm_result<ExPolicy, hpx::ranges::merge_result<Iter1, Iter2, Iter3>>::type merge(ExPolicy&& policy, Iter1 first1, Sent1 last1, Iter2 first2, Sent2 last2, Iter3 dest, Comp&& comp = Comp(), Proj1&& proj1 = Proj1(), Proj2&& proj2 = Proj2()); /// Merges two sorted ranges [first1, last1) and [first2, last2) /// into one sorted range beginning at \a dest. The order of /// equivalent elements in the each of original two ranges is preserved. /// For equivalent elements in the original two ranges, the elements from /// the first range precede the elements from the second range. /// The destination range cannot overlap with either of the input ranges. /// /// \note Complexity: Performs /// O(std::distance(first1, last1) + std::distance(first2, last2)) /// applications of the comparison \a comp and the each projection. /// /// \tparam Rng1 The type of the first source range used (deduced). /// The iterators extracted from this range type must /// meet the requirements of an random access iterator. /// \tparam Rng2 The type of the second source range used (deduced). /// The iterators extracted from this range type must /// meet the requirements of an random access iterator. /// \tparam Iter3 The type of the iterator representing the /// destination range (deduced). /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Comp The type of the function/function object to use /// (deduced). Unlike its sequential form, the parallel /// overload of \a merge requires \a Comp to meet the /// requirements of \a CopyConstructible. This defaults /// to std::less<> /// \tparam Proj1 The type of an optional projection function to be /// used for elements of the first range. This defaults /// to \a hpx::identity /// \tparam Proj2 The type of an optional projection function to be /// used for elements of the second range. This defaults /// to \a hpx::identity /// /// \param rng1 Refers to the first range of elements the algorithm /// will be applied to. /// \param rng2 Refers to the second range of elements the algorithm /// will be applied to. /// \param dest Refers to the beginning of the destination range. /// \param comp \a comp is a callable object which returns true if /// the first argument is less than the second, /// and false otherwise. The signature of this /// comparison should be equivalent to: /// \code /// bool comp(const Type1 &a, const Type2 &b); /// \endcode \n /// The signature does not need to have const&, but /// the function must not modify the objects passed to /// it. The types \a Type1 and \a Type2 must be such that /// objects of types \a Iter1 and \a Iter2 can be /// dereferenced and then implicitly converted to /// both \a Type1 and \a Type2 /// \param proj1 Specifies the function (or function object) which /// will be invoked for each of the elements of the /// first range as a projection operation before the /// actual comparison \a comp is invoked. /// \param proj2 Specifies the function (or function object) which /// will be invoked for each of the elements of the /// second range as a projection operation before the /// actual comparison \a comp is invoked. /// /// \returns The \a merge algorithm returns /// \a merge_result<Iter1, Iter2, Iter3>. /// The \a merge algorithm returns the tuple of /// the source iterator \a last1, /// the source iterator \a last2, /// the destination iterator to the end of the \a dest range. /// template <typename Rng1, typename Rng2, typename Iter3, typename Comp = hpx::ranges::less, typename Proj1 = hpx::identity, typename Proj2 = hpx::identity> hpx::ranges::merge_result< hpx::traits::range_iterator_t<Rng1>, hpx::traits::range_iterator_t<Rng2>, Iter3> merge(Rng1&& rng1, Rng2&& rng2, Iter3 dest, Comp&& comp = Comp(), Proj1&& proj1 = Proj1(), Proj2&& proj2 = Proj2()); /// Merges two sorted ranges [first1, last1) and [first2, last2) /// into one sorted range beginning at \a dest. The order of /// equivalent elements in the each of original two ranges is preserved. /// For equivalent elements in the original two ranges, the elements from /// the first range precede the elements from the second range. /// The destination range cannot overlap with either of the input ranges. /// /// \note Complexity: Performs /// O(std::distance(first1, last1) + std::distance(first2, last2)) /// applications of the comparison \a comp and the each projection. /// /// \tparam Iter1 The type of the source iterators used (deduced) /// representing the first sequence. /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Sent1 The type of the end source iterators used (deduced). /// This iterator type must meet the requirements of an /// sentinel for Iter1. /// \tparam Iter2 The type of the source iterators used (deduced) /// representing the second sequence. /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Sent2 The type of the end source iterators used (deduced) /// representing the second sequence. /// This iterator type must meet the requirements of an /// sentinel for Iter2. /// \tparam Iter3 The type of the iterator representing the /// destination range (deduced). /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Comp The type of the function/function object to use /// (deduced). Unlike its sequential form, the parallel /// overload of \a merge requires \a Comp to meet the /// requirements of \a CopyConstructible. This defaults /// to std::less<> /// \tparam Proj1 The type of an optional projection function to be /// used for elements of the first range. This defaults /// to \a hpx::identity /// \tparam Proj2 The type of an optional projection function to be /// used for elements of the second range. This defaults /// to \a hpx::identity /// /// \param first1 Refers to the beginning of the sequence of elements /// of the first range the algorithm will be applied to. /// \param last1 Refers to the end of the sequence of elements of /// the first range the algorithm will be applied to. /// \param first2 Refers to the beginning of the sequence of elements /// of the second range the algorithm will be applied to. /// \param last2 Refers to the end of the sequence of elements of /// the second range the algorithm will be applied to. /// \param dest Refers to the beginning of the destination range. /// \param comp \a comp is a callable object which returns true if /// the first argument is less than the second, /// and false otherwise. The signature of this /// comparison should be equivalent to: /// \code /// bool comp(const Type1 &a, const Type2 &b); /// \endcode \n /// The signature does not need to have const&, but /// the function must not modify the objects passed to /// it. The types \a Type1 and \a Type2 must be such that /// objects of types \a Iter1 and \a Iter2 can be /// dereferenced and then implicitly converted to /// both \a Type1 and \a Type2 /// \param proj1 Specifies the function (or function object) which /// will be invoked for each of the elements of the /// first range as a projection operation before the /// actual comparison \a comp is invoked. /// \param proj2 Specifies the function (or function object) which /// will be invoked for each of the elements of the /// second range as a projection operation before the /// actual comparison \a comp is invoked. /// /// \returns The \a merge algorithm returns /// \a merge_result<Iter1, Iter2, Iter3>. /// The \a merge algorithm returns the tuple of /// the source iterator \a last1, /// the source iterator \a last2, /// the destination iterator to the end of the \a dest range. /// template <typename Iter1, typename Sent1, typename Iter2, typename Sent2, typename Iter3, typename Comp = hpx::ranges::less, typename Proj1 = hpx::identity, typename Proj2 = hpx::identity> hpx::ranges::merge_result<Iter1, Iter2, Iter3> merge(Iter1 first1, Sent1 last1, Iter2 first2, Sent2 last2, Iter3 dest, Comp&& comp = Comp(), Proj1&& proj1 = Proj1(), Proj2&& proj2 = Proj2()); /// Merges two consecutive sorted ranges [first, middle) and /// [middle, last) into one sorted range [first, last). The order of /// equivalent elements in the each of original two ranges is preserved. /// For equivalent elements in the original two ranges, the elements from /// the first range precede the elements from the second range. /// /// \note Complexity: Performs O(std::distance(first, last)) /// applications of the comparison \a comp and the each projection. /// /// \tparam ExPolicy The type of the execution policy to use (deduced). /// It describes the manner in which the execution /// of the algorithm may be parallelized and the manner /// in which it executes the assignments. /// \tparam Rng The type of the source range used (deduced). /// The iterators extracted from this range type must /// meet the requirements of an random access iterator. /// \tparam Iter The type of the source iterators used (deduced). /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Comp The type of the function/function object to use /// (deduced). Unlike its sequential form, the parallel /// overload of \a inplace_merge requires \a Comp /// to meet the requirements of \a CopyConstructible. /// This defaults to std::less<> /// \tparam Proj The type of an optional projection function. This /// defaults to \a hpx::identity /// /// \param policy The execution policy to use for the scheduling of /// the iterations. /// \param rng Refers to the range of elements the algorithm /// will be applied to. /// \param middle Refers to the end of the first sorted range and /// the beginning of the second sorted range /// the algorithm will be applied to. /// \param comp \a comp is a callable object which returns true if /// the first argument is less than the second, /// and false otherwise. The signature of this /// comparison should be equivalent to: /// \code /// bool comp(const Type1 &a, const Type2 &b); /// \endcode \n /// The signature does not need to have const&, but /// the function must not modify the objects passed to /// it. The types \a Type1 and \a Type2 must be /// such that objects of types \a Iter can be /// dereferenced and then implicitly converted to both /// \a Type1 and \a Type2 /// \param proj Specifies the function (or function object) which /// will be invoked for each of the elements as a /// projection operation before the actual predicate /// \a is invoked. /// /// The assignments in the parallel \a inplace_merge algorithm invoked /// with an execution policy object of type \a sequenced_policy /// execute in sequential order in the calling thread. /// /// The assignments in the parallel \a inplace_merge algorithm invoked /// with an execution policy object of type \a parallel_policy or /// \a parallel_task_policy are permitted to execute in an unordered /// fashion in unspecified threads, and indeterminately sequenced /// within each thread. /// /// \returns The \a inplace_merge algorithm returns a /// \a hpx::future<Iter> if the execution policy is of type /// \a sequenced_task_policy or \a parallel_task_policy /// and returns \a Iter otherwise. /// The \a inplace_merge algorithm returns /// the source iterator \a last /// template <typename ExPolicy, typename Rng, typename Iter, typename Comp = hpx::ranges::less, typename Proj = hpx::identity> hpx::parallel::util::detail::algorithm_result_t<ExPolicy, Iter> inplace_merge(ExPolicy&& policy, Rng&& rng, Iter middle, Comp&& comp = Comp(), Proj&& proj = Proj()); /// Merges two consecutive sorted ranges [first, middle) and /// [middle, last) into one sorted range [first, last). The order of /// equivalent elements in the each of original two ranges is preserved. /// For equivalent elements in the original two ranges, the elements from /// the first range precede the elements from the second range. /// /// \note Complexity: Performs O(std::distance(first, last)) /// applications of the comparison \a comp and the each projection. /// /// \tparam ExPolicy The type of the execution policy to use (deduced). /// It describes the manner in which the execution /// of the algorithm may be parallelized and the manner /// in which it executes the assignments. /// \tparam Iter The type of the source iterators used (deduced). /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Sent The type of the end source iterators used (deduced). /// This iterator type must meet the requirements of an /// sentinel for Iter1. /// \tparam Comp The type of the function/function object to use /// (deduced). Unlike its sequential form, the parallel /// overload of \a inplace_merge requires \a Comp /// to meet the requirements of \a CopyConstructible. /// This defaults to std::less<> /// \tparam Proj The type of an optional projection function. This /// defaults to \a hpx::identity /// /// \param policy The execution policy to use for the scheduling of /// the iterations. /// \param first Refers to the beginning of the first sorted range /// the algorithm will be applied to. /// \param middle Refers to the end of the first sorted range and /// the beginning of the second sorted range /// the algorithm will be applied to. /// \param last Refers to the end of the second sorted range /// the algorithm will be applied to. /// \param comp \a comp is a callable object which returns true if /// the first argument is less than the second, /// and false otherwise. The signature of this /// comparison should be equivalent to: /// \code /// bool comp(const Type1 &a, const Type2 &b); /// \endcode \n /// The signature does not need to have const&, but /// the function must not modify the objects passed to /// it. The types \a Type1 and \a Type2 must be /// such that objects of types \a Iter can be /// dereferenced and then implicitly converted to both /// \a Type1 and \a Type2 /// \param proj Specifies the function (or function object) which /// will be invoked for each of the elements as a /// projection operation before the actual predicate /// \a is invoked. /// /// The assignments in the parallel \a inplace_merge algorithm invoked /// with an execution policy object of type \a sequenced_policy /// execute in sequential order in the calling thread. /// /// The assignments in the parallel \a inplace_merge algorithm invoked /// with an execution policy object of type \a parallel_policy or /// \a parallel_task_policy are permitted to execute in an unordered /// fashion in unspecified threads, and indeterminately sequenced /// within each thread. /// /// \returns The \a inplace_merge algorithm returns a /// \a hpx::future<Iter> if the execution policy is of type /// \a sequenced_task_policy or \a parallel_task_policy /// and returns \a Iter otherwise. /// The \a inplace_merge algorithm returns /// the source iterator \a last /// template <typename ExPolicy, typename Iter, typename Sent, typename Comp = hpx::ranges::less, typename Proj = hpx::identity> hpx::parallel::util::detail::algorithm_result_t<ExPolicy, Iter> inplace_merge(ExPolicy&& policy, Iter first, Iter middle, Sent last, Comp&& comp = Comp(), Proj&& proj = Proj()); /// Merges two consecutive sorted ranges [first, middle) and /// [middle, last) into one sorted range [first, last). The order of /// equivalent elements in the each of original two ranges is preserved. /// For equivalent elements in the original two ranges, the elements from /// the first range precede the elements from the second range. /// /// \note Complexity: Performs O(std::distance(first, last)) /// applications of the comparison \a comp and the each projection. /// /// \tparam Rng The type of the source range used (deduced). /// The iterators extracted from this range type must /// meet the requirements of an random access iterator. /// \tparam Iter The type of the source iterators used (deduced). /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Comp The type of the function/function object to use /// (deduced). Unlike its sequential form, the parallel /// overload of \a inplace_merge requires \a Comp /// to meet the requirements of \a CopyConstructible. /// This defaults to std::less<> /// \tparam Proj The type of an optional projection function. This /// defaults to \a hpx::identity /// /// \param rng Refers to the range of elements the algorithm /// will be applied to. /// \param middle Refers to the end of the first sorted range and /// the beginning of the second sorted range /// the algorithm will be applied to. /// \param comp \a comp is a callable object which returns true if /// the first argument is less than the second, /// and false otherwise. The signature of this /// comparison should be equivalent to: /// \code /// bool comp(const Type1 &a, const Type2 &b); /// \endcode \n /// The signature does not need to have const&, but /// the function must not modify the objects passed to /// it. The types \a Type1 and \a Type2 must be /// such that objects of types \a Iter can be /// dereferenced and then implicitly converted to both /// \a Type1 and \a Type2 /// \param proj Specifies the function (or function object) which /// will be invoked for each of the elements as a /// projection operation before the actual predicate /// \a is invoked. /// /// \returns The \a inplace_merge algorithm returns \a Iter. /// The \a inplace_merge algorithm returns /// the source iterator \a last /// template <typename Rng, typename Iter, typename Comp = hpx::ranges::less, typename Proj = hpx::identity> Iter inplace_merge(Rng&& rng, Iter middle, Comp&& comp = Comp(), Proj&& proj = Proj()); /// Merges two consecutive sorted ranges [first, middle) and /// [middle, last) into one sorted range [first, last). The order of /// equivalent elements in the each of original two ranges is preserved. /// For equivalent elements in the original two ranges, the elements from /// the first range precede the elements from the second range. /// /// \note Complexity: Performs O(std::distance(first, last)) /// applications of the comparison \a comp and the each projection. /// /// \tparam Iter The type of the source iterators used (deduced). /// This iterator type must meet the requirements of an /// random access iterator. /// \tparam Sent The type of the end source iterators used (deduced). /// This iterator type must meet the requirements of an /// sentinel for Iter1. /// \tparam Comp The type of the function/function object to use /// (deduced). Unlike its sequential form, the parallel /// overload of \a inplace_merge requires \a Comp /// to meet the requirements of \a CopyConstructible. /// This defaults to std::less<> /// \tparam Proj The type of an optional projection function. This /// defaults to \a hpx::identity /// /// \param first Refers to the beginning of the first sorted range /// the algorithm will be applied to. /// \param middle Refers to the end of the first sorted range and /// the beginning of the second sorted range /// the algorithm will be applied to. /// \param last Refers to the end of the second sorted range /// the algorithm will be applied to. /// \param comp \a comp is a callable object which returns true if /// the first argument is less than the second, /// and false otherwise. The signature of this /// comparison should be equivalent to: /// \code /// bool comp(const Type1 &a, const Type2 &b); /// \endcode \n /// The signature does not need to have const&, but /// the function must not modify the objects passed to /// it. The types \a Type1 and \a Type2 must be /// such that objects of types \a Iter can be /// dereferenced and then implicitly converted to both /// \a Type1 and \a Type2 /// \param proj Specifies the function (or function object) which /// will be invoked for each of the elements as a /// projection operation before the actual predicate /// \a is invoked. /// /// \returns The \a inplace_merge algorithm \a Iter. /// The \a inplace_merge algorithm returns /// the source iterator \a last /// template <typename Iter, typename Sent, typename Comp = hpx::ranges::less, typename Proj = hpx::identity> Iter inplace_merge(Iter first, Iter middle, Sent last, Comp&& comp = Comp(), Proj&& proj = Proj()); // clang-format on }} // namespace hpx::ranges #else // DOXYGEN #include <hpx/config.hpp> #include <hpx/algorithms/traits/projected.hpp> #include <hpx/algorithms/traits/projected_range.hpp> #include <hpx/concepts/concepts.hpp> #include <hpx/executors/execution_policy.hpp> #include <hpx/iterator_support/range.hpp> #include <hpx/iterator_support/traits/is_iterator.hpp> #include <hpx/iterator_support/traits/is_sentinel_for.hpp> #include <hpx/parallel/algorithms/merge.hpp> #include <hpx/parallel/util/detail/algorithm_result.hpp> #include <hpx/parallel/util/detail/sender_util.hpp> #include <hpx/parallel/util/result_types.hpp> #include <type_traits> #include <utility> namespace hpx::ranges { template <typename I1, typename I2, typename O> using merge_result = parallel::util::in_in_out_result<I1, I2, O>; /////////////////////////////////////////////////////////////////////////// // CPO for hpx::ranges::merge inline constexpr struct merge_t final : hpx::detail::tag_parallel_algorithm<merge_t> { private: // clang-format off template <typename ExPolicy, typename Rng1, typename Rng2, typename Iter3, typename Comp = hpx::ranges::less, typename Proj1 = hpx::identity, typename Proj2 = hpx::identity, HPX_CONCEPT_REQUIRES_( hpx::is_execution_policy_v<ExPolicy> && hpx::traits::is_range_v<Rng1> && hpx::parallel::traits::is_projected_range_v<Proj1, Rng1> && hpx::traits::is_range_v<Rng2> && hpx::parallel::traits::is_projected_range_v<Proj2, Rng2> && hpx::traits::is_iterator_v<Iter3> && hpx::parallel::traits::is_indirect_callable_v<ExPolicy, Comp, hpx::parallel::traits::projected_range<Proj1, Rng1>, hpx::parallel::traits::projected_range<Proj2, Rng2> > )> // clang-format on friend hpx::parallel::util::detail::algorithm_result_t<ExPolicy, hpx::ranges::merge_result<hpx::traits::range_iterator_t<Rng1>, hpx::traits::range_iterator_t<Rng2>, Iter3>> tag_fallback_invoke(merge_t, ExPolicy&& policy, Rng1&& rng1, Rng2&& rng2, Iter3 dest, Comp comp = Comp(), Proj1 proj1 = Proj1(), Proj2 proj2 = Proj2()) { using iterator_type1 = hpx::traits::range_iterator_t<Rng1>; using iterator_type2 = hpx::traits::range_iterator_t<Rng2>; static_assert( hpx::traits::is_random_access_iterator_v<iterator_type1>, "Required at least random access iterator."); static_assert( hpx::traits::is_random_access_iterator_v<iterator_type2>, "Requires at least random access iterator."); static_assert(hpx::traits::is_random_access_iterator_v<Iter3>, "Requires at least random access iterator."); using result_type = hpx::ranges::merge_result<iterator_type1, iterator_type2, Iter3>; return hpx::parallel::detail::merge<result_type>().call( HPX_FORWARD(ExPolicy, policy), hpx::util::begin(rng1), hpx::util::end(rng1), hpx::util::begin(rng2), hpx::util::end(rng2), dest, HPX_MOVE(comp), HPX_MOVE(proj1), HPX_MOVE(proj2)); } // clang-format off template <typename ExPolicy, typename Iter1, typename Sent1, typename Iter2, typename Sent2, typename Iter3, typename Comp = hpx::ranges::less, typename Proj1 = hpx::identity, typename Proj2 = hpx::identity, HPX_CONCEPT_REQUIRES_( hpx::is_execution_policy_v<ExPolicy> && hpx::traits::is_sentinel_for_v<Sent1, Iter1> && hpx::parallel::traits::is_projected_v<Proj1, Iter1> && hpx::traits::is_sentinel_for_v<Sent2, Iter2> && hpx::parallel::traits::is_projected_v<Proj2, Iter2> && hpx::traits::is_iterator_v<Iter3> && hpx::parallel::traits::is_indirect_callable_v<ExPolicy, Comp, hpx::parallel::traits::projected<Proj1, Iter1>, hpx::parallel::traits::projected<Proj2, Iter2> > )> // clang-format on friend hpx::parallel::util::detail::algorithm_result_t<ExPolicy, hpx::ranges::merge_result<Iter1, Iter2, Iter3>> tag_fallback_invoke(merge_t, ExPolicy&& policy, Iter1 first1, Sent1 last1, Iter2 first2, Sent2 last2, Iter3 dest, Comp comp = Comp(), Proj1 proj1 = Proj1(), Proj2 proj2 = Proj2()) { static_assert(hpx::traits::is_random_access_iterator_v<Iter1>, "Required at least random access iterator."); static_assert(hpx::traits::is_random_access_iterator_v<Iter2>, "Requires at least random access iterator."); static_assert(hpx::traits::is_random_access_iterator_v<Iter3>, "Requires at least random access iterator."); using result_type = hpx::ranges::merge_result<Iter1, Iter2, Iter3>; return hpx::parallel::detail::merge<result_type>().call( HPX_FORWARD(ExPolicy, policy), first1, last1, first2, last2, dest, HPX_MOVE(comp), HPX_MOVE(proj1), HPX_MOVE(proj2)); } // clang-format off template <typename Rng1, typename Rng2, typename Iter3, typename Comp = hpx::ranges::less, typename Proj1 = hpx::identity, typename Proj2 = hpx::identity, HPX_CONCEPT_REQUIRES_( hpx::traits::is_range_v<Rng1> && hpx::parallel::traits::is_projected_range_v<Proj1, Rng1> && hpx::traits::is_range_v<Rng2> && hpx::parallel::traits::is_projected_range_v<Proj2, Rng2> && hpx::traits::is_iterator_v<Iter3> && hpx::parallel::traits::is_indirect_callable_v< hpx::execution::sequenced_policy, Comp, hpx::parallel::traits::projected_range<Proj1, Rng1>, hpx::parallel::traits::projected_range<Proj2, Rng2> > )> // clang-format on friend hpx::ranges::merge_result<hpx::traits::range_iterator_t<Rng1>, hpx::traits::range_iterator_t<Rng2>, Iter3> tag_fallback_invoke(merge_t, Rng1&& rng1, Rng2&& rng2, Iter3 dest, Comp comp = Comp(), Proj1 proj1 = Proj1(), Proj2 proj2 = Proj2()) { using iterator_type1 = hpx::traits::range_iterator_t<Rng1>; using iterator_type2 = hpx::traits::range_iterator_t<Rng2>; static_assert( hpx::traits::is_random_access_iterator_v<iterator_type1>, "Required at least random access iterator."); static_assert( hpx::traits::is_random_access_iterator_v<iterator_type2>, "Requires at least random access iterator."); static_assert(hpx::traits::is_random_access_iterator_v<Iter3>, "Requires at least random access iterator."); using result_type = hpx::ranges::merge_result<iterator_type1, iterator_type2, Iter3>; return hpx::parallel::detail::merge<result_type>().call( hpx::execution::seq, hpx::util::begin(rng1), hpx::util::end(rng1), hpx::util::begin(rng2), hpx::util::end(rng2), dest, HPX_MOVE(comp), HPX_MOVE(proj1), HPX_MOVE(proj2)); } // clang-format off template <typename Iter1, typename Sent1, typename Iter2, typename Sent2, typename Iter3, typename Comp = hpx::ranges::less, typename Proj1 = hpx::identity, typename Proj2 = hpx::identity, HPX_CONCEPT_REQUIRES_( hpx::traits::is_sentinel_for_v<Sent1, Iter1> && hpx::parallel::traits::is_projected_v<Proj1, Iter1> && hpx::traits::is_sentinel_for_v<Sent2, Iter2> && hpx::parallel::traits::is_projected_v<Proj2, Iter2> && hpx::traits::is_iterator_v<Iter3> && hpx::parallel::traits::is_indirect_callable_v< hpx::execution::sequenced_policy, Comp, hpx::parallel::traits::projected<Proj1, Iter1>, hpx::parallel::traits::projected<Proj2, Iter2> > )> // clang-format on friend hpx::ranges::merge_result<Iter1, Iter2, Iter3> tag_fallback_invoke(merge_t, Iter1 first1, Sent1 last1, Iter2 first2, Sent2 last2, Iter3 dest, Comp comp = Comp(), Proj1 proj1 = Proj1(), Proj2 proj2 = Proj2()) { static_assert(hpx::traits::is_random_access_iterator_v<Iter1>, "Required at least random access iterator."); static_assert(hpx::traits::is_random_access_iterator_v<Iter2>, "Requires at least random access iterator."); static_assert(hpx::traits::is_random_access_iterator_v<Iter3>, "Requires at least random access iterator."); using result_type = hpx::ranges::merge_result<Iter1, Iter2, Iter3>; return hpx::parallel::detail::merge<result_type>().call( hpx::execution::seq, first1, last1, first2, last2, dest, HPX_MOVE(comp), HPX_MOVE(proj1), HPX_MOVE(proj2)); } } merge{}; /////////////////////////////////////////////////////////////////////////// // CPO for hpx::ranges::inplace_merge inline constexpr struct inplace_merge_t final : hpx::detail::tag_parallel_algorithm<inplace_merge_t> { private: // clang-format off template <typename ExPolicy, typename Rng, typename Iter, typename Comp = hpx::ranges::less, typename Proj = hpx::identity, HPX_CONCEPT_REQUIRES_( hpx::is_execution_policy_v<ExPolicy> && hpx::traits::is_range_v<Rng> && hpx::parallel::traits::is_projected_range_v<Proj, Rng> && hpx::traits::is_iterator_v<Iter> && hpx::parallel::traits::is_projected_v<Proj, Iter> && hpx::parallel::traits::is_indirect_callable_v<ExPolicy, Comp, hpx::parallel::traits::projected_range<Proj, Rng>, hpx::parallel::traits::projected_range<Proj, Rng> > )> // clang-format on friend hpx::parallel::util::detail::algorithm_result_t<ExPolicy, Iter> tag_fallback_invoke(inplace_merge_t, ExPolicy&& policy, Rng&& rng, Iter middle, Comp comp = Comp(), Proj proj = Proj()) { using iterator_type = hpx::traits::range_iterator_t<Rng>; static_assert( hpx::traits::is_random_access_iterator_v<iterator_type>, "Required at least random access iterator."); static_assert(hpx::traits::is_random_access_iterator_v<Iter>, "Required at least random access iterator."); return hpx::parallel::detail::inplace_merge<Iter>().call( HPX_FORWARD(ExPolicy, policy), hpx::util::begin(rng), middle, hpx::util::end(rng), HPX_MOVE(comp), HPX_MOVE(proj)); } // clang-format off template <typename ExPolicy, typename Iter, typename Sent, typename Comp = hpx::ranges::less, typename Proj = hpx::identity, HPX_CONCEPT_REQUIRES_( hpx::is_execution_policy_v<ExPolicy> && hpx::traits::is_sentinel_for_v<Sent, Iter> && hpx::parallel::traits::is_projected_v<Proj, Iter> && hpx::parallel::traits::is_indirect_callable_v<ExPolicy, Comp, hpx::parallel::traits::projected<Proj, Iter>, hpx::parallel::traits::projected<Proj, Iter> > )> // clang-format on friend hpx::parallel::util::detail::algorithm_result_t<ExPolicy, Iter> tag_fallback_invoke(inplace_merge_t, ExPolicy&& policy, Iter first, Iter middle, Sent last, Comp comp = Comp(), Proj proj = Proj()) { static_assert(hpx::traits::is_random_access_iterator_v<Iter>, "Required at least random access iterator."); return hpx::parallel::detail::inplace_merge<Iter>().call( HPX_FORWARD(ExPolicy, policy), first, middle, last, HPX_MOVE(comp), HPX_MOVE(proj)); } // clang-format off template <typename Rng, typename Iter, typename Comp = hpx::ranges::less, typename Proj = hpx::identity, HPX_CONCEPT_REQUIRES_( hpx::traits::is_range_v<Rng> && hpx::parallel::traits::is_projected_range_v<Proj, Rng> && hpx::traits::is_iterator_v<Iter> && hpx::parallel::traits::is_projected_v<Proj, Iter> && hpx::parallel::traits::is_indirect_callable_v< hpx::execution::sequenced_policy, Comp, hpx::parallel::traits::projected_range<Proj, Rng>, hpx::parallel::traits::projected_range<Proj, Rng> > )> // clang-format on friend Iter tag_fallback_invoke(inplace_merge_t, Rng&& rng, Iter middle, Comp comp = Comp(), Proj proj = Proj()) { using iterator_type = hpx::traits::range_iterator_t<Rng>; static_assert( hpx::traits::is_random_access_iterator_v<iterator_type>, "Required at least random access iterator."); static_assert(hpx::traits::is_random_access_iterator_v<Iter>, "Required at least random access iterator."); return hpx::parallel::detail::inplace_merge<Iter>().call( hpx::execution::seq, hpx::util::begin(rng), middle, hpx::util::end(rng), HPX_MOVE(comp), HPX_MOVE(proj)); } // clang-format off template <typename Iter, typename Sent, typename Comp = hpx::ranges::less, typename Proj = hpx::identity, HPX_CONCEPT_REQUIRES_( hpx::traits::is_sentinel_for_v<Sent, Iter> && hpx::parallel::traits::is_projected_v<Proj, Iter> && hpx::parallel::traits::is_indirect_callable_v< hpx::execution::sequenced_policy, Comp, hpx::parallel::traits::projected<Proj, Iter>, hpx::parallel::traits::projected<Proj, Iter> > )> // clang-format on friend Iter tag_fallback_invoke(inplace_merge_t, Iter first, Iter middle, Sent last, Comp comp = Comp(), Proj proj = Proj()) { static_assert(hpx::traits::is_random_access_iterator_v<Iter>, "Required at least random access iterator."); return hpx::parallel::detail::inplace_merge<Iter>().call( hpx::execution::seq, first, middle, last, HPX_MOVE(comp), HPX_MOVE(proj)); } } inplace_merge{}; } // namespace hpx::ranges #endif //DOXYGEN
true
596b981b638c046e1cdb6714f15468fdace75719
C++
kanika2296/c-book-code
/createBook.h
WINDOWS-1258
2,446
3.140625
3
[]
no_license
#include "Book.h" class CreateBook { private: Book b; public: CreateBook() { b.setTitle("Clean Code"); b.setPrice(700); b.setAuthor("Robert C. Martin"); b.addCoverPage(); b.addEndPage(); // adding two chapters Chapters* ch = b.addChapters("Clean Code "); ch->addPage("There will be code")->addPara("One might argue that a book about code is somehow behind the timesthat code is no longer the issue that we should be concerned about models and requirements instead. Indeed some have suggested that we are close to the end of code"); Page* pg1 = ch->addPage("Bad Code"); pg1->addFigure("This is figure", "This is caption"); pg1->addPara("I know of one company that, in the late 80s, wrote a killer app.It was very popular, and lots of professionals bought and used it. "); pg1->addFigure("This is a figure", "CAPTION"); Chapters* ch2 = b.addChapters("Meaningfull Names"); ch2->addPage("Introduction")->addPara("Names are everywhere in software. We name our variables, our functions, our arguments,classes, and packages"); ch2->addPage("Use Intension Revealing names")->addPara("This is a paragraph"); } void printIndex() { b.getToc(); } void print() { b.print(); } void printBookChapter() { b.printChapterList(); cout << "Enter the chapter number (int) : \n"; int number; cin >> number; b.printChapter(number - 1); } void printPage() { int number; cout << "Enter page number (int) :\n"; cin >> number; b.printPage(number); } void Browse() { string cnt = "o"; int n = 0; b.printFirstPage(); cout << "\n \t \t Next [n] \t \t\n"; cin >> cnt; while (cnt == "n" || cnt == "p") { if (cnt == "n") { n++; } else if (cnt == "p") { n--; } if(n == 0 && cnt == "p") b.printFirstPage(); if (n > b.totalPages()) b.printEndPage(); else { b.printPage(n); } cout << "\n \t \t Next [n] | Previous [p] \t \t\n"; cin >> cnt; } } };
true
91481aafd0dcc2758532bacbc54cf0b4780a1f88
C++
laballea/piscinecpp
/cpp06/ex02/main.cpp
UTF-8
2,039
2.890625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: laballea <laballea@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/04 10:49:12 by laballea #+# #+# */ /* Updated: 2021/03/04 11:20:40 by laballea ### ########.fr */ /* */ /* ************************************************************************** */ #include "Base.hpp" Base *generate(void){ switch (std::rand() % 3) { case 0 : std::cout << "Data : A" << std::endl; return (new A()); case 1 : std::cout << "Data : B" << std::endl; return (new B()); case 2 : std::cout << "Data : C" << std::endl; return (new C()); } return (NULL); } void identify_from_pointer(Base *p){ if (dynamic_cast<A*> (p) != 0x0) std::cout << "Pointer result : A" << std::endl; else if (dynamic_cast<B*> (p) != 0x0) std::cout << "Pointer result : B" << std::endl; else if (dynamic_cast<C*> (p) != 0x0) std::cout << "Pointer result : C" << std::endl; } void identify_from_reference(Base &p){ try { (void)dynamic_cast<A&> (p); std::cout << "Reference result : A" << std::endl; } catch (std::bad_cast e){}; try { (void)dynamic_cast<B&> (p); std::cout << "Reference result : B" << std::endl; } catch (std::bad_cast e){}; try { (void)dynamic_cast<C&> (p); std::cout << "Reference result : C" << std::endl; } catch (std::bad_cast e){}; } int main(){ std::srand(std::time(0) * std::time(0)); Base *data = generate(); identify_from_pointer(data); identify_from_reference(*data); }
true
f327f025b64366e02334f504864085224bf0cdac
C++
Kouen74/ANicoletti_CSC17A
/RainOrShine.cpp
UTF-8
1,077
3.046875
3
[]
no_license
/* * File: prob6.cpp * Author: Andrew Nicoletti * Created on July 12, 2016, 12:10 PM * Purpose: Just another sequence */ #include <iostream> // System Library #include <cmath> // Math Library #include <iomanip> using namespace std; // Standard I/O Namespace // User Libraries // Global Constants // Functions Prototypes // Exe begins here int main(int argc, char** argv) { float x,terms,result,expnent,fact; cout<<"Input for x"<<endl; cin>>x; cout<<"Input the number of terms"<<endl; cin>>terms; expnent=1; fact=1; result=x; for (int count=1;count<terms;count++){ if(count%2!=0){ fact*=(fact*count); result-=pow(x,(count*2)-1)/fact; cout<<"test odd"<<endl; } if(count%2==0){ fact*=(fact*count); result+=pow(x,(count*2)-1)/fact; cout<<"test even"<<endl; } } cout<<"The result is "<<setprecision(15)<<result; return 0; }
true
35b9653cb168c4669dd451f6511fa42bc4dbab16
C++
unyieldingGlacier/coding-exercises
/intersection-arrays.cpp
UTF-8
1,284
3.6875
4
[]
no_license
/* LC 349 * Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. Note: Each element in the result must be unique. The result can be in any order. */ //approach 1 - sort and process duplicates while iterating class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> out; sort(nums1.begin(),nums1.end()); sort(nums2.begin(),nums2.end()); int i = 0, j = 0, n = nums1.size(), m = nums2.size(); while(i < n && j < m){ if(nums1[i] == nums2[j] && (out.size() == 0 || out.back() != nums1[i] )) { out.push_back(nums1[i]); i++; j++; } else if(nums1[i] < nums2[j]){ i++; } else { j++; } } return out; } }; //approach 2 - extra storage class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> out; set<int> s(nums1.begin(),nums1.end()); for(int n: nums2){ if(s.count(n)){ s.erase(n); out.push_back(n); } } return out; } };
true
b818af2cce95a34b2fd29583f35a814d7ceb422e
C++
Tomatosoup97/Web-Server
/src/exceptions.hpp
UTF-8
636
2.9375
3
[ "MIT" ]
permissive
#ifndef WEBSERVER_EXCEPTIONS_HPP #define WEBSERVER_EXCEPTIONS_HPP #include <iostream> #include <boost/asio.hpp> namespace webserver { void output_exception(std::exception &e) { std::cout << "Exception: " << e.what() << "\n"; } void output_error(const boost::system::error_code &error) { std::cout << "Error: " << error.message() << "\n"; } void output_error(std::string error_message) { std::cout << error_message << "\n"; } void check_error_code(const boost::system::error_code &error) { if (error) { output_error(error); return; } } } // namespace webserver #endif //WEBSERVER_EXCEPTIONS_HPP
true
009ce4b616f5cfd7a3669df400436b53c590d007
C++
QiuBiuBiu/LeetCode
/C++/Leetcode/16.cpp
UTF-8
1,193
3.8125
4
[]
no_license
/* 16. 最接近的三数之和 给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。 返回这三个数的和。 假定每组输入只存在恰好一个解。 输入:nums = [-1,2,1,-4], target = 1 输出:2 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。 */ /* 排序+双指针,T=O(n^2) 先排序,再固定一个数字nums[i],用双指针来寻找另外两个数字 */ class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int res = nums[0] + nums[1] + nums[2]; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) { for (int j = i + 1, k = nums.size() - 1; j < k; ) { int sum = nums[i] + nums[j] + nums[k]; if (sum == target) return sum; else if (sum > target) k--; else j++; if (abs(sum - target) < abs(res - target)) { res = sum; } } } return res; } };
true
79bf379dfa092a90d46555d32d2be6d3e2bd0fd1
C++
robillardstudio/Images-Generiques
/App/Engines/AppEngine/Interactions.cpp
UTF-8
3,848
2.5625
3
[]
no_license
// // Interactions.cpp // Xcode // // Created by Valentin Dufois on 12/01/2018. // Copyright © 2018 Valentin Dufois. All rights reserved. // #include "AppEngine.hpp" #include "Core/AppObject.hpp" void AppEngine::parseEvents() { SDL_Event event; m_mouse.scrollX = 0; m_mouse.scrollY = 0; m_window.resized = false; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYUP: case SDL_KEYDOWN: keyBoardEvents(event); break; case SDL_QUIT: return App->endApp(); break; case SDL_WINDOWEVENT: windowEvents(event); break; case SDL_MOUSEWHEEL: case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: mouseEvents(event); break; } } } void AppEngine::windowEvents(const SDL_Event &event) { switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: case SDL_WINDOWEVENT_SIZE_CHANGED: App->setWidth(event.window.data1); App->setHeigth(event.window.data2); m_window.resized = true; break; } } void AppEngine::keyBoardEvents(const SDL_Event &event) { bool newVal; if(event.type == SDL_KEYUP) newVal = false; else newVal = true; switch(event.key.keysym.sym) { case SDLK_a: m_keys.A = newVal; break; case SDLK_b: m_keys.B = newVal; break; case SDLK_c: m_keys.C = newVal; break; case SDLK_d: m_keys.RIGHT = newVal; m_keys.D = newVal; break; case SDLK_e: m_keys.E = newVal; break; case SDLK_f: m_keys.F = newVal; break; case SDLK_g: m_keys.G = newVal; break; case SDLK_h: m_keys.H = newVal; break; case SDLK_i: m_keys.I = newVal; break; case SDLK_j: m_keys.J = newVal; break; case SDLK_k: m_keys.K = newVal; break; case SDLK_l: m_keys.L = newVal; break; case SDLK_m: m_keys.M = newVal; break; case SDLK_n: m_keys.N = newVal; break; case SDLK_o: m_keys.O = newVal; break; case SDLK_p: m_keys.P = newVal; break; case SDLK_q: m_keys.LEFT = newVal; m_keys.Q = newVal; break; case SDLK_r: m_keys.R = newVal; break; case SDLK_s: m_keys.DOWN = newVal; m_keys.S = newVal; break; case SDLK_t: m_keys.T = newVal; break; case SDLK_u: m_keys.U = newVal; break; case SDLK_v: m_keys.V = newVal; break; case SDLK_w: m_keys.W = newVal; break; case SDLK_x: m_keys.X = newVal; break; case SDLK_y: m_keys.Y = newVal; break; case SDLK_z: m_keys.UP = newVal; m_keys.Z = newVal; break; case SDLK_UP: m_keys.UP = newVal; break; case SDLK_DOWN: m_keys.DOWN = newVal; break; case SDLK_LEFT: m_keys.LEFT = newVal; break; case SDLK_RIGHT: m_keys.RIGHT = newVal; break; case SDLK_ESCAPE: m_keys.ESC = newVal; break; case SDLK_BACKSPACE: m_keys.BACKSPACE = newVal; break; case SDLK_RETURN: m_keys.ENTER = newVal; break; case SDLK_SPACE: m_keys.SPACE = newVal; break; } } void AppEngine::mouseEvents(const SDL_Event &event) { switch(event.type) { case SDL_MOUSEWHEEL: m_mouse.scrollY = event.wheel.y; m_mouse.scrollX = event.wheel.x; break; case SDL_MOUSEMOTION: m_mouse.pos.x = event.motion.x; m_mouse.pos.y = event.motion.y; break; case SDL_MOUSEBUTTONDOWN: if(event.button.button == SDL_BUTTON_LEFT) m_mouse.leftBtn = true; else if(event.button.button == SDL_BUTTON_RIGHT) m_mouse.rightBtn = true; break; case SDL_MOUSEBUTTONUP: if(event.button.button == SDL_BUTTON_LEFT) m_mouse.leftBtn = false; else if(event.button.button == SDL_BUTTON_RIGHT) m_mouse.rightBtn = false; break; } }
true
9060a029b1e4d730c1c27abe2ae0928d425f2b7e
C++
pehlivanian/OrderedPartitions
/score.hpp
UTF-8
8,134
2.765625
3
[]
no_license
#ifndef __SCORE_HPP__ #define __SCORE_HPP__ #include <vector> #include <list> #include <limits> #include <algorithm> #include <numeric> #include <iostream> #include <cmath> #include <exception> #define UNUSED(expr) do { (void)(expr); } while (0) namespace Objectives { enum class objective_fn { Gaussian = 0, Poisson = 1, RationalScore = 2 }; struct optimizationFlagException : public std::exception { const char* what() const throw () { return "Optimized version not implemented"; }; }; class ParametricContext { protected: std::vector<float> a_; std::vector<float> b_; int n_; std::vector<std::vector<float>> a_sums_; std::vector<std::vector<float>> b_sums_; objective_fn parametric_dist_; bool risk_partitioning_objective_; bool use_rational_optimization_; public: ParametricContext(std::vector<float> a, std::vector<float> b, int n, objective_fn parametric_dist, bool risk_partitioning_objective, bool use_rational_optimization ) : a_{a}, b_{b}, n_{n}, parametric_dist_{parametric_dist}, risk_partitioning_objective_{risk_partitioning_objective}, use_rational_optimization_{use_rational_optimization} {} virtual ~ParametricContext() = default; virtual void compute_partial_sums() {}; virtual float compute_score_multclust(int, int) = 0; virtual float compute_score_multclust_optimized(int, int) = 0; virtual float compute_score_riskpart(int, int) = 0; virtual float compute_score_riskpart_optimized(int, int) = 0; virtual float compute_ambient_score_multclust(float, float) = 0; virtual float compute_ambient_score_riskpart(float, float) = 0; float compute_score(int i, int j) { if (risk_partitioning_objective_) { if (use_rational_optimization_) { return compute_score_riskpart_optimized(i, j); } else { return compute_score_riskpart(i, j); } } else { if (use_rational_optimization_) { return compute_score_multclust_optimized(i, j); } else { return compute_score_multclust(i, j); } } } float compute_ambient_score(float a, float b) { if (risk_partitioning_objective_) { return compute_ambient_score_riskpart(a, b); } else { return compute_ambient_score_multclust(a, b); } } }; class PoissonContext : public ParametricContext { public: PoissonContext(std::vector<float> a, std::vector<float> b, int n, objective_fn parametric_dist, bool risk_partitioning_objective, bool use_rational_optimization) : ParametricContext(a, b, n, parametric_dist, risk_partitioning_objective, use_rational_optimization) { if (use_rational_optimization) { compute_partial_sums(); } } float compute_score_multclust(int i, int j) override { // CHECK float C = std::accumulate(a_.begin()+i, a_.begin()+j, 0.); float B = std::accumulate(b_.begin()+i, b_.begin()+j, 0.); if (C > B) { return C*std::log(C/B) + B - C; } else { return 0.; } } float compute_score_riskpart(int i, int j) override { // CHECK float C = std::accumulate(a_.begin()+i, a_.begin()+j, 0.); float B = std::accumulate(b_.begin()+i, b_.begin()+j, 0.); return C*std::log(C/B); } float compute_ambient_score_multclust(float a, float b) override { // CHECK return a*std::log(a/b) + b - a; } float compute_ambient_score_riskpart(float a, float b) override { // CHECK if (a > b) { return a*std::log(a/b) + b - a; } else { return 0.; } } void compute_partial_sums() override { throw optimizationFlagException(); } float compute_score_multclust_optimized(int i, int j) override { UNUSED(i); UNUSED(j); throw optimizationFlagException(); } float compute_score_riskpart_optimized(int i, int j) override { UNUSED(i); UNUSED(j); throw optimizationFlagException(); } }; class GaussianContext : public ParametricContext { public: GaussianContext(std::vector<float> a, std::vector<float> b, int n, objective_fn parametric_dist, bool risk_partitioning_objective, bool use_rational_optimization) : ParametricContext(a, b, n, parametric_dist, risk_partitioning_objective, use_rational_optimization) { if (use_rational_optimization) { compute_partial_sums(); } } float compute_score_multclust(int i, int j) override { // CHECK float C = std::accumulate(a_.begin()+i, a_.begin()+j, 0.); float B = std::accumulate(b_.begin()+i, b_.begin()+j, 0.); if (C > B) { float summand = std::pow(C, 2) / B; return .5*(summand - 1); } else { return 0.; } } float compute_score_riskpart(int i, int j) override { // CHECK float C = std::accumulate(a_.begin()+i, a_.begin()+j, 0.); float B = std::accumulate(b_.begin()+i, b_.begin()+j, 0.); return C*C/2./B; } float compute_ambient_score_multclust(float a, float b) override { // CHECK return a*a/2./b + b/2. - a; } float compute_ambient_score_riskpart(float a, float b) override { // CHECK if (a > b) { return a*a/2./b + b/2. - a; } else { return 0.; } } void compute_partial_sums() override { throw optimizationFlagException(); } float compute_score_multclust_optimized(int i, int j) override { UNUSED(i); UNUSED(j); throw optimizationFlagException(); } float compute_score_riskpart_optimized(int i, int j) override { UNUSED(i); UNUSED(j); throw optimizationFlagException(); } }; class RationalScoreContext : public ParametricContext { // This class doesn't correspond to any regular exponential family, // it is used to define ambient functions on the partition polytope // for targeted applications - quadratic approximations to loss, for // XGBoost, e.g. public: RationalScoreContext(std::vector<float> a, std::vector<float> b, int n, objective_fn parametric_dist, bool risk_partitioning_objective, bool use_rational_optimization) : ParametricContext(a, b, n, parametric_dist, risk_partitioning_objective, use_rational_optimization) { if (use_rational_optimization) { compute_partial_sums(); } } void compute_partial_sums() override { float a_cum; a_sums_ = std::vector<std::vector<float>>(n_, std::vector<float>(n_+1, std::numeric_limits<float>::min())); b_sums_ = std::vector<std::vector<float>>(n_, std::vector<float>(n_+1, std::numeric_limits<float>::min())); for (int i=0; i<n_; ++i) { a_sums_[i][i] = 0.; b_sums_[i][i] = 0.; } for (int i=0; i<n_; ++i) { a_cum = -a_[i-1]; for (int j=i+1; j<=n_; ++j) { a_cum += a_[j-2]; a_sums_[i][j] = a_sums_[i][j-1] + (2*a_cum + a_[j-1])*a_[j-1]; b_sums_[i][j] = b_sums_[i][j-1] + b_[j-1]; } } } float compute_score_multclust_optimized(int i, int j) override { float score = a_sums_[i][j] / b_sums_[i][j]; return score; } float compute_score_multclust(int i, int j) override { float score = std::pow(std::accumulate(a_.begin()+i, a_.begin()+j, 0.), 2) / std::accumulate(b_.begin()+i, b_.begin()+j, 0.); return score; } float compute_score_riskpart(int i, int j) override { return compute_score_multclust(i, j); } float compute_score_riskpart_optimized(int i, int j) override { return compute_score_multclust_optimized(i, j); } float compute_ambient_score_multclust(float a, float b) override { return a*a/b; } float compute_ambient_score_riskpart(float a, float b) override { return a*a/b; } }; } // namespace Objectives #endif
true
c79b377cc036cf6c0137d4c04d986ca7f1bf64ec
C++
lilei/practice_book
/src/thread.cpp
UTF-8
706
3.609375
4
[]
no_license
#include <gtest/gtest.h> #include <thread> #include <chrono> #include <iostream> void foo() { std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout<<"func foo"<<std::endl; } void bar() { std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout<<"func bar"<<std::endl; } TEST(thread,thread) { std::thread t1(foo); std::thread t2(bar); std::cout << "2 thread started"<<std::endl; t1.join(); t2.join(); } TEST(thread,lambda) { auto f = []() { std::cout<<"func f"<<std::endl; }; auto b = []() { std::cout<<"func b"<<std::endl; }; std::thread t1(f); std::thread t2(b); t1.join(); t2.join(); }
true
4609239516b2d5ee5a6580dff61c4184667a97fe
C++
Alimurrazi/Programming
/beginner_level_and_uva/priority queue-9.cpp
UTF-8
1,166
2.859375
3
[]
no_license
#include<stdio.h> #include<queue> using namespace std; struct data { char c; int h,m,s; bool operator < (const data & p)const { // if(p.dist > dist) // return true; // if(p.dist==dist && p.city>city) // return false; // if(p.dist > dist) // return false; // return p.dist < dist; // return true; // return dist > p.dist; // return false; if(p.h<h) return false; if(p.h==h && p.m<m) return false; if(p.h==h && p.m==m && p.s<s) return false; if(p.h==h && p.m==m && p.s==s && p.c<c) return false; return true; } }; priority_queue<data>q; int main() { data u,v,t; int i,j,k,l,m,n; u.c='d'; u.h=1; u.m=10; u.s=15; q.push(u); u.c='a'; u.h=2; u.m=10; u.s=12; q.push(u); u.c='b'; u.h=1; u.m=15; u.s=25; q.push(u); u.c='c'; u.h=1; u.m=15; u.s=20; q.push(u); u.c='z'; u.h=2; u.m=10; u.s=12; q.push(u); while(!q.empty()) { v=q.top(); printf("%c %d %d %d\n",v.c,v.h,v.m,v.s); q.pop(); } }
true
048c5eb64ffcb992d595f6947aafb6f316d16f42
C++
Giordan0/URIOJ
/Iniciante/1018.cpp
UTF-8
756
3.328125
3
[]
no_license
#include <iostream> using namespace std; int main() { int x, temp, temp2; cin >> x; cout << x << endl; temp = x%100; cout << (x - temp)/100 << " nota(s) de R$ 100,00" << endl; temp2 = temp%50; cout << (temp - temp2)/50 << " nota(s) de R$ 50,00" << endl; temp = temp2%20; cout << (temp2 - temp)/20 << " nota(s) de R$ 20,00" << endl; temp2 = temp%10; cout << (temp - temp2)/10 << " nota(s) de R$ 10,00" << endl; temp = temp2%5; cout << (temp2 - temp)/5 << " nota(s) de R$ 5,00" << endl; temp2 = temp%2; cout << (temp - temp2)/2 << " nota(s) de R$ 2,00" << endl; temp = temp2%1; cout << (temp2 - temp)/1 << " nota(s) de R$ 1,00" << endl; return 0; }
true
c0c6e5f001617a72a6e331e10d618d7007c049e6
C++
charlesgingras/GoLite-Compiler
/programs-solution/3-extra+codegen/valid/7-2-slices-recursive.cpp
UTF-8
2,751
2.984375
3
[]
no_license
#include <iostream> #include <string> #include <array> bool __golite__true = true; bool __golite__false = false; namespace GoLite { template <typename T> struct __golite_builtin__slice { unsigned int __size = 0; unsigned int __capacity = 0; T *__contents = NULL; __golite_builtin__slice<T> append(T element) { return __append<__golite_builtin__slice<T>>(element); } template<class C> C __append(T element) { C ret; ret.__size = __size; ret.__capacity = __capacity; ret.__contents = __contents; if (ret.__contents == NULL || ret.__size + 1 > ret.__capacity) { if (ret.__capacity == 0) { ret.__capacity = 2; } else { ret.__capacity = ret.__capacity * 2; } ret.__contents = new T[ret.__capacity]; std::copy(__contents, __contents + __size, ret.__contents); } ret.__contents[__size] = element; ret.__size++; return ret; } T& at(unsigned int index) { if (index >= __size) { std::cerr << "Error: index " << index << " greater than size of slice (" << __size << ")" << std::endl; std::exit(EXIT_FAILURE); } return __contents[index]; } int size() { return __size; } int capacity() { return __capacity; } }; typedef struct __golite_tag__0 __golite_tag__0; typedef struct __golite_rec__0 __golite_rec__0; typedef struct __golite_rec__1 __golite_rec__1; typedef struct __golite_rec__2 __golite_rec__2; struct __golite_tag__0 { __golite_builtin__slice<__golite_tag__0> __golite__a; __golite_tag__0() { __golite__a = {}; } }; struct __golite_rec__0 : std::array<__golite_builtin__slice<__golite_rec__0>, 3> { }; struct __golite_rec__1 : __golite_builtin__slice<__golite_rec__1> { __golite_rec__1 append(__golite_rec__1 element) { return __append<__golite_rec__1>(element); } }; struct __golite_rec__2 : __golite_builtin__slice<__golite_builtin__slice<__golite_rec__2>> { __golite_rec__2 append(__golite_builtin__slice<__golite_rec__2> element) { return __append<__golite_rec__2>(element); } }; void __golite__main() { __golite_tag__0 __golite_tmp_a__0 = {}; __golite_tag__0 __golite__a = __golite_tmp_a__0; __golite_rec__0 __golite_tmp_b__1 = {}; __golite_rec__0 __golite__b = __golite_tmp_b__1; __golite_rec__1 __golite_tmp_c__2 = {}; __golite_rec__1 __golite_tmp_d__3 = {}; __golite_rec__1 __golite__c = __golite_tmp_c__2; __golite_rec__1 __golite__d = __golite_tmp_d__3; __golite_rec__1 __golite_tmp__4 = __golite__c.append(__golite__d); __golite__c = __golite_tmp__4; __golite_rec__2 __golite_tmp_e__5 = {}; __golite_rec__2 __golite_tmp_f__6 = {}; __golite_rec__2 __golite__e = __golite_tmp_e__5; __golite_rec__2 __golite__f = __golite_tmp_f__6; std::cout << std::string("Success") << std::endl; } } int main() { GoLite::__golite__main(); }
true
22b1d5e4af926b8b1850250874125cd9047e8c3d
C++
brad9895/BrewOS
/ArduinoTempController/Controller.cpp
UTF-8
1,043
2.640625
3
[]
no_license
using std; #include "DallasTemperature.h" #include "OneWire.h" //#include #define ONE_WIRE_BUS 2 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); #define BUFFSIZE 20 float temps[BUFFSIZE]; uint8_t addresses[BUFFSIZE]; uint8_t numSensors = 0; volatile char buffer[40]; void setup() { setupI2C(); setupOneWire(); Serial.begin(9600); delay(100); } void setupI2C() { Wire.begin(2); // Initiate the Wire library Wire.onReceive(receiveEvent); Wire.onRequest(requestEvent); } void setupOneWire() { sensors.begin(); } void loop() { sensors.requestTemperatures(); numSensors = sensors.getDS18Count(); for (int i = 0; i < numSensors; i++) { if (i == BUFFSIZE) break; uint8_t* address; sensors.getAddress(address, i); addresses[i] = *address; temps[i] = sensors.getTempF(address); } } void requestEvent() { } void receiveEvent(int howMany) { data = ""; Wire. while (Wire.available()) { data += (char)Wire.read(); } while (1 < Wire.available()) { Wire. } }
true
924ca370d065a4ef4bfaf1eae54fea5bead50c73
C++
BenSlaney17/Ben-s-BurgARia-Code
/CollisionEngine.cpp
UTF-8
4,082
2.859375
3
[]
no_license
#include "CollisionEngine.h" #include "Collision.h" #include "GameObject.h" #include "CollisionObject.h" #include "graphics\mesh.h" #include <system\platform.h> #include "graphics\renderer_3d.h" #include <sony_sample_framework.h> CollisionEngine::CollisionEngine(gef::Platform * platform, gef::Renderer3D* renderer) : platform_(platform), renderer_(renderer) { half_width_ = platform->width() * 0.5f; half_height_ = platform->height() * 0.5f; } CollisionEngine::~CollisionEngine() { for (size_t i = 0; i < world_objects_.size(); i++) { world_objects_[i] = NULL; } world_objects_.clear(); platform_ = NULL; renderer_ = NULL; } void CollisionEngine::Update() { PreCollisionCheckUpdate(); CollisionCheck(); PostCollisionCheckUpdate(); current_interactable_object_ = ScreenPointRaycast(gef::Vector2(half_width_, half_height_)); } void CollisionEngine::PreCollisionCheckUpdate() { // if an object is active, then call its PrePhysicsUpdate() function for (size_t i = 0; i < world_objects_.size(); i++) { if(world_objects_[i]->IsActive()) world_objects_[i]->PrePhysicsUpdate(); } } void CollisionEngine::CollisionCheck() { // loop through all objects in world_objects_ for (size_t i = 0; i < world_objects_.size() - 1; i++) { // if current object is not active then skip if (!world_objects_[i]->IsActive()) { continue; } const gef::Mesh* firstMesh = world_objects_[i]->mesh_.mesh(); for (size_t j = i + 1; j < world_objects_.size(); j++) { if (world_objects_[j]->IsActive() && CollisionFunctions::IsCollidingAABB(world_objects_[i]->mesh_, world_objects_[j]->mesh_)) { world_objects_[i]->Colliding(world_objects_[j]); world_objects_[j]->Colliding(world_objects_[i]); } } } } void CollisionEngine::PostCollisionCheckUpdate() { // if an object is active then call its PostPhysicsUpdate() function for (size_t i = 0; i < world_objects_.size(); i++) { if (world_objects_[i]->IsActive()) world_objects_[i]->PostPhysicsUpdate(); } } GameObject* CollisionEngine::ScreenPointRaycast(gef::Vector2 screen_point) { gef::Vector4 start_pos; gef::Vector4 direction; GetScreenPositionRay(screen_point, start_pos, direction); // for each interactable gameobject check if the ray intersects for (size_t i = 0; i < world_objects_.size(); i++) { if (IsLookingAtInteractableObject(i, start_pos, direction)) { return world_objects_[i]; } } return NULL; } bool CollisionEngine::IsLookingAtInteractableObject(std::size_t &i, gef::Vector4 &start_pos, gef::Vector4 &direction) { return world_objects_[i]->IsActive() && world_objects_[i]->IsInteractable() && IsHit(i, start_pos, direction); } bool CollisionEngine::IsHit(const std::size_t &i, gef::Vector4 &start_pos, gef::Vector4 &direction) { gef::Vector4 sphereCentre(world_objects_[i]->transform_.GetWorldPosition()); float sphereRadius = world_objects_[i]->transform_.GetScale().y() * 0.2f; gef::Vector4 m = start_pos - sphereCentre; float b = m.DotProduct(direction); float c = m.LengthSqr() - (sphereRadius * sphereRadius); // Exit if ray pointing away from sphere (b > 0) if (b > 0.0f) { return false; } // A negative discriminant corresponds to ray missing sphere float discr = b * b - c; return discr > 0.0f; } void CollisionEngine::GetScreenPositionRay(gef::Vector2 screen_point, gef::Vector4 & start_pos, gef::Vector4 & direction) { gef::Vector2 ndc; ndc.x = (static_cast<float>(screen_point.x) - half_width_ )/ half_width_; ndc.y = (half_height_ - static_cast<float>(screen_point.y)) / half_height_; gef::Matrix44 projectionInverse; projectionInverse.Inverse(renderer_->view_matrix() * renderer_->projection_matrix()); gef::Vector4 nearPoint, farPoint; nearPoint = gef::Vector4(ndc.x, ndc.y, -1.0f, 1.0f).TransformW(projectionInverse); farPoint = gef::Vector4(ndc.x, ndc.y, 1.0f, 1.0f).TransformW(projectionInverse); nearPoint /= nearPoint.w(); farPoint /= farPoint.w(); start_pos = gef::Vector4(nearPoint.x(), nearPoint.y(), nearPoint.z()); direction = farPoint - nearPoint; direction.Normalise(); }
true
a9a19991b5c81c54f1660a55ab973c24b6da4777
C++
balramsingh54/codeC-
/lect4/basicfunction.cpp
UTF-8
357
3.171875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void increment(int*a){ *a=*a+1; cout<<"Inside function "<<&a<<endl; } int main(int argc, char const *argv[]){ int a; a=10; increment(&a); cout<<"Inside main "<<a<<endl; int x = 10; int &z = x; cout<<z<<endl; cout<<x<<endl; cout<<&z<<endl; z++; cout<<x<<endl; cout<<z<<endl; return 0; }
true
765f5fc334a8921ce2f43731dd00387e60e1a100
C++
abhay-iy97/30-days-of-code
/Day29/day29_bitwise.cpp
UTF-8
692
3.078125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); void calculate(int n, int k) { int max = 0; for(int i=1;i<k;i++) { for(int j=i+1; j<=n; j++) { int temp = i & j; if(temp < k && temp > max) { max = temp; } } } cout<<max<<endl; } int main() { int t; cin >> t; vector<pair<int,int>> values; for (int t_itr = 0; t_itr < t; t_itr++) { int n,k; cin >> n >> k; cin.ignore(); values.push_back(make_pair(n,k)); } for(auto &i:values) { calculate(i.first, i.second); } return 0; }
true
e4509b81295aca13321ff440c50bc8d8d21f1ce1
C++
helloAda/Algorithm-Study
/Algorithm-Study/Algorithm-C++/Algorithm-C++/替换空格/ReplaceSpaces.cpp
UTF-8
2,906
3.890625
4
[ "MIT" ]
permissive
// // ReplaceSpaces.cpp // Algorithm-C++ // // Created by HelloAda on 2018/9/11. // Copyright © 2018年 HelloAda. All rights reserved. // #include "ReplaceSpaces.hpp" #include <iostream> /* 面试题5:替换空格 题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”, 则输出“We%20are%20happy.”。 */ namespace namespace_replaceSpaces { void replaceBlank(char str[], int length) { if (str == nullptr && length <= 0) { std::cout << "无效字符" << std::endl; return; } int originalLength = 0; // 原字符串长度 int numberOfBlank = 0; // 空格数量 int i = 0; while (str[i] != '\0') { originalLength++; if (str[i] == ' ') { numberOfBlank++; } i++; } int newLength = originalLength + numberOfBlank * 2; if (newLength > length) { std::cout << "替换后超过字符串最大容量" << std::endl; return; } int indexOfOriginal = originalLength; int indexOfNew = newLength; while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal) { if (str[indexOfOriginal] == ' ') { str[indexOfNew--] = '0'; str[indexOfNew--] = '2'; str[indexOfNew--] = '%'; } else { str[indexOfNew--] = str[indexOfOriginal]; } indexOfOriginal--; } std::cout << "替换后的字符串:" << str << std::endl; } // ------ 测试 -------- void test (char str[], int length) { std::cout << "==== 测试开始 ====" << std::endl; replaceBlank(str, length); std::cout << "==== 测试结束 ====" << std::endl; } // 空格在开始 void test1() { const int length = 100; char str[length] = " helloworld"; test(str, length); } // 空格在中间 void test2() { const int length = 100; char str[length] = "hello world"; test(str, length); } // 空格在末尾 void test3() { const int length = 100; char str[length] = "helloworld "; test(str, length); } // 连续空格 多个空格 void test4() { const int length = 100; char str[length] = "hello world "; test(str, length); } // 空指针 void test5() { test(nullptr, 0); } // 超过容量 void test6() { const int length = 12; char str[length] = "hello world"; test(str, length); } void replaceSpaces() { test1(); test2(); test3(); test4(); test5(); test6(); } }
true
c15c99a67d8fb97ba6840ebcd2a0273ea3d07dc6
C++
tsmit317/CIS-115-Labs
/Lab06/Lab06Program4.cpp
UTF-8
2,067
3.734375
4
[]
no_license
// Lab06Program4.cpp - Wake Tech Healthcare Phone System - Adding doctor choice. 3 // Created by Taylor Smith on 2/20/13. /* Input: Number Doctor number = dNumber Processing: Processing Items:None Algorithm: 1. Enter number. 2. Test value of number in switch 1: Ask which doctor to make an appointment with. If dNumber is: 1: display "Making an appointment with Dr. Green" 2: display "Making an appointemnt with Dr. Fox" 3: display "Making an appointemnt with Dr. Davis" other: display "Talking to operator" 2: display "Billing questions" 3: display "Talking to nurse" other: display : "Talking to operator" Output: Making an appointment with a chosen doctor Billing Questions Talking to nurse Talking to operator */ #include <iostream> using namespace std; int main() { // Enter variables int number = 0; int dNumber = 0; // Enter input items cout << "Press 1 for making an appointment, Press 2 for billing questions, Press 3 for talking to a nurse, Press any other key to talk to operator: "; cin >> number; // Enter switch statments switch (number) { case 1: cout << "Press 1 for an appointment with Dr. Green. Press 2 for an appointment with Dr. Fox. Press 3 for an appointment with Dr. Davis. Press any other key to talk to operator: "; cin >> dNumber; switch (dNumber) { case 1: cout << "Making an appointment with Dr. Green" << endl; break; case 2: cout << "Making an appointment with Dr. Fox" << endl; break; case 3: cout << "Making an appointment with Dr. Davis" << endl; break; default: cout << "Talking to operator" << endl; } break; case 2: cout << "Billing questions" << endl; break; case 3: cout << "Talking to a nurse" << endl; break; default: cout << "Talking to an operator" << endl; } cin.get(); return 0; }
true
bd4826930cb3fc8da95a6a2e5abf4bd04ed55488
C++
zbomb/Hyperion-Engine
/Hyperion Engine/Source/Core/Object.cpp
WINDOWS-1252
8,287
2.59375
3
[]
no_license
/*================================================================================================== Hyperion Engine Source/Core/Object.cpp 2019, Zachary Berry ==================================================================================================*/ #include "Hyperion/Core/Object.h" namespace Hyperion { // DEBUG //std::map< size_t, std::shared_ptr< RTTI::TypeInfo > > g_TypeInfoList; std::map< uint32, std::shared_ptr< _ObjectState > > __objCache; uint32 __objIdCounter( 0 ); void TickObjects( double inDelta ) { for( auto It = __objCache.begin(); It != __objCache.end(); It++ ) { // Validate object before ticking if( It->second && It->second->valid && It->second->ptr ) { It->second->ptr->PerformTick( inDelta ); } } } void TickObjectsInput( InputManager& im, double delta ) { for( auto it = __objCache.begin(); it != __objCache.end(); it++ ) { if( it->second && it->second->valid && it->second->ptr ) { it->second->ptr->PerformInput( im, delta ); } } } HypPtr< Type > Object::GetType() const { // First, we want to find the 'actual' type of this object, and not the type of pointer being used to refer to it // To do this, we store the type id on creation in the objects state info HYPERION_VERIFY( m_ThisState != nullptr, "Object is missing state info!" ); auto typeInfo = RTTI::GetTypeInfo( m_ThisState->rtti_id ); HYPERION_VERIFY( typeInfo != nullptr, "Couldnt find type info for object!" ); return CreateObject< Type >( typeInfo ); } /*------------------------------------------------------------------------------------------------------ Type Class Definition ------------------------------------------------------------------------------------------------------*/ bool Type::IsParentTo( const HypPtr< Type >& Other ) const { if( !Other ) { return false; } HYPERION_VERIFY( m_Info && Other->m_Info, "[RTTI] Type class had invalid info pointer" ); // Check if we are a parent to other // Object is a parent to every registered 'type' if( m_Info->Identifier == typeid( Object ).hash_code() ) { return true; } for( auto It = Other->m_Info->ParentChain.begin(); It != Other->m_Info->ParentChain.end(); It++ ) { if( *It == m_Info->Identifier ) { return true; } } return false; } bool Type::IsDirectParentTo( const HypPtr< Type >& Other ) const { if( !Other ) { return false; } HYPERION_VERIFY( m_Info && Other->m_Info, "[RTTI] Type class had invalid info pointer" ); // Check if we are direct parent to other // If an inheritance list is empty, it means its parent class is 'Object', so we check that case here if( Other->m_Info->ParentChain.size() == 0 && m_Info->Identifier == typeid( Object ).hash_code() ) { return true; } else return( *Other->m_Info->ParentChain.begin() == m_Info->Identifier ); } bool Type::IsDerivedFrom( const HypPtr< Type >& Other ) const { if( !Other ) { return false; } HYPERION_VERIFY( m_Info && Other->m_Info, "[RTTI] Type class had invalid info pointer" ); if( m_Info->Identifier == typeid( Object ).hash_code() ) { return false; } // Check if other is a parent to this // if 'Other' is an 'Object', then we must be derived from it if( typeid( Object ).hash_code() == Other->m_Info->Identifier ) { return true; } for( auto It = m_Info->ParentChain.begin(); It != m_Info->ParentChain.end(); It++ ) { if( *It == Other->m_Info->Identifier ) { return true; } } return false; } bool Type::IsDirectlyDerivedFrom( const HypPtr< Type >& Other ) const { if( !Other ) { return false; } HYPERION_VERIFY( m_Info && Other->m_Info, "[RTTI] Type class had invalid info pointer" ); if( m_Info->Identifier == typeid( Object ).hash_code() ) { return false; } // Check if other is a direct parent to this // If our inheritance list is empty, it means were derived directly from 'Object' if( m_Info->ParentChain.size() == 0 && Other->m_Info->Identifier == typeid( Object ).hash_code() ) { return true; } else return( *m_Info->ParentChain.begin() == Other->m_Info->Identifier ); } std::vector< HypPtr< Type > > Type::GetParentList() const { HYPERION_VERIFY( m_Info != nullptr, "[RTTI] Type object was missing info pointer!" ); std::vector< HypPtr< Type > > result; result.reserve( m_Info->ParentChain.size() + 1 ); // First, loop through and add parent types in order (closest parent -> furthest parent) for( auto It = m_Info->ParentChain.begin(); It != m_Info->ParentChain.end(); It++ ) { auto type = CreateObject< Type >( RTTI::GetTypeInfo( *It ) ); HYPERION_VERIFY( type != nullptr, "[RTTI] Couldnt find type entry for parent" ); result.push_back( type ); } // Add base 'Object' type to list result.push_back( CreateObject< Type >( RTTI::GetObjectType() ) ); return result; } HypPtr< Type > Type::GetParent() const { HYPERION_VERIFY( m_Info != nullptr, "[RTTI] Type object was missing info pointer!" ); if( m_Info->ParentChain.size() == 0 ) { return CreateObject< Type >( RTTI::GetObjectType() ); } else { auto parent_info = RTTI::GetTypeInfo( m_Info->ParentChain.front() ); HYPERION_VERIFY( parent_info != nullptr, "[RTTI] Couldnt find type entry for parent" ); return CreateObject< Type >( parent_info ); } } std::vector< HypPtr< Type > > Type::GetDirectChildren() const { HYPERION_VERIFY( m_Info != nullptr, "[RTTI] Type object was missing info pointer!" ); std::vector< HypPtr< Type > > output; output.reserve( m_Info->ChildrenList.size() ); for( auto It = m_Info->ChildrenList.begin(); It != m_Info->ChildrenList.end(); It++ ) { auto typePtr = CreateObject< Type >( RTTI::GetTypeInfo( *It ) ); HYPERION_VERIFY( typePtr && typePtr->m_Info, "[RTTI] Failed to get child type instance!" ); output.push_back( typePtr ); } return output; } /* * Private helper function */ void ProcessChildTreeNode( const std::shared_ptr< RTTI::TypeInfo >& inNode, std::vector< HypPtr< Type > >& outList ) { HYPERION_VERIFY( inNode != nullptr, "[RTTI] Failed to build full subclass list.. a type was invalid" ); // Add this node to the list auto thisType = CreateObject< Type >( inNode ); outList.push_back( thisType ); for( auto It = inNode->ChildrenList.begin(); It != inNode->ChildrenList.end(); It++ ) { ProcessChildTreeNode( RTTI::GetTypeInfo( *It ), outList ); } } std::vector< HypPtr< Type > > Type::GetChildren() const { HYPERION_VERIFY( m_Info != nullptr, "[RTTI] Type object was missing info pointer!" ); std::vector< HypPtr< Type > > output; // Loop through children and build list for( auto It = m_Info->ChildrenList.begin(); It != m_Info->ChildrenList.end(); It++ ) { ProcessChildTreeNode( RTTI::GetTypeInfo( *It ), output ); } return output; } HypPtr< Object > Type::CreateInstance() const { HYPERION_VERIFY( m_Info, "[RTTI] Type class had invalid info pointer" ); return m_Info->CreateFunc ? m_Info->CreateFunc() : nullptr; } HypPtr< Type > Type::Get( size_t inIdentifier ) { // Check for 'object' type if( inIdentifier == typeid( Object ).hash_code() ) { return CreateObject< Type >( RTTI::GetObjectType() ); } // Find entry in RTTI table auto infoPtr = RTTI::GetTypeInfo( inIdentifier ); // Create and return type instance return infoPtr ? CreateObject< Type >( infoPtr ) : nullptr; } HypPtr< Type > Type::Get( const String& inIdentifier ) { // Check if parameter is valid if( inIdentifier.IsWhitespaceOrEmpty() ) { return nullptr; } // Typenames are always stored lowercase String lowerName = String::ToLower( inIdentifier ); // Check for 'Object' type if( String::Equals( lowerName, "object" ) ) { return CreateObject< Type >( RTTI::GetObjectType() ); } // Lookup info from RTTI auto infoPtr = RTTI::GetTypeInfo( inIdentifier ); return infoPtr ? CreateObject< Type >( infoPtr ) : nullptr; } HypPtr< Type > Type::Get( const HypPtr< Object >& inObj ) { return inObj->GetType(); } } /* * Register the 'Type' type with RTTI * - If instantiated through the type system (i.e. myType.CreateInstance()), by default * it will refer to the base 'Object' type */ HYPERION_REGISTER_OBJECT_TYPE( Type, Object, Hyperion::RTTI::GetObjectType() );
true
d4b1656c06dbb9e7401637570f05cbe6eaf229cc
C++
yalishanda42/oop2021
/week2/2/Complex.hpp
UTF-8
364
2.984375
3
[]
no_license
#pragma once class Complex { public: double real; double imaginary; Complex(); Complex(double real); Complex(double real, double imaginary); bool isEqualTo(const Complex& other) const; Complex add(const Complex& other) const; Complex multiply(const Complex& other) const; Complex conjugated() const; void conjugate(); };
true
38251cb6ff6a4e2f6c2ed8626e3a944af6a7db0d
C++
LightningBilly/ACMAlgorithms
/图形学算法/多边形扫描线法填充/多边形填充.cpp
UTF-8
6,826
2.953125
3
[]
no_license
#include "glew/2.2.0_1/include/GL/glew.h" #include "glfw/3.3.4/include/GLFW/glfw3.h" #include <iostream> #include <vector> using namespace std; double esp = 1e-6; void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { //如果按下ESC,把windowShouldClose设置为True,外面的循环会关闭应用 if(key==GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); std::cout<<"ESC"<<mode; } int cmpDouble(double a, double b) { if (fabs(a-b)<esp)return 0; if (a<b)return -1; return 1; } class ActiveEdge { public: double x; // 每次+k int maxY; int deltaX, deltaY; double k ; // ∆x/∆y }; int curY; bool cmpActiveEdge(ActiveEdge a, ActiveEdge b) { if(curY>=a.maxY)return false; if(curY>=b.maxY)return true; int eq = cmpDouble(a.x, b.x); if(eq) return eq<0; // x小的排前面 eq = cmpDouble(a.k, b.k); // 斜率小说明x在减小得快 return eq<0; } class Point { public: int x, y; Point(int xx, int yy):x(xx), y(yy){} Point(){} }; class Line { public: Point low, high; Line(){} Line(Point tp1, Point tp2):low(tp1),high(tp2){ if (tp2.y<tp1.y){ low=tp2; high=tp1; } } void Out(){ printf("%d,%d-%d,%d\n", low.x, low.y, high.x, high.y); } }; bool cmpLine(Line a, Line b) { return a.low.y<b.low.y; } void setPixel(Point p) { // cout<<p.x<<","<<p.y<<endl; glPointSize(1.3); glBegin(GL_POINTS); glVertex2i(p.x, p.y); glEnd(); glFlush(); } void drawHorizon(int start, int end, int y) { for(;start<=end;start++){ setPixel(Point(start, y)); } } /* * 扫描线从低到高扫描 * 先更新活动边表x值,每一对点画一条线段。 * 查看当前y值是否有新线段加入,有则入加,并排序。 */ void fillPolygen(vector<Line> polygen) { //1. 对线段按照底端从低到高排序 sort(polygen.begin(), polygen.end(), cmpLine); // 2. 查找最低点与最高点 int minY = polygen[0].low.y; int maxY = polygen[0].high.y; for (Line l : polygen){ maxY = max(maxY, l.high.y); } // 定义活动边表 vector<ActiveEdge> ae; for(int h=minY, j=0;h<=maxY;h++) { bool needSort=false; // 更新提有活动边x值。 for(int i=0;i<ae.size();i++) { if (h>ae[i].maxY)continue; if (ae[i].deltaX) ae[i].x += ae[i].k; // 每两点画一条线 if (i&1 && h<=ae[i].maxY) { drawHorizon(ae[i-1].x, ae[i].x, h); } if (h>=ae[i].maxY && !needSort) needSort=true; // 有边需要删除,删除采用假删除,将无用边排到最后边去 } // 查看当前是否有边加入 for(;j<polygen.size() && polygen[j].low.y==h;j++){ // 平行边不需要 if (polygen[j].low.y== polygen[j].high.y)continue; if (!needSort) needSort=true; // 有新边加入,需要排序 ActiveEdge newEdge; newEdge.maxY = polygen[j].high.y; newEdge.x = polygen[j].low.x; newEdge.deltaX = polygen[j].high.x-polygen[j].low.x; newEdge.deltaY = polygen[j].high.y-polygen[j].low.y; newEdge.k = double(newEdge.deltaX) / double(newEdge.deltaY); // ∆x/∆y ae.push_back(newEdge); } if (needSort) { curY=h; sort(ae.begin(), ae.end(), cmpActiveEdge); } } } vector<Line> getTriangle() { vector<int> pList = { -100,-200,200,50, -100,-200,0,100, 0,100,200,50, }; vector<Line> sq; for(int i=0;i+3<pList.size();i+=4){ sq.push_back(Line(Point(pList[i]-350,pList[i+1]-250),Point(pList[i+2]-350,pList[i+3]-250))); } return sq; } vector<Line> get5Triangle() { vector<int> pList = { -100,-200,150,0, -100,-200,0,100, -150,0,150,0, 100,-200,-150,0, 100,-200,0,100, }; vector<Line> sq; //glBegin(GL_LINES); for(int i=0;i+3<pList.size();i+=4){ sq.push_back(Line(Point(pList[i]-350,pList[i+1]+50),Point(pList[i+2]-350,pList[i+3]+50))); //glVertex2i(pList[i],pList[i+1]); //glVertex2i(pList[i+2],pList[i+3]); } //glEnd(); return sq; } vector<Line> getUnNor() { vector<int> pList = { -10,10,100,-50, 120,51,150,-58, 170,100,200,-50, 300,150,250,120,300,170,270,200, 210,180,200,250, 150,210, 110,230, }; vector<Line> sq; // glBegin(GL_LINES); for(int i=0;i+3<pList.size();i+=2){ sq.push_back(Line(Point(pList[i],pList[i+1]),Point(pList[i+2],pList[i+3]))); //glVertex2i(pList[i],pList[i+1]); //glVertex2i(pList[i+2],pList[i+3]); } int n = pList.size(); sq.push_back(Line(Point(pList[n-2],pList[n-1]),Point(pList[0],pList[1]))); //glVertex2i(pList[n-2],pList[n-1]); //glVertex2i(pList[0],pList[1]); //glEnd(); return sq; } vector<Line> getSquare() { vector<int> pList = { 0,0,100,0, 0,0,0,100, 100,0,100,100, 0,100,100,100, }; vector<Line> sq; for(int i=0;i+3<pList.size();i+=4){ sq.push_back(Line(Point(pList[i]-350,pList[i+1]+250),Point(pList[i+2]-350,pList[i+3]+250))); } return sq; } int main(void) { //初始化GLFW库 if (!glfwInit()) return -1; //创建窗口以及上下文 GLFWwindow *window = glfwCreateWindow(1024, 900, "hello world", NULL, NULL); if (!window) { //创建失败会返回NULL glfwTerminate(); } //建立当前窗口的上下文 glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); //注册回调函数 //glViewport(0, 0, 400, 400); gluOrtho2D(-512, 512, -450, 450); //循环,直到用户关闭窗口 cout<<123<<endl; while (!glfwWindowShouldClose(window)) { /*******轮询事件*******/ glfwPollEvents(); //选择清空的颜色RGBA glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); vector<Line> polygen = getSquare(); glColor3f(1,0, 0); fillPolygen(polygen); polygen = getTriangle(); glColor3f(1,1, 0); fillPolygen(polygen); glColor3f(1,0, 1); polygen = get5Triangle(); fillPolygen(polygen); polygen = getUnNor(); fillPolygen(polygen); /******交换缓冲区,更新window上的内容******/ glfwSwapBuffers(window); //break; } glfwTerminate(); return 0; }
true
f1a4a3ac3b3df2f643f36d4d83145cab75364ded
C++
patrykpk/FYS4150
/Project_3/Scripts/C++ Scripts/Unit_Test/test.cpp
UTF-8
1,085
3.0625
3
[]
no_license
#define CATCH_CONFIG_MAIN #include <iostream> #include <cmath> #include <string> #include <iomanip> #include "catch.hpp" #include "lib.h" using namespace std; TEST_CASE("Checking if gauleg finds correct roots for 5th degree Legendre polynomial"){ int a = -1; int b = 1; int n = 5; double *x = new double [n]; double *w = new double [n]; gauss_legendre(a,b,x,w,n); // Checking for tabulated roots CHECK ( x[0] == Approx(-0.9061798459)); CHECK ( x[1] == Approx(-0.5384693101)); CHECK ( x[2] == Approx(0)); CHECK ( x[3] == Approx(0.5384693101)); CHECK ( x[4] == Approx(0.9061798459)); } TEST_CASE("Checking if gauss_laguerre finds the correct roots for 4th degree Laguerre polynomial"){ int n = 4; double *x = new double [n]; double *w = new double [n]; double alpha = 0; gauss_laguerre(x,w,n,alpha); // Checking for tabulated roots CHECK ( x[1] == Approx(0.3225476896)); CHECK ( x[2] == Approx(1.745761102)); CHECK ( x[3] == Approx(4.536620297)); CHECK ( x[4] == Approx(9.395070912)); }
true
0a54cb7d05c640d1d941607523def883ba66b155
C++
shivam-tripathi/code
/practice/graphs/colourfulGraph.cpp
UTF-8
949
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; vector<pii> adj[110]; int n, m; int a, b, c; bool visited[110]; bool dfs(int src, int c) { visited[src] = true; if (src == b) return true; for(int i=0; i<adj[src].size(); i++) { int node = adj[src][i].first; int color = adj[src][i].second; if (color == c && !visited[node]) { if (dfs(node, c)) return true; } } return false; } int main(int argc, char const *argv[]) { cin >> n >> m; for(int i=0; i<m; i++) { cin >> a >> b >> c; adj[a].push_back(pii(b,c)); adj[b].push_back(pii(a,c)); } int q; cin >> q; int ans; while(q--) { cin >> a >> b; ans=0; set<int> colorset; for(int i=0; i<adj[a].size(); i++) { int color = adj[a][i].second; if(colorset.find(color) != colorset.end()) continue; memset(visited, false, sizeof visited); if (dfs(a, color)) ans++; colorset.insert(color); } cout << ans << endl; } return 0; }
true
17777b7061825200474db82cfa4013adc2015ff2
C++
singhdharmveer311/PepCoding
/Level-2/18. Recursion-and-Backtracking/Coin Change - Permutations - 2.cpp
UTF-8
544
2.984375
3
[ "Apache-2.0" ]
permissive
#include "bits/stdc++.h" using namespace std; void coinchangePermutation(int idx,int *arr,int n,int sum,int ssf,string asf){ if(ssf > sum) { return; } if(ssf == sum){ cout << asf << "."<< endl; return; } for(int i=0;i<n;i++){ // if(arr[i]!=0){ int cn=arr[i]; // arr[i]=0; coinchangePermutation(i,arr,n,sum,ssf+cn,asf+to_string(cn)+"-"); // arr[i]=cn; // } } } int main(){ int n; cin >> n; int arr[n]; for(int i=0;i<n;i++){ cin >> arr[i]; } int sum; cin>> sum; coinchangePermutation(0,arr,n,sum,0,""); }
true
5c61e93a5895c4964ab2c1da3ff8714cf412900c
C++
insightcs/PAT
/AdvancedLevel/general_oalindromic_number.cpp
UTF-8
591
3.125
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main(int argc, char *argv[]) { unsigned int N = 0, base = 0; vector<unsigned int> result; unsigned int i = 0; cin >> N >> base; do { result.push_back(N % base); N /= base; }while(N); unsigned int size = result.size(); bool flag = true; for(i=0;i<size/2;i++) { if(result[i]!=result[size-1-i]) { flag = false; break; } } if(flag) cout << "Yes" << endl; else cout << "No" << endl; auto it=result.crbegin(); for(;it!=result.crend()-1;it++) cout << *it << ' '; cout << *it << endl; return 0; }
true
81da66d95d6f60019d53ded236c985ded72a4ff4
C++
Azure/azure-sdk-for-cpp
/sdk/core/azure-core/inc/azure/core/internal/diagnostics/log.hpp
UTF-8
7,443
3.03125
3
[ "MIT", "LicenseRef-scancode-generic-cla", "curl", "LGPL-2.1-or-later", "BSD-3-Clause", "ISC" ]
permissive
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "azure/core/diagnostics/logger.hpp" #include "azure/core/dll_import_export.hpp" #include <atomic> #include <iostream> #include <sstream> #include <type_traits> namespace Azure { namespace Core { namespace Diagnostics { namespace _internal { /** @brief Internal Log class used for generating diagnostic logs. * * When components within the Azure SDK wish to emit diagnostic log messages, they should use the * Azure::Core::Diagnostics::_internal::Log class to generate those messages. * * The Log class methods integrate with the public diagnostic logging infrastructure to generate * log messages which will be captured by either the default logger or a customer provided logger. * * Usage: * * There are two primary interfaces to the Log class. The first (and most common) is to use the * Log::Write method to write a string to the configured logger. For example: * * ```cpp * using namespace Azure::Core::Diagnostics::_internal; * using namespace Azure::Core::Diagnostics; * : * : * Log::Write(Logger::Level::Verbose, "This is a diagnostic message"); * ``` * * this will pass the string "This is a diagnostic message" to the configured logger at the * "Verbose" error level. * * The second interface is to use the Log::Stream() class to stream a string to the configured * logger. For example: * * ```cpp * using namespace Azure::Core::Diagnostics::_internal; * using namespace Azure::Core::Diagnostics; * : * : * int resultCode = 500; * Log::Stream(Logger::Level::Error) << "An error has occurred " << resultCode; * ``` * * this will pass the string "An error has occurred 500" to the configured logger at the "Error" * error level. * */ class Log final { static_assert( std::is_same<int, std::underlying_type<Logger::Level>::type>::value == true, "Logger::Level values must be representable as lock-free"); static_assert(ATOMIC_INT_LOCK_FREE == 2, "atomic<int> must be lock-free"); static_assert(ATOMIC_BOOL_LOCK_FREE == 2, "atomic<bool> must be lock-free"); static AZ_CORE_DLLEXPORT std::atomic<bool> g_isLoggingEnabled; static AZ_CORE_DLLEXPORT std::atomic<Logger::Level> g_logLevel; Log() = delete; ~Log() = delete; /** @brief String buffer for use in the logger. * * A specialization of std::stringbuf for use in the logger. * * This function primarily exists to implement the sync() function which triggers a call to * Log::Write(). */ class LoggerStringBuffer : public std::stringbuf { public: /** @brief Configure a LogStringBuffer with the specified logging level. */ LoggerStringBuffer(Logger::Level level) : m_level{level} {} LoggerStringBuffer(LoggerStringBuffer&& that) = default; LoggerStringBuffer& operator=(LoggerStringBuffer&& that) = default; ~LoggerStringBuffer() override = default; /** @brief Implementation of std::basic_streambuf<char>::sync. * * @returns 0 on success, -1 otherwise. */ virtual int sync() override; private: Logger::Level m_level; }; /** @brief Logger Stream used internally by the GetStream() private method. * * Stream class used to wrap a LoggerStringBuffer stringbuf object. */ class LoggerStream : public std::basic_ostream<char> { public: LoggerStream(Logger::Level level) : std::ostream(&m_stringBuffer), m_stringBuffer{level} {} ~LoggerStream() override = default; private: LoggerStringBuffer m_stringBuffer; }; public: /** @brief Stream class used to enable using iomanip operators on an I/O stream. * Usage: * * ```cpp * using namespace Azure::Core::Diagnostics::_internal; * using namespace Azure::Core::Diagnostics; * : * : * int resultCode = 500; * Log::Stream(Logger::Level::Error) << "An error has occurred " << resultCode; * ``` * * this will pass the string "An error has occurred 500" to the configured logger at the "Error" * error level. * * @remarks The Log::Stream() construct creates a temporary Stream object whose lifetime ends a * the end of the statement creating the Stream object. In the destructor for the stream, the * underlying stream object is flushed thus ensuring that the output is generated at the end of * the statement, even if the caller does not insert the std::endl object. */ class Stream { public: /** @brief Construct a new Stream object with the configured I/O level. * * @param level - Represents the desired diagnostic level for the operation. */ Stream(Logger::Level level) : m_stream(GetStream(level)) {} /** @brief Called when the Stream object goes out of scope. */ ~Stream() { m_stream.flush(); } Stream(Stream const&) = delete; Stream& operator=(Stream const&) = delete; /** @brief Insert an object of type T into the output stream. * * @tparam T Type of the object being inserted. * @param val value to be inserted into the underlying stream. */ template <typename T> std::ostream& operator<<(T val) { return m_stream << val; } private: LoggerStream& m_stream; }; /** @brief Returns true if the logger would write a string at the specified level. * * This function primarily exists to enable callers to avoid expensive computations if the * currently configured log level doesn't support logging at the specified level. * * @param level - log level to check. * @returns true if the logger will write at that log level. */ static bool ShouldWrite(Logger::Level level) { return g_isLoggingEnabled && level >= g_logLevel; } /** @brief Write a string to the configured logger at the specified log level. * * Expected usage: * * ```cpp * using namespace Azure::Core::Diagnostics::_internal; * using namespace Azure::Core::Diagnostics; * : * : * Log::Write(Logger::Level::Verbose, "This is a diagnostic message"); * ``` * * this will pass the string "This is a diagnostic message" to the configured logger at the * "Verbose" error level. * * @param level - log level to use for the message. * @param message - message to write to the logger. * */ static void Write(Logger::Level level, std::string const& message); /** @brief Enable logging. * * @param isEnabled - true if logging should be enabled, false if it should be disabled. */ static void EnableLogging(bool isEnabled); /** @brief Set the current log level globally. * * Note that this overrides any customer configuration of the log level and should generally be * avoided. * * @param logLevel - New global log level. */ static void SetLogLevel(Logger::Level logLevel); private: static LoggerStream g_verboseLogger; static LoggerStream g_informationalLogger; static LoggerStream g_warningLogger; static LoggerStream g_errorLogger; static LoggerStream& GetStream(Logger::Level level); }; }}}} // namespace Azure::Core::Diagnostics::_internal
true
b906860d074d0faf6c610fd8329fb459d5f30a5a
C++
joycitta-siqueira/ProgramacaoEstruturada
/ordenacao.cpp
UTF-8
439
3.25
3
[]
no_license
// ORDENAÇÃO #include <stdio.h> int main() { int num[5] = {0, 3, 1, 4, 2}, i, j, aux; for (i = 0; i < 4; i++) { for (j = i + 1; j < 5; j++) { if (num[i] > num[j]) { aux = num[i]; num[i] = num[j]; num[j] = aux; } } } printf("Vetor ordenado\n"); for (i = 0; i < 5; i++) printf("%d\t", num[i]); }
true
c3c736bed3d5b3db41ec5a3d728f05c123b39d42
C++
maomihz/kattis
/src/battlesimulation/battlesimulation.cpp
UTF-8
1,134
2.609375
3
[]
no_license
#include <iostream> #include <sstream> #include <stdexcept> #include <vector> #include <string> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <queue> #include <deque> #include <stack> #include <climits> #include <algorithm> #include <stdio.h> #include <stdlib.h> using namespace std; int main() { char ch, counter; char moves[1000001]; char check[3]; int ci = 0; // Check index int mi = 0; // Move index while (cin >> ch) { if (ch == 'R') { counter = 'S'; } else if (ch == 'B') { counter = 'K'; } else if (ch == 'L') { counter = 'H'; } moves[mi++] = counter; if (ci++ >= 2) { unordered_set<char> us; us.insert(moves[mi - 3]); us.insert(moves[mi - 2]); us.insert(moves[mi - 1]); if (us.size() == 3) { moves[mi - 3] = 'C'; mi -= 2; ci = 0; } } } moves[mi] = '\0'; cout << moves << endl; return 0; }
true
dd6cb62681042c146b423165d76054a39a02bcdb
C++
yukar1z0e/0day-Security
/Pointer/Pointer.cpp
UTF-8
2,782
2.90625
3
[ "Apache-2.0" ]
permissive
// Pointer.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <stdio.h> void f1(int x, int y, int* sum, int* product) { *sum = x + y; *product = x * y; }; int sum, product; void main() { f1(123, 456, &sum, &product); printf("sum=%d, product=%d\n", sum, product); }; /* --- C:\Users\test\0daySecurity\Pointer\Pointer.cpp ----------------------------- 1: // Pointer.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 2: // 3: 4: #include <stdio.h> 5: 6: void f1(int x, int y, int* sum, int* product) 7: { 004E1080 55 push ebp 004E1081 8B EC mov ebp,esp 8: *sum = x + y; 004E1083 8B 45 08 mov eax,dword ptr [x] 004E1086 03 45 0C add eax,dword ptr [y] 004E1089 8B 4D 10 mov ecx,dword ptr [sum] 004E108C 89 01 mov dword ptr [ecx],eax 9: *product = x * y; 004E108E 8B 55 08 mov edx,dword ptr [x] 004E1091 0F AF 55 0C imul edx,dword ptr [y] 004E1095 8B 45 14 mov eax,dword ptr [product] 004E1098 89 10 mov dword ptr [eax],edx 10: }; 004E109A 5D pop ebp 004E109B C3 ret --- 无源文件 ----------------------------------------------------------------------- 004E109C CC int 3 004E109D CC int 3 004E109E CC int 3 004E109F CC int 3 --- C:\Users\test\0daySecurity\Pointer\Pointer.cpp ----------------------------- 11: 12: int sum, product; 13: 14: void main() 15: { 004E10A0 55 push ebp 004E10A1 8B EC mov ebp,esp 16: f1(123, 456, &sum, &product); 004E10A3 68 78 33 4E 00 push offset product (04E3378h) 004E10A8 68 74 33 4E 00 push offset sum (04E3374h) 004E10AD 68 C8 01 00 00 push 1C8h 004E10B2 6A 7B push 7Bh 004E10B4 E8 C7 FF FF FF call f1 (04E1080h) 004E10B9 83 C4 10 add esp,10h 17: printf("sum=%d, product=%d\n", sum, product); 004E10BC A1 78 33 4E 00 mov eax,dword ptr [product (04E3378h)] 004E10C1 50 push eax 004E10C2 8B 0D 74 33 4E 00 mov ecx,dword ptr [sum (04E3374h)] 004E10C8 51 push ecx 004E10C9 68 08 21 4E 00 push 4E2108h 004E10CE E8 6D FF FF FF call printf (04E1040h) 004E10D3 83 C4 0C add esp,0Ch 18: }; 004E10D6 33 C0 xor eax,eax 004E10D8 5D pop ebp 004E10D9 C3 ret */
true
931ef9460db442499d4bb6cc6bb162a4841fda26
C++
dtraczewski/zpk2014
/home/dtraczewski/z2/nwd.cpp
UTF-8
377
2.890625
3
[]
no_license
#include <iostream> using namespace std; int nwd (int a, int b) { int r = a % b; while (r != 0) { a = b; b = r; r = a % b; } return b; } int main() { unsigned short n, a, x; cin >> n; cin >> a; x = a; for (unsigned short i = 2; i <= n; i++) { cin >> a; x = nwd(x, a); } cout << x << endl; }
true
b0dd98904c17ead0b3bd198c27ad84b197f24230
C++
shiinamiyuki/lunatic
/include/lunatic/opcode.h
UTF-8
1,840
2.546875
3
[ "MIT" ]
permissive
#pragma once #include <lunatic/common.h> namespace lunatic { constexpr size_t REG_MAX = 256; enum class Opcode { Add, //ABC Sub, //ABC Mul, //ABC Div, //ABC Mod,//ABC iDiv, //ABC, Concat, //ABC And, Or, Not, Neg, Len, LT, GT, LE, GE, NE, EQ, LoadNil, LoadInt, // A i32 LoadFloat, // A f64 LoadStr, // A Bx LoadBool, //A Bx LoadGlobal, //A Bx LoadRet,// A B GetValue,//A B C C = A[B] StoreValue,//A B C A[B] = C StoreRet,//A B StoreGlobal,//A Bx Move,//A B BRC, BZ, BNZ, Push,//A fCall,//A B C A: func reg B : number of args C: number of rets invoke,//A Bx Ret, MakeClosure, SetArgCount,// A i32 NewTable, Clone,//A B SetProto,// A B Break, MakeUpvalue,//A Upvalue -> A LoadUpvalue,//A B A: dest, Bx: index StoreUpvalue,//A B A: upvalue, Bx : index SetUpvalue,//A B , A: Closure, B: upvalue, ForLoopPrep, //A R[A], R[A+1], R[A+2] = Ret[0:3] ForLoopAssign, //A, Bx R[A:A+Bx] = Ret[0:Bx] }; struct Instruction { Opcode opcode; char operand[10]; inline int getA() const { return operand[0]; } inline int getB() const { return operand[1]; } inline int getC() const { return operand[2]; } inline int getInt() const { return *(int*)(operand + 1); } inline double getFloat() const { return *(double*)(operand + 1); } inline int getBx() const { return getInt() & 0xffff; } Instruction(Opcode op, int A, int B, int C) { opcode = op; operand[0] = A & 0xff; operand[1] = B & 0xff; operand[2] = C & 0xff; } Instruction(Opcode op, int A, int Bx) { opcode = op; operand[0] = A & 0xff; *(int*)(operand + 1) = Bx; } Instruction(Opcode op, int A, double f) { opcode = op; operand[0] = A & 0xff; *(double*)(operand + 1) = f; } std::string str()const; }; }
true
57758f3e2354ca78358e7e871a55abad9ae769b6
C++
TrieuKhanh/thuvientinh
/phepcong.cpp
UTF-8
502
2.59375
3
[]
no_license
#include "phepcong.h" #include <iostream> phepcong::phepcong(const int a, const int b) { std::cout << __FUNCTION__ << "__builtin_extract_return_addr(__builtin_return_address(0)): " << __builtin_extract_return_addr(__builtin_return_address(0)) << &std::endl; std::cout << __FUNCTION__ << "__builtin_return_address(0): " << __builtin_return_address(0) << &std::endl; m_a=a; m_b=b; m_re = m_a+m_b; } int phepcong::get() { return m_re; }
true
13edbcc3d091aa9ff9c72fab61c0521e952318ae
C++
prestocore/browser
/adjunct/m2/src/backend/irc/color-parser.h
UTF-8
3,414
2.546875
3
[]
no_license
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2006 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef IRC_COLOR_PARSER_H #define IRC_COLOR_PARSER_H # include "modules/util/adt/opvector.h" //**************************************************************************** // // ColorParserHandler // //**************************************************************************** class ColorParserHandler { public: virtual ~ColorParserHandler() {} enum color_type { COLOR_NONE = -1, COLOR_WHITE = 0, COLOR_BLACK = 1, COLOR_BLUE = 2, COLOR_GREEN = 3, COLOR_LIGHTRED = 4, COLOR_BROWN = 5, COLOR_PURPLE = 6, COLOR_ORANGE = 7, COLOR_YELLOW = 8, COLOR_LIGHTGREEN = 9, COLOR_CYAN = 10, COLOR_LIGHTCYAN = 11, COLOR_LIGHTBLUE = 12, COLOR_PINK = 13, COLOR_GREY = 14, COLOR_LIGHTGREY = 15, COLOR_TRANSPARENT = 99 }; static BOOL IsValidColorValue(int Value); virtual void OnPlainTextBegin() { } virtual void OnPlainTextEnd() { } virtual void OnBoldTextBegin() { } virtual void OnBoldTextEnd() { } virtual void OnColorTextBegin(color_type text_color, color_type background_color = COLOR_NONE) { } virtual void OnColorTextEnd() { } virtual void OnReverseTextBegin() { } virtual void OnReverseTextEnd() { } virtual void OnUnderlineTextBegin() { } virtual void OnUnderlineTextEnd() { } virtual void OnCharacter(uni_char character) { } }; //**************************************************************************** // // mIRCColorParser // //**************************************************************************** class mIRCColorParser { public: // Construction / destruction. mIRCColorParser(ColorParserHandler &handler); ~mIRCColorParser(); // Methods. OP_STATUS Parse(const OpStringC& text); private: // No copy or assignment. mIRCColorParser(const mIRCColorParser& other); mIRCColorParser& operator=(const mIRCColorParser& other); // Enumerations. enum ParseState { STATE_INSIDE_PLAIN_TEXT, STATE_INSIDE_BOLD_TEXT, STATE_INSIDE_UNDERLINED_TEXT, STATE_INSIDE_REVERSED_TEXT, STATE_INSIDE_COLOR_TEXT_CODE, STATE_INSIDE_COLOR_BACKGROUND_CODE, STATE_INSIDE_COLORED_TEXT }; // Methods. void ClearStack(); OP_STATUS StackPush(ParseState state); void StackPop(); ParseState StackTop() const; BOOL StackIsEmpty() const { return m_state_stack.GetCount() == 0; } // Static members. static uni_char m_plain_code; static uni_char m_bold_code; static uni_char m_color_code; static uni_char m_reverse_code; static uni_char m_underline_code; // Members. ColorParserHandler &m_handler; OpINT32Vector m_state_stack; }; //**************************************************************************** // // IRCColorStripper // //**************************************************************************** class IRCColorStripper : public ColorParserHandler { public: virtual ~IRCColorStripper() {} // Construction. IRCColorStripper() { } OP_STATUS Init(const OpStringC& text); // Accessor. const OpStringC& StrippedText() const { return m_stripped_text; } private: // ColorParserHandler. virtual void OnCharacter(uni_char character) { m_stripped_text.Append(&character, 1); } // Members. OpString m_stripped_text; }; #endif
true
8483e3242f0066f7f71eb8137f55bad02ad9e914
C++
lewisHeath/VisualSorter
/visualSorter/src/drawer.cpp
UTF-8
801
3.078125
3
[]
no_license
// // drawer.cpp // visualSorter // // Created by Benjamin Lewis-Jones on 26/10/2021. // #include "../headers/drawer.hpp" ///* #include <iostream> using namespace std; //*/ Drawer::Drawer() : square(sf::Vector2f(20.0f, 20.0f)) { square.setFillColor(sf::Color::Red); square.setPosition(-20.0f, 20.0f); } void Drawer::display(sf::RenderWindow* window) { window->draw(square); } void Drawer::updatePosition(sf::RenderWindow* window) { // allows the user to move the position of the square sf::Vector2i mousePosition = sf::Mouse::getPosition(*window); cout << mousePosition.x << ' ' << mousePosition.y << endl; if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) square.setPosition(static_cast<float>(mousePosition.x), static_cast<float>(mousePosition.y)); }
true
44985309659d6d2a6b3fc2b19ac17adf4b01c008
C++
niuxu18/logTracker-old
/second/download/git/gumtree/git_repos_function_4895_git-2.3.10.cpp
UTF-8
296
2.515625
3
[]
no_license
static void pretty_print_menus(struct string_list *menu_list) { unsigned int local_colopts = 0; struct column_options copts; local_colopts = COL_ENABLED | COL_ROW; memset(&copts, 0, sizeof(copts)); copts.indent = " "; copts.padding = 2; print_columns(menu_list, local_colopts, &copts); }
true
9daee7164a6f058f3ea3903b81588468e6ca42fa
C++
GKimGames/parkerandholt
/Box2DandOgre/include/FSMStateMachine.h
UTF-8
4,402
3.140625
3
[]
no_license
/*============================================================================= FSMStateMachine.h Author: Matt King Finite State Machine =============================================================================*/ #ifndef FSMSTATEMACHINE_H #define FSMSTATEMACHINE_H #include "FSMState.h" #include "GameObjectOgreBox2D.h" /// Finite state machines have two states at a time, a global state and a /// current state, both are updated every cycle if they exist. template <class T> class FSMStateMachine { public: FSMStateMachine(T* driver): driver_(driver), currentState_(0), previousState_(0), globalState_(0) { // Do Nothing } /// Delete the current state and global state if they exist. virtual ~FSMStateMachine() { if(currentState_ != 0) { delete currentState_; } if(globalState_ != 0) { delete globalState_; } } /// Update the FSM bool Update() { // If a global state exists update it. if(globalState_) { globalState_->Update(); } // If a current state exists update it. if (currentState_) { return currentState_->Update(); } return true; } /// Change current state to newState. /// This calls the exit method of the current state before calling the /// enter method of the new state. void ChangeState(FSMState<T>* newState) { previousState_ = currentState_; currentState_->Exit(); currentState_ = newState; currentState_->Enter(); } /// Change the current state back to the previous state. This calls /// ChangeState to change the state. void RevertToPreviousState() { ChangeState(previousState_); } /// Returns true if the current state's type is equal to the type of the /// class passed as a parameter. bool IsInState(const FSMState<T>& state )const { return typeid(*currentState_) == typeid(state); } /*============================================================================= These methods really should be in a class that extends FSMStateMachine but for the sake of convenience they are in here. =============================================================================*/ /// Send a message to the FSM bool HandleMessage(const KGBMessage message) { // If a global state exists hand it the message. if(globalState_) { globalState_->HandleMessage(message); } // If a current state exists hand it the message. if (currentState_) { return currentState_->HandleMessage(message); } return true; } /// Called when two fixtures begin to touch. void BeginContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture) { currentState_->BeginContact(contact,contactFixture, collidedFixture); } /// Called when two fixtures cease to touch. void EndContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture) { currentState_->EndContact(contact,contactFixture, collidedFixture); } void PostSolve(b2Contact* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture, const b2ContactImpulse* impulse) { currentState_->PostSolve(contact, contactFixture, collidedFixture, impulse); } /*============================================================================= Getter / Setter methods =============================================================================*/ void SetCurrentState(FSMState<T>* state) { currentState_ = state;} void SetGlobalState(FSMState<T>* state) { globalState_ = state;} void SetPreviousState(FSMState<T>* state) { previousState_ = state;} FSMState<T>* GetCurrentState() const { return currentState_;} FSMState<T>* GetGlobalState() const { return globalState_;} FSMState<T>* GetPreviousState() const { return previousState_;} protected: /// A pointer to the object that drives the state machine. T* driver_; FSMState<T>* currentState_; /// The previous state the machien was in. FSMState<T>* previousState_; /// The global state is updated all of the time and regularly does not change. FSMState<T>* globalState_; }; #endif
true
06c9c153427be89f3e97a610c6aab9bce2cc0f3f
C++
MarUser04/Sudoku-Binario
/main.cpp
UTF-8
2,397
2.6875
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <conio.h> #include <time.h> struct Mapa{ int **matriz; int filas, columnas; }; void cargarmatriz(Mapa *mapa); void mover(Mapa *mapa); int main(int argc, char** argv) { system("color b"); srand(time(0)); Mapa mapa; cargarmatriz(&mapa); printf("\n\n"); mover(&mapa); system("pause>null"); return 0; } void cargarmatriz(Mapa *mapa) { char opc; int aux; do{ system("cls"); printf("-------BIENVENIDO---------\n"); printf("1.---------4x4------------\n"); printf("2.---------6x6------------\n"); printf("3.---------8x8------------\n"); printf("4.---------10x10------------\n"); printf("-------ELIGA UNA OPCION.---------\n"); fflush(stdin); opc= getch(); aux=opc-48; }while(aux<1 || aux>4); switch(aux) { case 1: mapa->filas=4; mapa->columnas=4; break; case 2: mapa->filas=6; mapa->columnas=6; break; case 3: mapa->filas=8; mapa->columnas=8; break; case 4: mapa->filas=10; mapa->columnas=10; break; } mapa->matriz= new int *[mapa->filas]; for(int i=0; i<mapa->filas; i++) { mapa->matriz[i]=new int [mapa->columnas]; } for(int i=0;i<mapa->filas;i++){ for(int j=0;j<mapa->columnas;j++){ mapa->matriz[i][j]=rand()%9; } } for(int i=0;i<mapa->filas;i++){ printf("\n"); for(int j=0;j<mapa->columnas;j++){ if(mapa->matriz[i][j]==0 || mapa->matriz[i][j]==1 ) { printf(" %d ",mapa->matriz[i][j]); } else { printf(" - "); } } } } void mover(Mapa *mapa) { char tecla; int x=0, y=0; while(1) { for(int i=0; i<mapa->filas; i++) { printf("\n"); for(int j=0; j<mapa->columnas; j++) { if(x==j && y==i) { if(mapa->matriz[i][j]==0 || mapa->matriz[i][j]==1) { printf("[%d]", mapa->matriz[i][j]); } else { printf("[-]", mapa->matriz[i][j]); } } else{ if(mapa->matriz[i][j]==0 || mapa->matriz[i][j]==1) { printf(" %d ", mapa->matriz[i][j]); } else { printf(" - ", mapa->matriz[i][j]); } } }//for j }//for i tecla=getch(); if(tecla=='a' && x>0 ) x--; else if(tecla== 'd' && x<mapa->filas-1 ) x++; else if(tecla=='s' && y<mapa->columnas-1) y++; else if( tecla== 'w' && y>0) y--; system("cls"); }//while }
true
cd0a2b0aed133c50ac63bc14230118578ec4ef94
C++
SUQIGUANG/loop_subdivision
/src/LOOP.cpp
UTF-8
3,295
3.125
3
[ "MIT" ]
permissive
// loop-subdivision // // Author : Mi, Liang (Arizona State University) // Email : icemiliang@gmail.com // Date : Feb 22nd 2020 // License : MIT #include "LOOP.h" #include <assert.h> #include <math.h> #include <float.h> #include <iostream> #include <sstream> using namespace MeshLib; LOOP::LOOP(Mesh * mesh1, Mesh *mesh2) { m_mesh1 = mesh1; m_mesh2 = mesh2; } LOOP::~LOOP(){} float LOOP::calculateAlpha(int n){ float alpha; if (n > 3){ float center = (0.375f + (0.25f * cos(6.2831853f / (float)n))); // 2.0f * 3.1415926f alpha = (0.625f - (center * center)) / (float)n; } else { alpha = 0.1875f; // 3.0f / 16.0f; } return alpha; } void LOOP::subdivide() { // scan all vertices and update its coordinates int vid = 0; for (MeshVertexIterator viter(m_mesh1); !viter.end(); ++viter){ Vertex *v = *viter; Vertex *vNew = m_mesh2->create_vertex(++vid); // Crease if (v->boundary()) { //vNew->point() = v->point(); // Linear, blow is quadratic std::vector <Point > plist; // find most clw neighbor HalfEdge *a = v->halfedge(); while (a->clw_rotate_about_target()) { a = a->clw_rotate_about_target(); } a = a->he_next(); // find most ccw neighbor HalfEdge *b = v->halfedge(); while (b->ccw_rotate_about_target()) { b = b->clw_rotate_about_target(); } // assign new value vNew->point() = v->point() * 0.75f + (b->source()->point() + a->target()->point()) * 0.125f; } else { // examine all neighboring vertices std::vector <Point > plist; HalfEdge *he = v->halfedge(); int n = 0; // clw rotate do { plist.push_back(he->source()->point()); // save point he = he->clw_rotate_about_target(); n++; } while (he != v->halfedge()); float alpha = calculateAlpha(n); Point temp = {0.0f, 0.0f, 0.0f}; for (int i = 0; i < n; i++){ temp += plist.back(); plist.pop_back(); } // assign value vNew->point() = v->point() * (1 - n * alpha) + temp * alpha; } v_v(v) = vNew; } // scan all edges and create vertex on each edge for (MeshEdgeIterator eiter(m_mesh1); !eiter.end(); ++eiter){ Edge *e = *eiter; Vertex *ev1 = e->halfedge(0)->source(); Vertex *ev2 = e->halfedge(0)->target(); Vertex *vNew = m_mesh2->create_vertex(++vid); // Crease if (e->boundary()){ vNew->point() = (ev1->point() + ev2->point()) * 0.5f; } else{ vNew->point() = (ev1->point() + ev2->point()) * 0.375f; Vertex *vt1 = e->halfedge(0)->he_next()->target(); Vertex *vt2 = e->halfedge(1)->he_next()->target(); vNew->point() = vNew->point() + (vt1->point() + vt2->point()) * 0.125f; } e_v(e) = vNew; } // Create new faces int fid = 0; for (MeshFaceIterator fiter(m_mesh1); !fiter.end(); ++fiter){ Face *f = *fiter; HalfEdge * fhe[3]; fhe[0] = f->halfedge(); fhe[1] = fhe[0]->he_next(); fhe[2] = fhe[1]->he_next(); Vertex * v[3]; // create the central small triangle for (int i = 0; i < 3; i++){ v[i] = e_v(fhe[i]->edge()); } m_mesh2->create_face(v, ++fid); // create small triangles in three corners for (int i = 0; i < 3; i++){ v[0] = v_v(fhe[i]->source()); v[1] = e_v(fhe[i]->edge()); v[2] = e_v(fhe[(i + 2 ) % 3]->edge()); m_mesh2->create_face(v, ++fid); } } m_mesh2->refine_halfedge_structure(); }
true
ea803319c6e5e7b51a07068947fd23196b3a9fd2
C++
xuxinqiujiaoyizhiyang/c-normal
/c/Huffman tree.cpp
GB18030
3,657
2.796875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include<string.h> typedef struct BiThrNode { float weight; int parent,lchild,rchild; char data; } HTNode,*HuffmanTree; typedef char** HuffmanCode; void Select(HuffmanTree HT,int n,int &s1,int &s2)//parent=0С { float *a; int x=1; s1=0,s2=0; a=(float *)malloc(100*sizeof(float)); for(int k=1;k<=n;k++)//parent=0weightµa { if(HT[k].parent==0) { a[x]=HT[k].weight; x++; } } x--; for(int i=1; i<=x; i++)//aС { for(int j=1; j<=x-i; j++) { if(a[j] > a[j+1]) { float temp = a[j]; a[j] =a[j+1]; a[j+1]=temp; } } } for(int i=1;i<=n;i++)//aСƥHTеλ { int count=0; if(s1==0&&HT[i].parent==0)//s1ȷs1ûбֵ { if(a[1]==HT[i].weight) {s1=i; count++;} } if(count==0&&s2==0&&a[2]==HT[i].weight&&HT[i].parent==0)//countñ֤s1ֵٸs2ֵ s2=i; } } void CreaHuffman(HuffmanTree &HT,float *w,int n,char *ch) { if(n<=1) return; int i,k,s1=0,s2=0; int m=2*n-1; int x=0; HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode)); for(i=1;i<=n;i++)//ڵnʼ { HT[i].weight=*(w+i-1); HT[i].data=*(ch+i-1); HT[i].parent=0; HT[i].lchild=0; HT[i].rchild=0; } for(;i<=m;i++)//ʣn-1ʼ { HT[i].weight=0; HT[i].data='0'; HT[i].parent=0; HT[i].lchild=0; HT[i].rchild=0; } for(i=n+1;i<=m;i++)//γ { Select(HT,i-1,s1,s2); HT[s1].parent=i; HT[s2].parent=i; HT[i].lchild=s1; HT[i].rchild=s2; HT[i].weight=HT[s1].weight+HT[s2].weight; } } void Huffmancoding(HuffmanTree &HT,HuffmanCode &HC,int n)// { char *cd; int i,start,c; HC=(HuffmanCode)malloc((n+1)*sizeof(char *));//ָ룬cdַ cd=(char *)malloc(n*sizeof(char));//ʱ for(i=1;i<=n;i++) { start=n-1; int f=HT[i].parent; for(c=i;f!=0;c=f,f=HT[f].parent) if(HT[f].lchild==c) cd[--start]='0'; else cd[--start]='1'; HC[i]=(char *)malloc((n-start)*sizeof(char)); strcpy(HC[i],&cd[start]); } free(cd); } char* DispHuffman(HuffmanTree HT,char s) { HuffmanCode HC; Huffmancoding(HT,HC,8); for(int i=1;i<=8;i++) { if(HT[i].data==s) { printf("\t\t%c\t%s\n",s, HC[i]); return HC[i]; } } } void wpl(HuffmanTree HT,int n) { float s=0;int c; HuffmanCode HC; Huffmancoding(HT,HC,8); for(int i=1;i<=8;i++) { int count=0;//شڲ for(int k=0;k<4;k++) { if(HC[i][k]=='0'||HC[i][k]=='1') { count++; } } s=s+count*HT[i].weight;//ۼwpl } printf("\t%f",s); } main() { HuffmanTree HT; HuffmanCode HC; float w[8]={0.05,0.29,0.07,0.08,0.14,0.23,0.03,0.11}; char ch[8]={'a','b','c','d','e','f','h','i'}; CreaHuffman(HT,w,8,ch); printf("ĸӦֵ\n"); for(int i=0;i<8;i++) DispHuffman(HT,ch[i]); printf("WPLֵΪ\n"); wpl(HT,8); }
true
4325ee16c9e7727c5b6f189011ac6ee27cafb3c1
C++
DongJunK/Algorithm
/line/2018/C.cpp
UTF-8
435
2.75
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; int toilet[151] = {0,}; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin>>n; while(n--) { int start,end; cin>>start>>end; for(int i=start;i<end;++i) { ++toilet[i]; } } sort(toilet,toilet+151); cout << toilet[150] << endl; return 0; }
true
490156e4c34148c07a8d01e4b91c0ce870e9d65d
C++
andNikita/KR_oskolkov
/mycompute.cpp
UTF-8
4,332
3.34375
3
[]
no_license
/* создаем 2 массива, один для хранения чисел, второй для хранения операций. просбегаем по всем возможным вариантам, сохраняем в строках те, которые подходят и выводим ектор строк. пояснение за массив операторов "operators" | res = 16 data 1 2 4 operators OP_NO OP_PL то есть после единицы не ставить никакой оператор, после 2 ставить +. поянение за get_res() мы создаем список, состоящий из элементов и операций в том порядке, в котором должны быть. Сначала ищем умножения, умножаем два соседних числа и сам элемент с умножением заменяем на число. Два соседних удаляем. Потом аналогчино проходимся за + и -. */ #include <iostream> #include <string> #include <list> #include <vector> #include <cmath> #include <bits/stdc++.h> #include <iostream> #include <sstream> using namespace std; //____________________define operations #define OP_NO -1 //nothing #define OP_PL -2 // + #define OP_MI -3 // - #define OP_MU -4 // * #define OP_STOP -777 // stop search #define OP_GO -666 //____________________end define int get_int(vector<int>& x) { int res = 0; int k = x.size() - 1; for (int i = 0; i < x.size(); i++){ res += pow(10,k) * x[i]; k--; } x.clear(); return res; }; void init_list(vector<int> data, vector<int> operators, list<int>& list_res) { int size = operators.size() - 1; vector<int> x; for(int i = 0; i <= size; i++) { x.push_back(data[i]); while(operators[i] == OP_NO) { x.push_back(data[++i]); } list_res.push_back(get_int(x)); list_res.push_back(operators[i]); } list_res.pop_back(); }; int get_res(vector<int> data,vector<int> operators) { list<int> list_res; init_list(data, operators, list_res); int x = 0; for(auto it = list_res.begin(); it != list_res.end(); it++) { if (*it == OP_MU){ auto it_l = --it; ++it; auto it_r = ++it; --it; *it = (*it_l) * (*it_r); list_res.erase(it_l); list_res.erase(it_r); } } for(auto it = list_res.begin(); it != list_res.end(); it++) { if ((*it == OP_MI) || (*it == OP_PL)) { auto it_l = --it; ++it; auto it_r = ++it; --it; if (*it == OP_MI) *it = (*it_l) - (*it_r); else *it = (*it_l) + (*it_r); list_res.erase(it_l); list_res.erase(it_r); } } if (list_res.size() == 1) return list_res.front(); else { cout << "WTF NOT RES" << endl; return 0; } }; void change_operators(vector<int>& operators) { int i = 0; int size = operators.size() - 1; while(i < size) { if (operators[i] == OP_MU) { operators[i] = OP_NO; i++; if (i == size) { operators[i] = OP_STOP; } } else { operators[i] -= 1; break; } } }; string to_string(int x) { return std::to_string(x); } string get_string(vector<int> data,vector<int> operators) { string str; std::stringstream ss; int k = 0; for (int i = 0; i < data.size(); i++) { ss << data[i]; str.append(ss.str()); ss.str(""); if (operators[k] == OP_NO) { k++; continue; } else if (operators[k] == OP_PL) str.append("+"); else if (operators[k] == OP_MI) str.append("-"); else if (operators[k] == OP_MU) str.append("*"); k++; } return str; } void search(vector<int>& data, vector<int>& operators, int res, vector<string>& answer) { int i = 0; while(operators[operators.size() - 1] != OP_STOP) { if (res == get_res(data, operators)){ answer.push_back(get_string(data, operators)); } change_operators(operators); } }; int main(int argc, char* argv[]) { string argv_str = string(argv[1]); int res = atoi(argv[1]); vector<int> data; vector<int> operators; vector<string> answer; for (int i = 2; i < argc; i++) { int element = atoi(argv[i]); data.push_back(element); } for (int i = 0; i < data.size() - 1; i++) { operators.push_back(OP_NO); } operators.push_back(OP_GO); search(data, operators, res, answer); for (auto i: answer) { cout << i << "=" << res << endl; } }
true
e02eddf3dda7574465e3a88ab389b55a7709a29b
C++
mdakram09/C-and-Cpp-Practice
/votingAge.cpp
UTF-8
272
3.140625
3
[]
no_license
#include<iostream> using namespace std; int main() { int age; cout<<"Please enter your age \t : \t \n"; cin>>age; if(age>=18) { printf("Yes! You can vote, beacause your age is %d \n", age ); } else { printf("No! you cannot vote, your age is %d \n", age ); } }
true
4e5db0c895cf4009f8dd1ceec7900ca14da13bc5
C++
ritish73/codingBlocksPractice
/largest_histogram_area.cpp
UTF-8
1,375
3.390625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int largestHistogramArea(int* a, int n){ stack<int> s; s.push(0); int area = 0 , maximum_area = INT_MIN; int i; for(i=1; i<n; i++){ cout<<" for i = "<<i<<" stack size is "<<s.size()<<endl; int cur_val = a[i]; cout<<"cur val is "<<cur_val<<" and s.top is "<<s.top()<<endl; if(cur_val > a[s.top()]){ s.push(i); } else if(cur_val <= a[s.top()]){ while(!s.empty() && cur_val < a[s.top()]) { cout<<cur_val<< " " <<a[s.top()]<<endl; int top = s.top(); s.pop(); if(s.empty()){ area = a[top] * i; cout<<"area calc if st empty "<< area << endl; maximum_area = max(area , maximum_area); } else{ int l = i; int r = s.top(); area = a[top] * (l - r - 1); cout<<"area calc if st is non empty "<< area << endl; maximum_area = max(area , maximum_area); } } cout<<"pushing i : "<<i<<endl; s.push(i); } // cout<<area<<endl; } while(!s.empty()){ int top = s.top(); s.pop(); if(s.empty()){ area = a[top] * i; cout<<area<<endl; } else{ int l = i; int r = s.top(); area = a[top] * (l - r - 1); cout<<area<<endl; } maximum_area = max(area , maximum_area); } return maximum_area; } int main(){ int n = 6; int a[] = {2 ,3 ,4 , 5, 6}; cout<<endl<<endl<<largestHistogramArea(a , n); }
true
de59234b50d62b3fec6b153891923555ce58f849
C++
jayacosta/TPI_LAB1
/TPI LAB1/Tp de lab/juego.h
ISO-8859-1
4,232
2.671875
3
[]
no_license
#pragma once #include <iostream> #include <stdlib.h> using namespace std; #include "menu.h" #include "dado.h" #include "combinaciones.h" int juegodeuno() { int puntos_c; int puntosronda=0; bool turnode= true; bool generala_s; int maxp=0;//Acumulador que me indica la puntuacin maxima para ganar int dado[4];//Se inicializa el dado int seguir_t;//Variable para preguntar si quiere seguir tirando algun dado int dado_t;//Variable del dado que se tira int tiradas=0;//Las 3 veces que se pueden tirar los dados que se reinicia al final int cant_rondas;//Variable para cuando quieran ingresar la cantidad de rondas int op_rondas;//Opcion de cantidad de rondas, ya sea defaul o personalizada int maxrondas;//Le dice al programa la cantidad de rondas que va a realizar int rondas=1;//Contador de rondas int puntos=0,puntosj2=0;//Acumulador de puntos string nombrej1, nombrej2;//Nombre del jugador int juegodeuno; cout<<"Ingresa tu nombre para comenzar a jugar: "<<endl; cin>>nombrej1; system("cls"); cout<<"Que cantidad de rondas desea jugar?"<<endl; cout<<"1 - Cantidad estandar 10 rondas"<<endl; cout<<"2 - Cantidad de rondas personalizadas"<<endl; cout<<"- "; cin>>op_rondas; if (op_rondas==1) { maxrondas=10; } else { cout<<"Cuantas rondas desea jugar?"<<endl; cout<<"- "; cin>>cant_rondas; maxrondas=cant_rondas; } while(maxp<=60 || rondas==maxrondas) { puntosronda=0; menuturno(nombrej1,nombrej2,turnode, rondas, puntos,puntosj2); cargardado(dado); while (tiradas<3) { mostrardado(dado); cout << "-----------------------------------------------------------------------------------------------------------------------" << endl; cout<<"Desea seguir tirando?"<<endl; cout<<"1 - Si"<<endl; cout<<"2 - No"<<endl; cout<<"- "; cin>>seguir_t; if (seguir_t==1) { cout<<"Que dado quiere volver a tirar?"<<endl; cout<<"- "<<endl; cin>>dado_t; switch (dado_t) { case 1: dado[0] = (rand() % 6) + 1; tiradas++; break; case 2: dado[1] = (rand() % 6) + 1; tiradas++; break; case 3: dado[2] = (rand() % 6) + 1; tiradas++; break; case 4: dado[3] = (rand() % 6) + 1; tiradas++; break; case 5: dado[4] = (rand() % 6) + 1; tiradas++; break; default: cout<<"Debe elegir un numero valido (1-5)"<<endl; } } else { tiradas=3; } combinaciones(dado, tiradas); if(generala_s==true){ cout<< "Sacaste generala servida"<<endl; cout<<"Has ganado!"<<endl; if(turnode==true){ puntos=60; } else{ puntosj2=60; } puntos = puntos_c; puntosronda = puntos_c; system("cls"); cout <<"------------------------------------------------" << endl; cout << endl; cout << endl; cout << "puntaje obtenido en la ronda:" << puntosronda << "puntos" <<endl; cout << "Puntaje total de " << nombrej1 << ": " << puntos << "puntos" << endl; cout << endl; cout << endl; cout << "-----------------------------------------------" << endl; system("pause"); cout << "Presione una tecla para continuar..." << endl; system("cls"); rondas++; } } if(puntos>=60){ return puntos, rondas;} else{ return puntos, rondas; }
true
ff24e329e656a5e8696abeb9f3f26bae7c11bfef
C++
hugh-jazz/bigkek
/ECE220_Lab1.cpp
UTF-8
1,166
3.90625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> int main(void){ //declare the valuables int program_gussed_number; int user_hint; int counter = 1; //stores the number of times the program guessed the value int min; int max; //ask the user for two values that defines the range for a number printf("Range: minimum "); scanf("%d", &min); printf("Range: maximum "); scanf("%d", &max); //program guesses the number until it gets it right by asking for hints while (true) { program_gussed_number = (min + max)/2; printf("Guessed number : %d \n", program_gussed_number); printf(" 1. TOO LARGE \n 2. TOO SMALL \n 3. FOUND \n"); //ask user to select one of the options scanf("%d", &user_hint); if (user_hint == 1 ) { max = program_gussed_number - 1; counter = counter + 1; } else if (user_hint == 2) { min = program_gussed_number + 1; counter = counter + 1; } else { printf(" FOUNT IT \n No. of tries: %d", counter); break; } } return 0; }
true
970bb674d522ddebc8bcfe18c403f27dcc5c328d
C++
Cece-L/Code
/C++/二进制.cpp
GB18030
194
2.671875
3
[]
no_license
#include<iostream> using namespace std; int main(){ int x; int y; cout<<"һʮƵ"<<endl; cin>>x; while(x!=0){ y=x%2; cout<<y; x=x/2; } return 0; }
true
6adc385476c395f86c09beb78f01c4b14b2c8237
C++
jwbecalm/Head-First-Design-Patterns-CPP
/Composite/src/Waitress.cpp
UTF-8
624
2.8125
3
[]
no_license
#include "Waitress.hpp" #include <iostream> #include "Iterator.hpp" #include "Menu.hpp" Waitress::Waitress(MenuComponent* components) : m_components(components) { } Waitress::~Waitress() { } void Waitress::printMenu() { m_components->print(); } void Waitress::printVegetarianMenu() { Iterator* itr = m_components->createIterator(); std::cout << "\nVEGETARIAN MENU\n----"; while (itr->hasNext()) { MenuComponent* component = itr->next(); if (component->isVegetarian()) { component->print(); } } delete itr; }
true
9bea3fcf10d276c8d04d9fbd792dbf0f2a37ef8b
C++
terpos/Birday
/Birday_arcade/Birday_arcade/src/Entities/Enemy/Weapon/E_Weapon.h
UTF-8
1,238
2.984375
3
[]
no_license
/* Classes that inherit this class will use the same functions */ #include "global.h" #include "Asset_management/Image.h" #include "Asset_management/Sound.h" #pragma once class E_Weapon { public: //puts in initial value E_Weapon(Image &sprite_sheet, int x, int y, int vel, int direction); ~E_Weapon(); //gets x position, y position, speed, direction, and id of the weapon virtual int get_x(); virtual int get_y(); virtual int get_vel(); virtual int get_direction(); virtual int get_id(); //returns bitmap value virtual Image get_image(); //sets the x position, y position, speed, direction, and id of the weapon virtual void set_x(int x); virtual void set_y(int y); virtual void set_vel(int vel); virtual void set_direction(int direction); virtual void set_id(int id); //abstract variable of damage of the weapon virtual int damage() = 0; //sets the bitmap information virtual void set_image(Image image); //update weapon info virtual void update(); //displays the weapon virtual void render(); private: //integer variables int x, y, vel, direction, buttons[7], type, id; //boolean variable bool draw; //bitmap instance variables ALLEGRO_BITMAP *cropping; //pair variable Image image; };
true
9b54ca86c3bc065951bcb946acee64d1242fc984
C++
nelson510/LeetCode
/21. Merge Two Sorted Lists Modified.cpp
UTF-8
966
3.75
4
[]
no_license
/** Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ //In this recursion no need to create a new ListNode, because we can simply relocation the existing one to achieve the goal. class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; if(l2->val>=l1->val){ l1->next=mergeTwoLists(l1->next,l2); return l1; } if(l2->val<=l1->val){ l2->next=mergeTwoLists(l1,l2->next); return l2; } return NULL; //if the retrun statement will never reach, we can return NULL } };
true
a219af4a45250c68a683936fe451a328930f1648
C++
m4n1c22/opovlint
/test/src/tests/ExplicitCastMatchSet.inl
UTF-8
1,469
2.53125
3
[ "MIT" ]
permissive
SIMPLE_TEST1("A static cast." , SCAST("a") , SCAST_S("a")); SIMPLE_TEST1("A static cast of a binary op." , SCAST("a*ab") , SCAST_S("a*ab")); SIMPLE_TEST1("A static cast of a nested binary op." , SCAST("a*ab*aa") , SCAST_S("a*ab*aa")); SIMPLE_TEST1("A static cast of a casted variable." , SCAST(SCAST_T(_TYPE_, "res")) , SCAST_S(SCAST_T(_TYPE_, "res"))); SIMPLE_TEST1("A static cast of a binary op. with a cast." , SCAST("res*" SCAST_T(_TYPE_, "res")) , SCAST_S("res*" SCAST_T(_TYPE_, "res"))); SIMPLE_TEST1("A static cast of a binary op. with constant." , SCAST("a*1") , SCAST_S("a*1")); SIMPLE_TEST1("A static cast of a binary op. with paren expression." , SCAST("a*(res*2)") , SCAST_S("a*(res*2)")); SIMPLE_TEST1("A static cast of a paren expression with binary op." , SCAST("(a*2)") , SCAST_S("(a*2)")); SIMPLE_TEST1("A static cast of a binary op with paren expression." , SCAST("res*(a*2)") , SCAST_S("res*(a*2)")); SIMPLE_TEST1("A static cast of a nested cast expression." , SCAST(SCAST_S("a")) , SCAST_S("a")); SIMPLE_TEST1("A static cast of a nested cast expression of a binary op." , SCAST(SCAST_S("res*(a*2)")) , SCAST_S("res*(a*2)")); SIMPLE_TEST1("A static cast with parens." , SCAST("((a))") , SCAST_S("((a))")); SIMPLE_TEST1("A static cast of a binary op. with a cast inside parens." , SCAST("res*((" SCAST_T(_TYPE_, "res") "))") , SCAST_S("res*((" SCAST_T(_TYPE_, "res") "))"));
true
93c43bfa2a4404fc19452a92bc77daf1120e2b2c
C++
dowmq/HelloGameWorld
/MonsterFactory.cpp
UTF-8
1,328
2.75
3
[]
no_license
#include "MonsterFactory.h" #include "CWindow.h" #include <string> #include <exception> #include "SpriteProvider.h" CMonster* MonsterFactory::CreateGoblin(float logical_x, float logical_y) { try { CMonster* monster = new CMonster(logical_x, logical_y); monster->sprites[CMonster::MonsterSprite::walking_left] = SpriteProvider::Instance().GetMonsterSpriteBySpriteID(SpriteProvider::MonsterID::Goblin_walk_left); monster->sprites[CMonster::MonsterSprite::walking_right] = SpriteProvider::Instance().GetMonsterSpriteBySpriteID(SpriteProvider::MonsterID::Goblin_walk_right); monster->sprites[CMonster::MonsterSprite::stop_left] = SpriteProvider::Instance().GetMonsterSpriteBySpriteID(SpriteProvider::MonsterID::Goblin_stop_left); monster->sprites[CMonster::MonsterSprite::stop_right] = SpriteProvider::Instance().GetMonsterSpriteBySpriteID(SpriteProvider::MonsterID::Goblin_stop_right); monster->sprites[CMonster::MonsterSprite::die] = SpriteProvider::Instance().GetMonsterSpriteBySpriteID(SpriteProvider::MonsterID::Goblin_die); return monster; } catch (std::exception& e) { std::string str(e.what()); std::wstring wstr(str.begin(), str.end()); MessageBox(CWindow::Instance().m_hWnd, wstr.c_str(), TEXT("Exception"), MB_ICONERROR); } return nullptr; }
true
2b5ff12c27e956db761a290a7a3bb6499b1b61bc
C++
Isprinsessan/TNM096-Labs
/Lab2/Task 3 and Task 4/Lab2/Lab2/State.cpp
UTF-8
5,887
3.296875
3
[]
no_license
#include "stdafx.h" #include "State.h" using namespace std; State::State() { //Create a random schedule and calculate the number of conflicts in it //srand(time(0)); std::random_shuffle(std::begin(schedule), std::end(schedule)); numberOfConflicts = GetNumberOfConflicts(); } void State::Solve() { int totNrOfConflicts = numberOfConflicts; int nrOfIt = 0; int maxIt = 10000; //While not doing too many iterations and while there still are conflicts while (nrOfIt < maxIt && totNrOfConflicts > 0) { nrOfIt++; double random = (double)rand() / (double)RAND_MAX; //Get a random course index from the schedule int index = (int)( (size(schedule) -1 )* random); //Get the slot in the schedule with the lowest amount of conflicts int minIndex = FindMinConflicts(index); //cout << "index " << index << " minIndex " << minIndex<< endl; //Swap the courses position in the schedule SwapIndexPosition(index, minIndex); //Update the total number of conflicts in the schedule totNrOfConflicts = GetNumberOfConflicts(); } //Print out if no solution was found if (nrOfIt == maxIt) { cout << "" << endl; cout << "No solution found in " << nrOfIt << " iterations" << endl; } //Set the schedules number of conflicts numberOfConflicts = totNrOfConflicts; /*cout << endl; cout << "Number of iterations: " << nrOfIt << endl; cout << endl; */ //Task 4 PreferenceScore(); } int State::GetNumberOfConflicts() { int conflicts = 0; for (int i = 0; i < std::size(schedule); i+=3) { //Get course code infromation for each column string Col1 = schedule[i]; string Col2 = schedule[i + 1]; string Col3 = schedule[i + 2]; //cout << Col1[2] << " " << Col2[2] << " " << Col3[2] << endl; //Compare the course numbers, increase conflict if they are the same (Col1[2] gives a char)) if (Col1[2] == Col2[2]) conflicts++; if (Col1[2] == Col3[2]) conflicts++; if (Col2[2] == Col3[2]) conflicts++; } return conflicts; } int State::FindMinConflicts(int _indx) { //Get the current course being evaluated and its fist course digit string CurrentEvaluation = schedule[_indx]; string courseDigits(1, CurrentEvaluation[2]); int minIndex = _indx; int minIndexConflicts = 9999; //Special case for when there is an empty string in the course list if (courseDigits.compare(" ") == 0) return _indx; //Compare CurrentEvaluation to all other slots in the schedule for (int i = 0; i < std::size(schedule); i++) { //For each slot in the schedule, find the number of conflicts if the current course is moved there int nrOfConflicts = FindConflicts(courseDigits, i); if (nrOfConflicts < minIndexConflicts) { //String to check if the current slot have the same course digit as the moved one string compare(1, schedule[i][2]); //If they are not the same, set it to the lowest if (compare != courseDigits) { //Set min index to the current slot and update the amount of min conflicts minIndexConflicts = nrOfConflicts; minIndex = i; } } } return minIndex; } int State::FindConflicts(string _compare, int _indx) { //Get the current column int col = _indx % 3; int conflicts = 0; string neighbour1 = ""; string neighbour2 = ""; //Special case for MT5** if (_compare.compare("5") == 0) return 0; //Get neighbours from the column switch (col) { case 0: //indx is in the left column neighbour1 = schedule[_indx + 1]; neighbour2 = schedule[_indx + 2]; break; case 1: //indx is in the middle column neighbour1 = schedule[_indx - 1]; neighbour2 = schedule[_indx + 1]; break; case 2: //indx is in the right column neighbour1 = schedule[_indx - 1]; neighbour2 = schedule[_indx - 2]; break; } //Get the first course digit string neigh1(1, neighbour1[2]); string neigh2(1, neighbour2[2]); //If any of the neighbours course digit is the same as the current one, increase conflict if (_compare.compare(neigh1) == 0) conflicts++; if (_compare.compare(neigh2) == 0) conflicts++; return conflicts; } void State::SwapIndexPosition(int _indx1, int _indx2) { //Swap the courses position in the schedule string temp = schedule[_indx1]; schedule[_indx1] = schedule[_indx2]; schedule[_indx2] = temp; } void State::PreferenceScore() { int row0 = 0 * 3; int row3 = 3 * 3; int row4 = 4 * 3; int row5 = 5 * 3; int row7 = 7 * 3; //Loop through row0 (09:00) for (int i = row0; i < row0 + 3; i++) { string temp0(1, schedule[i][2]); //cout << "temp0 " << temp0 << endl; if (temp0.compare(" ") == 0) { //cout << "temp = 0 " << temp0 << endl; score++; } } //Loop through row3 (12:00) for (int i = row3; i < row3 + 3; i++) { string temp3(1, schedule[i][2]); //cout << temp3 << endl; if (temp3.compare(" ") == 0) { //cout << "temp = 0 " << temp3 << endl; score++; } } //Loop through row7 (16:00) for (int i = row7; i < row7 + 3; i++) { string temp7(1, schedule[i][2]); //cout << temp7 << endl; if (temp7.compare(" ") == 0) { //cout << "temp = 0 " << temp7 << endl; score++; } } //Check if MT501 or MT502 is scheduled at 1 or 2 //For 13:00 for (int i = row4; i < row4 + 3; i++) { string temp4(1, schedule[i][2]); if (temp4.compare("5") == 0) { //cout << "temp = 5 " << temp4 << endl; score++; } } //For 14:00 for (int i = row5; i < row5 + 3; i++) { string temp5(1, schedule[i][2]); if (temp5.compare("5") == 0) { score++; } } } void State::print() { cout << "TP51 " << "SP34 " << "K3 " << endl; cout << "---- " << "---- " << "---- " << endl; for (int row = 0; row < 8; row++) { for (int col = 0; col < 3; col++) { cout << schedule[row * 3 + col] << " "; } cout << " " << row + 9 << endl; } cout << endl; cout << "Number of conflicts: " << numberOfConflicts << endl; cout << endl; }
true