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
9ff5a4d2654faeac5539abe7a2ff68adaba87205
C++
doanhtdpl/game-cashtle-vania
/GameCashtleVania/GameCashtleVania/ObjectFactory.cpp
UTF-8
633
2.765625
3
[]
no_license
#include "ObjectFactoty.h" using namespace std; ObjectGame* ObjectFactory::createObj(int ID) { return NULL; } ObjectGame* ObjectFactory::createObj() { return NULL; } ObjectGame* ObjectFactory::createObj(std::vector<std::string> arr) { return NULL; } void ObjectFactory::addInfo(vector<string> arr) { info.push_back(arr); } std::vector<std::string> ObjectFactory::getInfoByID(int ID) { //tim arr nao co ID_Image = ID_BG thi lay std::vector<std::string> arr; for (int i = 0; i < info.size(); i++) { arr = info.at(i); if (atoi(arr.at(0).c_str()) == ID) { return arr; } } }
true
ac7224b0f1cfc327f832ad69a7150fcbcea964ea
C++
shurik111333/spbu
/olympic/CodeJam/29.05.16_disturbed_round1/untitled/main.cpp
UTF-8
225
2.625
3
[]
no_license
#include <iostream> using namespace std; int main() { int size = (1 << 27); int ans = 0; while (size > 1) { ans += size / 100 + 1; size >>= 1; } cout << ans << endl; return 0; }
true
55c1c7cf5ba8baadb80ecd433321be0eead40658
C++
Abhinav1997/TC-Programs
/Arrays/triangles.cpp
UTF-8
1,233
3.21875
3
[]
no_license
#include<iostream.h> #include<conio.h> static void triangles(char ar[][100], int); void main() { clrscr(); int m; char ar[100][100]; cout<<"--------------------------------TRIANGLES------------------------------\n\n\n"; cout<<"Enter the number of rows/columns you want in your 2D array - "; cin>>m; cout<<"Enter "<<m*m<<" values in array- "<<endl; for(int i=0;i<m;i++) { for(int j=0;j<m;j++) cin>>ar[i][j]; } cout<<"\nOutput -"<<endl; triangles(ar,m); getch(); } static void triangles(char ar[][100],int n) { cout<<"\nLower left triangle-"<<endl; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i>=j) cout<<ar[i][j]<<" "; else cout<<" "; } cout<<"\n"; } cout<<"\nLower right triangle-"<<endl; for(i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i+j>=(n-1)) cout<<ar[i][j]<<" "; else cout<<" "; } cout<<"\n"; } cout<<"\nUpper left triangle-"<<endl; for(i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i+j<=(n-1)) cout<<ar[i][j]<<" "; else cout<<" "; } cout<<"\n"; } cout<<"\nUpper right triangle-"<<endl; for(i=0;i<n;i++) { for(int j=0;j<n;j++) { if(j>=i) cout<<ar[i][j]<<" "; else cout<<" "; } cout<<"\n"; } }
true
bbef5cdab7a4b447fd0e342382d168d18a4c26bf
C++
trashcrash/TimeManager
/GUI/mainwindow.cpp
UTF-8
1,489
2.640625
3
[]
no_license
#include "mainwindow.h" #include "ui_mainwindow.h" #include <chrono> #include <iostream> #include <QFile> #include <QTextStream> #include <QDateTime> using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->setWindowTitle("TimeManager"); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_exit_button_clicked() { QApplication::quit(); } void MainWindow::on_lineEdit_returnPressed() { MainWindow::on_enter_button_clicked(); } void MainWindow::on_enter_button_clicked() { // Get the input from lineEdit QString input_event = ui->lineEdit->text(); // Get current datetime QString current_datetime = QDateTime::currentDateTime().toString(); // Open data.txt and append text QFile data("./data.txt"); data.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append); QTextStream outs(&data); outs << input_event << " -> " << current_datetime << '\n'; data.close(); // Clear lineEdit ui->lineEdit->clear(); } void MainWindow::on_history_button_clicked() { // Open data.txt QFile data("./data.txt"); data.open(QIODevice::ReadOnly); QTextStream read_file(&data); // Show text in textBrowser ui->textBrowser->setText(read_file.readAll()); } void MainWindow::on_clean_button_clicked() { // Remove data.txt QFile data("./data.txt"); data.remove(); ui->textBrowser->clear(); }
true
a2e23fdecd33d17a66e579f305386c5b856a96a4
C++
DancingOnAir/LeetCode
/Leetcode/Array/1337_TheKWeakestRowsinaMatrix.cpp
UTF-8
1,503
3.34375
3
[]
no_license
#include <iostream> #include <vector> #include <numeric> using namespace std; class Solution { public: vector<int> kWeakestRows(vector<vector<int>>& mat, int k) { int n = mat.size(); vector<pair<int, int>> v; for (int i = 0; i < n; ++i) { v.emplace_back(make_pair(i, accumulate(mat[i].begin(), mat[i].end(), 0))); } sort(v.begin(), v.end(), [](const pair<int, int>& x, const pair<int, int>& y) { return (x.second == y.second) ? x.first < y.first : x.second < y.second; }); vector<int> res; for (int i = 0; i < k; ++i) { res.emplace_back(v[i].first); } return res; } }; void printNums(const vector<int>& nums) { for (int num : nums) { cout << num << ", "; } cout << endl; } void testKWeakestRows() { Solution solution; vector<vector<int>> mat1 = {{1,1,0,0,0}, {1,1,1,1,0}, {1,0,0,0,0}, {1,1,0,0,0}, {1,1,1,1,1}}; int k1 = 3; auto res1 = solution.kWeakestRows(mat1, k1); printNums(res1); vector<vector<int>> mat2 = {{1,0,0,0}, {1,1,1,1}, {1,0,0,0}, {1,0,0,0}}; int k2 = 2; auto res2 = solution.kWeakestRows(mat2, k2); printNums(res2); } int main() { testKWeakestRows(); return 0; }
true
66e394c6ec3a2b28a412a19862b790b300e46a44
C++
Vilanya/SIT315
/Module1/SIT315_M1T3.cpp
UTF-8
957
2.859375
3
[]
no_license
int LED = 13; int PIR = 2; int PIR2 = 3; void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); pinMode(PIR, INPUT); pinMode(PIR2, INPUT); digitalWrite(LED, LOW); Serial.println("Ready"); Serial.println("LED off"); attachInterrupt(digitalPinToInterrupt(PIR), motion, CHANGE); attachInterrupt(digitalPinToInterrupt(PIR2), motion2, CHANGE); } void loop() { Serial.print("Motion1: "); Serial.println(String(digitalRead(PIR))); Serial.print("Motion2: "); Serial.println(String(digitalRead(PIR2))); delay(1000); } void motion() { if (digitalRead(PIR) == HIGH) { digitalWrite(LED, HIGH); Serial.println("LED on"); } else { digitalWrite(LED, LOW); Serial.println("LED off"); } } void motion2() { if (digitalRead(PIR2) == HIGH) { digitalWrite(LED, HIGH); Serial.println("LED on"); } else { digitalWrite(LED, LOW); Serial.println("LED off"); } }
true
c651809ba3ebe117c8ae10d66c5355964d77d7c7
C++
Xaeoz/TDA362
/project/Water.cpp
UTF-8
4,972
2.53125
3
[]
no_license
#include <vector> #include <stb_image.h> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <iostream> #include "Water.h" using namespace glm; using std::string; using std::vector; Water::Water() : m_texid_dudv(UINT32_MAX) , m_texid_normalMap(UINT32_MAX) , m_vao(UINT32_MAX) , m_positionBuffer(UINT32_MAX) , m_indexBuffer(UINT32_MAX) , m_modelMatrix() , m_moveFactor(0) { } void Water::init(vec3 &position, float scale, vec2 &reflectionMapRes, vec2 &refractionMapRes) { m_modelMatrix = glm::scale(vec3(scale, 1, scale))*translate(position); //Initialize Fbo objects m_reflectionFbo.resize(reflectionMapRes.x, reflectionMapRes.y); m_refractionFbo.resize(refractionMapRes.x, refractionMapRes.y); //Create mesh and corresponding buffers generateMesh(); //Load textures int width, height, components; //Not reference based, so no problem re-using for all textures //DuDv texture (aka. Distortion map) std::string dudvPath = "../res/waterDUDV.png"; float *dudvData = stbi_loadf(dudvPath.c_str(), &width, &height, &components, 3); if (dudvData == nullptr) { std::cout << "Failed to load image: " << dudvPath << ".\n"; return; //Not handled, this will cause the water component to break when used } if (m_texid_dudv == UINT32_MAX) { glGenTextures(1, &m_texid_dudv); } //Set texture to modify glBindTexture(GL_TEXTURE_2D, m_texid_dudv); //Repeat to allow distortions and such to loop around the texture glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //Not a visible texture per say, so linear works well enough glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, dudvData); //Load in normalMap data from file std::string nMapPath = "../res/matchingNormalMap.png"; float *nMapdata = stbi_loadf(nMapPath.c_str(), &width, &height, &components, 3); if (nMapdata == nullptr) { std::cout << "Failed to load image: " << nMapPath << ".\n"; return; //Not handled, this will cause the water component to break when used } //Get a GLuint reference for the texture if one is not already present if (m_texid_normalMap == UINT32_MAX) { glGenTextures(1, &m_texid_normalMap); } //Set texture to modify glBindTexture(GL_TEXTURE_2D, m_texid_normalMap); //Repeat to allow distortions and such to loop around the texture glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //Not a visible texture per say, so linear works well enough glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, nMapdata); } //////////////////////////////////////////// // Generate the mesh through indices and vertices. Also generate bindings for the VAO and buffers ////////////////////////////////////////// void Water::generateMesh() { glGenVertexArrays(1, &m_vao); glBindVertexArray(m_vao); //const float magnitude = 100; float verts[] = { -1, 0, 1, //v0 1, 0, 1, //v1 1, 0, -1, //v2 -1, 0, -1, //v3 }; //for (int i = 0; i < sizeof(verts) / sizeof(float); i++) //{ // verts[i] = verts[i] * magnitude; //} glGenBuffers(1, &m_positionBuffer); // Create a handle for the vertex position buffer glBindBuffer(GL_ARRAY_BUFFER, m_positionBuffer); // Set the newly created buffer as the current one glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW); // Send the vetex position data to the current buffer glVertexAttribPointer(0, 3, GL_FLOAT, false/*normalized*/, 0/*stride*/, 0/*offset*/); glEnableVertexAttribArray(0); const int indices[] = { 0,1,3, 3,1,2 }; glGenBuffers(1, &m_indexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); } void Water::render() { //Bind mesh data glBindVertexArray(m_vao); //Bind indices data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer); //Bind textures to the references specified in the shader //Reflection texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_reflectionFbo.colorTextureTargets[0]); //Refraction texture glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_refractionFbo.colorTextureTargets[0]); //DuDv (Distortion) map glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, m_texid_dudv); //Normal Map glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, m_texid_normalMap); //Depth Map glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, m_refractionFbo.depthBuffer); //Refraction buffer contains everything below water, which can be used to find the depth of the water }
true
f0a2bf883a036250625f1c2b2cd1efc53acce9b9
C++
scudrt/gobang
/gameContainer.cpp
UTF-8
4,831
2.734375
3
[]
no_license
#include <graphics.h> #include "gameContainer.h" Position::Position(int nowx,int nowy) { x=nowx; y=nowy; } Position::Position() { x=y=0; } PlayerController::PlayerController(bool _isAIPlayer_,bool _isBlackChess_) { _isAIPlayer = _isAIPlayer_; _isBlackChess = _isBlackChess_; } bool PlayerController::isAIPlayer() { return _isAIPlayer; } bool PlayerController::isBlackChess() { return _isBlackChess; } Position PlayerController::getXY() { Position pos; mouse_msg msg={0}; if (isAIPlayer()) { ; } else { while (1) { msg=getmouse(); if (msg.is_down()) { pos.x=msg.x; pos.y=msg.y; break; } } } return pos; } GameDirector::GameDirector() { mapX = mapY = 0; currentPlayerNumber = 1; player[0] = player[1] = NULL; } GameDirector::GameDirector(Position _map,Position start,Position end) { mapX = _map.x; mapY = _map.y; startX = start.x; startY = start.y; endX = end.x; endY = end.y; blockX = (endX - startX) / mapX; blockY = (endY - startY) / mapY; map = new int[mapX*mapY]; restBlank = mapX*mapY; for (int i=0;i<restBlank;++i) { map[i]=-1; } currentPlayerNumber = 1; player[0] = player[1] = NULL; _makeMap(); } GameDirector::~GameDirector() { for (int i=0;i<=1;++i) { if (player[i] != NULL) { delete player[i]; } } delete[] map; } void GameDirector::_makeMap() { //background color setbkcolor(EGERGB(120,120,120)); //grey //draw the lines setcolor(EGERGB(180,180,180)); for (int i=1;i<=mapX+1;++i) { //row line(startX,startY+(i-1)*blockY,endX,startY+(i-1)*blockY); } for (int i=1;i<=mapY+1;++i) { //column line(startX+(i-1)*blockX,startY,startX+(i-1)*blockX,endY); } } void GameDirector::addPlayer(bool isAI) { if (player[0]==NULL) //no this player yet { player[0] = new PlayerController(isAI,true); } else if (player[1]==NULL) //no this player yet { player[1] = new PlayerController(isAI,false); } } void GameDirector::changePlayer() { //1 to 0 , 0 to 1 currentPlayerNumber = 1 - currentPlayerNumber; setfont(20,0,"Atarix"); setcolor(currentPlayerNumber?WHITE:BLACK); xyprintf((startX+endX)/2-60,10,"player:%s",(currentPlayerNumber==1?"White":"Black")); } bool GameDirector::putChess(Position pos) { if (player[currentPlayerNumber]->isAIPlayer() == false) { //people with mouse input if (pos.x>=startX && pos.x<=endX && pos.y>=startY && pos.y<=endY) { //legal mouse position pos.x=(pos.x-startX) / blockX; pos.y=(pos.y-startY) / blockY; } else { return false; } } int *currentPosition=map+pos.y*mapX+pos.x; if (*currentPosition != -1) { //occupied position return false; } else { //record this operation lastX = pos.x; lastY = pos.y; } *currentPosition = currentPlayerNumber; if (currentPlayerNumber == 1) //white { setfillcolor(WHITE); } else //color is black { setfillcolor(BLACK); } //draw a chess in the blank int chessx=startX+pos.x*blockX; int chessy=startY+pos.y*blockY; bar(chessx+1,chessy+1,chessx+blockX,chessy+blockY); --restBlank; return true; } void GameDirector::showResult() { setfont(60,0,"Atarix"); setbkmode(TRANSPARENT); if (winnerNumber==-1) { setcolor(EGERGB(255,0,0)); outtextxy((startX+endX)/2-40,(startY+endY)/2-40,"tie"); } else if (winnerNumber==1) { setcolor(WHITE); outtextxy((startX+endX)/2-160,20,"white win!!"); } else //winnerNumber == 0 { setcolor(BLACK); outtextxy((startX+endX)/2-160,20,"black win!!"); } while (1) { if (getmouse().is_down()) break; } } bool GameDirector::isTheGameEnded() { //check whether the player wins //win first , tie next int tick=0; //record the chess number //row tick=0; for (int i=0;i<mapX;++i) { if (*(map+mapX*lastY+i) == currentPlayerNumber) { ++tick; if (tick>=5) { winnerNumber = currentPlayerNumber; return true; } } else { tick=0; } } //column tick=0; for (int i=0;i<mapY;++i) { if (*(map+i*mapY+lastX) == currentPlayerNumber) { ++tick; if (tick>=5) { winnerNumber = currentPlayerNumber; return true; } } else { tick=0; } } //diagonal for (int i=(lastX>lastY?lastX-lastY:0),j=(i?0:lastY-lastX);i<mapX && j<mapY;++i,++j) { if (*(map+mapX*j+i) == currentPlayerNumber) { ++tick; if (tick>=5) { winnerNumber = currentPlayerNumber; return true; } } else { tick=0; } } for (int i=(lastX>mapY-lastY?lastX+lastY-mapY:0),j=(i?mapY:lastY+lastX);i<mapX && j>=0;++i,--j) { if (*(map+mapX*j+i) == currentPlayerNumber) { ++tick; if (tick>=5) { winnerNumber = currentPlayerNumber; return true; } } else { tick=0; } } //tie if (restBlank <= 0) { winnerNumber = -1; return true; } return false; } PlayerController* GameDirector::getCurrentPlayer() { return player[currentPlayerNumber]; }
true
e988f7095e73888a750eca77c46f8cad6111ff8b
C++
shorn1/OI-ICPC-Problems
/luogu/3366_prim.cpp
UTF-8
1,598
2.578125
3
[ "MIT" ]
permissive
#include<cmath> #include<cctype> #include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> #define ns namespace #define lol long long using ns std; const int M = 233333; struct Edge { int tow,nxt,dat; }; Edge e[2 * M]; int n, m, s, a, b, c, sume = 0, vis[2 * M],hea[2 * M],dis[2 * M]; void add(int u, int v, int w) { sume++; e[sume].nxt = hea[u]; hea[u] = sume; e[sume].tow = v; e[sume].dat = w; } int prim(int st) { int cur = st; long long res = 0LL; for(int i = 1;i <= n;i++) { dis[i] = 2147483647; } memset(vis, 0, sizeof(vis)); for(int now = hea[st];now;now = e[now].nxt) { int t = e[now].tow; dis[t] = min(dis[t],e[now].dat); } for(int i = 1;i < n;i++) { int mi = 2147483647; vis[cur] = 1; for(int j = 1;j <= n;j++) { if(!vis[j] && mi > dis[j]) { mi = dis[j]; cur = j; } } res += mi; for(int now = hea[cur];now;now = e[now].nxt) { int t = e[now].tow; if(dis[t] > e[now].dat && !vis[t]) { dis[t] = e[now].dat; } } } return res >= 2147483647 ? -1 : res; } int main(int argc,char** argv) { scanf("%d%d",&n,&m); for(int i = 1;i <= m;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); add(u,v,w); add(v,u,w); } int r; r = prim(1); if(r == -1) printf("orz\n"); else printf("%d\n",r); return 0; }
true
8ce3cc834c49ae8fd9d0d435f03bc67cd9b25a69
C++
ElitCoder/EITN50
/project2/src/Cryptography.cpp
UTF-8
2,585
3.171875
3
[]
no_license
#include "Cryptography.h" #include <iostream> #include "crypto++/aes.h" #include "crypto++/filters.h" #include "crypto++/hmac.h" #include "crypto++/sha.h" using namespace std; byte *Cryptography::m_iv = new byte[CryptoPP::AES::BLOCKSIZE]; byte *Cryptography::m_key = new byte[CryptoPP::AES::DEFAULT_KEYLENGTH]; string Cryptography::createHMAC(const string &encodedMessage) { using namespace CryptoPP; HMAC<SHA256> hmac(m_iv, AES::BLOCKSIZE); string mac; StringSource(encodedMessage, true, new HashFilter(hmac, new StringSink(mac))); cout << "<CRYPTO> Created HMAC from AES-encrypted message with size " << mac.length() * 8 << endl; return mac; } bool Cryptography::checkHMAC(const string &hmac, const string &encryptedMessage) { auto result = hmac == createHMAC(encryptedMessage); cout << "<CRYPTO> Checking HMAC.. " << (result ? "matching!" : "not matching!") << endl; return result; } void Cryptography::initialize(const int secret) { memset(m_key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH); memset(m_iv, 0x00, CryptoPP::AES::BLOCKSIZE); cout << "<CRYPTO> Creating IV with information from DH shared key\n"; m_iv[0] = (secret >> 24) & 0xFF; m_iv[1] = (secret >> 16) & 0xFF; m_iv[2] = (secret >> 8) & 0xFF; m_iv[3] = secret & 0xFF; } string Cryptography::encrypt(const string &plainText) { cout << "<CRYPTO> Encrypting message using AES, message: " << plainText << endl; CryptoPP::AES::Encryption aesEncryption(m_key, CryptoPP::AES::DEFAULT_KEYLENGTH); CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, m_iv); string encryptedText; CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink(encryptedText)); stfEncryptor.Put(reinterpret_cast<const unsigned char*>(plainText.c_str()), plainText.length() + 1); stfEncryptor.MessageEnd(); return encryptedText; } string Cryptography::decrypt(const string &encryptedText) { cout << "<CRYPTO> Decrypting message using AES\n"; CryptoPP::AES::Decryption aesDecryption(m_key, CryptoPP::AES::DEFAULT_KEYLENGTH); CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, m_iv); string decryptedText; CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink(decryptedText)); stfDecryptor.Put(reinterpret_cast<const unsigned char*>(encryptedText.c_str()), encryptedText.size()); stfDecryptor.MessageEnd(); return decryptedText; }
true
b28d974e301c4e82f56118646fb3dbc4345b2c90
C++
himichael/LeetCode
/src/301_400/0376_wiggle-subsequence/wiggle-subsequence.cpp
UTF-8
505
2.859375
3
[ "Apache-2.0" ]
permissive
class Solution { public: int wiggleMaxLength(vector<int>& nums) { int n = nums.size(); if(n < 2) { return n; } int pre_diff = nums[1] - nums[0]; int res = pre_diff != 0 ? 2 : 1; for(int i = 2; i < n; ++i) { int diff = nums[i] - nums[i - 1]; if((diff > 0 && pre_diff <= 0) || (diff < 0 && pre_diff >= 0)) { ++res; pre_diff = diff; } } return res; } };
true
5b66fae5a880398bc1c8606bac2e860f2a8f08e2
C++
ha6017/MIPS_SIMULATOR
/src/memory.cpp
UTF-8
11,665
3.046875
3
[]
no_license
#include "memory.hpp" #include <iostream> #include <fstream> memory::memory(std::string name_bin) { ADDR_DATA.resize(0x4000000); //ADDR_INSTR.resize(0x1000000); std::fill(ADDR_DATA.begin(), ADDR_DATA.end() , 0); //std::cout<< "data zeroed\n"; //std::fill(ADDR_INSTR.begin(), ADDR_INSTR.end() , 0); //std::cout<< "Insts zeroed\n"; std::ifstream file_name(name_bin.c_str(), std::ifstream::binary); //std::cout<<"file is loaded\n"; if(!file_name.is_open()) { std::exit(-21); } //std::cout<<"file is open\n"; file_name.seekg(0, std::ios::end); int size = file_name.tellg(); //tells the size of file if(size>0x1000000) { std::exit(-11); } char bin_array [size]; file_name.seekg(0, std::ios::beg); //put the cursor back to 0 file_name.read (bin_array, size); //read the file file_name.close(); num_instructions = sizeof(bin_array)/4; int ar_i=0; for (int i=0;i<num_instructions;i++) { ar_i=i*4; //ADDR_INSTR[i] = ((bin_array[ar_i]<<24)&0xFF000000)|((bin_array[ar_i+1]<<16)&0x00FF0000)|((bin_array[ar_i+2]<<8)&0x0000FF00)|((bin_array[ar_i+3])&0x000000FF); //std::cout << std::hex<< ADDR_INSTR[i] << std::endl; ADDR_INSTR.push_back(((bin_array[ar_i]<<24)&0xFF000000)|((bin_array[ar_i+1]<<16)&0x00FF0000)|((bin_array[ar_i+2]<<8)&0x0000FF00)|((bin_array[ar_i+3])&0x000000FF)); } } uint32_t memory::readInstruction(uint32_t PC) { if((PC%4==0) && ((PC < 0x11000000) && (PC >= 0x10000000))) { uint32_t indexPC=(PC-0x10000000)/4; if(indexPC<ADDR_INSTR.size()) return ADDR_INSTR[indexPC]; else return 0; } else std::exit(-11); } int32_t memory::load_from_memory(int index) { //CHECKING FOR GETCHAR if(index==0x30000000) { int data_in = std::getchar(); if(std::cin.eof()) return 0xFFFFFFFF; if(!std::cin.good()) std::exit(-21); return (data_in);//how to return char from the function } //RUNNNING THE NORMAL INSTRUCTION if((index%4 == 0) && (index>=0x20000000) && (index<0x24000000) )//this is only loading word so should only call from the start { uint32_t Index_actual = (index-0x20000000); return (((int32_t(ADDR_DATA[Index_actual]<<24))&0xFF000000)|((int32_t(ADDR_DATA[Index_actual+1]<<16))&0x00FF0000)|((int32_t(ADDR_DATA[Index_actual+2])<<8)&0x0000FF00)|(int32_t(ADDR_DATA[Index_actual+3])&0x000000FF)); } else { std::exit(-11); //memory exception } } int32_t memory::load_byte_from_memory(int index) { //CHECKING FOR GETCHAR if((index>=0x30000000)&&(index<0x30000004))//getc { char data_in = std::getchar(); if(std::cin.eof() || feof(stdin)) return -1; if(!std::cin.good()) std::exit(-21); if(index==0x30000003) return int32_t(data_in); return 0x00000000; } //RUNNINNG NORMAL INSTRUCTIONN if((index>=0x20000000) && (index<0x24000000))//check if we are only getting the least significant byte { uint32_t Index_actual = (index-0x20000000); //int32_t Sign_ext_byte = ADDR_DATA[Index_actual]; //std::cout<<std::hex<<"ADDR_DATA["<<Index_actual<<"]="<<ADDR_DATA[Index_actual]<<std::endl; //int32_t check = int32_t(ADDR_DATA[Index_actual]); //std::cout<<std::hex<<check<<std::endl; int value = (0x000000FF & ADDR_DATA[Index_actual]); int mask = 0x00000080; if(mask & ADDR_DATA[Index_actual]) { value += 0xFFFFFF00; } //std::cout<<std::hex<<"value ="<<value<<std::endl; return value; } else { std::exit(-11); } } uint32_t memory::load_unsigned_byte_from_memory(int index) { //CHECKING FOR GETCHAR if((index>=0x30000000)&&(index<0x30000004))//getc { char data_in = std::getchar(); if(std::cin.eof() || feof(stdin)) return 0x000000FF; if(!std::cin.good()) std::exit(-21); if(index==0x30000003) return (int32_t(data_in)&0x000000FF); return 0; } //RUNNING NORMAL INSTRUCTION if((index>=0x20000000) && (index<0x24000000)) { uint32_t Index_actual = (index-0x20000000); //uint32_t zero_ext_byte = int32_t(ADDR_DATA[Index_actual])&0x000000FF; return uint32_t(int32_t(ADDR_DATA[Index_actual])&0x000000FF); } else { std::exit(-11); } } int32_t memory::load_half_word_from_memory(int index) { //CHECKING FOR GETCHAR if((index==0x30000000) || (index==0x30000002)) { char data_in = std::getchar(); if(std::cin.eof() || feof(stdin)) return 0xFFFFFFFF; if(!std::cin.good()) std::exit(-21); if(index==0x30000002) return (int32_t)(data_in) & 0xFF; return 0; } //RUNNING NORMAL INNSTRUCTION if((index>=0x20000000) && (index<0x24000000) && (index%2==0)) { uint32_t Index_actual = (index-0x20000000); int16_t sign_ext_halfword = (((ADDR_DATA[Index_actual]<<8)&0xFF00)|(ADDR_DATA[Index_actual+1]&0xFF)); //std::cout<<std::hex<<"load halfword from mem ="<<(int32_t)sign_ext_halfword<<std::endl; return (int32_t)sign_ext_halfword; } else { std::exit(-11); } } uint32_t memory::load_unsigned_half_word_from_memory(int index) { //CHECKING FOR GETCHAR if((index==0x30000000) || (index==0x30000002)) { char data_in = std::getchar(); if(std::cin.eof() || feof(stdin)) return 0x0000FFFF; if(!std::cin.good()) std::exit(-21); if(index==0x30000002) return (int32_t(data_in)&0x000000FF); return 0; } //RUNNING NORMAL INNSTRUCTION if((index>=0x20000000) && (index<0x24000000) && (index%2==0)) { uint32_t Index_actual = (index-0x20000000); return (int32_t((int16_t(ADDR_DATA[Index_actual]<<8)&0xFF00)|(int16_t(ADDR_DATA[Index_actual+1])&0xFF))&0xFFFF);//CHECK************************* } else std::exit(-11); } int32_t memory::load_word_right_from_memory(int index) { //CHECKING FOR GETCHAR if(index>=0x30000000 && index<0x30000004) { int data_in = std::getchar(); if(std::cin.eof() || feof(stdin)) return 0xFFFFFFFF; if(!std::cin.good()) std::exit(-21); if(index==0x30000003) { return (data_in);//how to return char from the function } else return 0; } /*if(index==0x30000003) { int data_in = std::getchar(); if(std::cin.eof()) return 0xFFFFFFFF; if(!std::cin.good()) std::exit(-21); return (data_in);//how to return char from the function }*/ if((index>=0x20000000) && (index<0x24000000)) { uint32_t Index_actual = (index-0x20000000); switch (Index_actual%4) { case 0: return(int32_t(ADDR_DATA[Index_actual])&0x000000FF); break; case 1: return(int32_t(((ADDR_DATA[Index_actual-1]<<8)&0x0000FF00)|(ADDR_DATA[Index_actual]&0x000000FF))); break; case 2: return(int32_t(((ADDR_DATA[Index_actual-2]<<16)&0x00FF0000)|((ADDR_DATA[Index_actual-1]<<8)&0x0000FF00)|(ADDR_DATA[Index_actual]&0x000000FF))); break; case 3: return(int32_t(((ADDR_DATA[Index_actual-3]<<24)&0xFF000000)|((ADDR_DATA[Index_actual-2]<<16)&0x00FF0000)|((ADDR_DATA[Index_actual-1]<<8)&0x0000FF00)|(ADDR_DATA[Index_actual]&0x000000FF))); break; } } else std::exit(-11); } int32_t memory::load_word_left_from_memory(int index) { //CHECKING FOR GETCHAR if(index>=0x30000000 && index<0x30000004) { int data_in = std::getchar(); if(std::cin.eof() || feof(stdin)) return 0xFFFFFFFF; if(!std::cin.good()) std::exit(-21); if(index==0x30000000) { return (data_in);//how to return char from the function } else return 0; } /*if(index==0x30000000) { int data_in = std::getchar(); if(std::cin.eof() || feof(stdin)) return 0xFFFFFFFF; if(!std::cin.good()) std::exit(-21); return (data_in);//how to return char from the function }*/ if((index>=0x20000000) && (index<0x24000000)) { uint32_t Index_actual = (index-0x20000000); switch (Index_actual%4) { case 0: return (((ADDR_DATA[Index_actual]<<24)&0xFF000000)|((ADDR_DATA[Index_actual+1]<<16)&0x00FF0000)|((ADDR_DATA[Index_actual+2]<<8)&0x0000FF00)|(ADDR_DATA[Index_actual+3]&0x000000FF)); break; case 1: return (int32_t(((ADDR_DATA[Index_actual]<<24)&0xFF000000)|((ADDR_DATA[Index_actual+1]<<16)&0x00FF0000)|((ADDR_DATA[Index_actual+2]<<8)&0x0000FF00))&0xFFFFFF00); break; case 2: return (int32_t(((ADDR_DATA[Index_actual]<<24)&0xFF000000)|((ADDR_DATA[Index_actual+1]<<16)&0x00FF0000))&0xFFFF0000); break; case 3: return(int32_t(ADDR_DATA[Index_actual]<<24)&0xFF000000); break; } } else std::exit(-11); } void memory::store_to_memory(int index, int32_t value) { //CHECKING FOR PUTCHAR if(index==0x30000004){ char data_out= int8_t(value&0xFF); if(!std::cout.good()) std::exit(-21); std::putchar(data_out);//how to return char from the function return; } //RUNNINNG NORMAL INSTRUCTION if ((index%4 == 0) && (index>=0x20000000) && (index<0x24000000)) { uint32_t Index_actual = (index-0x20000000); ADDR_DATA[Index_actual] = int8_t((value&0xFF000000)>>24); //std::cout<<"ADDR_DATA["<<Index_actual<<"]="<< static_cast<int16_t>(ADDR_DATA[Index_actual]) <<std::endl; ADDR_DATA[Index_actual+1] = int8_t((value&0xFF0000)>>16); //std::cout<<"ADDR_DATA["<<Index_actual+1<<"]="<<static_cast<int16_t>(ADDR_DATA[Index_actual+1])<<std::endl; ADDR_DATA[Index_actual+2] = int8_t((value&0xFF00)>>8); //std::cout<<"ADDR_DATA["<<Index_actual+2<<"]="<< static_cast<int16_t>(ADDR_DATA[Index_actual+2]) <<std::endl; ADDR_DATA[Index_actual+3] = int8_t(value&0xFF); //std::cout<<"ADDR_DATA["<<Index_actual+3<<"]="<< static_cast<int16_t>(ADDR_DATA[Index_actual+3]) <<std::endl; } else std::exit(-11); // memory exception } void memory::store_byte_to_memory(int index, int8_t value) { //CHECKING FOR PUTCHAR if((index>=0x30000004)&&(index<0x30000008))//putc { char data_out= value&0xFF; if(!std::cout.good()) { std::exit(-21); } if(index==0x30000007) { std::putchar(data_out);//how to return char from the function } else { std::putchar(0); } return; } //RUNNNING NORMAL INSTRUCTION if ((index>=0x20000000) && (index<0x24000000)) { uint32_t Index_actual = (index-0x20000000); ADDR_DATA[Index_actual] = value; } else { std::exit(-11); // memory exception } } void memory::store_halfword_to_memory(int index, int16_t value) { //CHECKING FOR PUTCHAR if((index==0x30000004) || (index==0x30000006)) { char data_out= int8_t(value&0xFF); if(!std::cout.good()) std::exit(-21); if(index==0x30000006) std::putchar(data_out); else std::putchar(0); return; } //RUNNNING NORMAL INSTRUCTION if ((index>=0x20000000) && (index<0x24000000) && (index%2==0)) { uint32_t Index_actual = (index-0x20000000); ADDR_DATA[Index_actual] = int8_t((value&0xFF00)>>8); ADDR_DATA[Index_actual+1] = int8_t((value&0xFF)); } else std::exit(-11); // memory exception } int8_t memory::load_byte_from_instruction(int index) { int offset = index % 4; uint32_t Index_actual = (index - offset - 0x10000000)/4; if(Index_actual<ADDR_INSTR.size()) { switch (offset) { case 0: return((ADDR_INSTR[Index_actual]&0xFF000000)>>24); break; case 1: return((ADDR_INSTR[Index_actual]&0x00FF0000)>>16); break; case 2: return((ADDR_INSTR[Index_actual]&0x0000FF00)>>8); break; case 3: return(ADDR_INSTR[Index_actual]&0x000000FF); break; } } else return 0; } int16_t memory::load_half_word_from_instruction(int index) { int offset = index % 4; uint32_t Index_actual = (index - offset - 0x10000000)/4; if(Index_actual<ADDR_INSTR.size()) { switch (offset) { case 0: return((ADDR_INSTR[Index_actual]&0xFFFF0000)>>16); break; case 2: return(ADDR_INSTR[Index_actual]&0x0000FFFF); break; } } else return 0; }
true
2bf564e52de37b3295e4555bb08b7b60a1e0b4ff
C++
Sayak9495/_100daysofcoding_
/_100daysofcoding_/CCI/2. Linked List/linked_list_2.6.cpp
UTF-8
1,381
4
4
[ "MIT" ]
permissive
// check if a linked list is a palindrome #include<iostream> #include<string> using namespace std; struct node{ int data; node *next; }; node* create_list(){ int x; cin>>x; node* list; list = NULL; while (x--){ node* temp = new node(); cin>>(*temp).data; if (list==NULL){ list=temp; } else{ node* temp_ = list; while((*temp_).next!=NULL){ temp_ = (*temp_).next; } (*temp_).next = temp; } } return list; } void show_list(node* root){ cout<<"-----------"<<endl; while((*root).next!=NULL){ cout<<(*root).data<<endl; root = (*root).next; } cout<<(*root).data<<endl<<endl; } string list_to_string(node* root){ string list_str=""; while((*root).next!=NULL){ list_str+=(*root).data; //Anyone reading this code please let me know if this code will fail any test case. p.s Im not coverting int to char correctly (int to char can be done as intended using sstream used in arra_string1.6.cpp) root = (*root).next; } list_str+=(*root).data; return list_str; } string check_palindrome(string str){ string rev_str=""; for(int i=str.size()-1;i>=0;i--){ rev_str+=str[i]; } cout<<str<<"--"<<rev_str<<endl; if(str==rev_str) return "Palindrome"; return "Not Palindrome"; } int main(){ node* list = create_list(); show_list(list); string list_str = list_to_string(list); cout<<check_palindrome(list_str); return 1; }
true
9b59685301c37974a586e382a3c46b7482d8c999
C++
JamieAgate/Hangman
/Hangman 2/Main.cpp
UTF-8
13,829
3.65625
4
[]
no_license
#include <iostream> #include <iomanip> #include <random> #include <chrono> #include <Windows.h> //List of all game functions. int mainmenu(); void boards(int i); void instructions(); char* difficulty(char* currentWord); bool Replay(bool replay); int drawTheGame(int length, bool guessedCorrectly[], char* currentWord, char wrongLetters[], int counter); char guessALetter(); int letterCheck(int oldFalseCounter, int newFalseCounter, int len, char* currentWord, char guessedLetter, bool guessedCorrectly[]); int failStateCounterUpdate(int oldFalseCounter, int newFalseCounter, char wrongLetters[], int failStateCounter, char guessedLetter); void win(int exit); int checkWonOrLost(int failStateCounter,int exit, int counter, int len); //Main game loop int main() { //Replay loop: will break if user does not want to replay bool replay = true; while (replay == true) { //Go to main menu and get the user choice int c = mainmenu(); //variable that counts if player has lost int failStateCounter = 0; //switch that changes based on what the player chose. switch (c) { //play game case 1: { //Variables bool guessedCorrectly[11] = { false };//if player guessed letter n correctly flase n will be set to true int counter = 0;//if counter = length of word then the game has been won because all letters have been guessed correctly char wrongLetters[6] = { ' ',' ',' ',' ',' ',' ' };//keeps track of all the wrongly guessed letters. char guessedLetters[17] = { ' ' };//array that holds all of the letters that have been guessed. char guessedLetter = ' ';//variable that will hold the value of the players guessed letter int oldFalseCounter = 0;//counter that will keep track of the past number of flase's in the guessedCorrectly array char* currentWord = " ";//variable that will hold the current secret word int exit = 0;//varible that dictates when to end the game loop and if the player has won or not int noOfGuessedLetters = 0;//variable that keeps track of the number of latters that have been guessed system("CLS"); //Get the random word by selecting the difficulty and then the word currentWord = difficulty(currentWord);//function that will ask the player what difficulty they want to play and select the random word. size_t len = std::strlen(currentWord);//length of current word int newFalseCounter = len;//variable that will keep track of the current number of false's in the guessedCorrectly array //main game loop while (exit == 0) { system("cls"); //function that will draw the boards based on what failstate the player is at. boards(failStateCounter); //function that will check the letter to see if it matches any of the letters in the word, counts them up and outputs them. oldFalseCounter = letterCheck(oldFalseCounter, newFalseCounter, len, currentWord, guessedLetter, guessedCorrectly); //function that will see if any of the elements in the guessedCorrectly array have changed, if not then the failStateCounter will be the same as the oldFailStateCoutner failStateCounter = failStateCounterUpdate(oldFalseCounter, newFalseCounter, wrongLetters, failStateCounter, guessedLetter); //function that will draw the rest of the game elements and output how many letters have been guessed correctly. counter = drawTheGame(len, guessedCorrectly, currentWord, wrongLetters, counter); //function that checks if the game has been won or lost. exit = checkWonOrLost(failStateCounter, exit, counter, len); //if the game is won or lost then another letter input is not needed. if (exit == 0) { //function to let the player guess a letter guessedLetter = guessALetter(); //START OF VALIDATION// bool alreadyEntered = true;//if the letter has not already been enterd this will be set to false bool passedTest = true;//if it is set to true this will break the loop and continue with the rest of the program //loop will not exit unless already entered is false. while (alreadyEntered == true) { //check if the input was a letter. while (96 >= int(guessedLetter) || 123 <= int(guessedLetter)) { //tells the user the input is invalid and prompts for another input. std::cout << std::endl << guessedLetter << " is invalid.\nGuess a letter: "; std::cin >> guessedLetter; guessedLetter = tolower(guessedLetter); } //check if letter enterd has already been entered for (int i = 0; i < 15; i++) { passedTest = true;//sets to true after every loop //checks to see if letter entered has already been entered if (guessedLetter == guessedLetters[i]) { //prompts user for a new letter. std::cout << "\nAlready Entered, please guess again: "; std::cin >> guessedLetter; guessedLetter = tolower(guessedLetter); passedTest = false; //breaks the for loop break; } } //if the test was passed and no letter was found to match. if (passedTest == true) { //sets the number element in the numberOfGuessedLetters to equal the guessed letter so it cant be guessed again. guessedLetters[noOfGuessedLetters] = guessedLetter; noOfGuessedLetters++; //breaks the while loop alreadyEntered = false; } } //END OF VALIDATION// } } //END OF MAIN GAME LOOP// //function that will check if the game has been won or lost and output as appropriate. win(exit); //prompts the user if they want to play again. replay = Replay(replay); break; } //instructions case 2: { instructions(); break; } //exit game case 3: { std::cout << "Goodbye... \n"; Sleep(500); replay = false; break; } //if the user has entered an invalid option. default: { system("cls"); std::cout << "Invalid Response.\n"; break; } } } } //Main Menu of the game int mainmenu() { //print out menu std::cout << "#######################\n# HANGMAN #\n#######################\n_______________________\n"; std::cout << "Play:" << std::setw(19) << "Press 1\n"; std::cout << "Instructions:" << std::setw(11) << "press 2\n"; std::cout << "Exit:" << std::setw(19) << "press 3\n"; //switch that takes the users choice of what they want to do int c = 0; std::cin >> c; return c; } //user selects the difficulty of the game char* difficulty(char* currentWord) { //sets the current word to be empty currentWord = " "; bool esc = false;//varible that will make the loop repeat if given an invalid response while (esc == false) { //Print out menu std::cout << "#######################\n# HANGMAN #\n#######################\n_______________________\n"; std::cout << "Slect a difficly\n"; std::cout << "Easy:" << std::setw(19) << "Press 1\n"; std::cout << "Medium:" << std::setw(17) << "press 2\n"; std::cout << "Hard:" << std::setw(19) << "press 3\n"; //get the user input for what difficulty they want int x = 0; std::cin >> x; //all difficulty word arrays. char* easyWords[5] = { "cat", "hat", "sat", "dog", "egg" }; char* medWords[5] = { "logical", "pointer", "hangman", "keyboard", "orange" }; char* hardWords[5] = { "kickboxer", "equalizing", "meaningless", "jaywalking", "microwave" }; //seading the rand srand(time(NULL)); //switch that chooses the difficulty switch (x) { //Easy words case 1: { currentWord = easyWords[rand() % 5]; esc = true; break; } //Medium words case 2: { currentWord = medWords[rand() % 5]; esc = true; break; } //Hard words case 3: { currentWord = hardWords[rand() % 5]; esc = true; break; } //if the user has entered an invalid option default: { system("cls"); std::cout << "Invalid Response.\n"; break; } } } return currentWord; } //game outputs all the information the user needs and counts up all the correctly guessed letters int drawTheGame(int length, bool guessedCorrectly[], char* currentWord, char wrongLetters[], int counter) { //resets the counter. counter = 0; for (int i = 0; i < length; i++) { //if letter hasnt been guessed outputs a dash else outputs the correctly guessed letter. if (guessedCorrectly[i] == true) { std::cout << currentWord[i]; counter++; } else { std::cout << "_ "; } } //outputs all the incorrect guesses std::cout << "\nIncorrect Guesses: "; for (int i = 1; i < 6; i++) { //if there is nothing in the wron letters array element print out nothing else print a dash if (wrongLetters[i] != ' ') { std::cout << wrongLetters[i] << " "; } else { std::cout << "_ "; } } return counter; } //allows user to input a letter. char guessALetter() { //get the user input std::cout << "\nGuess a letter: "; char guessedLetter = ' '; std::cin >> guessedLetter; guessedLetter = tolower(guessedLetter); return guessedLetter; } //checks if the letter was guessed correcly int letterCheck(int oldFalseCounter ,int newFalseCounter, int len, char* currentWord, char guessedLetter, bool guessedCorrectly[]) { //checking if any letters have been guessed correctly oldFalseCounter = newFalseCounter; newFalseCounter = 0; for (int i = 0; i < len; i++) { //check if the letter in i matches the guessed letter if (currentWord[i] == guessedLetter) { guessedCorrectly[i] = true; } //count up number of letters that have remained in the same state (correct or incorrect) if (guessedCorrectly[i] == false) { newFalseCounter++; } } return oldFalseCounter, newFalseCounter; } //adds the letter to wrong letters if it was guessed wrong and updates the failstatecounter. int failStateCounterUpdate(int oldFalseCounter, int newFalseCounter, char wrongLetters[], int failStateCounter, char guessedLetter) { //if the newfalsecounter is the same as the oldfalsecounter then no letter was guessed correctly that time so loose a life. if (oldFalseCounter == newFalseCounter) { wrongLetters[failStateCounter] = guessedLetter; failStateCounter++; } return failStateCounter; } //checks if the game has been won or lost int checkWonOrLost(int failStateCounter, int exit, int counter, int len) { //if the plater is out of lives if (failStateCounter == 6) { exit = 1; } //if the number of correct letters = the length of the word if (counter == len) { exit = 2; } return exit; } //will output win or loose as apropriate void win(int exit) { system("cls"); //if the game has been won if (exit == 2) { std::cout << "\n\nYOU WIN!!!\n\n"; } //if the game has been lost else { std::cout << "\n\n _______\n"; std::cout << " |/ |\n"; std::cout << " | (_)\n"; std::cout << " | \\|/\n"; std::cout << " | |\n"; std::cout << " | / \\ \n"; std::cout << " |\n"; std::cout << " _|___\n"; std::cout << "\n\nYOU LOOSE!!!\n\n"; } } //function that draws the boards void boards(int i) { switch (i) { case 0: std::cout << "\n\n \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " _|___\n"; break; case 1: std::cout << "\n\n _______\n"; std::cout << " |/ \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " _|___\n"; break; case 2: std::cout << "\n\n _______\n"; std::cout << " |/ |\n"; std::cout << " | (_)\n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " _|___\n"; break; case 3: std::cout << "\n\n _______\n"; std::cout << " |/ |\n"; std::cout << " | (_)\n"; std::cout << " | |\n"; std::cout << " | |\n"; std::cout << " | \n"; std::cout << " |\n"; std::cout << " _|___\n"; break; case 4: std::cout << "\n\n _______\n"; std::cout << " |/ |\n"; std::cout << " | (_)\n"; std::cout << " | \\|/ \n"; std::cout << " | |\n"; std::cout << " | \n"; std::cout << " | \n"; std::cout << " _|___\n"; break; } } //Does the player want to replay the game bool Replay(bool replay) { //variable that means the input has to be valid before continuing bool esc = false; while (esc == false) { //propmpts the user if they want to replay std::cout << "Play again?(y/n): "; char playAgain = ' '; std::cin >> playAgain; switch (playAgain) { case 'y': { //if yes the game will restat std::cout << "Restarting... "; Sleep(500); system("cls"); replay = true; esc = true; break; } case 'n': { //if no the game will stop std::cout << "Goodbye... \n"; Sleep(500); replay = false; esc = true; break; } default: { //if not a valid response std::cout << "\nInvalid Response\n"; break; } } } return replay; } //instuctions for the game void instructions() { system("cls"); std::cout << "#######################\n# HANGMAN #\n#######################\n_______________________\n"; std::cout << "The objective is to guess \nthe word that is hidden in \nthe blanks at the top, \nwhen you guess incorrectly \nthe hangman will be drawn \na bit more. \nYou must guess the word before \nthe man is hung.\n\nPress any key to go back to the menu.\n\n"; system("pause"); system("cls"); main(); }
true
d6e66d2c5566fc8bce95d4e76282ddf2a1727ae0
C++
CodeDiary18/CodeUp
/1001-1100/1093.cpp
UTF-8
270
2.6875
3
[]
no_license
#include<iostream> int main(){ int n; std::cin>>n; int arr[24]={0,}; int temp; for(int i=0;i<n;i++){ std::cin>>temp; arr[temp]=arr[temp]+1; } for(int i=1;i<=23;i++){ std::cout<<arr[i]<<" "; } return 0; }
true
2b149228e7d4fe0f68c810e0ca8567d333e7fd1f
C++
JRTitor/CppDevelopment
/yellowBelt/week3_1/week3_1.cpp
UTF-8
281
3.03125
3
[]
no_license
#include "sum_reverse_sort.h" #include <algorithm> int Sum(int x, int y){ return x+y; } string Reverse(string s){ string out; for(size_t i = s.length() - 1; i >0 ; --i) { out += s[i]; } return out; } void Sort(vector<int>& nums){ sort(nums.begin(), nums.end()); }
true
9b7cd4adb55d67ea61cbb1270c8108d083d05a3e
C++
misule0423/BOJ
/10870.cpp
UTF-8
463
2.90625
3
[]
no_license
// // main.cpp // 10870 // // Created by 이민석 on 2016. 9. 1.. // Copyright © 2016년 Roop. All rights reserved. // #include <iostream> using namespace std; int fibonacchi(int n){ if(n==0) return 0; else if(n==1) return 1; else return fibonacchi(n-1) + fibonacchi(n-2); } int main(int argc, const char * argv[]) { int k; cin >> k; cout << fibonacchi(k) << endl; return 0; }
true
a87fe99f1925dbf80f82ae6523c7d769ab4514b6
C++
NuChitsanupong/prob-solve
/pdf_week3/ic.cpp
UTF-8
1,739
2.5625
3
[]
no_license
<<<<<<< HEAD #include <iostream> #include <stdio.h> #include <list> using namespace std; list<int> ll; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { string c; int num; cin >> c; if (c == "li") { cin >> num; ll.push_front(num); } else if (c == "ri") { cin >> num; ll.push_back(num); } else if (c == "lr") { int tmp = ll.front(); ll.push_back(tmp); ll.pop_front(); } else if (c == "rr") { int tmp = ll.back(); ll.push_front(tmp); ll.pop_back(); } } for (list<int>::iterator it = ll.begin(); it != ll.end(); it++) { cout << *it << " "; } return 0; ======= #include <iostream> #include <stdio.h> #include <list> using namespace std; list<int> ll; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { string c; int num; cin >> c; if (c == "li") { cin >> num; ll.push_front(num); } else if (c == "ri") { cin >> num; ll.push_back(num); } else if (c == "lr") { int tmp = ll.front(); ll.push_back(tmp); ll.pop_front(); } else if (c == "rr") { int tmp = ll.back(); ll.push_front(tmp); ll.pop_back(); } } for (list<int>::iterator it = ll.begin(); it != ll.end(); it++) { cout << *it << " "; } return 0; >>>>>>> c46aa179a8a23e5373040e0f81a74ba2ccfabaaf }
true
30fc3b7efef6bf39b6378ab40536402a4a70aab8
C++
HubStew/algorithmProblem
/1152_단어의 개수.cpp
UTF-8
530
3.0625
3
[]
no_license
#include<iostream> #include<string> using namespace std; string str[1000000] = {"", }; int main() { string input; getline(cin, input); //for (int i = 0; i < 1000000; i++) // str[i] = ""; int count = 0; for (int i = 0; i < input.length(); i++) { if (input[i] == ' ') { count++; continue; } str[count] += input[i]; } int result = 0; for (int i = 0; i <= count; i++) { //cout << str[i] << endl; if (str[i] == "") { } else result++; } cout << result << endl; return 0; }
true
9ee069b045516586ac9153678dd82a07ec6bbc8e
C++
LArSoft/lardata
/lardata/RecoObjects/Surface.h
UTF-8
4,032
3.015625
3
[]
no_license
//////////////////////////////////////////////////////////////////////// /// /// \file Surface.h /// /// \brief Base class for Kalman filter surface. /// /// \author H. Greenlee /// /// Surfaces may have the following distinct uses in the context /// of the Kalman filter. /// /// 1. Destination for track propagation. /// 2. Define a local 3D coordinate systems. /// 3. Have a standard set of track parameters, which are meaningful /// in the local coordinate system. /// /// Larsoft global coordinates are (x,y,z). /// /// Surface local coordinates are called (u,v,w), where w=0 is the /// surface, and (u,v) are the local coordinates within the surface. /// /// Notes about track and surface directions: /// /// 1. Surfaces are in general orientable, which means that a track /// that is located at a surface can be propagating in the forward /// direction with respect to the surface (dw/ds > 0) or in the /// backward direction (dw/ds < 0). /// 2. For some kinds surfaces and track parameters, the track /// direction is implied by the track parameters themselves. /// For others it isn't, and must be supplied externally. /// 3. A surface can be queried to find the track direction implied /// by track parameters, (via method Surface::getDirection), with /// result returned via enum TrackDirection (possible values FORWARD, /// BACKWARD, UNKNOWN). /// 4. In all situations, a direction implied by track parameters /// has precedence over an externally supplied one. /// /// This class doesn't have any attributes of its own, but it provides /// several virtual methods that derived classes can or must override. /// //////////////////////////////////////////////////////////////////////// #ifndef SURFACE_H #define SURFACE_H #include "lardata/RecoObjects/KalmanLinearAlgebra.h" #include <iosfwd> namespace trkf { class Surface { public: /// Track direction enum. enum TrackDirection { FORWARD, BACKWARD, UNKNOWN }; /// Default constructor. Surface(); /// Destructor. virtual ~Surface(); // Virtual methods. /// Clone method. virtual Surface* clone() const = 0; /// Surface-specific tests of validity of track parameters. virtual bool isTrackValid(const TrackVector& vec) const = 0; /// Transform global to local coordinates. virtual void toLocal(const double xyz[3], double uvw[3]) const = 0; /// Transform local to global coordinates. virtual void toGlobal(const double uvw[3], double xyz[3]) const = 0; /// Calculate difference of two track parameter vectors. virtual TrackVector getDiff(const TrackVector& vec1, const TrackVector& vec2) const; /// Get position of track. virtual void getPosition(const TrackVector& vec, double xyz[3]) const = 0; /// Get direction of track (default UNKNOWN). virtual TrackDirection getDirection(const TrackVector& /* vec */, TrackDirection dir = UNKNOWN) const { return dir; } /// Get momentum vector of track. virtual void getMomentum(const TrackVector& vec, double mom[3], TrackDirection dir = UNKNOWN) const = 0; /// Get pointing error of track. virtual double PointingError(const TrackVector& vec, const TrackError& err) const = 0; /// Get starting error matrix for Kalman filter. virtual void getStartingError(TrackError& err) const = 0; /// Test whether two surfaces are parallel, within tolerance. virtual bool isParallel(const Surface& surf) const = 0; /// Find perpendicular forward distance to a parallel surface virtual double distanceTo(const Surface& surf) const = 0; /// Test two surfaces for equality, within tolerance. virtual bool isEqual(const Surface& surf) const = 0; /// Printout virtual std::ostream& Print(std::ostream& out) const = 0; }; /// Output operator. std::ostream& operator<<(std::ostream& out, const Surface& surf); } #endif
true
0316aa65b24279c4154b6ddbff796e7e5740959c
C++
zacharyvincze/chip8
/src/display.cpp
UTF-8
1,798
3.109375
3
[]
no_license
#include "display.h" #include "easylogging++.h" Display::Display() { clear(); LOG(INFO) << "Initialized Chip8 64x32 display"; }; Display::~Display() { SDL_DestroyRenderer(_renderer); SDL_DestroyWindow(_window); } void Display::clear() { for (int y = 0; y < 32; y++) { for (int x = 0; x < 64; x++) { _display_data[y][x] = 0; } } } bool Display::drawPixel(bool pixel, uint8_t x, uint8_t y) { /** * XOR <pixel> into display data at coordinates <x> and <y>. * Return 1 if this causes the pixel to turn off, 0 otherwise. */ bool turned_off = false; // If the pixel is on and the pixel at that location is also on, then they // collide. if (_display_data[y][x] && pixel) turned_off = true; _display_data[y][x] = _display_data[y][x] ^ pixel; return turned_off; } void Display::createWindow() { _window = SDL_CreateWindow("Chip-8 Emulator", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_FLAGS); _renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_FLAGS); SDL_RenderSetLogicalSize(_renderer, RENDERER_WIDTH, RENDERER_HEIGHT); SDL_ShowCursor(SDL_FALSE); } void Display::draw() { SDL_SetRenderDrawColor(_renderer, primaryColor.r, primaryColor.g, primaryColor.b, primaryColor.a); SDL_RenderClear(_renderer); SDL_SetRenderDrawColor(_renderer, secondaryColor.r, secondaryColor.g, secondaryColor.b, secondaryColor.a); for (int y = 0; y < 32; y++) { for (int x = 0; x < 64; x++) { if (_display_data[y][x]) SDL_RenderDrawPoint(_renderer, x, y); } } SDL_RenderPresent(_renderer); }
true
b90d02309a910f677835f9e89caee9a67b93fe96
C++
bakinboy1/BigDump
/c++/Project1/Project1/Source.cpp
UTF-8
1,740
2.984375
3
[]
no_license
#include "windows.h" #include <iostream> #include <string> #include <vector> using namespace std; int main() { cout << "Hello World! "; return 0; }; class bunny { private: int bunnyID; bool gender; int age; string name; string color; boolean mutant; public: void setID(int ID); int getID(void); void setGender(bool gen); bool getGender(void); void setAge(int ag); int getAge(void); void setName(string nam); string getName(void); void setColor(string col); string getColor(void); void setMutant(bool mut); bool getMutant(void); }; bunny::bunny(void) { void bunny::setID(int ID) { bunnyID = ID; } int bunny::getID(void){ cout << "ID: " << bunnyID; } void bunny::setGender(bool gen) { gender = gen; } bool bunny::getGender(void) { cout << "sex: " << gender; } void bunny::setAge(int ag) { age = ag; } int bunny::getAge(void) { cout << "age: " << age; } void bunny::setName(string nam) { name = nam; } string bunny::getName(void) { cout << "name: " << name; } void bunny::setColor(string col) { color = col; } string bunny::getColor(void) { cout << "color: " << color; } void bunny::setMutant(bool mut) { mutant = mut; } bool bunny:i:getMutant(void) { cout << "is a mutant? " << mutant; } }; Names() { std::vector<std::string> nameList; //add string name to nameList // nameList.push_back("example"); nameList.push_back("Thumper"); nameList.push_back("Fifel"); nameList.push_back("MACHO MAN RANDY SAVAGE"); nameList.push_back("carrot"); nameList.push_back("spot"); nameList.push_back("tulip"); nameList.push_back("poro"); nameList.push_back("atilla"); nameList.push_back("hamtaro"); nameList.push_back("floppy"); nameList.push_back("poof"); nameList.push_back("RICK FLAIR NATURE BOY WILSON"); }
true
2fc2c963e16a7c1345e7fa10c73cd8880cc1cf8c
C++
ParkDaeYi/Algorithm_Study
/10448.cpp
UTF-8
582
2.875
3
[]
no_license
#include <iostream> using namespace std; int dp[45], n, num; bool backt(int, int); int main() { ios_base::sync_with_stdio(0); cin.tie(0); for (int i = 1; i < 45; ++i) dp[i] = dp[i - 1] + i; cin >> n; for (int i = 0; i < n; ++i) { cin >> num; if (backt(0, 0)) cout << 1 << '\n'; else cout << 0 << '\n'; } return 0; } bool backt(int cnt,int sum) { if (cnt > 3) return 0; if (cnt == 3 && sum == num) return 1; if (cnt == 3 && sum != num) return 0; for (int i = 1; i < 45; ++i) { if (sum + dp[i] > num) return 0; if (backt(cnt + 1, sum + dp[i])) return 1; } }
true
6eae02b66f88550dbf63fdc6069edac58b75542f
C++
xlyoshi/Arduino
/2 - Efeitos com LEDs/Projeto 10 - Mood lamp com controle serial/Projeto_10_-_Mood_Lamp_com_controle_Serial/Projeto_10_-_Mood_Lamp_com_controle_Serial.ino
UTF-8
2,475
3.515625
4
[]
no_license
//Projeto 10 - Mood Lamp com controle Serial char buffer[18];//Armazena os parametros dos leds int red,green,blue;//parametros PWM dos leds int redPin=9,greenPin=10,bluePin=11;//portas dos LEds void setup() { Serial.begin(9600);//Inicia a comunicação serial while(Serial.available())//Limpa o serial Serial.read(); pinMode(redPin,OUTPUT); pinMode(greenPin,OUTPUT); pinMode(bluePin,OUTPUT); Serial.println("______________________________"); Serial.println("| Controle de Mood Lamp |"); Serial.println("| INPUT Format: |"); Serial.println("| r[val] g[val] b[val] |"); Serial.println("| Example: r255 g140 b72 |"); Serial.println("______________________________"); } void loop() { if(Serial.available()>0){//Verifica se algo foi digitado int index=0; delay(100);//deixa o buffer encher int numChar = Serial.available();/*Numero de caracteres digitados*/ if(numChar>15){//garante que não estouraremos o buffer numChar=15; } while(numChar--){//enquanto numChar!=0 buffer[index++]=Serial.read();//preenche os buffer } splitString(buffer); Serial.println("______________________________"); } } void splitString(char* data){//passagem por referência com cahr* Serial.print("Data entered: "); Serial.println(data); char* parameter; parameter = strtok(data," ,");//divide a string while(parameter!=NULL){ setLED(parameter); parameter=strtok(NULL," ,");/*Pega o próximo conjunto. O NULL indica que ela deve continuar de onde parou de extrair a string*/ } //Limpa o texto e os buffers seriais for(int x = 0;x<16;x++){ buffer[x]='\0'; } while(Serial.available()) Serial.read(); } void setLED(char* data){ if(data[0]=='r' || data[0]=='R'){ int Ans = strtol(data+1,NULL,10);//COnverte os //inteiros depois da letra em Números inteiros longos Ans=constrain(Ans,0,255);//Limita o valor entre 0 e 255 analogWrite(redPin,Ans); Serial.print("Red is set to: "); Serial.println(Ans); } if(data[0]=='g' || data[0]=='G'){ int Ans = strtol(data+1,NULL,10); Ans=constrain(Ans,0,255); analogWrite(greenPin,Ans); Serial.print("Green is set to: "); Serial.println(Ans); } if(data[0]=='b' || data[0]=='B'){ int Ans = strtol(data+1,NULL,10); Ans=constrain(Ans,0,255); analogWrite(bluePin,Ans); Serial.print("Blue is set to: "); Serial.println(Ans); } }
true
3bfc10597d5d5976b527f494312842c610112e0e
C++
tom3097/EiTI-Projects
/PROI/SymulacjaFirmyKurierskiej/Baza.cpp
WINDOWS-1250
9,856
2.703125
3
[]
no_license
//Projekt 3: Symulacja Firmy Kurierskiej //Przygotowal: Tomasz Bochenski //Prowadzacy: Piotr Witoski #include "Baza.h" extern std::vector<tymczasowa_przestrzen> vector_przestrzeni; extern std::vector<std::string> dozwolone_lokalizacje; extern std::ofstream plik_wynikowy; //konstruktor domyslny Baza::Baza(void) { } //konstruktor z parametrem Baza::Baza(std::string lokalizacja): Placowka("BAZA",lokalizacja) { } //destruktor Baza::~Baza(void) { b_baza_klientow.clear(); } //metoda sluzaca do dodawania klienta przez urzytkownika void Baza::dodaj_klienta(std::string tab_klient[4]) { Klient klient_do_dodania(tab_klient); if(Klient::poprawna_lokalizacja(tab_klient[2])) { unsigned rozmiar = b_baza_klientow.size(); for(unsigned i=0; i<rozmiar; i++) { if(b_baza_klientow[i] == klient_do_dodania) { std::cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"; std::cout<<"Podana osoba jest juz zarejestrowana jako klient.\n"; std::cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"; return; } } b_baza_klientow.push_back(klient_do_dodania); std::cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"; std::cout<<"Klient zostal dodany: \n"; klient_do_dodania.wyswietl_informacje(); std::cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"; } } //metoda sluzaca do usuwanie klienta przez urzytkownika void Baza::usun_klienta(std::string tab_klient[4]) { Klient klient_do_usuniecia (tab_klient); if(Klient::poprawna_lokalizacja(tab_klient[2])) { unsigned rozmiar = b_baza_klientow.size(); for(unsigned i=0; i<rozmiar; i++) { if(b_baza_klientow[i] == klient_do_usuniecia) { if(i == b_baza_klientow.size() - 1) b_baza_klientow.pop_back(); else b_baza_klientow.erase(b_baza_klientow.begin()+i); std::cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"; std::cout<<"Klient zostal usuniety.\n"; std::cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"; return; } } std::cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"; std::cout<<"Podany klient nie istnieje.\n"; std::cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"; } } //wyswietlanie listy klientow zarejestrowanych w bazie void Baza::wyswietl_klientow(void) { for(unsigned i=0; i<b_baza_klientow.size(); i++) { b_baza_klientow[i].wyswietl_informacje(); std::cout<<std::endl; } } //metoda generujaca przesylki //ilosc przesylke zalezy od liczby klientow void Baza::generuj_przesylki(void) { unsigned ilosc_klientow = b_baza_klientow.size(); for(unsigned i=0; i<ilosc_klientow; i++) { unsigned ilosc_pacz = 3+ rand()%4; for(unsigned j=0; j<ilosc_pacz; j++) { Przesylka nowa_przesylka(b_baza_klientow[i]); b_przesylki_w_bazie.push_back(nowa_przesylka); } } } //metoda sluzaca do ladowania samochodu void Baza::zaladuj_samochod(void) { //sprawdzanie czy w bazie znajduja sie samochody if(!p_kolejka_samochodow_oczekujacych.empty()) { //jesli pierwszy samochod w kolejce nie jest pusty usuwany jest on z kolejki //i przekazywany do wektora samochodow znajdujacych sie w drodze if(!p_kolejka_samochodow_oczekujacych.front()->sprawdz_czy_pusty()) { Samochod * tmp_samochod = p_kolejka_samochodow_oczekujacych.front(); p_vektor_samochodow_podrozujacych.push_back(tmp_samochod); p_kolejka_samochodow_oczekujacych.pop(); } //jesli w bazie sa samochody i przesylki samochod zostanie zaladowany przesylkami if(!p_kolejka_samochodow_oczekujacych.empty() && !b_przesylki_w_bazie.empty()) { std::string wybrana_lokalizacja = b_przesylki_w_bazie.front().zwroc_odbiorce().zwroc_lokalizacje(); unsigned wykonaj = b_przesylki_w_bazie.size(); p_kolejka_samochodow_oczekujacych.front()->zmien_docelowe_miejsce(wybrana_lokalizacja); unsigned liczba_wykonan =0; int index = 0; int liczba_przesylek = 0; while(liczba_wykonan != wykonaj) { if(wybrana_lokalizacja == b_przesylki_w_bazie[index].zwroc_odbiorce().zwroc_lokalizacje()) { Przesylka tmp = b_przesylki_w_bazie[index]; if(p_kolejka_samochodow_oczekujacych.front()->dodaj_towar(tmp)) { ++liczba_przesylek; if(index == wykonaj-1) { b_przesylki_w_bazie.pop_back(); } else { b_przesylki_w_bazie.erase(b_przesylki_w_bazie.begin()+index); } --index; } else break; } ++liczba_wykonan; ++index; } std::cout<<"***------------------------------------------------------------------------***\n"; std::cout<<p_kolejka_samochodow_oczekujacych.front()->wyswietl_informacje(); std::cout<<", zaladowano przesylki: "<<liczba_przesylek; std::cout<<", dla oddzialu: "<<p_kolejka_samochodow_oczekujacych.front()->zwroc_docelowe_miejsce()<<std::endl; std::cout<<"***------------------------------------------------------------------------***\n"; if(plik_wynikowy.is_open()) { plik_wynikowy<<"***------------------------------------------------------------------------***\n"; plik_wynikowy<<p_kolejka_samochodow_oczekujacych.front()->wyswietl_informacje(); plik_wynikowy<<", zaladowano przesylki: "<<liczba_przesylek; plik_wynikowy<<", dla oddzialu: "<<p_kolejka_samochodow_oczekujacych.front()->zwroc_docelowe_miejsce()<<"\n"; plik_wynikowy<<"***------------------------------------------------------------------------***\n"; } } } } //metoda sluzaca do usuwania samochodu z wektora samochodow w dordze //i dodawaniu do kolejki w bazie void Baza::wroc_do_bazy(int numer) { p_vektor_samochodow_podrozujacych[numer]->zmien_docelowe_miejsce("brak danych"); Placowka::wroc_do_placowki(numer); } //metoda do wyladowania samochodu //znajdowana jest odpowiednia przestrzen do ktorej przekazywane sa przesylki //potem z tej przestrzeni przesylki trafiaja do odpowiedniego oddzialu void Baza::wyladuj_samochod(int numer) { Przesylka tmp; std::string cel_podrozy = p_vektor_samochodow_podrozujacych[numer]->zwroc_docelowe_miejsce(); int index = znajdz_przestrzen(cel_podrozy); while(!p_vektor_samochodow_podrozujacych[numer]->sprawdz_czy_pusty()) { tmp = p_vektor_samochodow_podrozujacych[numer]->wypakuj_przesylke(); vector_przestrzeni[index].tmp_przestrzen.push_back(tmp); } } //metoda rozwozaca przesylki void Baza::rozwoz_przesylki_z_bazy(void) { unsigned ilosc = p_vektor_samochodow_podrozujacych.size(); unsigned wykonano= 0; int index =0; int czas = rand()%1000 + 2000; Sleep(czas); zaladuj_samochod(); while(wykonano != ilosc) { int czas = rand()%1000 + 2000; Sleep(czas); bool postep = p_vektor_samochodow_podrozujacych[index]->zwieksz_postep(); //jesli samochod wykonal widoczny postep i nie jest pusty to przewozone przez niego //przesylki wyladowywane sa do odpowiedniej przestrzeni tymczasowej if(postep && !p_vektor_samochodow_podrozujacych[index]->sprawdz_czy_pusty()) { std::cout<<"***------------------------------------------------------------------------***\n"; std::cout<<p_vektor_samochodow_podrozujacych[index]->wyswietl_informacje(); std::cout<<", wyladowano przesylki: "<<p_vektor_samochodow_podrozujacych[index]->zwroc_ilosc_przesylek(); std::cout<<", w oddziale: "<<p_vektor_samochodow_podrozujacych[index]->zwroc_docelowe_miejsce()<<std::endl; std::cout<<"***------------------------------------------------------------------------***\n"; if(plik_wynikowy.is_open()) { plik_wynikowy<<"***------------------------------------------------------------------------***\n"; plik_wynikowy<<p_vektor_samochodow_podrozujacych[index]->wyswietl_informacje(); plik_wynikowy<<", wyladowano przesylki: "<<p_vektor_samochodow_podrozujacych[index]->zwroc_ilosc_przesylek(); plik_wynikowy<<", w oddziale: "<<p_vektor_samochodow_podrozujacych[index]->zwroc_docelowe_miejsce()<<"\n"; plik_wynikowy<<"***------------------------------------------------------------------------***\n"; } wyladuj_samochod(index); } //jesli samochod wykonal widoczny postep i jest pusty to wraca do bazy else if(postep && p_vektor_samochodow_podrozujacych[index]->sprawdz_czy_pusty()) { std::cout<<"***------------------------------------------------------------------------***\n"; std::cout<<p_vektor_samochodow_podrozujacych[index]->wyswietl_informacje(); std::cout<<", wrocil do Bazy"<<std::endl; std::cout<<"***------------------------------------------------------------------------***\n"; if(plik_wynikowy.is_open()) { plik_wynikowy<<"***------------------------------------------------------------------------***\n"; plik_wynikowy<<p_vektor_samochodow_podrozujacych[index]->wyswietl_informacje(); plik_wynikowy<<", wrocil do Bazy"<<"\n"; plik_wynikowy<<"***------------------------------------------------------------------------***\n"; } wroc_do_bazy(index); --index; }; ++index; ++wykonano; } } //metoda usuwajaca niekatualnych klientow //jesli oddzial zostal zlikwidowany metoda usuwa kientow ktorych obslugiwal oddzial void Baza::usun_nieaktualnych_klientow(void) { bool usuwac; int ilosc_wykonan = b_baza_klientow.size(); int wykonano = 0; int index = 0; while(wykonano != ilosc_wykonan) { usuwac = true; for(unsigned j=0; j<dozwolone_lokalizacje.size(); j++) { if(b_baza_klientow[index].zwroc_lokalizacje() == dozwolone_lokalizacje[j]) { usuwac = false; break; } } if(usuwac == true) { if(index == b_baza_klientow.size()-1) b_baza_klientow.pop_back(); else b_baza_klientow.erase(b_baza_klientow.begin()+index); --index; } ++wykonano; ++index; } }
true
5e5b5ea52df704c81e2108b8c34d0608f22594a8
C++
CCLPRO/ArduinoFoundations
/DigitalReadSerial1.ino
UTF-8
497
3.375
3
[]
no_license
/* DigitalReadSerial Reads a digital input on pin 2, prints the result to the serial monitor This example code is in the public domain. */ int buttonState = 0; void setup() { pinMode(2, INPUT); Serial.begin(9600); } void loop() { // read the input pin buttonState = digitalRead(2); // print out the state of the button Serial.print(" Button state is "); Serial.println(buttonState); delay(2000); // Delay a little bit to improve viewing }
true
432bd6fb7fbfcb80a9ee1504a04d301605686e55
C++
ademjemaa/C-
/C04/ex02/AssaultTerminator.cpp
UTF-8
1,747
2.765625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* AssaultTerminator.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: adjemaa <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/26 02:23:01 by adjemaa #+# #+# */ /* Updated: 2020/08/26 03:19:02 by adjemaa ### ########.fr */ /* */ /* ************************************************************************** */ #include "AssaultTerminator.hpp" AssaultTerminator::AssaultTerminator(void) { std::cout << "* teleports from space *\n"; return ; } AssaultTerminator::~AssaultTerminator(void) { std::cout << "I’ll be back...\n"; return ; } AssaultTerminator::AssaultTerminator(const AssaultTerminator &ass) { *this = ass; return ; } AssaultTerminator &AssaultTerminator::operator=(const AssaultTerminator &ass) { (void)ass; return (*this); } AssaultTerminator *AssaultTerminator::clone(void) const { return (new AssaultTerminator); } void AssaultTerminator::battleCry(void) const { std::cout << "This code is unclean. PURIFY IT!\n"; return ; } void AssaultTerminator::rangedAttack(void) const { std::cout << "* does nothing *\n"; return ; } void AssaultTerminator::meleeAttack(void) const { std::cout << "* attacks with chainfists *\n"; return ; }
true
a556a701a5469110a1657ac5de90e5dee498710a
C++
imshyam/algos
/CLRS/dll.cpp
UTF-8
687
3.71875
4
[ "MIT" ]
permissive
#include<iostream> using namespace std; struct node { int val; node* next; node* prev; }; node* head = NULL; void insert_node(int n) { node* new_node = new node(); new_node->val = n; new_node->next = NULL; new_node->prev = NULL; if(head == NULL){ head = new_node; } else{ node* current = head; while(current->next != NULL){ current = current->next; } current->next = new_node; new_node->prev = current; } } void print_dll() { node* current = head; while(current != NULL){ cout << current->val << " -> "; current = current->next; } cout << "NULL \n"; } int main() { insert_node(1); insert_node(2); insert_node(3); insert_node(4); print_dll(); }
true
5db914d704f2a2d10cabd9745f7a5bd427fbb28e
C++
Arniox/Game-Programming-Work
/COMP710-2019-S2/students/nikkolas.diehl/Unit 1 - Exercises/Simple Dice Game - Ex1/MainEx1.cpp
UTF-8
3,577
3.203125
3
[]
no_license
#include <iostream> #include <ctime> #include <random> #include <string> #include "HeaderEx1.h" #define nl std::endl; #define cls system("CLS"); #define wait cin.ignore(); #define clr cin.clear(); using namespace std; //Create players struct struct Player { int diceRollOne; int diceRollTwo; }; Player players[2]; bool playAgain; //Win counter float playerWon = 0; float aiWon = 0; float aiWinPercentage = 0; float playerWinPercentage = 0; int main() { srand(time(0)); playAgain = true; int roundCount = 0; while (playAgain) { //Play game int computerIsCheatingValue = (rand() % 100) + 1; //Generate dice rolls for players GeneratePlayers(); CheckCheating(computerIsCheatingValue); PlayRound(roundCount); cout << "Do you wish to play again? Type y to play again!" << nl; input(); roundCount++; } } void GeneratePlayers() { //Generate four dice rolls int diceRolls[] = { ((rand() % 6) + 1), ((rand() % 6) + 1), ((rand() % 6) + 1), ((rand() % 6) + 1) }; //Set dice rolls in alternating fashion players[0].diceRollOne = diceRolls[0]; players[1].diceRollOne = diceRolls[1]; players[0].diceRollTwo = diceRolls[2]; players[1].diceRollTwo = diceRolls[3]; } void CheckCheating(int computerIsCheatingValue) { if (computerIsCheatingValue > 0 && computerIsCheatingValue < 71) { //Computer is cheating players[1].diceRollTwo = players[1].diceRollOne; } else { players[0].diceRollTwo = players[0].diceRollOne; } } void PlayRound(int roundCount) { cout << "Hello and welcome to the dice rolling game. Press enter to continue at every stopping point!" << nl; wait; cls; cout << "Current win ratio: AI: " << aiWon << " PLAYER: " << playerWon << nl; if (!((aiWon + playerWon) == 0)) { aiWinPercentage = ((aiWon) / (aiWon + playerWon)) * 100; playerWinPercentage = ((playerWon) / (aiWon + playerWon)) * 100; } cout << "AI wins " << aiWinPercentage << "% of the time. The player wins " << playerWinPercentage << "% of the time" << nl; //Check which player starts if (roundCount % 2 == 0) { cout << "First player to start is: AI!" << nl; cout << "His first roll is: " << players[1].diceRollOne << nl; wait; cout << "Your first roll is: " << players[0].diceRollOne << nl; wait; cout << "His second roll is: " << players[1].diceRollTwo << nl; wait; cout << "Your second roll is: " << players[0].diceRollTwo << nl; wait; } else { cout << "First player to start is: YOU, the user!" << nl; cout << "Your first roll is: " << players[0].diceRollOne << nl; wait; cout << "His first roll is: " << players[1].diceRollOne << nl; wait; cout << "Your second roll is: " << players[0].diceRollTwo << nl; wait; cout << "His second roll is: " << players[1].diceRollTwo << nl; wait; } //Check who wins checkWhoWon(); } void checkWhoWon() { //AI wins if (players[1].diceRollOne == players[1].diceRollTwo) { cout << "Sorry not sorry, the AI has won!!!" << nl; aiWon++; }//Tie else if ((players[1].diceRollOne == players[1].diceRollTwo) && (players[0].diceRollOne == players[0].diceRollTwo)) { cout << "IT WAS A TIE. Congradulations!" << nl; aiWon++; playerWon++; }//Player wins else if (players[0].diceRollOne == players[0].diceRollTwo) { cout << "Congradulations!!!! You have won!!!" << nl; playerWon++; } else { cout << "NO ONE WON. HA SHAME BITCH!" << nl; } //Play again? wait; } void input() { char input; clr; cin >> input; //Check which answer the user gave if (input == 'Y' || input == 'y') { playAgain = true; } else { playAgain = false; } }
true
2b5cfc4febd17e2fbd5f4e0e0ce069bd203c254f
C++
mikeb01/nonblock
/src/util.h
UTF-8
1,756
2.78125
3
[]
no_license
#include <time.h> #include <pthread.h> #include <stdint.h> #include "cpucounters.h" using std::cout; using std::endl; class Affinity { private: cpu_set_t old_affinity_; cpu_set_t new_affinity_; public: Affinity(uint32_t); ~Affinity(); }; Affinity::Affinity(uint32_t core_id) { #ifdef _LINUX_VER pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &old_affinity_); CPU_ZERO(&new_affinity_); CPU_SET(core_id, &new_affinity_); pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &new_affinity_); #endif } Affinity::~Affinity() { #ifdef _LINUX_VER pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &old_affinity_); #endif } timespec diff(timespec start, timespec end) { timespec temp; if ((end.tv_nsec-start.tv_nsec) < 0) { temp.tv_sec = end.tv_sec - start.tv_sec - 1; temp.tv_nsec = 1000000000 + end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec - start.tv_sec; temp.tv_nsec = end.tv_nsec - start.tv_nsec; } return temp; } static void measure(CoreCounterState& before_sstate, CoreCounterState& after_sstate, uint32_t core_id) { cout << "CoreId: " << core_id << endl; cout << "L2 Cache hit ratio : " << getL2CacheHitRatio(before_sstate, after_sstate) * 100. << " %" << endl; cout << "L3 Cache hit ratio : " << getL3CacheHitRatio(before_sstate, after_sstate) * 100. << " %" << endl; cout << "Instructions retired: " << getInstructionsRetired(before_sstate, after_sstate) / 1000000 << "mln" << endl; cout << "CPU cycles: " << getCycles(before_sstate, after_sstate) / 1000000 << "mln" << endl; cout << "Instructions per cycle: " << getIPC(before_sstate, after_sstate) << endl << endl; }
true
8637cc317ffc59b410e3b1d85d8c52256b3d06ac
C++
Vuean/AlgorithmNote
/Chapter10/Chapter10/Sec5Exe1MinimumSpanningTree_Prim/main.cpp
GB18030
1,299
2.96875
3
[]
no_license
#include <cstdio> #include <algorithm> using namespace std; const int MAXV = 1000; // 󶥵 const int INF = 100000000000; // INFΪһܴ int n, m, G[MAXV][MAXV]; // nΪMAXVΪ󶥵 int d[MAXV]; // 뼯S̾ bool vis[MAXV] = { false }; // // Ĭ0Ϊʼ㣬СıȨ֮ int prim() { fill(d, d + MAXV, INF); d[0] = 0; int ans = 0; for (int i = 0; i < n; i++) { int u = -1, MIN = INF; // uʹd[u]СMINŸСd[u] for (int j = 0; j < n; j++) { if (vis[j] == false && d[j] < MIN) { u = j; MIN = d[j]; } } // ҲСINFd[u]ʣµĶͼSͨ if (u == -1) return -1; vis[u] = true; ans += d[u]; for (int v = 0; v < n; v++) { // vδ&&uܵv&&uΪнʹv뼯S if (vis[v] == false && G[u][v] != INF && G[u][v] < d[v]) { d[v] = G[u][v]; } } } return ans; } int main() { int u, v, w; scanf_s("%d%d", &n, &m); fill(G[0], G[0] + MAXV * MAXV, INF); // ʼͼG for (int i = 0; i < m; i++) { scanf_s("%d%d%d", &u, &v, &w); G[u][v] = G[v][u] = w; } int ans = prim(); printf_s("%d\n", ans); return 0; }
true
8ae109f354d57040eac8c72d2590d0aa4dd22ad0
C++
D000M/Games
/Dijkstra/Dijkstra.h
UTF-8
1,540
3.1875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Dijkstra.h * Author: default * * Created on February 20, 2019, 1:22 PM */ #ifndef DIJKSTRA_H #define DIJKSTRA_H #include <string> #include <vector> #include <iostream> #include <memory> class Dijkstra { /** * Class to represent a single vertex. */ class Vertex { public: Vertex(bool l_visited, std::string l_value) : m_bIsVisited{l_visited}, m_sValue{l_value} { std::cout << "Vertex CREATED!\n"; } //end of Vertex constructor. ~Vertex() { std::cout << "Vertex with value: [" << m_sValue << "] DESTROYED!\n"; } private: bool m_bIsVisited; std::string m_sValue; void setVisited(bool l_visited) { m_bIsVisited = l_visited; } bool getIsVisited() const { return m_bIsVisited; } }; //end of nested class Vertex public: Dijkstra(); ~Dijkstra(); //Methods void createVertex(const std::string& l_val); void createMatrix(int row, int col, int weight); void executeLoads(); private: std::vector<std::unique_ptr<Vertex>> m_Vertices; std::vector<std::vector<int> > m_matrix; void loadVertices(); void loadMatrix(); void printMatrix(); void setMatrixSize(); }; #endif /* DIJKSTRA_H */
true
b4fcdc40216a2f547b0528cf318729afb1bccf43
C++
andy489/Object_Oriented_Programming_with_CPP
/HW.1.SE.17-18/Task2/BrowserHistory.cpp
UTF-8
5,665
3.609375
4
[]
no_license
#include "BrowserHistory.h" #include "String.h" #include <iomanip> String months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; Month BrowserHistory::strToMonth(const String& s) { /* Convert a string to Month enum, assuming the string is validated to be a month */ if (s == "January") return January; else if (s == "February") return February; else if (s == "March") return March; else if (s == "April") return April; else if (s == "May") return May; else if (s == "June") return June; else if (s == "July") return July; else if (s == "August") return August; else if (s == "September") return September; else if (s == "October") return October; else if (s == "November") return November; else if (s == "December") return December; return January; /* In case something goes wrong return January */ } bool BrowserHistory::IsStrMonth(const String& str) const { /* Check if a string is a month (is contained in Months[]) */ for (size_t i = 0; i < 12; i++) if (str == months[i]) return true; return false; } void BrowserHistory::swap(HistoryEntry& a, HistoryEntry& b) { /* Swap tow objects in the list (used for sorting) */ HistoryEntry temp = a; a = b; b = temp; } int BrowserHistory::partition(int low, int high) { /* Helper function for sorting */ int i = (low - 1); for (int j = low; j <= high - 1; j++) { if (list[j].month <= list[high].month) { i++; swap(list[i], list[j]); } } swap(list[i + 1], list[high]); return (i + 1); } void BrowserHistory::sort(int low, int high) { /* Quick sort modified to work properly for the BrowserHistory class */ if (high == -1) high = currIndx; if (low == -1) low = 0; if (low < high) { int pi = partition(low, high); sort(low, pi - 1); sort(pi + 1, high); } } BrowserHistory::BrowserHistory(int N) : size(N), currIndx(-1) { /* Constructor */ list = new HistoryEntry[N]; } BrowserHistory::~BrowserHistory() { /* Destructor */ delete[] list; } BrowserHistory::BrowserHistory(const BrowserHistory& history) : size(history.size), currIndx(0) { /* Copy constructor */ list = new HistoryEntry[size]; for (int i = 0; i < history.currIndx + 1; i++) { /* Iterate over the History object and copy all its elements */ list[i] = history.list[i]; } currIndx = history.currIndx; } BrowserHistory& BrowserHistory::operator=(const BrowserHistory& history) { /* operator= */ if (this != &history) { this->size = history.size; currIndx = -1; delete[] list; list = new HistoryEntry[size]; /* Iterate over the History object and copy all its elements */ for (int i = 0; i < history.currIndx + 1; i++) list[i] = history.list[i]; currIndx = history.currIndx; } return *this; } void BrowserHistory::add(const HistoryEntry& entry) { /* Add a history entry to the list if it has space */ if (currIndx >= size - 1) { std::cout << "This history is full. Cannot add more elements to it.\n"; return; } currIndx++; list[currIndx] = entry; } void BrowserHistory::printAll() { /* Print all the entries after sorting them */ if (currIndx == -1) { /* If the list is empty, do nothing */ std::cout << "There are no entries in the history"; return; } sort(); /* Iterate over the History object and copy all it's elements */ for (int i = 0; i < currIndx + 1; i++) std::cout << std::setw(12) << std::left << months[list[i].month - 1] << list[i].url << "\n"; std::cout << "\n"; } void BrowserHistory::inputFromConsole() { /* Prompt the user to input the next entry to a list and then add it via add() */ String month; String url; while (!IsStrMonth(month)) { std::cout << "Input the month for the History Entry (e.g December): "; std::cin >> month; } std::cout << "Input the url for the History Entry : "; std::cin >> url; add(HistoryEntry{ strToMonth(month), url }); } size_t BrowserHistory::numOfWebsVisitedInMonth(Month monthToCheckFor) { if (currIndx == -1) return 0; size_t visits = 0; for (int i = 0; i < currIndx; i++) if (list[i].month == monthToCheckFor) visits++; return visits; } String BrowserHistory::monthNumToStr(int num) { return months[num]; } Month BrowserHistory::monthWithMostVisits() { if (currIndx == -1) { std::cout << "There are no entries in the history"; return January; } /* Each index of the array is the visits during a month (0-11) */ int visits[] = { 0,0,0,0,0,0,0,0,0,0,0,0 }; for (int i = 0; i < currIndx+1; i++) visits[list[i].month - 1]++; /* Find the index from the visits[] with highest count */ int monthWithMostVisits = 0; for (int i = 0; i < 12; i++) if (visits[i] > monthWithMostVisits) monthWithMostVisits = i; /* Convert the index (from int to enum) and return it */ return (Month)(monthWithMostVisits+1); } void BrowserHistory::removeMostRecent() { if (currIndx == -1) { std::cout << "There are no entries in the history"; return; } /* Clear the string (aka url) and decrease the currentIndex by 1, leaving the last object unaccessible */ list[currIndx].url.clear(); currIndx--; } BrowserHistory BrowserHistory::concat(const BrowserHistory& anotherHistory) { BrowserHistory newHistory(size + anotherHistory.size); int i = 0; if (currIndx != -1) { /* Copy the elements of the current history into the new one */ for (i = 0; i < currIndx + 1; i++) newHistory.list[i] = list[i]; } int j = 0; /* Copy the elements of anotherHistory into the new one */ if (anotherHistory.currIndx != -1) for (j = 0; j < anotherHistory.currIndx + 1; j++) newHistory.list[i + j] = anotherHistory.list[j]; newHistory.currIndx = i + j - 1; return newHistory; }
true
35ad4ca48aead9576c37990eefc8268b09a63660
C++
eunjineunjin/Programming-Study
/C/DataStructure_RoundQueue.cpp
UTF-8
1,162
3.875
4
[]
no_license
/* Round Queue with C language only for integer, based on array */ #include <stdio.h> #define MAXSIZE 10 typedef struct Queue{ int arr[MAXSIZE]; int front; //front부터 데이터 존재 int rear; //rear-1까지 데이터 존재 }Queue; void Init(Queue* q) { q->front = 0; q->rear = 0; } int isFull(Queue* q) { return (q->rear+1)%MAXSIZE == q->front; //Full이면 1 return } void Push(Queue* q, int item) { if(isFull(q)) { printf("큐가 가득 찼습니다."); } else { q->arr[q->rear] = item; q->rear = (q->rear+1)%MAXSIZE; } } int isEmpty(Queue* q) { return (q->front)==(q->rear); //Empty면 1 return } int Pop(Queue* q) { if(isEmpty(q)) { printf("큐가 비었습니다."); } else { int item = q->arr[q->front]; q->front = (q->front+1)%MAXSIZE; return item; } } void Show(Queue* q) { int i = q->front; while(1) { if(i == q->rear) { break; } else { printf("%d ", q->arr[i]); i = (i+1)%MAXSIZE; } } } int main() { Queue Q; Init(&Q); Push(&Q, 1); Push(&Q, 2); Push(&Q, 3); Pop(&Q); Show(&Q); }
true
b1f9e742e41dcdf17066af8c8ba19b0c8bde242d
C++
stopiccot/googlecode
/different/fdom2/code/RenderTarget.cpp
UTF-8
7,252
2.765625
3
[]
no_license
#include "RenderTarget.h" #include "log.h" RenderTarget RenderTarget::screen; const RenderTarget RenderTarget::null; //========================================================================== // Default constructor to null everything //========================================================================== RenderTarget::RenderTarget() : width(0), height(0), count(0), cubeMap(false), multisample(false), texture(Texture::null), stencil(Texture::null), renderTargetView(NULL), depthStencilView(NULL) { //... } RenderTarget::RenderTarget(int width, int height, int count) : width(width), height(height), count(count), cubeMap(false), multisample(false), texture(Texture::null), stencil(Texture::null), renderTargetView(NULL), depthStencilView(NULL) { //... } //========================================================================== // Copy constructor, desctructor and operator = for updating COM refernces //========================================================================== RenderTarget::RenderTarget(const RenderTarget& renderTarget) : renderTargetView(NULL), depthStencilView(NULL) { copy(renderTarget); } void RenderTarget::operator = (const RenderTarget& renderTarget) { copy(renderTarget); } RenderTarget::~RenderTarget() { SAFE_RELEASE(renderTargetView); SAFE_RELEASE(depthStencilView); } void RenderTarget::copy(const RenderTarget& renderTarget) { this->texture = renderTarget.texture; this->stencil = renderTarget.stencil; this->width = renderTarget.width; this->height = renderTarget.height; this->count = renderTarget.count; this->cubeMap = renderTarget.cubeMap; this->multisample = renderTarget.multisample; if (renderTarget.renderTargetView) this->renderTargetView = renderTarget.renderTargetView, this->renderTargetView->AddRef(); if (renderTarget.depthStencilView) this->depthStencilView = renderTarget.depthStencilView, this->depthStencilView->AddRef(); } //========================================================================== // Creates new render target //========================================================================== RenderTarget RenderTarget::Create(int width, int height) { return RenderTarget::Create(width, height, false); } RenderTarget RenderTarget::Create(int width, int height, bool stencil) { RenderTarget result(width, height, 1); result.texture = Texture::Create(width, height, 1, 1, true, false, false, D3D10.getSampleDesc()); if (result.texture == Texture::null) { MessageBox(D3D10.getHWND(), L"RenderTarget::Create\nFailed to create texture", L"D3D10", MB_OK); } HRESULT hr = D3D10.getDevice()->CreateRenderTargetView(result.texture.getTexture(), NULL, &(result.renderTargetView)); if (FAILED(hr)) { MessageBox(D3D10.getHWND(), L"RenderTarget::Create", L"D3D10", MB_OK); } if (stencil) result.enableStencil(); return result; } //========================================================================== // Creates cubemap render target //========================================================================== RenderTarget RenderTarget::CreateCube(int width, int height) { RenderTarget result(width, height, 6); result.cubeMap = true; DXGI_SAMPLE_DESC noMultisample = {1, 0}; int mipLevels = 6; result.texture = Texture::Create(width, height, mipLevels, 6, true, false, true, noMultisample); if (result.texture == Texture::null) { MessageBox(D3D10.getHWND(), L"RenderTarget::CreateCube - Texture::Create failed", L"D3D10", MB_OK | MB_ICONERROR); return RenderTarget::null; } D3D10_RENDER_TARGET_VIEW_DESC desc; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2DARRAY; desc.Texture2DArray.FirstArraySlice = 0; desc.Texture2DArray.ArraySize = result.count; desc.Texture2DArray.MipSlice = 0; HRESULT hr = D3D10.getDevice()->CreateRenderTargetView(result.texture.getTexture(), &desc, &(result.renderTargetView)); if (FAILED(hr)) { MessageBox(D3D10.getHWND(), L"RenderTarget::CreateCube", L"D3D10", MB_OK | MB_ICONERROR); return RenderTarget::null; } return result; } //========================================================================== // Special constructor for screen render target //========================================================================== HRESULT RenderTarget::initScreenRenderTarget() { this->width = D3D10.getScreenX(); this->height = D3D10.getScreenY(); this->count = 1; this->cubeMap = false; ID3D10Texture2D* tex = NULL; HRESULT hr = D3D10.getSwapChain()->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&tex); if(FAILED(hr)) return hr; hr = D3D10.getDevice()->CreateRenderTargetView(tex, NULL, &(this->renderTargetView)); tex->Release(); return hr; } //========================================================================== // Adds stencil buffer to render target //========================================================================== HRESULT RenderTarget::enableStencil() { DXGI_SAMPLE_DESC noMultisample = {1, 0}; stencil = Texture::Create(width, height, 1, this->count, false, true, this->cubeMap, this->cubeMap ? noMultisample : D3D10.getSampleDesc()); if (stencil == Texture::null) { MessageBox(D3D10.getHWND(),L"CreateDepthStencilView\nstencil == Texture::null", L"d3d10", MB_OK); return E_FAIL; } HRESULT hr; D3D10_DEPTH_STENCIL_VIEW_DESC descDSV; descDSV.Format = DXGI_FORMAT_D32_FLOAT; if (!this->cubeMap) { descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2DMS; descDSV.Texture2D.MipSlice = 0; } else { descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2DARRAY; descDSV.Texture2DArray.MipSlice = 0; descDSV.Texture2DArray.FirstArraySlice = 0; descDSV.Texture2DArray.ArraySize = 6; } if (FAILED(hr = D3D10.getDevice()->CreateDepthStencilView(stencil.getTexture(), &descDSV, &depthStencilView))) { MessageBox(D3D10.getHWND(),L"CreateDepthStencilView", L"d3d10", MB_OK); return hr; } return S_OK; } //========================================================================== // Clear render target with specified color //========================================================================== RenderTarget& RenderTarget::clear(float R, float G, float B) { float ClearColor[4] = { R, G, B, 1.0f }; D3D10.getDevice()->ClearRenderTargetView(renderTargetView, ClearColor); if (depthStencilView) D3D10.getDevice()->ClearDepthStencilView(depthStencilView, D3D10_CLEAR_DEPTH, 1.0f, 0); return *this; } //========================================================================== // Properties //========================================================================== Texture RenderTarget::getTexture() const { return this->texture; } Texture RenderTarget::getStencilTexture() const { return this->stencil; } ID3D10RenderTargetView* RenderTarget::getRenderTargetView() const { return this->renderTargetView; } ID3D10DepthStencilView* RenderTarget::getDepthStencilView() const { return this->depthStencilView; }
true
4a90390eba4b13c6cf040fa2f1177f216da01906
C++
bbsekiya/ichiro
/meta/fff.cpp
UTF-8
547
3.578125
4
[]
no_license
#include <iostream> void fun(int& n) { std::cout << "--- fun(int& n) ---\n"; } void fun(int&& n) { std::cout << "--- fun(int&& n) ---\n"; } void fun(const int& n) { std::cout << "--- fun(const int& n) ---\n"; } template <typename T> void f(T&& t) { fun(std::forward<T>(t)); } int main() { int n = 100; f(n); const int cn = n; const int& rn = n; f(cn); f(rn); f(299); std::cout << "----------------------------\n"; fun(n); fun(300); fun(std::move(n)); return 0; }
true
fe97b0596fa6acc2694b4e31a8210b316dfc6826
C++
Yaseungho/myCodes
/Baekjoon_Solving/Baekjoon_2178.cpp
UTF-8
1,049
2.8125
3
[]
no_license
#include <iostream> #include <vector> #include <queue> #include <algorithm> #include <string> using namespace std; int n, m; int dx[4] = { 1,0,-1,0 }; int dy[4] = { 0,1,0,-1 }; char graph[102][102]; bool visited[102][102] = { false }; int result = -1; void BFS() { queue<pair<int,int>> q; q.push({ 1, 1 }); visited[1][1] = true; int depth = 1; while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; i++) { pair<int, int> now = q.front(); q.pop(); for (int j = 0; j < 4; j++) { int nx = now.second + dx[j]; int ny = now.first + dy[j]; if (!visited[ny][nx] && graph[ny][nx] != '0') { if (nx == m && ny == n) result = depth + 1; visited[ny][nx] = true; q.push({ ny,nx }); } } } depth++; } } int main() { for (int i = 0; i < 102; i++) { for (int j = 0; j < 102; j++) { graph[i][j] = '0'; } } cin >> n >> m; for (int i = 1; i <= n; i++) { string str; cin >> str; for (int j = 1; j <= m; j++) { graph[i][j] = str[j - 1]; } } BFS(); cout << result << "\n"; }
true
05a496fa57ade056df23627f319a9d2886070955
C++
verra11/Competitive_Programming
/LeetCode/April_Challenge/LeetCode-Day11.cpp
UTF-8
801
3.296875
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: pair <int,int> dfs(TreeNode* root) { if(root==NULL) return {0, 0}; pair <int,int> l = dfs(root->left); pair <int,int> r = dfs(root->right); int diameter = max({l.first, r.first, l.second+r.second}); return {diameter, max(l.second, r.second)+1}; } int diameterOfBinaryTree(TreeNode* root) { return dfs(root).first; } };
true
ee0c3918a8e85504730a7cb1c9c3134687deade5
C++
saif86/Printing-an-unsigned-integer-in-bits
/Source.cpp
UTF-8
870
3.765625
4
[]
no_license
// Fig. 18.5: fig18_05.cpp // Printing an unsigned integer in bits. #include <iostream> using std::cout; using std::cin; using std::endl; #include <iomanip> using std::setw; void displayBits(unsigned); // prototype void main(){ unsigned inputValue; cout << "Enter an unsigned integer: "; cin >> inputValue; displayBits(inputValue); system("pause"); } // end main // display bits of an unsigned integer value void displayBits(unsigned value){ const int SHIFT = 8 * sizeof(unsigned) - 1; const unsigned MASK = 1 << SHIFT; cout << setw(10) << value << " = "; for (unsigned i = 1; i <= SHIFT + 1; i++) { cout << (value & MASK ? '1' : '0'); value <<= 1; // shift value left by 1 if (i % 8 == 0) // output a space after 8 bits cout << ' '; } // end for cout << endl; } // end function displayBits
true
654ea2eed4042ecec541348158a9de60fb27faa9
C++
HolyBlackCat/modular-forms
/src/main/file_dialogs.h
UTF-8
1,392
2.546875
3
[ "Zlib" ]
permissive
#pragma once #include <string> #include <optional> #include <vector> #include <utility> #include "options.h" namespace FileDialogs { std::optional<std::string> Open(std::string title, const std::vector<std::pair<std::string, std::string>> &filters, std::string default_path = ""); std::optional<std::string> Save(std::string title, const std::vector<std::pair<std::string, std::string>> &filters, std::string default_path = ""); inline std::optional<std::string> OpenTemplate() { return FileDialogs::Open("Открытие шаблона", {{"Файлы шаблонов", Options::template_extension}, {"Все файлы", ".*"}}, Options::template_dir); } inline std::optional<std::string> SaveTemplate() { return FileDialogs::Save("Сохранение шаблона", {{"Файлы шаблонов", Options::template_extension}, {"Все файлы", ".*"}}, Options::template_dir); } inline std::optional<std::string> OpenReport() { return FileDialogs::Open("Открытие отчета", {{"Файлы отчетов", Options::report_extension}, {"Все файлы", ".*"}}); } inline std::optional<std::string> SaveReport() { return FileDialogs::Save("Сохранение отчета", {{"Файлы отчетов", Options::report_extension}, {"Все файлы", ".*"}}); } }
true
6dcb082cec722315882eb8c47d5fc0d64a3f98ee
C++
natiiix/SeePlusPlus
/src/instrCALL.cpp
UTF-8
1,431
2.65625
3
[ "MIT" ]
permissive
#include "h/Processor.hpp" bool Processor::instrCALL(const std::string& strDest) { unsigned programCounterOld = m_programCounter; if (instrJMP(strDest)) { m_stack.push_back(programCounterOld); return true; } else return false; } bool Processor::instrRET() { if (m_stack.size() > 0) { m_programCounter = m_stack.back(); m_stack.pop_back(); return true; } else { errMessage("Cannot perform RET! Stack is empty!"); return false; } } bool Processor::instrCZ(const std::string& strDest) { if (m_flagZero) return instrCALL(strDest); else return true; } bool Processor::instrCNZ(const std::string& strDest) { if (!m_flagZero) return instrCALL(strDest); else return true; } bool Processor::instrCG(const std::string& strDest) { if (m_flagCarry) return instrCALL(strDest); else return true; } bool Processor::instrCGE(const std::string& strDest) { if (m_flagCarry || m_flagZero) return instrCALL(strDest); else return true; } bool Processor::instrCL(const std::string& strDest) { if (m_flagBorrow) return instrCALL(strDest); else return true; } bool Processor::instrCLE(const std::string& strDest) { if (m_flagBorrow || m_flagZero) return instrCALL(strDest); else return true; }
true
2471225d7e8a095a022224808682855167f0730f
C++
dlee67/ArduinoWorkShop
/ProjectOneArduinoWorkshop/ProjectOneArduinoWorkshop.ino
UTF-8
1,144
3.28125
3
[]
no_license
//About the PWM /* lol * Am not entirely sure how this thing works.... */ int d = 5; void setup(){ pinMode(3, OUTPUT); } void loop(){ for(int a = 0; a < 256; a++){ analogWrite(3, a); delay(d); } for(int a = 255; a >= 0; a--){ analogWrite(3, a); delay(d); } delay(200); } /* void setup(){ pinMode(2, OUTPUT); } void loop(){ digitalWrite(2, HIGH); delay(500); digitalWrite(2, LOW); } */ /* void setup() { pinMode(2, OUTPUT); } void loop() { //Testing if delay works like a sleep(). delay(1000); for(int c = 5; c > 0; c--){ digitalWrite(2, HIGH); delay(c*100); digitalWrite(2, LOW); delay(c*100); } } */ /* Sequentially, lights up three LED light bulbds in a "wavy way". This project was inspired by project 1 in Was done during the 07/15/17. */ /* void setup() { pinMode(2, OUTPUT); pinMode(4, OUTPUT); pinMode(6, OUTPUT); } void loop() { digitalWrite(2, HIGH); delay(500); digitalWrite(2, LOW); digitalWrite(4, HIGH); delay(500); digitalWrite(4, LOW); digitalWrite(6, HIGH); delay(500); digitalWrite(6, LOW); } */
true
828de76557d224a48cb7fe3b4b682f24d0e04955
C++
sub-res/cool-compiler
/src/compiler/StringContainer.cpp
UTF-8
349
2.625
3
[]
no_license
/* * File: StringContainer.cpp * Author: len * * Created on December 25, 2015, 9:11 PM */ #include "StringContainer.h" namespace Cool { std::unordered_set<std::string> StringContainer::strings; const std::string& StringContainer::get(std::string && forText) { return *strings.insert(std::move(forText)).first; } }
true
b29e9e2abff5d490c099cc33c907bb673f036669
C++
liyinxin/Data-Structures-Algorithms
/5/listMap.cpp
UTF-8
5,357
3.828125
4
[]
no_license
#include "listMap.h" template<typename T> void listMap<T>::insert(int i,int index,const T &theElement){ bool rightFullFlag = 0,leftFullFlag = 0; int listSize = last[i] - front[i];//首先得到数组的大小 //判读索引是不是有效的 if(index < 0 || index > listSize)//你要插入的元素的索引不能小于0也不能超过当前数组的大小 throw illeagleParameter("the index must be right"); //判断完索引以后,我们需要去插入数据了 /* 1.第一步首先判断本线性列表的空间有没有满 */ if(last[i] != front[i+1]){//如果当前这个数组还有空间 //copy_back是将(first,last)元素拷贝到第三个迭代器指向的位置以及前边的位置,详情请看源码 //所以这样可以很好的避免-1这个下标的处理(-1,last[i]]的元素拷贝 //注意,这个copy_backward算法中的last表示的是尾后指针。所以需要last[i]+1; std::copy_backward(element+front[i]+index,element+last[i]+1,element+(last[i]+2));//从last[i]+1这个位置开始倒叙拷贝 //拷贝完以后,我们需要插入数据,以及更改尾部指针的索引值 element[front[i]+index+1] = theElement; last[i]++; }else{//如果内存空间已经被利用完了的话,那么先搜索右边的空间有没有有剩余的 int j = i+1;//现在j为i的右边的第一个数组 while(last[j] == front[j+1]){//如果右边的数组空间也被利用完了 //那么就继续向右边开始搜索,但是搜索之前要注意一点,先判断有没有到最右边的终点 if(last[j] == length-1)//如果到了终点,好的,退出,然后往左查找 { rightFullFlag = 1; break;//退出,开始从i的左端搜索 } j++;//如果没有达到终点的话,我们继续向右查找 } if(rightFullFlag == 0){//如果右边有空间, std::copy_backward(element+front[i]+index,element+last[j]+1,element+last[j]+2); //接下来需要把转移的数组进行下标的一个变换,因为位置发生变换了 //首先i的尾元素的指针的索引值要加1 element[front[i]+index+1] = theElement; last[i]++; //剩下的他们的首前和尾部指针的索引值都加1就好了,也就是顺移 for(int k = i+1;k <= j;k++){ front[k]++;last[k]++; } }else{//如果右边满了的话,那好,去左边找新的内存空间 j = i-1;//j为i左边第一个数组 while(last[j] == front[j+1]){ if(last[j] == -1){ leftFullFlag=1;//左边也满了,这个时候报错就好了 std::cout<<"\nthere is no space to insert"<<std::endl; } j--;//往左边找数组 } if(leftFullFlag==0){ std::copy(element+front[j]+1,element+front[i]+index+2,element+front[j+1]); //改变一些front和last的值 //首先改变front[i]的值 front[i]--; //接着顺移一些front和last的值 for(int k = i-1;k != j;--k){ last[k]--;//往左移动一下 front[k]--;//往左移动一下 } } } } } template<typename T> T listMap<T>::get(int i,int index)const{ return element[front[i]+index+1];//因为front[i]表示的第一个元素的 //前一个位置,所以查找元素的时候需要加1。 } template<typename T> int listMap<T>::capacity()const{ return length; } template<typename T> int listMap<T>::getFront(int i)const{ return front[i]; } template<typename T> int listMap<T>::getLast(int i)const{ return last[i]; } template<typename T> void listMap<T>::printAllMemeber()const{ for(int i = 0; i != length; ++i) std::cout<<element[i]<<","; } int main() { listMap<int> a(5,5); /* std::cout<<"the inist is\n"; for(int i = 1; i <= 5;++i) std::cout<<"font["<<i<<"] is "<<a.getFront(i)<<" and last[" <<i<<"]"<<" is "<<a.getLast(i)<<std::endl; std::cout<<std::endl; */ for(int i = 0;i != 5;++i){ a.insert(1,i,i*10+1); a.insert(2,i,i*10+2); a.insert(3,i,i*10+3); a.insert(4,i,i*10+4); } for(int i = 1; i <= 5;++i) std::cout<<"font["<<i<<"] is "<<a.getFront(i)<<" and last[" <<i<<"]"<<" is "<<a.getLast(i)<<std::endl; for(int i = 0;i != 5;++i) std::cout<<"get(1,"<<i<<") is "<<a.get(1,i)<<std::endl; std::cout<<std::endl; for(int i = 0;i != 5;++i){ std::cout<<"get(2,"<<i<<") is "<<a.get(2,i)<<std::endl; } std::cout<<"\nafter the operator a.insert(1,0,100) the a is\n"; a.insert(3,0,100); for(int i = 1; i <= 5;++i) std::cout<<"font["<<i<<"] is "<<a.getFront(i)<<" and last[" <<i<<"]"<<" is "<<a.getLast(i)<<std::endl; a.printAllMemeber(); for(int i = 0;i != 5;++i) std::cout<<"get(1,"<<i<<") is "<<a.get(1,i)<<std::endl; std::cout<<std::endl; for(int i = 0;i != 5;++i){ std::cout<<"get(2,"<<i<<") is "<<a.get(2,i)<<std::endl; } return 0; }
true
43b22dbc060b72258cb6a09d81b26223794cdee6
C++
MultivacX/leetcode2020
/algorithms/medium/1079. Letter Tile Possibilities.h
UTF-8
1,110
3.390625
3
[ "MIT" ]
permissive
// 1079. Letter Tile Possibilities // Runtime: 12 ms, faster than 62.07% of C++ online submissions for Letter Tile Possibilities. // Memory Usage: 6 MB, less than 100.00% of C++ online submissions for Letter Tile Possibilities. class Solution { public: int numTilePossibilities(string tiles) { sort(begin(tiles), end(tiles)); int ans = 0; for (int i = 1; i <= tiles.length(); ++i) { int visited = 0; ans += count(tiles, visited, i); } return ans; } int count(const string& tiles, int& visited, int length) { if (length == 0) { cout << endl; return 1; } int ans = 0; int cur = 0; for (int i = 0; i < tiles.length(); ++i) { if (visited & (1 << i)) continue; if (cur & (1 << (tiles[i] - 'A'))) continue; cur |= 1 << (tiles[i] - 'A'); // cout << tiles[i]; visited |= 1 << i; ans += count(tiles, visited, length - 1); visited ^= 1 << i; } return ans; } };
true
e17fe911c96d1c2d48ec262df05f30defb3cbccd
C++
kumina/awssyncer
/src/recursive_inotify_poller.cc
UTF-8
1,126
2.625
3
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright (c) 2016 Kumina, https://kumina.nl/ // // This file is distributed under a 2-clause BSD license. // See the LICENSE file for details. #include "recursive_inotify_poller.h" #include <dirent.h> #include <cstring> #include <experimental/optional> bool RecursiveInotifyPoller::AddWatch(const std::string& path) { // Add the path itself. if (!ip_->AddWatch(path)) return false; // Recursive add all of its children. DIR* d = opendir(path.c_str()); if (d != nullptr) { struct dirent* de; while ((de = readdir(d)) != nullptr) { if (de->d_type == DT_DIR && strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0) AddWatch(path + de->d_name + '/'); } closedir(d); } return true; } std::experimental::optional<InotifyEvent> RecursiveInotifyPoller::GetNextEvent() { // Add a new watch in case we've created a new directory. std::experimental::optional<InotifyEvent> event = ip_->GetNextEvent(); if (event && event->type == InotifyEventType::CREATED && event->path[event->path.size() - 1] == '/') AddWatch(event->path); return event; }
true
dbf29450eac3f4779c970419469b1f0f52de8e1d
C++
Elojah/Meuh2.0
/util/Rool/src/menus/MemberList.cpp
UTF-8
3,379
2.953125
3
[]
no_license
#include "MemberList.hpp" #include "MemberTemplate.hpp" #include "SortItems.hpp" #include <algorithm> #include <fstream> MemberList::MemberList(void) { } MemberList::MemberList(int h, int w, int y, int x) : Menu(h, w, y, x){ } MemberList::~MemberList(void) { } void MemberList::sortMenu(size_t length) { SortItems sortObject0("New member", "Return"); SortItems sortObject1("Rename", ""); std::sort(menuItems, menuItems + length, sortObject0); std::sort(&(menuItems[1]), &(menuItems[1]) + length - 2, sortObject1); } void MemberList::init(const std::string &path, const std::string &name) { _path = path; _name = name; simpleCreate(name, "", ""); } void MemberList::createItems(void) { std::string line; std::ifstream ifs; std::string access; std::size_t count; line = _path + "/include/" + _name + ".hpp"; access = ""; count = 0; ifs.open(line.c_str()); if (!ifs) { return ; } while (std::getline(ifs, line)) { if (line.find("class " + _name) != std::string::npos && std::getline(ifs, line)) { while (std::getline(ifs, line) && line.compare("};") != 0) { parseLine(line, count); if (line.empty()) { ; } else if (line.compare("public:") == 0) { access = "| "; } else if (line.compare("protected:") == 0) { access = "/ "; } else if (line.compare("private:") == 0) { access = "- "; } else { addItem(access + line, static_cast<Callback>(&MemberList::errorCallback)); } while (ifs.peek() == '\t' || ifs.peek() == ' ') { ifs.ignore(); } } break ; } } ifs.close(); addItem("New member", static_cast<Callback>(&MemberList::newMember)); addItem("Rename", static_cast<Callback>(&MemberList::renameClass)); addItem("Return", static_cast<Callback>(&MemberList::endMenu)); } /* **Define callback menus */ void MemberList::newMember(ITEM *item) { std::string memberName; MemberTemplate tpl(_path); (void)item; memberName = readUser(); notifyUser(tpl.create(memberName)); } void MemberList::renameClass(ITEM *item) { Items::iterator it; std::string newName; MemberTemplate tpl(_path); (void)item; newName = readUser(); /*Force replacement behaviour*/ newName = "${NEW_NAME=" + newName + "}${OLD_NAME=" + _name + "}"; notifyUser(tpl.create(newName)); it = items.find(current_item(menu)); it->second = static_cast<Callback>(&MemberList::endMenu); } void MemberList::parseLine(std::string &line, std::size_t &count) { std::size_t found; std::size_t bracket; if (line.empty()) { return ; } bracket = 0; while ((bracket = line.find('{', bracket)) != std::string::npos) { count++; bracket++; } bracket = 0; while ((bracket = line.find('}', bracket)) != std::string::npos) { count--; bracket++; } std::replace(line.begin(), line.end(), '\t', ' '); while (!line.empty() && line.at(0) == ' ') { line.erase(0, 1); } if ((count != 0 || line.find('}') != std::string::npos) && (line.find('{') == std::string::npos || count > 1)) { line.clear(); } else if ((found = line.find("//")) != std::string::npos || (found = line.find("/*")) != std::string::npos || (found = line.find("**")) != std::string::npos || (found = line.find("*/")) != std::string::npos || (found = line.find("{")) != std::string::npos) { line = line.substr(0, found); } if (line.find('(') != std::string::npos) { line.insert(0, "() "); } }
true
ed8b0a7fb8f8fdb468014f86f94f1a041e436fdf
C++
CGTGPY3G1/AGP-Group-Project
/src/MeshRenderer.cpp
UTF-8
2,444
2.65625
3
[]
no_license
#include "MeshRenderer.h" #include "Material.h" #include "GameObject.h" #include "Transform.h" #include "Shader.h" #include "Mesh.h" namespace B00289996B00227422 { MeshRenderer::MeshRenderer(const std::weak_ptr<GameObject>& g) : Component(g), dirty(false){ } MeshRenderer::~MeshRenderer() { } void MeshRenderer::AddMesh(const std::shared_ptr<Mesh> & toAdd) { if (!dirty) dirty = true; meshes.push_back(toAdd); RecalculateBounds(); } void MeshRenderer::AddMeshes(const std::vector<std::shared_ptr<Mesh>> & toAdd) { if (!dirty) dirty = true; for(size_t i = 0; i < toAdd.size(); i++) { meshes.push_back(toAdd[i]); } RecalculateBounds(); } const std::shared_ptr<Mesh> MeshRenderer::GetMesh(const unsigned int index) const { if(index >= 0 && index < meshes.size()) return meshes[index]; return std::shared_ptr<Mesh>(); } const std::vector<std::shared_ptr<Mesh>> MeshRenderer::GetMeshes() const { return meshes; } void MeshRenderer::SetMaterial(const std::shared_ptr<Material>& newMaterial) { material = newMaterial; } const std::shared_ptr<Material> MeshRenderer::GetMaterial() const { return material; } void MeshRenderer::Render() { material->Bind(); std::shared_ptr<ShaderProgram> shader = material->GetShader(); std::shared_ptr<Transform> transform = GetComponent<Transform>().lock(); shader->SetUniform("model", transform->GetWorldTransform()); shader->SetUniform("normalMatrix", transform->GetNormalMatrix()); for(std::vector<std::shared_ptr<Mesh>>::iterator i = meshes.begin(); i != meshes.end(); ++i) { (*i)->Render(); } } const AABB MeshRenderer::GetAABB() { if (dirty) RecalculateBounds(); return aabb; } const float MeshRenderer::GetRadius() { if (dirty) RecalculateBounds(); return radius; } void MeshRenderer::RecalculateBounds() { glm::vec3 min(0.0f), max(0.0f); float rad = 0.0f; for (std::vector<std::shared_ptr<Mesh>>::iterator i = meshes.begin(); i != meshes.end(); i++) { const AABB mAABB = (*i)->GetAABB(); if (mAABB.min.x < min.x) min.x = mAABB.min.x; if (mAABB.max.x > max.x) max.x = mAABB.max.x; if (mAABB.min.y < min.y) min.y = mAABB.min.y; if (mAABB.max.y > max.y) max.y = mAABB.max.y; if (mAABB.min.z < min.z) min.z = mAABB.min.z; if (mAABB.max.z > max.z) max.z = mAABB.max.z; if ((*i)->GetRadius() > rad) rad = (*i)->GetRadius(); } aabb.min = min; aabb.max = max; radius = rad; dirty = false; } }
true
af64b0073b10f260bb9543b8a76817681ca8db18
C++
davidzyc/oi
/codeforces/253813/j.cpp
UTF-8
1,468
2.734375
3
[]
no_license
#include<cstdio> #include<iostream> #include<cstring> using namespace std; int total_num = 0; char s[200]; int v[100]; bool f(int x, int y) { // cout << x << " " << y << endl; if(x > strlen(s)) { return false; } // cout << "Hi"; if(x == strlen(s)) { int flag = 1; for(int i=1; i<=total_num; i++){ flag = min(flag, v[i]); } if(flag == 1) return true; } int cur; cur = s[x] - '0'; if(cur > 0 && cur <= total_num && v[cur] == 0){ v[cur] = y; if(f(x + 1, y + 1)) return true; v[cur] = 0; } if(x == strlen(s) - 1) return false; cur = (s[x] - '0') * 10 + s[x+1] - '0'; if(cur > 0 && cur <= total_num && v[cur] == 0){ v[cur] = y; if(f(x + 2, y + 1)) return true; v[cur] = 0; } return false; } int main(){ // cout << "Hi"; freopen("joke.in", "r", stdin); freopen("joke.out", "w", stdout); scanf("%s", s); //cout << strlen(s); //cout << "Hi"; if(strlen(s) <= 9) { // cout << "Hi"; for(int i=0; i<strlen(s); i++){ printf("%d ", s[i] - '0'); } return 0; } // cout << "Hello world" ; memset(v, 0, sizeof(v)); total_num = (strlen(s) - 9) / 2 + 9; // cout << total_num; f(0, 1); for(int i=1; i<=total_num; i++){ for(int j=1; j<=total_num; j++) { if(v[j] == i) printf("%d ", j); } } return 0; }
true
7c6438c0f88b9a35b61e361bdbb4557763073961
C++
corinrose/Intro-to-Programming-2013-
/Hwk10rosec/main.cpp
UTF-8
5,708
3.03125
3
[]
no_license
#include <iostream> #include <time.h> #include <vector> #include <iomanip> #define clearScreen cout<<string(25,'\n') using namespace std; string descriptions[] = { "Aces:", "Twos:", "Threes:", "Fours:", "Fives:", "Sixes:", "3 of a Kind:", "4 of a Kind:", "Full House:", "Sm. Straight:", "Lg. Straight:", "Yhatzee!:", "Chance:" }; void displayBoard(vector<int> scoreTable) { for (int i = 0; i < 13; i++) cout << setw(3) << i << setw(15) << descriptions[i] << " " << setw(3) << scoreTable[i] << endl; } string printDieTop(int Value) { switch(Value) { case 0: return "| |"; case 1: return "| 0 |"; case 2: return "| 0 |"; case 3: return "| 0 0 |"; case 4: return "| 0 0 |"; case 5: return "| 0 0 |"; } } string printDieMiddle(int Value) { switch(Value) { case 0: return "| 0 |"; case 1: return "| |"; case 2: return "| 0 |"; case 3: return "| |"; case 4: return "| 0 |"; case 5: return "| 0 0 |"; } } string printDieBottom(int Value) { switch(Value) { case 0: return "| |"; case 1: return "| 0 |"; case 2: return "| 0 |"; case 3: return "| 0 0 |"; case 4: return "| 0 0 |"; case 5: return "| 0 0 |"; } } void randomizeDie(int numDie, vector<int> &dieList) { dieList.resize(numDie); for (int i = 0; i < numDie; i++) dieList[i] = rand() % 6; } void printDie(int numDie, const vector<int> &dieList) { for (int i = 0; i < numDie; i++) cout << "+-----+ "; cout << endl; for (int i = 0; i < numDie; i++) cout << printDieTop(dieList[i]) << " "; cout << endl; for (int i = 0; i < numDie; i++) cout << printDieMiddle(dieList[i]) << " "; cout << endl; for (int i = 0; i < numDie; i++) cout << printDieBottom(dieList[i]) << " "; cout << endl; for (int i = 0; i < numDie; i++) cout << "+-----+ "; cout << endl; } int scoreThroughSix(const vector<int> &diceRolled, int column) { int score = 0; for (int i = 0; i < diceRolled.size(); i ++) { if (diceRolled[i] == column) score += (diceRolled[i] + 1); } return score; } int findPair(const vector<int> &diceRolled, int column, int numPairs) { int kind = 0; int score = 0; for (int i = 0; i < diceRolled.size(); i++) { if (diceRolled[i] == diceRolled[i + 2]) { kind = 3; score = (diceRolled[i] + 1)*3; } else if (diceRolled[i] == diceRolled[i + 3]) { kind = 4; score = (diceRolled[i] + 1)*4; } else if (diceRolled[i] == diceRolled[i + 4]) { kind = 5; } } switch (kind) { case 3: if (column == 6) return score; case 4: if (column == 7) return score; case 5: if (column == 11) return 50; } return 0; } int fullHouse(const vector<int> &diceRolled) { for (int i = 0; i < diceRolled.size(); i++) { if (diceRolled[i] == diceRolled[i + 1] && diceRolled[i + 2] == diceRolled[i + 3] == diceRolled[i + 4] || diceRolled[i] == diceRolled[i + 1] == diceRolled[i + 2] && diceRolled[i + 3] == diceRolled[i + 4]) return 25; } return 0; } int straight(const vector<int> &diceRolled, bool isLgSraight) { int counter = 0; for (int i = 0; i < diceRolled.size(); i++) { if (diceRolled[i] + 1 == diceRolled[i + 1]) counter++; } if ((counter == 3 || counter == 4) && !isLgSraight) return 30; if (counter == 4 && isLgSraight) return 40; return 0; } int scoreDie(vector<int> diceRolled, int column) { sort(diceRolled.begin(), diceRolled.end()); switch (column) { case 0: case 1: case 2: case 3: case 4: case 5: return scoreThroughSix(diceRolled, column); case 6: return findPair(diceRolled, column, 3); case 7: return findPair(diceRolled, column, 4); case 8: return fullHouse(diceRolled); case 9: return straight(diceRolled, false); case 10: return straight(diceRolled, true); case 11: return findPair(diceRolled, column, 5); } } void rollReroll(vector<int> &diceRolled, int &die) { printDie(5, diceRolled); cout << "Select die to re-roll (enter zero when done): "; cin >> die; diceRolled[die - 1] = rand() % 6; clearScreen; } void doTurn(vector<int> &scoresTable, vector<int> diceRolled) { randomizeDie(5, diceRolled); int rowNum; int die = 1; while (die != 0) rollReroll(diceRolled, die); printDie(5, diceRolled); displayBoard(scoresTable); cout << "Select which row: "; cin >> rowNum; scoresTable[rowNum] = 0 + scoreDie(diceRolled, rowNum); clearScreen; displayBoard(scoresTable); } int main() { srand(time(0)); vector<int> scoresTableOne(13, -1); vector<int> scoresTableTwo(13, -1); vector<int> diceRolled(5); //fyi, in the vector int 0 is equivalent to the die 1, int 1 is equivalent to the die 2, etc. while (true) { cout << "Player 1's Turn!" << endl; doTurn(scoresTableOne, diceRolled); cout << "Player 2's Turn!" << endl; doTurn(scoresTableTwo, diceRolled); } }
true
d96b87758b1948c4fdb4ce3c00b304b5bdce8f9d
C++
codedim/nv12stream
/main.cpp
UTF-8
2,015
2.953125
3
[]
no_license
#include "main.h" #include "v4l2_dev.h" #include "v4l2_frame.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> int main(int argc,char* argv[]) { string dev_name = "/dev/video0"; // default dev name int fps; // parsing cli arguments if (argc == 4) dev_name = argv[3]; if (argc > 2 && (argv[1][0] == '-' && argv[1][1] == 'f')) { fps = atoi(argv[2]); } else { cerr << HELP << endl; exit(EXIT_FAILURE); } // open the v4l2 device v4l2_dev *video_dev = new v4l2_dev(dev_name); video_dev->openDevice(); cerr << "capturing frames from '" << dev_name << "' with " << video_dev->framewidth << "x" << video_dev->frameheight << " " << fps << "fps" << endl; void *yuyv_frame; // 'yuv' frame from the v4l2 device void *nv12_frame; // transcoded 'nv12' pixelfomat frame // init frame buffers v4l2_frame *fr = new v4l2_frame(video_dev->devfile, video_dev->framewidth, video_dev->frameheight); fr->initFrameBuffers(); fr->startCapturing(); // start capturing while (1) { yuyv_frame = fr->getFrame(); nv12_frame = fr->getNV12Frame((dev_buffer *) yuyv_frame); writeToStdout((raw_frame *) nv12_frame); } fr->stopCapturing(); fr->freeFrameBuffers(); cerr << frame_nmbr << " frames was cuptured" << endl; video_dev->closeDevice(); return EXIT_SUCCESS; } // appends frame data to the specified file void saveToFile(string file_name, raw_frame * frame) { FILE *out_file = fopen(file_name.c_str(), "a"); fwrite(frame->start, frame->length, 1, out_file); fclose(out_file); cerr << "write frame(" << ++frame_nmbr << ") to file: " << file_name << endl; } // writes frame data to the standard output void writeToStdout(raw_frame * frame) { fwrite(frame->start, frame->length, 1, stdout); cerr << "write frame(" << ++frame_nmbr << ") to stdout" << endl; }
true
0d8437352ee654f654be546b91390781cb62797b
C++
vibhamasti/battleship
/ship.cpp
UTF-8
683
3.1875
3
[]
no_license
// // ship.cpp // Battleship // #include "ship.h" #include <iostream> using namespace std; Ship::Ship() { len = 0; } int Ship::getLen() { return len; } Coord Ship::getPos() { return pos; } char Ship::getOri() { return ori; } // sets length of each ship void Ship::setLen(int l) { len = l; } // input ship details void Ship::input() { // input position (coordinates) cout << "Starting position (coordinates):\n"; pos.input(); // input orientation cout << "Orientation (v/h): "; cin >> ori; while (ori != 'h' && ori != 'v') { cout << "Please enter 'v' or 'h' only: "; cin >> ori; } }
true
5d81b675ebc67a04e86ef157d8a0b2d821f73dae
C++
fsp-ending/OJ
/gcd.cpp
UTF-8
489
2.9375
3
[]
no_license
/************************************************************************* > File Name: gcd.cpp > Author: > Mail: > Created Time: 2020年05月07日 星期四 20时27分38秒 ************************************************************************/ #include<iostream> #include<cstdio> using namespace std; int gcd(int a, int b) { return (b ? gcd(b, a % b) : a); } int main() { int a, b; while (~scanf("%d%d", &a, &b)){ cout << gcd(a, b) << endl; } return 0; }
true
66d8a4195bd86988d566270c33414af3f421c234
C++
ut0s/atcoder
/AGC/AGC036/a.cpp
UTF-8
1,441
3.078125
3
[]
no_license
/** @file a.cpp @title A - Triangle @url https://atcoder.jp/contests/agc036/tasks/agc036_a **/ #include <bits/stdc++.h> using namespace std; typedef long long LL; #define ALL(obj) (obj).begin(), (obj).end() #define REP(i, N) for (int i = 0; i < (N); ++i) vector<LL> div_list(int n) { vector<LL> ret; for (LL i = 1; i * i <= n; ++i) { if (n % i == 0) { ret.push_back(i); if (i != 1 && i * i != n) { ret.push_back(n / i); } } } return ret; } vector<LL> div_list_omit(int n) { vector<LL> ret; LL limit = n < 1e9 ? n : 1e9; for (LL i = 1; i * i < limit; ++i) { if (n % i == 0) { ret.push_back(i); if (i != 1 && i * i != n && (n / i) < 1e9) { ret.push_back(n / i); } } } return ret; } template <class T> void show(vector<T>& v) { for (uint i = 0; i < v.size(); i++) { cout << v[i] << " "; } cout << "\n"; } int main() { LL S; cin >> S; LL x1, x2, x3, y1, y2, y3; x1 = 0; y1 = 0; // vector<int> divlist = div_list(S); vector<LL> divlist = div_list_omit(S); // sort(ALL(divlist), greater<LL>()); // show(divlist); REP(i, divlist.size()) { x2 = divlist[i]; y2 = 0; x3 = 0; y3 = S / divlist[i]; LL q = abs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)); if (q == S) { break; } } cout << x1 << " " << y1 << " " << x2 << " " << y2 << " " << x3 << " " << y3 << endl; return 0; }
true
19b2fcc582469241b2f13665d14cfdb37674db23
C++
DMHACYJ/work1
/acm训练/7.23.随.cpp
GB18030
1,408
3.5625
4
[]
no_license
/* Ŀ XXŵXX֮䣬ߵǼ Ŀԣ봦ļ ÿԵĵһУ N M ( 0<N<=200<M<10 )ֱѧĿѯʴ ѧIDŷֱ1ൽN ڶаNNѧijʼɼеiIDΪiѧijɼ ʣMÿ֣ѯIDAB(AB)ѧУɼߵǶ ÿһѯʲһ߳ɼ*/ #include<iostream> using namespace std; struct tree { int l; int r; int grade; }stu[200]; int num[200]; void build(int k,int l,int r) { stu[k].l=l; stu[k].r=r; if(l==r) { stu[k].grade=num[l]; return; } int mid=(l+r)>>1; build(k<<1,l,mid); build(k<<1|1,mid+1,r); stu[k].grade=max(stu[k<<1].grade,stu[k<<1|1].grade); } int get_max(int k,int l,int r) { int res=0; if(l<=stu[k].l&&r>=stu[k].r) return stu[k].grade; int mid=(stu[k].r+stu[k].l)>>1; if(l<=mid) res=max(res,get_max(k<<1,l,r)); if(r>mid) res=max(res,get_max(k<<1|1,l,r)); return res; } int main() { int n,m; while(cin>>n>>m) { for(int i=1;i<=n;i++) { cin>>num[i]; } build(1,1,n); int a,b; while(m--) { cin>>a>>b; cout<<get_max(1,a,b)<<endl; } } return 0; }
true
22776695c1867a8fcdb9c3708fbd6e351a3c213f
C++
dengbohhxx/vscode
/leetcode/找不同.cpp
UTF-8
456
3.078125
3
[]
no_license
class Solution { public: char findTheDifference(string s, string t) { int n=s.size(); unordered_map<char,int> hash; for(int i=0;i<n;i++) { hash[s[i]]++; } int m=t.size(); char c; for(int i=0;i<m;i++) { hash[t[i]]--; if(hash[t[i]]<0) { c=t[i]; break; } } return c; } };
true
43ff06ea35f31404c3f1c827ecf80202a64f64c1
C++
mrFlatiron/project1
/Project1/src/error_prone.h
UTF-8
573
2.75
3
[]
no_license
#pragma once #include <string> #include <cstdio> enum base_error_code { FATAL = -1, FILE_NOT_FOUND = -2, READING_ERROR = -3 }; class error_prone { protected: int m_error_code; std::string m_error_msg; public: error_prone (); virtual ~error_prone (); std::string error_msg () const; void error_log_to (FILE *fout = stderr, bool any_key_to_continue = false) const; bool error_occurred () const; protected: void error_set (const std::string &error_msg = "Error occurred\n", const int error_code = -1); void error_set (const error_prone &other); };
true
2fcf69eec859bc2e63c3b0f124bb289bf75043c5
C++
Nuurek/Augmented-Reality
/Augmented Reality/RegionBasedOperator.h
UTF-8
683
2.90625
3
[]
no_license
#pragma once #include "Buffer.h" class RegionBasedOperator { protected: const size_t BORDER_SIZE; const size_t REGION_SIZE; const size_t STEP_SIZE; Buffer* buffer; inline bool isPointOutsideBorder(float x, float y) const { return ( x < BORDER_SIZE || x > buffer->getWidth() - BORDER_SIZE || y < BORDER_SIZE || y > buffer->getHeight() - BORDER_SIZE ); } inline bool isPointInsideFrame(size_t x, size_t y) const { return ( x >= 0 && x < buffer->getWidth() && y >= 0 && y < buffer->getHeight() ); } public: RegionBasedOperator(const size_t borderSize, const size_t regionSize, const size_t stepSize); void setBuffer(Buffer* buffer); };
true
e8fed51d11d17cdc0f6ad9a5f93653a63b74a241
C++
AndersonS001/Estrutura-de-Dados
/Agenda/ldde.h
UTF-8
2,244
2.921875
3
[]
no_license
#ifndef LDDE_H #define LDDE_H #include "compromisso.h" #include "no.h" #include <fstream> class Iterador; class LDDE{ private: No* primeiro; No* ultimo; void atualizaLista(); int n; public: LDDE(); ~LDDE(); /*Os argumentos "flag" são apenas para identificar onde serão usados * um QMessageBox*/ bool Inserir(Compromisso newAppointment, int flag); bool Remover(Iterador &removido, int flag); bool Imprimir(Compromisso compromisso); bool Buscar(Iterador& achou,Compromisso buscar); /* Para não quebrar a lógica da LDDE ser ordenada na inserção, o "Alterar" vai * deletar o nó buscado e inserir um novo se o valor buscado existir.*/ bool alterarCompromisso(Iterador removido, Compromisso novo); bool Inicio(Iterador &comeco); bool Fim(Iterador &fim); }; class Iterador{ private: No* it; /* as funções abaixo serão usadas na LDDE com o objetivo de tirar a LDDE como classe amiga do Nó. * Os métodos da LDDE que precisarão das funçõess abaixo são: * Inserir, Remover e o destrutor. */ No* getEnderecoAnterior(); No* getProximoEndereco(); No* getEnderecoAtual(); void setProximoEndereco(No* proximoEnd); void setEnderecoAnterior(No* enderecoAnterior); void setIt(No *no); public: friend bool LDDE::Inserir(Compromisso newAppointment, int flag); friend bool LDDE::Remover(Iterador &removido, int flag); friend LDDE::~LDDE(); Iterador(); Iterador(No* no); ~Iterador(); //iterador aponta para o proximo no bool avancar(); //iterador aponta para o no anterior bool voltar(); //verifica se o iterador esta apontando para um no que existe bool noExiste(); /* a ideia é usar essa funcão nas classe Alterar. * Se as funçõess de alterar e remover retornarem true, vou resetar o meu * iterador para a condição inicial - it = nullptr*/ bool setNulo(bool sucesso); Compromisso getValor()const; //sobrecarga de operadoes para fazer o iterador avançar ou voltar Iterador& operator++(int um); Iterador& operator--(int um); bool operator!(); }; #endif // LDDE_H
true
a0d03d3f23c9988c424bce2412e215a10162d18e
C++
programmerPhysicist/tomato
/src/display.h
UTF-8
734
2.6875
3
[]
no_license
/*********************************************************************** * display.h: * display class * Author: * Alexander Marvin * Summary: * Displays the timer and messages for pomodoro class ************************************************************************/ #ifndef TOMATO_DISPLAY_H #define TOMATO_DISPLAY_H #include <string> #include "ncurses.h" class display { public: //constructor display(); //member methods void displayMessage(std::string message); //put message out to screen char getUserInput(std::string message); //get user input void setClock(std::string time); //destructor ~display(); private: WINDOW *msgBar; WINDOW *backWin; WINDOW *timerWin; }; #endif // TOMATO_DISPLAY_H
true
e5d7a1bc026cc9dd7cb0041290cc82c2c7327d1e
C++
sunalii/MyNotebook-Desktop-Application
/notesdoodle.cpp
UTF-8
6,622
2.640625
3
[ "MIT" ]
permissive
#include "notesdoodle.h" #include "ui_notesdoodle.h" #include <QPainter> #include <QMouseEvent> #include <QFileDialog> #include <QPrinter> #include <QPrintDialog> #include <QMessageBox> #include <QCloseEvent> #include <QDesktopServices> #include <QUrl> //// NotesDoodle Constructor //// NotesDoodle::NotesDoodle(QWidget *parent) : QMainWindow(parent), ui(new Ui::NotesDoodle) { ui->setupUi(this); setWindowTitle(tr("Doodle")); // Window title image = QImage(this->size(), QImage::Format_RGB32); // Doodle area image.fill(Qt::white); // Setting default background drawing = false; // Clear screen brushColor = Qt::black; // Setting default Brush Color brushSize = 2; // Setting default Brush Color } NotesDoodle::~NotesDoodle() { delete ui; } //// Event Handling //// void NotesDoodle::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) // Allowing user to draw when the Left Mouse button is pressed { drawing = true; lastPoint = event->pos(); } } void NotesDoodle::mouseMoveEvent(QMouseEvent *event) { if ((event->buttons() & Qt::LeftButton) && drawing) // Allowing user to draw when the Left Mouse button is moving { QPainter painter(&image); painter.setPen(QPen(brushColor, brushSize, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); painter.drawLine(lastPoint, event->pos()); lastPoint = event->pos(); this->update(); } } void NotesDoodle::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) // Drawing stops with the relase of the Left Mouse button click { drawing = false; } } void NotesDoodle::paintEvent(QPaintEvent *event) { QPainter painter(this); // Interacting with the available printer QRect scribbleRect = event->rect(); painter.drawImage(scribbleRect,image,scribbleRect); // Printing the screen } void NotesDoodle::resizeEvent(QResizeEvent *event) // Not working { if (width() > image.width() || height() > image.height()) { // int newWidth = qMax(width() + 128, image.width()); // int newHeight = qMax(height() + 128, image.height()); //resizeImage(&image, QSize(newWidth, newHeight)); resize(1920,1080); update(); } QWidget::resizeEvent(event); } void NotesDoodle::closeEvent(QCloseEvent *event) { QMessageBox::StandardButton answer = QMessageBox::warning(this,"Unsaved file", "Unsaved doodle found. Do you want to close the doodle?", QMessageBox::Save | QMessageBox::Yes | QMessageBox::No); // Warning the user about an unsaved file if(answer == QMessageBox::Yes){ QWidget::closeEvent(event); // Closes the window } else if(answer == QMessageBox::Save){ QString filePath = QFileDialog::getSaveFileName(this,"Save Doodle", "", "PNG (*.png);;jpeg(*.jpg *.jpeg);;All files (*.*)"); // Triggering the Save action function to save the Doodle image.save(filePath); event->ignore(); } else if(answer == QMessageBox::No){ event->ignore(); // Returning back to the Doodle } } //// End of Event Handling //// //// Buttons //// void NotesDoodle::on_actionSave_triggered() { QString filePath = QFileDialog::getSaveFileName(this,"Save Doodle", "", "PNG (*.png);;jpeg(*.jpg *.jpeg);;All files (*.*)"); if(filePath == ""){ return; } image.save(filePath); } void NotesDoodle::on_actionClear_triggered() { image.fill(Qt::white); // Clearing the background this->update(); } void NotesDoodle::on_actionPrint_triggered() { QPrinter printer(QPrinter::HighResolution); // Can be used to print QPrintDialog printDialog(&printer, this); // Open printer dialog and print if asked if (printDialog.exec() == QDialog::Accepted) { QPainter painter(&printer); QRect rect = painter.viewport(); QSize size = image.size(); size.scale(rect.size(), Qt::KeepAspectRatio); painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); painter.setWindow(image.rect()); painter.drawImage(0, 0, image); } } void NotesDoodle::on_actionExit_triggered() { NotesDoodle::close(); // Exiting from the current window } void NotesDoodle::on_action2px_triggered() { brushSize = 2; brushColor = Qt::black; } void NotesDoodle::on_action5px_triggered() { brushSize = 5; brushColor = Qt::black; } void NotesDoodle::on_action10px_triggered() { brushSize = 10; brushColor = Qt::black; } void NotesDoodle::on_action12px_triggered() { brushSize = 20; brushColor = Qt::black; } void NotesDoodle::on_actionBlack_triggered() { brushColor = Qt::black; } void NotesDoodle::on_actionWhite_triggered() { brushColor = Qt::white; } void NotesDoodle::on_actionRed_triggered() { brushColor = Qt::red; } void NotesDoodle::on_actionGreen_triggered() { brushColor = Qt::green; } void NotesDoodle::on_actionBlue_triggered() { brushColor = Qt::blue; } void NotesDoodle::on_actionEraser_triggered() { brushSize = 5; brushColor = Qt::white; } void NotesDoodle::on_actionEraser_20px_triggered() { brushSize = 20; brushColor = Qt::white; } void NotesDoodle::on_actionPen_triggered() { brushSize = 5; brushColor = Qt::blue; } void NotesDoodle::on_actionPencil_triggered() { brushSize = 2; brushColor = Qt::black; } void NotesDoodle::on_actionAbout_MyNotebookDoodle_triggered() { QString aboutDoodle = "MyNotebook Doodle is a simple painting playground for the anyone to " "quickly get started with scribbling any patterns and designs. " "MyNotebook Doodle will provide the facilities simply from drawing patterns to printing it.\n\nEnjoy!"; QMessageBox::about(this,"About MyNotebook Doodle", aboutDoodle); } void NotesDoodle::on_actionAbout_QT_triggered() { QMessageBox::aboutQt(this); } void NotesDoodle::on_actionGo_to_Google_triggered() { QDesktopServices::openUrl(QUrl("https://www.google.com/")); // Opening Google webpage } void NotesDoodle::on_actionGo_to_Plymouth_triggered() { QDesktopServices::openUrl(QUrl("https://dle.plymouth.ac.uk/")); // Opening University of Plymouth website } //// End of Buttons //// //// End ////
true
e6113d7a6dadf69c816fdac2465b182745c289d1
C++
OlmoPrieto/bingo
/Project/common/include/card.h
UTF-8
770
3.046875
3
[]
no_license
#ifndef __CARD_H__ #define __CARD_H__ #include <random> #include <SFML/Graphics/RectangleShape.hpp> #include <SFML/Graphics/Text.hpp> #include <SFML/Graphics/RenderWindow.hpp> constexpr uint8_t NUMBERS_AMOUNT_IN_CARD = 15; class Card { public: Card(); Card(const sf::Vector2f& size, const sf::Vector2f& position); ~Card(); void create(const sf::Vector2f& size, const sf::Vector2f& position); void draw(sf::RenderWindow* window); uint8_t* getNumbers(); private: sf::RectangleShape m_shape; sf::Font m_font; sf::Text m_texts[NUMBERS_AMOUNT_IN_CARD]; sf::Vector2f m_position; sf::Vector2f m_size; static std::mt19937 m_random_generator; uint8_t m_numbers[NUMBERS_AMOUNT_IN_CARD] = { 0 }; static bool m_random_generator_seeded; }; #endif // __CARD_H__
true
f63170fe4ccbe4c011495124267bf842b15d8458
C++
jasjeetIM/OlympicMedalistSearch
/src/BinaryTree.cpp
UTF-8
5,175
3.203125
3
[]
no_license
#include "stdafx.h" #include "BinaryTree.h"; template<class AthleteType> BinaryNode<AthleteType>* BinaryTree<AthleteType>::_copyTree(const BinaryNode<AthleteType>* nodePtr, vector <AthleteType> &arr, AthleteType visit(AthleteType)) { BinaryNode<AthleteType>* newNodePtr = 0; if (nodePtr != 0) { AthleteType tempCopy = visit(nodePtr->getItem()); arr.push_back(tempCopy); newNodePtr = new BinaryNode<AthleteType>(tempCopy); newNodePtr->setLeftPtr(_copyTree(nodePtr->getLeftPtr(), arr, visit)); newNodePtr->setRightPtr(_copyTree(nodePtr->getRightPtr(), arr, visit)); } return newNodePtr; } template<class AthleteType> void BinaryTree<AthleteType>::destroyTree(BinaryNode<AthleteType>* nodePtr) { if (nodePtr != 0) { destroyTree(nodePtr->getLeftPtr()); destroyTree(nodePtr->getRightPtr()); delete nodePtr; } } template<class AthleteType> void BinaryTree<AthleteType>::_preorder(void visit(AthleteType &), BinaryNode<AthleteType>* nodePtr) const { if (nodePtr != 0) { AthleteType item = nodePtr->getItem(); visit(item); _preorder(visit, nodePtr->getLeftPtr()); _preorder(visit, nodePtr->getRightPtr()); } } template<class AthleteType> void BinaryTree<AthleteType>::_inorder(void visit(AthleteType &), BinaryNode<AthleteType>* nodePtr) const { if (nodePtr != 0) { _inorder(visit, nodePtr->getLeftPtr()); AthleteType item = nodePtr->getItem(); visit(item); _inorder(visit, nodePtr->getRightPtr()); } } template<class AthleteType> void BinaryTree<AthleteType>::_postorder(void visit(AthleteType &), BinaryNode<AthleteType>* nodePtr) const { if (nodePtr != 0) { _postorder(visit, nodePtr->getLeftPtr()); _postorder(visit, nodePtr->getRightPtr()); AthleteType item = nodePtr->getItem(); visit(item); } } template<class AthleteType> void BinaryTree<AthleteType>::_breadthtraversal(void visit(AthleteType &), BinaryNode<AthleteType>* nodePtr) const { ofstream out; out.open("Output.txt"); queue<BinaryNode<AthleteType>*> q; q.push(nodePtr); BinaryNode <AthleteType>* tmp = q.front(); while (!q.empty()) { tmp = q.front(); q.pop(); Athlete * item = tmp->getIte(); out << item->getName() << "," << item->getAge() << "," << item->getCountry() << "," << item->getYear() << endl; if (tmp->getLeftPtr() != NULL) q.push(tmp->getLeftPtr()); if (tmp->getRightPtr() != NULL) q.push(tmp->getRightPtr()); } out.close(); } template<class AthleteType> void BinaryTree<AthleteType>::_postorderprint(void visit(AthleteType &), BinaryNode<AthleteType>* nodePtr, int indent) const { if (nodePtr != 0) { _postorderprint(visit, nodePtr->getLeftPtr(), indent + 2); _postorderprint(visit, nodePtr->getRightPtr(), indent + 2); if (indent) cout << std::setw(indent) << ' '; if (nodePtr->getRightPtr() != 0) cout << " /\n" << setw(indent) << ' '; AthleteType item = nodePtr->getItem(); visit(item); if (nodePtr->getLeftPtr() != 0) cout << std::setw(indent) << ' ' << " \\\n"; } } template<class AthleteType> void BinaryTree<AthleteType>::_preorderprint(void visit(AthleteType &), BinaryNode<AthleteType>* nodePtr, int indent) const { if (nodePtr != 0) { if (indent) cout << std::setw(indent) << ' '; if (nodePtr->getRightPtr() != 0) cout << " /\n" << setw(indent) << ' '; AthleteType item = nodePtr->getItem(); visit(item); if (nodePtr->getLeftPtr() != 0) cout << std::setw(indent) << ' ' << " \\\n"; _preorderprint(visit, nodePtr->getLeftPtr(), indent + 2); _preorderprint(visit, nodePtr->getRightPtr(), indent + 2); } } template<class AthleteType> void BinaryTree<AthleteType>::_inorderprint(void visit(AthleteType &), BinaryNode<AthleteType>* nodePtr, int indent) const { if (nodePtr != 0) { _inorderprint(visit, nodePtr->getLeftPtr(), indent + 2); if (indent) cout << std::setw(indent) << ' '; if (nodePtr->getRightPtr() != 0) cout << " /\n" << setw(indent) << ' '; AthleteType item = nodePtr->getItem(); visit(item); if (nodePtr->getLeftPtr() != 0) { cout << std::setw(indent) << ' ' << " \\\n"; _inorderprint(visit, nodePtr->getRightPtr(), indent + 2); } } } template <class AthleteType> void BinaryTree<AthleteType>::_RNLorder(void visit(AthleteType &), BinaryNode<AthleteType>* nodePtr) const // For reverse alphabetical order. { if (nodePtr != 0) { _RNLorder(visit, nodePtr->getRightPtr()); AthleteType item = nodePtr->getItem(); visit(item); _RNLorder(visit, nodePtr->getLeftPtr()); } } template <class AthleteType> void BinaryTree<AthleteType>::_RNLorder(void visit(AthleteType &, int), BinaryNode<AthleteType>* nodePtr, int & width) const { if (nodePtr != 0) { width += 4; _RNLorder(visit, nodePtr->getRightPtr(), width); AthleteType item = nodePtr->getItem(); visit(item, width); _RNLorder(visit, nodePtr->getLeftPtr(), width); width -= 4; } } template <class AthleteType> BinaryTree<AthleteType> & BinaryTree<AthleteType>::operator=(const BinaryTree<AthleteType> & sourceTree) { clear(); root = sourceTree.root; count = sourceTree.count; return *this; } template <class AthleteType> void BinaryTree<AthleteType>:: clear() { destroyTree(root); root = 0; count = 0; }
true
bdb64985c1059188b7e70ba9c4935df6aacdc92d
C++
lehuuvinh92/arduino-examples
/dht-arduino/dht-lcd.ino
UTF-8
910
2.9375
3
[]
no_license
#include "DHT.h"//Khai báo thư viện DHT #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); int dht_pin = 7;//Khai báo chân kết nối DHT với Arduino int DHTTYPE = DHT11;//Khai báo loại cảm biến DHT DHT dht(dht_pin, DHTTYPE);//Khai báo một đối tượng DHT void setup() { lcd.begin(16, 2); dht.begin();//Khởi tạo đối tượng DHT } void loop() { float h = dht.readHumidity();//Lấy giá trị độ ẩm float t = dht.readTemperature();//Lấy giá trị nhiệt độ ở đơn vị độ C float tf = dht.readTemperature(true);//Lấy giá trị nhiệt độ ở đơn vị độ F lcd.setCursor(0, 0); lcd.print("HUMIDITY:"); lcd.print(h); lcd.print("%"); lcd.setCursor(0, 1); lcd.print(t); lcd.print(char(223)); lcd.print("C"); lcd.print("-"); lcd.print(tf); lcd.print(char(223)); lcd.print("F"); }
true
4f0b6ad1cb932e5edf5ffa150cbf860da846c96d
C++
nichols/polynomial-mxplus1
/f2t_findcycles.cpp
UTF-8
2,861
3.0625
3
[]
no_license
#include "f2t_findcycles.h" #include <cstdio> #include <cstdint> // find cycle in sequence starting at f using Brent's algorithm // mu is the number of iterations until it becomces periodic // lambda is the length of the period // sigma is the stopping time // returns 0 unless the iteration times out, in which case it // returns the degree where it stopped unsigned int f2t_findperiod( f2t_sequence_t f, unsigned int timeout, unsigned int *mu, unsigned int *lambda, unsigned int *sigma ) { f2t_sequence_t tortoise = f2t_sequence_t( f ); // tortoise f2t_sequence_t hare = f2t_sequence_t( f ); hare.step( ); // hare unsigned int i = 1; // current power of 2 *lambda = 1; // period *mu = 0; // time to begin periodic part *sigma = 0; unsigned int deg0 = tortoise.degree( ); // degree of initial poly // until the tortoise and hare are equal (or timeout) while( hare.count( ) < timeout && !hare.is_one( ) && tortoise != hare ) { //printf( "k= %6lu, ", k ); //if( !( k % 8 ) ) printf( "\n" ); // should we advance i to the next power of 2? if( i == *lambda ) { tortoise = hare; i <<= 1; *lambda = 0; } // if this is the first term with degree < degree of initial poly, // update sigma if( !*sigma && hare.degree( ) < deg0 ) *sigma = hare.count( ); hare.step( ); // hare steps foward (*lambda)++; // period counter } // why did we exit the loop? // if we hit 1... if( hare.is_one( ) ) { // return mu = time to 1, lambda = 0 *mu = hare.count( ); *lambda = 0; return 0; } // otherwise... // if we timed out... if( hare.count( ) >= timeout ) { *mu = 0; *lambda = 0; return hare.degree( ); // return the degree at which we timed out } // now we can be sure the sequence really does become periodic // lambda is the period of the sequence. We want to find the exact // point where the sequence becomes periodic. // set the tortoise at the beginning (f) and the hare lambda steps // ahead. Then step both forward together one at a time until they // agree tortoise = f; hare = f; // set the tortoise and hare (lambda) steps apart for( unsigned int j = 1; j <= *lambda; j++ ) hare.step( ); // now iterate until they're equal while( tortoise != hare ) { tortoise.step( ); hare.step( ); } *mu = tortoise.count( ); return 0; } // This function tests one polynomial using f2t_findperiod, then outputs // the information in a neat row of text void f2t_run_and_print( f2t_sequence_t f, unsigned int timeout ) { unsigned int mu, lambda, sigma, d; f.print( ); d = f2t_findperiod( f, timeout, &mu, &lambda, &sigma ); if( sigma ) printf( ", %8u", sigma ); else printf( ", %8s", "inf" ); if( d ) printf( ", timeout(%u), d=%u\n", timeout, d ); else printf( ", %8u, %8u\n", mu, lambda ); }
true
1ff3391befb32ff975be231a5b8271e753849fc8
C++
binc74/mc
/MC/game/objects/cube.cpp
UTF-8
5,620
2.71875
3
[]
no_license
#include "cube.h" namespace mc { Cube::Cube() : pos(0, 0, 0) { } Cube::Cube(World* world, float px, float py, float pz) : world(world), pos(px, py, pz) { } Cube::~Cube() { } void Cube::pushVerticesData(ChunkRenderer* cr, SpriteType top, SpriteType front, SpriteType right, SpriteType back, SpriteType left, SpriteType bot) { glm::vec3 color = glm::vec3(1.f, 1.f, 1.f); glm::vec3 normal_top = glm::vec3(0.f, 1.f, 0.f); glm::vec3 normal_bot = glm::vec3(0.f, -1.f, 0.f); glm::vec3 normal_left = glm::vec3(-1.f, 0.f, 0.f); glm::vec3 normal_right = glm::vec3(1.f, 0.f, 0.f); glm::vec3 normal_front = glm::vec3(0.f, 0.f, 1.f); glm::vec3 normal_back = glm::vec3(0.f, 0.f, -1.f); int x = (int)pos.x; int y = (int)pos.y; int z = (int)pos.z; float len = 0.5f; if (!world->getObjAt(x, y+1, z)) { // Order: top, front right back left bot // Add top face (vertices: top-front-left -> top-front-right -> top-back-right -> top-back-left) cr->addVertex(top, Vertex(glm::vec3(-len, len, -len) + pos, color, 0, 1, normal_top)); // v0 top-front-left cr->addVertex(top, Vertex(glm::vec3(-len, len, len) + pos, color, 0, 0, normal_top)); // v1 top-front-right cr->addVertex(top, Vertex(glm::vec3(len, len, len) + pos, color, 1, 0, normal_top)); // v2 top-back-right cr->addVertex(top, Vertex(glm::vec3(-len, len, -len) + pos, color, 0, 1, normal_top)); // v0 top-front-left cr->addVertex(top, Vertex(glm::vec3(len, len, len) + pos, color, 1, 0, normal_top)); // v2 top-back-right cr->addVertex(top, Vertex(glm::vec3(len, len, -len) + pos, color, 1, 1, normal_top)); // v3 top-back-left } if (!world->getObjAt(x, y, z+1)) { // Add front face (vertices: top-front-left -> bot-front-left -> bot-front-right -> top-front-right) cr->addVertex(front, Vertex(glm::vec3(-len, len, len) + pos, color, 0, 1, normal_front)); // v4 top-front-left cr->addVertex(front, Vertex(glm::vec3(-len, -len, len) + pos, color, 0, 0, normal_front)); // v5 bot-front-left cr->addVertex(front, Vertex(glm::vec3(len, -len, len) + pos, color, 1, 0, normal_front)); // v6 bot-front-right cr->addVertex(front, Vertex(glm::vec3(-len, len, len) + pos, color, 0, 1, normal_front)); // v4 top-front-left cr->addVertex(front, Vertex(glm::vec3(len, -len, len) + pos, color, 1, 0, normal_front)); // v6 bot-front-right cr->addVertex(front, Vertex(glm::vec3(len, len, len) + pos, color, 1, 1, normal_front)); // v7 top-front-right } if (!world->getObjAt(x+1, y, z)) { // Add right face cr->addVertex(right, Vertex(glm::vec3(len, len, len) + pos, color, 0, 1, normal_right)); // v8 top-front-right cr->addVertex(right, Vertex(glm::vec3(len, -len, len) + pos, color, 0, 0, normal_right)); // v9 bot-front-right cr->addVertex(right, Vertex(glm::vec3(len, -len, -len) + pos, color, 1, 0, normal_right)); // v10 bot-back-right cr->addVertex(right, Vertex(glm::vec3(len, len, len) + pos, color, 0, 1, normal_right)); // v8 top-front-right cr->addVertex(right, Vertex(glm::vec3(len, -len, -len) + pos, color, 1, 0, normal_right)); // v10 bot-back-right cr->addVertex(right, Vertex(glm::vec3(len, len, -len) + pos, color, 1, 1, normal_right)); // v11 top-back-right } if (!world->getObjAt(x, y, z - 1)) { // Add back face cr->addVertex(back, Vertex(glm::vec3(len, len, -len) + pos, color, 0, 1, normal_back)); // v12 top-back-right cr->addVertex(back, Vertex(glm::vec3(len, -len, -len) + pos, color, 0, 0, normal_back)); // v13 bot-back-right cr->addVertex(back, Vertex(glm::vec3(-len, -len, -len) + pos, color, 1, 0, normal_back)); // v14 bot-back-left cr->addVertex(back, Vertex(glm::vec3(len, len, -len) + pos, color, 0, 1, normal_back)); // v12 top-back-right cr->addVertex(back, Vertex(glm::vec3(-len, -len, -len) + pos, color, 1, 0, normal_back)); // v14 bot-back-left cr->addVertex(back, Vertex(glm::vec3(-len, len, -len) + pos, color, 1, 1, normal_back)); // v15 top-back-left } if (!world->getObjAt(x - 1, y, z)) { // Add left face cr->addVertex(left, Vertex(glm::vec3(-len, len, -len) + pos, color, 0, 1, normal_left)); // v16 top-back-left cr->addVertex(left, Vertex(glm::vec3(-len, -len, -len) + pos, color, 0, 0, normal_left)); // v17 bot-back-left cr->addVertex(left, Vertex(glm::vec3(-len, -len, len) + pos, color, 1, 0, normal_left)); // v18 bot-front-left cr->addVertex(left, Vertex(glm::vec3(-len, len, -len) + pos, color, 0, 1, normal_left)); // v16 top-back-left cr->addVertex(left, Vertex(glm::vec3(-len, -len, len) + pos, color, 1, 0, normal_left)); // v18 bot-front-left cr->addVertex(left, Vertex(glm::vec3(-len, len, len) + pos, color, 1, 1, normal_left)); // v19 top-front-left } if (!world->getObjAt(x, y - 1, z)) { // Add bot face cr->addVertex(bot, Vertex(glm::vec3(-len, -len, len) + pos, color, 0, 1, normal_bot)); // v20 bot-front-left cr->addVertex(bot, Vertex(glm::vec3(-len, -len, -len) + pos, color, 0, 0, normal_bot)); // v21 bot-back-left cr->addVertex(bot, Vertex(glm::vec3(len, -len, -len) + pos, color, 1, 0, normal_bot)); // v22 bot-back-right cr->addVertex(bot, Vertex(glm::vec3(-len, -len, len) + pos, color, 0, 1, normal_bot)); // v20 bot-front-left cr->addVertex(bot, Vertex(glm::vec3(len, -len, -len) + pos, color, 1, 0, normal_bot)); // v22 bot-back-right cr->addVertex(bot, Vertex(glm::vec3(len, -len, len) + pos, color, 1, 1, normal_bot)); // v23 bot-front-left } } void Cube::update(float dt) { } }
true
282ed9b8e4adf68f5055dbfb454eec018e59b799
C++
Dracono99/Mav-Games-Chimera-ProtoType
/DragonXMath.h
UTF-8
8,976
2.90625
3
[]
no_license
#pragma once #include "d3dUtility.h" class DragonXVector3 : public D3DXVECTOR3 { public: DragonXVector3():D3DXVECTOR3() { } DragonXVector3(D3DXVECTOR3 v3):D3DXVECTOR3(v3) { } DragonXVector3(real x,real y,real z):D3DXVECTOR3(x,y,z) { } inline void operator+=(const DragonXVector3& v) { x+=v.x; y+=v.y; z+=v.z; } inline void operator+=(const D3DXVECTOR3& v) { x+=v.x; y+=v.y; z+=v.z; } inline DragonXVector3 operator+(const DragonXVector3& v) const { return DragonXVector3(x+v.x,y+v.y,z+v.z); } inline D3DXVECTOR3 operator+(const D3DXVECTOR3& v) const { return D3DXVECTOR3(x+v.x,y+v.y,z+v.z); } inline void operator-=(const DragonXVector3& v) { x -= v.x; y -= v.y; z -= v.z; } inline void operator-=(const D3DXVECTOR3& v) { x -= v.x; y -= v.y; z -= v.z; } inline DragonXVector3 operator-(const DragonXVector3& v) const { return DragonXVector3(x-v.x,y-v.y,z-v.z); } inline D3DXVECTOR3 operator-(const D3DXVECTOR3& v) const { return D3DXVECTOR3(x-v.x,y-v.y,z-v.z); } inline void operator*=(const real value) { x *= value; y *= value; z *= value; } inline DragonXVector3 operator*(const real value) const { return DragonXVector3(x*value, y*value, z*value); } inline DragonXVector3 componentProductDrX(const DragonXVector3 &v) const { return DragonXVector3(x*v.x,y*v.y,z*v.z); } inline void componentProductUpdate(const DragonXVector3 &v) { x*=v.x; y*=v.y; z*=v.z; } inline D3DXVECTOR3 componentProductDX(const DragonXVector3 &v) const { return D3DXVECTOR3(x*v.x,y*v.y,z*v.z); } inline real operator*(const DragonXVector3 &v) const //dot product { return D3DXVec3Dot(this,&v); } inline real operator*(const D3DXVECTOR3 &v)const //dot product with dx9 v3 { return D3DXVec3Dot(this,&v); } inline DragonXVector3 operator%(const DragonXVector3 &vector)const //cross product of 2 dragonxv3s { DragonXVector3 v; D3DXVec3Cross(&v,this,&vector); return v; } inline D3DXVECTOR3 operator%(const D3DXVECTOR3 &vector)const //cross product of 2 dragonxv3s { D3DXVECTOR3 v; D3DXVec3Cross(&v,this,&vector); return v; } inline void Normalize() { D3DXVec3Normalize(this,this); } inline real GetMagnitude()const//returns the magnitude more processor intensive then get squared mag { return D3DXVec3Length(this); } inline real GetMagSquared() const // returns squared mag less processor intensive than get mag { return D3DXVec3LengthSq(this); } /*inline real operator[](unsigned i) const { if (i == 0) return x; if (i == 1) return y; return z; } inline real& operator[](unsigned i) { if (i == 0) return x; if (i == 1) return y; return z; }*/ inline void clear() { x=0.0f; y=0.0f; z=0.0f; } inline void invert() { x*=-1.0f; y*=-1.0f; z*=-1.0f; } inline void truncate(real max) { if (GetMagSquared() > max*max) { Normalize(); x *= max; y *= max; z *= max; } } /** Checks if the two vectors have identical components. */ inline bool operator==(const DragonXVector3& other) const { return x == other.x && y == other.y && z == other.z; } /** Checks if the two vectors have non-identical components. */ inline bool operator!=(const DragonXVector3& other) const { return !(*this == other); } /** * Checks if this vector is component-by-component less than * the other. * * @note This does not behave like a single-value comparison: * !(a < b) does not imply (b >= a). */ inline bool operator<(const DragonXVector3& other) const { return x < other.x && y < other.y && z < other.z; } /** * Checks if this vector is component-by-component less than * the other. * * @note This does not behave like a single-value comparison: * !(a < b) does not imply (b >= a). */ inline bool operator>(const DragonXVector3& other) const { return x > other.x && y > other.y && z > other.z; } /** * Checks if this vector is component-by-component less than * the other. * * @note This does not behave like a single-value comparison: * !(a <= b) does not imply (b > a). */ inline bool operator<=(const DragonXVector3& other) const { return x <= other.x && y <= other.y && z <= other.z; } /** * Checks if this vector is component-by-component less than * the other. * * @note This does not behave like a single-value comparison: * !(a <= b) does not imply (b > a). */ inline bool operator>=(const DragonXVector3& other) const { return x >= other.x && y >= other.y && z >= other.z; } }; class DragonXQuaternion : public D3DXQUATERNION { public: DragonXQuaternion():D3DXQUATERNION(0.0f,0.0f,0.0f,1.0f) { } DragonXQuaternion(real x,real y,real z, real w):D3DXQUATERNION(x,y,z,w) { } DragonXQuaternion(D3DXQUATERNION q):D3DXQUATERNION(q) { } inline void normalize() { D3DXQuaternionNormalize(this,this); } inline void operator*=(const DragonXQuaternion &q) { D3DXQuaternionMultiply(this,this,&q); } inline void addScaledVectorDrX(const DragonXVector3& vector,real scale) { D3DXQUATERNION q(vector.x * scale, vector.y * scale, vector.z * scale,0.0f); q *= *this; w += q.w * ((real)0.5); x += q.x * ((real)0.5); y += q.y * ((real)0.5); z += q.z * ((real)0.5); } inline void rotateByVector(const DragonXVector3& v) { DragonXQuaternion q(v.x,v.y,v.z,0.0f); (*this)*= q; } inline DragonXVector3 Forward() { return DragonXVector3( 2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)); } inline DragonXVector3 Up() { return DragonXVector3( 2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)); } inline DragonXVector3 Right() { return DragonXVector3( 1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)); } }; class DragonXMatrix : public D3DXMATRIX { public: DragonXMatrix():D3DXMATRIX(1.0f,0.0f,0.0f,0.0f,0.0f,1.0f,0.0f,0.0f,0.0f,0.0f,1.0f,0.0f,0.0f,0.0f,0.0f,1.0f) { } DragonXMatrix(D3DXMATRIX m):D3DXMATRIX(m) { } inline void setDiagonal(real a,real b, real c) { _11=a; _22=b; _33=c; } inline void setDiagonal(DragonXVector3 v) { setDiagonal(v.x,v.y,v.z); } inline DragonXVector3 operator*(const DragonXVector3 &v) const { return DragonXVector3( v.x*_11+v.y*_12+v.z*_13+_14, v.x*_21+v.y*_22+v.z*_23+_24, v.x*_31+v.y*_32+v.z*_33+_34); } inline DragonXVector3 transform(const DragonXVector3 &v) const { return (*this)*v; } inline real getDeterminant()const { return D3DXMatrixDeterminant(this); } inline DragonXMatrix operator*(const DragonXMatrix &x) const { DragonXMatrix m; D3DXMatrixMultiply(&m,this,&x); return m; } inline DragonXMatrix getInverse() const { DragonXMatrix m; return *D3DXMatrixInverse(&m,NULL,this); } inline DragonXVector3 TransformTranspose(const DragonXVector3 &vector) const { return DragonXVector3( vector.x * _11 + vector.y * _21 + vector.z * _31, vector.x * _12 + vector.y * _22 + vector.z * _32, vector.x * _13 + vector.y * _23 + vector.z * _33); } inline DragonXVector3 TransformDirection(const DragonXVector3 &v)const { return DragonXVector3(v.x*_11+v.y*_12+v.z*_13,v.x*_21+v.y*_22+v.z*_23,v.x*_31+v.y*_32+v.z*_33); } inline DragonXVector3 TransformInverseDirection(const DragonXVector3 &v) const { return DragonXVector3(v.x*_11+v.y*_21+v.z*_31,v.x*_12+v.y*_22+v.z*_32,v.x*_13+v.y*_23+v.z*_33); } inline DragonXVector3 TransformInverse(const DragonXVector3 &v) const { DragonXVector3 tmp = v; tmp.x-=_14; tmp.y-=_24; tmp.z-=_34; return DragonXVector3(tmp.x*_11+tmp.y*_21+tmp.z*_31,tmp.x*_12+tmp.y*_22+tmp.z*_32,tmp.x*_13+tmp.y*_23+tmp.z*_33); } inline void setComponents(const DragonXVector3 &compOne, const DragonXVector3 &compTwo, const DragonXVector3 &compThree) { _11 = compOne.x; _12 = compTwo.x; _13 = compThree.x; _21 = compOne.y; _22 = compTwo.y; _23 = compThree.y; _31 = compOne.z; _32 = compTwo.z; _33 = compThree.z; } inline DragonXVector3 getAxisVector(unsigned idx) const { return DragonXVector3(m[0][idx],m[1][idx],m[2][idx]); } /** * Sets the matrix to be a skew symmetric matrix based on * the given vector. The skew symmetric matrix is the equivalent * of the cross product. So if a,b are vectors. a x b = A_s b * where A_s is the skew symmetric form of a. */ inline void setSkewSymmetric(const DragonXVector3 vector) { _11 = _22 = _33 = 0.0f; _12 = -vector.z; _13 = vector.y; _21 = vector.z; _23 = -vector.x; _31 = -vector.y; _32 = vector.x; } /** * Sets the matrix to be the transpose of the given matrix. * * @param m The matrix to transpose and use to set this. */ inline void setTranspose(const DragonXMatrix &M) { _11 = M._11; _12 = M._21; _13 = M._31; _21 = M._12; _22 = M._22; _23 = M._32; _31 = M._13; _32 = M._23; _33 = M._33; } /** Returns a new matrix containing the transpose of this matrix. */ inline DragonXMatrix transpose() const { DragonXMatrix result; result.setTranspose(*this); return result; } };
true
ac07ed8b4cd2a6773faec7ccc72ed24b9a41c08a
C++
jiku100/ShadowDetectionMethod
/OpenCV_Version/Entropy_Lab_Invariant/entropy.h
ISO-8859-7
2,582
2.828125
3
[]
no_license
#pragma once #include "header.h" #include <numeric> #include <math.h> void RGB2LCS(Mat& src, vector<Point2f>& lcs) { for (int j = 0; j < src.rows; j++) { for (int i = 0; i < src.cols; i++) { Vec3b& pixel = src.at<Vec3b>(j, i); double b = pixel[0]; double g = pixel[1]; double r = pixel[2]; if (b < 0.1) { b = 0.1; } if (g < 0.1) { g = 0.1; } if (r < 0.1) { r = 0.1; } double x1 = logf(r) - logf(g); // x1 = log(R/G) double x2 = logf(b) - logf(r); // x2 = log(B/G) lcs.push_back(Point2f(x1, x2)); //if (pixel[0] != 0 && pixel[1] != 0 && pixel[2] != 0) { // double x1 = log(pixel[2]) - log(pixel[1]); // x1 = log(R/G) // double x2 = log(pixel[0]) - log(pixel[1]); // x2 = log(B/G) // lcs.push_back(Point2f(x1, x2)); //} //else { // lcs.push_back(Point2f(0, 0)); //} } } } void cal_T(vector<Point2f>& lcs, int angle, vector<double>& T) { double rad = angle * CV_PI / 180.; for (int i = 0; i < lcs.size(); i++) { T.push_back(lcs[i].x * cosf(rad) + lcs[i].y * sinf(rad)); } } void cal_T_90(vector<double>& T, vector<double>& T_90) { int lower = T.size() * 0.05; int upper = T.size() * 0.95; for (int i = lower; i < upper; i++) { T_90.push_back(T[i]); } } void cal_bin(vector<double>& T_90, double& bin) { double sum = 0.; for (double p : T_90) { sum += p; } double mean = sum / T_90.size(); double sum_dev = 0; for (double v : T_90) { sum_dev += powf(v - mean, 2); } double sigma = sqrtf(sum_dev / T_90.size()); bin = 3.5 * sigma / powf(T_90.size(), 1. / 3.); } void Prob_Dist(vector<double>& T_90, double& bin, vector<double>& prob) { int tot_count = (int)(T_90.back() - T_90.front()) / bin; int count = 1; int c = 0; vector<int> freq; for (int i = 0; i < T_90.size(); i++) { if (count != tot_count) { if (T_90[i] <= T_90[0] + bin * count) { c++; } else { freq.push_back(c); c = 1; count++; } } else { freq.push_back(T_90.size() - i); break; } } for (double cnt : freq) { prob.push_back(cnt / T_90.size()); } } double cal_entropy(vector<double>& prob) { double h = 0; for (double p : prob) { h += -p * (logf(p)); } return h; } void getEntropy(vector<Point2f>& lcs, vector<double>& entropy) { for (int angle = 1; angle < 181; angle++) { vector<double> T; vector<double> T_90; // ߰ 90% T double bin; vector<double> prob; cal_T(lcs, angle, T); std::sort(T.begin(), T.end()); cal_T_90(T, T_90); cal_bin(T_90, bin); Prob_Dist(T_90, bin, prob); entropy.push_back(cal_entropy(prob)); } }
true
3eb2bfa557684c2250b4d68b618276277869df96
C++
gilbertoalexsantos/judgesolutions
/Solved/URI/@URI 1433 - The Splitting Club/1433 - The Splitting Club.cpp
UTF-8
1,085
2.84375
3
[]
no_license
//Author: Gilberto A. dos Santos //Website: https://www.urionlinejudge.com.br/judge/en/problems/view/1433 #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <vector> #include <algorithm> using namespace std; const double EPS = 1e-9; struct type { int q, y; type(int q=0, int y=0) : q(q), y(y) {} bool operator< (const type &other) const { return q < other.q; } }; bool lessOrEqual(double a, double b) { return (a - b) < EPS; } int k; double r; vector<type> ar; int getGroup(int left) { if(ar.size() == 1) return 1; int right = left; double t = 1.0; do { right++; t = (double) ar[right].q / ar[left].q; } while(right < ar.size() && lessOrEqual(t,r)); return right; } int main() { while(scanf("%d %lf",&k,&r) && k) { ar.assign(k,type()); for(int i = 0; i < k; i++) { int q, y; scanf("%d %d",&q,&y); ar[i] = type(q,y); } sort(ar.begin(),ar.end()); int group = getGroup(0); int ans = 1; while(group < ar.size()) { ans++; group = getGroup(group); } printf("%d\n",ans); } }
true
1cc5d66e93fe718520cd225b194181bdf855f223
C++
antoniovazquezaraujo/8x8
/events/Page.cpp
UTF-8
1,490
2.875
3
[]
no_license
#include "Component.h" #include "Page.h" Page::Page() :levels(1, vector<int>()) ,colorBlock(1, COLS, ROWS){ this->componentW = 200/ COLS; this->componentH = 200/ ROWS; reset(); } Page::~Page(){ for(vector<Component*>::iterator i = components.begin(); i != components.end(); i++){ delete (*i); } } void Page::reset() { colorBlock.reset(); } void Page::addComponent(string name, int level, Component * component) { if(level >= colorBlock.getNumLevels()){ colorBlock.addLevel(); levels.push_back(vector<int>()); } components.push_back(component); int componentKey = components.size()-1; namesToComponents[name] = componentKey; levels[level].push_back(componentKey); componentsToLevels[componentKey]=level; } Component * Page::getComponent(string name){ return components[namesToComponents[name]]; } vector<Component*> Page::getComponentsAt(Pos pos){ // ordenar esto por NIVEL!! vector<Component*> ret; for(vector<Component*>::iterator i = components.begin(); i != components.end(); i++){ if((*i)->containsPoint(pos)){ ret.push_back((*i)); } } return ret; } ColorBlock & Page::getColorBlock(){ return colorBlock; } void Page::update() { reset(); for(Component * c: components){ c->update(); } for (int level = 0; level < colorBlock.getNumLevels(); level++) { for (unsigned int n = 0; n < levels[level].size(); n++) { Component *c = components[levels[level][n]]; c->paint(colorBlock[level], Pos(0,0), Size(COLS, ROWS)); } } }
true
e6a534ec4bdf271bc2de97de57186713f609541b
C++
FireFox2000000/GbaGameEngine
/GbaGameEngine/src/engine/base/core/stl/FixedPoint.h
UTF-8
6,036
3.15625
3
[]
no_license
#pragma once #include <type_traits> // for is_integral #include "engine/base/Typedefs.h" #include "engine/base/Macros.h" // If you don't provide an integer type as the IntType parameter then I hate you. template<class IntType, u8 FRACTIONAL_BITS> class FixedPoint { IntType storage; inline IntType GetIntStorage() const { return storage >> FRACTIONAL_BITS; } inline IntType GetFloatStorage() const { return storage & BITS_U32(FRACTIONAL_BITS); } // Looses float precision easily inline FixedPoint<IntType, FRACTIONAL_BITS>& MulHalfShift(const FixedPoint<IntType, FRACTIONAL_BITS>& b) { storage = ((int)storage >> (FRACTIONAL_BITS / 2)) * (b.storage >> (FRACTIONAL_BITS / 2)); return *this; } // High chance of encountering overflow inline FixedPoint<IntType, FRACTIONAL_BITS>& Mul(const FixedPoint<IntType, FRACTIONAL_BITS>& b) { storage = ((int)storage * b.storage) >> FRACTIONAL_BITS; return *this; } public: inline FixedPoint() : storage(0) { STATIC_ASSERT(std::is_integral<IntType>::value, "Integral required."); } inline FixedPoint(const FixedPoint<IntType, FRACTIONAL_BITS>& that) { *this = that; } inline IntType GetStorage() const { return storage; } inline void SetStorage(IntType val) volatile { storage = val; } template<class T, u8 BITS> FixedPoint(const FixedPoint<T, BITS>& that) { // Todo- Handle signed and unsigned types int shiftDir = int(FRACTIONAL_BITS) - BITS; if (shiftDir > 0) storage = that.GetStorage() << shiftDir; else storage = that.GetStorage() >> -shiftDir; } static constexpr IntType FloatCompress(float val) { return IntType(val * (1 << FRACTIONAL_BITS) + 0.5f); } static constexpr float FloatDecompress(IntType val) { return (1.0f / (float)(1 << FRACTIONAL_BITS)) * ((int)val); } constexpr inline FixedPoint(int val) : storage(val << FRACTIONAL_BITS) {} constexpr inline FixedPoint(float val) : storage(FloatCompress(val)) {} constexpr inline FixedPoint(double val) : storage(IntType(val * (1 << FRACTIONAL_BITS) + 0.5)) {} inline int ToInt() const { return (int)(GetIntStorage()); } inline int ToRoundedInt() const { return (int)((storage + (1 << FRACTIONAL_BITS) / 2) >> FRACTIONAL_BITS); } constexpr inline float ToFloat() const { return FloatDecompress(storage); } inline double ToDouble() const { return (1.0 / (double)(1 << FRACTIONAL_BITS)) * ((int)storage); } static constexpr inline u8 GetFpLevel() { return FRACTIONAL_BITS; } inline operator int() const { return ToInt(); } inline operator float() const { return ToFloat(); } inline operator double() const { return ToDouble(); } template<class T, u8 BITS> inline operator FixedPoint<T, BITS>() const { return FixedPoint<T, BITS>(*this); } /*******************************************************************************/ inline FixedPoint<IntType, FRACTIONAL_BITS>& operator += (const FixedPoint<IntType, FRACTIONAL_BITS>& b) { storage += b.storage; return *this; } inline FixedPoint<IntType, FRACTIONAL_BITS>& operator -= (const FixedPoint<IntType, FRACTIONAL_BITS>& b) { storage -= b.storage; return *this; } inline FixedPoint<IntType, FRACTIONAL_BITS>& operator *= (const FixedPoint<IntType, FRACTIONAL_BITS>& b) { return MulHalfShift(b); } // Easy to overflow and underflow. Try not to use this if it can be helped inline FixedPoint<IntType, FRACTIONAL_BITS>& operator /= (const FixedPoint<IntType, FRACTIONAL_BITS>& b) { storage = storage * (1 << FRACTIONAL_BITS) / b.storage; return *this; } inline FixedPoint<IntType, FRACTIONAL_BITS> operator+(const FixedPoint<IntType, FRACTIONAL_BITS>& b) const { return FixedPoint<IntType, FRACTIONAL_BITS>(*this) += b; } inline FixedPoint<IntType, FRACTIONAL_BITS> operator-(const FixedPoint<IntType, FRACTIONAL_BITS>& b) const { return FixedPoint<IntType, FRACTIONAL_BITS>(*this) -= b; } inline FixedPoint<IntType, FRACTIONAL_BITS> operator*(const FixedPoint<IntType, FRACTIONAL_BITS>& b) const { return FixedPoint<IntType, FRACTIONAL_BITS>(*this) *= b; } // Easy to overflow and underflow. Try not to use this if it can be helped inline FixedPoint<IntType, FRACTIONAL_BITS> operator/(const FixedPoint<IntType, FRACTIONAL_BITS>& b) const { return FixedPoint<IntType, FRACTIONAL_BITS>(*this) /= b; } inline bool operator > (const FixedPoint<IntType, FRACTIONAL_BITS>& b) const { return storage > b.storage; } inline bool operator < (const FixedPoint<IntType, FRACTIONAL_BITS>& b) const { return storage < b.storage; } inline bool operator <= (const FixedPoint<IntType, FRACTIONAL_BITS>& b) const { return !(*this > b); } inline bool operator >= (const FixedPoint<IntType, FRACTIONAL_BITS>& b) const { return !(*this < b); } inline bool operator == (const FixedPoint<IntType, FRACTIONAL_BITS>& b) const { return storage == b.storage; } inline bool operator != (const FixedPoint<IntType, FRACTIONAL_BITS>& b) const { return !(*this == b); } /*******************************************************************************/ inline FixedPoint<IntType, FRACTIONAL_BITS> operator*(const int& b) const { return FixedPoint<IntType, FRACTIONAL_BITS>(*this) *= FixedPoint<IntType, FRACTIONAL_BITS>(b); } inline bool operator > (const int& b) const { return *this > FixedPoint<IntType, FRACTIONAL_BITS>(b); } inline bool operator < (const int& b) const { return *this < FixedPoint<IntType, FRACTIONAL_BITS>(b); } inline bool operator <= (const int& b) const { return *this <= FixedPoint<IntType, FRACTIONAL_BITS>(b); } inline bool operator >= (const int& b) const { return *this >= FixedPoint<IntType, FRACTIONAL_BITS>(b); } inline bool operator == (const int& b) const { return *this == FixedPoint<IntType, FRACTIONAL_BITS>(b); } inline bool operator != (const int& b) const { return *this != FixedPoint<IntType, FRACTIONAL_BITS>(b); } }; using tFixedPoint8 = FixedPoint<int, 8>; using tFixedPoint16 = FixedPoint<int, 16>; using tFixedPoint24 = FixedPoint<int, 24>;
true
2eee635f7001674bd5ad93e18243ea2e5bc5c893
C++
cocokechun/Programming
/College/USACO/gift1.cpp
UTF-8
988
2.65625
3
[]
no_license
/* ID: kmao1 PROG: gift1 LANG: C++ */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> using namespace std; int main() { ofstream fout ("gift1.out"); ifstream fin ("gift1.in"); int n; vector<string> names; map<string, int> acc; fin >> n; string name; for (int i = 0; i < n; i++) { fin >> name; names.push_back(name); acc[name] = 0; } int gift, m, per, left; string receiver; for (int i = 0; i < n; i++) { fin >> name; fin >> gift >> m; if (gift > 0) { per = gift / m; left = gift % m; acc[name] = acc[name] - gift + left; for (int j = 0; j < m; j++) { fin >> receiver; acc[receiver] += per; } } } for (int i = 0; i < names.size(); i++) { fout << names[i] << ' ' << acc[names[i]] << endl; } return 0; }
true
20c24a9a4cee5e23d5d46b35aca2c940f1e28adc
C++
Ahiganbana/leetcode
/findPeakElement.cpp
UTF-8
1,023
3.640625
4
[]
no_license
#include <iostream> #include <vector> using namespace std; //找到数组中的峰值元素(使用O(logN的时间复杂度)) class Solution { public: int findPeakElement(vector<int>& nums) { int size = nums.size(); if(size == 0) { return 0; } int maxIndex = getMaxIndex(nums, 0, size - 1, 0); return maxIndex; } int getMaxIndex(vector<int>& nums, int left, int right, int max) { if(right - left <= 1) { if(nums[left] >= nums[right]) { max = left; }else{ max = right; } }else{ int max1 = INT_MIN; int max2 = INT_MIN; int mid = left + (left + right) / 2; max1 = getMaxIndex(nums, left, mid, max1); max2 = getMaxIndex(nums, mid + 1, right, max2); if(nums[max1] > nums[max2]) { max = max1; }else{ max = max2; } } return max; } };
true
3bb64a6a96bbaae4667b41b7361425fa726e2a7d
C++
GadyPu/OnlineJudge
/other-oj/ACdream/1738 世风日下的哗啦啦族I.cpp
UTF-8
13,208
2.546875
3
[]
no_license
/* * this code is made by Bug_Pu * Problem: 1738 * Verdict: Accepted * Submission Date: 2015-05-19 19:26:48 * Time: 420MS * Memory: 40160KB */ #include<algorithm> #include<iostream> #include<cstdlib> #include<cstring> #include<cstdio> #define lc root<<1 #define rc root<<1|1 const int Max_N = 50010; const int INF = ~0u >> 1; struct Node { int data, s, c; bool color; Node *fa, *ch[2]; inline void set(int _v, bool _color, int i, Node *p) { data = _v, color = _color, s = c = i; fa = ch[0] = ch[1] = p; } inline void push_up() { s = ch[0]->s + ch[1]->s + c; } inline void push_down() { for (Node *x = this; x->s; x = x->fa) x->s--; } inline int cmp(int v) const { return data == v ? -1 : v > data; } }; struct RedBlackTree { int top, ans, tot, sum, arr[Max_N]; Node *null, *tail; Node stack[Max_N * 18], *store[Max_N << 2], *ptr[Max_N << 2]; inline void init(int n) { top = 0; tail = &stack[0]; null = tail++; null->set(0, 0, 0, NULL); for (int i = 1; i <= n; i++) scanf("%d", &arr[i]); seg_built(1, 1, n); } inline Node *newNode(int v) { Node *p = null; if (!top) p = tail++; else p = store[--top]; p->set(v, 1, 1, null); return p; } inline void rotate(int root, Node* &x, bool d) { Node *y = x->ch[!d]; x->ch[!d] = y->ch[d]; if (y->ch[d]->s) y->ch[d]->fa = x; y->fa = x->fa; if (!x->fa->s) ptr[root] = y; else x->fa->ch[x->fa->ch[0] != x] = y; y->ch[d] = x; x->fa = y; y->s = x->s; x->push_up(); } inline void insert(int root, int v) { Node *x = ptr[root], *y = null; while (x->s) { x->s++, y = x; int d = x->cmp(v); if (-1 == d) { x->c++; return; } x = x->ch[d]; } x = newNode(v); if (y->s) y->ch[v > y->data] = x; else ptr[root] = x; x->fa = y; insert_fix(root, x); } inline void insert_fix(int root, Node* &x) { while (x->fa->color) { Node *par = x->fa, *Gp = par->fa; bool d = par == Gp->ch[0]; Node *uncle = Gp->ch[d]; if (uncle->color) { par->color = uncle->color = 0; Gp->color = 1; x = Gp; } else if (x == par->ch[d]) { rotate(root, x = par, !d); } else { Gp->color = 1; par->color = 0; rotate(root, Gp, d); } } ptr[root]->color = 0; } inline Node *find(Node *x, int data) { while (x->s && x->data != data) x = x->ch[x->data < data]; return x; } inline void del_fix(int root, Node* &x) { while (x != ptr[root] && !x->color) { bool d = x == x->fa->ch[0]; Node *par = x->fa, *sibling = par->ch[d]; if (sibling->color) { sibling->color = 0; par->color = 1; rotate(root, x->fa, !d); sibling = par->ch[d]; } else if (!sibling->ch[0]->color && !sibling->ch[1]->color) { sibling->color = 1, x = par; } else { if (!sibling->ch[d]->color) { sibling->ch[!d]->color = 0; sibling->color = 1; rotate(root, sibling, d); sibling = par->ch[d]; } sibling->color = par->color; sibling->ch[d]->color = par->color = 0; rotate(root, par, !d); break; } } x->color = 0; } inline void del(int root, int data) { Node *z = find(ptr[root], data); if (!z->s) return; if (z->c > 1) { z->c--; z->push_down(); return; } Node *y = z, *x = null; if (z->ch[0]->s && z->ch[1]->s) { y = z->ch[1]; while (y->ch[0]->s) y = y->ch[0]; } x = y->ch[!y->ch[0]->s]; x->fa = y->fa; if (!y->fa->s) ptr[root] = x; else y->fa->ch[y->fa->ch[1] == y] = x; if (z != y) z->data = y->data, z->c = y->c; y->fa->push_down(); for (Node *k = y->fa; y->c > 1 && k->s && k != z; k = k->fa) k->s -= y->c - 1; if (!y->color) del_fix(root, x); store[top++] = y; } inline Node* get_min(Node *x) { for (; x->ch[0]->s; x = x->ch[0]); return x; } inline int count(Node *x, int v) { int res = 0, t = 0; for (; x->s;) { t = x->ch[0]->s; if (v < x->data) x = x->ch[0]; else res += t + x->c, x = x->ch[1]; } return res; } inline void seg_built(int root, int l, int r) { ptr[root] = null; for (int i = l; i <= r; i++) insert(root, arr[i]); if (l == r) return; int mid = (l + r) >> 1; seg_built(lc, l, mid); seg_built(rc, mid + 1, r); } inline void seg_modify(int root, int l, int r, int pos, int v){ if (pos > r || pos < l) return; del(root, arr[pos]); insert(root, v); if (l == r) return; int mid = (l + r) >> 1; seg_modify(lc, l, mid, pos, v); seg_modify(rc, mid + 1, r, pos, v); } inline void seg_query_min(int root, int l, int r, int x, int y) { if (x > r || y < l) return; if (x <= l && y >= r) { Node *ret = get_min(ptr[root]); if (ret->data < ans) ans = ret->data; return; } int mid = (l + r) >> 1; seg_query_min(lc, l, mid, x, y); seg_query_min(rc, mid + 1, r, x, y); } inline void seg_query_tot(int root, int l, int r, int x, int y, int val) { if (x > r || y < l) return; if (x <= l && y >= r) { tot += find(ptr[root], val)->c; return; } int mid = (l + r) >> 1; seg_query_tot(lc, l, mid, x, y, val); seg_query_tot(rc, mid + 1, r, x, y, val); } inline void seg_query_count(int root, int l, int r, int x, int y, int val) { if (x > r || y < l) return; if (x <= l && y >= r) { sum += count(ptr[root], val); return; } int mid = (l + r) >> 1; seg_query_count(lc, l, mid, x, y, val); seg_query_count(rc, mid + 1, r, x, y, val); } inline void gogo(int n) { int a, b, c, d; scanf("%d", &a); if (1 == a) { scanf("%d %d", &b, &c); seg_modify(1, 1, n, b, c), arr[b] = c; } else if (2 == a) { ans = INF, tot = 0; scanf("%d %d", &b, &c); seg_query_min(1, 1, n, b, c); seg_query_tot(1, 1, n, b, c, ans); printf("%d %d\n", ans, tot); } else { sum = 0; scanf("%d %d %d", &b, &c, &d); seg_query_count(1, 1, n, b, c, d); printf("%d\n", sum); } } }rbt; int main() { #ifdef LOCAL freopen("in.txt", "r", stdin); freopen("out.txt", "w+", stdout); #endif int n, m; while (~scanf("%d %d", &n, &m)) { rbt.init(n); while (m--) rbt.gogo(n); } return 0; } /* * this code is made by Bug_Pu * Problem: 1738 * Verdict: Accepted * Submission Date: 2015-05-19 18:59:53 * Time: 508MS * Memory: 33128KB */ #include<algorithm> #include<iostream> #include<cstdlib> #include<cstring> #include<cstdio> #define lc root<<1 #define rc root<<1|1 using std::sort; using std::lower_bound; using std::upper_bound; const int Max_N = 50010; const int INF = ~0u >> 1; struct Node { int v, s, c; Node *ch[2]; inline void set(int _v, int _s, Node *p) { v = _v, s = c = _s; ch[0] = ch[1] = p; } inline void push_up() { s = ch[0]->s + ch[1]->s + c; } inline int cmp(int x) const { return x == v ? -1 : x > v; } }; struct SizeBalanceTree { int top, ans, tot, sum, arr[Max_N]; Node *null, *tail, stack[Max_N * 18]; Node *store[Max_N << 2], *ptr[Max_N << 2]; inline void init(int n) { top = 0; tail = &stack[0]; null = tail++; null->set(0, 0, NULL); for (int i = 1; i <= n; i++) scanf("%d", &arr[i]); seg_built(1, 1, n); } inline Node *newNode(int v) { Node *p = null; if (!top) p = tail++; else p = store[--top]; p->set(v, 1, null); return p; } inline void rotate(Node *&x, int d) { Node *k = x->ch[!d]; x->ch[!d] = k->ch[d]; k->ch[d] = x; k->s = x->s; x->push_up(); x = k; } inline void Maintain(Node *&x, int d) { if (!x->ch[d]->s) return; if (x->ch[d]->ch[d]->s > x->ch[!d]->s) { rotate(x, !d); } else if (x->ch[d]->ch[!d]->s > x->ch[!d]->s) { rotate(x->ch[d], d), rotate(x, !d); } else { return; } Maintain(x, 0), Maintain(x, 1); } inline void insert(Node *&x, int v) { if (x == null) { x = newNode(v); return; } else { x->s++; int d = x->cmp(v); if (-1 == d) { x->c++; return; } insert(x->ch[d], v); x->push_up(); Maintain(x, d); } } inline void del(Node *&x, int v) { if (!x->s) return; x->s--; int d = x->cmp(v); if (-1 == d) { if (x->c > 1) { x->c--; return; } else if (!x->ch[0]->s || !x->ch[1]->s) { store[top++] = x; x = x->ch[0]->s ? x->ch[0] : x->ch[1]; } else { Node *ret = x->ch[1]; for (; ret->ch[0]->s; ret = ret->ch[0]); del(x->ch[1], x->v = ret->v); } } else { del(x->ch[d], v); } if (x->s) x->push_up(); } inline Node *get_min(Node *x) { for (; x->ch[0]->s; x = x->ch[0]); return x; } inline int find(Node *x, int v) { while (x->s && x->v != v) x = x->ch[v > x->v]; return x->c; } inline int count(Node *x, int v) { int res = 0, t = 0; for (; x->s;) { t = x->ch[0]->s; if (v < x->v) x = x->ch[0]; else res += t + x->c, x = x->ch[1]; } return res; } inline void seg_built(int root, int l, int r) { ptr[root] = null; for (int i = l; i <= r; i++) insert(ptr[root], arr[i]); if (l == r) return; int mid = (l + r) >> 1; seg_built(lc, l, mid); seg_built(rc, mid + 1, r); } inline void seg_modify(int root, int l, int r, int pos, int v){ if (pos > r || pos < l) return; del(ptr[root], arr[pos]); insert(ptr[root], v); if (l == r) return; int mid = (l + r) >> 1; seg_modify(lc, l, mid, pos, v); seg_modify(rc, mid + 1, r, pos, v); } inline void seg_query_min(int root, int l, int r, int x, int y) { if (x > r || y < l) return; if (x <= l && y >= r) { Node *ret = get_min(ptr[root]); if (ret->v < ans) ans = ret->v; return; } int mid = (l + r) >> 1; seg_query_min(lc, l, mid, x, y); seg_query_min(rc, mid + 1, r, x, y); } inline void seg_query_tot(int root, int l, int r, int x, int y, int val) { if (x > r || y < l) return; if (x <= l && y >= r) { tot += find(ptr[root], val); return; } int mid = (l + r) >> 1; seg_query_tot(lc, l, mid, x, y, val); seg_query_tot(rc, mid + 1, r, x, y, val); } inline void seg_query_count(int root, int l, int r, int x, int y, int val) { if (x > r || y < l) return; if (x <= l && y >= r) { sum += count(ptr[root], val); return; } int mid = (l + r) >> 1; seg_query_count(lc, l, mid, x, y, val); seg_query_count(rc, mid + 1, r, x, y, val); } inline void gogo(int n) { int a, b, c, d; scanf("%d", &a); if (1 == a) { scanf("%d %d", &b, &c); seg_modify(1, 1, n, b, c), arr[b] = c; } else if (2 == a) { ans = INF, tot = 0; scanf("%d %d", &b, &c); seg_query_min(1, 1, n, b, c); seg_query_tot(1, 1, n, b, c, ans); printf("%d %d\n", ans, tot); } else { sum = 0; scanf("%d %d %d", &b, &c, &d); seg_query_count(1, 1, n, b, c, d); printf("%d\n", sum); } } }sbt; int main() { #ifdef LOCAL freopen("in.txt", "r", stdin); freopen("out.txt", "w+", stdout); #endif; int n, m; while (~scanf("%d %d", &n, &m)) { sbt.init(n); while (m--) sbt.gogo(n); } return 0; }
true
459f809166ce1d87288592136daadd0dcd87da4f
C++
pgentile/eva-mini-projet
/src/road-block.cpp
UTF-8
2,129
2.765625
3
[]
no_license
#include "road-block.h" #include <GL/glut.h> #include <GL/gl.h> #include "vector-3d.h" RoadBlock::RoadBlock(double width, Vector3D startPoint, Vector3D endPoint) :_width(width),_startPoint(startPoint),_endPoint(endPoint) { } RoadBlock::~RoadBlock() {} void RoadBlock::render() { glPushMatrix(); // ---- Renders a Road Block between StartPoint(xs,ys,zs) and EndPoint(xe,ye,ze) ---- Vector3D rbVector = _endPoint - _startPoint ; Vector3D rbNormalVector(0.,0.,-1.); //Vector3D rbNormalVector = _endPoint - _startPoint ; rbVector.normalize(); // Setting up Normal vector to roadBlock //rbNormalVector.normalize(); //rbNormalVector.rotate( 0 , M_PI /2 , 0 ); // Building Road Block Points Vector3D widthVector = rbVector.crossProduct( rbNormalVector ) * _width; Vector3D firstPoint = _startPoint + widthVector - rbNormalVector * (ROAD_HEIGHT / 2); Vector3D secondPoint = _startPoint - widthVector - rbNormalVector * (ROAD_HEIGHT / 2); Vector3D thirdPoint = _endPoint - widthVector - rbNormalVector * (ROAD_HEIGHT / 2); Vector3D fourthPoint = _endPoint + widthVector - rbNormalVector * (ROAD_HEIGHT / 2); #ifdef RB_DEBUG std::cout << "-----------" << std::endl; std::cout << "RB : First Point = " << firstPoint << std::endl; std::cout << "RB : Second Point = " << secondPoint << std::endl; std::cout << "RB : Third Point = " << thirdPoint << std::endl; std::cout << "RB : Fourth Point = " << fourthPoint << std::endl; #endif glBegin(GL_QUADS); glNormal3f(rbNormalVector.getX(),rbNormalVector.getY(),rbNormalVector.getZ()); glTexCoord2f(1,1); glVertex3f( firstPoint.getX() , firstPoint.getY() , 0 ); glTexCoord2f(0,1); glVertex3f( secondPoint.getX() , secondPoint.getY() , 0 ); glTexCoord2f(0,0); glVertex3f( thirdPoint.getX() , thirdPoint.getY() , 0 ); glTexCoord2f(1,0); glVertex3f( fourthPoint.getX() , fourthPoint.getY() , 0 ); glEnd(); glPopMatrix(); }
true
ece7a69c27d2ce6957a8e747645198d3dcbf3c34
C++
erkang/design
/Builder/PizzaBuilder.h
UTF-8
687
2.671875
3
[]
no_license
#include "Pizza.h" // "Abstract Builder" class PizzaBuilder { public: const Pizza & pizza(); virtual ~PizzaBuilder(); virtual void buildDough() = 0; virtual void buildSauce() = 0; virtual void buildTopping() = 0; protected: Pizza pizza_; }; //---------------------------------------------------------------- class HawaiianPizzaBuilder : public PizzaBuilder { public: ~HawaiianPizzaBuilder(); void buildDough(); void buildSauce(); void buildTopping(); }; class SpicyPizzaBuilder : public PizzaBuilder { public: ~SpicyPizzaBuilder(); void buildDough(); void buildSauce(); void buildTopping(); };
true
2cbb0f9783e74313f3226f2d3c291a076b0e2185
C++
mshmnv/ft_containers
/list.hpp
UTF-8
24,723
3.125
3
[]
no_license
#ifndef LIST_HPP #define LIST_HPP #include <iostream> #include "Node.hpp" namespace ft { template <class Type, class Alloc = std::allocator<Type> > class list { private: typedef Alloc allocator_type; typedef Type value_type; typedef value_type& reference; typedef const value_type& const_reference; typedef size_t size_type; std::allocator<Node<value_type> > _nodeAllocator; allocator_type _allocatorType; Node<Type>* _head; Node<Type>* _tail; Node<Type>* _empty; size_t _size; template <bool B, class T = void> struct enable_if {}; template <class T> struct enable_if <true, T> { typedef T type; }; public: ///////////////////////////// //// CONSTRUCTORS //// ///////////////////////////// explicit list(const allocator_type& = allocator_type()); explicit list(size_type, const value_type& = value_type(), const allocator_type& = allocator_type()); template <class InputIterator> list(InputIterator first, InputIterator last, const allocator_type& = allocator_type(), typename ft::list<Type, Alloc>::enable_if <!std::numeric_limits<InputIterator>::is_specialized>::type* = 0); explicit list(list const &); list &operator=(list const &); ////////////////////////// //// DESTRUCTOR //// ////////////////////////// ~list(); ////////////////////////// //// ITERATORS //// ////////////////////////// class const_iterator; class iterator { protected: Node<Type>* _curNode; friend class list; public: iterator() : _curNode(NULL) {} iterator(Node<Type> *other) : _curNode(other) {} iterator(iterator const &other) { this->_curNode = other._curNode; } iterator& operator++() { this->_curNode = this->_curNode->next; return *this; } iterator& operator--() { this->_curNode = this->_curNode->prev; return *this; } iterator operator++(int) { iterator tmp = *this; ++(*this); return tmp; } iterator operator--(int) { iterator tmp = *this; --(*this); return tmp; } bool operator!=(iterator const &it) { return this->_curNode != it._curNode; } bool operator==(iterator const &it) { return this->_curNode == it._curNode; } Type operator*() { return this->_curNode->getData(); } }; class const_iterator : public iterator { public: const_iterator() : iterator() {} const_iterator(Node<Type> *other) : iterator(other) {} const_iterator(iterator const &other) : iterator(other) {} const_iterator& operator=(iterator &other) { this->_curNode = other._curNode; return *this; } }; class const_reverse_iterator; class reverse_iterator { private: Node<Type>* _curNode; public: reverse_iterator() : _curNode(NULL) {} reverse_iterator(Node<Type> *other) : _curNode(other) {} reverse_iterator(reverse_iterator const &other) { this->_curNode = other._curNode; } reverse_iterator& operator++() { this->_curNode = this->_curNode->prev; return *this; } reverse_iterator& operator--() { this->_curNode = this->_curNode->next; return *this; } reverse_iterator operator++(int) { reverse_iterator tmp = *this; ++(*this); return tmp; } reverse_iterator operator--(int) { reverse_iterator tmp = *this; --(*this); return tmp; } bool operator!=(reverse_iterator const &it) { return this->_curNode != it._curNode; } Type operator*() { return this->_curNode->getData(); } }; class const_reverse_iterator : public reverse_iterator { public: const_reverse_iterator() : reverse_iterator() {} const_reverse_iterator(Node<Type> *other) : reverse_iterator(other) {} const_reverse_iterator(reverse_iterator const &other) : reverse_iterator(other) {} const_reverse_iterator& operator=(reverse_iterator &other) { this->_curNode = other._curNode; return *this; } }; iterator begin() { return iterator(this->_head); } const_iterator begin() const { return const_iterator(this->_head); } iterator end() { return iterator(this->_tail->next); } const_iterator end() const { return const_iterator(this->_tail->next); } reverse_iterator rbegin() { return reverse_iterator(this->_tail); } const_reverse_iterator rbegin() const { return const_reverse_iterator(this->_tail); } reverse_iterator rend() { return reverse_iterator(this->_head->prev); } const_reverse_iterator rend() const { return const_reverse_iterator(this->_head->prev); } ///////////////////////// //// CAPACITY //// ///////////////////////// bool empty() const; size_t size() const; size_t max_size() const; /////////////////////////////// //// ELEMENT ACCESS //// /////////////////////////////// reference back(); const_reference back() const; reference front(); const_reference front() const; ////////////////////////// //// MODIFIERS //// ////////////////////////// void assign(size_t, Type const&); template <class InputIterator> void assign(InputIterator, InputIterator, typename enable_if <!std::numeric_limits<InputIterator>::is_specialized>::type* = 0); void push_front (Type const&); void pop_front(); void push_back(Type const&); void pop_back(); iterator insert(iterator, Type const&); void insert(iterator, size_t, Type const&); template <class InputIterator> void insert(iterator, InputIterator, InputIterator, typename enable_if <!std::numeric_limits<InputIterator>::is_specialized>::type* = 0); iterator erase(iterator); iterator erase(iterator, iterator); void swap(list&); void resize(size_t, Type = value_type()); void clear(); /////////////////////////// //// OPERATIONS //// /////////////////////////// void splice(iterator, list&); void splice(iterator, list&, iterator); void splice(iterator, list&, iterator, iterator); void remove(const Type& val); template <class Predicate> void remove_if(Predicate pred); void unique(); template <class BinaryPredicate> void unique(BinaryPredicate binary_pred); void merge (list& x); template <class Compare> void merge(list& x, Compare comp); void reverse(); void sort(); template <class Compare> void sort(Compare comp); ////////////////////////// //// ALLOCATOR //// ////////////////////////// allocator_type get_allocator() const { return this->_allocatorType; } }; ///////////////////////////////////// //// NON-MEMBER FUNCTIONS //// ///////////////////////////////////// template <class Type, class Alloc> void swap(ft::list<Type,Alloc>& x, ft::list<Type,Alloc>& y); template <class Type, class Alloc> bool operator==(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs); template <class Type, class Alloc> bool operator!=(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs); template <class Type, class Alloc> bool operator<(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs); template <class Type, class Alloc> bool operator>(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs); template <class Type, class Alloc> bool operator<=(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs); template <class Type, class Alloc> bool operator>=(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs); } ///////////////////////////// //// CONSTRUCTORS //// ///////////////////////////// template <class Type, class Alloc> ft::list<Type, Alloc>::list(const allocator_type& alloc) : _allocatorType(alloc), _size(0){ this->_empty = this->_nodeAllocator.allocate(1); this->_nodeAllocator.construct(this->_empty, value_type()); this->_head = this->_empty; this->_tail = this->_empty; this->_head->next = this->_empty; this->_head->prev = this->_empty; this->_tail->prev = this->_empty; this->_tail->next = this->_empty; this->_empty->prev = this->_tail; this->_empty->next = this->_head; } template <class Type, class Alloc> ft::list<Type, Alloc>::list(size_type count, const Type& data, const allocator_type& alloc) : _allocatorType(alloc), _size(0) { this->_empty = this->_nodeAllocator.allocate(1); this->_nodeAllocator.construct(this->_empty, value_type()); this->_head = this->_empty; this->_tail = this->_empty; this->_head->next = this->_empty; this->_head->prev = this->_empty; this->_tail->prev = this->_empty; this->_tail->next = this->_empty; this->_empty->prev = this->_tail; this->_empty->next = this->_head; for (size_type i = 0; i < count; i++) this->push_back(data); } template <class Type, class Alloc> template <class InputIterator> ft::list<Type, Alloc>::list(InputIterator first, InputIterator last, const allocator_type& alloc, typename ft::list<Type, Alloc>::enable_if <!std::numeric_limits<InputIterator>::is_specialized>::type*) : _allocatorType(alloc), _size(0) { this->_empty = this->_nodeAllocator.allocate(1); this->_nodeAllocator.construct(this->_empty, value_type()); this->_head = this->_empty; this->_tail = this->_empty; this->_head->next = this->_empty; this->_head->prev = this->_empty; this->_tail->prev = this->_empty; this->_tail->next = this->_empty; this->_empty->prev = this->_tail; this->_empty->next = this->_head; for (; first != last; first++) { this->push_back(*first); } } template <class Type, class Alloc> ft::list<Type, Alloc>::list(list const &other) { *this = other; } template <class Type, class Alloc> ft::list<Type, Alloc>& ft::list<Type, Alloc>::operator=(list const& list) { this->clear(); this->insert(this->begin(), list.begin(), list.end()); this->_allocatorType = list._allocatorType; this->_nodeAllocator = list._nodeAllocator; return *this; } /////////////////////////// //// DESTRUCTOR //// /////////////////////////// template <class Type, class Alloc> ft::list<Type, Alloc>::~list() { clear(); this->_nodeAllocator.deallocate(this->_empty, 1); } ///////////////////////// //// CAPACITY //// ///////////////////////// template <class Type, class Alloc> bool ft::list<Type, Alloc>::empty() const { return this->_size == 0; } template <class Type, class Alloc> size_t ft::list<Type, Alloc>::size() const { return this->_size; } template <class Type, class Alloc> size_t ft::list<Type, Alloc>::max_size() const { return (std::numeric_limits<size_t>::max() / sizeof(this->_head)); } /////////////////////////////// //// ELEMENT ACCESS //// /////////////////////////////// template <class Type, class Alloc> typename ft::list<Type, Alloc>::reference ft::list<Type, Alloc>::back() { return this->_tail->getData(); } template <class Type, class Alloc> typename ft::list<Type, Alloc>::const_reference ft::list<Type, Alloc>::back() const{ return this->_tail->getData(); } template <class Type, class Alloc> typename ft::list<Type, Alloc>::reference ft::list<Type, Alloc>::front() { return this->_head->getData(); } template <class Type, class Alloc> typename ft::list<Type, Alloc>::const_reference ft::list<Type, Alloc>::front() const{ return this->_head->getData(); } ////////////////////////// //// MODIFIERS //// ////////////////////////// template <class Type, class Alloc> void ft::list<Type, Alloc>::assign(size_type count, Type const& value) { this->clear(); for (size_type i = 0; i < count; i++) { push_back(value); } } template <class Type, class Alloc> template <class InputIterator> void ft::list<Type, Alloc>::assign(InputIterator first, InputIterator last, typename enable_if <!std::numeric_limits<InputIterator>::is_specialized>::type*) { this->clear(); while (first != last) { push_back(*first); first++; } } template <class Type, class Alloc> void ft::list<Type, Alloc>::push_front(Type const &data) { insert(this->begin(), data); } template <class Type, class Alloc> void ft::list<Type, Alloc>::pop_front() { this->_size--; Node<Type>* tmp = this->_head->next; tmp->prev = this->_empty; this->_empty->next = tmp; this->_nodeAllocator.deallocate(this->_head, 1); this->_head = tmp; } template <class Type, class Alloc> void ft::list<Type, Alloc>::push_back(Type const &data) { insert(this->end(), data); } template <class Type, class Alloc> void ft::list<Type, Alloc>::pop_back() { this->_size--; Node<Type>* tmp = this->_tail->prev; tmp->next = this->_empty; this->_empty->prev = tmp; this->_nodeAllocator.deallocate(this->_tail, 1); this->_tail = tmp; } template <class Type, class Alloc> typename ft::list<Type, Alloc>::iterator ft::list<Type, Alloc>::insert(iterator position, Type const& data) { Node<Type>* newNode = this->_nodeAllocator.allocate(1); this->_nodeAllocator.construct(newNode, data); this->_size++; if (position == this->begin()) this->_head = newNode; if (position == this->end()) this->_tail = newNode; position._curNode->prev->next = newNode; newNode->prev = position._curNode->prev; position._curNode->prev = newNode; newNode->next = position._curNode; return iterator(newNode); } template <class Type, class Alloc> void ft::list<Type, Alloc>::insert(iterator position, size_type n, Type const& data) { for (size_type i = 0; i < n; i++) { position = this->insert(position, data); } } template <class Type, class Alloc> template <class InputIterator> void ft::list<Type, Alloc>::insert(iterator position, InputIterator first, InputIterator last, typename ft::list<Type, Alloc>::enable_if <!std::numeric_limits<InputIterator>::is_specialized>::type*) { while (first != last) { insert(position, *first); first++; } } template <class Type, class Alloc> typename ft::list<Type, Alloc>::iterator ft::list<Type, Alloc>::erase(iterator position) { if (position == this->end()) return this->end(); this->_size--; Node<Type> *nextNode = position._curNode->next; if (position == this->begin()) this->_head = nextNode; if (position == --this->end()) this->_tail = position._curNode->prev; position._curNode->prev->next = nextNode; nextNode->prev = position._curNode->prev; this->_nodeAllocator.deallocate(position._curNode, 1); return iterator(nextNode); } template <class Type, class Alloc> typename ft::list<Type, Alloc>::iterator ft::list<Type, Alloc>::erase(iterator first, iterator last) { iterator tmp; while (first != last) { first = erase(first); } return first; } template <class Type, class Alloc> void ft::list<Type, Alloc>::swap(list& x) { Node<Type> *tmpHead = x._head; Node<Type> *tmpTail = x._tail; Node<Type> *tmpEmpty = x._empty; size_type tmpSize = x._size; allocator_type tmpAT = x._allocatorType; std::allocator<Node<value_type> > tmpAlloc = x._nodeAllocator; x._head = this->_head; x._tail = this->_tail; x._empty = this->_empty; x._size = this->_size; x._allocatorType = this->_allocatorType; x._nodeAllocator = this->_nodeAllocator; this->_head = tmpHead; this->_tail = tmpTail; this->_empty = tmpEmpty; this->_size = tmpSize; this->_allocatorType = tmpAT; this->_nodeAllocator = tmpAlloc; } template <class Type, class Alloc> void ft::list<Type, Alloc>::resize(size_t n, Type data) { Node<Type> *tmpNode = this->_head; for (size_type i = 0; i < this->_size; i++) { if (i == n) { Node<Type>* tmp; this->_tail = tmpNode->prev; this->_tail->next = this->_empty; this->_empty->prev = tmpNode->prev; for (;this->_size != n; ) { this->_size--; tmp = tmpNode; tmpNode = tmpNode->next; this->_nodeAllocator.deallocate(tmp, 1); } return ; } tmpNode = tmpNode->next; } for (;this->_size < n; ) push_back(data); } template <class Type, class Alloc> void ft::list<Type, Alloc>::clear() { erase(this->begin(), this->end()); } /////////////////////////// //// OPERATIONS //// /////////////////////////// template <class Type, class Alloc> void ft::list<Type, Alloc>::splice(iterator position, list& x) { if (x._size == 0) return; this->_size += x._size; x._size = 0; if (position == this->begin()) this->_head = x._head; if (position == this->end()) this->_tail = x._tail; x._head->prev = position._curNode->prev; position._curNode->prev->next = x._head; x._tail->next = position._curNode; position._curNode->prev = x._tail; x._head = x._empty; x._tail = x._empty; x._head->next = x._empty; x._head->prev = x._empty; x._tail->next = x._empty; x._tail->prev = x._empty; } template <class Type, class Alloc> void ft::list<Type, Alloc>::splice(iterator position, list& x, iterator i) { if (x._size == 0) return; this->_size++; x._size--; if (position == this->begin()) this->_head = i._curNode; if (position == this->end()) this->_tail = i._curNode; if (i == --x.end()) x._tail = i._curNode->prev; if (i == x._head) x._head = i._curNode->next; i._curNode->prev->next = i._curNode->next; i._curNode->next->prev = i._curNode->prev; i._curNode->prev = position._curNode->prev; position._curNode->prev->next = i._curNode; i._curNode->next = position._curNode; position._curNode->prev = i._curNode; } template <class Type, class Alloc> void ft::list<Type, Alloc>::splice(iterator position, list& x, iterator first, iterator last) { if (first == last) return ; size_t len = 0; for (iterator tmpFirst = first; tmpFirst != last; tmpFirst++) len++; if (position == this->begin()) this->_head = first._curNode; if (position == this->end()) this->_tail = last._curNode->prev; if (last == x.end()) x._tail = first._curNode->prev; if (first == x._head) x._head = last._curNode; Node<Type> *prevNode = last._curNode->prev; first._curNode->prev->next = last._curNode; last._curNode->prev = first._curNode->prev; position._curNode->prev->next = first._curNode; first._curNode->prev = position._curNode->prev; position._curNode->prev = prevNode; prevNode->next = position._curNode; if (len > x._size) x._size = 0; else x._size -= len; this->_size += len; } template <class Type, class Alloc> void ft::list<Type, Alloc>::remove(const Type& val) { iterator ite = this->end(); iterator it = this->begin(); for (; it != ite; ) { if (*it == val) it = this->erase(it); else it++; } } template <class Type, class Alloc> template <class Predicate> void ft::list<Type, Alloc>::remove_if(Predicate pred) { for (iterator it = this->begin(); it != this->end(); ) { if (pred(*it)) it = erase(it); else it++; } } template <class Type, class Alloc> void ft::list<Type, Alloc>::unique() { iterator prev = this->begin(); for (iterator it = ++this->begin(); it != this->end();) { if (*it == *prev) it = this->erase(it); else { it++; prev++; } } } template <class Type, class Alloc> template <class BinaryPredicate> void ft::list<Type, Alloc>::unique(BinaryPredicate binary_pred) { iterator prev = this->begin(); for (iterator it = ++this->begin(); it != this->end();) { if (binary_pred(*prev, *it)) it = this->erase(it); else { it++; prev++; } } } template <class Type, class Alloc> void ft::list<Type, Alloc>::merge(list& x) { iterator it = this->begin(); if (x.empty()) return ; if (this->empty()) { splice(this->begin(), x); return ; } int n = this->_size; for (int i = 0; i < n; i++) { if (it._curNode->getData() > x._head->getData()) this->splice(it, x, x.begin()); else it++; } if (!x.empty()) this->splice(++it, x); } template <class Type, class Alloc> template <class Compare> void ft::list<Type, Alloc>::merge(list& x, Compare comp) { iterator it = this->begin(); if (x.empty()) return ; if (this->empty()) { splice(this->begin(), x); return ; } int n = this->_size; for (int i = 0; i < n; i++) { if (comp(x._head->getData(), it._curNode->getData())) this->splice(it, x, x.begin()); else it++; } if (!x.empty()) this->splice(++it, x); } template <class Type, class Alloc> void ft::list<Type, Alloc>::sort() { if (this->_size > 1) { ft::list<Type> *less = new ft::list<Type>; ft::list<Type> *more = new ft::list<Type>; Node<Type> *base = this->_head; Node<Type> *right = this->_head->next; for (Node<Type> *left = this->_tail->next; right != left;) { Node<Type> *tmp = right->next; if (right->getData() <= base->getData()) less->splice(less->end(), *this, iterator(right)); else more->splice(more->end(), *this, iterator(right)); right = tmp; } less->sort(); more->sort(); this->splice(this->begin(), *less); this->splice(this->end(), *more); delete less; delete more; } } template <class Type, class Alloc> template <class Compare> void ft::list<Type, Alloc>::sort(Compare comp) { if (this->_size > 1) { ft::list<Type> *less = new ft::list<Type>; ft::list<Type> *more = new ft::list<Type>; Node<Type> *base = this->_head; Node<Type> *right = this->_head->next; for (Node<Type> *left = this->_tail->next; right != left;) { Node<Type> *tmp = right->next; if (comp(right->getData(), base->getData())) less->splice(less->end(), *this, iterator(right)); else more->splice(more->end(), *this, iterator(right)); right = tmp; } less->sort(); more->sort(); this->splice(this->begin(), *less); this->splice(this->end(), *more); delete less; delete more; } } template <class Type, class Alloc> void ft::list<Type, Alloc>::reverse() { Node<Type> *tmpHead = this->_head; Node<Type> *tmpTail = this->_tail; Node<Type> *tmpNext; Node<Type> *tmpPrev; this->_head = tmpTail; this->_tail = tmpHead; for (size_t i = 0; i < this->_size / 2 - 1; i++) { tmpHead->next->prev = tmpTail; tmpTail->prev->next = tmpHead; tmpNext = tmpHead->next; tmpHead->next = tmpTail->next; tmpHead->next->prev = tmpHead; tmpTail->next = tmpNext; tmpNext->prev = tmpTail; tmpPrev = tmpHead->prev; tmpHead->prev = tmpTail->prev; tmpTail->prev = tmpPrev; tmpPrev->next = tmpTail; tmpNext = tmpHead; tmpHead = tmpTail->next; tmpTail = tmpNext->prev; } tmpHead->next = tmpTail->next; tmpHead->next->prev = tmpHead; tmpTail->prev = tmpHead->prev; tmpHead->prev->next = tmpTail; tmpTail->next = tmpHead; tmpHead->prev = tmpTail; } ///////////////////////////////////// //// NON-MEMBER FUNCTIONS //// ///////////////////////////////////// template <class Type, class Alloc> bool ft::operator==(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs) { if (lhs.size() != rhs.size()) return false; typename ft::list<Type,Alloc>::iterator lit = lhs.begin(); typename ft::list<Type,Alloc>:: iterator lite = lhs.end(); typename ft::list<Type,Alloc>::iterator rit = rhs.begin(); for (; lit != lite; lit++, rit++) { if (*lit != *rit) return false; } return true; } template <class Type, class Alloc> bool ft::operator!=(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs) { return !(lhs==rhs); } template <class Type, class Alloc> bool ft::operator<(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs) { typename ft::list<Type,Alloc>::iterator lit = lhs.begin(); typename ft::list<Type,Alloc>::iterator lite = lhs.end(); typename ft::list<Type,Alloc>::iterator rit = rhs.begin(); typename ft::list<Type,Alloc>::iterator rite = rhs.end(); for (; lit != lite; lit++, rit++) { if (*lit > *rit) return false; } return true; } template <class Type, class Alloc> bool ft::operator>(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs) { return !(lhs<rhs); } template <class Type, class Alloc> bool ft::operator<=(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs) { return !(lhs>rhs); } template <class Type, class Alloc> bool ft::operator>=(const ft::list<Type,Alloc>& lhs, const ft::list<Type,Alloc>& rhs) { return !(lhs<rhs); } template <class Type, class Alloc> void ft::swap(ft::list<Type,Alloc>& x, ft::list<Type,Alloc>& y) { x.swap(y); } #endif
true
8753d610f9ff6e26bf227caaf88c578b5de92b49
C++
SergeyGaluzov/Lab9
/Source.cpp
UTF-8
1,360
3.46875
3
[]
no_license
7. Із заданого рядка символів вилучити слова, довжина яких менша, за вказану користувачем. #include <iostream> #include <string> using namespace std; string input_string(); string changing_the_string(string str); void output_the_changed_string(string str_final); string input_string() { string str; cout << "Please, input the string: "; getline(cin, str); return str; } string changing_the_string(string str) { int n; cout << "Please, input the number (n) and the words, that have letters less than n will be removed from the string: "; cin >> n; string str_final, word; for (int i = 0; i < str.length(); i++) { if (str[i] != *(strpbrk(str.c_str(), " ,."))) { word += str[i]; } if (str[i] == *(strpbrk(str.c_str(), " ,.")) || (str[i] != *(strpbrk(str.c_str(), " ,.")) && (i == str.length() - 1))) { if (word.length() >= n) { str_final += word + " "; word = ""; } else { word = ""; } } } return str_final; } void output_the_changed_string(string str_final) { cout << "The changed string is: " << str_final << endl; } int main() { string str = input_string(); string str_final = changing_the_string(str); output_the_changed_string(str_final); system("pause"); }
true
787356d5dd24c80cabba07e3b0d399efedf204d0
C++
Jackiebarman/PnC_Lab_IT
/lab6.cpp
UTF-8
2,494
2.640625
3
[]
no_license
#include<bits/stdc++.h> #include<omp.h> using namespace std; int main() { ifstream ptr; int R,G,B,i; double Gray; ptr.open("KittenRGB.txt"); double t1,t2; vector<vector<int>> v; vector<int> m; int size=300*300; vector<double>Y(size,0),I(size,0),Q(size,0),Gr(size,0); for(int i=0;i<size;i++) { m.clear(); ptr>>R; ptr>>G; ptr>>B; m.push_back(R); m.push_back(G); m.push_back(B); v.push_back(m); } ptr.close(); printf("1.serial execution\n"); t1=omp_get_wtime(); for(i=0;i<size;i++) { Gr[i]=(v[i][0]*0.21+v[i][1]*0.72+v[i][2]*0.07); Y[i]=(0.299*v[i][0]+0.587*v[i][1] + 0.114*v[i][2]); I[i]=(0.596*v[i][0]-0.275*v[i][1]-0.321*v[i][2]); Q[i]=(0.212*v[i][0]-0.523*v[i][1]+0.311*v[i][2]); } t2=omp_get_wtime(); printf("Time taken =%lf s\n\n",t2-t1);printf("2.parallel execution with 2 thread\n"); t1=omp_get_wtime(); #pragma omp parallel num_threads(2) #pragma omp for private(i) schedule(guided,100) for(i=0;i<size;i++) { Gr[i]=(v[i][0]*0.21+v[i][1]*0.72+v[i][2]*0.07); Y[i]=(0.299*v[i][0]+0.587*v[i][1] + 0.114*v[i][2]); I[i]=(0.596*v[i][0]-0.275*v[i][1]-0.321*v[i][2]); Q[i]=(0.212*v[i][0]-0.523*v[i][1]+0.311*v[i][2]); } t2=omp_get_wtime(); printf("Time taken =%lf s\n\n",t2-t1); printf("3.parallel execution with 4 thread\n"); t1=omp_get_wtime(); #pragma omp parallel num_threads(4) #pragma omp for private(i) schedule(guided,100) for(i=0;i<size;i++) { Gr[i]=(v[i][0]*0.21+v[i][1]*0.72+v[i][2]*0.07); Y[i]=(0.299*v[i][0]+0.587*v[i][1] + 0.114*v[i][2]); I[i]=(0.596*v[i][0]-0.275*v[i][1]-0.321*v[i][2]); Q[i]=(0.212*v[i][0]-0.523*v[i][1]+0.311*v[i][2]); } t2=omp_get_wtime(); printf("Time taken =%lf s\n\n",t2-t1); printf("4.parallel execution with 8 thread\n"); t1=omp_get_wtime(); #pragma omp parallel num_threads(8) #pragma omp for private(i) schedule(guided,100) for(i=0;i<size;i++) { Gr[i]=(v[i][0]*0.21+v[i][1]*0.72+v[i][2]*0.07); Y[i]=(0.299*v[i][0]+0.587*v[i][1] + 0.114*v[i][2]); I[i]=(0.596*v[i][0]-0.275*v[i][1]-0.321*v[i][2]);Q[i]=(0.212*v[i][0]-0.523*v[i][1]+0.311*v[i][2]); } t2=omp_get_wtime(); printf("Time taken =%lf s\n\n",t2-t1); printf("5.parallel execution with 16 thread\n"); t1=omp_get_wtime(); #pragma omp parallel num_threads(16) #pragma omp for private(i) schedule(guided,100) for(i=0;i<size;i++) { Gr[i]=(v[i][0]*0.21+v[i][1]*0.72+v[i][2]*0.07); Y[i]=(0.299*v[i][0]+0.587*v[i][1] + 0.114*v[i][2]); I[i]=(0.596*v[i][0]-0.275*v[i][1]-0.321*v[i][2]); Q[i]=(0.212*v[i][0]-0.523*v[i][1]+0.311*v[i][2]); } t2=omp_get_wtime(); printf("Time taken =%lf s\n\n",t2-t1); return 0; }
true
f82fa25fb9bf1ac61990be6b24bfb3761232c7d1
C++
JangMiKyung/DX2_pf_ver_2
/Direct3D_14/Direct3D_14.v12.v12/cTerrain.cpp
UHC
4,605
2.765625
3
[]
no_license
#include "stdafx.h" #include "cTerrain.h" cTerrain::cTerrain() { } cTerrain::~cTerrain() { } //ʱȭ HRESULT cTerrain::Init(int vertexNum, float cellSize) { // this->nVerNumX = vertexNum; this->nVerNumZ = vertexNum; this->nTotalVerNum = this->nVerNumX * this->nVerNumZ; // this->nCellNumX = this->nVerNumX - 1; this->nCellNumZ = this->nVerNumZ - 1; this->nTotalCellNum = this->nCellNumX * this->nCellNumZ; // this->fCellScale = cellSize; // this->nTotalTri = this->nTotalCellNum * 2; //ͷ this->fTerrainSizeX = this->nCellNumX * cellSize; this->fTerrainSizeZ = this->nCellNumZ * cellSize; // // ͷ // // ġ . vertexPoses = new D3DXVECTOR3[nTotalVerNum]; // ϴ 0. 0. 0 ġ D3DXVECTOR3 startPos(0, 0, 0); for (int z = 0; z < this->nVerNumZ; z++) { for (int x = 0; x < this->nVerNumX; x++) { //ε int idx = z * this->nVerNumX + x; //ġ vertexPoses[idx].x = startPos.x + (x * fCellScale); vertexPoses[idx].z = startPos.z + (z * fCellScale); vertexPoses[idx].y = cos(x * 10 * ONE_RAD) * 3.0f; } } // // ε // pIndices = new TERRAININDEX[this->nTotalTri]; for (int z = 0; z < this->nCellNumZ; z++) { // int nowZ = z; int nextZ = z + 1; for (int x = 0; x < this->nCellNumX; x++) { // int nowX = x; int nextX = x + 1; // lt-----rt // | /| // | / | // | / | // | / | // |/ | // lb-----rb //𼭸 ε DWORD lt = nextZ * this->nVerNumX + nowX; DWORD rt = nextZ * this->nVerNumX + nextX; DWORD lb = nowZ * this->nVerNumX + nowX; DWORD rb = nowZ * this->nVerNumX + nextX; //Tri ε 迭 ε int idx = (z * this->nCellNumX + x) * 2; //Cell 1 //lb, lt, rt, pIndices[idx]._0 = lb; pIndices[idx]._1 = lt; pIndices[idx]._2 = rt; //Cell 1 //lb, rt, rb, pIndices[idx + 1]._0 = lb; pIndices[idx + 1]._1 = rt; pIndices[idx + 1]._2 = rb; } } // // ü // /* //Position vertElement[0].Stream = 0; //Stream 0 vertElement[0].Offset = 0; //޸ Byte 0 vertElement[0].Type = D3DDECLTYPE_FLOAT3; //ڷ Ÿ vertElement[0].Method = D3DDECLMETHOD_DEFAULT; //ϴ D3DDECLMETHOD_DEFAULT vertElement[0].Usage = D3DDECLUSAGE_POSITION; // Ÿ vertElement[0].UsageIndex = 0; //UsageIndex ϴ 0 */ D3DVERTEXELEMENT9 vertElement[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, D3DDECL_END() }; Device->CreateVertexDeclaration( vertElement, //տ D3DVERTEXELEMENT9 迭 &this->terrainDecl // LPDIRECT3DVERTEXDECLARATION9 ); // // ۸ . // if (FAILED(Device->CreateVertexBuffer( sizeof(TERRAINVERTEX) * this->nTotalVerNum, D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, &this->terrainVb, 0))) return E_FAIL; LPTERRAINVERTTEX pVertices = NULL; if (SUCCEEDED(this->terrainVb->Lock(0, 0, (void**)&pVertices, 0))) { for (int i = 0; i < this->nTotalVerNum; i++) { // ġ pVertices[i].pos = this->vertexPoses[i]; } this->terrainVb->Unlock(); } // // ε // if (FAILED(Device->CreateIndexBuffer( sizeof(TERRAININDEX) * this->nTotalTri, D3DUSAGE_WRITEONLY, D3DFMT_INDEX32, D3DPOOL_DEFAULT, &this->terrainIb, NULL))) return E_FAIL; void* pI = NULL; if (SUCCEEDED(this->terrainIb->Lock(0, 0, &pI, 0))) { memcpy(pI, this->pIndices, sizeof(TERRAININDEX) * this->nTotalTri); this->terrainIb->Unlock(); } return S_OK; } // void cTerrain::Release() { SAFE_DELETE_ARR(this->vertexPoses); SAFE_DELETE_ARR(this->pIndices); SAFE_RELEASE(this->terrainIb); SAFE_RELEASE(this->terrainVb); } // void cTerrain::Render() { Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); // ϴ ʱȭ D3DXMATRIXA16 matWorld; D3DXMatrixIdentity(&matWorld); Device->SetTransform(D3DTS_WORLD, &matWorld); Device->SetStreamSource(0, this->terrainVb, 0, sizeof(TERRAINVERTEX)); Device->SetIndices(this->terrainIb); Device->SetVertexDeclaration(this->terrainDecl); Device->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, this->nTotalVerNum, 0, this->nTotalTri); Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); }
true
35331da6c878399e1d965a57d52c079a239fa1a6
C++
likhitgarimella/OOPS-CPP
/CountInversion.cpp
UTF-8
794
4.1875
4
[]
no_license
// C++ Program to Count Inversion in an Array // The number of switches required to make an array sorted is termed as inversion count. // The time complexity is O(n^2). #include<iostream> using namespace std; int CountInversion(int a[], int n) { int i, j, count = 0; for(i = 0; i < n; i++) { for(j = i+1; j < n; j++) if(a[i] > a[j]) count++; } return count; } // Compare the values of the element with each other. int main() { int n, i; cout<<"\nEnter the number of data elements: "; cin>>n; int arr[n]; for(i = 0; i < n; i++) { cout<<"Enter element "<<i+1<<": "; cin>>arr[i]; } // Print the no. of inversions in the array. cout<<"\nThe number of inversions in the array: "<<CountInversion(arr, n); return 0; }
true
e2029f2e0bf6a25cc1331736d7964239bb897a40
C++
whysofar72/SOME-Projects
/C Lang/029/029/029.cpp
UTF-8
173
2.890625
3
[]
no_license
#include <stdio.h> int main() { int num1 = 10, num2 = 10; int a, b; a = ++num1; printf("%d, %d \n", a, num1); b = num2++; printf("%d, %d \n", b, num2); return 0; }
true
e717a3c6f915c7a93d6b3b1f37fe5469353f0c6b
C++
reshmasivakumar/CSE-342-Data-Structures-And_Algorithms-In-CPP
/ImageSegmentation/ImageSegmentation/PixelContainer.cpp
UTF-8
15,467
3.859375
4
[]
no_license
/* Program 4: PixelContainer.cpp Author: Reshma Maduri Sivakumar Design Due Date: 03/08/2017 Purpose: Purpose: This is a container class for storing a set of image pixels and additional support information related to the pixels such as the list size, seed pixel, count of all pixels RGB values (redpixelcount, greenpixelcount and bluepixelcount). The container class is implemented as linked list which has data members as - struct PixelNode { NodeData* data; // pointer to Node data(pixel) class PixelNode *next; } - head which is pointer of type PixelNode //head of the list - seed which is type pixel - size which int value to store the size of the list(container) - redPixelCount, greenPixelCount, bluePixelCount which are int values that store the pixel counts of all RGB color values in all the nodes of the list. The container class implements the following member operations: - constructor and copy constructor - overloaded operators =, ==, !=, << - destructor which deallocates the list - methods to create new node in the list and add an existing node to list - merge a given list to the list. - set and get the seed pixel - methods that returns the average of the RGB color values of all the pixels in the list. */ #include "ImageLib.h" #include "Image.h" #include "PixelContainer.h" #include "NodeData.h" #include <iostream> /* PixelContainer: Default Constructor that constructs a PixelContainer object with a dummy head node and other data members: seed and size set to default values. Precondition: Must be valid integer values for the data members, seed and size. Postcondition: A PixelContainer object is created with default values: 1) seed: The pixel's row, col, red, green and blue values are all set to 0. 2) size: Size is set to 0 as the list is still empty. 3) head: the head node is set to NULL. */ PixelContainer::PixelContainer() { head = new NodeData; head->setNext(NULL); this->size = 0; // To mark this as an unused seed this->seed = { 0,0,0 }; } /* PixelContainer: Copy constructor that calls the private function copy to construct a PixelContainer object with its data members copied from other PixelContainer object. The copy function traverses through the other list and copies the nodes to this list and thus creating a copy. Size is set to the size of other and the values for the seed pixel are copied from other. Precondition: Other should not be an empty list. Must have valid integer values for seed pixel. Postcondition: A PielContainer object is created with its data members copied */ PixelContainer::PixelContainer(const PixelContainer& other) { this->size = 0; copy(other); } /* Operator= : The assignment constructor is overloaded to copy all the nodes other data members of other to this object. It does so by checking for self assignment and if not, calls deleteContainer() to delete the pre existing container in this linkedlist (if any) and calls copy() to copy all the nodes to this. Then, it copies all the values from seed pixel of other object to the seed pixel of this object. Precondition: Other should have valid values for its data members. PostCondition: Operator return *this if the opeator is called on this object. Otherwise, calls deleteContainer() to delete the contents of this list and copies the linkedlist and seed pixel from other to this object. */ PixelContainer& PixelContainer::operator=(const PixelContainer& other) { if (*this != other) { deleteContainer(); copy(other); } return *this; } /* Operator<<: The cout operator is overloaded to print the following to the console: The total size of the list and the average color values of the pixel group. Precondition: Valid values for the data members in other object. Postcondition: Prints to console the other object's seed pixel's row and column, the total size of the other object's list and the average color values of the pixel group. */ ostream& operator<<(ostream& out, const PixelContainer& other) { cout << "Number of pixels " << other.getSize() << endl; cout << "Average Red color " << other.getRedAverageColor() << endl; cout << "Average Blue color " << other.getBlueAverageColor() << endl; cout << "Average Green color " << other.getGreenAverageColor() << endl; int avgColor = other.getRedAverageColor() + other.getBlueAverageColor() + other.getGreenAverageColor(); cout << "Average color " << avgColor << endl; return out; } /* Operator==: The equal to operator is overloaded to check if all the data members of this object is equal that in other object. The operator traverses through the other's list and checks if ' every single node is equal to the list in this object. The function also checks if the the other seed pixel's row, col and RGB values are similiar to this object's seed pixel. Precondition: Valid values for the other objects data members. Postcondition: Returns true of both objects are equal. Returns false if not. */ bool PixelContainer::operator==(const PixelContainer& other)const{ if (this->size != other.size) return false; if (this->size == 0 && other.size == 0) return true; if (this->size == 0 || other.size == 0) return false; if (this->seed.blue != other.getSeed().blue || this->seed.red != other.getSeed().red || this->seed.green != other.getSeed().green ) return false; if (this->getRedAverageColor() != other.getRedAverageColor() || this->getGreenAverageColor() != other.getGreenAverageColor() || this->getBlueAverageColor() != other.getBlueAverageColor()) return false; else { NodeData *current = head; NodeData *otherCurrent = other.head; while (current != NULL) { if (current != otherCurrent) return false; current = current->getNext(); otherCurrent = otherCurrent->getNext(); } delete current; delete otherCurrent; current = NULL; otherCurrent = NULL; return true; } } /* Operator!=: The not equal to operator is overloaded to call the operator== and return the !(not). Precondition: Valid values for the other objects data members. Postcondition: Returns true if both the objects are not equal, and false if they are. */ bool PixelContainer::operator!=(const PixelContainer& other)const { return !(*this == other); } /* createPixelNode: The createPixelNode() creates a new node and sets its data to the the other pixel object and adds the node to this object's linkedlist. The new node is added to the begining of the list and hence the head is set to this newly created node. The method also increments the redPixelCount, greenPixelCount and bluePixelCount when each node is added. The size of the linked list increments by one when each node is added. Precondition: The pixel object cannot be NULL and valid integer data for row and col. Postcondition: A new node is created and added to this linkedlist. Head is set to the newly created node. The size is incremented by 1 and sums the redPixelCount, bluePixelCount and greenPixelCount. */ void PixelContainer::createPixelNode(const pixel& other, int row, int col) { NodeData* newNode = new NodeData(); int red = other.red; int blue = other.blue; int green = other.green; pixel newPixel = { red, green, blue }; newNode->setData(newPixel, row, col); if (this->head == nullptr) { head = newNode; head->setNext(NULL); this->size=1; } else { newNode->setNext( this->head); this->head = newNode; this->size++; } this->redPixelCount += other.red; this->greenPixelCount += other.green; this->bluePixelCount += other.blue; } /* addPixelNode: This method creates a new node and copies the rgb values and the row and col from the other pixelNode and computes the sum of redPixelCount, greenPixelCount and bluePixelCount. This new node is added to the beginning of the list. Precondition: other cannot be null and must have valid values for row and col. Postcondition: A new pixel node is created with values copied from other and is added to the begininng of this list. The size and redPixelCount, bluePixelCount and greenPixelCount values are updated. */ void PixelContainer::addPixelNode(const NodeData* other) { //cout << "Inside addPixelNode" << endl; if (other ==nullptr ) return; NodeData* newNode = new NodeData; //get data of other node pixel newPixel = other->getNodeData(); int row = other->getRow(); int col = other->getCol(); //create instance of newNodeData NodeData* newNodeData = new NodeData(); newNodeData->setData(newPixel, row, col); newNode = newNodeData; //set new node to head if first node if (this->getSize() == 0) { head = newNode; newNode->setNext(NULL); } else { //add node to list with next as head newNode->setNext(this->head); this->head = newNode; } this->size++; //increment pixelcounts this->redPixelCount += other->getRedPixel(); this->greenPixelCount += other->getGreenPixel(); this->bluePixelCount += other->getBluePixel(); } /* setSeed(): Setter method that sets otherSeed pixel to this seed pixel and all the RGB values, rows and cols are also set. Precondition: The passed pixel cannot be NULL and must have valid values for the RGB values and the row and col. Postcondition: Sets the seed pixel to otherSeed. */ void PixelContainer::setSeed(const pixel& otherSeed) { this->seed = otherSeed; } /* getSize: getSize returns the size of this pixel group (linkedlist). Precondition: None. PostCondition: Returns the value of this->size. */ int PixelContainer::getSize() const { return this->size; } /* getSeed: getSeed returns the seed pixel of this object. Precondition: None. PostCondition: Returns the value of this->seed. */ pixel PixelContainer::getSeed() const { return this->seed; } /* getRedAverageColor: getRedAverageColor computes the average of red pixel color by dividing the redPixelCount instance variable by size of the pixel group. Precondition: Size cannot be zero as it will result in divide by zero error. PostCondition: Computes and returns the average red pixel color value. */ int PixelContainer::getRedAverageColor() const { int averageRed = redPixelCount / size; return averageRed; } /* getBlueAverageColor: getBlueAverageColor computes the average of blue pixel color by dividing the bluePixelCount instance variable by size of the pixel group. Precondition: Size cannot be zero as it will result in divide by zero error. PostCondition: Computes and returns the average blue pixel color value. */ int PixelContainer::getBlueAverageColor() const { int averageBlue = bluePixelCount / size; return averageBlue; } /* getGreenAverageColor: getGreenAverageColor computes the average of green pixel color by dividing the greenPixelCount instance variable by size of the pixel group. Precondition: Size cannot be zero as it will result in divide by zero error. PostCondition: Computes and returns the average green pixel color value. */ int PixelContainer::getGreenAverageColor() const { int averageGreen = greenPixelCount / size; return averageGreen; } /* merge: The merge method adds the nodes from other object's list by calling the addPixelNode method and merges the other objects list to this. Preconditions: Both lists cannot be empty and cannot merge itself. Poatconditions: All the nodes from other is added to the end of this list. The size and the redPixelCount, bluePixelCount and greenPixelCount sums are updated to this. */ void PixelContainer::merge(const PixelContainer& other) { if (this->size == 0 && other.size == 0) { cout << "Error: Both lists are empty. No action" << endl; return; } if (this->size == 0) { copy(other); } else { NodeData* current = other.head; while (current != NULL) { addPixelNode(current); current = current->getNext(); } } //cout << "leaving merge " << endl; } /* deleteContainer(): The delete container method traverses through this list and deletes every node until the list is empty. Precondition: List cannot be null Postcondition: Safely deletes the nodes in this linked list. */ void PixelContainer::deleteContainer() { if (this->size == 0) return; NodeData *current = this->head; while (current != NULL) { head = head->getNext(); delete current; current = head; } delete current; current = NULL; size = 0; seed.blue = 0; seed.green = 0; seed.red = 0; redPixelCount = 0; greenPixelCount = 0; bluePixelCount = 0; } /* Copy: The private copy method calls addPixelNode to copy the contents of other objects likedlist to this. Te addPixelNode method increments the size of the list and the redPixelCount, bluePixelCount and greenPixelCount values. Precondition: Cannot be an empty list and cannot copy if the method is called on itself. Postcondition: All the nodes from other object is copied to this and the method jsut returns and does nothing if the copy method is called on itself. */ void PixelContainer::copy(const PixelContainer& other) { if (other.size == 0) { cout << "List passed is empty!" << endl; return; } if (this == &other) // if trying to copy same lists return; NodeData *current = other.head; while (current != NULL) { addPixelNode(current); current = current->getNext(); } } /* getNextData(): This method is used to get pixel data the head points to, and the row and col stored with the data. The head is set to point to next. The method takes the pixel variable and row and col as reference input variables and returns the pixel data of the head node. The head read of the list and head is set to next node Precondition: Three valid reference variables to return back the color pixel values of red, ble and green pixels and int reference variables for row and col Postcondition: The head node is read from the list and the pixel data in the head node is returned . The input reference variables are set to the row and col stored with the pixel data in the head node. */ void PixelContainer::getNextData(pixel& pixel, int& row, int& col) { NodeData *current = head; if (current != NULL) { pixel = current->getNodeData(); row = current->getRow(); col = current->getCol(); head = current->getNext(); } current = NULL; } /* ~PixelContainer: Destructor that calls deletContainer() to safely delete this linked list and deletes the head node. Precondition: None. Postcondition: All the nodes in this linked list are deleted and this->head is also deleted. */ PixelContainer::~PixelContainer() { deleteContainer(); }
true
40e7efae453b0590f13dc0c5e28bbde1de3cf7e4
C++
stephen-soul/CPP-Code-Samples
/phonebook/programState.cpp
UTF-8
2,096
3.140625
3
[]
no_license
/*Stephen Fetinko 2018*/ #include "programState.h" state::state() { programRunning = true; mainMenuActive = true; askingForName = true; askingForNumber = false; askingForEditedSpot = true; askingForEditedName = false; askingForEditedNumber = false; } state::~state() = default; /* All of the below functions exist to manipulate the state of the program through bools */ bool state::changeMainMenuState() { if(mainMenuActive) mainMenuActive = false; else mainMenuActive = true; } bool state::changeProgramRunningState() { if(programRunning) programRunning = false; else programRunning = true; } bool state::changeNameState() { if(askingForName) askingForName = false; else askingForName = true; } bool state::changeNumberState() { if(askingForNumber) askingForNumber = false; else askingForNumber = true; } bool state::changeDeleteNumberState() { if(askingForDeleteNumber) askingForDeleteNumber = false; else askingForDeleteNumber = true; } bool state::changeEditingSpotState() { if(askingForEditedSpot) askingForEditedSpot = false; else askingForEditedSpot = true; } bool state::changeEditingNameState() { if(askingForEditedName) askingForEditedName = false; else askingForEditedName = true; } bool state::changeEditingNumberState() { if(askingForEditedNumber) askingForEditedNumber = false; else askingForEditedNumber = true; } bool state::isMainMenuActive() { return mainMenuActive; } bool state::isProgramRunning() { return programRunning; } bool state::isNameActive() { return askingForName; } bool state::isNumberActive() { return askingForNumber; } bool state::isDeleteNumberActive() { return askingForDeleteNumber; } bool state::isEditingSpotActive() { return askingForEditedSpot; } bool state::isEditingNameActive() { return askingForEditedName; } bool state::isEditingNumberActive() { return askingForEditedNumber; }
true
d391242483f47b73d8398137d98d9b1a755f2699
C++
Deep9110/coders-archive
/DSA/Beginner level FAQ/day1.cpp
UTF-8
251
2.703125
3
[]
no_license
#include<iostream> using namespace std; int main(){ int i = 12; float f = 4.0f; string s = "hackerRank "; cout<<i + 4<<endl; cout<<f + 4.0<<endl; cout<<s<<"is the best place to learn and practice coding!"<<endl; return 0; }
true
ec46c47bc6208de7722cdfb84eb908678e7b4f79
C++
Angelos-89/membrane_project
/src/Vec3dLib.cpp
UTF-8
792
3.515625
4
[]
no_license
#include <iostream> #include <cmath> #include "Vec3dLib.hpp" double Dot(const Vec3d& v, const Vec3d& w) { return v.X()*w.X() + v.Y()*w.Y() + v.Z()*w.Z(); } Vec3d Cross(const Vec3d& v, const Vec3d& w) { return {v.Y()*w.Z()-v.Z()*w.Y(), v.Z()*w.X()-v.X()*w.Z(), v.X()*w.Y()-v.Y()*w.X()}; } double Square(const Vec3d& vec1) { return Dot(vec1,vec1); } double Norm(const Vec3d& vec1) { return sqrt(Dot(vec1,vec1)); } Vec3d Normalize(const Vec3d& v, double magnitude) { if (magnitude == 0) { std::cout << "Division with zero! Vector cannot be normalized." << std::endl; return v; } else { return {v.X()/magnitude, v.Y()/magnitude, v.Z()/magnitude}; } } double Distance(Vec3d& v, Vec3d& w) { Vec3d diff = v-w; return Norm(diff); }
true
daf7adc0fb03ed28ade5b1d30b53b7dc6de00032
C++
gbakkk5951/OI
/__history/17.8/cdvs1038牛顿法标程.cpp
UTF-8
656
2.578125
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const double eps=1e-3; double a,b,c,d; inline double f(double x){return ((a*x+b)*x+c)*x+d;} inline double df(double x){return (3*a*x+2*b)*x+c;} double sol(double l,double r){//printf("sol %lf %lf\n",l,r); int step=20;double x=0; while(step--){ x=x-f(x)/df(x); } return x; } int main(int argc, const char * argv[]) { scanf("%lf%lf%lf%lf",&a,&b,&c,&d); double p1=(-sqrt(b*b-3*a*c)-b)/(3*a), p2=(+sqrt(b*b-3*a*c)-b)/(3*a); printf("%.2f %.2f %.2f\n",sol(-100,p1),sol(p1,p2),sol(p2,100)); return 0; }
true
52628e06af15d49cfe3dd150bf52fad62ddc9746
C++
joss185/PECUS
/simple_test/simple_test/simple_test.ino
UTF-8
2,704
2.84375
3
[]
no_license
#include <SoftwareSerial.h> #include <TinyGPS.h> /* This sample code demonstrates the normal use of a TinyGPS object. It requires the use of SoftwareSerial, and aSerial3umes that you have a 4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx). */ TinyGPS gps; //SoftwareSerial Serial3(4, 3); void setup() { Serial.begin(9600); Serial3.begin(9600); Serial.print("Simple TinyGPS library v. "); Serial.println(TinyGPS::library_version()); Serial.println("by Mikal Hart"); Serial.println(); } void loop() { bool newData = false; unsigned long chars; unsigned short sentences, failed; // For one second we parse GPS data and report some key values for (unsigned long start = millis(); millis() - start < 1000;) { while (Serial3.available()) { char c = Serial3.read(); // Serial.write(c); // uncomment this line if you want to see the GPS data flowing if (gps.encode(c)) // Did a new valid sentence come in? newData = true; } } if (newData) { float flat, flon; unsigned long age; gps.f_get_position(&flat, &flon, &age); Serial.print("LAT="); Serial.print(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6); Serial.print(" LON="); Serial.print(flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6); print_date(gps); Serial.print(" SAT="); Serial.print(gps.satellites() == TinyGPS::GPS_INVALID_SATELLITES ? 0 : gps.satellites()); Serial.print(" PREC="); Serial.print(gps.hdop() == TinyGPS::GPS_INVALID_HDOP ? 0 : gps.hdop()); } gps.stats(&chars, &sentences, &failed); Serial.print(" CHARS="); Serial.print(chars); Serial.print(" SENTENCES="); Serial.print(sentences); Serial.print(" CSUM ERR="); Serial.println(failed); if (chars == 0) Serial.println("** No characters received from GPS: check wiring **"); } static void print_date(TinyGPS &gps) { int year; byte month, day, hour, minute, second, hundredths; unsigned long age; gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age); if (age == TinyGPS::GPS_INVALID_AGE) Serial.print(" ********** ******** "); else { char sz[32]; sprintf(sz, " %02d/%02d/%02d %02d:%02d:%02d ", month, day, year, hour, minute, second); Serial.print(sz); } print_int(age, TinyGPS::GPS_INVALID_AGE, 5); //smartdelay(0); } static void print_int(unsigned long val, unsigned long invalid, int len) { char sz[32]; if (val == invalid) strcpy(sz, " *******"); else sprintf(sz, " %ld", val); sz[len] = 0; for (int i=strlen(sz); i<len; ++i) sz[i] = ' '; if (len > 0) sz[len-1] = ' '; Serial.print(sz); // smartdelay(0); }
true
ca660a98f15dd1238e481567ea788a1164b712eb
C++
garyhubley/ProjectEuler
/src/problem032.cpp
UTF-8
1,457
3.265625
3
[]
no_license
/* * File: Problem032.cpp * Author: Gary Hubley * Company: Self * Description: * We shall say that an n-digit number is pandigital if it makes use of all * the digits 1 to n exactly once; for example, the 5-digit number, 15234, is * 1 through 5 pandigital. * * The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing * multiplicand, multiplier, and product is 1 through 9 pandigital. * * Find the sum of all products whose multiplicand/multiplier/product * identity can be written as a 1 through 9 pandigital. * * HINT: Some products can be obtained in more than one way so be sure to * only include it once in your sum. */ #include "EulerLib.h" #include <iostream> #include <chrono> typedef std::chrono::high_resolution_clock Clock; #define ToSeconds(x) (std::chrono::duration_cast<std::chrono::seconds>(x)) #define ToMilliSeconds(x) (std::chrono::duration_cast<std::chrono::milliseconds>(x)) #define ToMicroSeconds(x) (std::chrono::duration_cast<std::chrono::microseconds>(x)) void problem032() { auto start = Clock::now(); auto end = Clock::now(); std::cout << "Answer: " << std::endl; std::cout << "Time: " << std::endl; std::cout << " Seconds" << ToSeconds(end - start).count() << std::endl; std::cout << " Milliseconds" << ToMilliSeconds(end - start).count() << std::endl; std::cout << " Microseconds" << ToMicroSeconds(end - start).count() << std::endl; }
true
0b8c8eeca08e5b50d80c5105d2b1a5c030b3b82a
C++
jack-maber/bsc-live-coding
/COMP220/COMP220_Examples/15_Camera/main.cpp
UTF-8
17,762
2.71875
3
[]
no_license
//main.cpp - defines the entry point of the application #include "main.h" #pragma region "Initilisation" int main(int argc, char* args[]) { //Initialises the SDL Library, passing in SDL_INIT_VIDEO to only initialise the video subsystems //https://wiki.libsdl.org/SDL_Init if (SDL_Init(SDL_INIT_VIDEO) < 0) { //Display an error message box //https://wiki.libsdl.org/SDL_ShowSimpleMessageBox SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, SDL_GetError(), "SDL_Init failed", NULL); return 1; } //Create an SDL2 Window //https://wiki.libsdl.org/SDL_CreateWindow SDL_Window* window = SDL_CreateWindow("SDL2 Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 640, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); //Checks to see if the window has been created, the pointer will have a value of some kind if (window == nullptr) { //Shows error if creation of Window Fails SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, SDL_GetError(), "SDL_CreateWindow failed", NULL); //Close the SDL Library //https://wiki.libsdl.org/SDL_Quit SDL_Quit(); return 1; } //Gets 3.2 version of OPENGL SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); //SDL Context/Window is created here SDL_GLContext GL_Context = SDL_GL_CreateContext(window); if (GL_Context == nullptr) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, SDL_GetError(), "SDL GL Create Context failed", NULL); SDL_DestroyWindow(window); SDL_Quit(); return 1; } //Initialize GLEW glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, (char*)glewGetErrorString(glewError), "GLEW Init Failed", NULL); } #pragma endregion #pragma region "Variables" //Sets Up camera variables vec3 cameraPosition = vec3(10.0f, 0.0f, 0.0f); vec3 cameraTarget = vec3(0.0f, 0.0f, 0.0f); vec3 cameraUp = vec3(0.0f, 1.0f, 0.0f); vec3 cameraDirection = vec3(0.0f); vec3 FPScameraPos = vec3(0.0f); float CameraX = 0.0f; float CameraY = 0.0f; float CameraDistance = (float)(cameraTarget - cameraPosition).length(); //Sets Matrixes for Camera mat4 viewMatrix = lookAt(cameraPosition, cameraTarget, cameraUp); mat4 projectionMatrix = perspective(radians(90.0f), float(800 / 600), 0.1f, 100.0f); //Light Variables vec4 ambientLightColour = vec4(1.0f, 1.0f, 1.0f, 1.0f); vec3 lightDirection = vec3(0.0f, 0.0f, -5.0f); vec4 diffuseLightColour = vec4(2.0f, 2.0f, 2.0f, 2.0f); vec4 specularLightColour = vec4(2.0f, 2.0f, 2.0f, 2.0f); #pragma endregion #pragma region "GameObjects" //Creates ObjectList for desired Rendered Objects to reside in std::vector<GameObject*> gameObjectList; //Create GameObjects GameObject * pCar = new GameObject(); pCar->setPosition(vec3(0.5f, 0.0f, 0.0f)); pCar->loadMeshesFromFile("armoredrecon.fbx"); pCar->loadDiffuseTextureFromFile("armoredrecon_diff.png"); pCar->loadShaderProgram("textureVert.glsl", "textureFrag.glsl"); gameObjectList.push_back(pCar); GameObject * Tank1 = new GameObject(); Tank1->setPosition(vec3(-5.0f, 0.0f, 0.0f)); Tank1->loadMeshesFromFile("Tank1.FBX"); Tank1->loadDiffuseTextureFromFile("Tank1DF.png"); Tank1->loadShaderProgram("lightingVert.glsl", "lightingFrag.glsl"); Tank1->setRotation(vec3(0.0f, 1.6f, 0.0f)); gameObjectList.push_back(Tank1); #pragma endregion #pragma region Buffer and Screen Declerations //Colour Buffer Texture GLuint colourBufferID = createTexture(800, 640); //Create Depth Buffer GLuint depthRenderBufferID; glGenRenderbuffers(1, &depthRenderBufferID); glBindRenderbuffer(GL_RENDERBUFFER, depthRenderBufferID); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, 800, 640); //Create Framebuffer GLuint frameBufferID; glGenFramebuffers(1, &frameBufferID); glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderBufferID); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colourBufferID, 0); //Error checking for Frame Buffer for PP if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to create frame buffer for post processing", "Frame Buffer Error", NULL); } //Create Screen Sized Texture for Post Processing GLfloat screenVerts[] = { -1, -1, 1, -1, -1, 1, 1, 1 }; //Creates Screen Quad for PP GLuint screenQuadVBOID; glGenBuffers(1, &screenQuadVBOID); glBindBuffer(GL_ARRAY_BUFFER, screenQuadVBOID); glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), screenVerts, GL_STATIC_DRAW); //Creates Vertex Array for PP GLuint screenVAO; glGenVertexArrays(1, &screenVAO); glBindVertexArray(screenVAO); glBindBuffer(GL_ARRAY_BUFFER, screenQuadVBOID); //Enable Vertex Array glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL); //Loads Post Proccesing Shaders and Texture it is loaded onto GLuint postProcessingProgramID = LoadShaders("passThroughVert.glsl", "postBlackAndWhite.glsl"); GLint texture0Location = glGetUniformLocation(postProcessingProgramID, "texture0"); #pragma endregion #pragma region Physics //Initalise Bullet ///collision configuration contains default setup for memory, collision setup. Advanced users can create their own configuration. btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration(); ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded) btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration); ///btDbvtBroadphase is a good general purpose broadphase. You can also try out btAxis3Sweep. btBroadphaseInterface* overlappingPairCache = new btDbvtBroadphase(); ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded) btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver; btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration); //Sets dynamicsWorld->setGravity(btVector3(0, -2, 0)); //Creates Floor btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(50.), btScalar(2.), btScalar(50.))); btTransform groundTransform; groundTransform.setIdentity(); groundTransform.setOrigin(btVector3(0, -10, 0)); //Having Zero Mass means the object will not move when hit btScalar mass(0.); btVector3 localInertia(0, 0, 0); //using motionstate is optional, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform); //Constructs Rigidbody on info passed btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, groundShape, localInertia); btRigidBody* GroundRigidbody = new btRigidBody(rbInfo); //add the body to the dynamics world, dynamicworld holds all the simulations dynamicsWorld->addRigidBody(GroundRigidbody); //Creates Hitbox for Car btCollisionShape* carCollisionShape = new btBoxShape(btVector3(2, 2, 2)); //Sets car position to current Model position for Physics glm::vec3 carPosition = pCar->getPosition(); /// Create Dynamic Objects btTransform carTransform; carTransform.setIdentity(); //Sets hitbox position to same as the model location in the world space carTransform.setOrigin(btVector3(carPosition.x, carPosition.y, carPosition.z)); btVector3 carInertia(0, 0, 0); btScalar carMass(0.7f); carCollisionShape->calculateLocalInertia(carMass, carInertia); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* carMotionState = new btDefaultMotionState(carTransform); btRigidBody::btRigidBodyConstructionInfo carRbInfo(carMass, carMotionState, carCollisionShape, carInertia); btRigidBody* carRigidbody = new btRigidBody(carRbInfo); carRigidbody->setActivationState(DISABLE_DEACTIVATION); //Adds Car Ridgidbody to Dynamicworld dynamicsWorld->addRigidBody(carRigidbody); //Sets Impulse Direction int InvertGravity = -10; pCar->SetRigidbody(carRigidbody); pCar->SetCollision(carCollisionShape); #pragma endregion #pragma region Raycast //Raycast code comes from :http://www.opengl-tutorial.org/miscellaneous/clicking-on-objects/picking-with-a-physics-library/ // The ray Start and End positions, in Normalized Device Coordinates (Have you read Tutorial 4 ?) glm::vec4 lRayStart_NDC( ((float)CameraX / (float)640 - 0.5f) * 2.0f, // [0,1024] -> [-1,1] ((float)CameraY / (float)800 - 0.5f) * 2.0f, // [0, 768] -> [-1,1] -1.0, // The near plane maps to Z=-1 in Normalized Device Coordinates 1.0f ); glm::vec4 lRayEnd_NDC( ((float)CameraX / (float)640 - 0.5f) * 2.0f, ((float)CameraY / (float)800 - 0.5f) * 2.0f, 0.0, 1.0f ); // The Projection matrix goes from Camera Space to NDC. // So inverse(ProjectionMatrix) goes from NDC to Camera Space. glm::mat4 InverseProjectionMatrix = glm::inverse(projectionMatrix); // The View Matrix goes from World Space to Camera Space. // So inverse(ViewMatrix) goes from Camera Space to World Space. glm::mat4 InverseViewMatrix = glm::inverse(viewMatrix); glm::vec4 lRayStart_camera = InverseProjectionMatrix * lRayStart_NDC; lRayStart_camera /= lRayStart_camera.w; glm::vec4 lRayStart_world = InverseViewMatrix * lRayStart_camera; lRayStart_world /= lRayStart_world.w; glm::vec4 lRayEnd_camera = InverseProjectionMatrix * lRayEnd_NDC; lRayEnd_camera /= lRayEnd_camera.w; glm::vec4 lRayEnd_world = InverseViewMatrix * lRayEnd_camera; lRayEnd_world /= lRayEnd_world.w; glm::vec3 lRayDir_world(lRayEnd_world - lRayStart_world); lRayDir_world = glm::normalize(lRayDir_world); #pragma endregion //Locks cursor to OPENGL screen SDL_SetRelativeMouseMode(SDL_bool(SDL_ENABLE)); //Timing Declarations int lastTicks = SDL_GetTicks(); int currentTicks = SDL_GetTicks(); //Event loop, we will loop until running is set to false, usually if escape has been pressed or window is closed bool running = true; //SDL Event structure, this will be checked in the while loop SDL_Event ev; while (running) { //Poll for the events which have happened in this frame //https://wiki.libsdl.org/SDL_PollEvent while (SDL_PollEvent(&ev)) { //Switch case for every message we are intereted in switch (ev.type) { //QUIT Message, usually called when the window has been closed case SDL_QUIT: running = false; break; case SDL_MOUSEMOTION: // Get Mouse Direction CameraX += ev.motion.xrel / 200.0f; CameraY += -ev.motion.yrel / 200.0f; // Limits Camera View if (CameraY > 150.0f) CameraY = 150.0f; else if (CameraY < -150.0f) CameraY = -150.0f; // Calculate camera target cameraTarget = cameraPosition + CameraDistance * vec3(cos(CameraX), tan(CameraY), sin(CameraX)); // Normalises Camera Direction cameraDirection = normalize(cameraTarget - cameraPosition); break; //KEYDOWN Message, called when a key has been pressed down case SDL_KEYDOWN: //Check the actual key code of the key that has been pressed switch (ev.key.keysym.sym) { // Keys case SDLK_ESCAPE: running = false; break; //Camera Movement Keys case SDLK_w: FPScameraPos = cameraDirection * 0.2f; break; case SDLK_s: FPScameraPos = -cameraDirection * 0.2f; break; case SDLK_a: FPScameraPos = -cross(cameraDirection, cameraUp) * 0.5f; break; case SDLK_d: FPScameraPos = cross(cameraDirection, cameraUp) * 0.5f; break; case SDLK_RIGHT: //Apply an impulse to car carRigidbody->applyCentralForce(btVector3(-5, 0, 0) * 50); break; case SDLK_LEFT: //Apply an impulse to car in key direction carRigidbody->applyCentralForce(btVector3(5, 0, 0) * 50); break; case SDLK_UP: //Apply an impulse to car in key direction carRigidbody->applyCentralForce(btVector3(0, 5, 0) * 50); break; case SDLK_DOWN: //Apply an impulse to car in key direction carRigidbody->applyCentralForce(btVector3(0, -5, 0) * 50); break; case SDLK_SPACE: //Invert gravity in simulation InvertGravity *= -1; dynamicsWorld->setGravity(btVector3(0.0, InvertGravity, 0.0)); break; //Changes post proccesing effects case SDLK_p: pCar->loadShaderProgram("passThroughVert.glsl", "postBlackAndWhite.glsl"); break; //Changes post proccesing effects case SDLK_o: pCar->loadShaderProgram("textureVert.glsl", "textureFrag.glsl"); break; case SDLK_LCTRL: //Raycast Controls glm::vec3 out_direction = cameraTarget - cameraPosition; out_direction = glm::normalize(out_direction); glm::vec3 out_end = cameraPosition + out_direction*1000.0f; //Declares Raycast position btCollisionWorld::ClosestRayResultCallback RayCallback( btVector3(cameraPosition.x, cameraPosition.y, cameraPosition.z), btVector3(out_end.x, out_end.y, out_end.z) ); //Calls back position of object dynamicsWorld->rayTest( btVector3(cameraPosition.x, cameraPosition.y, cameraPosition.z), btVector3(out_end.x, out_end.y, out_end.z), RayCallback ); //If raycast hits a physics object it's user pointer is printed to window if (RayCallback.hasHit()) { printf("Hit Mesh %i", (int)RayCallback.m_collisionObject->getUserPointer()); } //And if not returns a not hit message else { printf("Not Hit"); } break; } //Updates Camera Position cameraPosition += FPScameraPos; cameraTarget += FPScameraPos; } } //Gets Tick and Steps through simulation currentTicks = SDL_GetTicks(); float deltaTime = (float)(currentTicks - lastTicks) / 1000.0f; dynamicsWorld->stepSimulation(1.f / 60.f, 10); //Sets View Matrix viewMatrix = lookAt(cameraPosition, cameraTarget, cameraUp); //Iterates through game objects in the list then updates the render command for (GameObject * pObj : gameObjectList) { pObj->update(); } //Enables Depth Test and backface culling to save on processing glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glBindFramebuffer(GL_FRAMEBUFFER, 0); //Changes Background Colour glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Passes through GameObject list and renders each of them for (GameObject * pObj : gameObjectList) { pObj->preRender(); GLuint currentProgramID = pObj->getShaderProgramID(); //retrieve the shader values GLint viewMatrixLocation = glGetUniformLocation(currentProgramID, "viewMatrix"); GLint projectionMatrixLocation = glGetUniformLocation(currentProgramID, "projectionMatrix"); GLint lightDirectionLocation = glGetUniformLocation(currentProgramID, "lightDirection"); GLint ambientLightColourLocation = glGetUniformLocation(currentProgramID, "ambientLightColour"); GLint diffuseLightColourLocation = glGetUniformLocation(currentProgramID, "diffuseLightColour"); GLint specularLightColourLocation = glGetUniformLocation(currentProgramID, "specularLightColour"); //send shader values glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, value_ptr(viewMatrix)); glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, value_ptr(projectionMatrix)); glUniform3fv(lightDirectionLocation, 1, value_ptr(lightDirection)); glUniform4fv(ambientLightColourLocation, 1, value_ptr(ambientLightColour)); glUniform4fv(diffuseLightColourLocation, 1, value_ptr(diffuseLightColour)); glUniform4fv(specularLightColourLocation, 1, value_ptr(specularLightColour)); pObj->render(); } //Swaps Window for next rendered window SDL_GL_SwapWindow(window); //Updated Last tick to current ticks lastTicks = currentTicks; } #pragma region "Delete" //Remove Rigidbodys from simulation int NoOfCollisionObjects=dynamicsWorld->getNumCollisionObjects(); for (int i = 0; i < NoOfCollisionObjects -1; i++) { btCollisionObject* obj = dynamicsWorld->getCollisionObjectArray()[i]; dynamicsWorld->removeCollisionObject(obj); } //Iterates through models and deletes them auto gameObjectIter = gameObjectList.begin(); while (gameObjectIter != gameObjectList.end()) { if ((*gameObjectIter)) { (*gameObjectIter)->destroy(); delete (*gameObjectIter); gameObjectIter = gameObjectList.erase(gameObjectIter); } } //All the deleting goes on down here glDeleteProgram(postProcessingProgramID); glDeleteVertexArrays(1, &screenVAO); glDeleteBuffers(1, &screenQuadVBOID); glDeleteFramebuffers(1, &frameBufferID); glDeleteRenderbuffers(1, &depthRenderBufferID); glDeleteTextures(1, &colourBufferID); //Deletes GL_CONTEXT/Window SDL_GL_DeleteContext(GL_Context); // Delete Ground delete groundShape; if (GroundRigidbody->getMotionState() != NULL) { delete GroundRigidbody->getMotionState(); } delete GroundRigidbody; //delete solver delete solver; //delete broadphase delete overlappingPairCache; //delete dispatcher delete dispatcher; delete collisionConfiguration; //Destroy the window and quit SDL2 //https://wiki.libsdl.org/SDL_DestroyWindow SDL_DestroyWindow(window); //https://wiki.libsdl.org/SDL_Quit SDL_Quit(); return 0; } #pragma endregion
true
cc2beae8b1287e464c00e078a4c4e5f5d954bf98
C++
Yaseungho/myCodes
/Baekjoon_Solving/Baekjoon_10448.cpp
UTF-8
547
2.96875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int sum = 0, i, j, k, num, T; bool is = true; vector<int> Tvec; for (i = 1; sum < 1000; i++) { sum += i; Tvec.push_back(sum); } cin >> T; while (T--) { cin >> num; is = true; for (i = 0; i < Tvec.size() && is; i++) { for (j = 0; j < Tvec.size() && is; j++) { for (k = 0; k < Tvec.size() && is; k++) { if (num == Tvec[i] + Tvec[j] + Tvec[k]) { is = false; } } } } if (is) cout << "0\n"; else cout << "1\n"; } return 0; }
true
5e5f73a4e49e7cd30812120e44f35e20b120dd9a
C++
Snake174/PipmakAssistant
/LoadingEffect.h
UTF-8
2,182
2.5625
3
[]
no_license
#ifndef LOADINGEFFECT_H #define LOADINGEFFECT_H //================================================================================================= #include <QObject> #include <QWidget> #include <QLabel> #include <QToolButton> #include <QStackedWidget> //================================================================================================= class ProgressIndicator : public QWidget { Q_OBJECT Q_PROPERTY( int delay READ animationDelay WRITE setAnimationDelay ) Q_PROPERTY( bool displayedWhenStopped READ isDisplayedWhenStopped WRITE setDisplayedWhenStopped ) Q_PROPERTY( QColor color READ color WRITE setColor ) public: ProgressIndicator( QWidget *parent = 0 ); int animationDelay() const { return m_delay; } bool isAnimated () const; bool isDisplayedWhenStopped() const; const QColor &color() const { return m_color; } virtual QSize sizeHint() const; int heightForWidth( int w ) const; int angle; int procent; public slots: void startAnimation(); void stopAnimation(); void setAnimationDelay( int delay ); void setDisplayedWhenStopped( bool state ); void setColor( const QColor &color ); protected: virtual void timerEvent( QTimerEvent *event ); virtual void paintEvent( QPaintEvent *event ); private: int m_angle; int m_timerId; int m_delay; bool m_displayedWhenStopped; QColor m_color; }; //================================================================================================= //================================================================================================= class LoadingEffect : public QStackedWidget { Q_OBJECT ProgressIndicator *pProgress; QLabel *info; public: LoadingEffect( QWidget *parent = 0 ); virtual ~LoadingEffect(); void setWidget( QWidget *wgt ) { insertWidget( 1, wgt ); setCurrentIndex(1); } public slots: void install(); void remove(); void setProgress( int cur, int cnt ); void setInfo( const QString &txt ) { info->setText( txt ); } }; //================================================================================================= #endif // LOADINGEFFECT_H
true
584796e59d6393002d29888ec977d7b9bf8f39d1
C++
liutuoni/skia
/src/gpu/tessellate/shaders/GrPathTessellationShader.h
UTF-8
9,848
2.78125
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright 2019 Google LLC. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef GrPathTessellationShader_DEFINED #define GrPathTessellationShader_DEFINED #include "src/gpu/tessellate/shaders/GrTessellationShader.h" // This is the base class for shaders in the GPU tessellator that fill paths. class GrPathTessellationShader : public GrTessellationShader { public: // Draws a simple array of triangles. static GrPathTessellationShader* MakeSimpleTriangleShader(SkArenaAlloc*, const SkMatrix& viewMatrix, const SkPMColor4f&); // How many triangles are in a curve with 2^resolveLevel line segments? constexpr static int NumCurveTrianglesAtResolveLevel(int resolveLevel) { // resolveLevel=0 -> 0 line segments -> 0 triangles // resolveLevel=1 -> 2 line segments -> 1 triangle // resolveLevel=2 -> 4 line segments -> 3 triangles // resolveLevel=3 -> 8 line segments -> 7 triangles // ... return (1 << resolveLevel) - 1; } enum class PatchType : bool { // An ice cream cone shaped patch, with 4 curve control points on top of a triangle that // fans from a 5th point at the center of the contour. (5 points per patch.) kWedges, // A standalone closed curve made up 4 control points. (4 points per patch.) kCurves }; // Uses instanced draws to triangulate curves with a "middle-out" topology. Middle-out draws a // triangle with vertices at T=[0, 1/2, 1] and then recurses breadth first: // // depth=0: T=[0, 1/2, 1] // depth=1: T=[0, 1/4, 2/4], T=[2/4, 3/4, 1] // depth=2: T=[0, 1/8, 2/8], T=[2/8, 3/8, 4/8], T=[4/8, 5/8, 6/8], T=[6/8, 7/8, 1] // ... // // The shader determines how many segments are required to render each individual curve // smoothly, and emits empty triangles at any vertices whose sk_VertexIDs are higher than // necessary. It is the caller's responsibility to draw enough vertices per instance for the // most complex curve in the batch to render smoothly (i.e., NumTrianglesAtResolveLevel() * 3). static GrPathTessellationShader* MakeMiddleOutFixedCountShader(const GrShaderCaps&, SkArenaAlloc*, const SkMatrix& viewMatrix, const SkPMColor4f&, PatchType); // This is the largest number of segments the middle-out shader will accept in a single // instance. If a curve requires more segments, it needs to be chopped. constexpr static int kMaxFixedCountSegments = 32; constexpr static int kMaxFixedCountResolveLevel = 5; // log2(kMaxFixedCountSegments) static_assert(kMaxFixedCountSegments == 1 << kMaxFixedCountResolveLevel); // These functions define the vertex and index buffers that should be bound when drawing with // the middle-out fixed count shader. The data sequence is identical for any length of // tessellation segments, so the caller can use them with any instance length (up to // kMaxFixedCountResolveLevel). // // The "curve" and "wedge" buffers are nearly identical, but we keep them separate for now in // case there is a perf hit in the curve case for not using index 0. constexpr static int SizeOfVertexBufferForMiddleOutCurves() { constexpr int kMaxVertexCount = (1 << kMaxFixedCountResolveLevel) + 1; return kMaxVertexCount * kMiddleOutVertexStride; } static void InitializeVertexBufferForMiddleOutCurves(GrVertexWriter, size_t bufferSize); constexpr static size_t SizeOfIndexBufferForMiddleOutCurves() { constexpr int kMaxTriangleCount = NumCurveTrianglesAtResolveLevel(kMaxFixedCountResolveLevel); return kMaxTriangleCount * 3 * sizeof(uint16_t); } static void InitializeIndexBufferForMiddleOutCurves(GrVertexWriter, size_t bufferSize); constexpr static int SizeOfVertexBufferForMiddleOutWedges() { return SizeOfVertexBufferForMiddleOutCurves() + kMiddleOutVertexStride; } static void InitializeVertexBufferForMiddleOutWedges(GrVertexWriter, size_t bufferSize); constexpr static size_t SizeOfIndexBufferForMiddleOutWedges() { return SizeOfIndexBufferForMiddleOutCurves() + 3 * sizeof(uint16_t); } static void InitializeIndexBufferForMiddleOutWedges(GrVertexWriter, size_t bufferSize); // Uses GPU tessellation shaders to linearize, triangulate, and render cubic "wedge" patches. A // wedge is a 5-point patch consisting of 4 cubic control points, plus an anchor point fanning // from the center of the curve's resident contour. static GrPathTessellationShader* MakeHardwareTessellationShader(SkArenaAlloc*, const SkMatrix& viewMatrix, const SkPMColor4f&, PatchType); // Returns the stencil settings to use for a standard Redbook "stencil" pass. static const GrUserStencilSettings* StencilPathSettings(GrFillRule fillRule) { // Increments clockwise triangles and decrements counterclockwise. Used for "winding" fill. constexpr static GrUserStencilSettings kIncrDecrStencil( GrUserStencilSettings::StaticInitSeparate< 0x0000, 0x0000, GrUserStencilTest::kAlwaysIfInClip, GrUserStencilTest::kAlwaysIfInClip, 0xffff, 0xffff, GrUserStencilOp::kIncWrap, GrUserStencilOp::kDecWrap, GrUserStencilOp::kKeep, GrUserStencilOp::kKeep, 0xffff, 0xffff>()); // Inverts the bottom stencil bit. Used for "even/odd" fill. constexpr static GrUserStencilSettings kInvertStencil( GrUserStencilSettings::StaticInit< 0x0000, GrUserStencilTest::kAlwaysIfInClip, 0xffff, GrUserStencilOp::kInvert, GrUserStencilOp::kKeep, 0x0001>()); return (fillRule == GrFillRule::kNonzero) ? &kIncrDecrStencil : &kInvertStencil; } // Returns the stencil settings to use for a standard Redbook "fill" pass. Allows non-zero // stencil values to pass and write a color, and resets the stencil value back to zero; discards // immediately on stencil values of zero. static const GrUserStencilSettings* TestAndResetStencilSettings(bool isInverseFill = false) { constexpr static GrUserStencilSettings kTestAndResetStencil( GrUserStencilSettings::StaticInit< 0x0000, // No need to check the clip because the previous stencil pass will have only // written to samples already inside the clip. GrUserStencilTest::kNotEqual, 0xffff, GrUserStencilOp::kZero, GrUserStencilOp::kKeep, 0xffff>()); constexpr static GrUserStencilSettings kTestAndResetStencilInverted( GrUserStencilSettings::StaticInit< 0x0000, // No need to check the clip because the previous stencil pass will have only // written to samples already inside the clip. GrUserStencilTest::kEqual, 0xffff, GrUserStencilOp::kKeep, GrUserStencilOp::kZero, 0xffff>()); return isInverseFill ? &kTestAndResetStencilInverted : &kTestAndResetStencil; } // Creates a pipeline that does not write to the color buffer. static const GrPipeline* MakeStencilOnlyPipeline( const ProgramArgs&, GrAAType, const GrAppliedHardClip&, GrPipeline::InputFlags = GrPipeline::InputFlags::kNone); protected: constexpr static size_t kMiddleOutVertexStride = 2 * sizeof(float); GrPathTessellationShader(ClassID classID, GrPrimitiveType primitiveType, int tessellationPatchVertexCount, const SkMatrix& viewMatrix, const SkPMColor4f& color) : GrTessellationShader(classID, primitiveType, tessellationPatchVertexCount, viewMatrix, color) { } // Default path tessellation shader implementation that manages a uniform matrix and color. class Impl : public ProgramImpl { public: void onEmitCode(EmitArgs&, GrGPArgs*) final; void setData(const GrGLSLProgramDataManager&, const GrShaderCaps&, const GrGeometryProcessor&) override; protected: // float4x3 unpack_rational_cubic(float2 p0, float2 p1, float2 p2, float2 p3) { ... // // Evaluate our point of interest using numerically stable linear interpolations. We add our // own "safe_mix" method to guarantee we get exactly "b" when T=1. The builtin mix() // function seems spec'd to behave this way, but empirical results results have shown it // does not always. static const char* kEvalRationalCubicFn; virtual void emitVertexCode(const GrShaderCaps&, const GrPathTessellationShader&, GrGLSLVertexBuilder*, GrGPArgs*) = 0; GrGLSLUniformHandler::UniformHandle fAffineMatrixUniform; GrGLSLUniformHandler::UniformHandle fTranslateUniform; GrGLSLUniformHandler::UniformHandle fColorUniform; }; }; #endif
true
025cabbb17d98ede28e894af257d2089bfbfc430
C++
MheZa/ALFBM
/bladeInfo.H
UTF-8
6,180
2.53125
3
[]
no_license
/****************************************************************************\ This program is based on the openFOAM, and is developed by MaZhe. The goal of this program is to build an bladeInfo class . \****************************************************************************/ #ifndef bladeInfo_H #define bladeInfo_H #include "scalar.H" #include "List.H" #include "airfoilInfo.H" #include <vector> #include "Eigen/Dense" /******************************************class declaration******************************************/ namespace Foam { namespace fv { class bladeInfo { public: //Constructor bladeInfo ( dictionary& bladeInfoPath ): bladeName_(bladeInfoPath.dictName()) { read(bladeInfoPath); interfaceCalulate(); bladeACCalculate(); } //blade information APIs const word& bladeName() const {return bladeName_;} //blade aerodynamic characteristic APIs const List<point> & bladeAEP() const {return bladeAEP_;} const List<word> & airfoilName() const {return airfoilName_;} const List<List<scalar>> & bladeAEI() const {return bladeAEI_;} //blade finite element characteristic APIs const List<point> & bladeNP() const {return bladeNP_;} const List<List<int>> & bladeEI() const {return bladeEI_;} const List<List<scalar>> & bladeSI() const {return bladeSI_;} const List<List<scalar>> & bladeSP() const {return bladeSP_;} const List<scalar> & bladeAC() const {return bladeAC_;} //blade aero finite element interface APIs const List<List<int>> & aeroInBeamNumber() const {return aeroInBeamNumber_;} const List<scalar> & aeroInBeamK() const {return aeroInBeamK_;} private: //blade name word bladeName_; //aero infomations of blade //blade aero element position List<point> bladeAEP_; //blade airfoil type List<word> airfoilName_; //blade aero element info List<List<scalar>> bladeAEI_; //structure informations of blade //blade node position List<point> bladeNP_; //blade element info, node number of element List<List<int>> bladeEI_; //blade element section info List<List<scalar>> bladeSI_; //blade element section position List<List<scalar>> bladeSP_; //blade element aerodynamic center List<scalar> bladeAC_; //blade aero and finite element interface List<List<int>> aeroInBeamNumber_; List<scalar> aeroInBeamK_; //private member functions bool read(dictionary& bladeDict); bool check(); void interfaceCalulate(); void bladeACCalculate(); }; }//end namespace fv }//end namespace Foam /******************************************************************************************************************************\ | | | function definition | | | \******************************************************************************************************************************/ /******************************************private member functions******************************************/ inline bool Foam::fv::bladeInfo::read(dictionary& bladeDict) { //must find profileData! if(bladeDict.found("bladeAEP")) { bladeDict.lookup("bladeAEP") >> bladeAEP_; bladeDict.lookup("airfoilName") >> airfoilName_; bladeDict.lookup("bladeAEI") >> bladeAEI_; bladeDict.lookup("bladeNP") >> bladeNP_; bladeDict.lookup("bladeEI") >> bladeEI_; bladeDict.lookup("bladeSI") >> bladeSI_; bladeDict.lookup("bladeSP") >> bladeSP_; if(check()) { return true; } else { Info<<"Data check failed for "<<bladeDict.name()<<". Please correct the blade data."<<endl; return false; } } else { Info<<"No profileData for "<<bladeDict.name()<<endl; return false; } } inline bool Foam::fv::bladeInfo::check() { if(airfoilName_.size()!=bladeAEP_.size()) { Info<<"Error: error occured in airfoilName data of "<<bladeName_<<endl; return false; } else { if(bladeAEI_.size()!=bladeAEP_.size()) { Info<<"Error: error occured in elementInfo data of "<<bladeName_<<endl; return false; } else { if(bladeSI_.size()!=bladeNP_.size() || bladeSI_.size()!=bladeSP_.size()) { Info<<"Error: error occured in blade element info and blade element section info data of "<<bladeName_<<endl; return false; } else { return true; } } } } inline void Foam::fv::bladeInfo::interfaceCalulate() { List<int> temp; temp.setSize(2,0); aeroInBeamNumber_.setSize(bladeAEP_.size(),temp); aeroInBeamK_.setSize(bladeAEP_.size(),0.0); int j=1; forAll(bladeAEP_,i) { while(j!=bladeNP_.size()) { vector temp01=bladeAEP_[i]-bladeNP_[j-1]; vector temp02=bladeAEP_[i]-bladeNP_[j]; if((temp01&temp02)<=0.0) { aeroInBeamNumber_[i][0]=j-1; aeroInBeamNumber_[i][1]=j; aeroInBeamK_[i]=mag(temp01)/mag(bladeNP_[j]-bladeNP_[j-1]); break; } else { j+=1; } } if(j==bladeNP_.size()) { Info<<"Error: Error occured in interfaceCalulate function for aero element number "<<i<<" of blade "<<bladeName_<<endl; } } Info<<"interface number of "<<bladeName_<<" is "<<aeroInBeamK_<<endl; } inline void Foam::fv::bladeInfo::bladeACCalculate() { bladeAC_.setSize(bladeAEP_.size(),0.0); forAll(bladeAC_,i) { scalar temp=(1-aeroInBeamK_[i])*bladeSP_[aeroInBeamNumber_[i][0]][0]+aeroInBeamK_[i]*bladeSP_[aeroInBeamNumber_[i][1]][0]-0.25; bladeAC_[i]=temp*bladeAEI_[i][0]; } } #endif
true
3fbc4981cd68b04faa862caa5439e982e7071ad1
C++
Noymul-Islam/problems
/The Party, Part I.cpp
UTF-8
1,506
2.609375
3
[]
no_license
#include<cstdio> #include<cstring> #include<cmath> #include<vector> using namespace std; void bfs(int node, int source); vector<int>G[1100],v1,v2; int main() { int c=0,cases,folow; while(scanf("%d",&cases)==1) { for(folow=1;folow<=cases;folow++) { int nodes,edges,i,j,m,n; scanf("%d %d",&nodes,&edges); for(i=0;i<edges;i++) { int x,y; scanf("%d %d",&x,&y); G[x].push_back(y); G[y].push_back(x); } bfs(nodes,0); v1.clear(); v2.clear(); for(int i=0;i<nodes;i++) G[i].clear(); if(folow!=cases) printf("\n"); } } return 0; } void bfs(int nodes,int source) { v1.push_back(source); int taken[1100]={0}; int distance[1100]; taken[source]=1; distance[source]=0; for(int loop=0;;loop++) { for(int i=0;i<v1.size();i++) { int u=v1[i]; for( int j=0;j<G[u].size();j++) { int v=G[u][j]; if(!taken[v]) { taken[v]=1; distance[v]=distance[u]+1; v2.push_back(v); } } } if(v2.empty()) break; else { v1.clear(); v1=v2; v2.clear(); } } for(int k=1;k<nodes;k++) printf("%d\n",distance[k]); }
true
5ff4694c9551ad682fc531c26cbe2a4262a2920e
C++
yieldthought/hemelb
/Code/util/fileutils.cc
UTF-8
5,135
2.75
3
[]
no_license
// // Copyright (C) University College London, 2007-2012, all rights reserved. // // This file is part of HemeLB and is CONFIDENTIAL. You may not work // with, install, use, duplicate, modify, redistribute or share this // file, or any part thereof, other than as allowed by any agreement // specifically made by you with University College London. // #include <cstdlib> #include <cstdio> #include <cstring> #include <fstream> #include <unistd.h> #include <dirent.h> #include <sys/dir.h> #include <sys/types.h> #include <sys/stat.h> #include <sstream> #include "log/Logger.h" #include "util/fileutils.h" namespace hemelb { namespace util { // Returns true if the file with the given name exists for reading, // false otherwise. //bool file_exists(const char * filename); // Function to select directory contents that are not "." or ".." // int selectOnlyContents (direct_t *entry); // Return true if file exists for reading, false if not. bool file_exists(const char * filename) { if (access(filename, R_OK) == -1) { return false; } return true; } // Check the existence of a critical file - exit if it's not there void check_file(const char * filename) { if (!file_exists(filename)) { log::Logger::Log<log::Critical, log::OnePerCore>("Cannot open file %s\nExiting.", filename); std::exit(0); } } // Function to select directory contents that are not "." or ".." int selectOnlyContents(direct_t *entry) { if ( (std::strcmp(entry->d_name, ".") == 0) || (std::strcmp(entry->d_name, "..") == 0)) { return 0; } else { return 1; } } void ChangeDirectory(const char * target) { chdir(target); } void ChangeDirectory(const std::string & target) { chdir(target.c_str()); } void GetCurrentDir(char * result, int bufflength) { getcwd(result, bufflength); } std::string GetCurrentDir() { char buff[1000]; GetCurrentDir(buff, 1000); return std::string(buff); // return by copy. } // This copied from BOOST. TODO: Use boost std::string GetTemporaryDir() { const char *dirname; dirname = std::getenv("TMP"); if (NULL == dirname) dirname = std::getenv("TMPDIR"); if (NULL == dirname) dirname = std::getenv("TEMP"); if (NULL == dirname) { //assert(false); // no temp directory found return GetCurrentDir(); } return std::string(dirname); // return by copy } // Delete all files within a directory. int DeleteDirContents(std::string pathname) { struct direct **files; int file_count = scandir(pathname.c_str(), &files, selectOnlyContents, alphasort); for (int i = 0; i < file_count; i++) { std::stringstream filename; filename << pathname.c_str() << "/" << files[i]->d_name <<std::flush; unlink(filename.str().c_str()); } return 0; } // Detect whether a directory exists. bool DoesDirectoryExist(const char *pathname) { struct stat st; return stat(pathname, &st) == 0; } bool FileCopy(const char* iOriginalPath, const char* iNewPath) { std::ifstream lSource; std::ofstream lDestination; // open in binary to prevent jargon at the end of the buffer lSource.open(iOriginalPath, std::ios::binary); lDestination.open(iNewPath, std::ios::binary); if (!lSource.is_open() || !lDestination.is_open()) { return false; } lDestination << lSource.rdbuf(); lDestination.close(); lSource.close(); return true; } // Function to create the directory of given path, which user group and anyone // can read write and execute. void MakeDirAllRXW(std::string &dirPath) { mkdir(dirPath.c_str(), 0777); } std::string NormalizePathRelativeToPath(std::string inPath, std::string basePath) { // If it's an absolute path, just return it if (inPath[0] == '/') { return inPath; } // Going to check if it's a directory std::string baseDir; struct stat st; stat(basePath.c_str(), &st); // Assume it's a regular file in case it doesn't exist st.st_mode = S_IFREG; if (st.st_mode == S_IFDIR) { // It's a directory baseDir = basePath; } else { // Not a dir, find the last slash unsigned long lastSlash = basePath.rfind('/'); if (lastSlash == basePath.npos) { // No slashes, so the baseDir is just the working dir baseDir = "."; } else { // Has slashes, return up to the last baseDir = basePath.substr(0, lastSlash); } } // Make sure it ends in a slash if (baseDir[baseDir.size() - 1] != '/') { baseDir += "/"; } //Append the path of interest return baseDir + inPath; } } }
true
0a13b3e2ffaeb7d20fa86881806f576d3149c3fc
C++
kohnakagawa/LSCMD
/test/test_tensor2.cpp
UTF-8
3,569
2.921875
3
[ "BSD-3-Clause" ]
permissive
#include "gtest/gtest.h" #include "../tensor2.hpp" using namespace LocalStress; typedef Tensor2<double> dtensor; typedef Vector2<double> dvec2; TEST(Constructor, test0) { dtensor dt; ASSERT_EQ(dt.xx, 0); ASSERT_EQ(dt.xy, 0); ASSERT_EQ(dt.yx, 0); ASSERT_EQ(dt.yy, 0); } TEST(Constructor, test1) { dtensor dt(12.0); ASSERT_EQ(dt.xx, 12.0); ASSERT_EQ(dt.xy, 12.0); ASSERT_EQ(dt.yx, 12.0); ASSERT_EQ(dt.yy, 12.0); } TEST(Constructor, test2) { dtensor dt(1.0, 2.0, 4.0, 5.0); ASSERT_EQ(dt.xx, 1.0); ASSERT_EQ(dt.xy, 2.0); ASSERT_EQ(dt.yx, 4.0); ASSERT_EQ(dt.yy, 5.0); } TEST(Constructor, test3) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dtensor dt(dt0); ASSERT_EQ(dt.xx, 1.0); ASSERT_EQ(dt.xy, 2.0); ASSERT_EQ(dt.yx, 4.0); ASSERT_EQ(dt.yy, 5.0); } TEST(Constructor, test4) { dtensor dt { 1.0, 2.0, 4.0, 5.0 }; ASSERT_EQ(dt.xx, 1.0); ASSERT_EQ(dt.xy, 2.0); ASSERT_EQ(dt.yx, 4.0); ASSERT_EQ(dt.yy, 5.0); } TEST(Operator, copy) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dtensor dt = dt0; ASSERT_EQ(dt.xx, 1.0); ASSERT_EQ(dt.xy, 2.0); ASSERT_EQ(dt.yx, 4.0); ASSERT_EQ(dt.yy, 5.0); } TEST(Operator, add) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dtensor dt1(3.0, 4.0, 3.0, 2.0); dtensor dt2 = dt0 + dt1; ASSERT_EQ(dt2.xx, 4.0); ASSERT_EQ(dt2.xy, 6.0); ASSERT_EQ(dt2.yx, 7.0); ASSERT_EQ(dt2.yy, 7.0); } TEST(Operator, addeq) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dtensor dt1(3.0, 4.0, 3.0, 2.0); dt1 += dt0; ASSERT_EQ(dt1.xx, 4.0); ASSERT_EQ(dt1.xy, 6.0); ASSERT_EQ(dt1.yx, 7.0); ASSERT_EQ(dt1.yy, 7.0); } TEST(Operator, sub) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dtensor dt1(3.0, 4.0, 3.0, 2.0); dtensor dt2 = dt0 - dt1; ASSERT_EQ(dt2.xx, -2.0); ASSERT_EQ(dt2.xy, -2.0); ASSERT_EQ(dt2.yx, 1.0); ASSERT_EQ(dt2.yy, 3.0); } TEST(Operator, subeq) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dtensor dt1(3.0, 4.0, 3.0, 2.0); dt0 -= dt1; ASSERT_EQ(dt0.xx, -2.0); ASSERT_EQ(dt0.xy, -2.0); ASSERT_EQ(dt0.yx, 1.0); ASSERT_EQ(dt0.yy, 3.0); } TEST(Operator, mul0) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dtensor dt1 = dt0 * 2.0; ASSERT_EQ(dt1.xx, dt0.xx * 2.0); ASSERT_EQ(dt1.xy, dt0.xy * 2.0); ASSERT_EQ(dt1.yx, dt0.yx * 2.0); ASSERT_EQ(dt1.yy, dt0.yy * 2.0); } TEST(Operator, mul1) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dtensor dt1 = 2.0 * dt0; ASSERT_EQ(dt1.xx, 2.0 * dt0.xx); ASSERT_EQ(dt1.xy, 2.0 * dt0.xy); ASSERT_EQ(dt1.yx, 2.0 * dt0.yx); ASSERT_EQ(dt1.yy, 2.0 * dt0.yy); } TEST(Operator, muleq) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dt0 *= 2.0; ASSERT_EQ(dt0.xx, 2.0); ASSERT_EQ(dt0.xy, 4.0); ASSERT_EQ(dt0.yx, 8.0); ASSERT_EQ(dt0.yy, 10.0); } TEST(Operator, div) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dtensor dt1 = dt0 / 2.0; ASSERT_EQ(dt1.xx, dt0.xx / 2.0); ASSERT_EQ(dt1.xy, dt0.xy / 2.0); ASSERT_EQ(dt1.yx, dt0.yx / 2.0); ASSERT_EQ(dt1.yy, dt0.yy / 2.0); } TEST(Operator, diveq) { dtensor dt0(1.0, 2.0, 4.0, 5.0); dt0 /= 2.0; ASSERT_EQ(dt0.xx, 0.5); ASSERT_EQ(dt0.xy, 1.0); ASSERT_EQ(dt0.yx, 2.0); ASSERT_EQ(dt0.yy, 2.5); } TEST(Utils, tensordot) { dvec2 v0(1.0, 2.0); dvec2 v1(2.0, 1.0); dtensor t01 = tensor_dot(v0, v1); ASSERT_EQ(t01.xx, v0.x * v1.x); ASSERT_EQ(t01.xy, v0.x * v1.y); ASSERT_EQ(t01.yx, v0.y * v1.x); ASSERT_EQ(t01.yy, v0.y * v1.y); }
true
e111f4690d085f44accdf96b2e1ad0e237b4d885
C++
pmiddend/fcppt
/test/container/array/map.cpp
UTF-8
1,625
2.71875
3
[ "BSL-1.0" ]
permissive
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fcppt/make_strong_typedef.hpp> #include <fcppt/output_to_std_string.hpp> #include <fcppt/strong_typedef.hpp> #include <fcppt/catch/movable.hpp> #include <fcppt/container/array/map.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <array> #include <string> #include <utility> #include <fcppt/config/external_end.hpp> TEST_CASE( "array::map", "[container],[array]" ) { CHECK( fcppt::container::array::map( std::array< int, 2 >{{ 1, 2 }}, []( int const _value ) -> std::string { return fcppt::output_to_std_string( _value ); } ) == std::array< std::string, 2 >{{ std::string{ "1" }, std::string{ "2" } }} ); } TEST_CASE( "array::map move", "[container],[array]" ) { typedef fcppt::catch_::movable< int > int_movable; FCPPT_MAKE_STRONG_TYPEDEF( int_movable, strong_int_movable ); CHECK( fcppt::container::array::map( std::array< int_movable, 2 >{{ int_movable{ 1 }, int_movable{ 2 } }}, []( int_movable &&_arg ) { return strong_int_movable{ std::move( _arg ) }; } ) == std::array< strong_int_movable, 2 >{{ strong_int_movable{ int_movable{ 1 } }, strong_int_movable{ int_movable{ 2 } } }} ); }
true
2560fc99d1915e7dd49f2198aed56a1992471e27
C++
a1clark1a/ParticleExplosion
/SDL2_Project(Particles)/SDL2_Project(Particles)/Screen.h
UTF-8
512
2.515625
3
[]
no_license
#pragma once #include <SDL.h> namespace ParticleExplosion { class Screen { public: const static int SCREEN_WIDTH = 800; const static int SCREEN_HEIGHT = 600; Screen(); bool Init(); bool ProcessEvents(); void Close(); void SetPixel(const int x, const int y, const Uint8 red, const Uint8 green, const Uint8 blue); void Update(); void BoxBlur(); private: SDL_Window * m_window; SDL_Renderer * m_renderer; SDL_Texture * m_texture; Uint32 * m_buffer1; Uint32 * m_buffer2; }; }
true
502db188b8bb43aee3082b8cda40c311e2e49720
C++
zhouguoguo/C-plus-plus-Primer
/Chapter13/13.4.cpp
UTF-8
530
3.359375
3
[]
no_license
#include <iostream> using namespace std; class Point { public: Point() = default; Point(Point& p) : m_x(p.m_x), m_y(p.m_y) { ++i; cout << "copy constructor, i = " << i << endl; } private: double m_x; double m_y; static int i; }; int Point::i = 0; Point global; Point foo_bar(Point arg) { Point local = arg, *heap = new Point(global); *heap = local; Point pa[4] = {local, *heap}; return *heap; } int main() { Point p1 = global; Point p2(global); foo_bar(global); return 0; }
true