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
9c08e0fe319f84176498477b532db75d06d313e6
C++
Mp5A5/c--primer-plus
/chapter14-reusing/private.cpp
UTF-8
751
3.40625
3
[]
no_license
#include <iostream> using namespace std; class SuperClass { private: void private_call() { cout << "super private call" << endl; } public: SuperClass(/* args */){}; ~SuperClass(){}; void say() { cout << "super say..." << endl; } }; class SubClass : protected SuperClass { private: /* data */ public: SubClass(/* args */){}; ~SubClass(){}; void myName() { cout << "sub myName" << endl; // say(); SuperClass &sup = *this; sup.say(); } // void say() // { // SuperClass::say(); // } using SuperClass::say; }; int main(int argc, char const *argv[]) { SubClass sub; // sub.myName(); sub.say(); return 0; }
true
4d42377b46cd4b1dc81b824cbba39cb340724790
C++
jaronho/project_memory_monitor
/logger/Logger.cpp
UTF-8
3,043
2.859375
3
[]
no_license
/********************************************************************** * Author: jaron.ho * Date: 2019-08-25 * Brief: 日志模块 **********************************************************************/ #include "Logger.h" #include <fstream> #include <iostream> #include <mutex> #ifdef __linux #include <syslog.h> #endif void writeLog(const std::string& path, const std::string& filename, const std::string& content) { std::cout << content << std::endl; static std::mutex sMutex; static std::ofstream sFstream; static std::string sFullFilePath; sMutex.lock(); std::string fullFilePath = path + filename; if (sFullFilePath != fullFilePath) { if (sFstream.is_open()) { sFstream.close(); } sFstream.open(fullFilePath, std::ios_base::out | std::ios_base::app); } if (sFstream.is_open()) { sFstream << content << std::endl; sFstream.flush(); } sMutex.unlock(); } Logger::Logger(void) { mSysLogOpened = false; mPath = ""; } Logger::~Logger(void) { if (mSysLogOpened) { #ifdef __linux closelog(); #endif } } Logger* Logger::getInstance(void) { static Logger* instance = nullptr; if (nullptr == instance) { instance = new Logger(); } return instance; } std::string Logger::header(std::string& filename, const std::string& tag, bool withTag, bool withTime) { time_t now; time(&now); struct tm t = *localtime(&now); char file[13] = { 0 }; strftime(file, sizeof(file), "%Y%m%d.log", &t); char date[22] = { 0 }; strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", &t); std::string hdr; if (withTime) { hdr += "["; hdr += date; hdr += "]"; } if (withTag) { hdr += "["; hdr += tag; hdr += "]"; } filename = file; return hdr; } void Logger::openSyslog(const std::string& ident) { if (mSysLogOpened) { return; } mSysLogOpened = true; #ifdef __linux openlog(ident.c_str(), LOG_PID | LOG_CONS, LOG_USER); #endif } void Logger::writeSyslog(const std::string& content) { if (!mSysLogOpened) { return; } #ifdef __linux syslog(LOG_DEBUG, "%s", content.c_str()); #endif } void Logger::setPath(const std::string& path) { mPath = path; } void Logger::setFilename(const std::string& filename) { mFilename = filename; } std::string Logger::print(const std::string& content, const std::string& tag, bool withTag, bool withTime) { std::string filename; std::string hdr = header(filename, tag, withTag, withTime); writeLog(mPath, mFilename.empty() ? filename : mFilename, hdr + " " + content); return hdr; } std::string Logger::printSyslog(const std::string& content, const std::string& tag) { std::string filename; std::string hdr = header(filename, tag, true, true); std::string buff = hdr + " " + content; writeLog(mPath, mFilename.empty() ? filename : mFilename, buff); writeSyslog(tag + " " + content); return hdr; }
true
512ffc34bd7e6091b870e6f82cc9965cec518a53
C++
jhashivam1996/problem_solving
/dynamic_programing/coin_combinations.cpp
UTF-8
621
3.3125
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; int wayOfCoinChange(int *denominations, int amount) { int combinations[amount + 1]; memset(combinations, 0, sizeof(combinations)); combinations[0] = 1; for (int i = 0; i < 3; i++) { for (int j = 1; j < amount + 1; j++) { if (j >= denominations[i]) { combinations[j] += combinations[j - denominations[i]]; } } } return combinations[amount]; } int main() { int denominations[] = {1, 2, 5}; cout << wayOfCoinChange(denominations, 5); return 0; }
true
3c2adce3ba2b0e50d43649e4e8263a4fedde779d
C++
RaviKim/CentDir
/CPlusTest.d/dailyPractice.d/0202.d/itervector.cpp
UTF-8
284
3.15625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int ari[] = {1, 2, 3, 4, 5}; vector<int> vi(&ari[0], &ari[5]); vector<int> :: iterator it; for(it = vi.begin() ; it!=vi.end(); it++) { cout << *it << endl; cout << "Address : " << &*it << endl; } }
true
615f4d3c69f8119c1563bc6f5a8e02d63a5cbba0
C++
Diegores14/CompetitiveProgramming
/Lightoj/1204 - Weird Advertisement/solution.cpp
UTF-8
2,304
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int n, k; const int tam = 30000; struct node { int count, sum; node *left, *right; node(): count(0), sum(0), left(NULL), right(NULL) {} }; struct edge { int x, y1, y2, value; bool operator <(const edge & other) { return x < other.x; } } lines[2*tam]; void update(node* &p, int b, int e, int l, int r, int val, int up) { if(r < b || e < l) return; if(!p) p = new node(); int mid = (b+e)>>1; if(l <= b && e <= r) { p->count += val; if(p->count + up >= k) {p->sum = (e - b + 1); } else { p->sum = 0; if(p->left){ update(p->left, b, mid, l, r, 0, p->count + up); p->sum += p->left->sum; } if(p->right){ update(p->right, mid+1, e, l, r, 0, p->count + up); p->sum += p->right->sum; } } } else { update(p->left, b, mid, l, r, val, p->count + up); update(p->right, mid+1, e, l, r, val, p->count + up); if(p->count + up >= k) { p->sum = (e - b + 1); return ; } p->sum = 0; if(p->left) p->sum += p->left->sum; if(p->right) p->sum += p->right->sum; } } int main() { //ios_base::sync_with_stdio(false); cin.tie(NULL); int t, x1, x2, y1, y2; scanf("%d", &t); for(int cases = 1; cases <= t; cases++) { scanf("%d %d", &n, &k); int j = 0; for(int i = 0; i < n; i++) { scanf("%d %d %d %d", &x1, &y1, &x2, &y2); x2++; y2++; lines[j].x = x1; lines[j].y1 = y1; lines[j].y2 = y2; lines[j++].value = 1; lines[j].x = x2; lines[j].y1 = y1; lines[j].y2 = y2; lines[j++].value = -1; } sort(lines, lines+j); long long ans = 0; long long dx = lines[0].x; node *root = new node(); for(int i = 0; i < j; i++) { ans += (lines[i].x - dx) * root->sum; dx = lines[i].x; update(root, 0, 1e9, lines[i].y1, lines[i].y2 - 1, lines[i].value, 0); } printf("Case %d: %lld\n", cases, ans); } return 0; }
true
32a941d51c7daa1a41aff7fef1899907a9c31401
C++
kingkk31/BOJ
/source code/12813_이진수 연산.cpp
UTF-8
844
2.765625
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include <list> #include <algorithm> #include <utility> #pragma warning (disable:4996) using namespace std; int main(void) { string a, b; cin >> a >> b; for (int i = 0; i < a.length(); i++) printf("%d", ((int)(a[i] - '0')) & ((int)(b[i] - '0'))); printf("\n"); for (int i = 0; i < a.length(); i++) printf("%d", ((int)(a[i] - '0')) | ((int)(b[i] - '0'))); printf("\n"); for (int i = 0; i < a.length(); i++) printf("%d", ((int)(a[i] - '0')) ^ ((int)(b[i] - '0'))); printf("\n"); for (int i = 0; i < a.length(); i++) { if((int)(a[i] - '0')) printf("0"); else printf("1"); } printf("\n"); for (int i = 0; i < b.length(); i++) { if ((int)(b[i] - '0')) printf("0"); else printf("1"); } printf("\n"); return 0; }
true
5d071ea781284eee826337074f9c8fb734f32521
C++
jchan1e/graphics
/second_semester/examples/ex26/ex26.cpp
UTF-8
13,727
2.671875
3
[]
no_license
/* * nBody Simulator * This program requires OpenGL 3.2 or above * * Demonstrates using OpenMP and OpenCL to accelerate computations and * displaying the result in OpenGL * * Key bindings: * m/M Cycle through modes * a Toggle axes * arrows Change view angle * PgDn/PgUp Zoom in and out * 0 Reset view angle * ESC Exit */ #include "CSCIx239.h" #include "InitCL.h" int N=8192; // Number of bodies size_t nloc=1; // Number of local work threads int src=0; // Offset of star positions int axes=0; // Display axes int th=0; // Azimuth of view angle int ph=0; // Elevation of view angle double dim=10; // Size of universe double spd=1; // Relative speed double mass=2; // Relative mass int mode=0; // Solver mode int shader=0; // Shader const char* text[] = {"Sequential","OpenMP","OpenCL"}; // RGB Color class class Color { public: float r,g,b; Color() { r = g = b = 0; } Color(float R,float G,float B) { r = R; g = G; b = B; } }; // float3 class // Killer fact: OpenCL doesn't have a real float3, it is an alias for float4 // So the C++ float3 MUST pad out with a dummy w value class float3 { public: float x,y,z,w; float3(void) { x = y = z = w = 0; } float3(float X,float Y,float Z) { x = X; y = Y; z = Z; w = 0; } inline float3& operator+=(const float3& v) {x+=v.x;y+=v.y;z+=v.z; return *this;} }; // float3 operators inline float3 operator+(const float3& v1 , const float3& v2) {return float3(v1.x+v2.x , v1.y+v2.y , v1.z+v2.z);} // v1+v2 inline float3 operator-(const float3& v1 , const float3& v2) {return float3(v1.x-v2.x , v1.y-v2.y , v1.z-v2.z);} // v1-v2 inline float operator*(const float3& v1 , const float3& v2) {return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;} // v1*v2 inline float3 operator*(float f , const float3& v) {return float3(f*v.x , f*v.y , f*v.z);} // f*v // Position, velocity and color float3* pos[]={NULL,NULL}; float3* vel=NULL; float* M=NULL; Color* col=NULL; // OpenCL constants cl_device_id devid; cl_context context; cl_command_queue queue; cl_program prog; cl_kernel kernel; cl_mem Dpos[2],Dvel,Dm; /* * Advance time one time step for star k */ void Move(float3 pos0[],float3 pos1[],int k) { // Position of this star float3 X = pos0[k]; float dt = 1e-3; // Calculate force components float3 F; for (int i=0;i<N;i++) { float3 D = pos0[i] - X; float d = sqrt(D*D)+1; // Add 1 to d to dampen movement F += M[i]/(d*d*d)*D; // Normalize and scale to 1/r^2 } // Update velocity vel[k] += dt*F; // Set new position pos1[k] = X + dt*vel[k]; } /* * Advance time one time step for star k */ const char* source = "__kernel void Move(__global const float3 pos0[],__global float3 pos1[],__global float3 vel[],__global const float M[],const int N) \n" "{ \n" " int k = get_global_id(0); \n" " float3 X = pos0[k]; \n" " float dt = 1e-3; \n" " float3 F = (float3)(0,0,0); \n" " for (int i=0;i<N;i++) \n" " { \n" " float3 D = pos0[i] - X; \n" " float d = sqrt(dot(D,D))+1; \n" " F += M[i]/(d*d*d)*D; \n" " } \n" " vel[k] += dt*F; \n" " pos1[k] = X + dt*vel[k]; \n" "} \n" ; /* * Advance time one time step */ void Step() { int k; // Destination is 1-src; int dst = 1-src; // Sequential if (mode==0) { for (k=0;k<N;k++) Move(pos[src],pos[dst],k); } // OpenMP else if (mode==1) { #pragma omp parallel for for (k=0;k<N;k++) Move(pos[src],pos[dst],k); } // OpenCL else { // Set parameters for kernel if (clSetKernelArg(kernel,0,sizeof(Dvel),&Dpos[src])) Fatal("Cannot set kernel parameter Dpos0\n"); if (clSetKernelArg(kernel,1,sizeof(Dvel),&Dpos[dst])) Fatal("Cannot set kernel parameter Dpos1\n"); if (clSetKernelArg(kernel,2,sizeof(Dvel),&Dvel)) Fatal("Cannot set kernel parameter Dvel\n"); if (clSetKernelArg(kernel,3,sizeof(Dm) ,&Dm)) Fatal("Cannot set kernel parameter Dm\n"); if (clSetKernelArg(kernel,4,sizeof(int) ,&N)) Fatal("Cannot set kernel parameter N\n"); // Queue kernel size_t Global[1] = {(size_t)N}; size_t Local[1] = {nloc}; if (clEnqueueNDRangeKernel(queue,kernel,1,NULL,Global,Local,0,NULL,NULL)) Fatal("Cannot run kernel\n"); // Wait for kernel to finish if (clFinish(queue)) Fatal("Wait for kernel failed\n"); // Copy pos from device to host (block until done) if (clEnqueueReadBuffer(queue,Dpos[dst],CL_TRUE,0,N*sizeof(float3),pos[dst],0,NULL,NULL)) Fatal("Cannot copy pos from device to host\n"); } // Set new source src = dst; } /* * Scaled random value */ float rand1(float S) { return S*exp(rand()/RAND_MAX); } float3 rand3(float S) { float d = 2; float3 v(0,0,0); while (d>1) { v.x = rand()/(0.5*RAND_MAX)-1; v.y = rand()/(0.5*RAND_MAX)-1; v.z = rand()/(0.5*RAND_MAX)-1; d = v.x*v.x+v.y*v.y+v.z*v.z; } return S*v; } /* * Initialize Nbody problem */ void InitLoc() { int k; Color color[3]; color[0] = Color(1.0,1.0,1.0); color[1] = Color(1.0,0.9,0.5); color[2] = Color(0.5,0.9,1.0); // Allocate room for twice as many bodies to facilitate ping-pong pos[0] = (float3*)malloc(N*sizeof(float3)); if (!pos[0]) Fatal("Error allocating memory for %d stars\n",N); pos[1] = (float3*)malloc(N*sizeof(float3)); if (!pos[1]) Fatal("Error allocating memory for %d stars\n",N); vel = (float3*)malloc(N*sizeof(float3)); if (!vel) Fatal("Error allocating memory for %d stars\n",N); M = (float*)malloc(N*sizeof(float)); if (!M) Fatal("Error allocating memory for %d stars\n",N); col = (Color*)malloc(N*sizeof(Color)); if (!col) Fatal("Error allocating memory for %d stars\n",N); // Assign random locations for (k=0;k<N;k++) { pos[0][k] = rand3(dim/2); vel[k] = rand3(spd); col[k] = color[k%3]; M[k] = rand1(mass); } // Initialize src src = 0; } /* * OpenGL (GLUT) calls this routine to display the scene */ void display() { const double len=2.5; // Length of axes double Ex = -2*dim*Sin(th)*Cos(ph); double Ey = +2*dim *Sin(ph); double Ez = +2*dim*Cos(th)*Cos(ph); // Erase the window and the depth buffer glClear(GL_COLOR_BUFFER_BIT); // Undo previous transformations glLoadIdentity(); // Perspective - set eye position gluLookAt(Ex,Ey,Ez , 0,0,0 , 0,Cos(ph),0); // Integrate Step(); // Set shader glUseProgram(shader); int id = glGetUniformLocation(shader,"star"); if (id>=0) glUniform1i(id,0); id = glGetUniformLocation(shader,"size"); if (id>=0) glUniform1f(id,0.1); glBlendFunc(GL_ONE,GL_ONE); glEnable(GL_BLEND); // Draw stars using vertex arrays glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(3,GL_FLOAT,sizeof(float3),pos[src]); glColorPointer(3,GL_FLOAT,sizeof(Color),col); // Draw all stars glDrawArrays(GL_POINTS,0,N); // Disable vertex arrays glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); // Unset shader glUseProgram(0); glDisable(GL_BLEND); // Draw axes glDisable(GL_LIGHTING); glColor3f(1,1,1); if (axes) { glBegin(GL_LINES); glVertex3d(0.0,0.0,0.0); glVertex3d(len,0.0,0.0); glVertex3d(0.0,0.0,0.0); glVertex3d(0.0,len,0.0); glVertex3d(0.0,0.0,0.0); glVertex3d(0.0,0.0,len); glEnd(); // Label axes glRasterPos3d(len,0.0,0.0); Print("X"); glRasterPos3d(0.0,len,0.0); Print("Y"); glRasterPos3d(0.0,0.0,len); Print("Z"); } // Display parameters glWindowPos2i(5,5); Print("FPS=%d Angle=%d,%d Mode=%s", FramesPerSecond(),th,ph,text[mode]); // Render the scene and make it visible ErrCheck("display"); glFlush(); glutSwapBuffers(); } /* * GLUT calls this routine when an arrow key is pressed */ void special(int key,int x,int y) { // Right arrow key - increase angle by 5 degrees if (key == GLUT_KEY_RIGHT) th += 5; // Left arrow key - decrease angle by 5 degrees else if (key == GLUT_KEY_LEFT) th -= 5; // Up arrow key - increase elevation by 5 degrees else if (key == GLUT_KEY_UP) ph += 5; // Down arrow key - decrease elevation by 5 degrees else if (key == GLUT_KEY_DOWN) ph -= 5; // Keep angles to +/-360 degrees th %= 360; ph %= 360; // Tell GLUT it is necessary to redisplay the scene glutPostRedisplay(); } /* * GLUT calls this routine when a key is pressed */ void key(unsigned char ch,int x,int y) { int mode0 = mode; // Exit on ESC if (ch == 27) exit(0); // Cycle modes else if (ch == 'm') mode = (mode+1)%3; else if (ch == 'M') mode = (mode+2)%3; // Reset view angle else if (ch == '0') th = ph = 0; // Toggle axes else if (ch == 'a' || ch == 'A') axes = 1-axes; // Initialize pos and vel on device (block until done) if (mode==2 && mode0!=2) { if (clEnqueueWriteBuffer(queue,Dpos[src],CL_TRUE,0,N*sizeof(float3),pos[src],0,NULL,NULL)) Fatal("Cannot copy pos from host to device\n"); if (clEnqueueWriteBuffer(queue,Dvel,CL_TRUE,0,N*sizeof(float3),vel,0,NULL,NULL)) Fatal("Cannot copy vel from host to device\n"); if (clEnqueueWriteBuffer(queue,Dm,CL_TRUE,0,N*sizeof(float),M,0,NULL,NULL)) Fatal("Cannot copy M from host to device\n"); } // Initiaize vel on host (block until done) else if (mode!=2 && mode0==2) { if (clEnqueueReadBuffer(queue,Dvel,CL_TRUE,0,N*sizeof(float3),vel,0,NULL,NULL)) Fatal("Cannot copy vel from device to host\n"); } // Tell GLUT it is necessary to redisplay the scene glutPostRedisplay(); } /* * GLUT calls this routine when the window is resized */ void reshape(int width,int height) { int fov=55; // Field of view (for perspective) // Ratio of the width to the height of the window double asp = (height>0) ? (double)width/height : 1; // Set the viewport to the entire window glViewport(0,0, width,height); // Set projection Project(fov,asp,dim); } /* * GLUT calls this routine when the window is resized */ void idle() { // Tell GLUT it is necessary to redisplay the scene glutPostRedisplay(); } // // Create Shader Program including Geometry Shader // int CreateShaderProgGeom() { // Create program int prog = glCreateProgram(); // Compile and add shaders CreateShader(prog,GL_VERTEX_SHADER ,"nbody.vert"); #ifdef __APPLE__ // OpenGL 3.1 for OSX CreateShader(prog,GL_GEOMETRY_SHADER_EXT,"nbody.geom_ext"); glProgramParameteriEXT(prog,GL_GEOMETRY_INPUT_TYPE_EXT ,GL_POINTS); glProgramParameteriEXT(prog,GL_GEOMETRY_OUTPUT_TYPE_EXT ,GL_TRIANGLE_STRIP); glProgramParameteriEXT(prog,GL_GEOMETRY_VERTICES_OUT_EXT,4); #else // OpenGL 3.2 adds layout () CreateShader(prog,GL_GEOMETRY_SHADER,"nbody.geom"); #endif CreateShader(prog,GL_FRAGMENT_SHADER,"nbody.frag"); // Link program glLinkProgram(prog); // Check for errors PrintProgramLog(prog); // Return name return prog; } /* * Initialize OpenCL */ void InitCL() { cl_int err; // Initialize OpenCL nloc = InitGPU(1,devid,context,queue); // Allocate memory for array on device Dpos[0] = clCreateBuffer(context,CL_MEM_READ_WRITE,N*sizeof(float3),NULL,&err); Dpos[1] = clCreateBuffer(context,CL_MEM_READ_WRITE,N*sizeof(float3),NULL,&err); Dvel = clCreateBuffer(context,CL_MEM_READ_WRITE,N*sizeof(float3),NULL,&err); Dm = clCreateBuffer(context,CL_MEM_WRITE_ONLY,N*sizeof(float) ,NULL,&err); if (err) Fatal("Cannot create array on device\n"); // Compile kernel prog = clCreateProgramWithSource(context,1,&source,0,&err); if (err) Fatal("Cannot create program\n"); if (clBuildProgram(prog,0,NULL,NULL,NULL,NULL)) { char log[1048576]; if (clGetProgramBuildInfo(prog,devid,CL_PROGRAM_BUILD_LOG,sizeof(log),log,NULL)) Fatal("Cannot get build log\n"); else Fatal("Cannot build program\n%s\n",log); } kernel = clCreateKernel(prog,"Move",&err); if (err) Fatal("Cannot create kernel\n"); } /* * Start up GLUT and tell it what to do */ int main(int argc,char* argv[]) { // Initialize GLUT glutInit(&argc,argv); // Request double buffered, true color window with Z buffering at 600x600 glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutInitWindowSize(600,600); glutCreateWindow("Nbody Simulator"); #ifdef USEGLEW // Initialize GLEW if (glewInit()!=GLEW_OK) Fatal("Error initializing GLEW\n"); if (!GLEW_VERSION_2_0) Fatal("OpenGL 2.0 not supported\n"); #endif // Set callbacks glutDisplayFunc(display); glutReshapeFunc(reshape); glutSpecialFunc(special); glutKeyboardFunc(key); glutIdleFunc(idle); // Initialize stars InitLoc(); // Initialize OpenCL InitCL(); // Shader program shader = CreateShaderProgGeom(); ErrCheck("init"); // Star texture LoadTexBMP("star.bmp"); // Pass control to GLUT so it can interact with the user glutMainLoop(); return 0; }
true
ab9a26b8e54b27debe31ce421d14a055ce1420fe
C++
Kam-Sergei/PNRPU
/2 семестр/Лабораторные/Лабораторная 18.1/Lab1_main.cpp
UTF-8
1,550
3.1875
3
[]
no_license
#include<iostream> #include"fraction.h" using namespace std; fraction make_fraction(double F, double S) { fraction t; t.Init(F, S); return t; } int main() { fraction A; A.Init(0.4,0.3); A.Show(); cout << "A.hipotenuse(" << A.first << "," << A.second << ")=" << A.hipotenuse() << endl<<endl; fraction B; B.Read(); B.Show(); cout << "B.hipotenuse(" << B.first << "," << B.second << ")=" << B.hipotenuse() << endl<<endl; fraction* X = new fraction; X->Init(2.0, 5); X->Show(); X->hipotenuse(); cout << "X.hipotenuse(" << X->first <<","<<X->second<<") = "<<X->hipotenuse() <<endl<<endl; fraction mas[3]; for (int i = 0; i < 3; i++ ) mas[i].Read(); for (int i = 0; i < 3; i++) mas[i].Show(); for (int i = 0; i < 3; i++) { mas[i].hipotenuse(); cout << "mas[" << i << "].hipotenuse(" << mas[i].first << "," << mas[i].second << ")="; cout << mas[i].hipotenuse() << endl; } cout << endl; fraction* p_mas = new fraction[3]; for (int i = 0; i < 3; i++) p_mas[i].Read(); for (int i = 0; i < 3; i++) p_mas[i].Show(); for (int i = 0; i < 3; i++) { p_mas[i].hipotenuse(); cout << "p_bass[" << i << "].hipotenuse(" << p_mas[i].first << "," << p_mas[i].second; cout << ")=" << p_mas[i].hipotenuse() << endl; } cout << endl; double y; double z; cout << "first?"; cin >> y; cout << "second?"; cin >> z; fraction F = make_fraction(y, z); F.Show(); cout << "F.hipotenuse(" << F.first << "," << F.second << ") = " << F.hipotenuse() << endl; return 0; }
true
c9468273584adcca2d6a0b6a7a7b9115da340a4f
C++
chenditc/hackathon_2014
/simulator.cpp
UTF-8
2,935
3.234375
3
[]
no_license
#include "simulator.h" #include <algorithm> #include <assert.h> struct StateComp { bool operator() (const game_state &lhs, const game_state &rhs) { return lhs.getScore() > rhs.getScore(); } } stateComp; board_point Simulator::getBestMove() { // stateContainer.push_back(gameState); simulateAllMyMove(gameState); // calculate the score in all condition for(StateContainer::iterator it = stateContainer.begin(); it != stateContainer.end(); it++) { it->calcualteScore(); } // sort the container using comparator sort(stateContainer.begin(), stateContainer.end(), stateComp); // return the move that can lead to best situation. assert(stateContainer.size() > 0); assert(stateContainer.at(0).getScore() >= stateContainer.back().getScore()); stateContainer.at(0).logInfo(); return stateContainer.at(0).nextMove; } void Simulator::simulateAllMyMove(const game_state &oldGameState) { // calcualte the legal move for my side and call simuate on that player for (int i = 0; i < oldGameState.legal_moves.size(); i++) { game_state newGameState = placeMove(oldGameState, i, me.myPlayerNum) ; // put all generated game_state into container stateContainer.push_back(newGameState); } // assume wait stateContainer.push_back(wait(oldGameState, me.myPlayerNum)); } void Simulator::simulateAllHisMove() { // TODO: calcualte the legal move for my side and call simulate on that player // TODO: put all generated game_state into container } void updateBoard(vector< vector< vector<int> > > &board, int x, int y, int z, int side) { if(board[x][y][z] != side && board[x][y][z] != 0) assert("trying to update something not legal"); if (z > 0) { updateBoard(board, x+1, y, z-1, side); updateBoard(board, x, y+1, z-1, side); updateBoard(board, x, y , z-1, side); } board[x][y][z] = side; } // create a new game state and put a new move on specific point game_state Simulator::placeMove(const game_state &gameState, const int nextPoint, const int side) { game_state result = gameState; board_point next = gameState.legal_moves.at(nextPoint); // place move result.board[next.x][next.y][next.z] = side; // update all points under it. updateBoard(result.board, next.x, next.y, next.z, side); // take out tokens result.your_tokens -= next.z + 1; result.nextMove = next; // update legal move result.updateLegalMovesAndEmptyCount(); return result; } game_state Simulator::wait(const game_state &gameState, const int side) { game_state result = gameState; result.your_tokens++; result.updateLegalMovesAndEmptyCount(); result.nextMove = {256, 256, 256}; return result; }
true
5c580a3bceaa1da272f94d2484aaf4122b4e83a3
C++
jehalladay/CS1-Fundamental-of-Computer-Science
/Assignments/assign4/images/HDDB.cpp
UTF-8
6,714
2.828125
3
[ "MIT" ]
permissive
/********************************************************************************************* * Implementation program for Practicum 8 by Sherine and CSCI 111 student: * ****************************************************************** * Filename: HDDB.cpp * By. James Halladay * Project: week 15 Assignment #4 * Login: jehalladay * Assignment No: 4 * File Description: * * Creates all the functions used in the A4main.cpp file * * I declare that all material in this assessment task is my work * except where there is clear acknowledgement * or reference to the work of others. I further declare that I * have complied and agreed to the CMU Academic Integrity Policy * at the University website. * * Author�s Name: James Halladay UID(700#): 700425363 * Date: 4/30/2020 * * Date Last Modified: 4/30/2020 ******************************************************************* */ #include <iostream> #include <fstream> #include <string.h> using namespace std; #include "HDDB.h" const int MAXDB = 100; struct disc { char* title; char* director; int year; int runtime; char* genre; char* pic; }; typedef disc* discPtr; discPtr DB[MAXDB]; bool selected[MAXDB]; int numDB; void HTMLGen(); void YearFilter() { int low, high; bool correct; do { cout << "Please enter a range of years to select items." << endl; cout << "Filter video database from: "; cin >> low; cout << " to "; cin >> high; cout << endl; cin.ignore(100,'\n'); correct = low < high && low > 1900; if(!correct) { cout << "correct: " << correct << endl; cout << "Input not recognized, please try again." << endl; }; } while(!correct); for (int i=0;i<numDB;i++) { if(DB[i]->year >= low && DB[i]->year <= high) { selected[i] = true; }; }; HTMLGen(); } void GenreFilter() { int choice; bool correct; char selection[20]; do { cout << "Filter video database on\n" << "1. Action \n" << "2. Adventure \n" << "3. Animation \n" << "4. Comedy \n" << "5. Drama \n" << "6. Fantasy \n" << "7. Horror \n" << "8. Music \n" << "9. Science-Fiction \n" << "10. Western \n" << "\nWhich Genre do you prefer? "; cin >> choice; cin.ignore(100,'\n'); correct = choice < 11 && choice > 0; if(!correct) { cout << "Input not recognized, please try again." << endl; }; } while(!correct); switch (choice) { case 1: strcpy(selection, "Action"); break; case 2: strcpy(selection, "Adventure"); break; case 3: strcpy(selection, "Animation"); break; case 4: strcpy(selection, "Comedy"); break; case 5: strcpy(selection, "Drama"); break; case 6: strcpy(selection, "Fantasy"); break; case 7: strcpy(selection, "Horror"); break; case 8: strcpy(selection, "Music"); break; case 9: strcpy(selection, "Science-Fiction"); break; case 20: strcpy(selection, "Western"); }; for (int i=0;i<numDB;i++) { // cout << DB[i]->genre << endl; // cout << "comparison:\t" << (strcmp(selection, DB[i]->genre) == 0) << endl; if(strcmp(selection, DB[i]->genre) == 0) { selected[i] = true; // cout << "Match" << endl; }; }; HTMLGen(); } void TimeFilter() { int time; bool correct; do { cout << "Please enter a maximum runtime to filter the results." << endl; cin >> time; cout << "minutes" << endl; cin.ignore(100,'\n'); correct = time > 0; if(!correct) { cout << "Input not recognized, please try again." << endl; }; } while(!correct); for (int i=0;i<numDB;i++) { if(DB[i]->runtime >= time) { selected[i] = true; } } HTMLGen(); } void DisplayAll() { for (int i=0;i<numDB;i++) { selected[i] = true; } HTMLGen(); } void LoadDB() { //variable to contain the input char fname[100], temp[256], ch; ifstream ifs; cout << "Please provide file name: "; //this getline argument gets target and size cin.getline(fname, 100, '\n'); // open the file ifs.open(fname); if(!ifs.is_open()) { cerr<<"Could not find/open said file, sorry!"<<endl; exit(1); }; // we have a file read to read //initialize array index to 0 numDB = 0; ifs.getline(temp, 255, '\n'); while(!ifs.eof()) { //process what we have read from the HDDB.txt //Title DB[numDB] = new disc;\ //database, number in our Database, Title pointer is changed from pointer to new data DB[numDB] -> title = new char[strlen(temp)+1]; strcpy(DB[numDB]->title, temp); ifs >> DB[numDB]->year; //reading gennre requires memory allocation ifs >> temp; DB[numDB]->genre = new char[strlen(temp)+1]; strcpy(DB[numDB]->genre, temp); // no dynamic memory is required to read runtime ifs >> DB[numDB]->runtime; // read picture requires dynamic memory ifs >> temp; DB[numDB]->pic = new char [strlen(temp)+1]; strcpy(DB[numDB]->pic, temp); // do { ifs>>ch; // } while (isspace(ch)); // cout << "\ndata in ch:\t" << ch << endl; ifs.getline(temp, 255, '\n'); DB[numDB]->director = new char[strlen(temp)+2]; DB[numDB]->director[0]=ch; strcpy(&DB[numDB]->director[1], temp); cout << "numDB:\t" << numDB << "\tDirector:\t" << DB[numDB]->director << endl; numDB++; ifs.getline(temp, 255, '\n'); }; ifs.close(); cout << "Read: " << numDB << " Video titles. " << endl; }; void ClearDB() { for(int i = 0; i < MAXDB; i++) { delete DB[i]->title; delete DB[i]->director; delete DB[i]->genre; delete DB[i]->pic; delete DB[i]; }; } void HTMLGen() { char fname[256]; ofstream ofs; cout << "Output file name: "; cin.getline(fname,255,'\n'); ofs.open(fname); if (!ofs.is_open()) { cerr << "Could not open output file " << fname << endl; exit(1); } ofs << "<html>\n" << "<body>\n"; for(int i = 0; i < numDB; i++) { ofs << "<p><img src=\"images/" << DB[i]->pic << "\" align = left hspace=12>\n" << "<b>Title:</b>" << DB[i]->title <<"</p>\n" << "<p><b>Director: </b> " << DB[i]->director << "</p>\n" << "<p><b>Year: </b> " << DB[i]->year << "</p>\n" << "<p><b>Running Time: </b> " << DB[i]->runtime << " minutes</p>\n" << "<p>Genre: <b></b> " << DB[i]->genre << "</p>\n" << "<p>&nbsp;</p>\n" << "<HR> \n"; }; ofs << "</body>\n" << "</html>\n"; ofs.close(); }
true
cd335d5a4903022baac03ba0b80996f90e51eb07
C++
zzDeagle545zz/CSC-5
/Lecture/Lecture_gCh5_sCh4/main.cpp
UTF-8
3,098
3.140625
3
[]
no_license
/* * File: main.cpp * Author: Christopher Garcia * * Created on January 26, 2016, 5:25 PM */ #include <iostream> #include <cstring> using namespace std; int main(int argc, char** argv) { /*Functions * fstream library * * modular programming * breaking the program into smaller pieces * short blocks 50 lines and 80 colums * easy to debugg * Function call excutes * * function definition * return type * parameter list name body * * void doesnt return value * Call a fucntion use the name with (); * * Function Prototypes * placed at the top and just defined * return values can return one piece of information * void function name(int); prototype * void function name (int num); actual function * function name (variable); call * * return statemets should be at the bottom unless it is a short * * * returning a boolean should be called a is... * * * static local variables \ * keeps the value after leaving * like a global variable * static trouble shooting * * Default arguments * are declared in the name * * project * use all the constructs * all data types * validation * write to a file * random numbers * flowchart * write up * libraries * global constants * string * char array * write and read * instruction from a file * * reference Varibles as Parameteres * can change ithe varrible from the function * returning more than one value * not a copy * must be a variable * copy is faster reference is slower * for primative data types * void getfunction(int&, Int&); reference * doesnt have to return changes the value * can return more values in theory * return is only one number * const int can protect reference variable * * * Overloading function * differnt parameters could have the same name * * exit function leaves the program * stopps * cstdlib * exit(); function is cstdlib * can return a value * * stubs and drivers * drivers * fucntion to test * a way to test software to manage loads of people / data * stubs * dummy function * tests portions of codes without fully working code * * start=time to start timer * enstop=time to end time * final=end-start * * Arrays * weaker points of c++ * good for viruses malware * 1D 2D 3D * column table tables * static array upto 500,000 * char array * char name[size]; * int name[size]; * * Static array doesn change * const int SIZE=10 * int tests[SIZE]; * always choose the largest size * faster than dynamic * to access info use subscript * array starts at 0-(n-1) * can be used for a deck of cards * * const in SIZE=5 * int test[SIZE]= {} for everything sets it to zero * sizeof(quizzes) * size of int * * no bounds checking * * model view controller * * * setw iomanip * * char array could be a string * * parallel arrays are used to adress the same index * * * * * * * */ char string[5]; char a,b,c,d; cin>>string; a=string[0]; b=string[1]; c=string[2]; d=string[3]; cout<<a<<b<<c<<d<<endl; cin>>string; return 0; }
true
9c2a0a24d193aa1655ecc21deb980015ad401547
C++
malytomas/asciilabyrinthgen
/sources/labgen/paths.cpp
UTF-8
2,581
3
3
[]
no_license
#include "labgen.h" #include <vector> #include <utility> // std::swap namespace { struct Paths { Labyrinth &lab; std::vector<uint32> dists; std::vector<ivec2> prevs; Paths(Labyrinth &lab) : lab(lab) {} Cell &cell(ivec2 p) { CAGE_ASSERT(p[0] >= 0 && (uint32)p[0] < lab.width && p[1] >= 0 && (uint32)p[1] < lab.height); return lab.cells[p[1] * lab.width + p[0]]; } bool walkable(ivec2 p) { switch (cell(p)) { case Cell::Empty: case Cell::Start: case Cell::Goal: case Cell::Path: return true; default: return false; } } uint32 &dist(ivec2 p) { return dists[p[1] * lab.width + p[0]]; } ivec2 &prev(ivec2 p) { return prevs[p[1] * lab.width + p[0]]; } void distances(ivec2 start) { CAGE_ASSERT(walkable(start)); dists.clear(); prevs.clear(); dists.resize(lab.cells.size(), m); prevs.resize(lab.cells.size(), ivec2(-1)); std::vector<ivec2> q; q.push_back(start); dist(start) = 0; while (!q.empty()) { const ivec2 p = q.front(); q.erase(q.begin()); const uint32 pd = dist(p); CAGE_ASSERT(pd != m); CAGE_ASSERT(walkable(p)); for (ivec2 it : { p + ivec2(-1, 0), p + ivec2(1, 0), p + ivec2(0, -1), p + ivec2(0, 1) }) { if (!walkable(it)) continue; if (dist(it) <= pd + 1) continue; dist(it) = pd + 1; prev(it) = p; q.push_back(it); } } } ivec2 pickRandom() { while (true) { const ivec2 p = ivec2(randomRange(1u, lab.width - 1), randomRange(1u, lab.height - 1)); if (walkable(p)) return p; } } ivec2 pickFurthest() { uint32 d = 0; ivec2 p = ivec2(-1); for (uint32 i = 0; i < dists.size(); i++) { uint32 k = dists[i]; if (k == m) continue; if (k > d) { d = k; p = ivec2(i % lab.width, i / lab.width); } } return p; } void markPath(ivec2 start, ivec2 goal) { uint32 cnt = 1; start = prev(start); while (start != goal) { cell(start) = Cell::Path; start = prev(start); cnt++; } CAGE_LOG(SeverityEnum::Info, "paths", stringizer() + "the path has " + cnt + " steps"); } void paths() { CAGE_LOG(SeverityEnum::Info, "paths", "determining start and goal positions"); distances(pickRandom()); ivec2 start = pickFurthest(); distances(start); ivec2 goal = pickFurthest(); std::swap(start, goal); cell(start) = Cell::Start; cell(goal) = Cell::Goal; markPath(start, goal); } }; } void paths(Labyrinth &lab) { Paths paths(lab); paths.paths(); }
true
e01b0ae8f130897a78df4bd9958074a516437c4c
C++
NikolayKIvanov/Banking-System
/Task1/Account.h
UTF-8
501
3.203125
3
[]
no_license
#pragma once #include "iostream" class Account { public: Account(const char* _iban = "", int _ownerid = 0, double _amount = 0.0); Account(const Account&); Account& operator=(const Account&); ~Account(); virtual void deposit(double) = 0; virtual bool withdraw(double) = 0; virtual void display() const = 0; double getBalance() const; int getOwnerId() const { return ownerid; } const char* getIBAN() const { return iban; } protected: char* iban; int ownerid; double amount; };
true
095639198fb8f44753751cbc85c7f068f4967e06
C++
gadm21/INTERPRETER
/Instruction.h
UTF-8
16,237
2.90625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Instruction.h * Author: gad * * Created on April 25, 2018, 2:49 PM */ #ifndef INSTRUCTION_H #define INSTRUCTION_H #include "common.h" class expression{ protected: int label; public: expression(){} expression(int l); virtual int getlabel(); static string print; //valid() and execute() functions are the core of the interpretation process thus //every class that inherits from expression must difine this function static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); virtual int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs)=0; //this static function takes the expression vector we collected from the input file lines and a name of a variable to fetch a pointer to static expression* getexpr(const vector<expression*> &exprVector, string name); //this static function takes the expression vector we collected from the input file lines and a label defining the type of a class //and the name of the varible stored inside the expression //this function is used only with VAR child classes to check if a class of that type and that name exists or not static bool checkexpr(const vector<expression*> &exprVector,int label, string name); //this static function takes the expression vector we collected from the input file lines and a name of a variable //the function loops through all the expressions in the vector and returns a bool indicating a variable with the name we //passed exist or not static bool alreadyExist(const vector<expression*> &exprVector, string name); //this static function takes the expression vector we collected from the input file lines and a name of STRING to fetch its value static string getstr(const vector<expression*> &exprVector, string name); //this static function takes the expression vector we collected from the input file lines and a name of NUMERIC OR REAL to fetch its value static double getdou(const vector<expression*> &exprVector, string name); //this static function takes the expression vector we collected from the input file lines and a name of CHAR to fetch its value static char getchr(const vector<expression*> &exprVector, string name); //this static function takes the expression vector we collected from the input file lines and a name of a NUMERIC or REAL class that we know exists //and a number we want to replace the current value of the concerned NUMERIC or REAL with it. static void setdou(const vector<expression*> &exprVector, string name, double d); //this static function takes the expression vector we collected from the input file lines and a name of a CHAR class that we know exists //and a character we want to replace the current value of the concerned STRING with it. static void setchr(const vector<expression*> &exprVector, string name, char c); //this static function takes the expression vector we collected from the input file lines and a name of a STRING class that we know exists //and a string we want to replace the current value of the concerned STRING with it. static void setstr(const vector<expression*> &exprVector, string name, string s); //the destructor is virtual so that if a new instruction is to be added at any time //and that instruction uses a pointer to some object //it can delete that pointer virtual ~expression(); }; class ADD: public expression{ protected: vector <string> myparameters; public: ADD(){} ADD(int l, vector<string> myparameters); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); }; class MUL: public expression{ protected: vector <string> myparameters; public: MUL(){} MUL(int l, vector<string> myparameters); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class SUB: public expression{ protected: vector <string> myparameters; public: SUB(){} SUB(int l, vector<string> myparameters); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class DIV: public expression{ protected: vector <string> myparameters; public: DIV(){} DIV(int l, vector<string> myparameters); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class OUT: public expression{ protected: vector <string> myparameters; pthread_mutex_t lock; public: OUT(){} ~OUT(); OUT(int l, vector<string> myparameters); string outputs; static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class ASSIGN: public expression{ protected: vector <string> myparameters; public: ASSIGN(){} ASSIGN(int l, vector<string> myparameters); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class SETAFFINITY: public expression{ protected: int cpuid; public: SETAFFINITY(){} SETAFFINITY(int l, int _cpuid); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class LABEL: public expression{ protected: string name; public: LABEL(){} LABEL(int l, string n); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); string getname(); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class THREAD: public expression{ protected: public: THREAD(){} THREAD(int l); static int threadFlag; static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class THREAD_BEGIN: public THREAD{ protected: public: THREAD_BEGIN(){} THREAD_BEGIN(int l); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class THREAD_END: public THREAD{ protected: vector<expression*> myvarVector; vector<expression*> myinstrVector; pthread_t mythread; public: THREAD_END(){} THREAD_END(int l, vector<expression*> _myinstrVector); ~THREAD_END(); static void* run(void* arg); string *threadoutput; void threadMainBody(void* arg); void join(); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class BARRIER: public expression{ protected: public: BARRIER(){} BARRIER(int l); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class LOCK: public expression{ protected: string name; public: LOCK(){} LOCK(int l, string _name); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class UNLOCK: public expression{ protected: string name; public: UNLOCK(){} UNLOCK(int l, string _name); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class JMP: public expression{ protected: string name; public: JMP(){} JMP(int l, string n); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); string getname(); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; //child classes of JMP uses the string name that JMP has in addition to a value or two to apply conditions on class JMPZ: public JMP{ protected: string value; public: JMPZ(){} JMPZ(int l, string n, string v); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); string getvalue(); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class JMPNZ: public JMP{ protected: string value; public: JMPNZ(){} JMPNZ(int l, string n, string v); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); string getvalue(); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class JMPGT: public JMP{ protected: string first; string second; public: JMPGT(){} JMPGT(string f, string s, int l, string n); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); string getfirst(); string getsecond(); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class JMPLT: public JMPGT{ protected: public: JMPLT(){} JMPLT(string f, string s, int l, string n); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class JMPGTE: public JMPGT{ protected: public: JMPGTE(){} JMPGTE(string f, string s, int l, string n); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class JMPLTE: public JMPGT{ protected: public: JMPLTE(){} JMPLTE(string f, string s, int l, string n); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class SLEEP: public expression{ protected: long value; public: SLEEP(){} SLEEP(int l, long v); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); long getvalue(); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class SET_STR_CHAR: public expression{ protected: vector <string> myparameters; public: SET_STR_CHAR(){} SET_STR_CHAR(int l, vector<string> myparameters); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class GET_STR_CHAR: public expression{ protected: vector <string> myparameters; public: GET_STR_CHAR(){} GET_STR_CHAR(int l, vector<string> myparameters); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class VAR: public expression{ protected: string name; pthread_mutex_t lock; pthread_mutex_t explicitlock; public: VAR(){} ~VAR(); VAR(int l, string n); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); virtual string getname(); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); void locking(); void unlocking(); }; class CHAR: public VAR{ protected: char value; public: CHAR(){} CHAR(int l, string n, char v); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); char getvalue(); void setvalue(char v); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class NUMERIC: public VAR{ protected: long value; public: NUMERIC(){} NUMERIC(int l, string n, long v); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); long getvalue(); void setvalue(long v); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class REAL: public VAR{ protected: double value; public: REAL(){} REAL(int l, string n, double v); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); double getvalue(); void setvalue(double v); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; class STRING: public VAR{ protected: string value; public: STRING(){} STRING(int l, string n, string v); static int valid(vector<string> &tokens, vector<expression*> &instrVector, vector<expression*> &varVector, string &error, bool &accept); string getvalue(); void setvalue(string v); int execute(vector<expression*> &instrVector, vector<expression*> &varVector, string &outputs); }; #endif /* INSTRUCTION_H */
true
c610d3730c595c16fb33603c011ac6695ea557f4
C++
HPMongo/CS325_Max_Sum_Subarray
/MSS.cpp
UTF-8
14,663
3.359375
3
[]
no_license
/* * Author: Mike Sharkazy & Huy Pham * Date Created: 07/11/15 * Last Date Modified: 07/12/15 * File Name: MSS.cpp * Assignment: Project 1 - Project Group 18 * Overview: A program to calculate the maximum subarray sum of arrays * using different algorithms; The program reads input from * a text file and output to a text file; The text file * contains lines of integers separated by commas with one * set of square brackets around each line; The integers on * each line are placed in an array; The maximum sum of a * subarray of the arrays on each line are calculated; The * original array, subarray and the sum is output to a text * file for each array; The results of each algorithm for a * single array are output to the file before moving to the * next array to be calculated * * The output file is always named MSS_Results.txt and all * results are appended to the end of the file. If the * program is run more than once, the results for each * successive program run will be appended to * MSS_Results.txt if it is not deleted * * Format for command line arguments * mss <file name> * * The file name is the input file being used * * The program should be compiled with C++11 flags; Example * for use with the flip servers below * * g++ -std=c++0x MSS.cpp -o mss * * Input: Text file with bracketed lines of integers * Output: The integers in the arrays, and the sums are output to a * text file * * */ #include <iostream> #include <string> #include <chrono> #include <stdio.h> #include <fstream> #include <vector> #include <sstream> /* * The enumMSS() function calculates the maximum sum of a subarray of an array * through enumeration */ void enumMSS(const std::vector<int> &a, std::vector<int> &sa, int &max); /* * The betterEnumMSS() function calculates the maximum sum of a subarray of an array * through better enumeration */ void betterEnumMSS(const std::vector<int> &a, std::vector<int> &sa, int &max); /* * The dncMSS() function calculates the maximum sum of a subarray of an array * using divide and conquer algorithm */ void dncMSS(const std::vector<int> &a, std::vector<int> &sa, int &max); /* * Recursive function for the divide and conquer algorithm */ int dncMSS_recursive(const std::vector<int> &a, int left, int right, int &startIndex, int &endIndex); /* * Linear function calculate the maximum sum of a subarray of a given array * using linear algorithm */ void linearMSS(const std::vector<int> &a, std::vector<int> &sa, int &max); /* * The outputToFile() function writes the vectors and sum to the output file */ void outputToFile(std::ofstream &out, const std::vector<int> &a, const std::vector<int> &sa, const int &sum); /* * The fillVector() function fills the vector and with the ints from the input * line */ void fillVector(std::string &s, std::vector<int> &a); int main(int argc, char *argv[]) { // Declare input and ouput stream objects and open input stream std::ifstream inStream(argv[1]); if (inStream.fail()) { std::cout << "Input file opening failed.\n"; exit(1); } std::ofstream outStream("MSS_Results.txt");//, std::ios::app); while (!inStream.eof()) { // Declare a string for the line, get next line, declare vector for ints std::string line; getline(inStream, line); std::vector<int> intVect; // Fill the vector with the ints in the line fillVector(line, intVect); // Declare subarray vectors and sum variable std::vector<int> subArray1; std::vector<int> subArray2; std::vector<int> subArray3; std::vector<int> subArray4; int sum = 0; if(line.size() > 0) { /// Using enumeration method /// std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); //set first time point // Call function to calculate the maximum sum of a subarray enumMSS(intVect, subArray1, sum); std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now(); //set second time point auto duration1 = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); //calculate duration std::cout << "Algorithm 1 took " << duration1 << " milliseconds to run." << std::endl; // Write vector contents and sum to the output file outputToFile(outStream, intVect, subArray1, sum); /// Using better enumeration method /// std::chrono::high_resolution_clock::time_point t3 = std::chrono::high_resolution_clock::now(); //set first time point // Call the next function to calculate the maximum sum of a subarray betterEnumMSS(intVect, subArray2, sum); std::chrono::high_resolution_clock::time_point t4 = std::chrono::high_resolution_clock::now(); //set second time point auto duration2 = std::chrono::duration_cast<std::chrono::microseconds>( t4 - t3 ).count(); //calculate duration std::cout << "Algorithm 2 took " << duration2 << " milliseconds to run." << std::endl; // Write vector contents and sum to the output file outputToFile(outStream, intVect, subArray2, sum); /// Using divide and conquer method /// std::chrono::high_resolution_clock::time_point t5 = std::chrono::high_resolution_clock::now(); //set first time point // Call the next function to calculate the max sum dncMSS(intVect, subArray3, sum); std::chrono::high_resolution_clock::time_point t6 = std::chrono::high_resolution_clock::now(); //set second time point auto duration3 = std::chrono::duration_cast<std::chrono::microseconds>( t6 - t5 ).count(); //calculate duration std::cout << "Algorithm 3 took " << duration3 << " milliseconds to run." << std::endl; // Write vector contents and sum to the output file outputToFile(outStream, intVect, subArray3, sum); /// Using linear method /// std::chrono::high_resolution_clock::time_point t7 = std::chrono::high_resolution_clock::now(); //set first time point // Call the next function to calculate the max sum linearMSS(intVect, subArray4, sum); std::chrono::high_resolution_clock::time_point t8 = std::chrono::high_resolution_clock::now(); //set second time point auto duration4 = std::chrono::duration_cast<std::chrono::microseconds>( t8 - t7 ).count(); //calculate duration std::cout << "Algorithm 4 took " << duration4 << " milliseconds to run." << std::endl; // Write vector contents and sum to the output file outputToFile(outStream, intVect, subArray4, sum); } } // Close input and output streams inStream.close(); outStream.close(); std::cout << "Main program executed successfully!\n"; } /* * * * * * * * * Function: enumMSS() * * Entry: A const vector by reference, a vector by reference for the * subarray, and an int by reference * * Exit: Values of parameters sa and sum will be changed by the function * * Purpose: Calculate the maximum sum of a subarray using enumeration * * * * * * * */ void enumMSS(const std::vector<int> &a, std::vector<int> &sa, int &max) { //std::cout << "In enumMSS \n"; // Set the sum to 0 and declare a variable for the temp sum max = 0; int tempSum; int startIndex; int endIndex; // Loop over the indices, keeping the best sum found for (int i = 0; i < a.size(); i++) { for (int j = i; j < a.size(); j++) { tempSum = 0; for (int k = i; k <= j; k++) { tempSum += a[k]; if (tempSum > max) { max = tempSum; startIndex = i; endIndex = j; } } } } //std::cout << "Best sum is: " << max << std::endl; // Create the subarray for (int i = startIndex; i <= endIndex; i++) { sa.push_back(a[i]); } //std::cout << "Best sub array is: " << std::endl; //for (int i = 0; i < sa.size(); i++) //{ // std::cout << sa.at(i) << std::endl; //} } /* * * * * * * * * Function: betterEnumMSS() * * Entry: A const vector by reference, a vector by reference for the * subarray, and an int by reference * * Exit: Values of parameters sa and sum will be changed by the function * * Purpose: Calculate the maximum sum of a subarray using better enumeration * * * * * * * */ void betterEnumMSS(const std::vector<int> &a, std::vector<int> &sa, int &max) { // Set the sum to 0 and declare a variable for the temp sum max = 0; int tempSum; int startIndex; int endIndex; // Loop over the indices, keeping the best sum found for (int i = 0; i < a.size(); i++) { tempSum = 0; for (int j = i; j < a.size(); j++) { tempSum += a[j]; if (tempSum > max) { max = tempSum; startIndex = i; endIndex = j; } } } // Create the subarray for (int i = startIndex; i <= endIndex; i++) { sa.push_back(a[i]); } } /* * * * * * * * * Function: dncMSS() * * Entry: A const vector by reference, a vector by reference for the * subarray, and an int by reference * * Exit: Values of parameters sa and sum will be changed by the function * * Purpose: Calculate the maximum sum of a subarray using divide and conquer * * * * * * * */ void dncMSS(const std::vector<int> &a, std::vector<int> &sa, int &max) { //std::cout << "In main dnc\n"; int beg = 0; int end = a.size() - 1; int startIndex = 0; int endIndex = 0; max = dncMSS_recursive(a, beg, end, startIndex, endIndex); // Create the subarray for (int i = startIndex; i <= endIndex; i++) { sa.push_back(a[i]); } } int dncMSS_recursive(const std::vector<int> &a, int left, int right, int &startIndex, int &endIndex) { //std::cout << "In recursive dnc \n"; //Base case if(left == right) { startIndex = left; endIndex = right; return a[left]; } int l_idx_start, l_idx_end, r_idx_start, r_idx_end, m_idx_start, m_idx_end; int max = 0; int mid = (left + right) / 2; int maxLeft = dncMSS_recursive(a, left, mid, l_idx_start, l_idx_end); int maxRight = dncMSS_recursive(a, mid + 1, right, r_idx_start, r_idx_end); int maxMidLeft = 0, maxMidRight = 0, leftSum = 0, rightSum = 0; // Calculate maximum subarray of mid left side for (int i = mid; i >= left; i--) { leftSum += a[i]; if(leftSum > maxMidLeft) { maxMidLeft = leftSum; m_idx_start = i; } } // Calculate maximum subarray of mid right side for (int i = mid + 1; i <= right; i++) { rightSum += a[i]; if(rightSum > maxMidRight) { maxMidRight = rightSum; m_idx_end = i; } } if(maxLeft > maxRight) { if(maxLeft > maxMidLeft + maxMidRight) { startIndex = l_idx_start; endIndex = l_idx_end; return maxLeft; } else { startIndex = m_idx_start; endIndex = m_idx_end; return maxMidLeft + maxMidRight; } } else { if(maxRight > maxMidLeft + maxMidRight) { startIndex = r_idx_start; endIndex = r_idx_end; return maxRight; } else { startIndex = m_idx_start; endIndex = m_idx_end; return maxMidLeft + maxMidRight; } } } /* * * * * * * * * Function: linearMSS() * * Entry: A const vector by reference, a vector by reference for the * subarray, and an int by reference * * Exit: Values of parameters sa and sum will be changed by the function * * Purpose: Calculate the maximum sum of a subarray using linear algorithm * * * * * * * */ void linearMSS(const std::vector<int> &a, std::vector<int> &sa, int &max) { //std::cout << "In linear\n"; int startIndex = 0; int endIndex = 0; int currentMax = 0; max = 0; int i_low = 0; int i_high = 0;; for (int i = 1; i < a.size() ; i++) { i_high = i; if(currentMax > 0) { currentMax += a.at(i); } else { i_low = i; currentMax = a.at(i); } if(currentMax > max) { max = currentMax; startIndex = i_low; endIndex = i_high; } } // Create the subarray for (int i = startIndex; i <= endIndex; i++) { sa.push_back(a[i]); } } /* * * * * * * * * Function: outputToFile() * * Entry: An ofstream object by reference, a const vector by reference, a * const vector by reference for the subarray, and an int by reference * * Exit: Values of parameters will be written to the output file * * Purpose: Write vectors and sums to the output file * * * * * * * */ void outputToFile(std::ofstream &out, const std::vector<int> &a, const std::vector<int> &sa, const int &sum) { //std::cout << "In output - \n"; // Write vector contents and sum to the output stream out << "["; for (int i = 0; i < a.size(); i++) { if (i < a.size() - 1) { out << a[i] << ", "; } else { out << a[i] << "]\n"; } } out << "["; for (int i = 0; i < sa.size(); i++) { if (i < sa.size() - 1) { out << sa[i] << ", "; } else { out << sa[i] << "]\n"; } } out << sum << "\n\n"; } void fillVector(std::string &s, std::vector<int> &a) { // Declare stringstream object for line and int for each number std::stringstream lineSS(s); int num; // Check if the first char in the line is the left bracket if (lineSS.peek() == '[') { lineSS.ignore(); while (lineSS >> num) { // Add the number to the vector a.push_back(num); // Ignore commas or spaces if (lineSS.peek() == ',' || lineSS.peek() == ' ') { lineSS.ignore(); } } //std::cout << "Vector size: " << a.size() << std::endl; //for(int i = 0; i<a.size(); i++){ // std::cout << a.at(i) << std::endl; //} } else if(!lineSS.eof()) { std::cout << "Error: First character in line not a left bracket.\n"; //std::cout << "'" << lineSS.peek() << "'\n"; exit(1); } }
true
e1d740261181d19ff9d0b02d1d8e2c58b9f791bd
C++
SRamsey73/RoomControl
/controllers/desk_controller/src/main.cpp
UTF-8
1,523
2.75
3
[]
no_license
#include <Arduino.h> #include <TemperatureSensor.h> #include <LightSensor.h> #include <OccupancySensor.h> #include <LEDStrip.h> //Defines led strip animations in a separte file to keep main tidy #include "DeskAnimations.h" TemperatureSensor* roomTemperauteSensor; LightSensor* roomLightSensor; OccupancySensor* roomOccupancySensor; const int numLEDs = 90; CRGB* strip = new CRGB[numLEDs]; LEDStrip* deskLEDStrip; //Read serial input buffer void readSerialInputBuffer() { // Check if data is in serial buffer if (Serial.available() > 0) { char msg[1024] = {}; Serial.readBytesUntil('\4', msg, sizeof(msg) - 1); Peripheral::callRemoteFunction(msg); } } void setup() { //Open serial port Serial.begin(19200); delay(500); //Constructors for sensors roomTemperauteSensor = new TemperatureSensor("temperature_sensor", A14); roomLightSensor = new LightSensor("light_sensor", A15); roomOccupancySensor = new OccupancySensor("occupancy_sensor", 45); //Create LED strip FastLED.addLeds<WS2812B,47,GRB>(strip, numLEDs).setCorrection(TypicalLEDStrip); // initializes strip //Create object to interact with strip deskLEDStrip = new LEDStrip("desk_leds", strip, numLEDs, { { "tail_effect", new TailEffect(strip, numLEDs) }, { "rwb_center", new RWBCenter(strip, numLEDs) } }); Peripheral::sendSerial("Desk Arduino Initialized"); delay(200); } void loop() { readSerialInputBuffer(); Peripheral::update(); delay(2); }
true
494046f48ec61bd89936225a714ed0449f127876
C++
migaelstrydom/haggis
/src/test/testwindow.cpp
UTF-8
17,477
3.15625
3
[ "Apache-2.0" ]
permissive
/************************************************************************ * * testwindow.cpp * Window class tests * ************************************************************************/ #include "window.h" #include "test.h" #include <iostream> #include <cppunit/extensions/HelperMacros.h> /** * An extended version of Window for testing the event methods. * When it receives an event, it increments the corresponding counter and * returns the chosen response. It also keeps a count of the number of time * render() and draw() are called. */ class TestWindow : public Window { private: bool response; // response to events public: int mouseEvent, buttonEvent, keyEvent; // event counters int renders, draws; // render counters TestWindow() { mouseEvent = buttonEvent = keyEvent = 0; renders = draws = 0; response = false; } void setResponse(bool r) { response = r; } virtual void handleKeyEvent(KeyEvent event) { Window::handleKeyEvent(event); keyEvent++; } virtual void render(int pass, float dt) { Window::render(pass, dt); renders++; } protected: virtual bool onHandleMouseEvent(MouseEvent event) { mouseEvent++; return response; } virtual bool onHandleButtonEvent(ButtonEvent event) { buttonEvent++; return response; } virtual void draw(float dt) { draws++; } }; /** * This test suite contains two test cases: * * Code: CT-Win * Name: Window class unit tests * Configuration: Unit testing context * Tools: Cppunit * Description: Class tests for the Window class * * Code: IN-Win * Name: Window class integration tests * Configuration: Unit testing context * Tools: Cppunit * Description: Integration tests for the Window class */ class testwindow : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(testwindow); CPPUNIT_TEST(testConstructor); CPPUNIT_TEST(testAddChild_NoParent); CPPUNIT_TEST(testAddChild_Parent); CPPUNIT_TEST(testRemoveChild_WrongParent); CPPUNIT_TEST(testRemoveChild_RightParent); CPPUNIT_TEST(testIsInside_Inside); CPPUNIT_TEST(testIsInside_Outside); CPPUNIT_TEST(testSetPosition); CPPUNIT_TEST(testAbsolutePosition); CPPUNIT_TEST(testSetSize); CPPUNIT_TEST(testSetEnabled); CPPUNIT_TEST(testSetRenderPasses); CPPUNIT_TEST(testKeyEvent); CPPUNIT_TEST(testMouseEvent_All); CPPUNIT_TEST(testMouseEvent_Priority); CPPUNIT_TEST(testMouseEvent_Second); CPPUNIT_TEST(testButtonEvent_All); CPPUNIT_TEST(testButtonEvent_Priority); CPPUNIT_TEST(testButtonEvent_Second); CPPUNIT_TEST(testRender_Draw); CPPUNIT_TEST(testRender_All); CPPUNIT_TEST(testRender_Enabled); CPPUNIT_TEST(testRender_Pass1); CPPUNIT_TEST(testRender_Pass2); CPPUNIT_TEST(testRender_Pass3); CPPUNIT_TEST_SUITE_END(); private: /** * Count the number of occurences of child in the parent's child list. */ bool countChild(Window *parent, Window *child) { int n = 0; std::vector<Window*> c = parent->getChildren(); for (std::vector<Window*>::iterator i=c.begin(); i != c.end(); i++) { if (*i == child) { n++; } } return n; } /** * A hierarchy of TestWindows. */ TestWindow a, b, c, d; public: void setUp() { // setup the TestWindow hierarchy a.addChild(&b); a.addChild(&c); b.addChild(&d); a.setSize(vector4(10, 10)); b.setSize(vector4(10, 10)); c.setSize(vector4(10, 10)); d.setSize(vector4(10, 10)); a.setRenderPasses(RENDER_PASS_1 | RENDER_PASS_2 | RENDER_PASS_3); b.setRenderPasses(RENDER_PASS_2); c.setRenderPasses(RENDER_PASS_3); d.setRenderPasses(RENDER_PASS_1); } void tearDown() { } /** * Test the state initialized by the constructor. */ void testConstructor() { Window win; CPPUNIT_ASSERT(win.getPosition() == vector4()); CPPUNIT_ASSERT(win.getSize() == vector4()); CPPUNIT_ASSERT(win.getParent() == NULL); CPPUNIT_ASSERT(win.isEnabled()); CPPUNIT_ASSERT(win.getRenderPasses() == RENDER_PASS_1); } /** * Test adding a parentless child to a window. */ void testAddChild_NoParent() { Window win; Window child; win.addChild(&child); // check that the child's parent pointer is set CPPUNIT_ASSERT(child.getParent() == &win); // check that the child is in the parent's child list CPPUNIT_ASSERT(countChild(&win, &child) == 1); } /** * Test adding an already parented child to a window. */ void testAddChild_Parent() { Window win; Window parent; Window child; parent.addChild(&child); win.addChild(&child); // check that the child's parent pointer is correct CPPUNIT_ASSERT(child.getParent() == &win); // check that the child is not found in the previous parent's list CPPUNIT_ASSERT(countChild(&parent, &child) == 0); // check that the child is in the new parent's child list CPPUNIT_ASSERT(countChild(&win, &child) == 1); } /** * Test removing a child from the wrong parent. */ void testRemoveChild_WrongParent() { Window win, parent, child; parent.addChild(&child); bool result = win.removeChild(&child); // check the return code CPPUNIT_ASSERT(result == false); // check that the child's parent pointer is still correct CPPUNIT_ASSERT(child.getParent() == &parent); // check that the child is still in the parent's child list CPPUNIT_ASSERT(countChild(&parent, &child) == 1); // check that the child is not in win's child list CPPUNIT_ASSERT(countChild(&win, &child) == 0); } /** * Test removing a child from its parent. */ void testRemoveChild_RightParent() { Window win, child; win.addChild(&child); bool result = win.removeChild(&child); // check the return code CPPUNIT_ASSERT(result == true); // check the child's parent pointer CPPUNIT_ASSERT(child.getParent() == NULL); // check that the child is not in win's child list CPPUNIT_ASSERT(countChild(&win, &child) == 0); } /** * Test whether isInside() works for a point inside the window. */ void testIsInside_Inside() { Window win; win.setSize(vector4(100, 100)); // check for the window positioned at the origin CPPUNIT_ASSERT(win.isInside(vector4(50, 50))); // middle CPPUNIT_ASSERT(win.isInside(vector4(0, 0))); // botton-left CPPUNIT_ASSERT(win.isInside(vector4(99, 99))); // top-right // check for the window positioned not at the origin win.setPosition(vector4(50, 50)); CPPUNIT_ASSERT(win.isInside(vector4(75, 75))); // middle CPPUNIT_ASSERT(win.isInside(vector4(0, 0))); // bottom-left CPPUNIT_ASSERT(win.isInside(vector4(99, 99))); // top-right } /** * Test whether isInside() works for a point outside the window. */ void testIsInside_Outside() { Window win; win.setSize(vector4(100, 100)); // check for the window positioned at the origin CPPUNIT_ASSERT(!win.isInside(vector4(-1, -1))); // bottom-left CPPUNIT_ASSERT(!win.isInside(vector4(100, 100))); // top-right CPPUNIT_ASSERT(!win.isInside(vector4(50, -1))); // y out of range // check for the window positioned not at the origin win.setPosition(vector4(50, 50)); CPPUNIT_ASSERT(!win.isInside(vector4(-1, -1))); // bottom-left CPPUNIT_ASSERT(!win.isInside(vector4(100, 100))); // top-right CPPUNIT_ASSERT(!win.isInside(vector4(50, -1))); // y out of range } /** * Test setting the window position. */ void testSetPosition() { Window win; win.setPosition(vector4(25, 25)); CPPUNIT_ASSERT(win.getPosition() == vector4(25, 25)); } /** * Test calculating the window's absolute position. */ void testAbsolutePosition() { Window parent, win, win2; parent.addChild(&win); win.addChild(&win2); parent.setPosition(vector4(25, 25)); win.setPosition(vector4(5, 3)); win2.setPosition(vector4(1, 2)); CPPUNIT_ASSERT(parent.getAbsolutePosition() == vector4(25, 25)); CPPUNIT_ASSERT(win.getAbsolutePosition() == vector4(30, 28)); CPPUNIT_ASSERT(win2.getAbsolutePosition() == vector4(31, 30)); } /** * Test setting the window size. */ void testSetSize() { Window win; win.setSize(vector4(100, 256)); CPPUNIT_ASSERT(win.getSize() == vector4(100, 256)); } /** * Test setting the enabled state of the window. */ void testSetEnabled() { Window win; win.setEnabled(true); CPPUNIT_ASSERT(win.isEnabled()); win.setEnabled(false); CPPUNIT_ASSERT(!win.isEnabled()); } /** * Test setting the window render passes bitmask. */ void testSetRenderPasses() { Window win; win.setRenderPasses(0); CPPUNIT_ASSERT(win.getRenderPasses() == 0); win.setRenderPasses(RENDER_PASS_1); CPPUNIT_ASSERT(win.getRenderPasses() == RENDER_PASS_1); int pass = RENDER_PASS_2 | RENDER_PASS_3; win.setRenderPasses(pass); CPPUNIT_ASSERT(win.getRenderPasses() == pass); } /** * Tests that key events are passed to every child. */ void testKeyEvent() { // emit an event KeyEvent e('x', KeyEvent::PRESSED); a.handleKeyEvent(e); // check that that all the windows received a single event CPPUNIT_ASSERT(a.keyEvent == 1); CPPUNIT_ASSERT(b.keyEvent == 1); CPPUNIT_ASSERT(c.keyEvent == 1); CPPUNIT_ASSERT(d.keyEvent == 1); } /** * Tests that mouse events are passed to every child if none of them * accept the event. */ void testMouseEvent_All() { // emit an event bool r = a.handleMouseEvent(MouseEvent(vector4(1, 1), vector4())); // check the result CPPUNIT_ASSERT(r == false); // check that all the windows received a single event CPPUNIT_ASSERT(a.mouseEvent == 1); CPPUNIT_ASSERT(b.mouseEvent == 1); CPPUNIT_ASSERT(c.mouseEvent == 1); CPPUNIT_ASSERT(d.mouseEvent == 1); } /** * Tests that childs added first get a higher mouse event priority. */ void testMouseEvent_Priority() { // make both d and c respond d.setResponse(true); c.setResponse(true); // emit an event bool r = a.handleMouseEvent(MouseEvent(vector4(1, 1), vector4())); // check the result CPPUNIT_ASSERT(r == true); // check that the windows recieve the correct number of events CPPUNIT_ASSERT(a.mouseEvent == 0); CPPUNIT_ASSERT(b.mouseEvent == 0); CPPUNIT_ASSERT(c.mouseEvent == 0); CPPUNIT_ASSERT(d.mouseEvent == 1); } /** * Tests that the second child gets the mouse event if the first didn't * accept it. */ void testMouseEvent_Second() { // make only c respond c.setResponse(true); // emit an event bool r = a.handleMouseEvent(MouseEvent(vector4(1, 1), vector4())); // check the result CPPUNIT_ASSERT(r == true); // check that the windows recieve the correct number of events CPPUNIT_ASSERT(a.mouseEvent == 0); CPPUNIT_ASSERT(b.mouseEvent == 1); CPPUNIT_ASSERT(c.mouseEvent == 1); CPPUNIT_ASSERT(d.mouseEvent == 1); } /** * Tests that button events are passed to every child if none of them * accept the event. */ void testButtonEvent_All() { // emit an event bool r = a.handleButtonEvent(ButtonEvent(ButtonEvent::LEFT, ButtonEvent::PRESSED, vector4(1, 1))); // check the result CPPUNIT_ASSERT(r == false); // check that all the windows received a single event CPPUNIT_ASSERT(a.buttonEvent == 1); CPPUNIT_ASSERT(b.buttonEvent == 1); CPPUNIT_ASSERT(c.buttonEvent == 1); CPPUNIT_ASSERT(d.buttonEvent == 1); } /** * Tests that childs added first get a higher button event priority. */ void testButtonEvent_Priority() { // make both d and c respond d.setResponse(true); c.setResponse(true); // emit an event bool r = a.handleButtonEvent(ButtonEvent(ButtonEvent::LEFT, ButtonEvent::PRESSED, vector4(1, 1))); // check the result CPPUNIT_ASSERT(r == true); // check that the windows recieve the correct number of events CPPUNIT_ASSERT(a.buttonEvent == 0); CPPUNIT_ASSERT(b.buttonEvent == 0); CPPUNIT_ASSERT(c.buttonEvent == 0); CPPUNIT_ASSERT(d.buttonEvent == 1); } /** * Tests that the second child gets the button event if the first didn't * accept it. */ void testButtonEvent_Second() { // make only c respond c.setResponse(true); // emit an event bool r = a.handleButtonEvent(ButtonEvent(ButtonEvent::LEFT, ButtonEvent::PRESSED, vector4(1, 1))); // check the result CPPUNIT_ASSERT(r == true); // check that the windows recieve the correct number of events CPPUNIT_ASSERT(a.buttonEvent == 0); CPPUNIT_ASSERT(b.buttonEvent == 1); CPPUNIT_ASSERT(c.buttonEvent == 1); CPPUNIT_ASSERT(d.buttonEvent == 1); } /** * Tests that render() calls the draw() method. */ void testRender_Draw() { TestWindow win; win.render(RENDER_PASS_1 | RENDER_PASS_2 | RENDER_PASS_3, 0); // check that the right number of methods were called CPPUNIT_ASSERT(win.renders == 1); CPPUNIT_ASSERT(win.draws == 1); } /** * Test rendering the entire hierarchy. */ void testRender_All() { a.render(RENDER_PASS_1 | RENDER_PASS_2 | RENDER_PASS_3, 0); // check that everything was rendered and drawn CPPUNIT_ASSERT(a.renders == 1); CPPUNIT_ASSERT(b.renders == 1); CPPUNIT_ASSERT(c.renders == 1); CPPUNIT_ASSERT(d.renders == 1); CPPUNIT_ASSERT(a.draws == 1); CPPUNIT_ASSERT(b.draws == 1); CPPUNIT_ASSERT(c.draws == 1); CPPUNIT_ASSERT(d.draws == 1); } /** * Tests that child windows are not rendered or drawn if a window is * disabled. */ void testRender_Enabled() { b.setEnabled(false); a.render(RENDER_PASS_1 | RENDER_PASS_2 | RENDER_PASS_3, 0); // check the number of renders CPPUNIT_ASSERT(a.renders == 1); CPPUNIT_ASSERT(b.renders == 1); CPPUNIT_ASSERT(c.renders == 1); CPPUNIT_ASSERT(d.renders == 0); // check the number of draws CPPUNIT_ASSERT(a.draws == 1); CPPUNIT_ASSERT(b.draws == 0); CPPUNIT_ASSERT(c.draws == 1); CPPUNIT_ASSERT(d.draws == 0); } /** * Tests that the right windows get drawn in RENDER_PASS_1. */ void testRender_Pass1() { a.render(RENDER_PASS_1, 0); CPPUNIT_ASSERT(a.draws == 1); CPPUNIT_ASSERT(b.draws == 0); CPPUNIT_ASSERT(c.draws == 0); CPPUNIT_ASSERT(d.draws == 1); } /** * Tests that the right windows get drawn in RENDER_PASS_2. */ void testRender_Pass2() { a.render(RENDER_PASS_2, 0); CPPUNIT_ASSERT(a.draws == 1); CPPUNIT_ASSERT(b.draws == 1); CPPUNIT_ASSERT(c.draws == 0); CPPUNIT_ASSERT(d.draws == 0); } /** * Tests that the right windows get drawn in RENDER_PASS_3. */ void testRender_Pass3() { a.render(RENDER_PASS_3, 0); CPPUNIT_ASSERT(a.draws == 1); CPPUNIT_ASSERT(b.draws == 0); CPPUNIT_ASSERT(c.draws == 1); CPPUNIT_ASSERT(d.draws == 0); } }; void register_window() { CPPUNIT_TEST_SUITE_REGISTRATION(testwindow); }
true
cc31bf8b7116616c5be1a6a0fde47011da16ed90
C++
Artemmm91/CSES
/Dynamic Programming/Edit Distance/Edit Distance/main.cpp
UTF-8
905
2.796875
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int main() { int n, m, temp; string s1, s2; cin >> s1 >> s2; n = (int)s1.size(); m = (int)s2.size(); vector<int> v_0; vector<vector<int>> v; for(int i =0; i <= n; i++){ v_0.push_back(i); } v.push_back(v_0); for(int i = 1; i <= m; i++){ v_0.clear(); for(int j = 0; j <= n; j++){ if(j == 0){ v_0.push_back(i); } else{ if(s2[i - 1] == s1[j - 1]){ v_0.push_back(v[i - 1][j - 1]); } else{ temp = min(v[i - 1][j - 1], min(v[i - 1][j], v_0[j - 1])); v_0.push_back(temp+1); } } } v.push_back(v_0); } cout << v[m][n]; return 0; }
true
1c9b9da68e14b4a50fe1b60bce5a3fd3c2f0fa7f
C++
gg-uah/GARouter
/GAROUTER/CommonUtils/include/StringUtilsException.hpp
UTF-8
1,271
3.34375
3
[]
no_license
#ifndef __STRING_UTILS_EXCEPTION #define __STRING_UTILS_EXCEPTION #include <string> namespace common { enum StrUtilErrorType {STRUTIL_UNSPECIFIED, STRUTIL_BAD_INT_CAST, STRUTIL_BAD_LONG_CAST, STRUTIL_BAD_FLOAT_CAST, STRUTIL_BAD_DOUBLE_CAST}; /** * This is the possible exceptions of the class StringUtilities */ class StringUtilsException { public: /** * Constructors of class */ StringUtilsException(); /** * Constructor of the class * * @param typeException Numeric value indicating the type of the exception */ StringUtilsException(StrUtilErrorType typeException); /** * Method that return the type of exception * * @deprecated Only the getReason method should be used * @return the type of exception */ int getType(); /** * Method that return the reason of the exception * * @return the reason of the exception */ std::string getReason(); private: /** * Property that indicates the type of exception. */ StrUtilErrorType type; }; } /* namespace */ #endif
true
c44834052d162fa47892eb01c608761b1d2414fe
C++
ariyonaty/ECE1310
/Exercises/exercise_89.cpp
UTF-8
2,663
4.03125
4
[]
no_license
/* Ari Yonaty ECE 1310 3.21.2019 Exercise 89: Tic Tac Toe */ // Libraries #include <iostream> #include <iomanip> using namespace std; // Functions char setup(); void printBoard(char array[][3]); bool turn(char array[][3], int t); bool winner(char array[][3]); // Variables char player; char computer = 'X'; bool game; int main() { char introArray[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; cout << "Welcome to TicTacToe!\nThis is the layout of the board:\n"; printBoard(introArray); cout << "In order to play, select a position 1 - 9 to place board.\n3 in a row wins.\n...\nReady? Let's begin!\n...\n"; player = setup(); if (player == 'X') { computer = 'O'; } cout << "Player: " << player << endl; cout << "Computer: " << computer << endl << "...\n"; char array[3][3] = { '-', '-', '-', '-', '-', '-', '-', '-', '-'}; while (game == false) { turn(array, 1); } return 0; } char setup() { char choice; cout << "Do you want to be X or O? "; cin >> choice; return choice; } void printBoard(char array[][3]) { cout << array[0][0] << " | " << array[0][1] << " | " << array[0][2] << endl; cout << "---------" << endl; cout << array[1][0] << " | " << array[1][1] << " | " << array[1][2] << endl; cout << "---------" << endl; cout << array[2][0] << " | " << array[2][1] << " | " << array[2][2] << endl; } bool turn(char array[][3], int t) { if (t == 1) { cout << "Player turn....\n"; printBoard(array); int posX, posY; cout << "Enter x, y (1-3, 1-3): "; cin >> posX >> posY; if (array[posX - 1][posY - 1] == '-') { array[posX - 1][posY - 1] = player; } else { turn(array, 1); } turn(array, 0); } else if (t == 0) { cout << "Computer turn....\n"; printBoard(array); int posX = rand() % 3; int posY = rand() % 3; if (array[posX][posY] == '-') { array[posX][posY] = computer; } else { turn(array, 0); } turn(array, 1); } return game = winner(array); } bool winner(char array[][3]) { for (int i = 0; i < 3; i++) { if (array[0][i] == array[1][i] == array[2][i]) { return true; } } for (int i = 0; i < 3; i++) { if (array[i][0] == array[i][1] == array[i][2]) { return true; } } return false; }
true
c5bf97d930f73f640ba73641e4d0d3a9f78e5a75
C++
yhencay/CayShienne_CSC17A_42636
/Hmwk/Assignment_4/Gaddis_8thEd_Chap12_Prob5_LineNumbers/main.cpp
UTF-8
1,916
3.53125
4
[]
no_license
/* * File: main.cpp * Author: Shienne Cay * Created on April 3, 2017, 9:20 PM * Purpose: Homework #4 Line Numbers * * Problem: (This assignment could be done as a modification of the program in * Programming Challenge 2.) Write a program that asks the user for the name of * a file. The program should display the contents of the file on the screen. * Each line of screen output should be preceded with a line number, followed * by a colon. The line numbering should start at 1. */ //System Libraries #include <iostream> #include <fstream> #include <string> using namespace std; //User Libraries //Global Constants //Such as PI, Vc, -> Math/Science values //as well as conversions from one system of measurements //to another //Function Prototypes //Executable code begins here! Always begins in Main int main(int argc, char** argv) { //Declare Variables string fylName, hold; int cnt=0; char press='\0'; //Input Values cout<<"Choose file to open:"<<endl<<endl; cout<<"- One\n- Two\n- Three\n"<<endl; cout<<"CHOICE: "; cin>>fylName; cout<<endl; //Process by mapping inputs to outputs fstream file; file.open(fylName+".txt", ios::in); if(file) { while(file) { getline(file, hold); cnt++; } cnt--; file.close(); //Output Values file.open(fylName+".txt", ios::in); for (int i=0;i<cnt;i++) { getline(file, hold); cout<<i+1<<": "<<hold<<endl; if ((i+1)%24==0) { cout<<"\nPress enter key to continue!"<<endl<<endl; cin.get(press); cin.ignore(256, '\n'); cin.clear(); } } file.close(); } else { cout<<"\nERROR! File does not exist!"<<endl<<endl; } //Exit stage right! - This is the 'return 0' call return 0; }
true
37bd23b67b20d61b761253319178dc57ce4b885f
C++
jk983294/CommonScript
/cpp/std_cpp/stl/iterator/istream_iterator.cpp
UTF-8
472
3.65625
4
[]
no_license
#include <iostream> #include <iterator> using namespace std; // istream iterators read successive elements from an input stream (such as cin, file). int main() { double value1, value2; std::cout << "Please, insert two values: "; std::istream_iterator<double> iit(std::cin), eos; if (iit != eos) value1 = *iit; ++iit; if (iit != eos) value2 = *iit; std::cout << value1 << "*" << value2 << "=" << (value1 * value2) << '\n'; return 0; }
true
27a447161d90ca9694e8d50a2f695e976a017150
C++
burakbayramli/books
/Riemann_Solvers_and_Numerical_Methods_for_Fluid_Dynamics_Toro/Riemann-Solvers-master/Euler Equation/MUSCL/basic.cc
UTF-8
16,467
2.8125
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <cmath> #include <algorithm> #include <vector> #include <string> using namespace std; const double G0 = 1.4; const double G1 = 0.5 * (G0 - 1) / G0; const double G2 = 0.5 * (G0 + 1) / G0; const double G3 = 2 * G0 / (G0 - 1); const double G4 = 2 / (G0 - 1); const double G5 = 2 / (G0 + 1); const double G6 = (G0 - 1) / (G0 + 1); const double G7 = (G0 - 1) / 2; const double G8 = G0 - 1; const double G9 = -G2; const double G10 = -0.5 * (G0 + 1) / pow(G0, 2); const double G11 = -0.5 * (3 * G0 + 1) / G0; const double G12 = 1.0 / G0; double CFL = 0.2; const int NumOfPnt = 201; const double xL = 0, xR = 1.0; const double xM = (xL + xR) / 2; const double dx = (xR - xL) / (NumOfPnt - 1); inline double sound_speed(double p, double rho) { return sqrt(G0 * p / rho); } inline double internal_energy(double p, double rho) { return p / (G8 * rho); } inline double kinetic_energy(double u) { return 0.5 * pow(u, 2); } inline double E(double rho, double u, double p) { return rho * (internal_energy(p, rho) + kinetic_energy(u)); } class PrimitiveVar { public: double rho, u, p; double a, e, Ma; double H; public: PrimitiveVar(double density = 1.0, double velocity = 0.0, double pressure = 101325.0) { set(density, velocity, pressure); } PrimitiveVar(istream &in) { double density, velocity, pressure; in >> density >> velocity >> pressure; set(density, velocity, pressure); } ~PrimitiveVar() = default; double &at(size_t idx) { switch(idx) { case 0: return rho; case 1: return u; case 2: return p; default: throw("Invalid index!"); } } double at(size_t idx) const { switch(idx) { case 0: return rho; case 1: return u; case 2: return p; default: throw("Invalid index!"); } } void set(double density, double velocity, double pressure) { rho = density; u = velocity; p = pressure; a = sound_speed(p, rho); e = internal_energy(p, rho); Ma = u / a; H = (E(density, velocity, pressure) + pressure) / density; } PrimitiveVar operator+(const PrimitiveVar &rhs) { return PrimitiveVar(rho + rhs.rho, u + rhs.u, p + rhs.p); } }; inline double Ak(const PrimitiveVar &W) { return G5 / W.rho; } inline double Bk(const PrimitiveVar &W) { return G6 * W.p; } inline double gk(double p, const PrimitiveVar &W) { return sqrt(Ak(W) / (p + Bk(W))); } inline double fk(double p, const PrimitiveVar &W) { if (p > W.p) return (p - W.p) * gk(p, W); else return G4 * W.a * (pow(p / W.p, G1) - 1); } inline double dfk(double p, const PrimitiveVar &W) { if (p > W.p) { double B = Bk(W); return sqrt(Ak(W) / (B + p)) * (1 - 0.5 * (p - W.p) / (B + p)); } else return 1.0 / (W.rho * W.a) / pow(p / W.p, G2); } inline double ddfk(double p, const PrimitiveVar &W) { if (p > W.p) { double B = Bk(W); return -0.25 * sqrt(Ak(W) / (B + p)) * (4 * B + 3 * p + W.p) / pow(B + p, 2); } else return G10 * W.a / pow(W.p, 2) * pow(p / W.p, G11); } inline double f(double p, const PrimitiveVar &Wl, const PrimitiveVar &Wr) { return fk(p, Wl) + fk(p, Wr) + (Wr.u - Wl.u); } inline double df(double p, const PrimitiveVar &Wl, const PrimitiveVar &Wr) { return dfk(p, Wl) + dfk(p, Wr); } inline double ddf(double p, const PrimitiveVar &Wl, const PrimitiveVar &Wr) { return ddfk(p, Wl) + ddfk(p, Wr); } //Exact solution of then 1-D Euler equation //This is the Riemann problem, where initial discontinuity exists double p_star(const PrimitiveVar &Wl, const PrimitiveVar &Wr) { const double TOL = 1e-6; const double du = Wr.u - Wl.u; //Select initial pressure const double f_min = f(min(Wl.p, Wr.p), Wl, Wr); const double f_max = f(max(Wl.p, Wr.p), Wl, Wr); double p_m = (Wl.p + Wr.p) / 2; p_m = max(TOL, p_m); double p_pv = p_m - du * (Wl.rho + Wr.rho) * (Wl.a + Wr.a) / 8; p_pv = max(TOL, p_pv); const double gL = gk(p_pv, Wl); const double gR = gk(p_pv, Wr); double p_ts = (gL * Wl.p + gR * Wr.p - du) / (gL + gR); p_ts = max(TOL, p_ts); double p_tr = pow((Wl.a + Wr.a - G7 * du) / (Wl.a / pow(Wl.p, G1) + Wr.a / pow(Wr.p, G1)), G3); p_tr = max(TOL, p_tr); double p0 = p_m; if (f_min < 0 && f_max < 0) p0 = p_ts; else if (f_min > 0 && f_max > 0) p0 = p_tr; else p0 = p_pv; //Solve int iter_cnt = 0; double CHA = 1.0; while (CHA > TOL) { ++iter_cnt; double fder = df(p0, Wl, Wr); if (fder == 0) throw "Zero derivative!"; double fval = f(p0, Wl, Wr); double fder2 = ddf(p0, Wl, Wr); double p = p0 - fval * fder / (pow(fder, 2) - 0.5 * fval * fder2); if (p < 0) { p0 = TOL; break; } CHA = abs(2 * (p - p0) / (p + p0)); p0 = p; } return p0; } inline double u_star(double p, const PrimitiveVar &Wl, const PrimitiveVar &Wr) { return (Wl.u + Wr.u) / 2 + (fk(p, Wr) - fk(p, Wl)) / 2; } inline double rho_star(double p, const PrimitiveVar &W) { const double t = p / W.p; if (t > 1.0) return W.rho * ((t + G6) / (G6 * t + 1)); else return W.rho * pow(t, G12); } class FluxVar { private: double f[3]; public: FluxVar(double a = 0.0, double b = 0.0, double c = 0.0) { f[0] = a; f[1] = b; f[2] = c; } ~FluxVar() = default; void set(const PrimitiveVar &W) { f[0] = W.rho * W.u; f[1] = W.rho * pow(W.u, 2) + W.p; f[2] = W.u * (E(W.rho, W.u, W.p) + W.p); } void set(double density, double velocity, double pressure) { f[0] = density * velocity; f[1] = density * pow(velocity, 2) + pressure; f[2] = velocity * (E(density, velocity, pressure) + pressure); } double &mass_flux() { return f[0]; } double &momentum_flux() { return f[1]; } double &energy_flux() { return f[2]; } FluxVar operator+(const FluxVar &rhs) { return FluxVar(this->f[0] + rhs.f[0], this->f[1] + rhs.f[1], this->f[2] + rhs.f[2]); } FluxVar operator-(const FluxVar &rhs) { return FluxVar(this->f[0] - rhs.f[0], this->f[1] - rhs.f[1], this->f[2] - rhs.f[2]); } }; class ConservativeVar { private: double u[3]; public: ConservativeVar(double a = 0.0, double b = 0.0, double c = 0.0) { u[0] = a; u[1] = b; u[2] = c; } ConservativeVar(const PrimitiveVar &x) { set(x.rho, x.u, x.p); } ~ConservativeVar() = default; void set(double density, double velocity, double pressure) { u[0] = density; u[1] = density * velocity; u[2] = E(density, velocity, pressure); } double &at(int k) { return u[k]; } double at(int k) const { return u[k]; } double density() const { return u[0]; } double velocity() const { return u[1] / u[0]; } double pressure() const { return max(G8 * (u[2] - 0.5 * pow(u[1], 2) / u[0]), 0.0); } PrimitiveVar toPrimitive() { return PrimitiveVar(density(), velocity(), pressure()); } ConservativeVar operator+(const ConservativeVar &rhs) { return ConservativeVar(this->u[0] + rhs.u[0], this->u[1] + rhs.u[1], this->u[2] + rhs.u[2]); } ConservativeVar operator-(const ConservativeVar &rhs) { return ConservativeVar(this->u[0] - rhs.u[0], this->u[1] - rhs.u[1], this->u[2] - rhs.u[2]); } ConservativeVar &operator*=(double rhs) { this->u[0] *= rhs; this->u[1] *= rhs; this->u[2] *= rhs; return *this; } }; void W_fanL(const PrimitiveVar *W, double S, PrimitiveVar &ans) { double density = W->rho * pow(G5 + G6 / W->a * (W->u - S), G4); double velocity = G5 * (W->a + G7 * W->u + S); double pressure = W->p * pow(G5 + G6 / W->a * (W->u - S), G3); ans.set(density, velocity, pressure); } void W_fanR(const PrimitiveVar *W, double S, PrimitiveVar &ans) { double density = W->rho * pow(G5 - G6 / W->a * (W->u - S), G4); double velocity = G5 * (-W->a + G7 * W->u + S); double pressure = W->p * pow(G5 - G6 / W->a * (W->u - S), G3); ans.set(density, velocity, pressure); } void ExactSol(const PrimitiveVar &Wl, const PrimitiveVar &Wr, double p_s, double u_s, double rho_sL, double rho_sR, double S, PrimitiveVar &ans) { const bool leftIsVacuum = fabs(Wl.rho) < 1e-6; const bool rightIsVacuum = fabs(Wr.rho) < 1e-6; if(leftIsVacuum && !rightIsVacuum) { // Left vacuum const double SsR = Wr.u - G4 * Wr.a; const double S_HR = Wr.u + Wr.a; if (S <= SsR) ans.set(0, SsR, 0); else if(S < S_HR) W_fanR(&Wr, S, ans); else ans = Wr; } else if(!leftIsVacuum && rightIsVacuum) { // Right vacuum const double SsL = Wl.u + G4 * Wl.a; const double S_HL = Wl.u - Wl.a; if (S <= S_HL) ans = Wl; else if(S < SsL) W_fanL(&Wl, S, ans); else ans.set(0, SsL, 0); } else if(leftIsVacuum && rightIsVacuum) { // Vacuum on both sides ans.set(0.0, 0.5*(Wl.u + Wr.u), 0); } else { // No vacuum on either side const double du = Wr.u - Wl.u; const double du_crit = G4 * (Wl.a + Wr.a); const bool vacuumInBetween = !(du_crit > du); if(vacuumInBetween) { // Vacuum generated from the Riemann Problem const double SsL = Wl.u + G4 * Wl.a; const double SsR = Wr.u - G4 * Wr.a; const double S_HL = Wl.u - Wl.a; const double S_HR = Wr.u + Wr.a; if (S < S_HL) ans = Wl; else if(S < SsL) W_fanL(&Wl, S, ans); else if(S < SsR) ans.set(0.0, 0.5*(Wl.u + Wr.u), 0); else if(S < S_HR) W_fanR(&Wr, S, ans); else ans = Wr; } else { if (S < u_s) { const double S_L = Wl.u - Wl.a * sqrt(G2 * p_s / Wl.p + G1); const double S_HL = Wl.u - Wl.a; const double S_TL = u_s - sound_speed(p_s, rho_sL); if (p_s > Wl.p) { if (S < S_L) ans = Wl; else ans.set(rho_sL, u_s, p_s); } else { if (S < S_HL) ans = Wl; else if (S > S_TL) ans.set(rho_sL, u_s, p_s); else W_fanL(&Wl, S, ans); } } else { const double S_R = Wr.u + Wr.a * sqrt(G2 * p_s / Wr.p + G1); const double S_HR = Wr.u + Wr.a; const double S_TR = u_s + sound_speed(p_s, rho_sR); if (p_s > Wr.p) { if (S > S_R) ans = Wr; else ans.set(rho_sR, u_s, p_s); } else { if (S > S_HR) ans = Wr; else if (S < S_TR) ans.set(rho_sR, u_s, p_s); else W_fanR(&Wr, S, ans); } } } } } class InterCell { public: PrimitiveVar Wl, Wr; double p_s, u_s, rho_sL, rho_sR; FluxVar local_flux; public: InterCell() { p_s = 101325.0; u_s = 0.0; rho_sL = 1.0; rho_sR = 1.0; } ~InterCell() = default; void set(const PrimitiveVar &left, const PrimitiveVar &right) { Wl = left; Wr = right; p_s = p_star(Wl, Wr); u_s = u_star(p_s, Wl, Wr); rho_sL = rho_star(p_s, Wl); rho_sR = rho_star(p_s, Wr); PrimitiveVar ans; ExactSol(Wl, Wr, p_s, u_s, rho_sL, rho_sR, 0.0, ans); local_flux.set(ans); } }; void output(ofstream &f, int time_step, const vector<PrimitiveVar> &W, const vector<PrimitiveVar> &W_exact) { f << time_step << endl; for (int i = 1; i <= NumOfPnt; i++) { f << setw(18) << setprecision(6) << scientific << W[i].rho; f << setw(18) << setprecision(6) << scientific << W[i].u; f << setw(18) << setprecision(6) << scientific << W[i].p; f << setw(18) << setprecision(6) << scientific << W[i].e; f << setw(18) << setprecision(6) << scientific << W[i].Ma; f << setw(18) << setprecision(6) << scientific << W_exact[i].rho; f << setw(18) << setprecision(6) << scientific << W_exact[i].u; f << setw(18) << setprecision(6) << scientific << W_exact[i].p; f << setw(18) << setprecision(6) << scientific << W_exact[i].e; f << setw(18) << setprecision(6) << scientific << W_exact[i].Ma; f << endl; } } int main(int argc, char **argv) { //Coordinates vector<double> x(NumOfPnt, xL); for (int k = 1; k < NumOfPnt; ++k) x[k] = x[k - 1] + dx; //Loop all cases int NumOfCase; cin >> NumOfCase; for (int c = 0; c < NumOfCase; ++c) { cout << "Case" << c + 1 << "..." << endl; //Input PrimitiveVar Wl(cin), Wr(cin); int NumOfStep; cin >> NumOfStep; //For exact solution const double p_middle = p_star(Wl, Wr); const double u_middle = u_star(p_middle, Wl, Wr); const double rho_middle_left = rho_star(p_middle, Wl); const double rho_middle_right = rho_star(p_middle, Wr); //Create output data file stringstream ss; ss << c + 1; string header = "Case" + ss.str() + ".txt"; ofstream fout(header); if (!fout) throw "Failed to open file!"; //Output coordinates and intial settings fout << NumOfStep << '\t' << NumOfPnt << endl; for (int i = 0; i < NumOfPnt; i++) fout << x[i] << endl; //Initialize int PREV = 0, CUR = 1; vector<vector<PrimitiveVar>> w(2, vector<PrimitiveVar>(NumOfPnt + 2)); w[PREV][0] = Wl; for (int j = 1; j <= NumOfPnt; ++j) { if (x[j - 1] < xM) w[PREV][j] = Wl; else w[PREV][j] = Wr; } w[PREV][NumOfPnt + 1] = Wr; output(fout, 0, w[PREV], w[PREV]); //Iterate double t = 0.0; vector<InterCell> f(NumOfPnt + 1); vector<ConservativeVar> slope_vec(NumOfPnt+2); vector<ConservativeVar> u(NumOfPnt + 2); vector<vector<PrimitiveVar>> w_extrapolate(NumOfPnt+2, vector<PrimitiveVar>(2)); for (int i = 1; i < NumOfStep; i++) { cout << "Step: " << i << endl; if(i <= 5) CFL = 0.2; else if(i <= 10) CFL = 0.2 + (i-5) * 0.14; else CFL = 0.9; cout << "Converting to conservative form ..." << endl; for(int j = 0; j < NumOfPnt+2; ++j) u[j] = ConservativeVar(w[PREV][j]); // Choose proper time-step double S = 0.0; for (int j = 1; j <= NumOfPnt; ++j) { double S_local = fabs(w[PREV][j].u) + w[PREV][j].a; if (S_local > S) S = S_local; } const double dt = CFL * dx / S; t += dt; cout << "dt = " << dt << " t = " << t << endl; cout << "Data Reconstruction ..." << endl; // Slope vector at both left and right mirror points are set to 0 by default constructor. const double omega = 1.0 / 2; for(int j = 1; j <= NumOfPnt; ++j) { ConservativeVar slope_vec_left = u[j] - u[j-1]; ConservativeVar slope_vec_right = u[j+1] - u[j]; slope_vec_left *= 0.5 * (1+omega); slope_vec_right *= 0.5 * (1-omega); slope_vec[j] = slope_vec_left + slope_vec_right; } cout << "Evolving half of current time-step ... " << endl; const double loc_marching_factor = 0.5 * dt / dx; const vector<vector<double>> I{{0.5, 0, 0}, {0, 0.5, 0}, {0, 0, 0.5}}; vector<vector<double>> lMat(3, vector<double>(3, 0.0)); vector<vector<double>> rMat(3, vector<double>(3, 0.0)); for (int j = 0; j <= NumOfPnt+1; ++j) { // cout << "Processing point: " << j << endl; // Compute Matrix const double loc_rho = w[PREV][j].rho; const double loc_u = w[PREV][j].u; const double loc_a = w[PREV][j].a; vector<vector<double>> A{{loc_u, loc_rho, 0}, {0, loc_u, 1.0/loc_rho}, {0, loc_rho*pow(loc_a, 2), loc_u}}; for(int ii = 0; ii < 3; ++ii) for(int jj = 0; jj < 3; ++jj) A[ii][jj] *= loc_marching_factor; for(int ii = 0; ii < 3; ++ii) for(int jj = 0; jj < 3; ++jj) { lMat[ii][jj] = I[ii][jj] + A[ii][jj]; rMat[ii][jj] = I[ii][jj] - A[ii][jj]; } // Evolve double ltmp[3] = {0}, rtmp[3] = {0}; for(int kk = 0; kk < 3; ++kk) for(int tt = 0; tt < 3; ++tt) { ltmp[kk] += lMat[kk][tt] * slope_vec[j].at(tt); rtmp[kk] += rMat[kk][tt] * slope_vec[j].at(tt); } w_extrapolate[j][0].set(w[PREV][j].at(0) - ltmp[0], w[PREV][j].at(1) - ltmp[1], w[PREV][j].at(2) - ltmp[2]); w_extrapolate[j][1].set(w[PREV][j].at(0) + rtmp[0], w[PREV][j].at(1) + rtmp[1], w[PREV][j].at(2) + rtmp[2]); } cout << "Solving the Riemann Problem locally ... " << endl; for (int j = 0; j <= NumOfPnt; ++j) f[j].set(w_extrapolate[j][1], w_extrapolate[j+1][0]); //Apply the Godunov method const double r = -dt / dx; for (int j = 1; j <= NumOfPnt; ++j) { FluxVar cf = f[j].local_flux - f[j - 1].local_flux; ConservativeVar dU(cf.mass_flux() * r, cf.momentum_flux() * r, cf.energy_flux() * r); ConservativeVar U_prev(w[PREV][j]); ConservativeVar U_cur = U_prev + dU; w[CUR][j] = U_cur.toPrimitive(); } //Transmissive B.C. w[CUR][0] = w[CUR][1]; w[CUR][NumOfPnt + 1] = w[CUR][NumOfPnt]; //Calculate exact solution for comparision vector<PrimitiveVar> w_exact(NumOfPnt + 2); for (int j = 1; j <= NumOfPnt; ++j) { const double S = (x[j - 1] - xM) / t; ExactSol(Wl, Wr, p_middle, u_middle, rho_middle_left, rho_middle_right, S, w_exact[j]); } //Log output(fout, i, w[CUR], w_exact); swap(PREV, CUR); } fout.close(); } return 0; }
true
c451408b3d006412dcbe3bf973af52636086ad72
C++
wandsu/arduino
/semaforo.ino
UTF-8
1,722
2.796875
3
[]
no_license
//Botão Pedestre int botaoPedestre = (9); //Pinos Semáforo Carros int carrosVerde = (3); int carrosAmarelo = (2); int carrosVermelho = (1); //Pinos Semáforo Pedestre int pedestreVerde = (7); int pedestreVermelho = (6); void setup() { pinMode(botaoPedestre,INPUT); pinMode(pedestreVerde,OUTPUT); pinMode(pedestreVermelho,OUTPUT); pinMode(carrosVerde,OUTPUT); pinMode(carrosAmarelo,OUTPUT); pinMode(carrosVermelho,OUTPUT); } void loop() { while(digitalRead(botaoPedestre) != HIGH) { //Sinal Verde digitalWrite(carrosVermelho,LOW); digitalWrite(pedestreVerde,LOW); digitalWrite(carrosVerde,HIGH); digitalWrite(pedestreVermelho,HIGH); botaoPressionado(); delay(1000); botaoPressionado(); delay(1000); botaoPressionado(); delay(1000); botaoPressionado(); delay(1000); botaoPressionado(); delay(1000); botaoPressionado(); delay(1000); botaoPressionado(); delay(1000); botaoPressionado(); //Sinal Amarelo digitalWrite(carrosVerde,LOW); digitalWrite(carrosAmarelo,HIGH); delay(2000); //Sinal Vermelho digitalWrite(carrosAmarelo,LOW); digitalWrite(pedestreVermelho,LOW); digitalWrite(carrosVermelho,HIGH); digitalWrite(pedestreVerde,HIGH); delay(4000); } } void botaoPressionado(){ if(digitalRead(botaoPedestre) == HIGH) { digitalWrite(carrosVerde,LOW); digitalWrite(carrosAmarelo,HIGH); delay(2000); digitalWrite(carrosAmarelo,LOW); digitalWrite(pedestreVermelho,LOW); digitalWrite(carrosVermelho,HIGH); digitalWrite(pedestreVerde,HIGH); delay(4000); loop(); } }
true
4748cf9207ba91c8c91e3cb0770d42246ba374b0
C++
ltjohn25/Galaxianfinal
/includes/Star.h
UTF-8
718
2.75
3
[]
no_license
#ifndef STAR_H #define STAR_H #include <vector> #include <cmath> #include <ctime> #include <cstdlib> #include "Includes.h" #include "Rect.h" #include "Constants.h" #include "Color.h" #include "Surface.h" #include "Event.h" class Star { private: int x; int y; int h_; int w_; Color color; int star_dy; Surface & surface_; public: Star(int speed,int w,int h, Surface & surface) :surface_(surface),w_(w),h_(h), star_dy(speed) { color.r = rand() % 255; color.g = rand() % 255; color.b = rand() % 255; x = rand() % W; y = rand() % H; } void MoveStar(); void draw(); }; #endif
true
399379c278502b6528e262892b6e6b3696d27822
C++
Novota15/Space-Invaders
/controls.cpp
UTF-8
677
2.625
3
[]
no_license
// control functions #include "controls.h" void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { switch (key) { case GLFW_KEY_ESCAPE: if (action == GLFW_PRESS) game_running = false; break; case GLFW_KEY_RIGHT: if (action == GLFW_PRESS) move_dir += 1; else if(action == GLFW_RELEASE) move_dir -= 1; break; case GLFW_KEY_LEFT: if (action == GLFW_PRESS) move_dir -= 1; else if (action == GLFW_RELEASE) move_dir += 1; break; case GLFW_KEY_SPACE: if (action == GLFW_RELEASE) fire_pressed = true; break; default: break; } return; }
true
2317fe23a70f285baf57ef998e1fbd354755a206
C++
WhiZTiM/coliru
/Archive2/0d/91d6c1b887569a/main.cpp
UTF-8
852
3.140625
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <boost/asio.hpp> namespace foo { const int _1 = 1; const int _2 = 2; } template<typename Derived> struct helper { using Derived::_1; using Derived::_2; void print_this() { std::cout << _1 << ", " << _2 << std::endl; std::cout << static_cast<void*>(this) << std::endl; std::cout << static_cast<Derived*>(this) << std::endl; std::cout << static_cast<Derived*>(this)->value_ << std::endl; std::cout << ((Derived*)static_cast<void*>(this))->value_ << std::endl; } char dummy_[1000]; }; struct a { char dummy_[100]; }; struct b : a, helper<b> { enum { _1 = 1, _2 }; b() : value_(1000){} char dummy_[300]; int value_; }; int main() { b bb; bb.print_this(); return 0; }
true
c8da9ed9882827ada951ac6aef449bff61dfd9b8
C++
N4PSTER013/TheNewBostonCPP
/Class 8 || If.cpp
UTF-8
606
3.15625
3
[]
no_license
#include <iostream> using namespace std; int main() { if(5 > 2) { cout << "Bucky is awesome!" << endl; } if(1 > 2) { cout << "Bucky is awesome!" << endl; } if(2 >= 2) { cout << "Bucky is awesome!" << endl; } if(0 >= 2) { cout << "Bucky is awesome!" << endl; } if(5 != 2) { cout << "Bucky is awesome!" << endl; } if(3 == 3) { cout << "Bucky is awesome!" << endl; } int a = 100; int b = 87; if(a > b) { cout << "Bucky is awesome!" << endl; } return 0; }
true
916e17fee4a65caa8234208c13b8e525926fd7db
C++
dupes/carp
/shared/Object.h
UTF-8
1,382
2.734375
3
[]
no_license
/* * Object.h * * Created on: Nov 20, 2012 * Author: dupes */ #ifndef OBJECT_H_ #define OBJECT_H_ #include <string> #include <opencv2/imgproc/imgproc.hpp> #include "Database.h" #include "CVImage.h" using namespace std; using namespace cv; struct tObject { int id; int frame_id; Mat object_image; vector<Point> contour; Rect boundingBox; int number; double area; string label; int clusterID; bool verified; tObject(){}; tObject(const tObject &object) { // printf("copy construct\n"); id = object.id; frame_id = object.frame_id; object.object_image.copyTo(object_image); boundingBox = object.boundingBox; number = object.number; label = object.label; clusterID = object.clusterID; verified = object.verified; } }; class Object { private: sqlite3_stmt *m_insertObject; sqlite3_stmt *m_findObjectsByFrameID; sqlite3_stmt *m_findObjectsByVideoID; sqlite3_stmt *m_findObjectsByLabel; sqlite3_stmt *m_updateObject; sqlite3_stmt *m_currentSelect; Database *m_db; bool parseObject(tObject &object); public: Object(Database *db); virtual ~Object(); bool saveObject(tObject *object); bool updateObject(tObject *object); bool findObjects(int frameID); bool findByLabel(string label); bool findObjectsByVideoID(int videoID); bool nextObject(tObject &object); tObject *nextObject(); }; #endif /* OBJECT_H_ */
true
4d5895bc0ef924bbc880a40e076d055a78559a89
C++
zhongfanZhang/flightsim
/Physics.cpp
UTF-8
2,412
3.09375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <math.h> #include "Physics.h" #define DEG2RAD(x) ((x)*M_PI/180.0) #define RAD2DEG(x) ((x)*180.0/M_PI) Physics::Physics() { //position of the start of the runway position = glm::vec3(14.0, 96.0, 250.0); yaw = M_PI; pitch = 0.0; roll = 0.0; speed = 0.0; power = 0.0; } //speed is a scaled version of the plane's power output void Physics::updateSpeed(float deltaTime) { speed = 50 * power * deltaTime; } //position is updated using yaw and pitch only //we did not succeed in implementing roll void Physics::updatePosition(float deltaTime) { position.x += speed * glm::sin(-yaw) * glm::cos(pitch); //gravity is included which drops the plane's altitude based on the current speed position.y += speed * glm::sin(pitch) - (1/(10*speed + 1)); position.z += speed * glm::cos(-yaw) * glm::cos(pitch); } void Physics::setCollision() { power = 0; position = glm::vec3(14.0, 96.0, 220.0); yaw = M_PI; pitch = 0.0; roll = 0.0; } void Physics::setLanding() { pitch = 0.0; position.y = 96.0; } void Physics::setCeiling() { pitch = 0.0; position.y = 400.0; } float Physics::getYaw() { return yaw; } float Physics::getPitch() { return pitch; } float Physics::getRoll() { return roll; } glm::vec3 Physics::getPosition() { return position; } float Physics::getPower() { return power; } float Physics::getSpeed() { return speed; } void Physics::updateYaw(float yawInput, InputState &Input) { if (Input.qPressed){ yaw -= 2 * yawInput; } if (Input.ePressed){ yaw += 2 * yawInput; } } void Physics::updatePitch(float pitchInput, InputState &Input) { if (Input.wPressed){ pitch -= 2 * pitchInput; } if (Input.sPressed){ pitch += 2 * pitchInput; } } void Physics::updateRoll(float rollInput, InputState &Input) { if (Input.aPressed){ roll -= 2 * rollInput; } if (Input.dPressed){ roll += 2 * rollInput; } } void Physics::updatePower(float powerInput, InputState &Input) { if (Input.spacePressed){ power += 0.5 * powerInput; } else{ power -= 0.1 * powerInput; } if (Input.altPressed){ power -= 0.5 * powerInput; } if (power > 1.0){ power = 1.0; } if (power < 0.0){ power = 0.0; } }
true
ca5b35673278f4c8b1b85d690d07ceb251565088
C++
amandewatnitrr/Cpp
/String/Program_to_trace_out_sub_string.cpp
UTF-8
825
3.125
3
[]
no_license
#include<iostream> #include<conio.h> #include<process.h> #include<string.h> #define max 80 using namespace std; int main() { char m[max],s[max]; int n,len; cout<<"\nEnter the main String --> \n"; cin.getline(m,max); cout<<"\nEnter the start point for string --> "; cin>>n; if(n>strlen(m)) { cout<<"\nWrong Start Point in feed!! "; exit(0); } cout<<"\nEnter the length of the sub-string --> "; cin>>len; if(n>strlen(m)) { cout<<"\nWrong Start Point in feed!! "; exit(0); } if(n<=0) {cout<<"\nExtracted String is empty";} else if(n+len-1>strlen(m)) { cout<<"\nString size exceeding the limit"; len = len-n; } else { cout<<"\nNum = "<<len; } int j=0; for(int k=--n;k<=n+len;++k) { s[j]=m[k]; j++; } cout<<"\nSubstring = "; cout.write(s,j); return 0; }
true
e54dc997cf8c59921aa188516032821f173b4f2b
C++
FraserGreen/APT
/repoGit/PreRecVideos_w03/w03-03-pointers.cpp
UTF-8
665
3.375
3
[]
no_license
#include <iostream> #define ROWS 10 #define COLS 5 int main(void) { int x = 10; int y = -3; int* ptr = &x; int* qtr = &y; // int** pptr = &ptr; // int*** ppptr = &pptr; std::cout << x << std::endl; std::cout << y << std::endl; std::cout << *ptr << std::endl; std::cout << *qtr << std::endl; // std::cout << **pptr << std::endl; // std::cout << ***ppptr << std::endl; // int array[ROWS][COLS] = {}; // for (int i = 0; i < ROWS; ++i) { // for (int j = 0; j < COLS; ++j) { // std::cout << i << j << ": " << array[i][j] << std::endl; // } // } return EXIT_SUCCESS; }
true
c2adb97b40a6c541b2303017d3f8e7cd6a5eae43
C++
hmmvot/gltest
/GLTest/src/Renderer.cpp
UTF-8
3,419
2.5625
3
[ "MIT" ]
permissive
#include "Renderer.h" #include "Camera.h" #include <list> void Renderer::Render(const Camera &camera, const std::vector<ObjectRef> &objects) { glClearColor(0.9f, 0.9f, 0.9f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); const auto projection = camera.GetProjectionMatrix(); const auto view = camera.GetViewMatrix(); std::list<ObjectRef> lights; for (const auto &obj : objects) { if (obj->light) { if (obj->light->type == Light::Type::Directional) { if (lights.size() > 0 && lights.front()->light->type == Light::Type::Directional) { std::cout << "Only one directional ligth on scene supported" << std::endl; continue; } lights.push_front(obj); } else { lights.push_back(obj); } } } for (const auto &obj : objects) { auto material = obj->material; auto mesh = obj->mesh; if (!mesh || !material) { continue; } auto shader = material->GetShader(); shader->Use(); shader->SetInt("actualLightsCount", lights.size()); int i = 0; for (auto light : lights) { light->light->Setup(shader, i++, light->GetMatrix(), light->GetPosition()); } shader->SetVec3("cameraPos", camera.GetPosition()); shader->SetMat4("projection", projection); shader->SetMat4("view", view); shader->SetMat4("model", obj->GetMatrix()); shader->SetMat3("normalMatrix", obj->GetNormalMatrix()); if (obj->light) { shader->SetVec3("color", obj->light->ambient); } else { shader->SetVec3("material.ambient", material->ambient); shader->SetVec3("material.diffuse", material->diffuse); shader->SetVec3("material.specular", material->specular); shader->SetFloat("material.shiness", material->shiness); shader->SetFloat("textures[0].intensity", material->mainTex.intensity); shader->SetVec2("textures[0].scale", material->mainTex.scale); shader->SetVec2("textures[0].shift", material->mainTex.GetShift()); shader->SetFloat("textures[1].intensity", material->tex1.intensity); shader->SetVec2("textures[1].scale", material->tex1.scale); shader->SetVec2("textures[1].shift", material->tex1.GetShift()); shader->SetFloat("textures[2].intensity", material->tex2.intensity); shader->SetVec2("textures[2].scale", material->tex2.scale); shader->SetVec2("textures[2].shift", material->tex2.GetShift()); shader->SetFloat("textures[3].intensity", material->tex3.intensity); shader->SetVec2("textures[3].scale", material->tex3.scale); shader->SetVec2("textures[3].shift", material->tex3.GetShift()); glActiveTexture(GL_TEXTURE0); GLuint id = material->mainTex.texture ? material->mainTex.texture->GetId() : 0; glBindTexture(GL_TEXTURE_2D, id); shader->SetInt("textures[0].id", 0); glActiveTexture(GL_TEXTURE1); id = material->tex1.texture ? material->tex1.texture->GetId() : 0; glBindTexture(GL_TEXTURE_2D, id); shader->SetInt("textures[1].id", 1); glActiveTexture(GL_TEXTURE2); id = material->tex2.texture ? material->tex2.texture->GetId() : 0; glBindTexture(GL_TEXTURE_2D, id); shader->SetInt("textures[2].id", 2); glActiveTexture(GL_TEXTURE3); id = material->tex3.texture ? material->tex3.texture->GetId() : 0; glBindTexture(GL_TEXTURE_2D, id); shader->SetInt("textures[3].id", 3); } mesh->Draw(); } }
true
6bb5875cace6c272355b0f85732063055d5acbd7
C++
trikstor/laboratory_work
/lab2/main.cpp
UTF-8
2,091
3.453125
3
[]
no_license
#include <iostream> #include <cstdlib> #include <iostream> #include <cstdlib> #include <cmath> #include "func_mass.h" using namespace std; /* * 8. *Сформировать одномерный массив целых чисел, используя датчик случайных чисел. *Распечатать полученный массив. *Удалить все элементы с заданным значением. *Добавить перед каждым четным элементом массива элемент со значением 0. *Распечатать полученный массив. */ int main() { int num, del_val, n; srand(time(NULL)); // Генерирует случайное число, используя текущею дату, как параметр, для непредсказуемости результата. cout << "Введите кол-во элементов массива."<< endl; cin >> num; // Ввод количества элементов массивва. int *mass = new int[num]; // Объявление массива, который будет заполнен случайными числами. cycle_rand(num, mass); // Заполнение массива mass случайными числами. cout << "Введите число для удаления."<< endl; cin >> del_val; // Ввод числа, которое будет удалено из массива. n = cycle_counter(num, mass, del_val); // Подсчет элементов массива после удаления элементов del_val и добавления 0 к четным элементам массива. cycle_fill(num, mass, del_val); // Заполнение нового массива элементами старого без del_val и с нулем перед четными элементами. delete [] mass; // Удаление массива. system("pause"); // Для MVS return 0; }
true
e0b3a6f1dd10ee2fdcb717e8303219e00ab23eb7
C++
AL5624/TH-Rosenheim-Backup
/INF/B4/Rechnerarchitektur (RA)/CA_exercises/sheet_12_bus/io_prog_isolated_io/io_prog_isolated_io.ino
UTF-8
972
2.984375
3
[]
no_license
//TODO: set a "1" for ON and a "0" for OFF for the right bit into the register. //use an appropriate number representation for that. //".equ" is nearly similar to the C-preprocessor statement "#define" asm (".equ ON, "); //value for enable (switch on) asm (".equ OFF, "); //value for disable (switch off) void setup() { //The built-in LED is connected to digital PIN 13, //which is physically connected to PB7 on the ATMEGA 2560, //so we have to set it as OUTPUT DDRB |= 1 << DDB7; //Using a MACRO to increase the readability // DDRB = DDRB | B10000000; //but this is also a possible solution } void loop() { //Switch LED on asm("ldi r16, ON"); // load the immediate value ON into r16 //TODO: check out the ATmega Datasheet for the separate IO memory space asm("out ,r16"); delay(1000); //wait a second //Switch LED off //TODO: switch of the LED using and modifying your assembly code from above delay(1000); //wait a second }
true
de03f750e0a1d3524a372f837cff36c5e26930c8
C++
MaciekMr/SofarInverter
/inverter.cpp
UTF-8
2,134
2.625
3
[]
no_license
#include "inverter.h" #include "configmodel.h" #include "datacollector.h" #include <threadset.h> #include <connector.h> #include "definitions.h" Inverter::Inverter() { timer = new QTimer(this); worker = nullptr; //new Worker(new server_point); } Inverter::~Inverter(){ if(timer->isActive()) timer->stop(); delete(timer); } /****************************** * inv_id - id of configuration of inverter * * get inverter parameters, ip and port * and fire the worker * * Set up the timer to update data from inverter * ***********************************/ void Inverter::setup(string inv_id){ //1. Set up the connection // - get configuration ConfigModel *conf = ConfigModel::getConfig(); m_address.append(conf->findparameter<string>(inv_id,IP)); m_port.append(conf->findparameter<string>(inv_id,PORT)); //set the server_point target _target(&m_address, &m_port); //Create Worker worker = new Worker(std::stoi(inv_id)); // - get the pointer to logger DataCollector *datacollector = DataCollector::getDataCollector(); auto object = datacollector->findModel("logwindow"); //Start the worker thread Thread inverter_thread(&Worker::client_connect, worker); // - set the timer connect(timer, &QTimer::timeout, this, &Inverter::update); timer->start(1000); } /*********************************** * Method to use every second by QTimer * the interrupt runs the single run thread * where the connection is established * and data is collected * * Worker will be unbreakable connected to inverter * this method will: * 1. Check the connectivity of worker (if unconnected, reconnect) * 2. Get the current data from worker * 3. Send data to data storage (file, db, xml, etc.) * * *********************************/ void Inverter::update(){ //cretate thread //Thread inverter_thread(std::function<Worker>Worker::client_connect, worker); Thread inverter_thread(&Worker::client_connect, worker); //Get the record //Update the logmodel by a new record //store record to database //end thread }
true
f0730f70c2c7105cf8a83839344411816dd69fcb
C++
RomainDuclos/M1alma2017-2018_Complexite
/Complex/include/AlgoLib.hpp
UTF-8
6,596
3.203125
3
[]
no_license
#ifndef ALGOLIB_HPP #define ALGOLIB_HPP #include <vector> #include <iostream> #include <string> #include "../include/MyLib.hpp" using namespace std; int LSA(vector<int> v) { vector<Machine> ens_mach; vector<Tache> ens_tache; //Creation machines for (int i = 0; i < v[0]; ++i) { Machine m; m.ind = i; ens_mach.push_back(m); } //Creation ensemble tache for (int i = 0; i < v[1]; ++i) { Tache t; t.ind = i; t.duree = v[i+2]; ens_tache.push_back(t); } //<TEST> : affiche indice machine /* for (int i = 0; i < ens_mach.size(); ++i) { cout << ens_mach[i].ind << " "; } cout << endl; //affiche duree taches for (int i = 0; i < ens_tache.size(); ++i) { cout << ens_tache[i].ind << " "; } cout << endl; */ //</TEST> //nombre de tache libre int nb_free_task = ens_tache.size(); int ind = 0; //indice des taches int time = 0; //simule le traitement des taches par une machine //tant qu' on a des taches non affectées while(nb_free_task != 0) { //on parcours les machines for (int i = 0; i < ens_mach.size(); ++i) { //si une est libre if(ens_mach[i].libre) { //alors on affecte une tache en ajoutant la durée de la tache à l'occupation de la machine ens_mach[i].occupation = ens_mach[i].occupation + ens_tache[ind].duree; ind ++; //on passe à la tache suivante nb_free_task--; //on a une tache de moins à affecter ens_mach[i].libre = false; //et la machine est occupée } else //si une machine n'est pas libre { if(ens_mach[i].occupation == time - 1) //si une machine traite une tache depuis temps - 1 { ens_mach[i].libre = true; //alors au prochain tour de boucle elle sera bien libre } } } time++; //le temps de traitement passe à plus 1 } //<TEST> : affichage occupation machine /* for (int i = 0; i < ens_mach.size(); ++i) { cout << ens_mach[i].ind << " : " << ens_mach[i].occupation << " ; "; } cout << endl; */ //</TEST> //Résultat : temps d'occupation maximum d'une machine int max = ens_mach[0].occupation; for (int i = 0; i < ens_mach.size(); ++i) { if (max < ens_mach[i].occupation) { max = ens_mach[i].occupation; } } return max; } int LPT(vector<int> v) { vector<Machine> ens_mach; vector<Tache> ens_tache; //Creation machines for (int i = 0; i < v[0]; ++i) { Machine m; m.ind = i; ens_mach.push_back(m); } //Creation ensemble tache for (int i = 0; i < v[1]; ++i) { Tache t; t.ind = i; t.duree = v[i+2]; ens_tache.push_back(t); } //On ordonne les taches taskQuickSort(ens_tache,0,ens_tache.size()-1,true); //<TEST> : affiche indice machine /* for (int i = 0; i < ens_mach.size(); ++i) { cout << ens_mach[i].ind << " "; } cout << endl; //affiche duree taches for (int i = 0; i < ens_tache.size(); ++i) { cout << ens_tache[i].ind << " : " << ens_tache[i].duree << " ; "; } cout << endl; */ //</TEST> //nombre de tache libre int nb_free_task = ens_tache.size(); int ind = 0; //indice des taches int time = 0; //simule le traitement des taches par une machine //tant qu' on a des taches non affectées while(nb_free_task != 0) { //on parcours les machines for (int i = 0; i < ens_mach.size(); ++i) { //si une est libre if(ens_mach[i].libre) { //alors on affecte une tache en ajoutant la durée de la tache à l'occupation de la machine ens_mach[i].occupation = ens_mach[i].occupation + ens_tache[ind].duree; ind ++; //on passe à la tache suivante nb_free_task--; //on a une tache de moins à affecter ens_mach[i].libre = false; //et la machine est occupée } else //si une machine n'est pas libre { if(ens_mach[i].occupation == time - 1) //si une machine traite une tache depuis temps - 1 { ens_mach[i].libre = true; //alors au prochain tour de boucle elle sera bien libre } } } time++; //le temps de traitement passe à plus 1 } //<TEST> : affichage occupation machine /* for (int i = 0; i < ens_mach.size(); ++i) { cout << ens_mach[i].ind << " : " << ens_mach[i].occupation << " ; "; } cout << endl; */ //</TEST> //Résultat : temps d'occupation maximum d'une machine int max = ens_mach[0].occupation; for (int i = 0; i < ens_mach.size(); ++i) { if (max < ens_mach[i].occupation) { max = ens_mach[i].occupation; } } return max; } //Pour le moment c'est comme LPT mais avec order croissant int MyAlgo(vector<int> v) { vector<Machine> ens_mach; vector<Tache> ens_tache; //Creation machines for (int i = 0; i < v[0]; ++i) { Machine m; m.ind = i; ens_mach.push_back(m); } //Creation ensemble tache for (int i = 0; i < v[1]; ++i) { Tache t; t.ind = i; t.duree = v[i+2]; ens_tache.push_back(t); } //On ordonne les taches taskQuickSort(ens_tache,0,ens_tache.size()-1,false); //<TEST> : affiche indice machine /* for (int i = 0; i < ens_mach.size(); ++i) { cout << ens_mach[i].ind << " "; } cout << endl; //affiche duree taches for (int i = 0; i < ens_tache.size(); ++i) { cout << ens_tache[i].ind << " : " << ens_tache[i].duree << " ; "; } cout << endl; */ //</TEST> //nombre de tache libre int nb_free_task = ens_tache.size(); int ind = 0; //indice des taches int time = 0; //simule le traitement des taches par une machine //tant qu' on a des taches non affectées while(nb_free_task != 0) { //on parcours les machines for (int i = 0; i < ens_mach.size(); ++i) { //si une est libre if(ens_mach[i].libre) { //alors on affecte une tache en ajoutant la durée de la tache à l'occupation de la machine ens_mach[i].occupation = ens_mach[i].occupation + ens_tache[ind].duree; ind ++; //on passe à la tache suivante nb_free_task--; //on a une tache de moins à affecter ens_mach[i].libre = false; //et la machine est occupée } else //si une machine n'est pas libre { if(ens_mach[i].occupation == time - 1) //si une machine traite une tache depuis temps - 1 { ens_mach[i].libre = true; //alors au prochain tour de boucle elle sera bien libre } } } time++; //le temps de traitement passe à plus 1 } //<TEST> : affichage occupation machine /* for (int i = 0; i < ens_mach.size(); ++i) { cout << ens_mach[i].ind << " : " << ens_mach[i].occupation << " ; "; } cout << endl; */ //</TEST> //Résultat : temps d'occupation maximum d'une machine int max = ens_mach[0].occupation; for (int i = 0; i < ens_mach.size(); ++i) { if (max < ens_mach[i].occupation) { max = ens_mach[i].occupation; } } return max; } #endif
true
a4515da25003a3f7534254f71f60dcc7b86b5a75
C++
abhishek1BM19CS400/C-plusplus
/Day-1/bitwise.cpp
UTF-8
348
3.484375
3
[]
no_license
#include <iostream> using namespace std; int main() { int a = 10, b = 12; int c1, c2, c3, c4, c5; c1 = a & b; //And c2 = a | b; //or c3 = ~a; //not c4 = a >> b; //right shift c5 = a << b; //left shift cout << c1 << endl; cout << c2 << endl; cout << c3 << endl; cout << c4 << endl; cout << c5 << endl; }
true
69d2aae7d4ec73375bd0aa1a4b8233ceb3fb53c3
C++
cstrike111/Watermelon
/GameEngine/GameEngine/Physics/Physics.h
UTF-8
2,006
2.90625
3
[]
no_license
#pragma once #include <string> #include <map> #include "..\Entity\Entity.h" #include "..\EventSystem\EventSystem.h" #include "..\Profile\Profile.h" #include "Box2D\Box2D.h" #include "..\Entity\BulletEntity.h" #include "ContactListener.h" #include <vector> using namespace std; class Physics { public: /* For the unit conversion: 1 m = 10 pixels. 1 m = 1 unit pixel. */ Physics(b2Vec2 gravity); ~Physics(); //constant float UNIT_PIXEL = 10; bool collisionDetect(Entity* e1, Entity* e2); //collision detect between 2 entity void update(); //update every entity and apply some features (gravity etc.) void handleEvent(int eventType); //handle the events //add entity to the system void addStaticEntity(Entity* e); //add static entity void addDynamicEntity(Entity* e); //add dynamic entity void addBullet(BulletEntity* e, int player); void setEventSystem(EventSystem* es); void getPlayer(Entity* player1, Entity* player2); //get player pointer void setGravity(b2Vec2 gravity); //change the gravity void createBody(Entity* e); //create box2d body void setProfileSystem(Profile* pro); //some actions to the player void hitPlayer(float damage, int player, int direction); //contact listener ContactListener cl; //bullet list vector<BulletEntity*> bulletList1; //bulletList1 vector<BulletEntity*> bulletList2; //bulletList2 //jump parameter bool jump1; bool doubleJump1; bool jump2; bool doubleJump2; //win flag bool win = false; //parameter for the player float PLAYER_MOVE_SPEED = 50; private: /* Here! This is a list of pointers of entities. Don't forget clean the memory of entities after you use them. */ vector<Entity*> dynamicEntityList; vector<Entity*> staticEntityList; Entity* player1; //player1 object Entity* player2; //plyaer2 object //static entity list? EventSystem* es; //get the event system Profile* pro; //get the profile system //store the information of box2d b2Vec2 gravity; b2World* world; float timeStep = 1.0f / 60.0f; };
true
43dbbc729d2eeaed85bf9211e8fb06cf612f2b66
C++
elbica/INHA
/02_22/Eunseo/10824.cpp
UTF-8
341
3.09375
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { int a, b, c, d; cin >> a >> b >> c >> d; string s1, s2; s1 = to_string(a) + to_string(b); s2 = to_string(c) + to_string(d); long long num1 = stoll(s1); //string -> int long long num2 = stoll(s2); cout << num1 + num2; return 0; }
true
31af7d6eb86d5b938d4a2e91bc63bbee750143b1
C++
repmop/CUDAbins
/main.cpp
UTF-8
1,833
2.84375
3
[]
no_license
/* * CLI for bin-packing optimizer * Takes an input file in the format specified in README.md */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <iostream> #include <unistd.h> #include "bin.h" #include "parse.h" void usage() { fprintf(stderr, "-f /path/to/input [-o /path/to/output]\n"); } int threads_per_block = 1; int main(int argc, char *argv[]) { char *infile = NULL; char *outfile = NULL; bool bfd_flag = false; int opt; opterr = 0; while ((opt = getopt(argc, argv, "f:o:bt:")) != -1) { switch (opt) { case 'f': infile = optarg; break; case 'o': outfile = optarg; break; case 'b': bfd_flag = true; break; case 't': threads_per_block = atoi(optarg); break; case '?': if (optopt == 'f') { fprintf(stderr, "Option -%c requires an argument.\n", optopt); } else if (optopt == 'o') { fprintf(stderr, "Option -%c requires an argument.\n", optopt); } else if (optopt == 't') { fprintf(stderr, "Option -%c requires an argument.\n", optopt); } else if (isprint (optopt)) { fprintf(stderr, "Unknown option `-%c'.\n", optopt); } else { fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); usage(); return 1; } default: fprintf(stderr, "Malformed input arguments. Aborting.\n"); usage(); return 1; } } if (infile==NULL) { fprintf(stderr, "Input file unspecified\n"); usage(); return 1; } if (!parse(infile)) { fprintf(stderr, "Failed to parse input\n"); } if(!bfd_flag){ run(); } else { runBFD(); } if (!dump(outfile)) { fprintf(stderr, "Failed to write output\n"); } return 0; }
true
ffb1d2e98a23bebf4744e4c3c7ee63a8df97c359
C++
Zhiwei5/Duke-Algorithm-Data-Structure-Class
/dukeC++class/077_sort_cpp/sortLines.cpp
UTF-8
1,201
3.5625
4
[]
no_license
#include <algorithm> #include <fstream> #include <iostream> #include <string> #include <vector> void print_vec(std::vector<std::string> & vec) { std::vector<std::string>::iterator it = vec.begin(); while (it != vec.end()) { std::cout << *it << std::endl; ++it; } } int main(int argc, char ** argv) { if (argc == 1) { std::string line; std::vector<std::string> vec; while (std::getline(std::cin, line)) { if (line.length() == 0) { continue; } vec.push_back(line); } std::sort(vec.begin(), vec.end()); print_vec(vec); } if (argc > 1) { for (int i = 1; i < argc; ++i) { const char * file_name = argv[i]; std::ifstream in_file; in_file.open(file_name, std::ios::in); if (!in_file) { std::cerr << "cannot open the file" << std::endl; return EXIT_FAILURE; } std::string line; std::vector<std::string> vec; while (std::getline(in_file, line)) { if (line.length() == 0) { continue; } vec.push_back(line); } std::sort(vec.begin(), vec.end()); print_vec(vec); in_file.close(); } } return EXIT_SUCCESS; }
true
a7731442c03c91938122b6ac4a6f6e3ca6e24c15
C++
dOrgJelli/UrsineMath
/Source/UrsineMath.hpp
UTF-8
3,279
3.140625
3
[ "MIT" ]
permissive
/* --------------------------------------------------------------------------- ** Team Bear King ** DigiPen Institute of Technology 2014 ** ** UrsineMath.hpp ** ** Author: ** - Jordan Ellis - J.Ellis@digipen.edu ** ** Contributors: ** - <list in same format as author if applicable> ** -------------------------------------------------------------------------*/ #pragma once #include <math.h> #include <stdlib.h> namespace ursine { namespace math { template<typename T> inline bool IsZero(T value) { return (value <= math::Epsilon) && (value >= -math::Epsilon); } template<typename T1, typename T2> inline bool IsEqual(T1 a, T2 b) { return ((a >= b) ? (a - b) : (b - a)) < math::Epsilon; } // for use on doubles and floats // http://www.johndcook.com/blog/ieee_exceptions_in_cpp/ template<typename T> inline bool IsFiniteNumber(T x) { return (x <= std::numeric_limits<T>::max() && x >= -std::numeric_limits<T>::max()); } template<typename T> inline T Clamp(T value, T min, T max) { if (!IsFiniteNumber(value)) { if (value < 0) value = min; else value = max; } return (value > max) ? max : ((value < min) ? min : value); } template<typename T> inline T Max(T a, T b) { return (a > b) ? a : b; } template<typename T> inline T Min(T a, T b) { return (a < b) ? a : b; } inline float Wrap(float in_val, float min, float max) { float range = max - min; float val = fmod(in_val, range); // fmod doesn't function like normal % on negative numbers // this forces the same behavior. Talk to Jordan for further // explanation. if (val < 0) val += range; val += min; return val; } template<typename T> T Lerp(const T &a, const T &b, float percent) { return a + (b - a) * percent; } template<typename T> T Rand(T min, T max) { return min + rand() / static_cast<T>(RAND_MAX / (max - min)); } inline float fastSqrt(float val) { if (val == 0.0f) return 0.0f; union { float f; int i; } workval; workval.f = val; workval.i -= 0x3f800000; // subtract 127 from biased exponent workval.i >>= 1; // requires signed shift to preserve sign workval.i += 0x3f800000; // rebias the new exponent workval.i &= 0x7FFFFFFF; // remove sign bit return workval.f; } inline float RadiansToDegrees(float radians) { static const float scalar = 180.0f / PI; return radians * scalar; } inline float DegreesToRadians(float degrees) { static const float scalar = PI / 180.0f; return degrees * scalar; } } }
true
296bccc21e30e40163066449f1035f2de989ab4f
C++
yangyanggong28/SmartString
/SmartString_test/SmartString_test.cpp
UTF-8
1,376
2.859375
3
[]
no_license
// SmartString_test.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <vector> #include <string> #include "SmartString.h" int main() { SmartString testStr(" gyy "); std::cout << testStr << std::endl; testStr.trimLeft(); std::cout << "trimLeft testStr is:" << testStr << std::endl; SmartString testStr89(" gyy "); testStr89.trimRight(); std::cout << "trimRight testStr is:" << testStr89 << std::endl; SmartString testStr1(" gyy "); testStr1.trim(); std::cout << "trim testStr1 is:" << testStr1 << std::endl; SmartString testStr2(" gyy "); std::cout << "trimmed testStr2 is:" << testStr2.trimmed() << std::endl; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
true
bc32d93a670a6c87a5921733e7afa9ecb33a0d0c
C++
wpilibsuite/allwpilib
/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Elevator.h
UTF-8
1,632
2.59375
3
[ "BSD-3-Clause" ]
permissive
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #pragma once #include <frc/AnalogPotentiometer.h> #include <frc/motorcontrol/PWMSparkMax.h> #include <frc2/command/PIDSubsystem.h> /** * The elevator subsystem uses PID to go to a given height. Unfortunately, in * it's current * state PID values for simulation are different than in the real world do to * minor differences. */ class Elevator : public frc2::PIDSubsystem { public: Elevator(); /** * The log method puts interesting information to the SmartDashboard. */ void Log(); /** * Use the potentiometer as the PID sensor. This method is automatically * called by the subsystem. */ double GetMeasurement() override; /** * Use the motor as the PID output. This method is automatically called * by * the subsystem. */ void UseOutput(double output, double setpoint) override; /** * Log the data periodically. This method is automatically called * by the subsystem. */ void Periodic() override; private: frc::PWMSparkMax m_motor{5}; double m_setpoint = 0; // Conversion value of potentiometer varies between the real world and // simulation #ifndef SIMULATION frc::AnalogPotentiometer m_pot{2, -2.0 / 5}; #else frc::AnalogPotentiometer m_pot{2}; // Defaults to meters #endif static constexpr double kP_real = 4; static constexpr double kI_real = 0.07; static constexpr double kP_simulation = 18; static constexpr double kI_simulation = 0.2; };
true
82080a6d35f004fd4c8de4a049e799794cac4107
C++
dujingui/LetCode
/LetCode/LetCode/Code_1603.h
UTF-8
482
3.1875
3
[]
no_license
#pragma once #include "Define.h" class ParkingSystem { public: enum CarType { BIG, MEDIUM, SMALL, MAX, }; public: ParkingSystem(int big, int medium, int small) { m_ParkingNum[CarType::BIG] = big; m_ParkingNum[CarType::MEDIUM] = medium; m_ParkingNum[CarType::SMALL] = small; } bool addCar(int carType) { if (m_ParkingNum[carType - 1] > 0) { m_ParkingNum[carType] --; return true; } return false; } private: int m_ParkingNum[CarType::MAX]; };
true
ffb3abaa3a5ea850770d470572ce42424a666826
C++
mikee649/Project-Euler-Solutions
/Problems/P107/Disjoint_sets.h
UTF-8
2,738
3.34375
3
[]
no_license
#ifndef DISJOINT_SET_H #define DISJOINT_SET_H #ifndef nullptr #define nullptr 0 #endif #include <limits> using namespace std; struct ll_entry; // represents each element of the linked list struct set_info; // keeps track of the information (pointers to head and tail and the size of the set) of each set //could we delete the above two lines? struct ll_entry{ int content; set_info* ptr_to_info; // ptr to the info entry of the corresponding set ll_entry* next; }; struct set_info { ll_entry* head; ll_entry* tail; int size; }; class Disjoint_set { private: ll_entry** nodes; set_info** sets; int set_counter; int initial_num_sets; public: Disjoint_set(int); ~Disjoint_set(); int find_set(int) const; int num_sets() const; void union_sets(int, int); }; Disjoint_set::Disjoint_set(int n) : nodes(new ll_entry*[n]), sets (new set_info*[n]), set_counter(n), initial_num_sets(n) { for(int i = 0; i < n; i++){ nodes[i] = new ll_entry; sets[i] = new set_info; nodes[i]->content = i; nodes[i]->next = nullptr; nodes[i]->ptr_to_info = sets[i]; sets[i]->head = nodes[i]; sets[i]->tail = nodes[i]; sets[i]->size = 1; } } Disjoint_set::~Disjoint_set() { for(int i = 0; i < initial_num_sets; i++){ delete nodes[i]; delete sets[i]; } delete[] nodes; delete[] sets; } int Disjoint_set::find_set(int item) const{ return nodes[item]->ptr_to_info->head->content; } int Disjoint_set::num_sets() const { return set_counter; } void Disjoint_set::union_sets(int node_index1, int node_index2) { if (node_index1 == node_index2) return; set_info* si1 = nodes[node_index1]->ptr_to_info; set_info* si2 = nodes[node_index2]->ptr_to_info; // ni1: the index of the larger set, ni2: the index of the smaller index int ni1 = si1->size >= si2->size ? node_index1 : node_index2; int ni2 = si1->size < si2->size ? node_index1 : node_index2; ll_entry* head = nodes[ni1]->ptr_to_info->head; ll_entry* tail = nodes[ni2]->ptr_to_info->tail; head->ptr_to_info->tail->next = tail->ptr_to_info->head; head->ptr_to_info->tail = tail; head->ptr_to_info->size = head->ptr_to_info->size + tail->ptr_to_info->size; ll_entry* traverse = nodes[ni2]->ptr_to_info->head; while(traverse != nullptr){ traverse->ptr_to_info = head->ptr_to_info; traverse = traverse->next; } // do we need to modify anything else? // delete the set_info entry that no longer exists //delete sets[ni2]; } #endif
true
78b3bd1ffe7b06b69d4501ae8c69171ae227abc2
C++
hanky3/HLP_CodeJam
/AlgoSpot/02_Graph/MCHESS.cpp
UTF-8
3,737
2.59375
3
[]
no_license
#include <stdio.h> #include <string.h> #include <iostream> #include <vector> #include <queue> #include <map> using namespace std; #define MAX_TEXT_SIZE 101 typedef pair<int, int> _pos; FILE *fpInput; FILE *fpOutput; int N; vector<vector<char>> chessMap; _pos startPos; _pos endPos; map<char, vector<_pos>> chessDirections; map<char, bool> chessDirOnce; vector<vector<bool>> visited; // P B N R Q K void initConstValue() { chessDirOnce.insert(make_pair('P', true)); chessDirOnce.insert(make_pair('B', false)); chessDirOnce.insert(make_pair('N', true)); chessDirOnce.insert(make_pair('R', false)); chessDirOnce.insert(make_pair('Q', false)); chessDirOnce.insert(make_pair('K', true)); vector<_pos> posList = {{-1,-1}, {-1,1}, {1,-1}, {1,1}, {0,1}, {0,-1}, {-1,0}, {1,0}}; chessDirections.insert(make_pair('K', posList)); chessDirections.insert(make_pair('Q', posList)); posList = { {1,0} }; chessDirections.insert(make_pair('P', posList)); posList = { {-1,-1}, {-1,1}, {1,-1}, {1,1} }; chessDirections.insert(make_pair('B', posList)); posList = { {1,2}, {1,-2}, {-1,2}, {-1,-2}, {2,-1}, {2,1}, {-2,-1}, {-2,1} }; chessDirections.insert(make_pair('N', posList)); posList = { {0,1}, {0,-1}, {-1,0}, {1,0} }; chessDirections.insert(make_pair('R', posList)); } void readInputData() { fscanf(fpInput, "%d\n", &N); chessMap = vector<vector<char>>(N + 1, vector<char>(N + 1, 0)); visited = vector<vector<bool>>(N + 1, vector<bool>(N + 1, false)); fscanf(fpInput, "%d %d %d %d\n", &startPos.first, &startPos.second, &endPos.first, &endPos.second); for (int h = N; h >= 1; h--) { for (int w = 1; w <= N; w++) { fscanf(fpInput, "%c", &chessMap[h][w]); } fscanf(fpInput, "\n"); } } void candidateMoves(int step, _pos curr, char type, queue<pair<int, pair<_pos, char>>> &q) { if (type == '.') return; vector<_pos> directions = chessDirections[type]; bool once = chessDirOnce[type]; for (auto dir : directions) { int m = 1; while (true) { _pos next(curr.first + (dir.first*m), curr.second + (dir.second*m)); if (next.first <= 0 || next.first > N || next.second <= 0 || next.second > N) break; if (!visited[next.first][next.second]) q.push(make_pair(step+1, make_pair(next, type))); if (once) break; m++; } } } int minMovesToDest() { int ret = 0; queue<pair<int, pair<_pos, char>>> q; q.push(make_pair(0, make_pair(startPos, 'K'))); while (true) { int step = q.front().first; _pos currPos = q.front().second.first; char type = q.front().second.second; q.pop(); if (endPos == currPos) return step; if (currPos.first <= 0 || currPos.first > N || currPos.second <= 0 || currPos.second > N) continue; if (visited[currPos.first][currPos.second]) continue; visited[currPos.first][currPos.second] = true; candidateMoves(step, currPos, type, q); char newType = chessMap[currPos.first][currPos.second]; if (type != newType) candidateMoves(step, currPos, newType, q); } return -1; } void solveProblem(const char *fileName, bool isFile) { fpInput = stdin; fpOutput = stdout; if (isFile) { fpInput = fopen(fileName, "r"); string outputFileName = string(fileName); outputFileName = outputFileName.substr(0, outputFileName.length() - 2) + "out"; fpOutput = fopen(outputFileName.c_str(), "w"); } initConstValue(); int testCase = 0; fscanf(fpInput, "%d", &testCase); while (testCase > 0) { readInputData(); int ret = minMovesToDest(); if (isFile) { printf("%d\n", ret); } fprintf(fpOutput, "%d\n", ret); testCase--; } fclose(fpInput); fclose(fpOutput); } int main(int argc, char* argv[]) { #ifdef _FILE_ solveProblem(argv[1], true); #else solveProblem("", false); #endif return 0; }
true
1a406297230d2c2e0b26cce88b5a27d4c0a55a12
C++
tangsancai/algorithm
/PAT-B/1013. 数素数.cpp
UTF-8
596
2.6875
3
[]
no_license
#include<stdio.h> #include<math.h> int main() { int M; int N; scanf("%d%d",&M,&N); int i=0; int Num=2; int flag=0; int huan=0; while(i<=N) { for(int j=2;j<=(int)sqrt((double)Num);j++) { if(Num%j==0) { flag=1; break; } } if(flag==1) { flag=0; } else { i++; if(i>=M&&i<N) { huan++; printf("%d",Num); if(huan==10) { printf("\n"); huan=0; } else { printf(" "); } } else if(i>=M&&i==N) { printf("%d\n",Num); } } Num++; } }
true
fe03d7124114971843b16f0fe8421b07e9048864
C++
ArtTolston/myrepository
/Coursera_MIPT_Yandex_Courses/Yellow_Belt_C++/bus_stations-2/bus_manager.cpp
UTF-8
2,046
2.890625
3
[]
no_license
#include "bus_manager.h" #include "responses.h" void BusManager::AddBus(const string& bus, const vector<string>& stops) { for(const auto& i: stops) { BusManager::stops_for_buses[bus].push_back(i); BusManager::buses_for_stops[i].push_back(bus); } } BusesForStopResponse BusManager::GetBusesForStop(const string& stop) const { if(BusManager::buses_for_stops.count(stop) == 0) { return BusesForStopResponse("No stop"); } else { string s; for(const auto& i: BusManager::buses_for_stops.at(stop)) { s += i + " "; } s += "\n"; return BusesForStopResponse(s); } } StopsForBusResponse BusManager::GetStopsForBus(const string& bus) const { if (BusManager::stops_for_buses.count(bus) == 0) { return StopsForBusResponse("No bus"); } else { string s; for (const string& stop : BusManager::stops_for_buses.at(bus)) { s += "Stop " + stop + ": "; if (BusManager::buses_for_stops.at(stop).size() == 1) { s += "no interchange\n"; } else { for (const string& other_bus : BusManager::buses_for_stops.at(stop)) { if (bus != other_bus) { s += other_bus + " "; } } s += "\n"; } } return StopsForBusResponse(s); } } AllBusesResponse BusManager::GetAllBuses() const { if (BusManager::stops_for_buses.empty()) { return AllBusesResponse("No buses"); } else { string s; for (const auto& bus_item : BusManager::stops_for_buses) { s += "Bus " + bus_item.first + ": "; for (const string& stop : bus_item.second) { s += stop + " "; } s += "\n"; } return AllBusesResponse(s); } } // tuple<Table_of_buses, Table_of_buses> For_Unit_Tests(void) { // return make_tuple(stops_for_buses, buses_for_stops);
true
4cb9d7a4bded5bd74100ccdcdbf12caf546ede9e
C++
brendangoldz/coursework_cplus
/BrendanGoldsmith_WeatherStation 5/BrendanGoldsmith_WeatherStation/wind.cpp
UTF-8
1,236
3.296875
3
[]
no_license
#include "stdafx.h" #include <string> #include <iostream> #include <sstream> #include <regex> #include "wind.h" using namespace std; bool validate_wind(string in, string val) { const char* test = in.c_str(); regex re(val); cmatch match; if (regex_match(test, match, re)) { return true; } else { return false; } } class Wind { string str; string speed_re = "[0-9]{0,3}"; string dir_re = "[nNeEsSwW]{1,2}"; wind_t t; Wind::wind_t Wind::getWind(){ cout << "Please enter current Wind Speed: (Press ENTER when finished)" << endl; getline(cin, str); while (validate_wind(str, speed_re) != true) { cout << "Bad input. Enter a Wind Speed from 0 to 999, miles per hour. Press ENTER when finished." << endl; getline(cin, str); } stringstream(str) >> t.speed; cout << "Please enter current wind direction (N, NW, S etc.): (Press ENTER when finished)" << endl; getline(cin, str); while (validate_wind(str, dir_re) != true) { cout << "Bad input. Enter a Wind Direction using the letter notation; N for North, NW for NorthWest, S for South etc. Press ENTER when finished." << endl; getline(cin, str); } stringstream(str) >> t.dir; return t; } };
true
194c6101a7637b838ce36fcdc58ee4ccb6e83def
C++
ValdemarOrn/NoiseInvaderVST
/VstNoiseGate/AudioLib/Utils.cpp
UTF-8
1,017
2.71875
3
[]
no_license
#include "MathDefs.h" #include <cmath> #include "Utils.h" namespace AudioLib { float Utils::note2Freq[12800]; float Utils::sintable[TableSize]; float Utils::costable[TableSize]; float Utils::tableScaler; float Utils::tanhTable[TanhTableSize]; void Utils::Initialize() { for (int i = 0; i < 12800; i++) { note2Freq[i] = (float)(440.0 * std::pow(2, (0.01*i - 69) / 12.0)); } tableScaler = (float)(1.0 / (2.0f * M_PI) * TableSize); for (int i = 0; i < TableSize; i++) { sintable[i] = (float)std::sin(i / (double)TableSize * M_PI); costable[i] = (float)std::cos(i / (double)TableSize * M_PI); } for (int i = 0; i < TanhTableSize; i++) { tanhTable[i] = std::tanh(-3.0f + i / 10000.0f); } } float Utils::Note2Freq(float note) { auto base = (int)(note * 100); auto partial = note * 100 - base; if (base > 12799) { base = 12799; partial = 0; } auto freq = note2Freq[base]; auto slope = note2Freq[base + 1] - freq; return freq + partial * slope; } }
true
bc5d15ed6207e903f69787f849bf30d125300114
C++
ChristopherHX/libjnivm
/src/tests/Tests.cpp
UTF-8
60,068
2.703125
3
[ "MIT" ]
permissive
#include <jnivm/class.h> #include <jnivm/wrap.h> #include <gtest/gtest.h> #include <jnivm.h> #include <stdexcept> struct Class1 : public jnivm::Object { jboolean b; static jboolean b2; std::shared_ptr<jnivm::String> s; static std::shared_ptr<jnivm::String> s2; }; jboolean Class1::b2 = false; std::shared_ptr<jnivm::String> Class1::s2; TEST(JNIVM, BooleanFields) { jnivm::VM vm; auto cl = vm.GetEnv()->GetClass<Class1>("Class1"); cl->Hook(vm.GetEnv().get(), "b", &Class1::b); cl->Hook(vm.GetEnv().get(), "b2", &Class1::b2); auto env = vm.GetJNIEnv(); auto obj = std::make_shared<Class1>(); auto ncl = env->FindClass("Class1"); auto field = env->GetFieldID(ncl, "b", "Z"); auto nobj = jnivm::JNITypes<Class1>::ToJNIType(vm.GetEnv().get(), obj); env->SetBooleanField(nobj, field, true); ASSERT_TRUE(obj->b); ASSERT_TRUE(env->GetBooleanField(nobj, field)); env->SetBooleanField(nobj, field, false); ASSERT_FALSE(obj->b); ASSERT_FALSE(env->GetBooleanField(nobj, field)); auto field2 = env->GetStaticFieldID(ncl, "b2", "Z"); env->SetStaticBooleanField(ncl, field2, true); ASSERT_TRUE(obj->b2); ASSERT_TRUE(env->GetStaticBooleanField(ncl, field2)); env->SetStaticBooleanField(ncl, field2, false); ASSERT_FALSE(obj->b2); ASSERT_FALSE(env->GetStaticBooleanField(ncl, field2)); } TEST(JNIVM, StringFields) { jnivm::VM vm; auto cl = vm.GetEnv()->GetClass<Class1>("Class1"); cl->Hook(vm.GetEnv().get(), "s", &Class1::s); cl->Hook(vm.GetEnv().get(), "s2", &Class1::s2); auto env = vm.GetJNIEnv(); auto obj = std::make_shared<Class1>(); auto ncl = env->FindClass("Class1"); auto field = env->GetFieldID(ncl, "s", "Ljava/lang/String;"); static_assert(sizeof(jchar) == sizeof(char16_t), "jchar is not as large as char16_t"); auto str1 = env->NewString((jchar*) u"Hello World", 11); auto str2 = env->NewStringUTF("Hello World"); auto nobj = jnivm::JNITypes<Class1>::ToJNIType(vm.GetEnv().get(), obj); env->SetObjectField(nobj, field, str1); ASSERT_EQ((jstring)obj->s.get(), str1); ASSERT_EQ(env->GetObjectField(nobj, field), str1); env->SetObjectField(nobj, field, str2); ASSERT_EQ((jstring)obj->s.get(), str2); ASSERT_EQ(env->GetObjectField(nobj, field), str2); auto field2 = env->GetStaticFieldID(ncl, "s2", "Ljava/lang/String;"); env->SetStaticObjectField(ncl, field2, str1); ASSERT_EQ((jstring)obj->s2.get(), str1); ASSERT_EQ(env->GetStaticObjectField(ncl, field2), str1); env->SetStaticObjectField(ncl, field2, str2); ASSERT_EQ((jstring)obj->s2.get(), str2); ASSERT_EQ(env->GetStaticObjectField(ncl, field2), str2); } TEST(JNIVM, Strings) { jnivm::VM vm; auto env = vm.GetJNIEnv(); const char samplestr[] = "Hello World"; const char16_t samplestr2[] = u"Hello World"; auto jstr = env->NewStringUTF(samplestr); auto utflen = env->GetStringUTFLength(jstr); ASSERT_EQ(strlen(samplestr), utflen); jboolean copy; auto utfchars = env->GetStringUTFChars(jstr, &copy); ASSERT_STRCASEEQ(samplestr, utfchars); env->ReleaseStringUTFChars(jstr, utfchars); utfchars = env->GetStringUTFChars(jstr, nullptr); ASSERT_STRCASEEQ(samplestr, utfchars); env->ReleaseStringUTFChars(jstr, utfchars); auto len = env->GetStringLength(jstr); ASSERT_EQ(sizeof(samplestr2) / sizeof(char16_t) - 1, len); auto chars = env->GetStringChars(jstr, &copy); env->ReleaseStringChars(jstr, chars); chars = env->GetStringChars(jstr, nullptr); env->ReleaseStringChars(jstr, chars); ASSERT_EQ(sizeof(samplestr2) / sizeof(char16_t) - 1, len); jchar ret[sizeof(samplestr2) / sizeof(char16_t) - 3]; env->GetStringRegion(jstr, 1, len - 2, ret); ASSERT_FALSE(memcmp(samplestr2 + 1, ret, (len - 2) * sizeof(jchar))); } TEST(JNIVM, Strings2) { jnivm::VM vm; auto env = vm.GetJNIEnv(); const char samplestr[] = "Hello World"; const char16_t samplestr2[] = u"Hello World"; auto jstr = env->NewString((jchar*)samplestr2, sizeof(samplestr2) / sizeof(char16_t) - 1); auto len = env->GetStringLength(jstr); ASSERT_EQ(sizeof(samplestr2) / sizeof(char16_t) - 1, len); jchar ret[sizeof(samplestr2) / sizeof(char16_t) - 3]; env->GetStringRegion(jstr, 1, len - 2, ret); ASSERT_FALSE(memcmp(samplestr2 + 1, ret, (len - 2) * sizeof(jchar))); } TEST(JNIVM, ModifiedUtf8Null) { jnivm::VM vm; auto env = vm.GetJNIEnv(); const char16_t samplestr[] = u"String with \0 Nullbyte"; auto js = env->NewString((jchar*)samplestr, sizeof(samplestr) / sizeof(char16_t)); char buf[3] = { 0 }; env->GetStringUTFRegion(js, 12, 1, buf); ASSERT_EQ(buf[0], '\300'); ASSERT_EQ(buf[1], '\200'); ASSERT_EQ(buf[2], '\0'); } TEST(JNIVM, ObjectArray) { jnivm::VM vm; auto env = vm.GetJNIEnv(); jclass js = env->FindClass("java/lang/String"); jobjectArray arr = env->NewObjectArray(100, js, env->NewStringUTF("Hi")); ASSERT_EQ(env->GetObjectClass(arr), env->FindClass("[Ljava/lang/String;")); ASSERT_EQ(env->GetArrayLength(arr), 100); for (jsize i = 0; i < env->GetArrayLength(arr); i++) { auto el = env->GetObjectArrayElement(arr, i); ASSERT_TRUE(el); ASSERT_EQ(env->GetObjectClass(el), js); ASSERT_EQ(env->GetStringLength((jstring)el), 2); ASSERT_EQ(env->GetStringUTFLength((jstring)el), 2); } } TEST(JNIVM, jbooleanArray) { jnivm::VM vm; auto env = vm.GetJNIEnv(); jclass js = env->FindClass("java/lang/String"); jbooleanArray arr = env->NewBooleanArray(100); ASSERT_EQ(env->GetObjectClass(arr), env->FindClass("[Z")); ASSERT_EQ(env->GetArrayLength(arr), 100); for (jsize i = 0; i < env->GetArrayLength(arr); i++) { jboolean el; env->GetBooleanArrayRegion(arr, i, 1, &el); ASSERT_FALSE(el); } for (jsize i = 0; i < env->GetArrayLength(arr); i++) { jboolean el = true; env->SetBooleanArrayRegion(arr, i, 1, &el); } for (jsize i = 0; i < env->GetArrayLength(arr); i++) { jboolean el; env->GetBooleanArrayRegion(arr, i, 1, &el); ASSERT_TRUE(el); } } #include <jnivm/internal/jValuesfromValist.h> #include <limits> std::vector<jvalue> jValuesfromValistTestHelper(const char * sign, ...) { va_list l; va_start(l, sign); auto ret = jnivm::JValuesfromValist(l, sign); va_end(l); return std::move(ret); } TEST(JNIVM, jValuesfromValistPrimitives) { auto v1 = jValuesfromValistTestHelper("(ZIJIZBSLjava/lang/String;)Z", 1, std::numeric_limits<jint>::max(), std::numeric_limits<jlong>::max() / 2, std::numeric_limits<jint>::min(), 0, 12, 34, (jstring) 0x24455464); ASSERT_EQ(v1.size(), 8); ASSERT_EQ(v1[0].z, 1); ASSERT_EQ(v1[1].i, std::numeric_limits<jint>::max()); ASSERT_EQ(v1[2].j, std::numeric_limits<jlong>::max() / 2); ASSERT_EQ(v1[3].i, std::numeric_limits<jint>::min()); ASSERT_EQ(v1[4].z, 0); ASSERT_EQ(v1[5].b, 12); ASSERT_EQ(v1[6].s, 34); ASSERT_EQ(v1[7].l, (jstring) 0x24455464); } #include <jnivm/internal/skipJNIType.h> TEST(JNIVM, skipJNITypeTest) { const char type[] = "[[[[[Ljava/lang/string;Ljava/lang/object;ZI[CJ"; auto res = jnivm::SkipJNIType(type, type + sizeof(type) - 1); ASSERT_EQ(res, type + 23); res = jnivm::SkipJNIType(res, type + sizeof(type) - 1); ASSERT_EQ(res, type + 41); res = jnivm::SkipJNIType(res, type + sizeof(type) - 1); ASSERT_EQ(res, type + 42); res = jnivm::SkipJNIType(res, type + sizeof(type) - 1); ASSERT_EQ(res, type + 43); res = jnivm::SkipJNIType(res, type + sizeof(type) - 1); ASSERT_EQ(res, type + 45); res = jnivm::SkipJNIType(res, type + sizeof(type) - 1); ASSERT_EQ(res, type + 46); } class Class2 : public jnivm::Object { public: static std::shared_ptr<Class2> test() { return std::make_shared<Class2>(); } static std::shared_ptr<jnivm::Array<Class2>> test2() { auto array = std::make_shared<jnivm::Array<Class2>>(1); (*array)[0] = std::make_shared<Class2>(); return array; } }; // TODO Add asserts // If DeleteLocalRef logges an error it should fail TEST(JNIVM, returnedrefs) { jnivm::VM vm; auto cl = vm.GetEnv()->GetClass<Class2>("Class2"); cl->Hook(vm.GetEnv().get(), "test", &Class2::test); auto env = vm.GetJNIEnv(); env->PushLocalFrame(32); env->EnsureLocalCapacity(64); jclass c = env->FindClass("Class2"); jmethodID m = env->GetStaticMethodID(c, "test", "()LClass2;"); env->PushLocalFrame(32); jobject ref = env->CallStaticObjectMethod(c, m); env->DeleteLocalRef(ref); env->PopLocalFrame(nullptr); env->PopLocalFrame(nullptr); // Test if deleting a nullptr isn't an error env->DeleteLocalRef(nullptr); env->DeleteGlobalRef(nullptr); env->DeleteWeakGlobalRef(nullptr); // Test if we can free more frames than allocated env->PopLocalFrame(nullptr); env->PopLocalFrame(nullptr); env->PopLocalFrame(nullptr); } // TODO Add asserts // If DeleteLocalRef logges an error it should fail TEST(JNIVM, returnedarrayrefs) { jnivm::VM vm; auto cl = vm.GetEnv()->GetClass<Class2>("Class2"); cl->Hook(vm.GetEnv().get(), "test2", &Class2::test2); auto env = vm.GetJNIEnv(); env->PushLocalFrame(32); jclass c = env->FindClass("Class2"); jmethodID m = env->GetStaticMethodID(c, "test2", "()[LClass2;"); env->PushLocalFrame(32); jobject ref = env->CallStaticObjectMethod(c, m); env->PushLocalFrame(32); jobject ref2 = env->GetObjectArrayElement((jobjectArray)ref, 0); env->DeleteLocalRef(ref2); env->PopLocalFrame(nullptr); env->DeleteLocalRef(ref); env->PopLocalFrame(nullptr); env->PopLocalFrame(nullptr); } TEST(JNIVM, classofclassobject) { jnivm::VM vm; auto env = vm.GetJNIEnv(); jclass c = env->FindClass("Class2"); // auto __c2 = dynamic_cast<jnivm::Class*>((jnivm::Object*)c); // auto count = __c2->clazz.use_count(); // jclass c2 = env->FindClass("java/lang/Class"); // count = __c2->clazz.use_count(); // env->DeleteLocalRef(c2); // count = __c2->clazz.use_count(); // // ((jnivm::Object*)c)->shared_from_this(); // auto ref = jnivm::JNITypes<std::shared_ptr<jnivm::Class>>::JNICast(vm.GetEnv().get(), c); // std::weak_ptr<jnivm::Class> w (ref); // ref = nullptr; // auto c0 = w.use_count(); // jclass jc = env->GetObjectClass(c); // auto c1 = w.use_count(); // ref = jnivm::JNITypes<std::shared_ptr<jnivm::Class>>::JNICast(vm.GetEnv().get(), jc); // std::weak_ptr<jnivm::Class> w2 (ref); // ref = nullptr; // auto c2 = w.use_count(); // auto c3 = w2.use_count(); ASSERT_EQ(env->GetObjectClass(c), env->FindClass("java/lang/Class")); // auto c4 = w.use_count(); // auto c5 = w2.use_count(); } TEST(JNIVM, DONOTReturnSpecializedStubs) { jnivm::VM vm; auto env = vm.GetEnv(); std::shared_ptr<jnivm::Array<Class2>> a = std::make_shared<jnivm::Array<Class2>>(); static_assert(std::is_same<decltype(jnivm::JNITypes<std::shared_ptr<jnivm::Array<Class2>>>::ToJNIType(env.get(), a)), jobjectArray>::value, "Invalid Return Type"); static_assert(std::is_same<decltype(jnivm::JNITypes<std::shared_ptr<jnivm::Array<Class2>>>::ToJNIReturnType(env.get(), a)), jobject>::value, "Invalid Return Type"); static_assert(std::is_same<decltype(jnivm::JNITypes<std::shared_ptr<jnivm::Array<jbyte>>>::ToJNIType(env.get(), std::shared_ptr<jnivm::Array<jbyte>>{})), jbyteArray>::value, "Invalid Return Type"); static_assert(std::is_same<decltype(jnivm::JNITypes<std::shared_ptr<jnivm::Array<jbyte>>>::ToJNIReturnType(env.get(), std::shared_ptr<jnivm::Array<jbyte>>{})), jobject>::value, "Invalid Return Type"); } TEST(JNIVM, Excepts) { jnivm::VM vm; auto env = vm.GetEnv(); auto _Class2 = env->GetClass<Class2>("Class2"); _Class2->HookInstanceFunction(env.get(), "test", [](jnivm::ENV*, jnivm::Object *) { throw std::runtime_error("Test"); }); auto o = std::make_shared<Class2>(); auto obj = jnivm::JNITypes<decltype(o)>::ToJNIReturnType(env.get(), o); auto c = jnivm::JNITypes<decltype(_Class2)>::ToJNIType(env.get(), _Class2); auto nenv = vm.GetJNIEnv(); auto mid = nenv->GetMethodID(c, "test", "()V"); nenv->CallVoidMethod(obj, mid); jthrowable th = nenv->ExceptionOccurred(); ASSERT_NE(th, nullptr); nenv->ExceptionDescribe(); nenv->ExceptionClear(); jthrowable th2 = nenv->ExceptionOccurred(); ASSERT_EQ(th2, nullptr); nenv->ExceptionDescribe(); } TEST(JNIVM, Monitor) { jnivm::VM vm; auto env = vm.GetEnv(); auto _Class2 = env->GetClass<Class2>("Class2"); _Class2->HookInstanceFunction(env.get(), "test", [](jnivm::ENV*, jnivm::Object *) { throw std::runtime_error("Test"); }); auto o = std::make_shared<Class2>(); auto obj = jnivm::JNITypes<decltype(o)>::ToJNIReturnType(env.get(), o); auto c = jnivm::JNITypes<decltype(_Class2)>::ToJNIType(env.get(), _Class2); auto nenv = vm.GetJNIEnv(); nenv->MonitorEnter(c); nenv->MonitorEnter(c); // Should work nenv->MonitorExit(c); nenv->MonitorExit(c); } class TestInterface : public jnivm::Extends<jnivm::Object> { public: virtual void Test() = 0; }; class TestClass : public jnivm::Extends<jnivm::Object, TestInterface> { virtual void Test() override { } }; #include <jnivm/weak.h> TEST(JNIVM, BaseClass) { jnivm::VM vm; auto env = vm.GetEnv(); jnivm::Weak::GetBaseClasses(env.get()); jnivm::Object::GetBaseClasses(env.get()); } TEST(JNIVM, Interfaces) { jnivm::VM vm; auto env = vm.GetEnv(); vm.GetEnv()->GetClass<TestClass>("TestClass"); vm.GetEnv()->GetClass<TestInterface>("TestInterface"); auto bc = TestClass::GetBaseClasses(env.get()); ASSERT_EQ(bc.size(), 2); ASSERT_EQ(bc[0]->name, "Object"); ASSERT_EQ(bc[1]->name, "TestInterface"); } class TestClass2 : public jnivm::Extends<TestClass> { }; // TEST(JNIVM, InheritedInterfaces) { // jnivm::VM vm; // auto env = vm.GetEnv(); // vm.GetEnv()->GetClass<TestClass>("TestClass"); // vm.GetEnv()->GetClass<TestInterface>("TestInterface"); // vm.GetEnv()->GetClass<TestClass2>("TestClass2"); // auto bc = TestClass2::GetBaseClass(env.get()); // ASSERT_EQ(bc->name, "TestClass"); // auto interfaces = TestClass2::GetInterfaces(env.get()); // ASSERT_EQ(interfaces.size(), 1); // ASSERT_EQ(interfaces[0]->name, "TestInterface"); // } class TestInterface2 : public jnivm::Extends<jnivm::Object>{ public: virtual void Test2() = 0; }; struct TestClass3Ex : std::exception { }; class TestClass3 : public jnivm::Extends<TestClass2, TestInterface2> { virtual void Test() override { throw TestClass3Ex(); } virtual void Test2() override { } }; // TEST(JNIVM, InheritedInterfacesWithNew) { // jnivm::VM vm; // auto env = vm.GetEnv(); // vm.GetEnv()->GetClass<TestClass>("TestClass"); // vm.GetEnv()->GetClass<TestInterface>("TestInterface")->Hook(env.get(), "Test", &TestInterface::Test); // vm.GetEnv()->GetClass<TestInterface2>("TestInterface2")->Hook(env.get(), "Test2", &TestInterface2::Test2); // vm.GetEnv()->GetClass<TestClass2>("TestClass2"); // vm.GetEnv()->GetClass<TestClass3>("TestClass3"); // auto bc = TestClass3::GetBaseClass(env.get()); // ASSERT_EQ(bc->name, "TestClass2"); // auto interfaces = TestClass3::GetInterfaces(env.get()); // ASSERT_EQ(interfaces.size(), 2); // ASSERT_EQ(interfaces[0]->name, "TestInterface"); // ASSERT_EQ(interfaces[1]->name, "TestInterface2"); // } #include <fake-jni/fake-jni.h> class FakeJniTest : public FakeJni::JObject { jint f = 1; public: DEFINE_CLASS_NAME("FakeJniTest", FakeJni::JObject) void test() { throw TestClass3Ex(); } }; BEGIN_NATIVE_DESCRIPTOR(FakeJniTest) FakeJni::Constructor<FakeJniTest>{}, #ifdef __cpp_nontype_template_parameter_auto {FakeJni::Field<&FakeJniTest::f>{}, "f"}, {FakeJni::Function<&FakeJniTest::test>{}, "test"} #endif END_NATIVE_DESCRIPTOR #include <baron/baron.h> TEST(Baron, Test) { Baron::Jvm jvm; jvm.registerClass<FakeJniTest>(); FakeJni::LocalFrame frame(jvm); jclass c = (&frame.getJniEnv())->FindClass("FakeJniTest"); jmethodID ctor = (&frame.getJniEnv())->GetMethodID(c, "<init>", "()V"); jobject o = (&frame.getJniEnv())->NewObject(c, ctor); auto ret = std::make_shared<FakeJniTest>(FakeJniTest()); auto id2 = (&frame.getJniEnv())->GetStaticMethodID(c, "test", "()LFakeJniTest;"); jobject obj = (&frame.getJniEnv())->CallStaticObjectMethod(c, id2); #ifdef JNI_RETURN_NON_ZERO ASSERT_NE(obj, nullptr); #else ASSERT_EQ(obj, nullptr); #endif auto s = std::make_shared<FakeJni::JString>(); std::string t1 = "Test"; auto s2 = std::make_shared<FakeJni::JString>(t1); ASSERT_EQ(s2->asStdString(), t1); auto s3 = std::make_shared<FakeJni::JString>(std::move(t1)); ASSERT_EQ(t1, ""); ASSERT_EQ(s3->asStdString(), "Test"); ASSERT_EQ(jvm.findClass("FakeJniTest")->getClass().getName(), "java/lang/Class"); } template<char...ch> struct TemplateString { }; // #define ToTemplateString(literal) decltype([](){ \ // \ // }\ // }())} TEST(JNIVM, Inherience) { jnivm::VM vm; auto env = vm.GetEnv(); vm.GetEnv()->GetClass<TestInterface>("TestInterface")->Hook(env.get(), "Test", &TestInterface::Test); vm.GetEnv()->GetClass<TestInterface2>("TestInterface2")->Hook(env.get(), "Test2", &TestInterface2::Test2); vm.GetEnv()->GetClass<TestClass>("TestClass"); vm.GetEnv()->GetClass<TestClass2>("TestClass2"); vm.GetEnv()->GetClass<TestClass3>("TestClass3"); auto jenv = vm.GetJNIEnv(); jclass testClass = jenv->FindClass("TestClass"); jclass testClass2 = jenv->FindClass("TestClass2"); jclass testClass3 = jenv->FindClass("TestClass3"); jclass testInterface = jenv->FindClass("TestInterface"); jclass testInterface2 = jenv->FindClass("TestInterface2"); jclass c = jenv->FindClass("java/lang/Class"); ASSERT_TRUE(jenv->IsInstanceOf(testClass, c)); ASSERT_FALSE(jenv->IsAssignableFrom(testClass, c)); ASSERT_TRUE(jenv->IsAssignableFrom(testClass, testClass)); ASSERT_TRUE(jenv->IsAssignableFrom(testClass2, testClass)); ASSERT_TRUE(jenv->IsAssignableFrom(testClass, testInterface)); ASSERT_FALSE(jenv->IsAssignableFrom(testClass, testInterface2)); ASSERT_TRUE(jenv->IsAssignableFrom(testClass2, testInterface)); ASSERT_FALSE(jenv->IsAssignableFrom(testClass2, testInterface2)); ASSERT_TRUE(jenv->IsAssignableFrom(testClass3, testInterface)); ASSERT_TRUE(jenv->IsAssignableFrom(testClass3, testInterface2)); ASSERT_FALSE(jenv->IsAssignableFrom(testInterface2, testClass3)); auto test = jenv->GetMethodID(testInterface, "Test", "()V"); auto test2 = jenv->GetMethodID(testClass3, "Test2", "()V"); auto obje = std::make_shared<TestClass3>(); auto v1 = jnivm::JNITypes<decltype(obje)>::ToJNIReturnType(env.get(), obje); std::shared_ptr<TestInterface> obji = obje; auto& testClass3_ = typeid(TestClass3); auto v2_1 = static_cast<jnivm::Object*>(obje.get()); auto v2 = jnivm::JNITypes<std::shared_ptr<TestInterface>>::ToJNIReturnType(env.get(), obji); auto obje2 = jnivm::JNITypes<std::shared_ptr<TestClass3>>::JNICast(env.get(), v2); ASSERT_EQ(obje, obje2); auto obji2 = jnivm::JNITypes<std::shared_ptr<TestInterface>>::JNICast(env.get(), v2); ASSERT_EQ(obji, obji2); ASSERT_FALSE(jenv->ExceptionCheck()); jenv->CallVoidMethod((jobject)(jnivm::Object*)obje.get(), test); ASSERT_TRUE(jenv->ExceptionCheck()); jenv->ExceptionClear(); ASSERT_FALSE(jenv->ExceptionCheck()); jenv->CallVoidMethod((jobject)(jnivm::Object*)obje.get(), test2); ASSERT_FALSE(jenv->ExceptionCheck()); // decltype(TemplateStringConverter<void>::ToTemplateString("Test")) y; // static constexpr const char test2[] = __FUNCTION__; // struct TemplateStringConverter { // static constexpr auto ToTemplateString() { // return TemplateString<test2[0], test2[1], test2[2], test2[sizeof(test2) - 1]>(); // } // }; ASSERT_EQ(env->GetJNIEnv()->GetSuperclass(testClass2), testClass); ASSERT_EQ(env->GetJNIEnv()->GetSuperclass(testClass3), testClass2); } class TestInterface3 : public jnivm::Extends<TestInterface, TestInterface2> { }; class TestClass4 : public jnivm::Extends<TestClass3, TestInterface3> { virtual void Test() override { throw TestClass3Ex(); } virtual void Test2() override { throw std::runtime_error("Hi"); } }; TEST(JNIVM, Inherience2) { jnivm::VM vm; auto env = vm.GetEnv(); vm.GetEnv()->GetClass<TestInterface>("TestInterface")->Hook(env.get(), "Test", &TestInterface::Test); vm.GetEnv()->GetClass<TestInterface2>("TestInterface2")->Hook(env.get(), "Test2", &TestInterface2::Test2); vm.GetEnv()->GetClass<TestInterface3>("TestInterface3"); vm.GetEnv()->GetClass<TestClass>("TestClass"); vm.GetEnv()->GetClass<TestClass2>("TestClass2"); vm.GetEnv()->GetClass<TestClass3>("TestClass3"); vm.GetEnv()->GetClass<TestClass4>("TestClass4"); auto jenv = vm.GetJNIEnv(); jclass testClass = jenv->FindClass("TestClass"); jclass testClass2 = jenv->FindClass("TestClass2"); jclass testClass3 = jenv->FindClass("TestClass3"); jclass testClass4 = jenv->FindClass("TestClass4"); jclass testInterface = jenv->FindClass("TestInterface"); jclass testInterface2 = jenv->FindClass("TestInterface2"); jclass testInterface3 = jenv->FindClass("TestInterface3"); jclass c = jenv->FindClass("java/lang/Class"); ASSERT_TRUE(jenv->IsInstanceOf(testClass, c)); ASSERT_FALSE(jenv->IsAssignableFrom(testClass, c)); ASSERT_TRUE(jenv->IsAssignableFrom(testClass4, testInterface3)); ASSERT_TRUE(jenv->IsAssignableFrom(testClass4, testInterface2)); ASSERT_TRUE(jenv->IsAssignableFrom(testClass4, testInterface)); auto test = jenv->GetMethodID(testInterface, "Test", "()V"); auto test2 = jenv->GetMethodID(testClass4, "Test2", "()V"); auto i = std::make_shared<TestClass4>(); auto v1 = jnivm::JNITypes<std::shared_ptr<TestClass4>>::ToJNIReturnType(env.get(), i); auto v2 = jnivm::JNITypes<std::shared_ptr<TestInterface>>::ToJNIReturnType(env.get(), (std::shared_ptr<TestInterface>)i); auto v3 = jnivm::JNITypes<std::shared_ptr<TestInterface2>>::JNICast(env.get(), v2); auto v4 = jnivm::JNITypes<std::shared_ptr<TestClass4>>::JNICast(env.get(), v2); ASSERT_EQ(v1, (jobject)(jnivm::Object*)i.get()); ASSERT_EQ(v4, i); jenv->CallVoidMethod(v1, test2); jenv->CallVoidMethod(v2, test2); size_t olduse = i.use_count(); auto weak = jenv->NewWeakGlobalRef(v2); ASSERT_EQ(olduse, i.use_count()) << "Weak pointer is no strong reference"; auto v5 = jnivm::JNITypes<std::shared_ptr<TestClass4>>::JNICast(env.get(), weak); ASSERT_NE(v5, nullptr) << "Weak pointer isn't expired!"; ASSERT_EQ(olduse + 1, i.use_count()); jenv->DeleteWeakGlobalRef(weak); ASSERT_EQ(olduse + 1, i.use_count()); } TEST(JNIVM, ExternalFuncs) { jnivm::VM vm; auto env = vm.GetEnv(); env->GetClass<TestInterface>("TestInterface"); auto c = env->GetClass<TestClass>("TestClass"); bool succeded = false; auto x = env->GetJNIEnv()->FindClass("TestClass"); auto m = env->GetJNIEnv()->GetStaticMethodID(x, "factory", "()LTestClass;"); auto o = env->GetJNIEnv()->CallStaticObjectMethod(x, m); c->HookInstanceFunction(env.get(), "test", [&succeded, src = jnivm::JNITypes<std::shared_ptr<jnivm::Object>>::JNICast(env.get(), o)](jnivm::ENV*env, jnivm::Object*obj) { ASSERT_EQ(src.get(), obj); succeded = true; }); auto m2 = env->GetJNIEnv()->GetMethodID(x, "test", "()V"); env->GetJNIEnv()->CallVoidMethod(o, m2); ASSERT_TRUE(succeded); c->HookInstanceFunction(env.get(), "test", [&succeded, src = jnivm::JNITypes<std::shared_ptr<jnivm::Object>>::JNICast(env.get(), o)](jnivm::Object*obj) { ASSERT_EQ(src.get(), obj); succeded = false; }); env->GetJNIEnv()->CallVoidMethod(o, m2); ASSERT_FALSE(succeded); c->HookInstanceFunction(env.get(), "test", [&succeded, src = jnivm::JNITypes<std::shared_ptr<jnivm::Object>>::JNICast(env.get(), o)]() { succeded = true; }); env->GetJNIEnv()->CallVoidMethod(o, m2); ASSERT_TRUE(succeded); // static succeded = false; c->Hook(env.get(), "test", [&succeded, &c](jnivm::ENV*env, jnivm::Class*obj) { ASSERT_EQ(c.get(), obj); succeded = true; }); m2 = env->GetJNIEnv()->GetStaticMethodID(x, "test", "()V"); env->GetJNIEnv()->CallStaticVoidMethod(x, m2); ASSERT_TRUE(succeded); c->Hook(env.get(), "test", [&succeded, &c](jnivm::Class*obj) { ASSERT_EQ(c.get(), obj); succeded = false; }); env->GetJNIEnv()->CallStaticVoidMethod(x, m2); ASSERT_FALSE(succeded); c->Hook(env.get(), "test", [&succeded, &c]() { succeded = true; }); env->GetJNIEnv()->CallStaticVoidMethod(x, m2); ASSERT_TRUE(succeded); } TEST(JNIVM, WeakAndIsSame) { jnivm::VM vm; auto env = vm.GetEnv(); env->GetClass<TestInterface>("TestInterface"); auto c = env->GetClass<TestClass>("TestClass"); bool succeded = false; auto x = env->GetJNIEnv()->FindClass("TestClass"); auto m = env->GetJNIEnv()->GetStaticMethodID(x, "factory", "()LTestClass;"); env->GetJNIEnv()->PushLocalFrame(100); auto o = env->GetJNIEnv()->CallStaticObjectMethod(x, m); auto w = env->GetJNIEnv()->NewWeakGlobalRef(o); ASSERT_TRUE(env->GetJNIEnv()->IsSameObject(o, w)); env->GetJNIEnv()->PopLocalFrame(nullptr); ASSERT_TRUE(env->GetJNIEnv()->IsSameObject(0, w)); } TEST(JNIVM, WeakToGlobalReference) { jnivm::VM vm; auto env = vm.GetEnv(); env->GetClass<TestInterface>("TestInterface"); auto c = env->GetClass<TestClass>("TestClass"); bool succeded = false; auto x = env->GetJNIEnv()->FindClass("TestClass"); auto m = env->GetJNIEnv()->GetStaticMethodID(x, "factory", "()LTestClass;"); env->GetJNIEnv()->PushLocalFrame(100); auto o = env->GetJNIEnv()->CallStaticObjectMethod(x, m); auto w = env->GetJNIEnv()->NewWeakGlobalRef(o); ASSERT_TRUE(env->GetJNIEnv()->IsSameObject(o, w)); ASSERT_EQ(env->GetJNIEnv()->GetObjectRefType(w), JNIWeakGlobalRefType); auto g = env->GetJNIEnv()->NewGlobalRef(w); ASSERT_TRUE(env->GetJNIEnv()->IsSameObject(g, w)); ASSERT_TRUE(env->GetJNIEnv()->IsSameObject(g, o)); ASSERT_EQ(env->GetJNIEnv()->GetObjectRefType(g), JNIGlobalRefType); env->GetJNIEnv()->PopLocalFrame(nullptr); ASSERT_FALSE(env->GetJNIEnv()->IsSameObject(0, w)); env->GetJNIEnv()->DeleteGlobalRef(g); ASSERT_TRUE(env->GetJNIEnv()->IsSameObject(0, w)); ASSERT_EQ(env->GetJNIEnv()->NewGlobalRef(w), (jobject)0); } TEST(JNIVM, WeakToLocalReference) { jnivm::VM vm; auto env = vm.GetEnv(); env->GetClass<TestInterface>("TestInterface"); auto c = env->GetClass<TestClass>("TestClass"); bool succeded = false; ASSERT_EQ(env->GetJNIEnv()->GetObjectRefType(nullptr), JNIInvalidRefType); auto x = env->GetJNIEnv()->FindClass("TestClass"); auto m = env->GetJNIEnv()->GetStaticMethodID(x, "factory", "()LTestClass;"); env->GetJNIEnv()->PushLocalFrame(100); auto o = env->GetJNIEnv()->CallStaticObjectMethod(x, m); auto w = env->GetJNIEnv()->NewWeakGlobalRef(o); ASSERT_TRUE(env->GetJNIEnv()->IsSameObject(o, w)); ASSERT_EQ(env->GetJNIEnv()->GetObjectRefType(w), JNIWeakGlobalRefType); auto g = env->GetJNIEnv()->NewLocalRef(w); ASSERT_TRUE(env->GetJNIEnv()->IsSameObject(g, w)); ASSERT_TRUE(env->GetJNIEnv()->IsSameObject(g, o)); ASSERT_EQ(env->GetJNIEnv()->GetObjectRefType(g), JNILocalRefType); env->GetJNIEnv()->DeleteLocalRef(o); ASSERT_FALSE(env->GetJNIEnv()->IsSameObject(0, w)); env->GetJNIEnv()->PopLocalFrame(nullptr); ASSERT_TRUE(env->GetJNIEnv()->IsSameObject(0, w)); ASSERT_EQ(env->GetJNIEnv()->NewLocalRef(w), (jobject)0); ASSERT_EQ(env->GetJNIEnv()->NewWeakGlobalRef(w), (jobject)0); ASSERT_EQ(env->GetJNIEnv()->NewGlobalRef(w), (jobject)0); } #include <baron/baron.h> TEST(FakeJni, Master) { Baron::Jvm b; b.registerClass<FakeJniTest>(); FakeJni::LocalFrame f; auto& p = f.getJniEnv(); auto c = b.findClass("FakeJniTest"); auto m = c->getMethod("()V", "test"); auto test = std::make_shared<FakeJniTest>(); EXPECT_THROW(m->invoke(p, test.get()), TestClass3Ex); } namespace Test2 { class TestClass : public jnivm::Extends<> { public: bool Test(bool a) { return !a; } jboolean Test2() { return false; } static void Test3(std::shared_ptr<jnivm::Class> c, std::shared_ptr<TestClass> o) { ASSERT_TRUE(c); ASSERT_TRUE(o); ASSERT_EQ(c, o->clazz.lock()); } static void NativeTest3(JNIEnv*env, jclass clazz, jobject o) { auto m = env->GetStaticMethodID(clazz, "Test2", "(Ljava/lang/Class;LTestClass;)V"); env->CallStaticVoidMethod(clazz, m, clazz, o); } static void NativeTest4(JNIEnv*env, jobject o, jobject clazz) { NativeTest3(env, (jclass)clazz, o); } static jobject NativeTest5(JNIEnv*env, jobject o, jobject clazz) { NativeTest3(env, (jclass)clazz, o); return clazz; } static void Test4(std::shared_ptr<jnivm::Array<jnivm::Class>> c, std::shared_ptr<jnivm::Array<jnivm::Array<TestClass>>> o) { std::shared_ptr<jnivm::Array<TestClass>> test = (*o)[0]; std::shared_ptr<jnivm::Array<Object>> test2 = (*o)[0]; std::shared_ptr<TestClass> tc = (*test)[0], ty = (*(*o)[0])[0]; ASSERT_ANY_THROW((*test2)[0] = o); } }; template<class T> struct TestArray; template<> struct TestArray<jnivm::Object> { jnivm::Object* ptr; }; template<class T> struct TestArray : TestArray<std::tuple_element_t<0, typename T::BaseClasseTuple>> { }; class TestClass3 : public jnivm::Extends<TestClass2> { public: std::shared_ptr<TestArray<TestClass3>> test() { auto ret = std::make_shared<Test2::TestArray<Test2::TestClass3>>(); std::shared_ptr<Test2::TestArray<TestClass2>> test = ret; return ret; } }; // std::shared_ptr<Test2::TestArray<Test2::TestClass3>> Test2::TestClass3::test() { // auto ret = std::make_shared<Test2::TestArray<Test2::TestClass3>>(); // std::shared_ptr<Test2::TestArray<TestClass2>> test = ret; // return ret; // } // DISABLED: getMethod is a exclusive feature of FakeJni::Jvm and throws an exception TEST(JNIVM, Hooking) { jnivm::VM vm; auto env = vm.GetEnv().get(); auto c = env->GetClass<TestClass>("TestClass"); c->Hook(env, "Test", &TestClass::Test); c->Hook(env, "Test2", &TestClass::Test2); c->Hook(env, "Test2", &TestClass::Test3); c->Hook(env, "Test4", &TestClass::Test4); auto mid = env->GetJNIEnv()->GetStaticMethodID((jclass)c.get(), "Instatiate", "()LTestClass;"); auto obj = env->GetJNIEnv()->CallStaticObjectMethod((jclass)c.get(), mid); auto jenv = vm.GetJNIEnv(); // ASSERT_TRUE(c->getMethod("(Z)Z", "Test")->invoke(*jenv, (jnivm::Object*)obj, false).z); // ASSERT_FALSE(c->getMethod("(Z)Z", "Test")->invoke(*jenv, (jnivm::Object*)obj, true).z); // c->getMethod("()Z", "Test2")->invoke(*jenv, (jnivm::Object*)obj); // c->getMethod("(Ljava/lang/Class;LTestClass;)V", "Test2")->invoke(*jenv, c.get(), c, obj); JNINativeMethod methods[] = { { "NativeTest3", "(LTestClass;)V", (void*)&TestClass::NativeTest3 }, { "NativeTest4", "(Ljava/lang/Class;)V", (void*)&TestClass::NativeTest4 }, { "NativeTest5", "(Ljava/lang/Class;)Ljava/lang/Class;", (void*)&TestClass::NativeTest5 } }; env->GetJNIEnv()->RegisterNatives((jclass)c.get(), methods, sizeof(methods) / sizeof(*methods)); ASSERT_EQ(c->natives.size(), sizeof(methods) / sizeof(*methods)); // c->getMethod("(LTestClass;)V", "NativeTest3")->invoke(*jenv, c.get(), obj); // c->getMethod("(Ljava/lang/Class;)V", "NativeTest4")->invoke(*jenv, (jnivm::Object*)obj, c); // c->getMethod("(Ljava/lang/Class;)Ljava/lang/Class;", "NativeTest5")->invoke(*jenv, (jnivm::Object*)obj, c); // c->InstantiateArray = [](jnivm::ENV *jenv, jsize length) { // return std::make_shared<jnivm::Array<TestClass>>(length); // }; auto innerArray = env->GetJNIEnv()->NewObjectArray(12, (jclass)c.get(), obj); // auto c2 = jnivm::JNITypes<std::shared_ptr<jnivm::Class>>::JNICast(env, env->GetJNIEnv()->GetObjectClass(innerArray)); // c2->InstantiateArray = [](jnivm::ENV *jenv, jsize length) { // return std::make_shared<jnivm::Array<jnivm::Array<TestClass>>>(length); // }; auto outerArray = env->GetJNIEnv()->NewObjectArray(20, env->GetJNIEnv()->GetObjectClass(innerArray), innerArray); // c->getMethod("([Ljava/lang/Class;[[LTestClass;)V", "Test4")->invoke(*jenv, c.get(), (jobject)nullptr, (jobject)outerArray); env->GetJNIEnv()->CallStaticVoidMethod((jclass)c.get(), env->GetJNIEnv()->GetStaticMethodID((jclass)c.get(), "Test4", "([Ljava/lang/Class;[[LTestClass;)V"), (jobject)nullptr, (jobject)outerArray); std::shared_ptr<jnivm::Array<TestClass>> specArray; class TestClass2 : public jnivm::Extends<TestClass> {}; std::shared_ptr<jnivm::Array<TestClass2>> specArray2; specArray = specArray2; std::shared_ptr<jnivm::Array<jnivm::Object>> objArray = specArray2; std::shared_ptr<jnivm::Array<jnivm::Object>> objArray2 = specArray; auto obj6 = std::make_shared<TestClass3>(); obj6->test(); env->GetJNIEnv()->UnregisterNatives((jclass)c.get()); ASSERT_EQ(c->natives.size(), 0); } TEST(JNIVM, VirtualFunction) { jnivm::VM vm; enum class TestEnum { A, B }; class TestClass : public jnivm::Extends<> { public: int Test() { return (int)TestEnum::A; } virtual int Test2() { return (int)TestEnum::A; } }; class TestClass2 : public jnivm::Extends<TestClass> { public: int Test() { return (int)TestEnum::B; } int Test2() override { return (int)TestEnum::B; } }; auto env = vm.GetEnv().get(); auto c = env->GetClass<TestClass>("TestClass"); auto c2 = env->GetClass<TestClass2>("TestClass2"); c->Hook(env, "Test", &TestClass::Test); c2->Hook(env, "Test", &TestClass2::Test); c->HookInstanceFunction(env, "Test2", [](jnivm::ENV*, TestClass*o) { return o->TestClass::Test2(); }); c2->HookInstanceFunction(env, "Test2",[](jnivm::ENV*, TestClass2*o) { return o->TestClass2::Test2(); }); auto val = std::make_shared<TestClass2>(); auto ptr = jnivm::JNITypes<decltype(val)>::ToJNIReturnType(env, val); auto _c2 = jnivm::JNITypes<decltype(c2)>::ToJNIType(env, c2); auto _c = jnivm::JNITypes<decltype(c)>::ToJNIType(env, c); ASSERT_EQ(env->GetJNIEnv()->CallIntMethod(ptr, env->GetJNIEnv()->GetMethodID(_c, "Test", "()I")), (int)TestEnum::B); ASSERT_EQ(env->GetJNIEnv()->CallIntMethod(ptr, env->GetJNIEnv()->GetMethodID(_c2, "Test", "()I")), (int)TestEnum::B); // This part is disabled, because this isn't save and is not supported anymore // ASSERT_EQ(env->GetJNIEnv()->CallNonvirtualIntMethod(ptr, _c2, env->GetJNIEnv()->GetMethodID(_c, "Test", "()I")), (int)TestEnum::B); // ASSERT_EQ(env->GetJNIEnv()->CallNonvirtualIntMethod(ptr, _c2, env->GetJNIEnv()->GetMethodID(_c2, "Test", "()I")), (int)TestEnum::B); // ASSERT_EQ(env->GetJNIEnv()->CallNonvirtualIntMethod(ptr, _c, env->GetJNIEnv()->GetMethodID(_c, "Test", "()I")), (int)TestEnum::A); // ASSERT_EQ(env->GetJNIEnv()->CallNonvirtualIntMethod(ptr, _c, env->GetJNIEnv()->GetMethodID(_c2, "Test", "()I")), (int)TestEnum::A); ASSERT_EQ(env->GetJNIEnv()->CallIntMethod(ptr, env->GetJNIEnv()->GetMethodID(_c, "Test2", "()I")), (int)TestEnum::B); ASSERT_EQ(env->GetJNIEnv()->CallIntMethod(ptr, env->GetJNIEnv()->GetMethodID(_c2, "Test2", "()I")), (int)TestEnum::B); ASSERT_EQ(env->GetJNIEnv()->CallNonvirtualIntMethod(ptr, _c2, env->GetJNIEnv()->GetMethodID(_c, "Test2", "()I")), (int)TestEnum::B); ASSERT_EQ(env->GetJNIEnv()->CallNonvirtualIntMethod(ptr, _c2, env->GetJNIEnv()->GetMethodID(_c2, "Test2", "()I")), (int)TestEnum::B); ASSERT_EQ(env->GetJNIEnv()->CallNonvirtualIntMethod(ptr, _c, env->GetJNIEnv()->GetMethodID(_c, "Test2", "()I")), (int)TestEnum::A); ASSERT_EQ(env->GetJNIEnv()->CallNonvirtualIntMethod(ptr, _c, env->GetJNIEnv()->GetMethodID(_c2, "Test2", "()I")), (int)TestEnum::A); } } #include <thread> TEST(JNIVM, VM) { jnivm::VM vm; jweak glob; std::thread([&glob, jni = vm.GetJavaVM()]() { JNIEnv * env, *env2, *env3; auto res = jni->AttachCurrentThread(&env, nullptr); ASSERT_TRUE(env); res = jni->AttachCurrentThreadAsDaemon(&env2, nullptr); ASSERT_TRUE(env2); ASSERT_EQ(env, env2); res = jni->GetEnv((void**)&env3, JNI_VERSION_1_6); ASSERT_TRUE(env3); ASSERT_EQ(env, env3); JavaVM* vm; env->GetJavaVM(&vm); ASSERT_EQ(jni, vm); auto a = env->NewCharArray(1000); glob = env->NewWeakGlobalRef(a); ASSERT_TRUE(env->NewLocalRef(glob)); res = jni->DetachCurrentThread(); }).join(); ASSERT_FALSE(vm.GetJNIEnv()->NewLocalRef(glob)); ASSERT_DEATH(vm.GetJNIEnv()->FatalError("Fatal error no recover"), ".*"); } TEST(FakeJni, VM) { FakeJni::Jvm vm; ASSERT_NO_THROW(FakeJni::JniEnvContext().getJniEnv()); std::thread([&jni = vm]() { ASSERT_THROW(FakeJni::JniEnvContext().getJniEnv(), std::runtime_error); FakeJni::LocalFrame f(jni); auto& env = f.getJniEnv(); }).join(); ASSERT_NO_THROW(FakeJni::JniEnvContext().getJniEnv()); } TEST(FakeJni, attachLibrary) { static bool dlopenCalled = false; static bool JNI_OnLoadCalled = false; static bool dlsymCalled = false; static bool dlcloseCalled = false; static bool JNI_OnUnloadCalled = false; { FakeJni::Jvm vm; static void * handle = (void *)34; vm.attachLibrary("testpath", "", { [](const char*name, int) -> void*{ dlopenCalled = true; return handle; }, [](void* _handle, const char*name) ->void* { dlsymCalled = true; if(!strcmp(name, "JNI_OnLoad")) { return (void*)+[](JavaVM* vm, void* reserved) -> jint { JNI_OnLoadCalled = true; return 0; }; } if(!strcmp(name, "JNI_OnUnload")) { return (void*)+[](JavaVM* vm, void* reserved) -> void { JNI_OnUnloadCalled = true; }; } return nullptr; }, [](void* _handle) -> int { dlcloseCalled = true; return 0; } }); ASSERT_TRUE(dlopenCalled); ASSERT_TRUE(dlsymCalled); ASSERT_TRUE(JNI_OnLoadCalled); ASSERT_FALSE(JNI_OnUnloadCalled); ASSERT_FALSE(dlcloseCalled); } ASSERT_TRUE(JNI_OnUnloadCalled); ASSERT_TRUE(dlcloseCalled); } TEST(FakeJni, attachLibrary2) { static int dlopenCalled= 0; static int JNI_OnLoadCalled= 0; static int dlsymCalled= 0; static int dlcloseCalled= 0; static int JNI_OnUnloadCalled= 0; { FakeJni::Jvm vm; FakeJni::LibraryOptions opts = { [](const char*name, int) -> void*{ ++dlopenCalled; return (void*)678; }, [](void* handle, const char*name) ->void* { ++dlsymCalled; if(!strcmp(name, "JNI_OnLoad")) { return (void*)+[](JavaVM* vm, void* reserved) -> jint { ++JNI_OnLoadCalled; return 0; }; } if(!strcmp(name, "JNI_OnUnload")) { return (void*)+[](JavaVM* vm, void* reserved) -> void { ++JNI_OnUnloadCalled; }; } return nullptr; }, [](void* handle) -> int { ++dlcloseCalled; return 0; } }; vm.attachLibrary("testpath", "", opts); ASSERT_EQ(dlopenCalled, 1); ASSERT_EQ(dlsymCalled, 1); ASSERT_EQ(JNI_OnLoadCalled, 1); ASSERT_EQ(JNI_OnUnloadCalled, 0); ASSERT_EQ(dlcloseCalled, 0); vm.attachLibrary("testpath2", "", opts); ASSERT_EQ(dlopenCalled, 2); ASSERT_EQ(dlsymCalled, 2); ASSERT_EQ(JNI_OnLoadCalled, 2); ASSERT_EQ(JNI_OnUnloadCalled, 0); ASSERT_EQ(dlcloseCalled, 0); } ASSERT_EQ(JNI_OnUnloadCalled, 2); ASSERT_EQ(dlcloseCalled, 2); } TEST(FakeJni, attachLibrary3) { static int dlopenCalled= 0; static int JNI_OnLoadCalled= 0; static int dlsymCalled= 0; static int dlcloseCalled= 0; static int JNI_OnUnloadCalled= 0; { FakeJni::Jvm vm; FakeJni::LibraryOptions opts = { [](const char*name, int) -> void*{ ++dlopenCalled; return (void*)678; }, [](void* handle, const char*name) ->void* { ++dlsymCalled; if(!strcmp(name, "JNI_OnLoad")) { return (void*)+[](JavaVM* vm, void* reserved) -> jint { ++JNI_OnLoadCalled; return 0; }; } if(!strcmp(name, "JNI_OnUnload")) { return (void*)+[](JavaVM* vm, void* reserved) -> void { ++JNI_OnUnloadCalled; }; } return nullptr; }, [](void* handle) -> int { ++dlcloseCalled; return 0; } }; vm.attachLibrary("testpath", "", opts); ASSERT_EQ(dlopenCalled, 1); ASSERT_EQ(dlsymCalled, 1); ASSERT_EQ(JNI_OnLoadCalled, 1); ASSERT_EQ(JNI_OnUnloadCalled, 0); ASSERT_EQ(dlcloseCalled, 0); vm.removeLibrary("testpath"); ASSERT_EQ(dlsymCalled, 2); ASSERT_EQ(JNI_OnUnloadCalled, 1); ASSERT_EQ(dlcloseCalled, 1); vm.attachLibrary("testpath2", "", opts); ASSERT_EQ(dlopenCalled, 2); ASSERT_EQ(dlsymCalled, 3); ASSERT_EQ(JNI_OnLoadCalled, 2); ASSERT_EQ(JNI_OnUnloadCalled, 1); ASSERT_EQ(dlcloseCalled, 1); } ASSERT_EQ(JNI_OnUnloadCalled, 2); ASSERT_EQ(dlcloseCalled, 2); } // DISABLED: getMethod is a exclusive feature of FakeJni::Jvm and throws an exception TEST(JNIVM, DISABLED_ThrowingExceptions) { jnivm::VM vm; vm.GetJNIEnv()->ThrowNew(vm.GetJNIEnv()->FindClass("java/lang/Throwable"), "Fatal error"); ASSERT_TRUE(vm.GetJNIEnv()->ExceptionCheck()); auto except = vm.GetJNIEnv()->ExceptionOccurred(); ASSERT_TRUE(except); vm.GetJNIEnv()->ExceptionClear(); ASSERT_FALSE(vm.GetJNIEnv()->ExceptionCheck()); ASSERT_FALSE(vm.GetJNIEnv()->ExceptionOccurred()); vm.GetJNIEnv()->Throw(except); ASSERT_TRUE(vm.GetJNIEnv()->ExceptionCheck()); auto except2 = vm.GetJNIEnv()->ExceptionOccurred(); ASSERT_EQ(except, except2); auto Test = vm.GetJNIEnv()->FindClass("Test"); ASSERT_TRUE(Test); auto gTest = (jclass)vm.GetJNIEnv()->NewGlobalRef(Test); ASSERT_TRUE(vm.GetJNIEnv()->GetStaticMethodID(gTest, "AnotherTest", "()V")); auto cTest = vm.GetEnv()->GetClass("Test"); auto m = cTest->getMethod("()V", "AnotherTest"); ASSERT_TRUE(m); // ASSERT_THROWS(m->invoke(*vm.GetEnv(), cTest.get()), jnivm::Throwable); // ASSERT_FALSE(vm.GetJNIEnv()->ExceptionCheck()); // ASSERT_FALSE(vm.GetJNIEnv()->ExceptionOccurred()); } TEST(JNIVM, Reflection) { jnivm::VM vm; auto env = vm.GetJNIEnv(); auto Test2 = env->FindClass("Test2"); ASSERT_TRUE(Test2); auto ITest = env->GetMethodID(Test2, "Test", "()V"); ASSERT_TRUE(ITest); auto IPTest = env->GetFieldID(Test2, "Test", "I"); ASSERT_TRUE(IPTest); auto STest = env->GetStaticMethodID(Test2, "Test", "()V"); ASSERT_TRUE(STest); auto SPTest = env->GetStaticFieldID(Test2, "Test", "I"); ASSERT_TRUE(SPTest); ASSERT_FALSE(env->ToReflectedMethod(Test2, ITest, true)); auto rITest = env->ToReflectedMethod(Test2, ITest, false); ASSERT_TRUE(rITest); // ASSERT_FALSE(env->ToReflectedField(Test2, IPTest, false)); // auto rIPTest = env->ToReflectedMethod(Test2, IPTest, true); // ASSERT_TRUE(rIPTest); // ASSERT_FALSE(env->ToReflectedMethod(Test2, STest, false)); // auto rSTest = env->ToReflectedMethod(Test2, STest, true); // ASSERT_TRUE(rSTest); // ASSERT_FALSE(env->ToReflectedField(Test2, SPTest, false)); // auto rSPTest = env->ToReflectedMethod(Test2, SPTest, true); // ASSERT_TRUE(rSPTest); // ASSERT_EQ(env->FromReflectedMethod(rITest), ITest); // ASSERT_EQ(env->FromReflectedField(rIPTest), IPTest); // ASSERT_EQ(env->FromReflectedMethod(rSTest), STest); // ASSERT_EQ(env->FromReflectedField(rSPTest), SPTest); } #include "../jnivm/internal/stringUtil.h" TEST(JNIVM, StringUtil) { auto&& u8_2 = u8"ä"; auto&& u_2 = u"ä"; ASSERT_EQ(jnivm::UTFToJCharLength((const char*)u8_2), 2); ASSERT_EQ(jnivm::JCharToUTFLength((jchar)u_2[0]), 2); int size; ASSERT_EQ(jnivm::UTFToJChar((const char*)u8_2, size), (jchar)u_2[0]); char buf[5]; ASSERT_EQ(size, 2); ASSERT_EQ(jnivm::JCharToUTF((jchar)u_2[0], buf, 5), 2); buf[2] = 0; ASSERT_STRCASEEQ((const char*)u8_2, buf); auto&& u8_3 = u8"ඦ"; auto&& u_3 = u"ඦ"; ASSERT_EQ(jnivm::UTFToJCharLength((const char*)u8_3), 3); ASSERT_EQ(jnivm::JCharToUTFLength((jchar)u_3[0]), 3); ASSERT_EQ(jnivm::UTFToJChar((const char*)u8_3, size), (jchar)u_3[0]); ASSERT_EQ(size, 3); ASSERT_EQ(jnivm::JCharToUTF((jchar)u_3[0], buf, 5), 3); buf[3] = 0; ASSERT_STRCASEEQ((const char*)u8_3, buf); auto&& u8_4 = u8"🧲"; auto&& u_4 = u"🧲"; ASSERT_THROW(jnivm::UTFToJCharLength((const char*)u8_4), std::runtime_error); ASSERT_THROW(jnivm::UTFToJChar((const char*)u8_4, size), std::runtime_error); ASSERT_EQ(jnivm::JCharToUTFLength((jchar)u_4[0]), 3); ASSERT_EQ(jnivm::JCharToUTFLength((jchar)u_4[1]), 3); ASSERT_EQ(jnivm::JCharToUTF((jchar)u_4[0], buf, 5), 3); ASSERT_EQ(jnivm::UTFToJCharLength(buf), 3); ASSERT_EQ(jnivm::UTFToJChar(buf, size), (jchar)u_4[0]); ASSERT_EQ(jnivm::JCharToUTF((jchar)u_4[1], buf, 5), 3); ASSERT_EQ(jnivm::UTFToJCharLength(buf), 3); ASSERT_EQ(jnivm::UTFToJChar(buf, size), (jchar)u_4[1]); } TEST(JNIVM, ContructArray) { jnivm::VM vm; auto env = vm.GetJNIEnv(); auto Test = env->FindClass("Test"); auto mTest = env->GetStaticMethodID(Test, "Test", "()[LTest;"); auto a = env->CallStaticObjectMethod(Test, mTest); ASSERT_TRUE(a); jsize len = env->GetArrayLength((jarray)a); auto mTest2 = env->GetStaticMethodID(Test, "Test", "()[I"); auto a2 = env->CallStaticObjectMethod(Test, mTest2); len = env->GetArrayLength((jarray)a2); auto a_2 = jnivm::JNITypes<std::shared_ptr<jnivm::Array<jint>>>::JNICast(vm.GetEnv().get(), a2); ASSERT_TRUE(a_2); ASSERT_EQ(a_2->getSize(), len); } #include <baron/baron.h> #include <fake-jni/fake-jni.h> namespace jnivm { namespace baron { namespace impl { class createMainMethod; } } namespace test { namespace Gamma { class Functional; } } } class jnivm::baron::impl::createMainMethod : public FakeJni::JObject { public: DEFINE_CLASS_NAME("baron/impl/createMainMethod") static void main(std::shared_ptr<FakeJni::JArray<std::shared_ptr<java::lang::String>>>); }; class jnivm::test::Gamma::Functional : public FakeJni::JObject { public: DEFINE_CLASS_NAME("test/Gamma/Functional") class Test5; }; class jnivm::test::Gamma::Functional::Test5 : public FakeJni::JObject { public: DEFINE_CLASS_NAME("test/Gamma/Functional$Test5") class HelloWorld; }; class jnivm::test::Gamma::Functional::Test5::HelloWorld : public FakeJni::JObject { public: DEFINE_CLASS_NAME("test/Gamma/Functional$Test5$HelloWorld") HelloWorld(std::shared_ptr<test::Gamma::Functional::Test5>); }; void jnivm::baron::impl::createMainMethod::main(std::shared_ptr<FakeJni::JArray<std::shared_ptr<java::lang::String>>> arg0) { } jnivm::test::Gamma::Functional::Test5::HelloWorld::HelloWorld(std::shared_ptr<test::Gamma::Functional::Test5> arg0) { } BEGIN_NATIVE_DESCRIPTOR(jnivm::baron::impl::createMainMethod) {FakeJni::Function<&createMainMethod::main>{}, "main", FakeJni::JMethodID::PUBLIC | FakeJni::JMethodID::STATIC }, END_NATIVE_DESCRIPTOR BEGIN_NATIVE_DESCRIPTOR(jnivm::test::Gamma::Functional) END_NATIVE_DESCRIPTOR BEGIN_NATIVE_DESCRIPTOR(jnivm::test::Gamma::Functional::Test5) END_NATIVE_DESCRIPTOR BEGIN_NATIVE_DESCRIPTOR(jnivm::test::Gamma::Functional::Test5::HelloWorld) {FakeJni::Constructor<HelloWorld, std::shared_ptr<test::Gamma::Functional::Test5>>{}}, END_NATIVE_DESCRIPTOR TEST(Baron, Test23) { Baron::Jvm vm; createMainMethod(vm, [](std::shared_ptr<FakeJni::JArray<FakeJni::JString>> args) { std::cout << "main called\n"; FakeJni::LocalFrame frame; jclass c = frame.getJniEnv().FindClass("test/Gamma/Functional$Test5$HelloWorld"); frame.getJniEnv().GetMethodID(c, "<init>", "(Ltest/Gamma/Functional$Test5;)V"); }); vm.registerClass<jnivm::baron::impl::createMainMethod>(); vm.registerClass<jnivm::test::Gamma::Functional::Test5::HelloWorld>(); vm.start(); vm.destroy(); vm.printStatistics(); } TEST(JNIVM, FakeJni_0_0_5_COMPAT) { jstring jo; using namespace jnivm; VM vm; std::shared_ptr<String> s = std::make_shared<String>("Test"); { String s2 = { "Test2" }; // created a copy jo = JNITypes<String>::ToJNIType(vm.GetEnv().get(), s2); auto j2 = JNITypes<String>::ToJNIType(vm.GetEnv().get(), &s2); } auto len = vm.GetJNIEnv()->GetStringLength(jo); String s3; s3 = JNITypes<String>::JNICast(vm.GetEnv().get(), jo); } class FakeJni_0_0_5_COMPAT_TEST : public FakeJni::JObject { FakeJni::JString testmember; // std::string testmember2; public: DEFINE_CLASS_NAME("FakeJni_0_0_5_COMPAT_TEST"); }; BEGIN_NATIVE_DESCRIPTOR(FakeJni_0_0_5_COMPAT_TEST) {FakeJni::Constructor<FakeJni_0_0_5_COMPAT_TEST>{}}, {FakeJni::Field<&FakeJni_0_0_5_COMPAT_TEST::testmember>{}, "testmember" }, // {FakeJni::Field<&FakeJni_0_0_5_COMPAT_TEST::testmember2>{}, "testmember2" }, END_NATIVE_DESCRIPTOR TEST(FakeJni, FakeJni_0_0_5_COMPAT_TEST) { FakeJni::Jvm vm; vm.registerClass<FakeJni_0_0_5_COMPAT_TEST>(); FakeJni::LocalFrame frame; auto&&env = frame.getJniEnv(); jclass cl = env.FindClass("FakeJni_0_0_5_COMPAT_TEST"); jmethodID mid = env.GetMethodID(cl, "<init>", "()V"); jobject obj = env.NewObject(cl, mid); jfieldID fid = env.GetFieldID(cl, "testmember", "Ljava/lang/String;"); jstring value = (jstring)env.GetObjectField(obj, fid); auto chars = env.GetStringUTFChars(value, nullptr); std::cout << "value: `" << chars << "`\n"; env.ReleaseStringUTFChars(value, chars); env.SetObjectField(obj, fid, env.NewStringUTF("Hello World")); value = (jstring)env.GetObjectField(obj, fid); chars = env.GetStringUTFChars(value, nullptr); std::cout << "value: `" << chars << "`\n"; env.ReleaseStringUTFChars(value, chars); vm.destroy(); static_assert(std::is_same<FakeJni::JArray<FakeJni::JString *>, FakeJni::JArray<FakeJni::JString>>::value, "SameType"); FakeJni::JString s = {"Hi"}; auto ay = std::make_shared<FakeJni::JArray<FakeJni::JString>>(1); FakeJni::JArray<FakeJni::JString *> * args = ay.get(); (*args)[0] = &s; ASSERT_TRUE((*args)[0]); FakeJni::JString* s5 = (*args)[0] = s; ASSERT_TRUE(s5); std::cout << *s5 << "\n"; } TEST(Baron, DeniedFabrication) { Baron::Jvm jvm; jvm.denyClass("Test"); FakeJni::LocalFrame f; ASSERT_EQ(f.getJniEnv().FindClass("Test"), (jclass)0); ASSERT_NE(f.getJniEnv().FindClass("Test2"), (jclass)0); jvm.denyClass("Test2"); ASSERT_NE(f.getJniEnv().FindClass("Test2"), (jclass)0); jvm.denyMethod("<init>", "()V"); jclass t2 = f.getJniEnv().FindClass("Test2"); ASSERT_EQ(f.getJniEnv().GetMethodID(t2, "<init>", "()V"), (jmethodID)0); ASSERT_NE(f.getJniEnv().GetMethodID(t2, "test", "()V"), (jmethodID)0); ASSERT_NE(f.getJniEnv().GetMethodID(t2, "<init>", "(Ljava/lang/String;)V"), (jmethodID)0); jvm.denyMethod("", "()Ljava/lang/String;"); ASSERT_EQ(f.getJniEnv().GetMethodID(t2, "test2", "()Ljava/lang/String;"), (jmethodID)0); ASSERT_NE(f.getJniEnv().GetMethodID(t2, "test3", "()Ljava/lang/Object;"), (jmethodID)0); ASSERT_NE(f.getJniEnv().GetMethodID(t2, "somethingelse", "()Ljava/lang/Object;"), (jmethodID)0); ASSERT_EQ(f.getJniEnv().GetMethodID(t2, "somethingelse", "()Ljava/lang/String;"), (jmethodID)0); jvm.denyField("", "Ljava/lang/String;"); ASSERT_EQ(f.getJniEnv().GetFieldID(t2, "test2", "Ljava/lang/String;"), (jfieldID)0); ASSERT_NE(f.getJniEnv().GetFieldID(t2, "test3", "Ljava/lang/Object;"), (jfieldID)0); ASSERT_NE(f.getJniEnv().GetFieldID(t2, "somethingelse", "Ljava/lang/Object;"), (jfieldID)0); ASSERT_EQ(f.getJniEnv().GetFieldID(t2, "somethingelse", "Ljava/lang/String;"), (jfieldID)0); jvm.denyField("somethingelseAgain", "Ljava/lang/Object;"); ASSERT_EQ(f.getJniEnv().GetFieldID(t2, "somethingelseAgain", "Ljava/lang/Object;"), (jfieldID)0); jvm.denyField("somethingelseAgain2", "Ljava/lang/Object;", "java/lang/String"); ASSERT_NE(f.getJniEnv().GetFieldID(t2, "somethingelseAgain2", "Ljava/lang/Object;"), (jfieldID)0); ASSERT_EQ(f.getJniEnv().GetFieldID(f.getJniEnv().FindClass("java/lang/String"), "somethingelseAgain2", "Ljava/lang/Object;"), (jfieldID)0); jvm.printStatistics(); { jnivm::VM vm; class Y : public jnivm::Extends<> { public: virtual void Gamma() {} }; class X : public jnivm::Extends<Y> { public: void Gamma() override {} }; vm.GetEnv()->GetClass<Y>("Y")->Hook(vm.GetEnv().get(), "Gamma", &Y::Gamma); vm.GetEnv()->GetClass<X>("X")->Hook(vm.GetEnv().get(), "Gamma", &X::Gamma); auto c = vm.GetJNIEnv()->FindClass("X"); auto m = vm.GetJNIEnv()->GetMethodID(c, "<init>", "()V"); auto o = vm.GetJNIEnv()->NewObject(c, m); auto m2 = vm.GetJNIEnv()->GetMethodID(c, "Gamma", "()V"); vm.GetJNIEnv()->CallNonvirtualVoidMethod(o, c, m2); // X y; // Y* x = &y; // void (Y::*gamma)() = &Y::Gamma; // (x->*gamma)(); } } TEST(JNIVM, Wrapper) { jnivm::VM vm; auto env = vm.GetEnv().get(); class Testclass : public jnivm::Extends<> { }; auto testclass = env->GetClass<Testclass>("Testclass"); bool success = false; testclass->HookInstanceFunction(env, "A", [&success, e2=env](jnivm::ENV* env) { success = (e2 == env); }); testclass->HookInstanceFunction(env, "B", [&success, e2=env](jnivm::ENV* env, jnivm::Object* obj) { success = (e2 == env) && obj != nullptr; }); testclass->HookInstanceFunction(env, "C", [&success, e2=env](jnivm::ENV* env, Testclass* obj) { success = (e2 == env) && obj != nullptr; }); auto nenv = env->GetJNIEnv(); auto nc = nenv->FindClass("Testclass"); auto no = nenv->NewObject(nc, nenv->GetMethodID(nc, "<init>", "()V")); nenv->CallVoidMethod(no, nenv->GetMethodID(nc, "A", "()V")); ASSERT_TRUE(success); success = false; nenv->CallVoidMethod(no, nenv->GetMethodID(nc, "B", "()V")); ASSERT_TRUE(success); success = false; nenv->CallVoidMethod(no, nenv->GetMethodID(nc, "C", "()V")); ASSERT_TRUE(success); success = false; nenv->CallVoidMethod(no, nenv->GetMethodID(nc, "D", "(Ljava/lang/String;)V"), nenv->NewStringUTF("Test")); } TEST(JNIVM, FilterFalsePositives) { using namespace jnivm; VM vm(false, true); auto&& env = vm.GetEnv(); env->GetClass<TestInterface>("TestInterface"); bool success = false; env->GetClass<TestClass>("TestClass")->HookInstance(env.get(), "Test", [&success](TestInterface* interface) { success = true; }); auto jenv = env->GetJNIEnv(); auto c = jenv->FindClass("TestClass"); ASSERT_FALSE(jenv->GetMethodID(c, "Test", "()V")); auto id = jenv->GetMethodID(c, "Test", "(LTestInterface;)V"); ASSERT_TRUE(id); auto tc = std::make_shared<TestClass>(); auto nobj = jnivm::JNITypes<TestClass>::ToJNIType(vm.GetEnv().get(), tc); jenv->CallVoidMethod(nobj, id, nullptr); ASSERT_TRUE(success); } TEST(JNIVM, OptionalParameter) { using namespace jnivm; VM vm(false, true); auto&& env = vm.GetEnv(); env->GetClass("JustATest")->Hook(env.get(), "member", [](ENV* env) { }); env->GetClass("JustATest")->Hook(env.get(), "member2", [](ENV* env, Object* obj) { }); // JNITypes<jclass>::JNICast() env->GetClass("JustATest")->Hook(env.get(), "member3", [](ENV* env, jobject obj) { }); env->GetClass("JustATest")->Hook(env.get(), "member4", [](ENV* env, jclass c) { }); env->GetClass("JustATest")->Hook(env.get(), "member5", [](ENV* env, Class* c) { }); env->GetClass("JustATest")->Hook(env.get(), "member6", [](JNIEnv* env, jclass c) { auto m = env->GetStaticMethodID(c, "member", "()V"); env->CallStaticVoidMethod(c, m); }); env->GetClass("JustATest")->Hook(env.get(), "member7", [](jclass c) { }); env->GetClass("JustATest")->Hook(env.get(), "member8", [](Class* c) { }); env->GetClass("JustATest")->Hook(env.get(), "member9", [](JNIEnv* env) { }); env->GetClass("JustATest")->HookGetterFunction(env.get(), "field0", [](JNIEnv* env) { return 2; }); env->GetClass("JustATest")->HookGetterFunction(env.get(), "field0", [](Class* cl) { return 4; }); env->GetClass("JustATest")->HookGetterFunction(env.get(), "field0", [](JNIEnv* env, Class* cl) { return 3; }); env->GetClass("JustATest")->HookSetterFunction(env.get(), "field0", [](JNIEnv* env, int i) { }); env->GetClass("JustATest")->HookSetterFunction(env.get(), "field0", [](Class* cl, int i) { }); env->GetClass("JustATest")->HookSetterFunction(env.get(), "field0", [](JNIEnv* env, Class* cl, int i) { }); env->GetClass("JustATest")->HookInstanceGetterFunction(env.get(), "field2", [](JNIEnv* env) { return 2; }); env->GetClass("JustATest")->HookInstanceGetterFunction(env.get(), "field2", [](Object* cl) { return 4; }); env->GetClass("JustATest")->HookInstanceGetterFunction(env.get(), "field2", [](JNIEnv* env, Object* cl) { return 3; }); env->GetClass("JustATest")->HookInstanceSetterFunction(env.get(), "field2", [](JNIEnv* env, int i) { }); env->GetClass("JustATest")->HookInstanceSetterFunction(env.get(), "field2", [](Object* cl, int i) { }); env->GetClass("JustATest")->HookInstanceSetterFunction(env.get(), "field2", [](JNIEnv* env, Object* cl, int i) { }); auto c = env->GetJNIEnv()->FindClass("JustATest"); auto m = env->GetJNIEnv()->GetStaticMethodID(c, "member6", "()V"); ASSERT_TRUE(m); env->GetJNIEnv()->CallStaticVoidMethod(c, m); }
true
5632c2872d9aa3e1f33a96b44039a04ec5d23f69
C++
mytpp/FakeOS
/FakeOS/FakeOS/CPUCore.cpp
GB18030
11,403
2.65625
3
[]
no_license
#include "CPUCore.h" #include "ProcessScheduler.h" #include "MemoryManager.h" #include "FileSystem.h" #include <cassert> #include <iostream> #include <sstream> using namespace std; using namespace kernel; inline void removePrefixedSpace(string_view& sv) { sv.remove_prefix(min(sv.find_first_not_of(' '), sv.size())); } inline string_view getNextParameter(string_view& sv, int& pos) { sv = sv.substr(pos + 1); removePrefixedSpace(sv); pos = sv.find_first_of(' '); string_view ret = sv.substr(0, pos); removePrefixedSpace(sv); return ret; } CPUCore::CPUCore() :_quit(false) , _thread(nullptr, kernel::ThreadDeleter) , _timeElapsed(0) { } CPUCore::~CPUCore() { } void CPUCore::start() { assert(!_thread); _quit = false; _thread.reset(new thread( bind(&CPUCore::threadFunc, this) )); } void CPUCore::quit() { _quit = true; } /******************************************************************************* ƣ:threadFunc() : ѭóһ׼õḶ̌ȥӦʱӣ£ʱִС *******************************************************************************/ void CPUCore::threadFunc() { while (!_quit) { //periodically wake up processScheduler //cout << "33333"; if (_timeElapsed % kScheduleInterval == 0) processScheduler->wakeUp(); {//critical section //scoped_lock lock(ScheduleQueue::readyQueueMutex); if (processScheduler->getRunningProcess() == NULL) { } else { processScheduler->getRunningProcess()->programCounter--; //cout << processScheduler->getRunningProcess()->programCounter; processScheduler->getRunningProcess()->state = ScheduleQueue::kReady; if (processScheduler->getRunningProcess()->programCounter == 0) { string tmpStr; if (processScheduler->getRunningProcess()->restCode.find('\n') == processScheduler->getRunningProcess()->restCode.npos || processScheduler->getRunningProcess()->restCode.find('\n') == processScheduler->getRunningProcess()->restCode.length() - 1) { tmpStr = processScheduler->getRunningProcess()->restCode.substr(processScheduler->getRunningProcess()->restCode.find(' ')+1); //cout << tmpStr; if (tmpStr.back() == '\n') { tmpStr = tmpStr.substr(0, tmpStr.length() - 1); } //cout << tmpStr; ParseAndDoDirective(tmpStr, processScheduler->getRunningProcess()->file_ptr); } else { tmpStr = processScheduler->getRunningProcess()->restCode.substr(processScheduler->getRunningProcess()->restCode.find(' ') + 1,processScheduler->getRunningProcess()->restCode.find('\n')-1); //cout << tmpStr; //cout << tmpStr; if (tmpStr.back() == '\n') { tmpStr = tmpStr.substr(0, tmpStr.length() - 1); } ParseAndDoDirective(tmpStr, processScheduler->getRunningProcess()->file_ptr); } if (processScheduler->getRunningProcess()->restCode.find('\n') == processScheduler->getRunningProcess()->restCode.npos || processScheduler->getRunningProcess()->restCode.find('\n') == processScheduler->getRunningProcess()->restCode.length() - 1) { processScheduler->getRunningProcess()->state = ScheduleQueue::kTerminated; /*All demands have been done, so the process should be terminated*/ } else { /*There are still demands needed to be done.*/ int index = processScheduler->getRunningProcess()->restCode.find('\n'); processScheduler->getRunningProcess()->restCode = processScheduler->getRunningProcess()->restCode.substr(index + 1, processScheduler->getRunningProcess()->restCode.length() - 1); processScheduler->getRunningProcess()->programCounter = processScheduler->getRunningProcess()->restCode.at(0); } } } //peek the top element of kernel::readyQueue //if programCounter reach 0, call ParseAndDoDirective() } {//critical section //scoped_lock lock(ScheduleQueue::waitingQueueMutex); for (int ioCounter = 0; ioCounter < _ioChannel.size(); ioCounter++) { if (_ioChannel[ioCounter].event.wait_for(std::chrono::milliseconds(5)) == std::future_status::ready) { _ioChannel[ioCounter].pcb->state = ScheduleQueue::kReady; } } //poll _ioChannel to see if there is IO event ready, //and change the corresponding PCB's state to ready } this_thread::sleep_for(kernel::kCPUCycle); _timeElapsed++; } } /******************************************************************************* ƣ:ParseAndDoDirective(const string& directive, uint16_t file_ptr) : ̵ִк *******************************************************************************/ bool CPUCore::ParseAndDoDirective(const string& directive, uint16_t file_ptr) { //interact with MemoryAllocator and FileSystem //code here... //stringstream ss(directive); //string word; //int len = directive.length(); //int numind = directive.find(' '); //if (numind == string::npos) // return false; //int time=atoi(directive.substr(0, numind).c_str()); //if (!(ss >> word))return false; //int time = atoi(word.c_str()); //if (time < 0) // return false; //if (!(ss >> word))return false; //string curd_d = word; //if (curd_d == "DemandMemory") //{ // if (!(ss >> word))return false; // int var1 = atoi(word.c_str()); // if (!(ss >> word) || word != "As")return false; // if (!(ss >> word))return false; // int var2 = atoi(word.c_str()); // // process // //memoryManager->virtualAllocate(_ioChannel.pcb, var1, var2); //} //else if (curd_d == "FreeMemory") //{ // if (!(ss >> word))return false; // int var1 = atoi(word.c_str()); // // process // //memoryManager->virtualFree(_ioChannel.pcb, var1); //} //else if (curd_d == "AccessMemory") //{ // if (!(ss >> word))return false; // int var1 = atoi(word.c_str()); // // process // //memoryManager->accessMemory(_ioChannel.pcb, var1); //} //else if (curd_d == "CreateFile") //{ // if (!(ss >> word))return false; // string filename = word; // int ind = directive.find(word); // string content = directive.substr(ind + word.length()); // //process // fileSystem->createFile(filename, content); //} //else if (curd_d == "DeleteFile") //{ // if (!(ss >> word))return false; // string filename = word; // //process // fileSystem->removeFile(filename); //} //else if (curd_d == "DeleteFile") //{ // cout << "ls" << endl; // auto names = fileSystem->list(); // for (auto& name : names) // cout << name << endl; //} //else if (curd_d == "cd") //{ // if (!(ss >> word))return false; // string path = word; // if (path == "..") // fileSystem->back(); // else { // cout << "loading..." << endl; // fileSystem->load(path); // } //} string_view command_view(directive); removePrefixedSpace(command_view); int separatorPosition = command_view.find_first_of(' '); string_view commandName = command_view.substr(0, separatorPosition); if (commandName == "DemandMemory") { size_t var1, var2; string_view word = getNextParameter(command_view, separatorPosition); if (command_view != "") { var1 = atoi(string{ word }.c_str()); } else cout << "Unrecognized Parameters" << endl; separatorPosition = command_view.find_first_of(' '); string_view middle = getNextParameter(command_view, separatorPosition); if (command_view == "" || string{ middle } == "As") cout << "Unrecognized Parameters" << endl; separatorPosition = command_view.find_first_of(' '); string_view word2 = getNextParameter(command_view, separatorPosition); if (command_view != "" && string{ middle } == "As") { var2 = atoi(string{ word2 }.c_str()); } else cout << "Unrecognized Parameters" << endl; // process memoryManager->virtualAllocate(processScheduler->getRunningProcess(), var1, var2); } else if (commandName == "FreeMemory") { string_view word = getNextParameter(command_view, separatorPosition); size_t var1 = atoi(string{ word }.c_str()); // process memoryManager->virtualFree(processScheduler->getRunningProcess(), var1); } else if (commandName == "AccessMemory") { string_view word = getNextParameter(command_view, separatorPosition); size_t var1 = atoi(string{ word }.c_str()); // process memoryManager->accessMemory(processScheduler->getRunningProcess(), var1); } else if (commandName == "ls") { auto names = fileSystem->list(file_ptr); for (auto& name : names) cout << name << endl; } else if (commandName == "cd") { string_view path = getNextParameter(command_view, separatorPosition); if (command_view != "") { if (string{ path } == "..") fileSystem->back(file_ptr); else { cout << "loading..." << endl; fileSystem->load(string{ path }, file_ptr); } } else cout << "Unrecognized Parameters" << endl; } else if (commandName == "cf") { string_view name = getNextParameter(command_view, separatorPosition); separatorPosition = command_view.find_first_of(' '); string_view content = getNextParameter(command_view, separatorPosition); //cout << command_view.size() << endl; //cout << command_view.front() << endl; //cout << command_view.back() << endl; //cout << command_view; if (command_view.size() >= 2 && command_view.front() == '"' && command_view.back() == '"') { size_t pos1 = command_view.find_first_of('"'); size_t pos2 = command_view.find_last_of('"'); command_view = command_view.substr(pos1 + 1, pos2 - 1); fileSystem->createFile( string{ name }, string{ command_view }, file_ptr); } else cout << "Unrecognized Parameters" << endl; } else if (commandName == "af") { string_view name = getNextParameter(command_view, separatorPosition); separatorPosition = command_view.find_first_of(' '); string_view content = getNextParameter(command_view, separatorPosition); if (command_view.size() >= 2 && command_view.front() == '"' && command_view.back() == '"') { size_t pos1 = command_view.find_first_of('"'); size_t pos2 = command_view.find_last_of('"'); cout << pos1 << " " << pos2 << endl; command_view = command_view.substr(pos1 + 1, pos2 - 1); cout << string{ command_view } << endl; fileSystem->appendFile( string{ name }, string{ command_view }, file_ptr); } else cout << "Unrecognized Parameters" << endl; } else if (commandName == "md") { string_view name = getNextParameter(command_view, separatorPosition); if (command_view != "") { fileSystem->createDirectory(string{ name }, file_ptr); } else cout << "Unrecognized Parameters" << endl; } else if (commandName == "rm") { string_view name = getNextParameter(command_view, separatorPosition); if (command_view != "") { fileSystem->removeFile(string{ name }, file_ptr); } else cout << "Unrecognized Parameters" << endl; } else if (commandName._Starts_with("./")) { string_view programName = commandName.substr(2); ScheduleQueue::LoadProcess(string{ programName }, file_ptr); } else return false;//if directive is unrecognizable return true; }
true
15e84f3d2b2d4a99baacebfc1ea8e67fe1a50af0
C++
Ynjxsjmh/DataStructureAssignment
/结果/第七次在线测评结果/source/1114/preorder.cpp
UTF-8
1,122
3.328125
3
[]
no_license
#include <iostream> #include <string> #include <fstream> using namespace std; ifstream fin("preorder.in"); ofstream fout("preorder.out"); struct point { char data; point *left; point *right; }; class tree { public: point *root; void build(string &, string &, point *&); tree(); void preorder(point *); }; void tree::preorder(point * p) { if(p == NULL) return; fout << p->data; preorder(p->left); preorder(p->right); } tree::tree() { string s2; string s1; fin >> s2; fin >> s1; build(s1, s2, root); } void tree::build(string &s1, string &s2, point *&p) { int j, l; char c; l = s1.length(); if(l == 0) { p = NULL; return; } p = new point; c = *(s1.substr(l-1,1).c_str()); p->data = c; for(j = 0; *(s2.substr(j,1).c_str()) != c; j++); string s11 = s1.substr(0, j); string s21 = s2.substr(0, j); string s12 = s1.substr(j, l-j-1); string s22 = s2.substr(j+1, l-j-1); build(s11, s21, p->left); build(s12, s22, p->right); } int main() { tree t; t.preorder(t.root); }
true
16b81015c374c3a3a613b0a4a5dd82950dd741e6
C++
nathan-create/assignment-problems
/seqSum.cpp
UTF-8
1,061
3.671875
4
[]
no_license
# include <iostream> # include <cassert> int seqSum(int n){ if (n==0){ return 0; } int seqList[n+1]; int sum = 1; seqList[0] = 0; seqList[1] = 1; for (int x = 2; x <= n; x++){ seqList[x] = seqList[x-1] + 2 * seqList[x-2]; sum += seqList[x]; } return sum; } int extendedSeqSum(int n){ int seqList[n+1]; int extendedSum = 1; seqList[0] = 0; seqList[1] = 1; for (int x = 2; x <= n; x++){ seqList[x] = seqList[x-1] + 2 * seqList[x-2]; } int extendedSeqList[seqList[n]+1]; extendedSeqList[0] = 0; extendedSeqList[1] = 1; for (int x = 2; x<=seqList[n]; x++){ extendedSeqList[x] = extendedSeqList[x-1] + 2 * extendedSeqList[x-2]; extendedSum += extendedSeqList[x]; } return extendedSum; } int main() { std::cout << "Testing...\n"; assert(seqSum(0)==0); assert(seqSum(3)==5); assert(seqSum(8)==170); assert(extendedSeqSum(2)==1); assert(extendedSeqSum(4)==21); std::cout << "Success!"; return 0; }
true
61357dfcfb90b97828a2352ee71f5531356d0e78
C++
sharp104/SmartMancala
/Mancala.cpp
UTF-8
9,992
2.984375
3
[]
no_license
// Mancala.cpp : Defines the entry point for the application. // #include "Mancala.h" #include <array> using namespace std; MancalaState::MancalaState() { init(); } void MancalaState::init() { cur_p = 0; p1pock = 0; p2pock = 0; gameover = false; for (int i = 0; i < BOARD_SIZE; i++) { board[i] = 4; } } void MancalaState::set_cur_p(short cp) { cur_p = cp; } void MancalaState::add_p1pock(short num) { p1pock += num; } void MancalaState::add_p2pock(short num) { p2pock += num; } void MancalaState::set_gameover() { gameover = true; } void MancalaState::set_board(short index, short value) { if (index < BOARD_SIZE) { board[index] = value; } } void MancalaState::make_move(int move) { int held_rocks; bool flip = true; if (move < 0 || move >= 6) return; int cur_spot = cur_p * 6 + move; held_rocks = board[cur_spot]; board[cur_spot] = 0; while (held_rocks > 0) { if (cur_spot == 0) { if (cur_p == 0) { p1pock++; held_rocks--; if (held_rocks == 0) { flip = false; break; } } cur_spot = 6; board[cur_spot]++; held_rocks--; continue; } else if (cur_spot == 11) { if (cur_p == 1) { p2pock++; held_rocks--; if (held_rocks == 0) { flip = false; break; } } cur_spot = 5; board[cur_spot]++; held_rocks--; continue; } // Handle directional movement if (cur_spot < 6) cur_spot--; else cur_spot++; board[cur_spot]++; held_rocks--; } // Check for capture if (flip && (cur_spot / 6 == cur_p) && board[cur_spot] == 1) { if (cur_p == 0) { if (board[cur_spot + 6] > 0) { p1pock += board[cur_spot + 6]; p1pock++; board[cur_spot] = 0; board[cur_spot + 6] = 0; } } else if (cur_p == 1) { if (board[cur_spot - 6] > 0) { p2pock += board[cur_spot - 6]; p2pock++; board[cur_spot] = 0; board[cur_spot - 6] = 0; } } } // Flip players if needed if (flip) { if (cur_p == 0) cur_p = 1; else cur_p = 0; } array<bool, 6> legal_moves = this->get_legal_moves(); for (int i = 0; i < 6; i++) { if (legal_moves[i]) return; } gameover = true; for (int j = 0; j < 6; j++) { p1pock += board[j]; p2pock += board[j + 6]; board[j] = 0; board[j + 6] = 0; } } array<bool, 6> MancalaState::get_legal_moves() { array<bool, 6> retvals; for (int i = 0; i < 6; i++) { if (board[cur_p * 6 + i] > 0) retvals[i] = true; else retvals[i] = false; } return retvals; } void MancalaState::print() { cout << "Player 1: " << p1pock << endl; cout << "Player 2: " << p2pock << endl; for (int i = 0; i < 6; i++) { cout << " " << board[i]; } cout << endl; for (int i = 6; i < 12; i++) { cout << " " << board[i]; } cout << endl; if (cur_p == 0) cout << "Player 1 to move." << endl; else cout << "Player 2 to move." << endl; } MancalaState MancalaState::copy() { MancalaState new_state; new_state.cur_p = cur_p; new_state.p1pock = p1pock; new_state.p2pock = p2pock; new_state.gameover = gameover; new_state.board[0] = board[0]; new_state.board[1] = board[1]; new_state.board[2] = board[2]; new_state.board[3] = board[3]; new_state.board[4] = board[4]; new_state.board[5] = board[5]; new_state.board[6] = board[6]; new_state.board[7] = board[7]; new_state.board[8] = board[8]; new_state.board[9] = board[9]; new_state.board[10] = board[10]; new_state.board[11] = board[11]; return new_state; } float MancalaEval::evaluate(MancalaState state) { // Should only ever see MancalaState float eval = state.p1pock - state.p2pock; return eval; } Mancala::Mancala(Agent* p_1, MancalaMMAgent a1, MancalaMMAgent a2) { p1 = p_1; ai1 = a1; ai2 = a2; } short Mancala::play(short mode) { int move; if (state.gameover) state.init(); while (!state.gameover) { state.print(); if (mode == 0) { move = p1->get_move(); } else if (mode == 1) { // AIvP if (state.cur_p == 0) { move = ai1.get_move(state); cout << "Computer plays: " << move << endl; cout << endl; } else { move = p1->get_move(); } } else if (mode == 2) { // PvAI if (state.cur_p == 0) { move = p1->get_move(); } else { move = ai1.get_move(state); cout << "Computer plays: " << move << endl; } } else { // AIvAI if (state.cur_p == 1) { move = ai2.get_move(state); cout << "Computer plays: " << move << endl; } else { move = ai1.get_move(state); cout << "Computer plays: " << move << endl; } } state.make_move(move); } cout << "Game Over!" << endl; state.print(); if (state.p1pock > state.p2pock) return 0; return 1; } SMDouble::SMDouble(float sc, short mv) { score = sc; move = mv; } SMQuad::SMQuad(float sc, short mv, float a, float b) { score = sc; move = mv; alpha = a; beta = b; } MancalaMMAgent::MancalaMMAgent() { evaluator = MancalaEval(); max_depth = 10; } MancalaMMAgent::MancalaMMAgent(MancalaEval e, int max_d) { evaluator = e; max_depth = max_d; } short MancalaMMAgent::get_move(MancalaState state) { bool isMax = state.cur_p == 0; SMDouble result = abpruned(state, 0, max_depth, isMax, -9999, 9999); cout << "Eval of position: " << result.score << endl; return result.move; } SMDouble MancalaMMAgent::minimax(MancalaState state, int cur_depth, int max_depth, bool isMax) { if (cur_depth == max_depth) { float score = evaluator.evaluate(state); return SMDouble(score, -1); } array<bool, 6> legal_moves = state.get_legal_moves(); array<float, 6> move_evals; bool still_legal_moves_flag = false; for (int i = 0; i < 6; i++) { // Explore all moves to legal depth if (!legal_moves[i]) continue; still_legal_moves_flag = true; MancalaState state_copy = state.copy(); state_copy.make_move(i); if (state_copy.gameover) { float score = evaluator.evaluate(state); return SMDouble(score, i); } else { SMDouble future = minimax( state_copy, cur_depth + 1, max_depth, state_copy.cur_p == 0 ); move_evals[i] = future.score; } } // Look for best move short best_move = -1; float best_score = -1000; for (int i = 0; i < 6; i++) { if (!legal_moves[i]) continue; if (best_move == -1) { best_move = i; best_score = move_evals[i]; } else { if (isMax) { if (move_evals[i] > best_score) { best_move = i; best_score = move_evals[i]; } } else { if (move_evals[i] < best_score) { best_move = i; best_score = move_evals[i]; } } } } return SMDouble(best_score, best_move); } SMDouble MancalaMMAgent::abpruned(MancalaState state, int cur_depth, int max_depth, bool isMax, float alpha, float beta) { if (cur_depth >= max_depth) { int score = evaluator.evaluate(state); return SMDouble(score, -1); } array<bool, 6> legal_moves = state.get_legal_moves(); array<float, 6> move_evals = { 99, 99, 99, 99, 99, 99 }; bool still_legal_moves_flag = false; if (isMax) { float v = alpha; for (int i = 0; i < 6; i++) { // Explore all moves to legal depth if (!legal_moves[i]) continue; still_legal_moves_flag = true; MancalaState state_copy = state.copy(); state_copy.make_move(i); if (state_copy.gameover) { float score = evaluator.evaluate(state_copy); move_evals[i] = score; v = max(score, v); if (beta <= v) break; } else { int new_depth = cur_depth; if (state_copy.cur_p != state.cur_p) new_depth++; SMDouble future = abpruned( state_copy, new_depth, max_depth, state_copy.cur_p == 0, v, beta ); move_evals[i] = future.score; v = max(future.score, v); if (beta <= v) break; } } } else { float v = beta; for (int i = 0; i < 6; i++) { // Explore all moves to legal depth if (!legal_moves[i]) continue; still_legal_moves_flag = true; MancalaState state_copy = state.copy(); state_copy.make_move(i); if (state_copy.gameover) { float score = evaluator.evaluate(state_copy); move_evals[i] = score; v = min(score, v); if (v <= alpha) break; } else { int new_depth = cur_depth; if (state_copy.cur_p != state.cur_p) new_depth++; SMDouble future = abpruned( state_copy, new_depth, max_depth, state_copy.cur_p == 0, alpha, v ); move_evals[i] = future.score; v = min(future.score, v); if (v <= alpha) break; } } } // Look for best move short best_move = -1; float best_score = -1000; for (int i = 0; i < 6; i++) { if (!legal_moves[i] || move_evals[i] == 99) continue; if (best_move == -1) { best_move = i; best_score = move_evals[i]; } else { if (isMax) { if (move_evals[i] > best_score) { best_move = i; best_score = move_evals[i]; } } else { if (move_evals[i] < best_score) { best_move = i; best_score = move_evals[i]; } } } } return SMDouble(best_score, best_move); } int main() { HumAgent *h = new HumAgent(); MancalaState s; MancalaEval evaluator; int depth; cout << "What search depth? "; cin >> depth; cout << endl; MancalaMMAgent mma(evaluator, depth); //cout << mma.get_move(s, 11) << endl; Mancala m(h, mma, mma); int status = 1; while (status > 0 && status < 3) { cout << "First or second? "; cin >> status; cout << endl; if (status == 1) { m.play(1); } else if (status == 2) { m.play(2); } } return 0; }
true
725c51b3682120a0b6337f7fd14b8f538d71ca61
C++
AnvilOnline/AnvilClient
/AnvilEldorado/Source/Blam/Math/RealOrientation3D.cpp
UTF-8
649
2.921875
3
[ "MIT" ]
permissive
#include "RealOrientation3D.hpp" namespace Blam::Math { RealOrientation3D::RealOrientation3D() : RealOrientation3D(RealQuaternion(), RealPoint3D(), 0.0f) { } RealOrientation3D::RealOrientation3D(const RealQuaternion &rotation, const RealPoint3D &translation, const float scale) : Rotation(rotation), Translation(translation), Scale(scale) { } bool RealOrientation3D::operator==(const RealOrientation3D &other) const { return Rotation == other.Rotation && Translation == other.Translation && Scale == other.Scale; } bool RealOrientation3D::operator!=(const RealOrientation3D &other) const { return !(*this == other); } }
true
001895860d7523797528968a4b32438dc137c12c
C++
westlicht/teensy-template
/src/Point.h
UTF-8
178
2.859375
3
[]
no_license
#pragma once #include <cstdint> //! 2D point. struct Point { int16_t x; int16_t y; constexpr Point(int16_t x_, int16_t y_) : x(x_), y(y_) {} }; typedef Point Size;
true
0a077a92abc3b1a74df2e088fa389a9246ed9199
C++
tonyinuma/ArduinoNodeJS
/counter/counter.ino
UTF-8
292
2.546875
3
[]
no_license
//int counter = 0; float tempC; int pinLM35 = 0; void setup() { Serial.begin(9600); } void loop() { //Serial.print(++counter, DEC); //delay(2000); tempC = analogRead(pinLM35); tempC = (5.0 * tempC * 100.0)/1024.0; Serial.print(tempC); Serial.print("\n"); delay(10000); }
true
4a518697899e9be4ec0e16bebf8f2f135fac199f
C++
JuanFerInc/Prog-4
/3_lab0/Lab_0/Source/DtViajeBase.cpp
UTF-8
592
2.5625
3
[]
no_license
#include <string> #include "../Header/DtViajeBase.h" //Constructora DtViajeBase::DtViajeBase() { } DtViajeBase::DtViajeBase(DtFecha fecha_arg, int duracion_arg, int distancia_arg) { fecha = fecha_arg; duracion = duracion_arg; distancia = distancia_arg; } DtViajeBase::DtViajeBase(const DtViajeBase& via) { this->fecha = via.fecha; this->duracion = via.duracion; this->distancia = via.distancia; } //Get DtFecha DtViajeBase::getFecha(){ return this->fecha; } int DtViajeBase::getDuracion(){ return this->duracion; } int DtViajeBase::getDistancia(){ return this->distancia; }
true
28733ec35575412bf07f52338fdfb9e2a855a77a
C++
SX-CPP/sci_computing_cpp_wi2019
/exercises/solution/sheet8/exercise3/almost_equal.hh
UTF-8
580
3.390625
3
[]
no_license
#pragma once #include <cmath> #include <limits> #include <utility> // floating-point comparison template <class T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type almost_equal(T x, T y, int ulp = 2) { return std::abs(x-y) <= std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp // unless the result is subnormal || std::abs(x-y) < std::numeric_limits<T>::min(); } // integer comparison template <class T> typename std::enable_if< std::numeric_limits<T>::is_integer, bool>::type almost_equal(T x, T y, int ulp = 2) { return x == y; }
true
d2097924e6a481f08086b0f0a8b1e2a29ed65931
C++
nuttert/Server-back
/Utils/Containers/multi_index_container.hpp
UTF-8
7,504
3.046875
3
[]
no_license
#pragma once #include <boost/multi_index_container.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/mem_fun.hpp> #include <Utils/type_traits.hpp> #include "types_container.hpp" namespace { namespace mi = boost::multi_index; namespace tt = utils::type_traits; } /* Пример использования котейнера: struct Struct { std::string name; size_t number; struct ByName{}; struct ByNumber{}; using Tags = std::tuple<Struct::ByName, Struct::ByNumber>;____________required using PtrsToMembers = std::tuple<&Struct::name, &Struct::number>;________required }; MultiIndexContainer<Struct, std::tuple<Struct>> container{}; container.emplace(MyStruct{"name", 123}); container.emplace(MyStruct{"name_1", 123}); const auto &list = container.get<MyStruct::ByName>(); for (const auto &element : list) { std::cout << element.name << std::endl; std::cout << element.number << std::endl; } */ namespace utils { namespace containers { namespace { template < typename Structure, typename MemberType> auto GetStructureOfPointer(MemberType Structure::*) -> Structure; template <auto PtrToMember> using StructureOfPointe = decltype(GetStructureOfPointer(PtrToMember)); template < typename Structure, typename MemberType> auto GetMemberTypeOfPointer(MemberType (Structure::*)() const) -> MemberType; template < typename Structure, typename MemberType> auto GetMemberTypeOfPointer(MemberType Structure::*) -> MemberType; template <auto PtrToMember> using MemberTypeOfPointer = decltype(GetMemberTypeOfPointer(PtrToMember)); } // namespace //________________________________________________________________________________ namespace { template <auto PtrToMember, typename Structure = StructureOfPointe<PtrToMember>, typename Type = MemberTypeOfPointer<PtrToMember>> auto GetBoostMemberConstructor() -> mi::const_mem_fun<Structure, Type, PtrToMember>; template <auto PtrToMember, typename Structure = StructureOfPointe<PtrToMember>, typename Type = MemberTypeOfPointer<PtrToMember>> auto GetBoostMemberConstructor() -> mi::member<Structure, Type, PtrToMember>; /*1.0 С помощью данного шаблона мы можем получить класс member, передав ему лишь указатель на член структуры(класса) Structure - произвольная(ый) структура(класс) Type - тип члена PtrToMember - указатели на данный член */ template <auto PtrToMember> using BoostMember = decltype(GetBoostMemberConstructor<PtrToMember>()); //1.1 С помощью данного шаблона мы можем получить класс tag template <typename Tag> using BoostTag = mi::tag<Tag>; } // namespace //________________________________________________________________________________ namespace { template < bool Unique = true, template <typename... Tags> typename TagsContainer, typename... Tags, template <auto... PtrsToMembers> typename PtrsToMembersContainer, auto... PtrsToMembers> auto IndexConstructorForOneStructure(TagsContainer<Tags...>, PtrsToMembersContainer<PtrsToMembers...>) { if constexpr (Unique) return std::tuple<mi::ordered_unique<BoostTag<Tags>, BoostMember<PtrsToMembers>>...>{}; else return std::tuple<mi::ordered_non_unique<BoostTag<Tags>, BoostMember<PtrsToMembers>>...>{}; } /*2. С помощью данного шаблона мы можем получить множество классов ordered_unique для одной структуры TagsContainer - совокупность тэгов Tags - сами тэги(пакет) PtrsToMembersContainer - контейнер указателей на методы PtrsToMembers - сами указатели */ template <typename Structure, typename Tags = typename Structure::Tags, typename PtrsToMembers = typename Structure::PtrsToMembers> struct StructureUniqueProperies{ using TagsContainer = Tags; using PtrsToMembersContainer = PtrsToMembers; }; template <typename Structure> struct StructureUniqueProperies<Structure,std::tuple<>,std::tuple<>>{}; template <typename Structure, typename TagsContainer = typename StructureUniqueProperies<Structure>::TagsContainer, typename PtrsToMembersContainer = typename StructureUniqueProperies<Structure>::PtrsToMembersContainer> using IndexiesForOneStructure = decltype(IndexConstructorForOneStructure(TagsContainer{}, PtrsToMembersContainer{})); } // namespace //________________________________________________________________________________ namespace { template < template <typename... Structures> typename StructuresContainer, typename... Structures> auto IndexConstructorForManyStructure(const StructuresContainer<Structures...> &) -> tt::TupleCat<IndexiesForOneStructure<Structures>...>; /*4. С помощью данного шаблона мы можем получить множество классов ordered_unique для множества структур StructuresContainer - совокупность структур Structures - структуры(пакет типов) */ template <typename StructuresContainer> using IndexiesForManyStructures = decltype(IndexConstructorForManyStructure(StructuresContainer{})); } // namespace //________________________________________________________________________________ namespace { template < template <typename... Indexies> typename IndexiesContainer, typename... Indexies> auto IndexiesByConstructor(const IndexiesContainer<Indexies...> &) -> mi::indexed_by<Indexies...>; /*5. С помощью данного шаблона мы можем получить множество классов index_by UniqueIndexiesContainer - совокупность индексов */ template <typename IndexiesContainer> using IndexiesBy = decltype(IndexiesByConstructor(IndexiesContainer{})); } // namespace //________________________________________________________________________________ namespace { template < typename BaseStructure, template <typename... Structures> typename StructuresContainer, typename... Structures > auto MultiIndexConstructorFromStructures (BaseStructure, StructuresContainer<Structures...>) -> boost::multi_index_container<BaseStructure, IndexiesBy< IndexiesForManyStructures< StructuresContainer<Structures...>>>>; } // namespace /*5. С помощью данного шаблона мы можем получить класс boost::multi_index_container, основываясь лишь на базовой структуре и её методах */ template < typename BaseStructure, typename DerivedStructure = BaseStructure, typename StructuresContainer = TypesContainer<DerivedStructure>> using MultiIndexContainer = decltype(MultiIndexConstructorFromStructures(std::declval<BaseStructure>(), StructuresContainer{})); } // namespace containers } // namespace utils
true
8eb8f53439f69f5151eba0d18aee33928c068268
C++
mdqyy/hpm
/src/hpm/hpmatch.cpp
UTF-8
10,860
2.53125
3
[]
no_license
#include <hpm/hpmatch.hpp> using namespace std; using namespace cv; namespace hpm { template<> const unsigned int feat::oob = -1; //--------------------------------------------------------------------------- // main HPM entry point when feature labels (visual words) are known // (cv style) double HPMatcher::match(const vector<KeyPoint>& points1, const vector<size_t>& lab1, const vector<KeyPoint>& points2, // features [x y scale rotation] const vector<size_t>& lab2, // labels (visual words) vector<vector<DMatch> >& matches, // tentative correspondences vector<double>& strengths, // correspondence strengths vector<bool>& erased, // erased correspondences vector<bool>& out_of_bounds) // out of bound transformations { vector<vector<size_t> > cor; double sim = match(feat::key2featv(points1), lab1, feat::key2featv(points2), lab2, cor, strengths, erased, out_of_bounds); matches = corr::cor2match(cor); return sim; } //--------------------------------------------------------------------------- // main HPM entry point when correspondences are known (cv style) double HPMatcher::match(const vector<KeyPoint>& points1, const vector<KeyPoint>& points2, // features [x y scale rotation] const vector<vector<DMatch> >& matches, // tentative correspondences vector<double>& strengths, // correspondence strengths vector<bool>& erased, // erased correspondences vector<bool>& out_of_bounds) // out of bound transformations { return match(feat::key2featv(points1), feat::key2featv(points2), corr::match2corv(matches), strengths, erased, out_of_bounds); } //--------------------------------------------------------------------------- // main HPM entry point when feature labels (visual words) are known, // but not correspondences. just find correspondences and call inner HPM. double HPMatcher::match(const vector<feat>& feat1, const vector<size_t>& lab1, const vector<feat>& feat2, // features [x y scale rotation] const vector<size_t>& lab2, // labels (visual words) vector<vector<size_t> >& cor, // tentative correspondences vector<double>& strengths, // correspondence strengths vector<bool>& erased, // erased correspondences vector<bool>& out_of_bounds) // out of bound transformations { // find correspondences from labels cor = corr::lab2cor(lab1, lab2); // call inner HPM, giving both labels and correspondences return hpm(feat1, lab1, feat2, lab2, cor, strengths, erased, out_of_bounds); // test/debug: conversely, find labels again from correspondences //return hpm(feat1, feat2, cor, strengths, erased, out_of_bounds); } //--------------------------------------------------------------------------- // main HPM entry point when correspondences are known, but not // feature labels (visual words). just find labels and call inner HPM. double HPMatcher::match(const vector<feat>& feat1, const vector<feat>& feat2, // features [x y scale rotation] const vector<vector<size_t> >& cor, // tentative correspondences vector<double>& strengths, // correspondence strengths vector<bool>& erased, // erased correspondences vector<bool>& out_of_bounds) // out of bound transformations { // find components (labels / visual words) from correspondences vector<size_t> lab1, lab2; corr::cor2lab(cor, lab1, lab2); // call inner HPM, giving both labels and correspondences return hpm(feat1, lab1, feat2, lab2, cor, strengths, erased, out_of_bounds); } //--------------------------------------------------------------------------- // inner HPM call when both labels and correspondences are known. // given two input vectors of features and corresponding vectors of labels // (visual words) and correspondences, quantize relative transformations, // call recursive HPM, and return correspondences, strengths, and vectors // of correspondences that are erased or out of (transformation space) // bounds. double HPMatcher::hpm(const vector<feat>& feat1, const vector<size_t>& lab1, const vector<feat>& feat2, // features [x y scale rotation] const vector<size_t>& lab2, // labels (visual words) const vector<vector<size_t> >& cor, // tentative correspondences vector<double>& strengths, // correspondence strengths vector<bool>& erased, // erased correspondences vector<bool>& out_of_bounds) // out of bound transformations { // align features based on tentative correspondences vector<feat> af1, af2; corr::align(feat1, feat2, cor, af1, af2); // at least two correspondences needed to match the images if(!af1.size()) return 0.0; // align correspondence labels (visual words) vector<size_t> lab; corr::align(lab1, lab2, cor, lab, lab); // relative transformations vector<feat> tran = feat::rel_tran(af1, af2); // quantized transformations within bounds vector<size_t> kept; vector<unsigned int> qtran = feat::quant(tran, kept, rt, rs, rr, z); // number of correspondence transformations kept size_t C = qtran.size(); vector<vector<size_t> > g(C); // group count of each correspondence at each level vector<float> s(C, 0.0); // correspondence strengths vector<bool> X(C, false); // erased correspondences vector<vector<vector<size_t> > > sib(L); // sibling groups at each level // initialize groups for(size_t i=0; i<g.size(); i++) g[i].resize(L, 0); // recursive HPM call vector<size_t> rng; for(size_t i=0;i<C;i++) rng.push_back(i); if(C) hpm_rec(0, qtran, lab, rng, g, s, X, sib); // update group count of correspondences in same bin with erased ones // "undoing" contribution of correspondences that are eventually erased for(size_t l=0; l<L; l++) for(size_t i=0, x; x = 0, i<sib[l].size(); i++) { const vector<size_t>& si = sib[l][i]; for(size_t j=0; j<si.size(); j++) if(X[si[j]]) x++; for(size_t j=0; j<si.size(); j++) if(!X[si[j]]) g[si[j]][l] -= x; } // correspondence strengths; erased ones have zero strength strengths.resize(af1.size(), 0.0); for(size_t i=0; i<C; i++) if(!X[i]) for(size_t l=0; l<L && g[i][l] > 0; l++) strengths[kept[i]] += g[i][l] << (l ? (l-1) : 0); // weigh strengths by idf if(idf.size()) for(size_t i=0;i<kept.size();i++) strengths[kept[i]] *= idf[lab[kept[i]]]; // positions of erased correspondences erased.resize(tran.size(), false); for(size_t i=0;i<X.size();i++) if(X[i]) erased[kept[i]] = true; // positions of correspondences out of bounds out_of_bounds.resize(tran.size(), true); for(size_t i=0;i<kept.size();i++) out_of_bounds[kept[i]] = false; double sm = 0.0; for(size_t i=0;i<strengths.size();i++) sm+= strengths[i]; // similarity score return sm; } //----------------------------------------------------------------------------- // recursive part of HPM. given current level, encoded correspondence // transformations, their visual words and positions in initial vector, // call HPM recursively to quantize and group correspondences at all levels // below, then update their group count, strengths, and vector of erased // correspondences. also update "sibling" groups to be used in "undoing" // strength contributions from correspondences that are eventually erased. // level l starts from 0 and increases through recursion down the pyramid. // l = 0 corresponds to the top, coarsest level, with only one bin. // l = L-1 corresponds to the bottom, finest level. void HPMatcher::hpm_rec(const size_t l, // current level in pyramid const vector<unsigned int>& qtran, // encoded correspondence transformations const vector<size_t>& lab, // label (visual word) of each correspondence const vector<size_t>& index, // current subset of correspondences vector<vector<size_t> >& g, // group count of each correspondence at each level vector<float>& s, // correspondence strengths vector<bool>& X, // erased correspondences vector<vector<vector<size_t> > >& sib) // sibling groups at each level { // groups of correspondences in each bin, and their count vector<vector<size_t> > bins; vector<size_t> bc; // quantize transformations at current level and group them in bins unique_count(feat::quant(qtran, z, L-1-l), bc, bins); // if not at bottom, recursively call hpm on bins with more than one correspondence if(l < L-1) for(size_t i=0; i<bins.size(); i++) if(bc[i] > 1) { const vector<size_t>& b = bins[i]; vector<unsigned int> qtrant; vector<size_t> labt; vector<size_t> indext; for(size_t i=0;i<b.size();i++) { qtrant.push_back(qtran[b[i]]); labt.push_back(lab[b[i]]); indext.push_back(index[b[i]]); } hpm_rec(l+1, qtrant, labt, indext, g, s, X, sib); } // loop over bins with more than one correspondence for(size_t i=0; i<bins.size(); i++) if(bc[i] > 1) { const vector<size_t>&b = bins[i]; // group of current bin vector<size_t> labt; for(size_t i=0;i<b.size();i++) labt.push_back(lab[b[i]]); // conflict groups in current bin, and their count vector<vector<size_t> > conflicts; vector<size_t> cc; // unique visual words in current bin //vector<size_t> ulab = unique_count(lab[b], cc, conflicts); vector<size_t> ulab = unique_count(labt, cc, conflicts); // there is exactly one representative correspondence for each // unique visual word if(ulab.size() < 2) continue; // update correspondence group counts and strengths, unless erased for(size_t j=0, cj; j<b.size(); j++) if(!X[cj = index[b[j]]]) s[cj] += (g[cj][l] = ulab.size()-1) << (l ? (l-1) : 0); // siblings in current bin sib[l].push_back(vector<size_t>()); vector<size_t>& si = sib[l].back(); // loop over unique visual words in current bin for(size_t u=0; u<cc.size(); u++) { // keep position of strongest correspondence in conflict group //vector<float> wgs = s[index[ b[conflicts[u]] ]]; vector<float> wgs; for(size_t k=0;k<conflicts[u].size();k++) wgs.push_back(s[index[b[conflicts[u][k]]]]); //size_t strong = find(wgs == max(wgs))[0]; size_t strong = 0; for(size_t k=0;k<wgs.size();k++) if(wgs[strong]<wgs[k]) strong = k; si.push_back(index[ b[conflicts[u][strong]] ]); // erase all other correspondences for(size_t k=0; k<cc[u]; k++) if(k != strong) X[index[ b[conflicts[u][k]] ]] = true; } } } } // namespace hpm
true
9960b8b14095e78c4d6af54a47a0dbc5daa3e767
C++
BorduzRazvan/IEP_2017-2018
/Server/IEP_SERVER_APP/pin.h
UTF-8
1,011
2.875
3
[]
no_license
#ifndef PIN_H #define PIN_H #define OFF_VALUE 0u #define ON_VALUE 1u class Pin { public: Pin(int pin); Pin(int pin, int dir); Pin(int pin, int dir, int pull_up); void set(int Option); int getValue(void); void changeDir(int new_Dir); void set_eds(void); int get_eds(void); void enable_Low(void); private: int pin_nr; int pull_up; // 0- no, 1- yes int direction; /** Enum for Direction Values BCM2835_GPIO_FSEL_INPT -> Input 0b000 BCM2835_GPIO_FSEL_OUTP -> Output 0b001 BCM2835_GPIO_FSEL_ALT0 -> Alternate function 0 0b100 BCM2835_GPIO_FSEL_ALT1 -> Alternate function 1 0b101 BCM2835_GPIO_FSEL_ALT2 -> Alternate function 2 0b110, BCM2835_GPIO_FSEL_ALT3 -> Alternate function 3 0b111 BCM2835_GPIO_FSEL_ALT4 -> Alternate function 4 0b011 BCM2835_GPIO_FSEL_ALT5 -> Alternate function 5 0b010 BCM2835_GPIO_FSEL_MASK -> Function select bits mask 0b111 */ }; #endif // PIN_H
true
00538294535c5b05a374bb2e167ab18e1f1a4a08
C++
ericoloewe/computer-science
/aulas/sistemas-embarcados/praticas/pir/pir.ino
UTF-8
717
2.84375
3
[]
no_license
int motionSensorPort = 27; void setup() { // put your setup code here, to run once: Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } establishContact(); attachInterrupt(digitalPinToInterrupt(motionSensorPort), detectsMovement, RISING); } void loop() { Serial.print("VALOR ATUAL: "); Serial.print(digitalRead(motionSensorPort)); Serial.print("\n"); delay(1000); } void establishContact() { int count = 0; while (Serial.available() <= 0) { Serial.print("Carregando "); Serial.print(count++); Serial.print("\n"); delay(300); } } void detectsMovement() { Serial.println("Movimento detectado!!!"); }
true
67cb3c1faf4adb1bf027aa766ff7cace76fd3d16
C++
rickflaget/bpy
/grammartypes.cpp
UTF-8
2,036
2.9375
3
[]
no_license
#include <map> #include <string> using namespace std; typedef enum gtypes {IF, MAIN, PROGRAM, ELSE, WHILE, FOR, VAR, FUNCTION, CLASS, EQUAL, OR, AND, VARIABLE, NUMBER, STRING, COMMENT, ENDofINPUT, OPAREN, CPAREN, COMMA, PLUS, TIMES, MINUS, DIVIDES, LESSTHAN, GREATERTHAN, ASSIGN, SEMICOLON, MOD, EXP, OBRACE, CBRACE, DOT, UNKNOWN, UMINUS, GLUE, BINARY,LIST,STATEMENTS,FUNCTIONCALL,UNARY, OPERATOR,LOGICALOPERATOR,STATEMENT,TABLE,ENV_TYPE ,CLOSURE,BOOLEAN,UNDECLARED,ARRAY,NEWLINE,NEWTAB,ANON,OBRACKET,CBRACKET,ANONCALL,NOT,NIL} GTYPE; const char* printG(int x) { const char *printGTYPES[] = { "IF", "MAIN", "PROGRAM", "ELSE", "WHILE", "FOR", "VAR", "FUNCTION", "CLASS", "EQUAL", "OR", "AND", "VARIABLE", "NUMBER", "STRING", "COMMENT", "ENDofINPUT", "OPAREN", "CPAREN", "COMMA", "PLUS", "TIMES", "MINUS", "DIVIDES", "LESSTHAN", "GREATERTHAN", "ASSIGN", "SEMICOLON", "MOD", "EXP", "OBRACE", "CBRACE", "DOT", "UNKNOWN", "UMINUS", "GLUE", "BINARY", "LIST", "STATEMENTS", "FUNCTIONCALL", "UNARY", "OPERATOR", "LOGICALOPERATOR", "STATEMENT", "TABLE", "ENV_TYPE", "CLOSURE", "BOOLEAN", "UNDECLARED", "ARRAY", "NEWLINE", "NEWTAB", "ANON", "OBRACKET", "CBRACKET", "ANONCALL", "NOT", "NIL" }; return printGTYPES[x]; } const char* printINPUT(int x) { const char *printGTYPES[] = { "if", "main", "program", "else", "while", "for", "var", "function", "class", "eq", "or", "and", "VARIABLE", "NUMBER", "STRING", "~", "ENDofINPUT", "OPAREN", "CPAREN", ",", " + ", " * ", " - ", " / ", " < ", " > ", " = ", " ; ", " % ", " ^ ", " OBRACE ", " CBRACE ", " . ", " UNKNOWN ", " - ", "GLUE", "BINARY", "LIST", "STATEMENTS", "FUNCTIONCALL", "UNARY", "OPERATOR", "LOGICALOPERATOR", "STATEMENT", "TABLE", "ENV_TYPE", "CLOSURE", "BOOLEAN", "UNDECLARED", "ARRAY", "NEWLINE", "NEWTAB", "ANON", "[", "]", "ANONCALL", "!", "NIL" }; return printGTYPES[x]; }
true
093920e8bca3e084304e644eeea488a3b2bced08
C++
10098/braveball
/game/objects/threat.cpp
UTF-8
557
2.640625
3
[]
no_license
#include "game/objects/threat.h" #include "game/engine.h" namespace game { Threat::Threat(const game::Engine& e, int x, int y): GameObject(x, y, 15, 9), m_movementThr(15), m_anim(e.resourceManager().getAnimationData("meanies/king/king")) { addTag("king"); } void Threat::update(Engine& ctx) { m_anim.update(ctx.clock()); if(m_movementThr(ctx.clock().ticks())) { setX(x() + 1); } } void Threat::draw(graphics::SpriteBatch& b) { b.add(x(), y(), m_anim.frame()); } }
true
39608b3681bdd4a5c7d2c8ad624969b85ac95469
C++
LangdalP/ecs-vs-oo
/utils.h
UTF-8
2,120
2.796875
3
[]
no_license
// // Created by Peder Voldnes Langdal on 20/04/2020. // #ifndef ECS_VS_OO_UTILS_H #define ECS_VS_OO_UTILS_H #include <cstdlib> #include "GameObject.h" #include "Components.h" #include "GameObjectWithPointers.h" float random_float() { auto randomInt = rand(); return (float)randomInt; } Position generate_position() { return Position(random_float(), random_float()); } Position* generate_position_heap() { return new Position(random_float(), random_float()); } AttemptedInputs generate_player_inputs() { return AttemptedInputs(random_float(), random_float(), random_float(), random_float()); } AttemptedInputs* generate_player_inputs_heap() { return new AttemptedInputs(random_float(), random_float(), random_float(), random_float()); } GameObject generate_game_object() { return GameObject(generate_position(), generate_player_inputs()); } GameObjectWithPointers generate_game_object_with_pointers() { return GameObjectWithPointers(generate_position_heap(), generate_player_inputs_heap()); } std::vector<GameObjectWithPointers> generate_game_objects_with_pointers(int num_objects) { auto game_objects = std::vector<GameObjectWithPointers>(); game_objects.reserve(num_objects); for (int i = 0; i < num_objects; ++i) { game_objects.push_back(generate_game_object_with_pointers()); } return game_objects; } std::vector<GameObject> generate_game_objects(int num_objects) { auto game_objects = std::vector<GameObject>(); game_objects.reserve(num_objects); for (int i = 0; i < num_objects; ++i) { game_objects.push_back(generate_game_object()); } return game_objects; } Components generate_components(int num_objects) { auto positions = std::vector<Position>(); positions.reserve(num_objects); auto playerInputs = std::vector<AttemptedInputs>(); playerInputs.reserve(num_objects); for (int i = 0; i < num_objects; ++i) { positions.push_back(generate_position()); playerInputs.push_back(generate_player_inputs()); } return Components(positions, playerInputs); } #endif //ECS_VS_OO_UTILS_H
true
93761c4e07c485acde802574a321cf43c48aa3e7
C++
idaohang/QML-GPSKoordinaten
/pointmodel.h
UTF-8
699
2.640625
3
[]
no_license
#ifndef POINTMODEL_H #define POINTMODEL_H #include <QAbstractListModel> #include <QList> #include "point.h" class PointModel : public QAbstractListModel { Q_OBJECT public: explicit PointModel(QObject *parent = 0); int rowCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; Point &last() {return points.last();} Point &first() {return points.first();} void setFormat(Point::GPSFormat format) { this->format = format; } signals: public slots: void addPoint(const Point &point); private: QList<Point> points; Point::GPSFormat format; }; #endif // POINTMODEL_H
true
a1ad3c38626a5bbf7a87a0f9bb925fa2be58bbeb
C++
frchaban/CPP-42
/5_day_CPP/ex02/Form.hpp
UTF-8
1,473
3.09375
3
[]
no_license
#ifndef FORM_HPP # define FORM_HPP # include <string> # include <iostream> # include "Bureaucrat.hpp" class Bureaucrat; class Form; class Form { public: Form(std::string const &name, unsigned int const signed_grade, unsigned int const exec, std::string target); Form(Form const &other); Form& operator=(Form const &other); virtual ~Form(); std::string getName() const; bool getSignedStatus() const; unsigned int getSignedGrade() const; unsigned int getExecGrade() const; std::string getTarget() const; virtual void beSigned(Bureaucrat &bureaucrat); virtual void execute(Bureaucrat const &executor) const = 0; class GradeTooHighException : public std::exception { public : GradeTooHighException() throw() {} virtual ~GradeTooHighException() throw() {} virtual const char* what() const throw(); }; class GradeTooLowException : public std::exception { public : GradeTooLowException() throw() {} virtual ~GradeTooLowException() throw() {} virtual const char* what() const throw(); }; class NotSignedException : public std::exception { public : NotSignedException() throw() {} virtual ~NotSignedException() throw() {} virtual const char* what() const throw(); }; private: std::string const _Name; bool _Signed; unsigned int const _Signed_Grade; unsigned int const _Exec_Grade; std::string _Target; }; std::ostream& operator<<(std::ostream &out, Form &form); #endif
true
319d432d0c99bbc0025f09441098162fd75e1b50
C++
HaoLi-China/Mobility-Reconstruction
/geom/map_copier.cpp
UTF-8
4,703
2.609375
3
[]
no_license
#include "map_copier.h" #include "map_builder.h" MapCopier::MapCopier() { copy_all_attributes_ = false ; current_source_ = nil ; current_destination_ = nil ; // By default: copy vertex locks declare_vertex_attribute_to_copy("lock") ; } MapCopier::~MapCopier() { } void MapCopier::copy( MapBuilder& builder, MapComponent* component, MapVertexAttribute<int>& vertex_id, MapTexVertexAttribute<int>& tex_vertex_id, int& cur_vertex_id, int& cur_tex_vertex_id ) { bind_attribute_copiers(builder.target(), component->map()) ; // Step 1 : clear vertex and tex vertex ids FOR_EACH_VERTEX(MapComponent, component, it) { vertex_id[it] = -1 ; } FOR_EACH_HALFEDGE(MapComponent, component, it) { tex_vertex_id[it->tex_vertex()] = -1 ; } // Step 2: enumerate vertices FOR_EACH_VERTEX(MapComponent, component, it) { vertex_id[it] = cur_vertex_id ; builder.add_vertex(it->point()) ; copy_vertex_attributes(builder.current_vertex(), it) ; cur_vertex_id++ ; } // Step 3: enumerate tex vertices FOR_EACH_HALFEDGE(MapComponent, component, it) { if(tex_vertex_id[it->tex_vertex()] == -1) { tex_vertex_id[it->tex_vertex()] = cur_tex_vertex_id ; builder.add_tex_vertex(it->tex_vertex()->tex_coord()) ; copy_tex_vertex_attributes(builder.current_tex_vertex(), it->tex_vertex()) ; cur_tex_vertex_id++ ; } } // Step 4: create facets FOR_EACH_FACET(MapComponent, component, it) { Map::Halfedge* h = it->halfedge() ; builder.begin_facet() ; do { builder.add_vertex_to_facet(vertex_id[h->vertex()]) ; builder.set_corner_tex_vertex(tex_vertex_id[h->tex_vertex()]) ; h = h->next() ; } while(h != it->halfedge()) ; builder.end_facet() ; copy_facet_attributes(builder.current_facet(), it) ; } // TODO: copy halfedge attributes } void MapCopier::copy( MapBuilder& builder, Map* source, MapVertexAttribute<int>& vertex_id, MapTexVertexAttribute<int>& tex_vertex_id, int& cur_vertex_id, int& cur_tex_vertex_id ) { bind_attribute_copiers(builder.target(), source) ; // Step 1 : clear vertex and tex vertex ids FOR_EACH_VERTEX(Map, source, it) { vertex_id[it] = -1 ; } FOR_EACH_HALFEDGE(Map, source, it) { tex_vertex_id[it->tex_vertex()] = -1 ; } // Step 2: enumerate vertices FOR_EACH_VERTEX(Map, source, it) { vertex_id[it] = cur_vertex_id ; builder.add_vertex(it->point()) ; copy_vertex_attributes(builder.current_vertex(), it) ; cur_vertex_id++ ; } // Step 3: enumerate tex vertices FOR_EACH_HALFEDGE(Map, source, it) { if(tex_vertex_id[it->tex_vertex()] == -1) { tex_vertex_id[it->tex_vertex()] = cur_tex_vertex_id ; builder.add_tex_vertex(it->tex_vertex()->tex_coord()) ; copy_tex_vertex_attributes(builder.current_tex_vertex(), it->tex_vertex()) ; cur_tex_vertex_id++ ; } } // Step 4: create facets FOR_EACH_FACET(Map, source, it) { Map::Halfedge* h = it->halfedge() ; builder.begin_facet() ; do { builder.add_vertex_to_facet(vertex_id[h->vertex()]) ; builder.set_corner_tex_vertex(tex_vertex_id[h->tex_vertex()]) ; h = h->next() ; } while(h != it->halfedge()) ; builder.end_facet() ; copy_facet_attributes(builder.current_facet(), it) ; // TODO: copy halfedge attributes } } template <class RECORD> inline void bind_attribute_copiers( std::vector< AttributeCopier<RECORD> >& copiers, AttributeManager* to, AttributeManager* from, const std::set<std::string>& attributes_to_copy, bool copy_all_attributes ) { copiers.clear() ; std::vector<std::string> names ; from->list_named_attributes(names) ; for(unsigned int i=0; i<names.size(); i++) { if(copy_all_attributes || (attributes_to_copy.find(names[i]) != attributes_to_copy.end())) { bind_source(copiers, from, names[i]) ; } } bind_destinations(copiers, to) ; } void MapCopier::bind_attribute_copiers(Map* destination, Map* source) { ::bind_attribute_copiers( vertex_attribute_copiers_, destination->vertex_attribute_manager(), source->vertex_attribute_manager(), vertex_attributes_to_copy_, copy_all_attributes_ ) ; ::bind_attribute_copiers( tex_vertex_attribute_copiers_, destination->tex_vertex_attribute_manager(), source->tex_vertex_attribute_manager(), tex_vertex_attributes_to_copy_, copy_all_attributes_ ) ; ::bind_attribute_copiers( halfedge_attribute_copiers_, destination->halfedge_attribute_manager(), source->halfedge_attribute_manager(), halfedge_attributes_to_copy_, copy_all_attributes_ ) ; ::bind_attribute_copiers( facet_attribute_copiers_, destination->facet_attribute_manager(), source->facet_attribute_manager(), facet_attributes_to_copy_, copy_all_attributes_ ) ; }
true
7d5b37cead1eabde5b3249142d9a8a714e91e5f5
C++
refiute/special_study
/genetic_algorithm_template.cpp
UTF-8
3,388
3.140625
3
[]
no_license
#include <boost/random.hpp> #include <boost/dynamic_bitset.hpp> using namespace std; boost::random::mt19937 gen; class Gene{ public: boost::dynamic_bitset<> chromosome; int fitness; Gene(int l){ boost::random::uniform_int_distribution<> dist(0, 1); chromosome.resize(l); for(int i=0;i<chromosome.size();i++){ chromosome[i] = (bool)dist(gen); } } bool operator<(const Gene &g)const{ return this->fitness > g.fitness; } // 突然変異 void mutate(double per){ int range = 100; while(per - (int)per > 1e-7){ range *= 10; per *= 10; } boost::random::uniform_int_distribution<> dist(0, range); for(int i=0;i<chromosome.size();i++) if(per <= dist(gen)) chromosome.flip(i); } // choromosomeをstringに string to_string(){ string str; boost::to_string(chromosome, str); return str; } }; // 初期集団生成 void init_population(){ int population_size,gene_size; // cout << "Population Size: "; cin >> population_size; // cout << "Gene Size: "; cin >> gene_size; for(int i=0;i<population_size;i++){ population.push_back(Gene(gene_size)); } } // 遺伝子評価 void evaluate_gene(Gene* g){ } // 世代評価 void evaluate_population(){ for(int i=0;i<population.size();i++){ evaluate_gene(&population[i]); } sort(population.begin(), population.end()); if(best_fitness < population[0].fitness){ best_fitness = population[0].fitness; cout << "result: generation=" << generation << " fitness=" << best_fitness << " " << time(NULL)-start << "s" << endl; cout << '\a'; //cout << " gene: " << population[0].chromosome << endl; } } // 2点交叉 void two_point_crossover(vector<Gene>* next_population, Gene a, Gene b){ boost::random::uniform_int_distribution<> dist(0, a.chromosome.size()-1); int end = dist(gen); for(int i=dist(gen);i<end;i++){ if(a.chromosome[i] != b.chromosome[i]){ a.chromosome.flip(i); b.chromosome.flip(i); } } next_population->push_back(a); next_population->push_back(b); } // 次世代生成 void generate_population(){ vector<Gene> next_population; next_population.push_back(population[0]); vector<int> sum_fitness(population.size()); sum_fitness[0] = population[0].fitness; for(int i=1;i<population.size();i++) sum_fitness[i] = population[i].fitness + sum_fitness[i-1]; cout << sum_fitness[population.size()-1] << endl; boost::random::uniform_int_distribution<> dist(0, sum_fitness[population.size()-1]); while(next_population.size() < population.size()){ int apos = (int)(lower_bound(sum_fitness.begin(), sum_fitness.end(), dist(gen))-sum_fitness.begin()); int bpos = (int)(lower_bound(sum_fitness.begin(), sum_fitness.end(), dist(gen))-sum_fitness.begin()); two_point_crossover(&next_population, population[apos], population[bpos]); } population = next_population; } // 集団の特別変異 void mutate_population(double per){ for(int i=0;i<population.size();i++) population[i].mutate(per); } int main(){ gen.seed((unsigned)time(NULL)); start = time(NULL); init_population(); //初期集団生成 double mutate_probaility; cin >> mutate_probaility; //突然変異率 cout << "init done!" << endl; while(true){ if(time(NULL)-start > 300)break; // 300sで打ち切り evaluate_population(); //世代評価 generate_population(); //次世代生成 mutate_population(mutate_probaility); //突然変異 generation++; } }
true
1be5ba6b57d0ef1b95aed00c347a4fe26e0fad95
C++
andrewhannebrink/C---Command-Line-Poker
/lab5332.cpp
UTF-8
907
2.578125
3
[]
no_license
//Andrew Hannebrink (408421) //ahannebrink@wustl.edu //This is the main function, it makes sure the user puts in the right input and then repeated calls before_round, round, and //after_round until there are no players left in the game #include "stdafx.h" #include "rwfuncs.h" #include "deck.h" #include <iostream> #include <string> #include "player.h" #include "game.h" #include "fivecarddraw.h" using namespace std; enum FailState {success, uMes, fileNotOpened, emptyCardVector, unknownErr}; int main(int argc, char* argv[]) { if (argc < 3) { usageMessage(); return uMes; } try { Game::start_game(argv[1]); for (int i = 2; i < argc; i++) { Game::instance()->add_player(argv[i]); } while (true){ Game::instance()->before_round(); Game::instance()->round(); Game::instance()->after_round(); } } catch (errorStates & e) { return e; } return 0; }
true
5efa9f9134474a6f961e04b899c1990614d8f84a
C++
filipedgb/Myriades
/Rectangle.cpp
UTF-8
542
2.953125
3
[]
no_license
#include "Rectangle.h" Rectangle::Rectangle(float x1, float y1, float x2, float y2){ this->x1 = x1; this->x2 = x2; this->y1 = y1; this->y2 = y2; } void Rectangle::draw(float text_s, float text_l) { glNormal3d(0,0,1); glBegin(GL_QUADS); glTexCoord2d(0,0); glVertex3d(x1,y1,0); glTexCoord2d(abs(x2-x1)/text_s,0); glVertex3d(x2,y1,0); glTexCoord2d(abs(x2-x1)/text_s,abs(y2-y1)/text_l); glVertex3d(x2,y2,0); glTexCoord2d(0,abs(y2-y1)/text_l); glVertex3d(x1,y2,0); glEnd(); }
true
89d799a1995845e28877cc7d0f1507f0fd2cd432
C++
ialhashim/extend-mesh
/GraphicsLibrary/Slicer.h
UTF-8
934
2.546875
3
[]
no_license
#ifndef SLICER_H #define SLICER_H #include "Mesh.h" #include "Plane.h" #include "HashTable.h" struct SliceResult { StdSet<Face*> cutFaces, removeFaces, keepFaces; IntSet cutPoints; IntSet newPoints; EdgeSet cutEdges; SliceResult(StdSet<Face*>& faces, IntSet& points, IntSet& new_points, EdgeSet& edges, StdSet<Face*>& RemoveFaces, StdSet<Face*>& KeepFaces) { cutPoints = points; newPoints = new_points; cutFaces = faces; cutEdges = edges; removeFaces = RemoveFaces; keepFaces = KeepFaces; } SliceResult(){} }; class Slicer { private: public: static void FindSliceStrip(Mesh * mesh, Vector<int> & facesIndices, const Plane& cutPlane, StdSet<int> & cutPoints, IntSet & cutPointsTable, IntSet & cutFaces, EdgeSet & cutEdges); static SliceResult SliceAt(Mesh * mesh, Vector<int> & facesIndices, const Plane& cutPlane); }; #endif // SLICER_H
true
fb26b3119f75d1b7dab170b4296cf448051c0f2c
C++
haspeleo/Algorithms-implementation
/BINPACKING/main.cpp
UTF-8
2,712
3.375
3
[]
no_license
/* * http://www2.algorithm.cs.sunysb.edu/mediawiki/index.php/Introduction-TADM2E //wiki for book Skiena * a better way to do this is to use intefaces * for diffrenting picking policies */ #include <cstdlib> #include <vector> #include <iostream> #include <algorithm> #include <fstream> using namespace std; int pickElement(vector<int> v) { int size = v.size(); int index = (rand() % size) + 1; return v[index]; } int partition(vector<int>&v, int p, int r) { int x = v[r]; int j = p - 1; for (int i = p; i < r; i++) { if (x >= v[i]) { //ascending order j = j + 1; int temp = v[j]; v[j] = v[i]; v[i] = temp; } } v[r] = v[j + 1]; v[j + 1] = x; return (j + 1); } void quickSort(vector<int>&v, int start, int stop) { if (stop > start) { int pivot = partition(v, start, stop); //for a better partitionning quickSort(v, start, pivot -1); quickSort(v, pivot + 1, stop); } } vector<int> binPacking(vector<int> elements, int binSize) { vector<int> w; quickSort(elements, 0, elements.size() - 1); for(int i = 0; i < elements.size(); i++) { //int e = pickElement(elements); if( binSize > 0) { binSize = binSize - elements[i]; w.push_back(elements[i]); } } return w; } void printVector(vector<int> v) { for(int i = 0; i < v.size(); i++) { cout <<v[i]<<" "; } cout <<""<<endl; } void permutate() { string myints[] = {"E5", "E3", "F3", "F3", "D2", "C3", "E1", "C3", "D1", "E2"}; cout << "The 3! possible permutations with 3 elements:\n"; sort(myints, myints +9); ofstream SaveFile("permutations.txt"); do { string output ="les combinaisons here"; SaveFile << output; SaveFile.close(); // cout << myints[0] << " " << myints[1] // << " " << myints[2] << " " << myints[3] << " " <<myints[4] // << " " << myints[5] << " " << myints[6] << " " <<myints[7] // << " " << myints[8] << " " << myints[9] <<endl; // << " " << myints[8] << " " << myints[9] << " " <<myints[10]<< endl; } while (next_permutation(myints, myints + 9)); } int main(int argc, char** argv) { int BIN_SIZE = 6; vector<int> set ; //= {1, 2, 5, 9, 10}; set.push_back(2); set.push_back(1); set.push_back(9); set.push_back(5); set.push_back(10); permutate(); printVector(set); vector<int> choice = binPacking(set, BIN_SIZE); printVector(choice); return 0; }
true
42b97d437d237bf036e3346e5cc79a3fef867dc1
C++
JarneBeaufays/2DAE01_Engine_Beaufays_Jarne
/Minigin/SceneObject.h
UTF-8
545
2.75
3
[]
no_license
#pragma once namespace dae { class SceneObject { public: virtual void Delete() { m_Delete = true; } virtual void Update() = 0; virtual void Render() const = 0; virtual bool GetDelete() const { return m_Delete; } SceneObject() = default; virtual ~SceneObject() = default; SceneObject(const SceneObject& other) = delete; SceneObject(SceneObject&& other) = delete; SceneObject& operator=(const SceneObject& other) = delete; SceneObject& operator=(SceneObject&& other) = delete; private: bool m_Delete{ false }; }; }
true
3f0f3f811e90822720902c34c8784370fafc49a6
C++
RDLLab/tapir
/src/solver/changes/HistoryCorrector.hpp
UTF-8
2,663
3.015625
3
[]
no_license
/** @file HistoryCorrector.hpp * * Defines an abstract base class for correcting history sequences. */ #ifndef SOLVER_HISTORYCORRECTOR_HPP_ #define SOLVER_HISTORYCORRECTOR_HPP_ #include <unordered_set> #include "global.hpp" #include "solver/Solver.hpp" namespace solver { class HistorySequence; class Model; /** An abstract base class for correcting history sequences that have been affected by changes. * * The core virtual method is reviseSequence(), which should modify the given history sequence * in-place. * * This class also allows for distinct handling of history sequences in batches - the default * reviseHistories() simply calls reviseSequence() on each individual sequence, but it can be * overridden for a different approach. */ class HistoryCorrector { public: /** Constructs a new HistoryCorrector, which will be associated with the given Solver. */ HistoryCorrector(Solver *solver) : solver_(solver) { } virtual ~HistoryCorrector() = default; _NO_COPY_OR_MOVE(HistoryCorrector); /** Revises all of the history sequences in the given set. * * Any sequences left in the set after this method finishes are considered incomplete, and will * be continued via the solver's default search algorithm. * * By default this method simply calls reviseSequence() on each sequence, but it can be * overridden to take a custom approach to dealing with all of the sequences. */ virtual void reviseHistories( std::unordered_set<HistorySequence *> &affectedSequences) { for (auto it = affectedSequences. begin(); it != affectedSequences.end(); ) { HistorySequence *sequence = *it; if (reviseSequence(sequence)) { // Successful revision => remove it from the set. it = affectedSequences.erase(it); } else { // Search required => leave it in the set. it++; } } } /** Revises the given sequence, and returns true if the revision was fully successful. * * Incomplete revisions must later be extended by the search algorithm (e.g. UCB) to * avoid having bad sequences in the tree. */ virtual bool reviseSequence(HistorySequence *sequence) = 0; /** Returns the solver used with this corrector. */ virtual Solver *getSolver() const { return solver_; } /** Returns the model used with this corrector. */ virtual Model *getModel() const { return solver_->getModel(); } private: Solver *solver_; }; } /* namespace solver */ #endif /* SOLVER_HISTORYCORRECTOR_HPP_ */
true
dabec0a713362e9a58a78177516abc3f59972b9a
C++
petrkamnev/cf-tasks
/Фокус со стаканчиками/source.cpp
UTF-8
3,930
3
3
[]
no_license
#define _CRT_DISABLE_PERFCRIT_LOCKS #include <iostream> #include <map> #include <vector> #include <algorithm> #include <random> #include <ctime> using namespace std; int INF = 1e9; struct Node { int y, val, size, num; Node *left, *right; Node(int x, int t) { num = t; val = x; y = rand(); size = 1; left = nullptr; right = nullptr; } Node() { if (left) delete left; if (right) delete right; } }; int get_size(Node *root) { if (!root) return 0; return root->size; } int &get_elem(Node *root, int k) { int s1 = get_size(root->left); if (s1 == k) { return root->val; } else if (k < s1) { return get_elem(root->left, k); } else { return get_elem(root->right, k - s1 - 1); } } int get_elem2(Node *root, int k) { int s1 = get_size(root->left); if (s1 == k) { return root->val; } else if (k < s1) { return get_elem(root->left, k); } else { return get_elem(root->right, k - s1 - 1); } } pair<int, int> getelem(Node *root, int k) { int s1 = get_size(root->left); if (s1 == k) { return {root->val, root->num}; } else if (k < s1) { return getelem(root->left, k); } else { return getelem(root->right, k - s1 - 1); } } void update(Node *root) { if (!root) return; root->size = get_size(root->left) + get_size(root->right) + 1; } pair<Node *, Node *> split(Node *root, int key) { if (!root) return {nullptr, nullptr}; int s1 = get_size(root->left); if (s1 >= key) { auto[root1, root2] = split(root->left, key); root->left = root2; update(root); return {root1, root}; } else { auto[root1, root2] = split(root->right, key - s1 - 1); root->right = root1; update(root); return {root, root2}; } } Node *merge(Node *root1, Node *root2) { if (!root1) return root2; if (!root2) return root1; if (root1->y > root2->y) { root1->right = merge(root1->right, root2); update(root1); return root1; } else { root2->left = merge(root1, root2->left); update(root2); return root2; } } Node *pb(Node *root, int x, int i) { Node *t = new Node(x, i); root = merge(root, t); return root; } int next(vector<bool> &mp, int now) { for (int i = now; true; i++) { if (!mp[i]) return i; } } bool comp(pair<int, int> a, pair<int, int> b) { return a.second < b.second; } void print(Node *root, vector<bool> &used, int &now) { cin.sync_with_stdio(false); cout.sync_with_stdio(false); if (!root) return; print(root->left, used, now); if (root->val == INF) { cout << now << " "; now = next(used, now + 1); } else { cout << root->val << " "; } print(root->right, used, now); } int main() { srand(time(0)); #ifdef LOCAL freopen("in.txt", "r", stdin); freopen("out", "w", stdout); #endif int n, m; cin.sync_with_stdio(false); cout.sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m; Node *root = nullptr; for (int i = 0; i < n; i++) { root = pb(root, INF, i); } vector<bool> used(n + 1, 0); vector<pair<int, int>> q; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; q.push_back({a, b}); } reverse(q.begin(), q.end()); for (auto i : q) { auto[a, b] = i; int &x = get_elem(root, 0); if ((x != a && x != INF) || (x == INF && used[a])) { cout << -1; return 0; } x = a; auto[root1, root23] = split(root, 1); auto[root2, root3] = split(root23, b - 1); root = merge(merge(root2, root1), root3); used[a] = 1; } int now = next(used, 1); print(root, used, now); return 0; }
true
c8ed1b01051ca077e25b9b92800d52229323104e
C++
ThomasDetemmerman/gevorderde-algoritmen
/2019-2020/12.2 - labo Suffixtabellen/LGP.h
UTF-8
2,737
2.78125
3
[]
no_license
// // Created by Thomas on 03/12/2019. // #ifndef A___LABO_SUFFIXTABELLEN_LGP_H #define A___LABO_SUFFIXTABELLEN_LGP_H #include <vector> #include <string> #include "saisclass.h" using std::vector; using std::string; using std::ostream; class LGP:public vector<int> { public: LGP(SAIS suffixArray, string data); friend ostream& operator<<(ostream& os, const LGP& dt); private: SAIS sa; string data; void primitieveManier(SAIS suffixArray, string data); void efficienteManier(); //int geefIndexVanopvolger(int i); int getcommonPrefixLenght(string data1, string data2); int getcommonPrefixLenght(int startIndexA, int startIndexB, int startPunt); int opvolger(int i); }; LGP::LGP(SAIS suffixArray, string data_) : data(data_), sa(suffixArray), vector<int>(suffixArray.size(),0) { //primitieveManier(suffixArray, data); efficienteManier(); } //////////////////////////// // efficiente manier // //////////////////////////// // tijdscomplexiteit: O(t) void LGP::efficienteManier() { //todo: werkt niet int k = 0; for (int i = 0; i < size(); i++) { if (opvolger(i) == this->size()-1) { k = 0; continue; } int j = opvolger(i+1); // while (i + k < size() && j + k < size() && data[i+k] == data[j+k]) // k++; k = getcommonPrefixLenght(i,j,k); this->operator[](opvolger(i)) = k; if (k){ k--; } } } // cursus zegt: In SA zoeken we zijn opvolger. Dit //houdt dus in dat we eerst j bepalen met SA[j] = i; int LGP::getcommonPrefixLenght(int i, int j, int k) { while (i + k < size() && j + k < size() && data[i+k] == data[j+k]){ k++; } return k; } int LGP::opvolger(int i) { for (int j = 0; j < this->size(); i++) if(sa[j] == i){ return j; } return -1; } //////////////////////////// // primitieve manier // //////////////////////////// // tijdscomplexiteit: O(t^2) void LGP::primitieveManier(SAIS suffixArray, string data){ if(suffixArray.size() ==0){ return; } if(suffixArray.size() > 1){ for(int i=0; i < this->size()-1; i++){ this->operator[](i) = getcommonPrefixLenght(data.substr(i),data.substr(i+1)); } } } int LGP::getcommonPrefixLenght(string data1, string data2) { int i=0; while(data1[i] == data2[i]){ i++; } return i; } std::ostream& operator<<(std::ostream& os, const LGP& dt) { for (int i = 0; i < dt.size(); ++i) { os << i << "\t"; } os << std::endl; for (int i = 0; i < dt.size(); ++i) { os << dt[i]<< "\t"; } return os; } #endif //A___LABO_SUFFIXTABELLEN_LGP_H
true
f9cb59bcbf5d4e6302863cc9c3ac4644b08caf0a
C++
zshwuhan/graphchi_mf_topn_index
/rtree.hpp
UTF-8
5,511
2.9375
3
[]
no_license
#ifndef __RTREE_H #define __RTREE_H #include <algorithm> #include <cmath> #include <vector> using std::vector; bool sort_items_rtree(std::pair<double, unsigned int> a, std::pair<double, unsigned int> b) { return a.first > b.second; } class RTreeNode { public: RTreeNode() { } ~RTreeNode() { } public: vector<RTreeNode*> _children; vec _lbound; vec _rbound; int _count; vector<int> _tids; }; class RTree { public: RTree() { } ~RTree() { // Release memory for rtree nodes recursive_delete(_root); } private: void recursive_delete(RTreeNode* node) { if (node->_children.size() != 0) { for (unsigned int i = 0; i < node->_children.size(); i++) { recursive_delete(node->_children[i]); } } delete node; } public: void print_rtree() { print_rtree_node(0, _root); } void print_rtree_node(int level, RTreeNode *node) { for (int i = 0; i < level; i++) std::cout << " "; std::cout << node->_count << std::endl; for (int i = 0; i < level; i++) std::cout << " "; for (int i = 0; i < D; i++) std::cout << node->_lbound[i] << " "; std::cout << std::endl; for (int i = 0; i < level; i++) std::cout << " "; for (int i = 0; i < D; i++) std::cout << node->_rbound[i] << " "; std::cout << std::endl; if (node->_tids.size() != 0) { for (unsigned int i = 0; i < node->_tids.size(); i++) std::cout << node->_tids[i] << " "; std::cout << std::endl; } if (node->_children.size() != 0) { for (unsigned int i = 0; i < node->_children.size(); i++) print_rtree_node(level + 1, node->_children[i]); } } void build_rtree(vector<vertex_data> *latent_factors_inmem) { _data = latent_factors_inmem; vec lbound(D), rbound(D); for (int i = 0; i < D; i++) { lbound[i] = 10000; rbound[i] = -10000; } double max_val = -10000; int max_idx = 0; for (int i = 0; i < D; i++) { if (rbound[i] - lbound[i] > max_val) { max_idx = i; } } int NODE_SIZE = 50; vector<std::pair<double, unsigned int> > items; for(unsigned int i = M; i < M + N; i++) { items.push_back(std::make_pair(latent_factors_inmem->at(i).pvec[max_idx], i)); } std::sort(items.begin(), items.end(), sort_items_rtree); vector<RTreeNode*> *cnode_list = new vector<RTreeNode*>(); vector<RTreeNode*> *nnode_list = new vector<RTreeNode*>(); // Initiate leaf nodes int num_nodes = (int)(N / (float)(NODE_SIZE) + 0.5); for (int ni = 0; ni < num_nodes; ni++) { RTreeNode *node = new RTreeNode(); node->_lbound = zeros(D); node->_rbound = zeros(D); for (int i = 0; i < D; i++) { node->_lbound[i] = 10000; node->_rbound[i] = -10000; } node->_count = 0; int tmpN = (int)N; for (int i = ni * NODE_SIZE; i < std::min(ni * NODE_SIZE + NODE_SIZE, tmpN); i++) { node->_tids.push_back(items[i].second); ++node->_count; for (int j = 0; j < D; j++) { if (latent_factors_inmem->at(items[i].second).pvec[j] < node->_lbound[j]) node->_lbound[j] = latent_factors_inmem->at(items[i].second).pvec[j]; if (latent_factors_inmem->at(items[i].second).pvec[j] > node->_rbound[j]) node->_rbound[j] = latent_factors_inmem->at(items[i].second).pvec[j]; } } cnode_list->push_back(node); } // Initiate intermediate nodes while (cnode_list->size() > NODE_SIZE) { num_nodes = (int)(cnode_list->size() / (float)(NODE_SIZE) + 0.5); for (int ni = 0; ni < num_nodes; ni++) { RTreeNode *node = new RTreeNode(); node->_lbound = zeros(D); node->_rbound = zeros(D); for (int i = 0; i < D; i++) { node->_lbound[i] = 10000; node->_rbound[i] = -10000; } node->_count = 0; int tmpN = (int)(cnode_list->size()); for (int i = ni * NODE_SIZE; i < std::min(ni * NODE_SIZE + NODE_SIZE, tmpN); i++) { node->_children.push_back((*cnode_list)[i]); node->_count += (*cnode_list)[i]->_count; for (int j = 0; j < D; j++) { if ((*cnode_list)[i]->_lbound[j] < node->_lbound[j]) node->_lbound[j] = (*cnode_list)[i]->_lbound[j]; if ((*cnode_list)[i]->_rbound[j] > node->_rbound[j]) node->_rbound[j] = (*cnode_list)[i]->_rbound[j]; } } nnode_list->push_back(node); } cnode_list->clear(); vector<RTreeNode*> *tmp_list = cnode_list; cnode_list = nnode_list; nnode_list = tmp_list; } // Final root setup _root = new RTreeNode(); _root->_lbound = zeros(D); _root->_rbound = zeros(D); for (int i = 0; i < D; i++) { _root->_lbound[i] = 10000; _root->_rbound[i] = -10000; } _root->_count = 0; for (int i = 0; i < cnode_list->size(); i++) { _root->_children.push_back((*cnode_list)[i]); _root->_count += (*cnode_list)[i]->_count; for (int j = 0; j < D; j++) { if ((*cnode_list)[i]->_lbound[j] < _root->_lbound[j]) _root->_lbound[j] = (*cnode_list)[i]->_lbound[j]; if ((*cnode_list)[i]->_rbound[j] > _root->_rbound[j]) _root->_rbound[j] = (*cnode_list)[i]->_rbound[j]; } } delete cnode_list; delete nnode_list; } public: RTreeNode* _root; vector<vertex_data> * _data; }; #endif
true
af144cdf886abdff2bec1ce9cc8dab1d6fcec7d1
C++
ukibs/GameEngine
/GameEngine/GameEngine/ActionManager.h
UTF-8
671
2.703125
3
[]
no_license
#pragma once #include <vector> #include <string> #include <stdio.h> #include <iostream> #include <stdarg.h> #include "Singleton.h" #include "Action.h" using namespace std; class ActionManager : public Singleton<ActionManager> { private: vector <Action> actions; public: ActionManager(); ~ActionManager(); void addAction(Action action); void addAction(string name, string keyName); void addAction(string name,int numKeys, string keyName, ...); void removeAction(string name); void update(); bool getDown(string name); bool getPressed(string name); bool getReleased(string name); Action* getActionByName(string name); void close() { actions.clear(); }; };
true
064e824ebec0f224713efb4f9f010ab01e394ae9
C++
Legendaries/Cpp
/Assignment3/Assignment3/Converter.cpp
UTF-8
206
3.125
3
[]
no_license
#include "Converter.h" double inToFt(double in) { return in / 12; } double ftToIn(double ft) { return ft * 12; } double fahrenheitToCelcius(double fahrenheit) { return (fahrenheit - 32)*(5.0 / 9.0); }
true
da2eade9942412963b7c65bf8f2ba656e510466c
C++
iridium-browser/iridium-browser
/buildtools/third_party/libc++/trunk/test/std/strings/string.view/string.view.template/contains.char.pass.cpp
UTF-8
996
2.546875
3
[ "BSD-3-Clause", "NCSA", "MIT", "LLVM-exception", "Apache-2.0" ]
permissive
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11, c++14, c++17, c++20 // <string_view> // constexpr bool contains(charT x) const noexcept; #include <string_view> #include <cassert> #include "test_macros.h" constexpr bool test() { using SV = std::string_view; SV sv1 {}; SV sv2 {"abcde", 5}; ASSERT_NOEXCEPT(sv1.contains('e')); assert(!sv1.contains('c')); assert(!sv1.contains('e')); assert(!sv1.contains('x')); assert( sv2.contains('c')); assert( sv2.contains('e')); assert(!sv2.contains('x')); return true; } int main(int, char**) { test(); static_assert(test()); return 0; }
true
00cfb331e5bdbd78b947444dd212974d785de176
C++
Astarx1/plt
/src/state/Mobile.cpp
UTF-8
748
2.6875
3
[]
no_license
#include "Mobile.h" using namespace state; Mobile::Mobile () { } bool const Mobile::isStatic () { return true; } Direction Mobile::getDirection () { return this->direction; } void Mobile::setDirection (Direction d) { this->direction = d; } bool Mobile::getEnDeplacement () { return enDeplacement; } void Mobile::setEnDeplacement (bool b) { this->enDeplacement = b; } sf::Time Mobile::getTimer () { return this->timer; } void Mobile::setTimer (sf::Time timer) { this->timer = timer; } int const Mobile::getXobj () { return xObj; } void Mobile::setXobj (int x) { xObj = x; } int const Mobile::getYobj () { return yObj; } void Mobile::setYobj (int y) { yObj = y; }
true
2e0991744f946de96eeb87860a0b1d9a37641f1f
C++
LawrenceScroggs/CS161
/wk4_buggy_lscroggs.cpp
UTF-8
1,386
3.859375
4
[]
no_license
/************************************************** * File: wk4_buggy_lscroggs.cpp * Description: Displays the number of positive integers * and the number of negative integers entered by the user * * Lawrence Scroggs * 1/30/18 * * Modifications: Included namespace std; line 20 * cin >> variable was not correct n in number was capitalized line 29 * change not to !=. line 31 * changed =+ to ++; line 35 and 37 * changed to " " instead of ' ' on cout statement line 40 * changed positive to negative variable and negative to pos variable line 44 & 45 * added 0 to return line 48 * * **************************************************/ #include <iostream> using namespace std; int main() { int number; int positive = 0; int negative = 0; cout << "Enter a positive or negative integer (enter 0 to end): "; cin >> number; // changed N to n while (number != 0) { if (number > 0) positive++; // change =+ to ++ else negative++; // change =+ to ++ cout << "Enter another positive or negative integer (enter 0 to end): "; // changed to double quotes cin >> number; } cout << endl; cout << "Total positive integers: " << positive << endl; // changed from neg to pos. added a < cout << "Total negative integers: " << negative << endl; // changed from pos to neg. added a < cout << endl; return 0; // added 0 }
true
40057277595c613918c665274f1ca6577d77b25b
C++
lokvamsi/Candidate_Elim
/candel.cpp
UTF-8
11,816
3.265625
3
[]
no_license
/* * candel.cpp * * Created on: Oct 1, 2017 * Author: Binki */ #include <iostream> #include<list> #include<fstream> #include<string> #include "DataUtil.h" struct feature; using namespace std; /** * Function to print a list of datapoints/hypotheses * @param ls list containing the datapoints/hypotheses */ void printList(list<feature> ls) { list<feature>::iterator it = ls.begin(); if (ls.empty()) cout << "List empty \n"; for (; it != ls.end(); it++) { cout << "\n"; for (int i = 0; i < 16; i++) { if ((*it).attributes[i] == 99) cout << "?" << " "; else cout << (*it).attributes[i] << " "; } } cout<<endl; } /** * Function to print a single hypothesis/datapoint * @param s struct containing hypothesis/datapoint */ void printFeature(feature s) { for (int i = 0; i < 16; i++) cout << (s).attributes[i] << " "; cout << "\n"; } /** * Function to check if a datapoint/hypothesis is consistent with a hypothesis * @param hyp_it: hypothesis * @param data_it: datapoint * @return 1 if consistent, 0 if inconsistent */ int isConsistent(feature hyp_it, feature data_it) { int check = 1; for (int i = 0; i < 16; i++) { if ((hyp_it).attributes[i] != (data_it).attributes[i] && (hyp_it).attributes[i] != 99) { check = 0; break; } } return check; } /** * Function to check if a hypothesis is more general than a datapoint/hypothesis * @param data_it: the supposedly less general hypothesis * @param hyp_it: the claimed more general hypothesis * @return 1 if required hypothesis is more general, 0 if not */ int isMoreGeneral(feature data_it, feature hyp_it) { //check if hyp_it is more general than data_it int check = 1; int equal = 1; for (int i = 0; i < 16; i++) { if ((hyp_it).attributes[i] != (data_it).attributes[i]) equal = 0; } if (equal == 1) return 0; for (int i = 0; i < 16; i++) { if ((hyp_it).attributes[i] != (data_it).attributes[i] && (hyp_it).attributes[i] != 99) { check = 0; break; } } return check; } /** *Function to check if any of the hypothesis in a list is reachable/less general from a given hypothesis * @param test: hypothesis 'from which to reach'/claimed more general hypothesis * @param spec: list which contains elements 'to reach' * @return 1 if any element is reachable, 0 if none */ int isReachable(feature test, list<feature> spec) { list<feature>::iterator s_it = spec.begin(); for (; s_it != spec.end(); s_it++) { if (isMoreGeneral((*s_it), (test)) == 1) { return 1; } } return 0; } /** * Function to make a hypothesis more general to accomodate given datapoint * @param hyp_it: pointer to the hypothesis in question, so we can edit the original value * @param data_it: data point to be accomodated */ void generalise(list<feature>::iterator &hyp_it, feature data_it) { for (int i = 0; i < 16; i++) { if ((*hyp_it).attributes[i] == -1) { (*hyp_it).attributes[i] = data_it.attributes[i]; } else if ((*hyp_it).attributes[i] != (data_it).attributes[i] && (*hyp_it).attributes[i] != 99) { (*hyp_it).attributes[i] = 99; } } } /** * Function to return list of minimal specializations of a hypothesis made * so as to not accommodate inconsistent datapoint, it also checks the reachability * in specific boundary * @param hyp_it: hypothesis to be specialised * @param data_it: inconsistent data point * @param spec: list to check reachability * @return list containing all required minimal specializations based on given data */ list<feature> specify(feature hyp_it, feature data_it, list<feature> spec) { list<feature> sp_list; feature t0; for (int i = 0; i < 16; i++) { t0.attributes[i] = hyp_it.attributes[i]; } for (int i = 0; i < 16; i++) { feature t1 = t0; if (hyp_it.attributes[i] == 99) { if (i == 12) { if (data_it.attributes[i] == 0) { t1.attributes[i] = 2; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 4; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 5; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 6; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 8; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); } else if (data_it.attributes[i] == 2) { t1.attributes[i] = 0; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 4; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 5; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 6; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 8; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); } else if (data_it.attributes[i] == 4) { t1.attributes[i] = 2; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 0; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 5; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 6; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 8; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); } else if (data_it.attributes[i] == 5) { t1.attributes[i] = 2; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 4; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 0; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 6; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 8; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); } else if (data_it.attributes[i] == 6) { t1.attributes[i] = 2; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 4; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 5; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 0; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 8; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); } else if (data_it.attributes[i] == 8) { t1.attributes[i] = 2; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 4; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 5; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 6; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); t1.attributes[i] = 0; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); } } else if (data_it.attributes[i] == 1) { t1.attributes[i] = 0; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); } else if (data_it.attributes[i] == 0) { t1.attributes[i] = 1; if (isReachable(t1, spec) == 1) sp_list.push_back(t1); } } } return sp_list; } /** * Driver function for candidate elimination algorithm * @param train_set: Set of datapoints * @param target_class: value of target attribute to be taken as positive */ void candidateElim(list<feature> train_set, int target_class) { //Initialize lists list<feature> spec_bound; list<feature> gen_bound; feature s1; feature g1; for (int i = 0; i < 16; i++) { s1.attributes[i] = -1; g1.attributes[i] = 99; } spec_bound.push_back(s1); gen_bound.push_back(g1); //iterate through training data list<feature>::iterator train_it = train_set.begin(); // cout<<(*train_it).attributes[16]<<"\n"; // printList(train_set); list<feature>::iterator g_it = gen_bound.begin(); list<feature>::iterator s_it = spec_bound.begin(); for (; train_it != train_set.end(); train_it++) { //handling +ve training data if ((*train_it).attributes[16] == target_class) { // cout<<"Entered +ve example \n"; g_it = gen_bound.begin(); //traverse G and remove inconsistent for (; g_it != gen_bound.end(); g_it++) { if (isConsistent((*g_it), (*train_it)) == 0) { // cout << "Inconsistent with gen bound \n"; // cout << "gen hyp: "; // printFeature(*g_it); // cout << "\n" << "train data:"; // printFeature(*train_it); // cout << "\n"; g_it = gen_bound.erase(g_it); } } //traverse S and add generalisations (Is there more than one minimal generalisation?Need to check) s_it = spec_bound.begin(); for (; s_it != spec_bound.end(); s_it++) { // cout<<"Entered S \n"; if (isConsistent((*s_it), (*train_it)) == 0) { // cout<<"Inconsistent with S example \n"; // cout<<"Hyp:"; // printFeature(*s_it); // cout<<"\n Train Data:"; // printFeature(*train_it); // cout<<"\n"; int flag = 0; generalise(s_it, (*train_it)); // cout<<"Generalised hyp:"; // printFeature(*s_it); // cout<<"\n"; //traverse G for reachability check list<feature>::iterator g_temp_it = gen_bound.begin(); //check reachability in G for new element for (; g_temp_it != gen_bound.end(); g_temp_it++) { if (isMoreGeneral((*s_it), (*g_temp_it)) == 1) { //check s_it or train_it flag = 1; break; } } if (flag == 0) { s_it = spec_bound.erase(s_it); continue; } //traverse S to remove any element more general than the other list<feature>::iterator s_temp_it = spec_bound.begin(); for (; s_temp_it != spec_bound.end(); s_temp_it++) { if (isMoreGeneral((*s_temp_it), (*s_it)) == 1) { s_it = spec_bound.erase(s_it); break; } } } } } //handling -ve training data else { //traverse S check inconsistent, remove // cout << "Entered negative example \n" << (*train_it).attributes[16]; s_it = spec_bound.begin(); for (; s_it != spec_bound.end(); s_it++) { if (isConsistent((*s_it), (*train_it)) == 1) { s_it = spec_bound.erase(s_it); } } //traverse G, add minimal specialisations g_it = gen_bound.begin(); for (; g_it != gen_bound.end();) { //CHECK IF WORKING list<feature> min_sp; if (isConsistent((*g_it), (*train_it)) == 1) { min_sp = specify((*g_it), (*train_it), spec_bound); //specify takes care of reachability // cout << "Removing from gen bound:"; // printFeature(*g_it); // cout << endl; // cout << "Inconsistent with:"; // printFeature(*train_it); // cout << endl; g_it = gen_bound.erase(g_it); list<feature>::iterator min_sp_it = min_sp.begin(); for (; min_sp_it != min_sp.end(); min_sp_it++) { //check for more general int check = 1; list<feature>::iterator gen_comp = gen_bound.begin(); for (; gen_comp != gen_bound.end(); gen_comp++) { if (isMoreGeneral((*min_sp_it), (*gen_comp)) == 1) check = 0; } if (check == 1) gen_bound.push_back((*min_sp_it)); } } else g_it++; } } } cout<<"Specific Boundary:"<<endl; printList(spec_bound); cout << endl; cout<<"General Boundary:"<<endl; printList(gen_bound); cout << endl; }
true
766a73d77b6f8d05ba7c9f0a4ac2a30a55a28ddd
C++
plumer/hcm
/math/geometry_compact.hpp
UTF-8
6,852
3.15625
3
[]
no_license
#pragma once #include "config.hpp" #include <cassert> #include <cmath> namespace hcm { class cpt3; class cnormal3; class cvec3 { public: float x, y, z; // Constructors cvec3() : x{ 0.0f }, y{ 0.0f }, z{ 0.0f } {} cvec3(float _x, float _y, float _z) : x{ _x }, y{ _y }, z{ _z } {} explicit cvec3(const vec3 &v) : x{ v.x }, y{ v.y }, z{ v.z } {} float & operator [] (int i) { return (&x)[i]; } float operator [] (int i) const { return (&x)[i]; } // conversion explicit operator cpt3() const; explicit operator cnormal3() const; cvec3 & operator += (const cvec3 & rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } cvec3 & operator -= (const cvec3 & rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } cvec3 & operator *= (float s) { x *= s; y *= s; z *= s; return *this; } cvec3 & operator /= (float s) { assert(s != 0.0f); float inverse = 1.0f / s; x *= inverse; y *= inverse; z *= inverse; return *this; } float length() const { return std::sqrt(length_squared()); } float length_squared() const { return x*x + y*y + z*z; } void normalize() { float l = length(); assert(l != 0.0f); if (l != 1.0f) { float inv = 1.0f / l; x *= inv; y *= inv; z *= inv; } } cvec3 normalized() const { float l = length(); assert(l != 0.0f); if (l != 1.0f) { float inv = 1.0f / l; return cvec3{ x * inv, y * inv, z * inv }; } else { return (*this); } } static cvec3 xbase() { return cvec3{1, 0, 0};} static cvec3 ybase() { return cvec3{0, 1, 0};} static cvec3 zbase() { return cvec3{0, 0, 1};} }; class cpt3 { public: float x, y, z; cpt3() :x{ 0.0f }, y{ 0.0f }, z{ 0.0f } {} cpt3(float _x, float _y, float _z) : x{ _x }, y{ _y }, z{ _z } {} explicit cpt3(const pt3 &p) : x{ p.x }, y{ p.y }, z{ p.z } {} float & operator [] (int i) { return (&x)[i]; } float operator [] (int i) const { return (&x)[i]; } // conversion explicit operator cvec3() const {return cvec3{x, y, z};} cpt3 & operator += (const cvec3 & rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } cpt3 & operator -= (const cvec3 & rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } // static methods static cpt3 origin() { return cpt3{0, 0, 0}; } static cpt3 all(float x) { return cpt3{x, x, x}; } }; class cnormal3 { public: float x, y, z; cnormal3() : x{ 0.0f }, y{ 0.0f }, z{ 1.0f } {} cnormal3(float x, float y, float z) :x{ x }, y{ y }, z{ z } {} float & operator [] (int i) { return (&x)[i]; }; float operator [] (int i) const { return (&x)[i]; }; // conversion explicit operator cvec3 () const { return cvec3{x, y, z}; } // n +/+= n, n -/-= n, n */*= s, s*n, n / or /=s cnormal3 & operator += (const cnormal3 &rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } cnormal3 & operator -= (const cnormal3 &rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } cnormal3 & operator *= (float s) { x *= s; y *= s; z *= s; return *this; } cnormal3 & operator /= (float s) { assert(s != 0.0f); float inv = 1.0f / s; x *= inv; y *= inv; z *= inv; return *this; } void flip_direction() { x = -x; y = -y; z = -z; } // normalize, length, normalized float length() const { return std::sqrt(length_squared()); } float length_squared() const { return x*x + y*y + z*z; } cnormal3 normalized() const { float l = this->length(); assert(l != 0.0f); float inv = 1.0f / l; return cnormal3{ x*inv, y*inv, z*inv }; } void normalize() { float l = this->length(); assert(l != 0.0f); float inv = 1.0f / l; x *= inv; y *= inv; z *= inv; } }; // solving forward declaration inline cvec3::operator cpt3() const{ return cpt3{x, y, z}; } inline cvec3::operator cnormal3() const { return cnormal3{x, y, z}; } // v+v, v-v, v*s, v/s inline cvec3 operator + (const cvec3 & lhs, const cvec3 & rhs) { return cvec3{ lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z }; } inline cvec3 operator - (const cvec3 & lhs, const cvec3 & rhs) { return cvec3{ lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z }; } inline cvec3 operator * (const cvec3 & lhs, float s) { return cvec3{ lhs.x*s, lhs.y*s, lhs.z*s }; } inline cvec3 operator * (float s, const cvec3 &v) { return v*s;} inline cvec3 operator / (const cvec3 & lhs, float s) { assert(s != 0.0f); float inverse = 1.0f / s; return cvec3{ lhs.x*inverse, lhs.y*inverse, lhs.z*inverse }; } // return vector in opposite direction inline cvec3 operator - (const cvec3 &v) { return cvec3{ -v.x, -v.y, -v.z }; } // point +/+= vec, point -/-= vec inline cpt3 operator + (const cpt3 &p, const cvec3 & v) { return cpt3{ p.x + v.x, p.y + v.y, p.z + v.z }; } inline cpt3 operator - (const cpt3 &p, const cvec3 & v) { return cpt3{ p.x - v.x, p.y - v.y, p.z - v.z }; } // point - point inline cvec3 operator - (const cpt3 &lhs, const cpt3 & rhs) { return cvec3{ lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z }; } inline cnormal3 operator + (const cnormal3 &lhs, const cnormal3 &rhs) { return cnormal3{ lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z }; } inline cnormal3 operator - (const cnormal3 &lhs, const cnormal3 &rhs) { return cnormal3{ lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z }; } inline cnormal3 operator * (const cnormal3 &lhs, float s) { return cnormal3{ lhs.x*s, lhs.y*s, lhs.z*s }; } inline cnormal3 operator * (float s, const cnormal3 &n) {return n*s;} inline cnormal3 operator / (const cnormal3 &lhs, float s) { float inv = 1.0f / s; assert(s != 0.0f); return cnormal3{ lhs.x*inv, lhs.y*inv, lhs.z*inv }; } inline cnormal3 operator -(const cnormal3 &n) { return cnormal3{ -n.x, -n.y, -n.z }; } // Dot-product and cross-product inline float dot(const cvec3 &lhs, const cvec3 & rhs) { return lhs.x*rhs.x + lhs.y*rhs.y + lhs.z*rhs.z; } inline cvec3 cross(const cvec3 &lhs, const cvec3 & rhs) { // | x | y | z | // | x'| y'| z'| // | i | j | k | return cvec3{ lhs.y*rhs.z - lhs.z*rhs.y, lhs.z*rhs.x - lhs.x*rhs.z, lhs.x*rhs.y - lhs.y*rhs.x }; } inline float dot(const cvec3 &v, const cnormal3 &n) { return v.x*n.x + v.y*n.y + v.z*n.z; } inline float dot(const cnormal3 &n, const cvec3 &v) { return dot(v,n); } #ifdef GLWHEEL_MATH_GEOMETRY_USE_OPOV_DC inline float operator * (const cvec3 &v, const cvec3 &u) {return dot(v, u);} inline float operator * (const cvec3 &v, const cnormal3 &n) {return dot(v, n);} inline float operator * (const cnormal3 &n, const cvec3 &v) {return dot(v, n);} inline cvec3 operator ^ (const cvec3 &v, const cvec3 &u) {return cross(v, u);} #endif float dist(const cpt3& lhs, const cpt3 &rhs) { return (lhs - rhs).length(); } } // namespace hcm
true
2b1594b24163ae8d93881069f74e7ab7975941c5
C++
swy20190/Leetcode-Cracker
/1423/P1423/P1423/main.cpp
UTF-8
637
3.0625
3
[ "MIT" ]
permissive
#include <vector> #include <algorithm> using namespace std; class Solution { public: int maxScore(vector<int>& cardPoints, int k) { int sum = 0; int len = cardPoints.size(); for (auto p : cardPoints) { sum += p; } if (len == k) { return sum; } int window_size = len - k; int left = 0; int right = window_size; int curr_sum = 0; for (int i = 0; i < right; i++) { curr_sum += cardPoints[i]; } int min_sum = curr_sum; while (right < len) { curr_sum += cardPoints[right]; curr_sum -= cardPoints[left]; right++; left++; min_sum = min(min_sum, curr_sum); } return sum - min_sum; } };
true
37cb092b963c5da8f7b4d2806596d8f73d3aee5f
C++
samopal-pro/SoilMoistureController
/Gateway_esp8266/WC_Decoder.cpp
UTF-8
2,881
2.84375
3
[]
no_license
/** * Контроллер умного дома. Версия 2.0 ESP8266 * Copyright (C) 2016 Алексей Шихарбеев * http://samopal.pro */ #include "WC_Decoder.h" WC_Data RC_Data[MAX_SENSORS]; int RC_DataCount = 0; /** * Проверка контрольной суммы пакета */ bool RC_CheckSRC( uint32_t data ){ // Считаем контрольную сумму полубайтами uint8_t src = 0; src = (uint8_t)(data & 0xf); src += (uint8_t)(data>>4 & 0xf); src += (uint8_t)(data>>8 & 0xf); src += (uint8_t)(data>>12 & 0xf); src += (uint8_t)(data>>20 & 0xf); src += (uint8_t)(data>>24 & 0xf); src += (uint8_t)(data>>28 & 0xf); uint8_t src1 = (uint8_t)(data>>16 & 0xf); if( (src&0xf) != (src1&0xf) ){ Serial.printf("Bad SRC 0x%lx calc=0x%x decode=0x%x\n",data,src&0xf,src1&0xf); return false; } return true; } /* * Находим номер записи в массиве данных по ID датчика или создаем новый */ int RC_CountById( uint8_t id ){ for( int i=0; i<RC_DataCount; i++ ){ // Если найден сенсор в списке if( RC_Data[i].Id == id )return i; } // Если превышено количество сенсоров if( RC_DataCount >= MAX_SENSORS )return -1; // Создаем новый сенсор RC_Data[RC_DataCount].Id = id; RC_Data[RC_DataCount].Time = 0; RC_Clear(RC_DataCount); RC_DataCount++; return RC_DataCount-1; } /** * Очистка строки данных */ void RC_Clear(int n){ if( n < 0 || n >= MAX_SENSORS )return; for( int i=0; i<MAX_PACKET; i++ ){ // RC_Data[n].Data[i] = 0; RC_Data[n].DataFlag[i] = false; } RC_Data[n].Enabled = false; } /** * Декодирование сигнала */ int RC_Decode( uint32_t data, uint32_t tm1 ){ // Проверка контрольной суммы if( RC_CheckSRC( data ) == false )return -1; // Декодируем данные uint8_t id = (uint8_t)(data>>24 &0xff); uint8_t count = (uint8_t)(data>>20 &0xf); int val = (int)(data &0xffff); // Находим номер в массиве данных int n = RC_CountById(id); if( n < 0 )return false; // Проверка на максимальное число пакетов if( count >= MAX_PACKET )return -1; // Сохранение данных в массив RC_Data[n].Time = tm1; RC_Data[n].Data[count] = val; RC_Data[n].DataFlag[count] = true; RC_Data[n].Enabled = true; Serial.printf("Decode: tm=%ld n=%d id=0x%x count=%d val=%d\n",tm1,n,id,count,val); // Проверка на последний пакет if( count == MAX_PACKET-1 )return n; return -1; } /* * Декодируем четыре байта данных */ /* bool DecodeRC_Packet(uint32_t raw_data){ } */
true
14e298fe1ee063940d511aab4ea4415a779607c5
C++
dmishin/dmishin-pyscript
/cpp/alife2/src/world.hpp
UTF-8
1,283
2.625
3
[]
no_license
#pragma once #ifndef _WORLD_H_ #define _WORLD_H_ //#include "grid.hpp" #include "grid.hpp" #include "simulated.hpp" #include "point.hpp" #include "ticker.hpp" namespace alife2{ class Mobile; class Food; class World: public Simulated{ float timeStep; //simulation step float friction; //movement friction float rotationFriction; //friciton koefficient for rotation rectangle bounds; //Grid initialization code void initGrids( float width, float height, float cellSize ); void initParameters(); public: Grid gridMobiles; Grid gridFood; World( float width, float height, float cellSize); //Get the walue of the simulation time step float getSimulationStep()const { return timeStep; }; float setSimulationStep( float step ){ timeStep = step; }; float getFriction()const {return friction; }; float getRotFriction() const { return rotationFriction; }; //world geometry const rectangle& getBounds()const {return bounds; }; vec2 getCenter()const { return bounds.center(); }; void add( Mobile * mobile ); void add( Food* food ); //Implementation of the Simulated virtual bool simulate(); //Apply world geometry to the mobile: force it to stay inside the world bounds void applyBounds( Mobile & mob ); }; }; #endif /* _WORLD_H_ */
true
228ec489a17d9dfbe296e8f1877eed1d58f9db0d
C++
duckdog/Signal
/Signal/Classes/AnchorPoint.hpp
UTF-8
1,391
2.765625
3
[ "MIT" ]
permissive
// // AnchorPoint.hpp // CocosTemplate // // Created by 佐藤 匠 on 2016/03/05. // // #pragma once #include <map> //アンカーポイントを定義 namespace AncPoint { enum Key { LeftTop = 0, RightTop = 1, LeftBottom = 2, RightBottom = 3, Left, Right, Top, Bottom, Center, Last, }; const cocos2d::Vec2 AnchorLeftTop = cocos2d::Point(0,1); const cocos2d::Vec2 AnchorRightTop = cocos2d::Point(1,1); const cocos2d::Vec2 AnchorLeftBottom = cocos2d::Point(0,0); const cocos2d::Vec2 AnchorRightBottom = cocos2d::Point(1,0); const cocos2d::Vec2 AnchorLeft = cocos2d::Point(0,0.5f); const cocos2d::Vec2 AnchorRight = cocos2d::Point(1,0.5f); const cocos2d::Vec2 AnchorCenter = cocos2d::Point(0.5f,0.5f); const cocos2d::Vec2 AnchorTop = cocos2d::Point(0.5f,1); const cocos2d::Vec2 AnchorBottom = cocos2d::Point(0.5f,0); static std::map<AncPoint::Key,cocos2d::Vec2> anchorMap = { {LeftTop,AnchorLeftTop}, {LeftBottom,AnchorLeftBottom}, {RightTop,AnchorRightTop}, {RightBottom,AnchorRightBottom}, {Right,AnchorRight}, {Left,AnchorLeft}, {Top,AnchorTop}, {Bottom,AnchorBottom}, {Center,AnchorCenter}, }; }
true
f745574c29a817f0539424fe38c58a4c14ba11d5
C++
mldbai/mldb
/utils/progress.cc
UTF-8
2,570
2.796875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/** * progress.cc * Guy Dumais, 2016-04-28 * Mich, 2016-05-24 * This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved. **/ #include "progress.h" #include "mldb/types/basic_value_descriptions.h" #include "mldb/types/optional_description.h" namespace MLDB { using namespace std; shared_ptr<Step> Step:: nextStep(float endValue) { ended = Date::now(); value = endValue; auto nextStep = _nextStep.lock(); if (!nextStep) { throw MLDB::Exception("No next step!"); } nextStep->started = Date::now(); return nextStep; } DEFINE_STRUCTURE_DESCRIPTION(Step); StepDescription:: StepDescription() { addField("name", &Step::name, ""); addField("started", &Step::started, ""); addField("ended", &Step::ended, ""); addField("value", &Step::value, ""); addField("type", &Step::type, ""); } shared_ptr<Step> Progress:: steps(vector<pair<string, string>> nameAndTypes) { std::shared_ptr<Step> previousStep; for (const auto & nameAndType : nameAndTypes) { auto step = std::make_shared<Step>(nameAndType.first, nameAndType.second); if (previousStep) { previousStep->_nextStep = step; } _steps.push_back(step); previousStep = step; } auto firstStep = _steps.begin(); if (firstStep != _steps.end()) { (*firstStep)->started = Date::now(); } return *firstStep; } DEFINE_STRUCTURE_DESCRIPTION(Progress); ProgressDescription:: ProgressDescription() { addField("steps", &Progress::_steps, ""); } DEFINE_STRUCTURE_DESCRIPTION(ProgressState); ProgressStateDescription:: ProgressStateDescription() { addField("count", &ProgressState::count, "the number of items processed so far"); addField("total", &ProgressState::total, "if available, the total number of items to processed"); } ProgressState:: ProgressState() : count(0) {} ProgressState:: ProgressState(uint64_t total_) : count(0) { total.emplace(total_); } ProgressState & ProgressState:: operator = (uint64_t count_) { count = count_; return *this; } ConvertProgressToJson:: ConvertProgressToJson(const std::function<bool(const Json::Value &)> & onJsonProgress) : onJsonProgress(onJsonProgress) { } bool ConvertProgressToJson:: operator () (const ProgressState & progress) { Json::Value value; ExcAssert(*progress.total); value["percent"] = (float) progress.count / *progress.total; return onJsonProgress(value); } } // namespace MLDB
true
8a01642c7f02703cc2e8ffce981d505942aa6e02
C++
bsy6766/VoxelEngine
/VoxelEngine/Classes/TerrainType.h
UTF-8
512
2.890625
3
[]
no_license
#ifndef TERRAIN_TYPE_H #define TERRAIN_TYPE_H namespace Voxel { // Default terrains. enum class TerrainType { NONE = 0, PLAIN, // Flat terrain. No hills and mountains HILLS, // Few hills in flat terrain MOUNTAINS, // Few mountinas PLATEAU, }; // Modifiers gives changes on world generation, gives more randomness to the game enum class TerrainModifier { NONE = 0, // Defult terrain MEDIUM, // Few variation LARGE, // Some variation MEGA // Large variation }; } #endif
true
a0a860d0aca12919d5e9839d4fdf336d8329f32e
C++
skilling0722/Project-VLC_arduino
/Stored_info.ino
UTF-8
3,496
2.890625
3
[]
no_license
#include <EEPROM.h> //160 까지 기기정보 16칸 //161~168 비밀번호 8킨 //300 기기개수 1칸 //char **Stored_device_info; //char *Stored_pwd; const int Stored_device_number = 10; const int Stored_deviceinfo_length = 16; const int Stored_pwd_number = 1; const int Stored_pwd_length = 8; int device_count = 0; char pwd_temp[8]; char deviceinfo_temp[16]; String Stored_device_info_str; String Stored_pwd_str; //void init_Stored_value() { // Stored_device_info = (char **) malloc (sizeof(char *) * Stored_device_number); // for(int i = 0; i < Stored_device_number; i++) { // Stored_device_info[i] = (char *) malloc (sizeof(char) * Stored_deviceinfo_length); // } // // Stored_pwd = (char *) malloc (sizeof(char) * Stored_pwd_length); //} void write_count_EEPROM() { EEPROM.write(300, device_count); } void read_count_EEPROM() { int count = EEPROM.read(300); Serial.print("EEPROM에서 읽어온 기기개수: "); Serial.println(count); } void plus_count() { device_count++; } void write_device_info_EEPROM(String device_info) { char buf[Stored_deviceinfo_length + 1]; device_info.toCharArray(buf, Stored_deviceinfo_length + 1); for (int i = 0; i < Stored_deviceinfo_length; i++) { EEPROM.write(i + (16 * device_count), buf[i]); //write(addr, value); } plus_count(); } void read_device_info_EEPROM() { for (int i = 0; i < Stored_deviceinfo_length; i++) { deviceinfo_temp[i] = EEPROM.read(i); } Stored_device_info_str = deviceinfo_temp; Serial.print("EEPROM에서 읽어온 기기정보: "); Serial.println(Stored_device_info_str); } boolean search_EEPROM(String input, String type) { int divide; int length_val; int number; char *search_temp; int fork; if ( type.equals("deviceinfo") ) { fork = 0; divide = 16; length_val = Stored_deviceinfo_length; number = Stored_device_number; search_temp = (char *) malloc (sizeof(char) * Stored_deviceinfo_length); Serial.println("기기정보 서치"); } else if ( type.equals("pwd") ) { fork = 1; divide = 8; length_val = Stored_pwd_length; number = Stored_pwd_number; search_temp = (char *) malloc (sizeof(char) * Stored_pwd_length); Serial.println("비번 서치"); } else { Serial.println("Stored_info - search_EEPROM - 해당 type 없음 "); } for (int i = 0; i < (length_val * number) + 1; i++) { if ( i % divide == 0 && i != 0 ) { String search_temp_str = search_temp; search_temp_str = search_temp_str.substring(0, length_val); Serial.println(search_temp_str); if ( search_temp_str.equals(input) ) { Serial.print("EEPROM에 찾던 값 있음: "); Serial.println(search_temp_str); free(search_temp); return true; } } search_temp[i % divide] = EEPROM.read( (160 * fork) + i ); } Serial.println("없얼"); free(search_temp); return false; } void write_pwd_EEPROM(String pwd) { char buf[Stored_pwd_length + 1]; pwd.toCharArray(buf, Stored_pwd_length + 1); for (int i = 0; i < Stored_pwd_length; i++) { EEPROM.write(160 + i, buf[i]); //write(addr, value); } } void read_pwd_EEPROM() { for (int i = 0; i < Stored_pwd_length; i++) { pwd_temp[i] = EEPROM.read(160 + i); } Stored_pwd_str = pwd_temp; Serial.print("EEPROM에서 읽어온 비밀번호: "); Serial.println(Stored_pwd_str); } void clear_EEPROM() { for (int i = 0 ; i < 350 ; i++) { EEPROM.write(i, 0); } }
true
4bda5f982d445bd59f170a265c878d17b6a1e333
C++
errorcodexero/fiddle
/luke/CSV_manipulation.cpp
UTF-8
1,072
3
3
[]
no_license
#include<iostream> #include<fstream> #include<stdlib.h> #include<string> #include<vector> using namespace std; ostream& operator<<(ostream& o, vector<string> v){ for(unsigned i = 0; i < v.size(); i++){ o<<v[i]<<"\n"; } return o; } int main(){ fstream f("a.csv"); if(f.good() == false){ cout<<"No file available."; exit(1); } /*while(f.good()){ string s; getline(f,s); cout<<s<<"\n"; }*/ //getcolNumList /* //User input int userCol; cout<<"Which col to list? "; cin>>userCol; int commaPos; while(f.good()){ string s; getline(f,s); //For to parse through and find for(int i = 0; i < userCol; i++){ s = s.substr(commaPos = s.find(",")+1); } s = s.substr(0,s.find(",")); cout<<s<<"\n"; }*/ vector<string> v; //Store Items in a vector while(f.good()){ string s; getline(f,s); while(s.find(",") != string::npos){ v.push_back(s.substr(0,s.find(","))); s = s.substr(s.find(",")+1); } v.push_back(s); } cout<<v; }
true
8bfea874ac465e34ad41fa6ff31b90e4b2ccb56d
C++
ianmetcalf/iot-workshop
/examples/ReadBMP280/ReadBMP280.ino
UTF-8
629
2.90625
3
[ "MIT" ]
permissive
/********************************************************************* Example: Read from a BMP280 Sensor *********************************************************************/ #include <Adafruit_BMP280.h> Adafruit_BMP280 bmp; void setup() { Serial.begin(57600); while (!Serial) { delay(1); } if (!bmp.begin()) { Serial.println("BMP280 not present"); while (true); } } void loop() { Serial.print("Pressure: "); Serial.print(bmp.readPressure() / 1000); Serial.println(" kPa"); Serial.print("Temperature: "); Serial.print(bmp.readTemperature()); Serial.println(" C"); delay(1000); }
true
53c7a281ccd1ae34a418839b3a0743af6f98311b
C++
Nurl4n/Fundamental-Structures-of-Computer-Science-II
/Project 1/src/main.cpp
UTF-8
980
3.140625
3
[ "MIT" ]
permissive
/* * Title : Algorithm Efficiency and Sorting * Author : Nurlan Farzaliyev * ID : 21503756 * Section : 1 * Assignment : 1 * Description : Main class to test some of the sorting algorithms. */ #include <iostream> #include <string> #include <cstdlib> #include <ctime> #include "sorting.h" using namespace std; int main() { Sorting test; cout << "-------------------------Size 20000----------------------" << endl; test.performanceAnalysis(20000); cout << "-------------------------Size 30000----------------------" << endl; test.performanceAnalysis(30000); cout << "-------------------------Size 40000----------------------" << endl; test.performanceAnalysis(40000); cout << "-------------------------Size 50000----------------------" << endl; test.performanceAnalysis(50000); cout << "-------------------------Size 60000----------------------" << endl; test.performanceAnalysis(60000); return 0; }
true
7dbecdc0223b0cba6885d645980777502c079ee1
C++
TheNsBhasin/CodeChef
/TABGAME/main.cpp
UTF-8
1,734
2.78125
3
[]
no_license
/*input 2 101 01 6 1 1 1 2 1 3 2 1 2 2 2 3 1011001 0101111 6 5 5 3 4 2 6 3 7 7 7 6 5 */ // // main.cpp // TABGAME // // Created by Nirmaljot Singh Bhasin on 13/09/18. // Copyright © 2018 Nirmaljot Singh Bhasin. All rights reserved. // #include <iostream> #include <memory.h> using namespace std; typedef long long int lli; const int MAXN = 100005; bool row[2][MAXN]; bool col[MAXN][2]; int main(int argc, const char * argv[]) { int t; cin >> t; while (t--) { memset(row, false, sizeof(row)); memset(col, false, sizeof(col)); string s1, s2; cin >> s1 >> s2; lli m = s1.length(); lli n = s2.length(); row[0][0] = col[0][0] = (s1[0] == '0') || (s2[0] == '0'); row[0][1] = col[0][1] = (m > 1 && s1[1] == '0') || (!row[0][0]); row[1][0] = col[1][0] = (n > 1 && s2[1] == '0') || (!row[0][0]); row[1][1] = col[1][1] = (!row[0][1]) || (!col[1][0]); for (int i = 2; i < n; ++i) { col[i][0] = (s2[i] == '0') || (!col[i - 1][0]); } for (int j = 2; j < m; ++j) { row[0][j] = (s1[j] == '0') || (!row[0][j - 1]); } for (int i = 2; i < n; ++i) { col[i][1] = (!col[i][0]) || (!col[i - 1][1]); } for (int j = 2; j < m; ++j) { row[1][j] = (!row[1][j - 1]) || (!row[0][j]); } int q; cin >> q; string ans = ""; for (int i = 0; i < q; ++i) { lli x, y; cin >> x >> y; --x; --y; if (x < 2) { ans += (row[x][y] ? "1" : "0"); } else if (y < 2) { ans += (col[x][y] ? "1" : "0"); } else { if (x < y) { // cout << 1 << ", " << y - x + 1 << endl; ans += (row[1][y - x + 1] ? "1" : "0"); } else { // cout << x - y + 1 << ", " << 1 << endl; ans += (col[x - y + 1][1] ? "1" : "0"); } } } cout << ans << endl; } return 0; }
true