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
25478f504b521701194f0a67ba9d0de76758cd73
C++
rathoresrikant/HacktoberFestContribute
/Algorithms/SparseMatrix/SparseAddMultipl.cpp
UTF-8
4,400
2.75
3
[ "MIT" ]
permissive
#include<iostream> #include<cstring> using namespace std; void print_sparse(int mat[][3]){ int c[mat[0][0]][mat[0][1]] ,k = 1; for(int i = 0; i< mat[0][0]; i++){ for(int j = 0; j<mat[0][1]; j++){ if(i == mat[k][0] && j == mat[k][1]){ c[i][j] = mat[k][2]; k++; } else c[i][j] = 0; } } cout<<endl; /*for(int i =0; i<= mat[0][2]; i++){ cout<<mat[i][0]<<" "<<mat[i][1]<<" "<<mat[i][2]<<endl; } cout<<endl;*/ for(int i=0; i<mat[0][0]; i++){ for(int j=0; j<mat[0][1]; j++){ cout<<c[i][j]<<" "; } cout<<endl; } } void print(int mat[][3]){ cout<<endl; for(int i =0; i<= mat[0][2]; i++){ cout<<mat[i][0]<<" "<<mat[i][1]<<" "<<mat[i][2]<<endl; } cout<<endl; } void del(int mul[][3], int x, int n){ for(int i = x; i< n; i++){ mul[i][0]= mul[i+1][0]; mul[i][1]= mul[i+1][1]; mul[i][2]= mul[i+1][2]; } } int partition(int a[][3],int s,int e) { int pivot=a[e][1]; int indexpivot=s; for(int i=s;i<e;i++) { if(a[i][1] < pivot) { swap(a[i],a[indexpivot]); indexpivot++; } } swap(a[indexpivot],a[e]); return indexpivot; } void quicksort(int a[][3], int s,int e) { if(s>=e) return; int indexpivot=partition(a,s,e); quicksort(a, s, indexpivot-1); quicksort(a, indexpivot+1, e); } void sorted(int a[][3]){ int *count = new int[10]; for(int i = 0; i<10 ; i++){ count[i] = 0; } for(int i = 1; i <= a[0][2]; i++){ count[a[i][0]]++; } int start = 1, end = count[0] + 1; for(int i =0; i<a[0][0] ; i++){ quicksort(a, start, end - 1); start = end ; end += count[i+1]; } // print(a); } void multiply_sparse(int A[][3], int B[][3], int mul[][3], int cnta, int cntb){ int i = 1, k = 1; while(i <= cnta){ int j = 1; while(j <= cntb){ if(A[i][1] == B[j][1]){ mul[k][0]= A[i][0]; mul[k][1]= B[j][0]; mul[k++][2]= A[i][2] * B[j][2]; } j++; } i++; } mul[0][2] = k - 1; print(mul); //sort by column sorted(mul); for(int m = 1; m < k - 1; m++){ if((mul[m][0] == mul[m + 1][0]) && (mul[m][1] == mul[m + 1][1])){ mul[m][2] = mul[m][2] + mul[m + 1][2]; del(mul, m+1, k-1); mul[0][2] = --k - 1; } } print(mul); print_sparse(mul); } int main(){ int row1, row2, col1, col2; cin>>row1>>col1>>row2>>col2; cout<<endl; int **A = new int*[row1]; for(int i= 0; i< row1; i++){ A[i] = new int[col1]; } int **B = new int*[row2]; for(int i = 0; i< row2; i++){ B[i] = new int[col2]; } int cnt_a = 0, cnt_b = 0; for(int i = 0; i < row1; i++){ for(int j = 0;j < col1; j++){ cin>>A[i][j]; if(A[i][j] != 0) cnt_a++; } } cout<<endl; for(int i = 0; i < row2; i++){ for(int j = 0;j < col2; j++){ cin>>B[i][j]; if(B[i][j] != 0) cnt_b++; } } int t[row2][col2]; for(int i = 0; i < row2; i++){ for(int j = 0;j < col2; j++){ t[j][i] = B[i][j]; } } int A_sparse [cnt_a + 1][3]; int B_sparse [cnt_b + 1][3]; //cout<<endl; A_sparse[0][0] = row1; A_sparse[0][1] = col1; A_sparse[0][2] = cnt_a; int k =1; for(int i =0; i < row1; i++){ for(int j =0; j< col1; j++){ if(A[i][j] != 0){ A_sparse[k][0] = i; A_sparse[k][1] = j; A_sparse[k][2] = A[i][j]; k++; } } } //print_sparse(A_sparse); B_sparse[0][0] = row2; B_sparse[0][1] = col2; B_sparse[0][2] = cnt_b; int c =1; for(int i =0; i < row2; i++){ for(int j =0; j< col2; j++){ if(t[i][j] != 0){ B_sparse[c][0] = i; B_sparse[c][1] = j; B_sparse[c][2] = t[i][j]; c++; } } } //print_sparse(B_sparse); int mul[row1 * col2 + 1][3]; mul[0][0] = row1; mul[0][1] = col2; multiply_sparse(A_sparse, B_sparse, mul, cnt_a, cnt_b); }
true
dec450a806f01b0bd83263f07864d2e502379402
C++
MAhsan-Raza/AlgorithmsPractice
/HackerRank./C++./TemplateSpecialization.cpp
UTF-8
901
3.578125
4
[ "MIT" ]
permissive
// Define specializations for the Traits class template here. template<> struct Traits<Fruit> { public: static string name(int i) { switch((Fruit)i) { case Fruit::apple: return "apple"; break; case Fruit::orange: return "orange"; break; case Fruit::pear: return "pear"; break; } return "unknown"; } }; template<> struct Traits<Color> { public: static string name(int i) { switch((Color)i) { case Color::red: return "red"; break; case Color::green: return "green"; break; case Color::orange: return "orange"; break; } return "unknown"; } };
true
3b4eae0cd9cae606d6e1f998fa3c4572c0d384ce
C++
kaabimg/opengl-demos
/transforms/lab_solar_system/solarsystemscene.cpp
UTF-8
6,497
2.53125
3
[]
no_license
#include "solarsystemscene.h" #include "orbitingbody.h" #include <camera.h> #include <sphere.h> #include <QGLWidget> #include <QImage> SolarSystemScene::SolarSystemScene( QObject* parent ) : AbstractScene( parent ), m_camera( new Camera( this ) ), m_vx( 0.0f ), m_vy( 0.0f ), m_vz( 0.0f ), m_viewCenterFixed( false ), m_panAngle( 0.0f ), m_tiltAngle( 0.0f ), m_sphere( 0 ), m_animate( true ), m_time( 0.0f ) { // Initialize the camera position and orientation // TODO Set camera position to (0, 0, 60) // TODO Set camera to look at the origin with positive y-axis as "up" vector } void SolarSystemScene::initialise() { // Create a material for the Sun m_sunMaterial = createSunMaterial(); // Create a material for the planets MaterialPtr material = createPhongMaterial(); // Create a sphere and set the material on it m_sphere = new Sphere( this ); m_sphere->setMaterial( material ); m_sphere->create(); // Create some objects for our solar system createOrbitingBodies(); // Enable depth testing glEnable( GL_DEPTH_TEST ); // Set the clear color to (almost) white glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); } void SolarSystemScene::createOrbitingBodies() { // Create some "planets" OrbitingBody* redPlanet = new OrbitingBody( this ); redPlanet->setBodyRadius( 0.5f ); redPlanet->setColor( QColor::fromRgbF( 0.8f, 0.0f, 0.0f ) ); redPlanet->setOrbitalRadius( 3.0f ); redPlanet->setOrbitalPhase( 0.0f ); redPlanet->setOrbitalPeriod( 1.5f ); m_bodies.append( redPlanet ); OrbitingBody* greenPlanet = new OrbitingBody( this ); greenPlanet->setBodyRadius( 0.8f ); greenPlanet->setColor( QColor::fromRgbF( 0.0f, 0.8f, 0.0f ) ); greenPlanet->setOrbitalRadius( 8.0f ); greenPlanet->setOrbitalPhase( 0.33f ); greenPlanet->setOrbitalPeriod( 7.0f ); m_bodies.append( greenPlanet ); OrbitingBody* bluePlanet = new OrbitingBody( this ); bluePlanet->setBodyRadius( 0.6f ); bluePlanet->setColor( QColor::fromRgbF( 0.0f, 0.0f, 0.8f ) ); bluePlanet->setOrbitalRadius( 15.0f ); bluePlanet->setOrbitalPhase( 0.66f ); bluePlanet->setOrbitalPeriod( 25.0f ); m_bodies.append( bluePlanet ); OrbitingBody* purplePlanet = new OrbitingBody( this ); purplePlanet->setBodyRadius( 0.6f ); purplePlanet->setColor( QColor::fromRgbF( 0.8f, 0.0f, 0.8f ) ); purplePlanet->setOrbitalRadius( 12.0f ); purplePlanet->setOrbitalPhase( 0.5f ); purplePlanet->setOrbitalPeriod( 10.0f ); purplePlanet->setOrbitalInclination( 10.0f ); m_bodies.append( purplePlanet ); // Create a moon as child of the red planet OrbitingBody* greyMoon = new OrbitingBody( greenPlanet ); greyMoon->setBodyRadius( 0.3f ); greyMoon->setColor( QColor::fromRgbF( 0.8f, 0.8f, 0.8f ) ); greyMoon->setOrbitalRadius( 1.8f ); greyMoon->setOrbitalPhase( 0.0f ); greyMoon->setOrbitalPeriod( -2.0f ); greyMoon->setOrbitalInclination( 0.0f ); m_bodies.append( greyMoon ); // TODO Add some more planets/moons of your own } void SolarSystemScene::update( float t ) { // Store the current time so that we can feed it to the Sun shader m_time = t; // Advance the animation if ( m_animate ) { // TODO Update the transformation of each planet/moon } m_modelMatrix.setToIdentity(); m_modelMatrix.scale( 2.0f ); // TODO Update the camera position and orientation } void SolarSystemScene::render() { // Clear the buffer with the current clearing color glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // // Render the Sun // m_sunMaterial->bind(); QOpenGLShaderProgramPtr shader = m_sunMaterial->shader(); // Set the usual view/projection matrices QMatrix4x4 mvp = m_camera->viewProjectionMatrix() * m_modelMatrix; shader->setUniformValue( "mvp", mvp ); shader->setUniformValue( "time", m_time ); // Let the mesh setup the remainder of its state and draw itself m_sphere->render(); // // Render the planets and moons // // Setup the rendering pipeline - bind Phong lighting shader m_sphere->material()->bind(); shader = m_sphere->material()->shader(); // Set the lighting parameters // Light is at the origin in world coordinates to simulate the Sun // We need to convert this to eye coordinates which the shader expects QVector4D worldLightPos( 0.0f, 0.0f, 0.0f, 1.0f ); QVector4D eyeLightPos = m_camera->viewMatrix() * worldLightPos; shader->setUniformValue( "light.position", eyeLightPos ); shader->setUniformValue( "light.intensity", QVector3D( 1.0f, 1.0f, 1.0f ) ); // Iterate through the oribiting bodies, set uniforms and draw each one foreach ( OrbitingBody* body, m_bodies ) { // TODO Get the world/model matrix for the planet/moon // TODO Construct modelView, normal, projection and mvp matrices // TODO Set matrices as uniform variables on the shader program setBodyColor( shader, body ); m_sphere->render(); } } void SolarSystemScene::setBodyColor( const QOpenGLShaderProgramPtr& shader, OrbitingBody* body ) const { QColor c = body->color(); QVector3D color( c.redF(), c.greenF(), c.blueF() ); shader->setUniformValue( "material.kd", color ); c = c.darker( 200 ); QVector3D ambientColor( c.redF(), c.greenF(), c.blueF() ); shader->setUniformValue( "material.ka", ambientColor ); shader->setUniformValue( "material.ks", QVector3D( 0.4f, 0.4f, 0.4f ) ); shader->setUniformValue( "material.shininess", 20.0f ); } void SolarSystemScene::resize( int w, int h ) { // Make sure the viewport covers the entire window glViewport( 0, 0, w, h ); // Update the projection matrix float aspect = static_cast<float>( w ) / static_cast<float>( h ); m_camera->setPerspectiveProjection( 20.0f, aspect, 0.3, 1000.0f ); } MaterialPtr SolarSystemScene::createPhongMaterial() { MaterialPtr material( new Material ); material->setShaders( ":/shaders/phong.vert", ":/shaders/phong.frag" ); return material; } MaterialPtr SolarSystemScene::createSunMaterial() { MaterialPtr material( new Material ); material->setShaders( ":/shaders/noise.vert", ":/shaders/noise.frag" ); return material; }
true
0c4201727de6b315cbcd62a2966b2d3db92d8bbb
C++
stwrd/SmallTool
/CvtVideoToFrame.cpp
GB18030
2,426
2.640625
3
[]
no_license
// Vedio2Img.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include <Windows.h> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; class MySVM : public CvSVM { public: //svmľߺеalpha double * get_alpha_vector() { return this->decision_func->alpha; } //svmľߺеrho,ƫ float get_rho() { return this->decision_func->rho; } }; int _tmain(int argc, _TCHAR* argv[]) { if (argc != 4) { cout << "input arguments error" << endl; return 0; } //Ŀ¼Ƶļ string inputDir = argv[1]; string outputDir = argv[2]; //趨Ƶ int interval = atoi(argv[3]);//ÿintervalȡһ֡ WIN32_FIND_DATA FindData; HANDLE hError; int FileCount = 0; char FilePathName[MAX_PATH] = { 0 }; // · char FullPathName[MAX_PATH] = { 0 }; strcpy(FilePathName, argv[1]); strcat(FilePathName, "\\*.*"); hError = FindFirstFile(FilePathName, &FindData); if (hError == INVALID_HANDLE_VALUE) { printf("ʧ!\n"); return 0; } //趨ͼƬ vector<int> compression_params; compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); //pngʽ£ĬϵIJΪ3. //ȡƵеͼƬ int videoCount = 1; do { // ... if (strcmp(FindData.cFileName, ".") == 0 || strcmp(FindData.cFileName, "..") == 0) { continue; } // · sprintf_s(FullPathName, "%s\\%s", argv[1], FindData.cFileName); VideoCapture cap; cap.open(FullPathName); Mat img; if (cap.isOpened()) { cout << "start to extract video " << videoCount++ << "...\r"; char directoryName[MAX_PATH] = { 0 }; sprintf_s(directoryName, "%s\\%s", argv[2], FindData.cFileName); CreateDirectory(directoryName, NULL); int cnt = 0; int frameNum = 0; while (true) { cap >> img; if (!img.empty()) { if (cnt++ == 0) { resize(img, img, Size(), 1, 1); char fileName[MAX_PATH] = { 0 }; sprintf_s(fileName, "%s\\%s\\%06d.jpg", argv[2], FindData.cFileName, frameNum++); imwrite(fileName, img); } if (cnt >= interval) { cnt = 0; } //imshow("test",img); //waitKey(10); } else { break; } } } } while (::FindNextFile(hError, &FindData)); getchar(); return 0; }
true
6a434c7cf5bacc280cbed8db04719c4f9421aa4f
C++
kyuhwang3/AwayTeamstar
/study/increaseNum.cpp
UTF-8
669
2.984375
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; void solve(int *dataInput, int dataSize) { int *memo = new int[dataSize]; for (int i = 0; i < dataSize; i ++) { memo[i] = 1; } for (int i = 0; i < dataSize; i++) { for (int j = 0; j < i; j++) { if (dataInput[i] > dataInput[j] && memo[i] < memo[j] + 1) { memo[i] = memo[j] + 1; } } } int maxCount = 0; for (int i = 0; i < dataSize; i++) { if (memo[i] > maxCount) { maxCount = memo[i]; } } cout << maxCount << endl; } int main(void) { int N; cin >> N; int *num = new int[N]; for (int i = 0; i < N; i++) { cin >> num[i]; } solve(num, N); delete(num); return 0; }
true
a74edefcd8fcf2633988357674b0901b70f2be57
C++
ykw1225/CS-132
/cpp/10-5.cpp
UTF-8
906
3.984375
4
[]
no_license
//10-5: Sentence Capitalizer //Yeung Kit Wong #include<iostream> #include<string> using namespace std; void stcCap(char* array){ int i = 0; //if the element is the first letter, and after '.', '!', or '?', then upper the case. while(*(array+i) != '\0'){ if(i == 0 || *(array+i-2) == '.' || *(array+i-2) == '!' || *(array+i-2) == '?') *(array+i) = char(*(array+i)-32); i++; } } void stcCap(string &s){ int i = 0; while(s[i] != '\0'){ if(i == 0 || s[i-2] == '.' || s[i-2] == '!' || s[i-2] == '?') s[i] = char(s[i]-32); i++; } } int main(){ char array[999]; string s; cout << "Enter a C-string: "; cin.getline(array,999); stcCap(array); cout << array; cout << endl; cout << "Enter a string: "; getline(cin, s); stcCap(s); cout << s << endl; return 0; }
true
2113b73e3bcdf50ffe807c09d677253ade2447ca
C++
Shailendra53/Projects
/hash analysis/name_map.hpp
UTF-8
10,672
3.390625
3
[]
no_license
#ifndef NAME_MAP_HPP #define NAME_MAP_HPP #include <iostream> #include <cmath> using namespace std; template <typename K,typename V> class NODE; template <typename K, typename V> class Name_Map { // map interface public: Name_Map(int capacity); // constructor int size() const; // number of entries in the map bool empty() const; // is the map empty? V& find(const K& k); // find entry with key k void put(const K& k, const V& v); // insert/replace pair (k,v) void erase(const K& k); // remove entry with key k unsigned int integercasting(const K& k); //function for integer casting unsigned int componentsum(const K& k); //function for component sum unsigned int polynomialsum(const K& k); //function for polynomial sum unsigned int cyclicshift(const K& k); //function for cyclic shift void remove(NODE<K,V>*& temp,int place); int division(unsigned int key); int mad(unsigned int key); int multiplication(unsigned int key); void add(int place, const K& k, const V& v, int hash, int method); void print(); int sizeofelement(const K& k); void enter_component(const K& k, const V& v); void enter_polynomial(const K& k, const V& v); void enter_cyclicshift(const K& k, const V& v); void enter_integercasting(const K& k, const V& v); V& check_key(NODE<K,V>* temp, const K& k); void filewrite(ofstream &fwrite); void find_hash(); void removespaces(V& v); unsigned int get_key(const K& k); int get_place(unsigned int key); private : NODE<K,V> **array[12]; float counter[4][3]; int size_hash; int m; int hash; int key_change_method; int index_method; int find_hash_count; }; template <typename K,typename V> class NODE { private : K key; V value; NODE<K,V>* next; public : friend class Name_Map<K,V>; }; template <typename K,typename V> int Name_Map <K,V> :: size() const { return size_hash; } template <typename K,typename V> bool Name_Map <K,V> :: empty() const { if(size_hash) return false; else return true; } template <typename K,typename V> void Name_Map <K,V> :: filewrite(ofstream &fwrite) { fwrite<<"4X3 MATRIX OF NAME MAP :-\n"; for(int i=0;i<4;i++) { for(int j=0;j<3;j++) fwrite<<counter[i][j]*100/size_hash<<" "; fwrite<<"\n"; } } template <typename K,typename V> unsigned int Name_Map <K,V> :: get_key(const K& k) { switch(key_change_method) { case 0 : return componentsum(k); case 1 : return polynomialsum(k); case 2 : return cyclicshift(k); case 3 : return integercasting(k); } } template <typename K,typename V> int Name_Map <K,V> :: get_place(unsigned int key) { switch(index_method) { case 0 : return division(key); case 1 : return mad(key); case 2 : return multiplication(key); } } template <typename K,typename V> void Name_Map <K,V> :: erase(const K& k) { if(find_hash_count==0) find_hash(); //cout<<hash<<endl; unsigned int key = get_key(k); int place = get_place(key); NODE<K,V>* temp = array[hash][place]; while(temp!=NULL) { if(temp->key == k) { remove(temp,place); size_hash--; return; } temp = temp->next; } cout<<"\nELEMENT DOES NOT EXIST.....\n"; } template <typename K,typename V> void Name_Map <K,V> :: remove(NODE<K,V>*& temp, int place) { NODE<K,V>* check =array[hash][place]; if(check == temp) { check = check->next; array[hash][place] = check; cout<<"deleted\n"; } else { while(check!=NULL) { if(check->next == temp) { check -> next = temp -> next; delete temp; cout<<"deleted"; } check = check ->next; } } } template <typename K,typename V> Name_Map <K,V>:: Name_Map(int capacity) { for(int i=0;i<12;i++) { array[i] = new NODE<K,V>* [capacity]; for(int j=0;j<capacity;j++) { array[i][j] = NULL; //cout<<j<<" "; } } for(int i=0;i<4;i++) for(int j=0;j<3;j++) counter[i][j]=0;// size_hash = 0; m = capacity; hash = 0; key_change_method = 0; index_method = 0; find_hash_count = 0; } template <typename K,typename V> void Name_Map <K,V> :: find_hash() { int min = counter[0][0]; for(int i=0;i<3;i++) for(int j=0;j<3;j++) if(counter[i][j]<min) { min = counter[i][j]; hash = i*3+j; key_change_method=i; index_method=j; } } template <typename K,typename V> V& Name_Map <K,V> :: find(const K& k) { if(find_hash_count==0) find_hash(); //cout<<hash<<endl;; unsigned int key = get_key(k) ; int place = get_place(key); NODE<K,V> *temp = array[hash][place]; return check_key(temp,k); } template <typename K,typename V> V& Name_Map <K,V> :: check_key(NODE<K,V>* temp, const K& k) { bool flag = true; while(temp!=NULL) { if(temp->key==k) { return temp -> value; } temp = temp -> next; } cout<<"\nDOES NOT EXIST.......AS THE FUNCTION RETURNS A REFERENCE OF ELEMENT AND AS THE ELEMENT DOES NOT EXIST THEREFORE SEGMATATION FAULT MAY OCCUR \n\n"; } template <typename K,typename V> int Name_Map <K,V> :: sizeofelement(const K& k) { int size; for(size=0;k[size]!='\0';size++); //cout<<size; return size; } template <typename K,typename V> void Name_Map <K,V> :: print() { //for(int i=0;i<12;i++) /*{ cout<<"\nvalues of hash function "<<hash+1<<endl; for(int j=0;j<m;j++) { if(array[hash][j] != NULL) { //cout<<"\t"; //cout<<"collisions "<<counter[i][j]; NODE<K,V> *temp = array[hash][j]; while(temp != NULL) { cout<<temp -> value<<" | "; temp = temp->next; } cout<<"\n\n"; } } }*/ for(int i=0;i<4;i++) { for(int j=0;j<3;j++) cout<<counter[i][j]*100/size_hash<<" "; cout<<"\n"; } } template <typename K,typename V> void Name_Map <K,V>:: put(const K& k, const V& v) { size_hash++; enter_component(k,v); enter_polynomial(k,v); enter_cyclicshift(k,v); enter_integercasting(k,v); //find_hash(); //cout<<"////////////////"<<endl; } template <typename K,typename V> void Name_Map <K,V> :: enter_component(const K& k, const V& v) { unsigned int key; int place; key = componentsum(k); //cout<<key<<endl; place = division(key); add(place,k,v,0,0); place = mad(key); add(place,k,v,1,1); place = multiplication(key); add(place,k,v,2,2); //cout<<"\ncomponent over\n"; } template <typename K,typename V> void Name_Map <K,V> :: enter_polynomial(const K& k, const V& v) { unsigned int key; int place; key = polynomialsum(k); //cout<<key<<endl; place = division(key); add(place,k,v,3,0); place = mad(key); add(place,k,v,4,1); place = multiplication(key); add(place,k,v,5,2); //cout<<"\npolynomial over\n"; } template <typename K,typename V> void Name_Map <K,V> :: enter_cyclicshift(const K& k, const V& v) { unsigned int key; int place; key = cyclicshift(k); //cout<<key<<endl; //cout << "main key is "<<key << endl; place = division(key); //cout << "key1 is "<< place <<endl; add(place,k,v,6,0); place = mad(key); //cout << "key2 is "<< place <<endl; add(place,k,v,7,1); place = multiplication(key); //cout << "key3 is "<< place <<endl; add(place,k,v,8,2); //cout<<"\ncyclic over\n"; } template <typename K,typename V> void Name_Map <K,V> :: enter_integercasting(const K& k, const V& v) { unsigned int key; int place; key = integercasting(k); //cout<<key<<endl; place = division(key); add(place,k,v,9,0); place = mad(key); add(place,k,v,10,1); place = multiplication(key); add(place,k,v,11,2); } template <typename K,typename V> unsigned int Name_Map <K,V>:: integercasting(const K& k) { char temp; unsigned int sum = 0; int loop; unsigned int size = sizeofelement(k); if(size>=4) loop=4; else loop = size; for(int i=1;i<=loop;i++) { temp = k[size-i]; sum = sum + (int)temp; } return sum; } template <typename K,typename V> unsigned int Name_Map <K,V>:: componentsum(const K& k) { unsigned int temp = 0; unsigned int size = sizeofelement(k); for(int i=0;i<size;i++) { temp = temp + (unsigned int)k[i]; } return temp; } template <typename K,typename V> unsigned int Name_Map <K,V>:: polynomialsum(const K& k) { unsigned int temp = 0; unsigned int size = sizeofelement(k); //cout<<size; unsigned int a = 33; for(int i=0;i<size;i++) { temp = (temp+ (int)k[i])*a; //cout<<temp<<endl; //a*=33; } return temp; } template <typename K,typename V> unsigned int Name_Map <K,V>:: cyclicshift(const K& k) { unsigned int temp = 0; unsigned int size = sizeofelement(k); //cout << "size is "<<size << endl; unsigned int a = 1; for(int i=0;i<size;i++) { temp = (temp << 5) | (temp >> 27); temp = temp + (unsigned int)k[i]; } //cout<<temp<<"\n"; return temp; } //template <typename K,typename V> template <typename K,typename V> int Name_Map <K,V>:: division(unsigned int key) { int place = (key)%m; //cout<<"place->"<<place<<endl; return place; } template <typename K,typename V> int Name_Map <K,V>:: mad(unsigned int key) { int a,b; a = 1000002334; b = 444444444; int place = ((a*key+b))%m; //cout<<"place->"<<place<<endl; return place; } template <typename K,typename V> int Name_Map <K,V>:: multiplication(unsigned int key) { double x = ((double)key*(sqrt(5.0)-1)/2); double num = x - (long long int)x; //cout<<x<<" "<<num; int place = floor(num*pow(2,12)); place = place %m; //cout<<"place->"<<place<<endl; return place; } template <typename K,typename V> void Name_Map <K,V> :: add(int place, const K& k, const V& v, int hash, int method) { NODE<K,V> *temp = new NODE<K,V>; temp -> key = k; temp -> value = v; temp -> next = NULL; if(array[hash][place] == NULL) { //cout<<temp->next<<"<- node next"<<endl; array[hash][place] = temp; //node -> next = NULL; array[hash][place] -> next = NULL; //cout<<array[hash][place] -> next<<"<- initial node"<<endl; } else { counter[hash/3][method]++; //cout<<hash/3<<" "<<method<<" "<<counter[hash/3][method]<<endl; //cout<<array[hash][place] -> next<<"<- initial node"<<endl; NODE<K,V> *temp1 = array[hash][place]; //cout<<temp1->value<<" "<<temp1 -> next <<"<- printing nullllllllll"<<endl; //cout<<temp->next<<"<- node next"<<endl; while(temp1->next != NULL) { //cout<<"\n"<<temp->next; temp1 = temp1 -> next; } //cout<<temp->next<<"<- node next"<<endl; temp1 -> next = temp; temp -> next = NULL; } } #endif
true
4e673ac177b17b342ce7df5bec91bfe50aed35de
C++
yprateek136/Data_structure_in_120days
/Check if strings are rotations of each other or not.cpp
UTF-8
747
3.75
4
[]
no_license
// Check if strings are rotations of each other or not.cpp #include<bits/stdc++.h> using namespace std; class Solution { public: //Function to check if two strings are rotations of each other or not. bool areRotations(string s1,string s2) { if(s1.length() != s2.length()) { return false; } //concatenate string string temp = s1 + s1; if(temp.find(s2) != string::npos) return true; else return false; } }; //Driver Code Starts. int main() { int t; cin>>t; while(t--) { string s1; string s2; cin>>s1>>s2; Solution obj; cout<<obj.areRotations(s1,s2)<<endl; } return 0; }
true
cf96a80f0220bf0b71b2ed2c0268744b408dce29
C++
palwxc/Lists-and-BigInteger
/MyList.hpp
UTF-8
8,362
3.5625
4
[]
no_license
//Programmer: Phillip LaFrance //Student ID: 12398940 //Intructor: Patrick Taylor //Section: A //Date: 03/19/2018 //File: MyList.hpp //Description: Defines functions for MyList.h /* Define all your MyVector-related functions here. * You do not need to include the h file. * It included this file at the bottom. */ //Node already defined /**Default constructor*/ template <typename T> MyList<T>::MyList() { m_head = new Node<T>(NULL, NULL, NULL); m_head->m_next = m_tail = new Node<T>(NULL, m_head, NULL); m_size = 0; } /**Destructor*/ template <typename T> MyList<T>::~MyList() { Node<T> *curr; while(m_head != NULL) { curr = m_head; m_head = m_head->m_next; delete curr; } } /**Operator =*/ //shallow copy?? template <typename T> MyList<T>& MyList<T>::operator=(const MyList<T> &source) { if(this != &source) { /* m_head = source.m_head; m_tail = source.m_tail; m_size = source.m_size; */ m_head = new Node<T>(NULL, NULL, NULL); m_head->m_next = m_tail = new Node<T>(NULL, m_head, NULL); m_size = 0; Node<T> *curr = source.m_head; while(curr) { T tmp = curr->m_element; push_back(tmp); curr = curr->m_next; } } return *this; } /**Copy constructor*/ //deep copy constructor template <typename T> MyList<T>::MyList(const MyList<T> &source) { if(this != &source) { m_head = new Node<T>(NULL, NULL, NULL); m_head->m_next = m_tail = new Node<T>(NULL, m_head, NULL); m_size = 0; Node<T> *curr = source.m_head; while(curr) { T tmp = curr->m_element; push_back(tmp); curr = curr->m_next; } } } /**front*/ //returns element of head template <typename T> T & MyList<T>::front() { return m_head->m_element; } /**back*/ //returns element of tail template <typename T> T & MyList<T>::back() { return m_tail->m_element; } /**assign*/ //recreates dll with length=count and m_element=value for all nodes template <typename T> void MyList<T>::assign(int count, const T &value) { clear(); for (int i=0; i<count; i++) push_back(value); } /**clear*/ //removes all nodes using pop_back template <typename T> void MyList<T>::clear() { int tmp = m_size; for(auto i = 0; i < tmp; i++) pop_back(); } /**push_front*/ //adds node to front of dll template <typename T> void MyList<T>::push_front(const T &x) { if(m_size == 0) { Node<T> *newNode = new Node<T>(x, NULL, NULL); m_head = newNode; m_tail = newNode; } else { Node<T> *newNode = new Node<T>(x, NULL, m_head); m_head->m_prev=newNode; m_head=newNode; } m_size++; } /**push_back*/ //adds node to back of dll template <typename T> void MyList<T>::push_back(const T &x) { /* if(m_head == NULL) { cout << "m_head" << endl; } Node<T> *newNode = new Node<T>(x, m_tail->m_prev, m_tail); m_tail->m_next = newNode; //delete m_tail?? m_tail = newNode; m_size++; //cout << "push_back complete" << endl; */ if(m_size == 0) { Node<T> *newNode = new Node<T>(x, NULL, NULL); m_head = newNode; m_tail = newNode; } else { Node<T> *newNode = new Node<T>(x, m_tail, NULL); m_tail->m_next=newNode; m_tail=newNode; } m_size++; /* m_size++; Node<T> *newNode = new Node<T>(NULL, NULL, NULL); new (&(newNode->m_element)) T(x); newNode->m_next = NULL; newNode->m_prev = m_tail; if(m_head == NULL && m_tail == NULL) { cout << "first node" << endl; m_head = m_tail = newNode; } else { cout << "new node" << endl; m_tail->m_next = newNode; m_tail = newNode; }*/ } /**pop_back*/ //removes node from back of dll template <typename T> void MyList<T>::pop_back() { /* if(m_size==0) return; Node<T> *tmpNode = m_tail; m_tail = m_tail->m_prev; m_tail->m_next = NULL; delete tmpNode; m_size--; return; */ if(m_size==0) return; if(m_size == 1) { delete m_tail; m_tail = m_head = NULL; m_size--; return; } Node<T> *tmp = m_tail->m_prev; tmp->m_next = NULL; delete m_tail; m_tail = tmp; m_size--; } /**insert*/ //0 is start of dll & m_size is end of dll //therefore, one is the second position in the dll // Simplified version that only takes one position template <typename T> void MyList<T>::insert(int i, const T &x) { if(m_size==0) { cout << "ERROR - erase: no elements in list" << endl; return; } if(i<0 || i>m_size) { cout << "ERROR - erase: invalid number for i" << endl; return; } if(i==m_size) { push_back(x); return; } if(i==0) { push_front(x); return; } Node<T> *pre = m_head; for(int k=0; k<i-1; k++) pre = pre->m_next; Node<T> *aft = pre->m_next; Node<T> *newNode = new Node<T>(x, pre, aft); aft->m_prev = newNode; pre->m_next = newNode; m_size++; } /**remove*/ //removes all occurrences of i template <typename T> void MyList<T>::remove(T i) { if(m_size==0) { cout << "ERROR - erase: no elements in list" << endl; return; } while(m_head->m_element == i) { Node<T> *tmp = m_head->m_next; tmp->m_prev = NULL; delete m_head; m_head = tmp; m_size--; } while(m_tail->m_element == i) { pop_back(); } Node<T> *removedNode = m_head; for (int k=0; k<m_size; k++) { if(removedNode->m_element == i) { Node<T> *tmpNode = removedNode->m_prev; removedNode->m_prev->m_next = removedNode->m_next; removedNode->m_next->m_prev = removedNode->m_prev; delete removedNode; removedNode = tmpNode; m_size--; } removedNode=removedNode->m_next; } } /**erase*/ //erases element at index i //0 is head //m_size-1 is tail template <typename T> void MyList<T>::erase(int i) { if(m_size==0) { cout << "ERROR - erase: no elements in list" << endl; return; } if(i<0 || i>m_size) { cout << "ERROR - erase: invalid number for i" << i << endl; return; } if(i==m_size || i==m_size-1) //because dll is from 0 to m_size-1, yet m_size works for standard list { pop_back(); return; } if(i==0) { Node<T> *tmp = m_head->m_next; tmp->m_prev = NULL; delete m_head; m_head = tmp; m_size--; return; } Node<T> *removedNode = m_head; for(int k=0; k<i; k++) removedNode = removedNode->m_next; //cout << endl << removedNode->m_element << endl << endl; removedNode->m_prev->m_next = removedNode->m_next; removedNode->m_next->m_prev = removedNode->m_prev; delete removedNode; m_size--; } /**reverse*/ //reverses dll by swapping m_next and m_prev for each node, and swapping m_head and m_tail template <typename T> void MyList<T>::reverse() { if(m_size==0 || m_size==1) return; Node<T> *tmp = NULL; Node<T> *curr = m_head; while(curr != NULL) { tmp = curr->m_prev; curr->m_prev = curr->m_next; curr->m_next = tmp; curr = curr->m_prev; } //if(tmp != NULL) m_tail = m_head; m_head = tmp->m_prev; //cout << "reverse has finished" << endl; } /**resize*/ //resizes dll, uses 0 as element if dll is growing template <typename T> void MyList<T>::resize(int count) { if(count<0) { cout << "ERROR - resize: invalid number for count" << endl; return; } if(count < m_size) for (int i=m_size; i>count; i--) pop_back(); else if (count > m_size) for (int i=m_size; i<count; i++) push_back(0); else return; } /**empty*/ //true if empty, false if not empty template <typename T> bool MyList<T>::empty() { if(m_size==0) return true; return false; } /**size*/ template <typename T> int MyList<T>::size() { return m_size; }
true
927660c2b994754382400d178bcab24c3148baa1
C++
livingthdrm/Practice-
/conversions/main.cpp
UTF-8
490
3.234375
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int main(){ double x, y, result1, result2, result3, result4, result5 ; x = 3; y = 4; result1 = abs(x + y); cout << result1 <<endl; result2 = abs(x) + abs(y); cout << result2 << endl; result3 = pow(x, 3)/ x + y; cout << result3 << endl; result4 = sqrt(pow(x, 6) + pow(y, 5)); cout << result4 << endl; result5 = pow((x + sqrt(y)), 7); cout << result5 << endl; return 0; }
true
7b7df483cc1b21ce44cdf9aecd6f9bc721101eae
C++
tangjz/acm-icpc
/self_training/2016-06-18/T.cpp
UTF-8
1,304
2.578125
3
[ "Apache-2.0" ]
permissive
#include <cstdio> #include <algorithm> typedef long long LL; const int maxn = 1001; int t, n, x[maxn], y[maxn], r[maxn], fa[maxn], dis[maxn]; bool vis[maxn]; int find(int x) { if(x == fa[x]) return x; int tmp = fa[x]; fa[x] = find(fa[x]); dis[x] ^= dis[tmp]; return fa[x]; } inline LL sqr(int x) { return (LL)x * x; } void dfs(int u) { vis[u] = 1; for(int i = 1; i <= n; ++i) if(!vis[i] && sqr(x[i] - x[u]) + sqr(y[i] - y[u]) <= sqr(r[i] + r[u])) dfs(i); } int main() { scanf("%d", &t); while(t--) { scanf("%d", &n); for(int i = 1; i <= n; ++i) { scanf("%d%d%d", x + i, y + i, r + i); fa[i] = i; dis[i] = 0; vis[i] = 0; } dfs(1); bool flag = vis[n]; for(int i = 1; i <= n && flag; ++i) { if(!vis[i]) continue; for(int j = i + 1; j <= n && flag; ++j) { if(!vis[j] || sqr(x[i] - x[j]) + sqr(y[i] - y[j]) > sqr(r[i] + r[j])) continue; int u = find(i), v = find(j); if(u == v) flag &= dis[i] != dis[j]; else { fa[u] = v; dis[u] = dis[i] ^ dis[j] ^ 1; } } } if(flag && find(1) == find(n)) { int fz = r[1], fm = r[n], rr = std::__gcd(fz, fm); printf("%d/%d %s\n", fz / rr, fm / rr, dis[1] == dis[n] ? "clockwise" : "counterclockwise"); } else puts("does not rotate"); } return 0; }
true
64925f32bb5b62be824400f5cb4a21617b7d2a82
C++
DavidConsidine/Project-Engine
/ProjectEngine/src/Core/Renderer/OrthographicCamera.cpp
UTF-8
1,164
2.625
3
[ "Apache-2.0" ]
permissive
#include "pepch.h" #include "Core/Renderer/OrthographicCamera.h" #include <glm/gtc/matrix_transform.hpp> namespace ProjectEngine { OrthographicCamera::OrthographicCamera(float left, float right, float bottom, float top) :m_ProjectionMatrix(glm::ortho(left, right, bottom, top, -1.0f, 1.0f)), m_ViewMatrix(1.0f) { m_ViewProjectionMatrix = m_ProjectionMatrix * m_ViewMatrix; } void OrthographicCamera::SetProjection(float left, float right, float bottom, float top) { m_ProjectionMatrix = glm::ortho(left, right, bottom, top, -1.0f, 1.0f); m_ViewProjectionMatrix = m_ProjectionMatrix * m_ViewMatrix; } void OrthographicCamera::SetPosition(const glm::vec3 & position) { m_Position = position; RecalculateViewMatrix(); } void OrthographicCamera::SetRotation(float rotation) { m_Rotation = rotation; RecalculateViewMatrix(); } void OrthographicCamera::RecalculateViewMatrix() { glm::mat4 transform = glm::translate(glm::mat4(1.0f), m_Position) * glm::rotate(glm::mat4(1.0f), glm::radians(m_Rotation), glm::vec3(0, 0, 1)); m_ViewMatrix = glm::inverse(transform); m_ViewProjectionMatrix = m_ProjectionMatrix * m_ViewMatrix; } }
true
23f76d42c710fa9551d1ef87807f052f0a2be109
C++
DocN/CPP-Stack-Implementation
/Stack/Stack/Stack.cpp
UTF-8
1,663
3.96875
4
[]
no_license
#include "Stack.hpp" #include <iostream> using namespace std; Stack::Stack() { //initial position in array count = -1; } /* push - pushes an integer onto the stack Input~ int value - an integer value we're pushing onto the stack return - success or failure boolean */ bool Stack::push(int value) { if (count == (MAX-1)) { cout << "Stack is full!" << endl; return false; } count++; A[count] = value; return true; } int Stack::pop() { if (count > 0) { //check if there are an elements on the stack int popedVal = A[count]; count--; return popedVal; } cout << "no elements to pop off the stack" << endl; return -1; } int const Stack::top() { if (count >= 0) { return A[(count)]; } return -1; } int const Stack::empty() { if (count == -1) { return true; } return false; } int const Stack::full() { if (count == (MAX - 1)) { return true; } return false; } void const Stack::print() { cout << "printing" << endl; cout << "---------------------------" << endl; for (int i = 0; i <= (count); i++) { cout << A[i] << endl; } cout << "---------------------------" << endl; } int * Stack::getStack() { return A; } int Stack::getCount() { return count; } ostream& operator<<(ostream& os, const Stack &obj) { os << "Printing" << endl; os << "-------------------------" << endl; for (int i = 0; i <=obj.count; i++) { os << obj.A[i] << endl; } os << "-------------------------" << endl; return os; } // A simplistic implementation of operator= (do not use) Stack& Stack::operator= (Stack &oldStack) { for (int i = 0; i < oldStack.getCount(); i++) { this->push(oldStack.getStack()[i]); } return *this; }
true
8d7cfdae7fa306d32140788bd5f30917d40c6d04
C++
Sadik/TSS-SIM
/src/Signal.h
UTF-8
1,328
2.65625
3
[]
no_license
#pragma once #include "Gate.h" #include "SAFault.h" #include "SignalValue.h" #include <string> #include <bitset> #include <boost/make_shared.hpp> class Gate; class SAFault; class Signal { public: Signal(); Signal(std::string name, bool isPrimary = false); // Signal(std::string name, Gate* source, Gate* target, bool isPrimary = false); shared_ptr<Signal> clone(); bool isPrimary(); void setIsPrimary(bool isPrimary); std::string name() const; void setName(const std::string &name); shared_ptr<Gate> source() const; void setSource(shared_ptr<Gate> source); shared_ptr<Gate> target() const; void setTarget(shared_ptr<Gate> target); SignalValue value() const; void setValue(SignalValue value); bool initSet() const; void setInitSet(bool init_set); void reset(); SAFault *fault() const; void setFault(SAFault *fault); bool compare(const std::string& name); bool hasTarget() const; bool operator==(const shared_ptr<Signal> signal) const; bool operator==(const std::string &name) const; bool operator==(const Signal& signal) const; private: SAFault* m_fault; std::string m_name; bool m_isPrimary; shared_ptr<Gate> m_source; shared_ptr<Gate> m_target; SignalValue m_value; bool m_init_set; };
true
314ca2d1f8739fdfbbbe01058331e21d967527d9
C++
dattapro001/C-Codes-3G
/task4/number-4.cpp
UTF-8
1,107
3.828125
4
[]
no_license
#include <iostream> using namespace std; struct Node { int data; Node* next; }; Node* deleteNode( Node* head) { if (head == NULL) return NULL; else if (head->next == NULL) { delete head; return NULL; } Node* again = head; while (again->next->next != NULL) again = again->next; delete(again->next); again->next = NULL; return head; } void remove_node(struct Node** head_new, int new_data) { struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_new); (*head_new) = new_node; } int main() { Node* head = NULL; remove_node(&head,10); remove_node(&head,25); remove_node(&head,18); remove_node(&head,37); remove_node(&head,32); remove_node(&head,43); remove_node(&head,18); remove_node(&head,6); remove_node(&head,51); remove_node(&head,44); head = deleteNode(head); for (Node*element = head; element!= NULL; element= element->next) cout <<element->data <<endl; return 0; }
true
dfc68a8da9d75d305b696488f5f559d035757e09
C++
theandrewcosta/Rose
/Rose/src/Rose/Core/Timestep.h
UTF-8
306
3.03125
3
[ "Apache-2.0" ]
permissive
#pragma once namespace Rose { class Timestep { public: Timestep(float time = 0.0f) : time(time) { } float GetSeconds() const { return time; } float GetMiliSeconds() const { return time * 1000.0f; } private: float time; }; }
true
4927076693ad403b7ede7950232074e0138753a0
C++
pmac1965/proteus
/source/display/prFadeManager.h
UTF-8
2,886
2.703125
3
[ "Apache-2.0" ]
permissive
// File: prFadeManager.h /** * Copyright 2014 Paul Michael McNab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "../core/prCoreSystem.h" #include "../core/prTypes.h" // Enum: prFade // The type of fade to update and draw // // - FadeToBlack // - FadeToWhite // - FadeToNormal typedef enum prFade { FadeToBlack, FadeToWhite, FadeToNormal } prFade; // Enum: prFadeColour // The fade colour // // - FadeColourNone // - FadeColourBlack // - FadeColourWhite typedef enum prFadeColour { FadeColourNone, FadeColourBlack, FadeColourWhite } prFadeColour; // Fade type. // This is an internal enumeration and is not documented externally typedef enum prFadeType { FadeTypeNone, FadeTypeColour, FadeTypeNormal } prFadeType; // Class: prFadeManager // Does basic screen fading to/from black, white and normal (No fade) class prFadeManager : public prCoreSystem { public: // Method: prFadeManager // Ctor prFadeManager(); // Method: ~prFadeManager // Dtor ~prFadeManager(); // Method: Update // Updates the fade. // // Parameters: // dt - Delta time void Update(f32 dt); // Method: Draw // Draws the fade. void Draw(); // Method: Start // Starts a fade running. // // Parameters: // fade - The type of fade // runtime - How long should fading take? // // See Also: // <prFade> void Start(prFade fade, f32 runtime); // Method: Isfading // Determines if a fade is running. bool Isfading() const; // Method: IsFadeVisible // Determines if the fade is visible. bool IsFadeVisible() const; // Method: SetBlack // Set fade to black // // Parameters: // in - The fade value // // Notes: // The in value will be clamped to between 0 and 255 void SetBlack(f32 in = 255.0f); // Method: SetWhite // Set fade to white void SetWhite(); // Method: SetNormal // Turns off the fade void SetNormal(); private: // Resets to normal void Reset(); private: prFadeColour colour; prFadeType type; f32 alpha; f32 time; f32 step; bool fading; };
true
53bf63d4c8c691582d338300750ef53d8642f592
C++
MrLolthe1st/disasm
/Antivir/disasm.cpp
UTF-8
36,916
2.703125
3
[]
no_license
/* disasm.cpp - disassembler and other structures. Converts bytes to assembler code. Simply logic recovery to pseudo C-like style. Main convertion to code, that will be analyzed later will be in clogic.cpp. Copyright (C) 2019 Novozhilov Alexandr (MrLolthe1st) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <fstream> #include "disasm.h" //There is main register table, sorted in intel-asm style (000 is ax, 001 is cx and e.g.) std::vector<std::string> reg_names = { "ah", "al", "ax", "eax", "rax", "ch", "cl", "cx", "ecx", "rcx", "dh", "dl", "dx", "edx", "rdx", "bh", "bl", "bx", "ebx", "rbx", "--", "--", "sp", "esp", "rsp", "--", "--", "bp", "ebp", "rbp", "--", "--", "si", "esi", "rsi", "--", "--", "di", "edi", "rdi", "es", "cs", "ss", "ds", "fs", "gs" }; //8-bit registers is excepted std::vector<std::string> reg8_names = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh" }; void disasm_init() { } void init_transitions() { } //Returns a segment register, ds will be replaced with 0x7F character(del). std::string SREG_GET(int f, bool a = false) { if (f == 3 && !a) return std::string(1, 0x7f); //We're return by mod, because sometimes it greater, that table size return (reg_names[((f)+SREG_OFFSET) % reg_names.size()]); } //Checks if char C is string-char bool is_string(char c) { return (c == ' ' || c == '\n' || c == '\t' || c == '\b' || (c >= 'a'&&c <= 'z') || (c >= 'A'&&c <= 'Z')); } std::vector<std::string> bytes_names_by_op_size = { "-", "b", "w", "d" }; std::vector<int> addr_overrides = { 32, 16, 32 }; std::vector<int> addr_overrides_1 = { 32, 16, 64 }; //Computes a logarithm of power of two int log2c(int a) { int cnt = 0; while (a > 1) { cnt++; a /= 2; } return cnt; } //Converts U 8-byte to Signed BTS-byte number long long conv(unsigned long long a, int bts) { if (bts == 1) return (char)a; else if (bts == 2) return (short)a; else if (bts == 4) return (int)a; else return (long long)a; } //Returns string of char x std::string get_string(char x) { // string class has a constructor // that allows us to specify size of // string as first parameter and character // to be filled in given size as second // parameter. if (x == '\n') return "\\n"; if (x == '\b') return "\\b"; if (x == '\t') return "\\t"; std::string s(1, x); return s; } //O(1) access to dword, qword, and etc. std::vector<std::string> bytes_names(65); //O(1) convertation byte to hex-representation std::string table("0123456789ABCDEF"); std::string get_hex(unsigned char c) { std::string a; a.push_back(table[(int)c >> 4]); a.push_back(table[(int)c & 15]); return a; } //Returns intel-style register name std::string get_reg(int op_size, int ndx) { if (op_size == 8) return reg8_names[ndx]; else return REG_GET(op_size, ndx); } //Crutch: mov [es:bp + 3], ... std::vector<int> map_tab = { 0, 0, 0, 0, 6, 7, 5, 3 }; std::string get_reg1(int op_size, int ndx) { if (op_size == 8) return reg8_names[ndx]; else { //Crutch: mov [bp + si], ... if (ndx == 0) return "bx+si"; if (ndx == 1) return "bx+di"; if (ndx == 2) return "bp+si"; if (ndx == 3) return "bp+di"; return REG_GET(op_size, map_tab[ndx]); } } //Parses representation of operands, provided next byte in ifstream. //Gets opcode, and masks it with mask. //There are 3 situations: //reg, reg ax, bx //reg, mem ax, [0xDEAD] //reg, reg_mem ax, [bp + si] std::string parse_ops(int mode, int seg_reg, int op_size, int addr_size, std::ifstream &fl, int cnt, int dir, int mask, bool use = false, bool use_sizes = true, int o_s = 0) { std::string res = ""; unsigned char op_code = 0; //Read an opcode desc and regs fl.read((char*)&op_code, 1); op_code &= mask; std::string regs[2]; regs[0] = get_reg(op_size, op_code & 0b111); regs[1] = get_reg(op_size, (op_code & 0b111000) >> 3); if ((op_code & 0b11000000) == 0b11000000) { int strt = cnt - 1; if (dir == 1) strt = 0; for (int i = strt; i > -1 && i < cnt; i += dir) res += regs[i] + ", "; res = res.substr(0, res.length() - 2); } else { int off_cnt = (op_code & 0b11000000) >> 6, offset = 0; if ((op_code & 0b111) != 0x06 - mode || addr_size != (1 << (mode + 4)) || off_cnt > 0) { //[es:si] std::string op1 = ""; if (use_sizes)op1 += bytes_names[op_size]; else op1 += bytes_names[o_s / 2]; op1 += " [" + SREG_GET(seg_reg) + ":"; if (addr_size == 16) op1 += get_reg1(addr_size, op_code & 0b111); else { op1 += get_reg(addr_size, op_code & 0b111); if ((op_code & 0b111) == 4) fl.seekg(1, fl.cur); } if (off_cnt > 0) fl.read((char*)&offset, off_cnt); if (conv(offset, off_cnt) > 0) op1 += "+"; if (offset != 0) op1 += std::to_string(conv(offset, off_cnt)); op1 += "]"; if (cnt > 1) { if (dir == 1) res += op1 + ", " + regs[1]; else res += regs[1] + ", " + op1; } else { res += op1; } } else //[es:addr] { unsigned long long addr = 0; fl.read((char*)&addr, (1 << (mode + 4)) / 8); std::string op1 = ""; if (use_sizes)op1 += bytes_names[op_size]; else op1 += bytes_names[o_s / 2]; op1 += " [" + SREG_GET(seg_reg) + ":" + std::to_string(addr) + "]"; if (cnt > 1) { if (dir == 1) res += op1 + ", " + regs[1]; else res += regs[1] + ", " + op1; } else res += op1; } } if (use) return res; return res + "\n"; } //Disassembles the code std::string disasm_code(std::string filename, int mode) { bytes_names[8] = "byte"; bytes_names[16] = "word"; bytes_names[32] = "dword"; bytes_names[64] = "qword"; std::string result = "; That code was generated by MrLolthe1st disassembler v0.0.1\n"; std::ifstream fl(filename, std::ios::binary); if (!fl.is_open()) { return "1"; } unsigned char * buffer = (unsigned char*)malloc(8); int seg_reg = 3, op_size = 1 << (mode + 4), addr_size = 1 << (mode + 4); unsigned char last_byte = 0; std::string rep_pr = ""; long long cur = fl.tellg(); bool read = true; while (1) { last_byte = *buffer; int lb = 0; unsigned long long a = 0; if (!read) { cur = fl.tellg(); read = true; } fl.read((char*)buffer, 1); if (fl.eof()) break; if (*buffer >= 0x91 && *buffer < 0x98) { result += "xchg eax, "; result += get_reg(op_size, *buffer - 0x90) + "\n"; goto ennnnd; } if (*buffer >= 0x40 && *buffer <= 0x4F) { if (!(*buffer & 0x8))result += "inc "; else result += "dec "; result += get_reg(op_size, *buffer&(~8) - 0x40) + "\n"; goto ennnnd; } if (*buffer >= 0x50 && *buffer <= 0x5F) { if (!(*buffer & 0x8))result += "push "; else result += "pop "; result += get_reg(op_size, *buffer&(~8) - 0x50) + "\n"; goto ennnnd; } if (*buffer >= 0xB0 && *buffer <= 0xBF) { if (!(*buffer & 0x8)) { op_size = 8; }; fl.read((char*)&a, op_size / 8); result += "mov " + get_reg(op_size, *buffer&(~8) - 0xB0) + ", " + std::to_string(a) + "\n"; goto ennnnd; } switch (*buffer) { case 0x0: result += "add " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, 1, 0xFF); break; case 0x1: result += "add " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, 1, 0xFF); break; case 0x2: result += "add " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x3: result += "add " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x4: fl.read((char*)&a, 1); result += "add al, " + std::to_string(a) + "\n"; break; case 0x5: fl.read((char*)&a, op_size / 8); result += "add " + get_reg(op_size, 0) + ", " + std::to_string(a) + "\n"; break; case 0x6: result += "push es\n"; break; case 0x7: result += "pop es\n"; break; case 0x0 + 0x008: result += "or " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, 1, 0xFF); break; case 0x1 + 0x008: result += "or " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, 1, 0xFF); break; case 0x2 + 0x008: result += "or " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x3 + 0x008: result += "or " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x4 + 0x008: fl.read((char*)&a, 1); result += "or al, " + std::to_string(a) + "\n"; break; case 0x5 + 0x008: fl.read((char*)&a, op_size / 8); result += "or " + get_reg(op_size, 0) + ", " + std::to_string(a) + "\n"; break; case 0xE: result += "push cs\n"; break; case 0x0 + 0x010: result += "adc " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, 1, 0xFF); break; case 0x1 + 0x010: result += "adc " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, 1, 0xFF); break; case 0x2 + 0x010: result += "adc " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x3 + 0x010: result += "adc " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x4 + 0x010: fl.read((char*)&a, 1); result += "adc al, " + std::to_string(a) + "\n"; break; case 0x5 + 0x010: fl.read((char*)&a, op_size / 8); result += "adc " + get_reg(op_size, 0) + ", " + std::to_string(a) + "\n"; break; case 0x16: result += "push ss\n"; break; case 0x17: result += "pop ss\n"; break; case 0x0 + 0x018: result += "sbb " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, 1, 0xFF); break; case 0x1 + 0x018: result += "sbb " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, 1, 0xFF); break; case 0x2 + 0x018: result += "sbb " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x3 + 0x018: result += "sbb " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x4 + 0x018: fl.read((char*)&a, 1); result += "sbb al, " + std::to_string(a) + "\n"; break; case 0x5 + 0x018: fl.read((char*)&a, op_size / 8); result += "sbb " + get_reg(op_size, 0) + ", " + std::to_string(a) + "\n"; break; case 0x1E: result += "push ds\n"; break; case 0x1F: result += "pop ds\n"; break; case 0x0 + 0x020: result += "and " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, 1, 0xFF); break; case 0x1 + 0x020: result += "and " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, 1, 0xFF); break; case 0x2 + 0x020: result += "and " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x3 + 0x020: result += "and " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x4 + 0x020: fl.read((char*)&a, 1); result += "and al, " + std::to_string(a) + "\n"; break; case 0x5 + 0x020: fl.read((char*)&a, op_size / 8); result += "and " + get_reg(op_size, 0) + ", " + std::to_string(a) + "\n"; break; case 0x26: // ES Override seg_reg = 0; result += ";ES Override\n"; continue; case 0x0 + 0x028: result += "sub " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, 1, 0xFF); break; case 0x1 + 0x028: result += "sub " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, 1, 0xFF); break; case 0x2 + 0x028: result += "sub " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x3 + 0x028: result += "sub " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x4 + 0x028: fl.read((char*)&a, 1); result += "sub al, " + std::to_string(a) + "\n"; break; case 0x5 + 0x028: fl.read((char*)&a, op_size / 8); result += "sub " + get_reg(op_size, 0) + ", " + std::to_string(a) + "\n"; break; case 0x2E: // CS Override seg_reg = 1; result += ";CS Override\n"; continue; case 0x0 + 0x030: result += "xor " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, 1, 0xFF); break; case 0x1 + 0x030: result += "xor " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, 1, 0xFF); break; case 0x2 + 0x030: result += "xor " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x3 + 0x030: result += "xor " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x4 + 0x030: fl.read((char*)&a, 1); result += "xor al, " + std::to_string(a) + "\n"; break; case 0x5 + 0x030: fl.read((char*)&a, op_size / 8); result += "xor " + get_reg(op_size, 0) + ", " + std::to_string(a) + "\n"; break; case 0x36: // SS Override seg_reg = 2; result += ";SS Override\n"; continue; case 0x0 + 0x038: result += "cmp " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, 1, 0xFF); break; case 0x1 + 0x038: result += "cmp " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, 1, 0xFF); break; case 0x2 + 0x038: result += "cmp " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x3 + 0x038: result += "cmp " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x4 + 0x038: fl.read((char*)&a, 1); result += "cmp al, " + std::to_string(a) + "\n"; break; case 0x5 + 0x038: fl.read((char*)&a, op_size / 8); result += "cmp " + get_reg(op_size, 0) + ", " + std::to_string(a) + "\n"; break; case 0x3E: // DS Override seg_reg = 3; result += ";DS Override\n"; continue; case 0x48: op_size = 64; result += ";Opcode size override 64\n"; continue; case 0x60: if (op_size == 32) result += "pushad\n"; else result += "pusha\n"; break; case 0x61: if (op_size == 32) result += "popad\n"; else result += "popa\n"; break; case 0x64: // FS Override seg_reg = 4; result += ";FS Override\n"; break; case 0x65: // GS Override seg_reg = 5; result += ";GS Override\n"; break; case 0x66: op_size = addr_overrides[mode]; result += ";Opcode size override\n"; continue; case 0x67: addr_size = addr_overrides[mode]; result += ";Address size override\n"; continue; case 0x68: fl.read((char*)&a, op_size / 8); result += "push " + bytes_names[op_size] + " " + std::to_string(a) + "\n"; break; case 0x6A: fl.read((char*)&a, 1); result += "push byte " + std::to_string(a) + "\n"; break; case 0x6C: result += rep_pr + "insb\n"; rep_pr = ""; break; case 0x6D: result += rep_pr + "ins" + bytes_names_by_op_size[log2c(op_size) - 2] + "\n"; rep_pr = ""; break; case 0x6E: result += rep_pr + "outsb\n"; rep_pr = ""; break; case 0x6F: result += rep_pr + "outs" + bytes_names_by_op_size[log2c(op_size) - 2] + "\n"; rep_pr = ""; break; case 0x70: fl.read((char*)&a, 1); result += "jo short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x71: fl.read((char*)&a, 1); result += "jno short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x72: fl.read((char*)&a, 1); result += "jc short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x73: fl.read((char*)&a, 1); result += "jnc short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x74: fl.read((char*)&a, 1); result += "jz short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x75: fl.read((char*)&a, 1); result += "jnz short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x76: fl.read((char*)&a, 1); result += "jna short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x77: fl.read((char*)&a, 1); result += "ja short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x78: fl.read((char*)&a, 1); result += "js short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x79: fl.read((char*)&a, 1); result += "jns short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x7A: fl.read((char*)&a, 1); result += "jpe short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x7B: fl.read((char*)&a, 1); result += "jpo short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x7C: fl.read((char*)&a, 1); result += "jl short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x7D: fl.read((char*)&a, 1); result += "jnl short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x7E: fl.read((char*)&a, 1); result += "jng short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x7F: fl.read((char*)&a, 1); result += "jg short "; if (conv(a, 1) > 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0x80: op_size = 8; fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "add "; break; case 1: result += "or "; break; case 2: result += "adc "; break; case 3: result += "sbb "; break; case 4: result += "and "; break; case 5: result += "sub "; break; case 6: result += "xor "; break; case 7: result += "cmp "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, true) + ", "; a = 0; fl.read((char*)&a, 1); result += std::to_string(a) + "\n"; break; case 0x81: fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "add "; break; case 1: result += "or "; break; case 2: result += "adc "; break; case 3: result += "sbb "; break; case 4: result += "and "; break; case 5: result += "sub "; break; case 6: result += "xor "; break; case 7: result += "cmp "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, true) + ", "; a = 0; fl.read((char*)&a, op_size / 8); result += std::to_string(a) + "\n"; break; case 0x82: op_size = 8; fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "add "; break; case 1: result += "or "; break; case 2: result += "adc "; break; case 3: result += "sbb "; break; case 4: result += "and "; break; case 5: result += "sub "; break; case 6: result += "xor "; break; case 7: result += "cmp "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, true) + ", "; a = 0; fl.read((char*)&a, 1); result += std::to_string(a) + "\n"; break; case 0x83: fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "add "; break; case 1: result += "or "; break; case 2: result += "adc "; break; case 3: result += "sbb "; break; case 4: result += "and "; break; case 5: result += "sub "; break; case 6: result += "xor "; break; case 7: result += "cmp "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, true) + ", "; a = 0; fl.read((char*)&a, 1); result += std::to_string(a) + "\n"; break; case 0x84: result += "test " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x85: result += "test " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x86: result += "xchg " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x87: result += "xchg " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x88: result += "mov " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, 1, 0xFF); break; case 0x89: result += "mov " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, 1, 0xFF); break; case 0x8A: result += "mov " + parse_ops(mode, seg_reg, 8, addr_size, fl, 2, -1, 0xFF); break; case 0x8B: result += "mov " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF); break; case 0x8C: fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); result += "mov " + parse_ops(mode, seg_reg, 16, addr_size, fl, 1, 1, 0xFF, 1) + ", " + SREG_GET((a & 0b111000) >> 3, true) + "\n"; break; case 0x8D: result += "lea " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF, false, false, 0); break; case 0x8E: fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); result += "mov " + SREG_GET((a & 0b111000) >> 3, true) + ", " + parse_ops(mode, seg_reg, 16, addr_size, fl, 1, 1, 0xFF); break; case 0x8F: result += "pop " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0xFF); break; case 0x90: result += "nop\n"; break; case 0x98: if (op_size == 16) result += "cbw\n"; else if (op_size == 32) result += "cwde\n"; else if (op_size == 64) result += "cdqe\n"; break; case 0x99: if (op_size == 16) result += "cwd\n"; else if (op_size == 32) result += "cdq\n"; else if (op_size == 64) result += "cqo\n"; break; case 0x9B: result += "wait\n"; break; case 0x9C: result += "pushf\n"; break; case 0x9D: result += "popf\n"; break; case 0x9E: result += "sahf\n"; break; case 0x9F: result += "lahf\n"; break; case 0xA0: fl.read((char*)&a, op_size / 8); result += "mov al, [" + SREG_GET(seg_reg) + ":" + std::to_string(a) + "]\n"; break; case 0xA1: fl.read((char*)&a, op_size / 8); result += "mov " + get_reg(op_size, 0) + ", [" + SREG_GET(seg_reg) + ":" + std::to_string(a) + "]\n"; break; case 0xA2: fl.read((char*)&a, op_size / 8); result += "mov [" + SREG_GET(seg_reg) + ":" + std::to_string(a) + "], al\n"; break; case 0xA3: fl.read((char*)&a, op_size / 8); result += "mov [" + SREG_GET(seg_reg) + ":" + std::to_string(a) + "], " + get_reg(op_size, 0) + "\n"; break; case 0xA4: result += rep_pr + "movsb\n"; break; case 0xA5: result += rep_pr + "movs" + bytes_names_by_op_size[log2c(op_size) - 2] + "\n"; rep_pr = ""; break; case 0xA6: result += rep_pr + "cmpsb\n"; rep_pr = ""; break; case 0xA7: result += rep_pr + "cmps" + bytes_names_by_op_size[log2c(op_size) - 2] + "\n"; rep_pr = ""; break; case 0xA8: fl.read((char*)&a, op_size / 8); result += "test al, [" + SREG_GET(seg_reg) + ":" + std::to_string(a) + "]\n"; break; case 0xA9: fl.read((char*)&a, op_size / 8); result += "test " + get_reg(op_size, 0) + ", [" + SREG_GET(seg_reg) + ":" + std::to_string(a) + "]\n"; break; case 0xAA: result += rep_pr + "stosb\n"; rep_pr = ""; break; case 0xAB: result += rep_pr + "stos" + bytes_names_by_op_size[log2c(op_size) - 2] + "\n"; rep_pr = ""; break; case 0xAC: result += rep_pr + "lodsb\n"; rep_pr = ""; break; case 0xAD: result += rep_pr + "lods" + bytes_names_by_op_size[log2c(op_size) - 2] + "\n"; rep_pr = ""; break; case 0xAE: result += rep_pr + "scasb\n"; rep_pr = ""; break; case 0xAF: result += rep_pr + "scas" + bytes_names_by_op_size[log2c(op_size) - 2] + "\n"; rep_pr = ""; break; case 0xC0: op_size = 8; fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "rol "; break; case 1: result += "ror "; break; case 2: result += "rcl "; break; case 3: result += "rcr "; break; case 4: result += "shl "; break; case 5: result += "shr "; break; case 6: result += "shl "; break; case 7: result += "sar "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, true) + ", "; a = 0; fl.read((char*)&a, 1); result += std::to_string(a) + "\n"; break; case 0xC1: fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "rol "; break; case 1: result += "ror "; break; case 2: result += "rcl "; break; case 3: result += "rcr "; break; case 4: result += "shl "; break; case 5: result += "shr "; break; case 6: result += "shl "; break; case 7: result += "sar "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, true) + ", "; a = 0; fl.read((char*)&a, 1); result += std::to_string(a) + "\n"; break; case 0xC2: result += "retn\n"; break; case 0xC3: result += "ret\n"; break; case 0xCB: result += "retf\n"; break; case 0xCC: result += "int 3\n"; break; case 0xCD: fl.read((char*)buffer, 1); result += "int " + std::to_string(*buffer) + "\n"; break; case 0xCF: if (op_size == 64) result += "iretq\n"; else if (op_size == 32) result += "iretd\n"; else if (op_size == 16) result += "iretb\n"; break; case 0xD0: op_size = 8; fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "rol "; break; case 1: result += "ror "; break; case 2: result += "rcl "; break; case 3: result += "rcr "; break; case 4: result += "shl "; break; case 5: result += "shr "; break; case 6: result += "shl "; break; case 7: result += "sar "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, true) + ", "; a = 1; result += std::to_string(a) + "\n"; break; case 0xD1: fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "rol "; break; case 1: result += "ror "; break; case 2: result += "rcl "; break; case 3: result += "rcr "; break; case 4: result += "shl "; break; case 5: result += "shr "; break; case 6: result += "shl "; break; case 7: result += "sar "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, true) + ", "; a = 1; result += std::to_string(a) + "\n"; break; case 0xD2: op_size = 8; fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "rol "; break; case 1: result += "ror "; break; case 2: result += "rcl "; break; case 3: result += "rcr "; break; case 4: result += "shl "; break; case 5: result += "shr "; break; case 6: result += "shl "; break; case 7: result += "sar "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, true) + ", "; result += "cl\n"; break; case 0xD3: fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "rol "; break; case 1: result += "ror "; break; case 2: result += "rcl "; break; case 3: result += "rcr "; break; case 4: result += "shl "; break; case 5: result += "shr "; break; case 6: result += "shl "; break; case 7: result += "sar "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, true) + ", "; result += "cl\n"; break; case 0xE0: fl.read((char*)&a, 1); result += "loopnz near "; if (conv(a, 1) >= 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0xE1: fl.read((char*)&a, 1); result += "loopz near "; if (conv(a, 1) >= 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0xE2: fl.read((char*)&a, 1); result += "loop near "; if (conv(a, 1) >= 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0xE3: fl.read((char*)&a, 1); result += "JECXZ near "; if (conv(a, 1) >= 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0xE4: fl.read((char*)&a, 1); result += "in al, " + std::to_string(a) + "\n"; break; case 0xE5: fl.read((char*)&a, 1); result += "in " + REG_GET(op_size, 0) + ", " + std::to_string(a) + "\n"; break; case 0xE6: fl.read((char*)&a, 1); result += "out " + std::to_string(a) + ", al\n"; break; case 0xE7: fl.read((char*)&a, 1); result += "out " + std::to_string(a) + ", " + REG_GET(op_size, 0) + "\n"; break; case 0xE8: fl.read((char*)&a, mode * 2 + 2); result += "call "; if (conv(a + cur + mode * 2 + 3, mode * 2 + 2) >= 0) result += "+"; result += std::to_string(conv(a + cur + mode * 2 + 3, mode * 2 + 2)) + "\n"; break; case 0xE9: fl.read((char*)&a, mode * 2 + 2); result += "jmp "; if (conv(a, mode * 2 + 2) >= 0) result += "+"; result += std::to_string(conv(a + 1 + mode * 2 + 2 + cur, mode * 2 + 2)) + "\n"; break; case 0xEA: fl.read((char*)&a, mode * 2 + 2); result += "jmp "; fl.read((char*)&lb, 2); result += std::to_string((lb)) + ":" + std::to_string(a) + "\n"; break; case 0xEB: fl.read((char*)&a, 1); result += "jmp short "; if (conv(a, 1) >= 0) result += "+"; result += std::to_string(conv(a + 2 + cur, 1)) + "\n"; break; case 0xEC: result += "in al, dx\n"; break; case 0xED: result += "in " + REG_GET(op_size, 0) + ", dx\n"; break; case 0xEE: result += "out dx, al\n"; break; case 0xEF: result += "out dx, " + REG_GET(op_size, 0) + "\n"; break; case 0xF2: rep_pr = "repnz "; continue; case 0xF3: rep_pr = "repz "; continue; case 0xF4: result += "hlt\n"; break; case 0xF5: result += "cmc\n"; break; case 0xF6: op_size = 8; fl.read((char*)&a, 1); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "test "; fl.read((char*)&a, op_size / 8); fl.seekg(-(op_size / 8), fl.cur); rep_pr = ", " + std::to_string(a) + "\n"; a = 10; break; case 1: result += "test "; fl.read((char*)&a, op_size / 8); fl.seekg(-(op_size / 8), fl.cur); rep_pr = ", " + std::to_string(a) + "\n"; a = 10; break; case 2: result += "not "; break; case 3: result += "neg "; break; case 4: result += "mul "; break; case 5: result += "imul "; break; case 6: result += "div "; break; case 7: result += "idiv "; break; default: break; } fl.seekg(-1, fl.cur); result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, a == 10) + rep_pr; if (a == 10) fl.seekg((op_size / 8), fl.cur); rep_pr = ""; break; case 0xF7: fl.read((char*)&a, 1); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "test "; fl.read((char*)&a, op_size / 8); fl.seekg(-(op_size / 8), fl.cur); rep_pr = ", " + std::to_string(a) + "\n"; a = 10; break; case 1: result += "test "; fl.read((char*)&a, op_size / 8); fl.seekg(-(op_size / 8), fl.cur); rep_pr = ", " + std::to_string(a) + "\n"; a = 10; break; case 2: result += "not "; break; case 3: result += "neg "; break; case 4: result += "mul "; break; case 5: result += "imul "; break; case 6: result += "div "; break; case 7: result += "idiv "; break; default: break; } fl.seekg(-1, fl.cur); result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111, a == 10) + rep_pr; if (a == 10) fl.seekg((op_size / 8), fl.cur); rep_pr = ""; break; case 0xF8: result += "clc\n"; break; case 0xF9: result += "stc\n"; break; case 0xFA: result += "cli\n"; break; case 0xFB: result += "sti\n"; break; case 0xFC: result += "cld\n"; break; case 0xFD: result += "std\n"; break; case 0xFE: fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "inc "; break; case 1: result += "dec "; break; case 2: result += "call "; break; case 3: result += "callf "; break; case 4: result += "jmp "; break; case 5: result += "jmpf "; break; case 6: result += "push "; break; default: break; } result += parse_ops(mode, seg_reg, 8, addr_size, fl, 1, 1, 0b11000111); break; case 0xFF: fl.read((char*)&a, 1); fl.seekg(-1, fl.cur); a &= 0b00111000; a >>= 3; switch (a) { case 0: result += "inc "; break; case 1: result += "dec "; break; case 2: result += "call "; break; case 3: result += "callf "; break; case 4: result += "jmp "; break; case 5: result += "jmpf "; break; case 6: result += "push "; break; default: break; } result += parse_ops(mode, seg_reg, op_size, addr_size, fl, 1, 1, 0b11000111); break; case 0x0F: fl.read((char*)buffer, 1); switch (*buffer) { case 0xb6: result += "movzx " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF, false, false, 16); break; case 0xb7: result += "movzx " + parse_ops(mode, seg_reg, op_size, addr_size, fl, 2, -1, 0xFF, false, false, 32); break; default: break; } break; default: if (op_size != (1 << (mode + 4)) || rep_pr == "") result += "db " + std::to_string(last_byte) + "\n"; result += "db " + std::to_string(*buffer) + "\n"; seg_reg = 3; break; }; ennnnd: result += ";+" + std::to_string(cur) + " : "; long long cr = fl.tellg(); fl.seekg(cur, fl.beg); for (; cur < cr; cur++) { unsigned char a; fl.read((char*)&a, 1); result += get_hex(a); } result += "\n"; seg_reg = 3; op_size = (1 << (mode + 4)); addr_size = (1 << (mode + 4)); read = false; } std::string q; q.resize(result.length()); int z = 0; for (size_t i = 0; i < result.length(); i++) { if (result[i] == 0x7F) { i += 1; continue; } q[z++] = result[i]; } q.resize(z); free(buffer); return q; } char az[256] = { 0 }; bool prepared = false; void prepare() { for (int i = 'a'; i <= 'z'; i++) az[i] = i - 'a' + 10; for (int i = 'A'; i <= 'Z'; i++) az[i] = i - 'A' + 10; for (int i = '0'; i <= '1'; i++) az[i] = i - '0'; } //Builds a flexible structure from generated assembler code. std::vector<el> build_structure(const std::string& asms) { if (!prepared) prepare(); std::vector<el> res; size_t idx = 0; while (1) { /* ; comment \n ... ; comment \n command \n ;+offset : HEX REPRESENTATION OF CODE \n */ if (idx >= asms.length() - 1) break; while (asms[idx] == ';') { while (asms[++idx] != '\n'); idx++; } size_t idx1 = idx; while (asms[++idx] != '\n'); std::string cmd = asms.substr(idx1, idx - idx1); idx++; el e; e.cmd = cmd; idx += 2; idx1 = idx; while (asms[++idx] != ' '); std::string offs = asms.substr(idx1, idx - idx1); idx++; while (asms[++idx] != ' '); idx++; idx1 = idx; while (asms[++idx] != '\n'); std::string bts = asms.substr(idx1, idx - idx1); ++idx; for (size_t i = 0; i < bts.length() / 2; i++) { unsigned char z = (az[(int)bts[i * 2]] * 16) + (az[(int)bts[i * 2 + 1]]); e.bytes.push_back(z); } e.offset = atoi(offs.c_str()); res.push_back(e); } return res; }
true
d17d309c8e27bd4ae314d00e62d4d3f9b5348927
C++
Andreea15B/Facultate_an_I
/Semestru I/IP/Proiect TABL2/inversa_matrice.cpp
UTF-8
1,816
2.796875
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; ifstream fin("inversa.in"); int calcul_det(int **matr,int n); int **calcul_minor(int **matr,int lin,int col,int n); int **calcul_inversa(int **matr,int n); int main() { int i,j,det,n; fin>>n; int **matr=new int*[n]; for(i=0;i<n;i++) matr[i]=new int[n]; for(i=0;i<n;i++) for(j=0;j<n;j++) fin>>matr[i][j]; det=calcul_det(matr,n); cout<<det<<endl; if(det==0) cout<<"Nu e inversabila."; else { int **inversa=calcul_inversa(matr,n); for(i=0;i<n;i++){ for(j=0;j<n;j++) { if(inversa[i][j]%det==0) cout<<inversa[i][j]/det<<" "; else if(inversa[i][j]<0 && det<0) cout<<-inversa[i][j]<<"/"<<-det<<" "; else cout<<inversa[i][j]<<"/"<<det<<" "; } cout<<endl; } } return 0; } int **calcul_inversa(int **matr,int n) { int **rez=new int *[n],i,j,**minor,k,p; for(i=0;i<n;i++) rez[i]=new int[n]; for(i=0;i<n;i++) { for(j=0;j<n;j++) { minor=calcul_minor(matr,j,i,n); rez[i][j]=((i+j)%2?1:-1)*calcul_det(minor,n-1); } } return rez; } int calcul_det(int **matr,int n) { //recursiv if(n==1) return matr[0][0]; int i,s=0; for(i=0;i<n;i++) s+=matr[0][i]*(i%2?1:-1)*calcul_det(calcul_minor(matr,0,i,n),n-1); return s; } int **calcul_minor(int **matr,int lin,int col,int n) { int i,j,**a=new int*[n-1]; for(i=0;i<n-1;i++) a[i]=new int[n-1]; for(i=0;i<n-1;i++) { for(j=0;j<n-1;j++) { if(i<lin) { if(j<col) a[i][j]=matr[i][j]; else a[i][j]=matr[i][j+1]; } else if(j<col) a[i][j]=matr[i+1][j]; else a[i][j]=matr[i+1][j+1]; } } return a; }
true
71f9f20ee2f74839575b3cd6a45884bffe16429b
C++
avnyaswanth/DS_AND_ALGO
/ds_Algo/number_theory/binary_exponentiation.cpp
UTF-8
288
3.546875
4
[]
no_license
#include<iostream> using namespace std; void a_power_b(int a,int b) { int res = 1; while(b!=0) { if(b % 2 != 0) res = res*a , b--; a *= a , b /= 2; } cout<<res; } int main() { int a,b; cout<<"Enter base and exponent"; cin>>a>>b; a_power_b(a,b); }
true
e9f68ec9cfd9ea80c6fd2f6a94ec183e02b35c56
C++
dekonoplyov/try_stuff
/xlib/mouse_move.cpp
UTF-8
1,912
3.03125
3
[ "MIT" ]
permissive
#include <linux/uinput.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> /* emit function is identical to of the first example */ void emit(int fd, int type, int code, int val) { struct input_event ie; ie.type = type; ie.code = code; ie.value = val; /* timestamp values below are ignored */ ie.time.tv_sec = 0; ie.time.tv_usec = 0; write(fd, &ie, sizeof(ie)); } int main(void) { struct uinput_setup usetup; int i = 50; int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK); /* enable mouse button left and relative events */ ioctl(fd, UI_SET_EVBIT, EV_KEY); ioctl(fd, UI_SET_KEYBIT, BTN_LEFT); ioctl(fd, UI_SET_EVBIT, EV_REL); ioctl(fd, UI_SET_RELBIT, REL_X); ioctl(fd, UI_SET_RELBIT, REL_Y); memset(&usetup, 0, sizeof(usetup)); usetup.id.bustype = BUS_USB; usetup.id.vendor = 0x1234; /* sample vendor */ usetup.id.product = 0x5678; /* sample product */ strcpy(usetup.name, "Example device"); ioctl(fd, UI_DEV_SETUP, &usetup); ioctl(fd, UI_DEV_CREATE); /* * On UI_DEV_CREATE the kernel will create the device node for this * device. We are inserting a pause here so that userspace has time * to detect, initialize the new device, and can start listening to * the event, otherwise it will not notice the event we are about * to send. This pause is only needed in our example code! */ sleep(1); /* Move the mouse diagonally, 5 units per axis */ while (i--) { emit(fd, EV_REL, REL_X, 10); emit(fd, EV_REL, REL_Y, 10); emit(fd, EV_SYN, SYN_REPORT, 0); usleep(15000); } /* * Give userspace some time to read the events before we destroy the * device with UI_DEV_DESTOY. */ sleep(1); ioctl(fd, UI_DEV_DESTROY); close(fd); return 0; }
true
211b018c6cf4084fca87331b244bfb713524cc40
C++
vei123/PATTestAdvanced
/C++/1023趣味数字.cpp
UTF-8
1,141
2.984375
3
[]
no_license
#include<iostream> #include<string> #include<unordered_map> #include<algorithm> using namespace std; void delprezeros(string& s) { while (!s.empty() && s[0] == '0') s.erase(0, 1); } string stradd(string a, string b) { string res; int al = a.size(), bl = b.size(); int* cc = new int[max(al, bl) + 1](); int* aa = new int[max(al, bl) + 1](); int* bb = new int[max(al, bl) + 1](); reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); for (int i = 0; i < a.size(); i++) aa[i] = (int)(a[i] - '0'); for (int i = 0; i < b.size(); i++) bb[i] = (int)(b[i] - '0'); for (int i = 0; i < max(al, bl) + 1; i++) { cc[i + 1] += (aa[i] + bb[i] + cc[i]) / 10; cc[i] = (aa[i] + bb[i] + cc[i]) % 10; res.push_back((char)cc[i] + '0'); } reverse(res.begin(), res.end()); delprezeros(res); return res; } int main() { ios::sync_with_stdio(0); string s, t, v; cin >> s; v = t = stradd(s, s); unordered_map<char, int> umap; for (char c : s) umap[c]++; for (char c : t) umap[c]--; for (auto p : umap) { if (p.second) { cout << "No\n"; cout << v; return 0; } } cout << "Yes\n"; cout << v; return 0; }
true
2625b6ef728b84376dd2f84e8aa260a9a1308f16
C++
igorgsh/SmartHouse
/SmartHomeBoard/utils.cpp
WINDOWS-1251
643
2.5625
3
[]
no_license
// // // #include "utils.h" // , , // extern int __bss_end; extern void *__brkval; // , (RAM) int memoryFree() { int freeValue; if ((int)__brkval == 0) freeValue = ((int)&freeValue) - ((int)&__bss_end); else freeValue = ((int)&freeValue) - ((int)__brkval); return freeValue; } //String PrintIP(IPAddress addr) { // return String(addr[0]) + "." + String(addr[1]) + "." + String(addr[2]) + "." + String(addr[3]); //}
true
a9213a9c949f99dd0e288f5c04cb955b5a930260
C++
JChristensen/piXBee
/main.cpp
UTF-8
8,486
2.609375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#include <iostream> #include <string.h> #include "XBee.h" using namespace std; class myXBee : public XBee { public: myXBee( XBeeAddress64 dest = XBeeAddress64(0x0, 0x0) ); //default destination is the coordinator bool read(void); void transmit(void); XBeeAddress64 m_destAddr; // destination address struct payload_t { uint16_t seq; // sequence number uint16_t ack; // if acknowledging a received packet, sender's sequence number, else zero uint32_t time; // time of transmission char message[32]; } m_payload; private: ZBTxStatusResponse m_zbStat; ModemStatusResponse m_zbMSR; ZBRxResponse m_zbRX; ZBTxRequest m_zbTX; uint32_t m_msTX; // time of last transmission uint16_t sendSeq; // sending sequence number. }; myXBee::myXBee(XBeeAddress64 dest) { m_destAddr = dest; } //process incoming traffic from the XBee bool myXBee::read() { uint8_t delyStat; //TX delivery status uint8_t dscyStat; //TX discovery status uint8_t txRetry; //TX retrycount uint8_t modemStat; //modem status response bool packetReceived(false); uint32_t ms = millis(); readPacket(); if ( getResponse().isAvailable() ) { switch (getResponse().getApiId()) //what kind of packet did we get? { case ZB_TX_STATUS_RESPONSE: //transmit status for packets we've sent getResponse().getZBTxStatusResponse(m_zbStat); delyStat = m_zbStat.getDeliveryStatus(); dscyStat = m_zbStat.getDiscoveryStatus(); txRetry = m_zbStat.getTxRetryCount(); switch (delyStat) { case SUCCESS: //digitalWrite(LED_BUILTIN, LOW); cout << ms << " XBee TX OK " << ms - m_msTX << "ms RETRY="; cout << static_cast<unsigned int>(txRetry) << " DSCY=" << static_cast<unsigned int>(dscyStat) << endl; break; default: cout << ms << " XBee TX FAIL " << ms - m_msTX << "ms RETRY="; cout << txRetry << " DELY=" << static_cast<unsigned int>(delyStat) << " DSCY=" << static_cast<unsigned int>(dscyStat) << endl; break; } break; case ZB_RX_RESPONSE: //rx data packet getResponse().getZBRxResponse(m_zbRX); //get the received data switch (m_zbRX.getOption() & 0x01) //check ack bit only { case ZB_PACKET_ACKNOWLEDGED: { uint8_t dataLen = m_zbRX.getDataLength(); if ( dataLen > sizeof(m_payload) ) { cout << ms << "Received data too long (" << dataLen << "), truncated to " << sizeof(m_payload) << endl; dataLen = sizeof(m_payload); } uint8_t* p = (uint8_t*) &m_payload; for (uint8_t i=0; i<dataLen; i++) //copy the received data to our buffer { *p++ = m_zbRX.getData(i); } //process the received data m_destAddr = m_zbRX.getRemoteAddress64(); //save the sender's address packetReceived = true; if (m_payload.ack == 0) { cout << endl << ms << " Received message seq " << m_payload.seq << " sent at " << m_payload.time; cout << " \"" << m_payload.message << "\"" << endl; } else { cout << endl << ms << " Received ack for seq " << m_payload.ack << " sent at " << m_payload.time; cout << " \"" << m_payload.message << "\"" << endl; } break; } default: cout << endl << ms << " XBee RX no ACK\n"; //packet received and not ACKed break; } break; case MODEM_STATUS_RESPONSE: //XBee administrative messages getResponse().getModemStatusResponse(m_zbMSR); modemStat = m_zbMSR.getStatus(); cout << ms << " "; switch (modemStat) { case HARDWARE_RESET: cout << "XBee HW reset\n"; break; case ASSOCIATED: cout << "XBee associated\n"; break; case DISASSOCIATED: cout << "XBee disassociated\n"; break; default: cout << "XBee modem status 0x" << hex << static_cast<unsigned int>(modemStat) << endl; break; } break; default: //something else we were not expecting cout << ms << " XBee unexpected frame\n"; break; } } return packetReceived; } //Send an XBee data packet. //Our data packet is defined as follows: //Byte 0-3: Transmission time from millis() //Bytes 4-19: Text message. void myXBee::transmit(void) { m_zbTX.setAddress64(m_destAddr); //build the tx request packet m_zbTX.setAddress16(0xFFFE); m_zbTX.setPayload((uint8_t*)&m_payload); m_zbTX.setPayloadLength(sizeof(m_payload)); m_msTX = millis(); m_payload.time = m_msTX; m_payload.seq = ++sendSeq; send(m_zbTX); //digitalWrite(LED_BUILTIN, HIGH); cout << endl << m_msTX << " XBee TX\n"; } // global variables myXBee xb; const char *device = "/dev/ttyUSB0"; const speed_t baudrate(B9600); //const uint8_t xbeeReset(7); // logic 0 on this pin resets the XBee //const uint8_t xbeeFunction(8); // ground this pin for transmitter/router, leave open for receiver/coordinator bool isTransmitter(false); // these variables can be modified to adjust message timing and sending of ack packets by the receiver const uint32_t txInterval(10000); // transmission interval, milliseconds const bool sendAckMessage(true); // set to true for receiver to send ack packets const uint32_t ackDelayTime(1000); // delay time before sending ack packet void setup(void) { //pinMode(xbeeFunction, INPUT_PULLUP); //pinMode(LED_BUILTIN, OUTPUT); //Serial.begin(baudrate); int beginStatus = Serial.begin(device, baudrate, 0); if (beginStatus == 0) { cerr << "Serial device opened.\n"; } else { cerr << "Serial device open failed, status: " << beginStatus << endl; exit(1); } xb.begin(Serial); //Serial << F( "\n" __FILE__ " " __DATE__ " " __TIME__ "\n" ); //isTransmitter = !digitalRead(xbeeFunction); if (isTransmitter) { cout << "\nTransmitter (XBee Router)\n"; } else { cout << "\nReceiver (XBee Coordinator)\n"; } //pinMode(xbeeReset, OUTPUT); //delay(10); //digitalWrite(xbeeReset, HIGH); } void loop(void) { static uint32_t msLast; static uint32_t msRecv; static bool ackPending(false); if (xb.read() && sendAckMessage) // if we received a data packet, prepare to respond to it { msRecv = millis(); ackPending = true; } if ( isTransmitter && (millis() - msLast >= txInterval) ) { msLast += txInterval; xb.m_payload.ack = 0; // transmitter message, not an ack strcpy(xb.m_payload.message, "Hello from Arduino!"); xb.transmit(); } else if (!isTransmitter) { if (ackPending && (millis() - msRecv >= ackDelayTime)) { xb.m_payload.ack = xb.m_payload.seq; strcpy(xb.m_payload.message, "Received packet"); xb.transmit(); ackPending = false; } } } int g_signal(0); void sigintHandler(int s) { g_signal = s; } int main() { // catch Ctrl-C (SIGINT) struct sigaction sig; sig.sa_handler = sigintHandler; sigaction(SIGINT, &sig, NULL); setup(); while (!g_signal) loop(); int endStatus = Serial.end(); if (endStatus == 0) { cout << "\nSerial device closed." << endl; } else { cerr << "Serial device close failed, status: " << endStatus << endl; } return 0; }
true
756af31d74470648ca25d58bfd58ae5f018e620f
C++
eshlykov/junk
/school-31/coding/olymp/1810numB.cpp
UTF-8
751
2.6875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; vector<vector<int> > mc; vector<int> pra; vector<int> fr; vector<int> cl; void dfs(int v, int st) { cl[v] = true; for (int i = 0; i < mc[v].size(); ++i) { fr[mc[v][i]] = st; dfs(mc[v][i], st); } } int main() { int n, x; cin >> n; mc.resize(n + 1); fr.resize(n + 1); cl.resize(n + 1); for (int i = 1; i <= n; ++i) { cin >> x; mc[x].push_back(i); cl[x] = false; if (x == 0) { pra.push_back(i); fr[x] = 0; } } for (int i = 0; i < pra.size(); ++i) { dfs(pra[i], pra[i]); } for (int i = 1; i <= n; ++i) cout << fr[i] << '\n'; return 0; }
true
10bc4553756060d3744d56a1a2285f32e6f387fc
C++
OptoCloud/VRC-BundleExtractor
/filereadsource.cpp
UTF-8
1,020
2.78125
3
[]
no_license
#include "filereadsource.h" VRCE::IReadSource::Type VRCE::FileReadSource::InterfaceType() const { return IReadSource::Type::File; } VRCE::FileReadSource::FileReadSource(const std::filesystem::path& path) : VRCE::IReadSource() , m_stream(std::make_shared<std::ifstream>(path)) { } bool VRCE::FileReadSource::isValid() const { return m_stream->is_open(); } std::uint8_t VRCE::FileReadSource::get() { return (std::uint8_t)m_stream->get(); } void VRCE::FileReadSource::read(std::uint8_t* buf, std::size_t size) { m_stream->read((char*)buf, size); } std::string VRCE::FileReadSource::readString() { std::string value; std::getline(*m_stream, value, '\0'); return value; } void VRCE::FileReadSource::seekBeg(std::ptrdiff_t offset) { m_stream->seekg(offset, std::ios::beg); } void VRCE::FileReadSource::seekRel(std::ptrdiff_t offset) { m_stream->seekg(offset, std::ios::cur); } std::ptrdiff_t VRCE::FileReadSource::position() const { return (std::ptrdiff_t)m_stream->tellg(); }
true
8b522f84ac91aa7439f8c6063989f131686a3afc
C++
H-Shen/Collection_of_my_coding_practice
/Leetcode/1203/1203.cpp
UTF-8
3,111
2.765625
3
[]
no_license
vector<unordered_set<int>> AL; namespace Topo { int n; vector<int> vis, result; bool dfs(int u) { vis[u] = -1; for (const auto &v : AL[u]) { if (vis[v] < 0) { return false; } else if (vis[v] == 0) { if (!dfs(v)) { return false; } } } vis[u] = 1; result.emplace_back(u); return true; } bool topo() { n = (int)AL.size(); vector<int>().swap(vis); vector<int>().swap(result); vis.resize(n); for (int i = 0; i < n; ++i) { if (vis[i] == 0) { if (!dfs(i)) { return false; } } } reverse(result.begin(),result.end()); return true; } void reset() { n = (int)AL.size(); vector<int>().swap(vis); vis.resize(n); } bool topo2(vector<int>& vec) { vector<int>().swap(result); for (auto &i : vec) { if (vis[i] == 0) { if (!dfs(i)) { return false; } } } reverse(result.begin(),result.end()); return true; } } class Solution { public: vector<int> sortItems(int n, int m, vector<int>& group, vector<vector<int>>& beforeItems) { int maxGroupId = m; for (int i = 0; i < n; ++i) { if (group[i] == -1) { group[i] = maxGroupId; ++maxGroupId; } } int u, v; // toposort groups decltype(AL)().swap(AL); AL.resize(maxGroupId); for (int i = 0; i < n; ++i) { v = group[i]; for (const auto &j : beforeItems[i]) { u = group[j]; if (v != u) { AL[u].insert(v); } } } if (!Topo::topo()) { return vector<int>(); } vector<int> ans(n); auto iter = ans.begin(); vector<int> g; g.swap(Topo::result); vector<vector<int>> vec(maxGroupId); // toposort in each group for (int j = 0; j < n; ++j) { vec[group[j]].emplace_back(j); } decltype(AL)().swap(AL); AL.resize(n); Topo::reset(); for (auto &elements : vec) { for (auto &element : elements) { v = element; for (auto &i : beforeItems[element]) { u = i; if (group[v] == group[u]) { AL[u].insert(v); } } } if (!Topo::topo2(elements)) { return vector<int>(); } else { swap(elements, Topo::result); } } // output for (const auto &i : g) { for (const auto &j : vec[i]) { *iter = j; ++iter; } } return ans; } };
true
10603625fa00ede383f1a6d1c59ba0fa6fa67fff
C++
rohitbhatghare/c-c-
/even_odd_array.cpp
UTF-8
634
3.3125
3
[]
no_license
#include <iostream> using namespace std; int main() { int a[24]; int n,i; cout<<"enter the elements in array"<<endl; cin>>n; cout<<"enter the 1st array element"<<endl; for (i =0 ; i < n; i++) { cin>>a[i]; } cout<<"the even numbers are "<< a[i] <<endl; for (i =0 ; i < n; i++) { if ( a[i] % 2 == 0) cout<<a[i]; } cout<<"the odd numbers are "<< a[i] <<endl; for(i=0;i<n;i++) { if ( a[i] % 2 == 1) cout<<a[i]; } return 0; }
true
3d53a0845ce31a4a0b93711798fd5a947d8af853
C++
zhandb/tegrenys
/TGSystem/TGRefCounter.h
WINDOWS-1251
4,195
2.90625
3
[]
no_license
#ifndef TGRefCounter_h__ #define TGRefCounter_h__ //----------------------------------------------------------------------------- #define uint32_t uint //----------------------------------------------------------------------------- #include "windows.h" //----------------------------------------------------------------------------- /** */ class TGReferenceCounter { public: //! . TGReferenceCounter(); //! . virtual ~TGReferenceCounter(void); //! . . void AddRef(); //! . . virtual void DelRef(); //! . void PushDestroyMonitor(); //! -. QT , virtual TGReferenceCounter* GetReferenceCounter(); //! long GetReferenceCount() const; protected: #ifdef _DEBUG bool CanBeDestructed; #endif private: long ReferenceCount; //!< bool UseMonitor; //!< }; template <typename T> class TGRefCountPtr { public: //! TGRefCountPtr(T* object = NULL) : Object(object ? (T*)((TGReferenceCounter*)object)->GetReferenceCounter() : NULL) { AddRef(); } //! TGRefCountPtr(const TGRefCountPtr& left) { this->Object = left.Object; AddRef(); } //SN_TODO( T*); //! TGRefCountPtr& operator=(const TGRefCountPtr& left) { if (this->Object != left.Object) { DelRef(); this->Object = left.Object; AddRef(); } return *this; } //! virtual ~TGRefCountPtr(void) { DelRef(); } //! void AddRef() const { if (Object) ((TGReferenceCounter*)Object)->AddRef(); } //! void DelRef() const { if (Object) ((TGReferenceCounter*)Object)->DelRef(); } //! void Reset() { DelRef(); Object = NULL; } //! T* operator->() const { return Object; } //! const T* GetData() const { return Object; } T* GetData() { return Object; } //! template<typename A> operator TGRefCountPtr<A>() const { return check_cast<A*>(Object); } //! T* operator T*() const { return Object; } bool operator < (const TGRefCountPtr& left) const { return Object < left.Object; } private: T* Object; //!< , }; //----------------------------------------------------------------------------- #define TG_REFC_PTR(T) \ class T; \ typedef TGRefCountPtr<T> P##T;\ typedef const TGRefCountPtr<T> PC##T; //----------------------------------------------------------------------------- #endif // TGRefCounter_h__
true
9e57a769ae45da2c0ee30e3ca6cc8c713413b999
C++
D34Dspy/warz-client
/External/NaturalMotion/common/XMD/src/XMD/CollisionSphere.cpp
UTF-8
3,744
2.515625
3
[]
no_license
//---------------------------------------------------------------------------------------------------------------------- /// \file CollisionSphere.cpp /// \note (C) Copyright 2003-2005 Robert Bateman. All rights reserved. //---------------------------------------------------------------------------------------------------------------------- #include "XMD/CollisionSphere.h" #include "XMD/FileIO.h" namespace XMD { //---------------------------------------------------------------------------------------------------------------------- XCollisionSphere::XCollisionSphere(XModel* pmod) : XCollisionObject(pmod),m_Radius(1.0f) { } //---------------------------------------------------------------------------------------------------------------------- XCollisionSphere::~XCollisionSphere() { } //---------------------------------------------------------------------------------------------------------------------- XFn::Type XCollisionSphere::GetApiType() const { return XFn::CollisionSphere; } //---------------------------------------------------------------------------------------------------------------------- XU32 XCollisionSphere::GetDataSize() const { return XCollisionObject::GetDataSize() + sizeof(XReal); } //---------------------------------------------------------------------------------------------------------------------- XBase* XCollisionSphere::GetFn(XFn::Type type) { if(XFn::CollisionSphere==type) return (XCollisionSphere*)this; return XCollisionObject::GetFn(type); } //---------------------------------------------------------------------------------------------------------------------- const XBase* XCollisionSphere::GetFn(XFn::Type type) const { if(XFn::CollisionSphere==type) return (const XCollisionSphere*)this; return XCollisionObject::GetFn(type); } //---------------------------------------------------------------------------------------------------------------------- bool XCollisionSphere::NodeDeath(XId id) { return XCollisionObject::NodeDeath(id); } //---------------------------------------------------------------------------------------------------------------------- void XCollisionSphere::PreDelete(XIdSet& extra_nodes) { XCollisionObject::PreDelete(extra_nodes); } //---------------------------------------------------------------------------------------------------------------------- XReal XCollisionSphere::GetRadius() const { return m_Radius; } //---------------------------------------------------------------------------------------------------------------------- void XCollisionSphere::SetRadius(const XReal v) { m_Radius = v; } //---------------------------------------------------------------------------------------------------------------------- bool XCollisionSphere::ReadChunk(std::istream& ifs) { READ_CHECK("radius",ifs); ifs >> m_Radius; return ifs.good(); } //---------------------------------------------------------------------------------------------------------------------- bool XCollisionSphere::WriteChunk(std::ostream& ofs) { ofs << "\tradius " << m_Radius << "\n"; return ofs.good(); } //---------------------------------------------------------------------------------------------------------------------- bool XCollisionSphere::DoData(XFileIO& io) { DUMPER(XCollisionSphere); IO_CHECK( XCollisionObject::DoData(io) ); IO_CHECK( io.DoData(&m_Radius) ); DPARAM( m_Radius ); return true; } //---------------------------------------------------------------------------------------------------------------------- void XCollisionSphere::DoCopy(const XBase* rhs) { const XCollisionSphere* cb = rhs->HasFn<XCollisionSphere>(); XMD_ASSERT(cb); m_Radius = cb->m_Radius; XCollisionObject::DoCopy(cb); } }
true
dc8bde4acdb9ef26e40e2bd5c0867eef75ca36b3
C++
Ashwinbicholiya/cpp-Practice
/Practice on functions/numbercover.cpp
UTF-8
1,080
3.484375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int BinarytoDecimal(int n) { int ans = 0; int x = 1; while (n > 0) { int y = n % 10; ans += x * y; x *= 2; n /= 10; } return ans; } int OctaltoDecimal(int n) { int ans = 0; int x = 1; while (n > 0) { int y = n % 10; ans += x * y; x *= 8; n /= 10; } return ans; } int HexaDecimaltoDecimal(string n) { int ans = 0; int x = 1; int s = n.size(); for (int i = s - 1; i >= 0; i--) { if (n[i] >= '0' && n[i] <= '9') { ans += x * (n[i] - '0'); } else if (n[i] >= 'A' && n[i] <= 'F') { ans+=x*(n[i] - 'A' + 10); } x*=16; } return ans; } int DecimaltoBinary(int n){ int x =1; int ans = 0; while (x<=n) x*=2; x/=2; while(x>0) { int lastdigit =n/x; n-=lastdigit*x; x/=2; ans=ans*10+lastdigit; } return ans; } int main() { int n; cin >> n; //cout<<BinarytoDecimal(n)<<endl; //cout<<OctaltoDecimal(n)<<endl; //cout << HexaDecimaltoDecimal(n) << endl; cout<< DecimaltoBinary(n)<<endl; }
true
167e27db3c04b4194348194e05c6f84f9afd74c6
C++
g4workshop/gamelet
/gamelet/player.h
UTF-8
2,537
2.671875
3
[]
no_license
// // Player_manager.h // Player manager // // Created by Dawen Rie on 12-4-9. // Copyright (c) 2012年 G4 Workshop. All rights reserved. // #ifndef gamelet_player_manager_h #define gamelet_player_manager_h #include <event2/util.h> #include <string> #include <map> #include <set> #include <list> #include "cmd.h" class bufferevent; class evbuffer; class Group; // Player connection data struct Player{ Player(); void setPlayerId(std::string &playerid); const char *getPlayerId() { return playerid.c_str(); } const char *desc(); bool isNPC(); bool attributeMatch(Player *other); void handleCommand(); void forwardToPlayer(std::string &userid, short length); void forwardToGroup(short length); void login(Command &cmd); void logout(Command &cmd); void match(Command &cmd); void leaveMatch(Command &cmd); // The bufferedevent for this player. struct bufferevent *bev; // The recieved command buffer. struct evbuffer *commandBuffer; // is the player belong a game group Group *group; std::string description; // player attributes //std::string userid; std::string passwd; std::string gameid; bool NPC; time_t loginTime; std::map<std::string, std::string> attributes; private: std::string playerid; }; struct Group{ Group(); const char *desc(); bool add(Player *player); bool remove(Player *player); bool isEmpty(); // if it's enough player(included NPC) return true bool isEnoughToPlay(); // if is enough player(not inclued NPC) return true; bool isEnoughPlayer(); bool isFull(); void notify(unsigned short cmd); void notifyPlayerMatched(); void startGame(); void stopGame(); std::string description; std::list<Player*> players; unsigned int minimum; unsigned int maxima; time_t createdTime; }; class PlayerManager{ public: static PlayerManager &instance(); Player *newPlayer(struct event_base *base, evutil_socket_t fd); void deletePlayer(Player *player); Group *newGroup(int min, int max); void deleteGroup(Group *group); bool login(Player *player, std::string &userid, std::string &passwd); bool logout(Player *player); Group *matchGroup(Player* player, unsigned int min, unsigned int max); bool leaveGroup(Player *player); private: PlayerManager(); ~PlayerManager(); private: std::set<Player *> players; std::set<Group *> groups; }; #endif
true
e86bd1445e4fd818a4eb79646e7b33b56f35ef19
C++
alexandraback/datacollection
/solutions_1595491_1/C++/piyapan/q2.cpp
UTF-8
517
2.65625
3
[]
no_license
#include<stdio.h> #include<iostream> using namespace std; int main() { int N, i, j, d, p, m, S, max, tmp; cin >> m; for(i=0;i<m;i++) { cin >> N; cin >> S; cin >> p; max = 0; for(j=0;j<N;j++) { cin >> d; if((d%3==0 && d/3 >= p) || (d>0 && d%3!=0 && d/3+1 >= p)) { max++; } else if(d>=2 && d <= 28 && (d-2)/3+2 >= p && S > 0) { //cout << "x" << d << " "; max++; S--; } } cout << "Case #" << i+1 << ": " << max << endl; } }
true
7a6ca76ee06443122d2cdf8995a5a7f3ff4c5eaf
C++
GhulamMustafaGM/C-Programming
/05-C++ Programming/Threedigits.cpp
UTF-8
140
2.828125
3
[]
no_license
// Three digit number #include <iostream> int main() { int n; std::cin >> n; std::cout << n / 100 + n / 10 % 10 + n % 10; }
true
14a19a35e751474c35316f5218d2291c3abea43f
C++
endyul/my-leetcode-solution
/Remove-Element.cpp
UTF-8
283
3.03125
3
[ "MIT" ]
permissive
class Solution { public: int removeElement(int A[], int n, int elem) { int cnt = 0; for (int i = n-1; i >= 0; i--) { if(A[i] == elem){ A[i] = A[n-1-cnt]; cnt++; } } return n - cnt; } };
true
b5f02810f7905662edd992b4f3bad9895d4448a8
C++
rajneeshkumar146/pepcoding-Batches
/2019/levelUp302/lecture_001_Recursion/extraClass.cpp
UTF-8
3,182
3.015625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; void laxcigraphicalOrder(int st, int end) { if (st > end) return; cout << st << endl; for (int i = 0; i < 10; i++) if (st * 10 + i < end) laxcigraphicalOrder(st * 10 + i, end); else break; if (st + 1 < 10) laxcigraphicalOrder(st + 1, end); } int numTilePossibilities(string &str) { if (str.length() == 0) { return 0; } int count = 0; // vector<bool> vis(26, false); int vis = 0; for (int i = 0; i < str.length(); i++) { // int chIdx = str[i] - 'A'; int mask = 1 << (str[i] - 'A'); // if (vis[chIdx] == false) if ((vis & mask) == 0) { vis ^= mask; string nstr = str.substr(0, i) + str.substr(i + 1); count += numTilePossibilities(nstr) + 1; } } return count; } // List<String> res; // public List<String> generateParenthesis(int n) { // res=new ArrayList<>(); // generateParenthesis("",0,0,n); // return res; // } // // public void generateParenthesis(String ans,int OB,int CB,int n){ // if(OB+CB==2*n) { // res.add(ans); // return; // } // // if(OB<n) // generateParenthesis(ans+"(", OB+1,CB,n); // if(CB<OB) // generateParenthesis(ans+")", OB,CB+1,n); // // } int board[13][5] = {0}; int originalBoard[13][5] = {0}; int dir[3] = {-1, 0, 1}; int maxCoin; void Blast(int row) { for (int i = row, count = 0; count < 5 && i >= 0; count++, i--) { for (int j = 0; j < 5; j++) { if (board[i][j] == 2) board[i][j] = 0; } } } void unBlast(int row) { for (int i = row, count = 0; count < 5 && i >= 0; count++, i--) { for (int j = 0; j < 5; j++) { if (originalBoard[i][j] == 2) board[i][j] = 2; } } } void oldDaysSolu(int n, int c, int coins) { // if(coins == -1) return; if (n == 0 || coins == -1) { maxCoin = max(maxCoin, coins); return; } for (int d = 0; d < 3; d++) { int y = c + dir[d]; if (y >= 0 && y < 5) { if (board[n - 1][y] == 1) coins += 1; if (board[n - 1][y] == 2) coins -= 1; oldDaysSolu(n - 1, y, coins); if (board[n - 1][y] == 1) coins -= 1; if (board[n - 1][y] == 2) coins += 1; } } } void oldDays_() { int n; cin >> n; for (int i = 0; i < n; i++) { for (int j = 0; j < 5; j++) { int a; cin >> a; originalBoard[i][j] = board[i][j] = a; } } maxCoin = -1; for (int row = n - 1; row >= 4; row--) { Blast(row); oldDaysSolu(n, 2, 0); unBlast(row); } cout << maxCoin << endl; } void oldDays() { int t; cin >> t; while (t-- > 0) oldDays_(); } int main() { // laxcigraphicalOrder(1, 1005); return 0; }
true
650032d111e76637e0ccd1e7a2c597e993a8891f
C++
ShreyJ1729/Competitive-Programming
/Project Euler/solutions/P26.cpp
UTF-8
1,605
3.4375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <set> using std::cout; using std::endl; int len_cycle(int n) { // std::vector<int> quotient; std::vector<int> rems; int d = 1; bool isRepeat = false; while (true) { // check to see if d == 0 (division terminated) or if rems has a repeat --> repeating decmimal if (d == 0) { break; } std::set<int> rems_sorted(rems.begin(), rems.end()); if (!(rems.size() == rems_sorted.size())) { isRepeat = true; break; } d *= 10; rems.push_back(d); while (d < n) { d *= 10; // quotient.push_back(0); rems.push_back(d); } // quotient.push_back(d/n); d = d % n; } // for (int i : quotient) // { // cout << i << " "; // } // cout << endl; // for (int i : rems) // { // cout << i << " "; // } if (isRepeat) { int repeat = rems[rems.size()-1]; for (int i = rems.size() - 2; i >= 0; i--) { if (rems[i] == repeat) { return (rems.size() - 1) - i; } } } else { return 0; } } int main() { int d = 2; int max_len = 0; int clen; for (int i = 2; i < 1000; i++) { clen = len_cycle(i); if (clen > max_len) { max_len = clen; d = i; } } cout << d << endl; // cout << max_len << endl; }
true
5c366db636c651fdaf5302b1bbe3203614a0c87f
C++
VerhelstJoris/DirectX_Framework
/Engine/PostProcessingShader.h
UTF-8
1,863
2.515625
3
[]
no_license
////////////// // INCLUDES // ////////////// #include <d3d11.h> #include <d3dx10math.h> #include <d3dx11async.h> #include <fstream> using namespace std; //////////////////////////////////////////////////////////////////////////////// // Class name: PostProcessingShader //////////////////////////////////////////////////////////////////////////////// class PostProcessingShader { private: struct ConstantBufferType { D3DXMATRIX world; D3DXMATRIX view; D3DXMATRIX projection; }; struct ConstantDataBuffer { float amountOfColumns; float vignetteStrength; float time; float speed; float distortionStrength; float padding0; float padding1; float padding2; }; public: PostProcessingShader(); PostProcessingShader(const PostProcessingShader&); ~PostProcessingShader(); bool Initialize(ID3D11Device*, HWND); void Shutdown(); bool Render(ID3D11DeviceContext*, int, D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, ID3D11ShaderResourceView*); void IncrementCount(bool); void IncrementSpeed(bool); void IncrementBrightness(bool); void IncrementDistortion(bool); void UpdateTimer(float); void Toggle(); bool GetToggledOn() { return m_ToggledOn; }; private: bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*); void ShutdownShader(); void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*); bool SetShaderParameters(ID3D11DeviceContext*, D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, ID3D11ShaderResourceView*); void RenderShader(ID3D11DeviceContext*, int); private: ID3D11VertexShader* m_vertexShader; ID3D11PixelShader* m_pixelShader; ID3D11InputLayout* m_layout; ID3D11Buffer* m_constantBuffer; ID3D11Buffer* m_DataBuffer; ID3D11SamplerState* m_sampleState; // float m_Count = 256; float m_Time = 0.0f; float m_Speed = 4.0f; float m_Brightness = 4.0f; float m_DistortionStrength =1.5f; bool m_ToggledOn = true; };
true
358424f440350bb918942a522c08f67837316a05
C++
te-bachi/libines
/src/util/sort/Comparator.cxx
UTF-8
1,258
2.515625
3
[]
no_license
#include "jam/util/sort/Comparator.hxx" #include "jam/lang/Class.hxx" using namespace jam::util::sort; using namespace jam::lang; const Class Comparator::klass = Class::newInstance("jam::util::sort::Comparator"); /*** Reference ***/ Comparator::Comparator() : Object() { // } Comparator::Comparator(const Reference& ref) : Object(ref) { // } Comparator::Comparator(Implementation* impl) : Object(impl) { // } Comparator::~Comparator() { // } ComparatorImpl& Comparator::operator*() { return (ComparatorImpl&) Object::operator*(); } ComparatorImpl* Comparator::operator->() { return (ComparatorImpl*) Object::operator->(); } const Comparator& Comparator::operator=(const Reference& ref) { return (Comparator&) Object::operator=(ref); } const Comparator& Comparator::operator=(Implementation* impl) { return (Comparator&) Object::operator=(impl); } /*** Implementation ***/ ComparatorImpl::ComparatorImpl() { } ComparatorImpl::~ComparatorImpl() { } ComparatorImpl::ComparatorImpl(const ComparatorImpl& copy) { // } #ifdef __DEBUG__ const char* ComparatorImpl::debugClassName() { return "jam::util::sort::Comparator"; } #endif Class ComparatorImpl::getClass() { return Comparator::klass; }
true
b19b525c1c59cd20a251e1e2a5a9822a07d7e48c
C++
AlleCrossCosti/4.-Pulsanti-e-interuttori
/Pulsanti e interrutori 1.cpp
UTF-8
674
3.265625
3
[]
no_license
// Pin del pulsante const byte PIN_PULSANTE = 2; // Pin del LED const byte PIN_LED = 13; // Variabile di stato del pulsante byte statoPulsante = 0; void setup () { pinMode (PIN_LED, OUTPUT) ; // LED in OUTPUT pinMode (PIN_PULSANTE, INPUT) ; // pulsante in INPUT } void loop () { // Leggo il pulsante e memorizzo lo stato statoPulsante = digitalRead (PIN_PULSANTE); // se il pin del pulsante è HIGH (premuto)... if (statoPulsante == HIGH) { // Accendo il LED digitalWrtite (PIN_LED, HIGH) ; } // Altrimenti... else { // Spengo il LED digitalWrite (PIN_LED, LOW) ; } delay (10) ; }
true
444160f18bc0cda92fdc5066cfb8806808edaec7
C++
sunshinekai/Exercise
/day_13/day_13/day_13.cpp
GB18030
7,261
3.3125
3
[]
no_license
/* ѡ⣺ 1. ǶʹifʱCԹ涨else(C) A ֮ǰͬλõif B ֮ǰif C ֮ǰҲelseif D ֮ǰĵһif עif elseʹù 2. ³(C) #include <stdio.h> int main() { int i,a[10]; for(i=9;i>=0;i--) a[i]=10-i; printf("%d%d%d",a[2],a[5],a[8]); return 0; } A 258 B 741 C 852 D 369 עa[10] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 3. 벻ȷhelloѡΪ(B) #include <stdio.h> #include <stdlib.h> struct str_t{ long long len; char data[32]; }; struct data1_t{ long long len; int data[2]; }; struct data2_t{ long long len; char *data[1]; }; struct data3_t{ long long len; void *data[]; }; int main(void) { struct str_t str; memset((void*)&str, 0, sizeof(struct str_t)); str.len = sizeof(struct str_t) - sizeof(int); snprintf(str.data, str.len, "hello");//VSΪ_snprintf ____________________________________; ____________________________________; return 0; } A struct data3_t *pData=(struct data3_t*)&str; printf("data:%s%s\n",str.data,(char*)(&(pData->data[0]))); B struct data2_t *pData=(struct data2_t*)&str; printf("data:%s%s\n",str.data,(char*)(pData->data[0])); C struct data1_t *pData=(struct data1_t*)&str;printf("data:%s%s\n",str.data,(char*)(pData->data)); D struct str_t *pData=(struct str_t*)&str; printf("data:%s%s\n",str.data,(char*)(pData->data)); עBɶδ 4. һγ(A) #include<iostream> using namespace std; class B { public : B() { cout << "default constructor" << " "; } ~B() { cout << "destructed" << " "; } B(int i) : data(i) { cout << "constructed by parameter" << data << " "; } private : int data; }; B Play(B b) { return b; } int main(int argc, char *argv[]) { B temp = Play(5); return 0; } A constructed by parameter5 destructed destructed B constructed by parameter5 destructed C default constructor" constructed by parameter5 destructed D default constructor" constructed by parameter5 destructed destructed ע ִΪ ִf(5) ൱baif((B)5) 5ʱΪf ù캯B(int i) ӡ constructed by parameter 5 ˳f ʱ ӡ destructed ֵt1 Ĭϸƹ캯 ִf(t1) t1ʱΪf Ĭϸƹ캯 */ /* 1. ӣhttps://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677?tpId=37&&tqId=21297&rp=1&ru=/activity/oj&qru=/ta/huawei/question-ranking  xcopy /s c:\ d:\ £ 1xcopy 2ַ/s 3ַc:\ 4: ַd:\ дһʵֽи 1.ָΪո 2.áIJмпո񣬲ܽΪxcopy /s C:\program files d:\ʱ Ȼ43ӦַC:\program filesC:\programעʱҪȥŲǶ 3. 4.ֲ֤Ҫ */ /* ͨԿո˫ΪͳƲ˫ţͨflag֤˫е ո */ #include <iostream> #include <string> using namespace std; int main() { string str; while (getline(cin, str)) { int count = 0; //ȼ for (int i = 0; i < str.size(); i++) { if (str[i] == ' ') count++; //˫ţֱһ˫Ž if (str[i] == '"') { do { i++; } while (str[i] != '"'); } } // ԿոոȲ1 cout << count + 1 << endl; //flagʾǷ˫ţ0ʾ˫ //˫еĿոҪӡ //ıflagֵ˫ſʹflagԭ int flag = 1; for (int i = 0; i < str.size(); i++) { //˫ţflagͨΪ0һ˫ţflagΪ1 if (str[i] == '"') flag ^= 1; //˫źͨո񲻴ӡ if (str[i] != ' ' && str[i] != '"') cout << str[i]; //˫еĿոҪӡ if (str[i] == ' ' && (!flag)) cout << str[i]; //˫֮Ŀոͻ if (str[i] == ' ' && flag) cout << endl; } cout << endl; } return 0; } /* 2. ӣhttps://www.nowcoder.com/practice/4284c8f466814870bae7799a07d49ec8?tpId=85&&tqId=29852&rp=1&ru=/activity/oj&qru=/ta/2017test/question-ranking Сһʯ·ǰÿʯϴ1űΪ123....... ʯ·ҪĹǰС׵ǰڵıΪK ʯ壬С׵ֻǰKһԼ(1K) K+X(XΪKһ1ͱԼ)λá С׵ǰڱΪNʯ壬ǡΪMʯȥС֪ҪԾοԵ 磺 N = 4M = 24 4->6->8->12->18->24 СҪԾ5ΣͿԴ4ʯ24ʯ 4 24 5 */ /*1 - Mʯ忴һstepNumÿstepNum[i]Ŵ㵽һСIJ 0Ϊܵ 㿪ʼstepNumбiԼstepNum[i]ߵIJȻ ǼܵλõСܵΪʱλõС + 1ܵ ľ͸ΪminѼ¼С˴С + 1һõ*/ #include <iostream> #include <vector> #include <algorithm> using namespace std; // Լ1ͱԼ void divisorNum(int n, vector<int> &divNum) { for (int i = 2; i <= sqrt(n); i++) { if (n%i == 0) { divNum.push_back(i); //ƽʱһҲҪ if (n / i != i) divNum.push_back(n / i); } } } int Jump(int N, int M) { //ĵstepNumIJʼNΪ1NNΪ1 vector<int> stepNum(M + 1, 0); stepNum[N] = 1; for (int i = N; i < M; i++) { //NԼΪӱ㿪ʼߵ vector<int> divNum; //0㲻ܵ if (stepNum[i] == 0) continue; //ߵIJdivNum divisorNum(i, divNum); for (int j = 0; j < divNum.size(); j++) { //λiܵĵΪ stepNum[divNum[j]+i] if ((divNum[j] + i) <= M && stepNum[divNum[j] + i] != 0) stepNum[divNum[j] + i] = min(stepNum[divNum[j] + i],stepNum[i] + 1); else if ((divNum[j] + i) <= M) stepNum[divNum[j] + i] = stepNum[i] + 1; } } if(stepNum[M] == 0) return -1; else // ʼʱһҪ1 return stepNum[M] - 1; } int main() { int n, m; cin >> n >> m; cout << Jump(n, m) << endl; return 0; }
true
a2604a01f213e2bf1e95ecbfa5753cf455c00fb1
C++
zeroplusone/AlgorithmPractice
/Leetcode/90. Subsets II-3.cpp
UTF-8
725
3.125
3
[]
no_license
//back tracking solution class Solution { public: vector<vector<int>> subsetsWithDup(vector<int>& nums) { vector<vector<int>> ans; vector<int> current(0); sort(nums.begin(), nums.end()); backtracking(0, current, nums, ans); return ans; } void backtracking(int now, vector<int>& current, vector<int>& nums, vector<vector<int>>& ans) { ans.push_back(current); for(int i=now;i<nums.size();++i) { if(i>=1 && i!=now && nums[i]==nums[i-1]) { continue; } current.push_back(nums[i]); backtracking(i+1, current, nums, ans); current.pop_back(); } } };
true
ec424187e8b46a53822200911e1414a72c33e80e
C++
qwefgh90/aaateamopencvserver1
/AAATeamServer/ImageManager.cpp
UHC
1,779
2.578125
3
[]
no_license
#include "stdafx.h" #include "ImageManager.h" ImageManager* ImageManager::singleton= NULL; ImageManager::ImageManager(){ sift = SiftEngine::getSiftEngine(); } ImageManager* ImageManager::getImageManager() { if(ImageManager::singleton==NULL) { ImageManager::singleton = new ImageManager(); } return ImageManager::singleton; } //1) õ ̹ 2) ̹ 3)̹ Ʈ bool ImageManager::matchingImage(__out Imagelist& image,__in Memory& memory, __in vector<Imagelist>& imageList,std::vector<OUT_List>& out_list) { bool result = false; cv::Mat target; //Create key if(!sift->createKey(memory,target)) { goto END; } //compare target with a compared list if(!sift->matchingImageWithVector(image,target,imageList,out_list)) { goto END; } result = true; END: return result; } //1) õ ̹ 2) ̹ 3)̹ Ʈ bool ImageManager::matchingImageWithCache(__out ImageBufferElement& image,__in Memory& memory, __in vector<ImageBufferElement>& imageList, u_char filter,std::vector<OUT_List>& out_list) { bool result = false; cv::Mat target; //Create key if(!sift->createKey(memory,target)) { goto END; } //compare target with a compared list if(!sift->matchingImageWithCache(image,target,imageList,filter,out_list)) { goto END; } result = true; END: return result; } bool ImageManager::storeKey(__in Memory& memory,__in char* store_path) { bool result = false; char img_path[255]={0,}; SiftEngine* sift = SiftEngine::getSiftEngine(); //Image Save sprintf(img_path,"%s.jpeg",store_path); FILE* f = fopen(img_path,"wb"); fwrite(memory.buf,memory.len,1,f); fclose(f); if(!sift->storeKey(memory,store_path)) { goto END; } result = true; END: return result; }
true
85b4bcbf097ff0750aacc9b4b63aff9a8d801d94
C++
SPYCODER-droid/DSA
/Merge_two_sorted_arrays_in_O(1)_space/main.cpp
UTF-8
727
2.703125
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; int main() { vector<int> a1,a2; int n1,n2,a,b; cin>>n1>>n2; for (int i = 0; i < n1; i++){ cin>>a; a1.push_back(a); } for (int i = 0; i < n2; i++){ cin>>b; a2.push_back(b); } sort(a1.begin(), a1.end()); sort(a2.begin(), a2.end()); for(int i = 0; i < n1; i++){ if(a1[i]>a2[0]){ swap(a1[i],a2[0]); int i; for(i=0;i<n2&&a2[0]>a2[i];i++){ a2[i-1]=a2[i]; } a2[i]=a2[0]; } } for (int i = 0; i < n1; i++){ cout<<a1[i]; } cout<<endl; for (int i = 0; i < n2; i++){ cout<<a2[i]; } }
true
103be8a87d5c1991cf707398132c5614ce3281d1
C++
RomanYu/leetcode
/q342.cpp
UTF-8
264
3.0625
3
[]
no_license
#include<iostream> using namespace std; class Solution { public: bool isPowerOfFour(int num) { return (num & (num - 1)) == 0 && (num & 0x55555555); } }; int main() { Solution s; cout<<s.isPowerOfFour(16)<<endl; }
true
717837248a593c0a3574a4d209d2cc1ef5696d54
C++
shashwatg1/Coding_Practice
/sorting/bucketSort.cpp
UTF-8
1,242
4.25
4
[]
no_license
// decimal numbers in a range #include <iostream> #include <vector> #include <algorithm> using namespace std; void printArr(float arr[], int size) { std::cout << "the array is : "; for (int i = 0; i < size; ++i) std::cout << arr[i] << " "; std::cout << "\n"; } void createArr(float arr[], int size) { for(int i=0;i<size;i++) { std::cout << "Element " << i+1 << " -> Enter Value : "; std::cin >> arr[i]; } } void bucketSort(float arr[], int n) { // 1) Create n empty buckets vector<float> b[n]; // 2) Put array elements in different buckets for (int i=0; i<n; i++) { int bi = n*arr[i]; // Index in bucket b[bi].push_back(arr[i]); } // 3) Sort individual buckets for (int i=0; i<n; i++) std::sort(b[i].begin(), b[i].end()); // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; } int main() { std::cout << "Enter size of array : "; int size=0; std::cin >> size; float arr[size]; createArr(arr, size); std::cout << "Initially, "; printArr(arr, size); bucketSort(arr, size); std::cout << "After sorting in ascending order, "; printArr(arr,size); }
true
8560107dc102224556ebcb88635aed909e8218b2
C++
davidghobson1/Dragons-Dungeon-Game-Simulator
/source/GameObjects/Items/Potions/HealthPotion.cc
UTF-8
587
3
3
[]
no_license
#include <iostream> using namespace std; #include "HealthPotion.h" #include <string> #include "random.h" HealthPotion::HealthPotion(int x, int y): Potion(x, y) { name = "Health Potion"; boostType = "health"; boost = random(100)%4 + 1; } HealthPotion::~HealthPotion() { } //Health potions collect function //A health potion increases the health for a Hero, but is not used by a Fighter void HealthPotion::collect(int& health, int& strength, int& armour, char type) { if(hasBeenCollected()){ return; } if(type == 1){ health += getBoost(); setCollected(true); } }
true
885ee62d951b1e40958506d7677a8bd142f603ea
C++
kl4kennylee81/Canon
/source/PathAIData.hpp
UTF-8
2,576
2.78125
3
[]
no_license
// // PathAIData.hpp // Canon // // Created by Jonathan Chen on 3/21/17. // Copyright � 2017 Game Design Initiative at Cornell. All rights reserved. // #ifndef PathAIData_hpp #define PathAIData_hpp #include <stdio.h> #include <cugl/cugl.h> #include "AIData.hpp" #include "ActiveAI.hpp" #include "GameObject.hpp" enum class PathType : int { HORIZONTAL, VERTICAL, CUSTOM, NONE }; enum class PathDirection : int { LEFT, RIGHT, UP, DOWN, RANDOM }; class PathAIData : public AIData { public: PathType _pathType; PathDirection _direction; std::vector<cugl::Vec2> _path; PathAIData() : AIData() {} bool init(PathType pathType, std::vector<cugl::Vec2> path, PathDirection direction); static std::shared_ptr<PathAIData> alloc(PathType pathType, std::vector<cugl::Vec2> path, PathDirection direction) { std::shared_ptr<PathAIData> result = std::make_shared<PathAIData>(); return (result->init(pathType, path, direction) ? result : nullptr); } std::shared_ptr<cugl::JsonValue> toJsonValue() override; bool preload(const std::string& file) override; bool preload(const std::shared_ptr<cugl::JsonValue>& json) override; bool materialize() override; std::shared_ptr<ActiveAI> newActiveAI(std::shared_ptr<GameObject> object) override; static std::string getStringFromPathType(PathType pt) { switch (pt) { case PathType::CUSTOM: return "CUSTOM"; case PathType::HORIZONTAL: return "HORIZONTAL"; case PathType::NONE: return "NONE"; case PathType::VERTICAL: return "VERTICAL"; default: return "NONE"; } } static PathType getPathTypeFromString(std::string s) { if (s == "CUSTOM") return PathType::CUSTOM; if (s == "HORIZONTAL") return PathType::HORIZONTAL; if (s == "NONE") return PathType::NONE; if (s == "VERTICAL") return PathType::VERTICAL; return PathType::NONE; } static std::string getStringFromPathDirection(PathDirection dir) { switch (dir) { case PathDirection::LEFT: return "LEFT"; case PathDirection::RIGHT: return "RIGHT"; case PathDirection::UP: return "UP"; case PathDirection::RANDOM: return "RANDOM"; case PathDirection::DOWN: return "DOWN"; default: return "RANDOM"; } } static PathDirection getPathDirectionFromString(std::string s) { if (s == "LEFT") return PathDirection::LEFT; if (s == "RIGHT") return PathDirection::RIGHT; if (s == "UP") return PathDirection::UP; if (s == "DOWN") return PathDirection::DOWN; if (s == "RANDOM") return PathDirection::RANDOM; return PathDirection::UP; } }; #endif /* PathAIData.hpp */
true
d1c566c70c4cac069bf9fcfa1ccf5296c20058ae
C++
jk127jp/kinmu
/kinmu.cpp
UTF-8
8,398
2.765625
3
[]
no_license
#include <fstream> #include <iostream> #include <string> #include <cstdlib> using namespace std; const int staffNum = 9+1; // 社員数 const int tanmuNum =3+1; // 担務数 const int dayNum=30+1; const int mawariHit=2; // 回りがヒットした場合の加算値 const int defaultPriority=100; // 標準の優先度 class Staff{ public: // int getID(){return id;}; Staff(); void setProperty(int v, int g, int *t); int getGroup(){return group;}; int getTanmu(int t){return tanmu[t];}; int getKinmu(int d){return kinmu[d];}; void setKinmu(int d, int t); //int checkKinmu(int d, int t); int getPriority(int d, int t); private: // int id; int valid; int group; // 1:左 2:中 3:右 int tanmu[tanmuNum]; int kinmu[dayNum+2]; }; class Kinmu{ public: int getNextDay(){return nextDay;}; int getNextTanmu(){return nextTanmu;}; int getBeforeDay(){return beforeDay;}; int getBeforeTanmu(){return beforeTanmu;}; int getCanWork(){return canWork;}; //働ける人数を返す int getStaff(){return staff;}; int getPriority(){return priority;}; void setStaff(int s, int pr){staff=s; priority=pr;}; //staffのidをセットする。0なら未設定 void setNext(int d, int t); void setBefore(int d, int t); void setCanWork(int cw); Kinmu(); private: int day; int tanmu; int nextDay; int nextTanmu; int beforeDay; int beforeTanmu; int staff; int canWork; int priority; }; Kinmu::Kinmu(){ day=0; tanmu=0; nextDay=0; nextTanmu=0; beforeDay=0; beforeTanmu=0; staff=0; canWork=0; priority=defaultPriority; } void Kinmu::setCanWork(int cw){ canWork=cw; } void Kinmu::setNext(int d, int t){ nextDay=d; nextTanmu=t; } void Kinmu::setBefore(int d, int t){ beforeDay=d; beforeTanmu=t; } Staff::Staff() { //cout << "make!" << endl; } void Staff::setProperty(int v, int g, int *t){ valid = v; group = g; int i; for (i=1;i<tanmuNum;i++){ tanmu[i]=t[i]; } } void Staff::setKinmu(int d, int t){ kinmu[d]=t; if(d<dayNum){ if(t==0){ kinmu[d+1]=t; } } } int Staff::getPriority(int d, int t){ int ans; int bfr=1; int aft=1; int i; int mawari; if (kinmu[d]+kinmu[d+1]>0){ ans = 0; }else if(tanmu[t]==0){ ans=0; }else{ for(i=4;i>0;i--){ //勤務が連続していないかチェック if(d-i<1){ bfr=0; if(kinmu[d+i+1]>0 && kinmu[d+i+1]<900){ aft+=1; }else{ aft=0; } }else if(d+i+1>dayNum){ if(kinmu[d-i]>0 && kinmu[d-i]<900){ bfr+=1; }else{ bfr=0; } aft=0; }else{ if(kinmu[d-i]>0 && kinmu[d-i]<900){ bfr+=1; }else{ bfr=0; } if(kinmu[d+i+1]>0 && kinmu[d+i+1]<900){ aft+=1; }else{ aft=0; } } } if(bfr+aft>3){ // 5連勤になる場合 ans=0; }else{ if((d-1)%3==group-1){ mawari=mawariHit; }else{ mawari=0; } ans = tanmu[t]+mawari; } } return ans; } Staff staff[staffNum]; Kinmu kinmu[dayNum][tanmuNum]; int main(){ string str; ifstream fin("tanmu.csv"); if(!fin){ cout << "Cannot open tanmu.csv" << endl; return 1; } int line; int i; int bfrcomma; int phaze; int sid; int svalid; int sgroup; int stanmu[tanmuNum]; int s; // staff用一時変数 //string tmp[100]; line=0; fin >> str; // 1行目はラベルなので無視 for (line=0; line<staffNum-1; line++){ fin >> str; cout << str << endl; phaze =0; bfrcomma=0; for (i=0; i<300; i++){ if (str[i]==','){ if (phaze==0){ sid=atoi(str.substr(0,i).c_str()); }else if(phaze==1){ svalid= atoi(str.substr(bfrcomma,i-bfrcomma).c_str()); }else if(phaze==2){ sgroup= atoi(str.substr(bfrcomma,i-bfrcomma).c_str()); }else if(phaze-2<tanmuNum){ stanmu[phaze-2]= atoi(str.substr(bfrcomma,i-bfrcomma).c_str()); } bfrcomma=i+1; phaze++; } } //cout << sgroup << endl; staff[sid].setProperty(svalid,sgroup,stanmu); } fin.close(); // ここまで担務情報の読み込み ifstream fin2("schedule.csv"); if(!fin2){ cout << "Cannot open schedule.csv" << endl; return 1; } line=0; fin2 >> str; // 1行目はラベルなので無視 for (line=0; line<staffNum-1; line++){ fin2 >> str; cout << str << endl; phaze =0; bfrcomma=0; for (i=0; i<300; i++){ if (str[i]==','){ if (phaze==0){ sid=atoi(str.substr(0,i).c_str()); }else if(phaze<dayNum){ staff[sid].setKinmu(phaze,atoi(str.substr(bfrcomma,i-bfrcomma).c_str())); } bfrcomma=i+1; phaze++; } } } for(s=1; s<staffNum; s++){ staff[s].setKinmu(dayNum,0); //翌月はじめは0にしておく } fin2.close(); // ここまで勤務指定の入力 int day; int tanmu; int canwork; int tmp; for(day=1;day<dayNum;day++){ for(tanmu=1;tanmu<tanmuNum;tanmu++){ canwork=0; for(i=1;i<staffNum;i++){ tmp=staff[i].getPriority(day,tanmu); if (tmp>0){ canwork++; } } kinmu[day][tanmu].setCanWork(canwork); } } // ここまで働ける人数を数えてkinmuに格納 int tmp_beforeDay=0; int tmp_beforeTanmu=0; int minCanWork; int minDay; int minTanmu; for(day=0;day<dayNum;day++){ for(tanmu=1;tanmu<tanmuNum;tanmu++){ kinmu[day][tanmu].setNext(0,0); kinmu[day][tanmu].setBefore(dayNum+1,0); // 初期化 } } minCanWork=0; while(minCanWork<staffNum+1){ minCanWork=staffNum+1; for(day=1;day<dayNum;day++){ for(tanmu=1;tanmu<tanmuNum;tanmu++){ // cout << kinmu[day][tanmu].getBeforeDay(); if((kinmu[day][tanmu].getCanWork() < minCanWork) && (kinmu[day][tanmu].getNextDay()==0) && (kinmu[day][tanmu].getBeforeDay()==dayNum+1)){ // 働ける人が最小で、優先順位にまだ登録されていない場合 minCanWork=kinmu[day][tanmu].getCanWork(); minDay=day; minTanmu=tanmu; } } } cout << "(" << minDay << " " << minTanmu << " " << minCanWork << ")" << endl; if(minCanWork<staffNum+1){ //cout << "(" << tmp_beforeDay << " " << tmp_beforeTanmu << " " << minDay << " " << minTanmu << " " << minCanWork << ")"; kinmu[tmp_beforeDay][tmp_beforeTanmu].setNext(minDay,minTanmu); kinmu[minDay][minTanmu].setBefore(tmp_beforeDay,tmp_beforeTanmu); tmp_beforeDay=minDay; tmp_beforeTanmu=minTanmu; }else{ kinmu[tmp_beforeDay][tmp_beforeTanmu].setNext(32,0); } } int day_tmp; int maxPriority; int maxID; int s_tmp; int pr_tmp; int pr; day=kinmu[0][0].getNextDay(); tanmu=kinmu[0][0].getNextTanmu(); while(day>0 && day<dayNum){ maxPriority=0; s_tmp=kinmu[day][tanmu].getStaff(); staff[s_tmp].setKinmu(day,0); pr_tmp=kinmu[day][tanmu].getPriority(); // kinmu[day][tanmu].setStaff(0,0); // staff[s_tmp].setKinmu(day,0); for(s=1;s<staffNum;s++){ pr=staff[s].getPriority(day,tanmu); if(pr>maxPriority){ if(pr==pr_tmp && s>s_tmp){ maxPriority=pr; maxID=s; }else if(pr<pr_tmp){ maxPriority=pr; maxID=s; } } } if(maxPriority<1){ //NoOneCanWork cout << "NoOne (" << day << " " << tanmu << ")" << endl; kinmu[day][tanmu].setStaff(0,defaultPriority); //staff[s_tmp].setKinmu(day,0); day_tmp = kinmu[day][tanmu].getBeforeDay(); tanmu = kinmu[day][tanmu].getBeforeTanmu(); day = day_tmp; //前の日、坦務の呼び出し //staff[s_tmp].setKinmu(day,0); cout << "D(" << day << " " << tanmu << " " << kinmu[day][tanmu].getStaff() << ")" << endl; }else{ //KinmuAssign cout << "A(" << day << " " << tanmu << " " << maxID << ")" << endl; kinmu[day][tanmu].setStaff(maxID,maxPriority); staff[maxID].setKinmu(day,tanmu); staff[maxID].setKinmu(day+1,100);//Ake day_tmp = kinmu[day][tanmu].getNextDay(); tanmu = kinmu[day][tanmu].getNextTanmu(); day = day_tmp; } } if(day==0){ cout << "Error!" << endl; }else{ cout << "Done." << endl; } /* ここまででkinmu[0][0]のnextに 一番勤務可能者が少ない日・担務が 割り当てられている。 もっとも優先度が低いkinmuには、 nextDayに32が割り当てられている。 */ for(day=1;day<dayNum;day++){ cout << day << " : "; for(tanmu=1;tanmu<tanmuNum;tanmu++){ cout << kinmu[day][tanmu].getStaff() << " "; } cout << endl; } return 0; }
true
3e724515a9038cabda85bc7318ae8d8616523b15
C++
mmrraju/HackerRank-Basic-Problem_Solving-soluiton-with-cpp
/ElectronicsShop.cpp
UTF-8
1,098
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int s; int n; int m; cin >> s >> n >> m; int k[n]; int z=-1; int u[m]; for(int i=0;i<n;i++) { cin >> k[i]; } for(int i=0;i<m;i++) { cin >> u[i]; } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(k[i]+u[j]<=s && k[i]+u[j]>z) z=k[i]+u[j]; } } cout<<z; return 0; } /*#include<bits/stdc++.h> using namespace std; int main() { vector<int>a; vector<int>b; int budget, k, d; cin>>budget>>k>>d; for(int i=0; i<k; i++) { int j; cin>>j; a.push_back(j); } for(int i=0; i<d; i++) { int j; cin>>j; b.push_back(j); } sort(a.begin(), a.end()); sort(b.begin(), b.end()); int h=0; for(int i=0; i<k; i++) { for(int j=d-1; j>0; j--) { if(a[i]+b[j]<=budget) h=max(h,a[i]+b[j]); } } if(h==0) { h=-1; cout<<h<<endl; } else cout<<h<<endl; }*/
true
a164f4130593422df59b04eda8dedb8a123c8c94
C++
crowleydi/ece231-challenges
/main.cpp
UTF-8
187
2.546875
3
[]
no_license
#include <iostream> #include "hashmap.h" int main() { HashMap<std::string, int, StringHash> hmap; hmap.insert("ECE231", 5); std::cout << hmap["ECE231"] << std::endl; return 0; }
true
c656d2805e751326855c95931b32d29f33f919b1
C++
DoMoCo/Skyline
/Skyline.h
GB18030
2,771
2.65625
3
[]
no_license
#ifndef __SKYLINEONRDF__SKYLINE__ #define __SKYLINEONRDF__SKYLINE__ #include <iostream> #include <vector> #include <list> #include <string> #include <unordered_map> #include <unordered_set> #include <iterator> #include <queue> #include <stack> #include <set> //#include "BTree.h" namespace SkylineOnRDF { const int inf = (1 << 31) - 1; typedef struct Node { std::vector<std::string> info; //Ϣ std::set<int> next; //һ std::set<int> prior; //һ //std::string name; bool is_location; int visited; Node() { visited = -1; } }RDFNode; typedef struct TNode { int id; // std::set<struct TNode*> child; int space_num; TNode(){ space_num = 0; } }TreeNode,*Tree; /*typedef struct LNode { int id; struct LNode* next; }LinkNode, *LinkList;*/ class Skyline { public: Skyline() {}; // void init(const std::vector<RDFNode> &nodes, const std::unordered_map<int, std::string> &id_to_name); //ӺϢ void addNext(const int index, const std::set<int> &nexts); //ǰϢ void addPrior(const int index, const std::set<int> &nexts); //òѯؼ void setKeywords(const std::vector<std::string> &keywords); // void setKeywords(const int num); //ͨBFSؼmapн㰴 void buildKeywordMap(bool acquire_depth = false); //㵽ѯؼֵ̾ void fastComputeDistanceMatrix(); void computeDistanceMatrix(); //skylineѯ int BNL(); //void BFS(); // void buildTree(); //ݷѡһؼ std::stack<std::pair<TreeNode*, bool>> backTrack(Tree &T, int which, int index); //ʾ void displayTree(Tree T); ~Skyline(); private: //BFS void reverseBFS(const std::vector<int> origins, const int which); void reverseBFS(int origin, int which); //ɾ void deleteTree(Tree t); //ϲ· bool meregeListToTree(const std::list<int>& L, Tree &T, std::stack<std::pair<TreeNode *, bool>> &track_pos); //Ļ˵ľ루ո int setSpace(Tree T, int left_num); std::vector<RDFNode> rdf_; std::vector<std::vector<int>> distance_matrix_; std::vector<Tree> trees_; std::vector<int> sp_; std::vector<std::string> keywords_; //spؼֵһ· std::vector<std::vector<std::list<int>>> sp_keyword_lists_; std::unordered_map<int, std::string> id_to_name_; std::unordered_map<std::string, std::vector<std::pair<int, int>>> keyword_HashMap_; std::unordered_map<std::string, std::vector<int>> mini_keyword_HashMap_; int name_max_size_; }; } #endif
true
1075e1c11895d8a7cdf1e5a25c89f35bc481f685
C++
pzhxbz/CCpp2016
/practices/cpp/level1/p_CircleAndPoint/Circle.h
UTF-8
386
2.59375
3
[]
no_license
#ifndef CIRCLE_H #define CIRCLE_H #include "Point.h" class Circle { public: Circle(); virtual ~Circle(); Circle(Point center,int r); void draw(); void trans(int x,int y); void put_trans(int x,int y); protected: private: Point center; Point tran; int r; }; #endif // CIRCLE_H
true
87a298d4db85961da21f0c93a351e2f745db942b
C++
syedfarhanashraf/CPP-Program-Reference-
/CPP/Course2/classes.cpp
UTF-8
723
3.890625
4
[]
no_license
#include <iostream> #include <cassert> class Date{ public: //---Getters(accessors)----// int Day(){return day;} int Month(){return month;} int Year(){return year;} //---Setters(mutators)----// void Day(int d){ if (d > 0 && d <= 31) day = d; } void Month(int m){ if (m > 0 && m <= 12) month = m; } void Year(int y){year = y;} private: int day{0}; int month{0}; int year{0}; }; int main() { Date date; date.Day(-1); date.Month(14); date.Year(2000); assert(date.Day() != -1); assert(date.Month() != 14); assert(date.Year() == 2000); }
true
7af623f470fc92febacf22c75c4858d0c3625127
C++
pointer20qt/wudi
/2-11test/try_catch.cpp
GB18030
720
3.59375
4
[]
no_license
#include<iostream> #include<vector> using namespace std; int main() { vector<int> arr{ 1, 2, 3, 4, 5, 6 }; try{ for (int i = 0; i < 7; i++) { cout << arr.at(i) << endl; }//쳣תcatch 쳣1 throw 2;//Լ׳쳣 쳣2 ֻcatchǰ쳣 cout << "ӡ" << endl; } catch (int test) { cout << "쳣,쳣"<<test << endl; } catch (out_of_range & e) { cout << "Խ쳣" << endl;//ƥ쳣catchƥ֮󣬾Ͳ쳣 } catch (...)//(...)쳣catch { cout << "쳣" << endl; } cout << "һ" << endl;//Ȼ }
true
29854391086d822c589e0e24c0f8cd1f8f77e61d
C++
firewood/topcoder
/atcoder/agc_008/a.cpp
UTF-8
423
2.875
3
[]
no_license
// A. #include <iostream> #include <algorithm> #include <sstream> #include <cstdio> #include <cstring> using namespace std; int main(int argc, char *argv[]) { int x, y; cin >> x >> y; int ans = 1 << 30; for (int a = -1; a <= 1; a += 2) { for (int b = -1; b <= 1; b += 2) { int p = x * a, q = y * b; if (p <= q) { ans = min(ans, (a < 0) + (b < 0) + q - p); } } } cout << ans << endl; return 0; }
true
424095653bfb0549e87dfe9c7edc0e9a6ae27f31
C++
thlucena/ray-tracer-2020
/project04/src/cameras/orthographic.h
UTF-8
887
2.875
3
[]
no_license
#ifndef _ORTHO_CAM_ #define _ORTHO_CAM_ #include "../core/film.h" #include "../core/camera.h" #include "../core/point3D.h" #include "../core/vec3.h" #include "../core/ray.h" class OrthographicCamera : public Camera { public: OrthographicCamera( float l, float r, float b, float t ) { this->type = CameraTypes::ORTHOGRAPHIC; this->l = l; this->r = r; this->b = b; this->t = t; }; void finishSetup() override { /* Empty */ } Ray generate_ray( int i, int j ) override { float u_coord = l + ( r - l ) * ( i + 0.5f ) / film->getWidth(); float v_coord = b + ( t - b ) * ( j + 0.5f ) / film->getHeight(); Ray r = Ray(eye + u_coord * u + v_coord * v, w ); return r; } }; #endif
true
0a27115528d1a9ea1215da468289e8d326f0f69c
C++
SeisSol/easi
/include/easi/util/RegularGrid.h
UTF-8
864
2.546875
3
[ "BSD-3-Clause" ]
permissive
#ifndef EASI_UTIL_REGULARGRID_H_ #define EASI_UTIL_REGULARGRID_H_ namespace easi { template <typename T> class Slice; class RegularGrid { public: static unsigned const MaxDimensions = 6; inline ~RegularGrid() { delete[] m_values; } void allocate(unsigned const* numGridPoints, unsigned dimensions, unsigned numValues); void setVolume(double const* min, double const* max); double* operator()(unsigned const* index); void getNearestNeighbour(Slice<double> const& x, double* buffer); void getNeighbours(Slice<double> const& x, double* weights, double* buffer); private: double* m_values = nullptr; unsigned m_dimensions = 0; unsigned m_numValues = 0; double m_min[MaxDimensions]; double m_max[MaxDimensions]; unsigned m_num[MaxDimensions]; double m_delta[MaxDimensions]; }; } // namespace easi #endif
true
2c3167b114a050e517e0cd6d06506d04f2ed2a83
C++
OpenLocalizationTestOrg/ECMA2YamlTestRepo2
/fulldocset/add/codesnippet/CPP/p-system.windows.forms.d_42_1.cpp
UTF-8
227
2.5625
3
[ "CC-BY-4.0", "MIT" ]
permissive
public: void SetMyCustomFormat() { // Set the Format type and the CustomFormat string. dateTimePicker1->Format = DateTimePickerFormat::Custom; dateTimePicker1->CustomFormat = "MMMM dd, yyyy - dddd"; }
true
755b4abb4c5f3adde5be23d53e0a4f625858f3cd
C++
DreadedX/raid
/src/raid/platform/android/android.cpp
UTF-8
6,236
2.515625
3
[]
no_license
//---------------------------------------------- #include <GLES3/gl3.h> #include <android/log.h> #include "raid/platform/android/android.h" #include "logger.h" //---------------------------------------------- static void engine_handle_cmd(android_app*, int32_t cmd) { switch(cmd) { case APP_CMD_INIT_WINDOW: break; case APP_CMD_TERM_WINDOW: break; } } //---------------------------------------------- struct Pointer { int x = 0; int y = 0; bool pressed = false; }; //---------------------------------------------- #define POINTER_COUNT 10 static std::array<Pointer, POINTER_COUNT> pointers; //---------------------------------------------- static int engine_handle_input(android_app* app, AInputEvent* event) { if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { int pointer_id = ((AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT); if (pointer_id >= POINTER_COUNT) { return 0; } pointers[pointer_id].x = AMotionEvent_getX(event, pointer_id); pointers[pointer_id].y = AMotionEvent_getY(event, pointer_id); switch (AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK) { case AMOTION_EVENT_ACTION_UP: case AMOTION_EVENT_ACTION_POINTER_UP: pointers[pointer_id].pressed = false; break; case AMOTION_EVENT_ACTION_DOWN: case AMOTION_EVENT_ACTION_POINTER_DOWN: pointers[pointer_id].pressed = true; break; default: break; } return 1; } return 0; } //---------------------------------------------- raid::Android::Android(android_app* app) { app_dummy(); // app->onAppCmd = engine_handle_cmd; app->onInputEvent = engine_handle_input; this->app = app; } //---------------------------------------------- void raid::Android::create_window(int, int, std::string) { // initialize OpenGL ES and EGL /* * Here specify the attributes of the desired configuration. * Below, we select an EGLConfig with at least 8 bits per color * component compatible with on-screen windows */ const EGLint attribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_NONE }; EGLint format; EGLint numConfigs; EGLConfig config; display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(display, 0, 0); /* Here, the application chooses the configuration it desires. * find the best match if possible, otherwise use the very first one */ eglChooseConfig(display, attribs, nullptr,0, &numConfigs); std::unique_ptr<EGLConfig[]> supportedConfigs(new EGLConfig[numConfigs]); assert(supportedConfigs); eglChooseConfig(display, attribs, supportedConfigs.get(), numConfigs, &numConfigs); assert(numConfigs); auto i = 0; for (; i < numConfigs; i++) { auto& cfg = supportedConfigs[i]; EGLint r, g, b, d; if (eglGetConfigAttrib(display, cfg, EGL_RED_SIZE, &r) && eglGetConfigAttrib(display, cfg, EGL_GREEN_SIZE, &g) && eglGetConfigAttrib(display, cfg, EGL_BLUE_SIZE, &b) && eglGetConfigAttrib(display, cfg, EGL_DEPTH_SIZE, &d) && r == 8 && g == 8 && b == 8 && d == 0 ) { config = supportedConfigs[i]; break; } } if (i == numConfigs) { config = supportedConfigs[0]; } /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). * As soon as we picked a EGLConfig, we can safely reconfigure the * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); surface = eglCreateWindowSurface(display, config, app->window, NULL); const EGLint context_version[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE }; context = eglCreateContext(display, config, NULL, context_version); if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { warning << "Unable to eglMakeCurrent\n"; } eglQuerySurface(display, surface, EGL_WIDTH, &width); eglQuerySurface(display, surface, EGL_HEIGHT, &height); // Check openGL on the system auto opengl_info = {GL_VENDOR, GL_RENDERER, GL_VERSION, GL_EXTENSIONS}; for (auto name : opengl_info) { auto information = glGetString(name); warning << "OpenGL Info: " << information << '\n'; } // Initialize GL state. // glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); // glEnable(GL_CULL_FACE); // glShadeModel(GL_SMOOTH); // glDisable(GL_DEPTH_TEST); } //---------------------------------------------- void raid::Android::terminate() { if (display != EGL_NO_DISPLAY) { eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (context != EGL_NO_CONTEXT){ eglDestroyContext(display, context); } if (surface != EGL_NO_SURFACE){ eglDestroySurface(display, surface); } eglTerminate(display); } display = EGL_NO_DISPLAY; context = EGL_NO_CONTEXT; surface = EGL_NO_SURFACE; } //---------------------------------------------- bool raid::Android::should_window_close() { return app->destroyRequested; } //---------------------------------------------- bool raid::Android::has_context() { return app->window != nullptr; } //---------------------------------------------- void raid::Android::poll_events() { int ident; int fdesc; int events; struct android_poll_source* source; while((ident = ALooper_pollAll(0, &fdesc, &events, (void**)&source)) >= 0) { // process this event if (source) { source->process(app, source); } } } //---------------------------------------------- void raid::Android::swap_buffers() { eglSwapBuffers(display, surface); } //---------------------------------------------- bool raid::Android::is_pressed(int x, int y, int width, int height) { /// @todo Check this for all pointers for (auto& pointer : pointers) { if (x <= pointer.x && pointer.x <= x+width && y <= pointer.y && pointer.y <= y+height && pointer.pressed) { return true; } } return false; }
true
5f684e8a1a6a64b30491582d44bccbdc1f49acc8
C++
ashuy280/hackerrank
/Linked_List/Insert_a_node_at_a_specific_position_in_a_linked_list.cpp
UTF-8
459
3.640625
4
[]
no_license
SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position) { SinglyLinkedListNode *add=new SinglyLinkedListNode(data); SinglyLinkedListNode *temp=nullptr; temp=head; while(position>1){ temp=temp->next; position--; } if(temp->next==NULL){ temp->next=add; return head; } else{ add->next=temp->next; temp->next=add; return head; } }
true
1cff8b108990d9fecae0b4ef140fdf0e3905c687
C++
marcosrodriigues/ufop
/conteudo/AEDS I/Práticas/Prática 05/Marcos-Rodrigues-1/Pilha.cpp
UTF-8
886
2.96875
3
[]
no_license
#include <stdlib.h> #include <iostream> #include "Pilha.h" using namespace std; void TPilha_Inicia(TPilha *pilha) { pilha->pPrimeiro = NULL; pilha->pUltimo = NULL; } int TPilha_EhVazia(TPilha *pilha) { return (pilha->pPrimeiro == pilha->pUltimo ? 1 : 0 ); } int TPilha_Push(TPilha *pilha, TItem item) { TCelula *aux = new TCelula; aux->item = item; aux->pProx = pilha->pPrimeiro; pilha->pPrimeiro = aux; pilha->count++; return 1; } int TPilha_Pop(TPilha *pilha, TItem *item) { if (TPilha_EhVazia(pilha)) return 0; TCelula *pAux = pilha->pPrimeiro; pilha->pPrimeiro = pAux->pProx; *item = pAux->item; delete pAux; pilha->count--; return 1; } int TPilha_Tamanho (TPilha *pilha) { //cout << "Tamanho: " << pilha->count << endl; return pilha->count; } void TPilha_Limpa (TPilha *pilha) { pilha->pPrimeiro = NULL; pilha->pUltimo = NULL; pilha->count = 0; }
true
d8c284d58d9f6e383203443267afc2b279ef30b6
C++
MarshalStewart/EECE_2080_Lab_07
/Lab07/Main.cpp
UTF-8
18,072
3.09375
3
[]
no_license
// FleetAttack.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <stack> #include <cstdlib> #include <ctime> #include "Fleet.h" #include "IShip.h" #include "IRace.h" #include "ShipFactory.cpp" using namespace std; int main() { cout << "Welcome to our game\n"; // TODO print the stats available for each ship int count = 0; int p_count = 1; string input = ""; ShipFactory shipFactory; ShipFactory::Race_Type faction; ShipFactory::Ship_Type ship; Fleet<IShip*> *fleet = nullptr; Fleet<IShip*> *fleet1 = new Fleet<IShip*>(); Fleet<IShip*> *fleet2 = new Fleet<IShip*>(); // Select a Fleet while (p_count < 3) { for (int i=0; i<50; i++) cout << "*"; cout << endl; cout << "Player " << p_count << " choose fleet: \n"; if (p_count == 1) fleet = fleet1; else fleet = fleet2; // Player chooses fleet count = 0; while (count < 4) { // TODO print out which ship ur selecting aka front left, right etc for (int i=0; i<50; i++) cout << "-"; cout << endl; cout << "Choose a faction: NAZI, USSR, USA, SPQR\n"; cin >> input; if (input.compare("NAZI") == 0) { faction = ShipFactory::Race_Type::E_NAZI; cout << "NAZI selected\n"; } else if (input.compare("USSR") == 0) { faction = ShipFactory::Race_Type::E_USSR; cout << "USSR selected\n"; } else if (input.compare("USA") == 0) { faction = ShipFactory::Race_Type::E_USA; cout << "USA selected\n"; } else if (input.compare("SPQR") == 0) { faction = ShipFactory::Race_Type::E_SPQR; cout << "SPQR selected\n"; } else { cout << "Invalid input\n"; continue; } cout << "Choose a ship type: StarDestroyer, StarFighter, StarBomber, StarApacheAttackHelicopter\n"; cin >> input; if (input.compare("StarDestroyer") == 0) { ship = ShipFactory::Ship_Type::STAR_DESTROYER; cout << "StarDestroyer selected\n"; } else if (input.compare("StarFighter") == 0) { ship = ShipFactory::Ship_Type::STAR_FIGHTER; cout << "StarFighter selected\n"; } else if (input.compare("StarBomber") == 0) { ship = ShipFactory::Ship_Type::STAR_BOMBER; cout << "StarBomber selected\n"; } else if (input.compare("StarApacheAttackHelicopter") == 0) { ship = ShipFactory::Ship_Type::STAR_APACHEATTACKHELICOPTER; cout << "StarApacheAttackHelicopter selected\n"; } else { cout << "Invalid input\n"; continue; } IShip* new_ship = shipFactory.CreateShip(ship, faction); // cout statement here instead of in faction and shiptype // something like "Nazi StarFighter created" // assign temp string variables in above if else statements if (count == 0) fleet->setFlagShip(new_ship); fleet->addFlotilla(new_ship); count++; } p_count++; } // Player Turns bool p_turn = false; // 0 Player 1 turn, 1 Player 2 turn bool player1_won = false; bool player2_won = false; std::srand(time(nullptr)); // use current time as seed for random generator int dice_roll = 0; int fleet_size = 0; int enemy_fleet_size = 0; int turn_counter = 0; int initiative_counter = 0; IShip *cur_ship; IRace *cur_race; IShip *enemy_ship; Fleet<IShip*> *enemy_fleet; vector<IShip*> flotilla; vector<IShip*> enemy_flotilla; // Create initiative vector vector<IShip*> initiative_flotilla; vector<bool> initiative_id; for (auto ship : fleet1->getFlotilla()) { initiative_flotilla.push_back(ship); initiative_id.push_back(0); } for (auto ship : fleet2->getFlotilla()) { initiative_flotilla.push_back(ship); initiative_id.push_back(1); } // Sort(insert sort) initiative vector for (int r=0; r<initiative_flotilla.size(); r++) { int l = r; int nxtItem = initiative_flotilla[r]->GetInitiativeBonus(); while ((l > 0) && (initiative_flotilla[l-1]->GetInitiativeBonus() > nxtItem)) { initiative_flotilla[l] = initiative_flotilla[l-1]; initiative_id[l] = initiative_id[l-1]; l--; } initiative_flotilla[l] = initiative_flotilla[r]; // nxt Item initiative_id[l] = initiative_id[r]; } while (!player1_won && !player2_won) { for (int i=0; i<50; i++) cout << "#"; cout << endl; initiative_counter = turn_counter; while (initiative_counter >= 8) { initiative_counter -= 8; } cur_ship = initiative_flotilla[initiative_counter]; cur_race = cur_ship->GetRace(); p_turn = initiative_id[initiative_counter]; if (!p_turn) { cout << "Player 1 is up!\n"; fleet = fleet1; enemy_fleet = fleet2; flotilla = fleet->getFlotilla(); fleet_size = flotilla.size(); enemy_flotilla = enemy_fleet->getFlotilla(); enemy_fleet_size = enemy_flotilla.size(); } else { cout << "Player 2 is up!\n"; fleet = fleet2; enemy_fleet = fleet1; flotilla = fleet->getFlotilla(); fleet_size = flotilla.size(); enemy_flotilla = enemy_fleet->getFlotilla(); enemy_fleet_size = enemy_flotilla.size(); } // Summary of all ships int c = 0; for (auto ship : flotilla) { for (int i=0; i<50; i++) cout << "-"; cout << endl; cout << "Ship " << c << ":" << endl << "Race: " << ship->GetStrRace() << endl << "Ship: " << ship->GetStrShip() << endl; if (ship->GetHitPoints() > 0){ cout << "Hit Points: " << ship->GetHitPoints() << endl; } else { cout << "Destroyed\n"; } c++; // lmo } // input = ""; // cout << "Press enter to play turn" << endl; // cin >> input; // check if flotilla is dead for (auto ship : flotilla) { if (ship->GetHitPoints() <= 0) { fleet_size--; } } // Check if enemy_flotilla is dead for (auto ship : enemy_flotilla) { if (ship->GetHitPoints() <= 0) { enemy_fleet_size--; } } // Check if game won if (fleet_size == 0) { player2_won = true; cout << "Player " << (p_turn ? "1" : "2") << " Wins\n" << "took " << turn_counter << " turns" << endl; continue; // exits loop } else if (enemy_fleet_size == 0) { player1_won = true; cout << "Player " << (p_turn ? "2" : "1") << " Wins\n" << "took " << turn_counter << " turns" << endl; continue; // exits loop } // Check if current ship is dead if (cur_ship->GetHitPoints() <= 0) { cout << cur_ship->GetStrRace() << " " << cur_ship->GetStrShip() << " is dead" << endl; turn_counter++; continue; } // Select current ship // cur_ship = flotilla[fleet_size-1]; // cur_race = cur_ship->GetRace(); // Role dice dice_roll = rand() % 20 + 1; // 1-20 // Add hit bonus dice_roll += cur_ship->GetHitBonus(); // Check which front ship to attack int pos = 0; if (cur_ship->GetStrRace().compare("SPQR") == 0) // SPQR special ability { pos = rand() % 4; if (pos == 0) enemy_ship = enemy_fleet->getLeftFrontShip(); else if (pos == 1) enemy_ship = enemy_fleet->getRightFrontShip(); else if (pos == 2) enemy_ship = enemy_fleet->getLeftBackShip(); else enemy_ship = enemy_fleet->getRightBackShip(); // Grab ship till we get one that's not dead while (enemy_ship->GetHitPoints() <= 0) { pos = rand() % 4; if (pos == 0) enemy_ship = enemy_fleet->getLeftFrontShip(); else if (pos == 1) enemy_ship = enemy_fleet->getRightFrontShip(); else if (pos == 2) enemy_ship = enemy_fleet->getLeftBackShip(); else enemy_ship = enemy_fleet->getRightBackShip(); } } else { // Grab one of front 2 pos = rand() % 2; if (pos == 0) enemy_ship = enemy_fleet->getLeftFrontShip(); else enemy_ship = enemy_fleet->getRightFrontShip(); // Grab ship till we get one that's not dead while (enemy_ship->GetHitPoints() <= 0) { // only 1 front is dead if (!((enemy_fleet->getLeftFrontShip()->GetHitPoints() <= 0) && (enemy_fleet->getRightFrontShip()->GetHitPoints() <= 0))) { if (pos == 1) enemy_ship = enemy_fleet->getLeftFrontShip(); else enemy_ship = enemy_fleet->getRightFrontShip(); } else { while (enemy_ship->GetHitPoints() <= 0) { pos = rand() % 2; if (pos == 0) enemy_ship = enemy_fleet->getLeftBackShip(); else enemy_ship = enemy_fleet->getRightBackShip(); } } } } // Check Special Ability for (int i=0; i<50; i++) cout << "-"; cout << endl // << "Player " << (p_turn ? "2" : "1") << endl << "Race: " << cur_ship->GetStrRace() << endl << "Ship: " << cur_ship->GetStrShip() << endl << "is up to attack" << endl; if (cur_ship->GetStrRace().compare("NAZI") == 0) { dice_roll -= 3; // compare to AC if (enemy_ship->GetArmorClass() < dice_roll) { // Damage Ship dice_roll = rand() % cur_ship->GetDamageBonus() + 16; // 1-min damage int damage = enemy_ship->GetHitPoints() - (dice_roll); // if damage < 0 // damage=0; enemy_ship->SetHitPoints(damage); cout << "Player " << (p_turn ? "1" : "2") << endl << "Race: " << enemy_ship->GetStrRace() << endl << "Ship: " << enemy_ship->GetStrShip() << endl << "got hit for " << dice_roll << endl; } else { cout << "Player " << (p_turn ? "2" : "1") << " Misses" << endl; } } else if (cur_ship->GetStrRace().compare("SPQR") == 0) { // SPQR // Can attack backrow, already implemented by this point // compare to AC if (enemy_ship->GetArmorClass() < dice_roll) { // Damage Ship dice_roll = rand() % cur_ship->GetDamageBonus() + 1; // 1-min damage int damage = enemy_ship->GetHitPoints() - (dice_roll); // if damage < 0 // damage=0; enemy_ship->SetHitPoints(damage); cout << "Player " << (p_turn ? "1" : "2") << endl << "Race: " << enemy_ship->GetStrRace() << endl << "Ship: " << enemy_ship->GetStrShip() << endl << "got hit for " << dice_roll << endl; } else { cout << "Player " << (p_turn ? "2" : "1") << " Misses" << endl; } } else if (cur_ship->GetStrRace().compare("USA") == 0) { // USA // 1/10 chance to do big damage to all enemies // compare to AC // enemy_ship = enemy_fleet->getFrontShip(); if (enemy_ship->GetArmorClass() < dice_roll) { if (rand() % 10 != 9) { // Damage Ship dice_roll = rand() % cur_ship->GetDamageBonus() + 1; // 1-min damage int damage = enemy_ship->GetHitPoints() - (dice_roll); // if damage < 0 // damage=0; enemy_ship->SetHitPoints(damage); } else { dice_roll = cur_ship->GetDamageBonus(); // apply damage to all enemy ships enemy_ship = enemy_fleet->getLeftFrontShip(); int damage = enemy_ship->GetHitPoints() - dice_roll; enemy_ship->SetHitPoints(damage); enemy_ship = enemy_fleet->getRightFrontShip(); damage = enemy_ship->GetHitPoints() - dice_roll; enemy_ship->SetHitPoints(damage); enemy_ship = enemy_fleet->getLeftBackShip(); damage = enemy_ship->GetHitPoints() - dice_roll; enemy_ship->SetHitPoints(damage); enemy_ship = enemy_fleet->getLeftBackShip(); damage = enemy_ship->GetHitPoints() - dice_roll; enemy_ship->SetHitPoints(damage); } cout << "Player " << (p_turn ? "1" : "2") << endl << "Race: " << enemy_ship->GetStrRace() << endl << "Ship: " << enemy_ship->GetStrShip() << endl << "got hit for " << dice_roll << endl; } else { cout << "Player " << (p_turn ? "2" : "1") << " Misses" << endl; } } else { // USSR // recoil damage and damage bonus // compare to AC // enemy_ship = enemy_fleet->getFrontShip(); if (enemy_ship->GetArmorClass() < dice_roll) { // Damage Ship dice_roll = 2*(rand() % cur_ship->GetDamageBonus() + 1); // 1-min damage int damage = enemy_ship->GetHitPoints() - (dice_roll); // Do Damage to Enemy enemy_ship->SetHitPoints(damage); // Recoil Damage int new_hp = cur_ship->GetHitPoints(); new_hp -= (int)((new_hp * 0.05)+3); cur_ship->SetHitPoints(new_hp); cout << "Player " << (p_turn ? "1" : "2") << endl << "Race: " << enemy_ship->GetStrRace() << endl << "Ship: " << enemy_ship->GetStrShip() << endl << "got hit for " << dice_roll << endl; } else { cout << "Player " << (p_turn ? "2" : "1") << " Misses" << endl; } } // Move selected ship // fleet_size--; // p_turn = !p_turn; turn_counter++; } // Game Won // std::cout << "Hello World!\n"; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
true
1a9ef21051734a2892ca1f857b415622765931ca
C++
danielpereira/AoETechTree
/TechTree/AnotherControlRelatedClass.h
UTF-8
454
2.53125
3
[ "MIT" ]
permissive
#pragma once /* INCLUDES */ // Base class header #include "GameType.h" /* DEFINITIONS */ #pragma pack(push, 1) // Represents an unknown control related class. // Research type name: AnotherWindowRelatedStruct. class AnotherControlRelatedClass : public GameType { protected: // Member variables DWORD _unknown1[27]; DWORD _flag; DWORD _unknown2[8]; DWORD _width; DWORD _height; DWORD _positionX; DWORD _positionY; public: }; #pragma pack(pop)
true
af4dc8e10659d37ee95f7095c1f3d741bcb4e0ff
C++
ymmtshny/ArizonaStateUniversity
/SER221/week2/produce.cpp
UTF-8
7,127
3.84375
4
[]
no_license
/****************************************************** * Programmed by : Shinya Yamamoto * Created on : 17 January 2016 * Class : SER221 * Week : 2nd week * Problem : BoxOfProduce Class * * This program randamaly selects three bundles of fruits * or vegetables as an array of type string, and the user * can substitute any one of possible fruits or vegetables * for any of the furits or vegetabels selected. ******************************************************/ //g++ -o produce.exe produce.cpp #include <iostream> #include <string> #include <cctype> #include <ctime> #include <cstdlib> using namespace std; //This function gives me a random number between 1 to 5 int getRandomNumber(); class BoxOfProduce { public: string content[3]; static int numberOfBoxes; //constructo, initialize the box BoxOfProduce(); //mutator(set) method void setContentOfBox(); //mutator(set) method void changeContentOfBox(); //accessor(get) method void showContentOfBox(); //static member function static int getNumberOfBoxes(); }; /************************************************************* * GLOBAL VARIABLE * ----------------------------------------------------------- * SIZE = 3 // This the size of content string * LISTS = 5; // This is the number of vegetables and fruits. *************************************************************/ const int SIZE = 3; const int LISTS = 5; int main() { char yesOrNo; int totalBoxes = 0; do { //initialize a box BoxOfProduce box; //randamly set the content of box box.setContentOfBox(); //diplays the content of box box.showContentOfBox(); cout << "Would you like to change one of the contents? (Y/N)" << endl; cin >> yesOrNo; if(toupper(yesOrNo) == 'Y'){ //change the content of box box.changeContentOfBox(); } //diplays the content of box box.showContentOfBox(); //get the total number of boxes that have been created totalBoxes = box.getNumberOfBoxes(); cout << "Do you want to create another box? (Y/N)" << endl; cin >> yesOrNo; } while(toupper(yesOrNo) == 'Y'); cout << "The total number of boxes :" << totalBoxes << endl; return 0; } /************************************************************* * int getRandomNumber() *------------------------------------------------------------ * This function generates a random number and returns it. * LISTS is 5, which is the number of vegetables or fruits *************************************************************/ int getRandomNumber() { return rand() % LISTS + 1; } /************************************************************* * BoxOfProduce::BoxOfProduce() * ----------------------------------------------------------- * This is a constractor. *************************************************************/ BoxOfProduce::BoxOfProduce() { //intentionally blank here } /************************************************************* * void BoxOfProduce::setContentOfBox(); *------------------------------------------------------------ * This member function sets the content of box *************************************************************/ void BoxOfProduce::setContentOfBox() { unsigned seed = time(0); srand(seed); int random; for(int index = 0; index < SIZE; index ++) { random = getRandomNumber(); switch (random) { case 1: content[index] = "Broccoli"; break; case 2: content[index] = "Tomato"; break; case 3: content[index] = "Kiwi"; break; case 4: content[index] = "Kale"; break; case 5: content[index] = "Tomatillo"; break; default: cout << "ERROR"; } } } /************************************************************* * void BoxOfProduce::changeContentOfBox(); *------------------------------------------------------------ * This member function asks the user to input the number to * change an element of content array and changes the elemet * depending on the user input. *************************************************************/ void BoxOfProduce::changeContentOfBox(){ int indexOfContent; // this should be 0 to 2 int indexOfItem; // this should be 1 to 5 cout << "Enter the number whose content you what to change" << endl; cin >> indexOfContent; cout << "Enter the nubmer you want to add" << endl; cout << "1. Broccoli" << endl; cout << "2. Tomato" << endl; cout << "3. Kiwi" << endl; cout << "4. Kale" << endl; cout << "5. Tomatillo" << endl; cin >> indexOfItem; switch(indexOfItem) { case 1: content[indexOfContent] = "Broccoli"; break; case 2: content[indexOfContent] = "Tomato"; break; case 3: content[indexOfContent] = "Kiwi"; break; case 4: content[indexOfContent] = "Kale"; break; case 5: content[indexOfContent] = "Tomatillo"; break; default: cout << "ERROR"; } } /************************************************************* * void BoxOfProduce::showContentOfBox(); *------------------------------------------------------------ * This member function outputs contents of box with * index numbers *************************************************************/ void BoxOfProduce::showContentOfBox(){ cout << "Your box contains the followings" << endl; cout << "----------------------------------" << endl; for(int index = 0; index < SIZE ; index ++) { cout << index << ". " << content[index] << endl; } cout << "----------------------------------" << endl; } /************************************************************* * int BoxOfProduce::numberOfBoxes *------------------------------------------------------------ * This is a static member varialbe to count the number of * boxes that has been created. Here, numberOfBoxes is * initialized as 0. *************************************************************/ int BoxOfProduce::numberOfBoxes = 0; /************************************************************* * void BoxOfProduce::getNumberOfBoxes(); *------------------------------------------------------------ * This static member function adds 1 to numberOfBoxes, then * the function returns numberOfBoxes. *************************************************************/ //static member function NO NEED TO WRITE static here int BoxOfProduce::getNumberOfBoxes() { return ++numberOfBoxes; }
true
bb0963fed97aa1f41839c4e1c420d85f5a015e90
C++
StateFromJakeFarm/compProgramming
/leetcode/google/strictly_palindromic_number.cpp
UTF-8
398
3.171875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class Solution { public: bool isStrictlyPalindromic(int n) { // Because a number's representation in base n-2 will always be 12 (duh) return false; } }; int main() { Solution S; for (int i=4; i<=10000; i++) { if (S.isStrictlyPalindromic(i)) { cout << i << endl; } } return 0; }
true
3729b17c0f6a6590d990aba3832ba3dac72fc053
C++
AswinTorch/Semester1
/Assignment7.cpp
UTF-8
7,807
2.859375
3
[]
no_license
//Aswin Nair //Assignment 7: Buffon's Needle #define _USE_MATH_DEFINES #include <iostream> #include <sstream> #include "Simple_window.h" #include "GUI.h" #include "Graph.h" #include "Window.h" #include <cstdlib> #include <ctime> #include <cmath> #include <vector> using namespace Graph_lib; using namespace std; struct Lines_window : Graph_lib::Window { Lines_window(Point xy, int w, int h, const string& title ); //Needle variables vector <Point*> midpoints, points1, points2, parallelPoints1, parallelPoints2; vector <Text*> orderDisplayVector; Graph_lib::Rectangle textBox; Text piDisplay; vector <Line*> needles, parallelLines; private: //Buttons and Menus (Widgets) Button quitButton, dropButton, menuButton; In_box dropCountInput; Menu motionMenu; //Callback functions static void cb_count(Address, Address); static void cb_rotate(Address, Address); static void cb_unlist(Address, Address); static void cb_menu(Address, Address); static void cb_quit(Address, Address); static void cb_drop(Address, Address); //Actions invoked by callback functions void hide_menu() { motionMenu.hide(); menuButton.show(); } void count_pressed(); void rotate_pressed(); void unlist_pressed(); void menu_pressed() { menuButton.hide(); motionMenu.show(); } void quit(); void drop(); }; Lines_window::Lines_window(Point xy, int w, int h, const string& title) :Window(xy,w,h,title), quitButton(Point(x_max()-70,0), 70, 20, "Quit", cb_quit), dropButton(Point(x_max()-150,0), 70, 20, "Drop", cb_drop), menuButton(Point(x_max()-90,30), 90, 20, "Motion Menu", cb_menu), dropCountInput(Point(x_max()-230,0), 70, 20, "Enter Drop Count:"), motionMenu(Point(x_max()-70,30),70,20,Menu::vertical,"Motion"), textBox (Point{350, 325}, Point{1050, 350}), piDisplay(Point{490, 345}, "") { //Attaching menus attach(dropCountInput); attach(quitButton); attach(dropButton); motionMenu.attach(new Button(Point(0,0),0,0,"Count",cb_count)); motionMenu.attach(new Button(Point(0,0),0,0,"Rotate",cb_rotate)); motionMenu.attach(new Button(Point(0,0),0,0,"(Un)List",cb_unlist)); attach(motionMenu); motionMenu.hide(); attach(menuButton); //Constant Parallel Lines for (int a = 200; a <= 1200; a += 200){ Point* p1 = new Point(a,25); parallelPoints1.push_back(p1); Point* p2 = new Point(a,675); parallelPoints2.push_back(p2); Line* parallelLine = new Line(*p1, *p2); parallelLines.push_back(parallelLine); } for (int a = 0, l = parallelLines.size(); a < l; ++a){ parallelLines[a]->set_color(Color::blue); attach (*parallelLines[a]); } } void Lines_window::cb_drop(Address, Address pw) { reference_to<Lines_window>(pw).drop(); } void Lines_window::cb_quit(Address, Address pw) { reference_to<Lines_window>(pw).quit(); } void Lines_window::cb_count(Address, Address pw) { reference_to<Lines_window>(pw).count_pressed(); } void Lines_window::cb_rotate(Address, Address pw) { reference_to<Lines_window>(pw).rotate_pressed(); } void Lines_window::cb_unlist(Address, Address pw) { reference_to<Lines_window>(pw).unlist_pressed(); } void Lines_window::cb_menu(Address, Address pw) { reference_to<Lines_window>(pw).menu_pressed(); } //Functions void Lines_window::quit() { hide(); } void Lines_window::drop() { //Drops the needles according to user input int dropCount = dropCountInput.get_int(); for (int a = 0, l = needles.size(); a < l; ++a){ detach(*needles[a]); delete needles[a]; delete points1[a]; delete points2[a]; delete midpoints[a];} for (int b = 0, l = orderDisplayVector.size(); b < l; ++b) {detach(*orderDisplayVector[b]); delete orderDisplayVector[b];} needles.clear(); midpoints.clear(); points1.clear(); points2.clear(); orderDisplayVector.clear(); detach(piDisplay); detach(textBox); int x, y; double x1, y1, x2, y2, theta = 0; for(int a = 0, l = dropCount; a < l; ++a){ theta = (rand()%360) * (M_PI/180); x = rand() % 1200 + 100; y = rand() % 600 + 50; Point* midpoint = new Point(x,y); midpoints.push_back(midpoint); x1 = x + 100*cos(theta); y1 = y + 100*sin(theta); Point* p1 = new Point(x1,y1); points1.push_back(p1); x2 = x - (100 * cos(theta)); y2 = y - (100 * sin(theta)); Point* p2 = new Point (x2,y2); points2.push_back(p2); Line* needle = new Line(Point(x1,y1), Point(x2,y2)); needles.push_back(needle); attach(*needles[a]); } redraw(); } void Lines_window::count_pressed() { //Counts and colors the crossed needles red, approximates and displays pi. for (int a = 0, l = orderDisplayVector.size(); a < l; ++a) { detach(*orderDisplayVector[a]); delete orderDisplayVector[a]; } detach(piDisplay); detach(textBox); orderDisplayVector.clear(); int dropCount = dropCountInput.get_int(), crossedCount = 0, mainX; //Calculating the intersecting lines and coloring them red for (int a = 0, l = needles.size(); a < l; ++a){ for (int b = 0, l = parallelLines.size(); b < l; ++b){ mainX = parallelPoints1[b]->x; if (points1[a]->x < mainX && points2[a]->x > mainX){ needles[a]->set_color(Color::red); ++crossedCount; } else if (points2[a]->x < mainX && points1[a]->x > mainX){ needles[a]->set_color(Color::red); ++crossedCount; } } } //Calculation and display of pi double calculatedPi = double(2 * dropCount)/double(crossedCount); textBox.set_fill_color(Color::white); attach(textBox); ostringstream piMessage; piMessage << "Found " << crossedCount << " crossed needles, and estimated pi is " << calculatedPi << "!"; piDisplay.set_label(piMessage.str()); attach(piDisplay); redraw(); } void Lines_window::rotate_pressed() { //Rotates the needles on a random angle, resets color to black, removes order display int dropCount = dropCountInput.get_int(); for (int a = 0, l = needles.size(); a < l; ++a){ detach(*needles[a]); delete needles[a]; delete points1[a]; delete points2[a]; } for (int a = 0, l = orderDisplayVector.size(); a < l; ++a) {detach(*orderDisplayVector[a]); delete orderDisplayVector[a];} needles.clear(); points1.clear(); points2.clear(); orderDisplayVector.clear(); detach(piDisplay); detach(textBox); double x1, y1, x2, y2, theta = 0; for (int a = 0, l = dropCount; a < l; ++a){ theta = (rand() % 360) * (M_PI/180); x1 = midpoints[a]->x + 100*cos(theta), y1 = midpoints[a]->y + 100*sin(theta); x2 = midpoints[a]->x - 100*cos(theta), y2 = midpoints[a]->y - 100*sin(theta); Point* p1 = new Point(x1,y1); points1.push_back(p1); Point* p2 = new Point (x2,y2); points2.push_back(p2); Line* needle = new Line (Point (x1, y1), Point (x2, y2)); needles.push_back(needle); attach(*needles[a]); } redraw(); } void Lines_window::unlist_pressed() { //(Un)Lists the order of the creation of needles next to their midpoints for (int a = 0, l = orderDisplayVector.size(); a < l; ++a) {detach(*orderDisplayVector[a]); delete orderDisplayVector[a]; } detach(piDisplay); detach(textBox); if (orderDisplayVector.size() == 0){ for (int a = 0, l = needles.size(); a < l; ++a) needles[a]->set_color(Color::black); int dropOrder = 0; for (int a = 0, l = midpoints.size(); a < l; ++a){ ostringstream orderMessage; orderMessage << a + 1; Text* orderDisplay = new Text (*midpoints[a], orderMessage.str()); orderDisplayVector.push_back(orderDisplay); attach(*orderDisplayVector[a]); } } else { orderDisplayVector.clear(); for (int a = 0, l = orderDisplayVector.size(); a < l; ++a) {detach(*orderDisplayVector[a]); delete orderDisplayVector[a]; } } redraw(); } int main() { srand(unsigned(time(0))); Lines_window mainWindow(Point(0,0),1400,700,"Assignment 7: Buffon's Needle"); gui_main(); //Runs the program }
true
7b93a040556b4e14ac5822b9173fc4881a92a4fc
C++
DYu24/Warzone
/src/player/PlayerDriver.cpp
UTF-8
2,044
3.046875
3
[]
no_license
#include "../game_engine/GameEngine.h" #include "../orders/Orders.h" #include "Player.h" int main() { // Setup Territory* t1 = new Territory("Territory1"); Territory* t2 = new Territory("Territory2"); Territory* t3 = new Territory("Territory3"); Territory* t4 = new Territory("Territory4"); Territory* t5 = new Territory("Territory5"); t1->addArmies(10); t2->addArmies(2); t3->addArmies(5); t4->addArmies(1); t5->addArmies(1); std::unordered_map<Territory*, std::vector<Territory*>> adjacencyList{ {t2, {t3, t4}}, {t5, {t4}} }; Continent* c1 = new Continent("Continent1", 3); c1->setTerritories({ t1, t2, t3, t4, t5 }); std::vector<Continent*> continents{ c1 }; Map* map = new Map(continents, adjacencyList); GameEngine::setMap(map); GameEngine::getDeck()->generateCards(5); Player p1 = Player("Player 1", new AggressivePlayerStrategy()); p1.addOwnedTerritory(t1); p1.addOwnedTerritory(t2); p1.addOwnedTerritory(t5); p1.drawCardFromDeck(); p1.addReinforcements(20); // Show the initial Player object std::cout << p1 << std::endl; // Show the list of territories to defend std::cout << "\n-----Calling Player.toDefend(): -----" << std::endl; std::vector<Territory*> toDefend = p1.toDefend(); std::cout << "\nTerritories to defend: \n" << std::endl; for (const auto &territory : toDefend) { std::cout << "- " << *territory << std::endl; } // Show the list of territories to attack std::cout << "\n-----Calling Player.toAttack(): -----" << std::endl; std::vector<Territory*> toAttack = p1.toAttack(); std::cout << "\nTerritories to attack: \n" << std::endl; for (const auto &territory : toAttack) { std::cout << "- " << *territory << std::endl; } std::cout << "\n-----Calling Player.issueOrder(): -----" << std::endl; p1.issueOrder(); std::cout << p1 << std::endl; GameEngine::resetGameEngine(); return 0; }
true
264997a912e5f197952642b4553b57bade928e3e
C++
TheDonsky/DumbRay
/__source__/DataStructures/GeneralPurpose/Matrix/Matrix.impl.h
UTF-8
6,034
2.75
3
[ "MIT" ]
permissive
#include"Matrix.h" /** ########################################################################## **/ /** //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\// **/ /** ########################################################################## **/ template<typename Type> __device__ __host__ inline Matrix<Type>::Matrix(){ matWidth = 0; matHeight = 0; } template<typename Type> __device__ __host__ inline Matrix<Type>::Matrix(int width, int height){ setDimensions(width, height); } /** ########################################################################## **/ /** //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\// **/ /** ########################################################################## **/ template<typename Type> __device__ __host__ inline Type* Matrix<Type>::operator[](int y){ return (data + (y * matWidth)); } template<typename Type> __device__ __host__ inline const Type* Matrix<Type>::operator[](int y)const{ return (data + (y * matWidth)); } template<typename Type> __device__ __host__ inline Type& Matrix<Type>::operator()(int y, int x){ return data[(y * matWidth) + x]; } template<typename Type> __device__ __host__ inline const Type& Matrix<Type>::operator()(int y, int x)const{ return data[(y * matWidth) + x]; } template<typename Type> __device__ __host__ inline int Matrix<Type>::width()const{ return matWidth; } template<typename Type> __device__ __host__ inline int Matrix<Type>::height()const{ return matHeight; } template<typename Type> __device__ __host__ inline int Matrix<Type>::surface()const{ return matWidth * matHeight; } template<typename Type> __device__ __host__ inline void Matrix<Type>::clear(){ matWidth = 0; matHeight = 0; data.clear(); } template<typename Type> __device__ __host__ inline void Matrix<Type>::setDimensions(int width, int height){ matWidth = width; matHeight = height; data.clear(); data.flush(matWidth * matHeight); } /** ########################################################################## **/ /** //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\// **/ /** ########################################################################## **/ template<typename Type> /* Uploads unit to CUDA device and returns the clone address */ inline Matrix<Type>* Matrix<Type>::upload()const { IMPLEMENT_CUDA_LOAD_INTERFACE_UPLOAD_BODY(Matrix); } template<typename Type> /* Uploads unit to the given location on the CUDA device (returns true, if successful; needs RAW data address) */ inline bool Matrix<Type>::uploadAt(Matrix *address)const { IMPLEMENT_CUDA_LOAD_INTERFACE_UPLOAD_AT_BODY(Matrix); } template<typename Type> /* Uploads given source array/unit to the given target location on CUDA device (returns true, if successful; needs RAW data address) */ inline bool Matrix<Type>::upload(const Matrix *source, Matrix *target, int count) { IMPLEMENT_CUDA_LOAD_INTERFACE_UPLOAD_ARRAY_AT_BODY(Matrix); } template<typename Type> /* Uploads given source array/unit to CUDA device and returns the clone address */ inline Matrix<Type>* Matrix<Type>::upload(const Matrix<Type> *source, int count) { IMPLEMENT_CUDA_LOAD_INTERFACE_UPLOAD_ARRAY_BODY(Matrix); } template<typename Type> /* Disposed given array/unit on CUDA device, making it ready to be free-ed (returns true, if successful) */ inline bool Matrix<Type>::dispose(Matrix *arr, int count) { IMPLEMENT_CUDA_LOAD_INTERFACE_DISPOSE_BODY(Matrix); } /** ########################################################################## **/ /** //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\// **/ /** ########################################################################## **/ /** Friends: **/ template<typename ElemType> __device__ __host__ inline void TypeTools<Matrix<ElemType> >::init(Matrix<ElemType> &m){ TypeTools<Stacktor<ElemType, 1> >::init(m.data); m.matWidth = 0; m.matHeight = 0; } template<typename ElemType> __device__ __host__ inline void TypeTools<Matrix<ElemType> >::dispose(Matrix<ElemType> &m){ TypeTools<Stacktor<ElemType, 1> >::dispose(m.data); } template<typename ElemType> __device__ __host__ inline void TypeTools<Matrix<ElemType> >::swap(Matrix<ElemType> &a, Matrix<ElemType> &b){ TypeTools<Stacktor<ElemType, 1> >::swap(a.data, b.data); TypeTools<int>::swap(a.matWidth, b.matWidth); TypeTools<int>::swap(a.matHeight, b.matHeight); } template<typename ElemType> __device__ __host__ inline void TypeTools<Matrix<ElemType> >::transfer(Matrix<ElemType> &src, Matrix<ElemType> &dst){ TypeTools<ElemType>::transfer(src.data, dst.data); dst.matWidth = src.matWidth; dst.matHeight = src.matHeight; } template<typename ElemType> inline bool TypeTools<Matrix<ElemType> >::prepareForCpyLoad(const Matrix<ElemType> *source, Matrix<ElemType> *hosClone, Matrix<ElemType> *devTarget, int count){ int i = 0; for (i = 0; i < count; i++){ if (!TypeTools<Stacktor<ElemType, 1> >::prepareForCpyLoad(&(source + i)->data, &(hosClone + i)->data, &(devTarget + i)->data, 1)) break; hosClone[i].matWidth = source[i].matWidth; hosClone[i].matHeight = source[i].matHeight; } if (i < count){ undoCpyLoadPreparations(source, hosClone, devTarget, i); return(false); } return(true); } template<typename ElemType> inline void TypeTools<Matrix<ElemType> >::undoCpyLoadPreparations(const Matrix<ElemType> *source, Matrix<ElemType> *hosClone, Matrix<ElemType> *devTarget, int count){ for (int i = 0; i < count; i++) TypeTools<Stacktor<ElemType, 1> >::undoCpyLoadPreparations(&(source + i)->data, &(hosClone + i)->data, &(devTarget + i)->data, 1); } template<typename ElemType> inline bool TypeTools<Matrix<ElemType> >::devArrayNeedsToBeDisposed(){ return TypeTools<ElemType>::devArrayNeedsToBeDisposed(); } template<typename ElemType> inline bool TypeTools<Matrix<ElemType> >::disposeDevArray(Matrix<ElemType> *arr, int count){ for (int i = 0; i < count; i++) if (!TypeTools<Stacktor<ElemType, 1> >::disposeDevArray(&(arr + i)->data, 1)) return(false); return(true); }
true
c4549a2c6284ee6931c7cddc5c6dff259d6e43c9
C++
ankitpahwa111/DSA
/StringSortSTL.cpp
UTF-8
512
3.1875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void changing(int a[], int size) { for (int i = 0; i < size; i++) a[i] = a[i] + 1; } void change(vector<int> v) { for (int i = 0; i < v.size(); i++) v[i] = v[i] + 1; } int main() { int a[3] = {0, 1, 2}; vector<int> v; for (int i = 0; i < 3; i++) v.push_back(i); changing(a, 3); change(v); for (int i = 0; i < 3; i++) cout << a[i] << " "; for (int i = 0; i < 3; i++) cout << v[i] << " "; }
true
95258b11fe106e147fc732a1957e91ddc7f26bae
C++
NeelimaGundu/CodeforcesProblemsSolutions
/ChocolateFeast.cpp
UTF-8
558
2.671875
3
[]
no_license
#include<iostream> using namespace std; int main() { int t; cin>>t; int *a=new int[t]; for(int i=0;i<t;i++) { int n,c,m,left=0,wraps=0; cin>>n>>c>>m; int choci=0; choci=n/c; wraps=choci; while(wraps!=1) { if(wraps<m) break; left=wraps/m; choci+=left; wraps=wraps-left*m; wraps+=left; } a[i]=choci; } for(int i=0;i<t;i++) cout<<a[i]<<endl; return 0; }
true
a93d77fdec73314a151c3a8f81e213f0d43807e3
C++
ucam-comparch-loki/lokisim
/src/Utility/Trace/Callgrind.h
UTF-8
4,337
2.734375
3
[ "MIT" ]
permissive
/* * Callgrind.h * * Class used to generate a trace in a format compatible with Callgrind. * * For each function executed, need a block like: * fl=<file name> * fn=<function name> * <line number> <events for this function> * cfi=<file name of called function> * cfn=<called function name> * calls=<number of calls> <line in file> * <line number> <events for this function> * * fn data only cares about functions called directly from this one * cfn data collapses all time spent in called functions * * More documentation available here: * http://valgrind.org/docs/manual/cl-format.html * * Created on: 24 Oct 2014 * Author: db434 */ #ifndef CALLGRIND_H_ #define CALLGRIND_H_ #include <map> #include "../../Datatype/Identifier.h" #include "../../Memory/MemoryTypes.h" #include "../../Types.h" using std::ofstream; using std::ostream; using std::string; using std::vector; class Callgrind { private: // Used to determine which function any given instruction is within. // TODO: including the file and line number would be useful. typedef struct { MemoryAddr start; MemoryAddr end; string name; } FunctionInfo; // Information to be collected. struct Stats_ { count_t instructions; count_t cycles; void clear() {instructions = cycles = 0;} void operator+= (const struct Stats_& s) { instructions += s.instructions; cycles += s.cycles; } friend ostream& operator<< (ostream& os, struct Stats_ const& s) { os << s.instructions << " " << s.cycles; return os; } }; typedef struct Stats_ Stats; // Data on any function which has been called from another function. // Stats are *inclusive* of any functions which are called internally. typedef struct { count_t timesCalled; Stats stats; } CalledFunction; // Standalone data for each function. // Stats are *exclusive* of any called functions - the data is contained in // calledFunctions. typedef struct { Stats stats; std::map<MemoryAddr, CalledFunction> calledFunctions; } TopLevelFunction; public: // Open the named file and print a header. Also collect information from the // symbol table of the binary so later we can determine which function is // being executed at any time. static void startTrace(const string& logFile, const string& binaryFile, const chip_parameters_t& params); // Tidy up when execution has finished. static void endTrace(); // Call this method to record that an instruction from a given address was // executed on a given cycle. static void instructionExecuted(CoreIndex core, MemoryAddr address, cycle_count_t cycle); // Returns whether instructionExecuted may be called. static bool acceptingData(); private: // Return the function which contains the given instruction address. static const FunctionInfo& functionOf(MemoryAddr instAddress); // Extract information from all functions in the named binary. static void buildFunctionList(const string& binaryFile); // Call this method whenever the functions of the previous two instructions // differ. static void functionChanged(unsigned int coreID, MemoryAddr address, cycle_count_t cycle); // Record that one function called another. static void functionCall(MemoryAddr caller, MemoryAddr callee); private: // Keep track of whether we are currently tracing. static bool tracing; // The stream to write all information to. static ofstream* log; // A sorted list of all functions in the program. Used to determine which // function a given instruction is within. static vector<FunctionInfo> functions; // A special case which allows us to continue tracing even if we see // unexpected instructions. static FunctionInfo unknownFunction; // Record the execution statistics for each function. static std::map<MemoryAddr, TopLevelFunction> functionStats; // Memory addresses showing which functions have called which. // Use a vector (not a stack) because we need to be able to iterate through. // One for each core. static vector<vector<MemoryAddr> > callStack; // Data for the function which is currently executing. // One for each core. static vector<Stats> currentFunction; }; #endif /* CALLGRIND_H_ */
true
afc5959920fc375563cbb5ac68d86f95e5a2b85f
C++
vicmars5/EDA
/enclase/12-abril/Stack/include/stack.h
UTF-8
1,715
3.640625
4
[]
no_license
#ifndef STACK_H #define STACK_H #include <exception> class StackException : public std::exception { private: public: } template <class T> class Stack{ private: Node<T>* anchor; public: Stack(); ~Stack(); Stack(const Stack&); bool isEmpty(); bool isFull(); void push(const T&); T& pop(); T& getTop(); }; template <class T> Stack<T>::Stack() { anchor = nullptr; } template <class T> Stack<T>::~Stack() { Node<T>* aux; while(anchor != nullptr) { //ELIMINA } } template <class T> Stack<T>::Stack(const Stack& s) : Stack() { Node<T>* last = nullptr; Node<T>* auxN; Node<T>* auxR = s.anchor; while(aux != nullptr) { auxN = new Node<T>(auxR.getData()); if(last == nullptr){ anchor = auxN; } else { last->setNext(auxN); } last = auxN; } } template <class T> bool Stack<T>::isEmpty() { return anchor == nullptr; } template <class T> bool Stack<T>::isFull() { } template <class T> void Stack<T>::push(const T&) { Node<T>* aux = new Node<T>(e); if(aux == nullptr) { throw StackException("Memoria no disponible al hacer push"); } aux->setNext(anchor); anchor = aux; } template <class T> void Stack<T>::pop() { if(isEmpty) { throw StackException("Pila vacia, tratando de hacer un POP"); } T r = anchor->getData(); Node<T>* aux = anchor; anchor= (anchor->getNext()); delete aux; return r; } template <class T> T Stack<T>::getTop() { if(isEmpty()) { throw StackException("Pila vacia al tratar de hacer GET TOP"); } return anchor->getData(); } #endif // STACK_H
true
a1eb3b4eb21e0ec2ed2a840327dc5e33dc4274d1
C++
nranjan2014/mytc
/Glossary/main.cpp
UTF-8
1,940
2.65625
3
[]
no_license
#include "Glossary.cpp" int main(int argc, char **argv) { int i; class Glossary TheClass; vector <string> retval; vector <string> items; if (argc != 2) { fprintf(stderr, "usage: a.out num\n"); exit(1); } /* items = ; */ if (atoi(argv[1]) == 0) { items.push_back("Canada"); items.push_back( "France"); items.push_back( "Germany"); items.push_back( "Italy"); items.push_back( "Japan"); items.push_back( "Russia"); items.push_back( "United Kingdom"); items.push_back( "United States"); } if (atoi(argv[1]) == 1) { items.push_back("alpha"); items.push_back( "beta"); items.push_back( "gamma"); items.push_back( "delta"); items.push_back( "omega"); } if (atoi(argv[1]) == 2) { items.push_back("AVL tree"); items.push_back( "backtracking"); items.push_back( "array"); items.push_back( "balanced tree"); items.push_back( "binary search"); } if (atoi(argv[1]) == 3) { items.push_back("XXXXXXXXXXXXXXXXX"); items.push_back( "YYYYYYYYYYYYYYYYY"); items.push_back( "ZZZZZZZZZZZZZZZZZ"); } if (atoi(argv[1]) == 4) { items.push_back("Asteria"); items.push_back( "Astraeus"); items.push_back( "Atlas"); items.push_back( "Clymene"); items.push_back( "Coeus"); items.push_back( "Crius"); items.push_back( "Cronus"); items.push_back( "Dione"); items.push_back( "Epimetheus"); items.push_back( "Helios"); items.push_back( "Hyperion"); items.push_back( "Iapetus"); items.push_back( "Leto"); items.push_back( "Mnemosyne"); items.push_back( "Oceanus"); items.push_back( "Ophion"); items.push_back( "Phoebe"); items.push_back( "Prometheus"); items.push_back( "Rhea"); items.push_back( "Tethys"); items.push_back( "Theia"); items.push_back( "Themis"); } retval = TheClass.buildGlossary(items); VIT(i, retval) cout << retval[i] << endl; exit(0); }
true
527595e3cc4ff1b229da7d14f1d24d1b99e1c9e6
C++
Ablyamitov/Programming
/Practice/24/c++/24/24/24.cpp
UTF-8
917
2.75
3
[]
no_license
#include<fstream> #include"json.h" #include<iostream> #include<iomanip> #include<vector> using nlohmann::json; using namespace std; int main() { int complete_work ; vector <int>all_userId; ifstream in("in.json"); json inin; in >> inin; ofstream out("out.json"); json outout = json::array(); size_t size_inin = inin.size(); int maxId; for (int i = 0; i < size_inin;i++) { all_userId.push_back(inin[i]["userId"]); } maxId = *max_element(all_userId.begin(), all_userId.end()); for (int different_id = 1;different_id <= maxId;different_id++) { complete_work = 0; for (int allwork = 0; allwork <= size_inin;allwork++) { if (inin[allwork]["userId"] == different_id && inin[allwork]["completed"]) complete_work++; } if (complete_work > 0) { outout.push_back( { { "task_completed", complete_work }, {"userId", different_id}, } ); } } out << setw(4) << outout << endl; }
true
1b0f7ab7684698e891063abd1096cfc84cb89f1c
C++
alex1701c/KDevelopTemplates
/qt_cpp_templates/qt_cli_templates/validated_qt_cli_template/Validator.cpp
UTF-8
1,526
2.5625
3
[]
no_license
#include "Validator.h" #include <QDebug> CommandLineParseResult validateCommandLine(QCommandLineParser &parser, CommandLineValues *data, QString *errorMessage) { parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions); parser.setApplicationDescription("Description..."); const QCommandLineOption helpOption = parser.addHelpOption(); const QCommandLineOption versionOption = parser.addVersionOption(); parser.addPositionalArgument("data", "Data property of struct", "<data>"); const QCommandLineOption debugOption(QStringList() << "d" << "debug", "Debug results"); parser.addOption(debugOption); if (!parser.parse(QCoreApplication::arguments())) { *errorMessage = parser.errorText(); return CommandLineError; } if (parser.isSet(versionOption)) return CommandLineVersionRequested; if (parser.isSet(helpOption)) return CommandLineHelpRequested; const QStringList positionalArguments = parser.positionalArguments(); if (positionalArguments.isEmpty() || positionalArguments.first().isEmpty()) { *errorMessage = "Argument <data> missing."; return CommandLineError; } if (positionalArguments.size() > 1) { *errorMessage = "Several <data> arguments specified."; return CommandLineError; } data->data = positionalArguments.first(); if (parser.isSet(debugOption)) { qDebug() << "Positional arguments: " << positionalArguments; } return CommandLineOk; }
true
0f6c23c4cf4491c8f57d77f50910e9f0c5a0ca8e
C++
Utkarshmalik/dailycodebase
/day11/C++/day-11.cpp
UTF-8
756
3.4375
3
[]
no_license
/** * @author Utkarshmalik * @date 06/01/2019 */ #include<iostream> using namespace std; string lcs(string str1,string str2) { //first make sure that s2 is the smaller of the two strings if(str2.size()>str1.size()) { //swap the two given strings string temp=str1; str1=str2; str2=temp; } for(int i=str2.size();i>=1;i--) { for(int j=0;j<=str2.size()-i;j++) { string tempS=str2.substr(j,i); if(str1.find(tempS)!=string::npos) { return tempS; } } } return ""; } int main() { int t; cin>>t; for(int i=0;i<t;i++) { string str1,str2,str3; cin>>str1; cin>>str2; str3=lcs(str1,str2); cout<<str3; } }
true
b37220409a4d40b8ebbcd1ec34fbe2336415d32c
C++
wusunmoon/Interview_Ex
/Linear1/Linear1/main.cpp
UTF-8
745
3.59375
4
[]
no_license
#include<iostream> #include<algorithm> #include<vector> using namespace std; bool BeSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); //对数组排序 for (int i = 0; i < nums.size(); ++i) { if (nums[i] > target) //如果当前元素大于target,后面元素也必定大于target break; bool b = binary_search(nums.begin() + i + 1, nums.end(), target-nums[i]); //对后面元素二分查找 if (b) return true; } return false; } int main() { vector<int> nums; int n,t; cin >> n; //输入数组元素个数 for(int i = 0; i < n; ++i) { cin >> t; nums.push_back(t); } int target; cin >> target; if (BeSum(nums, target)) cout << "true" << endl; else cout << "false" << endl; return 0; }
true
bfdf90ec8079d90a2bc7018bf6df4287cc10604c
C++
GoodRon/dataKeeper
/plugins/journal/JournalRequests.hxx
UTF-8
2,765
2.515625
3
[]
no_license
/* * Created by Roman Meyta 2016 <meyta@incom.tomsk.ru> * Incom inc Tomsk Russia http://incom.tomsk.ru/ */ #ifndef JOURNAL_REQUESTS_HXX #define JOURNAL_REQUESTS_HXX #include <string> #include "MsgPack_types.h" namespace journal_db { /** * @brief Сформировать запрос добавление записи * * @param sa источник * @param da приемник * @param toper время совершения операции * @param oper описание операции * @param returnAddress обратный адрес в системе IPC для ответного сообщения * @return MsgPack::package **/ MsgPack::package insertRecord(int32_t sa, int32_t da, time_t toper, const std::string& oper, const std::string& returnAddress = ""); /** * @brief Сформировать запрос на удаление всех записей * * @param returnAddress обратный адрес в системе IPC для ответного сообщения * @return MsgPack::package **/ MsgPack::package deleteAll(const std::string &returnAddress = ""); /** * @brief Сформировать запрос на удаление устаревших записей * * @param amount допустимое количество наиболее свежих записей в базе * @param returnAddress обратный адрес в системе IPC для ответного сообщения * @return MsgPack::package **/ MsgPack::package deleteOldRecords(unsigned int amount, const std::string& returnAddress); /** * @brief Сформировать параметризированный запрос на удаление устаревших записей * * @param sa источник (-1 - не учитывается) * @param da приемник (-1 - не учитывается) * @param topermax (0 - не учитывается) * @param topermin (0 - не учитывается) * @param returnAddress обратный адрес в системе IPC для ответного сообщения * @return MsgPack::package **/ MsgPack::package selectRecordsByParameters(int32_t sa, int32_t da, time_t topermax, time_t topermin, const std::string& returnAddress = ""); /** * @brief Сформировать запрос на выдачу записи по mid * * @param mid уникальный идентификатор записи * @param returnAddress обратный адрес в системе IPC для ответного сообщения * @return MsgPack::package **/ MsgPack::package selectRecordByMid(int64_t mid, const std::string& returnAddress = ""); } #endif // JOURNAL_REQUESTS_HXX
true
d2bf365d99f8081b7b8e0cebea24e352d0223377
C++
BCITTeamOmega/MouseCraft
/MouseCraft/Graphics/Renderable.cpp
UTF-8
2,546
2.71875
3
[]
no_license
#include "Renderable.h" #include "ModelGen.h" #include "../Core/Entity.h" #include "../Loading/ModelLoader.h" #include "../Loading/ImageLoader.h" #include "../ResourceCache.h" #include <string> #include <sstream> Renderable::Renderable() : _shininess(0.5), _smoothness(25.0) {} Model* Renderable::getModel() { return _model; } void Renderable::setModel(Model& model) { _model = &model; } Transform Renderable::getTransform() { Entity* e = GetEntity(); if (e != nullptr) { return e->transform; } return Transform(); } Color Renderable::getColor() { return _color; } void Renderable::setColor(Color color) { _color = color; } void Renderable::setShininess(float f) { _shininess = f; } float Renderable::getShininess() { return _shininess; } void Renderable::setRoughness(float f) { _smoothness = f; } float Renderable::getSmoothness() { return _smoothness; } #pragma region prefab support Component* Renderable::CreateFromJson(json json) { auto c = ComponentManager<Renderable>::Instance().Create<Renderable>(); // parse shininess if (json.find("shininess") != json.end()) { c->_shininess = json["shininess"].get<double>(); } // parse smoothness if (json.find("smoothness") != json.end()) { c->_smoothness = json["smoothness"].get<double>(); } // parse color if (json.find("color") != json.end()) { c->_color = Color( json["color"]["r"].get<double>(), json["color"]["g"].get<double>(), json["color"]["b"].get<double>()); } // parse geometry and texture if (json.find("model_gen") != json.end()) { // use model generation if (json["model_gen"]["type"].get<std::string>() == "cube") { auto& jval = json["model_gen"]["size"]; c->_model = ModelGen::makeCube(jval[0].get<float>(), jval[1].get<float>(), jval[2].get<float>()); } else { std::cerr << "ERROR: Renderable JSON ctor failed to generate model for unknown type." << std::endl; } } else { // use model loading std::string mPath = json["model_path"].get<std::string>(); std::string tPath = json["texture_path"].get<std::string>(); std::string key = mPath + tPath; // use cached model if possible Model* model = ResourceCache<Model>::Instance().Get(key); if (model == nullptr) { model = ModelLoader::loadModel(mPath); if (tPath.size() > 0) model->setTexture(new std::string(tPath)); ResourceCache<Model>::Instance().Add(key, model); } c->_model = model; } return c; } PrefabRegistrar Renderable::reg("Renderable", &Renderable::CreateFromJson); #pragma endregion
true
4ee9ef9802894473365a562b6f1cc8eccb3f4e24
C++
moevm/oop
/6381/GerasimovaDV/Lab2/EllipseSector.h
UTF-8
1,085
3.234375
3
[]
no_license
#ifndef OOP_ELLIPSESECTOR_H #define OOP_ELLIPSESECTOR_H #include "Shape.h" class EllipseSector : public Shape { public: EllipseSector(Point* center, float R1, float R2, float start_angle, float end_angle, Color* color, int id); Point* getCenterPoint() override; float area() override; ostream& printShape(ostream& stream, Shape& figure) const override { stream << fixed << setprecision(3); stream << "Фигура: сектор эллипса" << endl; stream << "Идентификационный номер объекта: " << figure.getId() << endl; stream << "Цвет фигуры: " << figure.getColor()->getRed() << " " << figure.getColor()->getGreen() << " " << figure.getColor()->getBlue() << endl; stream << "Координаты, задающие фигуру:" << endl; for(Point* point : figure.getPoints()) { stream << "(" << point->x() << ";" << point->y() << ")" << endl; } return stream; } private: float rad; }; #endif //OOP_ELLIPSESECTOR_H
true
0a222dcfa4c8b371aad8d1f888505aeec85ad9cb
C++
vandrw/K-armed_Bandits
/src/bandit.cpp
UTF-8
5,848
2.78125
3
[]
no_license
#include <random> #include <iostream> #include <vector> #include <cmath> #include "bandit.h" #include "distrib.h" #include "user.h" using namespace std; Bandit::Bandit(Parameters param) { algorithm = param.algorithm; K = param.K_arms; distribution = param.distrib; switch (algorithm) { case 1: epsilon = param.epsilon; break; case 2: optimisticValue = param.optimisticValue; break; case 3: armPreference.resize(K, 0.0); alpha = param.alpha; betav = param.beta; break; case 4: exploreDegree = param.exploreDegree; break; default: break; } // If the algorithm chosen is not Optimistic Initial Values, // the optimisticValue variable will be set to 0, thus // initializing the observed rewards realistically. observedRewards.resize(K, optimisticValue); // Initializing the frequency array with zeros. armChoice.resize(K, 0); allRewards.resize(T*N, 0.0); optimalChoice.resize(T*N, 0); } void Bandit::reinitBandit() { counter = 0; std::fill(observedRewards.begin(), observedRewards.end(), optimisticValue); std::fill(armChoice.begin(), armChoice.end(), 0); if (algorithm == 3) { std::fill(armPreference.begin(), armPreference.end(), 0.0); referenceReward = 1.5; } } void Bandit::makeExperiment(std::vector<double> &arms) { for (int i=0; i<N; i++) { reinitBandit(); realMaxIndex = initializeArms(K, distribution, arms); makeRun(arms); } printStats(arms); } void Bandit::makeRun(std::vector<double> &arms) { for (int i=0; i<T; i++) { makeStep(arms); } } double Bandit::makeStep(std::vector<double> &arms) { int rewardIndex; double reward; switch (algorithm) { case 1: // Epsilon-Greedy rewardIndex = EpsilonGreedy(); break; case 2: // Optimistic initial values rewardIndex = OptimisticInit(); break; case 3: // Reinforcement comparison rewardIndex = ReinforcementCompar(); break; case 4: // UCB rewardIndex = UCB(); break; default: break; } switch (distribution) { case 1: // Normal { reward = rewardGaussian(arms[rewardIndex]); break; } case 2: // Bernoulli { reward = rewardBernoulli(arms[rewardIndex]); break; } default: { break; } } armChoice[rewardIndex]++; if (rewardIndex == realMaxIndex) { optimalChoice[simCounter] = 1; } else { optimalChoice[simCounter] = 0; } allRewards[simCounter] = reward; simCounter++; counter++; if (observedRewards[rewardIndex] == 0) { observedRewards[rewardIndex] = reward; } else { observedRewards[rewardIndex] = (observedRewards[rewardIndex] + reward) / 2; } if ((algorithm != 4) && (algorithm != 3)) { if (observedRewards[rewardIndex] > observedRewards[indexMaxReward]) { indexMaxReward = rewardIndex; } } if (algorithm == 3) { armPreference[indexMaxReward] += betav * (reward - referenceReward); referenceReward = referenceReward + alpha * (reward - referenceReward); } return reward; } // Exporation/Expoilation algorithms int Bandit::EpsilonGreedy() { random_device generator; uniform_real_distribution<double> realDist(0.0, 1.0); double rewardIndex; double check = realDist(generator); if (check <= epsilon) { rewardIndex = explore(); } else { rewardIndex = exploit(); } return rewardIndex; } int Bandit::OptimisticInit() { return exploit(); } int Bandit::ReinforcementCompar() { random_device generator; uniform_real_distribution<double> realDist(0.0, 1.0); double sumExp=0.0; double prob, maxProb=-10.0; int rewardIndex; double check = realDist(generator); for (int i=0; i<K; i++) { sumExp += exp(armPreference[i]); } for (int i=0; i<K; i++) { prob = exp(armPreference[i])/ sumExp; if ( prob > maxProb ) { maxProb = prob; indexMaxReward = i; } } if (check <= armPreference[indexMaxReward]) { rewardIndex = explore(); } else { rewardIndex = indexMaxReward; } return rewardIndex; } int Bandit::UCB() { int maxReward=-10; int rewardUCB; for (int i=0; i<K; i++) { if (armChoice[i] == 0) { return i; } rewardUCB = observedRewards[i] + exploreDegree * sqrt(log(counter) / armChoice[i]); if (rewardUCB > maxReward) { maxReward = rewardUCB; indexMaxReward = i; } } return indexMaxReward; } int Bandit::explore() { random_device generator; uniform_int_distribution<int> intDist(0, K-1); int choice = intDist(generator); return choice; } int Bandit::exploit() { int maxReward=-10; for (int i=0; i<K; i++) { if (observedRewards[i] > maxReward) { maxReward = observedRewards[i]; indexMaxReward = i; } } return indexMaxReward; } void Bandit::printStats(std::vector<double> &arms) { cout << "The choices were made as follows:\n\n"; cout << "Index" << "\tNum. Choices" << "\tObserved" << "\tReal\n"; for (int i=0; i<K;i++) { cout << " " << i << "\t" << armChoice[i] << "\t\t" << observedRewards[i] << "\t" << arms[i] << "\n"; } }
true
60b73f903a5b80bad0a00edf658466d82c9e1457
C++
felipe241920/TALLER-NO.3
/Taller 3/Taller 3/If/Punto 2 C.cpp
UTF-8
488
3.609375
4
[]
no_license
/* * Programa: numero menor * Fecha: 21-08-2018 * Elaborado por: Felipe Henao */ #include <stdio.h> using namespace std; //Funcion principal int main(int argc, char *argv[]) { float num1,num2,num3,menor; printf("\nIngrese tres numeros para saber cual es el menor\n"); scanf("%f %f %f",&num1,&num2,&num3); if(num1<num2 && num1<num3) { menor=num1; } else if(num2<num3) { menor=num2; } else { menor=num3; } printf ("\nEl numero menor es: %.2f ",menor); return 0; }
true
5716628e05479081341cc43a641768233c90cc3a
C++
davidhwang-rtr/qt_test
/tableview/inc/flashingled.h
UTF-8
1,508
2.859375
3
[]
no_license
#ifndef FLASHINGLED_H #define FLASHINGLED_H #include <QWidget> class QTimer; class FlashingLed : public QWidget { Q_OBJECT Q_PROPERTY(double diameter READ diameter WRITE setDiameter) // mm Q_PROPERTY(QColor color READ color WRITE setColor) Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment) Q_PROPERTY(bool state READ state WRITE setState) Q_PROPERTY(bool flashing READ isFlashing WRITE setFlashing) Q_PROPERTY(int flashRate READ flashRate WRITE setFlashRate) public: explicit FlashingLed(QWidget* parent=nullptr); ~FlashingLed(); double diameter() const; void setDiameter(double diameter); QColor color() const; void setColor(const QColor& color); Qt::Alignment alignment() const; void setAlignment(Qt::Alignment alignment); bool state() const; bool isFlashing() const; int flashRate() const; public slots: void setState(bool state); void toggleState(); void setFlashing(bool flashing); void setFlashRate(int rate); void startFlashing(); void stopFlashing(); public: int heightForWidth(int width) const; QSize sizeHint() const; QSize minimumSizeHint() const; protected: void paintEvent(QPaintEvent* event); private: double diameter_; QColor color_; Qt::Alignment alignment_; bool initialState_; bool state_; int flashRate_; bool flashing_; // // Pixels per mm for x and y... // int pixX_, pixY_; // // Scaled values for x and y diameter. // int diamX_, diamY_; QRadialGradient gradient_; QTimer* timer_; }; #endif
true
742d787779192824c916e12c93bf840ddb4ed7c8
C++
NBAlexis/GiNaCToolsVC
/Code/CLN/src/integer/output/cl_I_print_string.cc
UTF-8
997
2.671875
3
[]
no_license
// print_integer_to_string(). // General includes. #include "cln_private.h" // Specification. #include "cln/integer_io.h" // Implementation. #include "integer/cl_I.h" #include "base/digitseq/cl_DS.h" #include "base/string/cl_sstring.h" namespace cln { char * print_integer_to_string (unsigned int base, const cl_I& z) { var bool minus_p = false; var cl_I abs_z; if (minusp(z)) { // z<0 -> später Vorzeichen ausgeben: minus_p = true; abs_z = -z; } else abs_z = z; CL_ALLOCA_STACK; var uintC need = 1+cl_digits_need(abs_z,base); var uintB* ziffern = cl_alloc_array(uintB,need); // Platz für die Ziffern var cl_digits erg; erg.LSBptr = &ziffern[need]; I_to_digits(abs_z,(uintD)base,&erg); // Umwandlung in Ziffern // Vorzeichen ankleben: var char* ergptr = (char*)erg.MSBptr; var uintC erglen = erg.len; if (minus_p) { *--ergptr = '-'; erglen++; } var char* result = cl_sstring(ergptr,erglen); // Ziffern in String schreiben return result; } } // namespace cln
true
ef62f8639abaa99dc074847d5b6531debfa7c1c8
C++
pranav245/CP2_CIPHERSCHOOLS
/239.SlidingWindow My solution.cpp
UTF-8
551
2.921875
3
[]
no_license
class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { deque<int> dq; int m=nums[0]; for(int i=0;i<k;i++) { if(nums[i]>m) m=nums[i]; dq.push_back(nums[i]); } vector<int> v; v.push_back(m); for(int i = k;i<nums.size();i++) { dq.push_back(nums[i]); dq.pop_front(); m = *max_element(dq.begin(),dq.end()); v.push_back(m); } return v; } };
true
207d537575a5a18d695e9e1d3c1e2e4b330129ce
C++
romanaminov/slot_machine.
/headers/wheel.h
UTF-8
1,753
3.09375
3
[]
no_license
#ifndef WHEEL_H #define WHEEL_H #include "headers/object.h" #include <ctime> #include "headers/textureobjectmanager.h" /* Cass Wheel наслеуется от Object */ // Состояние барабана enum WheelState { _stopped, _running }; class Wheel: public Object { public: Wheel(WheelState _state, double _lb_xrf, double _lb_yrf, double _rt_xrf, double _rt_yr); ~Wheel(); // Запускает вращение барабана void Start(); // Останавливает вращение барабана void Stop(); virtual void Update(); private: // Связанные текстуры. std::shared_ptr<TextureObjectManager> wheel; // Время момента начала вращения барабана std::time_t lastTime; // Текущее время std::time_t currentTime; // Время, которое барабан бует вращаться double rotatingTime; // Текущая "скорость вращения" double rotatingSpeed; // Доп угол ля оворота при остановке барабана double currentAnngle; // Тормоз вращения double brake; //Состояние ВЫКЛ барабанов bool stopStatus; // Позиция, на которой в данный момент находится барабан // необходима для подсчёта результатов // Угол доворота double adjustmenAngle; // Счётчик итераций доворота int currentAdjustmentCount; // Максимальное значение счётчика const static int AdjustmentCount = 250; }; #endif // WHEEL_H
true
5f6d97e26393a750d96b1ebb71b9e6fc894690f0
C++
imulan/procon
/aoj/vol5/0556.cpp
UTF-8
436
2.765625
3
[]
no_license
#include <cstdio> #include <iostream> #include <utility> using namespace std; int main(){ long n; int k; scanf(" %ld", &n); scanf(" %d", &k); for(int i=0; i<k; ++i){ long a, b; scanf(" %ld %ld", &a, &b); //対称性を利用して折り返し(1/8サイズになる) if(a > (n+1)/2) a=n-a+1; if(b > (n+1)/2) b=n-b+1; if(a<b) swap(a,b); long ans=b%3; if(ans==0) ans=3; printf("%ld\n", ans); } return 0; }
true
5914e9a7c99d730c4cf4741d154beae9efcfabb0
C++
TheMetabug/Fysiikkakoodaus
/Operaattorit/Operaattorit/Main.cpp
UTF-8
3,349
3.078125
3
[]
no_license
#include <iostream> #include "Vector2D.h" #include "Vector3D.h" #include "Matrix3.h" #include "Matrix4.h" #include "Quaternion.h" using namespace std; int main(void) { Vector3D vektor_1(1.f,1.f,3.f); Vector3D vektor_2(2.f,1.f,3.f); float matriisi_1[] = { 1.5f , 0.0f , 0.0f, 0.0f , 1.2f , 0.0f, 0.0f , 0.0f , 1.0f }; Matrix3 matrix_1(matriisi_1); Matrix3 matrix_2( 2.0f , 1.0f , 1.0f, 3.0f , 3.0f , 4.0f, 1.0f , 2.0f , 5.0f); Matrix4 matrix_3( 2.0f , 1.0f , 1.0f, 1.0f, 3.0f , 3.0f , 4.0f, 1.0f, 1.0f , 2.0f , 5.0f, 1.0f, 2.0f , 1.0f , 2.0f, 1.0f); Matrix4 matrix_4( 1.0f , 3.0f , 2.0f, 4.0f, 1.0f , 1.0f , 2.0f, 2.0f, 3.0f , 1.0f , 2.0f, 1.0f, 1.0f , 2.0f , 2.0f, 3.0f); Quaternion quaternion_1(2.f,3.f,4.f,5.f); Quaternion quaternion_2(1.f,1.f,2.f,2.f); cout << "_________________VEKTORI3 LASKUT__________________" << endl; cout << "Vektori 1: " << vektor_1 << " Pituus: " << vektor_1.length() << endl; cout << "Vektori 2: " << vektor_2 << " Pituus: " << vektor_2.length() << endl; cout << "Summa: " << vektor_1+vektor_2 << endl; cout << "Erotus: " << vektor_1-vektor_2 << endl; cout << "Pistetulo: " << vektor_1.dot(vektor_1,vektor_2) << endl; cout << "Ristitulo: " << vektor_1.cross(vektor_2) << endl; cout << "Normalisointi: " << vektor_1.normalize() << endl; cout << "_________________MATRIISI LASKUT__________________" << endl; cout << "Matriisi 1: \n" << matrix_1 << endl << endl; cout << "Matriisi 2: \n" << matrix_2 << endl << endl; cout << "Summa: \n" << matrix_1 + matrix_2 << endl << endl; cout << "Tulo: \n" << matrix_1 * matrix_2 << endl<< endl; cout << "Determinantti: \n" << matrix_1.determ() << endl << endl; cout << "Tansponointi: \n" << matrix_2.Transpose() << endl << endl; cout << "Kaanteismatriisi: \n" << matrix_1.Revert() << endl << endl << endl; cout << "Matriisi 3 (4x4): \n" << matrix_3 << endl << endl; cout << "Matriisi 4 (4x4): \n" << matrix_4 << endl << endl; cout << "Skalaarilla kertominen: \n" << matrix_3*3 << endl << endl; cout << "Vektorilla kertominen: \n" << matrix_3*vektor_2 << endl << endl; cout << "Yhteenlasku: \n" << matrix_3+matrix_4 << endl << endl; cout << "Kertolasku: \n" << matrix_3*matrix_4 << endl << endl; cout << "Determinantti: (4x4) \n" << matrix_3.determ() << endl << endl; cout << "Kaanteismatriisi: (4x4) \n" << matrix_3.Inverse() << endl << endl << endl; cout << "_________________KVATERNIO LASKUT__________________" << endl; cout << "Kvaternio 1: \n" << quaternion_1 << endl << endl; cout << "Kvaternio 2: \n" << quaternion_2 << endl << endl; cout << "Kvaternioiden yhteenlasku: \n" << quaternion_1+quaternion_2 << endl << endl; cout << "Kvaternioiden erotus: \n" << quaternion_1-quaternion_2 << endl << endl; cout << "Kvaternioiden kertolasku: \n" << (quaternion_1*quaternion_2) << endl << endl; cout << "Kvaternio 1:sen normalisointi: \n" << quaternion_1.normalize() << endl << endl; Matrix3 matrix_5 = matrix_1; matrix_5.setOrientation(quaternion_1); cout << "Kvaternio 1:sen ja matriisi 1:sen orientaatio: \n" << matrix_5 << endl << endl; //Vector2D* A = new Vector2D(1.f,2.f); //Vector2D* B = new Vector2D(3.f,1.f); //A.print(); //B.print(); //Vector2D C(A+B); //C.print(); //C = A-B; //C.print(); //C = A*3; //C.print(); //float V = A*B; //std::cout << V << std::endl; return 0; }
true
8e701305716ec4a6d7aad3a26597edcd72014092
C++
Assianguyen/BE_Cpp
/Tests/test_sms2/test_sms2.ino
UTF-8
1,990
2.5625
3
[]
no_license
#include <Wire.h> #include <ESP8266WiFi.h> // WiFi network info. //const char *ssid = "ViewLiteAssia"; // Enter your WiFi Name //const char *pass = "3399fc7ac862"; // Enter your WiFi Password //const char *ssid = "Gathou"; // Enter your WiFi Name //const char *pass = "12345678"; // Enter your WiFi Password boolean fall=true; const char* ssid = "Livebox-43BA"; const char* pass = "mxsxmTxN32ZGeeRpjo"; void send_event(const char *event); const char *host = "maker.ifttt.com"; const char *privateKey = "KyzwOybgYJBeVvQQD_1IX"; void setup(){ Serial.begin(115200); Wire.begin(); Serial.println("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); // print ... till not connected } Serial.println(""); Serial.println("WiFi connected"); } void loop(){ if (fall==true){ //in event of a fall detection Serial.println("FALL DETECTED"); send_event("alarm_on"); fall=false; } delay(100); } void send_event(const char *event) { Serial.print("Connecting to "); Serial.println(host); // Use WiFiClient class to create TCP connections WiFiClient client; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println("Connection failed"); return; } // We now create a URI for the request String url = "/trigger/"; url += event; url += "/with/key/"; url += privateKey; Serial.print("Requesting URL: "); Serial.println(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); while(client.connected()) { if(client.available()) { String line = client.readStringUntil('\r'); Serial.print(line); } else { // No data yet, wait a bit delay(50); }; } Serial.println(); Serial.println("closing connection"); client.stop(); }
true
0b85f7ababfb529252fa28dc8e09d6425830415e
C++
AdnarLozano/School
/RCCD/CSC-7/Ch7 Probability of Movement/Source.cpp
UTF-8
635
3.171875
3
[]
no_license
#include <iostream> using namespace std; float temp[20]; void CalcP(float p[], float p_m, int size) { for (int i = 0; i < size; i++) { // at loc i and didnt move or at loc i-1 and moved if (i > 0) temp[i] = p[i] * (1 - p_m) + p[i - 1] * p_m; else temp[i] = p[i] * (1 - p_m); } memcpy(p, temp, sizeof(float)*size); } int main() { float p[20] = { 1, 0 }; float p_m = .9f; for (int t = 0; t < 100; t++) { cout << "t = " << t << endl; for (int i = 0; i < 20; i++) { cout << p[i] << "\t | "; } CalcP(p, p_m, 20); system("pause"); } return 0; }
true
c5c3c5c03a83a5de10a57ac1d38926505335b5bc
C++
andreas-volz/pluxx
/include/pluxx/Plugin.h
UTF-8
867
2.546875
3
[ "MIT" ]
permissive
#ifndef PLUGIN_H #define PLUGIN_H #include <string> #define PLUGIN_EXPORT extern "C" namespace pluxx { /* forward declarations */ class PluginLoader; class Plugin { public: friend class PluginLoader; /*! * Warning: Never call 'new' direct on Plugin! * Use PluginLoader::loadFactory() instead to create the object! */ Plugin () : mHandle (NULL) {} /*! * Warning: Never call 'delete' direct on Plugin! * Use PluginLoader::destroyFactory() instead to destroy the object! */ virtual ~Plugin () {} virtual const std::string getType () = 0; virtual const unsigned int getMajorVersion () = 0; virtual const unsigned int getMinorVersion () = 0; private: void setHandle (void *handle) {mHandle = handle;} void *getHandle () {return mHandle;} void *mHandle; }; } // end namespace pluxx #endif // PLUGIN_H
true
5a7924405bdf343b9589a21ad9aafac3647cf130
C++
melaphor/Arcade-Warrior
/arkade_warrior_jun05c.ino
UTF-8
13,504
2.625
3
[]
no_license
//teensy++ code for arcade warrior //tomash ghz //www.tomashg.com #include <Bounce.h> //debugging will print out in serial instead of midi boolean debugging=false; boolean traktorrr=false; //channel number for midi messages int midiChannel=3; //pin numbers for elements int leds[3]= { 20, 21, 22 }; int buttons[16]= { 5, 9, 13, 17, //first row 4, 8, 12, 16, 1, 7, 11, 15, 0, 6, 10, 14 }; int knobs[4]= { A2, A3, A0, A1 }; int faders[3]= { A7, A6, A5 }; //bank int bank=0; // pins for joystick buttons int joystic[4]= { 24, 26, 25, 23 }; // variables to store values Bounce *buttonState[16]; int knobVal[4]; int faderVal[3]; boolean joysticState[4]; int joysticVal[4]; // save the joystic cc values boolean ledState[3]; Bounce jUp = Bounce( joystic[0], 10 ); Bounce jDown = Bounce( joystic[1], 10 ); Bounce jLeft = Bounce( joystic[2], 10 ); Bounce jRight = Bounce( joystic[3], 10 ); int comboState=0; //state of the current combo int temp; //initialize values and set modes void setup() { //DEBUG if (debugging) { Serial.begin(9600);//open serail port } else { Serial.begin(31250);//open midi usbMIDI.setHandleNoteOn(myNoteOn); usbMIDI.setHandleNoteOff(myNoteOff); } //arcade buttons for (int i=0;i<16;i++) { pinMode(buttons[i], INPUT_PULLUP); buttonState[i]= new Bounce(buttons[i], 5); } pinMode(6, OUTPUT); //hope this doesnt fry the led //joystick buttons for (int i=0;i<4;i++) { pinMode(joystic[i], INPUT_PULLUP); joysticVal[i]=0; } // LEDS for (int i=0;i<3;i++) { pinMode(leds[i], OUTPUT); digitalWrite(leds[i], HIGH); delay(50); digitalWrite(leds[i], LOW); } //switch to traktor mode // to switch hold the lower left and right buttons while the device is booting for (int i=0;i<10;i++) { digitalWrite(leds[0], HIGH); delay(100); digitalWrite(leds[0], LOW); delay(100); if ((buttonState[0]->read()==LOW)&&(buttonState[3]->read()==LOW)) { traktorrr=true; //flash leds to indicate the mode change for (int i=0;i<10;i++) { digitalWrite(leds[0], HIGH); digitalWrite(leds[1], HIGH); digitalWrite(leds[2], HIGH); delay(100); digitalWrite(leds[0], LOW); digitalWrite(leds[1], LOW); digitalWrite(leds[2], LOW); delay(100); } break; } } } void loop() { //read buttons for (int i=0;i<16;i++) { if (buttonState[i]->update()) {//state changed if (buttonState[i]->read()==LOW) {//is pressed midiNoteOnOff(true, i+36+bank*16); } else { midiNoteOnOff(false, i+36+bank*16); } } }//end loop //read knobs and faders for (int i=0;i<4;i++) { temp=map(analogRead(knobs[i]), 0, 1023, 0, 127); if (temp!=knobVal[i]) { //value changed midiCC(temp, knobVal[i], i*2+16+bank*17); } knobVal[i]=temp; }// end loop for (int i=0;i<3;i++) { temp=map(analogRead(faders[i]), 0, 1023, 0, 127); if (temp!=faderVal[i]) { //value changed midiCC(temp, faderVal[i], i*2+24+bank*17); } faderVal[i]=temp; }// end loop // read joystic guestures readJoystic(); // update leds depending on bank switch(bank) { case 0: ledState[0]=false; ledState[1]=false; ledState[2]=false; break; case 1: ledState[0]=true; ledState[1]=false; ledState[2]=false; break; case 2: ledState[0]=true; ledState[1]=true; ledState[2]=false; break; case 3: ledState[0]=true; ledState[1]=true; ledState[2]=true; break; } // update leds for (int i=0;i<3;i++) { digitalWrite(leds[i], ledState[i]); } //recieve MIDI messages if (!debugging) { usbMIDI.read(); } } // function to handle noteon outgoing messages void midiNoteOnOff(boolean s, int n) { //check if the key pressed is part of any secret combo if (traktorrr) { checkCombo(s); } if (s) { if (debugging) {//debbuging enabled Serial.print("Button "); Serial.print(n); Serial.println(" pressed."); } else { usbMIDI.sendNoteOn(n, 127, midiChannel); } } else { if (debugging) {//debbuging enabled Serial.print("Button "); Serial.print(n); Serial.println(" released."); } else { usbMIDI.sendNoteOff(n, 0, midiChannel); } } } //function to check for secret combos void checkCombo(boolean s) { // from MIDI Fighter Pro documentation: // COMBOS // // A B C D E // +--------+ +--------+ +--------+ +--------+ +--------+ // | | | | | | | | | | // | | | | | 3 4 | | | |u | // | | |n n n n | | 1 2 | |a b c d | |l r A B | // |1 2 3 4 | | | | | | | |d | // +--------+ +--------+ +--------+ +--------+ +--------+ // a-b-c-c-d uuddlrlrBA // // Combos retain a NoteOn while the final key is depressed and emit a NoteUp // when it is released. // Combo A G#-2 // Combo B A-2 // Combo C A#-2 // Combo D B-2 // Combo E C-1 // lets simplify things a bit :) // A B C D E // +--------+ +--------+ +--------+ +--------+ +--------+ // | | | | | | | | | | // | | | | | x x | | | |x | // | | |x x x x | | x x | | x x x | | x x | // |x x x x | | | | | | | |x | // +--------+ +--------+ +--------+ +--------+ +--------+ //no combo active and a button is pressed if ((comboState==0)&&(s)) { // combo A if ((buttonState[0]->read()==LOW) &&(buttonState[1]->read()==LOW) &&(buttonState[2]->read()==LOW) &&(buttonState[3]->read()==LOW)) { comboState=1; usbMIDI.sendNoteOn(8, 127, midiChannel); } else //combo B if ((buttonState[4]->read()==LOW) &&(buttonState[5]->read()==LOW) &&(buttonState[6]->read()==LOW) &&(buttonState[7]->read()==LOW)) { comboState=2; usbMIDI.sendNoteOn(9, 127, midiChannel); } else //combo C if ((buttonState[5]->read()==LOW) &&(buttonState[6]->read()==LOW) &&(buttonState[9]->read()==LOW) &&(buttonState[10]->read()==LOW)) { comboState=3; usbMIDI.sendNoteOn(10, 127, midiChannel); } else //combo D if ((buttonState[5]->read()==LOW) &&(buttonState[6]->read()==LOW) &&(buttonState[7]->read()==LOW)) { comboState=4; usbMIDI.sendNoteOn(11, 127, midiChannel); } else //combo E if ((buttonState[0]->read()==LOW) &&(buttonState[8]->read()==LOW) &&(buttonState[6]->read()==LOW) &&(buttonState[7]->read()==LOW)) { comboState=5; usbMIDI.sendNoteOn(12, 127, midiChannel); } } else if ((comboState!=0)&&(!s)) {//combo was active and released switch(comboState) { case 1: usbMIDI.sendNoteOff(8, 0, midiChannel); break; case 2: usbMIDI.sendNoteOff(9, 0, midiChannel); break; case 3: usbMIDI.sendNoteOff(10, 0, midiChannel); break; case 4: usbMIDI.sendNoteOff(11, 0, midiChannel); break; case 5: usbMIDI.sendNoteOff(12, 0, midiChannel); break; } comboState=0; } } // function to handle cc outgoing messages void midiCC(int v, int oldv, int n) { if (debugging) {//debbuging enabled Serial.print("Potentiometer "); Serial.print(n); Serial.print(" changed value to "); Serial.println(v); } else { usbMIDI.sendControlChange(n, v, midiChannel); //send the advanced traktor midi messages // 0 3 64 124 127 // |--|-------------|-------------|--| - full range // // |0=======================127| - CC A // |0=========105| - CC B // // |__|on____________________________| - note A // |off___________________________|on| - note B // 3 124 if (traktorrr) { if ((v>3)&&(oldv<=3)) { // send the 0 value note on usbMIDI.sendNoteOn(n+84, 127, midiChannel); } else if ((v<=3)&&(oldv>3)) { usbMIDI.sendNoteOff(n+84, 127, midiChannel); } if ((v>124)&&(oldv<=124)) { // send the 127 value note on usbMIDI.sendNoteOn(n+85, 127, midiChannel); } else if ((v<=124)&&(oldv>124)) { usbMIDI.sendNoteOff(n+85, 127, midiChannel); } if (v<=64) //send secondary cc usbMIDI.sendControlChange(n+1, map(v, 0, 64, 0, 105), midiChannel); } } } void readJoystic() { //up joystick if ( jUp.update() ) {//state changed if ( jUp.read() != HIGH) {// it is pressed if ( joysticState[0] == LOW ) {//last state was low joysticState[0] = HIGH; midiNoteOnOff(true, 4); } } else {// it was released if ( joysticState[0] == HIGH ) {//last state was low joysticState[0] = LOW; joysticVal[0]=0; if (debugging) { Serial.println(joysticVal[0]); } else { usbMIDI.sendControlChange(30, joysticVal[0], midiChannel); } //midiNoteOnOff(true,4); midiNoteOnOff(false, 4); } } } else {//state didnot change if ( jUp.read() != HIGH) {//is held on if (jUp.duration()>500) {// was held longer than half sec if (jUp.duration()%100>90) {//increment the value joysticVal[0]++; joysticVal[0]=constrain(joysticVal[0], 0, 127); if (debugging) { Serial.println(joysticVal[0]); } else { usbMIDI.sendControlChange(30, joysticVal[0], midiChannel); } } } } } //down joystick if ( jDown.update() ) {//state changed if ( jDown.read() != HIGH) {// it is pressed if ( joysticState[1] == LOW ) {//last state was low joysticState[1] = HIGH; midiNoteOnOff(true, 5); } } else {// it was released if ( joysticState[1] == HIGH ) {//last state was low joysticState[1] = LOW; joysticVal[1]=0; if (debugging) { Serial.println(joysticVal[1]); } else { usbMIDI.sendControlChange(31, joysticVal[1], midiChannel); } //midiNoteOnOff(true,5); midiNoteOnOff(false, 5); } } } else {//state didnot change if ( jDown.read() != HIGH) {//is held on if (jDown.duration()>500) {// was held longer than half sec if (jDown.duration()%100>95) {//increment the value joysticVal[1]++; joysticVal[1]=constrain(joysticVal[1], 0, 127); if (debugging) { Serial.println(joysticVal[1]); } else { usbMIDI.sendControlChange(31, joysticVal[1], midiChannel); } } } } } //left joystick if ( !jLeft.update() ) {//state didnot change if ( jLeft.read() != HIGH) {//is held on if (traktorrr) { if (jLeft.duration()%100>85)//increment the value usbMIDI.sendControlChange(32, 63, midiChannel); //act as rotary encoder } if ( joysticState[2] == LOW ) {//last state was low joysticState[2] = HIGH; if (!traktorrr) { // decrease the bank number if (bank==0) bank=3; else bank=bank-1; } else usbMIDI.sendNoteOn(0, 127, midiChannel); } } else {// it was released if ( joysticState[2] == HIGH ) {//last state was low joysticState[2] = LOW; usbMIDI.sendNoteOff(0, 127, midiChannel); } } } //right joystick if ( !jRight.update() ) {//state didnot change if ( jRight.read() != HIGH) {//is held on if (traktorrr) { if (jRight.duration()%100>85)//increment the value usbMIDI.sendControlChange(32, 65, midiChannel); //act as rotary encoder } if ( joysticState[3] == LOW ) {//last state was low joysticState[3] = HIGH; if (!traktorrr) // increase the bank number bank=(bank+1)%4; else usbMIDI.sendNoteOn(0, 127, midiChannel); } } else {// it was released if ( joysticState[3] == HIGH ) {//last state was low joysticState[3] = LOW; usbMIDI.sendNoteOff(0, 127, midiChannel); } } } } //event handlers for recieved note ons void myNoteOn(byte channel, byte note, byte velocity) { if (channel==midiChannel) { //determine which led to turn on if (note==(byte)0) ledState[0]=true; if (note==(byte)1) ledState[1]=true; if (note==(byte)2) ledState[2]=true; } if ((channel==midiChannel)&&(velocity==0)) { //traktor note off if (note==(byte)0) ledState[0]=false; if (note==(byte)1) ledState[1]=false; if (note==(byte)2) ledState[2]=false; } } void myNoteOff(byte channel, byte note, byte velocity) { if (channel==midiChannel) { if (note==(byte)0) ledState[0]=false; if (note==(byte)1) ledState[1]=false; if (note==(byte)2) ledState[2]=false; } }
true
e9d922645e12f4a800c11c5ccb6c3a1e604fa281
C++
Magiczne/MidiCreator
/MidiCreator/Sequence.cpp
UTF-8
8,325
2.703125
3
[]
no_license
#include "Sequence.h" #include "SequenceNote.h" #include "SequenceFile.h" #include "SMF/StandardMIDIFile.h" #include "SMF/HeaderChunk.h" #include "SMF/Exceptions/NoTracksException.h" using namespace SMF; using namespace SMF::Exceptions; using namespace std; Sequence::Sequence() { this->name("New Sequence"); this->format(FileFormat::SINGLE_TRACK); this->tempo(130); this->setMeasure(6, 8); this->_firstBarToShow = 1; this->_firstPitchToShow = NotePitch::C3; this->_currentChannel = MIDIChannel::CHANNEL_1; this->_currentNote = 0; this->_currentNotePitch = 0; this->_current32NoteInBar = 0; for(uint8_t i = 0; i < 16; i++) { _channelPatches[static_cast<MIDIChannel>(i)] = GMPatch::ACOUSTIC_GRAND_PIANO; } } void Sequence::loadFromFile(const SequenceFile& file) { this->name(file.name); this->format(static_cast<FileFormat>(file.fileFormat)); this->numerator(file.numerator); this->denominator(file.denominator); if(this->hasNotes()) { for (auto& map : this->_notes) { map.clear(); } } for(const auto& note : file.notesData) { this->currentChannel(static_cast<MIDIChannel>(note.channel)); this->addNote( { static_cast<NotePitch>(note.notePitch), note.barNumber }, note.barPosition, note.noteVolume, note.noteDuration, note.noteLigature == 0x00 ? false : true ); } } bool Sequence::showPreviousBar() { if (this->_firstBarToShow > 1) { this->_firstBarToShow--; return true; } return false; } bool Sequence::showNextBar(uint16_t pianoRollWidth) { if (this->_firstBarToShow < Sequence::MAX_BAR - (pianoRollWidth / this->_numerator) + 1) { this->_firstBarToShow++; return true; } return false; } bool Sequence::showPreviousNote() { if (this->_firstPitchToShow > NotePitch::C_MINUS_1) { this->_firstPitchToShow = NotePitch(static_cast<uint8_t>(this->_firstPitchToShow) - 1); return true; } return false; } bool Sequence::showNextNote(uint16_t pianoRollHeight) { if (static_cast<uint8_t>(this->_firstPitchToShow) < static_cast<uint8_t>(NotePitch::G9) - pianoRollHeight + 1) { this->_firstPitchToShow = NotePitch(static_cast<uint8_t>(this->_firstPitchToShow) + 1); return true; } return false; } bool Sequence::moveIndicatorUp() { if (this->_currentNotePitch > 0) { this->_currentNotePitch--; return true; } return false; } bool Sequence::moveIndicatorDown(uint16_t pianoRollHeight) { if (this->_currentNotePitch < pianoRollHeight - 1U) { this->_currentNotePitch++; return true; } return false; } bool Sequence::moveIndicatorLeft() { if (this->_currentNote > 0) { this->_currentNote--; return true; } return false; } bool Sequence::moveIndicatorRight(uint16_t pianoRollWidth) { if (this->_currentNote < pianoRollWidth - 1U) { this->_currentNote++; return true; } return false; } bool Sequence::moveCloseUpIndicatorLeft() { if(this->_current32NoteInBar > 0) { this->_current32NoteInBar--; return true; } return false; } bool Sequence::moveCloseUpIndicatorRight() { if(this->_current32NoteInBar < this->_numOf32NotesInBar -1) { this->_current32NoteInBar++; return true; } return false; } vector<shared_ptr<SequenceNote>>& Sequence::getBar(PianoRollCoords coords) { return this->_notes[static_cast<uint8_t>(this->_currentChannel)][coords]; } #pragma region Note manipulation shared_ptr<SequenceNote> Sequence::getNote(PianoRollCoords coords, uint8_t index) { uint8_t channel = static_cast<uint8_t>(this->_currentChannel); if (this->_notes[channel].find(coords) == this->_notes[channel].end()) { return nullptr; } if (this->_notes[channel][coords].size() == 0) { return nullptr; } return this->_notes[channel][coords][index]; } shared_ptr<SequenceNote> Sequence::getCurrentNote() { return this->getNote(this->getCurrentNoteCoords(), this->_current32NoteInBar); } PianoRollCoords Sequence::getCurrentNoteCoords() const { uint8_t pitch = static_cast<uint8_t>(this->_firstPitchToShow) + this->_currentNotePitch; unsigned note = (this->_firstBarToShow - 1) * this->_numerator + this->_currentNote; return { NotePitch(pitch), note }; } bool Sequence::isNotePositionEmpty(const PianoRollCoords& coords, const uint8_t index, const uint8_t channel) { //Theoretically can happen if (this->_notes[channel].find(coords) == this->_notes[channel].end()) { this->_notes[channel][coords] = vector<shared_ptr<SequenceNote>>(0); } //No bar position data found in map. We need to create empty vector of notes //To represent that bar position, and fill them with nullptrs //Size is that many 32nd notes that can be held by denominator if (this->_notes[channel][coords].size() == 0) { size_t newSize = static_cast<size_t>(pow(2, 5 - log2(this->_denominator))); this->_notes[channel][coords].resize(newSize, nullptr); return true; } if (this->_notes[channel][coords][index] != nullptr) { return false; } return true; } bool Sequence::addNote(PianoRollCoords coords, uint8_t index, uint8_t volume, uint16_t duration, bool ligature) { uint8_t channel = static_cast<uint8_t>(this->_currentChannel); auto res = isNotePositionEmpty(coords, index, channel); if(res) { this->_notes[channel][coords][index] = make_shared<SequenceNote>(coords.pitch(), volume, duration, ligature); return true; } return res; } bool Sequence::addNote(PianoRollCoords coords, uint8_t index) { uint8_t channel = static_cast<uint8_t>(this->_currentChannel); auto res = isNotePositionEmpty(coords, index, channel); if (res) { this->_notes[channel][coords][index] = make_shared<SequenceNote>(coords.pitch()); return true; } return res; } bool Sequence::addNoteAtCurrentPosition() { auto coords = this->getCurrentNoteCoords(); auto ret = this->addNote(coords, this->_current32NoteInBar); return ret; } bool Sequence::removeNote(PianoRollCoords coords, uint8_t index) { uint8_t channel = static_cast<uint8_t>(this->_currentChannel); if(this->_notes[channel].find(coords) == this->_notes[channel].end()) { return false; } if(this->_notes[channel][coords][index] == nullptr) { return false; } this->_notes[channel][coords][index] = nullptr; return true; } bool Sequence::removeNoteAtCurrentPosition() { auto coords = this->getCurrentNoteCoords(); return this->removeNote(coords, this->_current32NoteInBar); } #pragma endregion void Sequence::setMeasure(const uint16_t numerator, const uint16_t denominator) { this->_numerator = numerator; this->_denominator = denominator; this->_numOf32NotesInBar = static_cast<uint8_t>(pow(2, 5 - log2(this->_denominator))); } bool Sequence::hasMultipleTracks() { int trackCounter = 0; for(const auto& map : this->_notes) { for(const auto& pair : map) { for(const auto& ptr : pair.second) { if (ptr != nullptr) { trackCounter++; } } } if(trackCounter > 1) { return true; } } return false; } StandardMIDIFile Sequence::toMidiFile() { bool multipleTracks = this->hasMultipleTracks(); StandardMIDIFile smf; //HeaderChunk smf.setHeader(multipleTracks ? FileFormat::MULTIPLE_TRACK : FileFormat::SINGLE_TRACK); UI::Util::debug(multipleTracks ? "MULT\n" : "SING\n"); try { smf.setTimeSignature(this->numerator(), this->denominator()); smf.setTempo(this->tempo()); } catch(NoTracksException) { smf.addTrack(); smf.setTimeSignature(this->numerator(), this->denominator()); smf.setTempo(this->tempo()); } size_t repetitions = multipleTracks ? 16 : 1; for(size_t i = 0; i < repetitions; i++) { UI::Util::debug("Track " + to_string(i) + "\n"); smf.setCurrentTrack(i + 1); smf.setVoiceProgram(this->_channelPatches[static_cast<MIDIChannel>(i)]); //system("cls"); for(const auto& pair : this->_notes[i]) { //cout << "this->_notes[" << i << "][" << NotePitchMap[pair.first.pitch()] << ", " << pair.first.notePosition() << "]"; for(size_t j = 0; j < pair.second.size(); j++) { //CRITICAL: Currently without support for ligatures(only 32nds), or even pauses XD //cout << "[" << j << "]"; if(pair.second[j] != nullptr) { smf.addNote( pair.second[j]->pitch(), pair.second[j]->volume(), pair.second[j]->duration() * smf.get32NoteDuration() ); //cout << " -> Data present "; } //cout << endl; } //system("pause"); } } return smf; }
true
32c5cfc72835246434fd91363edf78b59202a53f
C++
kravtsun/au-cg
/salute/src/gl_holder.cpp
UTF-8
2,457
2.53125
3
[ "MIT" ]
permissive
#include <memory> #include <cassert> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include "glfw_window_manager.h" #include "gl_holder.h" GLHolder::GLHolder(std::shared_ptr<GLFWWindowManager> window_manager) : window_manager(window_manager) , salutes_combiner_pass(width(), height()) , passthrough_pass(width(), height()) , sky_pass(width(), height(), "black_clouds.bmp") { assert(glGetError() == GL_NO_ERROR); } void GLHolder::add_salute(double x, double y) { x = (x / width() - 0.5) * 2 * FramePass::limit; y = (0.5 - y / height()) * 2 * FramePass::limit; const glm::vec3 position{x, y, 0}; glm::vec3 color{1, 1, 1}; for (int i = 0; i < 3; ++i) { color[i] = static_cast<float>(rand()) / RAND_MAX; } const int nparticles = (rand() % 10 + 1) * 100; const float speed_magnitude = (rand() % 10 + 3) * 5.f; salutes.push_back(std::make_shared<SalutePass>(width(), height(), position, color, nparticles, speed_magnitude)); } void GLHolder::paint() { static bool is_paused = false; if (glfwGetKey(window_manager->window(), GLFW_KEY_SPACE) == GLFW_PRESS) { is_paused = !is_paused; } if (is_paused) { return; } if (glfwGetKey(window_manager->window(), GLFW_KEY_ENTER) == GLFW_PRESS) { for (auto &salute : salutes) { salute->reset(); } } sky_pass.pass(); salutes_combiner_pass.reset(); salutes_combiner_pass.set_input_texture(sky_pass.output_texture()); salutes_combiner_pass.pass(); for (auto it = salutes.begin(); it != salutes.end(); ) { auto &salute = *it; if (!salute->is_alive()) { it = salutes.erase(it); } else { salute->pass(); salutes_combiner_pass.set_input_texture(salute->output_texture()); salutes_combiner_pass.pass(); ++it; } } passthrough_pass.set_input_texture(salutes_combiner_pass.output_texture()); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, width(), height()); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); passthrough_pass.pass(); assert(glGetError() == GL_NO_ERROR); } GLHolder::~GLHolder() = default; int GLHolder::width() const { return window_manager->win_width(); } int GLHolder::height() const { return window_manager->win_height(); }
true
1adb50fda8cd824e0be78daaf5cf0b50d43a90f5
C++
Wikzo/CPP_FirstTutorials
/menu_chooser.cpp
UTF-8
658
3.84375
4
[]
no_license
// Menu Chooser // Demonstrates the switch statement #include <iostream> using namespace std; int main() { cout << "Choose a difficulty:\n\n"; cout << "1 - EASY\n2 - NORMAL\n3 - HARD\n\n"; int choice; cout << "Choice: "; cin >> choice; switch (choice) { case 1: cout << "You picked EASY"; break; case 2: cout << "You picked NORMAL"; break; case 3: cout << "You picked HARD"; break; default: cout << "You made an illegal choice..."; } return 0; }
true
c7a99550192a00eab2df4abda2be7d802708d518
C++
ironiron/LCRmeter
/LCRmeter_CODE/tests/fakes/I2C_fake.hpp
UTF-8
2,840
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/* * I2C.h * * Created on: 12.05.2019 * Author: Rafa� */ #ifndef I2C_HPP_ #define I2C_HPP_ #include <stdint.h> #include <vector> /** * @class I2C * @brief This class handles communication either by DMA or blocking transmission * */ class I2C { public: I2C (){} enum ErrorCode{OK,TIMEOUT,NACK,BUS_ERROR,ARBITION_LOST,BUS_BUSY, GENERAL_ERROR,DMA_DISABLED};//TODO consider this I2C::ErrorCode Send_Data(uint8_t addr, uint8_t byte); I2C::ErrorCode Send_Data(uint8_t addr, uint16_t byte) { index++; data.push_back(byte); adress.push_back(addr); } I2C::ErrorCode Send_Data(uint8_t addr, uint8_t byte,uint8_t mem_addr); I2C::ErrorCode Send_Data(uint8_t addr, uint16_t byte,uint8_t mem_addr) { index++; data.push_back(byte); adress.push_back(addr); memoryaddress.push_back(mem_addr); } I2C::ErrorCode Send_Data(uint8_t addr, uint16_t byte,uint16_t mem_addr) { index++; data.push_back(byte); adress.push_back(addr); memoryaddress.push_back(mem_addr); } I2C::ErrorCode Send_Data_Cont(uint8_t addr, const uint8_t *byte,uint32_t size); I2C::ErrorCode Send_Data_Cont(uint8_t addr, const uint16_t *byte,uint32_t size) { for (uint32_t in = 0; in < size; ++in) { index++; data.push_back (byte[in]); adress.push_back (addr); } } I2C::ErrorCode Send_Data_Cont(uint8_t addr, const uint8_t *byte,uint32_t size,uint8_t mem_addr); I2C::ErrorCode Send_Data_Cont(uint8_t addr, const uint16_t *byte,uint32_t size,uint16_t mem_addr) { for (uint32_t in = 0; in < size; ++in) { index++; data.push_back (byte[in]); adress.push_back (addr); memoryaddress.push_back (mem_addr); } } I2C::ErrorCode Send_Data_Circular(uint8_t addr, const uint8_t *byte,uint32_t size); I2C::ErrorCode Send_Data_Circular(uint8_t addr, const uint16_t *byte,uint32_t size) { for (uint32_t in = 0; in < size; ++in) { index++; data.push_back (byte[in]); adress.push_back (addr); } } I2C::ErrorCode Send_Data_Circular(uint8_t addr, const uint8_t *byte,uint32_t size,uint8_t mem_addr); I2C::ErrorCode Send_Data_Circular(uint8_t addr, const uint16_t *byte,uint32_t size,uint8_t mem_addr) { for (uint32_t in = 0; in < size; ++in) { index++; data.push_back (byte[in]); adress.push_back (addr); memoryaddress.push_back (mem_addr); } } I2C::ErrorCode Send_Data_Circular(uint8_t addr, const uint16_t *byte,uint32_t size,uint16_t mem_addr) { for (uint32_t in = 0; in < size; ++in) { index++; data.push_back (byte[in]); adress.push_back (addr); memoryaddress.push_back (mem_addr); } } int index=0; std::vector<uint16_t> data={0}; std::vector<uint16_t> adress={0}; std::vector<uint16_t> memoryaddress={0}; void Stop_Transfer (void); }; #endif /* I2C_HPP_ */
true
0cf9a9f0231d939302b385e228fa230c25a43902
C++
borsim/AJADEBA
/screens/subScreens/Helps/howToPlayScreen.cpp
UTF-8
1,514
2.984375
3
[]
no_license
#include "howToPlayScreen.h" howToPlayScreen::howToPlayScreen() { widgetBase* backButton=new button ((vFunctionCall)terminateSub, makeCoor(30,WINDOW_Y-80),makeCoor(150,WINDOW_Y-30),"Back",30); widgets.push_back(backButton); widgets.push_back(new lButton([](){newSub=screen::HELPII;},makeCoor(WINDOW_X-100,WINDOW_Y-55),120,50,"Next")); draw(); } void howToPlayScreen::draw() { helpBase::draw(); addTitle("How to play"); addParagraph("It's a turn-based game, where two medieval kingdoms (the two player) try to " "overpower each other. As it was invented on boring lessons, it's played on a sqare grid. Your" " final aim is to destroy all the stongholds of your opponent. To achieve that in each turn" " you can either build or start an assault. Let's see what objects can you build! "); addParagraph("Barracks: their point is to provide soldiers for your " "strongholds. Marker: rombus with the owner player's pattern. "); addParagraph("Stronghold bases: they can be strongholds later... Marker: square. "); addParagraph("Roads: you can connect objects, by using roads. You can " "build north-, east-, south-, and west roads. Marker: blue line from middle to edge. "); addParagraph("In one turn you can build: 1 barrack/1 stronghold base/4 roads. You can't build to enemy" " territory. Exception: in the first turn, the second player can build plus 2 roads. "); }
true
afa5b4ab000993ddd139287d7ae05d4d469f74ff
C++
paulkokos/DesignPatternsInCpp
/src/[002]SOLID Design Principles/[003]Single Responsibility Principle/source/PersistenceManager.cpp
UTF-8
309
2.65625
3
[ "BSD-3-Clause" ]
permissive
#include "../include/PersistenceManager.hpp" #include <string> #include <fstream> using std::ofstream; using std::endl; void PersistenceManager::save(const Journal &journal, const string& filename) { ofstream ofs(filename); for (auto &e: journal.getEntries()) { ofs << e << endl; } }
true
9a9d772b01d9ad01a5d0954bb48a2857fc5d6afa
C++
poilpy/RoboticsPrograms
/nameReplace.cpp
UTF-8
528
2.875
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <algorithm> using namespace std; int main(int argc, char* argv[]) { std::ifstream mystream; mystream.open("Mandela.txt"); std::string story; std::string nameToReplace(argv[1]); std::string replacingName(argv[2]); std::size_t position; while(std::getline(mystream, story)) { } while((position = story.find(nameToReplace))!= string::npos) { story.replace(position, nameToReplace.length(), replacingName); } std::cout << story; std::cin.ignore(); }
true