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
ff83e026925721d3acbcc6df2352259604f55f56
C++
zswDev/libgco
/utils.cpp
UTF-8
1,652
2.65625
3
[]
no_license
#include <sched.h> #include <unistd.h> #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <time.h> #include "utils.h" int CPUS = 0; cpu_set_t* CPU_masks = 0; void cpu_init() { CPUS = sysconf(_SC_NPROCESSORS_CONF); cpu_set_t* CPU_masks = (cpu_set_t*)malloc(sizeof(cpu_set_t)* CPUS); }; void set_affinity(int i, pthread_t thid){ CPU_ZERO(&CPU_masks[i]); CPU_SET(i, &CPU_masks[i]); int s = pthread_setaffinity_np(thid, sizeof(cpu_set_t), &CPU_masks[i]); if (s != 0){ throw "err: pthread_setaffinity_np"; } } void condx::wait(){ pthread_mutex_lock(&mtx); pthread_cond_wait(&cond, &mtx); pthread_mutex_unlock(&mtx); } void condx::notify(){ pthread_mutex_lock(&mtx); pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); } int get_random(int n){ // 0 ~ n srand((unsigned)time(NULL)); // 播种 int ret = rand() % n; return ret; } int Gcd(int m,int n){ int o; while(n>0){ o=m%n; m=n; n=o; } return m; } void get_coprimes(vector<int>& arr, int n) { vector<int>().swap(arr); //清空元素 for(int i=2;i<n;i++){ int b=Gcd(i,n); if(b==1){ arr.push_back(i); } } } // void get_coprimes (vector<int>& arr,int n) { // vector<int>().swap(arr); //清空元素 // for(int i=2;i<=n;i++){ // bool flag = true; // for(int j=2;j<=i/2;j++){ // if(i%j == 0) { // flag = false; // break; // } // } // if (flag && i != 2) { // arr.push_back(i); // } // } // }
true
06ab95205eec47264e6f8c0b76a9c4e26418ab93
C++
wsldwo/CPlusPlus
/NOI/NOI1139.cpp
GB18030
1,575
3.703125
4
[]
no_license
#include <iostream> #include <string> using namespace std; string s1,s2; string sub(string a,string b)//a - b { //ȣҪȽabĴСaСbҪתΪ -b - a int len_a = a.length(),len_b = b.length(); int is_a_bigger = 0;//0Ϊ if(len_a > len_b) is_a_bigger = 1;//1Ϊ else if(len_a == len_b) { for(int i = 0;i < len_a;i++) { if(a[i] - '0' > b[i] - '0') { is_a_bigger = 1; break; } else if(a[i] - '0' < b[i] - '0') { is_a_bigger = -1; break; } } } else is_a_bigger = -1;//-1ΪС //Ȼ󣬿ʼ a - b if(is_a_bigger == 0) return "0"; else if(is_a_bigger == -1)//aС򽻻ab { string t = a; a = b; b = t; int temp = len_a;//Ҳ뽻 len_a = len_b; len_b = temp; } string c; int borrow = 0;//λ int i = len_a - 1,j = len_b - 1; while(i >= 0 || j >= 0) { int _a = a[i] - '0' - borrow; int _b = 0; if(j >= 0)//bûa _b += b[j] - '0'; if(_a >= _b) { c += char((_a - _b) + '0'); borrow = 0; } else { c += char((10 + _a - _b) + '0'); borrow = 1;//λһ } i--,j--; } //תc i = 0,j = c.length() - 1; while(i < j) { char ch = c[i]; c[i] = c[j]; c[j] = ch; i++,j--; } //ǰ0 while(c[0] == '0') c.erase(0,1);//string.erase(pos,n) ɾposʼnַ if(is_a_bigger == -1) c = "-" + c;//ϸ return c; } int main() { cin >> s1 >> s2; cout << sub(s1,s2) << endl; return 0; }
true
b9d018dbead2c9ee734d6671f2ebdade1b210df4
C++
iShubhamRana/DSA-Prep
/Leetcode-Contests/biweekly-54/1894.cpp
UTF-8
385
3.21875
3
[]
no_license
// 2 tricks // 1. use '0l' instead of '0' in accumulate as sum may be 'long' // 2. if((k -= c[i]) < 0) class Solution { public: int chalkReplacer(vector<int> &c, long k) { long sum = accumulate(c.begin(), c.end(), 0l); k %= sum; for (int i = 0; i < c.size(); ++i) if ((k -= c[i]) < 0) return i; return 0; } };
true
90a691b1a1a6d83f031ce59e92cdf6ebb1245906
C++
wildandri/sudoku_solver
/main.cpp
UTF-8
1,622
2.671875
3
[]
no_license
#include "solverengine.h" #include "opencv2/core.hpp" #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <iostream> #include <vector> int main() { std::cout << "- - - START PROGRAMM - - -" << std::endl; double time = (double)cv::getTickCount(); // Load Image // cv::Mat frame = cv::imread("/home/andri/frametures/pic.jpg",cv::IMREAD_GRAYSCALE); // if( pic.empty() ) // { // std::cout << "Could not open or find the image!\n" << std::endl; // return -1; // } // Video stream input cv::Mat frame; cv::VideoCapture cameraFrame(0); if(!cameraFrame.isOpened()){ std::cout << "Video stream not opened !!!" << std::endl; } SolverEngine es = SolverEngine(1280,720); cameraFrame.set(cv::CAP_PROP_FRAME_WIDTH ,es.getWidth()); cameraFrame.set(cv::CAP_PROP_FRAME_HEIGHT ,es.getHeight()); do { cameraFrame >> frame; cvtColor( frame, frame, cv::COLOR_BGR2GRAY ); cv::imshow("Livestream", frame); es.setPicture(frame); cv::waitKey(1); } while (!es.findSudoku()); cameraFrame.release(); std::vector<short int> result = es.detectNumbers(es.getDetectedSudoku()); for(size_t i = 1; i < result.size() + 1; i++) { std::cout << result[i-1] << " "; if(i % 9 == 0){ std::cout << std::endl; } } time = ((double)cv::getTickCount() - time)/cv::getTickFrequency(); std::cout << "Times passed in ms: " << time*1000 << std::endl; std::cout << "- - - END PROGRAMM - - -" << std::endl; cv::waitKey(0); return 0; }
true
c26d886b99592eb909d98eebae9955e40271534a
C++
tkubicz/ngengine
/source/src/NGE/Geometry/Basic/Box.cpp
UTF-8
5,233
2.65625
3
[]
no_license
#include "NGE/Geometry/Basic/Box.hpp" #include "NGE/Math/Vector3.hpp" #include "NGE/Rendering/Renderer.hpp" #include "NGE/Core/Core.hpp" using namespace NGE::Geometry::Basic; bool Box::Initialize() { return Initialize(1.0f); } bool Box::Initialize(float size) { this->boxSize = size / 2.0f; InitializeGeometry(); InitializeVBO(); InitializeVBA(); return true; } void Box::DeleteBuffers() { if (vertexBuffer != 0) glDeleteBuffers(1, &vertexBuffer); if (normalBuffer != 0) glDeleteBuffers(1, &normalBuffer); if (texCoordBuffer != 0) glDeleteBuffers(1, &texCoordBuffer); if (indexBuffer != 0) glDeleteBuffers(1, &indexBuffer); } void Box::DeleteArrays() { if (vertexArray != 0) glDeleteVertexArrays(1, &vertexArray); } bool Box::InitializeGeometry() { int vertexCount = 24; int indexCount = 36; float vertices[] = {-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, +1.0f, -1.0f, +1.0f, +1.0f, -1.0f, -1.0f, -1.0f, +1.0f, -1.0f, -1.0f, +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, -1.0f, +1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, -1.0f, +1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, -1.0f, +1.0f, -1.0f, +1.0f, -1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, -1.0f}; float normals[] = {0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f, +1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f, +1.0f, 0.0f, 0.0f}; float texCoords[] = {0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f}; unsigned int indices[] = {0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 15, 14, 12, 14, 13, 16, 17, 18, 16, 18, 19, 20, 23, 22, 20, 22, 21}; this->vertices.reserve(vertexCount); this->texCoords.reserve(vertexCount); this->normals.reserve(vertexCount); this->indices.reserve(indexCount); for (int i = 0; i < vertexCount; ++i) { vertices[i * 3 + 0] *= boxSize; vertices[i * 3 + 1] *= boxSize; vertices[i * 3 + 2] *= boxSize; this->vertices.push_back(Math::vec3f(vertices[i * 3 + 0], vertices[i * 3 + 1], vertices[i * 3 + 2])); this->normals.push_back(Math::vec3f(normals[i * 3 + 0], normals[i * 3 + 1], normals[i * 3 + 2])); this->texCoords.push_back(Math::vec2f(texCoords[i * 2 + 0], texCoords[i * 2 + 1])); } for (int i = 0; i < indexCount; ++i) this->indices.push_back(indices[i]); return true; } bool Box::InitializeVBO() { glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof (GLfloat) * 3 * vertices.size(), &vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &normalBuffer); glBindBuffer(GL_ARRAY_BUFFER, normalBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof (GLfloat) * 3 * normals.size(), &normals[0], GL_STATIC_DRAW); glGenBuffers(1, &texCoordBuffer); glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof (GLfloat) * 2 * texCoords.size(), &texCoords[0], GL_STATIC_DRAW); glGenBuffers(1, &indexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof (GLuint) * indices.size(), &indices[0], GL_STATIC_DRAW); return true; } bool Box::InitializeVBA() { glGenVertexArrays(1, &vertexArray); glBindVertexArray(vertexArray); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, normalBuffer); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(2); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); glBindVertexArray(0); return true; } void Box::SetShader(NGE::Media::Shaders::GLSLProgram* shader) { this->shader = shader; } void Box::SetTexture(NGE::Media::Images::Texture* texture) { this->texture = texture; } void Box::Update(float deltaTime) { } void Box::Render() { if (shader == NULL) return; shader->BindShader(); //texture->Activate(); shader->sendUniform4x4("modelview_matrix", Rendering::Renderer::GetInstance().GetMatrixStack().GetMatrix(MODELVIEW_MATRIX)); shader->sendUniform4x4("projection_matrix", Rendering::Renderer::GetInstance().GetMatrixStack().GetMatrix(PROJECTION_MATRIX)); shader->sendUniform("in_color", Math::vec4f(0.55f, 0.26f, 0.27f)); //shader->SendUniform("texture0", 0); glBindVertexArray(vertexArray); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); shader->UnbindShader(); }
true
4e5025d64313553c3310bb28329a6cefc4e27a67
C++
SoulPoet/ITCG_coding_project
/CommonFunc.cpp
UTF-8
2,859
2.90625
3
[]
no_license
#include "CommonFunc.h" const int A = 48271; const long M = 2147483647; const int Q = M / A; const int R = M % A; long int state; bool normal_flag; CodeWord::CodeWord(int codeword_len) { len = codeword_len; cw = new int[codeword_len]; } CodeWord::~CodeWord() { delete[] cw; } CodeWord CodeWord::operator + (const CodeWord &t) const { CodeWord rst(len); for(int i = 0; i < len; ++i) rst.cw[i] = cw[i] ^ t.cw[i]; return rst; } void SetSeed(int flag) { if (flag < 0) state = 17; else if (flag == 0) { state = 0; while (state == 0) { srand((unsigned)time(NULL)); state = rand(); } } else { fprintf(stdout, "\nEnter the initial state: "); fscanf(stdin, "%ld", &state); } normal_flag = false; } void PrintState(FILE *fp) { fprintf(fp, "\n***init_state = %ld***\n", state); } double Uniform(double a, double b, long int &seed) { seed = 2045 * seed + 1; seed %= 1048576; double rst = seed / 1048576.0; rst = a + (a - b) * rst; return rst; } double Uniform() { double u; int tmpState = A * ( state % Q ) - R * ( state / Q ); if ( tmpState >= 0) { state = tmpState; } else { state = tmpState + M; } u = state / (double)M; return u; } double Gauss(double mean, double segma, long int &seed) { double rst = 0.0; for(int i = 0; i < 12; ++i) rst += Uniform(0.0, 1.0, seed); rst = mean + (rst - 6.0) * segma; return rst; } double Normal(double mean, double segma) { static double x1, x2, w; if(normal_flag) { normal_flag = false; return mean + segma * x2 * w; } w = 2.0; while (w > 1.0){ x1 = 2.0 * Uniform() - 1.0; x2 = 2.0 * Uniform() - 1.0; w = x1 * x1 + x2 * x2; } w = sqrt(-2.0 * log(w) / w); normal_flag = true; return mean + segma * x1 * w; } int HammingDistance(int *str1, int *str2, int len) { int rst = 0; for(int i = 0; i < len; ++i) if(str1[i] != str2[i]) ++rst; return rst; } FILE* OpenFile(const char *file_path, const char *mode) { FILE *fp = fopen(file_path, mode); if(fp == NULL) { fprintf(stderr, "\n Cannot open the file \"%s\"!!!\n", file_path); exit(1); } return fp; } double SNR(double sigal_power, double noise_power) { return 10.0 * log10(sigal_power / noise_power); } void Debug(char *var_name, int val) { printf("\nDebug:%s=%d\n", var_name, val); } void Debug(char *var_name, double val) { printf("\nDebug:%s=%f\n", var_name, val); } void Debug(char *var_name, char *str) { printf("\nDebug:%s=%s\n", var_name, str); }
true
d5a595132b2334977ba4370de9a4587c2b7a9a2f
C++
guardiancrow/clipss
/PNGChunk.h
UTF-8
1,067
2.671875
3
[ "MIT" ]
permissive
//Copyright (C) 2014 - 2016, guardiancrow #pragma once #ifndef _PNGCHUNK_H_ #define _PNGCHUNK_H_ #include "CRC32.hpp" class PNGChunk { public: PNGChunk(){ ChunkType = new char[5]; memset(ChunkType, 0, 5); ChunkData = NULL; Size = 0; CRC = 0; Offset = 0; isCritial = false; isPublic = false; isReserved = false; isCopySafe = false; crcStatus = false; } virtual ~PNGChunk(){ delete [] ChunkType; ChunkType = NULL; if(ChunkData){ delete [] ChunkData; ChunkData = NULL; } Size = 0; CRC = 0; Offset = 0; isCritial = false; isPublic = false; isReserved = false; isCopySafe = false; crcStatus = false; } bool Check_CRC(){ CRC32 crc; unsigned long newcrc = 0; newcrc = crc.pngchunkcrc((unsigned char*)ChunkType, 4, (unsigned char*)ChunkData, Size); return (newcrc - CRC == 0)?true:false; } unsigned long Size; unsigned long Offset; unsigned long CRC; char *ChunkType; unsigned char *ChunkData; bool isCritial; bool isPublic; bool isReserved; bool isCopySafe; bool crcStatus; }; #endif
true
fab7416a78017d445e3ecebea5af2033ea4f3856
C++
ivandryi/csci333-queue
/src/AQueue/AQueue.h
UTF-8
571
3.078125
3
[]
no_license
#ifndef __AQUEUE_H__ #define __AQUEUE_H__ class AQueue { private: int* theQueue; // array that holds the elements of the queue int front; // references the first element in the queue int back; // references the last element in the queue int numOfElements; // stores number of elements in the queue int capacity; // stores the maximum queue size, its capacity int initSize; // stores the initial size of the queue public: AQueue(int maxSize); ~AQueue(); int dequeue(); void enqueue(int value); int size(); bool isEmpty(); }; #endif
true
971325d9ab4d068938ac456d9aeac41d88c3b448
C++
Yhatoh/Programacion_competitiva
/codeforces/1030A-In_Search_Of_An_Easy_Problem.cpp
UTF-8
303
2.53125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.setf(ios::fixed); cout.precision(4); int n, x; cin >> n; while(n--){ cin >> x; if(x == 1) break; } cout << (x == 1 ? "HARD" : "EASY") << "\n"; return 0; }
true
48cbbf8e31f85faed46cb7f2fc84fb5e613be025
C++
Klaudiaklaudia98/repo158251
/mysin.h
UTF-8
848
3.140625
3
[ "MIT" ]
permissive
#ifndef MYSIN_H #define MYSIN_H class MySin { //! \defgroup 1 metody_publiczne public: //! \{ /**publiczna metoda MySin()*/ MySin(); /**publiczna metoda MySin(double x)*/ MySin(double x); /**publiczna metoda MySin(const MySin &obj)*/ MySin(const MySin &obj); /**publiczna metoda ~MySin()*/ ~MySin(); /**publiczna metoda double value()*/ /** Funkcja \b value ma zwracać wartość \b sin(x) która jest wyliczona na podstawie pierwszych 10 wyrazów szeregu \f$sin(x)=\sum_{k=0}^\infty (-1)^k\frac{x^{2k+1}}{(2k+1)!}.\f$ \image html sinusx.png */ double value(); /**publiczna metoda void setX(double)*/ void setX(double); /**publiczna metoda double getX()*/ double getX(); //! \} //! \defgroup 2 składowe_prywatne private: //! \{ /**Składowa prywatna */ double mX(); //! \} }; #endiff //MYSIN_H
true
3fac1f84df115ab954117db2420c95fbc6f843aa
C++
MTM-Almog-Tom/ex2
/part2/Sniper.cpp
UTF-8
2,756
3.046875
3
[]
no_license
#include "Sniper.h" namespace mtm { Sniper::Sniper(int health, int ammo, int range, int power, Team team) : Character(health, ammo, range, power, team), attack_counter(1) {} //constructor Sniper::Sniper(const Sniper &copy_from) : Character(copy_from) {} //copy constructor Sniper &Sniper::operator=(const Sniper &copy_from) { Character::operator=(copy_from); return *this; } shared_ptr<Character> Sniper::clone() const { shared_ptr<Character> ptr(new Sniper(*this)); return ptr; } //geters int Sniper::getMovmentRange() const { return movment_range; } int Sniper::getAttackAmmoCost() const { return attack_ammo_cost; } void Sniper::characterAttack(const GridPoint &src_coordinates, const GridPoint &dst_coordinates, vector<vector<std::shared_ptr<Character>>> board, int height, int width) { if (board[src_coordinates.row][src_coordinates.col]->getRange() < mtm::GridPoint::distance(src_coordinates, dst_coordinates)) { throw OutOfRange(); } if (((board[src_coordinates.row][src_coordinates.col]->getRange() + 1) / 2) > mtm::GridPoint::distance(src_coordinates, dst_coordinates)) { throw OutOfRange(); } if (ammo < attack_ammo_cost) { throw OutOfAmmo(); } if (board[dst_coordinates.row][dst_coordinates.col] == nullptr) { throw IllegalTarget(); } else if (board[dst_coordinates.row][dst_coordinates.col]->getTeam() == this->getTeam()) { throw IllegalTarget(); } if (board[dst_coordinates.row][dst_coordinates.col]->getTeam() != this->getTeam()) { if (this->attack_counter == 3) { board[dst_coordinates.row][dst_coordinates.col]->setHealth(-(power * 2)); this->attack_counter = 1; } else { board[dst_coordinates.row][dst_coordinates.col]->setHealth(-power); this->attack_counter++; } // if (board[dst_coordinates.row][dst_coordinates.col]->getHealth() <= 0) // { // board[dst_coordinates.row][dst_coordinates.col] = nullptr; // } ammo--; } } void Sniper::characterReload(const GridPoint &coordinates) { ammo = ammo + load_ammo; } char Sniper::getChar() { return 'n'; } Sniper::~Sniper() { } }
true
1cdf75abd6f31e1c954bd9504319afb053e3cc5c
C++
zhaoxuyang13/distributed-system
/lab1-rdt/rdt_receiver.cc
UTF-8
5,491
2.703125
3
[]
no_license
/* * FILE: rdt_receiver.cc * DESCRIPTION: Reliable data transfer receiver. * NOTE: This implementation assumes there is no packet loss, corruption, or * reordering. You will need to enhance it to deal with all these * situations. In this implementation, the packet format is laid out as * the following: * * |<- 1 byte ->|<- the rest ->| * | payload size |<- payload ->| * * The first byte of each packet indicates the size of the payload * (excluding this single-byte header) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <list> #include "rdt_struct.h" #include "rdt_receiver.h" #include "utils.h" static bool buffer_flag[SEQUNCE_SIZE] = {}; static struct message * msg_buffer[SEQUNCE_SIZE] = {}; static seq_nr_t expected_seq = 0; static std::list<struct message *> submit_buffer; /* receiver initialization, called once at the very beginning */ void Receiver_Init() { fprintf(stdout, "At %.2fs: receiver initializing ...\n", GetSimulationTime()); } /* receiver finalization, called once at the very end. you may find that you don't need it, in which case you can leave it blank. in certain cases, you might want to use this opportunity to release some memory you allocated in Receiver_init(). */ void Receiver_Final() { fprintf(stdout, "At %.2fs: receiver finalizing ...\n", GetSimulationTime()); } void Ack_seq(seq_nr_t seq_num){ fprintf(stdout, "At %.2fs: Receiver: ack seq %d send \n", GetSimulationTime(), seq_num); packet pkt; pkt.data[2] = 0; pkt.data[3] = seq_num; uint16_t checksum = crc_16((const unsigned char *)(pkt.data + 2), 2); memcpy(pkt.data, &checksum, 2); Receiver_ToLowerLayer(&pkt); } static void SubmitMsg(struct message* msg, bool last_pkt){ ASSERT(msg); if(last_pkt){// build msg and to upper layer int size = 0; for(auto message : submit_buffer){ size += message->size; } size += msg->size; struct message *final_msg = (struct message *) malloc(sizeof(struct message)); final_msg->size = size; final_msg->data = (char *)malloc(size); int cursor = 0; for(auto& message :submit_buffer){ memcpy(final_msg->data+cursor, message->data, message->size); cursor += message->size; free(message->data); free(message); } memcpy(final_msg->data+cursor, msg->data, msg->size); fprintf(stdout,"submiting \n"); Receiver_ToUpperLayer(final_msg); free(msg->data); free(msg); submit_buffer.clear(); }else{ submit_buffer.push_back(msg); } } /* event handler, called when a packet is passed from the lower layer at the receiver */ void Receiver_FromLowerLayer(struct packet *pkt) { /* 2-byte header indicating the chsum */ /* 1-byte header indicating the size of the payload */ /* 1-byte header indicating sequence number */ int header_size = 4; /* construct a message and deliver to the upper layer */ struct message *msg = (struct message*) malloc(sizeof(struct message)); // if not using unsigned char , computation of this value will be signed and negative. msg->size = (unsigned char) pkt->data[2]; int seq_num = pkt->data[3] & 127; bool last_pkt = (pkt->data[3] & 128) != 0; fprintf(stdout, "At %.2fs: Receiver: receive %d, expect %d, is last %d ,size %d\n", GetSimulationTime(), seq_num, expected_seq,last_pkt,msg->size); /* sanity check in case the packet is corrupted */ // int checklength = (unsigned char)msg->size + 2; int checklength = msg->size + 2; // fprintf(stdout,"checklength,%d\n",checklength); if ( *(uint16_t*)(pkt->data) != crc_16((const unsigned char *)pkt->data + 2,checklength)) { fprintf(stdout, "At %.2fs: packet checksum mismatch\n", GetSimulationTime()); return ; } // if msg size out of bounds. it will be detected by checksum. ASSERT(msg->size > 0 && msg->size <= RDT_PKTSIZE-header_size); if(!between(expected_seq, seq_num,(expected_seq + WINDOW_SIZE)% SEQUNCE_SIZE)){ fprintf(stdout, "At %.2fs: Receiver: packet %d, no in region\n", GetSimulationTime(), seq_num); Ack_seq((expected_seq - 1) % SEQUNCE_SIZE); return ; } /* send mesg to upper layer */ msg->data = (char*) malloc(msg->size); ASSERT(msg->data); memcpy(msg->data, pkt->data+header_size, msg->size); if(seq_num == expected_seq){ // this seq num, update state. SubmitMsg(msg,last_pkt); inc(expected_seq, SEQUNCE_SIZE); //flush receive buffer to msg slices. while (msg_buffer[expected_seq] != nullptr) { SubmitMsg(msg_buffer[expected_seq], buffer_flag[expected_seq]); msg_buffer[expected_seq] = nullptr; buffer_flag[expected_seq] = false; inc(expected_seq, SEQUNCE_SIZE); } //reply ack for this seqnum. Ack_seq((expected_seq - 1) % SEQUNCE_SIZE); }else { // other seq num, store in buffer if(msg_buffer[seq_num] == nullptr){ msg_buffer[seq_num] = msg; buffer_flag[seq_num ] = last_pkt; } else { /* don't forget to free the space */ if (msg->data!=NULL) free(msg->data); if (msg!=NULL) free(msg); } } }
true
24b7403a52de56efca6a48c17da32cc9f2001c91
C++
loloof64/ChessTrainingVsEngine
/libs/chessx-pgn/database/partialdate.h
UTF-8
3,369
3.015625
3
[ "MIT" ]
permissive
/*************************************************************************** * (C) 2005-2009 Michal Rudolf <mrudolf@kdewebdev.org> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #ifndef PARTIALDATE_H_INCLUDED #define PARTIALDATE_H_INCLUDED #include <QString> #include <QDateTime> /** @ingroup Database The PartialDate class represents a date, perhaps with missing month and day. All comparison operators should work. */ class PartialDate { public: enum {Year = 1, Month = 2, Day = 4, All = Year | Month | Day}; /** Constructor */ PartialDate(int y = 0, int m = 0, int d = 0); /** String constructor. Creates date from PGN date format (e.g. "1990.01.??"). */ explicit PartialDate(const QString& s); /** QDate constructor. */ explicit PartialDate(const QDate& d); /** Converts date to QDate. Undefined parts will be replaced with 0 for year, 1 for month and day */ QDate asDate() const; /** Converts date to string. Uses PGN date format (e.g. "1990.01.??"). */ QString asString() const; /** Converts date to string. Uses short format (e.g. "1990", "1990.01", "1990.01.15"). Optionally saves just a part of date. */ QString asShortString(int part = All) const; static PartialDate today(); /** @return year, @p 0 if undefined. */ int year() const; /** @return month, @p 0 if undefined. */ int month() const; /** @return day, @p 0 if undefined. */ int day() const; /** Sets date from string in PGN date format (e.g. "1990.01.??"). */ PartialDate& fromString(const QString& s); /** @return formatted date range (e. g. "1990.01.12-02.13", "1992-1997.11.12") */ QString range(const PartialDate& d) const; /** Test if PartialDate is valid */ bool isValid() const; PartialDate(const PartialDate& rhs) { *this = rhs; } PartialDate& operator= (const PartialDate& rhs) { if(this != &rhs) { m_bIsValid = rhs.m_bIsValid; m_year = rhs.m_year; m_month = rhs.m_month; m_day = rhs.m_day; } return *this; } friend bool operator==(const PartialDate& d1, const PartialDate& d2); friend bool operator>=(const PartialDate& d1, const PartialDate& d2); friend bool operator<=(const PartialDate& d1, const PartialDate& d2); friend bool operator<(const PartialDate& d1, const PartialDate& d2); friend bool operator>(const PartialDate& d1, const PartialDate& d2); friend bool operator!=(const PartialDate& d1, const PartialDate& d2); private: short int m_year; unsigned char m_month; unsigned char m_day; bool m_bIsValid; QString numberToString(int d, QChar fill = '0') const; }; const PartialDate PDMaxDate(9999); const PartialDate PDMinDate(1); const PartialDate PDInvalidDate(0, 0, 0); #endif
true
08c30c653dcdd066fbcdab8efe070f20cd754340
C++
AndreOliver/SpaceFlight-Game
/ShipSprite.h
UTF-8
1,216
2.515625
3
[]
no_license
#pragma once #include "tsprite.h" class ShipSprite : public TSprite { public: ShipSprite(sf::Texture & texture) { setPosition(sf::Vector2f((float)-(rand()%200+100),(float)-(rand()%200+100))); setSpeed(sf::Vector2f((float)(rand()%200+20),(float)(rand()%200+20))); setAcceleration(sf::Vector2f((float)(rand()%30-10),(float)(rand()%30-10))); setTexture(texture); setColor(TGraphic::randColor()); baseSprite.setScale(sf::Vector2f(0.5f,0.5f)); bounce=true; rotation=0; rotationSpeed=0; rotationAcceleration=0; } virtual void update(sf::Time elapsed) { position.x+=rand()%5-rand()%5; switch(state) { case 0: if(rand()%300 == 0) { rotationSpeed=108000.0; state=1; } break; case 1: if(rand()%300 == 0) { rotationSpeed=0; speed=sf::Vector2f(0,0); state=2; } break; case 2: if(rand()%300 == 0) { rotationSpeed=0; state=0; speed=sf::Vector2f(rand()*300,rand()%300); } break; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::G)) { setSpeed(sf::Vector2f((float)(0),(float)(0))); setPosition(sf::Vector2f((float)-(800),(float)-(800))); } TSprite::update(elapsed); } virtual ~ShipSprite(void) { } };
true
d803b15689bb8b1e6c132bb7ad971b18f5a9838a
C++
theaksharapathak/c-prog-assignments
/lab6.24.cpp
UTF-8
444
3.4375
3
[]
no_license
#include<stdio.h> int power(int base,int powerRaised); int main() { int base,powerRaised,result; printf("enter base no\n"); scanf("%d",&base); printf("enter power no(positive integer):\n"); scanf("%d",&powerRaised); result=power(base,powerRaised); printf("%d ^ %d = %d",base,powerRaised,result); return 0; } int power(int base,int powerRaised) { if(powerRaised!=0) return (base*power(base,powerRaised-1)); else return 1; }
true
b348d1c36ac45af3761b7cf10654680430ee7dea
C++
rvbc1/BLDC_DRIVER
/Inc/LedDriver.h
UTF-8
1,251
2.609375
3
[]
no_license
/* * LedDriver.h * * Created on: Apr 13, 2019 * Author: rvbc- */ #ifndef LEDDRIVER_H_ #define LEDDRIVER_H_ #include "stm32f3xx_hal.h" class Led_Driver { private: uint32_t pin; uint16_t start_pin; uint16_t end_pin; GPIO_TypeDef* port; void init(GPIO_TypeDef* port, uint16_t start_pin, uint16_t end_pin); public: Led_Driver(GPIO_TypeDef* port, uint16_t start_pin, uint16_t end_pin); void setAll(GPIO_PinState state); void allOn(); void allOff(); void allToggle(); void blink(uint32_t duration_ms); void showIntro(); void turnRightSET(uint16_t start_led_pin, uint32_t duration_ms); void turnLeftSET(uint16_t start_led_pin, uint32_t duration_ms); uint16_t circleLeft(uint16_t start_led_pin, uint32_t duration_ms, GPIO_PinState state); uint16_t circleRight(uint16_t start_led_pin, uint32_t duration_ms, GPIO_PinState state); void circleRightToggle(uint16_t start_led_pin, uint32_t duration_ms); void circleRightBack(uint16_t start_led_pin, uint32_t duration_ms); void circleRightFront(uint16_t start_led_pin, uint32_t duration_ms); void showSET(uint16_t led_pin); void showSET(uint8_t pos); void showRESET(uint16_t led_pin); void showRESET(uint8_t pos); virtual ~Led_Driver(); }; #endif /* LEDDRIVER_H_ */
true
3281219be09ac8fa4692a561aa36509c04b6b2ae
C++
arvind96/AGame-Engine
/AGame Engine/Engine/Input.cpp
UTF-8
2,693
3.15625
3
[]
no_license
#include "Input.h" #include <string> namespace AGameEngine { SDL_Event Input::_singleHitKeyEvent; const Uint8* Input::_continuousKey; Input::Input() { } Input::~Input() { } void Input::ProcessInput() { /* const Uint8* keystate = SDL_GetKeyboardState(NULL); //Continuous response keys if (keystate[SDL_SCANCODE_LEFT]) { xInput = -1.0f; } else if (keystate[SDL_SCANCODE_RIGHT]) { xInput = 1.0f; } else { xInput = 0.0f; } if (keystate[SDL_SCANCODE_UP]) { yInput = 1.0f; } else if (keystate[SDL_SCANCODE_DOWN]) { yInput = -1.0f; } else { yInput = 0.0f; } */ //Continuous key processing _continuousKey = SDL_GetKeyboardState(NULL); //Single hit key event SDL_Event event; //Create a new event to overide the older values SDL_PollEvent(&event); _singleHitKeyEvent = event; //if(_singleHitKeyEvent.type == SDL_MOUSEMOTION) //std::cout << "Motion: " << _singleHitKeyEvent.motion.y << std::endl; //if(_singleHitKeyEvent.type == SDL_MOUSEBUTTONDOWN) // std::cout << "Mouse Button Down: " << _singleHitKeyEvent.button.button << std::endl; /* //Single hit keys, mouse, and other general SDL events (eg. windowing) SDL_Event event; while (SDL_PollEvent(&event)) { std::cout << "R pressed" << std::endl; switch (event.type) { case SDL_MOUSEMOTION: break; case SDL_QUIT: break; case SDL_KEYDOWN: std::cout << "Key pressed down" << std::endl; if (event.key.keysym.sym == SDLK_ESCAPE) std::cout << "R pressed" << std::endl; break; } } */ } vec2 Input::GetMousePosition() { return vec2(_singleHitKeyEvent.motion.x, _singleHitKeyEvent.motion.y); } vec2 Input::GetMousePositionDelta() { if (_singleHitKeyEvent.type == SDL_MOUSEMOTION) { return vec2(_singleHitKeyEvent.motion.xrel, _singleHitKeyEvent.motion.yrel); } else { return vec2(0, 0); } } bool Input::GetKey(SDL_Scancode scancode) { if (_continuousKey[scancode]) { return true; } else { return false; } } bool Input::GetKeyDown(SDL_Keycode keycode) { if (_singleHitKeyEvent.type == SDL_KEYDOWN) { if (_singleHitKeyEvent.key.keysym.sym == keycode) { return true; } else { return false; } } else { return false; } } bool Input::GetKeyUp(SDL_Keycode keycode) { if (_singleHitKeyEvent.type == SDL_KEYUP) { if (_singleHitKeyEvent.key.keysym.sym == keycode) { return true; } else { return false; } } else { return false; } } bool Input::Quit() { if (_singleHitKeyEvent.type == SDL_QUIT) { return true; } else { return false; } } }
true
ecffd7c7fc5e89c38bd5d6fc2191559b39d74da5
C++
iceysteel/CS2
/lab_6/src/Time.cpp
UTF-8
2,294
3.171875
3
[]
no_license
#include "Time.h" #include <iostream> #include <iomanip> #include <string> using namespace std; Time::Time(int y, string mo, int d, int h, int m, int s) { setTime(y, mo, d, h, m, s); } void Time::setTime(int y, string mo, int d, int h, int m, int s) { setYear(y); setMonth(mo); setDay(d); setHr(h); setMin(m); setSec(s); } void Time::setYear(int y) { year = y; } void Time::setMonth(string mo) { month = mo; } void Time::setDay(int d) { day = (d >= 0 && d < 31) ? d : 0; } void Time::setHr(int h) { hour = (h >= 0 && h < 24) ? h : 0; } void Time::setMin(int m) { minute = (m >= 0 && m < 60) ? m : 0; } void Time::setSec(int s) { second = (s >= 0 && s < 60) ? s : 0; } int Time::getYear() const { return year; } string Time::getMonth() const { return month; } int Time::getDay() const { return day; } int Time::getHr() const { return hour; } int Time::getMin() const { return minute; } int Time::getSec() const { return second; } void Time::printUniversal() const { cout << month << " " << day << ", " << year << " /// " << setfill('0') << setw(2) << hour << " : " << setw(2) << minute << " : " << setw(2) << second << endl; } void Time::Tic(int y, string mo, int d, int h, int m, int s) { string arrayMo[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; int j = 0; for ( int i = 0; i < 12; i++) { if (mo == arrayMo[i]) j=i; } if (s < 59) second = s + 1; if (m < 59 && s == 59) { minute = m + 1; second = 0; } if (h < 10 && m == 59 && s == 59) { hour = h + 1; minute = 0; second = 0; } if ( d < 31 && h==11 && m==59 && s==59) { day = day + 1; hour = 0; minute = 0; second = 0; } if ( j < 11 && d == 31 && h==11 && m==59 && s==59) { month = arrayMo[j+1]; day = 0; hour = 0; minute = 0; second = 0; } if ( j == 11 && d == 31 && h==11 && m==59 && s==59) { year = y + 1; month = arrayMo[0]; day = 0; hour = 0; minute = 0; second = 0; } }
true
600ec7f2670b131d9309def419cd2ec41b375dcf
C++
4l3dx/DBOGLOBAL
/NtlLib/Server/NtlNetwork/PeekerQueue.cpp
UTF-8
2,173
2.625
3
[]
no_license
#include "stdafx.h" #include "PeekerQueue.h" #include "assert.h" CPeekerQueue::CPeekerQueue(UINT64 nBufferLimit) { m_nBufferLimit = nBufferLimit; } CPeekerQueue::~CPeekerQueue() { Clear(); } void CPeekerQueue::Clear() { CPeeker peeker; while (this->size()) { peeker = this->front(); peeker.Release(); this->pop_front(); } this->clear(); } bool CPeekerQueue::IsEmpty() { if (this->size() == 0) return true; if (this->size() == 1) { return this->front().IsEmpty(); } return false; } void CPeekerQueue::SetBufferLimit(UINT64 nLimit) { m_nBufferLimit = nLimit; } void CPeekerQueue::Add(CPacketBlock * pBlock) { CPeeker peeker(pBlock); this->push_back(peeker); } void CPeekerQueue::Add(CPeekerQueue * peek) { if (peek->IsEmpty() == false) { for (std::deque<CPeeker>::iterator it = this->begin(); it != this->end(); it++) { CPeeker& peeker = *it; peek->push_back(peeker); peeker.SetReference(); } } } CPacketBlock * CPeekerQueue::GetPacketBlock(DWORD dwRequiredSize) { CPeeker peeker; CPacketBlock* pBlock = NULL; if (this->size()) { peeker = this->back(); pBlock = peeker.GetPacketBlock(dwRequiredSize); } if (pBlock == NULL) { if (m_nBufferLimit && this->size() > m_nBufferLimit) { return NULL; } if (dwRequiredSize < c_nDefaultLimit) dwRequiredSize = c_nDefaultLimit; pBlock = peeker.CreatePacketBlock(dwRequiredSize); this->push_back(peeker); } return pBlock; } void CPeekerQueue::RemoveMsg(DWORD dwBytesRemoved) { while (dwBytesRemoved > 0) { assert(size() > 0); CPeeker& peeker = this->front(); if (this->size() == 1) { if (peeker.ReleaseRecyclic(dwBytesRemoved)) this->pop_front(); return; } if (peeker.Release(dwBytesRemoved)) this->pop_front(); } } int CPeekerQueue::PeekBuf(LPWSABUF pWsaBuf, int nWsaBufCount, int& rnSendBufCount) { rnSendBufCount = 0; if (IsEmpty()) { return 1; } for (std::deque<CPeeker>::iterator it = this->begin(); it != this->end(); it++) { CPeeker& peeker = *it; if (nWsaBufCount > rnSendBufCount) { if (peeker.ReadyForSending(pWsaBuf)) ++rnSendBufCount; } } return rnSendBufCount; }
true
dc656efb0e51de023506f52e001419ae7b42243f
C++
jacgoldberg/Assignment2
/Main.cpp
UTF-8
2,016
3.109375
3
[]
no_license
#include <iostream> #include <fstream> #include <cstdlib> #include "myGrid.h" #include <thread> #include <chrono> using namespace std; bool start(){ bool a; cout << "Would you like to begin?(1/0)" << endl; cin >> a; return a; } void flair(){ cout << " ---------WELCOME TO THE GAME OF LIFE---------" << endl; } int main(int argc, char **argv){ char answer = '\0'; int rowLength = 0; int colLength = 0; double inPopDensity = 0.0; myGrid* map; bool ent = false; bool fileBool = false; if(start()){ flair(); //inital user prompting char answer = '\0'; string fileName = "\0"; cout << "Would you like to provide a file map for the game or use a randomly generated one? (F/R)" << endl; cin >> answer; if(answer == 'F'){ cout << "Please enter the name of the .txt file: " << endl; cin >> fileName; map = new myGrid(fileName); } else{ //Random variable prompting cout << "What would you like the width of your world to be?: " << endl; cin >> rowLength; cout << "What would you like the length of your world to be?: " << endl; cin >> colLength; cout << "What would you like your initial population density to be?(1 > x > 0): " << endl; cin >> inPopDensity; map = new myGrid(rowLength, colLength, inPopDensity); map->fill(); } cout << "Which mode would you Like?\nDefault: (D)\nDonut/Torus: (T)\nMirror: (M)" << endl; cin >> answer; map->print(); if(answer == 'D'){ map->setMode(1); while(!(map->isEmpty())){ map->populate(); map->print(); } } if(answer == 'T'){ while(map->isEmpty() /* && isOsolating()*/){ map->setMode(2); map->populate(); map->print(); } } if(answer == 'M'){ map->setMode(3); while(!(map->isEmpty()) /* && isOsolating()*/){ map->populate(); map->print(); } } } }
true
aa6a95bf3d8105518b33fc30ed7f6cc333bd9a45
C++
mijanur-rahman-40/C-C-plus-plus-Online-Judge-Algorithms-Practise-Programming
/Bestt_algorithm Based problems code/C++ .STL Container/Map problems/Multimap/count.cpp
UTF-8
582
3.328125
3
[]
no_license
#include <iostream> #include <map> using namespace std; int main () { multimap<char,int> my; my.insert(make_pair('x',50)); my.insert(make_pair('y',100)); my.insert(make_pair('y',150)); my.insert(make_pair('y',200)); my.insert(make_pair('z',250)); my.insert(make_pair('z',300)); for (char c='x'; c<='z'; c++) { cout<<"There are"<< my.count(c)<<" elements with key "<< c << ":"; multimap<char,int>::iterator it; for (it=my.equal_range(c).first; it!=my.equal_range(c).second; ++it) cout << ' ' << (*it).second; cout << '\n'; } return 0; }
true
a400acf6a784eb46917dc55a8d00941001b20673
C++
NullStudio/NoNameGame
/src/Game.cpp
UTF-8
3,151
2.78125
3
[]
no_license
#include "Game.hpp" #include "SCredits.hpp" #include "SMenu.hpp" Game& Game::GetInstance() { static Game self; return self; } Game::Game() : mInput( mApp.GetInput() ), mStateManager( StateManager::GetInstance() ), mResourceManager( ResourceManager::GetInstance() ), mIsRunning(false) { } Game::~Game() { mIsRunning = false; } sf::RenderWindow& Game::GetApp() { return mApp; } void Game::Init(std::string theTitle) { std::cout << "Game::Init" << std::endl; mIsRunning = true; std::cout << "mApp.Create" << std::endl; mApp.Create(sf::VideoMode(1024, 768, 32), theTitle); //mApp.Create(sf::VideoMode(1024, 768, 32), theTitle, sf::Style::Fullscreen); //mApp.Create(sf::VideoMode(1024, 768, 32), "OLAF Game Test", sf::Style::Fullscreen); std::cout << "mApp.Create post" << std::endl; //mApp.ShowMouseCursor(true); mApp.EnableKeyRepeat(true); mApp.UseVerticalSync(true); mApp.SetFramerateLimit(60); //ResourceManager INIT //mResourceManager = new ResourceManager; mResourceManager.AddResourceDir("images/"); //StateManager INIT mStateManager.Register(this); mStateManager.AddActiveState(new(std::nothrow) SCredits(this) ); } void Game::End() { std::cout << "Game::End()" << std::endl; //delete mResourceManager; mApp.Close(); } int Game::Run() { Init("OLAF Game Test"); Loop(); return EXIT_SUCCESS; } void Game::Loop() { std::cout << "Game::Loop()" << std::endl; mApp.Display(); //EVENT LOOP HERE sf::Event Event; while( mIsRunning && mApp.IsOpened() ) { //Get current State GameState* ActualState = mStateManager.GetActiveState(); while( mApp.GetEvent(Event) ) { // Close window : exit if (Event.Type == sf::Event::Closed) End(); // Escape key : exit if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape)) End(); //Gained Focus if (Event.Type == sf::Event::GainedFocus) ActualState->Resume(); //Lost Focus if (Event.Type == sf::Event::LostFocus) ActualState->Pause(); /* switch(Event.Type) { case sf::Event::Closed: //ActualState->End(); End(); break; case sf::Event::GainedFocus: ActualState->Resume(); break; case sf::Event::LostFocus: ActualState->Pause(); break; case sf::Event::Resized: break; default: ActualState->HandleEvents(Event); break; } */ ActualState->HandleEvents(Event); } mApp.Clear(); //Current Scene Update & Draw HERE ActualState->Update(); ActualState->Draw(); mApp.Display(); } } void Game::SetView(const sf::View& view) { mApp.SetView(view); }
true
92b06245e352d7ca25da9b091f616932587104be
C++
withelm/Algorytmika
/leetcode/algorithms/c++/Car Pooling/Car Pooling.cpp
UTF-8
384
2.703125
3
[]
no_license
class Solution { public: bool carPooling(vector<vector<int>> &trips, int capacity) { vector<int> t(1000 + 10, 0); for (auto &x : trips) { for (int i = x[1]; i < x[2]; i++) { t[i] += x[0]; if (t[i] > capacity) return false; } } return true; } };
true
d568690fc28ef88f78dfcad7d7c9336b92e2e542
C++
qt/qtbase
/src/corelib/text/qlatin1stringmatcher.cpp
UTF-8
6,101
2.921875
3
[ "LicenseRef-scancode-unicode" ]
permissive
// Copyright (C) 2022 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qlatin1stringmatcher.h" #include <limits.h> QT_BEGIN_NAMESPACE /*! \class QLatin1StringMatcher \inmodule QtCore \brief Optimized search for substring in Latin-1 text. A QLatin1StringMatcher can search for one QLatin1StringView as a substring of another, either ignoring case or taking it into account. \since 6.5 \ingroup tools \ingroup string-processing This class is useful when you have a Latin-1 encoded string that you want to repeatedly search for in some QLatin1StringViews (perhaps in a loop), or when you want to search for all instances of it in a given QLatin1StringView. Using a matcher object and indexIn() is faster than matching a plain QLatin1StringView with QLatin1StringView::indexOf() if repeated matching takes place. This class offers no benefit if you are doing one-off matches. The string to be searched for must not be destroyed or changed before the matcher object is destroyed, as the matcher accesses the string when searching for it. Create a QLatin1StringMatcher for the QLatin1StringView you want to search for and the case sensitivity. Then call indexIn() with the QLatin1StringView that you want to search within. \sa QLatin1StringView, QStringMatcher, QByteArrayMatcher */ /*! Construct an empty Latin-1 string matcher. This will match at each position in any string. \sa setPattern(), setCaseSensitivity(), indexIn() */ QLatin1StringMatcher::QLatin1StringMatcher() noexcept : m_pattern(), m_cs(Qt::CaseSensitive), m_caseSensitiveSearcher(m_pattern.data(), m_pattern.data()) { } /*! Constructs a Latin-1 string matcher that searches for the given \a pattern with given case sensitivity \a cs. The \a pattern argument must not be destroyed before this matcher object. Call indexIn() to find the \a pattern in the given QLatin1StringView. */ QLatin1StringMatcher::QLatin1StringMatcher(QLatin1StringView pattern, Qt::CaseSensitivity cs) noexcept : m_pattern(pattern), m_cs(cs) { setSearcher(); } /*! Destroys the Latin-1 string matcher. */ QLatin1StringMatcher::~QLatin1StringMatcher() noexcept { freeSearcher(); } /*! \internal */ void QLatin1StringMatcher::setSearcher() noexcept { if (m_cs == Qt::CaseSensitive) { new (&m_caseSensitiveSearcher) CaseSensitiveSearcher(m_pattern.data(), m_pattern.end()); } else { QtPrivate::QCaseInsensitiveLatin1Hash foldCase; qsizetype bufferSize = std::min(m_pattern.size(), qsizetype(sizeof m_foldBuffer)); for (qsizetype i = 0; i < bufferSize; ++i) m_foldBuffer[i] = static_cast<char>(foldCase(m_pattern[i].toLatin1())); new (&m_caseInsensitiveSearcher) CaseInsensitiveSearcher(m_foldBuffer, &m_foldBuffer[bufferSize]); } } /*! \internal */ void QLatin1StringMatcher::freeSearcher() noexcept { if (m_cs == Qt::CaseSensitive) m_caseSensitiveSearcher.~CaseSensitiveSearcher(); else m_caseInsensitiveSearcher.~CaseInsensitiveSearcher(); } /*! Sets the \a pattern to search for. The string pointed to by the QLatin1StringView must not be destroyed before the matcher is destroyed, unless it is set to point to a different \a pattern with longer lifetime first. \sa pattern(), indexIn() */ void QLatin1StringMatcher::setPattern(QLatin1StringView pattern) noexcept { if (m_pattern.latin1() == pattern.latin1() && m_pattern.size() == pattern.size()) return; // Same address and size freeSearcher(); m_pattern = pattern; setSearcher(); } /*! Returns the Latin-1 pattern that the matcher searches for. \sa setPattern(), indexIn() */ QLatin1StringView QLatin1StringMatcher::pattern() const noexcept { return m_pattern; } /*! Sets the case sensitivity to \a cs. \sa caseSensitivity(), indexIn() */ void QLatin1StringMatcher::setCaseSensitivity(Qt::CaseSensitivity cs) noexcept { if (m_cs == cs) return; freeSearcher(); m_cs = cs; setSearcher(); } /*! Returns the case sensitivity the matcher uses. \sa setCaseSensitivity(), indexIn() */ Qt::CaseSensitivity QLatin1StringMatcher::caseSensitivity() const noexcept { return m_cs; } /*! Searches for the pattern in the given \a haystack starting from \a from. \sa caseSensitivity(), pattern() */ qsizetype QLatin1StringMatcher::indexIn(QLatin1StringView haystack, qsizetype from) const noexcept { if (m_pattern.isEmpty() && from == haystack.size()) return from; if (from >= haystack.size()) return -1; auto begin = haystack.begin() + from; auto end = haystack.end(); auto found = begin; if (m_cs == Qt::CaseSensitive) { found = m_caseSensitiveSearcher(begin, end, m_pattern.begin(), m_pattern.end()).begin; if (found == end) return -1; } else { const qsizetype bufferSize = std::min(m_pattern.size(), qsizetype(sizeof m_foldBuffer)); const QLatin1StringView restNeedle = m_pattern.sliced(bufferSize); const bool needleLongerThanBuffer = restNeedle.size() > 0; QLatin1StringView restHaystack = haystack; do { found = m_caseInsensitiveSearcher(found, end, m_foldBuffer, &m_foldBuffer[bufferSize]) .begin; if (found == end) { return -1; } else if (!needleLongerThanBuffer) { break; } restHaystack = haystack.sliced( qMin(haystack.size(), bufferSize + qsizetype(std::distance(haystack.begin(), found)))); if (restHaystack.startsWith(restNeedle, Qt::CaseInsensitive)) break; ++found; } while (true); } return std::distance(haystack.begin(), found); } QT_END_NAMESPACE
true
397cfaf320fb17da4342e8d7c63e365e519339cc
C++
romulosantos92/TrabalhoPesquisaOperacionalGurobi
/GurobiTestProj/SupportLib.cpp
UTF-8
2,374
3
3
[]
no_license
#include "SupportLib.h" void SupportLib::leArquivo() { char fileName[50] = "myFile.csv"; /* cout << "\nDigite o nome do arquivo:\n"; string str; //scanf("%s", fileName); gets(fileName);*/ //filename = ; ifstream Myfile(fileName); if (!Myfile.is_open()) { cout << "\nERROR!\n"; } else { string numberOfCalls, periodOfMinutes, averageHandlingTimeMinutes, requiredServiceLevel, targetAnswerTimeSeconds, maximumOccupancy, shrinkage; float serviceLvl, occupancy, shrink, avgHandlingTm; int nCalls, periodMin, tgtAnswerTm; string line, myStr; list<erlangRegister> registros; erlangRegister aux; while (getline(Myfile, line)) { stringstream ss(line); getline(ss, numberOfCalls, ','); getline(ss, periodOfMinutes, ','); getline(ss, averageHandlingTimeMinutes, ','); getline(ss, requiredServiceLevel, ','); getline(ss, targetAnswerTimeSeconds, ','); getline(ss, maximumOccupancy, ','); getline(ss, shrinkage, ','); nCalls = atoi(numberOfCalls.c_str()); periodMin = atoi(periodOfMinutes.c_str()); avgHandlingTm = atof(averageHandlingTimeMinutes.c_str()); serviceLvl = atof(requiredServiceLevel.c_str()); tgtAnswerTm = atoi(targetAnswerTimeSeconds.c_str()); occupancy = atof(maximumOccupancy.c_str()); shrink = atof(shrinkage.c_str()); aux = { nCalls, periodMin, avgHandlingTm, serviceLvl, tgtAnswerTm, occupancy,shrink }; registros.push_back(aux); } while (registros.size() > 0) { aux = registros.back(); registros.pop_back(); SupportLib::printRegister(aux); } } } void SupportLib::printRegister(erlangRegister e) { cout << endl << e.numberOfCalls << " - " << e.periodOfMinutes << " - " << e.averageHandlingTimeMinutes << " - " << e.requiredServiceLevel << " - " << e.targetAnswerTimeSeconds << " - " << e.maximumOccupancy << " - " << e.shrinkage; } int SupportLib::fatorial(int n) { if (n == 1) return n; else return n*SupportLib::fatorial(n - 1); }
true
fa88ed482acaf33dbd580b144b8afcfafb62498d
C++
Xumengqi0201/OJ
/PAT/Adavanced-level/1138/main2.cpp
UTF-8
786
2.984375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; vector <int> preorder , inorder; int n; void inpre(int inL, int inR, int preL, int preR); int main() { ios :: sync_with_stdio(false); cin.tie(0); cin >> n; preorder.resize(n); inorder.resize(n); for (int i = 0; i < n; i++){ cin >> preorder[i]; } for (int i = 0; i < n; i++){ cin >> inorder[i]; } inpre(0, n-1, 0, n-1); return 0; } void inpre(int inL, int inR, int preL, int preR){ if (inL > inR) return; int mid, val = preorder[preL]; for (mid = inL ; mid <= inR ; mid++){ if (inorder[mid] == val) break; } inpre(inL, mid-1, preL+1, preL+mid-inL); inpre(mid+1, inR, preL+mid-inL+1, preR); //递归到最左边直接输出结果并直接跳出程序。 cout << inorder[inL] <<'\n'; exit(0); }
true
ddbae3e906458fbf1cee5d123904d863d28c33da
C++
aranoy15/embedded-project
/src/lib/time/timer.cpp
UTF-8
550
2.828125
3
[]
no_license
#include <lib/time/timer.hpp> //#include <cassert> namespace lib::time { void Timer::start() { _start_time = Time::current(); _is_started = true; } void Timer::restart() { start(); } void Timer::stop() { _is_started = false; } bool Timer::has_expired(const Time& timeout) { //assert(is_started()); if (not is_started()) return false; if ((Time::current() - _start_time) >= timeout.as_time()) return true; return false; } Time Timer::elapsed() { return Time(Time::current() - _start_time); } }
true
9ce69a366ed61c22cc68dda37bdec3283cd26b2c
C++
uvazke/AtCoder
/ABC/ABC199/D.cpp
UTF-8
1,489
2.734375
3
[]
no_license
#include <cmath> #include <iostream> #include <queue> #include <vector> #define myFor(N) for (int i = 0; i < N; i++) #define myForFL(first, last) for (int i = first; i < last; i++) using namespace std; typedef struct { int nodeNum; vector<int> edgesTo; int color; } Node; vector<Node> nodes(N); int main(void) { int N, M, ans = 1; ; int A[20], B[20]; bool isChecked[20]; queue<Node> nextNodes; cin >> N >> M; myFor(N) { nodes[i].nodeNum = i; } myFor(M) { cin >> A[i] >> B[i]; nodes[A[i]].edgesTo.push_back(B[i]); nodes[B[i]].edgesTo.push_back(A[i]); } myFor(N) { isChecked[i] = false; } myFor(N) { if (!isChecked[i]) { ans *= 3; isChecked[i] = true; for (int j = 0; j < nodes[i].edgesTo.size(); j++) { if (!isChecked[nodes[i].edgesTo[j]]) { nextNodes.push(nodes[nodes[i].edgesTo[j]]); } } while (!nextNodes.empty()) { Node frontNode = nextNodes.front(); nextNodes.pop(); if (isChecked[frontNode.nodeNum]) { continue; } isChecked[frontNode.nodeNum] = true; for (int j = 0; j < nodes[i].edgesTo.size(); j++) { if (!isChecked[nodes[i].edgesTo[j]]) { nextNodes.push(nodes[nodes[i].edgesTo[j]]); } } } } } return 0; } void NodeCheck(Node node) { bool r = false, g = false, b = false; for (int i : node.edgesTo) { if (nodes[i].color == 1) { r = true; } } }
true
6e28fb8840324831a4153430ae74d0f423cff612
C++
LIAO-JIAN-PENG/CPE-One-Star-record
/STAR_33.cpp
EUC-JP
1,060
3.46875
3
[]
no_license
# include<stdio.h> # include<stdlib.h> # include<math.h> # pragma warning(disable: 4996) int isPrime(int); int reverse(int); int getDigit(int); int main() { /* 1. N is not prime., if N is not a Prime number. 2. N is prime., if N is Prime and N is not Emirp. 3. N is emirp., if N is Emirp. */ int num = 0; while (scanf("%d", &num) != EOF) { if (isPrime(num) && isPrime(reverse(num)) && num != reverse(num)) { printf("%d is emirp.\n", num); } else if (isPrime(num)) { printf("%d is prime.\n", num); } else{ printf("%d is not prime.\n", num); } } system("PAUSE"); return 0; } int isPrime(int n) { int i; for (i = 2; i <= int(sqrt(n)); i++) { if (n % i == 0) return 0; } return 1; } int reverse(int n) { int i = 0; int ren = 0; int digit = getDigit(n); for (i = digit - 1; i > -1; i--) { ren += (n % 10) * int(pow(10, i)); n /= 10; } return ren; } int getDigit(int n) { int i; for (i = 0; n; i++) { n /= 10; } return i; }
true
d5a74920639e616d155d7c38dee7f8c065ae9211
C++
xtachx/AutoBub3hs
/AlgorithmTraining/Trainer.cpp
UTF-8
8,644
2.609375
3
[]
no_license
#include <vector> #include <string> #include <dirent.h> #include <iostream> #include <stdexcept> #include <opencv2/opencv.hpp> #include "Trainer.hpp" #include "../LBP/LBPUser.hpp" #include "../ImageEntropyMethods/ImageEntropyMethods.hpp" #include "../common/UtilityFunctions.hpp" //#include "ImageEntropyMethods/ImageEntropyMethods.hpp" //#include "LBP/LBPUser.hpp" Trainer::Trainer(int camera, std::vector<std::string> EventList, std::string EventDir) { /*Give the properties required to make the object - the identifiers i.e. the camera number, and location*/ this->camera=camera; this->EventList = EventList; this->EventDir = EventDir; } Trainer::~Trainer(void ) {} /*! \brief Parse and sort a list of triggers from an event for a specific camera * * \param searchPattern * \return this->CameraFrames * * This function makes a list of all the file names matching the trigger * from a certain camera in a file and then makes aa sorted * list of all the images that can then be processed one by one . */ void Trainer::ParseAndSortFramesInFolder(std::string searchPattern, std::string ImageDir ) { /*Function to Generate File Lists*/ { DIR *dir = opendir (ImageDir.c_str()) ; if (dir) { /* print all the files and directories within directory */ struct dirent* hFile; while (( hFile = readdir( dir )) != NULL ) { if ( !strcmp( hFile->d_name, "." )) continue; if ( !strcmp( hFile->d_name, ".." )) continue; // in linux hidden files all start with '.' if ( hFile->d_name[0] == '.' ) continue; // dirFile.name is the name of the file. Do whatever string comparison // you want here. Something like: if ( strstr( hFile->d_name, searchPattern.c_str() )){ this->CameraFrames.push_back(std::string(hFile->d_name)); } } closedir (dir); std::sort(this->CameraFrames.begin(), this->CameraFrames.end(), frameSortFuncTrainer); } else { /* could not open directory */ //perror (""); this->StatusCode = 1; } } } /*! \brief Make sigma and mean of training images * * \return cv::Mat this->TrainedAvgImage * \return cv::Mat this->TrainedSigmaImage * * Function finds avg and std of all training frames */ void Trainer::CalculateMeanSigmaImageVector(std::vector<cv::Mat>& ImagesArray, cv::Mat& meanImageProcess, cv::Mat& sigmaImageProcess){ int rows, cols; rows = ImagesArray[0].rows; cols = ImagesArray[0].cols; /*Declare new variables for making the analyzed matrix*/ std::vector<cv::Mat>::size_type numImagesToProcess = ImagesArray.size(); sigmaImageProcess = cv::Mat::zeros(rows, cols, CV_8U); meanImageProcess = cv::Mat::zeros(rows, cols, CV_8U); std::vector<cv::Mat>::size_type processingFrame; /*few temp variables*/ float temp_variance=0; float temp_sigma=0; float temp_pixVal=0; float temp_mean=0; float temp_m2=0; float temp_delta=0; /*Make the sigma image*/ for (int row=0; row<rows; row++) { for (int col=0; col<cols; col++) { /*get the 1-D array of each layer*/ for (processingFrame=0; processingFrame<numImagesToProcess; processingFrame++ ) { temp_pixVal = (float) ImagesArray[processingFrame].at<uchar>(row, col); /*online mean and variance algorithm*/ temp_delta = temp_pixVal - temp_mean; temp_mean += temp_delta/(processingFrame+1); temp_m2 += temp_delta*(temp_pixVal - temp_mean); } temp_variance = temp_m2 / (numImagesToProcess - 1); temp_sigma = sqrt(temp_variance); /*Values in a CV_32F image must be between 0 and 1. Since the scale was 0-255 for pixels, we normalize it by dividing with 255*/ sigmaImageProcess.at<uchar>(row, col) = (int)temp_sigma; meanImageProcess.at<uchar>(row, col) = temp_mean; /*clear memory for reuse in next iter*/ temp_variance=0; temp_sigma=0; temp_pixVal=0; temp_mean=0; temp_m2=0; temp_delta=0; } } //AvgImg = meanImageProcess.clone(); //SigImg = sigmaImageProcess.clone(); } void Trainer::MakeAvgSigmaImage(bool PerformLBPOnImages=false) { this->isLBPApplied = PerformLBPOnImages; /*Declare memory to store all the images coming in*/ std::vector<cv::Mat> backgroundImagingArray, backgroundLBPImgArray, TestingForEntropyArray; cv::Mat tempImagingProcess, tempImagingLBP, tempTestingEntropy; float singleEntropyTest=0; bool isThisAGoodEvent; printf("Camera %d training ... ",this->camera); /*Store all the images*/ std::string ThisEventDir, thisEventLocation; for (int i=0; i<this->EventList.size(); i++) { ThisEventDir = this->EventDir+EventList[i]+"/Images/"; std::string ImageFilePattern = "cam"+std::to_string(this->camera)+"_image"; this->ParseAndSortFramesInFolder(ImageFilePattern, ThisEventDir); TestingForEntropyArray.clear(); /*The for block loads images 0 and 1 from each event*/ if (this->CameraFrames.size() >20 ){ for (std::vector<int>::iterator it = TrainingSequence.begin(); it !=TrainingSequence.end(); it++){ thisEventLocation = ThisEventDir + this->CameraFrames[*it]; if (getFilesize(thisEventLocation) > 1000000){ tempImagingProcess = cv::imread(thisEventLocation, 0); TestingForEntropyArray.push_back(tempImagingProcess); isThisAGoodEvent = true; } else { isThisAGoodEvent = false; std::cout<<"Event "<<EventList[i]<<" is malformed. Skipping training on this event\n"; break; } } } else { std::cout<<"Event "<<EventList[i]<<" is nonexistant on the disk. Skipping training on this event\n"; isThisAGoodEvent = false; } /*Test entropy for the first 2 trained sets*/ if (isThisAGoodEvent){ tempTestingEntropy = TestingForEntropyArray[1]-TestingForEntropyArray[0]; singleEntropyTest = calculateEntropyFrame(tempTestingEntropy); //std::cout<<ThisEventDir<<ImageFilePattern<<" "<<singleEntropyTest<<"\n"; } else { singleEntropyTest = 0.0000; } /*If entropy results pass, construct the images and LBP versions*/ if (singleEntropyTest <= 0.0005 and isThisAGoodEvent) { advance_cursor(); /*For all frames used for training*/ for (cv::Mat image : TestingForEntropyArray) { backgroundImagingArray.push_back(image); /*LBP versions required?*/ if (this->isLBPApplied) { tempImagingLBP = lbpImageSingleChan(image); backgroundLBPImgArray.push_back(tempImagingLBP); } } } /*GC*/ this->CameraFrames.clear(); } if (backgroundImagingArray.size()==0){ printf("Training image set has 0 frames. This means that the event is malformed.\n"); throw -7; } /*Calculate mean and sigma of the raw images*/ advance_cursor(); this->CalculateMeanSigmaImageVector(backgroundImagingArray, this->TrainedAvgImage, this->TrainedSigmaImage); /*Calculate mean and sigma of LBP*/ advance_cursor(); if (this->isLBPApplied) this->CalculateMeanSigmaImageVector(backgroundLBPImgArray, this->TrainedLBPAvg, this->TrainedLBPSigma); printf("complete.\n"); } /*Misc functions*/ /*! \brief Sorting function for camera frames * * To be used by std::sort for sorting files associated with * the camera frames. Not to be used otherwise. */ bool frameSortFuncTrainer(std::string i, std::string j) { unsigned int sequence_i, camera_i; int got_i = sscanf(i.c_str(), "cam%d_image%u.png", &camera_i, &sequence_i ); assert(got_i == 2); unsigned int sequence_j, camera_j; int got_j = sscanf(j.c_str(), "cam%d_image%u.png", &camera_j, &sequence_j ); assert(got_j == 2); return sequence_i < sequence_j; }
true
1f287abdc344da529b67cdfaafbb5a0f68d2eafa
C++
rishavjnv12/Code-backup
/range_q/sum.cpp
UTF-8
1,104
2.921875
3
[]
no_license
#include <bits/stdc++.h> #define vi vector<int> const int MAXN = 1000; using namespace std; int t[4*MAXN]; void build(vi a,int v,int tl,int tr){ if(tl==tr){ t[v]=a[tl]; }else{ int tm = (tl + tr) / 2; build(a, v*2, tl, tm); build(a, v*2+1, tm+1, tr); t[v] = t[v*2] + t[v*2+1]; } } void update(int v, int tl, int tr, int pos, int new_val) { if (tl == tr) { t[v] = new_val; } else { int tm = (tl + tr) / 2; if (pos <= tm) update(v*2, tl, tm, pos, new_val); else update(v*2+1, tm+1, tr, pos, new_val); t[v] = t[v*2] + t[v*2+1]; } } int sum(int v, int tl, int tr, int l, int r) { if(l>r) return 0; if(l==tl and r==tr) return t[v]; int tm=(tl+tr)/2; return sum(v*2,tl,tm,l,min(r,tm))+sum(v*2+1,tm+1,tr,max(l,tm+1),r); } int main(){ vi a={1,3,-2,8,-7}; build(a,1,0,a.size()-1); for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ cout<<"Sum"<<":"<<"("<<i<<","<<j<<"):"<<sum(1,0,4,i,j)<<endl; } } return 0; }
true
570bb9dfb062ac6dde529b670593cc59df7bf34d
C++
HaochenLiu/My-LeetCode-CPP
/191.cpp
UTF-8
610
3.640625
4
[]
no_license
/* 191. Number of 1 Bits Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. Credits: Special thanks to @ts for adding this problem and creating all test cases. */ class Solution { public: int hammingWeight(uint32_t n) { if(n == 0) return 0; int res = 1; while(n & (n - 1)) { res++; n = n & (n - 1); } return res; } };
true
c5fdf3132afefadd68f30268806eef8eff5b8928
C++
cmz2012/lt
/1260.cpp
UTF-8
548
3.125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) { int n=grid.size(),m=grid[0].size(); vector<vector<int>> res(n,vector<int>(m,0)); k = k%(n*m); for(int i=0;i<n;i++) for(int j=0;j<m;j++){ int ni=(i+(j+k)/m)%n; int nj=(j+k)%m; res[ni][nj]=grid[i][j]; } return res; } int main() { vector<vector<int>> grid={{1,2,3},{4,5,6},{7,8,9}}; vector<vector<int>> res = shiftGrid(grid, 1); return 0; }
true
5935a6e48991c9838721d2ef8542526c7c37dfb6
C++
dmdamen/photonic
/classes/filereader/filereader.cpp
UTF-8
1,241
3.125
3
[]
no_license
#include <algorithm> #include <cstring> #include "filereader.hpp" Filereader::Filereader(const std::string path) : Filereader(path, 65536) { } Filereader::Filereader(const std::string path, const size_t maxBufferLength) : m_path {path}, m_maxChunksize {maxBufferLength} { m_stream >> std::noskipws; m_stream.open(m_path, std::ios::binary | std::ios::in | std::ios::ate); if (!m_stream.is_open()) { throw std::runtime_error(std::string("Could not open file for reading") + m_path); } m_chunk = (char *) malloc(m_maxChunksize * sizeof(char)); m_numChunks = m_stream.tellg() / m_maxChunksize + 1; m_stream.seekg(0); // read the first block into // buffer for immediate use m_readNextChunk(); } Filereader::~Filereader() { if (!m_stream.is_open()) { m_stream.close(); } delete [] m_chunk; } const char *Filereader::CurrentChunk() const { return m_chunk; } const size_t Filereader::SizeOfCurrentChunk() const { return m_chunksize; } const size_t Filereader::TotalNumberOfchunks() const { return m_numChunks; } void Filereader::m_readNextChunk() { m_chunksize = m_stream.readsome(m_chunk, m_maxChunksize); }
true
ff8bbf4a8a2372307254f913f0222daac93455ae
C++
elatisy/shujujiegou
/HuffmanTree/HuffmanTree.h
UTF-8
2,348
3.578125
4
[]
no_license
#include "Node.h" #include "../MinHeap/MinHeap.h" #ifndef HUFFMANTREE_H #define HUFFMANTREE_H template <class T> class HuffmanTree { private: Node<T> *root; void deleteTree(Node<T> *node); void mergeTree(Node<T> *treeRoot1, Node<T> *treeRoot2, Node<T> *&mergedTreeRoot); Node<T>* objectToPtr(Node<T> object); public: HuffmanTree(); HuffmanTree(T w[], int n); ~HuffmanTree(); }; template <class T> void HuffmanTree<T>::deleteTree(Node<T> *node) { if(node->leftChild != nullptr) { this->deleteTree(node->leftChild); } if (node->rightChild != nullptr) { this->deleteTree(node->rightChild); } delete node; } template <class T> void HuffmanTree<T>::mergeTree(Node<T> *treeRoot1, Node<T> *treeRoot2, Node<T> *&mergedTreeRoot) { mergedTreeRoot = new Node<T>; mergedTreeRoot->data = treeRoot1->data + treeRoot2->data; mergedTreeRoot->parent = nullptr; mergedTreeRoot->leftChild = treeRoot1; mergedTreeRoot->rightChild = treeRoot2; treeRoot1->parent = treeRoot2->parent = mergedTreeRoot; } template <class T> Node<T>* HuffmanTree<T>::objectToPtr(Node<T> object) { Node<T> *ptr = new Node<T>(); ptr->data = object.data; ptr->leftChild = object.leftChild; ptr->rightChild = object.rightChild; ptr->parent = object.parent; return ptr; } template <class T> HuffmanTree<T>::HuffmanTree() { this->root = nullptr; } template <class T> HuffmanTree<T>::HuffmanTree(T w[], int n) { Node<T> *work = new Node<T>[n]; for (int i = 0; i < n; ++i){ work[i].data = w[i]; } MinHeap<Node<T>> *minHeap = new MinHeap<Node<T>>(work, n); Node<T> *first, *second, *parent, temp; for (int i = 0; i < n - 1; ++i) { /** Get first node */ minHeap->remove(temp); first = this->objectToPtr(temp); /** Get second node */ minHeap->remove(temp); second = this->objectToPtr(temp); /** Merge first and second node*/ this->mergeTree(first, second, parent); temp = parent; parent = this->objectToPtr(temp); /** Insert merged tree */ temp = parent; minHeap->insert(temp); } this->root = parent; } template <class T> HuffmanTree<T>::~HuffmanTree() { this->deleteTree(this->root); } #endif
true
dcc6d76cacccdf849dbb856cb707e8c0d37d78dc
C++
CKBird/HearthstoneSim
/Card.h
UTF-8
3,709
3.203125
3
[]
no_license
#pragma once #include <string> #include <iostream> #include <array> using namespace std; //Changes to the following enum classes must be maintained in the operator<< as well enum class card_type { none, minion, spell, weapon, hero }; enum class class_name { none, demon_hunter, druid, hunter, mage, paladin, priest, rogue, shaman, warlock, warrior, neutral }; const array<card_type, 5> all_types = { card_type::none, card_type::minion, card_type::spell, card_type::weapon, card_type::hero }; const array<class_name, 12> all_classes = {class_name::none, class_name::demon_hunter, class_name::druid, class_name::hunter, class_name::mage, class_name::paladin, class_name::priest, class_name::rogue, class_name::shaman, class_name::warlock, class_name::warrior, class_name::neutral}; //Base class for Minion, Spell, Hero classes class Card { public: Card(); //Prevent compiler from making Card(card_type cT, class_name cN); virtual void printInfo(); card_type getType() { return _cType;} int getCost() { return _cost; } string getEffect() { return _effect; } string getName() { return _name; } class_name getClassName() { return _cName; } void setType(card_type cT) { _cType = cT; } void setCost(int cost) { _cost = cost; } void setEffect(string effect) { _effect = effect; } void setName(string name) { _name = name; } void setClassName(class_name cN) { _cName = cN; } friend ostream& operator<< (ostream& out, const card_type& value); friend ostream& operator<< (ostream& out, const class_name& value); protected: card_type _cType; int _cost; string _effect, _name; class_name _cName; //Rarity }; class Minion : public Card { public: Minion(class_name cN, int cost, int atk, int health, string name, string effect = ""); void printInfo(); int getHealth() { return _health; } int getAtk() { return _atk; } void setHealth(int health) { _health = health; } void setAtk(int atk) { _atk = atk; } private: bool assertType() { if (_cType != card_type::minion) return false; } int _atk, _health; }; class Spell : public Card { public: Spell(class_name cN, int cost, string name, string effect = ""); void printInfo(); private: bool assertType() { if (_cType != card_type::spell) return false; } }; class Weapon : public Card { public: Weapon(class_name cN, int cost, int atk, int dura, string name, string effect = ""); void printInfo(); private: bool assertType() { if (_cType != card_type::weapon) return false; } int _atk, _dura; }; class Hero : public Card { public: Hero(class_name cN, int cost, int armor, string name, string effect = ""); void printInfo(); private: bool assertType() { if (_cType != card_type::hero) return false; } int _armor; }; inline std::ostream& operator<<(std::ostream& out, const card_type& value) { const char* s = 0; #define PROCESS_VAL(p) case(p): s = #p; break; switch (value) { PROCESS_VAL(card_type::none); PROCESS_VAL(card_type::minion); PROCESS_VAL(card_type::spell); PROCESS_VAL(card_type::weapon); PROCESS_VAL(card_type::hero); } #undef PROCESS_VAL return out << s; } inline std::ostream& operator<<(std::ostream& out, const class_name& value) { const char* s = 0; #define PROCESS_VAL(p) case(p): s = #p; break; switch (value) { PROCESS_VAL(class_name::none); PROCESS_VAL(class_name::demon_hunter); PROCESS_VAL(class_name::druid); PROCESS_VAL(class_name::hunter); PROCESS_VAL(class_name::mage); PROCESS_VAL(class_name::paladin); PROCESS_VAL(class_name::priest); PROCESS_VAL(class_name::rogue); PROCESS_VAL(class_name::shaman); PROCESS_VAL(class_name::warlock); PROCESS_VAL(class_name::warrior); PROCESS_VAL(class_name::neutral); } #undef PROCESS_VAL return out << s; }
true
15dfdb79f6b016dee340afcc471dbad9ec5dbe27
C++
peterisgood2002/99.NctuProject
/02.Computer Graphic/Assignment1/HW1/program23.cpp
BIG5
1,499
2.796875
3
[]
no_license
/****************************************** FILE program23.cpp Purpose Ѥl@~GҦO 2.Render the Utah teapot using Gouraud shading. (15%) Ѥl@~TҦO 4.Render the Utah teapot with bump mapping.(50%) NOTE Author 9757553 C *******************************************/ #include "function.h" extern GLuint texture[NTEX]; extern bool openBumpmapping; void drawPolygonWithTexture() { // lighting(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glColor3f(1.0, 1.0, 1.0); glEnable(GL_TEXTURE_2D); //Texture h]wTexture mapping覡 //string str[ NTEX ] ={ "colorTexture" ,"bumpMap" }; //Texture bindih Shading //1.Get the sampler uniform location. GLint location = glGetUniformLocationARB(bumpMapping, "colorTexture" ); //2.Bind the texture to texture unit i. glActiveTexture(GL_TEXTURE0 ); glBindTexture(GL_TEXTURE_2D, texture[0]); //3.Pass i as an integer by glUniform. if ( location == -1 ) printf("Cant find texture name: colorTexture\n"); else glUniform1iARB(location, 0); if ( openBumpmapping ) { //1.Get the sampler uniform location. GLint location = glGetUniformLocationARB(bumpMapping, "bumpMap" ); //2.Bind the texture to texture unit i. glActiveTexture(GL_TEXTURE1 ); glBindTexture(GL_TEXTURE_2D, texture[1]); //3.Pass i as an integer by glUniform. if ( location == -1 ) printf("Cant find texture name: colorTexture\n"); } //e drawPolygon( true ); }
true
76a8fff799abfbc49988d68f7735a44dca396fd7
C++
ttiozinho00/pac-man-em-cpp
/Headers/Console.hpp
UTF-8
362
3.203125
3
[]
no_license
#ifndef GAME_H #define GAME_H #include <string> #include <iostream> using namespace std; class Console { private: std::string m_name; public: Console(std::string name); void writeLine(std::string line); }; Console::Console(string name) { m_name = name; } void Console::writeLine(string line) { cout << "[" << m_name << "]: " << line << endl; } #endif
true
b0497eb833d961f96928dd424430b89ada0afaab
C++
fngoc/CppModules
/Module08/ex01/main.cpp
UTF-8
2,137
3.21875
3
[]
no_license
#include "span.hpp" using std::cout; using std::endl; int main() { srand(time(NULL)); cout << "---------TEST-0---------" << endl; { Span sp(1000); for (int i = 0; i < 1000; ++i) { sp.addNumber(i + rand() % 10); } cout << "short: " << sp.shortestSpan() << endl; cout << "longest: " << sp.longestSpan() << endl; } cout << "---------TEST-1---------" << endl; { Span sp(5); for (int i = 0; i < 5; ++i) { sp.addNumber(i + rand() % 10); cout << sp[i] << " "; } cout << endl; cout << "short: " << sp.shortestSpan() << endl; cout << "longest: " << sp.longestSpan() << endl; } cout << "---------TEST-2---------" << endl; { Span sp(5); for (int i = 0; i < 5; ++i) { sp.addNumber(i + rand() % 10); cout << sp[i] << " "; } cout << endl; cout << "short: " << sp.shortestSpan() << endl; cout << "longest: " << sp.longestSpan() << endl; } cout << "---------TEST-3---------" << endl; { try { Span sp(5); sp[9]; } catch (std::exception& exception) { cout << exception.what() << endl; } } cout << "---------TEST-4---------" << endl; { try { Span sp(1); sp.longestSpan(); } catch (std::exception& exception) { cout << exception.what() << endl; } } cout << "---------TEST-5---------" << endl; { try { Span sp(2); sp.addNumber(1); sp.addNumber(2); sp.addNumber(3); } catch (std::exception& exception) { cout << exception.what() << endl; } } cout << "--------SUBJTEST--------" << endl; { Span sp = Span(5); sp.addNumber(5); sp.addNumber(3); sp.addNumber(17); sp.addNumber(9); sp.addNumber(11); cout << sp.shortestSpan() << endl; cout << sp.longestSpan() << endl; } return 0; }
true
503f26f899e8fe1be6c7c1364fd99a4c30e181fd
C++
Antoniano1963/vscode_cpp
/cpp_window/Week4/assignment12.cpp
UTF-8
8,711
3.203125
3
[]
no_license
#include<iostream> #include<string> #include<ctime> #include<algorithm> #include<thread> #include<numeric> #include<vector> #include<functional> #include "big_operation1.1.h" #include<cmath> #include<cblas.h> using namespace std; bool testNum(string str); long testFunc(string str); void creatVector(string str, float *vector); big vector_DOT(long num, float *vector1, float *vector2); double vector_DOT1(long num, float *vector1, float *vector2); void vector_DOT2(long begin, long end, float *vector1, float *vector2, big &result); void vector_DOT3(long begin, long end, float *vector1, float *vector2, big &res); int main() { bool T = true; while (T) { cout << "Enter your tpye number(0 means you input two vectors and we give you the result, 1 means system creat two vectors which has 10m elements randomly and give you the answer and the cost time of calculate)" << endl; string str0; cin >> str0; if (str0.length() != 1) { cout << "you enter a wrong number" << endl; } else { if (str0.at(0) == '0') { cout << "Enter the first vector in [num1,num2,...] format" << endl; string str1; cin >> str1; cout << "Enter the second vector in [num1,num2,...] format" << endl; string str2; cin >> str2; long num1, num2; num1 = testFunc(str1); num2 = testFunc(str2); if (num1 == num2) { if (num1 > 0 && num2 > 0) { float *vector1 = new float[num1]; float *vector2 = new float[num2]; creatVector(str1, vector1); creatVector(str2, vector2); big result; result = vector_DOT(num1, vector1, vector2); cout << result.print() << endl; delete[] vector1; delete[] vector2; } } else { cout << "Number of vector1's elements is not equals to number of vector2's elements" << endl; } } else if (str0.at(0) == '1') { float *vector1 = new float[200000000]; float *vector2 = new float[200000000]; srand((int)time(NULL)); float array0[100]; for (int i = 0; i < 100; i++) { array0[i] = (rand()%100) + rand() / double(RAND_MAX); } for (int i = 0; i < 200000000; i++) { int num = i % 100; vector1[i] = array0[num]; vector2[i] = array0[num]; } time_t begin, end; double ret; begin = clock(); big result; result = vector_DOT(200000000, vector1, vector2); cout << result.print() << endl; end = clock(); ret = double(end - begin) / CLOCKS_PER_SEC; cout << "runtime: " << ret << endl; begin = clock(); double result1; result1 = vector_DOT1(200000000, vector1, vector2); cout << result1 << endl; end = clock(); ret = double(end - begin) / CLOCKS_PER_SEC; cout << "runtime: " << ret << endl; //method2 long num_theards = 4; long num_size = 200000000 / num_theards; vector<big> results(num_theards); vector<thread> threads; for (int i = 0; i < num_theards - 1; i++) { threads.push_back(thread(vector_DOT2, i * num_size, (i + 1) * num_size, vector1, vector2, ref(results[i]))); } threads.push_back(thread(vector_DOT2, (num_theards-1)* num_size, 200000000, vector1, vector2, ref(results[num_theards - 1]))); begin = clock(); for (auto &t : threads) { t.join(); } big result2=big(); for (int i = 0; i < num_theards; i++) { result2 = result2+results[i]; } cout << result2.print() << endl; end = clock(); ret = double(end - begin) / CLOCKS_PER_SEC; cout << "runtime: " << ret << endl; //method3 vector<big> resultss(num_theards); vector<thread> threadss; for (int i = 0; i < num_theards - 1; i++) { threadss.push_back(thread(vector_DOT3, i * num_size, (i + 1) * num_size, vector1, vector2, ref(resultss[i]))); } threadss.push_back(thread(vector_DOT3, (num_theards - 1)* num_size, 200000000, vector1, vector2, ref(resultss[num_theards - 1]))); begin = clock(); for (auto &t : threadss) { t.join(); } big result3 = big(); for (int i = 0; i < num_theards; i++) { result3 = result3 + resultss[i]; } cout << result3.print() << endl; end = clock(); ret = double(end - begin) / CLOCKS_PER_SEC; cout << "runtime: " << ret << endl; //method4 begin = clock(); float result4 = cblas_sdot(200000000, vector1, 1, vector2, 1); cout << result4 << endl; end = clock(); ret = double(end - begin) / CLOCKS_PER_SEC; cout << "runtime: " << ret << endl; delete[] vector1; delete[] vector2; } else { cout << "you enter a wrong number" << endl; } } } } big vector_DOT(long num, float *vector1, float *vector2) { big dot=big(); long register i = 0; while (i < num) { double result = 0; result = vector1[i] + vector2[i]; i++; while ((i % 1000000) != 0&&i<num) { result+= vector1[i] * vector2[i]; i++; } string str = to_string(result); dot = dot + big(str); } return dot; } double vector_DOT1(long num, float *vector1, float *vector2) { double dot = 0; long register i = 0; long num1 = num - 16; while (i < num1) { dot += vector1[i] * vector2[i] + vector1[i + 1] * vector2[i + 1] + vector1[i + 2] * vector2[i + 2] + vector1[i + 3] * vector2[i + 3] + vector1[i + 4] * vector2[i + 4] + vector1[i + 5] * vector2[i + 5] + vector1[i + 6] * vector2[i + 6] + vector1[i + 7] * vector2[i + 7]; i += 8; } while (i < num) { dot += vector1[i] + vector2[i]; i++; } return dot; } void vector_DOT2(long begin, long end, float *vector1, float *vector2, big &res) { res=big(); double result = 0; long register i = begin; long num1 = end - 16; while (i < num1) { result = 0; int count =0 ; while ((count!=10000)&&(i<num1)) { result += vector1[i] * vector2[i] + vector1[i + 1] * vector2[i + 1] + vector1[i + 2] * vector2[i + 2] + vector1[i + 3] * vector2[i + 3] + vector1[i + 4] * vector2[i + 4] + vector1[i + 5] * vector2[i + 5] + vector1[i + 6] * vector2[i + 6] + vector1[i + 7] * vector2[i + 7]; i += 8; count+=8; } string str = to_string(result); res = res + big(str); } while (i < end) { result = 0; result += vector1[i] * vector2[i]; i++; } string str = to_string(result); res = res + big(str); } void vector_DOT3(long begin, long end, float *vector1, float *vector2, big &res) { res = big(); double result = 0; long double result1=0; long long result2=0; long register i = begin; long num1 = end - 16; while (i < num1) { result = 0; int count = 0; while ((count != 1000) && (i < num1)) { result += vector1[i] * vector2[i] + vector1[i + 1] * vector2[i + 1] + vector1[i + 2] * vector2[i + 2] + vector1[i + 3] * vector2[i + 3] + vector1[i + 4] * vector2[i + 4] + vector1[i + 5] * vector2[i + 5] + vector1[i + 6] * vector2[i + 6] + vector1[i + 7] * vector2[i + 7]; i += 8; count += 1; } result1 += fmod(result, 1.0); result2 += ceil(result); } string str1 = to_string(result1); string str2 = to_string(result2); res = big(str1) + big(str2); while (i < end) { result = 0; result += vector1[i] * vector2[i]; i++; } string str = to_string(result); res = res + big(str); } void creatVector(string str, float *vector) { long length = str.length(); long num = 1; long num0 = 0; while (num < length) { string str1 = ""; while (str.at(num) != ',' && num < length - 1) { str1 += str.at(num); num++; } vector[num0++] = stof(str1); num++; } } long testFunc(string str) { long length = str.length(); if (length < 3) { cout << "the length of your vector is not correct" << endl; return -1; } if (str.at(0) != '[') { cout << "the vector should begin with [" << endl; return -1; } if (str.at(length - 1) != ']') { cout << "the vector should end with ]" << endl; return -1; } long count = 0; long num = 1; long num0 = 0; while (num < length) { string str1 = ""; while (str.at(num) != ',' && num < length - 1) { str1 += str.at(num); num++; } if (testNum(str1)) { num0++; } else { cout << "the type of your number is not right" << endl; return -1; } num++; } for (int i = 0; i < length; i++) { if (str.at(i) == ',') { if (str.at(i - 1) == ',') { cout << "the type of your , is not right" << endl; return -1; } } } return num0; } bool testNum(string str) { if (str.length() < 1) { return false; } int num = 0; if (str.at(0) == '-') { num = 1; } int count = 0; for (; num < str.length(); num++) { if (str.at(num) <= '9' || str.at(num) >= '0' || str.at(num) == '.') { if (str.at(num) == '.') { count++; } } else { return false; } } if (count > 1) { return false; } return true; }
true
0d924399408096831b39a6d909eeb09fe966daac
C++
ftiasch/ccpc-final-2020
/main/nondegenerate-triangle/solution.cc
UTF-8
1,076
2.8125
3
[]
no_license
#include <bits/stdc++.h> namespace { static const int ITERATIONS = 20; struct Point { int x, y; }; Point operator-(const Point &a, const Point &b) { return Point{a.x - b.x, a.y - b.y}; } using Long = long long; Long det(const Point &a, const Point &b) { return static_cast<Long>(a.x) * static_cast<Long>(b.y) - static_cast<Long>(a.y) * static_cast<Long>(b.x); } } // namespace int main() { std::mt19937_64 gen{0}; int n; while (scanf("%d", &n) == 1) { std::vector<Point> p(n); for (int i = 0; i < n; ++i) { scanf("%d%d", &p[i].x, &p[i].y); } int result = 0; if (n > 1) { int colinear = 0; for (int _ = 0; _ < ITERATIONS; ++_) { int x, y; do { x = gen() % n; y = gen() % n; } while (x == y); int count = 0; for (int i = 0; i < n; ++i) { count += det(p[i] - p[x], p[i] - p[y]) == 0; } colinear = std::max(colinear, count); } result = std::min(n / 3, n - colinear); } printf("%d\n", n - result * 3); } }
true
5598d4e08ef2572025572de634d126784f5669bb
C++
archer18/homework
/HW4 final.cpp
UTF-8
943
3
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; void extract(ifstream& read, ofstream& write); int main() { ifstream read; ofstream write; read.open("grades.dat"); write.open("Grades Calculated.dat"); if (read.fail()) { cout << "ERROR: Cannot read file \n"; exit(1); } if (write.fail()) { cout << "ERROR: Cannot create/write to file \n"; exit(1); } extract(read, write); cout << "\nGrade file transfer success\n"; read.close(); write.close(); return 0; } void extract(ifstream& read, ofstream& write) { string last, first; char a; do { double final=0.0; read>>last>>first; write<<last<<" "<<first<<" "; int grade=0; for(int x=0; x<10; x++) { read>>grade; final = grade + final; write<<grade<<" "; } write << (final/1000)*100 <<"%"; write << endl; read.get(a); }while(a == '\n'); }
true
c764225ff314e36a484135f928125647dfe9f611
C++
defuyun/ACM
/入门经典/part2/chapter6/6.2/6.2.2-链式结构.cpp
UTF-8
1,059
2.921875
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstdlib> using std::cin; using std::cout; using std::endl; const int maxn=500000 + 50; int left[maxn],right[maxn],n,t; void link(int a,int b){ right[a]=b; left[b]=a; } int main(){ cin >> n; for(int i=1;i<=n;i++) { left[i]=i-1; right[i]=i+1;} right[n]=0; cin >> t; for(int i=1;i<=t;i++){ int X,Y; char c; c=getchar(); while(c!='A'&&c!='B') c=getchar(); cin >> X >> Y; link(left[X],right[X]); if(c=='B'){ //X .. Y-> .. Y X right[Y] link(X,right[Y]); link(Y,X); } else {//A //X .. Y -> .. X Y link(left[Y],X); link(X,Y); } } int head; for(head=1;head<=n&&left[head]!=0;head++); cout << head<<" "; while(right[head]!=0){ head=right[head]; cout << head<<" "; } cout << endl; return 0; }
true
a6dd902da225bb193da6ef6bfb6dc827590b8776
C++
HarveyHub/NowCoder
/baidu/stand_order.cpp
UTF-8
393
3
3
[]
no_license
#include<iostream> #include<list> using namespace std; struct Person { int order; int no; Person(int i):order(i),no(i){}; }; int main() { int M; while(cin >> M) { list<Person> ps; for(int i = 1; i <= 100; i++) { ps.push_back(Person(i)); } // int left = 100; int pos = 0; while(ps.size() >= M) { pos = (pos + M - 1) % ps.size(); pos.erase(Person(pos)); } } }
true
30091dd7bae20977e67eb84e1b65035f3ae3f327
C++
caa-dev-apps/libcef_v2
/source/CUtils.cpp
UTF-8
840
2.65625
3
[ "MIT" ]
permissive
#include "stdio.h" #include "stdlib.h" #include <string> #include <vector> #include <stdbool.h> #include <cstdlib> #include <ctime> #include <ostream> #include <iostream> #include <unistd.h> using namespace std; //x #include <cstdlib> /////////////////////////////////////////////////////////////////////////// // class CTimer { const char *m_tag; clock_t m_stx; public: CTimer(const char *i_tag): m_tag(i_tag), m_stx(clock()) { now(); } void now() { clock_t l_ticks = clock() - m_stx; cout << "TICKS = " << l_ticks << " SECS = " << (l_ticks / CLOCKS_PER_SEC) << " " << " CLOCKS_PER_SEC = " << CLOCKS_PER_SEC << " " << m_tag << endl; } };
true
bc15b2376cc40d35e8b84f162399e8b0126344bc
C++
Mihret-T/SE-c-User_Defined_Header_Files
/main.cpp
UTF-8
1,172
3.578125
4
[]
no_license
//main.cpp #include "Cal.h" #include <iostream> #include<string> using namespace std; int main(){ char op; float a, b; cout <<"Enter operator: "; cin >> op; cout << "Enter the first number: "; cin >> a; cout << "Enter the second number: "; cin >> b; //Cal(x, y); switch(op) { case '+': cout << "The sum is: "; cout << Add(a,b)<< endl; break; case '-': cout << "The Difference is: "; cout << Sub(a,b)<< endl; break; case '*': cout << "The product is: "; cout << Mult(a,b)<< endl; break; case '/': cout << "The quotent is: "; cout << Div(a,b)<< endl; break; default: cout << "ERROR! operator not correct"<< endl; break; } return 0; }
true
6ef553a7b10fecabd689d4d4dd64f182c8251ab9
C++
dskading/iqrf-daemon
/daemon/MqttMessaging/MqttMessaging.h
UTF-8
1,033
2.609375
3
[ "Apache-2.0" ]
permissive
#pragma once #include "JsonUtils.h" #include "IMessaging.h" #include <string> class Impl; typedef std::basic_string<unsigned char> ustring; class MqttMessaging : public IMessaging { public: MqttMessaging() = delete; MqttMessaging(const std::string& name); virtual ~MqttMessaging(); //component void start() override; void stop() override; void update(const rapidjson::Value& cfg) override; const std::string& getName() const override; //interface void registerMessageHandler(MessageHandlerFunc hndl) override; void unregisterMessageHandler() override; void sendMessage(const ustring& msg) override; private: Impl* m_impl; }; class MqttChannelException : public std::exception { public: MqttChannelException(const std::string& cause) :m_cause(cause) {} //TODO ? #ifndef WIN32 virtual const char* what() const noexcept(true) #else virtual const char* what() const #endif { return m_cause.c_str(); } virtual ~MqttChannelException() {} protected: std::string m_cause; };
true
81ce263cf6e37b9a26b8b2771ffc37b63fcff2e4
C++
jsyeh/uva
/cpe/CPE_20201222/C_uva10415.cpp
UTF-8
1,273
3
3
[]
no_license
#include <stdio.h> int findNote(char c) { char note[]="cdefgabCDEFGAB"; for(int i=0; i<14; i++){ if(note[i]==c) return i; } } //table[note][finger]表示音符note對的手指finger有沒有按 int table[14][10]={ // 1,2,3,4,5,6,7,8,9,10 {0,1,1,1,0,0,1,1,1,1},//c {0,1,1,1,0,0,1,1,1,0},//d {0,1,1,1,0,0,1,1,0,0},//e {0,1,1,1,0,0,1,0,0,0},//f {0,1,1,1,0,0,0,0,0,0},//g {0,1,1,0,0,0,0,0,0,0},//a {0,1,0,0,0,0,0,0,0,0},//b {0,0,1,0,0,0,0,0,0,0},//C {1,1,1,1,0,0,1,1,1,0},//D {1,1,1,1,0,0,1,1,0,0},//E {1,1,1,1,0,0,1,0,0,0},//F {1,1,1,1,0,0,0,0,0,0},//G {1,1,1,0,0,0,0,0,0,0},//A {1,1,0,0,0,0,0,0,0,0}};//B char line[1002]; int main() { int n; scanf("%d", &n); for(int t=0; t<n; t++){ scanf("%s", line); int ans[10]={};//all zero,放最後按了幾下 int pressed[10]={};//存現在的手指狀態,0沒按,1按下 for(int i=0; line[i]!=0; i++){ char c = line[i]; int note = findNote(c);//現在的音符 for(int finger=0; finger<10; finger++){ if(table[note][finger]==1 && pressed[finger]==0){ pressed[finger]=1; ans[finger]++; }else if(table[note][finger]==0){ pressed[finger]=0; } } } for(int i=0; i<10; i++){ if(i<9) printf("%d ", ans[i]); else printf("%d\n", ans[i]); } } }
true
797f5ee9e1d3b1dad1204593ddd6f9e98b1fb27d
C++
flexoid/rTracer
/src/vector3.h
UTF-8
2,475
3.640625
4
[]
no_license
#ifndef VECTOR3_H #define VECTOR3_H #include <math.h> class Vector3 { public: // Data float x, y, z; // Ctors Vector3( float InX, float InY, float InZ ) : x( InX ), y( InY ), z( InZ ) { } Vector3( ) : x(0.0f), y(0.0f), z(0.0f) { } // Operator Overloads inline bool operator== (const Vector3& V2) const { return (x == V2.x && y == V2.y && z == V2.z); } inline bool operator!= (const Vector3& V2) const { return !(*this == V2); } inline Vector3 operator+ (const Vector3& V2) const { return Vector3( x + V2.x, y + V2.y, z + V2.z); } inline Vector3 operator- (const Vector3& V2) const { return Vector3( x - V2.x, y - V2.y, z - V2.z); } inline Vector3 operator- ( ) const { return Vector3(-x, -y, -z); } inline Vector3 operator/ (float S ) const { return Vector3 (x / S , y / S, z / S); } inline Vector3 operator* (const Vector3& V2) const { return CrossProduct(V2); } inline Vector3 operator* (float S) const { return Vector3 (x * S, y * S, z * S); } inline void operator+= ( const Vector3& V2 ) { x += V2.x; y += V2.y; z += V2.z; } inline void operator-= ( const Vector3& V2 ) { x -= V2.x; y -= V2.y; z -= V2.z; } inline float operator[] ( int i ) { if ( i == 0 ) return x; else if ( i == 1 ) return y; else return z; } // Functions inline float DotProduct( const Vector3 &V1 ) const { return V1.x*x + V1.y*y + V1.z*z; } Vector3 CrossProduct( const Vector3 &V1 ) const { return Vector3 (y*V1.z-z*V1.y, z*V1.x-x*V1.z, x* V1.y-y*V1.x); } // These require math.h for the sqrtf function float Length( ) const { return sqrtf( x*x + y*y + z*z ); } float DistanceFrom( const Vector3 &V1 ) const { return ( *this - V1 ).Length(); } Vector3 Norm() { float fMag = ( x*x + y*y + z*z ); if (fMag == 0) return Vector3(x,y,z); float fMult = 1.0f/sqrtf(fMag); return Vector3(x*fMult, y*fMult, z*fMult); } static Vector3 Null() { return Vector3(0.0f, 0.0f, 0.0f); } }; #endif // VECTOR3_H
true
ccc3dec34ae903e6455735ed5e5ab885d2b4438f
C++
giovgiac/AvalonEngine
/AvalonEngine/Source/Runtime/Components/SpriteComponent.h
UTF-8
455
2.546875
3
[]
no_license
/** * SpriteComponent.h * * Copyright (c) Giovanni Giacomo. All Rights Reserved. * */ #pragma once #include <Components/PrimitiveComponent.h> namespace Avalon { class ASpriteComponent : public APrimitiveComponent { private: virtual void ConstructObject(void); public: ASpriteComponent(void); void SetSprite(TSharedPtr<class ATexture2D> InSprite); virtual void UpdateDimensions(void) override; class ATexture2D* GetSprite(void) const; }; }
true
e03a306c2fc03ba23d5cdad32cdca38a5a82e985
C++
arakna/ArduinoLibraries
/LcdMenu/LcdMenuHandler.h
UTF-8
1,511
3.109375
3
[]
no_license
#ifndef LCDMENUHANDLER_H #define LCDMENUHANDLER_H #include <Arduino.h> #include <LiquidCrystal.h> #define TYPE_SHORT 0 #define TYPE_INT 1 #define TYPE_LONG 2 class LcdMenuHandler { public: LcdMenuHandler(int ident) { this->ident = ident; this->val = 0; this->state=0; }; virtual ~LcdMenuHandler() {}; void takeControl(LiquidCrystal* lcd) { this->lcd = lcd; this->active = true; this->state=0; }; void relinquishControl() { this->lcd = NULL; this->active = false; }; boolean wantsControl() { return this->active; }; virtual boolean procKeyPress(int k, char c); virtual void displayStart() {}; virtual void displayCancellation(); virtual void displayConfirmation(); virtual short getValueType() { return TYPE_SHORT; }; boolean isConfirmed() { return this->confirmed; }; boolean isValid() { return this->valid; }; int getIdent() { return ident; }; void setValue(long value) { val = value; }; long getValue() { return val; }; protected: // Holds internal state between keypresses short state; // Determines whether the user canceled or confirmed the action before the handler exited boolean confirmed; // Determines whether the last keypress was valid input or not boolean valid; // The value the user entered long val; // Whether the handler is currently active (receiving keypresses) boolean active; // The attached LCD to output user feedback LiquidCrystal* lcd; private: // Handler identity (should be unique to this handler) int ident; }; #endif //LCDMENUHANDLER_H
true
f751247a24501f12fdf739ea82ad62b7bd9f066f
C++
Sookmyung-Algos/2021algos
/algos_assignment/2nd_grade/김민정_mzeong/week1/4358.cpp
UTF-8
565
2.953125
3
[]
no_license
#include <iostream> #include <map> #include <string> using namespace std; void init() { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(false); } int main() { init(); map<string, float> m; string tree; int count = 0; while (getline(cin, tree)) { if (m.find(tree) != m.end()) m[tree] += 1; else m[tree] = 1; count++; } cout << fixed; cout.precision(4); // 소수점 넷째자리까지 for (auto it = m.begin(); it != m.end(); it++) { float per = (it->second/count)*100; cout << (it->first) << " " << per << "\n"; } return 0; }
true
bbd1a2e3c549c7e499ad2e4726d22e5e3b32b494
C++
rubenwardy/rufunge
/src/subroutine.hpp
UTF-8
284
2.734375
3
[]
no_license
#pragma once class Thread; class VM; class Subroutine { public: int users = 0; void grab() { users++; } void drop() { users--; } /// Either performs the calculation and adds it to the stack, or pops a new cursor onto /// The stack virtual void run(VM* vm, Thread *th) = 0; };
true
eb54f8427f2cc88e9175df3256649203a5f7388f
C++
miamiww/ghostDoll
/servoTester/servoTester.ino
UTF-8
797
2.640625
3
[]
no_license
#include <Servo.h> Servo panelServo; int pos = 140; int ledPin = 2; int servoPin = 10; int statePin = HIGH; int knockPin = 0; byte val = 0; int THRESHOLD = 80; void setup(){ Serial.begin(9600); pinMode(ledPin,OUTPUT); digitalWrite(ledPin, HIGH); panelServo.attach(servoPin); panelServo.write(pos); } void loop(){ val=analogRead(knockPin); if( val >= THRESHOLD){ pos = 10; panelServo.write(pos); delay(30); statePin = HIGH; Serial.print("!"); digitalWrite(ledPin, statePin); } delay(50); if(Serial.available()){ int readByte = Serial.read(); pos = 140; panelServo.write(pos); delay(30); statePin = LOW; digitalWrite(ledPin, statePin); } delay(50); } //void serialEvent(){ // statePin = LOW; // digitalWrite(ledPin, statePin); //}
true
3f12a4704e8c269724b0ef50374014d87c7394b1
C++
awarirahul365/CSE-2003-Data-Structures-and-Algorithms
/Leetcode 30 Days Solution/Find the Difference of Two Arrays.cpp
UTF-8
1,187
2.703125
3
[]
no_license
class Solution { public: vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) { vector<vector<int>>vect; unordered_set<int>notnums2; unordered_set<int>notrepeat1; unordered_set<int>notnums1; unordered_set<int>notrepeat2; for(int i=0;i<nums2.size();i++) { notnums2.insert(nums2[i]); } vector<int>temp; for(int i=0;i<nums1.size();i++) { if(notnums2.find(nums1[i])==notnums2.end() && notrepeat1.find(nums1[i])==notrepeat1.end()) { temp.push_back(nums1[i]); notrepeat1.insert(nums1[i]); } } vect.push_back(temp); temp.clear(); for(int i=0;i<nums1.size();i++) { notnums1.insert(nums1[i]); } for(int i=0;i<nums2.size();i++) { if(notnums1.find(nums2[i])==notnums1.end() && notrepeat2.find(nums2[i])==notrepeat2.end()) { temp.push_back(nums2[i]); notrepeat2.insert(nums2[i]); } } vect.push_back(temp); return vect; } };
true
625f1073a48795e39f859014459914a558089cbf
C++
mlitman/ShuntingYard
/Node.cpp
UTF-8
280
3.015625
3
[]
no_license
#include "Node.hpp" Node::Node(string payload) { this->payload = payload; this->nextNode = 0; } string Node::getPayload() { return this->payload; } Node* Node::getNextNode() { return this->nextNode; } void Node::setNextNode(Node* n) { this->nextNode = n; }
true
f37e3b3adcba3ad887efd0606f825c0c989650bd
C++
pwwpche/X-Locate-OpenCV
/scale_space.cpp
UTF-8
1,028
2.9375
3
[]
no_license
#include "scale_space.h" #include "gaussian_blur.h" IplImage *** generate_scale_space(IplImage * img, int octaves, int scales) { // scale_space[i][j] is the ith octave, jth scale (blur level) IplImage *** scale_space = new IplImage**[octaves]; for(int i=0;i<octaves;++i) { scale_space[i] = new IplImage*[scales]; } scale_space[0][0] = img; for(int i=1;i<octaves;++i) { IplImage * prev = scale_space[i-1][0]; int new_height = (int)ceil(prev->height / sqrt(2.0)); int new_width = (int)ceil(prev->width / sqrt(2.0)); CvSize new_cvSize = {new_width, new_height}; IplImage * resized = cvCreateImage( new_cvSize, prev->depth, prev->nChannels); cvResize(prev, resized); scale_space[i][0] = resized; } double sigma_step = 1 / sqrt(2.0); double k_step = 1 / sigma_step; for(int i=0;i<octaves;++i) { for(int j=1;j<scales;++j) { scale_space[i][j] = gaussianBlur(scale_space[i][j-1], sigma_step); } sigma_step *= k_step; } return scale_space; }
true
0f16c733efae744df1f9d87eeed19ead2a727d81
C++
Lawrenceh/AC_Monster
/two_sorted_kth/two_sorted_kth.cpp
UTF-8
1,590
3.3125
3
[]
no_license
#include <iostream> #include <string.h> #include <stdlib.h> using namespace std; int FindKthElm(int A[], int aBeg, int aEnd, int B[], int bBeg, int bEnd, int k) { if (aBeg > aEnd) return B[bBeg + k - 1]; if (bBeg > bEnd) return A[aBeg + k - 1]; int aMid = aBeg + (aEnd - aBeg)/2; int bMid = bBeg + (bEnd - bBeg)/2; int halfLen = aMid - aBeg + bMid - bBeg + 2; if (A[aMid] < B[bMid]) { if (halfLen > k) return FindKthElm(A, aBeg, aEnd, B, bBeg, bMid - 1, k); else return FindKthElm(A, aMid + 1, aEnd, B, bBeg, bEnd, k - (aMid - aBeg + 1)); } else { if (halfLen > k) return FindKthElm(A, aBeg, aMid - 1, B, bBeg, bEnd, k); else return FindKthElm(A, aBeg, aEnd, B, bMid + 1, bEnd, k - (bMid - bBeg + 1)); } } int main() { const int ALen = 11; const int BLen = 5; int apos = 0; int bpos = 0; int A[ALen]; int B[ALen]; for (int i = 1; i <= ALen + BLen; ++i) { if (apos >= ALen) B[bpos++] = i; else if (bpos >= BLen) A[apos++] = i; else { if (rand()%2 == 1) A[apos++] = i; else B[bpos++] = i; } } for (int i = 0; i < ALen; ++i) cout <<A[i] <<" "; cout <<endl; for (int i = 0; i < BLen; ++i) cout <<B[i] <<" "; cout <<endl; for (int i = 1; i <= ALen + BLen; ++i) { cout << i <<" : "<<FindKthElm(A, 0 , ALen - 1, B, 0 , BLen - 1, i)<<endl; } return 0; }
true
290054f57b63c93bbf0617521f87b9aeff27b14c
C++
DullemondWilliam/Bloom-Filter-UI
/Bloom-Filter/csvbuilder.cpp
UTF-8
1,795
2.921875
3
[]
no_license
#include <QFile> #include "csvbuilder.h" //Assuming data is entered linearly not logrithmicly CSVBuilder::CSVBuilder() { } void CSVBuilder::insertColomn( double head, QVector<double> m_colomn ) { m_xAxisLabel.push_back( head ); m_data.push_back( m_colomn ); } bool CSVBuilder::printToFile( QString fileName, QString Description, QString xaxis, QString yaxis, double minEntry, double maxEntry ) { // QFile file(fileName); // if( !file.open( QFile::WriteOnly ) ) // return false; // //Populate y-axis // QVector<double> yAxisLabel; // double interval = (double)(maxEntry - minEntry) / ((double)m_data[0].length()); // for( int i=0; i < m_data[0].length(); ++i ) // yAxisLabel.push_back( minEntry + (interval * i) ); // file.write( Description.toLocal8Bit() + "," + "\n" ); //Write Description // file.write( ",," + xaxis.toLocal8Bit() + "\n" ); //Write X-Axis Label // //Write X-Axis Values // QString line = ",,"; // for( int i=0; i < m_xAxisLabel.length(); ++i ) // line.append( QString::number(m_xAxisLabel.at(i)) + "," ); // file.write( line.toLocal8Bit() + "\n" ); // //Write First Line // line = yaxis + "," + QString::number( yAxisLabel[0] ) + ","; // for( int i=0; i < m_data.length(); ++i ) // line.append( QString::number(m_data[0][i]) + "," ); // file.write( line.toLocal8Bit() + "\n" ); // for( int i=1; i < m_data.length(); ++i ) // { // line = "," + QString::number( m_xAxisLabel[i] ) + ","; // for( int j=0; j < m_data[i].length(); ++j ) // line.append( QString::number(m_data[j][i]) + "," ); // file.write( line.toLocal8Bit() + "\n" ); // } // file.close(); } void CSVBuilder::clear() { m_data.clear(); m_xAxisLabel.clear(); }
true
d6c0848e482d5b97abb31fcc0f20c1d3fdd5e0c2
C++
charles-a-beswick/Collatz-conjecture
/Collatz conjecture.cpp
UTF-8
1,599
3.65625
4
[]
no_license
#include <iostream> #include<limits> int main() { char repeat; do { std::cout << "======================================================\n " << "Enter a number and we will perform the Collatz conjecture on it!\n" << "======================================================" << std::endl; std::cout << "Please enter a positive integer: "; float seed; std::cin >> seed; //Checks to see that the input is a positive integer, if not prompts user for another entry int test = seed * 10; while (seed < 1 || test % 10 != 0) { std::cout << "This number is not valid, please enter a POSITIVE INTEGER: "; std::cin >> seed; test = seed * 10; } int processNum = seed; std::cout << "You chose " << seed << "." << std::endl; int counter = 0; //Performing the conjecture while (processNum != 1) { if (processNum % 2 == 0) { processNum = processNum / 2; } else if (processNum % 2 == 1) { processNum = 3 * processNum + 1; } counter++; std::cout << processNum << std::endl; } std::cout << "It took " << counter << " iterations to get " << seed << " to 1 via the Collatz conjeture!" << std::endl; std::cout << "Would you like to go again? (y/n): "; std::cin >> repeat; } while (repeat == 'y' || repeat == 'Y'); return 0; }
true
07f4ea5fb7a994fd2e0daf621d550451488bb32f
C++
NemoLeiYANG/generalvisodom
/src/util/math.cpp
UTF-8
5,865
3.0625
3
[ "BSD-2-Clause" ]
permissive
#include "gvio/util/math.hpp" namespace gvio { void print_shape(const std::string &name, const MatX &A) { std::cout << name << ": " << A.rows() << "x" << A.cols() << std::endl; } void print_shape(const std::string &name, const VecX &v) { std::cout << name << ": " << v.rows() << "x" << v.cols() << std::endl; } void print_array(const std::string &name, const double *array, const size_t size) { std::cout << name << std::endl; for (size_t i = 0; i < size; i++) { printf("%.4f ", array[i]); } printf("\b\n"); } std::string array2str(const double *array, const size_t size) { std::stringstream os; for (size_t i = 0; i < (size - 1); i++) { os << array[i] << " "; } os << array[size - 1]; return os.str(); } void array2vec(const double *x, const size_t size, VecX y) { y.resize(size); for (size_t i = 0; i < size; i++) { y(i) = x[i]; } } double *vec2array(const VecX &v) { double *array = (double *) malloc(sizeof(double) * v.size()); for (int i = 0; i < v.size(); i++) { array[i] = v(i); } return array; } double *mat2array(const MatX &m) { double *array = (double *) malloc(sizeof(double) * m.size()); int index = 0; for (int i = 0; i < m.rows(); i++) { for (int j = 0; j < m.cols(); j++) { array[index] = m(i, j); index++; } } return array; } void vec2array(const VecX &v, double *out) { for (int i = 0; i < v.size(); i++) { out[i] = v(i); } } void mat2array(const MatX &A, double *out) { int index = 0; for (int i = 0; i < A.rows(); i++) { for (int j = 0; j < A.cols(); j++) { out[index] = A(i, j); index++; } } } std::vector<VecX> mat2vec(const MatX &m, bool row_wise) { std::vector<VecX> vectors; if (row_wise) { for (long i = 0; i < m.rows(); i++) { vectors.emplace_back(m.row(i)); } } else { for (long i = 0; i < m.cols(); i++) { vectors.emplace_back(m.col(i)); } } return vectors; } std::vector<Vec3> mat2vec3(const MatX &m, bool row_wise) { std::vector<Vec3> vectors; if (row_wise) { assert(m.cols() == 3); for (long i = 0; i < m.rows(); i++) { vectors.emplace_back(m.row(i)); } } else { assert(m.rows() == 3); for (long i = 0; i < m.cols(); i++) { vectors.emplace_back(m.col(i)); } } return vectors; } int randi(int ub, int lb) { return rand() % lb + ub; } double randf(const double ub, const double lb) { const double f = (double) rand() / RAND_MAX; return lb + f * (ub - lb); } int sign(const double x) { if (fltcmp(x, 0.0) == 0) { return 0; } else if (x < 0) { return -1; } return 1; } int fltcmp(const double f1, const double f2) { if (fabs(f1 - f2) <= 0.0001) { return 0; } else if (f1 > f2) { return 1; } else { return -1; } } double median(const std::vector<double> &v) { // sort values std::vector<double> v_copy = v; std::sort(v_copy.begin(), v_copy.end()); // obtain median if (v_copy.size() % 2 == 1) { // return middle value return v_copy[v_copy.size() / 2]; } else { // grab middle two values and calc mean const double a = v_copy[v_copy.size() / 2]; const double b = v_copy[(v_copy.size() / 2) - 1]; return (a + b) / 2.0; } } double deg2rad(const double d) { return d * (M_PI / 180); } double rad2deg(const double r) { return r * (180 / M_PI); } void load_matrix(const std::vector<double> &x, const int rows, const int cols, MatX &y) { int idx; // setup idx = 0; y.resize(rows, cols); // load matrix for (int i = 0; i < cols; i++) { for (int j = 0; j < rows; j++) { y(j, i) = x[idx]; idx++; } } } void load_matrix(const MatX &A, std::vector<double> &x) { for (int i = 0; i < A.cols(); i++) { for (int j = 0; j < A.rows(); j++) { x.push_back(A(j, i)); } } } double binomial(const double n, const double k) { if (k == 0 || k == n) { return 1.0; } return binomial(n - 1, k - 1) + binomial(n - 1, k); } double wrapTo180(const double euler_angle) { return fmod((euler_angle + 180.0), 360.0) - 180.0; } double wrapTo360(const double euler_angle) { if (euler_angle > 0) { return fmod(euler_angle, 360.0); } else { return fmod(euler_angle + 360, 360.0); } } double wrapToPi(const double r) { return deg2rad(wrapTo180(rad2deg(r))); } double wrapTo2Pi(const double r) { return deg2rad(wrapTo360(rad2deg(r))); } double cross_track_error(const Vec2 &p1, const Vec2 &p2, const Vec2 &pos) { const double x0 = pos(0); const double y0 = pos(1); const double x1 = p1(0); const double y1 = p1(0); const double x2 = p2(0); const double y2 = p2(0); // calculate perpendicular distance between line (p1, p2) and point (pos) const double n = ((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1); const double d = sqrt(pow(y2 - y1, 2) + pow(x2 - x1, 2)); return fabs(n) / d; } int point_left_right(const Vec2 &a, const Vec2 &b, const Vec2 &c) { const double a0 = a(0); const double a1 = a(1); const double b0 = b(0); const double b1 = b(1); const double c0 = c(0); const double c1 = c(1); const double x = (b0 - a0) * (c1 - a1) - (b1 - a1) * (c0 - a0); if (x > 0) { return 1; // left } else if (x < 0) { return 2; // right } else if (x == 0) { return 0; // parallel } return -1; } double closest_point(const Vec2 &a, const Vec2 &b, const Vec2 &p, Vec2 &closest) { // pre-check if ((a - b).norm() == 0) { closest = a; return -1; } // calculate closest point const Vec2 v1 = p - a; const Vec2 v2 = b - a; const double t = v1.dot(v2) / v2.squaredNorm(); closest = a + t * v2; return t; } Vec2 lerp(const Vec2 &a, const Vec2 &b, const double mu) { return a * (1 - mu) + b * mu; } } // eof gvio
true
4bfc61b36020d58f7a0b0b7c637ad7ee4a715322
C++
lord-of-logic/problem_solving
/trees/left_view.cpp
UTF-8
1,142
3.5
4
[]
no_license
#include<iostream> #include<vector> #include<stack> using namespace std; class node { public: int data; node *left; node *right; node(int data) { this->data=data; this->left=nullptr; this->right=nullptr; } }; void insert(node **root,int data) { node *temp_root=*root; if(!temp_root) { temp_root=new node(data); *root=temp_root; return; } if(temp_root->data>data) { insert(&temp_root->left,data); return; } insert(&temp_root->right,data); return; } void leftview(node* root,int curr_level,int* max_level) { if(!root) return; if(curr_level>*max_level) { cout<<root->data<<" "; } if(curr_level>*max_level) *max_level=curr_level; leftview(root->left,curr_level+1,max_level); leftview(root->right,curr_level+1,max_level); } int main() { node *root=nullptr; vector<int> A={50,15,62,5,20,58,91,3,8,37,60,24,100,101,102}; for(int i=0;i<A.size();i++) insert(&root,A[i]); int* max_level=new int(0); leftview(root,1,max_level); return 0; }
true
3c9d65c91574d717589dbad75833b9fd76520989
C++
armkernel/armkernel.github.io
/code_practice/10/advanced_cpp/2일차/2_vector2.cpp
UHC
781
3.78125
4
[ "MIT" ]
permissive
#include <iostream> using namespace std; template<typename T> class vector { T* buff; int sz; public: vector(int s, T value = T()) :sz(s) { buff = static_cast<T*>(operator new(sizeof(T)*sz)); try { std::uninitialized_fill_n(buff, sz, value); } catch (...) { operator delete(buff); } } ~vector() { for (int i = 0; i < sz; i++) buff[i].~T(); operator delete(buff); } //[] : ü 迭 ó 밡ϰ Ѵ. // v[0] = 100 ó Լ ȣ º Ƿ ȯ ʿ T& operator[](int idx) { return buff[idx]; } }; int main() { vector<int> v(10); v[0] = 100; // v.operator[](0) = 100 cout << v[0] << endl; }
true
a02b73bd3baa12f10c5623d018849366d6d653d4
C++
zachlambert/game-arena
/src/render/polygon_renderer.cpp
UTF-8
4,799
2.96875
3
[]
no_license
#include "render/polygon_renderer.h" #include <iostream> #include <stack> PolygonVertex::PolygonVertex(glm::vec3 position, glm::vec4 color) { // Position straightforward this->position = position; this->color = color; } void PolygonRenderer::initialise(unsigned int program_id) { this->program_id = program_id; m_loc = glGetUniformLocation(program_id, "M"); v_loc = glGetUniformLocation(program_id, "V"); glGenVertexArrays(1, &static_VAO); glGenBuffers(1, &static_VBO); glGenBuffers(1, &static_EBO); glBindVertexArray(static_VAO); glBindBuffer(GL_ARRAY_BUFFER, static_VBO); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof(PolygonVertex), (void*)0 ); glEnableVertexAttribArray(0); glVertexAttribPointer( 1, 4, GL_FLOAT, GL_TRUE, sizeof(PolygonVertex), (void*)offsetof(PolygonVertex, color) ); glEnableVertexAttribArray(1); // Force a reinitialisation of vertices and indices vertices.resize_flag = true; indices.resize_flag = true; reinitialise(); } void PolygonRenderer::enable(const glm::mat4 &view) { glUseProgram(program_id); glBindVertexArray(static_VAO); glUniformMatrix4fv(v_loc, 1, GL_FALSE, &view[0][0]); } void PolygonRenderer::store_polygon(const component::Polygon &polygon) { if (!polygon.visible) return; if (polygon.to_deallocate) { vertices.deallocate(polygon.vertices.size(), polygon.vertices_offset); indices.deallocate(polygon.indices.size(), polygon.indices_offset); } if (!polygon.allocated) { polygon.allocated = true; // TODO: !!! Will break of vertices and indices sizes aren't multiples of 2 vertices.allocate(polygon.vertices.size(), polygon.vertices_offset); indices.allocate(polygon.indices.size(), polygon.indices_offset); for (std::size_t i = 0; i < polygon.vertices.size(); i++) { vertices.data[i].position.z = 0; } } if (polygon.dirty) { for (std::size_t i = 0; i < polygon.vertices.size(); i++) { vertices.data[polygon.vertices_offset+i].position.x = polygon.vertices[i].x; vertices.data[polygon.vertices_offset+i].position.y = polygon.vertices[i].y; vertices.data[polygon.vertices_offset+i].color = polygon.colors[i]; } for (std::size_t i = 0; i < polygon.indices.size(); i++) { indices.data[polygon.indices_offset+i] = polygon.indices[i]; } polygon.dirty = false; if (!vertices.resize_flag) { glBindVertexArray(static_VAO); glBindBuffer(GL_ARRAY_BUFFER, static_VBO); glBufferSubData( GL_ARRAY_BUFFER, polygon.vertices_offset*sizeof(PolygonVertex), polygon.vertices.size()*sizeof(PolygonVertex), &vertices.data[polygon.vertices_offset] ); } // TODO: Use seperate flag for when indices change if (!indices.resize_flag) { glBindVertexArray(static_VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, static_EBO); glBufferSubData( GL_ELEMENT_ARRAY_BUFFER, polygon.indices_offset*sizeof(unsigned short), polygon.indices.size()*sizeof(unsigned short), &indices.data[polygon.indices_offset] ); } } } void PolygonRenderer::reinitialise() { glBindVertexArray(static_VAO); if (vertices.resize_flag) { vertices.resize_flag = false; glBindBuffer(GL_ARRAY_BUFFER, static_VBO); glBufferData( GL_ARRAY_BUFFER, vertices.data.size() * sizeof(PolygonVertex), &vertices.data[0], GL_STREAM_DRAW ); } if (indices.resize_flag) { indices.resize_flag = false; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, static_EBO); glBufferData( GL_ELEMENT_ARRAY_BUFFER, indices.data.size() * sizeof(unsigned short), &indices.data[0], GL_STREAM_DRAW ); } } void PolygonRenderer::render(const component::Polygon &polygon) { if (!polygon.visible) return; if (polygon.to_deallocate) return; glUniformMatrix4fv(m_loc, 1, GL_FALSE, &polygon.model[0][0]); glDrawElementsBaseVertex( GL_TRIANGLES, polygon.element_count, GL_UNSIGNED_SHORT, (void*)(sizeof(unsigned short) * polygon.indices_offset), polygon.vertices_offset ); } void PolygonRenderer::deallocate_polygon(const component::Polygon &polygon) { if (!polygon.allocated) return; vertices.deallocate(polygon.vertices.size(), polygon.vertices_offset); indices.deallocate(polygon.indices.size(), polygon.indices_offset); }
true
5ea8055606852843a0f520523a2f072a4a9675e0
C++
brunonevado/concatenateFasta
/source/main.cpp
UTF-8
3,957
2.828125
3
[]
no_license
// // main.cpp // concatenateFasta // // Created by bnevado on 26/09/2014. // Copyright (c) 2014 Bruno Nevado. All rights reserved. // #include <iostream> #include <fstream> #include "fasta.h" #include "args.h" void help(){ std::cout << "###################\n concatenateFasta 16022018 \n###################" << std::endl;; std::cout << "Concatenate any number of fasta files" << std::endl;; std::cout << "Usage: concatenateFasta -files in.txt -outfile out.fas -missChar N [ -pinfo partitions.txt ]" << std::endl; std::cout << "-files should contain list of input files to concatenate." << std::endl; std::cout << "Input files should be aligned, and in fasta format." << std::endl; std::cout << "Uses sequence names, so order in each file is irrelevant." << std::endl; std::cout << "Missing sequences are replaced with -missChar." << std::endl; std::cout << "Set '-verbose 0' to turn off warnings" << std::endl; std::cout << "Set '-pinfo file' to write partition information file for RAxML" << std::endl; } int main(int argc, const char * argv[]) { sargs myargs; try{ myargs = args::getargs(argc, argv, std::vector<std::string> {"files", "outfile","missChar"}, std::vector<std::string> {}, std::vector<std::string> {}, std::string {"pinfo"}, std::string {"verbose"}); } catch (std::string e){ std::cout << " Args failed: " << e << std::endl; help(); exit(1); } std::string infile = myargs.args_string.at(0); std::string outfile= myargs.args_string.at(1); std::string missString = myargs.args_string.at(2); char missChar = missString.at(0); int verb = ( myargs.args_int_optional.size() > 0 ) ? myargs.args_int_optional.at(0) : 2; std::string partitions = ( myargs.args_string_optional.size() > 0 ) ? myargs.args_string_optional.at(0) : ""; std::vector <std::string > files; std::string cline; std::vector < int > starts; std::vector < int > ends; std::ifstream fh; fh.open(infile); if( !fh.is_open()){ std::cerr << "<concatenateFasta> ERROR: cannot open for reading infile " << infile << std::endl; exit(1); } while (getline(fh, cline)) { files.push_back(cline); } if(verb > 0){ std::clog << "<concatenateFasta> Read " << files.size() << " file names to concatenate from file " << infile << std::endl; } fasta afasta(1); afasta.read_fasta_file(files.at(0)); starts.push_back(1); ends.push_back(afasta.num_bases()); if( afasta.is_aligned() != 0 ){ std::cerr << "<concatenateFasta> ERROR: fasta file " << files.at(0) << " does not seem to be aligned!" << std::endl; exit(1); } for (unsigned int i = 1; i < files.size(); i++) { fasta newfasta(afasta.num_lines()); newfasta.read_fasta_file(files.at(i)); if( newfasta.is_aligned() != 0 ){ std::cerr << "<concatenateFasta> ERROR: fasta file " << files.at(i) << " does not seem to be aligned!" << std::endl; exit(1); } starts.push_back(afasta.num_bases() + 1); afasta.free_concatenate(newfasta, verb, missChar); ends.push_back(afasta.num_bases()); } if(verb > 0){ std::clog << "<concatenateFasta> Finished concatenating files, final alignment contains " << afasta.num_bases() << " base-pairs. Now writing to file " << outfile << std::endl; } afasta.write_to_file(outfile); if( partitions.length() > 0 ){ std::ofstream fho(partitions); if(! fho.is_open() ){ std::cerr << "ERROR: cant open for writing partition file " << partitions << std::endl; exit(1); } for(int i = 0; i < starts.size(); i++){ fho << "DNA, p" << i+1 << " = " << starts.at(i) << "-" << ends.at(i) << std::endl; } } return 0; }
true
fdd3ee7a53500254e698be850b01de80d5f19fbb
C++
krconv/iot-devices
/src/LightSwitch/Button.cpp
UTF-8
1,867
3
3
[ "MIT" ]
permissive
#include "Button.h" #include <functional> #include <Arduino.h> #include "Configuration.h" namespace LightSwitch { Button::Button(MqttClient &mqttClient_) : mqttClient(mqttClient_) { } void Button::setup() { pinMode(Configuration::getButtonPin(), INPUT); mqttClient.subscribe( Configuration::getMqttTopicButtonState(), std::bind(&Button::handleStateUpdateMessage, this, std::placeholders::_1)); } void Button::loop() { voltage_t value = digitalRead(Configuration::getButtonPin()); switch (value) { case Configuration::getButtonVoltageNotPressed(): pressed = false; break; case Configuration::getButtonVoltagePressed(): if (!pressed) { toggleState(); pressed = true; } break; } } void Button::toggleState() { switch (currentState) { case Button::State::OFF: case Button::State::TURNING_OFF: mqttClient.publish(Configuration::getMqttTopicButtonSetState(), Configuration::getMqttPayloadOn()); currentState = Button::State::TURNING_ON; break; case Button::State::ON: case Button::State::TURNING_ON: default: mqttClient.publish(Configuration::getMqttTopicButtonSetState(), Configuration::getMqttPayloadOff()); currentState = Button::State::TURNING_OFF; break; } } void Button::handleStateUpdateMessage(const std::string &message) { if (message == Configuration::getMqttPayloadOff()) { currentState = Button::State::OFF; } else if (message == Configuration::getMqttPayloadOn()) { currentState = Button::State::ON; } } Button::State Button::getState() const { return currentState; } bool Button::isBeingPressed() const { return pressed; } } // namespace LightSwitch
true
6d5d375dd53a94a87ce07f3e857fd3798c42bd5d
C++
filippe24/ca_water_simulation
/watergrid.h
UTF-8
6,181
2.96875
3
[]
no_license
#ifndef WATERGRID_H #define WATERGRID_H #include <QApplication> #include <glm/glm.hpp> #include <iostream> class waterGrid { public: waterGrid(); waterGrid(float room_dim, float cube_dim, int mode) { room_dim_param = room_dim; cube_dimension = cube_dim; cubes_per_side = int(room_dim_param*int(room_dim_param/cube_dimension)); initializeWaterGrid(mode); } float room_dim_param; float cube_dimension; int cubes_per_side; float dt = 0.1f; float h = 1.0f; float c = 3.0f; //WATER CUBE typedef std::pair<uint,uint> positionType; struct waterCubeStruct { uint id; positionType position; float heigth = 2.0f; float velocity = 0.0f; void createWaterCube(uint id_in, positionType pos_in) { id = id_in; position = pos_in; } }; //WATER STRUCTURE std::vector<waterCubeStruct> water; void initializeWaterGrid(int mode) { uint id = 0; water.clear(); for(int col_i = 0; col_i < cubes_per_side; col_i++ ) { for(int row_j = 0; row_j < cubes_per_side; row_j++ ) { waterCubeStruct cube_i_j; positionType pos = positionType(col_i, row_j); cube_i_j.createWaterCube(id,pos); if(mode == 0) cube_i_j.heigth = cube_i_j.heigth + col_i*0.3f; else if(mode == 1) cube_i_j.heigth = cube_i_j.heigth + row_j*0.3f; else if(mode == 2) cube_i_j.heigth = (cube_i_j.heigth + 2.0f*(1.0f - float(col_i+row_j)/float(2*cubes_per_side)) ); water.push_back(cube_i_j); id++; } } } glm::vec3 getCubePosition(uint id) { glm::vec3 returned_vector = glm::vec3(0.0,0.0,0.0); int center = cubes_per_side/2; int col = int(water[id].position.first); int row = int(water[id].position.second); int col_diff = col - center; int row_diff = row - center; returned_vector.x = cube_dimension/2.0f + col_diff*cube_dimension; returned_vector.z = cube_dimension/2.0f + row_diff*cube_dimension; returned_vector.y = (cube_dimension/2.0f) * water[id].heigth; return returned_vector; } uint getIdFromPos(int col, int row) { return uint(col*cubes_per_side + row); } uint getIdFromPos(positionType cellPos) { return uint(cellPos.first*uint(cubes_per_side) + cellPos.second); } void updateWater() { std::vector<float> new_velocities; for(uint w = 0; w < water.size(); w++) { float old_vel = water[w].velocity; float neighH = 0.0f; std::vector<uint> neigh = getNeighbours(w); for(uint n = 0; n < neigh.size(); n++) { neighH += water[neigh[n]].heigth; } float new_vel = old_vel + 0.99f* (neighH/4.0f - water[w].heigth) ; new_vel = 0.99f*(old_vel + dt*c*c * (neighH - 4.0f*water[w].heigth)/(h*h)) ; // std::cout << std::endl; // std::cout << " cube " << w << std::endl; // std::cout << " position :" << water[w].position.first << " , " << water[w].position.second << " and computed id :"<<getIdFromPos(water[w].position) << std::endl; // std::cout << " old velocity = " << old_vel << std::endl; // std::cout << " old heigth = " << water[w].heigth << std::endl; // std::cout << " number of neigh = " << neigh.size() << std::endl; // std::cout << " neigh " << neigh[0] << " , " << neigh[1] << " , " << neigh[2] << ", " << neigh[3] <<std::endl ; // std::cout << " new velocity = " << new_vel << std::endl; // std::cout << " new heigth = " << water[w].heigth + new_vel << std::endl; // water[w].velocity = new_vel; // water[w].heigth += new_vel; new_velocities.push_back(new_vel); } for(uint w = 0; w < water.size(); w++) { water[w].velocity = new_velocities[w]; water[w].heigth += dt*new_velocities[w]; } // if(water[w].heigth < 2.0f) // { // water[w].heigth = 2.0f; // water[w].velocity = 0.0f; // } } std::vector<uint> getNeighbours(uint id) { std::vector<uint> returned_list; uint c = water[id].position.first; uint r = water[id].position.second; positionType neighPos; //1 if(c > 0) { neighPos.first = c-1; neighPos.second = r; returned_list.push_back(getIdFromPos(neighPos)); } else { neighPos.first = 0; neighPos.second = r; returned_list.push_back(getIdFromPos(neighPos)); } //2 if(r > 0) { neighPos.first = c; neighPos.second = r-1; returned_list.push_back(getIdFromPos(neighPos)); } else { neighPos.first = c; neighPos.second = 0; returned_list.push_back(getIdFromPos(neighPos)); } //3 if(r < uint(cubes_per_side)-1) { neighPos.first = c; neighPos.second = r+1; returned_list.push_back(getIdFromPos(neighPos)); } else { neighPos.first = c; neighPos.second = uint(cubes_per_side)-1; returned_list.push_back(getIdFromPos(neighPos)); } //4 if(c < uint(cubes_per_side)-1) { neighPos.first = c+1; neighPos.second = r; returned_list.push_back(getIdFromPos(neighPos)); } else { neighPos.first = uint(cubes_per_side)-1 ; neighPos.second = r; returned_list.push_back(getIdFromPos(neighPos)); } return returned_list; } }; #endif // WATERGRID_H
true
95eda7c159c1d7a50430521ecd5055e0842dea2d
C++
ms303956362/myexercise
/DS/8_Dict/diligence2.cpp
UTF-8
2,648
2.953125
3
[]
no_license
#include <cstdio> #include <cstring> char a[20011][10]; int cnt[20011]; struct Entry { //词条模板类 char * key; int value; Entry ( char* k, int v) : value ( v ) { key = new char[strlen(k) + 1]; strcpy(key, k); }; Entry (const Entry& e ) : value ( e.value ) { key = new char[strlen(e.key) + 1]; strcpy(key, e.key); }; ~Entry() { delete[] key; key = nullptr; } }; class HashTable { // 手动确定M,需要保证为素数,装填因子不负责最优 public: int N; int M; Entry **ht; int probe4Hit(char* k); int probe4Free(char* k); HashTable(int m); int size() const { return N; } bool put(char* k, int v); int *get(char* k); }; /*********************静态方法************************/ static size_t hashCode(char* s) { int h = 0; size_t n = strlen(s); for (size_t i = 0; i != n; ++i) { h = (h << 5) | (h >> 27); // 循环左移5位 h += static_cast<int>(s[i]); } return static_cast<size_t>(h); } /*********************保护***************************/ int HashTable::probe4Hit(char* k) { // 找匹配 int c = hashCode(k) % M, r = c; int i = 1; while (ht[r] && strcmp(ht[r]->key, k)) { r = (c + i * i) % M; ++i; } return r; } int HashTable::probe4Free(char* k) { // 找空桶 int c = hashCode(k) % M, r = c; int i = 1; while (ht[r]) { r = (c + i * i) % M; ++i; } return r; } /********************对外接口*************************/ HashTable::HashTable(int m) : N(0), M(m) { ht = new Entry*[m]; memset(ht, 0, sizeof(Entry*) * m); } bool HashTable::put(char* k, int v) { if (ht[probe4Hit(k)]) { // 相同元素直接返回 return false; } int r = probe4Free(k); ht[r] = new Entry(k, v); ++N; return true; } int *HashTable::get(char* k) { int r = probe4Hit(k); return ht[r] ? &(ht[r]->value) : nullptr; } int main(int argc, char const *argv[]) { setvbuf(stdin, new char[1 << 20], _IOFBF, 1 << 20); setvbuf(stdout, new char[1 << 20], _IOFBF, 1 << 20); int n; char s[10]; HashTable ht(50087); scanf("%d", &n); while (n-- > 0) { scanf("%s", s); int *p = ht.get(s); if (p) ++*p; else ht.put(s, 1); } Entry *p=nullptr; int max_cnt = 0; for (int i = 0; i != 50087; ++i) { p = ht.ht[i]; if (p && p->value > max_cnt) { strcpy(s, p->key); max_cnt = p->value; } } printf("%s %d", s, max_cnt); return 0; }
true
33154c124464540b7636adf42ae806116b5343fc
C++
felipebma/CompetitiveProgramming
/Seletiva2019/Homework#2/J.cpp
UTF-8
346
2.625
3
[]
no_license
#include <bits/stdc++.h> #define endl "\n" using namespace std; int main(){ ios::sync_with_stdio(0);cin.tie(0); vector<int> arr; int n,aux; cin >> n; while(n--){ cin >> aux; arr.push_back(aux); } sort(arr.begin(),arr.end()); if(arr.size()>0){ cout << arr[0]; for(int i=1;i<arr.size();i++) cout << " " << arr[i]; } return 0; }
true
3815b8795697f4c3004671bf82c50a588c042a79
C++
shannubansal/progettoP2
/vacation.h
UTF-8
1,368
2.96875
3
[]
no_license
#ifndef VACATION_H #define VACATION_H #include<QDate> #include<QString> #include<iostream> #include<sstream> #include<iomanip> using std::string; #include "writer.h" class Writer; class Vacation { private: string name; string place; string country; QDate date; double basePrice; unsigned int weeks; public: Vacation(string="", string="", string="", int=2020, int=1, int=1, double=0.0, unsigned int=1 ); virtual ~Vacation()=default; //metodi virtuali virtual Vacation* clone() const=0; virtual double calcFinalPrice() const=0; virtual double calcCommission() const=0; virtual string getTipo() const=0; virtual string getInfo() const; virtual bool operator==(const Vacation&) const; string getName() const; string getPlace() const; string getCountry() const; QDate getDate() const; int getYearD() const; int getMonthD() const; int getDayD() const; double getBasePrice() const; unsigned int getWeeks() const; void setName(string n); void setPlace(string p); void setCountry(string c); bool setDateVacation(int y, int m, int d); bool setDateVacation(QDate d); void setBasePrice(double bP); void setWeeks(int w); virtual void saveOnFile(Writer&) =0; }; std::ostream& operator<<(std::ostream& , const Vacation& ); #endif // VACATION_H
true
124fbc63c2d3d02d809020fc2c72a42f484ad5f9
C++
sql-sith/RPG
/RPG/RPG/dungeon.cpp
UTF-8
2,234
3.40625
3
[]
no_license
#include "dungeon.h" #include <fstream> #include <cstdlib> #include <cstddef> #include <iostream> using namespace std; class ForwardError {}; class BackwardError {}; Dungeon::Dungeon() { dunStart = new Room; dunStart->description = "DEFAULT_ROOM"; dunStart->isMonster = false; dunStart->next = NULL; playerLoc = dunStart; } // Pre: File contains correctly formatted room(s). // Post: Dungeon has been initialized with appropriate rooms. Dungeon::Dungeon(ifstream& inFile) { Room* prevLoc = NULL; int monsterLevel; string monsterName; dunStart = new Room; playerLoc = dunStart; string throwAway; getline(inFile, throwAway); playerLoc->previous= NULL; getline(inFile, playerLoc->description); inFile >> playerLoc->isMonster >> monsterLevel >> monsterName; getline(inFile, throwAway); // Read past EOL character. playerLoc->monster = Player(monsterName, monsterLevel); prevLoc = playerLoc; while (inFile) { playerLoc->next = new Room; playerLoc = playerLoc->next; playerLoc->previous=prevLoc; getline(inFile, playerLoc->description); inFile >> playerLoc->isMonster >> monsterLevel >> monsterName; getline(inFile, throwAway); // Read past EOL character. playerLoc->monster = Player(monsterName, monsterLevel); prevLoc = playerLoc; } playerLoc->next = NULL; playerLoc = dunStart; } string Dungeon::GetDescription() { return playerLoc->description; } void Dungeon::GoForward() { if (playerLoc->next == NULL) throw ForwardError(); else playerLoc = playerLoc->next; } void Dungeon::GoBackwards() { if (playerLoc->previous == NULL) throw BackwardError(); else playerLoc = playerLoc->previous; } bool Dungeon::IsMonster() { return playerLoc->isMonster; } bool Dungeon::IsBack() { return (playerLoc->previous != NULL); } bool Dungeon::IsForward() { return (playerLoc->next != NULL); } Player Dungeon::GetMonster() { return playerLoc->monster; } void Dungeon::Movement(char toMove) { try { switch (toMove) { case 'F': GoForward(); break; case 'B': GoBackwards(); break; }; } catch (ForwardError()) { cout << "Warning! NULL dereference attempted!" << endl; } catch (BackwardError()) { cout << "Warning! NULL dereference attempted!" << endl; } }
true
b457604e383e01488ed7fa6cb65a88b5f27ba3b1
C++
MahinHossainMunna/Solved-Codes-URI
/Problem1161.cpp
UTF-8
303
2.65625
3
[]
no_license
#include<stdio.h> main() { long long int i,j,n,m; long long int f1,f2; f1=f2=1; while(scanf("%lld %lld",&n,&m) != EOF){ for(i=1; i<=n; i++){ f1=f1 * i; } for(j=1; j<=m; j++){ f2=f2 * j; } long long int sum = f1+f2; printf("%lld\n",sum); f1=f2=1; } }
true
13f13a6037ead65f5e57d55a5a3b61d2fe048d61
C++
z34hyr/school21_projects
/10_cpp_modules/module_02/ex00/Fixed.class.cpp
UTF-8
814
3.1875
3
[]
no_license
#include "Fixed.class.hpp" const int _fb_number = 8; Fixed::Fixed(void) { std::cout << "Default constructor called" << std::endl; Fixed::_fp_value = 0; return; } Fixed::~Fixed(void) { std::cout << "Destructor constructor called" << std::endl; return; } // copy constructor Fixed::Fixed(const Fixed& obj)// : _fp_value(obj._fp_value) { std::cout << "Copy constructor called" << std::endl; _fp_value = obj.getRawBits(); return; } //assignment operator = Fixed& Fixed::operator = (const Fixed& obj) { std::cout << "Assignation operator called" << std::endl; _fp_value = obj.getRawBits(); return *this; } int Fixed::getRawBits(void) const { std::cout << "getRawBits member function called" << std::endl; return(this->_fp_value); } void Fixed::setRawBits(int const raw) { this->_fp_value = raw; }
true
255889c0c0987dad2187c363d9dcfcb771728c79
C++
LynnShaw/MyAlgorithm
/code_for_interview/10.斐波那契数列.cpp
UTF-8
707
3.34375
3
[]
no_license
#include <iostream> #include <stack> #include <vector> using namespace std; class Solution { public: int Fibonacci(int n) { // int a,b,c; int a = 0,b = 0,c = 0; for (int i = 1; i <= n; ++i) { if (i==1){ c=1; } else if(i==2){ b=0; a=1; c=1; } else { b = a; a = c; c = b + a; } } return c; } }; int main() { Solution s; cout<<s.Fibonacci(1)<<endl; cout<<s.Fibonacci(2)<<endl; cout<<s.Fibonacci(3)<<endl; cout<<s.Fibonacci(5)<<endl; cout<<s.Fibonacci(7)<<endl; return 0; }
true
19c415661eb164963732e66042bc942dac8acc1e
C++
MESH-Model/MESH_Project_Baker_Creek
/Model/Ostrich/ParameterABC.h
UTF-8
12,306
2.59375
3
[]
no_license
/****************************************************************************** File : ParameterABC.h Author : L. Shawn Matott Copyright : 2004, L. Shawn Matott Encapsulates a parameter. Parameters are variables in the model which are to be calibrated. Version History 06-12-03 lsm added copyright information and initial comments. 08-20-03 lsm created version history field and updated comments. 11-25-03 lsm Modified to support multiple stages of unit conversion. 07-05-04 lsm added integer and combinatorial parameter support 12-02-04 lsm made ConvertInVal() a required member function 03-03-05 lsm Added support for ON/OFF parameter threshold ******************************************************************************/ #ifndef PARAMETER_ABC_H #define PARAMETER_ABC_H #include "MyHeaderInc.h" // forward decs class ConstraintABC; /* An enum is defined for each type of transformation. */ typedef enum TRANSFORM_TYPE { TX_NONE = 0, TX_LOG10 = 1, TX_LN = 2 }TransformTypeEnum; /* An enum is defined for each stage of transformation. */ typedef enum TRANSFORM_STAGE { TX_IN = 0, TX_OST = 1, TX_OUT = 2 }TransformStageEnum; #define NUM_STAGES (3) /****************************************************************************** class ParameterABC Abstract base class of a parameter. ******************************************************************************/ class ParameterABC { public: virtual ~ParameterABC(void){ DBG_PRINT("ParameterABC::DTOR"); } virtual void Destroy(void) = 0; virtual void GetValAsStr(UnmoveableString valStr) = 0; virtual void Write(FILE * pFile, int type) = 0; virtual double GetLwrBnd(void) = 0; virtual double GetUprBnd(void) = 0; virtual void SetLwrBnd(double val) = 0; virtual void SetUprBnd(double val) = 0; virtual double GetEstVal(void) = 0; virtual double SetEstVal(double estVal) = 0; //threshold values (allow for implicit on/off of parameters) virtual void SetThreshVal(double lwr, double upr, double off) = 0; virtual UnchangeableString GetName(void) = 0; virtual double GetTransformedVal(void) = 0; virtual double ConvertOutVal(double val) = 0; virtual double ConvertInVal(double val) = 0; virtual const char * GetType(void) = 0; }; /* end class ParameterABC */ /****************************************************************************** class RealParam Represents a continuously varying parameter ******************************************************************************/ class RealParam : public ParameterABC { public: RealParam(void); RealParam(IroncladString name, double initialValue, double lowerBound , double upperBound, IroncladString txIn, IroncladString txOst, IroncladString txOut, IroncladString fixFmt); ~RealParam(void){ DBG_PRINT("RealParam::DTOR"); Destroy();} void Destroy(void); void GetValAsStr(UnmoveableString valStr); void Write(FILE * pFile, int type); double GetLwrBnd(void){ return m_LwrBnd;} double GetUprBnd(void){ return m_UprBnd;} void SetLwrBnd(double val){ m_LwrBnd = val;} void SetUprBnd(double val){ m_UprBnd = val;} double GetEstVal(void){ return m_EstVal;} double SetEstVal(double estVal); UnchangeableString GetName(void){ return m_pName;} double GetTransformedVal(void); double ConvertOutVal(double val); double ConvertInVal(double val); //threshold values (allow for implicit on/off of parameters) void SetThreshVal(double lwr, double upr, double off){ m_ThreshLwr = lwr; m_ThreshUpr = upr; m_ThreshOff = off;} const char * GetType(void) {return "real";} private: StringType m_pName; StringType m_pFixFmt; double m_InitVal; double m_LwrBnd; double m_UprBnd; double m_EstVal; double m_ThreshLwr, m_ThreshUpr, m_ThreshOff; TransformTypeEnum m_TransID[NUM_STAGES]; void SetTransformation(TransformStageEnum which, IroncladString tx); }; /* end class RealParam */ /****************************************************************************** class IntParam Represents an integer parameter ******************************************************************************/ class IntParam : public ParameterABC { public: IntParam(void); IntParam(IroncladString name, int initialValue, int lowerBound, int upperBound); ~IntParam(void){ DBG_PRINT("IntParam::DTOR"); Destroy();} void Destroy(void); void GetValAsStr(UnmoveableString valStr){sprintf(valStr, "%d", m_EstVal);} double GetEstVal(void){ return (double)m_EstVal;} double SetEstVal(double estVal); double GetLwrBnd(void){ return (double)m_LwrBnd;} double GetUprBnd(void){ return (double)m_UprBnd;} void SetLwrBnd(double val){ m_LwrBnd = (int)val;} void SetUprBnd(double val){ m_UprBnd = (int)val;} double GetTransformedVal(void){ return (double)m_EstVal;} double ConvertOutVal(double val){ return val;} double ConvertInVal(double val){ return val;} UnchangeableString GetName(void){ return m_pName;} void Write(FILE * pFile, int type); void SetThreshVal(double lwr, double upr, double off){ m_ThreshLwr = (int)lwr; m_ThreshUpr = (int)upr; m_ThreshOff = (int)off;} const char * GetType(void) {return "integer";} private: StringType m_pName; int m_InitVal; int m_LwrBnd; int m_UprBnd; int m_EstVal; int m_ThreshLwr, m_ThreshUpr, m_ThreshOff; }; /* end class IntParam */ /****************************************************************************** class ComboIntParam Class for the combinatorial integer parameters. ******************************************************************************/ class ComboIntParam : public ParameterABC { public: ComboIntParam(void); ComboIntParam(IroncladString name, UnmoveableString configStr); ~ComboIntParam(void){ DBG_PRINT("ComboIntParam::DTOR"); Destroy();} void Destroy(void); void GetValAsStr(UnmoveableString valStr){sprintf(valStr, "%d", m_pCombos[m_CurIdx]);} void Write(FILE * pFile, int type); double GetLwrBnd(void){ return 0.00;} double GetUprBnd(void){ return (double)(m_NumCombos - 1);} void SetLwrBnd(double val){ return;} void SetUprBnd(double val){ return;} double GetEstVal(void){ return (double)m_CurIdx;} double SetEstVal(double Idx); UnchangeableString GetName(void){ return m_pName;} double GetTransformedVal(void){ return (double)(m_pCombos[m_CurIdx]);} double ConvertOutVal(double val){ return val;} double ConvertInVal(double val){ return val;} void SetThreshVal(double lwr, double upr, double off){ return;} const char * GetType(void) {return "combinatorial integer";} private: StringType m_pName; int m_CurIdx; int m_NumCombos; int m_InitIdx; int * m_pCombos; }; /* end class ComboIntParam */ /****************************************************************************** class ComboDblParam Class for the combinatorial real parameters. ******************************************************************************/ class ComboDblParam : public ParameterABC { public: ComboDblParam(void); ComboDblParam(IroncladString name, UnmoveableString configStr); ~ComboDblParam(void){ DBG_PRINT("ComboDblParam::DTOR"); Destroy();} void Destroy(void); void GetValAsStr(UnmoveableString valStr); void Write(FILE * pFile, int type); double GetLwrBnd(void){ return 0.00;} double GetUprBnd(void){ return (double)(m_NumCombos - 1);} void SetLwrBnd(double val){ return;} void SetUprBnd(double val){ return;} double GetEstVal(void){ return (double)m_CurIdx;} double SetEstVal(double Idx); UnchangeableString GetName(void){ return m_pName;} double GetTransformedVal(void){ return m_pCombos[m_CurIdx];} double ConvertOutVal(double val){ return val;} double ConvertInVal(double val){ return val;} void SetThreshVal(double lwr, double upr, double off){ return;} const char * GetType(void) {return "combinatorial double";} private: StringType m_pName; int m_CurIdx; int m_NumCombos; int m_InitIdx; double * m_pCombos; }; /* end class ComboDblParam */ /****************************************************************************** class ComboStrParam Class for the combinatorial string parameters. ******************************************************************************/ class ComboStrParam : public ParameterABC { public: ComboStrParam(void); ComboStrParam(IroncladString name, UnmoveableString configStr); ~ComboStrParam(void){ DBG_PRINT("ComboStrParam::DTOR"); Destroy();} void Destroy(void); void GetValAsStr(UnmoveableString valStr); void Write(FILE * pFile, int type); double GetLwrBnd(void){ return 0.00;} double GetUprBnd(void){ return (double)(m_NumCombos - 1);} double GetEstVal(void){ return (double)m_CurIdx;} void SetLwrBnd(double val){ return;} void SetUprBnd(double val){ return;} double SetEstVal(double Idx); UnchangeableString GetName(void){ return m_pName;} double GetTransformedVal(void){ return atof(m_pCombos[m_CurIdx]);} double ConvertOutVal(double val){ return val;} double ConvertInVal(double val){ return val;} void SetThreshVal(double lwr, double upr, double off){ return;} const char * GetType(void) {return "combinatorial string";} private: StringType m_pName; int m_CurIdx; int m_NumCombos; int m_InitIdx; char ** m_pCombos; }; /* end class ComboStrParam */ /****************************************************************************** class SpecialParam Special Ostrich parameters. These correspond to 'optimal' cost and constraint values at any given stage of Ostrich. Can be used for linking Ostrich with the model pre-emption capabilities of a given model. ******************************************************************************/ class SpecialParam { public: SpecialParam(void); SpecialParam(IroncladString name, IroncladString type, IroncladString limit, IroncladString constraint, double init); ~SpecialParam(void){ DBG_PRINT("SpecialParam::DTOR"); Destroy();} void Destroy(void); void GetValAsStr(UnmoveableString valStr); void Write(FILE * pFile, int type); //treat special parameters as unbounded double GetLwrBnd(void){ return NEARLY_ZERO;} double GetUprBnd(void){ return NEARLY_HUGE;} void SetLwrBnd(double val){ return;} void SetUprBnd(double val){ return;} double GetEstVal(void){ return m_EstVal;} double SetEstVal(double estVal){ m_EstVal = estVal; return 0.00;} void SetEstVal(double minObj, double minCon); void SetMinObj(double minObj){ m_MinObj = minObj;} UnchangeableString GetName(void){ return m_pName;} double GetTransformedVal(void){ return m_EstVal;} double ConvertOutVal(double val){ return val;} double ConvertInVal(double val){ return val;} void Enable(void){ m_bSet = true;} //threshold values (allow for implicit on/off of parameters) void SetThreshVal(double lwr, double upr, double off){ return;} const char * GetType(void) {return "special";} ConstraintABC * GetConstraint(void); private: StringType m_pName; StringType m_pType; StringType m_pLimit; StringType m_pConstraint; double m_MinObj; double m_EstVal; bool m_bSet; }; /* end class SpecialParam */ #endif /* PARAMETER_H */
true
51b6ee08f0ddd72acecc8d79e818731203bce2ce
C++
leoleil/shu_ju
/Project3/VspdCTOMySQL.h
GB18030
1,806
2.796875
3
[]
no_license
#pragma once #include <stdio.h> #include <string> #include "winsock2.h" #include "mysql.h" using namespace std; class VspdCToMySQL { public: // MYSQL mysql; /* 캯ϡ */ VspdCToMySQL(); ~VspdCToMySQL(); /* ҪĹܣ ʼݿ ݿ ַ ڲ host MYSQLIP port:ݿ˿ Dbݿ userݿû passwdݿû charsetϣʹõַ Msg:صϢϢ ڲ int 0ʾɹ1ʾʧ */ int ConnMySQL(char *host, char * port, char * Db, char * user, char* passwd, char * charset, char * Msg); /* ҪĹܣ ѯ ڲ SQLѯSQL Cnum:ѯ Msg:صϢϢ ڲ string ׼÷صݣ¼0x06,λ0x05 صijȣ 0ʾ޽ */ string SelectData(char * SQL, int Cnum, char * Msg); /* Ҫܣ ڲ SQLѯSQL Msg:صϢϢ ڲ int 0ʾɹ1ʾʧ */ int InsertData(char * SQL, char * Msg); /* Ҫܣ ޸ ڲ SQLѯSQL Msg:صϢϢ ڲ int 0ʾɹ1ʾʧ */ int UpdateData(char * SQL, char * Msg); /* Ҫܣ ɾ ڲ SQLѯSQL Msg:صϢϢ ڲ int 0ʾɹ1ʾʧ */ int DeleteData(char * SQL, char * Msg); /* Ҫܣ رݿ */ void CloseMySQLConn(); };
true
b5df3dffd31189f6203b7f58f492118dafb2e65a
C++
xfile6912/Baekjoon
/Stack, Queue, Deque, List/boj11866.cpp
UTF-8
668
3.015625
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include<iostream> #include<vector> #include<string> #include<algorithm> #include <queue> using namespace std; int main(void) { queue<int> q; int n, k; scanf("%d %d", &n, &k); int i; for (i = 1; i <= n; i++) { q.push(i); } int cnt = 1; printf("<"); while (!q.empty()) { int temp = q.front(); q.pop(); if (cnt != k)//만약에 k번째가 아니라면 다시 q에 넣어준다. { q.push(temp); cnt++; } else { if (q.empty())//마지막 숫자를 뺄 때는 ,를 출력하면 안되므로 printf("%d", temp); else printf("%d, ",temp); cnt = 1; } } printf(">"); }
true
41d6f4b1166c1647dc797db193a01c4384cff036
C++
mucrow/PlayStation1Vsts
/PluginsCommon/ByteInputStream.h
UTF-8
2,056
3.328125
3
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#pragma once #include "InputStream.h" #include <cstring> //------------------------------------------------------------------------------------------------------------------------------------------ // Provides a byte oriented input stream from a given chunk of memory. // The stream is merely a view/wrapper around the given memory chunk and does NOT own the memory. //------------------------------------------------------------------------------------------------------------------------------------------ class ByteInputStream final : public InputStream { public: inline ByteInputStream(const std::byte* const pData, const uint32_t size) noexcept : mpData(pData) , mSize(size) , mCurByteIdx(0) { } inline ByteInputStream(const ByteInputStream& other) noexcept = default; virtual void readBytes(void* const pDstBytes, const size_t numBytes) THROWS override { ensureBytesLeft(numBytes); std::memcpy(pDstBytes, mpData + mCurByteIdx, numBytes); mCurByteIdx += numBytes; } virtual void skipBytes(const size_t numBytes) THROWS override { ensureBytesLeft(numBytes); mCurByteIdx += numBytes; } virtual size_t tell() noexcept override { return mCurByteIdx; } virtual bool isAtEnd() noexcept override { return (mCurByteIdx >= mSize); } // Return the next value ahead (of the given type) but do not consume the input. // This is possible for this stream type because we have all of the bytes available to us at all times. template <class T> T peek() { ensureBytesLeft(sizeof(T)); T output; std::memcpy(&output, mpData + mCurByteIdx, sizeof(T)); return output; } private: inline void ensureBytesLeft(const size_t numBytes) THROWS { if ((numBytes > mSize) || (mCurByteIdx + numBytes > mSize)) { throw StreamException(); } } const std::byte* const mpData; const size_t mSize; size_t mCurByteIdx; };
true
fd16f69c752bb90843b4a140c970bdce8468b95e
C++
ketteske/neuron_halo
/neuralstuff/neuralstuff/Layer.h
UTF-8
1,247
2.671875
3
[]
no_license
#pragma once #include "Connection.h" #include "Perceptron.h" #include "Global_header.h" class Layer { vector <Connection*> Contacts; vector <Perceptron*> StimulatedPercetrons; double default_weight_value = 1; // Back propagate automaticly void backPropagate(); public: Layer(vector <Perceptron*> Perceptrons); // Store perceptrons in the layer TODO create getter vector <Perceptron*> Perceptrons; Layer * next; Layer * previous; // Propagete forward void forwardPropagation(); // Connect all perceptrons in the layer to the one in parameter void connectToLayer(vector <Perceptron*> aPerceptrons); // Connect to layers void connectLayerToLayer(Layer * prev, Layer * next); double sumActivation(Perceptron* Target); ///BACK PROPAGATION // Calculate output error void calculateError(Layer* aResults, vector<int> aExpectedR); // Init the backpropagation algorithm void startBackPropagationRecursive(vector <double>* aDesiredOutput); // Update weight of the layers void updateWeightsRecursive(); // Connect to perceptrons to each other void connectNeurons(Layer * L1); // Print out preceptron values void printOutPerceptronValues(); // void changePerceptronsValue(vector <double> *aNewValues); ~Layer(); };
true
a720b26a09963afd49bbfc6759544449aefc099a
C++
CaptainEven/ColmapMVSMy
/ColMapMVSMy/depth_map.h
GB18030
2,599
2.78125
3
[]
no_license
#ifndef COLMAP_SRC_MVS_DEPTH_MAP_H_ #define COLMAP_SRC_MVS_DEPTH_MAP_H_ #include <string> #include <vector> #include <algorithm> #include "mat.h" #include <opencv2/highgui.hpp> namespace colmap { namespace mvs { class DepthMap : public Mat<float> { public: DepthMap(); DepthMap(const float depth_min, const float depth_max); DepthMap(const size_t width, const size_t height, const float depth_min, const float depth_max); DepthMap(const Mat<float>& mat, const float depth_min, const float depth_max); inline float GetDepthMin() const; inline float GetDepthMax() const; inline float GetDepth(const int row, const int col) const { return data_.at(row * width_ + col); } void Rescale(const float factor); void Downsize(const size_t max_width, const size_t max_height); // BitmapopencvеMatʾ cv::Mat ToBitmap(const float min_percentile, const float max_percentile) const; cv::Mat ToBitmapGray(const float min_percentile, const float max_percentile); // DepthMapתΪOpencv Mat: Ĭfloat32 inline cv::Mat Depth2Mat() { cv::Mat mat(height_, width_, CV_32F); for (size_t y = 0; y < height_; ++y) { for (size_t x = 0; x < width_; ++x) { //if (data_.at(y * width_ + x) < 0.0f) // printf("[%d, %d] depth: %.3f\n", x, y, data_.at(y * width_ + x)); mat.at<float>(y, x) = data_.at(y * width_ + x); } } return mat; } // Opencv MatDepthmap void fillDepthWithMat(const cv::Mat& mat); void mat2depth(cv::Mat &mat); // Ϻalpha inline double CalculateAlpha(const double& eps, const double& tau, const double& omega_depth) { return 1.0 / (1.0 + exp(-eps * (omega_depth - tau))); } float depth_min_ = -1.0f; float depth_max_ = -1.0f; private: //float depth_min_ = -1.0f; //float depth_max_ = -1.0f; // ³ȷΧתͼʽ float last_depth_min = 0.0f; float last_depth_max = 0.0f; }; float base(const float val); inline float interPolate(const float val, const float y0, const float x0, const float y1, const float x1); //////////////////////////////////////////////////////////////////////////////// // Implementation //////////////////////////////////////////////////////////////////////////////// inline float DepthMap::GetDepthMin() const { return depth_min_; } inline float DepthMap::GetDepthMax() const { return depth_max_; } } // namespace mvs } // namespace colmap #endif // COLMAP_SRC_MVS_DEPTH_MAP_H_
true
8b6c4542b97a9f69649383300a2c7f596a33a1f7
C++
bseazeng/c-_base
/trie.cpp
UTF-8
1,197
2.859375
3
[]
no_license
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; char s[11]; int n,m; bool p; struct node { int count; node * next[26]; }*root; node * build() { node * k=new(node); k->count=0; memset(k->next,0,sizeof(k->next)); return k; } void insert() { node * r=root; char * word=s; while(*word) { int id=*word-'a'; if(r->next[id]==NULL) r->next[id]=build(); r=r->next[id]; r->count++; word++; } } int search() { node * r=root; char * word=s; while(*word) { int id=*word-'a'; r=r->next[id]; if(r==NULL) return 0; word++; } return r->count; } int main() { root=build(); scanf("%d",&n);//字典树中存在的单词个数 for(int i=1;i<=n;i++) { cin>>s; insert(); } scanf("%d",&m);//查询单词个数 for(int i=1;i<=m;i++) { cin>>s; if ( 0 == search()) { printf("%s is not in \n",s); //不在字典树中 } else { printf("%s is in\n",s);//在字典树中 } } }
true
943fcf1c6ef40f88e22d9e058100984a8f45623a
C++
JJungs-lee/problem-solving
/BOJ/10811_바구니 뒤집기.cpp
UTF-8
484
2.921875
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, m; cin >> n >> m; vector<int> v(n); for (int i = 0; i < n; ++i) v[i] = i + 1; for (int i = 0; i < m; ++i) { int start, end; cin >> start >> end; for (int j = 0; j <= (end - start) / 2; ++j) { swap(v[start + j - 1], v[end - j - 1]); } } for (int num : v) cout << num << ' '; return 0; }
true
a23c41d1b588228771fce447bdfdf4aeadcf7239
C++
choihomeboy/Bus_Scheduling_Project
/project/src/route.h
UTF-8
3,931
3.078125
3
[]
no_license
/** * @file route.h * * @Copyright 2019 3081 Staff, All rights reserved. */ #ifndef SRC_ROUTE_H_ #define SRC_ROUTE_H_ /******************************************************************************* * Includes ******************************************************************************/ #include <list> #include <iostream> #include <string> #include "src/passenger_generator.h" #include "src/stop.h" #include "src/data_structs.h" class Stop; class PassengerGenerator; /** * @brief The main class for the acitivity of the route. * */ class Route { public: /** * @brief Constructs a route with name, stops, distances, the number of stops, * and passenger generator * * @param[in] string holding an route name * @param[in] stops stops that consist of the route * @param[in] distances distances between the stops * @param[in] num_stops the number of stops in stops * @param[in] PassengerGenerator generator for passengers * */ Route(std::string name, Stop ** stops, double * distances, int num_stops, PassengerGenerator *); /** * @brief Copy the same route for easier construction of bus * * @return cloned route */ Route * Clone(); /** * @brief Used in simulator, update the private list stops_ * */ void Update(std::ostream& = (std::cout)); /** * @brief report important information related to the route to the ostream * */ void Report(std::ostream&); /** * @brief At the transit of route, distanceleft-=incoming_route first distance * @brief used in the bus */ void SetTransitDistance(); /** * @brief Change destination_stop_(approaching stop) to next stop when arrived * */ void NextStop(); /** * @brief Check if bus is at the last stop checking if distance_left_<=0 * * @return true when it is at the end of the stop of the route. */ bool IsAtEnd(); /** * @brief Find where to go, used in the bus to track the location of the bus * * @return Destination stop object */ Stop * GetDestinationStop(); /** * @brief When arrived at stop, bus uses for distance remaining to next stop * * @return Distance from current stop to next stop */ double GetNextStopDistance(); /** * @brief How far is to the end of the route * * @return Distance from current stop to the last stop */ double GetDistanceLeft(); /** * @brief Get name of the route * * @return string name of the route */ std::string GetName(); /** * @brief Get stops used to build the route * * @return List of stops */ std::list<Stop *> GetStops(); /** * @brief Update the routedata struct to keep up with the newest values for simulator * * */ void UpdateRouteData(); /** * @brief Get RouteData which keeps tracking the route variables * * @return RouteData struct */ RouteData GetRouteData(); private: /** * @brief Generates passengers on its route * @brief located in here to create more than once as time increases * */ PassengerGenerator * generator_; /** * @brief Stops in a route cannot be share with the other routes * */ std::list<Stop *> stops_; /** * @brief Distances between the stops for the bus to track how more to go * @brief length = num_stops_ - 1 */ std::list<double> distances_between_; std::string name_; /** * @brief Number of stops at the route used in initialization and report. * */ int num_stops_; /** * @brief Always starts at zero, used to track where the bus is * */ int destination_stop_index_; /** * @brief The object of the closest stop where the bus is approaching. * */ Stop * destination_stop_; /** * @brief How far left until the end, used to track where the bus is in route. * */ double distance_left_; // double trip_time_; // derived data - total distance travelled on route RouteData route_data_; }; #endif // SRC_ROUTE_H_
true
e512a84337b07856cbcf2a5b1432534e02a214e4
C++
drudox/AlgebraSparseMatrix
/SparseMatrix/CompressedStorage/CRS/CRSmatrix.H
UTF-8
12,054
2.734375
3
[]
no_license
# ifndef __CRS_MATRIX_H__ # define __CRS_MATRIX_H__ # define __DEBUG__ # define __TESTING__ # include "../CompressedMatrix.H" namespace mg { namespace numeric { namespace algebra { // foward declarations template <typename U> class CRSmatrix ; template <typename U> std::ostream& operator<<(std::ostream& os , const CRSmatrix<U>& m ); template <typename U> std::vector<U> operator*(const CRSmatrix<U>& , const std::vector<U>& x); template<typename U> CRSmatrix<U> operator*(const CRSmatrix<U>& m1, const CRSmatrix<U>& m2) ; /*------------------------------------------------------------ * * Class for Compressed Row Storage (sparse) Matrix * * @Marco Ghiani Nov 2017 : * v 1.01 testing * ------------------------------------------------------------*/ template <typename Type> class CRSmatrix : public CompressedMatrix<Type> { template <typename U> friend std::ostream& operator<<(std::ostream& os , const CRSmatrix<U>& m ); template <typename U> friend std::vector<U> operator*(const CRSmatrix<U>& , const std::vector<U>& x); template<typename U> friend CRSmatrix<U> operator*(const CRSmatrix<U>& m1, const CRSmatrix<U>& m2) ; public: constexpr CRSmatrix(std::initializer_list<std::initializer_list<Type>> row ) noexcept; constexpr CRSmatrix(std::size_t i, std::size_t j) noexcept ; constexpr CRSmatrix(const std::string& ); virtual ~CRSmatrix() = default ; virtual Type& operator()(const std::size_t , const std::size_t) noexcept override final; virtual const Type& operator()(const std::size_t , const std::size_t) const noexcept override final ; void constexpr print() const noexcept override final; auto constexpr printCRS() const noexcept; using CompressedMatrix<Type>::printCompressed; private: using SparseMatrix<Type>::aa_ ; using SparseMatrix<Type>::ia_ ; using SparseMatrix<Type>::ja_ ; using SparseMatrix<Type>::denseRows ; using SparseMatrix<Type>::denseCols ; using SparseMatrix<Type>::nnz ; using SparseMatrix<Type>::zero ; std::size_t constexpr findIndex(std::size_t row, std::size_t col) const noexcept override final ; Type constexpr findValue(const std::size_t , const std::size_t ) const noexcept override final ; void insertAt(const std::size_t row, const std::size_t col,const Type val) noexcept override final; }; //--------------------------------- Implementation template<typename T> inline constexpr CRSmatrix<T>::CRSmatrix(std::initializer_list<std::initializer_list<T>> row ) noexcept { this->denseRows = row.size(); this->denseCols =(*row.begin()).size() ; auto i=0, j=0, RowCount=0; ia_.resize(denseRows+1); ia_[0] = 0; for(auto & r : row) { j=0 ; RowCount=0 ; for(auto & c : r) { if( c != 0.0 ) { aa_.push_back(c); ja_.push_back(j); RowCount++; } j++; } i++; ia_[i] = ia_[i-1] + RowCount ; } nnz = aa_.size() ; #ifdef __TESTING__ printCompressed(); # endif } // // template <typename T> inline constexpr CRSmatrix<T>::CRSmatrix(std::size_t i, std::size_t j) noexcept { this->denseRows= i; this->denseCols= j; aa_.resize(denseRows); ja_.resize(denseRows); ia_.resize(denseRows+1); } // -- construct from file // template <typename T> constexpr CRSmatrix<T>::CRSmatrix(const std::string& filename ) { std::ifstream f( filename , std::ios::in ); if(!f) { std::string mess = "Error opening file " + filename + "\n Exception thrown in COOmatrix constructor" ; throw OpeningFileException(mess); } if( filename.find(".mtx") != std::string::npos ) // Coo format { std::string line; T elem = 0 ; getline(f,line); // jump out the header line line = " " ; auto i=0; auto i1=0 , j1=0 ; while(getline(f,line)) { std::istringstream ss(line); if(i==0) { ss >> denseRows ; ss >> denseCols ; ss >> nnz ; ia_.resize(denseRows + 1); ia_.at(0)=0; } else { ss >> i1 >> j1 >> elem ; for(auto i=(i1) ; i <= denseRows ; i++) ia_.at(i)++ ; ja_.insert(ja_.begin() + (ia_.at(i1)-1), j1-1 ); aa_.insert(aa_.begin() + (ia_.at(i1)-1), elem ); } i++ ; } nnz = aa_.size(); } else { std::string line; std::string tmp ; T elem = 0; auto RowCount=0 ; ia_.push_back(0) ; auto i=0 , j=0 , k = 0; while(getline(f,line)) { std::istringstream ss(line); j=0; RowCount=0; while (ss >> elem) { if(elem != 0) { aa_.push_back(elem); ja_.push_back(j); RowCount++; } j++; this->denseCols = j; } ia_.push_back(ia_.at(i)+RowCount); i++ ; } this->denseRows = i; nnz = aa_.size() ; } # ifdef __TESTING__ printCompressed(); # endif } // print out the CRS storage // template <typename T> inline auto constexpr CRSmatrix<T>::printCRS() const noexcept { std::cout << "aa_ : " ; for(auto &x : aa_) std::cout << x << ' ' ; std::cout << std::endl; std::cout << "ja_ : " ; for(auto &x : ja_) std::cout << x << ' ' ; std::cout << std::endl; std::cout << "ia_ : " ; for(auto &x : ia_) std::cout << x << ' ' ; std::cout << std::endl; } // print out the whole matrix // template<typename T> inline void constexpr CRSmatrix<T>::print() const noexcept { for(std::size_t i=1 ; i <= denseRows ; i++) { for(std::size_t j=1 ; j <= denseCols ; j++) std::cout << std::setw(8) << this->operator()(i,j) << ' ' ; std::cout << std::endl; } } //- - private utility function // template<typename T> inline std::size_t constexpr CRSmatrix<T>::findIndex(std::size_t row, std::size_t col) const noexcept { assert( row >= 0 && row < denseRows && col >= 0 && col < denseCols ); auto jit = std::find(ja_.begin()+ia_.at(row) , ja_.begin()+ia_.at(row+1),col ); return static_cast<std::size_t>(std::distance(ja_.begin(), jit) ); } template<typename T> T constexpr CRSmatrix<T>::findValue(const std::size_t row, const std::size_t col) const noexcept { assert( row > 0 && row <= denseRows && col > 0 && col <= denseCols ); const auto j = findIndex(row-1,col-1); if(j < ia_.at(row)) return aa_.at(j); else return zero ; } // // template <typename T> inline void CRSmatrix<T>::insertAt(const std::size_t row, const std::size_t col,const T val) noexcept { if(val != 0) { auto j = findIndex(row,col); if( j < ia_.at(row+1) ) { aa_.at(j) = val; // change non zero } else // remove non-zero { for(auto i=(row+1) ; i <= this->denseRows ; i++ ) ia_.at(i)++ ; ja_.insert(ja_.begin() + (ia_.at(row+1)-1) , col); aa_.insert(aa_.begin() + (ia_.at(row+1)-1) , val); } } } //-- template<typename T> inline const T& CRSmatrix<T>::operator()(const std::size_t row, const std::size_t col) const noexcept { assert( row > 0 && row <= denseRows && col > 0 && col <= denseCols ); const auto j = findIndex(row-1,col-1); if(j < ia_.at(row)) return aa_.at(j); else return zero ; } //-- template <typename T> inline T& CRSmatrix<T>::operator()(const std::size_t row, const std::size_t col) noexcept { assert( row > 0 && row <= denseRows && col > 0 && col <= denseCols ); const auto j = findIndex(row-1,col-1); if(j < ia_.at(row)) return aa_.at(j); else return zero ; } // ------ non member function template <typename T> std::ostream& operator<<(std::ostream& os , const CRSmatrix<T>& m ) { for(auto i=1 ; i <= m.size1() ; i++ ){ for(auto j=1 ; j <= m.size2() ; j++){ std::cout << std::setw(8) << m.findValue(i,j) << " " ; } std::cout << std::endl; } } // ----- perform product template <typename U> std::vector<U> operator*(const CRSmatrix<U>& m, const std::vector<U>& x) { if(m.size2() != x.size() ) { std::string to = "x" ; std::string mess = "Error occured in operator* attempt to perfor productor between op1: " + std::to_string(m.size1()) + to + std::to_string(m.size2()) + " and op2: " + std::to_string(x.size()); throw InvalidSizeException(mess.c_str()); } std::vector<U> y(m.size1()); for(auto i=0 ; i < m.size1() ; i++){ for(auto j= m.ia_.at(i) ; j < m.ia_.at(i+1) ; j++){ y.at(i) += m.aa_.at(j) * x.at(m.ja_.at(j)); } } return y; } //--- Perform CRS * CRS // template<typename T> CRSmatrix<T> operator*(const CRSmatrix<T>& m1, const CRSmatrix<T>& m2) { if( m1.size2() != m2.size1() ) { std::string to = "x" ; std::string mess = "Error occured in operator* attempt to perfor productor between op1: " + std::to_string(m1.size1()) + to + std::to_string(m1.size2()) + " and op2: " + std::to_string(m2.size1()) + to + std::to_string(m2.size2()) ; throw InvalidSizeException(mess.c_str()); } CRSmatrix<T> res(m1.size1(), m2.size2()); double sum ; for(std::size_t i=1 ; i <= res.size1() ; i++ ) { for(std::size_t j=1; j<= res.size2() ; j++ ) { sum = 0; for(std::size_t k=1; k<= m1.size2() ; k++ ) { sum += m1(i,k)*m2(k,j) ; } res.insertAt(i-1,j-1,sum); } } return res; } /* template<typename T> CRSmatrix<T> operator*(const CRSmatrix<T>& m1, const CRSmatrix<T>& m2) { if( m1.size2() != m2.size1() ) { throw std::runtime_error("Exception in dot product : Matrix dimension must agree !"); } std::vector<T> col ; CRSmatrix<T> res(m1.size1(), m2.size2()); //ret.a.clear(); col.resize(res.size2()); for(std::size_t j=0 ; j < res.size2() ; j++ ) // loop over columns { col.clear(); // for(std::size_t i=0; i< res.size1() ; i++ ) col.push_back(static_cast<T> (m2(i+1,j+1) ) ); // perform multiplication col = m1*col; for(std::size_t i=0; i< col.size() ; i++ ) { res.insertAt(i,j,col.at(i)); } } return res; } */ }//algebra }//numeric }// mg # endif
true
322880138b6871808ad193be546d65557148e617
C++
juliolugo96/lozi-map
/lozi.cpp
UTF-8
18,875
3.21875
3
[ "MIT" ]
permissive
/** * @file lozi.cpp * @name Mapas de Lozi * @author Julio Lugo * @mail jmanuellugo96@gmail.com * @date 16/05/2017 * @brief Globaly coupled Lozi map */ # include <iostream> # include <iomanip> # include <cmath> # include <fstream> # include <ctime> # include <cstdlib> # include <cstdio> # include <random> # include <vector> # include <thread> using namespace std; # define alpha 1.4 ///Alpha parameter (fixed) # define b 0.5 ///B fixed parameter ///How to use the program void usage() { cout << "Execute as follows: \n\n"; cout << "\t[./your_chosen_name.exe],\n\t[epsilon value]\n\t[beta value],\n\t[mu value],\n\t[population i size],\n\t[population j size],\n\t[Total iterations],\n\t[Threshold]" << endl; } ///f(x,y) function definition inline double function_xy(const double &x, const double &y) { return 1 - alpha * fabs(x) + y; } inline double function_x(const double &x) { return (1 - pow(b, (1 - x)*x))/(1 - sqrt(sqrt(b))); } ///x value function inline double x_function(const double &epsilon, const double &mu, const double &f, const double &h_i, const double &h_j) { return (1 - epsilon)*f + epsilon * h_j + mu * h_i; } ///y value function inline double y_function(const double &x, double &beta) { return beta * x; } ///Routine for initial conditions setting void set_initial_conditions(double **x_axis, double **y_axis, double **f_var, const int * num_nodes, char &s) { random_device rd; //Will be used to obtain a seed for the random number engine mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() if(s != '4') { uniform_real_distribution<> dis(-1, 1); for(int i = 0; i < 2; i++) for(int j = 0; j < num_nodes[i]; j++) { x_axis[i][j] = dis(gen); y_axis[i][j] = dis(gen); } } else { uniform_real_distribution<> dis(0, 1); for(int i = 0; i < 2; i++) for(int j = 0; j < num_nodes[i]; j++) { x_axis[i][j] = dis(gen); y_axis[i][j] = dis(gen); } } } /// Copy values from x_axis to m_axis, it is used in threshold function inline void copy_values(double **x_axis, double **m_axis, const int *num_nodes) { for (int i = 0; i < 2; i++) for(int j = 0; j < num_nodes[i]; j++) m_axis[i][j] = x_axis[i][j]; } ///Set min value allows to sort all pops void set_min_value(double **x_axis, double **m_axis, const int *num_nodes) { int row = 0, col = 0; for(int i = 0; i < 2; i++) for (int j = 0; j < num_nodes[i]; j++) { double min = 2.0; for (int k = 0; k < 2; ++k) for(int l = 0; l < num_nodes[k]; l++) if(m_axis[k][l] < min) { min = m_axis[k][l]; row = k; col = l; } m_axis[row][col] = 2.0; x_axis[i][j] = min; } } void check_clusters(double **x_axis, const int *num_nodes) { vector < tuple<double, int, int> > values[2]; tuple<double, int, int> aux; pair <double, int> special_a(0,1), special_b(0,0); bool found = false; for(int i = 0; i < 2; i++) for (int j = 0; j < num_nodes[i]; j++) { found = false; for(auto &p : values[i]) if(x_axis[i][j] == get<0>(p)) { get<1>(p)++; found = true; break; } if(not found) values[i].push_back(make_tuple(x_axis[i][j], 1, j)); } /* for(int i = 0; i < 2; i++) { cout << "Pop " << i << endl; for(auto &p : values[i]) { cout << get<0>(p) << " cant: " << get<1>(p) << " pos: " << get<2>(p) << endl; } cout << "\n"; }*/ if(values[0].size() == 1 and values[1].size() == 1) return; found = false; if(fabs(get<0>(values[0].back()) - get<0>(values[1].front()) < 0.05)) { // cout << "Condición especial!" << endl; for(int j = num_nodes[0] - 1; j > 0; j--) { double result = fabs(x_axis[0][j] - x_axis[0][j - 1]); double min = 0.05; if(result < min) { // cout << x_axis[0][num_nodes[0] - 1] << " " << x_axis[0][j-1] << endl; special_a.second++; } else { special_a.first = x_axis[0][j - 1]; break; } } // cout << "\n\n"; for(int j = 0; j < num_nodes[1] - 1; j++) { double result = fabs(x_axis[1][j] - x_axis[1][j + 1]); double min = 0.05; if(result < min) { // cout << "diff: " << result << endl; // cout << "" << x_axis[0][j] << " " << x_axis[1][j + 1] << endl; special_b.second++; } else { special_b.first = x_axis[1][j + 1]; break; } } // cout << "pop a: " << special_a.second << " pop b: " << special_b.second << endl; if(special_a.second > special_b.second) { if(get<1>(values[1][1]) > 1) for(int j = 0; j <= special_b.second; j++) x_axis[1][j] = get<0>(values[1][1]); else for(int j = 0; j <= special_b.second; j++) { random_device rd; //Will be used to obtain a seed for the random number engine mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() uniform_real_distribution<> dis(special_b.first - 0.0001, special_b.first + 0.0001); x_axis[1][j] = dis(gen); } } else { if(get<1>(values[0][values[0].size()-1]) > 1) for(int j = num_nodes[0] - 1; j > (num_nodes[0] - 1 - special_a.second); j--) x_axis[0][j] = get<0>(values[0][values[0].size() - 2]); else for(int j = num_nodes[0] - 1; j > (num_nodes[0] - 1 - special_a.second); j--) { random_device rd; //Will be used to obtain a seed for the random number engine mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() uniform_real_distribution<> dis(special_a.first - 0.0001, special_a.first + 0.0001); x_axis[0][j] = dis(gen); } } } values[0].clear(); values[1].clear(); for(int i = 0; i < 2; i++) for (int j = 0; j < num_nodes[i]; j++) { found = false; for(auto &p : values[i]) if(x_axis[i][j] == get<0>(p)) { get<1>(p)++; found = true; break; } if(not found) values[i].push_back(make_tuple(x_axis[i][j], 1, j)); } /* for(int i = 0; i < 2; i++) { cout << "AFTER OPERATION " << i << endl; for(auto &p : values[i]) { cout << get<0>(p) << " cant: " << get<1>(p) << " pos: " << get<2>(p) << endl; } cout << "\n"; } */ } ///Threshold function: it allows to sort the population void threshold_function(double **x_axis, double **m_axis, const int *num_nodes) { copy_values(x_axis, m_axis, num_nodes); set_min_value(x_axis, m_axis, num_nodes); check_clusters(x_axis, num_nodes); } ///Print all both populations in one file inline void plot_print(int t, ofstream &out, double **x_axis, const int *num_nodes) { for(int i = 0; i <num_nodes[0]; i++) out << fixed << setprecision(5) << x_axis[0][i] << "\t"; for(int i = 0; i < num_nodes[1]; i++) out << fixed << setprecision(5) << x_axis[1][i] << "\t"; out << "\n"; } inline int theta(double result) { if(result < 0) return 0; else return 1; } pair < double, double > p_function(double **x_axis, const int * num_nodes) { double min_delta = 0.000005, distance = 0, productory = 1, summatory = 0; pair <double, double> ret_val; for (int i = 0; i < 2; ++i) { for (int j = 0; j < num_nodes[i]; ++j) { productory = 1; for(int k = 0; k < num_nodes[i]; k++) { if(j == k) continue; distance = fabs(x_axis[i][j] - x_axis[i][k]); productory *= theta(distance - min_delta); } summatory += productory; } if(i == 0) ret_val.first = 1 - summatory/num_nodes[i]; else ret_val.second = 1 - summatory/num_nodes[i]; summatory = 0; } return ret_val; } ///Simulation main module. It returns a tuple which contains delta value and sigma from pop i and pop j. tuple <double, double *> simulate(double &epsilon, double &beta, double &mu, int &pop_i, int &pop_j, const unsigned int &total_it, unsigned int &threshold, char &s) { const int num_nodes[2] = {pop_i, pop_j}; ///Vector used to define population sizes const unsigned int tau = total_it - 1000; if(epsilon == 0.0) epsilon = 0.05; ofstream out1("pop.dat"); ///Archivo final double N = num_nodes[0] + num_nodes[1]; /// N = Ni + Nij double ret_val_delta = 0, ret_val_sigma[2] = {0}, **y_axis = new double*[2], **x_axis = new double*[2],** f_var = new double*[2], **m_axis = new double*[2]; for(int i = 0; i < 2; i++) { x_axis[i] = new double[num_nodes[i]]; y_axis[i] = new double[num_nodes[i]]; m_axis[i] = new double[num_nodes[i]]; f_var[i] = new double[num_nodes[i]]; } set_initial_conditions(x_axis, y_axis, f_var, num_nodes, s); for(unsigned int t = 0; t < total_it; t++) ///Transient { double h[2] = {0}; ///For each t, medium field is initialized for(int j = 0; j < 2; j++) { for(int k = 0; k < num_nodes[j]; k++) { if(s == '4') f_var[j][k] = function_x(x_axis[j][k]); else f_var[j][k] = function_xy(x_axis[j][k], y_axis[j][k]); h[j] += f_var[j][k]; y_axis[j][k] = y_function(x_axis[j][k], beta); } h[j] /= (N + 0.0); ///Get medium field of time t } ///Set X values for(int j = 0, l = 1; j < 2; j++, l--) for(int k = 0; k < num_nodes[j]; k++) x_axis[j][k] = x_function(epsilon, mu, f_var[j][k], h[j], h[l]); if(t > threshold and t < threshold + 2) threshold_function(x_axis, m_axis, num_nodes); if(t > tau) ///If tau iteration is reached, then start printing { if(s != '2') ///Condition if you're diagramming or plotting plot_print(t + 1, out1, x_axis, num_nodes); ///Sigma and delta calculations double x_mean[2] = {0}, delta = 0, sigma[2] = {0}; // cout << "Tiempo: " << t << endl; for(int j = 0; j < 2; j++) { for(int k = 0; k < num_nodes[j]; k++) { // cout << setprecision(5) << x_axis[j][k] << " "; x_mean[j] += x_axis[j][k]; } // cout << "\n\n"; x_mean[j] /= num_nodes[j]; } // cout << "Valor medio de Xi: " << setprecision(5) << x_mean[0] << endl; // cout << "Valor medio de Xj: " << setprecision(5) << x_mean[1] << endl; for(int j = 0 ; j < 2; j++) { for(int k = 0; k < num_nodes[j]; k++) sigma[j] += (x_mean[j] - x_axis[j][k])*(x_mean[j] - x_axis[j][k]); sigma[j] /= num_nodes[j]; sigma[j] = sqrt(sigma[j]); ret_val_sigma[j] += sigma[j]; } // cout << "Sigma: " << setprecision(5) << sigma[0] << endl; // cout << "Sigma: " << setprecision(5) << sigma[1] << endl; delta = fabs(x_mean[0] - x_mean[1]); ret_val_delta += delta; } } ret_val_delta /= (total_it - tau); if(ret_val_delta < 0.0001) ret_val_delta = 0; for(int j = 0; j < 2; j++) { ret_val_sigma[j] /= (total_it - tau); if(ret_val_sigma[j] < 0.025) ret_val_sigma[j] = 0; } if(s == '3') { auto ret_val_p = p_function(x_axis, num_nodes); ret_val_sigma[0] = ret_val_p.first; ret_val_sigma[1] = ret_val_p.second; } out1.close(); for(int i = 0; i < 2; i++) { delete[] x_axis[i]; delete[] y_axis[i]; delete[] m_axis[i]; delete[] f_var[i]; } return make_tuple(ret_val_delta, ret_val_sigma); } ///Initial menu displayed inline char menu() { char ret_val; system("clear"); cout << "\t\tGLOBALLY COUPLED LOZI MAP" << endl; cout << "\t\t-------------------------\n\n" << endl; cout << "\tPlease choose an option.\n\n" << endl; cout << "\t1 .- Plot with delta and sigma (i, j)" << endl; cout << "\t2 .- Get phase diagram at range [mu: 0] [beta: 0.4]" << endl; cout << "\t3 .- Plot with delta and p (i, j)" << endl; cout << "\t4 .- Plot with new equation (using sigma (i, j) )\n\n" << endl; cout << "PRESS CTRL + C to finish the program" << endl; cout << "\n\nYour selection: "; cin >> ret_val; return ret_val; } void plot_phase_diagram(double &epsilon, double &beta, double &mu, int &pop_i, int &pop_j, const unsigned int &total_it, unsigned int &threshold, int &rows, int &cols) { ofstream m("plot.dat"), d("coord.dat"); vector <tuple <double, double*> > data; ///Here will be saved current delta and sigma values char s = 'n'; double ep_prop = (0.4)/(rows - 1 + 0.0); double beta_prop = (0.8)/(cols - 1 + 0.0); double new_mu = 0, new_beta = 0, act_ep = 0; cout << "\n\n\tPaso de mu: " << ep_prop << "\tPaso de beta: " << beta_prop << endl; for(int i = 0; new_mu >= 0.0 and i < rows; i++) { new_mu = mu - i*ep_prop; act_ep = mu - i*ep_prop; if(new_mu < 0.05) { new_mu = 0.05; } if(new_mu < 0.0) break; for(int j = 0; new_beta <= 0.40 and j < cols; j++) { new_beta = beta + j * beta_prop; double delta = 0, sigma_i = 0, sigma_j = 0; vector < tuple<double, double*> > aux; if(fabs(new_beta) < 0.000001) new_beta = 0.0; if(new_beta > 0.40) break; cout << "\t\t\tMu: " << act_ep << "\tBeta: " << new_beta << endl; cout << "\t\t--------------------------------------------------" << endl; for(int i = 0; i < 50; i++) { aux.push_back(simulate(epsilon, new_beta, new_mu, pop_i, pop_j, total_it, threshold, s)); delta += get<0>(aux[i]); sigma_i += get<1>(aux[i])[0]; sigma_j += get<1>(aux[i])[1]; /* cout << "Simu Nº: " << setw(4) << left << i + 1; cout << "Delta: "<< setw(12) << left << fixed << setprecision(5) << get<0>(aux[i]); cout << "Sigma i: " << setw(12) << left << fixed << setprecision(5) << get<1>(aux[i])[0]; cout << "Sigma j: "<< setw(12) << left << fixed << setprecision(5) << get<1>(aux[i])[1] << endl;*/ } delta /= 50.0; sigma_i /= 50.0; sigma_j /= 50.0; cout << "--------------------------------------------------" << endl; cout << "\n\nCoordinate: (" << new_beta << ", " << act_ep << "):\n"<< "\t\tDelta: "<< delta << "\tMean Sigma i: " << sigma_i << "\tMean Sigma j: " << sigma_j << "\n\nFINAL MATRIX VALUE: "; d << new_beta << "\t" << act_ep << "\t"; if(delta == 0 and sigma_i == 0 and sigma_j == 0) { m << "0\t"; d << "0" << endl; cout << "0\n\n" << endl; } else if(delta != 0 and sigma_i != 0 and sigma_j != 0) { m << "1\t"; d << "1" << endl; cout << "1\n\n" << endl; } else if(delta != 0 and (sigma_i == 0 and sigma_j == 0)) { m << "2\t"; d << "2" << endl; cout << "2\n\n" << endl; } else { m << "3\t"; d << "3" << endl; cout << "3\n\n" << endl; } } m << "\n"; new_beta = beta; } } int main(int argc, char *argv[]) { if(argc != 8) { usage(); return 0; } double epsilon = atof(argv[1]), beta = atof(argv[2]), mu = atof(argv[3]); ///Lectura del parámetro de acoplamiento int pop_i = atoi(argv[4]), pop_j = atoi(argv[5]); const unsigned int total_it = atoi(argv[6]); unsigned int threshold = atoi(argv[7]); if(epsilon < 0 or epsilon > 1) { cerr << "Invalid value for epsilon" << endl; return 0; } if(fabs(beta) > 0.40) { cerr << "Invalid value for beta" << endl; return 0; } if(fabs(mu) > 0.40) { cerr << "Invalid value for mu" << endl; return 0; } if(pop_j <= 0 or pop_i <= 0) { cerr << "One population has an invalid size" << endl; return 0; } if(threshold > total_it) { cerr << "Threshold must be lower than total iterations" << endl; return 0; } char s = menu(); tuple <double, double*> p; int rows = 0, cols = 0; switch(s) { case '1': p = simulate(epsilon, beta, mu, pop_i, pop_j, total_it, threshold, s); cout << "Delta: " << get<0>(p) << "\t\tSigma i: " << get<1>(p)[0] << "\tSigma j: " << get<1>(p)[1] << endl; system("./script.sh"); break; case '2': system("clear"); cout << "\n\n\n\t\tIntroduzca cantidad de filas de su matriz: "; cin >> rows; cout << "\t\tIntroduzca cantidad de columnas de su matriz: "; cin >> cols; cin.ignore(); plot_phase_diagram(epsilon, beta, mu, pop_i, pop_j, total_it, threshold, rows, cols); break; case '3': p = simulate(epsilon, beta, mu, pop_i, pop_j, total_it, threshold, s); cout << "Delta: " << get<0>(p) << "\t\tP i: " << get<1>(p)[0] << "\tP j: " << get<1>(p)[1] << endl; system("./script.sh"); break; case '4': p = simulate(epsilon, beta, mu, pop_i, pop_j, total_it, threshold, s); cout << "Delta: " << get<0>(p) << "\t\tSigma i: " << get<1>(p)[0] << "\tSigma j: " << get<1>(p)[1] << endl; system("./script.sh"); break; default: break; } return 0; }
true
9554a5d0db0a7251473fbe940f87ad96612f3228
C++
PitEG/todotoday
/src/cpp/Goal.cpp
UTF-8
488
2.828125
3
[ "MIT" ]
permissive
#include "Goal.hpp" // // GETTER/SETTERS // unsigned int Goal::NumTasks() { return tasks->Size(); } std::vector<Task*> Goal::Tasks() { return tasks->Tasks(); } bool Goal::Completed() { return tasks->Completed(); } // // CONSTRUCTORS // Goal::Goal(std::string name) : name(name){ } Goal::Goal(std::string name, std::vector<Task*> tasks) : name(name) { this->tasks = new TaskList(tasks); } Goal::Goal(std::string name, TaskList* tasks) : name(name), tasks(tasks) { }
true
b800003f866594b78ba1f352ff2f93251b4d041c
C++
kmisrano/butiran
/zpp/mrvp/ball.h
UTF-8
661
2.796875
3
[ "MIT" ]
permissive
/* ball.h Sparisoma Viridi 20121124 Simple ball struct Version: 20090520 The first version of ball class is written 20111022 ball is changed from a class to a struct 20120310 Member s for spin is added 20121124 Information of struct member is added */ #ifndef ball_h #define ball_h #ifndef vect3_h #include "vect3.h" #endif struct ball { public: // n-th derivative of linear position vect3 r0, r1, r2, r3, r4, r5; // n-th derivative of angular position vect3 t0, t1, t2, t3, t4, t5; // Mass and diameter double m, d; // RGB color \in [0, 1] for each component vect3 c; // Charge and spin double q, s; // Binding parameter double b; }; #endif
true
600de2f2edf0bbf1c54f2bdd97af652faa692748
C++
WhiZTiM/coliru
/Archive/01050ffcfeb0af113d3bde8adbc75c3f-653c64665bcb020f1c708d5e11734e4a/main.cpp
UTF-8
515
2.84375
3
[]
no_license
#include<iostream> #include<map> #include<vector> #include<string> #include<algorithm> #include<iterator> #include<utility> #include <stdio.h> template<class A, class B, B(A) Call> F<B> fmap(Call call, F<A> fa){ F<B> fb; for(auto&& a : fa){ fb.push_back(call(a)) } return fb; } struct A { }; struct callable { void operator()(A a) { std::cout << "Callable" << std::endl; } }; int main (int argc, char* argv[]) { callable cl; F<A,callable, callable>(cl, return 0; }
true
722c26bfd4cc40a87dda0978866f2c8b59c0d12b
C++
jpennington222/KU_EECS_Labs
/EECS_560/Lab03/Node.cpp
UTF-8
623
3.65625
4
[]
no_license
/* * @Author: Joseph Pennington * @File Name: Node.cpp * @Assignment: EECS 560 Lab 03 * @Brief: This program is the cpp for the Node class. It contains the constructor, getValue, getNext, setValue, and setNext functions to make a Node. */ template<typename T> Node<T>::Node(T& value) { m_value = value; m_next = nullptr; } template<typename T> T Node<T>::getValue()const { return(m_value); } template<typename T> Node<T>* Node<T>::getNext()const { return(m_next); } template<typename T> void Node<T>::setValue(T& value) { m_value = value; } template<typename T> void Node<T>::setNext(Node<T>* next) { m_next = next; }
true
e74f59bfbbf02dd2398ae94eadbb9d75bafdf746
C++
Aphodomus/Algoritmos-e-Estruturas-Dados-I
/Atividades/EstudoDirigido13/Contato.hpp
UTF-8
6,507
3.34375
3
[]
no_license
#ifndef _CONTATO_H_ #define _CONTATO_H_ #include <iostream> using std::cin ; // para entrada using std::cout; // para saida using std::endl; // para mudar de linha #include <iomanip> using std::setw; // para definir espacamento #include <string> using std::string; // para cadeia de caracteres #include <fstream> using std::ofstream; // para gravar arquivo using std::ifstream; // para ler arquivo void pause(std::string text) { std::string dummy; std::cin.clear ( ); std::cout << std::endl << text; std::cin.ignore( ); std::getline(std::cin, dummy); std::cout << std::endl << std::endl; } #include "Erro.hpp" class Contato : public Erro { private: string nome; string fone; string fone2; string adressHome; string adressProfessional; string telefone; public: //Destrutor ~Contato() { } //Construtor padrao Contato() { setErro(0); nome = ""; fone = ""; } //Construto alternativo Contato (std::string nomeInicial, std::string foneInicial) { setErro(0); setNome(nomeInicial);//nome = nomeInicial; setFone(foneInicial);//fone = foneInicial; } //Construtor alternativo baseado em copia Contato (Contato const &another) { setErro(0); setNome(another.nome); setFone(another.fone); } //Construtor apenas com nome Contato (std::string nomeInicial) { setErro(0); setNome(nomeInicial); } Contato (std::string nomeInicial, std::string foneInicial, std::string foneAlternativo) { setErro(0); setNome(nomeInicial);//nome = nomeInicial; setFone(foneInicial);//fone = foneInicial; setFone2(foneAlternativo); } //Construtor de telefone Telefone (std::string telefone) { setFone(telefone); } //Atribuir nome void setNome(std::string nome) { if (nome.empty()) { setErro(1); } else{ this->nome = nome; } } //Atribuir telefone void setFone(std::string fone) { if (fone.empty()) { setErro(2); } else { this->fone = fone; } } //Atribuir telefone alternativo void setFone2(std::string fone2) { if (fone2.empty()) { setErro(2); } else { this->fone2 = fone2; } } //Atribuir endereco residencial void setAdressHome(std::string adressHome) { if (adressHome.empty()) { setErro(2); } else { this->adressHome = adressHome; } } //Atribuir endereco profissional void setAdressProfessional(std::string adressProfessional) { if (adressProfessional.empty()) { setErro(2); } else { this->adressProfessional = adressProfessional; } } //Obter nome std::string getNome () { return(this->nome); } //Obter fone std::string getFone () { return(this->fone); } //Obter fone alternativo std::string getFone2 () { return(this->fone2); } //Obter dados de uma pessoa std::string toString() { return("{" + getNome() + ", " + getFone() + "}"); } //Obter endereco residencial std::string getAdressHome() { return(this->adressHome); } //Obter endereco profissional std::string getAdressProfessional() { return(this->adressProfessional); } //Indica a existencia de erro bool hasErro() { return(getErro() != 0); } //Ler do teclado e atribuir um valor ao nome void readNome(std::string nome) { if (nome.empty()) { setErro(2); } else { this->nome = nome; } } //Ler do teclado e atribuir um valor ao fone void readFone(std::string fone) { if (fone.empty()) { setErro(2); } else { this->fone = fone; } } //Testar cada valor para ver se e um numero ou simbolo "-" bool numberAndSymbol(char digito) { bool result = false; if (('0' <= digito && digito <= '9') || digito == '-') { result = true; } return(result); } //Verificar se o fone e valido bool isFoneValid(std::string nome) { bool result = true; for (int x = 0; x < nome.length(); x = x + 1) { if(! numberAndSymbol(nome[x])) { result = false; break; } } return(result); } //Ler nome de um arquivo void readFromFile(chars fileName) { ifstream afile; string nome; string fone; afile.open(fileName); afile >> nome; afile >> fone; this->nome = nome; this->fone = fone; afile.close(); } //Gravar dados de uma pessoa em um arquivo void writeToFile(chars fileName) { ofstream afile; afile.open(fileName); afile << 2 << endl; afile << this->nome << endl; afile << this->fone << endl; afile.close(); } //Verificar quantos telefones tem em cada objeto int telefones() { if (this->fone.empty() == 0 && this->fone2.empty() == 0) { return (2); } else { if (this->fone.empty() == 0 || this->fone2.empty() == 0) { return(1); } else { return(0); } } } //Remover o segundo telefone void removeFone2() { if (this->fone2.empty() != 1) { this->fone2 = ""; } else { cout << "Erro: Nao existe um segundo numero." << endl; } } }; using ref_Contato = Contato*; #endif
true
a23b59b68541ab64dac7b7baa3e0c5eb9b971939
C++
xocoatzin/algorithms
/src/string-matching/string-matching.cpp
UTF-8
4,500
3.21875
3
[]
no_license
#include <iostream> #include <string> #include "../common/string.h" #include "string-matching-tools.h" using namespace std; using namespace string_matching; int main(int argc, char *argv[]) { if (argc < 2) { cerr << "Error! you need to include the input file in the command line" << endl; tools::wait(); return -1; } tools::Reader reader(argv[1]); string line; size_t line_id; unsigned int offset = 0; while (reader.getLine(line, line_id)) { vector<string> tokens = tools::split(line, "->"); if (tokens.size() < 2) { cout << " Skipping line " << line_id << endl; continue; } string str = tokens[1], pattern = tokens[0]; cout << "\n\nNaive matching:\n===================================================\n\n"; { for (unsigned int i = 0; /* WRITE ME! */; i++) //[hint:str.length() for string length] { print(str, pattern, offset); // 2) For each character the pattern. Loop. for (;;/* WRITE ME! */) { // 3) Compare string to pattern [hint: str.at(j + offset) == pattern.at(j)] } // 4) Have you found the end of the pattern? if (true/* WRITE ME! */) cout << " IS A MATCH!" << endl << endl; else cout << endl << endl; tools::wait(); // wait for user to press [enter] } } cout << "\n\nKnuth-Morris-Pratt:\n===================================================\n\n"; { KMPPrefixTable table(pattern); // Note: pre-fix table is automatically created unsigned int n = str.length(); unsigned int m = pattern.length(); unsigned int i = 0; /* * Note: In c++, the indices start in 0. * The comments on this document are thus different from the slides */ // for j = 0 upto n step 1 do (Note j = 0) for (;;/* WRITE ME! */) { // while i > 0 and P[i] != T[j] do. while (false/* WRITE ME! */) { // Skip using prex table i = table[i]; } // if P[i] = T[j] then (Note P[i]) if (true/* WRITE ME! */) { // Next character matches } // if you reach end of pattern [hint: i == m] if (true/* WRITE ME! */) { // OUTPUT(j - m + 1) (Note + 1) // Look for next match } } } cout << "\n\nBoyer-Moore-Horspool:\n===================================================\n\n"; { BMHTable table(pattern); unsigned int n = str.length(); // Length of the string unsigned int m = pattern.length(); // Length of the pattern unsigned int offset = 0; // Offset (position of the pattern) unsigned int i = m - 1; // Character to test in pattern unsigned int j = i + offset; // Character to test in string // 1) Repeat until we reach the end of the string [hint: offset + m < n] while (false/* WRITE ME! */) { // 2) Compare character {i} to character {j} if (true/* WRITE ME! */) { // 3A) The character matches, test next one? if (i < 0) { // We haven't reached the first character } else { // We reached the first character, all matched, we found it!! // exit } } else { // 3B) The character didn't match, increase the offset // Hint: // Use the table to know how much to increment the offset: unsigned char increment = table.at(str.at(j)); // 4) Reset indices i = m - 1; j = i + offset; } } } } // while cout << "End" << endl; tools::wait(); return 0; }
true
ad1d764b2352c0bbb67d88a94ba1bdab9b74fd09
C++
kayru/librush
/Rush/GfxBitmapFont.h
UTF-8
2,536
2.640625
3
[ "MIT" ]
permissive
#pragma once #include "Rush.h" #include "GfxCommon.h" #include "GfxPrimitiveBatch.h" #include "UtilArray.h" namespace Rush { class DataStream; // Class for working with AngelCode BMFont files. // More details here: http://www.angelcode.com/products/bmfont/ // Current simple implementation is only suitable for ASCI single-byte encoding. class BitmapFontDesc { public: enum { MaxFontPages = 16, InvalidPage = 0xFF }; struct CharData { u16 x, y, width, height; s16 offsetX, offsetY, advanceX; u8 page, chan; }; struct PageData { char filename[128]; }; BitmapFontDesc(); bool read(DataStream& stream); CharData m_chars[256]; PageData m_pages[MaxFontPages]; u32 m_pageCount; u32 m_size; }; struct BitmapFontData { BitmapFontDesc font; DynamicArray<u32> pixels; u32 width = 0; u32 height = 0; }; class BitmapFontRenderer { public: BitmapFontRenderer(const BitmapFontData& data); BitmapFontRenderer(const void* headerData, size_t headerSize, const void* pixelsData, size_t pixelsSize, u32 width, u32 height, GfxFormat format); ~BitmapFontRenderer(); // returns position after the last drawn character Vec2 draw(PrimitiveBatch* batch, const Vec2& pos, const char* str, ColorRGBA8 col = ColorRGBA8::White(), bool flush = true); // returns the width and height of the text block in pixels Vec2 measure(const char* str); static BitmapFontData createEmbeddedFont(bool shadow = true, u32 padX = 0, u32 padY = 0); void setScale(Vec2 scale) { m_scale = scale; }; void setScale(float scale) { m_scale = Vec2(scale); }; const BitmapFontDesc& getFontDesc() const { return m_fontDesc; } const DynamicArray<GfxOwn<GfxTexture>>& getTextures() const { return m_textures; } const DynamicArray<GfxTextureDesc>& getTextureDescs() const { return m_textureDesc; } const TexturedQuad2D* getCharQuads() const { return m_chars; } Vec2 GetScale() const { return m_scale; } private: void createSprites(); private: BitmapFontDesc m_fontDesc; DynamicArray<GfxOwn<GfxTexture>> m_textures; DynamicArray<GfxTextureDesc> m_textureDesc; TexturedQuad2D m_chars[256]; Vec2 m_scale; }; // Draw characters into a 32bpp RGBA bitmap. // Only code-page 437 characters ' ' (32) to '~' (126) are supported. // Tabs, line breaks, etc.are not handled. An empty space will be emitted for unsupported characters. void EmbeddedFont_Blit6x8(u32* output, u32 width, u32 Color, const char* str); }
true
6c13eaffafdc2cdf895791c3cdaf801c6490335d
C++
ungidrid/Math
/MathC++/MathC++/Libraries/cpps/LinearEquation.inl
UTF-8
2,418
3.4375
3
[]
no_license
//CONSTRUCTORS template<class T> LinearEquation<T>::LinearEquation(size_t length) { valArray.resize(length); } template<class T> LinearEquation<T>::LinearEquation(const vector<T>& vect) :valArray{ vect } { } template<class T> LinearEquation<T>::LinearEquation(const initializer_list<T>& list) : valArray{ list } { } //METHODS template<class T> size_t LinearEquation<T>::size() const{ return valArray.size(); } template<class T> ostream& LinearEquation<T>::print(ostream& out) const { for (const auto &elem : valArray) out << elem << " "; return out; } //OPERATORS template<class T> LinearEquation<T> operator+(const LinearEquation<T>& left, const LinearEquation<T>& right) { if (left.size() != right.size()) throw runtime_error ("Linear combinations with different lengths could not be added!"); LinearEquation<T> eq(left.size()); for (size_t i = 0; i < left.size(); ++i) eq[i] = left[i] + right[i]; return eq; } template<class T> LinearEquation<T> operator-(const LinearEquation<T>& left, const LinearEquation<T>& right) { return left + (-right); } template<class T> T& LinearEquation<T>::operator[](size_t index) { if (!(index >= 0 && index < size())) throw runtime_error ("Index out of range!"); return valArray[index]; } template<class T> const T& LinearEquation<T>::operator[](size_t index) const { if (!(index >= 0 && index < size())) throw runtime_error ("Index out of range!"); return valArray[index]; } template<class T> LinearEquation<T> LinearEquation<T>::operator+() const { return *this; } template<class T> LinearEquation<T> LinearEquation<T>::operator-() const { vector<T> temp{ valArray }; for (auto& elem : temp) elem = -elem; return temp; } template<class S, class F> LinearEquation<F> operator*(const S& left, const LinearEquation<F>& right) { LinearEquation<F> eq(right.size()); for (size_t i = 0; i < right.size(); ++i) eq[i] = left * right[i]; return eq; } template<class S, class F> LinearEquation<F> operator*(const LinearEquation<F>& left, const S& right) { return right * left; } template<class T> bool operator==(const LinearEquation<T>& left, const LinearEquation<T>& right) { return left.valArray == right.valArray; } template<class T> bool operator!=(const LinearEquation<T>& left, const LinearEquation<T>& right) { return !(left == right); } template<class T> ostream& operator<<(ostream& out, const LinearEquation<T>& le) { return le.print(out); }
true
85db33e5e5f52c58aa76273459d0430e9cf3ba2c
C++
abuild-org/abuild
/src/WorkerPool.hh
UTF-8
8,522
3.03125
3
[ "Apache-2.0", "Artistic-2.0", "LicenseRef-scancode-unknown-license-reference", "Artistic-1.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
#ifndef __WORKERPOOL_HH__ #define __WORKERPOOL_HH__ // This object manages a pool of worker threads for processing a // number of objects in parallel. The WorkerPool is initialized with // the number of workers that should be created and a method to be // called for each item that processes the item and returns a status // code. // The intended mode of operation is that the user of the pool has a // loop that calls wait(). The wait() method blocks until the pool // has been requested to stop, a result is ready, or a worker is // available. When wait() returns, methods may be called to determine // which of those conditions have been satisfied, and appropriate // action may be taken. If you are in a state where there is nothing // else to do until there are results, then you should call // waitForResults() instead of wait(). Please see comments // accompanying the method declarations for details. // For a non-trivial example of using a worker pool, please see the // DependencyRunner class. #include <vector> #include <deque> #include <iostream> #include <boost/function.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/tuple/tuple.hpp> #include <boost/shared_ptr.hpp> #include <ThreadSafeQueue.hh> template <typename ItemType, typename StatusType> class WorkerPool { public: typedef boost::tuple<ItemType, StatusType> ResultType; WorkerPool(unsigned int num_workers, boost::function<StatusType (ItemType)> const& method) : num_workers(num_workers), method(method), shutdown_requested(false) { assert(num_workers >= 1); for (unsigned int i = 0; i < num_workers; ++i) { // Create an entry point and a message queue for each thread. // Each thread calls worker_main with its index into the array // as its argument. thread_entries.push_back( boost::bind( &WorkerPool<ItemType, StatusType>::worker_main, this, i)); queues.push_back(item_queue_ptr_t(new item_queue_t())); } for (unsigned int i = 0; i < num_workers; ++i) { // Now that the other vectors are initialized, create the // threads. The threads may read these vectors concurrently. threads.push_back( thread_ptr_t(new boost::thread(thread_entries[i]))); } } // Block until the worker pool is ready to do something. When // this method returns, at least one of the status querying // functions below will return true. void wait() { boost::mutex::scoped_lock lock(this->mutex); while ((! this->shutdown_requested) && (this->results.empty()) && (this->available_workers.empty())) { this->condition.wait(lock); } } // Block until there are results to report or there are no more // workers working. This should be called instead of wait() if // there is nothing ready to be processed and nothing new can // become available without additional results. void waitForResults() { boost::mutex::scoped_lock lock(this->mutex); while ((! this->shutdown_requested) && (this->results.empty()) && (this->available_workers.size() < this->num_workers)) { this->condition.wait(lock); } } // Status querying function. // Return true iff a shutdown request has been received. bool shutdownRequested() { boost::mutex::scoped_lock lock(this->mutex); return this->shutdown_requested; } // Return true iff any results are available bool resultsAvailable() { boost::mutex::scoped_lock lock(this->mutex); return (! this->results.empty()); } // Return the number of available workers int availableWorkers() { boost::mutex::scoped_lock lock(this->mutex); return this->available_workers.size(); } // Return the number of busy workers int busyWorkers() { boost::mutex::scoped_lock lock(this->mutex); return this->num_workers - this->available_workers.size(); } // Return true iff all workers are idle and there are no pending // results to read bool idle() { boost::mutex::scoped_lock lock(this->mutex); return ((this->available_workers.size() == this->num_workers) && (this->results.empty())); } // Action methods // Get a result. This method will block until a result is ready. // It is best to avoid calling this method unless // resultsAvailable() has returned true. This method returns a // tuple containing the item that was processed and the status // returned by its worker. boost::tuple<ItemType, StatusType> getResults() { boost::mutex::scoped_lock lock(this->mutex); while (this->results.empty()) { this->condition.wait(lock); } ResultType r = this->results.front(); this->results.pop_front(); if (this->results.empty()) { this->condition.notify_all(); } return r; } // Submit an item to be processed. This method will block until a // worker is ready. It is best to call it only after // availableWorkers() has returned > 0. When the worker has // finished, the results will be made available to be returned by // a subsequent call to getResults(). void processItem(ItemType item) { boost::mutex::scoped_lock lock(this->mutex); while (this->available_workers.empty()) { this->condition.wait(lock); } int worker_id = this->available_workers.front(); this->available_workers.pop_front(); // A true as the first item of the tuple means we do want to // process this item. A false would tell the thread to exit. this->queues[worker_id]->enqueue(boost::make_tuple(true, item)); } // Request shutdown. Calling this method from one thread any // thread blocked on wait() to return and the shutdownRequested() // method to subsequently return true. It also asks any running // worker threads to exit when they finish their current jobs. As // of the initial implementation, it does not have any impact on // any jobs that may be running. void requestShutdown() { boost::mutex::scoped_lock lock(this->mutex); this->shutdown_requested = true; for (unsigned int i = 0; i < this->num_workers; ++i) { // Placing false as first element of tuple tells the // thread to exit. this->queues[i]->enqueue(boost::make_tuple(false, ItemType())); } this->condition.notify_all(); } // Join all worker threads. Calls requestShutdown(). void joinThreads() { requestShutdown(); for (unsigned int i = 0; i < this->num_workers; ++i) { this->threads[i]->join(); } } private: void worker_main(int worker_id) { try { item_queue_t& queue = *(this->queues[worker_id]); { // local scope boost::mutex::scoped_lock lock(this->mutex); this->available_workers.push_back(worker_id); this->condition.notify_all(); } while (true) { item_tuple_t tuple = queue.dequeue(); bool process_item = boost::get<0>(tuple); if (! process_item) { break; } ItemType item = boost::get<1>(tuple); StatusType status = this->method(item); ResultType result = boost::make_tuple(item, status); { // local scope boost::mutex::scoped_lock lock(this->mutex); this->results.push_back(result); this->available_workers.push_back(worker_id); this->condition.notify_all(); } } } catch (std::exception& e) { std::cerr << "uncaught exception in thread: " << e.what() << std::endl; exit(2); } } boost::mutex mutex; boost::condition condition; unsigned int num_workers; boost::function<StatusType (ItemType)> method; bool shutdown_requested; // Here are a few typedefs to make the code more readable. typedef boost::tuple<bool, ItemType> item_tuple_t; typedef ThreadSafeQueue<item_tuple_t> item_queue_t; typedef boost::shared_ptr<item_queue_t> item_queue_ptr_t; typedef boost::shared_ptr<boost::thread> thread_ptr_t; // There is one of these for each worker. std::vector<boost::function<void (void)> > thread_entries; std::vector<item_queue_ptr_t> queues; std::vector<thread_ptr_t> threads; // Create results queue and worker queue. We'll use regular STL // containers for these instead of ThreadSafeQueues because we are // protecting them with our own mutex. std::deque<ResultType> results; // This queue contains the ID numbers of all available workers. std::deque<int> available_workers; }; #endif // __WORKERPOOL_HH__
true
e26cdc12c1fca360f723b08183e41ccd407058a9
C++
JosanSun/MyNote
/C++/关键字/functionTryBlock/functionTryBlock/oth.cpp
GB18030
821
2.890625
3
[]
no_license
///* // * --------------------------------------------------- // * Copyright (c) 2017 josan All rights reserved. // * --------------------------------------------------- // * // * ߣ Josan // * ʱ䣺 2017/9/22 14:56:55 // */ //void f(int &x) try //{ // throw 10; //} //catch(const int &i) //{ // x = i; //} // //static void test01() //{ // int v = 0; // f(v); //v = 10 //} // //class E //{ //public: // const char* error; // E(const char* arg) : error(arg) // { // } //}; // //class A //{ //public: ~A() //{ // throw E("Exception in ~A()"); //} //}; // //class B //{ //public: ~B() //{ // throw E("Exception in ~B()"); //} //}; // // //static void test02() //{ // //} // //static void test() //{ // test01(); // test02(); //} // //int main() //{ // test(); // return 0; //}
true
e20ceefe08186cc53fe6395534b4b1ed6022ccd2
C++
sgladchenko/cpp-examples
/Timer.h
UTF-8
858
2.953125
3
[]
no_license
#ifndef SGTIMER_H #define SGTIMER_H #include <chrono> namespace SG { // A short class needed for quick evaluation of the elapsed time between tick and tock calls template<class timeunit = std::chrono::milliseconds, class timeclock = std::chrono::steady_clock> class Timer { using timepoint = typename timeclock::time_point; private: timepoint _start; timepoint _end; public: void tick() { _end = {}; _start = timeclock::now(); } void tock() { _end = timeclock::now(); } // The main function that returns the duration object timeunit duration() const { if (_start == timepoint{} or _end == timepoint{}) throw; return std::chrono::duration_cast<timeunit>(_end - _start); } }; } #endif
true
13d8e84ec202d6ec0618483fa4623966c59e0f0b
C++
lowlander/nederrock
/src/parser_nodes/arithmetic_parser_node.cpp
UTF-8
4,219
2.6875
3
[ "MIT" ]
permissive
// // Copyright (c) 2020 Erwin Rol <erwin@erwinrol.com> // // SPDX-License-Identifier: MIT // #include "arithmetic_parser_node.hpp" #include "product_parser_node.hpp" #include "add_parser_node.hpp" #include "subtract_parser_node.hpp" #include "parser_node.hpp" #include <memory> #include <istream> #include <string> #include <vector> #include <variant> void Arithmetic_Parser_Node::Rest::dump(std::wostream& output) const { std::visit([&output](auto&& node) { node->dump(output); }, m_add_sub); m_product->dump(output); } void Arithmetic_Parser_Node::Choice_1::dump(std::wostream& output) const { m_product->dump(output); for (const auto& r: m_rest) { r->dump(output); } } void Arithmetic_Parser_Node::Choice_2::dump(std::wostream& output) const { m_product->dump(output); } Arithmetic_Parser_Node::Arithmetic_Parser_Node(Choice_1&& choice) : m_choice(std::move(choice)) { } Arithmetic_Parser_Node::Arithmetic_Parser_Node(Choice_2&& choice) : m_choice(std::move(choice)) { } Arithmetic_Parser_Node::Rest_Ptr Arithmetic_Parser_Node::parse_rest(Token_Stream& input) { auto offset = input.tellg(); auto rest = std::make_shared<Rest>(); auto add = Add_Parser_Node::parse(input); if (add) { rest->m_add_sub = add; } else { input.seekg(offset); auto sub = Subtract_Parser_Node::parse(input); if (sub) { rest->m_add_sub = sub; } else { input.seekg(offset); return nullptr; } } rest->m_product = Product_Parser_Node::parse(input); if (rest->m_product == nullptr) { input.seekg(offset); return nullptr; } return rest; } Arithmetic_Parser_Node_Ptr Arithmetic_Parser_Node::parse_choice_1(Token_Stream& input) { auto offset = input.tellg(); Choice_1 choice; choice.m_product = Product_Parser_Node::parse(input); if (choice.m_product == nullptr) { input.seekg(offset); return nullptr; } while (auto rest_entry = parse_rest(input)) { choice.m_rest.push_back(rest_entry); } if (choice.m_rest.empty()) { input.seekg(offset); return nullptr; } return std::make_shared<Arithmetic_Parser_Node>(std::move(choice)); } Arithmetic_Parser_Node_Ptr Arithmetic_Parser_Node::parse_choice_2(Token_Stream& input) { auto offset = input.tellg(); Choice_2 choice; choice.m_product = Product_Parser_Node::parse(input); if (choice.m_product == nullptr) { input.seekg(offset); return nullptr; } return std::make_shared<Arithmetic_Parser_Node>(std::move(choice)); } Arithmetic_Parser_Node_Ptr Arithmetic_Parser_Node::parse(Token_Stream& input) { auto offset = input.tellg(); auto node = parse_choice_1(input); if (node) { return node; } input.seekg(offset); node = parse_choice_2(input); if (node) { return node; } input.seekg(offset); return nullptr; } void Arithmetic_Parser_Node::dump(std::wostream& output) const { std::visit([&output](auto&& choice){ choice.dump(output); }, m_choice); } void Arithmetic_Parser_Node::Rest::generate_cpp(Scope_State_Ptr state) const { std::visit([&state](auto&& choice){ choice->generate_cpp(state); }, m_add_sub); m_product->generate_cpp(state); } void Arithmetic_Parser_Node::Choice_1::generate_cpp(Scope_State_Ptr state) const { m_product->generate_cpp(state); for (const auto& r: m_rest) { r->generate_cpp(state); } } void Arithmetic_Parser_Node::Choice_2::generate_cpp(Scope_State_Ptr state) const { m_product->generate_cpp(state); } void Arithmetic_Parser_Node::generate_cpp(Scope_State_Ptr state) const { std::visit([&state](auto&& choice){ choice.generate_cpp(state); }, m_choice); } void Arithmetic_Parser_Node::Rest::collect_variables(Scope_State_Ptr state) const { m_product->collect_variables(state); } void Arithmetic_Parser_Node::Choice_1::collect_variables(Scope_State_Ptr state) const { m_product->collect_variables(state); for (const auto& r: m_rest) { r->collect_variables(state); } } void Arithmetic_Parser_Node::Choice_2::collect_variables(Scope_State_Ptr state) const { m_product->collect_variables(state); } void Arithmetic_Parser_Node::collect_variables(Scope_State_Ptr state) const { std::visit([&state](auto&& choice){ choice.collect_variables(state); }, m_choice); }
true
af43114e12af80acfb04609316148cb77346dae7
C++
banouge/SeniorProject
/TurnHandler.cpp
UTF-8
2,153
3.015625
3
[ "MIT" ]
permissive
#include "Player.h" #include "TurnHandler.h" std::unordered_map<Player*, std::unordered_map<int, std::queue<Command*>*>*> TurnHandler::playerMap = std::unordered_map<Player*, std::unordered_map<int, std::queue<Command*>*>*>(); void TurnHandler::submitCommands(Player* player) { std::unordered_map<int, std::queue<Command*>*>* queueMap = new std::unordered_map<int, std::queue<Command*>*>(); playerMap.emplace(player, queueMap); for (int b = 0; b < 10; ++b) { if (player->getCommandsInBracket(b)->size()) { std::queue<Command*>* queue = new std::queue<Command*>(); queueMap->emplace(player->getCommandsInBracket(b)->at(0)->BRACKET, queue); for (Command* command : *player->getCommandsInBracket(b)) { queue->push(command); } } } player->setHasSubmittedCommands(true); } void TurnHandler::resolveTurn() { std::vector<Player*> players; for (std::pair<Player*, std::unordered_map<int, std::queue<Command*>*>*> pair : playerMap) { players.push_back(pair.first); } std::sort(players.begin(), players.end(), comparePlayerPtr); for (int b = 0; b < 10; ++b) { bool isForward = true; bool isEmpty = true; do { isForward = !isForward; isEmpty = true; for (int p = 0; p < players.size(); ++p) { Player* player = players.at((isForward) ? (p) : (players.size() - p - 1)); if (playerMap.at(player)->count(b) && player->isAlive()) { std::queue<Command*>* queue = playerMap.at(player)->at(b); if (!queue->empty()) { isEmpty = false; queue->front()->resolve(); queue->pop(); } } } } while (!isEmpty); } for (Player* player : players) { if (player->hasCapturedNewTerritoryThisTurn()) { player->gainCard(); } player->clearCommands(); } cleanUp(); } void TurnHandler::cleanUp() { for (std::pair<Player*, std::unordered_map<int, std::queue<Command*>*>*> pair1 : playerMap) { for (std::pair<int, std::queue<Command*>*> pair2 : *pair1.second) { delete pair2.second; } delete pair1.second; } playerMap.clear(); } bool TurnHandler::comparePlayerPtr(Player* a, Player* b) { return a->INDEX < b->INDEX; }
true
ebaa837e0d6c67db59e21af2eb820ab9126dacf0
C++
kila2862/Poisson-Disk-Sampling
/main.cpp
UTF-8
8,783
3.203125
3
[]
no_license
#include <iostream> #include <glut.h> #include <math.h> #include <random> #include <ctime> #define R 10 //The R value mentioned in paper #define K 30 //The K value mentioned in paper #define WINDOW_WIDTH 1000 #define WINDOW_HEIGHT 1000 #ifndef M_PI #define M_PI 3.14159265358979323846 //Need PI to generate the sample points of different angles #endif const float GRID_WIDTH = floor(R / sqrt(2)); //The width value for the table's grid const int rows = floor(WINDOW_WIDTH / GRID_WIDTH); //Total rows numbers in the table const int columns = floor(WINDOW_WIDTH / GRID_WIDTH); //Total columns numbers in the table using namespace std; struct PointData { float x; float y; PointData() { x = 0.0; y = 0.0; } PointData(float pos_x, float pos_y) { x = pos_x; y = pos_y; } }; std::vector<int> table; //Public data used to record if the grid in table is visited std::vector<PointData> point_positions; //Public data which is used to record the real position of the index in table std::vector<PointData> active_list; //Public data which is used to record the active point ///////////////////////////////////////////////////////////////////////////////////// // Function Name: get_transform // Purpose: To transform the position in window form to openGL coordinate system // Return: The transformed position that we need to draw for openGL //////////////////////////////////////////////////////////////////////////////////// PointData get_transform(int x, int y) { PointData pos; pos.x = -1 + (static_cast<float>(x) / WINDOW_WIDTH * 2); pos.y = -1 + (static_cast<float>(y) / WINDOW_HEIGHT * 2); return pos; } /////////////////////////////////////////////////////////////////////////////////// // Functoin Name: display // Purpose: Used to render the sample points // Return: No return value ////////////////////////////////////////////////////////////////////////////////// void display(void) { glPushMatrix(); glPointSize(5.0); glColor3f(1.0f, 0.0f, 0.0f); glEnable(GL_POINT_SMOOTH); glColor3f(0.0f, 1.0f, 0.0f); for (unsigned i = 0; i < table.size(); i++) { if (-1 != table[i]) { float x = point_positions[i].x; float y = point_positions[i].y; PointData point = get_transform(x, y); glBegin(GL_POINTS); glVertex2f(point.x, point.y); glEnd(); } } glEnd(); glDisable(GL_POINT_SMOOTH); glPopMatrix(); glutSwapBuffers(); } /////////////////////////////////////////////////////////////////////////////////////////// // Function Name: table_init // Purpose: init function for out public member data and generate the first sample point // Return: no return value ////////////////////////////////////////////////////////////////////////////////////////// void table_init() { //Step 0 in paper: initialize the grid with -1; glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); for (auto i = 0; i < rows*columns; i++) { table.push_back(-1); point_positions.push_back(PointData()); } //Step 1 in paper: Get the start point and push it in activelist std::default_random_engine gen = std::default_random_engine(time(NULL)); std::uniform_real_distribution<float> dis_width(0, WINDOW_WIDTH); std::uniform_real_distribution<float> dis_height(0, WINDOW_HEIGHT); int x = dis_width(gen); int y = dis_height(gen); int index_x = floor(x / GRID_WIDTH); int index_y = floor(y / GRID_WIDTH); PointData point(x, y); table[index_x + index_y * columns] = 1; point_positions[index_x + index_y * columns].x = x; point_positions[index_x + index_y * columns].y = y; active_list.push_back(point); } /////////////////////////////////////////////////////////////////////////////////////////////////// // Function Name: check_distance // Purpose: To check if the distance of the new sample point and its neiborhood is acceptable // Return: True - if the distance of the new sample point and neiborhood is larger than grid_width // False - if the distance of the new sample point and neiborhood is too close ////////////////////////////////////////////////////////////////////////////////////////////////// bool check_distance(int index, float pos_x, float pos_y) { bool accept = true; if (1 == table[index]) { PointData point = point_positions[index]; float distance = sqrt(abs(pos_x - point.x)*abs(pos_x - point.x) + abs(pos_y - point.y)*abs(pos_y - point.y)); if (distance < GRID_WIDTH) { accept = false; } } return accept; } //////////////////////////////////////////////////////////////////////////////////// // Function Name: check_out_of_table_boundary // Purpose: Used to check if the given index is out of the range of the table // Return : Ture - if the index is a valid index in table // False - if the index is out of the boundary of the table /////////////////////////////////////////////////////////////////////////////////// bool check_out_of_table_boundary(int index) { if (index < 0 || index >= table.size()-1) { return false; } return true; } /////////////////////////////////////////////////////////////////////////////////// // Function Name: update_data // Purpose: To update the public member data table and active_list // Return: no return value /////////////////////////////////////////////////////////////////////////////////// void update_data(int index, float pos_x, float pos_y) { table[index] = 1; point_positions[index].x = pos_x; point_positions[index].y = pos_y; PointData new_point(pos_x, pos_y); active_list.push_back(new_point); } /////////////////////////////////////////////////////////////////////////////////// // Function Name: generate_samples // Purpose: To generate the sample points for a given point in active_list // And finish when there is no points in active_list // Return: no return value ////////////////////////////////////////////////////////////////////////////////// void generate_samples() { //step 2 in paper: Generate the new sample points near the given poins in active_list const unsigned int seed = time(0); mt19937_64 rng(seed); std::uniform_real_distribution<float> dis_angle(0.0, 2 * M_PI); std::uniform_real_distribution<float> dis_distance(floor(R / sqrt(2)), 2 * floor(R / sqrt(2))); while (!active_list.empty()) { PointData point = active_list.back(); active_list.pop_back(); for (auto count = 0; count < K; count++) { float angle = dis_angle(rng); float distance = dis_distance(rng); float pos_x = point.x + distance * cos(angle); float pos_y = point.y + distance * sin(angle); if (0 > pos_x || pos_x > WINDOW_WIDTH || pos_y < 0 || pos_y > WINDOW_HEIGHT) continue; //skip the points that is out of the window form int index_x = floor(pos_x / GRID_WIDTH); int index_y = floor(pos_y / GRID_WIDTH); int index = index_x + index_y * columns; if (!check_out_of_table_boundary(index)) continue; //skip the invalid index of table if (1 == table[index]) continue; //skip for the the created grid in table bool all_ok = true; for (auto offset_x = -1; offset_x <= 1; offset_x++) { for (auto offset_y = -1; offset_y <= 1; offset_y++) { int new_index = (index_x + offset_x) + ((index_y + offset_y)*columns); if (!check_out_of_table_boundary(new_index)) continue; //skip the index that is out of table range if (false == check_distance(new_index, pos_x, pos_y)) { all_ok = false; } } } if (true == all_ok) { update_data(index, pos_x, pos_y); } }// end of the for loop for K times sample generation }//end of while loop } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // Functiona Name: main // Purpose: The entry point of the program. Not so many thing done. mainly are // (1) Set the window size and its position // (2) Call table_init() to initialize the public member data and get the initial sample point // (3) Call generate_samples() to generate the sample points from the the initialized sample point // (4) Render the sample points we get from generate_samples function // Retuen: 0 after process ends //////////////////////////////////////////////////////////////////////////////////////////////////////////// int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutInitWindowPosition(100, 100); //set the position of the window glutCreateWindow("Poisson Disk Sampling"); //set the title of the window table_init(); generate_samples(); glutDisplayFunc(display); glutMainLoop(); return 0; }
true
97115d3e5c4537d0a0611a4b8d3d32dae129cc21
C++
sohaibsyed95/Comsc-200
/Lab 0/HelloWorld.cpp
UTF-8
614
3.609375
4
[]
no_license
// Lab 0b, The "Hello, World" Program // Programmer: Sohaib Syed // Editor(s) used: Code::Blocks // Compiler(s) used: Code::Blocks #include <iostream> using namespace std; int main() { // print my name and this assignment's title cout << "Lab 0b, The \"Hello, World\" Program \n"; cout << "Programmer: Sohaib Syed\n"; cout << "Editor(s) used: Code::Blocks\n"; cout << "Compiler(s) used: Code::Blocks\n"; cout << "File: " << __FILE__ << endl; cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl << endl; //A code block cout << "Hello World! Have a nice day." << endl; }
true