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
5545241121d9c5195fc1fd5550f6503126571f82
C++
PrajaktaKeer/Programming
/A2OJ/Codeforces Div 2 A/young_physicist.cpp
UTF-8
414
2.53125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int n, a[101][3], i, j, sumx = 0, sumy = 0, sumz = 0; cin>>n; for(i = 0; i < n; i++) { for(j = 0; j < 3; j++) { cin>>a[i][j]; } } for(j = 0; j < n; j++) { sumx += a[j][0]; sumy += a[j][1]; sumz += a[j][2]; } //cout<<sumx<<" "<<sumy<<" "<<sumz; if(sumx == 0 && sumy == 0 && sumz == 0) cout<<"YES"; else cout<<"NO"; return 0; }
true
0c08abab7748dc6ba0660eddd40904c397cf0edc
C++
MarkMansell/OpenGLStarFighter
/OpenGL_SDL Base Project/OBJLoader.cpp
UTF-8
4,750
2.859375
3
[]
no_license
#include "OBJLoader.h" #include <stdio.h> #include <Windows.h> #include "../gl/glut.h" OBJLoader::OBJLoader(string modelFileName) { numVertices = 0; numUvs = 0; numNormals = 1; numPolygon = 0; std::strcpy(fileName, modelFileName.c_str()); // copy the file name to char LoadOBJ(&object, fileName); _TextureID = NULL; } OBJLoader::~OBJLoader() { } void OBJLoader::SetTexture(GLint _ID) { _TextureID = _ID; } bool OBJLoader::LoadOBJ(obj_type_ptr p_object, char *p_filename) { FILE * file = fopen(p_filename, "r"); if (file == NULL) { printf("File Could not be opened. \n"); return false; } while (1) { char LineHeader[128]; //read the first word of the line int res = fscanf(file, "%s", LineHeader); if (res == EOF) { break; // EOF = End of file. Quit Loop } if (strcmp(LineHeader, "v") == 0) { Vector3D vertex; fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z); p_object->vertex[numVertices].x = vertex.x; p_object->vertex[numVertices].y = vertex.y; p_object->vertex[numVertices].z = vertex.z; //printf("%f", vertex.x); //printf("%f", vertex.y); //printf("%f \n", vertex.z); numVertices++; } else if (strcmp(LineHeader, "vt") == 0) { Vector2D UV; fscanf(file, "%f %f\n", &UV.x, &UV.y); p_object->mapcoord[numUvs].u = UV.x; p_object->mapcoord[numUvs].v = UV.y; numUvs++; } else if (strcmp(LineHeader, "vn") == 0) { Vector3D normal; fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z); } else if (strcmp(LineHeader, "f") == 0) { //std::string vertex1, vertex2, vertex3; unsigned int vertexIndex[3], uvIndex[3], normalIndex[3]; int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]); if (matches != 9) { printf("File can't be read by our simple parser : ( Try exporting with other options\n"); return false; } p_object->polygon[numPolygon].a = vertexIndex[0] - 1; p_object->polygon[numPolygon].b = vertexIndex[1] - 1; p_object->polygon[numPolygon].c = vertexIndex[2] - 1; p_object->UV_Index[numPolygon].a = uvIndex[0] -1; p_object->UV_Index[numPolygon].b = uvIndex[1] -1; p_object->UV_Index[numPolygon].c = uvIndex[2] -1; numPolygon++; /* uvIndices.push_back(uvIndex[0]); uvIndices.push_back(uvIndex[1]); uvIndices.push_back(uvIndex[2]); normalIndices.push_back(normalIndex[0]); normalIndices.push_back(normalIndex[1]); normalIndices.push_back(normalIndex[2]);*/ } } } void OBJLoader::Render() { glPolygonMode(GL_FRONT, GL_FILL); glBindTexture(GL_TEXTURE_2D, _TextureID); // We set the active texture glBegin(GL_TRIANGLES); //glBegin and glEnd delimit the vertices that define a primative (in our case triangles) for (int l_index = 0; l_index < numPolygon; l_index++) { //FIRST VERTEX //Texture coordinates of the first vertex glTexCoord2f(object.mapcoord[object.UV_Index[l_index].a].u, object.mapcoord[object.UV_Index[l_index].a].v); //Coordinates of the first vertex glVertex3f(object.vertex[object.polygon[l_index].a].x, object.vertex[object.polygon[l_index].a].y, object.vertex[object.polygon[l_index].a].z); //printf(" First Vertex %i ", l_index); //printf(" %f", object.vertex[object.polygon[l_index].a].x); //printf(" %f", object.vertex[object.polygon[l_index].a].y); //printf(" %f \n", object.vertex[object.polygon[l_index].a].z); //SECOND VERTEX //Texture coordinates of the first vertex glTexCoord2f(object.mapcoord[object.UV_Index[l_index].b].u, object.mapcoord[object.UV_Index[l_index].b].v); //Coordinates of the second vertex glVertex3f(object.vertex[object.polygon[l_index].b].x, object.vertex[object.polygon[l_index].b].y, object.vertex[object.polygon[l_index].b].z); //printf(" 2nd vertex %i ", l_index); //printf(" %f", object.vertex[object.polygon[l_index].b].x); //printf(" %f", object.vertex[object.polygon[l_index].b].y); //printf(" %f \n", object.vertex[object.polygon[l_index].b].z); //THIRD VERTEX //Texture coordinates of the first vertex glTexCoord2f(object.mapcoord[object.UV_Index[l_index].c].u, object.mapcoord[object.UV_Index[l_index].c].v); //Coordinates of the second vertex glVertex3f(object.vertex[object.polygon[l_index].c].x, object.vertex[object.polygon[l_index].c].y, object.vertex[object.polygon[l_index].c].z); //printf(" 3nd vertex %i ", l_index); //printf(" %f", object.vertex[object.polygon[l_index].c].x); //printf(" %f", object.vertex[object.polygon[l_index].c].y); //printf(" %f \n", object.vertex[object.polygon[l_index].c].z); } glEnd(); //glPopMatrix(); glPolygonMode(GL_FRONT, GL_LINE); }
true
8a9f0f8d886a3f48585c61da5e32cfebb898576a
C++
wangcy6/weekly
/KM/03code/cpp/class/class_member.cpp
UTF-8
1,422
3.671875
4
[ "Apache-2.0" ]
permissive
#include <iostream> using namespace std; class Person{ public: Person(string& str,int x): name(str),value(x){ } string & name; const int value; }; class Grandparent { public: Grandparent(int no): grandparent_data(no){} void printRef() { cout << "myref is: " << grandparent_data << endl; } Grandparent& operator =(const Grandparent& other ) { this->grandparent_data =other.grandparent_data; //why 不报错。 cout <<" this->grandparent_data="<< this->grandparent_data <<"other.grandparent_data="<<other.grandparent_data<<endl; return *this; } private: int &grandparent_data; }; int main() { string s1 = "A", s2 = "B"; Person p1(s1,1),p2(s2,2); Person p3(p2); //拷贝构造函数可以正常调用,和预期结果一样。 cout << p1.name << " " << p1.value << endl; //A 1 cout << p2.name << " " << p2.value << endl; //B 2 cout << p3.name << " " << p3.value << endl; //B 2 //p1 = p2; //编译错误 int b=10; int& c=b; c=12; Grandparent gt1(1); gt1.printRef(); Grandparent gt2(13); gt2.printRef(); Grandparent gt3(gt1); //见鬼了 输出的有问题 gt3.printRef(); gt2 =gt1; gt2.printRef(); //error: non-static reference member ‘int& Grandparent::grandparent_data’, can’t use default assignment operator }
true
e4283d6cf81bcb4a1029657a665970e224bc7770
C++
suifengls/careercup150
/chapter01/01-02-reverse-string.cpp
UTF-8
522
3.515625
4
[]
no_license
#include <iostream> #include <cstring> #include <string> using namespace std; void reverse(char *str) { int len = strlen(str); // strlen() return the lenght, exclude '\0' for(int i = 0; i < len/2; ++i) { char tmp = str[i]; str[i] = str[len-1-i]; str[len-1-i] = tmp; } } int main() { char s1[] = "0123456789\0"; char s2[] = "asdfghjkl\0"; cout << s1 << " -> "; reverse(s1); cout << s1 << endl; cout << s2 << " -> "; reverse(s2); cout << s2 << endl; return 0; }
true
3e2c6584706c2f47ea832f67b3e288600a3fbfad
C++
orcchg/StudyProjects
/OBJECT_ORIENTED/SORTINGS/IntKey.h
UTF-8
595
2.984375
3
[]
no_license
#pragma once #include <iostream> using namespace std; #ifndef SORTINGS_INTKEY_H #define SORTINGS_INTKEY_H class IntKey { private: friend ostream & operator << (ostream & out, const IntKey & v); int value; public: IntKey(int v = 0) : value(v) {} IntKey(const IntKey & key) : value(key.value) {} int getValue() { return value; } int length() { return 8; } int power() { return 16; } int operator [] (int i) const { return (value >> (4*(7 - i))) & 15; } }; ostream & operator << (ostream & out, const IntKey & v) { return out << v.value; } #endif
true
11caddb6d1f34b849cf437d3025472bad183901b
C++
marvilchis1/AnomalyDetector
/filemanager.cpp
UTF-8
3,017
3.234375
3
[]
no_license
#include "filemanager.h" bool FileManager::CheckFile(string direction) { ifstream input(direction); if ( !input.is_open()) { std::cout << "El archivo: " << direction << " no pudo abrirse" << std::endl; return false; } if ( input.eof() ) { input.close(); return false; } return true; } vector<string> FileManager::ReadFile(string direction){ ifstream input(direction); // Average Class Vectors string aux_line; vector <string> container; //int num_rows = 0; while( getline(input, aux_line) ) container.push_back(aux_line); return container; } vector<string> FileManager::Split(const std::string line, char lim){ std::stringstream str(line); std::string token; std::vector<std::string> aux_vect; while( std::getline(str, token, lim)) aux_vect.push_back(token); return aux_vect; } tuple<vector<string>,int,int> FileManager::ProcessData(string direction) { ifstream input(direction); // Average Class Vectors string aux_line; vector <string> container; //int num_rows = 0; while( getline(input, aux_line) ) container.push_back(aux_line); std::stringstream str(container[0]); std::string token; std::vector<std::string> aux_vect; int num_rows = container.size(); int num_columns = 0; while( std::getline(str, token, ' ')) num_columns++; return std::make_tuple(container, num_rows, num_columns); } /* vector<vector<double>> FileManager::ToDoubleMatrix(string direction) { ifstream input(direction); // Average Class Vectors string aux_line; vector <string> container; //int num_rows = 0; while( getline(input, aux_line) ) container.push_back(aux_line); return Database::DataMatrix(container); } */ Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> FileManager::ToEigenMatrix(vector<string> str_matrix, int nrows, int ncols) { Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> M; M.resize(nrows, ncols); for (int i = 0; i != str_matrix.size(); ++i){ vector<double> aux_vector; std::istringstream str_values(str_matrix[i]); double d = 0.0; //std::cout << "Hola" << std::endl; //M.resize(i+1, 0); int j = 0; while ( str_values >> d ) { //std::cout << "Hola2" << std::endl; //cout << d << endl; //M.resize(i+1, j+1); M(i,j) = d; ++j; } } return M; } void FileManager::PrintVector(vector<double> d_vector) { std::cout << std::endl; for (int i = 0; i < d_vector.size(); ++i) std::cout << d_vector[i] << " "; std::cout << std::endl; } void FileManager::PrintMatrix(vector<vector<double>> d_matrix) { for(int i = 0; i < d_matrix.size(); ++i) { for (int j = 0; j < d_matrix[i].size(); ++j) std::cout << d_matrix[i][j] << " "; std::cout << std::endl; } }
true
34f0c10306af5df4d0715114997725fe02e7585e
C++
cies96035/CPP_programs
/TOJ/已註解,整碼/toj120.cpp
UTF-8
485
2.8125
3
[]
no_license
#include<iostream> using namespace std; int main() { cin.tie(0); ios_base::sync_with_stdio(0); //前綴和觀念稍微有就不會TLE int N,num,Q; cin>>N; long long Snum[N+1]={0};//儲存a0~an的總和(題目數字稍大要開long long for(int i=1;i<=N;i++) { cin>>num; Snum[i]=Snum[i-1]+num; } //輸出 cin>>Q; while(Q--) { int a,b; cin>>a>>b; if(a>b)swap(a,b);//求a,b區間和,並沒說a必小於b cout<<Snum[b]-Snum[a-1]<<endl; } return 0; }
true
1c20e60dce940abcb2ed303560dbbc32ee7af3ec
C++
igorternyuk/TeAllegro5Pacman
/allegro5timer.cpp
UTF-8
1,118
3.015625
3
[]
no_license
#include "allegro5timer.hpp" #include <stdexcept> Allegro5Timer::Allegro5Timer(double speedSecs) { auto timer = al_create_timer(speedSecs); if(!timer) { throw std::runtime_error("Could not create timer"); } my_unique_ptr<ALLEGRO_TIMER> ptr{ timer, al_destroy_timer }; mTimer.swap(ptr); } void Allegro5Timer::start() { al_start_timer(mTimer.get()); } void Allegro5Timer::stop() { al_stop_timer(mTimer.get()); } void Allegro5Timer::setTimerSpeed(double speed) { al_set_timer_speed(mTimer.get(), speed); } double Allegro5Timer::getTimerSpeed() const { return al_get_timer_speed(mTimer.get()); } void Allegro5Timer::setTimerCount( int64_t count) { al_set_timer_count(mTimer.get(), count); } int64_t Allegro5Timer::getTimerCount() const { return al_get_timer_count(mTimer.get()); } bool Allegro5Timer::isActive() const { return al_get_timer_started(mTimer.get()); } ALLEGRO_TIMER *Allegro5Timer::get() const { return mTimer.get(); } ALLEGRO_EVENT_SOURCE *Allegro5Timer::getEventSource() const { return al_get_timer_event_source(mTimer.get()); }
true
3eda9fcea56c0167a866247a2cb944b1013f8d25
C++
Exoron/CompilersHometasks
/04-scopes/Visitors/PrintVisitor.cpp
UTF-8
2,180
3.046875
3
[]
no_license
#include "PrintVisitor.h" #include "includes.h" PrintVisitor::PrintVisitor(const std::string& filename): out(filename) {} void PrintVisitor::PrintTabs() { for(int i = 0; i < tabs_; ++i) { out << "\t"; } } void PrintVisitor::Visit(NumberExpression* expr) { PrintTabs(); out << "Number" << std::endl; } void PrintVisitor::Visit(VariableExpression* expr) { PrintTabs(); out << "Variable" << std::endl; } void PrintVisitor::Visit(AddExpression* expr) { PrintTabs(); out << "Add" << std::endl; ++tabs_; expr->Right()->Accept(this); expr->Left()->Accept(this); --tabs_; } void PrintVisitor::Visit(SubExpression* expr) { PrintTabs(); out << "Sub" << std::endl; ++tabs_; expr->Right()->Accept(this); expr->Left()->Accept(this); --tabs_; } void PrintVisitor::Visit(MulExpression* expr) { PrintTabs(); out << "Mul" << std::endl; ++tabs_; expr->Right()->Accept(this); expr->Left()->Accept(this); --tabs_; } void PrintVisitor::Visit(DivExpression* expr) { PrintTabs(); out << "Div" << std::endl; ++tabs_; expr->Right()->Accept(this); expr->Left()->Accept(this); --tabs_; } void PrintVisitor::Visit(StatementList* list) { PrintTabs(); out << "Statements" << std::endl; ++tabs_; for(auto statement: list->Statements()) { statement->Accept(this); } --tabs_; } void PrintVisitor::Visit(AssignStatement* assign) { PrintTabs(); out << "Assign" << std::endl; ++tabs_; assign->Value()->Accept(this); --tabs_; } void PrintVisitor::Visit(DeclarationStatement* decl) { PrintTabs(); out << "Decl" << std::endl; ++tabs_; Expression* expr = decl->Value(); if(expr != nullptr) { expr->Accept(this); } --tabs_; } void PrintVisitor::Visit(PrintStatement* print) { PrintTabs(); out << "Print" << std::endl; ++tabs_; print->Value()->Accept(this); --tabs_; } void PrintVisitor::Visit(Program* program) { PrintTabs(); out << "Program" << std::endl; ++tabs_; program->List()->Accept(this); --tabs_; } void PrintVisitor::Visit(ScopeStatementList* scope) { PrintTabs(); out << "Scope Statements" << std::endl; ++tabs_; scope->Statements()->Accept(this); --tabs_; }
true
2e829b3262780d63257e13aceb7a9a52d08756bc
C++
VenkatKS/ParallelEnvironment
/cpp/core/abstract_agent.cpp
UTF-8
568
2.765625
3
[]
no_license
#include "abstract_agent.h" void AbstractAgent::RegisterAction (std::string action_name, uint32_t enumerated_action) { std::unordered_map<std::string, uint32_t>::iterator it = \ registered_actions.find(action_name); /* If the specified action is already in the dictionary, don't allow */ if(it != registered_actions.end()) { throw std::string("Action already registered"); } registered_actions[action_name] = enumerated_action; paired_actions.push_back(std::pair<std::string, uint32_t>(action_name,\ enumerated_action)); return; }
true
ec3d0bd1f9686b8a841ef9cea3eb77a0c6c71080
C++
mhikichi1969/hackEv3_2019
/judge/SectionJudge.cpp
UTF-8
1,836
2.765625
3
[]
no_license
#include "SectionJudge.h" #include "Flag.h" SectionJudge::SectionJudge(HPolling *polling, Odometry *odometry) : Judge( polling,odometry) { } void SectionJudge::setValue(int cmd_judge,double val) { int cmd = cmd_judge&0xff00; mEndFlag = (Flag::End)(cmd_judge&0xff); mTarget = val; switch(mEndFlag) { case Flag::END_LEN: mBackFlag = val<mLen; mVal = val; mLen = val; break; case Flag::END_ANG: case Flag::END_ANG2: setAngleParam(mEndFlag); break; } } void SectionJudge::setAngleParam(Flag::End endFlag) { /* char buf[256]; sprintf(buf,"SJ:setAP %3.1f,%3.1f",mOdo->getAngleDeg(),mTarget); msg_f(buf,8);*/ switch(endFlag) { case Flag::END_ANG: mStartAngle = mOdo->getAngleDeg(); case Flag::END_ANG2: mTarget += mStartAngle; if(mTarget < mOdo->getAngleDeg()){ mAngFlag = false; }else{ mAngFlag = true; } } } bool SectionJudge::angleCheck() { /* char buf[256]; sprintf(buf,"angleCheck %3.1f:%3.1f",mOdo->getAngleDeg(),mTarget); msg_f(buf,6);*/ bool f=false; if(mAngFlag && mOdo->getAngleDeg() >= mTarget - mPermitAngle ){ //msg_f("SectionJudge:angle:TRUE1",7); //msg_f("Judge:angle:TRUE1",2); f = true; }else if(!mAngFlag && mOdo->getAngleDeg() <= mTarget + mPermitAngle ){ //msg_f("SectionJudge:angle:TRUE2",7); //msg_f("Judge:angle:TRUE2",2); f = true; }else{ //msg_f("Judge:angle:ELSE",7); } return f; } void SectionJudge::resetLength() { mLen=0; mOdo->resetLength(); }
true
54dadba493bc2bd88d551612e4b1c0440ac086e0
C++
mugiseyebrows/mugi-grep
/src/parse/parsepython.h
UTF-8
1,214
2.578125
3
[ "MIT" ]
permissive
#ifndef PARSEPYTHON_H #define PARSEPYTHON_H #include "linecontext.h" class PythonSymbol { public: enum Type { Class, Method, }; PythonSymbol() {} PythonSymbol(Type type, const QString& name, const QString& shortName, int begin, int end, int indent); bool contains(int line) const; Type type; QString name; QString shortName; int begin; int end; int indent; }; class PythonReader { public: enum class State { Code, SignleQuoteStr, DoubleQuoteStr, HeredocStr, Comment }; PythonReader(QTextStream& stream); QPair<int,QString> read(); QTextStream& stream; int lineNumber; }; class PythonHelper { public: void startClass(int lineNumber, int indent, const QString& name); void startMethod(int lineNumber, int indent, const QString& name, const QString& shortName); void flush(int indent, int lineNumber); QList<LineContextItem> context() const; QMap<int, PythonSymbol> incomplete; QList<PythonSymbol> complete; }; class ParsePython { public: ParsePython(); static QList<LineContextItem> parse(const QString &path); }; #endif // PARSEPYTHON_H
true
e00cb7a8b5594e776bd38f8a6e27dd33191ef6c9
C++
wesleygriffin/SPLIT_VIS2
/preprocessing/generateSymmetry/genSymmetry.h
UTF-8
632
2.609375
3
[]
no_license
#include <fstream> #include <algorithm> #include <cmath> #include <vector> using namespace std; struct Spin { double px; double py; double pz; double vx; double vy; double vz; double den; }; class genSymmetry { public: genSymmetry(){} virtual ~genSymmetry(){cleanup();} int getNumOfIntegerDigits(double num); void SetData(char *file); void SetPlane(vector< vector<double> > pos, double *vec); void Process(); void SaveToFile(); protected: void cleanup(); private: vector<Spin> data; vector< vector<double> > planepos; double planevec[3]; };
true
20aaaf6ff7bc4414092679de76df27cd88bc5a6d
C++
zeroplusone/AlgorithmPractice
/UVA/UVA-Q445-Marvelous_Mazes.cpp
BIG5
607
3.203125
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> using namespace std; int main() { char c; int i; while(scanf("%c",&c)!=EOF) { if(c=='!') { printf("\n"); } else if(c==10) { printf("\n"); } else { i=0; while(c>='0' && c<='9') { i+=c-'0'; scanf("%c",&c); } for(int j=0;j<i;++j) { if(c=='b') printf(" "); else printf("%c",c); } } } return 0; } /*ƦrܭnLXXӫ᭱rβŸ ! bŮ ps.123T TTTTTT(1+2+3)*/
true
8bad9c14625df5e05bb7f69340d889a2a8ec435e
C++
GuanyiLi-Craig/interview
/Array/q28.cpp
UTF-8
1,616
3.515625
4
[]
no_license
/**************************************************************************************************** 28. Implement strStr() ----------------------------------------------------------------------------------------------------- Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. ****************************************************************************************************/ class Solution { public: int strStr(string haystack, string needle) { int lenh=haystack.size(); int lenn=needle.size(); if (lenn>lenh) return -1; if (lenn==0) return 0; // if needle is empty, return 0 for(int i=0;i<=lenh-lenn;i++) // here should be <= be cause it was 0 based { if(haystack[i]==needle[0]) { bool qfound=true; for(int j=1;j<lenn;j++) { if (haystack[i+j]!=needle[j]) { qfound=false; break; } } if (qfound) return i; } } return -1; // don't forget return something } }; /**************************************************************************************************** Note needle can be more than one char. ****************************************************************************************************/
true
64aff4ffdf41c9f41bd33da8c61cecb61a7f7922
C++
peterpanning/DICOMViewer
/dicomSeries.h
UTF-8
1,730
2.859375
3
[]
no_license
#ifndef FINALPROJECT_DICOMSERIES_H #define FINALPROJECT_DICOMSERIES_H // TODO: Is storing these header files here best practice? #include "itkImage.h" #include "itkGDCMImageIO.h" #include "itkGDCMSeriesFileNames.h" #include "itkImageSeriesReader.h" #include "itkConnectedThresholdImageFilter.h" #include "itkMaskImageFilter.h" class dicomSeries{ // Using allows us to define new types. // DICOMs use floats to represent pixels using DicomPixelType = float; // Used later to set the reader's filenames using DicomNamesGeneratorType = itk::GDCMSeriesFileNames; // Used to hold the names of files before passing them to reader using FileNamesContainer = std::vector< std::string >; // Used later to set the reader's IO using ImageIOType = itk::GDCMImageIO; public: // **VARIABLES AND TYPEDEFS** // We are reading in a 3D image represented with floats const static unsigned int Dimension = 3; using DicomImage = itk::Image<DicomPixelType, Dimension>; // Reader is an ITK image series reader using ReaderType = itk::ImageSeriesReader< DicomImage >; // Mask allows us to retrieve houndsfield intensity values after // performing connected component region growing using MaskImageFilter = itk::MaskImageFilter<DicomImage, DicomImage>; // **CONSTRUCTORS** // Default Constructor dicomSeries(); // Constructor given a filepath dicomSeries(char*); // **OTHER FUNCTIONS** DicomImage::Pointer GetOutput(); // Void because it will modify private variables, not return a value DicomImage::Pointer RegionGrow(); private: char* dirName; DicomNamesGeneratorType::Pointer nameGenerator; FileNamesContainer fileNames; ImageIOType::Pointer dicomIO; ReaderType::Pointer reader; }; #endif
true
04b02626d0318269513a1fa6d4c6d24ab82afad7
C++
cdbm/codeforces
/158A-Round.cpp
UTF-8
478
3.03125
3
[]
no_license
#include <iostream> using namespace std; int main() { int n, k, x; cin >> n; cin >> k; int students[n]; for(int i = 0; i<n; i++){ cin >>x; students[i] = x; } int pass =0; int media = students[k-1]; bool continua = true; for(int j=0; j<n;j++ && continua){ if(students[j] < media){ continua = false; } if((students[j] >= media) && (students[j] >0)){ pass++; } } cout<<pass; }
true
dbd08aa7be2d0451fe09af6ce0adb87b2cba052b
C++
lfermin77/cg_mrslam
/src/uncertainty/graph_distance.cpp
UTF-8
9,036
3.234375
3
[ "BSD-3-Clause" ]
permissive
#include "graph_distance.hpp" /////////////////// void Graph_Distance::clean_class(){ for(std::unordered_map<int, Vertex*>::iterator map_iter = Vertices_map.begin(); map_iter != Vertices_map.end(); map_iter ++){ Vertex* ptr = map_iter->second; delete ptr; } Vertices_map.clear(); for(std::map<std::set<int>, Arc*>::iterator map_iter = Arcs_map.begin(); map_iter != Arcs_map.end(); map_iter ++){ Arc* ptr = map_iter->second; delete ptr; } Arcs_map.clear(); } // Graph_Distance::~Graph_Distance(){ clean_class(); } std::ostream& operator<<(std::ostream& os, Graph_Distance& Graph){ os << "\n"; os << "Number of Nodes "<< Graph.Vertices_map.size() << "\n"; os << "Number of Edges "<< Graph.Arcs_map.size() << "\n"; /* for(std::unordered_map <int, std::unordered_map <int,float> >::iterator map_map_iter = Graph.map_distance_matrix.begin(); map_map_iter != Graph.map_distance_matrix.end(); map_map_iter ++){ int label_1 = map_map_iter->first; std::unordered_map <int,float> sub_map = map_map_iter->second; for(std::unordered_map <int,float>::iterator map_iter = sub_map.begin(); map_iter != sub_map.end(); map_iter ++){ int label_2 = map_iter->first; float current_distance = map_iter->second; os << "("<< label_1<<","<<label_2<<")-> "<< current_distance << ";\t"; } } //*/ return os; } /////////////////////////////////////// /////// void Graph_Distance::insert_first_edge(int label_first, int label_second, float distance){ clean_class(); Vertex* first_vertex = new Vertex; Vertex* second_vertex = new Vertex; Vertices_map[label_first] = first_vertex; Vertices_map[label_second] = second_vertex; first_vertex->label = label_first; second_vertex->label = label_second; Arc* first_arc = new Arc; first_arc->labels={label_first, label_second}; first_arc->distance =distance; first_vertex ->connections.push_back(first_arc); second_vertex->connections.push_back(first_arc); Arcs_map[first_arc->labels] = first_arc; } ////// int Graph_Distance::insert_new_node(int label, std::vector< std::pair<int, float> > Connections_label_distance ){ std::unordered_map<int, Vertex*>::iterator found_ptr = Vertices_map.find(label); if(found_ptr != Vertices_map.end() ){ std::cout << "Vertex label already in graph" << std::endl; return -1; } Vertex* vertex_new = new Vertex; Vertices_map[label] = vertex_new; vertex_new->label=label; //Insert all edges for(int i=0; i < Connections_label_distance.size(); i++){ Arc* current_arc = new Arc; int TO_label = Connections_label_distance[i].first; current_arc->labels={label, TO_label}; current_arc->distance = Connections_label_distance[i].second; vertex_new ->connections.push_back(current_arc); Vertices_map[TO_label]->connections.push_back(current_arc); Arcs_map[current_arc->labels] = current_arc; } //// return update_distances( label ); } ////// int Graph_Distance::insert_new_edge(int label_1, int label_2, float distance ){ std::unordered_map<int, Vertex*>::iterator found_ptr = Vertices_map.find(label_1); if(found_ptr == Vertices_map.end() ){ std::cout << "Vertex 1 label NOT in graph" << std::endl; return -1; } found_ptr = Vertices_map.find(label_2); if(found_ptr == Vertices_map.end() ){ std::cout << "Vertex 2 label NOT in graph" << std::endl; return -1; } Arc* current_arc = new Arc; current_arc->labels={label_1, label_2}; current_arc->distance = distance; Vertices_map[label_1]->connections.push_back(current_arc); Vertices_map[label_2]->connections.push_back(current_arc); Arcs_map[current_arc->labels] = current_arc; return update_distances( label_1 ); } int Graph_Distance::update_distances( int label_start_node ){ std::unordered_map<int, Vertex*> unvisited_vertices = Vertices_map; //List to work // Set initial conditions for(std::unordered_map<int, Vertex*>::iterator map_iter = unvisited_vertices.begin(); map_iter != unvisited_vertices.end(); map_iter ++){ map_iter->second->distance_in_this_iter = std::numeric_limits<float>::infinity(); } Vertices_map[label_start_node]->distance_in_this_iter = 0; unvisited_vertices[label_start_node]->distance_in_this_iter = 0; while(unvisited_vertices.size() > 0){ std::unordered_map<int, Vertex*>::iterator eliminate_iter = unvisited_vertices.begin(); //Find minimum float min_distance = std::numeric_limits<float>::infinity(); for(std::unordered_map<int, Vertex*>::iterator map_iter = unvisited_vertices.begin(); map_iter != unvisited_vertices.end(); map_iter ++){ if( map_iter->second->distance_in_this_iter < min_distance ){ eliminate_iter = map_iter; min_distance = map_iter->second->distance_in_this_iter; } } Vertex* current_vertex = eliminate_iter->second; unvisited_vertices.erase(eliminate_iter); //remove from unvisited //Expand the edges for(int i=0; i < current_vertex->connections.size();i++){ float new_distance = current_vertex->distance_in_this_iter + current_vertex->connections[i]->distance; int destination_label = *current_vertex->connections[i]->labels.begin(); if(destination_label == current_vertex->label) destination_label = *current_vertex->connections[i]->labels.rbegin(); if(new_distance < Vertices_map[destination_label] -> distance_in_this_iter ){ Vertices_map[destination_label] -> distance_in_this_iter = new_distance; } // } // } return update_distance_matrix(label_start_node); } int Graph_Distance::update_distance_matrix(int label_new_node){ //Create rows and columns (if any) for(std::unordered_map<int, Vertex*>::iterator map_iter = Vertices_map.begin(); map_iter != Vertices_map.end(); map_iter ++){ int lower_label = (label_new_node >= map_iter->first)? map_iter->first : label_new_node; int upper_label = (lower_label == label_new_node)? map_iter->first : label_new_node; map_distance_matrix [lower_label][upper_label] = map_iter->second->distance_in_this_iter; } //Update the rest for(std::unordered_map <int, std::unordered_map <int,float> >::iterator map_map_iter = map_distance_matrix.begin(); map_map_iter != map_distance_matrix.end(); map_map_iter ++){ int lower_label = map_map_iter->first; std::unordered_map <int,float> sub_map = map_map_iter->second; for(std::unordered_map <int,float>::iterator map_iter = sub_map.begin(); map_iter != sub_map.end(); map_iter ++){ int upper_label = map_iter->first; float current_distance = map_iter->second; int first_low = (label_new_node >= lower_label)? lower_label : label_new_node; int first_high = (lower_label == label_new_node)? lower_label : label_new_node; int second_low = (label_new_node >= upper_label)? upper_label : label_new_node; int second_high = (lower_label == label_new_node)? upper_label : label_new_node; float distance_alternative = map_distance_matrix [first_low][first_high] + map_distance_matrix [second_low][second_high]; if (distance_alternative < map_distance_matrix [lower_label][upper_label]){ map_distance_matrix [lower_label][upper_label] = distance_alternative; } // } // } //// return extract_central_vertex_label(); } int Graph_Distance::extract_central_vertex_label(){ std::unordered_map<int, float> max_dist_map; for(std::unordered_map<int, Vertex*>::iterator map_iter = Vertices_map.begin(); map_iter != Vertices_map.end(); map_iter ++){ int label_1 = map_iter->first; max_dist_map[label_1] = -1; for(std::unordered_map<int, Vertex*>::iterator map_iter_2 = Vertices_map.begin(); map_iter_2 != Vertices_map.end(); map_iter_2 ++){ int label_2 = map_iter_2->first; int lower_label = (label_1 >= label_2)? label_2 : label_1; int upper_label = (lower_label == label_1)? label_2 : label_1; float distance = map_distance_matrix [lower_label][upper_label]; if(distance >max_dist_map[label_1]) max_dist_map[label_1]=distance; } } //// // std::cout << " Largest Distances: " << std::endl; float min_dist = std::numeric_limits<float>::infinity(); int central_label=-1; for(std::unordered_map<int, float>::iterator map_iter = max_dist_map.begin(); map_iter != max_dist_map.end(); map_iter ++){ // std::cout << " node: "<< map_iter->first <<", distance "<< map_iter->second << std::endl; if(map_iter->second < min_dist){ central_label = map_iter->first; min_dist = map_iter->second; } } // std::cout << " Central vertex: "<< central_label << std::endl; return central_label; } bool Graph_Distance::is_node_in_graph(int label){ std::unordered_map<int, Vertex*>::iterator vertex_iter = Vertices_map.find(label) ; bool inside = (vertex_iter == Vertices_map.end() )? false : true; return inside; } bool Graph_Distance::is_edge_in_graph(std::set<int> labels){ std::map<std::set<int>, Arc*>::iterator arc_iter = Arcs_map.find(labels); bool inside = (arc_iter == Arcs_map.end() )? false : true; return inside; }
true
554eb93ee8b7ee03c0ab96613aa8434f251c700c
C++
SelyanWorker/cannon_game
/platforms/OpenGL/OGLVertexArray.cpp
UTF-8
2,888
2.703125
3
[]
no_license
#include "OGLVertexArray.h" #include <cassert> namespace selyan { VertexArray *VertexArray::create() { return new OGLVertexArray(); } OGLVertexArray::OGLVertexArray() : m_index(0), m_indexBuffer(nullptr), m_instanceCount(1) { glGenVertexArrays(1, &m_index); } void OGLVertexArray::setVertexBuffers(std::initializer_list<VertexBuffer *> buffers) { // RN_ASSERT(buffers.size() <= MAX_VERTEX_BUFFERS, "buffers.size() > // m_vertexBuffers.size()"); assert(buffers.size() <= MAX_VERTEX_BUFFERS && "buffers.size() > m_vertexBuffers.size()"); bind(); GLuint index = 0; for (auto initBuffer : buffers) { if (initBuffer == nullptr) continue; m_vertexBuffers.push_back(initBuffer); VertexBuffer *buffer = m_vertexBuffers.back(); buffer->bind(); auto bufferLayout = buffer->getBufferLayout(); GLuint stride = bufferLayout.getStride(); for (auto const &element : bufferLayout) { GLenum type; GLboolean normalize = element.Normalize ? GL_TRUE : GL_FALSE; switch (element.Type) { case float2: type = GL_FLOAT; break; case float3: type = GL_FLOAT; break; case none: // RN_CORE_ERROR("SetVertexBuffer element no type"); std::cout << "SetVertexBuffer element no type" << std::endl; default: // RN_CORE_ERROR("From setVertexBuffers -> default in type switch"); std::cout << "From setVertexBuffers -> default in type switch" << std::endl; } glVertexAttribPointer(index, element.Size, type, normalize, stride, (void *)element.Offset); glEnableVertexAttribArray(index); glVertexAttribDivisor(index, GLuint(element.Divisor)); index++; } buffer->unbind(); } unbind(); } void OGLVertexArray::setIndexBuffer(IndexBuffer *buffer) { m_indexBuffer = buffer; bind(); m_indexBuffer->bind(); unbind(); } std::vector<VertexBuffer *> OGLVertexArray::getVertexBuffers() const { return m_vertexBuffers; } IndexBuffer *OGLVertexArray::getIndexBuffer() const { return m_indexBuffer; } void OGLVertexArray::bind() { glBindVertexArray(m_index); } void OGLVertexArray::unbind() { glBindVertexArray(0); } }
true
2678ce52dbf8da1f54dff2d2ac7c7fac4af1bb79
C++
forkrp/imgui-Tristeon
/src/Core/Transform.h
UTF-8
5,912
2.78125
3
[ "MIT" ]
permissive
#pragma once #include "TObject.h" #include "Math/Vector3.h" #include "Misc/Property.h" #include "Editor/TypeRegister.h" #include "Misc/vector.h" #include <glm/mat4x4.hpp> #include "Math/Quaternion.h" namespace Tristeon { namespace Scenes { class SceneManager; } } namespace Tristeon { namespace Core { /** * \brief Transform is a class used to describe the transform, rotation and scale of an object. * It's most commonly used by GameObject. Every GameObject will always have a Transform at any time. * Transform also describes parent-child relationships between gameobjects. */ class Transform final : public TObject { friend Scenes::SceneManager; public: /** * \brief Cleans up transform and all of its relationships */ ~Transform(); /** * \brief The global position of this transform */ Property(Transform, position, Math::Vector3); GetProperty(position) { return getGlobalPosition(); } SetProperty(position) { setGlobalPosition(value); } /** * \brief The local position of this transform */ Property(Transform, localPosition, Math::Vector3); GetProperty(localPosition) { return _localPosition; } SetProperty(localPosition) { _localPosition = value; } /** * \brief The global scale of this transform */ Property(Transform, scale, Math::Vector3); GetProperty(scale) { return getGlobalScale(); } SetProperty(scale) { setGlobalScale(value); } /** * \brief The local scale of this transform */ Property(Transform, localScale, Math::Vector3); GetProperty(localScale) { return _localScale; } SetProperty(localScale) { _localScale = value; } /** * \brief The local rotation of this transform */ Property(Transform, localRotation, Math::Quaternion); GetProperty(localRotation) { return _localRotation; } SetProperty(localRotation) { _localRotation = value; } /** * \brief The global rotation of this transform */ Property(Transform, rotation, Math::Quaternion); GetProperty(rotation) { return getGlobalRotation(); } SetProperty(rotation) { setGlobalRotation(value); } /** * \brief Sets the parent of this transform * \param parent The parent * \param keepWorldTransform Defines wether or not our world transformation should be kept */ void setParent(Transform* parent, bool keepWorldTransform = true); /** * \brief Gets the parent of this transform * \return Returns the parent */ Transform* getParent() const; /** * \brief Serializes this transform into a json file * \return The json object */ nlohmann::json serialize() override; /** * \brief Deserializes this transform from a json file * \param json The json file */ void deserialize(nlohmann::json json) override; /** * \brief Returns a transformation matrix based on the position, scale, rotation and parent of this transform * \return Returns a transformation matrix */ glm::mat4 getTransformationMatrix(); /** * \brief Rotates around axis [axis] with rotation [rot] * \param axis The axis to be rotated around * \param rot The amount of rotation in degrees */ void rotate(Math::Vector3 axis, float rot); /** * \brief Translates the transform in local space * \param t The amount of translation */ void translate(Math::Vector3 t); /** * \brief Translates the transform in local space * \param t The amount of translation */ void translate(float x, float y, float z); /** * \brief Transforms a given point from local to global space * \param point The position to be transformed * \return The transformed position */ Math::Vector3 transformPoint(Math::Vector3 point); /** * \brief Transforms a given point from global to local space * \param point The position to be transformed * \return The transformed position */ Math::Vector3 inverseTransformPoint(Math::Vector3 point); void lookAt(Transform* target, Math::Vector3 worldUp = Math::Vector3::up); /** * \brief The green axis of the transform in world space. */ Math::Vector3 up(); /** * \brief The red axis of the transform in world space. */ Math::Vector3 right(); /** * \brief The blue axis of the transform in world space. */ Math::Vector3 forward(); private: /** * \brief Gets the global position of this transform * \return Returns the global position */ Math::Vector3 getGlobalPosition(); /** * \brief Sets the global position of this transform * \param pos The global position */ void setGlobalPosition(Math::Vector3 pos); /** * \brief Gets the global scale of this transform * \return Returns the global scale */ Math::Vector3 getGlobalScale(); /** * \brief Sets the global scale of this transform * \param scale The global scale */ void setGlobalScale(Math::Vector3 scale); /** * \brief Gets the global rotation of this transform * \return Returns the global rotation */ Math::Quaternion getGlobalRotation(); /** * \brief Sets the global rotation of this transform * \param rot The rotation */ void setGlobalRotation(Math::Quaternion rot); /** * \brief The local position of this transform */ Math::Vector3 _localPosition = { 0, 0, 0 }; /** * \brief The local scale of this transform */ Math::Vector3 _localScale = { 1, 1, 1 }; /** * \brief The local rotation of this transform */ Math::Quaternion _localRotation = {}; /** * \brief The parent of this transform */ Transform* parent = nullptr; /** * \brief The id of the parent */ std::string parentID = "null"; /** * \brief The children of this transform */ Tristeon::vector<Transform*> children; REGISTER_TYPE_H(Transform) }; } }
true
dece924a3d1bf2c6f5527edbbdeafe9df77de79e
C++
BahaaEldeenOsama/FCAI-CU-Assignments
/Data structure/Assignment-2/Queues/main.cpp
UTF-8
4,599
3.734375
4
[]
no_license
#include <bits/stdc++.h> using namespace std; template<class T> class Queue { private: int MX_Capacity; int length; int Front,Back; int init_SZ; T *Array; T val ; public: Queue() { MX_Capacity=9999; Array=new T[MX_Capacity]; Back=MX_Capacity-1; length=0; Front=0; }; Queue(T val ,int init_SZ) { if (init_SZ <= 0){MX_Capacity = 9999;} else{MX_Capacity = init_SZ;} Front = 0; Array = new T[MX_Capacity]; Back = MX_Capacity - 1; length = 0; for(int i=0 ; i<init_SZ;++i) { push_Back(val); } }; bool ISEmpty(){return (length==0);} bool ISFull(){return(length==MX_Capacity);} int Size(){return length;} T&get_front() { if(ISEmpty()) { cout << "The Queue is empty,can't return any item.\n"; } else { return Array[Front]; } } void pop_Front() { if(ISEmpty()) { cout << "The Queue is actually empty.\n"; } else { ++Front; --length; } }; void push_Back(T val) { if(ISFull()) { cout << "The queue is full can't push element.\n"; } else { Back=(Back+1)%MX_Capacity; Array[Back]=val; ++length; } }; void Print() { if(!ISEmpty()) { cout <<"The queue items = { "; for(int i=Front ; i!=Back; ++i) { cout << Array[i]<<" ,"; } cout <<Array[Back]; cout << " }\n\n\n"; } else { cout << "The Queue is actually empty.\n"; } } ~Queue() { delete[]Array; }; }; int main() { /** Pop_front Push_back**/ /** Front Back**/ /** Queue = {1,2,3,4,5} **/ /// Case 1 : integer. Queue<int>Q(1,9); Q.Print(); Queue<int>Q2; Q2.push_Back(1); Q2.push_Back(2); Q2.push_Back(3); Q2.push_Back(4); Q2.push_Back(5); cout <<"The front element = "<<Q2.get_front()<<"\n"; cout<<"The size = "<<Q2.Size()<<endl; Q2.Print(); Q2.pop_Front(); cout <<"The front element = "<<Q2.get_front()<<"\n"; cout<<"The size = "<<Q2.Size()<<endl; Q2.Print(); Q2.pop_Front(); cout <<"The front element = "<<Q2.get_front()<<"\n"; cout<<"The size = "<<Q2.Size()<<endl; Q2.Print(); Q2.pop_Front(); cout <<"The front element = "<<Q2.get_front()<<"\n"; cout<<"The size = "<<Q2.Size()<<endl; Q2.Print(); cout << "\n\n\n\n"; /// Case 2 : Character. Queue<char>Q3('Z',9); Q3.Print(); Queue<char>Q4; Q4.push_Back('A'); Q4.push_Back('B'); Q4.push_Back('C'); Q4.push_Back('D'); Q4.push_Back('E'); cout <<"The front element = "<<Q4.get_front()<<"\n"; cout<<"The size = "<<Q4.Size()<<endl; Q4.Print(); Q4.pop_Front(); cout <<"The front element = "<<Q4.get_front()<<"\n"; cout<<"The size = "<<Q4.Size()<<endl; Q4.Print(); Q4.pop_Front(); cout <<"The front element = "<<Q4.get_front()<<"\n"; cout<<"The size = "<<Q4.Size()<<endl; Q4.Print(); Q4.pop_Front(); cout <<"The front element = "<<Q4.get_front()<<"\n"; cout<<"The size = "<<Q4.Size()<<endl; Q4.Print(); cout << "\n\n\n\n"; /// Case 3 : String. Queue<string>Q5("Bahaa",9); Q5.Print(); Queue<string>Q6; Q6.push_Back("Bahaa EL-Deen Osama"); Q6.push_Back("Abdelrhman Nasr"); Q6.push_Back("Karim Nur El-Deen"); Q6.push_Back("Mohamed Ahmed "); Q6.push_Back("Alaa Mostafa"); cout <<"The front element = "<<Q6.get_front()<<"\n"; cout<<"The size = "<<Q6.Size()<<endl; Q6.Print(); Q6.pop_Front(); cout <<"The front element = "<<Q6.get_front()<<"\n"; cout<<"The size = "<<Q6.Size()<<endl; Q6.Print(); Q6.pop_Front(); cout <<"The front element = "<<Q6.get_front()<<"\n"; cout<<"The size = "<<Q6.Size()<<endl; Q6.Print(); Q6.pop_Front(); cout <<"The front element = "<<Q6.get_front()<<"\n"; cout<<"The size = "<<Q6.Size()<<endl; Q6.Print(); cout << "\n\n\n"; /// Case 4 :floating. Queue<float>Q8(1.345,9); Q8.Print(); Queue<float>Q9; Q9.push_Back(2.345); Q9.push_Back(5.23435); Q9.push_Back(6.7687); Q9.push_Back(7.2343); Q9.push_Back(8.3456); cout <<"The front element = "<<Q9.get_front()<<"\n"; cout<<"The size = "<<Q9.Size()<<endl; Q9.Print(); Q9.pop_Front(); cout <<"The front element = "<<Q9.get_front()<<"\n"; cout<<"The size = "<<Q9.Size()<<endl; Q9.Print(); Q9.pop_Front(); cout <<"The front element = "<<Q9.get_front()<<"\n"; cout<<"The size = "<<Q9.Size()<<endl; Q9.Print(); Q9.pop_Front(); cout <<"The front element = "<<Q9.get_front()<<"\n"; cout<<"The size = "<<Q9.Size()<<endl; Q9.Print(); return 0; }
true
86f6c446dc838d8f7bbe95176b395922e7c65dfc
C++
vishalbelsare/visibility_graph-1
/algorithm/src/math/line_like/ray/ray.hpp
UTF-8
799
2.90625
3
[]
no_license
#pragma once #include <math/line_like/line_like.hpp> MATH_NAMESPACE_BEGIN template<class T, size_t D> class ray : public line_like<T, D> { public: ray() = default; ray(const point<T, D>& p1, const point<T, D>& p2); ray(const ray& other) = default; ray(ray&& other) = default; explicit ray(const line_like<T, D>& other); explicit ray(line_like<T, D>&& other); public: ray& operator=(const ray& other) = default; ray& operator=(ray&& other) = default; public: ray& operator+=(const vector<T, D>& other); ray& operator-=(const vector<T, D>& other); ray operator+(const vector<T, D>& other) const; ray operator-(const vector<T, D>& other) const; public: virtual bool algebraically_inside(const T& coefficent) const override; }; MATH_NAMESPACE_END
true
26d334c3d2fdeb7d9d0190c3d832c682fd9461d6
C++
JoComp27/RockPaperScissors_Game
/RPS Project/OpponentPlayerManager.cpp
UTF-8
1,895
3.28125
3
[]
no_license
#include "OpponentPlayerManager.h" OpponentPlayerManager::OpponentPlayerManager() { this->counter = 0; } PLAY OpponentPlayerManager::play(int currentGame, History const &a, int type) { if (type == 0) { //if Type == 0, play randomly int random = rng.getRandom(0, 2); if (random == 0) { return PLAY::Rock; } else if (random == 1) { return PLAY::Paper; } else { return PLAY::Scissors; } } else if (type == 1) { // If Type == 1, play only Rock return PLAY::Rock; } else if (type == 2) { // If Type == 2, play only Rock, then Paper, then Scissors if (counter == 0) { counter++; return PLAY::Rock; } else if (counter == 1) { counter++; return PLAY::Paper; } else { counter = 0; return PLAY::Scissors; } } else if(type == 3){ // If type == 3, Play Average human strategy STATES lastGame; if (currentGame == 0) { lastGame = STATES::Draw; } else { lastGame = a.WinLossHistory[currentGame - 1]; } if (lastGame == STATES::Win) { return tools.win(a.UserHistory[currentGame - 1]); } else if (lastGame == STATES::Loss) { return a.OpponentHistory[currentGame - 1]; } else { int random = rng.getRandom(0, 2); if (random == 0) { return PLAY::Rock; } else if (random == 1) { return PLAY::Paper; } else { return PLAY::Scissors; } } } else if (type == 4) { if (counter == 0) { counter++; return PLAY::Rock; } else { counter = 0; return PLAY::Paper; } } else { //If type = 5 or other Input value with Cin for player int input; std::cout << "Enter your value : (0 : Rock, 1 : Paper, 2: Scissors): "; std::cin >> input; if (input == 0) { return PLAY::Rock; } else if (input == 1) { return PLAY::Paper; } else { return PLAY::Scissors; } } }
true
bed2cf77f9bd52d712ae11426254d011d544a3c9
C++
mmcike/HXEngine
/HXEngine/HXCore/include/HXColor.h
GB18030
2,000
2.984375
3
[ "MIT" ]
permissive
#pragma once #include "HXCommon.h" namespace HX3D { struct HXColor { // unsigned char r, g, b, a; // դԲֵstepcolor rgbaǸֵ float r, g, b, a; HXColor() :r(255), g(255), b(255), a(255) {} /*HXColor(int color, unsigned char alpha = 255) { r = (unsigned char)((color & 0xff0000) >> 16); g = (unsigned char)((color & 0x00ff00) >> 8); b = (unsigned char)(color & 0x0000ff); a = alpha; }*/ HXColor(float fr, float fg, float fb, float fa = 255) : r(fr), g(fg), b(fb), a(fa) {} /*inline int ToInt() const { return HXColor_TO_24BIT(r,g,b); }*/ inline HXColor operator*(const HXColor& rhs) const { // r >> 8 ൱ r / 255 return HXColor(r * (rhs.r / 255), g * (rhs.g / 255), b * (rhs.b / 255), a * (rhs.a / 255)); } inline HXColor operator*(float rhs) const { float fR = r * rhs; float fG = g * rhs; float fB = b * rhs; float fA = a * rhs; if (fR > 255) { fR = 255; } if (fR < 0) { fR = 0; } if (fG > 255) { fG = 255; } if (fG < 0) { fG = 0; } if (fB > 255) { fB = 255; } if (fB < 0) { fB = 0; } if (fA > 255) { fA = 255; } if (fA < 0) { fA = 0; } return HXColor(fR, fG, fB, fA); } inline HXColor operator/(float rhs) const { return HXColor(r / rhs, g / rhs, b / rhs, a / rhs); } inline HXColor operator-(const HXColor& rhs) const { float fR = r - rhs.r; float fG = g - rhs.g; float fB = b - rhs.b; float fA = a - rhs.a; return HXColor(fR, fG, fB, fA); } inline HXColor& operator+=(const HXColor& rhs) { float fR = r + rhs.r; float fG = g + rhs.g; float fB = b + rhs.b; float fA = a + rhs.a; if (fR > 255) { fR = 255; } if (fG > 255) { fG = 255; } if (fB > 255) { fB = 255; } if (fA > 255) { fA = 255; } r = fR; g = fG; b = fB; a = fA; return *this; } }; }
true
2d9fe95f9c28bf2202c09656f97b9a21c7650fcb
C++
a-kashirin-official/spbspu-labs-2018
/shalgueva.sofiya/A1/main.cpp
UTF-8
790
3.03125
3
[]
no_license
#include <iostream> #include "circle.hpp" #include "rectangle.hpp" int main() { point_t point = {30, 130}; Rectangle r({30, 70, point}); Shape *rectangle = & r; std::cout << "Area of rectangle " << rectangle -> getArea() << std::endl; rectangle -> getFrameRect(); rectangle -> move(70, -30); std::cout << "After moving" << std::endl; std::cout << "Area of rectangle " << rectangle -> getArea() << std::endl; rectangle -> getFrameRect(); Circle c({200, 130}, 25); Shape *circle = & c; std::cout << "Area of circle " << circle -> getArea() << std::endl; circle -> getFrameRect(); circle -> move({10, 10}); std::cout << "After moving" <<std::endl; std::cout << "Area of circle " << circle -> getArea() << std::endl; circle -> getFrameRect(); return 0; }
true
168fd3c7936892cb7b9ddd80fe1986428a7ff437
C++
Tomistong/MyLuoguRepo
/rates/[Mivik Round]nurture/A.cpp
UTF-8
1,127
2.6875
3
[]
no_license
#include <iostream> #include <cstdio> using namespace std; const int maxn = 120; char ht[maxn][maxn]; int ssx[maxn], ssy[maxn]; int oval = 0; int n,m; char dir; int sx,sy; bool rti() { if(dir=='>') { for(int j=sy;j<=m;j++) { if(ht[sx][j]=='x') { printf("GG"); // printf("%d %d = %c\n", sx,j ,ht[sx][j]); return true; } } }else if(dir=='^') { for(int i=sx;i>=1;i--) { if(ht[i][sy]=='x') { printf("GG"); return true; } } }else if(dir=='<') { for(int j=sy;j>=1;j--) { if(ht[sx][j]=='x') { printf("GG"); return true; } } }else if(dir=='v') { for(int i=sx;i<=n;i++) { if(ht[i][sy]=='x') { printf("GG"); return true; } } } return false; } int main() { scanf("%d %d",&n,&m); getchar(); scanf("%c", &dir); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { // scanf("%c", &ht[i][j]); cin >> ht[i][j]; if(ht[i][j]=='o') { ssx[++oval] = i; ssy[oval] = j; } } // getchar(); } if(!oval) { cout << "OK"; return 0; } for(int i=1;i<=oval;i++) { sx = ssx[i], sy=ssy[i]; if(rti()) return 0; } printf("OK"); return 0; }
true
917ec6d4faf34e602b5ff5ea298d00be6f502363
C++
jesperkristensen/algorithms-for-lce
/src/algHashLog.cpp
UTF-8
1,608
2.640625
3
[]
no_license
#include "algHashLog.h" #include <stdlib.h> #include <stdio.h> #include <new> #include <math.h> FingerprintLW::FingerprintLW() { this->s = NULL; this->n = 0; this->H = NULL; this->k = 0; } FingerprintLW::~FingerprintLW() { } bool FingerprintLW::preproc(TestString* s) { uint32 k = (uint32) ceil(log2(s->n+1)); H = new (std::nothrow) uint32[(s->n+1)*k]; if (!H) { return false; } this->s = s->s; this->n = s->n; this->k = k; uint32 h; for (uint32 c = 0; c < k; c++) { // loop through each suffix s->sa[i] in sorted order. for (uint32 i = 0; i < n; i++) { // if suffix s->sa[i] does not have a prefix of length 1<<c in common with its predecessor, then update the current hash if (s->lcp[i] < 1<<c) h = i; H[s->sa[i]] = h; } H[n] = n; H += n+1; } return true; } uint32 FingerprintLW::query(uint32 i, uint32 j) { if (i == j) return this->n - i; uint32 t = 0; uint32* H = this->H; for (int32 c = k-1; c >= 0; c--) { H -= (n+1); if (H[i + t] == H[j + t]) t += 1<<c; } return t; } void FingerprintLW::cleanup() { H -= k*(n+1); delete[] this->H; this->s = NULL; this->n = 0; this->H = NULL; this->k = 0; } void FingerprintLW::getName(char* name, uint32 size) { snprintf(name, size, "Fingerprint_{log n}wc"); } uint64 FingerprintLW::spaceUsage(uint32 n) { uint32 k = (uint32) ceil(log2(n+1)); return sizeof(FingerprintLW) + (n+1)*k*sizeof(uint32); }
true
b7520fb3793940ec5ef34dbae1563c93961218ef
C++
dbecad/Udacity-cpp-3_ObjectOrientedProgramming
/code/friends.cpp
UTF-8
511
2.546875
3
[]
no_license
// include iostream for printing // Declare class Rectangle // Define class Square as friend of Rectangle // Add private attribute squ_side to Square // Add public constructor to Square, initialize squ_side // Implement Rectangle // Add private attributes width, height // Add public functions to Rectangle: Rec_Area() and convert_SquToRec() // Define convert_SquToRec() to take Square and initialize Rectangle // Define Rec_Area() to compute area of Rectangle // Test in main()
true
b89fd9339c069b1169c8d906e364e16f5f45e099
C++
pigrange/LeetCodeStepByStep
/src/accepted/125.ValidPalindrome.cpp
UTF-8
607
3.3125
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> using namespace std; class Solution { public: bool isPalindrome(string s) { int l = 0, r = s.size() - 1; while (l < r) { if (!isValidate(s[l])) { ++l; continue; } if (!isValidate(s[r])) { --r; continue; } if (s[l] != s[r]) return false; else { ++l; --r; } } return true; } private: bool isValidate(char& ch) { if ('A' <= ch && ch <= 'Z') ch = ch + 32; return ('0' <= ch && ch <= '9' && ch <= 'z' && 'a' <= ch); } };
true
83107fb99f5f4a6abe762f5460381b1d090da7ff
C++
lnikon/SimpleCalculator
/include/tokenizer.h
UTF-8
1,394
3.453125
3
[]
no_license
#ifndef TOKENIZER_H #define TOKENIZER_H #include <istream> #include "tokentype.h" #include "token.h" /** * @todo write docs */ template <class NumericType> class Tokenizer { public: /** * Default constructor */ Tokenizer(std::istream&); Token<NumericType> GetToken(); private: std::istream & m_in; }; template <class NumericType> Tokenizer<NumericType>::Tokenizer(std::istream& is) : m_in(is) { } template<class NumericType> Token<NumericType> Tokenizer<NumericType>::GetToken() { char ch; NumericType theValue; while(m_in.get(ch) && ch == ' ') {} if(m_in.good() && ch != '\n' && ch != '\0') { switch(ch) { case '^': return TokenType::EXP; case '/': return TokenType::DIV; case '*': return TokenType::MUL; case '(': return TokenType::OPAREN; case ')': return TokenType::CPAREN; case '+': return TokenType::PLUS; case '-': return TokenType::MINUS; default: m_in.putback(ch); if(!(m_in >> theValue)) { std::cerr << "Parse error" << std::endl; return TokenType::EOL; } return Token<NumericType>(VALUE, theValue); } } return TokenType::EOL; } #endif // TOKENIZER_H
true
621809a975b6ed1f17ad9286f40f161f63674b6c
C++
IgorYunusov/Mega-collection-cpp-1
/CPP_cookbok_source/11-40.cpp
UTF-8
2,107
3.578125
4
[]
no_license
#include <iostream> using namespace std; template<int E> struct BasicFixedReal { typedef BasicFixedReal self; static const int factor = 1 << (E - 1); BasicFixedReal() : m(0) { } BasicFixedReal(double d) : m(static_cast<int>(d * factor)) { } self& operator+=(const self& x) { m += x.m; return *this; } self& operator-=(const self& x) { m -= x.m; return *this; } self& operator*=(const self& x) { m *= x.m; m >>= E; return *this; } self& operator/=(const self& x) { m /= x.m; m *= factor; return *this; } self& operator*=(int x) { m *= x; return *this; } self& operator/=(int x) { m /= x; return *this; } self operator-() { return self(-m); } double toDouble() const { return double(m) / factor; } // friend functions friend self operator+(self x, const self& y) { return x += y; } friend self operator-(self x, const self& y) { return x -= y; } friend self operator*(self x, const self& y) { return x *= y; } friend self operator/(self x, const self& y) { return x /= y; } // comparison operators friend bool operator==(const self& x, const self& y) { return x.m == y.m; } friend bool operator!=(const self& x, const self& y) { return x.m != y.m; } friend bool operator>(const self& x, const self& y) { return x.m > y.m; } friend bool operator<(const self& x, const self& y) { return x.m < y.m; } friend bool operator>=(const self& x, const self& y) { return x.m >= y.m; } friend bool operator<=(const self& x, const self& y) { return x.m <= y.m; } private: int m; }; typedef BasicFixedReal<10> FixedReal; int main() { FixedReal x(0); for (int i = 0; i < 100; ++i) { x += FixedReal(0.0625); } cout << x.toDouble() << endl; }
true
51239b5f6c97f3d6c175a5eb66283de2aff52e16
C++
Jarogna/Unit8_Inheritance_Ronald_Angora
/Classes.h
UTF-8
772
2.6875
3
[]
no_license
class Cost { Private: double tuition; double roomAndBoard; double travelCost; double foodCost; double bookCost; Public: Cost() = default; void setTution(double t) = { tuition = t; } void setRoomAndBoard(double rB) = { roomAndBoard = rB; } void setTravelCost(double tC) = { travelCost = tC; } void setFoodCost(double fC) = { foodCost = fC; } void setBookCost(double bC) = { bookCost = bC; } double getTution() const { return tution; } double getRoomAndBoard() const { return roomAndBoard; } double getTravelCost() const { return travelCost; } double getFoodCost() const { return foodCost; } double getBookCost() const { return bookCost; } void values() { } } class Semester: public Cost { }
true
87f63b16df3f6addfd6effc5cb7e1f84c2413121
C++
honpui/leetcode
/3-字符串/实现strstr/实现strstsr/实现strstsr/源.cpp
UTF-8
711
3.265625
3
[]
no_license
#include <iostream> using namespace std; int compare(char* haystack,int head,char* needle) { int i = 0; while (needle[i] != '\0') { if (haystack[head++] != needle[i++]) { return -1; } } return 0; } int strStr(char * haystack, char * needle){ if ((needle == NULL) ||(haystack == NULL ) || (needle[0] == '\0')) { return 0; } int index=0; while (haystack[index] != '\0') { if (0 == compare(haystack, index, needle)) { return index; } index++; } return -1; } int main() { /* char haystack[] = "aaabbb"; char needle[] = "aa"; */ char haystack[10] = ""; char needle[] = "ccc"; printf("%d\n", strlen(haystack)); int res= strStr(haystack,needle); return 0; }
true
c953ac59453c5d4ed1aa5e9cf779507f808c5050
C++
emilybache/custom-start-points
/start-points/C++Countdown/Round5/scorer.cpp
UTF-8
3,948
3.125
3
[ "BSD-2-Clause" ]
permissive
#include <algorithm> #include <cctype> #include <fstream> #include <iostream> #include <iomanip> #include <vector> using namespace std; #include "tokens.cpp" static void print_compiler_version() { cout << ">>> Compiler is G++ " << __VERSION__ << '\n'; cout << ">>> Standard C++ " << __cplusplus << '\n'; cout << ">>>\n"; } static int line_size(const string & line) { int size = 0; for (auto & ch : line) if (!isspace(ch)) size++; return size; } static int lines_size(const vector<string> & lines) { int size = 0; for (auto & line : lines) size += line_size(line); return size; } static void print_program_size(const vector<string> & lines) { const int width = 60; cout << endl; cout << "-----|" << string(width,'-') << endl; int total_size = 0; for (auto & line : lines) { const int size = line_size(line); cout << setw(3) << setfill(' ') << size << " |" << line << endl; total_size += size; } cout << "-----|" << string(width, '-') << endl; cout << setw(3) << setfill(' ') << total_size << " == countdown.cpp.size" << endl; cout << endl; } // - - - - - - - - - - - - - - - - - - - - static vector<string> read_lines(const char * filename) { vector<string> lines; ifstream is(filename); string line; while (getline(is, line)) lines.push_back(line); return lines; } // - - - - - - - - - - - - - - - - - - - - static bool uses(const vector<string> & lines, const string & token) { // ... also matches . // double also matches do // etc etc for (auto & line : lines) if (line.find(token) != string::npos) return true; return false; } static int tokens_size(const vector<string> & lines) { int size = 0; for (auto & token : tokens) if (uses(lines, token)) size += token.size(); return size; } static bool missing_tokens(const vector<string> & lines) { vector<string> unused; for (auto & token : tokens) if (!uses(lines, token)) return true; return false; } // - - - - - - - - - - - - - - - - - - - - static void print_token_bonuses(const vector<string> & lines) { const int width = 20; int tokens_size = 0; cout << "-----|" << string(width,'-') << endl; for (auto & token : tokens) if (uses(lines, token)) { cout << setw(3) << setfill(' ') << token.size() << " |" << token << endl; tokens_size += token.size(); } for (auto & token : tokens) if (!uses(lines, token)) cout << setw(3) << setfill(' ') << 0 << " |" << token << endl; cout << "-----|" << string(width,'-') << endl; cout << setw(3) << setfill(' ') << tokens_size << " == used_tokens.size" << endl; int completion_bonus = missing_tokens(lines) ? 0 : 50; cout << setw(3) << setfill(' ') << completion_bonus << " == completion.bonus" << endl; } // - - - - - - - - - - - - - - - - - - - - int main(int, const char * argv[]) { print_compiler_version(); vector<string> lines = read_lines(argv[1]); int program_size = lines_size(lines); int used_token_bonus = tokens_size(lines); int completion_bonus = missing_tokens(lines) ? 0 : 50; cout << ">>> Score = -countdown.cpp.size + 3*used_tokens.size + completion.bonus" << endl << ">>> = " << setw(3) << setfill(' ') << -program_size << " + " << "3*" << used_token_bonus << " + " << completion_bonus << endl << ">>> = " << (-program_size + (3*used_token_bonus) + completion_bonus) << endl; cout << endl; print_token_bonuses(lines); cout << endl; print_program_size(lines); // green-traffic light pattern...put it out of sight for(int i = 0; i < 100; i++) cout << endl; cout << "All tests passed\n"; }
true
1c31d3f7f80bc4fc742ce970152a42fc6416b832
C++
aleksandarkiridzic/dna-sequence-aligner
/str.h
UTF-8
1,134
2.9375
3
[]
no_license
#ifndef STR_H_INCLUDED #define STR_H_INCLUDED #include "general.h" #include <iostream> #include <cstring> // basic string structure holding characters and its length immutable_class Str { protected: const char* chars = nullptr; unsigned len = 0; public: Str() {} Str(const char* src, unsigned len); Str(std::string str): Str(str.c_str(), str.length()) {} Str(unsigned len, const char* ptr): chars(ptr), len(len) {} // shallow copy ~Str() { /* destroy(); */ } // must be destroyed explicitly const unsigned length() const { return len; } const bool isEmpty() const { return !chars || len == 0; } const char& operator[](int i) const; Str subStr(unsigned from, unsigned siz) const; Str subStrCatch(unsigned from, unsigned siz) const; const char lastCharVisible() const; static Str empty; protected: virtual void destroy(); friend std::ostream& operator<<(std::ostream& os, const Str& str); friend class StrUtil; friend class StrFact; friend class SuffixArray; friend class Checkpoint; }; #endif // STR_H_INCLUDED
true
5014a756bc84a8a91ddaad2fc4290c8423fdac14
C++
eduardosalas1/Proyecto1
/main.cpp
UTF-8
3,358
2.890625
3
[]
no_license
#include <iostream> #include <fstream> #include <vector> #include <ctime> #include <tuple> #include <string> #include <fstream> #include "SequentialFile.cpp" using namespace std; int main(){ /*srand(time(nullptr)); char nums[10] = {'0','1','2','3','4','5','6','7','8','9'}; //Dni vector<string> vDni; for(int i = 0; i < 300; i++){//es 300 string temp = ""; temp = temp + nums[rand()%10] + nums[rand()%10] + nums[rand()%10] + nums[rand()%10] + nums[rand()%10] + nums[rand()%10] + nums[rand()%10] + nums[rand()%10]; vDni.push_back(temp); } //Nombre string nombre[30] = {"Alvaro", "Eduardo", "Guillermo", "Wilder", "Miguel", "Gonzalo", "Fernanda", "Maria", "Fiorela", "Carla", "Carlos", "Heider", "Juan", "Jorge", "Valeria", "Chiara", "Ximena", "Ivana", "Cesar", "Paolo", "Paola", "Mario", "Xander", "Johnny", "Kevin", "Jimena", "Andrea", "Marcelo", "Grabiela", "Silvia"}; vector<string> vNombre; for(int i = 0; i < 300; i++){ string temp2 = ""; temp2 += nombre[rand()%30]; vNombre.push_back(temp2); } //Apellidos vector<string> vApellido; string apellido[30] = {"Salas", "Palacios", "Casas", "Sanchez", "Albarracin", "Aguirre", "Knel", "Ukzeyi", "Benavides", "Santillana", "Casillas", "Bernal", "Oyague", "Marquez", "Medina", "Campodonico", "Campos", "Sins", "Castillo", "Parker", "Lee", "Yelnats", "Guerrero", "Gaz", "Perez", "Berg", "Kayser", "Bin", "Laden", "Diaz"}; for(int i = 0; i < 300; i++){ string temp3 = ""; temp3 += apellido[rand()%30] + " " + apellido[rand()%30]; vApellido.push_back(temp3); } //Carrera vector<string> vCarrera; string carrera[9] = {"CS", "Bioingenieria", "Mecatronica", "Industrial", "Energia", "DS", "Mecanica", "Quimica", "Electronica"}; for(int i = 0 ; i < 300 ; i++){ string temp4 = ""; temp4 += carrera[rand()%9]; vCarrera.push_back(temp4); } //Mensualidad vector<float> vMensualidad; float mensualidad[8] = {1050.5, 1310.5, 2000, 2020.2, 3708.2, 3500.8, 4400.9, 4999.9}; for(int i = 0; i < 300; i++){ float temp5 = mensualidad[rand()%8]; vMensualidad.push_back(temp5); } ofstream file; file.open("Alumnos.dat",ios::out); if(file.is_open()){ file<<"Dni|Nombre|Apellido|Carrera|Mensualidad"<<endl; for(auto i = 0 ; i < vDni.size() ; i++){ file<<vDni.at(i)<<'|'<<vNombre.at(i)<<'|'<<vApellido.at(i)<<'|'<<vCarrera.at(i)<<'|'<<vMensualidad.at(i)<<endl; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// */ string filename = "Alumnos.dat"; Alumno alumno1("99999999", "Eduardo", "Salas Palacios", "CS", 2000.45); Alumno alumno2("69696969","Andrea","Aguirre","CS",3000); SequentialFile sf(filename); //thread th1() sf.insertAll(); sf.add(alumno1); cout << sf.Search(99999999, true)<<endl; cout<<sf.deletion(30)<<endl; sf.add(alumno2); cout << sf.Search(99999999, true)<<endl; cout<<sf.Search(69696969,true)<<endl; cout<<sf.deletion(207)<<endl; ifstream file("Alumnos.dat"); int pos = 207*sizeof(Alumno); Alumno temp; file.seekg(pos); file>>temp; cout<<temp.next; return 0; }
true
c94578eb530a7f6381ffb3a48c151155eb92e0f7
C++
JacobWheeler/AssemblerGroupAssignment
/AssemblerGroupAssignment/main.cpp
UTF-8
4,643
3.1875
3
[]
no_license
// // main.cpp // AssemblerGroupAssignment // // Created by Jacob Wheeler, Gabe Cerritos, Katie Rose on 9/6/19. // Copyright © 2019 Jacob Wheeler. All rights reserved. // #include <iostream> #include <fstream> #include <bitset> #include <algorithm> #include <vector> #include <string> #include <sstream> #include "Instruction.h" using namespace std; // FUNCTION DECLARATIONS vector <string> readFile(string file, vector <string> v); bitset<4> opcodeConversion(string s); bitset<2> registerConversion(string s); bitset<8> immediateConversion(int n); // MAIN int main(int argc, const char * argv[]) { vector <string> inputStrings; vector <string> z = readFile("gcd.s", inputStrings); for(int i = 0; i < z.size(); i++){ cout << z[i]; } return 0; } // TODO: 1) Loop through strings in readFile and send the parts to the appropriate // functions in order to turn them into binary... // 2) Shift the bits and | them together with the next assembly instruction // 3) Output to outStream("Assembler_Converted.bin") // 3a) This will store the binary in a .bin file... // 3b) If we output a string to the .bin file it will still // act as a .txt file... // 4) Call functions in main to actually run the program // FUNCTION DEFINITIONS vector<string> readFile(string file, vector<string> v) { // Variables ifstream myStream(file); ofstream outStream("Assembler_Converted.bin"); stringstream sstr; // Get lines of file while not at the end of file // Create string variable and store line string line; while (getline(myStream, line)) { stringstream splitter(line); string name; string arg1; string arg2; string arg3; splitter >> name; splitter >> arg1; splitter >> arg2; splitter >> arg3; // cout << name << endl << arg1<< endl << arg2 << endl << arg3 << endl; bitset<16> completeBinary; bitset<16> opcode = (bitset<16>)(opcodeConversion(name).to_ulong()); opcode <<= 12; completeBinary |= opcode; if(arg1[0] == '$'){ bitset<16> reg1 = (bitset<16>)(registerConversion(arg1).to_ulong()); reg1 <<= 10; completeBinary |= reg1; }else{ int imm = stoi(arg1); bitset<16> imm1 = (bitset<16>)(immediateConversion(imm).to_ulong()); imm1 <<= 4; completeBinary |= imm1; } if(!(arg2.empty())){ if(arg2[0] == '$'){ bitset<16> reg2 = (bitset<16>)(registerConversion(arg2).to_ulong()); reg2 <<= 8; completeBinary |= reg2; }else{ int imm = stoi(arg2); bitset<16> imm1 = (bitset<16>)(immediateConversion(imm).to_ulong()); imm1 <<= 2; completeBinary |= imm1; } } if(!(arg3.empty())){ if(arg3[0] == '$'){ bitset<16> reg3 = (bitset<16>)(registerConversion(arg3).to_ulong()); reg3 <<= 6; completeBinary |= reg3; }else{ int imm = stoi(arg3); bitset<16> imm1 = (bitset<16>)(immediateConversion(imm).to_ulong()); completeBinary |= imm1; } } ofstream outStream("Assembler_Converted.bin"); outStream << completeBinary << endl; cout << completeBinary << endl; } return v; } // Convert string into 4 bit binary bitset<4> opcodeConversion(string s) { int opcode = 0; // If statement to check which opcode to return if(s == "addi"){ opcode = 1; }else if(s == "blt"){ opcode = 2; }else if(s == "bne"){ opcode = 3; }else if(s == "j"){ opcode = 4; }else if(s == "mul"){ opcode = 5; }else if(s == "sub"){ opcode = 6; }else if(s == "read"){ opcode = 7; }else if(s == "print"){ opcode = 8; } bitset<4> opcodeBin(opcode); return opcodeBin; } // Convert integer into 2 bit binary bitset<2> registerConversion(string s) { int registerNum = 0; if(s == "$0"){ registerNum = 0; }else if(s == "$1"){ registerNum = 1; }else if(s == "$2"){ registerNum = 2; }else if(s == "$3"){ registerNum = 3; } bitset<2> registerBin(registerNum); return registerBin; } // Convert integer into 8 bit Binary bitset<8> immediateConversion(int n) { bitset<8> immediateBin(n); return immediateBin; }
true
b02b096a4198b82f2b1236a8d0e16d1a57802e70
C++
asdlei99/winupdate
/winupdate.cpp
UTF-8
3,813
2.6875
3
[ "MIT" ]
permissive
#include <windows.h> #include <stdio.h> #include <string> #include <string.h> #include "winupdate.h" using namespace std; namespace winupdate { // Retrieve directory of path, which is everything up to the last backslash (but excluding the last backslash) static std::wstring Dir(std::wstring path) { auto lastSlash = path.rfind('\\'); if (lastSlash == -1) return L""; else return path.substr(0, lastSlash); } // Returns everything after the last backslash, or the entire string if there are no backslashes static std::wstring Basename(std::wstring path) { auto lastSlash = path.rfind('\\'); if (lastSlash == -1) return path; else return path.substr(lastSlash + 1); } // Retrieve full path of current executing process static std::wstring AppPath() { wchar_t buf[4096]; GetModuleFileNameW(NULL, buf, 4096); buf[4095] = 0; return buf; } // Retrieve directory of current executing process static std::wstring AppDir() { return Dir(AppPath()); } static std::wstring BuildSpecialDir(std::wstring extension) { auto appDir = AppDir(); auto oneAbove = Dir(appDir); auto appName = appDir.substr(oneAbove.size()); return oneAbove + L"\\" + appName + extension; } // C:\Users\bob\AppData\Local\Company\Product-next static std::wstring NextUpdateDir() { return BuildSpecialDir(L"-next"); } // C:\Users\bob\AppData\Local\Company\Product-temp static std::wstring TempDir() { return BuildSpecialDir(L"-temp"); } static bool Launch(wstring cmd) { wchar_t* buf = new wchar_t[cmd.size() + 1]; wcscpy_s(buf, cmd.size() + 1, cmd.c_str()); STARTUPINFOW startInfo; PROCESS_INFORMATION procInfo; memset(&startInfo, 0, sizeof(startInfo)); memset(&procInfo, 0, sizeof(procInfo)); startInfo.cb = sizeof(startInfo); bool launchOK = !!CreateProcessW(nullptr, buf, nullptr, nullptr, false, DETACHED_PROCESS, nullptr, nullptr, &startInfo, &procInfo); delete[] buf; CloseHandle(procInfo.hProcess); CloseHandle(procInfo.hThread); return launchOK; } // Create a system-wide semaphore that signals to other processes, that there is at least one of us running. // This is necessary, because it is impossible to update an application when there are other copies of it // running. To put it another way, this is used to detect if we are the first instance of this program to run, // and only if that is true, do we proceed with an update. // This function returns true if we are the first instance to run. static bool IsFirstInstance() { // We never lock the mutex. We are merely using it's presence to detect if there are other versions of us running. auto name = AppDir(); for (size_t i = 0; i < name.size(); i++) { if (name[i] == '\\') name[i] = '_'; } // the Go side of us also has a runner lock, called "winupdate-runner-lock-" + ... name = L"winupdate-self-lock" + name; HANDLE mutex = CreateMutexW(nullptr, true, name.c_str()); if (mutex == nullptr) return false; if (GetLastError() == ERROR_ALREADY_EXISTS) return false; return true; } static bool IsUpdateReady() { return GetFileAttributesW((NextUpdateDir() + L"\\update.ready").c_str()) != INVALID_FILE_ATTRIBUTES; } static void LaunchUpdateDownloader(const wchar_t* archiveURL) { Launch(L"\"" + AppDir() + L"\\winupdate.exe\" download " + archiveURL); } Action Update(const wchar_t* archiveURL) { if (!IsFirstInstance()) return Action::ContinueAsUsual; // Regardless of whether we are going to update or not, we leave the mutex created, so that // other processes know we're still alive. if (!IsUpdateReady()) { LaunchUpdateDownloader(archiveURL); return Action::ContinueAsUsual; } auto self = Basename(AppPath()); if (Launch(L"\"" + TempDir() + L"\\winupdate.exe\" update \"" + self + L"\"")) return Action::ExitNow; return Action::ContinueAsUsual; } } // namespace winupdate
true
4fd05f096cc4cc0bed156ac2bf04c173f6f0bb0c
C++
ash9991win/VVVVVV
/source/UnitTest.Library.Desktop/SListIteratorTest.cpp
UTF-8
4,447
2.578125
3
[]
no_license
#include "pch.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace LibraryDesktop; namespace UnitTestLibraryDesktop { TEST_CLASS(SListIteratorTest) { public: TEST_METHOD_INITIALIZE(PrepForTests) { #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF); _CrtMemCheckpoint(&startMemState); #endif } #if defined(DEBUG) | defined(_DEBUG) TEST_METHOD_CLEANUP(CleanupTestObjects) { intSList.Clear(); intPtrSList.Clear(); fooSList.Clear(); _CrtMemState endMemState, diffMemState; _CrtMemCheckpoint(&endMemState); if (_CrtMemDifference(&diffMemState, &startMemState, &endMemState)) { _CrtMemDumpStatistics(&diffMemState); Assert::Fail(L"Memory Leaks!"); } } #endif TEST_METHOD(SListIteratorTestEquality) { //int tests SList<int>::Iterator intIterator, otherIntIterator; Assert::IsTrue(intIterator == otherIntIterator); intIterator = intSList.begin(); otherIntIterator = intSList.end(); Assert::IsTrue(intIterator == otherIntIterator); intSList.PushFront(20); intSList.PushBack(30); intSList.PushFront(40); intIterator = intSList.begin(); otherIntIterator = intSList.Find(30); Assert::IsTrue(intIterator != otherIntIterator); intIterator = intSList.Find(30); Assert::IsTrue(intIterator == otherIntIterator); //int* tests intPtrSList.PushFront(&testArray[0]); intPtrSList.PushBack(&testArray[1]); auto intPtrIterator = intPtrSList.Find(&testArray[1]); intPtrSList.PushFront(&testArray[1]); auto otherIntPtrIterator = intPtrSList.Find(&testArray[1]); Assert::IsTrue(intPtrIterator != otherIntPtrIterator); intPtrIterator = intPtrSList.begin(); Assert::IsTrue(intPtrIterator == otherIntPtrIterator); //Foo tests SList<Foo> otherFooSList; fooSList.PushFront(Foo(12)); fooSList.PushBack(Foo(13)); otherFooSList.PushFront(fooSList.Front()); otherFooSList.PushBack(fooSList.Back()); auto fooIterator = fooSList.begin(); auto otherFooIterator = otherFooSList.begin(); Assert::IsTrue(fooIterator != otherFooIterator); otherFooIterator = fooSList.begin(); Assert::IsTrue(fooIterator == otherFooIterator); } TEST_METHOD(SListIteratorTestInvalidOperations) { SList<int>::Iterator intIterator; SList<int*>::Iterator intPtrIterator; SList<Foo>::Iterator fooIterator; auto badDereference = [&] { (*intIterator); }; auto badPrefixIncrement = [&] { ++intPtrIterator; }; auto badPostfixIncrement = [&] { fooIterator++; }; Assert::ExpectException<std::exception>(badDereference); Assert::ExpectException<std::exception>(badPrefixIncrement); Assert::ExpectException<std::exception>(badPostfixIncrement); intIterator = intSList.begin(); intPtrIterator = intPtrSList.begin(); fooIterator = fooSList.begin(); Assert::IsTrue(intSList.IsEmpty()); Assert::IsTrue(intPtrSList.IsEmpty()); Assert::IsTrue(fooSList.IsEmpty()); Assert::ExpectException<std::exception>(badDereference); Assert::ExpectException<std::exception>(badPrefixIncrement); Assert::ExpectException<std::exception>(badPostfixIncrement); } TEST_METHOD(SListIteratorTestPostfixIncrement) { int i; for (i = 1; i < 6; i++) { intSList.PushBack(i); intPtrSList.PushBack(&testArray[i - 1]); fooSList.PushBack(Foo(i)); } //int test i = 0; for (auto intIterator = intSList.begin(); intIterator != intSList.end(); intIterator++) { Assert::AreEqual(testArray[i++], (*intIterator)); } //int* test i = 0; for (auto intPtrIterator = intPtrSList.begin(); intPtrIterator != intPtrSList.end(); intPtrIterator++) { Assert::AreEqual(&testArray[i++], (*intPtrIterator)); } //Foo test i = 0; for (auto fooIterator = fooSList.begin(); fooIterator != fooSList.end(); fooIterator++) { Assert::AreEqual(testArray[i++], (*fooIterator).Data()); } } private: static SList<int> intSList; static SList<int*> intPtrSList; static SList<Foo> fooSList; static int testArray[5]; #if defined(DEBUG) | defined(_DEBUG) static _CrtMemState startMemState; #endif }; SList<int> SListIteratorTest::intSList; SList<int*> SListIteratorTest::intPtrSList; SList<Foo> SListIteratorTest::fooSList; int SListIteratorTest::testArray[] = { 1, 2, 3, 4, 5 }; #if defined(DEBUG) | defined(_DEBUG) _CrtMemState SListIteratorTest::startMemState; #endif }
true
c76bb50e842b748951ea00d41f4f94540f7b4073
C++
MonikaWielgus/Cpp
/PRL/source.cpp
UTF-8
8,350
2.859375
3
[]
no_license
//Monika Wielgus #include <iostream> using namespace std; extern double limit_dziecko[]; extern double limit_kobieta_w_ciazy[]; extern double limit_robotnik[]; enum Grupa{dziecko, kobieta_w_ciazy, robotnik, bez_grupy}; static unsigned int ludnosc=0; struct Kartka { double mieso; double czekolada; }; struct Obywatel { int NIP; Grupa grupa; Kartka kartka; Obywatel *nastepny; Obywatel *poprzedni; Obywatel() { NIP=0; grupa=bez_grupy; kartka.mieso=0.0; kartka.czekolada=0.0; nastepny=NULL; poprzedni=NULL; } Obywatel(int g) { nastepny=NULL; poprzedni=NULL; NIP=ludnosc+1; ludnosc++; if(dziecko==g) { grupa=dziecko; kartka.mieso=*(limit_dziecko); kartka.czekolada=*(limit_dziecko+1); } if(kobieta_w_ciazy==g) { grupa=kobieta_w_ciazy; kartka.mieso=*(limit_kobieta_w_ciazy); kartka.czekolada=*(limit_kobieta_w_ciazy+1); } if(robotnik==g) { grupa=robotnik; kartka.mieso=*(limit_robotnik); kartka.czekolada=*(limit_robotnik+1); } } }; struct Sklep { char symbol; //M-sklep miesny, C-sklep z czekolada double towar; //ile miesa lub czekolady dany sklep moze sprzedac Obywatel *pierwszy; Obywatel *ostatni; Sklep() { pierwszy=NULL; ostatni=NULL; } Sklep(char s, double x) // s to C albo M { pierwszy=NULL; ostatni=NULL; symbol=s; towar=x; } void dostawa(double g) { towar+=g; } void ustawKlientaNaKoniec(int g) { Obywatel *nowy=new Obywatel(g); if (pierwszy==nullptr) { pierwszy=nowy; ostatni=nowy; } else { Obywatel *tymczasowy=ostatni; ostatni=nowy; tymczasowy->nastepny=ostatni; } } void ustawKlientaNaPoczatek(int g) { Obywatel* nowy = new Obywatel(g); nowy->poprzedni=nullptr; nowy->nastepny=pierwszy; if (pierwszy==nullptr) { pierwszy=nowy; ostatni=nowy; } else { pierwszy=nowy; } } void ustawZaKlientem(int k, int g) { Obywatel *nowy = new Obywatel(g); Obywatel *tymczasowy=pierwszy; for(int i=2; i<=k; i++) { if(tymczasowy!=nullptr) { tymczasowy=tymczasowy->nastepny; } else { break; } } if(tymczasowy!=nullptr&&tymczasowy->nastepny!=nullptr) { nowy->nastepny=tymczasowy->nastepny; nowy->poprzedni=tymczasowy; tymczasowy->nastepny=nowy; } else if(tymczasowy!=nullptr&&tymczasowy->nastepny==nullptr) { ostatni=nowy; tymczasowy->nastepny=nowy; nowy->poprzedni=tymczasowy; } else { nowy->poprzedni=ostatni; ostatni->nastepny=nowy; ostatni=nowy; } } void usunKlienta(int n) { struct Obywatel *tymczasowy; struct Obywatel *tymczasowy2; if(pierwszy->NIP==n) //pierwszy { tymczasowy=pierwszy; pierwszy=pierwszy->nastepny; pierwszy->poprzedni=nullptr; delete tymczasowy; ludnosc--; } tymczasowy2=pierwszy; while(tymczasowy2->nastepny->nastepny!=nullptr) //srodkowy, musza byc za nim dwa elementy, bo tsk dziala ten algorytm { if(tymczasowy2->nastepny->NIP==n) { tymczasowy=tymczasowy2->nastepny; tymczasowy2->nastepny=tymczasowy->nastepny; tymczasowy->nastepny->poprzedni=tymczasowy2; delete tymczasowy; ludnosc--; } tymczasowy2=tymczasowy2->nastepny; } if(tymczasowy2->nastepny->NIP==n) //ostatni { tymczasowy=tymczasowy2->nastepny; delete tymczasowy; tymczasowy2->nastepny=nullptr; ludnosc--; } } bool towarWydano(double x, Obywatel* o) { if(symbol=='C') { if(towar>0) { if(towar>=x) { if(o->kartka.czekolada>=x) { towar-=x; o->kartka.czekolada-=x; } else { o->kartka.czekolada=0; towar-=o->kartka.czekolada; } } else { if(o->kartka.czekolada>=x) { towar=0; o->kartka.czekolada-=towar; } else { if(towar>=o->kartka.czekolada) { towar-=x; o->kartka.czekolada-=x; } else { towar=0; o->kartka.czekolada-=x; } } } return true; } else return false; } else if(symbol=='M') { if(towar>0) { if(towar>=x) { if(o->kartka.mieso>=x) { towar-=x; o->kartka.mieso-=x; } else { o->kartka.mieso=0; towar-=o->kartka.mieso; } } else { if(o->kartka.mieso>=x) { towar=0; o->kartka.mieso-=towar; } else { if(towar>=o->kartka.mieso) { towar-=x; o->kartka.mieso-=x; } else { towar=0; o->kartka.mieso-=x; } } } return true; } else return false; } } void sprzedaz(double x) { Obywatel *tymczasowy=pierwszy; while(tymczasowy!=nullptr) { if(towarWydano(x,tymczasowy)==true) { if(tymczasowy->nastepny!=nullptr) { usunKlienta(tymczasowy->NIP); tymczasowy=pierwszy; } else usunKlienta(tymczasowy->NIP); } else break; } } void odwrocKolejnosc() { Obywatel *obecny=pierwszy; Obywatel *tpoprzedni=nullptr; Obywatel *tnastepny=nullptr; while(obecny) { tnastepny=obecny->nastepny; obecny->nastepny=tpoprzedni; obecny->poprzedni=tnastepny; tpoprzedni=obecny; obecny=tnastepny; } pierwszy=tpoprzedni; } int sprwadzObecnosc() { Obywatel *tymczasowy=pierwszy; int ludzie=0; while(tymczasowy!=nullptr) { cout << tymczasowy->NIP << " " <<tymczasowy->grupa << " " << tymczasowy->kartka.mieso << " " << tymczasowy->kartka.czekolada; cout << endl; ludzie++; tymczasowy=tymczasowy->nastepny; } return ludzie; } void dolaczKolejke(Sklep &sklep2) { if(sklep2.symbol==symbol) { sklep2.odwrocKolejnosc(); ostatni->nastepny=sklep2.pierwszy; } } ~Sklep() { } };
true
82dbcb9918b647c7c7198be52fae7b9067276b94
C++
btcup/sb-admin
/exams/2559/02204111/2/midterm/2_2_716_5920501791.cpp
UTF-8
286
2.6875
3
[ "MIT" ]
permissive
//5920501791 Amarin Sonti #include <iostream> #include <cmath> using namespace std; int main () { int num,n; if(num>0){ cout<<"Enter an integer : "; cin>>n; int num[n]; cout<<"Number of digit is "<<endl; } system ("pause"); return 0; }
true
7d6598772d4da88eda6d7227cea1101c4d93bd09
C++
henu/urhoextras
/json.cpp
UTF-8
22,991
2.9375
3
[ "MIT" ]
permissive
#include "json.hpp" namespace UrhoExtras { bool writeStringWithoutEnding(Urho3D::String const& str, Urho3D::Serializer& dest) { return dest.Write(str.CString(), str.Length()); } Urho3D::String escapeString(Urho3D::String const& str) { // TODO: Escape unicode characters! Urho3D::String result = str; result.Replace("\\", "\\\\"); result.Replace("\n", "\\n"); result.Replace("\"", "\\\""); result.Replace("\'", "\\\'"); return result; } bool saveJson(Urho3D::JSONValue const& json, Urho3D::Serializer& dest) { if (json.IsBool()) { if (json.GetBool()) { if (!writeStringWithoutEnding("true", dest)) return false; } else { if (!writeStringWithoutEnding("false", dest)) return false; } } else if (json.IsNull()) { if (!writeStringWithoutEnding("null", dest)) return false; } else if (json.IsNumber()) { if (json.GetNumberType() == Urho3D::JSONNT_NAN) { if (!writeStringWithoutEnding("null", dest)) return false; } else if (json.GetNumberType() == Urho3D::JSONNT_INT) { if (!writeStringWithoutEnding(Urho3D::String(json.GetInt()), dest)) return false; } else if (json.GetNumberType() == Urho3D::JSONNT_UINT) { if (!writeStringWithoutEnding(Urho3D::String(json.GetUInt()), dest)) return false; } else if (json.GetNumberType() == Urho3D::JSONNT_FLOAT_DOUBLE) { if (!writeStringWithoutEnding(Urho3D::String(json.GetDouble()), dest)) return false; } } else if (json.IsString()) { if (!dest.WriteByte('\"')) return false; if (!writeStringWithoutEnding(escapeString(json.GetString()), dest)) return false; if (!dest.WriteByte('\"')) return false; } else if (json.IsArray()) { if (!dest.WriteByte('[')) return false; Urho3D::JSONArray const& arr = json.GetArray(); for (unsigned i = 0; i < arr.Size(); ++ i) { if (!saveJson(arr[i], dest)) return false; if (i < arr.Size() - 1) { if (!dest.WriteByte(',')) return false; } } if (!dest.WriteByte(']')) return false; } else if (json.IsObject()) { if (!dest.WriteByte('{')) return false; for (Urho3D::JSONObject::ConstIterator it = json.GetObject().Begin(); it != json.GetObject().End(); ++ it) { Urho3D::String const& key = it->first_; Urho3D::JSONValue const& value = it->second_; if (!dest.WriteByte('\"')) return false; if (!writeStringWithoutEnding(escapeString(key), dest)) return false; if (!writeStringWithoutEnding("\":", dest)) return false; if (!saveJson(value, dest)) return false; Urho3D::JSONObject::ConstIterator it_next = it; ++ it_next; if (it_next != json.GetObject().End()) { if (!dest.WriteByte(',')) return false; } } if (!dest.WriteByte('}')) return false; } else { return false; } return true; } int jsonToInt( Urho3D::JSONValue const& json, Urho3D::String const& error_prefix, int min_limit, int max_limit ) { if (!json.IsNumber()) { throw JsonValidatorError(error_prefix + "Must be an integer!"); } if (json.GetNumberType() == Urho3D::JSONNT_NAN || json.GetNumberType() == Urho3D::JSONNT_FLOAT_DOUBLE) { throw JsonValidatorError(error_prefix + "Must be an integer!"); } int result = json.GetInt(); if (result < min_limit) { throw JsonValidatorError(error_prefix + "Must be " + Urho3D::String(min_limit) + " or bigger!"); } if (result > max_limit) { throw JsonValidatorError(error_prefix + "Must be " + Urho3D::String(max_limit) + " or smaller!"); } return result; } float jsonToFloat( Urho3D::JSONValue const& json, Urho3D::String const& error_prefix, float min_limit, float max_limit ) { if (!json.IsNumber()) { throw JsonValidatorError(error_prefix + "Must be a float!"); } if (json.GetNumberType() == Urho3D::JSONNT_NAN) { throw JsonValidatorError(error_prefix + "Must be a float!"); } float result = json.GetFloat(); if (result < min_limit) { throw JsonValidatorError(error_prefix + "Must be " + Urho3D::String(min_limit) + " or bigger!"); } if (result > max_limit) { throw JsonValidatorError(error_prefix + "Must be " + Urho3D::String(max_limit) + " or smaller!"); } return result; } Urho3D::JSONValue getJsonObject( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { throw JsonValidatorError(error_prefix + "Not found!"); } if (!json.Get(key).IsObject()) { throw JsonValidatorError(error_prefix + "Not an object!"); } return json.Get(key); } Urho3D::JSONValue getJsonObjectIfExists( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, Urho3D::JSONValue const& default_value ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { return default_value; } return getJsonObject(json, key, error_prefix); } Urho3D::String getJsonString( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, Urho3D::Vector<Urho3D::String> const& allowed_values ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { throw JsonValidatorError(error_prefix + "Not found!"); } if (!json.Get(key).IsString()) { throw JsonValidatorError(error_prefix + "Must be a string!"); } Urho3D::String result = json.Get(key).GetString(); if (!allowed_values.Empty() && !allowed_values.Contains(result)) { Urho3D::String error = error_prefix + "Must be a one of the following values: "; bool first = true; for (auto value : allowed_values) { if (first) { first = false; } else { error += ", "; } error += "\"" + value + "\""; } throw JsonValidatorError(error); } return result; } Urho3D::String getJsonStringIfExists( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, Urho3D::String const& default_value, Urho3D::Vector<Urho3D::String> const& allowed_values ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { return default_value; } return getJsonString(json, key, error_prefix, allowed_values); } bool getJsonBoolean( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { throw JsonValidatorError(error_prefix + "Not found!"); } if (!json.Get(key).IsBool()) { throw JsonValidatorError(error_prefix + "Must be true or false!"); } return json.Get(key).GetBool(); } bool getJsonBooleanIfExists( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, bool default_value ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { return default_value; } return getJsonBoolean(json, key, error_prefix); } int getJsonInt( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, int min_limit, int max_limit ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { throw JsonValidatorError(error_prefix + "Not found!"); } return jsonToInt(json.Get(key), error_prefix, min_limit, max_limit); } int getJsonIntIfExists( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, int default_value, int min_limit, int max_limit ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { return default_value; } return jsonToInt(json.Get(key), error_prefix, min_limit, max_limit); } float getJsonFloat( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, float min_limit, float max_limit ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { throw JsonValidatorError(error_prefix + "Not found!"); } return jsonToFloat(json.Get(key), error_prefix, min_limit, max_limit); } float getJsonFloatIfExists( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, float default_value, float min_limit, float max_limit ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { return default_value; } return jsonToFloat(json.Get(key), error_prefix, min_limit, max_limit); } Urho3D::JSONArray getJsonArray( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, unsigned min_size_limit, unsigned max_size_limit ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { throw JsonValidatorError(error_prefix + "Not found!"); } if (!json.Get(key).IsArray()) { throw JsonValidatorError(error_prefix + "Must be an array!"); } Urho3D::JSONArray result = json.Get(key).GetArray(); if (min_size_limit == max_size_limit && result.Size() != min_size_limit) { throw JsonValidatorError(error_prefix + "Must have exactly " + Urho3D::String(min_size_limit) + " items!"); } if (result.Size() < min_size_limit) { throw JsonValidatorError(error_prefix + "Must have at least " + Urho3D::String(min_size_limit) + " items!"); } if (result.Size() > max_size_limit) { throw JsonValidatorError(error_prefix + "Must have a maximum of " + Urho3D::String(min_size_limit) + " items!"); } return result; } Urho3D::JSONArray getJsonArrayIfExists( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, unsigned min_size_limit, unsigned max_size_limit ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { return Urho3D::JSONArray(); } return getJsonArray(json, key, error_prefix, min_size_limit, max_size_limit); } Urho3D::Vector2 getJsonVector2( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, Urho3D::Vector2 const& min_limit, Urho3D::Vector2 const& max_limit ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { throw JsonValidatorError(error_prefix + "Not found!"); } if (!json.Get(key).IsArray()) { throw JsonValidatorError(error_prefix + "Must be an array!"); } Urho3D::JSONArray array = json.Get(key).GetArray(); if (array.Size() != 2) { throw JsonValidatorError(error_prefix + "Must have exactly two numbers!"); } if (!array[0].IsNumber() || !array[1].IsNumber()) { throw JsonValidatorError(error_prefix + "Must have exactly two numbers!"); } Urho3D::Vector2 result = Urho3D::Vector2(array[0].GetFloat(), array[1].GetFloat()); if (result.x_ < min_limit.x_) { throw JsonValidatorError(error_prefix + "Must have an X component " + Urho3D::String(min_limit.x_) + " or bigger!"); } if (result.x_ > max_limit.x_) { throw JsonValidatorError(error_prefix + "Must have an X component " + Urho3D::String(max_limit.x_) + " or smaller!"); } if (result.y_ < min_limit.y_) { throw JsonValidatorError(error_prefix + "Must have an Y component " + Urho3D::String(min_limit.y_) + " or bigger!"); } if (result.y_ > max_limit.y_) { throw JsonValidatorError(error_prefix + "Must have an Y component " + Urho3D::String(max_limit.y_) + " or smaller!"); } return result; } Urho3D::Vector3 getJsonVector3( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, Urho3D::Vector3 const& min_limit, Urho3D::Vector3 const& max_limit ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { throw JsonValidatorError(error_prefix + "Not found!"); } if (!json.Get(key).IsArray()) { throw JsonValidatorError(error_prefix + "Must be an array!"); } Urho3D::JSONArray array = json.Get(key).GetArray(); if (array.Size() != 3) { throw JsonValidatorError(error_prefix + "Must have exactly three numbers!"); } if (!array[0].IsNumber() || !array[1].IsNumber() || !array[2].IsNumber()) { throw JsonValidatorError(error_prefix + "Must have exactly three numbers!"); } Urho3D::Vector3 result = Urho3D::Vector3(array[0].GetFloat(), array[1].GetFloat(), array[2].GetFloat()); if (result.x_ < min_limit.x_) { throw JsonValidatorError(error_prefix + "Must have an X component " + Urho3D::String(min_limit.x_) + " or bigger!"); } if (result.x_ > max_limit.x_) { throw JsonValidatorError(error_prefix + "Must have an X component " + Urho3D::String(max_limit.x_) + " or smaller!"); } if (result.y_ < min_limit.y_) { throw JsonValidatorError(error_prefix + "Must have an Y component " + Urho3D::String(min_limit.y_) + " or bigger!"); } if (result.y_ > max_limit.y_) { throw JsonValidatorError(error_prefix + "Must have an Y component " + Urho3D::String(max_limit.y_) + " or smaller!"); } if (result.z_ < min_limit.z_) { throw JsonValidatorError(error_prefix + "Must have an Z component " + Urho3D::String(min_limit.z_) + " or bigger!"); } if (result.z_ > max_limit.z_) { throw JsonValidatorError(error_prefix + "Must have an Z component " + Urho3D::String(max_limit.z_) + " or smaller!"); } return result; } Urho3D::Vector4 getJsonVector4( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, Urho3D::Vector4 const& min_limit, Urho3D::Vector4 const& max_limit ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { throw JsonValidatorError(error_prefix + "Not found!"); } if (!json.Get(key).IsArray()) { throw JsonValidatorError(error_prefix + "Must be an array!"); } Urho3D::JSONArray array = json.Get(key).GetArray(); if (array.Size() != 4) { throw JsonValidatorError(error_prefix + "Must have exactly four numbers!"); } if (!array[0].IsNumber() || !array[1].IsNumber() || !array[2].IsNumber() || !array[3].IsNumber()) { throw JsonValidatorError(error_prefix + "Must have exactly three numbers!"); } Urho3D::Vector4 result = Urho3D::Vector4(array[0].GetFloat(), array[1].GetFloat(), array[2].GetFloat(), array[3].GetFloat()); if (result.x_ < min_limit.x_) { throw JsonValidatorError(error_prefix + "Must have an X component " + Urho3D::String(min_limit.x_) + " or bigger!"); } if (result.x_ > max_limit.x_) { throw JsonValidatorError(error_prefix + "Must have an X component " + Urho3D::String(max_limit.x_) + " or smaller!"); } if (result.y_ < min_limit.y_) { throw JsonValidatorError(error_prefix + "Must have an Y component " + Urho3D::String(min_limit.y_) + " or bigger!"); } if (result.y_ > max_limit.y_) { throw JsonValidatorError(error_prefix + "Must have an Y component " + Urho3D::String(max_limit.y_) + " or smaller!"); } if (result.z_ < min_limit.z_) { throw JsonValidatorError(error_prefix + "Must have an Z component " + Urho3D::String(min_limit.z_) + " or bigger!"); } if (result.z_ > max_limit.z_) { throw JsonValidatorError(error_prefix + "Must have an Z component " + Urho3D::String(max_limit.z_) + " or smaller!"); } if (result.w_ < min_limit.w_) { throw JsonValidatorError(error_prefix + "Must have an W component " + Urho3D::String(min_limit.w_) + " or bigger!"); } if (result.w_ > max_limit.w_) { throw JsonValidatorError(error_prefix + "Must have an W component " + Urho3D::String(max_limit.w_) + " or smaller!"); } return result; } Urho3D::Color getJsonColor( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { throw JsonValidatorError(error_prefix + "Not found!"); } if (json.Get(key).IsArray()) { Urho3D::JSONArray array = json.Get(key).GetArray(); if (array.Size() < 3 || array.Size() > 4) { throw JsonValidatorError(error_prefix + "Must have three or four numbers between one and zero!"); } if (!array[0].IsNumber() || !array[1].IsNumber() || !array[2].IsNumber()) { throw JsonValidatorError(error_prefix + "Must have three or four numbers between one and zero!"); } float r = array[0].GetFloat(); float g = array[1].GetFloat(); float b = array[2].GetFloat(); float a = array.Size() == 4 ? array[3].GetFloat() : 1.0f; if (r < 0 || r > 1 || g < 0 || g > 1 || b < 0 || b > 1 || a < 0 || a > 1) { throw JsonValidatorError(error_prefix + "Must have three or four numbers between one and zero!"); } return Urho3D::Color(r, g, b, a); } if (json.Get(key).IsString()) { Urho3D::String color_str = json.Get(key).GetString(); if (color_str.Length() != 7 && color_str.Length() != 9) { throw JsonValidatorError(error_prefix + "Must be #rrggbb or #rrggbbaa!"); } if (color_str[0] != '#') { throw JsonValidatorError(error_prefix + "Must be #rrggbb or #rrggbbaa!"); } Urho3D::String hex_chars = "0123456789abcdefABCDEF"; for (unsigned i = 1; i < color_str.Length(); ++ i) { if (hex_chars.Find(color_str[i]) == Urho3D::String::NPOS) { throw JsonValidatorError(error_prefix + "Must be #rrggbb or #rrggbbaa!"); } } Urho3D::Color color; for (unsigned i = 1; i < color_str.Length(); i += 2) { Urho3D::String hex = color_str.Substring(i, 2); float value = ::strtol(hex.CString(), nullptr, 16) / 255.0f; if (i == 1) { color.r_ = value; } else if (i == 3) { color.g_ = value; } else if (i == 5) { color.b_ = value; } else { color.a_ = value; } } return color; } throw JsonValidatorError(error_prefix + "Must be an array or string!"); } Urho3D::Color getJsonColorIfExists( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, Urho3D::Color const& default_value ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { return default_value; } return getJsonColor(json, key, error_prefix); } Urho3D::PODVector<int> getJsonIntArray( Urho3D::JSONValue const& json, Urho3D::String const& error_prefix, unsigned min_size_limit, unsigned max_size_limit ) { if (!json.IsArray()) { throw JsonValidatorError(error_prefix + "Must be an array!"); } Urho3D::JSONArray arr = json.GetArray(); if (arr.Size() < min_size_limit) { throw JsonValidatorError(error_prefix + "Must have at least " + Urho3D::String(min_size_limit) + " items!"); } if (arr.Size() > max_size_limit) { throw JsonValidatorError(error_prefix + "Must have a maximum of " + Urho3D::String(min_size_limit) + " items!"); } Urho3D::PODVector<int> result; for (auto item : arr) { result.Push(jsonToInt(item)); } return result; } Urho3D::PODVector<int> getJsonIntArray( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, unsigned min_size_limit, unsigned max_size_limit ) { Urho3D::JSONArray arr = getJsonArray(json, key, error_prefix, min_size_limit, max_size_limit); Urho3D::PODVector<int> result; for (auto item : arr) { result.Push(jsonToInt(item)); } return result; } Urho3D::PODVector<int> getJsonIntArrayIfExists( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, unsigned min_size_limit, unsigned max_size_limit, Urho3D::PODVector<int> const& default_value ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { return default_value; } return getJsonIntArray(json, key, error_prefix, min_size_limit, max_size_limit); } Urho3D::PODVector<float> getJsonFloatArray( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, unsigned min_size_limit, unsigned max_size_limit ) { Urho3D::JSONArray arr = getJsonArray(json, key, error_prefix, min_size_limit, max_size_limit); Urho3D::PODVector<float> result; for (auto item : arr) { result.Push(jsonToFloat(item)); } return result; } Urho3D::PODVector<float> getJsonFloatArrayIfExists( Urho3D::JSONValue const& json, Urho3D::String const& key, Urho3D::String const& error_prefix, unsigned min_size_limit, unsigned max_size_limit, Urho3D::PODVector<float> const& default_value ) { if (!json.IsObject()) { throw JsonValidatorError(error_prefix + "Unable to get a member from non-object!"); } if (!json.Contains(key)) { return default_value; } return getJsonFloatArray(json, key, error_prefix, min_size_limit, max_size_limit); } }
true
7d156ae41bd4fd3f2050da622b4eadbe428539cc
C++
feng1st/md5checker
/Md5Checker/MD5Calculator.h
UTF-8
358
2.59375
3
[]
no_license
#pragma once class CMD5Calculator { public: void Init(); void Update(const LPBYTE input, UINT inputLen); LPBYTE Finalize(BYTE digest[16]); private: void Transform(const BYTE[64]); private: ULONG m_state[4]; // state (ABCD) ULONG m_count[2]; // number of bits, modulo 2^64 (lsb first) BYTE m_buffer[64]; // input buffer };
true
cffcbc32762c5016da641ae5e5d4f51b899d6492
C++
Maximilian762/simplescript
/SS_shared/SS_shared/AST_FunctionCalling.cpp
UTF-8
2,209
2.75
3
[]
no_license
#include "stdafx.h" #include "AST_FunctionCalling.h" #include "Table.h" using namespace std; AST_FunctionCalling::AST_FunctionCalling(std::string _callername, std::string _name, std::vector<SharedExpr>& _arguments) { SetType(AST_Type::FunctionCalling); callername = _callername; name = _name; arguments = _arguments; } AST_FunctionCalling::~AST_FunctionCalling() { } std::string AST_FunctionCalling::GetName() { return name; } std::vector<SharedExpr>& AST_FunctionCalling::GetArgs() { return arguments; } void AST_FunctionCalling::PrintSelf(int level) { PrintAlignment(level); cout << "call: " << callername << "->" << name << endl; PrintAlignment(level + 1); if (arguments.empty()) cout << "noargs" << endl; else { cout << "args:" << endl; for (auto &expr : arguments) { if (expr) expr->PrintSelf(level + 2); else { PrintAlignment(level + 2); cout << "<emptyarg>" << endl; } } } } bool AST_FunctionCalling::Evaluate(Table & obj, VarPtr &return_var, IMsgHandler &errhandler) { Table *caller = &obj; if (callername != "this") { bool exists = obj.GetVarContainer().GetVarPtr(callername).operator bool(); if (exists) { if (auto callerptr = obj.GetVarContainer().GetVarPtr(callername)->GetTablePtr()) { caller = callerptr.get(); } else { errhandler.OnMsg("Couldnt retrieve tableptr from caller"); return false; } } else { errhandler.OnMsg("Couldnt retrieve function caller: " + callername); return false; } } if (auto method = caller->GetMethodContainer().GetMethod(name)) { VarPtr res = method->Call(*caller, EvaluateArguments(obj, errhandler), errhandler); return_var = res; return true; } else { errhandler.OnMsg("Couldnt retrieve method " + name + " from " + callername); return false; } } std::vector<VarPtr> AST_FunctionCalling::EvaluateArguments(Table & obj, IMsgHandler &errhandler) { std::vector<VarPtr> evaluatedargs; for (auto &expr : arguments) { VarPtr ret; bool success = expr->Evaluate(obj, ret, errhandler); evaluatedargs.push_back(ret); } return evaluatedargs; }
true
e65fd0148100ce5ea8fc292eeef296f213ad5f15
C++
tungndtt/Praktikum_C
/exercise_3/task2/row.cpp
UTF-8
453
2.875
3
[]
no_license
#include "row.hpp" const std::string& Row::get(std::string& key) const { return this->fields.at(key); } void Row::insert(const std::string& key, const std::string& value) { this->fields.insert({key, value}); } std::unordered_map<std::string, std::string>::const_iterator Row::begin() const { return this->fields.cbegin(); } std::unordered_map<std::string, std::string>::const_iterator Row::end() const { return this->fields.cend(); }
true
5affe6a860d4a21acaffe4dfd5801ddac2908721
C++
truongpt/warm_up
/practice/cpp/hash_table/roman_to_integer.cpp
UTF-8
1,018
3.625
4
[]
no_license
/* - Problem: https://leetcode.com/problems/roman-to-integer - Solution: - Directly apply rule to convert from roman to integer. - Pre character value is decided after know current character in roman string. - Time and space complexity. - TC: O(n) - SC: O(n) */ #include <iostream> #include <unordered_map> using namespace std; int romanToInt(string s) { if (s.empty()) { return 0; } int res = 0; unordered_map<char, int> m = {{'I',1}, {'V',5}, {'X',10},{'L',50},{'C',100}, {'D',500}, {'M',1000}}; char pre = 'x'; for (int i = 0; i < s.length(); i++) { if (pre == 'x') { pre = s[i]; } else if (m[s[i]] <= m[pre]) { res += m[pre]; pre = s[i]; } else { res += (m[s[i]] - m[pre]); pre = 'x'; } } if (pre != 'x') { res += m[pre]; } return res; } int main(void) { cout << romanToInt("MCMXCIV") << endl; }
true
ee1ead1f001cce14b7339d97adee611497896e3c
C++
aiwithqasim/Competitive-Programming
/Data Structure & Algorithm C++/12 trees/Q1.cpp
UTF-8
990
3.8125
4
[]
no_license
#include<iostream> using namespace std; struct Node { char data; Node *left,*right; }; Node *Insert(Node *root,char data) { if(root==NULL){ root=new Node(); root->data=data; root->left=root->right=NULL; } else if(data<=root->data){ root->left=Insert(root->left,data); } else{ root->right=Insert(root->right,data); } return root; } void searchData(Node *root,char n) { if(n==root->data){ cout<<"Element found!"<<endl; } else if(n<root->data){ searchData(root->left,n); } else { searchData(root->right,n); } } int main() { Node *root=NULL; root=Insert(root,'Q'); root=Insert(root,'A'); root=Insert(root,'S'); root=Insert(root,'I'); root=Insert(root,'M'); root=Insert(root,'H'); root=Insert(root,'A'); root=Insert(root,'S'); root=Insert(root,'S'); root=Insert(root,'A'); root=Insert(root,'N'); char letter; cout<<"Enter character to search: "; cin>>letter; searchData(root,letter); }
true
ec96a94d7924b96c6a5a122c944ea972ab997490
C++
pjszzang2/ImageProcessing
/ImageProcessing/filter/sharpening.cpp
UTF-8
542
2.59375
3
[]
no_license
#include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace cv; using namespace std; void sharpening(Mat img) { Mat result; Mat kernel(3, 3, CV_32F, cv::Scalar(0)); kernel.at<float>(1, 1) = 5.0; kernel.at<float>(0, 1) = -1.0; kernel.at<float>(2, 1) = -1.0; kernel.at<float>(1, 0) = -1.0; kernel.at<float>(1, 2) = -1.0; filter2D(img, result, img.depth(), kernel); imshow("Sharpening", result); }
true
b4fe70cad7e4e7236a9739a568d162fdd175a6fe
C++
ashutosh-ve/Placement
/day2/q2.cpp
UTF-8
343
2.609375
3
[]
no_license
class Solution { public: int numIdenticalPairs(vector<int>& nums) { int n=nums.size(); int ans=0; for(int i=0;i<n-1;i++){ for(int j=i;j<n;j++){ if(nums[i]==nums[j] && i<j) ans+=1; } } return ans; } };
true
a258506786c5de749bbf8be427357bf4dc429fe7
C++
ganipa93/Figuras
/Figuras/Triangulo.h
WINDOWS-1250
2,809
3.390625
3
[]
no_license
#ifndef TRIANGULO_H_DECLARED #define TRIANGULO_H_INCLUDED #include <string> #include <string.h> /** Definicin del Tipo de Dato para manejo de triangulos. Atributos: * base, * altura, * color, * area. Axiomas: * base > 0 * altura >0 * area = (base*altura)/2 */ // Definicin del Tipo. typedef struct { char nombre[50]; char color[50]; float altura; float base; //enum dinamico de 1 a 10 } Triangulo; /** PRE: La instancia del TDA (trangulo) no debe haberse creado ni destruido con anterioridad. POST: Deja la instancia del TDA (triangulo) listo para ser usado. */ void constructor (Triangulo &triangulo); /** PRE: La instancia del TDA (triangulo) debe haberse creado pero no debe estar destruida. POST: Destruye la instancia del TDA y ya no podr ser utilizada. */ void destructor(Triangulo &triangulo); /** PRE: La instancia del TDA (triangulo) debe haberse creado pero no debe estar destruida. POST: Devuelve el nombre del triangulo. */ char* getNombre(Triangulo &triangulo); /** PRE: La instancia del TDA (triangulo) debe haberse creado pero no debe estar destruida. POST: Se modifica el triangulo con el nuevo nombre . */ void setNombre(Triangulo &triangulo, char nombre[]); /** PRE: La instancia del TDA (triangulo) debe haberse creado pero no debe estar destruida. POST: Devuelve el color del triangulo. */ char* getColor(Triangulo &triangulo); /** PRE: La instancia del TDA (triangulo) debe haberse creado pero no debe estar destruida. POST: Se modifica el triangulo con el nuevo color. */ void setColor(Triangulo &triangulo, char color[]); /** PRE: La instancia del TDA (triangulo) debe haberse creado pero no debe estar destruida. La base debe ser mayor a 0. POST: Se modifica el triangulo con la nueva base. */ void setBase(Triangulo &triangulo,float base); /** PRE: La instancia del TDA (triangulo) debe haberse creado pero no debe estar destruida. POST: Devuelve la base del triangulo. */ float getBase (Triangulo &triangulo); /** PRE: La instancia del TDA (triangulo) debe haberse creado pero no debe estar destruida. POST: Se modifica el triangulo con la nueva altura. */ void setAltura(Triangulo &triangulo, float altura); /** PRE: La instancia del TDA (triangulo) debe haberse creado pero no debe estar destruida- La altura debe ser mayor a 0. POST: Devuelve la altura del triangulo. */ float getAltura(Triangulo &triangulo); /** PRE: La instancia del TDA (triangulo) debe haberse creado pero no debe estar destruida. POST: Devuelve el area del triangulo ((base * altura)/2). */ float getArea(Triangulo &triangulo); #endif
true
fd6e0ddf37adcb3479134e0acd24716398a93b2b
C++
zilongwhu/ls-client
/include/server.h
UTF-8
1,951
2.515625
3
[]
no_license
/* * ===================================================================================== * * Filename: server.h * * Description: * * Version: 1.0 * Created: 04/11/2014 04:13:14 PM * Revision: none * Compiler: gcc * * Author: Zilong.Zhu (), zilong.whu@gmail.com * Company: edu.whu * * ===================================================================================== */ #ifndef __LS_CLIENT_SERVER_H__ #define __LS_CLIENT_SERVER_H__ #include <deque> #include <string> #include <strings.h> #include <sys/socket.h> #include "lock.h" struct server_args { int port; int pool_size; int connect_timeout; std::string addr; }; class Server { private: Server(const Server &o); Server &operator =(const Server &o); public: Server() { ::bzero(&_addr, sizeof _addr); _addrlen = 0; _connect_timeout = -1; ::bzero(_stats, sizeof _stats); _stats_off = 0; _fail_count = 0; _pool_size = 0; _healthy = true; } ~Server(); void set_pool_size(int sz) { _pool_size = sz; } void set_connect_timeout(int ms) { _connect_timeout = ms; } int set_addr(const char *ptr, int port); bool is_healthy() const { return _healthy; } int fail_ratio() const { return _fail_count * 100 / (sizeof(_stats)/sizeof(_stats[0])); } int connect(); int get_avail_sock(); void return_sock(int sock, bool is_ok); protected: Mutex _mutex; std::deque<int> _socks; int _pool_size; struct sockaddr_storage _addr; socklen_t _addrlen; std::string _addrstr; int _connect_timeout; volatile bool _healthy; int _stats_off; volatile int _fail_count; int8_t _stats[2048]; }; #endif
true
d2fae47034be6fcfad926d2dc4ecc14ef8983723
C++
Diusrex/UVA-Solutions
/637 Booklet Printing.cpp
UTF-8
1,303
3.140625
3
[ "Apache-2.0" ]
permissive
#include <cstdio> int main() { int P; while (scanf("%d", &P), P) { printf("Printing order for %d pages:\n", P); // Only one that does not have a back for each page if (P == 1) { printf("Sheet 1, front: Blank, 1\n"); } else { int numPages = P / 4; if (numPages * 4 < P) ++numPages; int numberSkipped = numPages * 4 - P; for (int i = 0; i < numPages; ++i) { int frontFirstPage = P - i * 2 + numberSkipped; int frontSecondPage = i * 2 + 1; if (frontFirstPage <= P) printf("Sheet %d, front: %d, %d\nSheet %d, back : %d, %d\n", i + 1, frontFirstPage, frontSecondPage, i + 1, frontSecondPage + 1, frontFirstPage - 1); else if (frontFirstPage - 1 <= P) printf("Sheet %d, front: Blank, %d\nSheet %d, back : %d, %d\n", i + 1, frontSecondPage, i + 1, frontSecondPage + 1, frontFirstPage - 1); else printf("Sheet %d, front: Blank, %d\nSheet %d, back : %d, Blank\n", i + 1, frontSecondPage, i + 1, frontSecondPage + 1); } } } }
true
7b6c8924aa41f21f6117ee601702023c463fa10f
C++
kronicler/cs2040_DSnA
/KattisPractices/arjo/tree.cpp
UTF-8
378
2.796875
3
[]
no_license
#include <iostream> #include <string> #include <cmath> using namespace std; int main(int argc, char** argv) { string directions = ""; int n; cin >> n; if(!cin.eof()) cin >> directions; long res = (long)pow(2,n+1); long diff = 1; for(int i = 0; i < directions.size() ; i++){ diff*=2; if(directions[i] == 'R') diff++; } cout << res-diff <<endl; return 0; }
true
4991712ee9be3f36e2d5cd9d2ecf5eb2feb0a6db
C++
scjurgen/lab64
/RandomGenerator.h
UTF-8
458
2.625
3
[]
no_license
#pragma once #include <memory> #include <random> class RandomGenerator { public: RandomGenerator(); void seed(int sd); double GetNormalizedUniformRange(); double GetUniformRange(double minValue, double maxValue); private: // std::mt19937 m_generator; std::default_random_engine m_generator; std::uniform_real_distribution<> m_uniformRealDistribution; std::normal_distribution<> m_normalDistribution; };
true
26cb5c1d1a4b750eeaf42dce1a259c1d32c4cbad
C++
mave89/CPlusPlus_Random
/LeetCode/hammingDistance.cpp
UTF-8
1,406
3.5625
4
[]
no_license
// https://leetcode.com/problems/hamming-distance/#/description class Solution { private: std::string convert2binary(int x){ std::string binary; while(x > 0){ binary += std::to_string(x % 2); x = x / 2; } // Reverse it std::reverse(binary.begin(), binary.end()); return binary; } public: int hammingDistance(int x, int y){ int ans = 0; std::string x_binary = convert2binary(x); std::string y_binary = convert2binary(y); // Add zeros if needed if(x_binary.size() > y_binary.size()){ std::string y_binary_new; int size_diff = x_binary.size() - y_binary.size(); for(int i = 0; i < size_diff; i++) y_binary_new += '0'; y_binary_new += y_binary; y_binary = y_binary_new; } else if(y_binary.size() > x_binary.size()){ std::string x_binary_new; int size_diff = y_binary.size() - x_binary.size(); for(int i = 0; i < size_diff; i++) x_binary_new += '0'; x_binary_new += x_binary; x_binary = x_binary_new; } // Compare the two for(int i = 0; i < x_binary.size(); i++){ if(x_binary[i] != y_binary[i]) ans++; } return ans; } };
true
290b374a61a69fde521b3a152433be80b570a296
C++
stefanandonov/OOP2020
/exercises/shapes5.cc
UTF-8
5,034
3.546875
4
[]
no_license
#include<iostream> #include<cstring> using namespace std; enum Color { RED, GREEN, BLUE }; class Shape { protected: char id [5]; char * description; Color color; void copy (const Shape &s) { strcpy(this->id, s.id); this->description = new char [strlen(s.description)+1]; strcpy(this->description, s.description); this->color = s.color; } public: Shape (const char * id = "NOID", char * description = "nodescription", Color color = RED) { strcpy(this->id, id); this->description = new char [strlen(description)+1]; strcpy(this->description, description); //this->area = area; this->color = color; } Shape (const Shape &s) { copy(s); } Shape & operator = (const Shape &s) { if (this!=&s) { delete [] description; copy(s); } return *this; } ~Shape () { delete [] description; } char * getColor () { switch(color) { case RED: return "RED"; case GREEN: return "GREEN"; case BLUE: return "BLUE"; default: return ""; } } virtual void draw() { cout<<id<<" "<<getColor()<<" "<<description<<" type: "; } virtual double area() = 0; virtual double perimeter() = 0; }; bool operator > (Shape & left, Shape & right) { return left.perimeter() > right.perimeter(); } class Circle : public Shape{ private: double radius; void copy (const Circle & c) { Shape::copy(c); this->radius = radius; } public: Circle (const char * id = "NOID", char * description = "nodescription", Color color = RED, double radius = 1.0) : Shape (id, description, color) { this->radius = radius; } Circle (const Circle & c) { copy(c); } Circle & operator = (const Circle &c){ if (this!=&c) { delete [] description; copy(c); } } void draw () { Shape::draw(); cout<<"circle "<<perimeter()<<" "<<area()<<endl; } double perimeter () { return 2*radius*3.14; } double area () { return radius* radius*3.14; } }; class Square : public Shape { private: double a; void copy (const Square & s) { Shape::copy(s); this->a=a; } public: Square (const char * id = "NOID", char * description = "nodescription", Color color = RED, double a = 1.0) : Shape (id, description, color) { this->a = a; } Square (const Square & s) : Shape(s) { copy(s); } Square & operator = (const Square & s) { if (this!=&s) { delete [] description; copy(s); } } ~Square() { delete [] description; } void draw () { Shape::draw(); cout<<"square "<<perimeter()<<" "<<area()<<endl; } double perimeter () { return 4*a; } double area () { return a*a; } }; class Rectangle : public Shape { private: double a; double b; void copy (const Rectangle & s) { Shape::copy(s); this->a=a; this->b=b; } public: Rectangle (const char * id = "NOID", char * description = "nodescription", Color color = RED, double a = 1.0, double b = 1.0) : Shape (id, description, color) { this->a = a; this->b=b; } Rectangle (const Rectangle & s) : Shape(s) { copy(s); } Rectangle & operator = (const Rectangle & s) { if (this!=&s) { delete [] description; copy(s); } } ~Rectangle() { delete [] description; } void draw () { Shape::draw(); cout<<"rectangle "<<perimeter()<<" "<<area()<<endl; } double perimeter () { return 4*a; } double area () { return a*a; } }; double totalArea (Shape ** shapes, int n) { double sum = 0.0; for (int i=0;i<n;i++) sum+=shapes[i]->area(); return sum; } Shape * maxPerimeter(Shape ** shapes, int n) { Shape * max = shapes[0]; for (int i=0;i<n;i++) if (*shapes[i]>*max) max=shapes[i]; return max; } void drawAllFromType(Shape ** shapes, int n, char * type) { for (int i=0;i<n;i++) { if (strcmp(type,"circle")==0) { Circle * c = dynamic_cast<Circle *>(shapes[i]); if (c!=0) c->draw(); } if (strcmp(type,"square")==0) { Square * c = dynamic_cast<Square *>(shapes[i]); if (c!=0) c->draw(); } if (strcmp(type,"rectangle")==0) { Rectangle * c = dynamic_cast<Rectangle *>(shapes[i]); if (c!=0) c->draw(); } } } int main () { int n; cin>>n; Shape ** shapes = new Shape * [n]; int type; char id [5]; char * description; int color; double radius, a, b; for (int i=0;i<n;i++) { cin>>type>>id>>description>>color; switch(type) { case 0: //circle cin>>radius; shapes[i] = new Circle (id, description, (Color) color, radius); break; case 1: //square cin>>a; shapes[i] = new Square (id, description, (Color) color, a); break; case 2: //rectangle cin>>a>>b; shapes[i] = new Rectangle (id, description, (Color) color, a, b); break; default: break; } } cout<<"Total area: "<<totalArea(shapes,n)<<endl; cout<<"Max perimeter of a shape is: "<<(maxPerimeter(shapes,n))->perimeter()<<endl; cout<<"Draw only circles"<<endl; drawAllFromType(shapes,n,"circle"); cout<<"Draw only squares"<<endl; drawAllFromType(shapes,n,"square"); cout<<"Draw only rectangle"<<endl; drawAllFromType(shapes,n,"rectangle"); return 0; }
true
d762aa4af36bb4e8ab0eacba88c2b2e2c08062b6
C++
artofimagination/simple-ftp-client-server
/UI/CommandLineImpl.h
UTF-8
662
2.671875
3
[ "MIT" ]
permissive
#ifndef COMMAND_LINE_IMPL_H #define COMMAND_LINE_IMPL_H #include <Common/Error.h> #include <map> namespace UI { class CommandLineImpl { public: CommandLineImpl(); //! Prints available options in command line. void listOptions(const std::map<int, std::string>& options) const; //! Prints the welcome message in command line. void printWelcome() const; //! Prints the error in comand line. void printError(const Common::Error& error) const; //! Prints the message in comand line. void printMessage(const std::string& message) const; //! Waits for user input. std::string listenToInput(); }; } // UI #endif // COMMAND_LINE_IMPL_H
true
337be97c491a43981d16741e4cc6c600c740b254
C++
FeridAdashov/C-and-CPP
/proqram-2015/ders.son.ededin tersi.cpp
UTF-8
162
2.8125
3
[]
no_license
#include<iostream> using namespace std; int main(){ int x,y=0; cout<<"Eded daxil et:"; cin>>x; while(x>0){ y=y*10+x%10; x/=10; } cout<<y; return 0; }
true
828105f833940a375744f3b72f1786bb98fdabe6
C++
moevm/oop
/8381/Pereverzev_Dmitriy/back/gameCPP/src/uuid/UUID.cpp
UTF-8
989
3.03125
3
[]
no_license
#include "UUID.hpp" UUID::UUID() { time_t timeSeed = time(nullptr); std::srand(timeSeed); x = std::rand() % 899999999 + 100000000; y = std::rand() % 899999999 + 100000000; z = std::rand() % 899999999 + 100000000; w = std::rand() % 899999999 + 100000000; } uint32_t UUID::xor128(void) { t = x ^ (x << 11); x = y; y = z; z = w; return w = w ^ (w >> 19) ^ (t ^ (t >> 8)); } std::string UUID::generateUUID() { std::string uuid = std::string(36, ' '); int rnd = 0; uuid[8] = '-'; uuid[13] = '-'; uuid[18] = '-'; uuid[23] = '-'; uuid[14] = '4'; for (int i = 0; i < 36; i++) { if (i != 8 && i != 13 && i != 18 && i != 14 && i != 23) { if (rnd <= 0x02) { rnd = 0x2000000 + (xor128() * 0x1000000) | 0; } rnd >>= 4; uuid[i] = CHARS[(i == 19) ? ((rnd & 0xf) & 0x3) | 0x8 : rnd & 0xf]; } } return uuid; }
true
8f38fb8f50e79ae47c8106628ccb38ccf28fab91
C++
seijihariki/brizas
/OGL/src/graphics/model/model.cpp
UTF-8
3,731
3.265625
3
[]
no_license
#include "graphics/model/model.hpp" #include <string.h> Model::Model(std::string filename) { loadFromFile(filename); loaded = false; } Model::~Model() { if (loaded) unloadFromGPU(); } void Model::loadFromFile(std::string filename) { vertices.clear(); texture_c.clear(); normals.clear(); std::vector<glm::vec3> tmpvertices; std::vector<glm::vec2> tmptexture_c; std::vector<glm::vec3> tmpnormals; printf("Loading model %s...\n", filename.c_str()); std::ifstream file; file.open(filename); if (file.fail()) { printf("Could not open %s\n", filename.c_str()); return; } std::string line; while (std::getline(file, line)) { std::istringstream line_stream(line); std::string header; line_stream >> header; if (!header.compare("v")) { glm::vec3 vertex; line_stream >> vertex.x >> vertex.y >> vertex.z; tmpvertices.push_back(vertex); } else if (!header.compare("vt")) { glm::vec2 vertex; line_stream >> vertex.x >> vertex.y; tmptexture_c.push_back(vertex); } else if (!header.compare("vn")) { glm::vec3 vertex; line_stream >> vertex.x >> vertex.y >> vertex.z; tmpnormals.push_back(vertex); } else if (!header.compare("f")) { int v1, t1, n1, v2, t2, n2, v3, t3, n3; char sep; line_stream >> v1 >> sep >> t1 >> sep >> n1 >> v2 >> sep >> t2 >> sep >> n2 >> v3 >> sep >> t3 >> sep >> n3; this->vertices.push_back(tmpvertices[v1 - 1]); this->vertices.push_back(tmpvertices[v2 - 1]); this->vertices.push_back(tmpvertices[v3 - 1]); this->texture_c.push_back(tmptexture_c[t1 - 1]); this->texture_c.push_back(tmptexture_c[t2 - 1]); this->texture_c.push_back(tmptexture_c[t3 - 1]); this->normals.push_back(tmpnormals[n1 - 1]); this->normals.push_back(tmpnormals[n2 - 1]); this->normals.push_back(tmpnormals[n3 - 1]); } else if (!header.compare("o")) { line_stream >> name; } else if (!header.compare("#")) { std::cout << line << '\n'; } else { std::cout << "Unknown line format: " << line << '\n'; } } file.close(); vertices_vd = new VertexData<glm::vec3>(vertices, 3); texture_vd = new VertexData<glm::vec2>(texture_c, 2); normals_vd = new VertexData<glm::vec3>(normals, 3); printf("Model %s was loaded with %lu triangles!\n", filename.c_str(), vertices.size()/3); } void Model::loadToGPU() { if (loaded) return; printf("Loading model %s to GPU...\n", name.c_str()); vertices_vd->loadToGPU(); texture_vd->loadToGPU(); normals_vd->loadToGPU(); loaded = true; printf("Model %s loaded to GPU!\n", name.c_str()); } void Model::unloadFromGPU() { if (!loaded) return; vertices_vd->unloadFromGPU(); texture_vd->unloadFromGPU(); normals_vd->unloadFromGPU(); loaded = false; } bool Model::isLoaded() { return loaded; } void Model::activate(GLuint vertex, GLuint texture, GLuint normal) { vertices_vd->activate(vertex); texture_vd->activate(texture); normals_vd->activate(normal); } void Model::deactivate() { vertices_vd->deactivate(); texture_vd->deactivate(); normals_vd->deactivate(); } std::string Model::getName() { return name; } GLuint Model::vertexCnt() { return vertices.size(); }
true
07e9e9bc08528c5b1f037cf1cad2b35082cf1d0b
C++
Glowny/Dalmuti
/Dalmuti/AlluAI.cpp
UTF-8
1,424
2.828125
3
[]
no_license
#include "AlluAI.h" AlluAI::AlluAI(std::vector<Card*> hand, std::string playerName) : Player(hand, playerName) { } AlluAI::~AlluAI() { } Card* AlluAI::AI(std::vector<Card*>* poytakortit, int ylinkortti, int ylimmankortinmaara) { std::vector<Card*> playbleCards; Card toPlay = Card(NOCARD); if (ylinkortti == NOCARD) { for (unsigned i = 0; i < hand.size(); i++) { if (hand.at(i)->GetCardValue() != 0) playbleCards.push_back(hand.at(i)); } } else { for (unsigned i = 0; i < hand.size(); i++) { if (hand.at(i)->GetCardValue() < ylinkortti) { if (hand.at(i)->GetCardValue() != 0) { if (hand.at(i)->GetCardAmount() >= ylimmankortinmaara) { playbleCards.push_back(hand.at(i)); } } } } } if (playbleCards.size() > 0) { toPlay = *playbleCards.at(0); for (unsigned i = 1; i < playbleCards.size(); i++) { if (playbleCards.at(i)->GetCardValue() > toPlay.GetCardValue()) { toPlay = *playbleCards.at(i); } } } if (toPlay.GetCardValue() != NOCARD) { for (unsigned i = 0; i < hand.size(); i++) { if (hand.at(i)->GetCardValue() == JOKER) { toPlay.SetCardAmount(toPlay.GetCardAmount() + hand.at(i)->GetCardAmount()); break; } } //std::cout << playerName << " plays: " << toPlay.GetCardAmount() << "x" << toPlay.GetCardValue() << std::endl; } return new Card(toPlay.GetCardValue(), toPlay.GetCardAmount()); }
true
64e0ad98bf88ee8249d637e57540c38763ce4f22
C++
PeopleCF/Boudjelida_Amin
/Sample-Test2/FileReaderTest.cpp
WINDOWS-1251
769
2.59375
3
[]
no_license
#include "pch.h" #include "C:/out/FileReader.cpp" #include <iostream> class FileReadTest : public ::testing::Test { protected: void SetUp() { FR = new FileReader(); } void TearDown() { delete FR; } FileReader *FR; }; TEST_F(FileReadTest, readFile_FileUnavailable_CannotReadFile) { EXPECT_EQ("Cannot Read file", FR->readFile("C:/Users//source/repos/ConsoleApplication2/Sample-Test1/NotExisting.txt")); } TEST_F(FileReadTest, readFile_UsualCase_Path) { std::ifstream file; std::string s; file.open("C:/Users//source/repos/ConsoleApplication2/Sample-Test1/FileReadExample.txt"); getline(file, s); file.close(); EXPECT_EQ(s, FR->readFile("C:/Users//source/repos/ConsoleApplication2/Sample-Test1/FileReadExample.txt")); }
true
f438283a708e99946962905d61372b39eef43b95
C++
ForNeVeR/cthulhu-bot
/history-import/import.cpp
UTF-8
2,529
2.59375
3
[ "MIT" ]
permissive
#include "import.h" #include "history.h" #include "unicode.h" #include <boost/filesystem.hpp> #include <boost/regex.hpp> #include <cstdlib> #include <ctime> #include <fstream> #include <iostream> #include <sstream> using namespace boost; using namespace boost::filesystem; using namespace boost::gregorian; using namespace boost::posix_time; using namespace std; void miranda_import(const string &from, const string &to, const std::string &conf_name, int minutes_delta) { static const wregex expr(L"^\\[([0-9]{2}):([0-9]{2}):([0-9]{2})\\] \\* (.*?) \\* (.*)\\r$"); path from_path(from); directory_iterator end_itr; // default construction yields past-the-end for(directory_iterator itr(from_path); itr != end_itr; ++itr) { cout << "Converting file " << itr->path().filename() << "..." << endl; std::wifstream input_file(itr->path().string().c_str(), ios_base::in | ios::binary); // ignore UTF-16 BOM input_file.ignore(2); while(!input_file.eof()) { wstring line; wchar_t c = L'\0'; while(c != L'\r' && !input_file.eof()) { wchar_t c1 = L'\0', c2 = L'\0'; input_file.get(c1); input_file.get(c2); c = c2 << 8 | c1; line += c; } input_file.ignore(2); // ignoring following L'\n' character // check regex matches wsmatch match; if(regex_match(line, match, expr)) { int year = atoi(itr->filename().substr(0, 4).c_str()); int month = atoi(itr->filename().substr(5, 2).c_str()); int day = atoi(itr->filename().substr(8, 2).c_str()); date d(year, month, day); // TODO: Some other than utf8() here, wcsto...() maybe? int hour = atoi(utf8(match[1].str().c_str()).c_str()); int min = atoi(utf8(match[2].str().c_str()).c_str()); int sec = atoi(utf8(match[3].str().c_str()).c_str()); ptime datetime(d, time_duration(hour, min, sec, 0) + minutes(minutes_delta)); string nick = utf8(match[4].str().c_str()); string message = utf8(match[5].str().c_str()); history_add(datetime, conf_name, nick, message, to, true); } } input_file.close(); } }
true
7a83a72cb908b53a72d20fb92461e7aa171c121b
C++
satyaaditya/My_C
/Add all greater values to every node in a BST.cpp
UTF-8
1,072
3.203125
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<conio.h> #include"bst.h" int get_inorder_sum(struct node* ); void fill_inorder(struct node *, int *, int *, int *); int get_inorder_sum(struct node *root){ if (root == NULL) return 0; else{ int sum = get_inorder_sum(root->left); sum += get_inorder_sum(root->right); sum += root->data; return sum; } } void fill_inorder(struct node *root, int *arr, int *index, int *sum){ if (root){ fill_inorder(root->left, arr, index, sum); root->data = *sum; *sum = *sum - arr[*index]; *index += 1; fill_inorder(root->right, arr, index, sum); } } int main(){ struct node *root = NULL; int n; printf(" enter size of bst ::: "); scanf("%d", &n); int *arr = (int*)calloc(n, sizeof(int)); printf("enter elements into bst\n"); for (int i = 0; i < n; i++) scanf("%d", &arr[i]); root = create_bst(arr,n); int len = 0; arr = get_inorder(root, arr, &len); int sum= get_inorder_sum(root); int index=0; fill_inorder(root, arr, &index, &sum); print_inorder(root); getch(); }
true
5863009487f5bdc002a537b8ed5ea4d5245126f8
C++
ivancea/TuentiChallenge7
/5/main.cpp
UTF-8
4,226
2.703125
3
[]
no_license
#include <iostream> #include <fstream> #include "http.h" using namespace std; int main1(){ http::GETRequest req("https://52.49.91.111:8443/ghost"); string fullBody; int contentLength = -1; do{ req.setField("range", "bytes=" + to_string(fullBody.size()) +"-"); http::response resp = http::sendRequest(req); fullBody += resp.getBody(); cout << fullBody.size() << endl; if(contentLength < 0){ contentLength = stoi(resp.getField("content-length")); } } while(fullBody.size() < contentLength); ofstream file("submit.txt"); file << fullBody << endl; } namespace Base64 { static bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } static std::string encode(const char* bytes_to_encode) { unsigned int in_len = strlen(bytes_to_encode); std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (i = 0; (i < 4); i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for (j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while ((i++ < 3)) ret += '='; } return ret; } static std::string decode(std::string const& encoded_string) { std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { for (i = 0; i < 4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j < 4; j++) char_array_4[j] = 0; for (j = 0; j < 4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } } int main2(){ ifstream file("submit.txt"); string fullBody; while(file){ string t; getline(file, t); fullBody += t; } file.close(); ofstream png("image.png", ios::binary); png << Base64::decode(fullBody); } int main(){ //4017-8120 http::GETRequest req("https://52.49.91.111:8443/ghost"); req.setField("range", "bytes=4017-8120"); //req.setField("if-range", "Fri, 28 Apr 2017 07:28:00 GMT"); http::response resp = http::sendRequest(req); cout << resp.toString() << endl; } int mainT(){ // Compiled this way to prevent the executable from editing correct files (yes, I'm so lazy) }
true
9b731750971956dbaa49fc4f1e2e22d3ba78575d
C++
SohaylaMohamed/Compiler
/Parser/Construct_Automata.cpp
UTF-8
13,444
2.65625
3
[]
no_license
// // Created by sohayla on 20/03/19. // #include <algorithm> #include <iostream> #include <regex> #include "Construct_Automata.h" #include "../Automata/Helpers.h" Construct_Automata::Construct_Automata() { def_t = Definitions_Table::getInstance(); } bool Construct_Automata::constructAutomata(string line) { Tokenizing tokeniser; vector<string> tokens = tokeniser.getTokens(line, ' '); if(tokens.size() < 1) return false; if (tokens[1] == "=") {// definition string id = tokens[0]; tokens.erase(tokens.begin()); tokens.erase(tokens.begin()); return constructDefinition(id, tokens); } if(tokens[1] == ":") { // part of the automata string id = tokens[0]; tokens.erase(tokens.begin()); tokens.erase(tokens.begin()); Graph *sub_g = constructNFASubGraph(tokens); // testGraph(sub_g); nfa_id = sub_g->getEndState()->getId()+1; sub_g->getEndState()->setStatus(id); sub_g->getEndState()->setPriority(priority++); sub_Automatas.push_back(sub_g); //construct new subgraph //add subgraph to map //return } else { //switch check if valid input if (tokens[0] == "{") { tokens.erase(tokens.begin()); tokens.erase(tokens.end()); constructKeyWords(tokens); //keywords //data types } else if (line.at(0) == '[') { tokens.erase(tokens.begin()); tokens.erase(tokens.end()); constructPunct(tokens); } else { return false; } } return true; } Graph* Construct_Automata::constructNFASubGraph(vector<string> tokens) { Graph* d_g = recurseBuild(tokens, &nfa_id); //insertDef(d_g->getEdges()); return d_g; } Graph* Construct_Automata::recurseBuild(vector<string> tokens, int* i) { Helpers* merge = Helpers::getInstance(); if(tokens.empty()) return NULL; string temp = tokens.front(); tokens.erase(tokens.begin()); bool brackets = false; Graph* d_g = new Graph(); if(temp == "(") { brackets = true; d_g = recurseBrackets(&tokens, i); } string h = helperValue(&tokens); if(!brackets) { d_g = createGraph(&tokens, temp, i,h); } if(h == "*" || h == "\\+") { if(!(temp.length() == 1 ||temp.find("-") != string::npos|| temp.at(0) == '\\' ) && !this->complexDefinitions.count(temp)) { h = helperValue(&tokens); } else { d_g = merge->mergeGraphs(d_g, NULL, h, i); } h = helperValue(&tokens); } while (h == "." && !tokens.empty()) { d_g = getCont(d_g, &tokens, i); // testGraph(d_g); h = helperValue(&tokens); } return merge->mergeGraphs(d_g, recurseBuild(tokens, i),h, i); } bool Construct_Automata::constructDefinition(string id, vector<string> definition) { // if(check_complex(definition)) { complexDefinitions.insert(pair<string, vector<string>>(id, definition)); defVisited.insert(pair<string, bool >(id, false)); // return false; //} else { // string de = mergeString(definition); //Node* n = new Node(def_id++); //n->setStatus(de); //Graph* g = new Graph(); //g->setStart(n); //g->setEnd(n); //def_t->insertInMap(id, new Definition(g)); //testGraph(g); //} /* Graph* g = recurseBuild(definition, &def_id); g->getEndState()->setStatus(id);*/ return true; } bool Construct_Automata::constructNFA() { Graph* nfa = new Graph(); Definition* eps = def_t->getDefinitions(EPS); Node* new_start = new Node(nfa_id); nfa->setStart(new_start); for (int i = 0; i <sub_Automatas.size() ; ++i) { // cout<<"Graph #" << i << endl << "-----------------------" << endl; testGraph(sub_Automatas[i]); nfa->mergeGraph(sub_Automatas[i]->getEdges(), sub_Automatas[i]->getAllstates()); nfa->addEdge(new_start, sub_Automatas[i]->getStartState(), eps); } NFA* n = NFA::getInstance(); n->setAutomata(nfa); // testGraph(nfa); return true; } Graph *Construct_Automata::recurseBrackets(vector<string> *pVector, int *pInt) { vector<string> p_t; string t = ""; while(t != ")") { t = pVector->front(); pVector->erase(pVector->begin()); p_t.push_back(t); } p_t.pop_back(); Graph* g = recurseBuild(p_t, pInt); string st = "(" + g->getEndState()->getStatus() + ")"; g->getEndState()->setStatus(st); return g; } string Construct_Automata::helperValue(vector<string> *pVector) { Helpers* helper = Helpers::getInstance(); string h = "."; if(!pVector->empty()) { if(pVector->front() == "."){ return h; } if(pVector->front() != "\\-" && pVector->front() != "\\L" && pVector->front() != "=") { if (helper->isAhelper(pVector->front()) && pVector->front() != "(") { h = pVector->front(); pVector->erase(pVector->begin()); } } } return h; } Graph *Construct_Automata::createGraph(string temp, int *i) { Definition *w = def_t->getDefinitions(temp); if(w == NULL) { Graph* g = new Graph(); Node *n3 = new Node(1); g->setStart(n3); g->setEnd(n3); g->getStartState()->setStatus(temp); w = new Definition(g); def_t->insertInMap(temp, w); } Graph* d_g = new Graph(); Node *n1 = new Node((*i)++); Node *n2 = new Node((*i)++); n2->setStatus(temp); d_g->addEdge(n1, n2, w); d_g->setStart(n1); d_g->setEnd(n2); return d_g; } Graph *Construct_Automata::splitToken(string temp, int *i, string h) { vector<string> rec; for (int j = 0; j < temp.length(); ++j) { rec.push_back(string(1, temp.at(j))); } if(h == "*" || h == "+") rec.push_back(h); return recurseBuild(rec, i); } Graph* Construct_Automata::createGraphFromExistingDefintition(Definition* def, int* i, string temp) { Graph* d_g = new Graph(); Node *n1 = new Node((*i)++); Node *n2 = new Node((*i)++); n2->setStatus(temp); d_g->addEdge(n1, n2, def); d_g->setStart(n1); d_g->setEnd(n2); return d_g; } Graph *Construct_Automata::createGraph(vector<string> *tokens, string temp, int *i,string h) { if(complexDefinitions.count(temp)) { Graph* g = recurseBuild(complexDefinitions[temp], i); g->getEndState()->setStatus(temp); //defVisited[temp] = true; return g; } if (temp.length() == 1 ||temp.find("-") != string::npos|| temp.at(0) == '\\' ) { if (!tokens->empty() || temp.find("-") != string::npos) { vector<string> expanded; if ((tokens->front() == "\\-" && temp.length() == 1)) { temp += tokens->front(); tokens->erase(tokens->begin()); temp += tokens->front(); tokens->erase(tokens->begin()); } } } Definition *d; if(temp == "\\L") { d = def_t->getDefinitions(EPS); } else { d = def_t->getDefinitions(temp); } if (d != NULL) { return createGraphFromExistingDefintition(d,i, temp); } else if (temp.length() == 1 ||temp.find("-") != string::npos|| temp.at(0) == '\\' ) { if(!tokens->empty() || temp.find("-") != string::npos) { vector<string> expanded; if((tokens->front() == "\\-" && temp.length() == 1 )) { temp += tokens->front(); tokens->erase(tokens->begin()); temp += tokens->front(); tokens->erase(tokens->begin()); return expandedGraph( temp, i); } else if( temp.find("-") != string::npos && temp.length() == 4) { return expandedGraph(temp, i); } } return createGraph(temp, i); } else if (temp.length() > 1) { return splitToken(temp, i,h); } } void Construct_Automata::testGraph(Graph *g) { vector<Node*> states = g->getAllstates(); vector<Edge*> edges = g->getEdges(); Node* start = g->getStartState(); cout << "States : "<<endl; for (int i = 0; i < states.size(); ++i) { cout<<"States# " <<states[i]->getId() << " status " << states[i]->getStatus() <<endl; if(states[i]->getStatus() != N_ACC) cout << "Accept state : " << states[i]->getId() << " status " << states[i]->getStatus() << " with Priority "<< states[i]->getPriority() <<endl; } cout << "start state : " << start->getId() << " status " << start->getStatus() <<endl; cout << "Egdes : "<<endl; for (int j = 0; j < edges.size(); ++j) { cout << "Edge Weight type " << edges[j]->getWeight()->getDef()->getEndState()->getStatus() << " from" << edges[j]->getSource()->getId() << " to " << edges[j]->getDestination()->getId() << endl; } } Graph* Construct_Automata::getCont(Graph *d_g, vector<string> *tokens, int *i) { Helpers* merge = Helpers::getInstance(); string temp = tokens->front(); tokens->erase(tokens->begin()); bool brackets = false; Graph* g = new Graph(); if(temp == "(") { brackets = true; g = recurseBrackets(tokens, i); } string h = helperValue(tokens); if(!brackets) { g = createGraph(tokens, temp, i, h); } if(h == "*" || h == "\\+") { g = merge->mergeGraphs(g, NULL, h, i); h = helperValue(tokens); } else { if(h != ".") tokens->insert(tokens->begin(), h); } return merge->mergeGraphs(d_g, g, ".", i); } /*bool Construct_Automata::check_complex(vector<string> tokens) { for (int i = 0; i < tokens.size() ; ++i) { if(def_t->getDefinitions(tokens[i]) != NULL) return true; } string de = mergeString(tokens); regex e ("[0aA]\\\-[9zZ]"); if(regex_match(de, e)) return false; if(tokens.size() == 1) { if(tokens[0].length() == 1) return false; } // Helpers* h = Helpers::getInstance(); //vector<string> graphH = h->getGraphHelpers(); //for (int j = 0; j < graphH.size() ; ++j) { // for (int i = 0; i < tokens.size(); ++i) { // if(tokens[i].find(graphH[j]) != string::npos) // return true; //} //} return true; }*/ void Construct_Automata::constructKeyWords(vector<string> tokens) { while (!tokens.empty()) { Helpers* merge = Helpers::getInstance(); Graph* d_g = splitToken(tokens.front(), &nfa_id, "."); d_g->getEndState()->setStatus(tokens.front()); d_g->getEndState()->setPriority(0); tokens.erase(tokens.begin()); sub_Automatas.push_back(d_g); //insertDef(d_g->getEdges()); } return; } void Construct_Automata::constructPunct(vector<string> tokens) { while (!tokens.empty()) { Helpers* merge = Helpers::getInstance(); Graph* d_g = createGraph(tokens.front(), &nfa_id); d_g->getEndState()->setStatus(tokens.front()); d_g->getEndState()->setPriority(priority); tokens.erase(tokens.begin()); sub_Automatas.push_back(d_g); //insertDef(d_g->getEdges()); } priority++; return; } void Construct_Automata::insertDef(vector<Edge *> edges) { for (int i = 0; i < edges.size(); ++i) { Definition* d = edges[i]->getWeight(); if(def_t->getDefinitions(d->getDef()->getEndState()->getStatus()) == NULL) { def_t->insertInMap(d->getDef()->getEndState()->getStatus(), d); } } } vector<string> Construct_Automata::expandDef(string def) { vector<string> seglist; std::stringstream test(def); string segment; while(std::getline(test, segment, '-')) { seglist.push_back(segment); } char start = seglist[0].at(0); char end = seglist[1].at(0); vector<string> result; while (start <= end) { result.push_back(string(1,start++)); } return result; } Graph *Construct_Automata::expandedGraph(string temp, int *i) { vector<string> tokens = expandDef(temp); vector<Graph*> subGraphs; Graph* result; while (!tokens.empty()) { Graph* d_g = createGraph(tokens.front(), i); d_g->getEndState()->setStatus(tokens.front()); tokens.erase(tokens.begin()); subGraphs.push_back(d_g); } Node* new_start = new Node((*i)++); Node* new_end = new Node((*i)++); new_end->setStatus(temp); result = new Graph(); result->setStart(new_start); result->setEnd(new_end); for (int j = 0; j <subGraphs.size() ; ++j) { cout<<"Graph #" << i << endl << "-----------------------" << endl; // testGraph(sub_Automatas[j]); result->mergeGraph(subGraphs[j]->getEdges(), subGraphs[j]->getAllstates()); result->addEdge(new_start, subGraphs[j]->getStartState(), def_t->getDefinitions(EPS)); subGraphs[j]->getEndState()->setStatus(N_ACC); result->addEdge(subGraphs[j]->getEndState(), new_end, def_t->getDefinitions(EPS)); } // testGraph(result); return result; } /*string Construct_Automata::mergeString(vector<string> tokens) { string result = tokens[0]; for (int i = 1; i < tokens.size(); ++i) { result += tokens[i]; } return result; }*/
true
80f56d044258594b8ebc4e86021d3c792ccc6556
C++
jjzhang166/GameEngine-2
/game/modelManipulation/src/Simplifier.cpp
UTF-8
5,473
2.859375
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> #include <glm/gtc/matrix_inverse.hpp> #include <glm/mat4x4.hpp> #include "Simplifier.h" struct ContractionPair { float cost; Index i0, i1; glm::vec3 recommendedPos; bool deleted; ContractionPair(float cost, const Index& i0, const Index& i1, const glm::vec3& recommendedPos) : cost(cost), i0(i0), i1(i1), recommendedPos(recommendedPos), deleted(false) {} bool operator<(const ContractionPair& other) const { return cost < other.cost; } }; float det(float a11, float a12, float a13, float a21, float a22, float a23, float a31, float a32, float a33) { return a11*a22*a33 + a13*a21*a32 + a12*a23*a31 - a13*a22*a31 - a11*a23*a32- a12*a21*a33; } float id(const glm::mat4& q, size_t i) { if (i <= 3) return q[i][0]; if (i <= 6) return q[i - 3][1]; else if (i <= 8) return q[i - 6 + 1][2]; else return q[3][3]; } float detid(const glm::mat4& q, size_t a11, size_t a12, size_t a13, size_t a21, size_t a22, size_t a23, size_t a31, size_t a32, size_t a33) { return det( id(q, a11), id(q, a12), id(q, a13), id(q, a21), id(q, a22), id(q, a23), id(q, a31), id(q, a32), id(q, a33) ); } float VertexError(const glm::mat4& q, const glm::vec3& p) { return id(q, 0)*p.x*p.x + 2*id(q, 1)*p.x*p.y + 2*id(q, 2)*p.x*p.z + 2*id(q, 3)*p.x + id(q, 4)*p.y*p.y + 2*id(q, 5)*p.y*p.z + 2*id(q, 6)*p.y + id(q, 7)*p.z*p.z + 2*id(q, 8)*p.z + id(q, 9); } float CalcError(const Index& i0, const Index& i1, const IndexedModel& model, glm::vec3& result) { const Vertex& v0 = model.vertices[i0.pos]; const Vertex& v1 = model.vertices[i1.pos]; glm::mat4 q = v0.quadric + v1.quadric; float deter = detid(q, 0, 1, 2, 1, 4, 5, 2, 5, 7); if (deter != 0) { result.x = -1/deter * detid(q, 1, 2, 3, 4, 5, 6, 5, 7, 8); result.y = -1/deter * detid(q, 0, 2, 3, 1, 5, 6, 2, 7, 8); result.z = -1/deter * detid(q, 0, 1, 3, 1, 4, 6, 2, 5, 8); return VertexError(q, result); } else { const glm::vec3& p0 = v0.position; const glm::vec3& p1 = v0.position; const glm::vec3 pAvg = (p0 + p1) * 0.5f; float p0err = VertexError(q, p0); float p1err = VertexError(q, p1); float pAvgerr = VertexError(q, pAvg); if (p0err <= p1err && p0err <= pAvgerr) { result = p0; return p0err; } else if (p1err <= p0err && p1err <= pAvgerr) { result = p1; return p1err; } else { result = pAvg; return pAvgerr; } } } void CreateContractionPair(const Index& i0, const Index& i1, const IndexedModel& model, std::vector<ContractionPair>& contractionPairs) { glm::vec3 recommendedPos; float error = CalcError(i0, i1, model, recommendedPos); contractionPairs.emplace_back(error, i0, i1, recommendedPos); const Vertex& v0 = model.vertices[i0.pos]; const Vertex& v1 = model.vertices[i1.pos]; #if 0 glm::mat4 quadric = v0.quadric + v1.quadric; glm::vec4 vt; float error; if (glm::determinant(quadric) != 0) //is the matrix invertible? { glm::mat4 quadricCopy = quadric; quadricCopy[0].w = 0; quadricCopy[1].w = 0; quadricCopy[2].w = 0; quadricCopy[3].w = 1; vt = glm::inverse(quadricCopy) * glm::vec4(0, 0, 0, 1); error = glm::dot(vt * quadric, vt); } else { Vertex avg((v0.position + v1.position) * 0.5f); glm::vec4 v0_pos(v0.position, 1.0); glm::vec4 v1_pos(v1.position, 1.0); glm::vec4 vavg_pos(avg.position, 1.0); float v0_error = glm::dot(v0_pos * quadric, v0_pos); float v1_error = glm::dot(v1_pos * quadric, v1_pos); float vavg_error = glm::dot(vavg_pos * quadric, vavg_pos); if (v0_error < v1_error && v0_error < vavg_error) { error = v0_error; vt = v0_pos; } else if (v1_error < v0_error && v1_error < vavg_error) { error = v1_error; vt = v1_pos; } else { error = vavg_error; vt = vavg_pos; } } contractionPairs.emplace_back(error, i0, i1, vt); #elif 0 contractionPairs.emplace_back( glm::dot(v1.position - v0.position, v1.position - v0.position), i0, i1, (v0.position + v1.position) * 0.5f ); #endif } void SimplifyMesh(IndexedModel& model) { std::vector<ContractionPair> pairs; pairs.reserve(model.triangles.size()); for (const Triangle& tri : model.triangles) { CreateContractionPair(tri.v[0], tri.v[1], model, pairs); CreateContractionPair(tri.v[0], tri.v[2], model, pairs); CreateContractionPair(tri.v[1], tri.v[2], model, pairs); } std::sort(pairs.begin(), pairs.end()); unsigned int edgesContracted = 0; for (ContractionPair& contraction : pairs) { for (Triangle& tri : model.triangles) { const bool equality[6] { tri.v[0].pos == contraction.i0.pos, tri.v[1].pos == contraction.i0.pos, tri.v[2].pos == contraction.i0.pos, tri.v[0].pos == contraction.i1.pos, tri.v[1].pos == contraction.i1.pos, tri.v[2].pos == contraction.i1.pos, }; const size_t equalityCount = equality[0] + equality[1] + equality[2] + equality[3] + equality[4] + equality[5]; // if (equalityCount == 1) // { // if (equality[3]) // tri.v[0] = contraction.i0; // else if (equality[4]) // tri.v[1] = contraction.i0; // else if (equality[5]) // tri.v[2] = contraction.i0; // } // else if (equalityCount >= 2) // { // for (Index& idx : tri.v) // idx.deleted = true; // } } model.vertices[contraction.i0.pos].position = (model.vertices[contraction.i0.pos].position + model.vertices[contraction.i1.pos].position) * 0.5f; edgesContracted++; if (edgesContracted >= pairs.size() / 10.0f) break; } }
true
08d4d14dc071c2b8eabe8dfa9c0efbc62fe422c9
C++
EvilPluto/Algorithm
/ComplexNode/ComplexNode/main.cpp
UTF-8
2,579
3.25
3
[]
no_license
// // main.cpp // ComplexNode // // Created by 修海锟 on 2017/3/12. // Copyright © 2017年 修海锟. All rights reserved. // #include <iostream> using namespace std; struct ComplexNode { int m_nValue; ComplexNode* m_pNext; ComplexNode* m_pSibling; }; void CloneNodes(ComplexNode* pHead) { if (pHead == NULL) { exit(1); } ComplexNode* pNode = pHead; while (pNode != NULL) { ComplexNode* pClone = (ComplexNode*)malloc(sizeof(ComplexNode)); pClone->m_nValue = pNode->m_nValue; pClone->m_pNext = pNode->m_pNext; pClone->m_pSibling = NULL; pNode->m_pNext = pClone; pNode = pClone->m_pNext; } } void SiblingNodes(ComplexNode* pHead) { ComplexNode* pNode = pHead; while (pNode != NULL) { ComplexNode* pClone = pNode->m_pNext; if (pNode->m_pSibling != NULL) { pClone->m_pSibling = pNode->m_pSibling->m_pNext; } pNode = pClone->m_pNext; } } ComplexNode* SplitList(ComplexNode* pHead) { ComplexNode* pNode = pHead; ComplexNode* pClonedHead = pNode->m_pNext; while (pNode != NULL) { ComplexNode* pClone = pNode->m_pNext; if (pClone->m_pNext != NULL) { ComplexNode* pTemp = pClone->m_pNext; pClone->m_pNext = pClone->m_pNext->m_pNext; pNode->m_pNext = pTemp; } else { pClone->m_pNext = NULL; pNode->m_pNext = NULL; } pNode = pNode->m_pNext; } return pClonedHead; } ComplexNode* Clone(ComplexNode* pHead) { CloneNodes(pHead); SiblingNodes(pHead); return SplitList(pHead); } int main(int argc, const char * argv[]) { ComplexNode* node1= (ComplexNode* )malloc(sizeof(ComplexNode)); ComplexNode* node2 = (ComplexNode* )malloc(sizeof(ComplexNode)); ComplexNode* node3 = (ComplexNode* )malloc(sizeof(ComplexNode)); ComplexNode* node4 = (ComplexNode* )malloc(sizeof(ComplexNode)); ComplexNode* node5 = (ComplexNode* )malloc(sizeof(ComplexNode)); node1->m_nValue = 1; node1->m_pNext = node2; node1->m_pSibling = node3; node2->m_nValue = 2; node2->m_pNext = node3; node2->m_pSibling = node5; node3->m_nValue = 3; node3->m_pNext = node4; node3->m_pSibling = NULL; node4->m_nValue = 4; node4->m_pNext = node5; node4->m_pSibling = node2; node5->m_nValue = 5; node5->m_pNext = NULL; node5->m_pSibling = NULL; ComplexNode* pCloned = Clone(node1); return 0; }
true
fe171c1cd35edeba27a860096a3feff8522784ff
C++
cskilbeck/react4
/firmware/Core/Src/song.cpp
UTF-8
2,634
2.59375
3
[]
no_license
#include "main.h" #include "util.h" #include "song.h" #define TIMER TIM14 #define CHANNEL LL_TIM_CHANNEL_CH1 #define PORT GPIOA #define PIN 4 namespace { int constexpr speed = 18; song::note const *tune; int tune_length; song::option loop_option = song::option::single; int when; int notes_to_play; song::note const *next_note; song::note const *cur_note; void set_port_mode(uint32 mode) { PORT->MODER = PORT->MODER & ~(GPIO_MODER_MODER0_Msk << (PIN * 2)) | (mode << (PIN * 2)); } } // namespace namespace song { void init() { // TIM14 for buzzer TIMER->CCER |= CHANNEL; TIMER->BDTR |= TIM_BDTR_MOE; } void play(note const *song, size_t num, option opt) { loop_option = opt; tune = song; tune_length = num; notes_to_play = num; next_note = song; cur_note = null; when = (ticks * speed) >> 8; set_port_mode(LL_GPIO_MODE_ALTERNATE); TIMER->CR1 |= TIM_CR1_CEN; } void stop() { // switch GPIO into input mode because otherwise it bleeds // some stuff which you can hear set_port_mode(LL_GPIO_MODE_INPUT); // and switch off the timer TIMER->CR1 &= ~TIM_CR1_CEN; tune = null; tune_length = 0; notes_to_play = 0; loop_option = option::single; } bool finished() { return notes_to_play == 0; } void update() { if(notes_to_play == 0) { if(loop_option == option::single) { stop(); return; } else if(loop_option == option::looping && tune != null) { play(tune, tune_length, loop_option); } } uint32 t = (ticks * speed) >> 8; if(next_note != null) { cur_note = next_note; next_note = null; when = t; } int played_time = t - when; if(played_time >= cur_note->delay) { notes_to_play -= 1; next_note = cur_note + 1; } // note slide int32 d = (played_time << 16) / cur_note->delay; // 0..65536 int x = (((cur_note->timer2 - cur_note->timer1) * d) >> 16) + cur_note->timer1; TIMER->ARR = x; // tone ramp int v = 32 - min(32, played_time * 4 / 32); v = 64 - ((((v * v) >> 5) * v) >> 5); TIMER->CCR1 = (cur_note->timer1 * v) / 128; } } // namespace song
true
427119d4bc0a354b978a81a1441e6b888d146976
C++
pjaluka13/C-Programs
/doublylinkedlist/doublylinkedlist.h
UTF-8
1,502
3.3125
3
[]
no_license
/*---------------------------------------------------------------------- Programming Assignment No: 1 (CSCI311 spring 15) Name: Tejas Vamanrao Patil Date : 6 Feb 2015 File Name: playlist.h Implementation of a Playlist for music. Description: Implementation of a Playlist for music. A doubly linked list is used to store the song names. -----------------------------------------------------------------------*/ #include <iostream> #include <string> using namespace std; /*---------------------------------------------------------------------- Description: Decleration of class DoublyLinkedList and Node which act as a decleration for doublylinked list -----------------------------------------------------------------------*/ class DoublyLinkedList { private: //class Node decleration and it constructor and Destructor class Node { public: Node(); Node(string& str); ~Node(); //Node dectructor //Node pointers string* data; Node* next; Node* prev; }; Node* head; Node* tail; Node* current; public: //Doublylinkedlist constructor and destructor decleration DoublyLinkedList(); ~DoublyLinkedList(); bool empty(); void append(string& str); void insertBefore(string& str); void insertAfter(string& str); void remove(string& str); void begin(); void end(); bool next(); bool prev(); bool find(string& str); const string& getData(); }; /*-------------------------------EOF-----------------------------------*/
true
c40963d24fc4fea71ba9b41d5e6ff8622fc26325
C++
eatoin5hrdlu/LemurCam
/LemurCam.ino
UTF-8
3,833
2.671875
3
[]
no_license
/* Flash pin 13 10 times and toggle a latching relay on pins 11 and 12 */ // DEFINE DEBUG to produce readable (ASCII) command strings //#define DEBUG 1 // DEFINE LEMUR for single camera version #define LEMUR 1 // For UP...CAM2, the constants correspond to Arduino inputs #define STOP 0 #define UNDEF1 1 #define UNDEF2 2 #define UP 3 // Input pin D3 #define DOWN 4 #define LEFT 5 #define RIGHT 6 #define IN 7 #define OUT 8 #define CAM1 9 #define CAM2 10 // Input pin D10 #define CAM 0 // Location of cameraID in command string #define PAN_SPEED 3 // Pan Speed byte #define TILT_SPEED 4 // Tilt speed byte int lastCommand = -1; int relayState = 0; int speed[2] = { 0x20, 0x20 } ; #ifdef DEBUG byte pelco_stop[5] = "czsss"; byte pelco_right[5] = "czrss"; byte pelco_left[5] = "czlss"; byte pelco_up[5] = "czuss"; byte pelco_down[5] = "czdss"; byte pelco_in[5] = "cziss"; byte pelco_out[5] = "czoss"; #else byte pelco_stop[5] = { 0x01, 0x00, 0x00, 0x20, 0x20 }; byte pelco_right[5] = { 0x01, 0x00, 0x02, 0x20, 0x20 }; byte pelco_left[5] = { 0x01, 0x00, 0x04, 0x20, 0x20 }; byte pelco_up[5] = { 0x01, 0x00, 0x08, 0x20, 0x20 }; byte pelco_down[5] = { 0x01, 0x00, 0x10, 0x20, 0x20 }; byte pelco_in[5] = { 0x01, 0x00, 0x20, 0x20, 0x20 }; byte pelco_out[5] = { 0x01, 0x00, 0x40, 0x20, 0x20 }; #endif byte *msg[9] = { pelco_stop, pelco_stop, // spare pelco_stop, // spare pelco_up, pelco_down, pelco_left, pelco_right, pelco_in, pelco_out }; void setup() { delay(2000); Serial.begin(2400, SERIAL_8N1); /* default */ #ifdef DEBUG Serial.print("hello, world.\n"); #endif for (int i = 3; i < 11; i++ ) { pinMode(i, INPUT); digitalWrite(i,1); } pinMode(11, OUTPUT); digitalWrite(11,1); pinMode(12, OUTPUT); digitalWrite(12,1); } /* If this command was already sent, just return * If previous command was not STOP: send STOP first * Finally, send the command */ void sendIfNeeded(int command) { if (command == lastCommand) // Command was already sent return; if (lastCommand != 0 || command == STOP) { // need a STOP send(msg[STOP]); delay(100); } if (command != STOP) send(msg[command]); // Send the new command lastCommand = command; // and remember it. } void pulse(int pin, int del) { digitalWrite(pin,0); delay(del); digitalWrite(pin,1); delay(del); } int relay(int onOff) { if (onOff) pulse(11, 8); else pulse(12, 8); return onOff; } void toggle(void) { relayState = relay(!relayState); } void send(byte *msg) { byte chksum = 0; /* * Before sending a command string: * 1) Put the current camera address into byte zero * 2) fill in the Pan/Tilt speeds for that camera */ #ifdef LEMUR msg[CAM] = 0x07; #else if (relayState) msg[CAM] = 0x03; else msg[CAM] = 0x07; #endif #ifdef DEBUG Serial.print("-"); msg[PAN_SPEED] = msg[TILT_SPEED] = 's'; #else Serial.write(0xFF); msg[PAN_SPEED] = msg[TILT_SPEED] = speed[relayState]; #endif for( int i=0; i < 5; i++) { Serial.write(msg[i]); chksum += msg[i]; } #ifdef DEBUG Serial.print("\n"); #else Serial.write(chksum); #endif } void loop() { pulse(13, 50); if ( !digitalRead(UP) ) sendIfNeeded(UP); else if ( !digitalRead(DOWN)) sendIfNeeded(DOWN); else if ( !digitalRead(LEFT)) sendIfNeeded(LEFT); else if ( !digitalRead(RIGHT)) sendIfNeeded(RIGHT); else if ( !digitalRead(IN) ) { sendIfNeeded(IN); if (speed[relayState] > 0x10) speed[relayState]--; } else if ( !digitalRead(OUT)) { sendIfNeeded(OUT); if (speed[relayState] < 0x20) speed[relayState]++; } else if ( !digitalRead(CAM1)) relayState = relay(1); else if ( !digitalRead(CAM2)) relayState = relay(0); else sendIfNeeded(STOP); delay(50); }
true
acc44685b2bedd5de775d742a09cd70673bb1e55
C++
P4piJoke/DroneFlightSimulation
/Kursova_Papizhuk/Commander.h
UTF-8
826
3
3
[]
no_license
#ifndef COMMANDER_H #define COMMANDER_H #include "Navigator.h" class Commander : public Navigator { // Child class Commander for Navigator private: /* Velocity - two conventional units Battery drain - one conventional unit */ std::string commandAndControlType; // Commander command and control type public: Commander(int id, std::string type, int currentX, std::string gpsType, std::string commandAndControlType); // Commander constructor // Get and Set methods for command and control type std::string getCommandAndControlType(); void setCommandAndControlType(std::string commandAndControlType); void info()override; // Overload of the info function for the Commander void info(Drone* obj); // Information about the drone at the beginning of the flight ~Commander(); // Destructor }; #endif // !COMMANDER_H
true
5d93661cbd6397b6d10d1d430f007060545c5180
C++
saparhadi/ESP32
/ESP32-Firebase/ESP32-Firebase.ino
UTF-8
2,170
2.59375
3
[]
no_license
#include <WiFi.h> // esp32 library #include <IOXhop_FirebaseESP32.h> #define FIREBASE_HOST "saparhadi-191118.firebaseio.com" // the project name address from firebase id #define FIREBASE_AUTH "fjuyfKHCJYJEVvpAhTon5J3RshAF0xsq09UNuAIK" // the secret key generated from firebase #define WIFI_SSID "Saparhadi" // input your home or public wifi name #define WIFI_PASSWORD "ahahahaha" //password of wifi ssid int fireStatus = 0; // led status received from firebase int led = 4; void setup() { Serial.begin(115200); delay(1000); pinMode(led, OUTPUT); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); //try to connect with wifi Serial.print("Connecting to "); Serial.print(WIFI_SSID); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("Connected to "); Serial.println(WIFI_SSID); Serial.print("IP Address is : "); Serial.println(WiFi.localIP()); //print local IP address Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); // connect to firebase Firebase.setInt("/led", 0); //send initial string of led status } void loop() { fireStatus = Firebase.getInt("/led"); // get led status input from firebase if (fireStatus == 255) { // compare the input of led status received from firebase Serial.println("Led Turned ON"); digitalWrite(led, HIGH); // make output led ON } else if (fireStatus == 0) { // compare the input of led status received from firebase Serial.println("Led Turned OFF"); digitalWrite(led, LOW); // make output led OFF } else { Serial.println("Wrong Credential! Please send ON/OFF"); } }
true
dac8b0db567d947e921e495bedec66094f3b8ba6
C++
Lcch/ngramtools
/ngram_server.h
UTF-8
1,278
2.765625
3
[]
no_license
#ifndef NGRAM_SERVER_H #define NGRAM_SERVER_H #include <string> #include <cstdio> #include <unistd.h> using namespace std; const string kEON = "<EON>"; const string kSearch = "s"; const string kSearchExact = "e"; const string kSearchAndFilter = "f"; const int kBufSize = 10000; const int kLineBufSize = 1024; class SocketBuffer { string buf_; char line_buf_[kLineBufSize + 1]; int socket_; bool eof_; public: bool eof() const { return eof_;} SocketBuffer(int socket = -1) { socket_ = socket; eof_ = false;} ~SocketBuffer() { if (socket_ >= 0) close(socket_);} void Socket(int s) { socket_ = s;} int Socket() { return socket_;} void Clear() { buf_.clear(); eof_ = false;} string GetNextLine() { string line; while (!eof_) { int p = buf_.find_first_of('\n'); if (p != string::npos) { if (p >= 1 && buf_[p - 1] == '\r') line = buf_.substr(0, p - 1); else line = buf_.substr(0, p); if (p + 1 == buf_.size()) buf_.clear(); else buf_ = buf_.substr(p + 1); break; } int len = ::read(socket_, line_buf_, kLineBufSize); if (len > 0) { line_buf_[len] = '\0'; buf_ += string(line_buf_, len); } else { line = buf_; buf_.clear(); eof_ = true; break; } } return line; } }; #endif
true
4d55857cdd691306229c69822a464a160d1462eb
C++
dbrisaro/algo1
/labos_algo1/labo02/ejercicio_03.cpp
UTF-8
1,637
3.171875
3
[]
no_license
/****************************************************************************** Ejercicio 03 Labo 02 AED1 Dani Risaro *******************************************************************************/ #include <iostream> using namespace std; int main() { float nota = 0; int i = 0; // cantidad de alumnos int aprobados = 0; int desaprobados = 0; float centinela = 0; while(centinela != -1){ cout << "Ingrese la nota (-1 para terminar): " << endl; cin >> nota; if(nota>=6){ aprobados = aprobados + 1; } if(nota>=0 and nota<6){ desaprobados = desaprobados + 1; } if(nota!=-1 and nota<0){ cout << "La nota no está entre 0 y 10!" << endl; break; } i = i+1; centinela = nota; } float numeroTotal = i; if (numeroTotal>=6){ cout << "Cantidad de aprobados " << aprobados << " de " << i << endl; cout << "Cantidad de desaprobados " << desaprobados << " de " << i << endl; float porcentajeAprobados = aprobados/numeroTotal; float dosTercios = 2.0/3.0; cout << "Porcentaje de aprobados " << porcentajeAprobados << ". Dos tercios " << dosTercios << endl; if(porcentajeAprobados > dosTercios){ cout << "Se puede incrementar el cupo del curso" << endl; } } else{ cout << "El total de alumnos es menor a 6!" << endl; } return 0; }
true
09c53a9706a4d1a204c98ffbb9a3e9c95ab07db6
C++
dessskris/Enigma_Machine
/reflector.h
UTF-8
894
2.640625
3
[]
no_license
/*--------------------------------------------------------------------------+ | HEADER FILE | | File Name: reflector.h | | Student: Desy Kristianti | | Coursework: MSc C++ Programming - Assessed Exercise No. 2 | | Date: 23 November 2015 | +--------------------------------------------------------------------------*/ #ifndef REFLECTOR_H #define REFLECTOR_H #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include "helper.h" using namespace std; class Reflector { private: int mapping[26]; public: int good; // Indicator of whether constructor was successful Reflector(const char *filename); int encrypt(const int &letter); }; #endif
true
de7237a819131c50e2059fb61c4162ce68986d77
C++
PJK136/Brutus
/CProgAST.cpp
UTF-8
46,165
2.609375
3
[]
no_license
// ---------------------------------------------------------- C++ System Headers #include <iostream> #include <string> #include <vector> // ------------------------------------------------------------- Project Headers #include "CProgAST.h" #include "IR.h" #include "Writer.h" //////////////////////////////////////////////////////////////////////////////// // class CProgAST // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTProgram::~CProgASTProgram() { for(CProgASTFuncdef* funcdef : funcdefs) { delete funcdef; } } // ----------------------------------------------------- Public Member Functions void CProgASTProgram::add_funcdef(CProgASTFuncdef* funcdef) { funcdefs.push_back(funcdef); } void CProgASTProgram::build_ir(IR& ir) const { for(CProgASTFuncdef* funcdef : funcdefs) { ir.add_cfg(funcdef->build_ir(&ir.global_symbols)); } } //////////////////////////////////////////////////////////////////////////////// // class CProgASTFuncdef // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTFuncdef::CProgASTFuncdef(const std::string &id, Type type) : identifier(id), return_type(type) {} CProgASTFuncdef::~CProgASTFuncdef() { for(CProgASTStatement* statement : statements) { delete statement; } } // ----------------------------------------------------- Public Member Functions void CProgASTFuncdef::add_arg(std::string id, Type type) { arg_types.push_back(type); arg_names.push_back(id); } void CProgASTFuncdef::add_statement(CProgASTStatement* statement) { statements.push_back(statement); } CFG* CProgASTFuncdef::build_ir(TableOfSymbols* global_symbols) const { global_symbols->add_symbol(identifier, return_type); SymbolProperties& fproperties = global_symbols->get_symbol(identifier); fproperties.callable = true; fproperties.arg_types = arg_types; CFG* cfg = new CFG(this, identifier, global_symbols); for(size_t i=0; i<arg_names.size(); ++i) { cfg->add_arg_to_symbol_table(arg_names[i], arg_types[i]); } for(CProgASTStatement* statement : statements) { statement->build_ir(cfg); } cfg->check_for_unused_symbols(); return cfg; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTCompoundStatement : public CProgASTStatement // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTCompoundStatement::~CProgASTCompoundStatement() { for(const CProgASTStatement* statement : statements) { delete statement; } } // ----------------------------------------------------- Public Member Functions void CProgASTCompoundStatement::add_statement(CProgASTStatement* statement) { statements.push_back(statement); } std::string CProgASTCompoundStatement::build_ir(CFG* cfg) const { for(const CProgASTStatement* statement : statements) { statement->build_ir(cfg); } return ""; // ?? } //////////////////////////////////////////////////////////////////////////////// // class CProgASTReturn : public CProgASTStatement // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTReturn::CProgASTReturn(CProgASTExpression* expression) : return_expression(expression) {} CProgASTReturn::~CProgASTReturn() { delete return_expression; } // ----------------------------------------------------- Public Member Functions std::string CProgASTReturn::build_ir(CFG* cfg) const { std::string rval = return_expression->build_ir(cfg); cfg->current_bb->add_IRInstr(IRInstr::ret, cfg->get_var_type(rval), {rval}); return ""; // ?? } //////////////////////////////////////////////////////////////////////////////// // class CProgASTDeclaration : public CProgASTStatement // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTDeclaration::CProgASTDeclaration(Type type) : type_specifier(type) {} CProgASTDeclaration::~CProgASTDeclaration() { for(const CProgASTDeclarator* declarator : declarators) { delete declarator; } } // ----------------------------------------------------- Public Member Functions void CProgASTDeclaration::add_declarator(CProgASTDeclarator* declarator) { declarator->set_type(type_specifier); declarators.push_back(declarator); } std::string CProgASTDeclaration::build_ir(CFG* cfg) const { for(const CProgASTDeclarator* declarator : declarators) { declarator->build_ir(cfg); } return ""; // ?? } //////////////////////////////////////////////////////////////////////////////// // class CProgASTDeclarator // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTDeclarator::CProgASTDeclarator(CProgASTIdentifier* id, CProgASTAssignment* init) : identifier(id), initializer(init) {} CProgASTDeclarator::~CProgASTDeclarator() { if(identifier) delete identifier; if(initializer) delete initializer; } // ----------------------------------------------------- Public Member Functions void CProgASTDeclarator::set_type(Type type) { type_specifier = type; } std::string CProgASTDeclarator::build_ir(CFG* cfg) const { std::string name = identifier->getText(); if(!cfg->is_declared(name)) { cfg->add_to_symbol_table(name, type_specifier); } else { Writer::error() << "multiple definition of '" << name << "'" << std::endl; } if(initializer != nullptr) { initializer->build_ir(cfg); } return ""; // ?? } //////////////////////////////////////////////////////////////////////////////// // class CProgASTIfStatement : public CProgASTStatement // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTIfStatement::CProgASTIfStatement(CProgASTExpression* condition, CProgASTStatement* if_statement, CProgASTStatement* else_statement) : condition(condition), if_statement(if_statement), else_statement(else_statement) {} CProgASTIfStatement::~CProgASTIfStatement() { delete condition; delete if_statement; delete else_statement; } // ----------------------------------------------------- Public Member Functions std::string CProgASTIfStatement::build_ir(CFG* cfg) const { std::string test_result = condition->build_ir(cfg); cfg->current_bb->add_IRInstr(IRInstr::cmp_null, cfg->get_var_type(test_result), {test_result}); BasicBlock* test_bb = cfg->current_bb; BasicBlock* then_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* after_if_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* else_bb = else_statement ? new BasicBlock(cfg, cfg->new_BB_name()) : nullptr; after_if_bb->exit_true = test_bb->exit_true; after_if_bb->exit_false = test_bb->exit_false; then_bb->exit_true = after_if_bb; then_bb->exit_false = nullptr; test_bb->exit_true = then_bb; test_bb->exit_false = else_bb ? else_bb : after_if_bb; cfg->current_bb = then_bb; if_statement->build_ir(cfg); cfg->add_bb(then_bb); if(else_bb) { cfg->current_bb = else_bb; else_bb->exit_true = after_if_bb; else_bb->exit_false = nullptr; else_statement->build_ir(cfg); cfg->add_bb(else_bb); } cfg->current_bb = after_if_bb; cfg->add_bb(after_if_bb); return ""; // ?? } //////////////////////////////////////////////////////////////////////////////// // class CProgASTWhileStatement : public CProgASTStatement // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTWhileStatement::CProgASTWhileStatement(CProgASTExpression* condition, CProgASTStatement* body) : condition(condition), body(body) {} CProgASTWhileStatement::~CProgASTWhileStatement() { delete condition; delete body; } // ----------------------------------------------------- Public Member Functions std::string CProgASTWhileStatement::build_ir(CFG* cfg) const { BasicBlock* before_while_bb = cfg->current_bb; BasicBlock* body_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* test_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* after_while_bb = new BasicBlock(cfg, cfg->new_BB_name()); after_while_bb->exit_true = before_while_bb->exit_true; after_while_bb->exit_false = before_while_bb->exit_false; before_while_bb->exit_true = test_bb; before_while_bb->exit_false = nullptr; test_bb->exit_true = body_bb; test_bb->exit_false = after_while_bb; body_bb->exit_true = test_bb; body_bb->exit_false = nullptr; cfg->current_bb = test_bb; std::string test_result = condition->build_ir(cfg); cfg->current_bb->add_IRInstr(IRInstr::cmp_null, cfg->get_var_type(test_result), {test_result}); cfg->add_bb(test_bb); cfg->current_bb = body_bb; body->build_ir(cfg); cfg->add_bb(body_bb); cfg->current_bb = after_while_bb; cfg->add_bb(after_while_bb); return ""; // ?? } //////////////////////////////////////////////////////////////////////////////// // class CProgASTForStatement : public CProgASTStatement // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTForStatement::CProgASTForStatement(CProgASTExpression* initialization, CProgASTExpression* condition, CProgASTExpression* increment, CProgASTStatement* body) : initialization(initialization), condition(condition), increment(increment), body(body) {} CProgASTForStatement::~CProgASTForStatement() { delete initialization; delete condition; delete increment; delete body; } // ----------------------------------------------------- Public Member Functions std::string CProgASTForStatement::build_ir(CFG* cfg) const { BasicBlock* before_for_bb = cfg->current_bb; BasicBlock* body_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* init_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* test_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* incr_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* after_for_bb = new BasicBlock(cfg, cfg->new_BB_name()); after_for_bb->exit_true = before_for_bb->exit_true; after_for_bb->exit_false = before_for_bb->exit_false; before_for_bb->exit_true = init_bb; before_for_bb->exit_false = nullptr; init_bb->exit_true = test_bb; init_bb->exit_false = nullptr; test_bb->exit_true = body_bb; test_bb->exit_false = after_for_bb; body_bb->exit_true = incr_bb; body_bb->exit_false = nullptr; incr_bb->exit_true = test_bb; incr_bb->exit_false = nullptr; cfg->current_bb = init_bb; initialization->build_ir(cfg); cfg->add_bb(init_bb); cfg->current_bb = test_bb; std::string test_result = condition->build_ir(cfg); cfg->current_bb->add_IRInstr(IRInstr::cmp_null, cfg->get_var_type(test_result), {test_result}); cfg->add_bb(test_bb); cfg->current_bb = body_bb; body->build_ir(cfg); cfg->add_bb(body_bb); cfg->current_bb = incr_bb; increment->build_ir(cfg); cfg->add_bb(incr_bb); cfg->current_bb = after_for_bb; cfg->add_bb(after_for_bb); return ""; // ?? } //////////////////////////////////////////////////////////////////////////////// // class CProgASTAssignment // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTAssignment::CProgASTAssignment( CProgASTIdentifier* identifier, CProgASTExpression* expression) : lhs_identifier(identifier), rhs_expression(expression) {} CProgASTAssignment::~CProgASTAssignment() { delete lhs_identifier; delete rhs_expression; } // ----------------------------------------------------- Public Member Functions std::string CProgASTAssignment::build_ir(CFG* cfg) const { std::string name = lhs_identifier->getText(); std::string init = rhs_expression->build_ir(cfg); if(!cfg->is_declared(name)) { Writer::error() << "use of undeclercqed identifier '" << name << "'" << std::endl; } cfg->initialize(name); cfg->current_bb->add_IRInstr(IRInstr::wmem, cfg->get_var_type(name), {name, init}); return name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTPrePP : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTPrePP::CProgASTPrePP(CProgASTExpression* expression) : inner_expression(expression) {} CProgASTPrePP::~CProgASTPrePP() { delete inner_expression; } // ----------------------------------------------------- Public Member Functions std::string CProgASTPrePP::build_ir(CFG* cfg) const { std::string exp_name = inner_expression->build_ir(cfg); cfg->current_bb->add_IRInstr(IRInstr::pre_pp, cfg->get_var_type(exp_name), {exp_name}); return exp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTPreMM : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTPreMM::CProgASTPreMM(CProgASTExpression* expression) : inner_expression(expression) {} CProgASTPreMM::~CProgASTPreMM() { delete inner_expression; } // ----------------------------------------------------- Public Member Functions std::string CProgASTPreMM::build_ir(CFG* cfg) const { std::string exp_name = inner_expression->build_ir(cfg); cfg->current_bb->add_IRInstr(IRInstr::pre_mm, cfg->get_var_type(exp_name), {exp_name}); return exp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTPostPP : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTPostPP::CProgASTPostPP(CProgASTExpression* expression) : inner_expression(expression) {} CProgASTPostPP::~CProgASTPostPP() { delete inner_expression; } // ----------------------------------------------------- Public Member Functions std::string CProgASTPostPP::build_ir(CFG* cfg) const { std::string exp_name = inner_expression->build_ir(cfg); Type result_type = cfg->get_var_type(exp_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::post_pp, result_type, {tmp_name, exp_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTPostMM : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTPostMM::CProgASTPostMM(CProgASTExpression* expression) : inner_expression(expression) {} CProgASTPostMM::~CProgASTPostMM() { delete inner_expression; } // ----------------------------------------------------- Public Member Functions std::string CProgASTPostMM::build_ir(CFG* cfg) const { std::string exp_name = inner_expression->build_ir(cfg); Type result_type = cfg->get_var_type(exp_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::post_mm, result_type, {tmp_name, exp_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTBAnd : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTBAnd::CProgASTBAnd(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTBAnd::~CProgASTBAnd() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTBAnd::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); Type result_type = cfg->get_max_type(lhs_name, rhs_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::band, result_type, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTBOr : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTBOr::CProgASTBOr(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTBOr::~CProgASTBOr() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTBOr::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); Type result_type = cfg->get_max_type(lhs_name, rhs_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::bor, result_type, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTBXor : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTBXor::CProgASTBXor(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTBXor::~CProgASTBXor() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTBXor::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); Type result_type = cfg->get_max_type(lhs_name, rhs_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::bxor, result_type, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTBNot : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTBNot::CProgASTBNot(CProgASTExpression* expression) : inner_expression(expression) {} CProgASTBNot::~CProgASTBNot() { delete inner_expression; } // ----------------------------------------------------- Public Member Functions std::string CProgASTBNot::build_ir(CFG* cfg) const { std::string exp_name = inner_expression->build_ir(cfg); Type result_type = cfg->get_var_type(exp_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::bnot, result_type, {tmp_name, exp_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTAnd : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTAnd::CProgASTAnd(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTAnd::~CProgASTAnd() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTAnd::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); cfg->current_bb->add_IRInstr(IRInstr::cmp_null, cfg->get_var_type(lhs_name), {lhs_name}); std::string tmp_name = cfg->create_new_tempvar(Type::INT_64); BasicBlock* test1_bb = cfg->current_bb; BasicBlock* then1_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* after_if1_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* else1_bb = new BasicBlock(cfg, cfg->new_BB_name()); after_if1_bb->exit_true = test1_bb->exit_true; after_if1_bb->exit_false = test1_bb->exit_false; then1_bb->exit_true = after_if1_bb; then1_bb->exit_false = nullptr; test1_bb->exit_true = then1_bb; test1_bb->exit_false = else1_bb; //then cfg->current_bb = then1_bb; { std::string rhs_name = rhs_operand->build_ir(cfg); cfg->current_bb->add_IRInstr(IRInstr::cmp_null, cfg->get_var_type(rhs_name), {rhs_name}); BasicBlock* test2_bb = cfg->current_bb; BasicBlock* then2_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* after_if2_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* else2_bb = new BasicBlock(cfg, cfg->new_BB_name()); after_if2_bb->exit_true = test2_bb->exit_true; after_if2_bb->exit_false = test2_bb->exit_false; then2_bb->exit_true = after_if2_bb; then2_bb->exit_false = nullptr; test2_bb->exit_true = then2_bb; test2_bb->exit_false = else2_bb; //then cfg->current_bb = then2_bb; cfg->current_bb->add_IRInstr(IRInstr::ldconst, Type::INT_64, {tmp_name, "1"}); cfg->add_bb(then2_bb); //else { cfg->current_bb = else2_bb; else2_bb->exit_true = after_if2_bb; else2_bb->exit_false = nullptr; else2_bb->add_IRInstr(IRInstr::ldconst, Type::INT_64, {tmp_name, "0"}); cfg->add_bb(else2_bb); } //after cfg->current_bb = after_if2_bb; cfg->add_bb(after_if2_bb); } cfg->add_bb(then1_bb); //else { cfg->current_bb = else1_bb; else1_bb->exit_true = after_if1_bb; else1_bb->exit_false = nullptr; cfg->current_bb->add_IRInstr(IRInstr::ldconst, Type::INT_64, {tmp_name, "0"}); cfg->add_bb(else1_bb); } //after cfg->current_bb = after_if1_bb; cfg->add_bb(after_if1_bb); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTOr : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTOr::CProgASTOr(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTOr::~CProgASTOr() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTOr::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); cfg->current_bb->add_IRInstr(IRInstr::cmp_null, cfg->get_var_type(lhs_name), {lhs_name}); std::string tmp_name = cfg->create_new_tempvar(Type::INT_64); BasicBlock* test1_bb = cfg->current_bb; BasicBlock* then1_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* after_if1_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* else1_bb = new BasicBlock(cfg, cfg->new_BB_name()); after_if1_bb->exit_true = test1_bb->exit_true; after_if1_bb->exit_false = test1_bb->exit_false; then1_bb->exit_true = after_if1_bb; then1_bb->exit_false = nullptr; test1_bb->exit_true = then1_bb; test1_bb->exit_false = else1_bb; //then cfg->current_bb = then1_bb; { cfg->current_bb->add_IRInstr(IRInstr::ldconst, Type::INT_64, {tmp_name, "1"}); } cfg->add_bb(then1_bb); //else { cfg->current_bb = else1_bb; else1_bb->exit_true = after_if1_bb; else1_bb->exit_false = nullptr; { std::string rhs_name = rhs_operand->build_ir(cfg); cfg->current_bb->add_IRInstr(IRInstr::cmp_null, cfg->get_var_type(rhs_name), {rhs_name}); BasicBlock* test2_bb = cfg->current_bb; BasicBlock* then2_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* after_if2_bb = new BasicBlock(cfg, cfg->new_BB_name()); BasicBlock* else2_bb = new BasicBlock(cfg, cfg->new_BB_name()); after_if2_bb->exit_true = test2_bb->exit_true; after_if2_bb->exit_false = test2_bb->exit_false; then2_bb->exit_true = after_if2_bb; then2_bb->exit_false = nullptr; test2_bb->exit_true = then2_bb; test2_bb->exit_false = else2_bb; //then cfg->current_bb = then2_bb; cfg->current_bb->add_IRInstr(IRInstr::ldconst, Type::INT_64, {tmp_name, "1"}); cfg->add_bb(then2_bb); //else { cfg->current_bb = else2_bb; else2_bb->exit_true = after_if2_bb; else2_bb->exit_false = nullptr; else2_bb->add_IRInstr(IRInstr::ldconst, Type::INT_64, {tmp_name, "0"}); cfg->add_bb(else2_bb); } //after cfg->current_bb = after_if2_bb; cfg->add_bb(after_if2_bb); } cfg->add_bb(else1_bb); } //after cfg->current_bb = after_if1_bb; cfg->add_bb(after_if1_bb); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTNot : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTNot::CProgASTNot(CProgASTExpression* expression) : inner_expression(expression) {} CProgASTNot::~CProgASTNot() { delete inner_expression; } // ----------------------------------------------------- Public Member Functions std::string CProgASTNot::build_ir(CFG* cfg) const { std::string exp_name = inner_expression->build_ir(cfg); Type result_type = cfg->get_var_type(exp_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::lnot, result_type, {tmp_name, exp_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTLessThan : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTLessThan::CProgASTLessThan(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTLessThan::~CProgASTLessThan() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTLessThan::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); std::string tmp_name = cfg->create_new_tempvar(Type::INT_64); cfg->current_bb->add_IRInstr(IRInstr::cmp_lt, Type::INT_64, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTLessThanOrEqual : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTLessThanOrEqual::CProgASTLessThanOrEqual(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTLessThanOrEqual::~CProgASTLessThanOrEqual() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTLessThanOrEqual::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); std::string tmp_name = cfg->create_new_tempvar(Type::INT_64); cfg->current_bb->add_IRInstr(IRInstr::cmp_le, Type::INT_64, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTGreaterThan : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTGreaterThan::CProgASTGreaterThan(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTGreaterThan::~CProgASTGreaterThan() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTGreaterThan::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); std::string tmp_name = cfg->create_new_tempvar(Type::INT_64); cfg->current_bb->add_IRInstr(IRInstr::cmp_gt, Type::INT_64, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTGreaterThanOrEqual : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTGreaterThanOrEqual::CProgASTGreaterThanOrEqual(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTGreaterThanOrEqual::~CProgASTGreaterThanOrEqual() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTGreaterThanOrEqual::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); std::string tmp_name = cfg->create_new_tempvar(Type::INT_64); cfg->current_bb->add_IRInstr(IRInstr::cmp_ge, Type::INT_64, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTEqual : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTEqual::CProgASTEqual(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTEqual::~CProgASTEqual() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTEqual::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); std::string tmp_name = cfg->create_new_tempvar(Type::INT_64); cfg->current_bb->add_IRInstr(IRInstr::cmp_eq, Type::INT_64, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTNotEqual : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTNotEqual::CProgASTNotEqual(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTNotEqual::~CProgASTNotEqual() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTNotEqual::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); std::string tmp_name = cfg->create_new_tempvar(Type::INT_64); cfg->current_bb->add_IRInstr(IRInstr::cmp_ne, Type::INT_64, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTAddition : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTAddition::CProgASTAddition(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTAddition::~CProgASTAddition() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTAddition::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); Type result_type = cfg->get_max_type(lhs_name, rhs_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::add, result_type, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTSubtraction : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTSubtraction::CProgASTSubtraction(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTSubtraction::~CProgASTSubtraction() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTSubtraction::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); Type result_type = cfg->get_max_type(lhs_name, rhs_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::sub, result_type, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTMultiplication : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTMultiplication::CProgASTMultiplication(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTMultiplication::~CProgASTMultiplication() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTMultiplication::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); Type result_type = cfg->get_max_type(lhs_name, rhs_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::mul, result_type, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTDivision : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTDivision::CProgASTDivision(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTDivision::~CProgASTDivision() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTDivision::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); Type result_type = cfg->get_max_type(lhs_name, rhs_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::div, result_type, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTModulo : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTModulo::CProgASTModulo(CProgASTExpression* lhs, CProgASTExpression* rhs) : lhs_operand(lhs), rhs_operand(rhs) {} CProgASTModulo::~CProgASTModulo() { delete lhs_operand; delete rhs_operand; } // ----------------------------------------------------- Public Member Functions std::string CProgASTModulo::build_ir(CFG* cfg) const { std::string lhs_name = lhs_operand->build_ir(cfg); std::string rhs_name = rhs_operand->build_ir(cfg); Type result_type = cfg->get_max_type(lhs_name, rhs_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::mod, result_type, {tmp_name, lhs_name, rhs_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTUnaryMinus : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTUnaryMinus::CProgASTUnaryMinus(CProgASTExpression* expression) : inner_expression(expression) {} CProgASTUnaryMinus::~CProgASTUnaryMinus() { delete inner_expression; } // ----------------------------------------------------- Public Member Functions std::string CProgASTUnaryMinus::build_ir(CFG* cfg) const { std::string exp_name = inner_expression->build_ir(cfg); Type result_type = cfg->get_var_type(exp_name); std::string tmp_name = cfg->create_new_tempvar(result_type); cfg->current_bb->add_IRInstr(IRInstr::neg, result_type, {tmp_name, exp_name}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTFunccall : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTFunccall::CProgASTFunccall(CProgASTIdentifier* identifier) : func_name(identifier) {} CProgASTFunccall::~CProgASTFunccall() { delete func_name; for(CProgASTExpression* arg : args) { delete arg; } } // ----------------------------------------------------- Public Member Functions void CProgASTFunccall::add_arg(CProgASTExpression* arg) { args.push_back(arg); } std::string CProgASTFunccall::build_ir(CFG* cfg) const { Type result_type; if (cfg->is_declared(func_name->getText())) { result_type = cfg->get_var_type(func_name->getText()); SymbolProperties sp = cfg->get_symbol_properties(func_name->getText()); if((sp.arg_types).size() > args.size()) { Writer::error() << "too few arguments to function '" << func_name->getText() << "'" << std::endl; } if((sp.arg_types).size() < args.size()) { Writer::error() << "too many arguments to function '" << func_name->getText() << "'" << std::endl; } } else { result_type = Type::INT_64; Writer::warning() << "implicit declaration of function '" << func_name->getText() << "'" << std::endl; } std::string tmp_name = ""; if (result_type != Type::VOID) { tmp_name = cfg->create_new_tempvar(result_type); } std::vector<std::string> params{tmp_name, func_name->getText()}; for(CProgASTExpression* arg : args) { params.push_back(arg->build_ir(cfg)); } cfg->current_bb->add_IRInstr(IRInstr::call, result_type, params); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTIntLiteral : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTIntLiteral::CProgASTIntLiteral(int64_t val) : value(val) {} // ----------------------------------------------------- Public Member Functions std::string CProgASTIntLiteral::build_ir(CFG* cfg) const { std::string tmp_name = cfg->create_new_tempvar(Type::INT_64); cfg->get_symbol_properties(tmp_name).initialized = true; std::string literal_str = std::to_string(value); cfg->current_bb->add_IRInstr(IRInstr::ldconst, Type::INT_64, {tmp_name, literal_str}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTCharLiteral : public CProgASTExpression // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTCharLiteral::CProgASTCharLiteral(const std::string &val) : value(val) {} // ----------------------------------------------------- Public Member Functions std::string CProgASTCharLiteral::build_ir(CFG* cfg) const { std::string tmp_name = cfg->create_new_tempvar(Type::CHAR); std::string literal_str; if (value.at(0) != '\\') literal_str = std::to_string(value.at(0)); else { switch (value.at(1)) { case 'a': literal_str = std::to_string(static_cast<unsigned int>('\a')); break; case 'b': literal_str = std::to_string(static_cast<unsigned int>('\b')); break; case 'f': literal_str = std::to_string(static_cast<unsigned int>('\f')); break; case 'n': literal_str = std::to_string(static_cast<unsigned int>('\n')); break; case 'r': literal_str = std::to_string(static_cast<unsigned int>('\r')); break; case 't': literal_str = std::to_string(static_cast<unsigned int>('\t')); break; case 'v': literal_str = std::to_string(static_cast<unsigned int>('\v')); break; case '\\': literal_str = std::to_string(static_cast<unsigned int>('\\')); break; case '\'': literal_str = std::to_string(static_cast<unsigned int>('\'')); break; case '"': literal_str = std::to_string(static_cast<unsigned int>('\"')); break; case '?': literal_str = std::to_string(static_cast<unsigned int>('\?')); break; } } cfg->current_bb->add_IRInstr(IRInstr::ldconst, Type::CHAR, {tmp_name, literal_str}); return tmp_name; } //////////////////////////////////////////////////////////////////////////////// // class CProgASTIdentifier // //////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------- Constructor / Destructor CProgASTIdentifier::CProgASTIdentifier(const std::string &identifier) : name(identifier) {} // ----------------------------------------------------- Public Member Functions std::string CProgASTIdentifier::getText() const { return name; } std::string CProgASTIdentifier::build_ir(CFG* cfg) const { if(!cfg->is_declared(name)) { Writer::error() << "use of undeclercqed identifier '" << name << "'" << std::endl; } else { if (!cfg->is_initialized(name)) { Writer::warning() << "use of uninitialized variable '" << name << "'" << std::endl; } cfg->set_used(name); } return name; }
true
496989217431fcd4398465546ba1f706749648d0
C++
CDAdkins/CS150
/zWeek13/SerendipityFinal/mainmenu.cpp
UTF-8
2,402
3.8125
4
[]
no_license
/* Serendipity Book Sellers Part 8 File Name:MainMenu.cpp Programmer: Chris Adkins Date Last Modified: 12/4/2019 CS 150 - Thursday 5:30PM Problem Statement: This program displays a main menu with the ability to show several other sub menus. As of right now there is some small logic used in order to allow the user to see every different menu but no functionality beyond that has been implemented yet aside from the cashier module. I have also added some input validation to check to see if the user enters a number outside the given parameters. The BookData class has been added which can hold some variables that let us keep track of the details of the book as well as the quantity and price. This particular revision of Serendipity took all of the loose code and placed it into properly named functions that are now called from main(). Overall Plan: 1. Display the main menu to the user. 2. Check the users input to determine what to show next. 3. Display the proper menu in regards to the user's input using switch statements. 4. Use while loops to validate the user's input, if the user enters anything that they shouldn't, then the program will loop and ask them to input again. */ #include <iostream> #include "cashier.h" #include "invmenu.h" #include "reports.h" #include "bookdata.h" using namespace std; int main() { int choice; // This value is set by the user when prompted. bool done = false; BookData books[20]; Cashier myCashier; InvMenu myInv; Reports myReports; cout << "Serendipity Booksellers\nMain Menu\n\n"; cout << "1. Cashier Module\n"; cout << "2. Inventory Database Module\n"; cout << "3. Report Module\n"; cout << "4. Print Books\n"; cout << "5. Exit\n\n"; cout << "Enter your choice: "; do { cout << "\nPlease enter a number between 1 - 5: "; cin >> choice; } while (choice < 1 || choice > 5); switch (choice) { case 1: { // Cashier myCashier.cashMain(); break; } case 2: { myInv.invMain(); break; } case 3: { myReports.reportMain(); break; } case 4: { cout << "Books In Array:"; int num = 1; for (BookData i : books) { i.insertBook(); i.setTitle("Book Number " + to_string(num)); cout << "\n" << i.getTitle(); num++; } break; } case 5: { cout << "Thank you for shopping Serendipity!"; break; } default: { cout << "\nPlease enter a number between 1 - 5"; } } }
true
7c6c1afa8a5c2397399210aebe532f7915aa9d15
C++
philipdongfei/DiscoveringModernCPP
/Chapter01/shared_ptr_simple.cc
UTF-8
368
3.25
3
[]
no_license
#include <memory> #include <iostream> #include <string> struct S { int i; std::string s; double d; S(int ii, std::string ss, double dd) { i = ii; s = ss; d = dd; } }; int main() { auto p = std::make_shared<S>(1,"Ankh Morpork", 4.65); std::cout << p->i << " " << p->s << " " << p->d << std::endl; return 0; }
true
1bb336de0f1885ce2a1f54a57deacbd0806985c4
C++
GabrielRavier/SmallPIM
/Menu.cpp
UTF-8
1,478
3.5625
4
[]
no_license
#include "Menu.h" #include <cctype> #include <iostream> #include <cstdlib> using std::tolower; using std::toupper; using std::string; using std::cin; using std::cout; using std::flush; /* Display a menu string and then allow user to enter a character from withing a string of choices. * If user enters a character not in the choices string, an error is printed and the user is prompted to try again. * * \param menu : String to be displayed * \param choices : Choices available to the user * \return After a valid character is entered, the selected character is returned ('\0' is returned in the case of an I/O error) * */ char Menu::getMenuSelection(const std::string& menu, const std::string& choices) { while (cin.good()) { cout << menu; char selection = '\0'; cin >> selection; if (cin.fail()) break; // Throw away rest of input line cin.ignore(INT_MAX, '\n'); // Search for selection in either uppercase and lowercase if (choices.find(toupper(selection)) != string::npos || choices.find(tolower(selection)) != string::npos) return toupper(selection); // Valid entry else cout << "Invalid selection, please try again.\n\n"; } return '\0'; } // Clear the screen void Menu::clearScreen() { system("cls"); } // Define m_menuStack member variable std::stack<Menu*> Menu::m_menuStack;
true
caf3e776a8761055022b85f8b19b786de7fa9183
C++
lehuyduc/Basic-System-Architecture
/Code/multifunction++/main.cpp
UTF-8
1,341
3
3
[]
no_license
#include <utils.h> #include <assembly.h> #include <compiler.h> #include <iostream> #include <vector> #include <map> #include <fstream> #include <deque> using namespace std; void fcfs(deque<PCB*> pcbs) { PCB *pcb; while (!pcbs.empty()) { pcb = pcbs.front(); pcbs.pop_front(); pcb->runAll(); } } void roundrobin(deque<PCB*> pcbs, int timeSlice) { PCB *pcb; while (!pcbs.empty()) { pcb = pcbs.front(); pcbs.pop_front(); pcb->runForMs(timeSlice); if (!pcb->finished()) pcbs.push_back(pcb); } } int main() { deque<PCB*> pcbs; PCB pcb1, pcb2, pcb3; Compiler compiler; compiler.compileFile("fibonacci.as", &pcb1); compiler.compileFile("gcd.as",&pcb2); compiler.compileFile("fibonacci2.as",&pcb3); cout << "\n\n***************TESTING FIRST-COME FIRST-SERVE***************\n\n"; pcbs.push_back(&pcb1); pcbs.push_back(&pcb2); pcbs.push_back(&pcb3); fcfs(pcbs); cout << "\n\n***************TESTING ROUND ROBIN***************\n\n"; compiler.compileFile("fibonacci.as", &pcb1); compiler.compileFile("gcd.as",&pcb2); compiler.compileFile("fibonacci2.as",&pcb3); pcbs.push_back(&pcb1); pcbs.push_back(&pcb2); pcbs.push_back(&pcb3); roundrobin(pcbs, 50); //cout << "Hello world!" << endl; return 0; }
true
bc38fed3516c4d6ce98d87c6df54c5fd85cde93b
C++
sourabbr/cpp_basics
/stl_maps_sets/src/main.cpp
UTF-8
2,079
3.578125
4
[]
no_license
#include "common.h" Void CountWords (ifstream &pFile); Void Display (const std::map <String, Int> &pWords1, const std::map <String, std::set <Int>> &pWords2); String CleanString (String &pStr); int main () { ifstream file; file.open ("../words.txt"); if (!file) { cerr << "Error in opening the file!!" << endl; return 1; } CountWords (file); file.close (); return 0; } Void CountWords (ifstream &pFile) { std::map <String, Int> words1; std::map <String, std::set <Int>> words2; String line {}; String word {}; Int line_count {0}; while (std::getline (pFile, line)) { line_count++; std::istringstream ss {line}; while (ss >> word) { word = CleanString (word); words1[word]++; words2[word].insert (line_count); } } Display (words1, words2); } Void Display (const std::map <String, Int> &pWords1, const std::map <String, std::set <Int>> &pWords2) { cout << "Part 1: " << endl; cout << std::setw (20) << std::left << "Words" << std::setw (5) << std::right << "Count" << endl; cout << "=========================" << endl; for (const auto pair: pWords1) { cout << std::setw (20) << std::left << pair.first << std::setw (5) << std::right << pair.second << endl; } cout << endl << endl; cout << "Part 2: " << endl; cout << std::setw (20) << std::left << "Words" << std::left << "Lines" << endl; cout << "=========================" << endl; for (const auto pair: pWords2) { cout << std::setw (20) << std::left << pair.first << std::left << "[ "; for (const auto i: pair.second) cout << i << " "; cout << "]" << endl; } } String CleanString (String &pStr) { String str {}; for (char c:pStr) { if (c == '.' || c == ',' || c == ';' || c == ':') continue; else str += c; } return str; }
true
f730b760c06757d68cfef74bc7b324c291fb8431
C++
KeioHigh-ElectronicsClub/quizJudgeController
/lib/quizControll/Test/TestRepository.h
UTF-8
837
2.84375
3
[]
no_license
#pragma once #include <Arduino.h> #include <vector> #include "domain/Recode/IResultRepository.h" #include "domain/Recode/Result.h" class TestRepository : public IResultRepository { public: TestRepository() {} ~TestRepository() {} bool init() { storage.clear(); return true; } bool store(std::unique_ptr<Recode> result) override { Data received; received.respondent = result->getRespondentNum(); received.isCorrect = result->getErratum() == Erratum::CORRECT; storage.push_back(received); return true; } bool storeResetRecode() { Serial.println("Reset"); } int getRespondent(int num) { return storage[num].respondent; } bool getIsCorrect(int num) { return storage[num].isCorrect; } private: struct Data { int respondent; bool isCorrect; }; std::vector<Data> storage; };
true
e5afdeac87d63b83429a63cce78ef3cf23a0f2ec
C++
cpuggal/Data-Structures
/cpp_learn/project/Birthday.h
UTF-8
248
2.515625
3
[]
no_license
#ifndef BIRTHDAY_H #define BIRTHDAY_H #include<iostream> using namespace std; class Birthday{ public: Birthday(int a, int b, int c); void print(); private: int month; int day; int year; }; #endif
true
36d73b7b8faac7179e4b2f59d19de83b8435b49d
C++
Oh-kyung-tak/Algorithm
/Baekjoon/baekjoon_2665.cpp
UTF-8
1,193
2.703125
3
[]
no_license
#include <iostream> #include <algorithm> #include <math.h> #include <queue> using namespace std; struct pos { int x; int y; int cnt; }; bool map[51][51]; bool visited[51][51][101]; int darkroom[51][51]; int dx[4] = { -1,0,0,1 }; int dy[4] = { 0,-1,1,0 }; int n; void check() { queue<pos> q; q.push({ 1,1,0 }); visited[1][1][0] = true; while (!q.empty()) { int x = q.front().x; int y = q.front().y; int cnt = q.front().cnt; q.pop(); for (int i = 0; i < 4; i++) { int xx = x + dx[i]; int yy = y + dy[i]; if (xx > 0 && yy > 0 && xx <= n && yy <= n && !visited[xx][yy][cnt]) { if (darkroom[xx][yy] == 0 || darkroom[xx][yy] > cnt) { if (map[xx][yy] == 1) { visited[xx][yy][cnt] = true; darkroom[xx][yy] = cnt; q.push({ xx,yy,cnt }); } else { visited[xx][yy][cnt + 1] = true; darkroom[xx][yy] = cnt + 1; q.push({ xx,yy, cnt + 1 }); } } } } } } int main() { cin >> n; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) scanf("%1d", &map[i][j]); check(); for (int i = 0; i <= 101; i++) { if (visited[n][n][i]) { printf("%d\n", i); break; } } }
true
48c872097d8dda6c09dd3cc3998fbbb89a66d3ae
C++
yungzyad/224FinalProject
/Reader.hpp
UTF-8
760
2.671875
3
[]
no_license
// // Reader.hpp // 224FinalProject // // Created by Zyad Gomaa on 11/10/17. // Copyright © 2017 Zyad Gomaa. All rights reserved. // #ifndef Reader_hpp #define Reader_hpp #include "User.hpp" #include <stdio.h> #include <string> #include <vector> using namespace std; #endif /* Reader_hpp */ class Reader: public User{ private: int maxCopies; int penalties; string copyBorrowed; string copyReserved; public: //Accessor Initalization int getMaxCopies(); int getPenalties(); vector<string> getCopiesBorrowed(); vector<string> getCopiesReserved(); //Mutator Initialization void setMaxCopies(int max); void setPenalties(int pen); void setCopiesBorrowed(string copyB); void setCopiesReserved(string copyR); };
true
b135045886a4d89d4f32a6e8e884019d0dde9cb8
C++
cfoytek/DVSim
/include/Packet.h
UTF-8
1,049
2.75
3
[]
no_license
//This class defines a packet. Each packet has a packet type: 0 for DVPacket //1 for Data Packet. If the packet is a DV packet, the packet will contain //the sender's Routing Table. Each packet also has an original sender and //destination field. These are used by the nodes to route the packet to the //proper destination. #ifndef PACKET_H #define PACKET_H #include "defines.h" #include "RoutingTableEntry.h" #include <vector> #include <utility> class Packet { private: int packetType; int sourceNode; int destNode; bool traceMe; struct DVUpdateEntry { int destNode; int cost; }; typedef std::vector<DVUpdateEntry> DVUpdateTable; DVUpdateTable dvTable; int DVUpdateTableSize; public: Packet(int type, int source, int dest); Packet(int type, int source, int dest, bool isTracked); void addDVUpdateEntry(int destNode, int cost); int getPacketType(); int getSourceNode(); int getDestNode(); int getDVUPdateTableSize(); bool isTrackedPacket(); std::pair<int, int> getDVEntryPair(int entryIndex); }; #endif
true
41913d79c685318248fc4c20b0e2a4232407fca4
C++
ImuraYasuaki/TimerCore
/Timer_Core/Classes/Utilities/pathutil.h
UTF-8
779
2.71875
3
[]
no_license
// // pathutil.h // Timer_Core // // Created by myuon on 2014/11/30. // Copyright (c) 2014年 yasu. All rights reserved. // #pragma once #ifndef Timer_Core_pathutil_h #define Timer_Core_pathutil_h #include <sys/stat.h> namespace pathutil { bool isExistsPath(const char *path) { struct stat buffer; int result = stat(path, &buffer); return result != -1; } bool isExistsPath(const std::string &path) { return isExistsPath(path.c_str()); } bool createDirectory(const std::string &path) { if (path.empty()) { return false; } if (isExistsPath(path)) { return false; } int result = mkdir(path.c_str(), 0777); return result == 0; } } #endif
true
bef493ce5e616e9be7382c1f8c295bdf0a3839ec
C++
marioviti/RayCharles
/src/Texture.h
UTF-8
707
2.546875
3
[]
no_license
#ifndef TEXTURE_H #define TEXTURE_H #include "src/Vec3.h" #include <vector> //#include <iostream> #include <GL/glew.h> //Always in this order! #include <GL/gl.h> //glew before gls class Texture { private: int w; int h; GLuint handleIndex; int bindIndex; int new_bind_idx(); unsigned char *imageTexture; std::vector<Vec3> vecImageTexture; public: Texture(){}; int static bilinear_filter; int static bind_index_gen; Vec3 evalue(float u, float v); // will return the pixel value from u,v coords void load_texture(std::string& filename); int get_bindIndex() const {return bindIndex;}; GLuint get_handleIndex() const {return handleIndex;}; }; #endif
true
420968775c8da31e2f861849c6cfe959d257ae0d
C++
JuanFerInc/Prog-4
/3_lab5/lab_5/Header/CtrlProducto.h
UTF-8
3,318
2.84375
3
[]
no_license
#ifndef CTRLPRODUCTO_H #define CTRLPRODUCTO_H #include <iostream> #include <set> #include <map> #include "../Header/IProducto.h" #include "../Header/Comida.h" #include "../Header/DtProducto.h" #include "../Header/DtMenu.h" #include "../Header/DtProductoMenu.h" using namespace std; class CtrlProducto :public IProducto { private: static CtrlProducto* instance; //DtProducto infoProducto; DtMenu infoMenu; string codigo; string descripcion; int precio; set<DtProductoMenu> infoMP; map<string, Comida*> coleccionDeComida; CtrlProducto(){} public: static CtrlProducto* getInstance(); //Alta Producto //retorna true sii este contiene al menos un producto bool masDeUnProducto(); //Ingresa los datos del nuevo producto que se ingresara al sistema //Pre: No existe producto con el mismo codigo //Post: El Sistema Recuerda lot atributos del Producto void agregarProducto(string codigo, string descripcion, int precio); ////Ingresa al sistema el nuevo producto //Pre: El sistema tiene los datos del nuevo producto //Post: Se almacena en la memoria del sistema un nuevo instancia del producto void aceptarAltaProducto(); // Se libera la memoria del sistema asociada al nuevo producto //Pre: El sistema tiene los datos del nuevo producto //Post: El sistema no tiene los datos del unevo producto void cancelarAltaProducto(); //Ingresa los datos del nuevo menu que se ingresa al sistema //Pre: No existe instancia de menu con el mismo codigo en el sistema //Post: El sistema recuerda los datos del menu set<DtProducto*> agregarMenu(string codigo, string descripcion); //Ingresa al sistema los productos que seran asociado al menu //Pre: Existe producto con el codigo ingresado //Post: El sistema recuerda el producto seleccionado void agregarProductoMenu(string codigo, int cantidad); //Ingresa al sistema el nuevo menu y los esocia con los productos que corresponde //Pre: El sistema tiene almacenado los datos del Meny y los productos con los que sera asociaco meditna el identificador codigo y la cantidad //de dicho producto que estan en el menu //Post: Se crea en la memoria del sistema una nueva instancia de Menu y se asocia con todos los productos que corresponda. //Tambien el sistme olvida todo lo recordado en este caso de uso. void aceptarAltaMenu(); //Libera la memoria del sistema asociada al menu y los productos //Pre: El sistema tiene almacenado los datos del Menu y los productos con los que sera asociado mediante el identificador //codigo y la cantidad de dicho producto que estan en el menu //Post: El sistema olvida los datos del Menu y los productos recordad. void cancelarAltaMenu(); //Baja de Producto set<DtComida*> listaDeComidaDisponible(); void ingresarCodigo(string codigo); void cancelarBaja(); void confirmarBaja(); Comida *pedirComida(string codigo); //Informacion de un producto //retorna true si existe la comida bool existeComida(string codigo); //retorna un DtMenuVentas o un DtProductoVentas que contiene la cantidad de comidas que se vendieron //el nombre de la funcion esta mal, tenemos que arreglar //funcion del caso de uso Informacion de un producto DtComida* ingresarCodigoParaInfo(); //carga los datos pedido por el profe void agregarDatosPredef(); void quitarMenu(string codigo); }; #endif
true
e3f642cc51bcd60ffa3bb293c5718279fafafa0a
C++
chenyu1927/hello-world
/NetWork/Base/MutexLock.hpp
UTF-8
770
3.046875
3
[]
no_license
#ifndef MUTEX_LOCK_H_H #define MUTEX_LOCK_H_H #include<pthread.h> #include<boost/noncopyable.hpp> class MutexLock { public: MutexLock(){ ::pthread_mutex_init(&mutex_, NULL); } ~MutexLock(){ ::pthread_mutex_destroy(&mutex_); } int lock(){ return ::pthread_mutex_lock(&mutex_); } int unlock(){ return ::pthread_mutex_unlock(&mutex_); } pthread_mutex_t* getMutexLock() { return &mutex_; } private: pthread_mutex_t mutex_; }; class MutexGuard : boost::noncopyable { public: MutexGuard(MutexLock& mutex) : lock_(mutex) { lock_.lock(); } ~MutexGuard(){ lock_.unlock(); } MutexLock& getMutexLock(){ return lock_; } private: MutexLock& lock_; }; #define MUTEX_GUARD(OBJ, LOCK) MutexGuard OBJ(LOCK) #endif /* MUTEX_LOCK_H_H */
true
6db327d5376445fa65ebfbfad536f036430031fb
C++
zouxianyu/query-pdb
/thirdparty/raw_pdb/src/Examples/ExampleContributions.cpp
UTF-8
3,374
2.515625
3
[ "BSD-2-Clause", "MIT" ]
permissive
// Copyright 2011-2022, Molecular Matters GmbH <office@molecular-matters.com> // See LICENSE.txt for licensing details (2-clause BSD License: https://opensource.org/licenses/BSD-2-Clause) #include "Examples_PCH.h" #include "ExampleTimedScope.h" #include "PDB_RawFile.h" #include "PDB_DBIStream.h" namespace { // we don't have to store std::string in the contributions, since all the data is memory-mapped anyway. // we do it in this example to ensure that we don't "cheat" when reading the PDB file. memory-mapped data will only // be faulted into the process once it's touched, so actually copying the string data makes us touch the needed data, // giving us a real performance measurement. struct Contribution { std::string objectFile; uint32_t rva; uint32_t size; }; } void ExampleContributions(const PDB::RawFile& rawPdbFile, const PDB::DBIStream& dbiStream); void ExampleContributions(const PDB::RawFile& rawPdbFile, const PDB::DBIStream& dbiStream) { TimedScope total("\nRunning example \"Contributions\""); // in order to keep the example easy to understand, we load the PDB data serially. // note that this can be improved a lot by reading streams concurrently. // prepare the image section stream first. it is needed for converting section + offset into an RVA TimedScope sectionScope("Reading image section stream"); const PDB::ImageSectionStream imageSectionStream = dbiStream.CreateImageSectionStream(rawPdbFile); sectionScope.Done(); // prepare the module info stream for matching contributions against files TimedScope moduleScope("Reading module info stream"); const PDB::ModuleInfoStream moduleInfoStream = dbiStream.CreateModuleInfoStream(rawPdbFile); moduleScope.Done(); // read contribution stream TimedScope contributionScope("Reading section contribution stream"); const PDB::SectionContributionStream sectionContributionStream = dbiStream.CreateSectionContributionStream(rawPdbFile); contributionScope.Done(); std::vector<Contribution> contributions; { TimedScope scope("Storing contributions"); const PDB::ArrayView<PDB::DBI::SectionContribution> sectionContributions = sectionContributionStream.GetContributions(); const size_t count = sectionContributions.GetLength(); contributions.reserve(count); for (const PDB::DBI::SectionContribution& contribution : sectionContributions) { const uint32_t rva = imageSectionStream.ConvertSectionOffsetToRVA(contribution.section, contribution.offset); if (rva == 0u) { printf("Contribution has invalid RVA\n"); continue; } const PDB::ModuleInfoStream::Module& module = moduleInfoStream.GetModule(contribution.moduleIndex); contributions.push_back(Contribution { module.GetName().Decay(), rva, contribution.size }); } scope.Done(count); } TimedScope sortScope("std::sort contributions"); std::sort(contributions.begin(), contributions.end(), [](const Contribution& lhs, const Contribution& rhs) { return lhs.size > rhs.size; }); sortScope.Done(); total.Done(); // log the 20 largest contributions { printf("20 largest contributions:\n"); const size_t countToShow = std::min<size_t>(20ul, contributions.size()); for (size_t i = 0u; i < countToShow; ++i) { const Contribution& contribution = contributions[i]; printf("%zu: %u bytes from %s\n", i + 1u, contribution.size, contribution.objectFile.c_str()); } } }
true
2c047d1f5517ef2eb52b004ddfe7c7efd63890c4
C++
javed2214/BitMasking
/Remove-Duplicates-From-Str.cpp
UTF-8
477
3.453125
3
[]
no_license
// Remove Duplicates from String in O(n) time and O(1) Space // https://www.geeksforgeeks.org/remove-duplicates-from-a-string-in-o1-extra-space/ #include<bits/stdc++.h> using namespace std; int main(){ string str="geeksforgeeks"; int n=str.length(); int counter=0,p=0; for(int i=0;i<n;i++){ int x=str[i]-'a'; if((counter & (1 << x)) == 0){ str[p++]=str[i]; counter = counter | (1 << x); } } cout<<str.substr(0,p); return 0; }
true
4a311d45e577a70e0ca3f39d3f39cfd377586f57
C++
Schorsch0815/rccarlights
/SimpleRcCarLightController.h
UTF-8
3,455
2.875
3
[]
no_license
/*-------------------------------------------------------------------- * This file is part of the RcCarLights arduino application. * * RcCarLights 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. * * RcCarLights 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 RcCarLights. If not, see <http://www.gnu.org/licenses/>. * * Copyright: Jochen Schales 2014 * * --------------------------------------------------------------------*/ #ifndef SIMPLERCCARLIGHTCONTROLLER_H_ #define SIMPLERCCARLIGHTCONTROLLER_H_ #include "AbstractRcCarLightController.h" #include "LightSwitchBehaviour.h" /** * Simple implementation of a RcCarLight output class * * This class uses 6 pins to control the lights for parking, headlights, brake, backup light, right and left blinker. * * The used pins have to passed in the right order to the constructor and the loop method will set these pins to HIGH * according the light status passed. */ class SimpleRcCarLightController : public AbstractRcCarLightController { public: /** * Constructor * @param pinParkingLight specifies pin used for parking light * @param pinHeadlight specifies pin used for headlight * @param pinRightBlinker specifies pin used for right blinker * @param pinLeftBlinker specifies pin used for left blinker * @param pinBackUpLight specifies pin used for back up light * @param pinBrakeLight specifies pin used for brake light */ SimpleRcCarLightController(int pPinParkingLight, int pPinHeadlight, int pPinRightBlinker, int pPinLeftBlinker, int pPinBackUpLight, int pPinBrakeLight); /** * configures the required pins for OUTPUT. * * The method has to be called during setup */ void setupPins(void); /** * allows to add a behavior for a specific light type. The SimpleRcCarLightControllor only support a behavior for the headlights. * * @param pLightType lights type where a behavior should be assigned * @param pLightSwitchBehaviour behavior, which influences the light switching */ void addBehaviour(LightType_t pLightType, LightSwitchBehaviour *pLightSwitchBehaviour); /** * sets the configured pins according to the light status * @param pLightStatus current light status */ void loop(CarLightsStatus_t pLightStatus); private: /** * set the headlights depending on the given light status * * @param pHeadlightStatus true if head lights should be turned on, false otherwise */ void setHeadlights(bool pHeadlightStatus); private: // pin for parking lights int mPinParkingLight; // pin for headlights int mPinHeadlight; // pin for right blinker int mPinRightBlinker; // pin for left blinker int mPinLeftBlinker; // pin for backup lights int mPinBackUpLight; // pin or brake lights int mPinBrakeLight; LightSwitchBehaviour *mHeadlightBehaviour; }; #endif /* SIMPLERCCARLIGHTCONTROLLER_H_ */
true
7dcf58b52cc0e5988df99f59b4decd49f4890934
C++
USNavalResearchLaboratory/simdissdk
/Testing/SimCore/CoreCommonTest.cpp
UTF-8
3,690
2.5625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
/* -*- mode: c++ -*- */ /**************************************************************************** ***** ***** ***** Classification: UNCLASSIFIED ***** ***** Classified By: ***** ***** Declassify On: ***** ***** ***** **************************************************************************** * * * Developed by: Naval Research Laboratory, Tactical Electronic Warfare Div. * EW Modeling & Simulation, Code 5773 * 4555 Overlook Ave. * Washington, D.C. 20375-5339 * * License for source code is in accompanying LICENSE.txt file. If you did * not receive a LICENSE.txt with this code, email simdis@nrl.navy.mil. * * The U.S. Government retains all rights to use, duplicate, distribute, * disclose, or release this software. * */ #include <cstdio> #include <cmath> #include <stdexcept> #include "simCore/Common/Exception.h" #include "simCore/Common/Version.h" #include "simCore/Common/SDKAssert.h" namespace { int testFailure() { int rv = 0; rv += SDK_ASSERT(rv == 0); rv += SDK_ASSERT(SDK_ASSERT(rv == 0) == 0); // Note: Expected test failure text printed to output on this failure rv += SDK_ASSERT(SDK_ASSERT(rv == 1) != 0); return rv; } // Helper function to return number of decimals (characters) for a given integer int numDecimals(int value) { if (value == 0) return 1; // '0' // log10 will return [0.0,1.0) for [1,10]. static_cast to int and add 1 to round up. Account for negative symbol return 1 + static_cast<int>(log10(static_cast<double>(std::abs(value)))) + (value < 0 ? 1 : 0); } int testVersion() { int rv = 0; rv += SDK_ASSERT(simCore::majorVersion() == simCore::SDKVERSION_MAJOR); rv += SDK_ASSERT(simCore::minorVersion() == simCore::SDKVERSION_MINOR); rv += SDK_ASSERT(simCore::revisionVersion() == simCore::SDKVERSION_REVISION); rv += SDK_ASSERT(simCore::soVersion() == simCore::SDKVERSION_SOVERSION); // Form the build string in a different manner from the typical code to ensure it matches expectations // Uses C - stdio on purpose to provide different formatting path to validate answer char versionString[256]; // 2 places for decimal, then use log10 to determine number of digits for each value const int expectedRv = 2 + numDecimals(simCore::majorVersion()) + numDecimals(simCore::minorVersion()) + numDecimals(simCore::revisionVersion()); // sprintf returns number of characters printed rv += SDK_ASSERT(expectedRv == sprintf(versionString, "%d.%d.%d", simCore::majorVersion(), simCore::minorVersion(), simCore::revisionVersion())); rv += SDK_ASSERT(simCore::versionString() == versionString); return rv; } int testException() { int rv = 0; // Create 2 classes of exceptions: STD one, and Unknown one class StdException : public std::logic_error { public: explicit StdException(const std::string& what) : std::logic_error(what) {} }; class UnknownException { public: UnknownException() {} }; // Throw each exception using the SAFETRYBEGIN/SAFETRYEND syntax (use SAFETRYCATCH to macro this) SAFETRYCATCH(throw StdException("Purposefully thrown"), "and successfully caught"); SAFETRYCATCH(throw UnknownException(), "and successfully caught"); return rv; } } int CoreCommonTest(int argc, char* arv[]) { int rv = 0; rv += SDK_ASSERT(testFailure() == 0); rv += SDK_ASSERT(testVersion() == 0); rv += SDK_ASSERT(testException() == 0); return rv; }
true
a41304ce662ba6b6a109fe561d76650e942ee0d0
C++
16131zzzzzzzz/Homework202001
/3-9/ex5.cpp
UTF-8
2,962
3.84375
4
[]
no_license
#include <iostream> using namespace std; class IntegerSet{ private: int k[101]; public: IntegerSet() { for(int i = 0;i < 101;++i) { k[i] = 0; } } IntegerSet(int*,int); void inputSet(); void printSet() const; bool isEqualTo(IntegerSet) const; void insertElement(int); IntegerSet unionOfSets(IntegerSet) const; IntegerSet intersectionOfSets(IntegerSet) const; void deleteElement(int); }; IntegerSet::IntegerSet(int* num,int n){ for (int i = 0; i < n; ++i) { k[num[i]] = 1; } } void IntegerSet::inputSet(){ int inp = 0; cout << "Enter an element ('-1' to end) :"; cin >> inp; while (inp != -1){ k[inp] = 1; cout << "Enter an element ('-1' to end) :"; cin >> inp; } cout << "Entry complete\n"; cout << endl; } void IntegerSet::printSet() const{ cout << "{ "; for (int i = 0; i < 101; ++i){ if(k[i] == 1) { cout << i << " "; } } cout << "}" << endl; } bool IntegerSet::isEqualTo(IntegerSet a)const{ for (int i = 0; i < 101; ++i){ if(k[i] != a.k[i]) { return 0; } } return 1; } void IntegerSet::insertElement(int n){ k[n] = 1; } IntegerSet IntegerSet::unionOfSets(IntegerSet a) const{ IntegerSet added = a; for (int i = 0; i < 101; ++i) { if(k[i] == 1) { added.k[i] = 1; } } return added; } IntegerSet IntegerSet::intersectionOfSets(IntegerSet a)const{ IntegerSet iso; for (int i = 0; i < 101; ++i){ if(a.k[i] == 1 && this -> k[i] == 1){ iso.k[i] = 1; } } return iso; } void IntegerSet::deleteElement(int n) { if(k[n] == 1){ k[n] = 0; } else{ cout << "Invalid insert attempted!" << endl; } } void printEqual(bool a){ if(a == 1){ cout << "A is equal to B\n"; } else{ cout << "A is not equal to B\n"; } } int main() { IntegerSet A; IntegerSet B; IntegerSet C; cout << "Enter set A:\n"; A.inputSet(); cout << "Enter set B:\n"; B.inputSet(); cout << "Union of A and B is:\n"; C = A.unionOfSets(B); C.printSet(); cout << "intersection of A and B is:\n"; C = A.intersectionOfSets(B); C.printSet(); printEqual(A.isEqualTo(B)); cout << endl; cout << "insert 77 into set A...\n"; A.insertElement(77); cout << "Set A is now :\n"; A.printSet(); cout << endl; cout << "delete 77 from A...\n"; A.deleteElement(77); cout << "Set A is now :\n"; A.printSet(); A.deleteElement(101); A.deleteElement(50); const int arraySize = 10; int intArray[arraySize] = {25,67,2,9,99,105,45,-5,101,1}; IntegerSet e(intArray,arraySize); cout << "\nSet e is:\n"; e.printSet(); cout << endl; return 0; }
true
46771d310a261e333f6593d47d611828fed5f96f
C++
billpugh/microcontroller
/fadeTest/fadeTest.ino
UTF-8
1,590
2.625
3
[]
no_license
#include <Adafruit_NeoPixel.h> #include <hsv2rgb.h> #include "RNLightsNeoPixel.h" #define PIN 18 void p(char *fmt, ... ){ char tmp[256]; // resulting string limited to 128 chars va_list args; va_start (args, fmt ); vsnprintf(tmp, 256, fmt, args); va_end (args); Serial.print(tmp); } // Parameter 1 = number of pixels in strip // Parameter 2 = pin number (most are valid) // Parameter 3 = pixel type flags, add together as needed: // NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) // NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) // NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) // NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) Adafruit_NeoPixel strip = Adafruit_NeoPixel(24, PIN, NEO_GRB + NEO_KHZ800); RNLightsNeoPixel lights = RNLightsNeoPixel(strip); int16_t pos = 0; CHSV hsv; CRGB rgb; void setup() { Serial.begin(115200); Serial.println("Starting"); hsv.s = 255; hsv.v = 255; delay(5000); Serial.println("Go"); } unsigned long lastUpdate = 0; void loop() { unsigned long ms = millis(); hsv.h = (ms/10)%256; hsv2rgb_rainbow(hsv,rgb); lights.fadeMultiply(220); lights.setPixelColor(pos, rgb.r, rgb.g, rgb.b); pos = lights.normalize(pos+1); if (0) { int b = (ms/10) % 512; if (b <= 256) lights.setBrightness(b); else lights.setBrightness(512-b); } unsigned long time = lights.show(); if (lastUpdate + 5000 < ms) { p("%d usecs to copy\n", time); lastUpdate = ms; } delay(1000 / 24); }
true
98fd92cfac42c7fed5306a46e2dbc7726df6a0c1
C++
TalPat/rubik
/app/src/Rubik.cpp
UTF-8
2,622
2.96875
3
[]
no_license
#include "Rubik.hpp" Rubik::Rubik(char *str) { input = str; tokens = lexer.lex(input); } Rubik::~Rubik() { } bool Rubik::validTokens(void) { // must be 1 or 2 in length // first char must be either "FRLBUD" // second characer must be either "'2" std::string target1 = "FRBLUD"; std::string target2 = "'2"; for (std::string str : tokens) { if (str.length() == 0 || str.length() > 2 || target1.find(str[0]) == std::string::npos) { throw ""; } if (str.length() == 2 && target2.find(str[1]) == std::string::npos) { throw ""; } } } void Rubik::execute(std::vector<std::string> instructions) { CubeSurface surface; Rotations rotation; for (std::string str : instructions) { switch (str[0]) { case 'F': surface = front; if (str.length() == 1) { rotation = clockwise; } else { if (str[1] == '2') rotation = twice; else rotation = anticlock; } break; case 'R': surface = right; if (str.length() == 1) { rotation = clockwise; } else { if (str[1] == '2') rotation = twice; else rotation = anticlock; } break; case 'B': surface = back; if (str.length() == 1) { rotation = clockwise; } else { if (str[1] == '2') rotation = twice; else rotation = anticlock; } break; case 'L': surface = left; if (str.length() == 1) { rotation = clockwise; } else { if (str[1] == '2') rotation = twice; else rotation = anticlock; } break; case 'U': surface = up; if (str.length() == 1) { rotation = clockwise; } else { if (str[1] == '2') rotation = twice; else rotation = anticlock; } break; case 'D': surface = down; if (str.length() == 1) { rotation = clockwise; } else { if (str[1] == '2') rotation = twice; else rotation = anticlock; } break; default: throw ""; break; } if (cube.isSolved(cube.getCubeState())) { std::cout << "Complete" << std::endl; } else { std::cout << "incomplete" << std::endl; } cube.rotate(surface, rotation); } cube.printCube(); } void Rubik::solve(void) { std::vector<std::string> solutionString; // solver.solve(0, cube.getCubeState(), solutionString); solver.solveWhiteCross(0, cube.getCubeState(), solutionString); solver.solveWhiteCorners(0, cube.getCubeState(), solutionString); solver.solveCorners(0, cube.getCubeState(), solutionString); solver.printSolution(); } std::vector<std::string> Rubik::getTokens(void) { return (tokens); }
true
7d3895561929c0caca0f78f4ea9ebbcd225d1ba2
C++
esra33/CppPatternsTutorials
/PatternsTutorial/CBinaryTreeIterator.cpp
UTF-8
2,047
3.0625
3
[]
no_license
#include <cstring> #include "CBinaryTreeIterator.h" #include "CBinaryTree.h" template <class T> CBinaryTreeIterator<T>::CBinaryTreeIterator(CBinaryTree<T>* binaryTree, CBinaryTreeIterator* parent, int index) : m_index(index), m_Status(0), m_BinaryTree(binaryTree) { m_NextNodes = new CBinaryTreeIterator*[3]; memset(m_NextNodes, 0, 3*sizeof(CBinaryTreeIterator*)); m_NextNodes[2] = parent; } template <class T> CBinaryTreeIterator<T>::~CBinaryTreeIterator() { delete [] m_NextNodes; } template <class T> CBinaryTreeIterator<T>* CBinaryTreeIterator<T>::CreateBinaryTree(int idx) { if(m_BinaryTree != NULL && idx < m_BinaryTree->Size()) { T* wrapper; m_BinaryTree->GetItem(idx, &wrapper); if((*wrapper) != NULL) { return new CBinaryTreeIterator(m_BinaryTree, this, idx); } } return NULL; } template <class T> bool CBinaryTreeIterator<T>::HasNext() { while(m_Status < 2) { if(m_NextNodes[m_Status] != NULL) { return true; } else { int idx = m_Status == 0? m_index*2 + 1 : 2*(m_index + 1); CBinaryTreeIterator* newNode = CreateBinaryTree(idx); if(newNode != NULL) { m_NextNodes[m_Status] = newNode; } else { ++m_Status; } } } if(m_NextNodes[m_Status] != NULL) return m_NextNodes[m_Status]->HasNext(); else return false; } template <class T> IIterator<T>* CBinaryTreeIterator<T>::Next() { while(m_Status < 2) { if(m_NextNodes[m_Status] != NULL) { ++m_Status; return m_NextNodes[m_Status - 1]; } else { int idx = m_Status == 0? m_index*2 + 1 : 2*(m_index + 1); CBinaryTreeIterator* newNode = CreateBinaryTree(idx); if(newNode != NULL) { m_NextNodes[m_Status] = newNode; ++m_Status; return m_NextNodes[m_Status - 1]; } } ++m_Status; } if(m_NextNodes[m_Status] != NULL) { m_Status = 0; return m_NextNodes[2]->Next(); } return NULL; } template <class T> T* CBinaryTreeIterator<T>::GetCurrent() { if(m_BinaryTree != NULL) { T* value; if(m_BinaryTree->GetItem(m_index, &value)) { return value; } } }
true
87308ec95916c460642b4bfdb846b709331c60ee
C++
punipuni21/competitive-programming
/AtCoder/ABC/ABC001-50/ABC027/A.cpp
UTF-8
381
2.984375
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { std::vector<int> array(4); int n = 0; for(int i = 0; i < 3 ; i++){ cin >> array[i]; } sort(array.begin(),array.end()); if(array[1] == array[2]){ n = array[3]; } if(array[2] == array[3]){ n = array[1]; } cout << n << endl; // your code goes here return 0; }
true