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
5c8234f9ced1d74e5b4df23c96f83f5700b2567c
C++
tingxueren/acm
/1002_v3.cc
UTF-8
1,745
2.6875
3
[]
no_license
/* * ===================================================================================== * * Filename: 1002_v3.cc * * Description: acm 1002 * * Version: 1.0 * Created: 10/12/2012 01:30:14 PM * Revision: none * Compiler: gcc * * Author: Zhang Dongsheng (mars), zhangdongsheng1224@gmail.com * Organization: HANGZHOU DIANZI UNIVERSITY * * ===================================================================================== */ #include <iostream> #include <algorithm> #include <string> using namespace std; int main() { string str1; string str2; while(cin>>str1>>str2) { int nLen1, nLen2, nLen; nLen1 = str1.length(); nLen2 = str2.length(); nLen = nLen1 > nLen2 ? nLen1 : nLen2; reverse(str1.begin(), str1.end()); reverse(str2.begin(), str2.end()); //高位补零 if (nLen > nLen1) str1.append(nLen - nLen1, '0'); if (nLen > nLen2) str2.append(nLen - nLen2, '0'); int temp = 0; //进位数目 int i = 0; string strResult; //存储结果 while (i < nLen) { if(str1[i] -0x30 + str2[i] + temp > '9') { strResult.append(1, str1[i] + str2[i] - '9' - 1 + temp); temp = 1; } else { strResult.append(1, str1[i] + str2[i] - '0' + temp); temp = 0; } i++; } if(temp == 1) strResult.append(1, '1'); reverse(strResult.begin(), strResult.end()); cout<<strResult<<endl; } return 0; }
true
53ad55682fa6fdeea3af5013be03e091ffb4cab5
C++
yabuta/eating_one
/joins/blockJoin_gpu/disk/cpu_disk/nestLoopJoin.cc
UTF-8
4,454
2.671875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <string.h> #include <sys/time.h> #include <error.h> #include "tuple.h" #include "debug.h" int left; int right; TUPLE *Tright; TUPLE *Tleft; JOIN_TUPLE *Tjoin; void diffplus(long *total,struct timeval begin,struct timeval end){ *total += (end.tv_sec - begin.tv_sec) * 1000 * 1000 + (end.tv_usec - begin.tv_usec); } static int getTupleId(void) { static int id; return ++id; } static void getJoinTuple(TUPLE *lt, TUPLE *rt,JOIN_TUPLE *jt) { int i; jt->lval = lt->val; jt->rval = rt->val; // lid & rid are just for debug jt->lid = lt->id; jt->rid = rt->id; } int join() { int i,j; static int count=0; for (i = 0 ; i < left ; i++) { for (j = 0 ; j < right ; j++) { if(Tleft[i].val == Tright[j].val){ getJoinTuple(&(Tleft[i]),&(Tright[j]),&(Tjoin[count])); count++; } } } printf("%d\n",count); return count; } void init(void) { if (!(Tright = (TUPLE *)calloc(right, sizeof(TUPLE)))) ERR; if (!(Tleft = (TUPLE *)calloc(left, sizeof(TUPLE)))) ERR; if (!(Tjoin = (JOIN_TUPLE *)calloc(JT_SIZE, sizeof(JOIN_TUPLE)))) ERR; } //メモリ解放のため新しく追加した関数。バグがあるかも void tuple_free(void){ free(Tleft); free(Tright); free(Tjoin); } int main(int argc, char *argv[]) { struct timeval time_s,time_f; double time_cal; int jt_size; FILE *lp,*rp; struct timeval leftread_time_s, leftread_time_f; struct timeval rightread_time_s, rightread_time_f; struct timeval hashjoin_s, hashjoin_f; long leftread_time = 0,rightread_time = 0,hashjoin_time = 0; /*******************init array*************************************/ init(); /*****************************************************************/ /*全体の実行時間計測*/ gettimeofday(&time_s,NULL); //read table size from both table file if((lp=fopen(LEFT_FILE,"r"))==NULL){ fprintf(stderr,"file open error(left)\n"); exit(1); } if(fread(&left,sizeof(int),1,lp)<1){ fprintf(stderr,"file write error\n"); exit(1); } if((rp=fopen(RIGHT_FILE,"r"))==NULL){ fprintf(stderr,"file open error(right)\n"); exit(1); } if(fread(&right,sizeof(int),1,rp)<1){ fprintf(stderr,"file write error\n"); exit(1); } #ifndef SIZEREADFILE left = LSIZE; right = RSIZE; #endif printf("left size = %d\tright size = %d\n",left,right); int lsize = left,rsize = right; Tleft = (TUPLE *)malloc(lsize*sizeof(TUPLE)); Tright = (TUPLE *)malloc(rsize*sizeof(TUPLE)); while(1){ gettimeofday(&leftread_time_s, NULL); if((left=fread(Tleft,sizeof(TUPLE),lsize,lp))<0){ fprintf(stderr,"file write error\n"); exit(1); } if(left == 0) break; gettimeofday(&leftread_time_f, NULL); diffplus(&leftread_time,leftread_time_s,leftread_time_f); while(1){ gettimeofday(&rightread_time_s, NULL); if((right=fread(Tright,sizeof(TUPLE),rsize,rp))<0){ fprintf(stderr,"file write error\n"); exit(1); } if(right == 0) break; gettimeofday(&rightread_time_f, NULL); diffplus(&rightread_time,rightread_time_s,rightread_time_f); gettimeofday(&hashjoin_s, NULL); jt_size = join(); gettimeofday(&hashjoin_f, NULL); diffplus(&hashjoin_time,hashjoin_s,hashjoin_f); } if(fseek(rp,sizeof(int),0)!=0){ fprintf(stderr,"file seek error.\n"); exit(1); } } fclose(lp); fclose(rp); gettimeofday(&time_f,NULL); time_cal=(time_f.tv_sec-time_s.tv_sec)*1000*1000+(time_f.tv_usec-time_s.tv_usec); printf("Caluculation with Devise : %6f(miri sec)\n",time_cal/1000); printf("file read time:\n"); printf("Diff: %ld us (%ld ms)\n", leftread_time+rightread_time, (leftread_time+rightread_time)/1000\ ); printf("hash join time:\n"); printf("Diff: %ld us (%ld ms)\n", hashjoin_time, hashjoin_time/1000); printf("result table size = %d\n",jt_size); printf("\n\n"); //結果の表示 むやみにやったら死ぬので気を付ける /* for(int i=0;i < right*left ;i++){ if(i%100000==0){ printf("id = %d\n",Tjoin[i].id); for(int j=0;j<VAL_NUM;j++){ printf("lval[%d] = %d\trval[%d] = %d\n",j,Tjoin[i].lval[j],j,Tjoin[i].rval[j]); } } } */ //割り当てたメモリを開放する tuple_free(); return 0; }
true
c5eca3202019d7d5d479d441ef016b96df18e87f
C++
Brandon-Ashworth/Physics-Simulation
/Demos/Pysics/Physics Stuff/Physics Stuff/ISE-Demo/Affordance.h
UTF-8
317
2.859375
3
[]
no_license
class Affordance { public: Affordance(); Affordance(float eat,float drink, float pickup); ~Affordance(void); void setEat(float eat); void setDrink(float drink); void setPickup(float pickup); float getEat(); float getDrink(); float getPickup(); private: float m_Eat; float m_Drink; float m_PickUp; };
true
8d513805199f40b1de7751c0a97d5ae0aef6bef4
C++
Mike-droid/EjerciciosDeCplusplus
/Funciones en c++/Ejercicio 19 funciones.cpp
WINDOWS-1250
691
3.875
4
[]
no_license
/*Ejercicio 19: Realice una funcin recursiva que sume los primeros n enteros positivos Nota: para plantear la funcin recursiva tenga en cuenta que la suma puede expresarse mediante la siguiente recurrencia: suma(n)=1 ,si n=1 n+suma(n-1) ,si n>1 */ #include<iostream> #include<conio.h> using namespace std; int sumar(int); int main(){ int nElementos; do{ cout<<"Digite el numero de elementos: "; cin>>nElementos; }while(nElementos<=0); cout<<"\nLa suma es: "<<sumar(nElementos)<<endl; getch(); return 0; } //Funcin recursiva int sumar(int n){ int suma = 0; if(n==1){ //Caso base suma=1; }else{ //Caso general suma = n+sumar(n-1); } return suma; }
true
d55667b9fce55798b76dc15a18bb6adcc094af1a
C++
issaiass/Turtlesim_Simple_Planner
/src/pid/pid.cpp
UTF-8
4,059
2.6875
3
[]
no_license
/* ******************************************************************************* * DATA ACQUISITION SYSTEMS, S.A. * PANAMA, REPUBLIC OF PANAMA * * File : pid.cpp * Progremmer(s) : Rangel Alvarado * Language : C++ * Description : A simple PID controller class function. * ---------------------------------------------------------------------------- * HISTORY * MM DD YY * 09 26 20 Created. * 09 28 20 Added comments * 10 30 20 Documented ******************************************************************************* */ /* ******************************************************************************* * NECCESARY HEADER FILES FOR THE APPLICATION ******************************************************************************* */ #include <pid/pid.hpp> /* ******************************************************************************* * FUNCTIONS ******************************************************************************* */ /* ******************************************************************************* * * PID CONSTRUCTOR BY GIVING THE PID CONSTANTS * * * Description : Initializes the PID with Kp, Ki, Kd for angle and distance * Func. Name : pid * Arguments : std::vector<double> &Kx * set the value of distances Kp, Ki, Kd constants * std::vector<double> &Kz * set the value of angles Kp, Ki, Kd constants * Returns : None * Notes : Initialization lisf of the error as 0 ******************************************************************************* */ pid::pid(std::vector<double> &Kx, std::vector<double> &Kz) : _Kx(Kx), _Kz(Kz), _error({0,0}) { } /* ******************************************************************************* * * A FUNCTION TO UPDATE THE PID CONTROLLER * * * Description : Update controller values by giving the transform and delta time * Func. Name : update * Arguments : geometry_msgs::TransformStamped ts * the transform between the current object and the goal * double dt * value in seconds of the time elapsed to apply the PID * Returns : geometry_msgs::Twist * pose format to easy pass to the cmd_vel publisher * Notes : None ******************************************************************************* */ geometry_msgs::Twist pid::update(geometry_msgs::TransformStamped ts, double dt) { double Kx_p = _Kx.at(0); double Kx_i = _Kx.at(1); double Kx_d = _Kx.at(2); double Kz_p = _Kz.at(0); double Kz_i = _Kz.at(1); double Kz_d = _Kz.at(2); double error_d = sqrt(pow(ts.transform.translation.x, 2) + pow(ts.transform.translation.y, 2)); double error_a = atan2(ts.transform.translation.y, ts.transform.translation.x); static double prev_error_d; static double prev_error_a; double ierror_d, ierror_a; ierror_d += prev_error_d + error_d; ierror_a += prev_error_a + error_a; double derror_d = error_d - prev_error_d; double derror_a = error_d - prev_error_a; geometry_msgs::Twist controller; controller.linear.x = Kx_p*error_d + Kx_i*error_d*dt + Kx_d*derror_d/dt; controller.angular.z = Kz_p*error_a + Kz_i*error_a*dt + Kz_d*derror_a/dt; prev_error_d = error_d; prev_error_a = error_a; _error[0] = error_d; _error[1] = error_a; return controller; } /* ******************************************************************************* * * GET ERRORS FOR COMPARE END OF MOTION * * * Description : get back the error of distance and angle * Func. Name : getError * Arguments : None * Returns : std::vector<double> * val[0] = error in distance * val[1] = error in angle * Notes : None ******************************************************************************* */ std::vector<double> pid::getError(void) { return _error; }
true
39fa3db106a5517878c10c732ba2b097177893da
C++
PanYicheng/PlanetSystem
/PlanetSystem/particle_generator.cpp
UTF-8
5,894
2.515625
3
[]
no_license
/******************************************************************* ** This code is part of Breakout. ** ** Breakout is free software: you can redistribute it and/or modify ** it under the terms of the CC BY 4.0 license as published by ** Creative Commons, either version 4 of the License, or (at your ** option) any later version. ******************************************************************/ #include "particle_generator.h" ParticleGenerator::ParticleGenerator(Shader shader, Texture2D texture, GLuint amount) : shader(shader), texture(texture), amount(amount) { this->init(); } void ParticleGenerator::Update(GLfloat dt, GLuint newParticles, glm::vec3 centerPos) { //std::cout <<"ParticleGenerator::Update "<< dt << std::endl; // Add new particles for (GLuint i = 0; i < newParticles; ++i) { int unusedParticle = this->firstUnusedParticle(); this->respawnParticle(this->particles[unusedParticle], centerPos); } // Update all particles for (GLuint i = 0; i < this->amount; ++i) { Particle &p = this->particles[i]; p.Life -= dt; // reduce life if (p.Life > 0.0f) { // particle is alive, thus update p.Position += p.Velocity * dt; p.Color.a -= dt * 2.5; GLfloat distance = glm::length(p.Position - centerPos); if (distance > 2.0f) { p.Visible = GL_TRUE; } } } } // Render all particles void ParticleGenerator::Draw() { // Use additive blending to give it a 'glow' effect glBlendFunc(GL_SRC_ALPHA, GL_ONE); //glDisable(GL_DEPTH_TEST); this->shader.Use(); for (Particle particle : this->particles) { if ( (particle.Life > 0.0f) && particle.Visible) { glm::mat4 model; model = glm::translate(model, particle.Position); model = glm::scale(model, glm::vec3(0.001f)); this->shader.SetMatrix4("model", model); this->shader.SetVector4f("color", particle.Color); //this->texture.Bind(); glBindVertexArray(this->VAO); glDrawElements(GL_TRIANGLE_STRIP, this->indexCount, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } } // Don't forget to reset to default blending mode glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //glm::mat4 model; //model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f)); //model = glm::scale(model, glm::vec3(0.5f)); //this->shader.SetMatrix4("model", model); //this->shader.SetVector4f("color", glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)); ////this->texture.Bind(); //glBindVertexArray(this->VAO); //glDrawElements(GL_TRIANGLE_STRIP, this->indexCount, GL_UNSIGNED_INT, 0); //glBindVertexArray(0); //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //glEnable(GL_DEPTH_TEST); } void ParticleGenerator::init() { // Set up mesh and attribute properties GLuint vbo, ebo; glGenVertexArrays(1, &this->VAO); glGenBuffers(1, &vbo); glGenBuffers(1, &ebo); std::vector<glm::vec3> positions; std::vector<unsigned int> indices; const unsigned int X_SEGMENTS = 32; const unsigned int Y_SEGMENTS = 32; const float PI = 3.14159265359; for (unsigned int y = 0; y <= Y_SEGMENTS; ++y) { for (unsigned int x = 0; x <= X_SEGMENTS; ++x) { float xSegment = (float)x / (float)X_SEGMENTS; float ySegment = (float)y / (float)Y_SEGMENTS; float xPos = std::cos(xSegment * 2.0f * PI) * std::sin(ySegment * PI); float yPos = std::cos(ySegment * PI); float zPos = std::sin(xSegment * 2.0f * PI) * std::sin(ySegment * PI); positions.push_back(glm::vec3(xPos, yPos, zPos)); } } bool oddRow = false; for (int y = 0; y < Y_SEGMENTS; ++y) { if (!oddRow) // even rows: y == 0, y == 2; and so on { for (int x = 0; x <= X_SEGMENTS; ++x) { indices.push_back(y * (X_SEGMENTS + 1) + x); indices.push_back((y + 1) * (X_SEGMENTS + 1) + x); } } else { for (int x = X_SEGMENTS; x >= 0; --x) { indices.push_back((y + 1) * (X_SEGMENTS + 1) + x); indices.push_back(y * (X_SEGMENTS + 1) + x); } } oddRow = !oddRow; } indexCount = indices.size(); std::vector<float> data; for (int i = 0; i < positions.size(); ++i) { data.push_back(positions[i].x); data.push_back(positions[i].y); data.push_back(positions[i].z); } glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(float), &data[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); float stride = (3) * sizeof(float); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (void*)0); glBindVertexArray(0); // Create this->amount default particle instances for (GLuint i = 0; i < this->amount; ++i) this->particles.push_back(Particle()); } // Stores the index of the last particle used (for quick access to next dead particle) GLuint lastUsedParticle = 0; GLuint ParticleGenerator::firstUnusedParticle() { // First search from last used particle, this will usually return almost instantly for (GLuint i = lastUsedParticle; i < this->amount; ++i) { if (this->particles[i].Life <= 0.0f) { lastUsedParticle = i; return i; } } // Otherwise, do a linear search for (GLuint i = 0; i < lastUsedParticle; ++i) { if (this->particles[i].Life <= 0.0f) { lastUsedParticle = i; return i; } } // All particles are taken, override the first one (note that if it repeatedly hits this case, more particles should be reserved) lastUsedParticle = 0; return 0; } void ParticleGenerator::respawnParticle(Particle &particle, glm::vec3 centerPos) { particle.Position = centerPos; particle.Color = RED_COLOR; particle.Life = 10.0f; particle.Visible = GL_FALSE; particle.Velocity = glm::vec3((rand() % 100) / 100.0f - 0.5f, (rand() % 100) / 100.0f - 0.5f, (rand() % 100) / 100.0f - 0.5f); particle.Acceleration = glm::vec3(0.0f); //particle.Velocity = randVelocity * 50.0f; }
true
bb250d5e6f481051e0ddd1b299a4a175ecc0ab02
C++
WorkingXXX/Jexer
/Test_Shader.cpp
UTF-8
2,032
2.546875
3
[]
no_license
#include <iostream> #include "JexerWindow.h" #include "JexerShaderProgramCreator.h" using namespace std; #pragma comment(lib, "OpenGL32.lib") #pragma comment(lib, "glfw3.lib") #pragma comment(lib, "glew32.lib") enum VAO_IDs { Triangles, NumVAOs }; enum Buffer_IDs { ArrayBuffer, NumBuffers }; enum Attrib_IDs { vPosition = 0 }; GLuint VAOs[NumVAOs]; GLuint Buffers[NumBuffers]; const GLuint NumVertices = 6; void Init() { glGenVertexArrays(NumVAOs, VAOs); glBindVertexArray(VAOs[Triangles]); GLfloat vertices[NumVertices][2] = { { -0.9, -0.9 }, { 0.85, -0.9 }, { -0.9, 0.85 }, { 0.9, -0.85 }, { 0.9, 0.9 }, { -0.85, 0.9 } }; glGenBuffers(NumBuffers, Buffers); glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); Jexer::JexerShader vertexShader(Jexer::JexerShaderType::JEXER_VERTEX_SHADER, "TestVertexShader.glsl"); Jexer::JexerShader pixelShader(Jexer::JexerShaderType::JEXER_PIXEL_SHADER, "TestPixelShader.glsl"); Jexer::JexerShaderSlot shaderSlot; shaderSlot.InsertShader(vertexShader); shaderSlot.InsertShader(pixelShader); Jexer::JexerShaderProgramCreator shaderPrgmCtr(shaderSlot); GLuint prgmId = shaderPrgmCtr.CreateShaderProgram(); shaderPrgmCtr.UseCurrentShaderProgram(); glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, static_cast<const void*>(0)); glEnableVertexAttribArray(vPosition); } void Display() { glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(VAOs[Triangles]); glDrawArrays(GL_TRIANGLES, 0, NumVertices); glFlush(); } //int main() //{ // if (glfwInit()) // { // Jexer::JexerWindow win(400, 400, "Test_Shader"); // // glfwMakeContextCurrent(win.GetHandle()); // // glewInit(); // // Init(); // // while (!glfwWindowShouldClose(win.GetHandle())) // { // // glClear(GL_COLOR_BUFFER_BIT); // // Display(); // // glfwSwapBuffers(win.GetHandle()); // glfwPollEvents(); // } // // glfwTerminate(); // // } // // glfwTerminate(); // system("pause"); //}
true
bdb49e594303ad9f7350f45bcb712c5bc13cff75
C++
santiago-iturriaga/cloud-cdn
/GlobeTraff/webproxysim/gdnode.h
UTF-8
714
2.90625
3
[]
no_license
//gdnode.h #ifndef GDNODE_H #define GDNODE_H #include <stdlib.h> class GDNode { public: GDNode(unsigned int initId, unsigned int initSize) //constructor { id = initId; size = initSize; right = NULL; } ~GDNode() {} //the destructor unsigned GetFileId() { return id; } unsigned GetFileSize() { return size; } GDNode* GetRight() { return right; } void SetRight(GDNode* initRight) { right = initRight; } void SetHValue(float initHValue) { HValue = initHValue; } float GetHValue() { return HValue; } unsigned GetHeapLoc() { return loc; } void SetHeapLoc(unsigned initLoc) { loc = initLoc; } private: unsigned id; unsigned size; unsigned loc; float HValue; GDNode *right; }; #endif
true
991350865719670f0a00316c9e0645737cc00dd8
C++
alisw/AliPhysics
/PWGCF/FEMTOSCOPY/AliFemto/AliFemtoV0Cut.h
UTF-8
1,482
2.734375
3
[]
permissive
/// /// \file AliFemtoV0Cut.h /// #ifndef AliFemtoV0Cut_hh #define AliFemtoV0Cut_hh #include "AliFemtoTypes.h" #include "AliFemtoV0.h" #include "AliFemtoXi.h" #include "AliFemtoParticleCut.h" /// \class AliFemtoV0Cut /// \brief The pure virtual base class for the V0 cut /// /// All V0 cuts must inherit from this one. /// class AliFemtoV0Cut : public AliFemtoParticleCut { public: AliFemtoV0Cut(); ///< default constructor. - Users should write their own AliFemtoV0Cut(const AliFemtoV0Cut& aCut); ///< copy constructor virtual ~AliFemtoV0Cut(); ///< destructor AliFemtoV0Cut& operator=(const AliFemtoV0Cut& aCut); ///< copy constructor virtual bool Pass(const AliFemtoV0* aV0) = 0; ///< true if V0 passes, false if not virtual bool Pass(const AliFemtoXi* aXi) = 0; ///< true if Xi passes, false if not virtual AliFemtoParticleType Type() { return hbtV0; }; virtual AliFemtoV0Cut* Clone() { return NULL; }; ///< WARNING - default implementation returns NULL #ifdef __ROOT__ /// \cond CLASSIMP ClassDef(AliFemtoV0Cut, 0); /// \endcond #endif }; inline AliFemtoV0Cut::AliFemtoV0Cut() { // no-op } inline AliFemtoV0Cut::AliFemtoV0Cut(const AliFemtoV0Cut& c): AliFemtoParticleCut(c) { // no-op } inline AliFemtoV0Cut::~AliFemtoV0Cut() { // no-op } inline AliFemtoV0Cut& AliFemtoV0Cut::operator=(const AliFemtoV0Cut& c) { if (this != &c) { AliFemtoParticleCut::operator=(c); } return *this; } #endif
true
f26f7376ffe8ce03dfe2ae9638ca0c0f57c06a5a
C++
SJSU-AD/FusionAD
/arduino/can_gateway/lib/ros_lib/geographic_msgs/GeoPath.h
UTF-8
2,334
2.546875
3
[ "MIT" ]
permissive
#ifndef _ROS_geographic_msgs_GeoPath_h #define _ROS_geographic_msgs_GeoPath_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "std_msgs/Header.h" #include "geographic_msgs/GeoPoseStamped.h" namespace geographic_msgs { class GeoPath : public ros::Msg { public: typedef std_msgs::Header _header_type; _header_type header; uint32_t poses_length; typedef geographic_msgs::GeoPoseStamped _poses_type; _poses_type st_poses; _poses_type * poses; GeoPath(): header(), poses_length(0), poses(NULL) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; offset += this->header.serialize(outbuffer + offset); *(outbuffer + offset + 0) = (this->poses_length >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->poses_length >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->poses_length >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->poses_length >> (8 * 3)) & 0xFF; offset += sizeof(this->poses_length); for( uint32_t i = 0; i < poses_length; i++){ offset += this->poses[i].serialize(outbuffer + offset); } return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; offset += this->header.deserialize(inbuffer + offset); uint32_t poses_lengthT = ((uint32_t) (*(inbuffer + offset))); poses_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); poses_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); poses_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->poses_length); if(poses_lengthT > poses_length) this->poses = (geographic_msgs::GeoPoseStamped*)realloc(this->poses, poses_lengthT * sizeof(geographic_msgs::GeoPoseStamped)); poses_length = poses_lengthT; for( uint32_t i = 0; i < poses_length; i++){ offset += this->st_poses.deserialize(inbuffer + offset); memcpy( &(this->poses[i]), &(this->st_poses), sizeof(geographic_msgs::GeoPoseStamped)); } return offset; } const char * getType(){ return "geographic_msgs/GeoPath"; }; const char * getMD5(){ return "1476008e63041203a89257cfad97308f"; }; }; } #endif
true
bcad00bedee903aeb9e2e34df02638c00904dab0
C++
matanaliz/ShellExt
/core/win/FileImpl.cpp
UTF-8
3,113
2.671875
3
[]
no_license
#include <sstream> #include <fstream> #include <Logger.h> #include <ThreadPool.h> #include "FileImpl.h" FileImpl::FileImpl(const std::wstring& path) : m_path(path) , m_date(L"") , m_size(0) , m_sizeKb(0) { } FileImpl::~FileImpl() { } unsigned long long FileImpl::computeSum() { unsigned long long sum = 0; std::ifstream fstr; try { fstr.open(m_path.c_str(), std::fstream::in | std::fstream::binary); if (fstr.is_open()) { while (!fstr.eof() && fstr.good()) { // Possible overflow. Change checksum to some other. char c; fstr.get(c); sum += static_cast<unsigned long>(c); } fstr.close(); } } catch (...) { // TODO Log exceptions with logger all over the project. } return sum; } //unsigned long FileImpl::LogInfo() //{ // std::wstringstream wss; // std::wstring spc(L"\t"); // wss.write(m_filePath.c_str(), m_filePath.size()); // wss.write(spc.c_str(), spc.size()); // wss.write(m_fileDate.c_str(), m_fileDate.size()); // wss.write(spc.c_str(), spc.size()); // wss.write(m_fileSize.c_str(), m_fileSize.size()); // wss.write(spc.c_str(), spc.size()); // // //Sum count thread pool test // //TODO: opend file by parts and feed to computeSumBuf // // //ThreadPool check // //ThreadPool tp(ThreadPool::THREAD_NUMBER); // //unsigned char a[3] = { 0, 1, 2 }; // //tp.enqueue(&FileImpl::computeSumBuf, this, &a[0], 3); // //tp.GetResult(); // // //computeSum is way too slow // wss << std::to_wstring(computeSum()); // Logger::GetInstance()->LogIt(wss.str()); // // return 0; //} const std::wstring& FileImpl::Date() { if (m_date.empty()) { WIN32_FILE_ATTRIBUTE_DATA fileInformation; if (0 != GetFileAttributesEx( m_path.c_str(), GET_FILEEX_INFO_LEVELS::GetFileExInfoStandard, &fileInformation)) { SYSTEMTIME lSystemTime; FILETIME ftCreationTime = fileInformation.ftCreationTime; if (0 != FileTimeToSystemTime(&ftCreationTime, &lSystemTime)) { wchar_t tmpDate[MAX_PATH + 1] = { '\0' }; if (0 != GetDateFormat( LOCALE_USER_DEFAULT, NULL, &lSystemTime, L"dd'.'MM'.'yyyy", tmpDate, ARRAYSIZE(tmpDate))) { std::wstringstream wss; wss << tmpDate; wchar_t tmpTime[MAX_PATH + 1] = { '\0' }; if (0 != GetTimeFormatEx( LOCALE_NAME_USER_DEFAULT, TIME_FORCE24HOURFORMAT, &lSystemTime, L"HH:mm:ss", tmpTime, ARRAYSIZE(tmpTime))) { wss << tmpTime; } m_date = wss.str(); } } } } return m_date; } const std::wstring& FileImpl::Path() { return m_path; } const unsigned long long FileImpl::Size() { if (0 == m_size) { WIN32_FILE_ATTRIBUTE_DATA fileInformation; if (0 != GetFileAttributesEx(m_path.c_str(), GET_FILEEX_INFO_LEVELS::GetFileExInfoStandard, &fileInformation)) { m_size = (static_cast<ULONGLONG>(fileInformation.nFileSizeHigh) << sizeof(fileInformation.nFileSizeLow) * 8) | fileInformation.nFileSizeLow; m_sizeKb = (m_size / 1024) == 0 ? 1 : m_size / 1024; } } return m_size; } const unsigned long long FileImpl::SizeKb() { if (0 == m_size) Size(); return m_sizeKb; }
true
a7c8333a873ea3b43e6ade787ea8e86b13d65a77
C++
kuangrenxuezhe/primary-election
/deps/include/util/coding_UT_List.h
UTF-8
5,399
2.796875
3
[]
no_license
// U_List.h #ifndef _UNIVERSAL_LIST_S_H_ #define _UNIVERSAL_LIST_S_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "UT_Allocator.h" #define max_val(a,b) (((a) > (b)) ? (a) : (b)) #define min_val(a,b) (((a) < (b)) ? (a) : (b)) template <class T_Key> struct _Node_List_S_ { _Node_List_S_* cpNext; T_Key tKey; }; template<class T_Key> inline long _DefaultCompareKey_List_(T_Key t1, T_Key t2) { return t1 - t2; } template<class T_Key> inline long _DefaultSaveNode_List_(_Node_List_S_<T_Key>* cpNode, FILE* fp) { fwrite(&cpNode->tKey, sizeof(T_Key), 1, fp); return 0; } template<class T_Key> inline long _DefaultLoadNode_List_(_Node_List_S_<T_Key>* cpNode, FILE* fp, void* vpArg) { fread(&cpNode->tKey, sizeof(T_Key), 1, fp); return 0; } template <class T_Key, class T_NodeType = _Node_List_S_<T_Key> > class U_List_S { public: U_List_S(); ~U_List_S(); T_NodeType* GetNode(); T_NodeType* AddNode(T_Key tKey); T_NodeType* SearchNode(T_Key tKey, long (__cdecl* _CompareKey)(T_Key, T_Key) = _DefaultCompareKey_List_); long SaveList(char* szpSaveFilename, long (__cdecl* _SaveNode)(T_NodeType*, FILE*) = _DefaultSaveNode_List_); long LoadList(char* szpLoadFilename, long (__cdecl* _LoadNode)(T_NodeType*, FILE*, void*) = _DefaultLoadNode_List_, void* vpArg = NULL); long GetNodeNum(); private: long m_lKeyNum; _Node_List_S_<T_Key>* m_cpHead; UT_Allocator<T_NodeType> m_tpAllocator; }; /************************************************************************/ /* U_List_S Implement */ /************************************************************************/ template <class T_Key, class T_NodeType> U_List_S<T_Key, T_NodeType>::U_List_S() { m_lKeyNum = 0; m_cpHead = NULL; } template <class T_Key, class T_NodeType> U_List_S<T_Key, T_NodeType>::~U_List_S() { } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T_Key, class T_NodeType> T_NodeType* U_List_S<T_Key, T_NodeType>::AddNode(T_Key tKey) { _Node_List_S_<T_Key>* cpNode = m_tpAllocator.Allocate(); if(cpNode == NULL) return NULL; cpNode->cpNext = m_cpHead; m_cpHead = cpNode; m_lKeyNum++; cpNode->tKey = tKey; return (T_NodeType*)cpNode; } template <class T_Key, class T_NodeType> T_NodeType* U_List_S<T_Key, T_NodeType>::GetNode() { _Node_List_S_<T_Key>* cpNode = m_cpHead; m_cpHead = m_cpHead->cpNext; m_lKeyNum--; return (T_NodeType*)cpNode; } template <class T_Key, class T_NodeType> T_NodeType* U_List_S<T_Key, T_NodeType>::SearchNode(T_Key tKey, long (__cdecl* _CompareKey)(T_Key, T_Key)) { _Node_List_S_<T_Key>* cpNode = m_cpHead; for(long i = 0; i < m_lKeyNum; i++) { if(_CompareKey(tKey, cpNode->tKey)) cpNode = cpNode->cpNext; else break; } if(i == m_lKeyNum) return NULL; return (T_NodeType*)cpNode; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T_Key, class T_NodeType> long U_List_S<T_Key, T_NodeType>::SaveList(char* szpSaveFilename, long (__cdecl* _SaveNode)(T_NodeType*, FILE*)) { FILE* fpSave = fopen(szpSaveFilename, "wb"); if(fpSave == NULL) return -1; if(fwrite(&m_lKeyNum, 4, 1, fpSave) != 1) { fclose(fpSave); return -1; } _Node_List_S_<T_Key>* cpNode = m_cpHead; for(long i = 0; i < m_lKeyNum; i++) { if(fwrite(&cpNode, 4, 1, fpSave) != 1) { fclose(fpSave); return -1; } if(_SaveNode(cpNode, fpSave)) { fclose(fpSave); return -1; } } cpNode = NULL; if(fwrite(&cpNode, 4, 1, fpSave) != 1) { fclose(fpSave); return -1; } fclose(fpSave); return 0; } template <class T_Key, class T_NodeType> long U_List_S<T_Key, T_NodeType>::LoadList(char* szpLoadFilename, long (__cdecl* _LoadNode)(T_NodeType*, FILE*, void*), void* vpArg) { FILE* fpLoad = fopen(szpLoadFilename, "rb"); if(fpLoad == NULL) return -1; long lNodeNum = 0; if(fread(&lNodeNum, 4, 1, fpLoad) != 1) { fclose(fpLoad); return -1; } m_cpHead = NULL; _Node_List_S_<T_Key>* cpNode = NULL; for(;;) { if(fread(&cpNode, 4, 1, fpLoad) != 1) { m_tpAllocator.FreeAllocator(); fclose(fpLoad); return -1; } if(cpNode == NULL) break; cpNode = m_tpAllocator.Allocate(); if(_LoadNode(cpNode, fpLoad, vpArg)) { m_tpAllocator.FreeAllocator(); fclose(fpLoad); return -1; } if(m_cpHead == NULL) m_cpHead = cpNode; else { cpNode->cpNext = m_cpHead; m_cpHead = cpNode; } m_lKeyNum++; } fclose(fpLoad); if(m_lKeyNum != lNodeNum) { m_tpAllocator.FreeAllocator(); return -1; } return 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T_Key, class T_NodeType> long U_List_S<T_Key, T_NodeType>::GetNodeNum() { return m_lKeyNum; } #endif // _UNIVERSAL_LIST_S_H_
true
47390e59939ef4097f87c2ddcce6c8059a3c9e3a
C++
ryannowen/TNAP
/Client/Light.hpp
UTF-8
2,064
2.828125
3
[]
no_license
#pragma once #include "Entity.hpp" #include "ExternalLibraryHeaders.h" namespace TNAP { struct SLightData { private: static unsigned int s_amountOfLightData; public: Transform m_transform; glm::vec3 m_colour{ 1, 1, 1 }; float m_intensity{ 1 }; virtual void sendLightData(const GLuint argProgram) { GLuint direction_id = glGetUniformLocation(argProgram, std::string("lightData[" + std::to_string(s_amountOfLightData) + "].m_direction").c_str()); glUniform3fv(direction_id, 1, glm::value_ptr(m_transform.getForwardAxis())); GLuint colour_id = glGetUniformLocation(argProgram, std::string("lightData[" + std::to_string(s_amountOfLightData) + "].m_colour").c_str()); glUniform3fv(colour_id, 1, glm::value_ptr(m_colour)); GLuint intensity_id = glGetUniformLocation(argProgram, std::string("lightData[" + std::to_string(s_amountOfLightData) + "].m_intensity").c_str()); glUniform1f(intensity_id, m_intensity); /// Increases amount of lights for next light sending s_amountOfLightData++; } static void sendAmountOfLights(const GLuint argProgram) { /// Create ID and then Sends data to shader as Uniform GLuint numOfLights_id = glGetUniformLocation(argProgram, "amountOfLightData"); glUniform1ui(numOfLights_id, s_amountOfLightData); s_amountOfLightData = 0; } }; class Light : public TNAP::Entity { protected: glm::vec3 m_colour{ 1, 1, 1 }; float m_intensity{ 1 }; public: Light(); ~Light(); virtual void update(const glm::mat4& parentTransform) override; virtual void saveData(std::ofstream& outputFile) override; inline virtual const EEntityType getEntityType() const { return EEntityType::eLight; } inline void setColour(const glm::vec3& argColour) { m_colour = argColour; } inline const glm::vec3& getColour() const { return m_colour; } inline void setIntensity(const float argIntensity) { m_intensity = argIntensity; } inline const float getIntensity() const { return m_intensity; } #if USE_IMGUI virtual void imGuiRenderProperties() override; #endif }; }
true
bff5cc5cb0e8bfe784a8cf77dc795b9004e22473
C++
mattytheb/C-Bjarne-Stroustrup-Exercises
/Chap 4/drill 4.7a.cpp
UTF-8
1,332
3.296875
3
[]
no_license
#include "std_lib_fac.h" int main() { double value = 0; double max = 0; double min = 0; double conv = 0; char unit = ' '; cout << "Enter a value followed by a unit; c, m, i or f: \n"; while (cin >> value >> unit) switch (unit) { case 'c': {conv = value;} break; case 'm': {conv = 100*value;} break; case 'i': {conv = 2.54*value;} break; case 'f': {conv = 12*2.54*value;} break; } if (min == 0 && max == 0) { min = conv; max = conv; cout << min << " centimetres" << " is the smallest so far.\n" << max << " centimetres" << " is the largest so far.\n"; } else { if (conv < min) { min = conv; cout << conv << " centimetres" << " is the smallest so far.\n" << max << " centimetres" << " is still the highest.\n"; } else { if (conv > max) { max = conv; cout << min << " centimetres" << " is still the smallest.\n" << max << " centimetres" << " is the largest so far.\n"; } else { cout << min << " centimetres" << " is still the lowest.\n" << max << " centimetres" << " is still the highest.\n"; } } } cout << "\nPlease enter another value and unit: "; }
true
942991022a1ada8141ad8c7dd879d3126a12eb8a
C++
ZongoForSpeed/ProjectEuler
/problemes/probleme390.cpp
UTF-8
1,226
3.140625
3
[ "MIT" ]
permissive
#include "problemes.h" #include "arithmetique.h" #include "utilitaires.h" #include "racine.h" typedef unsigned long long nombre; ENREGISTRER_PROBLEME(390, "Triangles with non rational sides and integral area") { // Consider the triangle with sides √5, √65 and √68. It can be shown that this triangle has area 9. // // S(n) is the sum of the areas of all triangles with sides √(1+b2), √(1+c2) and √(b2+c2) (for positive integers b // and c ) that have an integral area not exceeding n. // // The example triangle has b=2 and c=8. // // S(10^6) = 18018206. // // Find S(10^10). const nombre limite = 20'000'000'000ULL; nombre resultat = 0; for (nombre a = 2; a * a + 1 <= limite; a += 2) { nombre max_t = limite / (a * a + 1); for (nombre t = 2; t <= max_t; t += 2) { nombre s = a * a * t * t - a * a + t * t; auto v = racine::racine_carre<nombre>(s); if (v * v == s) { nombre b = a * t + v; nombre n = a * b + t; if (n > limite) break; resultat += n / 2; } } } return std::to_string(resultat); }
true
bb13096663fc65b4a94a2739186ab4c2619bc5e3
C++
JeonByeungGeol/BGIocpServer
/BGIOAcceptThread.h
UHC
604
2.546875
3
[]
no_license
#pragma once #include "BGIOThread.h" class BGIOObject; class BGIOAcceptThread : public BGIOThread { public: BGIOAcceptThread(HANDLE hAcceptEvent, BGIOObject* pServer); virtual ~BGIOAcceptThread(); /** ԼԴϴ.*/ virtual void Run(); /** 尡 ϱ ȣǴ ԼԴϴ.*/ virtual void OnTerminate(); protected: /** ù ° selectevent𵨿 ϴ ڵ ° ̺Ʈ */ HANDLE m_vHandle[2]; /** AcceptThread ü()Դϴ. */ BGIOObject* m_pObject; };
true
fd162dac49137ae3a47f3c014a4832d8fd8c99de
C++
zachng1/zftp
/utilities.cpp
UTF-8
478
2.6875
3
[]
no_license
#include "utilities.hpp" namespace ZUtil{ std::vector<std::string> stringSplit(std::string string, std::string delim) { std::vector<std::string> result; std::string token; size_t pos; while (!string.empty()) { pos = string.find(delim); if (pos == string.npos) { result.push_back(string); break; } result.push_back(string.substr(0, pos)); string = string.substr(pos+1); } return result; } }
true
9efb0951e4496c84e1ec9b3d08b17b1237990f3f
C++
qqbbtt/FlightNight
/Classes/GameEnemy.cpp
UHC
5,424
2.640625
3
[]
no_license
#include "GameEnemy.h" USING_NS_CC; /*Scene* GameEnemy::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = GameEnemy::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; }*/ // on "init" you need to initialize your instance bool GameEnemy::init() { ////////////////////////////// // 1. super init first if (!Layer::init()) { return false; } return true; } void GameEnemy::menuCloseCallback(Ref* pSender) { Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif } /*------------------------------------------------------------------------------------ | : setEnemy(float delta) | Ű : delta = | : | : ̴ |------------------------------------------------------------------------------------*/ void GameEnemy::setEnemy(float delta) { // x int start_x = PADDING_SCREEN + rand() % ((int)SizeW - PADDING_SCREEN * 2); int end_x = PADDING_SCREEN + rand() % ((int)SizeW - PADDING_SCREEN * 2); // Ʈ θ. auto sprEnemy = Sprite::create(); sprEnemy->setPosition(Point(start_x, SizeH)); layerScene->addChild(sprEnemy); // Ϳ ֱ Enemies.pushBack(sprEnemy); // ִϸ̼ auto texture = Director::getInstance()->getTextureCache()->addImage("game/Spaceship.png"); auto animation = Animation::create(); animation->setDelayPerUnit(0.1f); for (int i = 0; i<4; i++) { animation->addSpriteFrameWithTexture(texture, Rect((96*4)+(i % 4 * 96), 106 + i / 4 * 106, 96, 104)); } auto animate = Animate::create(animation); // action->setTag(TAG_MOVE_ACTION); sprEnemy->runAction(RepeatForever::create(animate)); // Ʒ ׼ auto action = Sequence::create(MoveTo::create(fSpeed, Point(end_x, -(SizeH))), CallFuncN::create(CC_CALLBACK_1(GameEnemy::resetEnemy, this)), NULL); sprEnemy->runAction(action); } /*------------------------------------------------------------------------------------ | : resetEnemy(Ref *sender) | Ű : sender = Ʈ | : | : Ʈ |------------------------------------------------------------------------------------*/ void GameEnemy::resetEnemy(Ref *sender) { auto sprEnemy = (Sprite*)sender; Enemies.eraseObject(sprEnemy); layerScene->removeChild(sprEnemy); } /*------------------------------------------------------------------------------------ | : initEnemy(cocos2d::Layer* lay) | Ű : lay = ȭ ̾ | : | : ȭ ̾ ʱȭ |------------------------------------------------------------------------------------*/ void GameEnemy::initEnemy(cocos2d::Layer* lay) { layerScene = lay; fSpeed = 5.0; // ڰ Ŭ õõ . Enemies.clear(); SizeW = Director::getInstance()->getWinSize().width; SizeH = Director::getInstance()->getWinSize().height; } /*------------------------------------------------------------------------------------ | : explosionEnemy(Ref *sender) | Ű : sender = 浹 Ʈ | : | : |------------------------------------------------------------------------------------*/ void GameEnemy::explosionEnemy(Ref *sender) { auto sprEnemy = (Sprite*)sender; auto particle = ParticleSystemQuad::create("game/explosion.plist"); particle->setPosition(sprEnemy->getPosition()); particle->setScale(0.5); layerScene->addChild(particle); auto action = Sequence::create( DelayTime::create(1.0), CallFuncN::create(CC_CALLBACK_1(GameEnemy::resetBoom, this)), NULL); particle->runAction(action); } /*------------------------------------------------------------------------------------ | : resetBoom(Ref *sender) | Ű : sender = Ʈ | : | : Ʈ ʱȭ |------------------------------------------------------------------------------------*/ void GameEnemy::resetBoom(Ref *sender) { auto particle = (ParticleSystemQuad*)sender; layerScene->removeChild(particle); } /*void GameEnemy::updateEnemy() { auto sprPlayer = (Sprite*)layerScene->getChildByTag(TAG_SPRITE_PLAYER); Rect rectPlayer = sprPlayer->getBoundingBox(); auto removeSpr = Sprite::create(); for (Sprite* sprItem : Items) { Rect rectItem = sprItem->getBoundingBox(); if (rectPlayer.intersectsRect(rectItem)) removeSpr = sprItem; } if (Items.contains(removeSpr)) { resetItem(removeSpr); isItem = true; layerScene->scheduleOnce(schedule_selector(GameItem::resetisItem), 5.0); } } void GameEnemy::resetisItem(float delta) { isItem = false; } bool GameEnemy::getisItem() { return isItem; } */ /*------------------------------------------------------------------------------------ | : getSprEnemies() | Ű : | : Vector<Sprite*> = vecor | : vecotr |------------------------------------------------------------------------------------*/ Vector<Sprite*> GameEnemy::getSprEnemies() { return Enemies; }
true
5a753fb18710ce62cc9b83cb34196c0d0bf69180
C++
Devansh-Sood/Stack_interviewbit
/area_histogram.cpp
UTF-8
1,909
3.015625
3
[]
no_license
int Solution::largestRectangleArea(vector<int> &A) { // stack<int> s; // int max_area = 0; // int tp; // int area_with_top; // int n=A.size(); // int i = 0; // while (i < n) // { // if (s.empty() || A[s.top()] <= A[i]) // s.push(i++); // else // { // tp = s.top(); // store the top index // s.pop(); // pop the top // // Calculate the area with hist[tp] stack // // as smallest bar // area_with_top = A[tp] * (s.empty() ? i : i - s.top() - 1); // if (max_area < area_with_top) // max_area = area_with_top; // } // } // while (s.empty() == false) // { // tp = s.top(); // s.pop(); // area_with_top = A[tp] * (s.empty() ? i : // i - s.top() - 1); // if (max_area < area_with_top) // max_area = area_with_top; // } // return max_area; stack<int>st; int i=0,e=0,area=0,max=0; int l=A.size(); while(i<l) { if(st.empty() || A[i]>=A[st.top()]) { st.push(i++); } else{ e=st.top(); st.pop(); if(st.empty()) { area=A[e]*i; } else { area=A[e]*(i-st.top()-1); } if(max<area) { max=area; } } } while(!st.empty()) { e=st.top(); st.pop(); if(st.empty()) { area=A[e]*i; } else { area=A[e]*(i-st.top()-1); } if(max<area) { max=area; } } return max; }
true
d43f8a32c148e75530eb80a4f927127b35b2d193
C++
graceli/DRsample
/source/manipulate_force_database.h
UTF-8
5,395
2.65625
3
[]
no_license
/* * This header file contains routines that are used by analyze_force_database and joinFDBs */ #include "force_database_class.h" #include "read_input_script_file.h" int read_in_database(const struct analysis_option_struct *opt, const struct script_struct *script, struct database_struct *db, const struct nominal_struct *nominal){ class force_database_class *database; int i,j; unsigned long size; database=new force_database_class(opt->title,1); database->get_header_information(db); if(db->Nrecords==0){ fprintf(stderr,"Error: the force database does not contain any records\n"); return 1; } if(db->Nadditional_data!=script->Nadditional_data){ fprintf(stderr,"Error: The forcedatabase has %u additional data types, while the input script specifies %u\n",db->Nadditional_data,script->Nadditional_data); return 1; } if(db->Nligands!=script->Nligands) { fprintf(stderr,"Error: the number of ligands in the database (%hhu) is not the number of ligands specified in the script file (%hhd)\n",db->Nligands,script->Nligands); return 1; } db->record_size=sizeof(record_struct)+(db->Nforces*db->Nligands+db->Nenergies+db->Nforces*db->Nadditional_data)*sizeof(float); size=db->Nrecords*db->record_size; fprintf(stderr,"The database size should be %lu excluding the header\n",size); /* if(size>MAX_DATABASE_SIZE){ fprintf(stderr,"The database is too big; only the first %.2fGB will be considered\n",MAX_DATABASE_SIZE/1000000); db->Nrecords=MAX_DATABASE_SIZE/db->record_size; size=db->Nrecords*db->record_size; fprintf(stderr,"Nrecords adjusted to %u\n",db->Nrecords); fprintf(stderr,"%lu bytes of the database will be considered\n",size); } */ if( (db->unsorted_record=(struct record_struct*)malloc(db->Nrecords*db->record_size))==NULL ){ fprintf(stderr,"Error: cannot allocated enough memory for the database\n"); return 1; } if( (db->record=(struct record_struct**)malloc((db->Nrecords+1)*sizeof(struct record_struct *)))==NULL ){ fprintf(stderr,"Error: cannot allocated enough memory for the database\n"); return 1; } fprintf(stderr,"Reading records"); for(i=0;i<db->Nrecords;i++){ database->read_record_to_given_memory(i,rec(i,db)); db->record[i]=rec(i,db); if( (i%1000)==999 ) fprintf(stderr,"."); fflush(stderr); } fprintf(stderr,"\n"); fprintf(stderr,"Quicksorting database... "); quicksort_database(db, 0, db->Nrecords-1); fprintf(stderr,"done.\n"); fprintf(stderr,"Removing duplicate records... "); for(i=0;i<db->Nrecords-1;i++){ if(compare_records(db->record[i],db->record[i+1])==0){ //void *memmove(void *s1, const void *s2, size_t n); //copies n bytes from the object pointed to by s2 into the object pointed to by s1 //Therefore this method copies over the second instance //There is an assumption that it is the first instance that was used... is this true? fprintf(stderr, "\nEliminating duplicate record at position %d ",i); memmove(db->record+i+1, db->record+i+2, ((int)db->Nrecords-i-2)*sizeof(struct record_struct *)); i--; db->Nrecords--; } } fprintf(stderr,"done.\n"); if(opt->sequence_number_limit>=0){ unsigned int count; fprintf(stderr,"Removing records with sequence numbers beyond the limit... "); for(i=0;i<db->Nrecords;i++) if(db->record[i]->sequence_number>opt->sequence_number_limit){ memmove(db->record+i, db->record+i+1, ((int)db->Nrecords-i-1)*sizeof(struct record_struct *)); i--; db->Nrecords--; count++; } fprintf(stderr,"removed %u records.\n",count); } fprintf(stderr,"Confirming new order... "); for(i=0;i<db->Nrecords-1;i++){ if(compare_records(db->record[i],db->record[i+1])!=-1){ fprintf(stderr,"There is a problem with the new order when comparing the following records:\n"); fprintf(stderr,"Record 1: replica number: %d sequence_number: %u\n",db->record[i]->replica_number,db->record[i]->sequence_number); fprintf(stderr,"Record 2: replica number: %d sequence_number: %u\n",db->record[i+1]->replica_number,db->record[i+1]->sequence_number); return 1; } } fprintf(stderr,"done.\n"); db->replica_offset=db->record[0]->replica_number; if(opt->writeDatabase){ // record_size=sizeof(record_struct)+(Nforces*Nligands+Nenergies+Nforces*Nadditional_data)*sizeof(float); FILE *f; int k; f=fopen(opt->writeDatabaseName,"w"); if(f==NULL){ fprintf(stderr,"Error: unable to open text database file for output, skipping\n"); return 1; } for(i=0;i<db->Nrecords;i++){ fprintf(f,"record: replica#: %d sequence#: %u w: %f w_nominal: %d\n",db->record[i]->replica_number,db->record[i]->sequence_number,db->record[i]->w,find_bin_from_w(db->record[i]->w,0,nominal,script)); if(opt->writeDatabaseFull){ for(j=0;j<db->Nforces*db->Nligands;j+=db->Nligands){ db->record[i]->generic_data[j]; if(db->Nligands==1) fprintf(f,"Force: %f\n",db->record[i]->generic_data[j]); else if(db->Nligands==2) fprintf(f,"Force: %f %f\n",db->record[i]->generic_data[j],db->record[i]->generic_data[j+1]); } if(db->Nadditional_data>0){ for(j=db->Nforces*db->Nligands;j<db->Nforces*db->Nligands+db->Nforces;j++){ fprintf(f,"Additional data: "); for(k=0;k<db->Nadditional_data;k++){ fprintf(f,"%f ",db->record[i]->generic_data[j+k*db->Nforces]); } fprintf(f,"\n"); } } } } fclose(f); } return 0; }
true
826577e5a6be7ebbe6581ec0122e1cd1e5b41a9d
C++
bryceroni9563/BYU-CS-236-Code
/Parameter.cpp
UTF-8
494
3
3
[]
no_license
#include "Parameter.h" Parameter::Parameter() { type = ""; value = ""; } Parameter::Parameter(string tokenType, string val) { type = tokenType; if (type == "STRING") isConstant = true; else isConstant = false; value = val; } string Parameter::getValue() { return value; } string Parameter::getType() { return type; } string Parameter::toString() { return value; } bool Parameter::constant() { return isConstant; }
true
daa888956838beee274a1f1df228738a170fb3c6
C++
JohnnyGuye/TPs
/TP_C++2/sources/TrafficData.h
UTF-8
2,379
2.984375
3
[]
no_license
/************************************************************************* TrafficData - description ------------------- start : 21 octobre 2015 copyright : (C) 2015 by Quentin "Johnny" Guye and Louis Mer *************************************************************************/ //---------- Interface of the class <TrafficData> (fichier TrafficData.h) ------ #if ! defined ( TRAFFICDATA_H ) #define TRAFFICDATA_H //------------------------------------------------------------------------ // Sumary of <TrafficData> // Keep the informations of an event //------------------------------------------------------------------------ class TrafficData { public: //---------------------------------------------------------------- Getters int GetYear(); // Return the integer corresponding to the year int GetMonth(); // Return the integer corresponding to the month (between 1 and 12) int GetDay(); // Return the integer corresponding to the day (between 1 and 31) int GetHour(); // Return the integer corresponding to the hour (between 0 and 23) int GetMinute(); // Return the integer corresponding to the minute (between 0 and 59) int GetDayWeek(); // Return the integer corresponding to the day of the week (between 1 and 7) char GetTrafficValue(); // Return the character corresponding to the state of the traffic (either V,J,R or N) //----------------------------------------------------- Constructors et Destructors TrafficData(int year,int month, int day, int hour, int minute, char trafficValue ); /* @param year : gives the year ** @param month : give the month ** @param day : gives the day ** @param hour : gives the hour ** @param minute : gives the minute ** @trafficValue : gives the degree of trafficjam for this Sensor (V,J,R or N) ** Create a new TrafficData and sets all the attributes'values to the corresponding parameter */ TrafficData(); //Create an empty TrafficData virtual ~TrafficData (); //The desctructor, there is nothing allocated protected: //----------------------------------------------------------------- Attributs int year; int month; int day; int hour; int minute; int dayWeek; char trafficValue; }; //----------------------------------------- Types dépendants de <TrafficData> #endif // TRAFFICDATA_H
true
f781ff4844d86b7a4722e869e75fd397fede16a3
C++
898311543/worship_stm32
/实验54 综合测试实验/NES/mapper/086.cpp
UTF-8
898
2.578125
3
[]
no_license
///////////////////////////////////////////////////////////////////// // Mapper 86 void NES_mapper86::Reset() { // set CPU bank pointers set_CPU_banks(0,1,2,3); set_PPU_banks(0,1,2,3,4,5,6,7); } void NES_mapper86::MemoryWriteSaveRAM(uint32 addr, uint8 data) { if(addr == 0x6000) { uint8 chr_bank = data & 0x03 | (data & 0x40) >> 4; uint8 prg_bank = (data & 0x30) >> 4; set_CPU_bank4(prg_bank*4+0); set_CPU_bank5(prg_bank*4+1); set_CPU_bank6(prg_bank*4+2); set_CPU_bank7(prg_bank*4+3); set_PPU_bank0(chr_bank*8+0); set_PPU_bank1(chr_bank*8+1); set_PPU_bank2(chr_bank*8+2); set_PPU_bank3(chr_bank*8+3); set_PPU_bank4(chr_bank*8+4); set_PPU_bank5(chr_bank*8+5); set_PPU_bank6(chr_bank*8+6); set_PPU_bank7(chr_bank*8+7); } } /////////////////////////////////////////////////////////////////////
true
d9feb63f85b99cbd7e363b4306de9f7d29122866
C++
hizani/ShittyEngine2D
/core/src/components/SpriteComponent.h
UTF-8
1,363
2.578125
3
[]
no_license
#ifndef SPRITECOMPONENT_H #define SPRITECOMPONENT_H #include <SDL2/SDL.h> #include "../TextureManager.h" #include "../AssetManager.h" #include "./TransformComponent.h" #include "../Animation.h" #include <vector> #include <string> class SpriteComponent : public Component { private: TransformComponent *transformComponent; //TransformComponent родительского объекта SDL_Texture *texture; //Текстура SDL_Rect sourceRectangle; //Источник SDL_Rect destinationRectangle; //координаты перемещения текстуры bool isAnimated; int numFrames; int animationSpeed; bool isFixed; std::map<std::string, Animation> animations; std::string currentAnimationName; unsigned int animationIndex = 0; public: SDL_RendererFlip spriteFlip = SDL_FLIP_NONE; SpriteComponent(std::string assetTextureId); SpriteComponent(std::string assetTextureId, bool isFixed); SpriteComponent(std::string asetTextureId, std::map<std::string, Animation> animations, bool isFixed); void SetTexture(std::string assetTextureId); void Play(std::string animationIndex); void Initialize() override; void Update(float deltaTime) override; void Render() override; }; #endif
true
8ec588e5d04ffe0d8f1ae1502afa5020b90d1fa7
C++
nikhiljha261/Algorithm
/BUCKET.cpp
UTF-8
1,289
2.890625
3
[]
no_license
// a[i]/(t+1) neighbour element class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& a, int k, int t) { int n=a.size(); int maxi=INT_MIN; for(int i=0;i<n;i++) { maxi=max(maxi,a[i]); } int sz=maxi/(t+1); vector<int> bucket(sz+1); for(int i=0;i<=sz;i++) { bucket[i]=-1; } int i=0; int j=i+k-1; while(j<n) { for(int t=i;t<=j;t++) { int x=a[i]/(t+1); if(bucket[x]!=-1) { return true; } else { bucket[x]=a[i]; } if(x>0) { if(bucket[x-1]!=-1 and bucket[x-1]-bucket[x]<=t) { return true; } } if(x<sz) { if(bucket[x+1]!=-1 and bucket[x+1]-bucket[x]<=t) { return true; } } } bucket[a[i]/(t+1)]=-1; i++; j++; } return false; } };
true
df8839fd1f1bf2f58a8c406fa55a366c09e065b2
C++
pedrojfs17/FEUP-MNUM
/Praticas/TP7/GaussJacobi.cpp
UTF-8
1,219
3.5
4
[]
no_license
#include <iostream> using namespace std; double first(double x2, double x3) { return (7 - x2 - x3) / 3; } double second(double x1, double x3) { return (4 - x1 - 2*x3) / 4; } double third(double x2) { return (5 - 2*x2) / 5; } int main() { double x1 = 0, x2 = 0, x3 = 0; double nextx1, nextx2, nextx3; //Gauss-Jacobi /*nextx1 = first(x2,x3); nextx2 = second(x1, x3); nextx3 = third(x2);*/ //Gauss-Seidel nextx1 = first(x2, x3); nextx2 = second(nextx1, x3); nextx3 = third(nextx2); int n = 1; cout << "N = " << n << endl; cout << x1 << " para " << nextx1 << endl; cout << x2 << " para " << nextx2 << endl; cout << x3 << " para " << nextx3 << endl << endl; while (abs(nextx1 - x1) > pow(10, -3) || abs(nextx2 - x2) > pow(10, -3) || abs(nextx3 - x3) > pow(10, -3)) { x1 = nextx1; x2 = nextx2; x3 = nextx3; n++; //Gauss-Jacobi /*nextx1 = first(x2, x3); nextx2 = second(x1, x3); nextx3 = third(x2);*/ //Gauss-Seidel nextx1 = first(x2, x3); nextx2 = second(nextx1, x3); nextx3 = third(nextx2); cout << "N = " << n << endl; cout << x1 << " para " << nextx1 << endl; cout << x2 << " para " << nextx2 << endl; cout << x3 << " para " << nextx3 << endl << endl; } }
true
d939f0b81286e155959c1f04ac61c14feaaeb77b
C++
bigplik/Arduino_mac
/REBREATHER_NEEDS/testy_menu_z_case/testy_menu_z_case_2_ino/testy_menu_z_case_2_ino.ino
UTF-8
2,240
2.8125
3
[]
no_license
const int buttonPin = 2; // the pin that the pushbutton is attached to int ocena1 = 1; // counter for the number of button presses int buttonState = 0; // current state of the button int lastButtonState = 0; void setup(){ Serial.begin(9600); pinMode(buttonPin, INPUT); } void loop(){ buttonState = digitalRead(buttonPin); if (buttonState != lastButtonState) { // if the state has changed, increment the counter if (buttonState == HIGH) { // if the current state is HIGH then the button // wend from off to on: ocena1++; Serial.println("on"); //Serial.print("number of button pushes: "); Serial.println(ocena1); } else {} } lastButtonState = buttonState; //int menu; // menu = buttonPushCounter; int ocena = ocena1; int cena; /* if(menu == 1){ ocena = 1; }else if(menu == 2){ ocena = 2; }else if(menu == 3){ ocena = 3; }else if(menu == 4){ ocena = 4; }else if(menu == 5){ ocena = 5; }else if(menu == 6){ ocena = 6; }else if(menu == 7){ ocena = 7; */ if(ocena1 > 7){ ocena = 1; ocena1 =1; } else if(ocena == 3){ cena = 'A'; }else if(ocena == 4){ ocena = 3; cena = 'B'; } switch(ocena){ case 1: Serial.println("SWITCH: Jedynka\n"); break; case 2: Serial.println("SWITCH: Dwójka\n"); break; case 3: switch(cena){ case 'A': Serial.println("SWITCH: A"); break; case 'B': Serial.println("SWITCH: B"); break; default: Serial.println("SWITCH: Nieznana ocena\n"); } break; case 5: Serial.println("SWITCH: Czwórka\n"); break; case 6: Serial.println("SWITCH: Piątka\n"); break; case 7: Serial.println("SWITCH: Szóstka\n"); break; default: ocena = 1; } delay(500); }
true
c1e50098171c3b509797a8ca3c946f4a2fc14cf3
C++
ALasib/Algorithms
/lazy propagation.cpp
UTF-8
1,578
3.015625
3
[]
no_license
#include<bits/stdc++.h> #define mx 100015 int arr[mx]; using namespace std; struct info { int prop; int sum; }tree[4*mx]; void init(int node,int b,int e) { if(b==e) { tree[node].sum=arr[b]; tree[node].prop=0; return; } int left=node<<1; int right=left+1; int mid=(b+e)>>1; init(left,b,mid); init(right,mid+1,e); tree[node].sum=tree[left].sum+tree[right].sum; tree[node].prop=0; } void update(int node,int b,int e,int i,int j,int x) { if(i>e || j<b) return; if(b>=i && e<=j) { tree[node].sum+=(e-b+1)*x; tree[node].prop+=x; return; } int left=node<<1; int right=left+1; int mid=(b+e)>>1; update(left,b,mid,i,j,x); update(right,mid+1,e,i,j,x); tree[node].sum=tree[left].sum+tree[right].sum+(e-b+1)*tree[node].prop; } int query(int node,int b,int e,int i,int j,int carry) { if(i>e || j<b) return 0; if(b>=i && e<=j) return tree[node].sum+(e-b+1)*carry; int left=node<<1; int right=left+1; int mid=(b+e)>>1; int p1=query(left,b,mid,i,j,carry+tree[node].prop); int p2=query(right,mid+1,e,i,j,carry+tree[node].prop); return p1+p2; } int main() { int n,carry = 0; cout<<"Enter how many number in an array:"<<endl; cin>>n; cout<<"Please insert the elements:"<<endl; for(int i=0;i<n;i++) cin>>arr[i]; init(1,0,n-1); update(1,0,n-1,0,6,6); update(1,0,n-1,1,1,2); update(1,0,n-1,0,3,7); cout<<query(1,0,n-1,0,1,carry)<<endl; return 0; }
true
21057ab2c464d0bfb42a3d001622303d9a71ab48
C++
notorious94/UVa-solution
/11332 UVA.cpp
UTF-8
611
2.8125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; char digit[5000]; int sum() { int sum=0; for(int i=0;digit[i]!='\0';i++) sum+=(digit[i]-'0'); sprintf(digit,"%d",sum); return sum; } int main() { //freopen("d:\\in.txt", "r", stdin); //freopen("d:\\out.txt", "w", stdout); int s; while(scanf("%s", &digit)) { if(!strcmp(digit,"0")) break; if(strlen(digit)==1) { printf("%s\n",digit); continue; } while(strlen(digit)>1) s=sum(); printf("%d\n",s); } return 0; }
true
dca23845009e82a75b61d928756487945ff07f2d
C++
allenfromu/Spreadsheet
/Client/server.cpp
UTF-8
2,914
2.734375
3
[]
no_license
#include <stdio.h> #include <iostream> #include <stdlib.h> #include <cstdlib> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <pthread.h> using namespace std; int equal(char *first, char* second){ cout<<first[0]<<endl; cout<<second[0]<<endl; if(first[0] != second[0]) return 0; while(first[0] != '\0' && second[0]!='\0'){ cout<<first[0]<<endl; cout<<second[0]<<endl; first++; second++; if(first[0] + 1== 14 && second[0] + 1== 1) return 1; if(first[0] != second[0] ){ cout<<first[0]+1<<endl; cout<<second[0]+1<<endl; return 0;} } cout<<"here"<<endl; return 1; } void error(const char *msg) { perror(msg); exit(1); } void *client(void *clisock){ int *newsockfd = (int *)clisock; while(1){ char buffer[256]; int n; bzero(buffer,256); n = read(*newsockfd,buffer,255); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\n",buffer); char logout[9] ="log out\0"; if(equal(buffer, logout)) break; n = write(*newsockfd,"I got your message",18); if (n < 0) error("ERROR writing to socket"); } close(*newsockfd); exit(1); } static int temp = 444444444; int main(int argc, char *argv[]){ //port number should be passed from argv if(argc != 2){ cout<<"arguments should pass in host and port number."<<argc<<endl; return 1; } //create socket int sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd < 0) error("ERROR opening socket."); struct sockaddr_in serv_addr, cli_addr; socklen_t clilen; int portno, newsockfd; //set struct buffer to all 0 bzero((char *) &serv_addr, sizeof(serv_addr)); //convert port number to int portno = atoi(argv[1]); //configure sockadd_in struct serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) error("ERROR on binding"); //set number of requests in the queue listen(sockfd,5); clilen = sizeof(cli_addr); pthread_t threads[5]; int i = 0; while(1){ cout<<"Waiting for connection"<<endl; newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr,&clilen); if (newsockfd < 0) error("ERROR on accept"); /* int rc = pthread_create(&threads[i],NULL,client,(void *)&newsockfd); if(rc) error("thread fail");*/ char buffer[256]; int n; bzero(buffer,256); n = read(newsockfd,buffer,255); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\n",buffer); cout<<temp<<endl; n = write(newsockfd,"I got your message",18); if (n < 0) error("ERROR writing to socket"); close(newsockfd); //exit(1); } close(sockfd); return 0; }
true
8823a4863165e0c8882349cb961daa79769a2bf4
C++
smhx/codelib
/data_structures/range_bit.cpp
UTF-8
1,110
3.6875
4
[]
no_license
#include <bits/stdc++.h> using namespace std; template <typename T> struct bit { vector<T> b; bit() { } bit(int N) { b = vector<T>(N + 5); } // Returns the sum of all elements in the range [1, x] T sum(int x) { T res = 0; for (; x; x -= x & -x) res += b[x]; return res; } // Adds v to the element at index x void update(int x, T v) { for (; x < b.size(); x += x & -x) b[x] += v; } void reset() { fill(b.begin(), b.end(), 0); } }; template <typename T> struct range_bit { bit<T> m, b; range_bit(int N) { m = bit(N + 5); b = bit(N + 5); } // adds v to each element in [l, r] void update(int l, int r, T v) { m.update(l, v); b.update(l, -v * (l - 1)); m.update(r + 1, -v); b.update(r + 1, v * r); } // returns the sum of each element in [1, x] T sum(int x) { return m.sum(x) * x + b.sum(x); } // returns the sum of each element in [l, r] T sum(int l, int r) { return sum(r) - sum(l - 1); } };
true
a590eed2a5d63dc616124abf514ec9ec5d91aff5
C++
AH911UA/CPP_Again
/Day11/main.cpp
UTF-8
2,705
3.6875
4
[]
no_license
#include <iostream> #include <string> #include <algorithm> bool IsPolindrom(std::string); int qVowels(std::string); std::string GetUpperString(std::string); std::string LineWithSpace(const std::string[], const int sizeArray); int GoodDay(const std::string); int main() { std::cout << " Enter the string 1 : "; std::string pol; getline(std::cin, pol); std::cout << (IsPolindrom(pol) == false ? "not polindrom" : "polindrom") << std::endl; std::cout << "_________________\n"; std::cout << " Enter the string 2 : "; std::string vowels; getline(std::cin, vowels); std::cout << "Vowels [a][e][i][o][u]: " << qVowels(vowels) << std::endl; std::cout << "_________________\n"; std::cout << " 1/2 upper symb : " << GetUpperString(vowels) << std::endl; std::cout << "_________________\n"; const int sizeArray = 4; std::string lines[sizeArray] = {"I", "LOVE", "STD", "String"}; std::cout << "Line with space : " << LineWithSpace(lines, sizeArray) << std::endl; std::cout << "_________________\n"; std::string line = "Good day String! Today is beautiful!"; std::cout << " sybm \"a\" : " << GoodDay(line) << std::endl; std::cout << "_________________\n"; return 0; } bool IsPolindrom(std::string pol) { auto its = pol.begin(); auto itend = pol.end() - 1; for(size_t i = 0; i < pol.length() / 2; i++) if(*(its++) != *(itend--)) return false; return true; } int qVowels(std::string word) { int count = 0; size_t next = 0; std::transform(word.begin(), word.end(), word.begin(), ::tolower); char arr[] = "aeiou"; for (int i = 0; i < 5; i++) { next = 0; while (next != std::string::npos) { if((next = word.find(arr[i], next)) == std::string::npos) break; count++; next ++; } } return count; } std::string GetUpperString(std::string str) { std::string tmpStr = str; for (size_t i = 0; i < str.length() - 1; i++) if(i % 2) std::transform(str.begin() + i, str.begin() + (i + 1), tmpStr.begin() + i, ::toupper); return tmpStr; } std::string LineWithSpace(const std::string str[], const int sizeArray) { std::string result = ""; for(size_t i = 0; i < sizeArray; i++) result += str[i] + " "; return result; } int GoodDay(const std::string str) { int count = 0; for (size_t i = 0; i < str.length(); i++) { size_t j = str.find("a", i); if(j != std::string::npos) { count ++; i += j; } } return count; }
true
6657883d6a58a26591ad4f24b44e9fa69b2568b6
C++
ellaprogrammer/binaryHeap
/priorityqueue.cpp
UTF-8
7,181
3.625
4
[]
no_license
/** * ECS 60 -- Project 2 * Max PriorityQueue Class IMPLEMENTATION * Author: Kevin Trujillo && Ella Queen * * Implemented as an array-based binary heap with the root node at index 1 of the array. * The keys are non-negative integers */ #include "priorityqueue.h" #include <iostream> priorityqueue::priorityqueue(int max_Size) { heap_size = 1; harr = new int[max_Size]; harr[0] = 10000000; } int priorityqueue::parent(int i) { if (i == 2){ return 1; } else{ return (i)/2; } } // to get index of left child of node at index i int priorityqueue::left(int i) { return (2*i + 0); } // to get index of right child of node at index i int priorityqueue::right(int i) { return (2*i + 1); } bool priorityqueue::parentBool(int i) { //false if root if (i == 1) { //if parent is root return false; } else { return true; } } // to get index of left child of node at index i bool priorityqueue::leftBool(int i) { if ((2*i + 0) > heap_size){ //no left child return false; } else { return true; } } // to get index of right child of node at index i bool priorityqueue::rightBool(int i) { if ((2*i + 1) > heap_size){ //no right child return false; } else{ return true; } } //FUNCTIONS TO CHANGE THE PQ----------------------------------- void priorityqueue::insert(int k){ if(heap_size == max_Size){ std::cout<< "PriorityQueue::insert called on full priority queue" << std::endl; return; } int i = heap_size ; harr[i] = k ; if (heap_size > 1){ heapifyDown(1); //heapifyUp(heap_size) ; } if (k > harr[1] || parentBool(i) == true){ //if max is being inserted heapifyUp(i); //heapifyDown(1); } heap_size++; } void priorityqueue::removeMax(){ //std::cout << "heap_size before remove max: " << heap_size << std::endl; //std::cout << "heap size: " << heap_size << std::endl; for (int i = 1; i < heap_size; i++){ harr[i] = harr[i + 1]; //move all the values over to replace the root node } //harr[1]=harr[heap_size]; heap_size--; heapifyDown(1); //std::cout << "heap_size after remove max: " << heap_size << std::endl; } void priorityqueue::removeKey(int v) { //std::cout << "heap_size before remove key: " << heap_size << std::endl; bool found = false; for (int i = 1; i <= heap_size; i++){ if(harr[i] == v) { found = true; if (i == heap_size){ heap_size--; i--; return; } else { for (int j = i; j < heap_size; j++){ harr[j] = harr[j + 1]; } heap_size--; i--; if (leftBool(i) == true || rightBool(i) == true){ heapifyDown(i); } if (parentBool(i) == true){ heapifyUp(i); } } } } /*bool found = false ; for(int i = 1; i <= heap_size ; ++i){ //possible seg fault if (harr[i] == v ){ found = true; if (i == heap_size){ heap_size--; return; } for(int j = i ; j < heap_size; ++j){ harr[j] = harr[j+1]; } if (((i*2) <= heap_size && rightBool(i) == true) || (leftBool(i) == true && ((i*2)+1) <= heap_size)){ heapifyDown(1); } if (i > 1 && harr[i] > harr[i / 2] && i <= heap_size){ heapifyUp(i); } heap_size--; } //heapifyDown(1) ; //std::cout << "heap_size after remove key: " << heap_size << std::endl; }*/ if(!found){ std::cout<< "PriorityQueue::removeKey " << v << " not found" << std::endl; } } void priorityqueue::change(int k, int newK){ bool found = false ; for(int i = 1; i <= heap_size ; ++i){ //possible seg fault if (harr[i] == k ){ found = true; harr[i] = newK ; if (rightBool(i) == true || leftBool(i) == true){ heapifyDown(1); } if (parentBool(i) == true){ heapifyUp(i); } } } if(!found){ std::cout<< "PriorityQueue::change key " << k << " not found" << std::endl; return; } } void priorityqueue::heapifyDown(int k) { //heapify Down int l = left(k); int r = right(k); int maximum = k; if (leftBool(k) == true && l < heap_size && l >= 0 &&harr[l] > harr[maximum]){ //changed this back to max maximum = l; } if (rightBool(k) == true&& r < heap_size && r >= 0 && harr[r] > harr[maximum]){ maximum = r; } if (maximum != k){ //std::swap(harr[k], harr[maximum]); //std::cout << "inside swap for heapify down" << std::endl; int temp = harr[k]; harr[k] = harr[maximum]; harr[maximum] = temp; heapifyDown(maximum); } } void priorityqueue::heapifyUp (int k){ if(parentBool(k) == true){ // If-Statment checks if node at index k and its parent violates the heap property if(harr[parent(k)] < harr[k] && k != 1){ // if true, swaps the two //std::swap(harr[k], harr[parent(k)]) ; //std::cout << "inside swap for heapify up" << std::endl; // std::cout << "paretn: " << parent(k) << std::endl; int temp = harr[k]; harr[k] = harr[parent(k)]; harr[parent(k)] = temp; // then recursivly calls heapifyUP passing the parent node heapifyUp(parent(k)) ; } } } int priorityqueue::get(int k) { return harr[k]; } void priorityqueue::printJSON(){ } /* COMMENTED OUT SO WE CAN USE PRIORITY QUEUEUEUEUE IN BUILDHEAP int main(){ priorityqueue pq(10); pq.insert(8); pq.insert(24); pq.insert(15); pq.insert(678); pq.insert(50); pq.insert(128); std::cout << pq.get(1) << std::endl; std::cout << pq.get(2) << std::endl; std::cout << pq.get(3) << std::endl; std::cout << pq.get(4) << std::endl; std::cout << pq.get(5) << std::endl; std::cout << pq.get(6) << std::endl << std::endl; pq.removeMax(); std::cout << pq.get(1) << std::endl; std::cout << pq.get(2) << std::endl; std::cout << pq.get(3) << std::endl; std::cout << pq.get(4) << std::endl; std::cout << pq.get(5) << std::endl << std::endl; pq.removeKey(128); std::cout << pq.get(1) << std::endl; std::cout << pq.get(2) << std::endl; std::cout << pq.get(3) << std::endl; std::cout << pq.get(4) << std::endl; //std::cout << pq.get(5) << std::endl << std::endl; pq.change(15,60); std::cout << std::endl<< pq.get(1) << std::endl; std::cout << pq.get(2) << std::endl; std::cout << pq.get(3) << std::endl; std::cout << pq.get(4) << std::endl; } */
true
9aa84e5c9ee23f584a1d7cc5459ce31d8e946742
C++
Pranshu258/SkylineQuery_Algorithms
/src/bnl.cpp
UTF-8
5,842
2.953125
3
[]
no_license
// Implements the Block Nested Loop Algorithm for Skyline Queries // Author: Pranshu Gupta #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <ctime> #include <list> #include <chrono> using namespace std; using namespace std::chrono; struct point { int* attributes; double timestamp; int index; }; void stupid_print (list<point> data) { for (list<point>::iterator p = data.begin(); p != data.end(); p++) { cout << (*p).index << " "; } cout << endl; return; } int main(int argc, char *argv[]) { if (argc != 3) { cout << "Usage: ./bnl data query" << endl; exit(0); } // Input file: data.txt ifstream infile(argv[1]); int N, D, index, win_size; infile >> N >> D; ifstream infile1(argv[2]); string line1, line2; // Read the Query Dimensions from the query.txt file getline(infile1, line1); stringstream ss1(line1); vector<int> dims; for(int i = 0; ss1 >> i; ) { dims.push_back(i); } // Read the Window size from the query.txt file getline(infile1, line2); stringstream ss2(line2); ss2 >> win_size; // Read data from file and create the lst of data list<point> data; list<point> original_data; bool *skyline = new bool[N]; for (int i = 0; i < N; ++i) { infile >> index; if (index == i+1) { // Read the dimensions now and put them in the vector point *p = new point; p->attributes = new int[D]; for (int j = 0; j < D; j++) { int val; infile >> val; p->attributes[j] = val; } p->timestamp = N*N; p->index = index; data.push_back(*p); original_data.push_back(*p); } else { cout << "Invalid Data" << endl; exit(0); } } // Print the Data // int c = 1; // for (list<point>::iterator p = data.begin(); p != data.end(); p++) { // // *p contains the current point // cout << "[" << c << "]: "; // for (vector<int>::iterator v = (*p).attributes.begin(); v != (*p).attributes.end(); v++) { // cout << *v << " "; // } // cout << endl; // c++; // } high_resolution_clock::time_point t1 = high_resolution_clock::now(); // BLOCK NESTED LOOP ALGORITHM FOR SKYLINES ////////////////////////////////////////////////////////////////////////////// // NOW WE CAN START FINDING THE SKYLINES int comparisons = 0;; list<point> skyline_window; while (!data.empty()) { list<point> temp_data; //cout << "Data: " << endl; //stupid_print(data); for (list<point>::iterator p = data.begin(); p != data.end(); p++) { bool not_skyline = false; list<point>::iterator swp = skyline_window.begin(); while (swp != skyline_window.end()) { int equalorworse = 0, worse = 0; int equalorbetter = 0, better = 0; for (vector<int>::iterator k = dims.begin(); k != dims.end(); ++k) { if ((*p).attributes[*k - 1] > (*swp).attributes[*k - 1]) { worse += 1; } else if ((*p).attributes[*k - 1] == (*swp).attributes[*k - 1]) { equalorworse += 1; equalorbetter += 1; } else if ((*p).attributes[*k - 1] < (*swp).attributes[*k - 1]) { better += 1; } } if (equalorworse + worse == dims.size() && worse > 0) { not_skyline = true; } if (equalorbetter + better == dims.size() && better > 0) { // remove swp from the window //cout << "Removed " << (*swp).index << " from Skyline window, dominated by: " << (*p).index << endl; swp = skyline_window.erase(swp); comparisons += 1; continue; } comparisons += 1; swp++; } // if not_skyline is still false, try to insert this point in the skyline window if (!not_skyline) { if (skyline_window.size() < win_size) { // get the timestamp and push in the skyline data (*p).timestamp = comparisons; skyline_window.push_back(*p); //cout << "Inserted " << (*p).index << " in Skyline window. Time: " << (*p).timestamp << endl; } else { // get the timestamp and put in the temp data (*p).timestamp = comparisons; temp_data.push_back(*p); //cout << "Inserted " << (*p).index << " in temp_data. Time: " << (*p).timestamp << endl; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //stupid_print(skyline_window); // mark the skyline points list<point>::iterator swp = skyline_window.begin(); while (swp != skyline_window.end()) { //cout << "Size of Skyline Window: " << skyline_window.size() << endl; if (skyline_window.size() > 0) { if ((*swp).timestamp < (temp_data.front()).timestamp || temp_data.size() == 0) { //cout << "Removing " << swp->index << " from window as valid skyline" << endl; if (swp->index <= N) { skyline[(swp->index)-1] = true; swp = skyline_window.erase(swp); continue; } else { cout << "Something went wrong" << endl; } } else { break; } } else { break; } swp++; } //cout << "-------------------------------------------" << endl; data = temp_data; temp_data.clear(); } ///////////////////////////////////////////////////////////////////////////// high_resolution_clock::time_point t2 = high_resolution_clock::now(); duration<double> time_span = duration_cast<duration<double>>(t2 - t1); cout << "Skyline Points: " << endl; int printed = 0; for (int i = 0; i < N; i++) { if (skyline[i]) { cout << i+1 << "\t"; printed += 1; if (printed % 10 == 0) cout << endl; } } cout << endl; cout << "Number of skyline points: " << printed << endl; cout << "Number of comparisons: " << comparisons << endl; cout << "Time taken: " << time_span.count() << " seconds" << endl; return 0; }
true
894d1a7420efb787471d6fbc28e6a73ac5681bd0
C++
xzrunner/uniaudio
/include/uniaudio/Source.h
UTF-8
1,291
2.84375
3
[ "MIT" ]
permissive
#ifndef _UNIAUDIO_SOURCE_H_ #define _UNIAUDIO_SOURCE_H_ #include <cu/uncopyable.h> #include <memory> namespace ua { class Decoder; class Source : private cu::Uncopyable { public: Source(); Source(const Source&); Source(const Decoder& decoder); virtual ~Source() {} virtual std::shared_ptr<Source> Clone() = 0; virtual bool Update() = 0; virtual void Play() = 0; virtual void Stop() = 0; virtual void Pause() = 0; virtual void Resume() = 0; virtual void Rewind() = 0; virtual void Seek(float offset) = 0; virtual float Tell() = 0; void SetOffset(float offset) { m_offset = offset; } float GetOffset() const { return m_offset; } void SetDuration(float duration) { m_duration = duration; } float GetDuration() const { return m_duration; } void SetFadeIn(float time) { m_fade_in = time; } float GetFadeIn() const { return m_fade_in; } void SetFadeOut(float time) { m_fade_out = time; } float GetFadeOut() const { return m_fade_out; } void SetOriVolume(float volume) { m_ori_volume = volume; } float GetOriVolume() const { return m_ori_volume; } float GetCurrVolume() const { return m_curr_volume; } protected: float m_offset, m_duration; float m_fade_in, m_fade_out; float m_ori_volume, m_curr_volume; }; // Source } #endif // _UNIAUDIO_SOURCE_H_
true
9192c93c6f8a5047d9f062cc965ad77503be1d34
C++
ksw1220/BOJ-Problem-Solving
/2467.cpp
UTF-8
845
2.8125
3
[]
no_license
#include <stdio.h> #include <vector> #define MAX 2000000000 using namespace std; vector<int> arr; int ansLeft, ansRight, opt = MAX; int isOptimal(int left, int right) { int re; int now = re = arr[left] + arr[right]; if (now < 0) now *= -1; if (opt > now) { opt = now; ansLeft = left; ansRight = right; } return re; } int main() { int N; scanf("%d", &N); arr.assign(N, 0); int left = 0, right = N - 1; for (int i = 0; i < N; i++) { scanf("%d", &arr[i]); } while (left < right) { int tmp = isOptimal(left, right); if (tmp == 0) { break; } else if (tmp < 0) left++; else right--; } printf("%d %d\n", arr[ansLeft], arr[ansRight]); return 0; }
true
466340fc0b832f13238b85937bd46e6e11c8ea0d
C++
Abbabara/Verkefni-2
/VerklegtNamskeid_vikuv2/src/models/employee.cpp
UTF-8
413
3.515625
4
[]
no_license
#include "employee.h" Employee::Employee(string name, string ssn){ this->name = name; this->ssn = ssn; } string Employee::get_name(){ return this->name; } string Employee::get_ssn(){ return this->ssn; } ostream& operator << (ostream& out, Employee& employee){ out << "Name: " << employee.name << endl << "Ssn: " << employee.ssn << endl; return out; }
true
16dc19c3a47c3f3b6994187bd10d8dd6779d93ec
C++
JmirY/Playground
/include/playground/object.h
UTF-8
1,995
2.78125
3
[ "MIT" ]
permissive
#ifndef OBJECT_H #define OBJECT_H #include "geometry.h" #include "physics/body.h" #include "physics/collider.h" #include "graphics/opengl/glm/glm.hpp" #include "graphics/shape.h" /* 전방 선언 */ class Playground; class Object { public: friend class Playground; protected: unsigned int id; Geometry geometry; physics::RigidBody* body; physics::Collider* collider; glm::vec3 color; graphics::Shape* shape; bool isSelected; bool isFixed; public: Object() : isSelected(false), isFixed(false) {} virtual ~Object() {}; unsigned int getID() const { return id; } Geometry getGeometry() const { return geometry; } glm::vec3 getColor() const { return color; } bool getIsSelected() const { return isSelected; } bool getIsFixed() const { return isFixed; } void getPositionInArray(float (&array)[3]) const; void getVelocityInArray(float (&array)[3]) const; void getRotationInArray(float (&array)[3]) const; void getAccelerationInArray(float (&array)[3]) const; void getMassInArray(float (&array)[3]) const; virtual void getGeometricDataInArray(float (&array)[3]) const = 0; /* 구의 반지름 또는 직육면체의 half-size 를 설정한다 */ virtual void setGeometricData(double, ...) = 0; /* 도형의 속성값에 따라 강체, 충돌체, Shape 의 데이터를 갱신한다 */ virtual void updateDerivedData() = 0; }; class SphereObject : public Object { protected: float radius; public: SphereObject() : radius(1.0f) {} void getGeometricDataInArray(float (&array)[3]) const; void setGeometricData(double, ...); void updateDerivedData(); }; class BoxObject : public Object { protected: float halfX; float halfY; float halfZ; public: BoxObject() : halfX(0.5f), halfY(0.5f), halfZ(0.5f) {} void getGeometricDataInArray(float (&array)[3]) const; void setGeometricData(double, ...); void updateDerivedData(); }; #endif // OBJECT_H
true
9b57584fd7f380cfa3e6146815574cfe6554fb6b
C++
rrti/liquidity
/coor_tuple.hpp
UTF-8
2,657
3.140625
3
[]
no_license
#ifndef LIQUIDITY_COOR_TUPLE_HDR #define LIQUIDITY_COOR_TUPLE_HDR #include <algorithm> // std::{min,max} #include <cassert> #include <cmath> // std::{sqrt,sin,cos} #include <cstring> // mem{set,cpy} #include <initializer_list> namespace math { template<typename type, size_t size> struct t_tuple { public: // note: IL's force {}-syntax in all ctor calls t_tuple(const t_tuple& c) { std::memcpy(&a[0], &c.a[0], size * sizeof(type)); } t_tuple(const std::initializer_list<type>& args = {}) { std::memset(&a[0], 0, sizeof(type) * size); std::memcpy(&a[0], args.begin(), std::min(args.size(), size) * sizeof(type)); } t_tuple operator - () const { t_tuple r; for (size_t n = 0; n < size; n++) r[n] = -(*this)[n]; return r; } t_tuple operator + (const t_tuple& v) const { t_tuple r; for (size_t n = 0; n < size; n++) r[n] = (*this)[n] + v[n]; return r; } t_tuple operator - (const t_tuple& v) const { t_tuple r; for (size_t n = 0; n < size; n++) r[n] = (*this)[n] - v[n]; return r; } t_tuple& operator += (const t_tuple& v) { for (size_t n = 0; n < size; n++) (*this)[n] += v[n]; return *this; } t_tuple& operator -= (const t_tuple& v) { for (size_t n = 0; n < size; n++) (*this)[n] -= v[n]; return *this; } t_tuple operator * (const type s) const { t_tuple r; for (size_t n = 0; n < size; n++) r[n] = (*this)[n] * s; return r; } t_tuple& operator *= (const type s) { for (size_t n = 0; n < size; n++) (*this)[n] *= s; return *this; } t_tuple operator / (const type s) const { return ((*this) * (type(1) / s)); } t_tuple& operator /= (const type s) { return ((*this) *= (type(1) / s)); } // inner-product type operator * (const t_tuple& v) const { type r = type(0); for (size_t n = 0; n < size; n++) r += ((*this)[n] * v[n]); return r; } type sq_len() const { return ((*this) * (*this)); } type len() const { return (std::sqrt(sq_len())); } type operator [] (const size_t i) const { assert(i < size); return a[i]; } type& operator [] (const size_t i) { assert(i < size); return a[i]; } // convenience accessors type x() const { return (*this)[0]; } type y() const { return (*this)[1]; } type z() const { return (*this)[2]; } type w() const { return (*this)[3]; } type& x() { return (*this)[0]; } type& y() { return (*this)[1]; } type& z() { return (*this)[2]; } type& w() { return (*this)[3]; } private: type a[size]; }; typedef t_tuple<float, 2> t_vec2f; typedef t_tuple<float, 3> t_vec3f; typedef t_tuple<float, 4> t_vec4f; }; using math::t_vec3f; using math::t_vec4f; #endif
true
ea736f3d952ce66d1f90a72619c5bf0d3e21c494
C++
catch4/yisoo
/week_11/7432_디스크-트리.cpp
UHC
1,207
3.28125
3
[]
no_license
// 7432 ũ Ʈ /* map ̿ ó \ depth depth ߴ ʰ -> Ǯ Ͽ ذ. */ #include <iostream> #include <string> #include <algorithm> #include <map> #include <set> #include <vector> using namespace std; int n; string path[501]; map<string, bool> m; vector<string> split(string str) { vector<string> ret; string temp; for (int i = 0; i < str.length(); i++) { if (str[i] == '\\') { ret.push_back(temp); temp.clear(); } else { temp += str[i]; } } ret.push_back(temp); return ret; } void insert(string s) { vector<string> p = split(s); string str =" "; for (int i = 0; i < p.size(); i++) { str += p[i]; if (!m[str]) { m[str] = true; for (int j = 0; j < i; j++) { cout << " "; } cout << p[i] << "\n"; } str += "\\"; } return; } bool cmp(string a, string b) { vector<string> x = split(a); vector<string> y = split(b); return x < y; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; for (int i = 0; i < n; i++) { cin >> path[i]; } sort(path, path + n,cmp); for(int i=0;i<n;i++){ insert(path[i]); } }
true
5c64e351f08cb9227b48d5d713ff1a5a5354d6df
C++
aisenn/avm
/Stack.cpp
UTF-8
4,711
3.265625
3
[]
no_license
#include "Stack.hpp" //********************************************** //* CONSTRUCTOR / DESTRUCTOR * //********************************************** Stack::Stack( void ) {} Stack::~Stack( void ) { auto rend = this->rend(); for (auto rit = this->rbegin(); rit != rend; rit++) delete *rit; } //********************************************** //* ITERATORS * //********************************************** Stack::iterator Stack::begin( void ) { return this->c.begin(); } Stack::iterator Stack::end( void ) { return this->c.end(); } Stack::riterator Stack::rbegin( void ) { return this->c.rbegin(); } Stack::riterator Stack::rend( void ) { return this->c.rend(); } //********************************************** //* INSTANCE GETTER * //********************************************** Stack &Stack::instance() { static Stack instance; return instance; } //********************************************** //* PUBLIC MEMBER FUNCTIONS * //********************************************** void Stack::mpop() { if (this->c.empty()) throw AvmExceptions::PopOnEmptyStack(); std::unique_ptr<const IOperand> lhs(this->top()); this->pop(); } void Stack::mpush(eOperandType &type, std::string &strValue) { STACK.push(FACTORY.createOperand(type, strValue)); } void Stack::massert(eOperandType &type, std::string &strValue) { if (this->top()->getType() != type || this->top()->toString() != strValue) throw (AvmExceptions::AssertError()); } void Stack::dump() { auto rend = this->rend(); for (auto rit = this->rbegin(); rit != rend; rit++) std::cout << (*rit)->toString() << std::endl; } void Stack::add() { if (this->size() < 2) throw (AvmExceptions::ExpressionError("addition")); std::unique_ptr<const IOperand> lhs(this->top()); this->pop(); std::unique_ptr<const IOperand> rhs(this->top()); this->pop(); this->push(*lhs + *rhs); } void Stack::sub() { if (this->size() < 2) throw (AvmExceptions::ExpressionError("subtract")); std::unique_ptr<const IOperand> lhs(this->top()); this->pop(); std::unique_ptr<const IOperand> rhs(this->top()); this->pop(); this->push(*rhs - *lhs); } void Stack::mul() { if (this->size() < 2) throw (AvmExceptions::ExpressionError("multiply")); std::unique_ptr<const IOperand> lhs(this->top()); this->pop(); std::unique_ptr<const IOperand> rhs(this->top()); this->pop(); this->push(*lhs * *rhs); } void Stack::div() { if (this->size() < 2) throw (AvmExceptions::ExpressionError("divide")); std::unique_ptr<const IOperand> lhs(this->top()); this->pop(); std::unique_ptr<const IOperand> rhs(this->top()); this->pop(); this->push(*rhs / *lhs); } void Stack::mod() { if (this->size() < 2) throw (AvmExceptions::ExpressionError("addition")); std::unique_ptr<const IOperand> lhs(this->top()); this->pop(); std::unique_ptr<const IOperand> rhs(this->top()); this->pop(); this->push(*rhs % *lhs); } void Stack::print() { if (this->empty()) throw (AvmExceptions::PrintOnEmptyStack()); if (this->top()->getType() != INT8) throw (AvmExceptions::ExceptionString("Printing invalid value")); char c = static_cast<char>(std::stoi(top()->toString())); if (std::isspace(c) || !std::isprint(c)) std::cout << "'" << c << "' unprintable char " << top()->toString() << std::endl; else std::cout << c << std::endl; } void Stack::clear() { Stack().swap(STACK); } void Stack::average() { unsigned long i = this->size(); if ( i > 1) { while (this->size() > 1) this->add(); this->push(FACTORY.createOperand(DOUBLE, std::to_string(i))); this->div(); } } void Stack::mlog() { std::unique_ptr<const IOperand> tmp(this->top()); auto val = std::stod(tmp->toString()); if (val == 0) throw(AvmExceptions::ExceptionString("Pole error occurs in log()")); if (val < 0) throw(AvmExceptions::ExceptionString("Domain error occurs in log()")); this->pop(); this->push(FACTORY.createOperand(DOUBLE, std::to_string(log(val)))); } void Stack::msqrt() { if (this->top()->toString() != "0") { std::unique_ptr<const IOperand> tmp(this->top()); auto val = std::stod(tmp->toString()); if (val < 0) throw (AvmExceptions::ExceptionString("Domain error occurs in sqrt()")); this->pop(); this->push(FACTORY.createOperand(DOUBLE, std::to_string(sqrt(val)))); } } void Stack::mpow(eOperandType &type, std::string &strValue) { std::unique_ptr<const IOperand> tmp(this->top()); auto lhs = std::stod(tmp->toString()); auto rhs = std::stod(strValue); if (rhs < 0) throw(AvmExceptions::ExceptionString("Error while pow()")); this->pop(); this->push(FACTORY.createOperand(type, std::to_string(pow(lhs, rhs)))); }
true
40c6bc480ef108ef6c8d5dc308ad9fe0375e1250
C++
kzlotekprogrammer/Marian
/Marian/Entity.cpp
UTF-8
1,333
2.578125
3
[]
no_license
#include "Entity.h" Entity::Entity(b2World * t_world, sf::Vector2f t_positionSFML, int t_rect_x, int t_rect_y) { //data world = t_world; rect_x = t_rect_x; rect_y = t_rect_y; //singleton data texture = SingletonData::getSingletonData().getTexture(); if(!(SingletonData::getSingletonData().isGood())) { toRemove = true; return; } toRemove = false; //Box2d body b2BodyDef bodyDef; bodyDef.fixedRotation = true; body = world->CreateBody(&bodyDef); body->SetTransform(b2Vec2(SFtoB2D(t_positionSFML.x), SFtoB2D(-t_positionSFML.y)), body->GetAngle()); body->SetUserData(this); //SFML sprite sprite.setTexture(*texture); sprite.setPosition(t_positionSFML); sprite.setTextureRect(sf::IntRect(sf::Vector2i(rect_x * 64, rect_y * 64), sf::Vector2i(64, 64))); health = 1; } Entity::~Entity() { world->DestroyBody(body); } void Entity::draw(sf::RenderTarget & target, sf::RenderStates states) const { states.transform *= getTransform(); target.draw(sprite); } void Entity::update() { sprite.setPosition(sf::Vector2f(B2DtoSF(body->GetPosition().x), -B2DtoSF(body->GetPosition().y))); } void Entity::takeDamage(int damage) { if (properties.isRemovable) { health -= damage; if (health <= 0) { toRemove = true; } } }
true
3425a34bedaeada166c97e847b046c4acbb502f8
C++
parvmor/da
/da/link/perfect_link.cc
UTF-8
4,687
2.640625
3
[ "MIT" ]
permissive
#include <da/link/perfect_link.h> #include <chrono> #include <cstring> #include <functional> #include <mutex> #include <shared_mutex> #include <sstream> #include <string> #include <da/executor/scheduler.h> #include <da/process/process.h> #include <da/socket/udp_socket.h> #include <da/util/logging.h> #include <da/util/status.h> #include <da/util/statusor.h> #include <da/util/util.h> namespace da { namespace link { namespace { // Assumes that message has a valid minimum length. bool isAckMessage(const std::string& msg) { return util::stringToBool(msg.data() + sizeof(uint16_t)); } // Assumes that message has a valid minimum length. std::string constructInverseMessage(std::string msg, int process_id, bool ack) { std::string process_id_str = util::integerToString<uint16_t>(process_id); for (int i = 0; i < int(sizeof(uint16_t)); i++) { msg[i] = process_id_str[i]; } msg[sizeof(uint16_t)] = util::boolToString(ack)[0]; return msg; } } // namespace const int max_length = 64 * sizeof(int); const int min_length = sizeof(uint16_t) + sizeof(bool); PerfectLink::PerfectLink(executor::Scheduler* scheduler, socket::UDPSocket* sock, const process::Process* local_process, const process::Process* foreign_process) : PerfectLink(scheduler, sock, local_process, foreign_process, std::chrono::microseconds(10000)) {} PerfectLink::PerfectLink(executor::Scheduler* scheduler, socket::UDPSocket* sock, const process::Process* local_process, const process::Process* foreign_process, std::chrono::microseconds interval) : scheduler_(scheduler), sock_(sock), local_process_(local_process), foreign_process_(foreign_process), interval_(interval) {} PerfectLink::~PerfectLink() { std::unique_lock<std::shared_timed_mutex> lock(mutex_); undelivered_messages_.clear(); } int PerfectLink::constructIdentity(const std::string* msg) { using namespace std::string_literals; std::string link_msg = ""s; link_msg += util::integerToString<uint16_t>(local_process_->getId()); link_msg += util::boolToString(false); link_msg += *msg; return identity_manager_.assignId(link_msg); } void PerfectLink::sendMessage(const std::string* msg) { int id = constructIdentity(msg); { std::unique_lock<std::shared_timed_mutex> lock(mutex_); undelivered_messages_.insert(id); } sendMessageCallback(id); } void PerfectLink::sendMessageCallback(int id) { { std::shared_lock<std::shared_timed_mutex> lock(mutex_); if (undelivered_messages_.find(id) == undelivered_messages_.end()) { return; } } const std::string* msg = identity_manager_.getValue(id); // The message is non-ascii and hence, cannot be printed. LOG("Sending message '", util::stringToBinary(msg), "' to ", *foreign_process_); const auto status = sock_->sendTo(msg->data(), msg->size(), foreign_process_->getIPAddr(), foreign_process_->getPort()); if (!status.ok()) { LOG("Sending of message '", util::stringToBinary(msg), "' to ", *foreign_process_, " failed. Status: ", status); } scheduler_->schedule(interval_, std::bind(&PerfectLink::sendMessageCallback, this, id)); } void PerfectLink::ackMessage(const std::string& msg) { const std::string ack_msg = constructInverseMessage(msg, local_process_->getId(), true); const auto status = sock_->sendTo(ack_msg.data(), ack_msg.size(), foreign_process_->getIPAddr(), foreign_process_->getPort()); if (!status.ok()) { LOG("Sending of message '", util::stringToBinary(&ack_msg), "' to ", *foreign_process_, " failed. Status: ", status); } } bool PerfectLink::recvMessage(const std::string& msg) { if (isAckMessage(msg)) { // The inverse message must already be there in the identity manager. int id = identity_manager_.getId( constructInverseMessage(msg, local_process_->getId(), false)); if (id == -1) { return false; } { std::unique_lock<std::shared_timed_mutex> lock(mutex_); undelivered_messages_.erase(id); } return false; } ackMessage(msg); // This message might be a new one. int id = identity_manager_.assignId(msg); std::unique_lock<std::shared_timed_mutex> lock(mutex_); if (delivered_messages_.find(id) != delivered_messages_.end()) { // We have already received this message. return false; } delivered_messages_.insert(id); return true; } } // namespace link } // namespace da
true
d7de7e76feef8b4d761af4a9f8c6b1ef7be77e4b
C++
user-ZJ/cpplib
/code/ModernCpp/8_lambda/13_variadic_base.cpp
UTF-8
868
3.34375
3
[ "MIT" ]
permissive
#include <iostream> #include <memory> #include <vector> using namespace std; struct WidgetA{ double x; }; struct WidgetB{ double y; double z; }; struct WidgetC{ double u; double v; double w; }; template<class...Base> struct Object: Base...{ }; // template<class T1> // struct Object: T1{ // }; // template<class T1, class T2> // struct Object: T1, T2{ // }; // template<class T1, class T2, class T3> // struct Object: T1, T2, T3{ // }; template<class... T> Object(T...)-> Object<T...>; int main(){ WidgetA a{1.1}; WidgetB b{2.2,3.3}; WidgetC c{4.4,5.5,6.6}; Object obj{a,b,c}; // //Object<WidgetA, WidgetB, WidgetC> obj{a,b,c}; cout<<sizeof(obj)<<endl; cout<<obj.x<<endl; cout<<obj.y<<endl; cout<<obj.z<<endl; cout<<obj.u<<endl; cout<<obj.v<<endl; cout<<obj.w<<endl; }
true
33f171ba55193a6c205ae221378c596e72e54928
C++
Bruteforceman/cp-submissions
/codeforces/1078/A.cpp
UTF-8
1,043
2.9375
3
[]
no_license
#include "bits/stdc++.h" using namespace std; struct point { double x, y; point () {} point (double x, double y) : x(x), y(y) {} void in () { cin >> x >> y; } }; double man(point a, point b) { return fabs(a.x - b.x) + fabs(a.y - b.y); } double dist(point a, point b) { double dx = a.x - b.x; double dy = a.y - b.y; return sqrt(dx*dx + dy*dy); } point a, b; double A, B, C; point getP(point p, int is_x) { if(is_x) { return point(p.x, (-A * p.x - C) / B); } else { return point((-B * p.y - C) / A, p.y); } } int main(int argc, char const *argv[]) { long long aa, bb, cc; cin >> aa >> bb >> cc; A = aa; B = bb; C = cc; a.in(); b.in(); double ans = man(a, b); for(int i = 0; i <= 1; i++) { for(int j = 0; j <= 1; j++) { if(bb == 0) { if(i == 1 || j == 1) continue; } if(aa == 0) { if(i == 0 || j == 0) continue; } point p = getP(a, i); point q = getP(b, j); ans = min(ans, man(a, p) + dist(p, q) + dist(q, b)); } } cout << setprecision(10) << fixed << ans << endl; return 0; }
true
30b7b06581e5c453af86fdc7b24bc599cbafc0bb
C++
Biswajee/Codestore
/Numberofgoodpairs.cpp
UTF-8
320
2.828125
3
[ "MIT" ]
permissive
class Solution { public: int numIdenticalPairs(vector<int>& nums) { unordered_map<int, int> mp; for(int x : nums) { mp[x]++; } int good_pairs = 0; for(auto a : mp) { good_pairs+=((a.second*(a.second-1))/2); } return good_pairs; } };
true
ad8aa712f28cecb9164a8058433d5b898781781e
C++
weimingtom/tanuki-mo-issyo
/プログラム/Ngllib/include/Ngl/IXMLFile.h
SHIFT_JIS
2,070
2.640625
3
[]
no_license
/*******************************************************************************/ /** * @file IXMLFile.h. * * @brief XMLt@CC^[tF[X. * * @date 2008/07/23. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #ifndef _NGL_IXMLFILE_H_ #define _NGL_IXMLFILE_H_ #include "IXMLElement.h" #include <string> namespace Ngl{ /** * @interface IXMLFileD * @brief XMLt@CC^[tF[X. */ class IXMLFile { public: /*=========================================================================*/ /** * @brief fXgN^ * * @param[in] Ȃ. */ virtual ~IXMLFile() {} /*=========================================================================*/ /** * @brief Ovf擾 * * @param[in] name 擾vf. * @return 擾vf. */ virtual IXMLElement* getElementByName( const std::string name ) = 0; /*=========================================================================*/ /** * @brief CfbNXԍvf擾 * * @param[in] index 擾vf̃CfbNXԍ. * @return 擾vf. */ virtual IXMLElement* getElementByIndex( unsigned int index ) = 0; /*=========================================================================*/ /** * @brief vf擾 * * @param[in] Ȃ. * @return 擾vf. */ virtual unsigned int elementCount() = 0; /*=========================================================================*/ /** * @brief [] ZqI[o[[h * * nameŎw肵vf擾. * * @param[in] name 擾vf. * @return 擾vf. */ virtual IXMLElement* operator [] ( const std::string name ) = 0; }; } // namespace Ngl #endif /*===== EOF ==================================================================*/
true
d40e1f800375c4b4e041270a5795502c5788c8ba
C++
nishimotz/dmcpp
/facerecog.cpp
UTF-8
2,935
2.515625
3
[]
no_license
#include "facerecog.h" bool FaceRecog::loadModels(void) { const string cascadeName = "/usr/local/share/opencv/haarcascades/haarcascade_frontalface_alt.xml"; const string nestedCascadeName = "/usr/local/share/opencv/haarcascades/haarcascade_mcs_eyepair_small.xml"; if( !cascade.load( cascadeName ) ) { cerr << "ERROR: Could not load classifier cascade" << endl; return false; } if( !nestedCascade.load( nestedCascadeName ) ) { cerr << "WARNING: Could not load classifier cascade for nested objects" << endl; return false; } return true; } void FaceRecog::detectAndDraw(Mat& img, double scale) { CascadeClassifier cascade = this->cascade; CascadeClassifier nestedCascade = this->cascade; const static Scalar colors[] = { CV_RGB(0,0,255), CV_RGB(0,128,255), CV_RGB(0,255,255), CV_RGB(0,255,0), CV_RGB(255,128,0), CV_RGB(255,255,0), CV_RGB(255,0,0), CV_RGB(255,0,255)} ; Mat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 ); cvtColor( img, gray, CV_BGR2GRAY ); resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR ); equalizeHist( smallImg, smallImg ); double t = 0; t = (double)cvGetTickCount(); cascade.detectMultiScale( smallImg, this->faces, 1.1, 2, 0 |CV_HAAR_FIND_BIGGEST_OBJECT //|CV_HAAR_DO_ROUGH_SEARCH |CV_HAAR_SCALE_IMAGE , Size(30, 30) ); t = (double)cvGetTickCount() - t; // fprintf(stderr, "detection time = %g ms\n", t/((double)cvGetTickFrequency()*1000.) ); int i = 0; for( vector<Rect>::const_iterator r = this->faces.begin(); r != this->faces.end(); r++, i++ ) { Mat smallImgROI; vector<Rect> nestedObjects; Point center; Scalar color = colors[i%8]; int radius; center.x = cvRound((r->x + r->width*0.5)*scale); center.y = cvRound((r->y + r->height*0.5)*scale); radius = cvRound((r->width + r->height)*0.25*scale); circle( img, center, radius, color, 3, 8, 0 ); if( nestedCascade.empty() ) continue; smallImgROI = smallImg(*r); nestedCascade.detectMultiScale( smallImgROI, nestedObjects, 1.1, 2, 0 |CV_HAAR_FIND_BIGGEST_OBJECT //|CV_HAAR_DO_ROUGH_SEARCH //|CV_HAAR_DO_CANNY_PRUNING |CV_HAAR_SCALE_IMAGE , Size( 3, 3 )); for( vector<Rect>::const_iterator nr = nestedObjects.begin(); nr != nestedObjects.end(); nr++ ) { center.x = cvRound((r->x + nr->x + nr->width*0.5)*scale); center.y = cvRound((r->y + nr->y + nr->height*0.5)*scale); radius = cvRound((nr->width + nr->height)*0.25*scale); //circle( img, center, radius, color, 3, 8, 0 ); Point p1, p2; p1.x = (r->x + nr->x)*scale; p2.x = p1.x + nr->width * scale; p1.y = (r->y + nr->y)*scale; p2.y = p1.y + nr->height * scale; rectangle( img, p1, p2, color, 3); } } }
true
394e06e5d46dc2b6edc92b25a955981ceed9805c
C++
mamepika426/Atcoder
/atcoder_problems/C_数を三つ選ぶマン.cpp
UTF-8
343
2.71875
3
[]
no_license
#include <iostream> #include <algorithm> #include <bits/stdc++.h> #include <vector> using namespace std; int main(){ vector<int> num(5,0); for(int n=0;n<5;n++) cin >> num[n]; if(num[0]+num[3]<num[1]+num[2]) cout << num[1] + num[2] + num[4] << endl; else cout << num[0] + num[3] + num[4] << endl; return 0; }
true
7c3494fb7007ee451671cb9062c822970a1dfce5
C++
kalejos/CS-200
/Lab04b-Dynamic Arrays/Lab4bpart3.cpp
UTF-8
976
3.078125
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { string ears[3] = { " ^ ^ ", " n n ", " * * " }; string heads[3] = { " ( o_o ) ", " ( x_x )" , " ( >_< ) " }; string bodies[3] = { "/( )\\", "\\( )/", "o( )o" }; string feet[3] = { " d b ", " @ @ ", " () () " }; string * ptrEars; string * ptrHead; string * ptrBody; string * ptrFeet; int choice; cout << "Enter ears (0 - 2): " << endl; cin >> choice; ptrEars = &ears[choice]; cout << "Enter head (0 - 2): " << endl; cin >> choice; ptrHead = &heads[choice]; cout << "Enter body (0 - 2): " << endl; cin >> choice; ptrBody = &bodies[choice]; cout << "Enter feet (0 - 2): " << endl; cin >> choice; ptrFeet = &feet[choice]; if (choice <= 2 && choice >= 0) { cout << endl << *ptrEars << endl << *ptrHead << endl << *ptrBody << endl << *ptrFeet << endl; } while (true); return 0; }
true
38d18c1c911a66667539d069364b6c5ab340c75c
C++
arximboldi/zug
/zug/transducer/take_nth.hpp
UTF-8
1,556
2.71875
3
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // zug: transducers for C++ // Copyright (C) 2019 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #pragma once #include <zug/compose.hpp> #include <zug/state_wrapper.hpp> #include <zug/util.hpp> #include <zug/with_state.hpp> namespace zug { /*! * Lets every nth elements of the sequence through. * * Similar to * [clojure.core/take-nth](https://clojuredocs.org/clojure.core/take-nth). * * @rst * .. literalinclude:: ../test/transducer/take_nth.cpp * :language: c++ * :start-after: // example1 { * :end-before: // } * :dedent: 4 * @endrst */ template <typename IntegralT> auto take_nth(IntegralT nth) { return comp([=](auto step) { return [=](auto&& s, auto&&... is) mutable { return with_state( ZUG_FWD(s), [&](auto&& st) { return wrap_state(step(ZUG_FWD(st), ZUG_FWD(is)...), 1); }, [&](auto&& st) { auto count = state_wrapper_data(ZUG_FWD(st)); return count != nth ? wrap_state(state_unwrap(ZUG_FWD(st)), count + 1) : wrap_state(step(state_unwrap(ZUG_FWD(st)), ZUG_FWD(is)...), 1); }); }; }); } } // namespace zug
true
4ccecfc995bf3f8ed934c7ec010274ba359d8338
C++
SterbenDa/NYOJ-Linda
/语言入门/就我不坑/Untitled1(1).cpp
WINDOWS-1252
3,209
3.03125
3
[]
no_license
#include "iostream" using namespace std; int main(){ int a[15]; string number[10]={"","Ҽ","","","","","½","","",""}; string wei[]={"","ʰ","","Ǫ"}; string s; int i,n; while(cin>>s){ int num=s.length(); bool flag=0; for(i=0,n=num-1;i<num;i++,n--){ a[n]=s[i]-'0'; } if(num<=4){ for(i=num-1;i>=0;i--){ if(a[i]==0&&i>0&&flag==0){ int j,ok=0; for(j=i-1;j>=0;j--){ if(a[j]!=0){ ok=1; break; } } if(ok){ cout<<number[a[i]]; flag=1;} } else if(a[i]!=0){ cout<<number[a[i]]<<wei[i]; flag=0; } } cout<<endl; continue; } else if(num>=5&&num<=8){ for(i=num-1,n=num-5;i>=4;i--,n--){ if(a[i]==0&&i>0&&flag==0){ int j,ok=0; for(j=i-1;j>=4;j--){ if(a[j]!=0){ ok=1; break; } } if(ok){ cout<<number[a[i]]; flag=1; } } else if(a[i]!=0){ cout<<number[a[i]]<<wei[n]; flag=0; } } cout<<""; for(;i>=0;i--){ if(a[i]==0&&i>0&&flag==0){ int j,ok=0; for(j=i-1;j>=0;j--){ if(a[j]!=0){ ok=1; break; } } if(ok){ cout<<number[a[i]]; flag=1; } } else if(a[i]!=0){ cout<<number[a[i]]<<wei[i]; flag=0; } } cout<<endl; continue; } else if(num>8){ bool fuck=0; for(i=num-1,n=num-9;i>=8;i--,n--){ if(a[i]==0&&i>0&&flag==0){ int j,ok=0; for(j=i-1;j>=8;j--){ if(a[j]!=0){ ok=1; break; } } if(ok){ cout<<number[a[i]]; flag=1; } } else if(a[i]!=0){ cout<<number[a[i]]<<wei[n]; flag=0; } } cout<<""; for(n=3;i>=4;i--,n--){ if(a[i]==0&&i>0&&flag==0){ int j,ok=0; for(j=i-1;j>=4;j--){ if(a[j]!=0){ ok=1; break; } } if(ok){ cout<<number[a[i]]; flag=1; } } else if(a[i]!=0){ cout<<number[a[i]]<<wei[n]; flag=0; fuck=1; } } if(fuck) cout<<""; for(;i>=0;i--){ if(a[i]==0&&i>0&&flag==0){ int j,ok=0; for(j=i-1;j>=0;j--){ if(a[j]!=0){ ok=1; break; } } if(ok){ cout<<number[a[i]]; flag=1; } } else if(a[i]!=0){ cout<<number[a[i]]<<wei[i]; flag=0; } } cout<<endl; continue; } } return 0; }
true
1235148a6d1dfb8858a6f0a538508e83fe69bd46
C++
luismoax/Competitive-Programming---luismo
/SPOJ_ACCEPTED/FACTCG2.cpp
ISO-8859-1
1,108
2.75
3
[]
no_license
/* Author: Luis Manuel Daz Barn (LUISMO) Problem: FACTCG2 Online Judge: SPOJ Idea: Nice Problem. Use Eratostenes' sieve and store in position i the minimun prime number which divides i. */ #include<bits/stdc++.h> // Types #define ll long long #define ull unsigned long long // IO #define sf scanf #define pf printf #define lim 10000007 using namespace std; int sieve[lim]; void eratostenes() { sieve[2] = 2; for(int i = 4; i < lim; i+= 2) sieve[i] = 2; for(int i = 3; i < lim; i+= 2) { if(sieve[i] == 0) { sieve[i] = i; for(int j = i + i; j < lim; j+= i) { if(sieve[j] == 0) sieve[j] = i; } } } } int N; void solve() { eratostenes(); while(cin >> N) { if(N == 1) cout << "1"; else { cout << "1"; while(N > 1) { cout << " x " << sieve[N]; N /= sieve[N]; } } cout << "\n"; } } void open_file() { // freopen("//media//Trabajo//lmo.in","r",stdin); freopen("d:\\lmo.in","r",stdin); // freopen("d:\\lmo.out","w",stdout); } int main() { // open_file(); cin.sync_with_stdio(false); cin.tie(0); solve(); }
true
cea2e442758427e54a13e25e8c3dfe97542c5abe
C++
nishgpt/competitive_programming
/spoj/ADAGAME4.cp
UTF-8
1,244
2.515625
3
[]
no_license
#include "bits/stdc++.h" #include<signal.h> using namespace std; #define LL long long int #define MAX 20000007 #define LIM 20000007 //d[i][0] = number of divisors of number i //d[i][1] = number i after being divided by some prime divisors //int d[MAX][2]; int ans[MAX]; int numdiv[MAX]; int prime[MAX]; void sieve() { int i, j; numdiv[1] = 1; for(i = 2; i * i < LIM; i++) { if(prime[i] == 0) { prime[i] = i; for(j = 2*i; j < LIM; j += i) { prime[j] = i; } } } for(; i < LIM; i++ ){ if(prime[i] == 0) { prime[i] = i; } } numdiv[0] = 0; numdiv[1] = 1; for(i = 2; i <LIM; i++) { int cnt = 0; j = i; while(j % prime[i] == 0) { cnt++; j /= prime[i]; } numdiv[i] = numdiv[j] * (cnt + 1); } int lastv = 0; for(i=3;i<LIM;i++) { if(i - numdiv[i] > lastv) { ans[i] = 1; lastv = i; } } } int main() { int i, n, t; scanf("%d", &t); sieve(); while(t--) { scanf("%d", &n); if(ans[n]) cout<<"Vinit"<<endl; else cout<<"Ada"<<endl; } }
true
3106ea501faacd0c5a21f874773336662d426bb6
C++
mastewal/Data-Structure-Labs
/Lab7/main.cpp
UTF-8
3,466
4.03125
4
[]
no_license
/* Lab#: 7 Course: CS 5123 Name: Mastewal Abawa A program that will create a hash table using the following collusion handling techniques - linear probing - double hashing - chaining The program also calculate the number of collisions, the total steps to place each element and the total number of entry */ #include "HashItem.h" #include "Hasher.h" #include <iostream> #include<cstdlib> #include<algorithm> using namespace std; int main() { // declare variables int key = 1; // the key value int myTableSize = 0;// the size of the table int hashType = 0;// hash type (1 for linear probing, 2 for double hashing,3 for chaining bool decidedToQuit = false; //a boolean to determine if the user want to quit hashing int numberOfElements =0; cout << "Enter Table Size: "<< endl; cin>> myTableSize; Hasher *h1 = new Hasher(myTableSize) ; // instantiate a pointer that points to new hasher object HashItem *ptr = new HashItem(key); // prompt the user cout << "1 is for linear probing "<< endl; cout << "2 is for double hashing "<< endl; cout << "3 is for chaining "<< endl; cout << "-1 to quit "<< endl; cout << "Enter Hash Type: "<< endl; cin>> hashType; // while that will allow the user to create hash table and insert values until s/he decided to quit while (!decidedToQuit){ //switch statement that allows the user to switch between different hashing techniques switch(hashType) { // linear probing case 1: cout<<"\n\nEnter key to be inserted: "; cin>> key; if (key == -1){ cout << "\nYou decided to quit! Good Bye!"<<endl; cout << "\n\nNumber of Elements: "<< numberOfElements<<endl; exit(!decidedToQuit); } h1->linearProbing(key); h1->printTable(key); numberOfElements++; cout << "steps: "<< h1->getSteps()<< " collisions: "<< h1->calculateCollision(key)<<endl; break; // Double hash case 2: cout<<"\n\nEnter key to be inserted: "; cin>> key; if (key == -1){ cout << "\nYou decided to quit! Good Bye!"<<endl; cout << "\n\nNumber of Elements: "<< numberOfElements<<endl; exit(!decidedToQuit); } h1->doubleHash(key); h1->printTable(key); numberOfElements++; cout << "steps: "<< h1->getSteps()<< " collisions: "<< h1->calculateCollision(key)<<endl; break; // chaining case 3: cout<<"\n\nEnter key to be inserted: "; cin>> key; if (key == -1){ cout << "\nYou decided to quit! Good Bye!"<<endl; cout << "\n\nNumber of Elements: "<< numberOfElements<<endl; exit(!decidedToQuit); } h1->chaining(key); h1->printTable(key); numberOfElements++; cout << " collisions: "<< h1->calculateCollision(key)<<endl; break; default: cout<<"\n Hashing interrupted\n"<<endl; decidedToQuit = true; break; }// end of switch statement }// end of while loop return 0; }
true
004d798c59884ab645e46351afe58741cba6a0cc
C++
tudocomp/tudocomp
/include/tudocomp/compressors/lcpcomp/compress/NaiveStrategy.hpp
UTF-8
1,961
2.640625
3
[ "Apache-2.0" ]
permissive
#pragma once #include <vector> #include <tudocomp/Algorithm.hpp> #include <tudocomp/ds/IntVector.hpp> #include <tudocomp/ds/TextDS.hpp> #include <tudocomp/compressors/lzss/LZSSFactors.hpp> namespace tdc { namespace lcpcomp { /// A very naive selection strategy for LCPComp. /// /// TODO: Describe class NaiveStrategy : public Algorithm { public: using Algorithm::Algorithm; inline static Meta meta() { Meta m("lcpcomp_comp", "naive"); return m; } inline static ds::dsflags_t textds_flags() { return ds::SA | ds::ISA | ds::LCP; } template<typename text_t> inline void factorize(text_t& text, size_t threshold, lzss::FactorBuffer& factors) { // Construct SA, ISA and LCP text.require(text_t::SA | text_t::ISA | text_t::LCP); auto& sa = text.require_sa(); auto& isa = text.require_isa(); auto& lcp = text.require_lcp(); // size_t n = sa.size(); size_t i = 0; BitVector marked(n, 0); while(i+1 < n) { // we skip text position T[n] == 0 size_t s = isa[i]; size_t l = lcp[s]; if(l >= threshold) { //check if any position is marked bool available = true; for(size_t k = 0; k < l; k++) { if(marked[i + k]) { available = false; break; } } if(available) { //introduce factor size_t src = sa[s - 1]; factors.emplace_back(i, src, l); //mark source positions for(size_t k = 0; k < l; k++) { marked[src + k] = 1; } i += l; continue; } } ++i; } } }; }}
true
4764c961364440938a0291e241ad7da6861697cd
C++
umerfarooqpucit/Object-Oriented-Programming
/Assignments/C-String Library assignment/string4.cpp
UTF-8
592
3.328125
3
[ "MIT" ]
permissive
/* NAME: MUHAMMAD UMER FAROOQ ROLL NUM: BCSF15M025 */ #include<iostream> using namespace std; int main() { //variable for length of string int len, //variable for no of words no_words=1; //array for string char st[50]; cout<<"Enter a sentence:"; cin.getline(st,50); //loop to calculate length of string for(len=0;st[len]!='\0';) { len++; } for(int i=0;st[i]!='\0';) { //condition to count all the words after " " or "." if((st[i]==' '||st[i]=='.')/*this conditon checks if dot is not on the last*/&&i!=len-1) { no_words++; } i++; } cout<<"\nNumber of words:"<<no_words; }
true
10ef855d5e646bcb6272ecf7dbedd7cfe67e94a4
C++
elffer/sdce
/term_2/P4 PID Control Project /src/PID.cpp
UTF-8
1,089
2.78125
3
[ "MIT" ]
permissive
#include "PID.h" /** * TODO: Complete the PID class. You may add any additional desired functions. */ PID::PID() {} PID::~PID() {} void PID::Init(double Kp_, double Ki_, double Kd_) { /** * TODO: Initialize PID coefficients (and errors, if needed) */ Kp = Kp_; Ki = Ki_; Kd = Kd_; cte_pre = 0.0; int_cte = 0.0; } double PID::CalcValue(double cte){ /* Calculate the control of mismatch */ double value; double diff_cte; diff_cte = cte - cte_pre; cte_pre = cte; int_cte += cte; value = - Kp*cte - Kd*diff_cte - Ki*int_cte; return value; } double PID::CalcValue_throttle(double cte){ /* Calculate the control of mismatch */ double value; double diff_cte; diff_cte = cte - cte_pre; cte_pre = cte; int_cte = 0.9*int_cte + cte; value = - Kp*cte - Kd*diff_cte - Ki*int_cte; return value; } void PID::UpdateError(double cte) { /** * TODO: Update PID errors based on cte. */ } double PID::TotalError() { /** * TODO: Calculate and return the total error */ return 0.0; // TODO: Add your total error calc here! }
true
a4ca808f969f551d0e2fd018227d90de45d504c0
C++
tal-shadmi/CompHw5
/AST.hpp
UTF-8
9,823
2.625
3
[]
no_license
#ifndef _AST_H #define _AST_H #include <string> #include <vector> #include <memory> #include <utility> #include "SymbolTable.hpp" #include "bp.hpp" using std::unique_ptr; using std::move; using std::vector; using std::string; namespace AST { using Type = SymbolTable::Type; class Node { protected: Node(Type type, string name): type(type), name(move(name)) {} public: virtual ~Node() = default; Type type; string name; vector<unique_ptr<Node>> children; virtual string value(); virtual pair<BackpatchList, BackpatchList> getBackpatchLists(); }; class BreakContinueMixin { protected: BackpatchList break_list; BackpatchList continue_list; public: pair<BackpatchList, BackpatchList> getBreakContinueLists(); static pair<BackpatchList, BackpatchList> getListsFromNode(Node *node); static pair<BackpatchList, BackpatchList> getListsFromNode(Node *node1, Node *node2); }; class ProgramNode : public Node { public: explicit ProgramNode(unique_ptr<Node> funcs); ~ProgramNode() override = default; }; class FuncsNode : public Node { public: FuncsNode(); FuncsNode(unique_ptr<Node> funcsImpl, unique_ptr<Node> funcs); ~FuncsNode() override = default; }; class FuncsSignNode : public Node { public: FuncsSignNode(unique_ptr<Node> retType, unique_ptr<Node> id, unique_ptr<Node> formals); ~FuncsSignNode() override = default; }; class FuncsImplNode : public Node { public: FuncsImplNode(unique_ptr<Node> sign_node, unique_ptr<Node> statements); ~FuncsImplNode() override = default; }; class RetTypeNode : public Node { public: RetTypeNode(); explicit RetTypeNode(unique_ptr<Node> type_node); ~RetTypeNode() override = default; }; class FormalsNode : public Node { public: FormalsNode(); explicit FormalsNode(unique_ptr<Node> formals_list); ~FormalsNode() override = default; }; class FormalsListNode : public Node { public: explicit FormalsListNode(unique_ptr<Node> formal_decl); FormalsListNode(unique_ptr<Node> formal_decl, unique_ptr<Node> formals_list); ~FormalsListNode() override = default; }; class FormalDeclNode : public Node { public: FormalDeclNode(unique_ptr<Node> type_node, unique_ptr<Node> id); ~FormalDeclNode() override = default; }; class StatementsNode : public Node, public BreakContinueMixin { public: explicit StatementsNode(unique_ptr<Node> Statement); StatementsNode(unique_ptr<Node> Statements, unique_ptr<Node> Statement); ~StatementsNode() override = default; }; class StatementsToStatementNode : public Node, public BreakContinueMixin { public: explicit StatementsToStatementNode(unique_ptr<Node> Statements); ~StatementsToStatementNode() override = default; }; class StatementDeclareVariableNode : public Node { public: StatementDeclareVariableNode(unique_ptr<Node> type_node, unique_ptr<Node> id); StatementDeclareVariableNode(unique_ptr<Node> type_node, unique_ptr<Node> id, unique_ptr<Node> exp); ~StatementDeclareVariableNode() override = default; }; class StatementAssignNode : public Node { public: StatementAssignNode(unique_ptr<Node> id, unique_ptr<Node> exp); ~StatementAssignNode() override = default; }; class StatementReturnNode : public Node { public: StatementReturnNode(); explicit StatementReturnNode(unique_ptr<Node> exp); ~StatementReturnNode() override = default; }; class StatementIfElseNode : public Node, public BreakContinueMixin { public: StatementIfElseNode(unique_ptr<Node> decl, unique_ptr<Node> m, unique_ptr<Node> statement); StatementIfElseNode(unique_ptr<Node> decl, unique_ptr<Node> m1, unique_ptr<Node> if_statement, unique_ptr<Node> n, unique_ptr<Node> m2, unique_ptr<Node> else_statement); ~StatementIfElseNode() override = default; }; class StatementWhileNode : public Node { public: StatementWhileNode(unique_ptr<Node> decl, unique_ptr<Node> m, unique_ptr<Node> statement); ~StatementWhileNode() override = default; }; class StatementBreakContinue : public Node, public BreakContinueMixin { public: explicit StatementBreakContinue(const string &break_or_continue); ~StatementBreakContinue() override = default; }; class StatementSwitchNode : public Node, public BreakContinueMixin { public: StatementSwitchNode(unique_ptr<Node> decl, unique_ptr<Node> n, unique_ptr<Node> case_list); ~StatementSwitchNode() override = default; }; class IfDeclNode : public Node { BackpatchList true_list; BackpatchList false_list; public: explicit IfDeclNode(unique_ptr<Node> exp); ~IfDeclNode() override = default; pair<BackpatchList, BackpatchList> getBackpatchLists() override; }; class WhileDeclNode : public Node { BackpatchList true_list; BackpatchList false_list; public: string label_to_bool_exp; explicit WhileDeclNode(unique_ptr<Node> n, unique_ptr<Node> m, unique_ptr<Node> exp); ~WhileDeclNode() override = default; pair<BackpatchList, BackpatchList> getBackpatchLists() override; }; class SwitchDeclNode : public Node { public: explicit SwitchDeclNode(unique_ptr<Node> exp); ~SwitchDeclNode() override = default; }; class CallNode : public Node { string result_reg; public: explicit CallNode(unique_ptr<Node> id_node); CallNode(unique_ptr<Node> id_node, unique_ptr<Node> exp_list); ~CallNode() override = default; string value() override; pair<BackpatchList, BackpatchList> getBackpatchLists() override; }; class ExpListNode : public Node { public: vector<pair<string, Type>> arguments; explicit ExpListNode(unique_ptr<Node> exp); ExpListNode(unique_ptr<Node> exp_list, unique_ptr<Node> exp); ~ExpListNode() override = default; }; class TypeNode : public Node { public: explicit TypeNode(Type type); ~TypeNode() override = default; }; class BinOpNode : public Node { string result_reg; public: BinOpNode(unique_ptr<Node> exp1, unique_ptr<Node> op, unique_ptr<Node> exp2); ~BinOpNode() override = default; string value() override; }; class BoolBinOpNode : public Node { BackpatchList true_list; BackpatchList false_list; public: BoolBinOpNode(unique_ptr<Node> exp1, unique_ptr<Node> op, unique_ptr<Node> N, unique_ptr<Node> M, unique_ptr<Node> exp2); ~BoolBinOpNode() override = default; string value() override; pair<BackpatchList, BackpatchList> getBackpatchLists() override; }; class RelOpNode : public Node { string result_reg; public: RelOpNode(unique_ptr<Node> exp1, unique_ptr<Node> op, unique_ptr<Node> exp2); ~RelOpNode() override = default; string value() override; pair<BackpatchList, BackpatchList> getBackpatchLists() override; }; class IDNode : public Node { public: explicit IDNode(string name); ~IDNode() override = default; }; class IDExp : public Node { string result_reg; public: explicit IDExp(unique_ptr<Node> id); ~IDExp() override = default; string value() override; pair<BackpatchList, BackpatchList> getBackpatchLists() override; }; class LiteralNode : public Node { string global_variable; public: LiteralNode(string name, Type type); ~LiteralNode() override = default; string value() override; pair<BackpatchList, BackpatchList> getBackpatchLists() override; }; class NotNode : public Node { BackpatchList true_list; BackpatchList false_list; public: explicit NotNode(unique_ptr<Node> exp); ~NotNode() override = default; string value() override; pair<BackpatchList, BackpatchList> getBackpatchLists() override; }; class CaseListNode : public Node, public BreakContinueMixin { public: explicit CaseListNode(unique_ptr<Node> case_decl); CaseListNode(unique_ptr<Node> case_decl, unique_ptr<Node> case_list); ~CaseListNode() override = default; }; class DefaultCaseNode : public Node, public BreakContinueMixin { public: string label; BackpatchList next; explicit DefaultCaseNode(unique_ptr<Node> M, unique_ptr<Node> statements); ~DefaultCaseNode() override = default; }; class CaseDeclNode : public Node, public BreakContinueMixin { public: string num; string label; BackpatchList next; explicit CaseDeclNode(unique_ptr<Node> num_node, unique_ptr<Node> M, unique_ptr<Node> statements); ~CaseDeclNode() override = default; }; class MNode : public Node { string label; public: explicit MNode(); ~MNode() override = default; string value() override; }; class NNode : public Node { BackpatchList nextList; public: explicit NNode(); ~NNode() override = default; pair<BackpatchList, BackpatchList> getBackpatchLists() override; }; extern int switch_count; extern int while_count; } #endif
true
fd25a3f5fa62dc707eda0b678607b26ae7c59239
C++
BobKerns/Altoid-Box-MIDI
/lib/Menu/Menu.h
UTF-8
947
3.03125
3
[ "MIT" ]
permissive
/** * @copyright Copyright (c) 2021 Bob Kerns * License: MIT */ #pragma once #include "lcdgfx.h" template<class T> class Menu { public: const uint8_t count; private: const char * const * items; uint8_t selection; bool wrap_items = false;; static const uint8_t top = 0; static const uint8_t left = 0; static const uint8_t width = 128; static const uint8_t height = 64 - top; public: Menu(uint8_t count, const char * const *items); Menu(uint8_t count, uint8_t selection, const char* const*items); Menu &select(uint8_t i); void draw(T &display); inline Menu &wrap(bool wrapItems = true) { wrap_items = wrapItems; return *this; } inline uint8_t size() const { return count; } inline const char *item(uint8_t idx) const { return items[idx]; } };
true
7ddcd1ed8de1b432a7d3ea48110af9f56fc643f7
C++
DPS0340/DoItDataRithm
/01/Q17.cpp
UTF-8
249
2.984375
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; void spira(int n) { for(int i=1;i<=n;i++) { for(int j=0;j<n-i;j++) { cout << " "; } for(int j=0;j<=(i-1)*2;j++) { cout << "*"; } cout << endl; } } int main() { spira(4); return 0; }
true
6b2f2327cc33ad5e7d1b38725f2da35f3d5ededc
C++
tbarnabas/web_scraper
/datastructure/datastructure_cpuffer.h
UTF-8
3,286
2.625
3
[]
no_license
///////////////////////////////////////////////////////////////////////////// // // datastructure_cpuffer.h - ::DATASTRUCTURE::CPuffer<T> class header // -------------------------------------------------------------------------- // // DATASTRUCTURE // ///////////////////////////////////////////////////////////////////////////// #pragma once #ifndef _DATASTRUCTURE_CPUFFER #define _DATASTRUCTURE_CPUFFER #include "datastructure_configuration.h" #include "datastructure_carray.h" namespace DATASTRUCTURE { DERIVE_EXCEPTION_BEGIN(::DATASTRUCTURE::EArray, EPuffer) IS_EMPTY DERIVE_EXCEPTION_END(EPuffer); template <class T> class CPuffer : public ::DATASTRUCTURE::CArray<T> { public: MEMBER_GET_SET(T_ULONG, Position); public: //! constructor CPuffer(const T * pElements = NULL, T_ULONG uSize = 0); //! destructor virtual ~CPuffer(); //! copy constructor CPuffer(const CPuffer<T> & tPuffer); //! assignment operator CPuffer<T> & operator=(const CPuffer<T> & tPuffer); //! if puffer is empty then return true T_BOOLEAN IsEmpty() const; //! peek element T & Peek() const; //! next element T & Next(); }; // class CPuffer } // namespace DATASTRUCTURE ///////////////////////////////////////////////////////////////////////////// // // ::DATASTRUCTURE::CPuffer<T> class source // ///////////////////////////////////////////////////////////////////////////// namespace DATASTRUCTURE { ///////////////////////////////////////////////////////////////////////////// template <class T> CPuffer<T>::CPuffer(const T * pElements, T_ULONG uSize) : ::DATASTRUCTURE::CArray<T>(pElements, uSize) { m_Position = 0; } // CPuffer ///////////////////////////////////////////////////////////////////////////// template <class T> CPuffer<T>::~CPuffer() { } // ~CPuffer ///////////////////////////////////////////////////////////////////////////// template <class T> CPuffer<T>::CPuffer(const CPuffer<T> & tPuffer) : ::DATASTRUCTURE::CArray<T>(tPuffer), m_Position(tPuffer.m_Position) { } // CPuffer ///////////////////////////////////////////////////////////////////////////// template <class T> CPuffer<T> & CPuffer<T>::operator=(const CPuffer<T> & tPuffer) { ::DATASTRUCTURE::CArray<T>::operator=(tPuffer); m_Position = tPuffer.m_Position; return (* this); } // operator= ///////////////////////////////////////////////////////////////////////////// template <class T> T_BOOLEAN CPuffer<T>::IsEmpty() const { return (m_Position >= ::DATASTRUCTURE::CArray<T>::GetSize()); } // IsEmpty ///////////////////////////////////////////////////////////////////////////// template <class T> T & CPuffer<T>::Peek() const { if (IsEmpty() == true) { EXCEPTION(MODULES, ::DATASTRUCTURE::CPuffer, Peek, MESSAGE("is empty")); THROW(EPuffer, IS_EMPTY); } return (::DATASTRUCTURE::CArray<T>::operator[](m_Position)); } // Peek ///////////////////////////////////////////////////////////////////////////// template <class T> T & CPuffer<T>::Next() { T & tResult = Peek(); m_Position = m_Position + 1; return (tResult); } // Next } // namespace DATASTRUCTURE #endif // #ifndef _DATASTRUCTURE_CPUFFER
true
a8dc9e86bb78d46b1d25bcdb4bb85e6d254748e9
C++
mangesh-kurambhatti/Cpp-Programms
/cpp/day2/15. Accept and Input functions using pointers and reference .cpp
UTF-8
767
3.671875
4
[]
no_license
#include<iostream> using namespace std; void AcceptInput(int *ptr); // by address void Printoutput(const int *ptr); void AcceptInput(int &ptr); // by reference void Printoutput(const int &ptr); int main(void) { int no1; // call by address AcceptInput(&no1); Printoutput(&no1); // call by reference AcceptInput(no1); Printoutput(no1); return 0; } void AcceptInput(int *ptr) { cout<<"Enter *ptr ::"; cin>>*ptr; //cin>>ptr; //error // scanf("%d", ptr); //allowed in c return; } void Printoutput(const int *ptr) { cout<<"*ptr="<<*ptr<<endl; return ; } // ptr is reference of no1 void AcceptInput(int &ptr) // by reference { cout<<"enter ptr::"; cin>>ptr; } // ptr is reference of no1 void Printoutput(const int &ptr) { cout<<"ptr :: "<<ptr<<endl; }
true
716b2f875a10f527ed418c0f44223e63079a9843
C++
gwqw/LeetCodeCpp
/Algorithms/medium/355_design_twitter.cpp
UTF-8
7,685
3.671875
4
[]
no_license
/** 355. Design Twitter Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed. Implement the Twitter class: - Twitter() Initializes your twitter object. - void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId. - List<Integer> getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent. - void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId. - void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId. Example 1: Input ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]] Output [null, null, [5], null, null, [6, 5], null, [5]] Explanation Twitter twitter = new Twitter(); twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] twitter.follow(1, 2); // User 1 follows user 2. twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. twitter.unfollow(1, 2); // User 1 unfollows user 2. twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2. Constraints: 1 <= userId, followerId, followeeId <= 500 0 <= tweetId <= 10^4 All the tweets have unique IDs. At most 3 * 10^4 calls will be made to postTweet, getNewsFeed, follow, and unfollow. Algo: getNewsFeed: merge k-sorted lists */ struct Tweet { int tweet_id = 0; int timestamp = 0; unique_ptr<Tweet> next; Tweet(int tweet_id_, int timestamp_, unique_ptr<Tweet> next_) : tweet_id(tweet_id_), timestamp(timestamp_), next(move(next_)) {} friend bool operator<(const Tweet& lhs, const Tweet& rhs) { return lhs.timestamp < rhs.timestamp; } }; struct TweetPtrCompare { bool operator()(Tweet* lhs, Tweet* rhs) const { return *lhs < *rhs; } }; struct User { unique_ptr<Tweet> posts_head; // or list? unordered_set<User*> follow_users; void postTweet(int tweetId, int timestamp) { auto head = make_unique<Tweet>(tweetId, timestamp, move(posts_head)); posts_head = move(head); } void follow(User* user) { follow_users.insert(user); } void unfollow(User* user) { follow_users.erase(user); } vector<int> getNews() { priority_queue<Tweet*, vector<Tweet*>, TweetPtrCompare> pq(TweetPtrCompare{}); if (posts_head) pq.push(posts_head.get()); for (auto user : follow_users) { if (user->posts_head) { pq.push(user->posts_head.get()); } } vector<int> res; res.reserve(10); while (res.size() < 10 && !pq.empty()) { auto head = pq.top(); pq.pop(); res.push_back(head->tweet_id); head = head->next.get(); if (head) pq.push(head); } return res; } }; class Twitter { public: /** Initialize your data structure here. */ Twitter() {} /** Compose a new tweet. */ void postTweet(int userId, int tweetId) { users[userId].postTweet(tweetId, timestamp++); } /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ vector<int> getNewsFeed(int userId) { return users[userId].getNews(); } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ void follow(int followerId, int followeeId) { users[followerId].follow(&users[followeeId]); } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ void unfollow(int followerId, int followeeId) { users[followerId].unfollow(&users[followeeId]); } private: unordered_map<int, User> users; int timestamp = 0; }; // with vector struct Tweet { int tweet_id = 0; int timestamp = 0; Tweet(int tweet_id_, int timestamp_, unique_ptr<Tweet> next_) : tweet_id(tweet_id_), timestamp(timestamp_) {} friend bool operator<(const Tweet& lhs, const Tweet& rhs) { return lhs.timestamp < rhs.timestamp; } }; struct TweetIteratorCmp { bool operator()(deque<Tweet>::const_iterator lhs, deque<Tweet>::const_iterator rhs) { return *lhs < *rhs; } }; struct User { User(const unordered_map<int, User>& users_) : users(users_) {} const unordered_map<int, User>& users; deque<Tweet> posts; unordered_set<int> follow_users; void postTweet(int tweetId, int timestamp) { posts.emplace_front(tweetId, timestamp); } void follow(int user) { follow_users.insert(user); } void unfollow(int user) { follow_users.erase(user); } vector<int> getNews() { priority_queue<deque<Tweet>::const_iterator, vector<deque<Tweet>::const_iterator>, TweetIteratorCmp> pq(TweetIteratorCmp{}); if (!posts.empty()) pq.push(posts.begin()); for (auto user : follow_users) { const auto& p = users.at(user).posts; if (!p) pq.push(p.begin()); } vector<int> res; res.reserve(10); while (res.size() < 10 && !pq.empty()) { auto post_iter = pq.top(); pq.pop(); res.push_back(post_iter->tweet_id); ++post_iter; if (post_iter != cont.end() make IteratorRange) pq.push(post_iter); } return res; } }; class Twitter { public: /** Initialize your data structure here. */ Twitter() {} /** Compose a new tweet. */ void postTweet(int userId, int tweetId) { users[userId].postTweet(tweetId, timestamp++); } /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ vector<int> getNewsFeed(int userId) { return users[userId].getNews(); } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ void follow(int followerId, int followeeId) { users[followerId].follow(&users[followeeId]); } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ void unfollow(int followerId, int followeeId) { users[followerId].unfollow(&users[followeeId]); } private: unordered_map<int, User> users; int timestamp = 0; }; /** * Your Twitter object will be instantiated and called as such: * Twitter* obj = new Twitter(); * obj->postTweet(userId,tweetId); * vector<int> param_2 = obj->getNewsFeed(userId); * obj->follow(followerId,followeeId); * obj->unfollow(followerId,followeeId); */
true
2b0b69488c14a133ba43ddad2f6a113e4b074711
C++
alexandraback/datacollection
/solutions_5688567749672960_0/C++/mikasa/a.cpp
UTF-8
1,014
2.5625
3
[]
no_license
#include<cstdio> #include<cmath> #include<cstring> #include<algorithm> #include<vector> #define pb push_back #define mkp make_pair using namespace std; const int maxn = 1000001; int vis[maxn]; int q[maxn]; int rev(int x) { int r = 0; while(x) { int t = x%10; r = 10*r + t; x/=10; } return r; } void bfs() { vis[1] = 1; int front =1,tail = 0; q[++tail] = 1; while(tail>=front) { int t= q[front++]; if(t+1<maxn&&vis[t+1]==0) { q[++tail] = t+1; vis[t+1] = vis[t]+1; } if(rev(t)<maxn&&vis[rev(t)]==0) { q[++tail] = rev(t); vis[rev(t)] = vis[t]+1; } } //puts("end"); //for(int i=1;i<maxn;i++) // printf("vis[%d]=%d\n",i,vis[i]); } int main() { //printf("%d\n",rev(432)); bfs(); int t,a,cas = 0; scanf("%d",&t); while(t--) { scanf("%d",&a); printf("Case #%d: %d\n",++cas,vis[a]); } }
true
8d336ad9e50e153ed25905bb5dbb99ac6523d5fd
C++
gamehero10/csc305-fall2018-lab3
/src/process.cpp
UTF-8
1,810
3.15625
3
[]
no_license
#ifndef PROCESS #define PROCESS class Process { public: Process(int, int, int, int); ~Process(); /* GETTERS */ int getId(); int getArrival(); int getPriority(); int getExecution(); int getStart(); int getCompletion(); int getTurnaround(); /* SETTERS */ void setId(int); void setArrival(int); void setPriority(int); void setExecution(int); void setStart(int); void setCompletion(int); void setTurnaround(int); private: int unsigned id, arrival, priority, execution; int unsigned start, completion, turnaround; }; #endif Process::Process (int id, int arrival, int priority, int execution) { this->setId(id); this->setArrival(arrival); this->setPriority(priority); this->setExecution(execution); } Process::~Process () {} /* GETTERS */ int Process::getId() { return this->id; } int Process::getArrival() { return this->arrival; } int Process::getPriority() { return this->priority; } int Process::getExecution() { return this->execution; } int Process::getStart() { return this->start; } int Process::getCompletion() { return this->completion; } int Process::getTurnaround() { return this->turnaround; } /* SETTERS */ void Process::setId(int id) { this->id = id; } void Process::setArrival(int arrival) { this->arrival = arrival; } void Process::setPriority(int priority) { this->priority = priority; } void Process::setExecution(int execution) { this->execution = execution; } void Process::setStart(int start) { this->start = start; } void Process::setCompletion(int completion) { this->completion = completion; } void Process::setTurnaround(int turnaround) { this->turnaround = turnaround; }
true
b9e94341665097839148619dea1c1abd56685ad4
C++
carlosgalvezp/DD2425_ht14_ras_utils
/include/ras_utils/ras_utils.h
UTF-8
2,904
2.84375
3
[]
no_license
#ifndef RAS_UTILS_H #define RAS_UTILS_H #include <ctime> #include <sys/time.h> #include <vector> #include <queue> #include <math.h> #include "ros/ros.h" #include <ras_srv_msgs/Command.h> #include <ras_utils/ras_names.h> #include <algorithm> #define PRINT_PADDING 5 namespace RAS_Utils { int sign(double a); double time_diff_ms(const std::clock_t &begin, const std::clock_t &end); double time_diff_ms(struct timeval *begin, struct timeval *end); double time_diff_ms(const ros::WallTime &begin, const ros::WallTime &end); double time_diff_ns(const ros::WallTime &begin, const ros::WallTime &end); void print(const std::string & text); void print(const std::string & text, const double value, std::string & padding); void print(const std::string & text, const double value); void print(const std::string & text, const double value1, const double value2); void print(const std::vector<std::string> & texts, const std::vector<double> & values); double mean(const std::vector<double> &data); double mean(const std::queue<double> &data); double std(const std::vector<double> &data, double mu); double std(const std::vector<double> &data); double std(const std::queue<double> &data); double mahalanobis_distance(const double &x, const double &mu, const double &sigma); double euclidean_distance(double x1, double y1, double x2, double y2 ); double normalize_angle( double angle ); void normalize_probabilities(std::vector<double> &prob); template<typename T> T get_most_repeated(const typename std::vector<T> &vector) { typename std::vector<T>::const_iterator it; typename std::vector<T> visited; typename std::vector<int> count; // ** Count the number of unique elements for(it = vector.begin(); it < vector.end(); ++it) { const T& obj = *it; typename std::vector<T>::iterator found = std::find(visited.begin(), visited.end(), obj); if(found == visited.end()) // Not yet seen { visited.push_back(obj); count.push_back(1); } else { ++count[found-visited.begin()]; } } // ** Get maximum element int maxCount=0; T maxResult; for(std::size_t i=0; i < count.size(); ++i) { if(count[i] > maxCount) { maxCount = count[i]; maxResult = visited[i]; } } return maxResult; } template<typename Iterator> double L2(Iterator begin, Iterator end) { double result = 0.0; for(Iterator it = begin; it < end; ++it) { result += (*it) * (*it); } return sqrt(result); } template<typename Iterator> double dotProduct(Iterator begin1, Iterator end1, Iterator begin2, Iterator end2) { double result = 0.0; for(Iterator it1 = begin1, it2 = begin2; it1 < end1, it2 < end2; ++it1, ++it2) { result += (*it1) * (*it2); } return result; } } #endif // RAS_UTILS_H
true
aa9b7026fce1b38eb00607c0833f0c0561985f17
C++
ARM-software/armnn
/samples/common/src/Audio/MFCC.cpp
UTF-8
11,197
2.609375
3
[ "BSD-3-Clause", "CC0-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // Copyright © 2020 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include "MFCC.hpp" #include "MathUtils.hpp" #include <cfloat> #include <cinttypes> #include <cstring> MfccParams::MfccParams( const float samplingFreq, const int numFbankBins, const float melLoFreq, const float melHiFreq, const int numMfccFeats, const int frameLen, const bool useHtkMethod, const int numMfccVectors): m_samplingFreq(samplingFreq), m_numFbankBins(numFbankBins), m_melLoFreq(melLoFreq), m_melHiFreq(melHiFreq), m_numMfccFeatures(numMfccFeats), m_frameLen(frameLen), m_numMfccVectors(numMfccVectors), /* Smallest power of 2 >= frame length. */ m_frameLenPadded(pow(2, ceil((log(frameLen)/log(2))))), m_useHtkMethod(useHtkMethod) {} std::string MfccParams::Str() { char strC[1024]; snprintf(strC, sizeof(strC) - 1, "\n \ \n\t Sampling frequency: %f\ \n\t Number of filter banks: %u\ \n\t Mel frequency limit (low): %f\ \n\t Mel frequency limit (high): %f\ \n\t Number of MFCC features: %u\ \n\t Frame length: %u\ \n\t Padded frame length: %u\ \n\t Using HTK for Mel scale: %s\n", this->m_samplingFreq, this->m_numFbankBins, this->m_melLoFreq, this->m_melHiFreq, this->m_numMfccFeatures, this->m_frameLen, this->m_frameLenPadded, this->m_useHtkMethod ? "yes" : "no"); return std::string{strC}; } MFCC::MFCC(const MfccParams& params): m_params(params), m_filterBankInitialised(false) { this->m_buffer = std::vector<float>( this->m_params.m_frameLenPadded, 0.0); this->m_frame = std::vector<float>( this->m_params.m_frameLenPadded, 0.0); this->m_melEnergies = std::vector<float>( this->m_params.m_numFbankBins, 0.0); this->m_windowFunc = std::vector<float>(this->m_params.m_frameLen); const auto multiplier = static_cast<float>(2 * M_PI / this->m_params.m_frameLen); /* Create window function. */ for (size_t i = 0; i < this->m_params.m_frameLen; i++) { this->m_windowFunc[i] = (0.5 - (0.5 * cosf(static_cast<float>(i) * multiplier))); } } void MFCC::Init() { this->InitMelFilterBank(); } float MFCC::MelScale(const float freq, const bool useHTKMethod) { if (useHTKMethod) { return 1127.0f * logf (1.0f + freq / 700.0f); } else { /* Slaney formula for mel scale. */ float mel = freq / ms_freqStep; if (freq >= ms_minLogHz) { mel = ms_minLogMel + logf(freq / ms_minLogHz) / ms_logStep; } return mel; } } float MFCC::InverseMelScale(const float melFreq, const bool useHTKMethod) { if (useHTKMethod) { return 700.0f * (expf (melFreq / 1127.0f) - 1.0f); } else { /* Slaney formula for mel scale. */ float freq = ms_freqStep * melFreq; if (melFreq >= ms_minLogMel) { freq = ms_minLogHz * expf(ms_logStep * (melFreq - ms_minLogMel)); } return freq; } } bool MFCC::ApplyMelFilterBank( std::vector<float>& fftVec, std::vector<std::vector<float>>& melFilterBank, std::vector<uint32_t>& filterBankFilterFirst, std::vector<uint32_t>& filterBankFilterLast, std::vector<float>& melEnergies) { const size_t numBanks = melEnergies.size(); if (numBanks != filterBankFilterFirst.size() || numBanks != filterBankFilterLast.size()) { printf("unexpected filter bank lengths\n"); return false; } for (size_t bin = 0; bin < numBanks; ++bin) { auto filterBankIter = melFilterBank[bin].begin(); auto end = melFilterBank[bin].end(); float melEnergy = FLT_MIN; /* Avoid log of zero at later stages */ const uint32_t firstIndex = filterBankFilterFirst[bin]; const uint32_t lastIndex = std::min<uint32_t>(filterBankFilterLast[bin], fftVec.size() - 1); for (uint32_t i = firstIndex; i <= lastIndex && filterBankIter != end; i++) { float energyRep = sqrt(fftVec[i]); melEnergy += (*filterBankIter++ * energyRep); } melEnergies[bin] = melEnergy; } return true; } void MFCC::ConvertToLogarithmicScale(std::vector<float>& melEnergies) { for (float& melEnergy : melEnergies) { melEnergy = logf(melEnergy); } } void MFCC::ConvertToPowerSpectrum() { const uint32_t halfDim = this->m_buffer.size() / 2; /* Handle this special case. */ float firstEnergy = this->m_buffer[0] * this->m_buffer[0]; float lastEnergy = this->m_buffer[1] * this->m_buffer[1]; MathUtils::ComplexMagnitudeSquaredF32( this->m_buffer.data(), this->m_buffer.size(), this->m_buffer.data(), this->m_buffer.size()/2); this->m_buffer[0] = firstEnergy; this->m_buffer[halfDim] = lastEnergy; } std::vector<float> MFCC::CreateDCTMatrix( const int32_t inputLength, const int32_t coefficientCount) { std::vector<float> dctMatrix(inputLength * coefficientCount); const float normalizer = sqrtf(2.0f/inputLength); const float angleIncr = M_PI/inputLength; float angle = 0; for (int32_t k = 0, m = 0; k < coefficientCount; k++, m += inputLength) { for (int32_t n = 0; n < inputLength; n++) { dctMatrix[m + n] = normalizer * cosf((n + 0.5f) * angle); } angle += angleIncr; } return dctMatrix; } float MFCC::GetMelFilterBankNormaliser( const float& leftMel, const float& rightMel, const bool useHTKMethod) { /* By default, no normalisation => return 1 */ return 1.f; } void MFCC::InitMelFilterBank() { if (!this->IsMelFilterBankInited()) { this->m_melFilterBank = this->CreateMelFilterBank(); this->m_dctMatrix = this->CreateDCTMatrix( this->m_params.m_numFbankBins, this->m_params.m_numMfccFeatures); this->m_filterBankInitialised = true; } } bool MFCC::IsMelFilterBankInited() const { return this->m_filterBankInitialised; } void MFCC::MfccComputePreFeature(const std::vector<float>& audioData) { this->InitMelFilterBank(); auto size = std::min(std::min(this->m_frame.size(), audioData.size()), static_cast<size_t>(this->m_params.m_frameLen)) * sizeof(float); std::memcpy(this->m_frame.data(), audioData.data(), size); /* Apply window function to input frame. */ for(size_t i = 0; i < this->m_params.m_frameLen; i++) { this->m_frame[i] *= this->m_windowFunc[i]; } /* Set remaining frame values to 0. */ std::fill(this->m_frame.begin() + this->m_params.m_frameLen,this->m_frame.end(), 0); /* Compute FFT. */ MathUtils::FftF32(this->m_frame, this->m_buffer); /* Convert to power spectrum. */ this->ConvertToPowerSpectrum(); /* Apply mel filterbanks. */ if (!this->ApplyMelFilterBank(this->m_buffer, this->m_melFilterBank, this->m_filterBankFilterFirst, this->m_filterBankFilterLast, this->m_melEnergies)) { printf("Failed to apply MEL filter banks\n"); } /* Convert to logarithmic scale. */ this->ConvertToLogarithmicScale(this->m_melEnergies); } std::vector<float> MFCC::MfccCompute(const std::vector<float>& audioData) { this->MfccComputePreFeature(audioData); std::vector<float> mfccOut(this->m_params.m_numMfccFeatures); float * ptrMel = this->m_melEnergies.data(); float * ptrDct = this->m_dctMatrix.data(); float * ptrMfcc = mfccOut.data(); /* Take DCT. Uses matrix mul. */ for (size_t i = 0, j = 0; i < mfccOut.size(); ++i, j += this->m_params.m_numFbankBins) { *ptrMfcc++ = MathUtils::DotProductF32( ptrDct + j, ptrMel, this->m_params.m_numFbankBins); } return mfccOut; } std::vector<std::vector<float>> MFCC::CreateMelFilterBank() { size_t numFftBins = this->m_params.m_frameLenPadded / 2; float fftBinWidth = static_cast<float>(this->m_params.m_samplingFreq) / this->m_params.m_frameLenPadded; float melLowFreq = MFCC::MelScale(this->m_params.m_melLoFreq, this->m_params.m_useHtkMethod); float melHighFreq = MFCC::MelScale(this->m_params.m_melHiFreq, this->m_params.m_useHtkMethod); float melFreqDelta = (melHighFreq - melLowFreq) / (this->m_params.m_numFbankBins + 1); std::vector<float> thisBin = std::vector<float>(numFftBins); std::vector<std::vector<float>> melFilterBank( this->m_params.m_numFbankBins); this->m_filterBankFilterFirst = std::vector<uint32_t>(this->m_params.m_numFbankBins); this->m_filterBankFilterLast = std::vector<uint32_t>(this->m_params.m_numFbankBins); for (size_t bin = 0; bin < this->m_params.m_numFbankBins; bin++) { float leftMel = melLowFreq + bin * melFreqDelta; float centerMel = melLowFreq + (bin + 1) * melFreqDelta; float rightMel = melLowFreq + (bin + 2) * melFreqDelta; uint32_t firstIndex = 0; uint32_t lastIndex = 0; bool firstIndexFound = false; const float normaliser = this->GetMelFilterBankNormaliser(leftMel, rightMel, this->m_params.m_useHtkMethod); for (size_t i = 0; i < numFftBins; i++) { float freq = (fftBinWidth * i); /* Center freq of this fft bin. */ float mel = MFCC::MelScale(freq, this->m_params.m_useHtkMethod); thisBin[i] = 0.0; if (mel > leftMel && mel < rightMel) { float weight; if (mel <= centerMel) { weight = (mel - leftMel) / (centerMel - leftMel); } else { weight = (rightMel - mel) / (rightMel - centerMel); } thisBin[i] = weight * normaliser; if (!firstIndexFound) { firstIndex = i; firstIndexFound = true; } lastIndex = i; } } this->m_filterBankFilterFirst[bin] = firstIndex; this->m_filterBankFilterLast[bin] = lastIndex; /* Copy the part we care about. */ for (uint32_t i = firstIndex; i <= lastIndex; i++) { melFilterBank[bin].push_back(thisBin[i]); } } return melFilterBank; }
true
91cde0ba47b19d1082cc87422639b786cea88e15
C++
rvignesh/disk-sim
/main.cpp
UTF-8
8,971
2.53125
3
[]
no_license
#include <iostream> #include <set> #include <cmath> #include <vector> #include <cstdlib> #include <iomanip> #include <map> #include <fstream> #include <queue> #include <cassert> extern "C" { #include "genzip.h" } #define CACHE_POLICY 0 #define EVICT_POLICY 0 using namespace std; int find_max_index(int* array,int N,int w,set<int>); int find_min_index(int* array,int N,int w,set<int>); int find_min(map<int,int> ma,bool evict_page); int memory_write=0; int host_write=0; // Page numbering and block numbering starts at zero. //Function that prints the physical disk void print_disk(int* a,int size,int s) { //int k; for(int i=0;i<size;i++) { cout<<"| "<<a[i]<< " |"; } cout<<endl; cout<<"Sim Count"<<s; //cin>>k; } double print_writeampl(int host_write,int memory_write) { return (double)host_write/memory_write; } int find_last_accessed(int *values,set<int> cache_set,int start_index); int main() { ofstream myfile; myfile.open("Min.txt"); queue<int> free_block_queue; set<int> free_set; // static int physical_disk[1024]; // Number of blocks in the total memory const int no_blocks=32; // Number of pages in the total memory const int no_pages=1024; // Number of pages per block const int block_size=32; // Write pointer points the page number that is written tofree_block // Multiply block_size times block number to get write pointer to start of block. starts are zero int write_pointer=0; // free count for all the blocks int free_block_count=31; // the number of pages at which the garbage collection is triggered. int garbage_treshold=5; //evict flag.. specifies if a page is evicted from cache bool evict_flag=false; // currently evicted page int evict_page; bool gc_flag=false; // page that is updated in cache int page_no; //cache set holds the cache elements set<int> cache_set; //cache count, map<int,int> cache_count_map; // Garbage collection flag bool garbage_collect=false; static int dirty_count[no_blocks]; map<int,int> ad_map; map<int,int> block_map; int simulation_count=0; int reclaim_block=0; int num_total_write=0; double alpha=1; int* zipf_values=NULL; zipf_values=NULL; zipf_values=generate_zipf(10000,alpha,32.0*32*27,434); for(int i=1;i<32;i++) { free_block_queue.push(i); free_set.insert(i); } while(num_total_write<10000) { //simulation runs until the user breaks it. int log_address=zipf_values[simulation_count]; int page_no=log_address/32; evict_page=page_no; // IF the page is found in the cache. if(cache_set.find(page_no)!=cache_set.end()) { if(cache_count_map.find(page_no)!=cache_count_map.end()){ map<int,int>::iterator it=cache_count_map.find(page_no); it->second=it->second+1; evict_flag=false; } else{ cache_count_map.insert(pair<int,int>(page_no,1)); evict_flag=false; } } else { if(cache_set.size()<32) { cache_set.insert(page_no); cache_count_map.insert(pair<int,int>(page_no,1)); evict_flag=false; } else { evict_flag=true; //find the index of the minimum element in the map evict_page=find_last_accessed(zipf_values,cache_set,simulation_count+1); //assert(evict_page!=0); cout<<"Evicted Page "<<evict_page<<endl; cache_set.erase(evict_page); cache_set.insert(page_no); cache_count_map.erase(evict_page); cache_count_map.insert(pair<int,int>(page_no,1)); // remove the element at that index from count map and also the set. //do something else } } if(evict_flag==true) { evict_flag=false; if(write_pointer%block_size==0 && write_pointer!=0) { free_block_count--; write_pointer=free_block_queue.front()*block_size; free_set.erase(free_block_queue.front()); free_block_queue.pop(); //print_disk(physical_disk,no_pages); //print_disk(dirty_count,block_size,simulation_count); //cout<<"Write Pointer"<<write_pointer<<endl; } if(ad_map.find(evict_page)!=ad_map.end()) { map<int,int>::iterator it=ad_map.find(evict_page); int block_address=it->second; assert(block_map.find(block_address)!=block_map.end()); block_map.erase(block_address); dirty_count[(block_address)/no_blocks]++; ad_map.erase(evict_page); } memory_write++; host_write++; assert(ad_map.size()==block_map.size()); ad_map.insert(pair<int,int>(evict_page,write_pointer)); if(block_map.find(write_pointer)!=block_map.end()) cout<<"Failed here!"<<write_pointer<<endl; block_map.insert(pair<int,int>(write_pointer,evict_page)); write_pointer++; if(free_block_queue.size()<5) { if(CACHE_POLICY==0) reclaim_block=find_max_index(dirty_count,no_blocks,write_pointer/no_blocks,free_set); if(CACHE_POLICY==1) reclaim_block=find_min_index(dirty_count,no_blocks,write_pointer/no_blocks,free_set); if(CACHE_POLICY==2) { int k=rand()%32; while(k==(write_pointer/no_blocks) || free_set.find(k)!=free_set.end()) k=rand()%32; reclaim_block=k; } cout<<"reclaim Block"<<reclaim_block<<"Free Block queue"<<free_block_queue.size(); free_block_count++; dirty_count[reclaim_block]=0; for(int j=0;j<block_size;j++) { if(write_pointer%block_size==0) { free_block_count--; write_pointer=free_block_queue.front()*block_size; free_set.erase(free_block_queue.front()); free_block_queue.pop(); } map<int,int>::iterator it=block_map.find((reclaim_block*block_size)+j); if(it!=block_map.end()) { int mem_address=it->second; assert(ad_map.find(it->second)!=ad_map.end()); ad_map.erase(it->second); block_map.erase(reclaim_block*block_size+j); ad_map.insert(pair<int,int>(mem_address,write_pointer)); block_map.insert(pair<int,int>(write_pointer,mem_address)); write_pointer++; host_write++; } block_map.erase(reclaim_block*block_size+j); } free_block_queue.push(reclaim_block); free_set.insert(reclaim_block); } } num_total_write++; simulation_count++; } simulation_count=0; num_total_write=0; num_total_write=0; myfile<<alpha<<"\t"<<print_writeampl(host_write,memory_write)<<endl; host_write=memory_write=0; alpha=alpha+0.1; while(!free_block_queue.empty()) free_block_queue.pop(); free_set.clear(); ad_map.clear(); block_map.clear(); myfile.close(); } int find_max_index(int* array,int N,int w,set<int> free_set) { int i,k = N-1; int max = 0; for (i = N-1; i >= 0 ; --i) { if (array[i] >= max && i!=w && free_set.find(i)==free_set.end()) { max = (int)array[i]; k = i; } } if(max==0) cout<<"Garbage Collected a Block with zero dirty Pages"; return k; } int find_min_index(int* array,int N,int w,set<int> free_set) { int i,k = 0; int min = 33; for (i = 0; i < N; ++i) { if (array[i] < min && array[i]>1 && i!=w && free_set.find(i)==free_set.end()) { min = (int)array[i]; k = i; } } return k; } int find_last_accessed(int *values,set<int> cache_set,int start_index) { set<int> access_list; int last_index=-1; while(access_list.size()<32 && start_index<10000) { if(cache_set.count(values[start_index]/32)!=0 && access_list.count(values[start_index]/32)==0) { access_list.insert(values[start_index]/32); last_index=start_index; } if(access_list.size()==32) return values[last_index]/32; start_index++; } for(set<int>::iterator it=cache_set.begin();it!=cache_set.end();it++) if(access_list.count((*it))==0) { return *it; } } int find_min(map<int,int> frequencyCount,bool rand_flag) { int currentMax = 9999; int rand_no=rand()%frequencyCount.size(); int arg_max = 0; int c=0; for(map<int,int>::iterator it = frequencyCount.begin(); it != frequencyCount.end(); ++it,c++ ) { if(rand_flag==1 && c==rand_no) { return it->first; } if(it ->second < currentMax) { arg_max = it->first; currentMax = it->second; } } return arg_max; }
true
7731763185b4d82a2a74e390ae6e1727217a3199
C++
lamlemonpie/EDA
/EDA_Lab3/bTree.h
UTF-8
1,949
3.25
3
[]
no_license
// // bTree.h // EDA // // Created by Alejandro Larraondo on 9/4/18. // Copyright © 2018 Alejandro Larraondo. All rights reserved. // #ifndef bTree_h #define bTree_h #include "bNode.h" #include <fstream> #include <stdio.h> using namespace std; template<class T> class bTree { bNode<T> * m_pRoot; public: bTree(); bool Add(T data); void generateDot(string &dot, bNode<T> * node); void getDot(); void showDot(); bNode<T>* root(); }; template<class T> bTree<T>::bTree(){ m_pRoot = NULL; } template<class T> bool bTree<T>::Add(T data){ if(!m_pRoot) m_pRoot = new bNode<T>(data); else{ bNode<T> *p,*q; p = q = m_pRoot; while(q!=NULL){ p=q; if(q->m_data==data) return false; if(q->m_data<data) q=q->m_pRight; else q=q->m_pLeft; } if(p->m_data<data) p->m_pRight = new bNode<T>(data); else p->m_pLeft = new bNode<T>(data); } return true; } template<class T> void bTree<T>::generateDot(string& dot, bNode<T>* node){ if (!node) return; if (node->m_pLeft) dot = dot + to_string(node->m_data) + " -> " + to_string(node->m_pLeft->m_data) + "; \n"; if (node->m_pRight) dot = dot + to_string(node->m_data) + " -> " + to_string(node->m_pRight->m_data) + "; \n"; generateDot(dot, node->m_pLeft); generateDot(dot, node->m_pRight); } template<class T> void bTree<T>::getDot(){ string dot = "digraph G {\n"; generateDot(dot,m_pRoot); dot = dot + "}"; cout << dot<<endl; //Generar archivo dot. ofstream dotFile; dotFile.open("tree.dot"); dotFile << dot; dotFile.close(); } template<class T> void bTree<T>::showDot(){ system("atom tree.dot"); system("dot -Tpng tree.dot -o tree.png"); system("open tree.png"); } template<class T> bNode<T> * bTree<T>::root(){ return m_pRoot; } #endif /* bTree_h */
true
8e7fffdbe7271c8f8186dbf6168c94dd68dfedae
C++
bqqbarbhg/adventofcode
/2015/23/jit.cpp
UTF-8
2,856
2.6875
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include "jit.h" #include <stdio.h> #include <stdlib.h> #include <Windows.h> #include <stdint.h> struct InstReloc { uint32_t off; uint32_t inst; }; typedef void jitFunc(VM*); struct JIT { char *code; uint32_t off; uint32_t *instOff; uint32_t numInst; InstReloc *instRelocs; uint32_t numInstRelocs; }; JIT *jitCreate() { JIT *jit = (JIT*)calloc(sizeof(JIT), 1); jit->code = (char*)VirtualAlloc(NULL, 4*1024, MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE); jit->instOff = (uint32_t*)calloc(sizeof(uint32_t), 1024); jit->instRelocs = (InstReloc*)calloc(sizeof(InstReloc), 1024); jitEmit(jit, "\x8B\x01\x8B\x59\x04", 5); return jit; } void jitEmit(JIT *jit, const char *code, uint32_t length) { memcpy(jit->code + jit->off, code, length); jit->instOff[jit->numInst] = jit->off; jit->off += length; jit->numInst++; } void jitInstReloc(JIT *jit, int32_t offset, uint32_t inst) { InstReloc *ir = &jit->instRelocs[jit->numInstRelocs++]; ir->off = (uint32_t)((int32_t)jit->off + offset); ir->inst = inst; } void jitFinish(JIT *jit) { jitEmit(jit, "\x89\x01\x89\x59\x04\xC3", 6); for (uint32_t i = 0; i < jit->numInstRelocs; i++) { InstReloc *ir = &jit->instRelocs[i]; int32_t off = jit->instOff[ir->inst] - (ir->off + 4); *(uint32_t*)(jit->code + ir->off) += off; } } void jitExec(JIT *jit, VM *vm) { ((jitFunc*)jit->code)(vm); } void jitCompile(JIT *jit, FILE *f) { char line[128]; while (fgets(line, sizeof(line), f)) { char reg; int32_t off; if (sscanf(line, "hlf %c", &reg) == 1) { if (reg == 'a') jitEmit(jit, "\xD1\xE8", 2); else if (reg == 'b') jitEmit(jit, "\xD1\xEB", 2); else exit(1); } else if (sscanf(line, "tpl %c", &reg) == 1) { if (reg == 'a') jitEmit(jit, "\x8D\x04\x40", 3); else if (reg == 'b') jitEmit(jit, "\x8D\x1C\x5B", 3); else exit(1); } else if (sscanf(line, "inc %c", &reg) == 1) { if (reg == 'a') jitEmit(jit, "\x83\xC0\x01", 3); else if (reg == 'b') jitEmit(jit, "\x83\xC3\x01", 3); else exit(1); } else if (sscanf(line, "jmp %d", &off) == 1) { jitEmit(jit, "\xE9\x00\x00\x00\x00", 5); jitInstReloc(jit, -4, (int)jit->numInst - 1 + off); } else if (sscanf(line, "jie %c, %d", &reg, &off) == 2) { if (reg == 'a') jitEmit(jit, "\xA8\x01\x0F\x84\x00\x00\x00\x00", 8); else if (reg == 'b') jitEmit(jit, "\xF6\xC3\x01\x0F\x84\x00\x00\x00\x00", 9); else exit(1); jitInstReloc(jit, -4, (int)jit->numInst - 1 + off); } else if (sscanf(line, "jio %c, %d", &reg, &off) == 2) { if (reg == 'a') jitEmit(jit, "\x83\xF8\x01\x0F\x84\x00\x00\x00\x00", 9); else if (reg == 'b') jitEmit(jit, "\x83\xFB\x01\x0F\x84\x00\x00\x00\x00", 9); else exit(1); jitInstReloc(jit, -4, (int)jit->numInst - 1 + off); } } }
true
117007cca35b4d97ca3e3b389eb42c978df395e1
C++
commshare/easyhttpcpp
/include/easyhttpcpp/Headers.h
UTF-8
2,357
2.890625
3
[ "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "Zlib", "OpenSSL", "BSD-3-Clause", "BSL-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright 2017 Sony Corporation */ #ifndef EASYHTTPCPP_HEADERS_H_INCLUDED #define EASYHTTPCPP_HEADERS_H_INCLUDED #include "Poco/AutoPtr.h" #include "Poco/ListMap.h" #include "Poco/RefCountedObject.h" #include "easyhttpcpp/HttpExports.h" namespace easyhttpcpp { /** * @brief A Headers collect request and response header. */ class EASYHTTPCPP_HTTP_API Headers : public Poco::RefCountedObject { public: typedef Poco::AutoPtr<Headers> Ptr; typedef Poco::ListMap<std::string, std::string> HeaderMap; /** * */ Headers(); Headers(const Headers& original); /** * */ virtual ~Headers(); Headers& operator=(const Headers& original); /** * @brief Add Header element. * @param name header name * @param value header value * @exception HttpIllegalArgumentException */ virtual void add(const std::string& name, const std::string& value); /** * @brief Set Header element. * @param name header name * @param value header value * @exception HttpIllegalArgumentException */ virtual void set(const std::string& name, const std::string& value); /** * @brief Get header value * @param name name to find * @param defaultValue if name is found, default value is returned. * @return value */ virtual const std::string& getValue(const std::string& name, const std::string& defaultValue) const; /** * @brief Check header * @param name name to check * @return if exist true. */ virtual bool has(const std::string& name) const; /** * @brief Get header element count. * @return element count. */ virtual size_t getSize() const; /** * @brief Check if the header has no elements. * @return true if the header is empty, false otherwise */ virtual bool empty() const; /** * @brief Begin Iterator * @return iterator */ virtual HeaderMap::ConstIterator begin() const; /** * @brief End Iterator * @return iterator */ virtual HeaderMap::ConstIterator end() const; /** * @brief Get header by string. * @return string */ virtual std::string toString(); private: HeaderMap m_headerItems; }; } /* namespace easyhttpcpp */ #endif /* EASYHTTPCPP_HEADERS_H_INCLUDED */
true
2ef11b9e9bdcfbf1be118baca30e4572d93df5a2
C++
Aman0002/Leetcode
/longest-common-subsequence/longest-common-subsequence.cpp
UTF-8
644
2.859375
3
[]
no_license
class Solution { public: int longestCommonSubsequence(string text1, string text2) { int n = text1.size(); int m = text2.size(); int **a = new int*[n+1]; for (int i =0 ;i <= n ;i++) { a[i] = new int[m+1]; for (int j =0 ;j<=m ;j++) { if (i==0||j==0) a[i][j]=0; else if (text1[i-1]==text2[j-1]) a[i][j] = 1+a[i-1][j-1]; else a[i][j] = max(a[i-1][j],a[i][j-1]); } } return a[n][m]; } };
true
e39a281cbe8fd72f5cffe6c7f379e53b19f48a75
C++
simpsont-oci/event_dispatcher
/ProactorSystemTimer.cpp
UTF-8
2,541
2.53125
3
[]
no_license
#include "ProactorSystemTimer.h" ProactorSystemTimer::ProactorSystemTimer(ProactorEventDispatcher* ped) : shutdown_(false), timer_id_(INVALID_TIMER), ped_(ped) {} ProactorSystemTimer::~ProactorSystemTimer() { std::unique_lock<std::mutex> lock(mutex_); shutdown_ = true; if (timer_id_ != INVALID_TIMER) { ped_->proactor()->cancel_timer(timer_id_); timer_id_ = INVALID_TIMER; } } void ProactorSystemTimer::expires_after(const SystemTimer::Duration& duration) { std::unique_lock<std::mutex> lock(mutex_); expiry_ = std::chrono::system_clock::now() + duration; } void ProactorSystemTimer::expires_at(const SystemTimer::TimePoint& timepoint) { std::unique_lock<std::mutex> lock(mutex_); expiry_ = timepoint; } SystemTimer::TimePoint ProactorSystemTimer::expiry() const { std::unique_lock<std::mutex> lock(mutex_); return expiry_; } void ProactorSystemTimer::wait() { std::unique_lock<std::mutex> lock(mutex_); check_and_create_timer_i(); cv_.wait(lock); } SystemTimer::ConVarStatus ProactorSystemTimer::wait_for(const SystemTimer::Duration& duration) { std::unique_lock<std::mutex> lock(mutex_); check_and_create_timer_i(); return cv_.wait_for(lock, duration); } SystemTimer::ConVarStatus ProactorSystemTimer::wait_until(const SystemTimer::TimePoint& timepoint) { std::unique_lock<std::mutex> lock(mutex_); check_and_create_timer_i(); return cv_.wait_until(lock, timepoint); } void ProactorSystemTimer::simple_async_wait(const std::shared_ptr<EventProxy>& proxy) { std::unique_lock<std::mutex> lock(mutex_); simple_async_wait_i(proxy); } void ProactorSystemTimer::check_and_create_timer_i() { if (timer_id_ == INVALID_TIMER) { TimePoint now = std::chrono::system_clock::now(); auto sec_delta = std::chrono::duration_cast<std::chrono::seconds>(expiry_ - now).count(); auto usec_delta = std::chrono::duration_cast<std::chrono::microseconds>((expiry_ - now) - std::chrono::seconds(sec_delta)).count(); ped_->proactor()->schedule_timer(*this, 0, ACE_Time_Value(sec_delta, usec_delta)); } } void ProactorSystemTimer::simple_async_wait_i(const std::shared_ptr<EventProxy>& proxy) { if (!shutdown_) { proxies_.emplace_back(proxy); check_and_create_timer_i(); } } void ProactorSystemTimer::handle_time_out(const ACE_Time_Value&, const void* arg) { std::unique_lock<std::mutex> lock(mutex_); for (auto it = proxies_.begin(); it != proxies_.end(); ++it) { ped_->dispatch(*it); } proxies_.clear(); timer_id_ = INVALID_TIMER; cv_.notify_all(); }
true
7f67e4f973b65d7dff806290209779cbb3a55a0b
C++
alexzanderr/ProgrammingProblems
/infoarena/cmmdc/solutie.cpp
UTF-8
489
2.84375
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; typedef unsigned long long ULL; ULL cmmdc(ULL a, ULL b) { unsigned long long rest; while(b) { rest = a % b; a = b; b = rest; } return a; } int main() { ifstream in("cmmdc.in"); ULL a, b; in >> a; in >> b; in.close(); ofstream out("cmmdc.out"); ULL result = cmmdc(a, b); if (result != 1) { out << result; } else { out << 0; } out.close(); return 0; }
true
9083997fccbaa346ac4ad235bd4cd838fdb325f9
C++
xunzhang/lcode
/leetcode/roman-to-integer.cc
UTF-8
670
3.125
3
[]
no_license
class Solution { public: Solution() { table['I'] = 1; table['V'] = 5; table['X'] = 10; table['L'] = 50; table['C'] = 100; table['D'] = 500; table['M'] = 1000; } int romanToInt(string s) { if(s.size() == 1) return table[s[0]]; int result = 0; for(size_t i = 0; i < s.size() - 1; ++i) { if(table[s[i]] < table[s[i+1]]) { result += table[s[i+1]] - table[s[i]]; i += 1; } else { result += table[s[i]]; } } if(table[s[s.size() - 2]] >= table[s[s.size() - 1]]) { result += table[s[s.size() - 1]]; } return result; } private: unordered_map<char, int> table; };
true
ef44c337769dac3a85008fbec953e1e83f25d1ae
C++
BenjaminDurante/Capstone
/Main_Code/Main_Code.ino
UTF-8
3,022
2.953125
3
[]
no_license
/* Main vehicle code For questions contact: benjamin.durante@ucalgary.ca */ //Initializing the various classes used in this main code #include "Pot.h" #include "Pressure.h" #include "SDCard.h" #include "LoadCell.h" #include "MotorControl.h" #include "PIDControl.h" #include "VtoP.h" #include "SpeedData.h" //Comment out once implementing device on the vehicle /* Assigning variables */ //Assigning potentiometer ports char pot1 = A1; char pot2 = A3; //Assigning pressure transducers ports char pressure1 = A0; char pressure2 = A2; //Assigning motor ports for the PWM and direction of the main motor int motordir1 = 7; int motorpwm1 = 6; //Assigning motor ports for the PWM and direction of the bench test motor int motordir2 = 4; int motorpwm2 = 5; //Setting the baud rate int baud = 9600; //Assigning load cell ports for the bench test validation int LOADCELL_DOUT_PIN = 3; int LOADCELL_SCK_PIN = 2; //Initializing the variable that will output all the data String Scope = ""; //Values for PID double Setpoint = 40; double kp = 75; //Proportional double ki = 15; //Integral double kd = 50; //Derivative //Initializes variables to be used for the PID of motor one int pwm1; boolean dir1; //Setup code goes here void setup() { //SDCard.SDCard_Setup(); //Comment this out if there is no SD Card otherwise the program will get stuck here //LoadCell.LoadCell_Setup(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN); //Setup the load cell MotorControl.PWMSetup(motorpwm1, motordir1); //Initializes the motor Serial.begin(baud); //Initializes the serial port while (!Serial) { ; //wait for serial port to connect. Needed for native USB port only //Good practice to include } //delay(1000); //Delay, if determined that it is required //SpeedData.Setup(); //Initializes the speed simulation function. COMMENT out if not testing PIDControl.Setup(); //Initializes the PIDControl. THIS SHOULD BE PLACED NEAR THE END OF THE PROGRAM } // put your main code here, to run repeatedly: void loop() { Setpoint = VtoP.VelocitytoPosition(SpeedData.SpeedSimulation(motordir1, motorpwm1)); //Determines the desired actuator/pistion setpoint based on vehicle speed pwm1 = PIDControl.Run_PWM(Pot.Pot_Distance(pot1, 87, 18, 50), Setpoint , kp , ki , kd ); //Sets the PID and returns a value for the PWM dir1 = PIDControl.Run_Direction(); //Pulls out motor direction from the previous calculation and stores it to the direction variable MotorControl.MotorMoveSmart(motordir1, motorpwm1, pwm1, dir1); //Moves motor based on the output of the PID function //Scope to see current position vs setpoint to validate code. Comment out if using scope within PIDControl.Run_PWM function Scope = String(Pot.Pot_Distance(pot1, 87, 18, 50)) + "," + String(Setpoint); //Shows current position vs setpoint Serial.println(Scope); //Prints data to the serial print //SDCard.SDCard_Write(dataString); //Comment this out if there is no SD Card otherwise the program will get stuck here delay(50); // delay in between reads for stability }
true
aa78c372ceae43b4144ae9a377f67451aee59251
C++
marbrb/practice-contest
/URI/1550.cpp
UTF-8
1,191
2.78125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef vector <int> vi; int level[10001]; bool vis[10001]; void bfs(int a, int b, vi *adj) { vis[a] = true; level[a] = 0; queue<int> q; q.push(a); while(!q.empty()) { int v = q.front(); q.pop(); for (int i=0; i< adj[v].size(); i++) { if(!vis[adj[v][i]]) { if (adj[v][i] == b) { level[b] = level[v] +1; return; } level[adj[v][i]] = level[v] +1; vis[adj[v][i]] = true; q.push(adj[v][i]); } } } } int main() { //david se la come int t, a, b, s; cin >> t; vi *adj = new vi[10001]; string aux; for (int i=0; i<10001; i++){ if (i<10000) adj[i].push_back(i+1); aux = to_string(i); reverse(aux.begin(), aux.end()); s = stoi(aux); if (s <= 10000) adj[i].push_back(s); } while (t--) { for (int i=0; i <10001; i++) level[i]=0; for (int j=0; j<10001; j++) vis[j]=false; cin >> a >> b; bfs(a, b, adj); cout << level[b] << '\n'; } }
true
c644a5f158d0a4855b48a76324674da4371ec4d6
C++
kk-katayama/com_pro
/atcoder/abc/abc154/abc154c.cpp
UTF-8
398
2.65625
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <map> #define rep(i,n) for(int i=0;i<n;++i) #define rep1(i,n) for(int i=1;i<=n;++i) using namespace std; int main() { map<int,int> mp; int n; bool f = true; cin >> n; rep(i,n){ int a; cin >> a; if(mp[a]>0) f = false; mp[a]++; } if(f) cout << "YES" << "\n"; else cout << "NO" << "\n"; return 0; }
true
6531eb656880d89fc067972675475bdfd53df0bd
C++
xchmwang/algorithm
/leetcode/leetcode212/word_searchII.cpp
UTF-8
3,391
3.140625
3
[]
no_license
#include <iostream> #include <string> #include <cstring> #include <vector> #include <set> using namespace std; const int CHSIZE = 30; typedef struct TrieNode { bool is_word; TrieNode *next[CHSIZE]; TrieNode(): is_word(false) { memset(next, 0, sizeof(next)); } }TrieNode; const int dir[][2] = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; class Solution { public: void init(vector<vector<char> >& board, vector<string>& words) { board_2d = board; row = board.size(); if (row == 0) col = 0; else col = board[0].size(); root = new TrieNode(); build_trie(words); return; } void build_trie(vector<string>& words) { for (int i = 0; i < words.size(); ++i) { TrieNode *p = root; for (int j = 0; j < words[i].length(); ++j) { int idx = words[i][j]-'a'; if (p->next[idx] == NULL) { p->next[idx] = new TrieNode(); } p = p->next[idx]; } p->is_word = true; } return; } void dfs(TrieNode *t, int r, int c, vector<char> &word, vector<vector<bool> > &visit) { int idx = board_2d[r][c]-'a'; if (t->next[idx] == NULL) return; t = t->next[idx]; if (t->is_word) { string str; for (int i = 0; i < word.size(); ++i) { str += word[i]; } s.insert(str); } for (int i = 0; i < sizeof(dir)/sizeof(dir[0]); ++i) { int dr = r+dir[i][0], dc = c+dir[i][1]; if (dr>=0 && dr<row && dc>=0 && dc<col && !visit[dr][dc]) { visit[dr][dc] = true; word.push_back(board_2d[dr][dc]); dfs(t, dr, dc, word, visit); word.pop_back(); visit[dr][dc] = false; } } return; } vector<string> findWords(vector<vector<char> >& board, vector<string>& words) { init(board, words); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { vector<char> word; vector<vector<bool> > visit(row, vector<bool>(col, false)); word.push_back(board[i][j]); visit[i][j] = true; dfs(root, i, j, word, visit); } } set<string>::iterator iter = s.begin(); for ( ; iter != s.end(); ++iter) { v.push_back(*iter); } return v; } private: TrieNode *root; vector<vector<char> > board_2d; int row, col; set<string> s; vector<string> v; }; int main() { char b[4][4] = { {'o', 'a', 'a', 'n'}, {'e', 't', 'a', 'e'}, {'i', 'h', 'k', 'r'}, {'i', 'f', 'l', 'v'} }; int row = sizeof(b)/sizeof(b[0]), col = sizeof(b[0])/sizeof(b[0][0]); vector<vector<char> > board(row, vector<char>(col)); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { board[i][j] = b[i][j]; } } vector<string> words; words.push_back("oath"); words.push_back("pea"); words.push_back("eat"); words.push_back("rain"); Solution sol; vector<string> v = sol.findWords(board, words); for (int i = 0; i < v.size(); ++i) { cout << v[i] << endl; } return 0; }
true
1b0e758f6d700841b1fe425ed609fa8621b0dbbb
C++
juliano7s/box
/main.cpp
UTF-8
1,969
2.65625
3
[]
no_license
#include <iostream> #include <cstdio> #include <assert.h> #include <list> #ifdef _WIN32 #include <Windows.h> #define SLEEP Sleep(3000) #else #define SLEEP usleep(500000) #endif #include "SDL/SDL.h" #include "SDL/SDL_image.h" #include "Matrix.h" #include "Vector2.h" #include "Rectangle.h" #include "TileBase.h" #include "ImageSdl.h" #include "ImageFactory.h" #include "SDLUtils.h" #include "RendererSdl.h" using namespace Box; int main(int argc, char** argv) { std::cout << "Initiating main.." << std::endl; SDL_Surface *displaySurface = NULL; if ((displaySurface = SDLUtils::initSDL()) == NULL) return -1; RendererSdl renderer; renderer.surface(displaySurface); ImageFactory imgFactory; imgFactory.renderer(renderer); ImageBase *img1 = imgFactory.acquire("resources/flash-logo.jpg"); Matrix<Tilei> tileMatrix(30,20); Vector2i tilePos(0,0); for (int i = 0; i < 30*20; i++) { //Tile *t = new Tile(tilePos, Vector2i(30,30)); tilePos.x += 30; //delete t } int x = 0, y = 0; while (true) { // renderer.renderImage(*img1, Vector2i(++x,++y)); img1->draw(Vector2i(x,y)); SDL_Flip(displaySurface); SLEEP; } std::cout << "Indexes: " << std::endl; int currentLine = 0; for (Matrix<Tilei>::iterator it = tileMatrix.begin(), end = tileMatrix.end(); it != end; ++it) { std::pair<int, int> elemPos = Matrix<Tilei>::elementPosition(it); if (elemPos.first != currentLine) { std::cout << std::endl; currentLine = elemPos.first; } std::cout << elemPos.first << "," << elemPos.second << " "; } std::cout << std::endl; std::cout << std::endl; std::cout << "Values: " << std::endl; for (int i = 0; i < 30; i++) { for (int j = 0; j < 20; j++) { std::cout << tileMatrix(i,j).position().x << "," << tileMatrix(i,j).position().y << " "; } std::cout << std::endl; } SDL_FreeSurface(displaySurface); SDL_Quit(); std::cout << "Terminating.." << std::endl; return 0; }
true
325d547ea8bae06ec4754cb5e851e44e367ce6c1
C++
Awaken0406/network
/socket/socket/multi_thread.cpp
UTF-8
641
3.109375
3
[]
no_license
#ifndef _WIN32 #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <string.h> int sum = 0; void* thread_summation(void* arg) { int start = ((int*)arg)[0]; int end = ((int*)arg)[1]; while (start <= end) { sum += start; start++; } return NULL; } int main(int argc, char* argv[]) { pthread_t id_t1,id_t2; int range1[] = { 1,5 }; int range2[] = { 6,10 }; pthread_create(&id_t1, NULL, thread_summation, (void*)range1); pthread_create(&id_t2, NULL, thread_summation, (void*)range2); pthread_join(id_t1, NULL); pthread_join(id_t2, NULL); printf("result:%d\n", sum); return 0; } #endif
true
c3ae6d389362a7b9c7c859b97a853593e097193f
C++
ArtemGomer/ProgrammingOnCpp_NSU
/EvmPu/Lab1.cpp
UTF-8
811
3.0625
3
[]
no_license
#include <iostream> #include <cmath> #include <random> #include <time.h> using namespace std; class pi { private: static float getNumber() { return (rand() / (float) RAND_MAX) * (rand() % 2 == 0 ? 1 : (-1)); } public: static float printPi(int N) { unsigned long long inCircle = 0; for (int i = 0; i < N; i++) { if ((powf(getNumber(), 2) + powf(getNumber(), 2)) <= 1) { inCircle++; } } return (4 * inCircle) / (float) N; } }; int main(int argc, char **argv) { struct timespec start, end; clock_gettime(CLOCK_MONOTONIC_RAW, &start); cout << pi::printPi(atoi(argv[1])) << endl; clock_gettime(CLOCK_MONOTONIC_RAW, &end); cout << "Time taken: " << to_string(end.tv_sec - start.tv_sec + 0.000000001 * (end.tv_nsec - start.tv_nsec)) << endl; return 0; }
true
db16288e55a158d7bd95a5fb789b7a0e1044bfbf
C++
AmiArnab/PolyNTT
/CPP/fp.cpp
UTF-8
1,425
2.90625
3
[]
no_license
#include "fp.h" mpz_class FP::P = mpz_class{"536903681",10}; FP::FP() { this->x.set_str("0",10); } FP::FP(mpz_class x) { mpz_mod(this->x.get_mpz_t(),x.get_mpz_t(),this->P.get_mpz_t()); } FP::~FP() { this->x.set_str("0",10); } FP FP::operator=(FP v) { this->x = v.x; return v; } FP FP::operator+(FP v) { FP t; t.x = this->x + v.x; mpz_mod(t.x.get_mpz_t(),t.x.get_mpz_t(),this->P.get_mpz_t()); return t; } FP FP::operator-(FP v) { FP t; t.x = this->x - v.x; mpz_mod(t.x.get_mpz_t(),t.x.get_mpz_t(),this->P.get_mpz_t()); return t; } FP FP::operator!() { FP t; t.x = mpz_class("0",10) - this->x; mpz_mod(t.x.get_mpz_t(),t.x.get_mpz_t(),this->P.get_mpz_t()); return t; } FP FP::operator*(FP v) { FP t; t.x = this->x * v.x; mpz_mod(t.x.get_mpz_t(),t.x.get_mpz_t(),this->P.get_mpz_t()); return t; } FP FP::operator^(mpz_class mexp) { FP t; mpz_powm(t.x.get_mpz_t(),this->x.get_mpz_t(),mexp.get_mpz_t(),this->P.get_mpz_t()); return t; } FP FP::operator~() { FP t; mpz_class iexp = this->P-2; mpz_powm(t.x.get_mpz_t(),this->x.get_mpz_t(),iexp.get_mpz_t(),this->P.get_mpz_t()); return t; } bool FP::operator==(FP v) { return this->x == v.x; } bool FP::operator!=(FP v) { return this->x != v.x; } mpz_class FP::val() { return this->x; } int FP::set(mpz_class v) { this->x = v; return 0; }
true
33977264bf9355ea9bfc8264e00193149c80bdaf
C++
chencorey/TopCoder
/SRM396/DNAString.cpp
UTF-8
1,105
3.1875
3
[]
no_license
// https://community.topcoder.com/stat?c=problem_statement&pm=8584&rd=12168 // This problem was used for: // Single Round Match 396 Round 1 - Division I, Level One // Single Round Match 396 Round 1 - Division II, Level Two #include <string> #include <vector> using namespace std; class DNAString { public: int minChanges(int maxPeriod, vector<string> dna) { string target = ""; for(int i=0; i<dna.size(); i++) { target+=dna[i]; } int result = 2500; for(int i=1; i<=maxPeriod; i++) { int changes = 0; for(int mod = 0; mod<i; mod++) { int j = mod; int counts[4]; for(int k=0; k<4; k++) { counts[k] = 0; } while(j<target.length()) { if(target[j]=='A')counts[0]++; if(target[j]=='C')counts[1]++; if(target[j]=='G')counts[2]++; if(target[j]=='T')counts[3]++; j+=i; } int max = 0; int numLetters = 0; for(int k=0; k<4; k++) { numLetters +=counts[k]; if(counts[k]>max) max = counts[k]; } changes+=numLetters-max; } if(changes<result)result = changes; } return result; } };
true
2d88b8ca0b2591bd0f5857f11097e84b4b0caf6c
C++
Palfore/Evolution-WildFire
/src/Simulation/Creatures/Types/StickBall.cpp
UTF-8
10,962
2.640625
3
[]
no_license
#include "StickBall.h" #include "utility.h" #include "Genome.h" #include "NodeGene.h" #include "MuscleGene.h" #include "BoneGene.h" #include "AxonGene.h" #include "Logger.h" #include "Ball.h" #include "Piston.h" #include "Shapes.h" #include <limits> static Vec* get_head_location(const std::vector<Ball*>& nodes) { Vec* head = &nodes[0]->position; double minZ = -std::numeric_limits<double>::max(); for (const auto& node: nodes) { double nodeZ = node->position.z; head = nodeZ > minZ ? &node->position : head; minZ = nodeZ > minZ ? nodeZ : minZ; } return head; } Genome* StickBall::createGenome(int n, int m, int b, std::vector<unsigned int> sizes) { if (m + b > comb(n)) LOG("Too many connections for valid creature", LogDegree::FATAL, LogType::GENETIC); if (n < 0) LOG("Creature created with 0 nodes.", LogDegree::FATAL, LogType::GENETIC); Genome *g = new Genome(); for (int i = 0; i < n; i++) { g->addGene(new NodeGene(*g)); } for (int i = 0; i < m; i++) { g->addGene(new MuscleGene(n, *g)); } for (int i = 0; i < b; i++) { g->addGene(new BoneGene(n, *g)); } sizes.insert(sizes.begin(), m + 2); sizes.push_back(m); for (unsigned int layer = 0; layer < sizes.size() - 1; layer++) { for (unsigned int i = 0; i < sizes[layer]; i++) { for (unsigned int j = 0; j < sizes[layer+1]; j++) { g->addGene(new AxonGene(i, j, layer, 0, pmRandf(1))); } } } return g; } StickBall::StickBall(const Genome& genome) : Creature(genome), head(nullptr), nodes({}), muscles({}), bones({}), NN(0, genome.getGenes<AxonGene>()) { for (auto const& gene: genome.getGenes<NodeGene>()) { this->nodes.push_back(new Ball(*gene)); } for (auto const& gene: genome.getGenes<MuscleGene>()) { this->muscles.push_back(new Piston(*gene, this->nodes)); } for (auto const& gene: genome.getGenes<BoneGene>()) { this->bones.push_back(new Piston(*static_cast<MuscleGene*>(gene), this->nodes)); } this->head = get_head_location(this->nodes); lowerToGround(); centerCOM(); initCOM = getCOM(); } StickBall::~StickBall() { for (Ball* b : nodes) { delete b; } for (Piston* m : muscles) { delete m; } for (Piston* b : bones) { delete b; } } StickBall::StickBall(const StickBall &other) : Creature(other), head(nullptr), nodes({}), muscles({}), bones({}), NN(other.NN) { for (auto const& node: other.nodes) { this->nodes.push_back(new Ball(*node)); } for (auto const& muscle: other.muscles) { this->muscles.push_back(new Piston(muscle->getIndex1(), muscle->getIndex2(), this->nodes[muscle->getIndex1()], this->nodes[muscle->getIndex2()], muscle->speed)); } for (auto const& bone: other.bones) { this->bones.push_back(new Piston(bone->getIndex1(), bone->getIndex2(), this->nodes[bone->getIndex1()], this->nodes[bone->getIndex2()], bone->speed)); } this->head = get_head_location(this->nodes); } void StickBall::draw(const Scenario*) const { DrawSphere<Appearance::FACE>(*head + Vec(0,0,4), 5, 180.0/3.1415926*atan2(moveTo.y - getCOM().y, moveTo.x - getCOM().x) + 90 ); DrawSphere<Appearance::BLUE>(getCOM(), 0.5); for (auto const& node : this->nodes) { node->draw(); } for (auto const& muscle : this->muscles) { muscle->draw(); } for (auto const& bone : this->bones) { bone->draw(); } } void StickBall::drawBrain(const bool drawLines) const { this->NN.draw(drawLines); } Vec StickBall::calculateCOM() const { Vec COM = Vec(0,0,0); double mass = 0.0; for (auto const& node : this->nodes) { COM += node->position * node->mass; mass += node->mass; } if (mass < 0.000000001) return Vec(0,0,0); return COM / mass; } void StickBall::moveCOMTo(Vec to) { Vec COM = getCOM(); Vec dr = to - COM; for (auto * node : this->nodes) { node->position += dr; } } void StickBall::lowerToGround() { double dz = this->getLowestBodyHeight() - 1; //-1 for not embeding creatures/padding for (auto * node : this->nodes) { node->position.z -= dz; } } double StickBall::getLowestBodyHeight() const { double minHeight = std::numeric_limits<double>::max(); for (auto const& node : this->nodes) { double lowestPart = node->position.z - node->radius; minHeight = lowestPart < minHeight ? lowestPart : minHeight ; } return minHeight; } Vec StickBall::getTop(const double offset=0) const { double highestNode = -std::numeric_limits<double>::max(); double comX = 0; double comY = 0; double mass = 0.0; for (auto const& node : this->nodes) { highestNode = node->position.z > highestNode ? node->position.z : highestNode; comX += node->position.x * node->mass; comY += node->position.y * node->mass; mass += node->mass; } return Vec(comX / mass, comY / mass, highestNode + offset); } void StickBall::update(Scenario*, int t) { return; const double dt = 1.0; // this->prevCOM = this->com; for (auto const& node: this->nodes) { node->acceleration = Vec(0, 0, -0.0066); } std::vector<double> inputs(this->muscles.size()); // std::transform(this->nodes.begin(), this->nodes.end(), inputs.begin(), [this](const Ball* ball) { // return tanh(0.01*(ball->position.x - moveTo.x)); // }); // std::transform(this->nodes.begin(), this->nodes.end(), inputs.begin() + this->nodes.size(), [this](const Ball* ball) { // return tanh(0.01*((ball->position.y - moveTo.y) / 6 - 1)); // }); // std::transform(this->nodes.begin(), this->nodes.end(), inputs.begin() + 2*this->nodes.size(), [this](const Ball* ball) { // return tanh(0.01*((ball->position.z - moveTo.z) / 6 - 1)); // }); std::vector<double> musclePercentages(this->muscles.size()); std::transform(this->muscles.begin(), this->muscles.end(), inputs.begin(), [](const Piston* muscle) { return (euc(muscle->getPosition1(), muscle->getPosition2()) / muscle->initialLength - 1.0) / (1.2 - 1.0); }); // const double a = acosh(10) / (this->moveTo.x + 0.3); // This scaling is probably wrong, because of (moveTo.x = 0) // const double b = acosh(10) / (this->moveTo.y + 0.3); // find out why +0.1 works, but +2 doesnt. const double distanceFactorX = tanh(0.01*(getCOM().x - this->moveTo.x)); //should be +/-(something) depending on direction => tanh const double distanceFactorY = tanh(0.01*(getCOM().y - this->moveTo.y)); inputs.push_back(distanceFactorX); inputs.push_back(distanceFactorY); std::vector<double> desiredChanges = NN.propagate(inputs); /* Get Muscle Forces : Find force needed to get to this frames length */ for (unsigned int i = 0; i < this->muscles.size(); i++) { Piston * muscle = this->muscles[i]; double currLength = euc(muscle->getPosition1(), muscle->getPosition2()); static constexpr double L = acosh(10); double stretch = currLength / muscle->initialLength - 1; double factor = 1.0 / cosh(L/0.4 * stretch); // maxes at stretch=1, ie best power at normal length double desiredLength = muscle->initialLength; double newFactor = (sgn<double>(stretch) * sgn<double>(factor) > 0 ? factor : 1); // Reduce movement capability if changing length away from init. desiredLength = currLength + 0.05 * desiredChanges[i] * newFactor; desiredLength *= exp(-0.01*(stretch)); // Low powered return to original length // desiredLength = muscle->initialLength * (1 + 0.2 * sin(0.005 * muscle->speed * (10* ((t) / dt)))); double deviation = desiredLength - currLength; Vec radVector = (muscle->getPosition1() - muscle->getPosition2()); Vec deltaAcc = radVector * (deviation * 0.5) / (radVector.length() * dt * dt); this->nodes[muscle->getIndex1()]->acceleration += deltaAcc; this->nodes[muscle->getIndex2()]->acceleration -= deltaAcc; } for (Piston * bone: this->bones) { double currLength = euc(bone->getPosition1(), bone->getPosition2()); double desiredLength = bone->initialLength; double deviation = desiredLength - currLength; Vec radVector = (bone->getPosition1() - bone->getPosition2()); Vec deltaAcc = radVector * (deviation * 0.4) / (radVector.length() * dt * dt); this->nodes[bone->getIndex1()]->acceleration += deltaAcc; this->nodes[bone->getIndex2()]->acceleration -= deltaAcc; } for (auto const& node: this->nodes) { /// Apply Constraints if (node->position.z < 1.03*node->radius) { // convert to exponential decay node->velocity.x *= (1 - (node->mass + 0.5) / NodeGene::MAX_MASS * 0.75 * dt) ;// * (isinf(x) || (x>100)? 1 : x / sqrt(1 + x*x)); node->velocity.y *= (1 - (node->mass + 0.5) / NodeGene::MAX_MASS * 0.75 * dt) ;// * (isinf(y) || (y>100)? 1 : y / sqrt(1 + y*y)); } if (node->position.z < 1.01*node->radius) { node->position.z = node->radius; node->velocity.z *= (1 - (node->mass + 0.5) / (NodeGene::MAX_MASS+0.5) * 0.1 * dt); // +0.5, so no v.z*=0 nodes. } node->velocity *= 1 - 0.01 * dt; /// Apply Kinematics node->velocity += node->acceleration * dt; node->position += node->velocity * dt; } // this->moveCOMTo(Vec(com.x, 0, com.z)); // Keep it two-d (confined to the x-z plane). // this->com = getCOM(); if (t > 0) return; } std::string StickBall::getGenomeString() const { std::string genomeString = Creature::getGenomeString(); for (auto const& node : this->nodes) { genomeString += Gene::toStringFormat(std::vector<std::string>({std::string(1, NodeGene::symbol), utility::numToStr<double>(node->position.x), utility::numToStr<double>(node->position.y), utility::numToStr<double>(node->position.z), utility::numToStr<double>(node->mass) })); } for (auto const& muscle : this->muscles) { genomeString += Gene::toStringFormat(std::vector<std::string>({std::string(1, MuscleGene::symbol), utility::numToStr<double>(muscle->getIndex1()), utility::numToStr<double>(muscle->getIndex2()), utility::numToStr<double>(muscle->speed) })); } for (auto const& bone : this->bones) { genomeString += Gene::toStringFormat(std::vector<std::string>({std::string(1, BoneGene::symbol), utility::numToStr<double>(bone->getIndex1()), utility::numToStr<double>(bone->getIndex2()) })); } return genomeString; }
true
db31c25394dbe70f7d6c7b27b20bafb62184d5b3
C++
YeonWon123/2019_Winter_Data_Structure
/Week 8/준규/이중연결리스트.cpp
UTF-8
1,699
3.203125
3
[]
no_license
#include <iostream> using namespace std; typedef struct _node { int data; struct _node* next; struct _node* prev; } Node; int main(void) { Node nodeArr[100]; int N, M; // 2 <= N <= 100, 0 <= M <= 10 cin >> N >> M; nodeArr[0].prev = NULL; nodeArr[N - 1].next = NULL; for (int i = 0; i < N; i++) { cin >> nodeArr[i].data; if (i != 0) { nodeArr[i].prev = &nodeArr[i - 1]; nodeArr[i - 1].next = &nodeArr[i]; } } Node* node = &nodeArr[0]; for (int i = 0; i < M; i++) { char op; int a, b; Node* node_a = NULL; Node* node_b = NULL; cin >> op >> a >> b; if (a == b) continue; for (int j = 0; j < N; j++) { if (nodeArr[j].data == a) node_a = &nodeArr[j]; if (nodeArr[j].data == b) node_b = &nodeArr[j]; if (node_a != NULL && node_b != NULL) break; } switch (op) { case 'A': if (node_a->prev != NULL) node_a->prev->next = node_a->next; if (node_a->next != NULL) node_a->next->prev = node_a->prev; node_a->prev = node_b->prev; node_a->next = node_b; if (node_b->prev != NULL) node_b->prev->next = node_a; node_b->prev = node_a; break; case 'B': if (node_a->prev != NULL) node_a->prev->next = node_a->next; if (node_a->next != NULL) node_a->next->prev = node_a->prev; node_a->prev = node_b; node_a->next = node_b->next; if (node_b->next != NULL) node_b->next->prev = node_a; node_b->next = node_a; break; default: break; } } while (true) { if (node->prev == NULL) break; node = node->prev; } for (int i = 0; ; i++) { cout << node->data << " "; if (node->next == NULL) break; node = node->next; } return 0; }
true
d5bff491283463e653b1f01c8135cbc5903c9e08
C++
iiabaloongroup/cutdown_mechanism
/write_zeros_eeprom.ino
UTF-8
275
2.765625
3
[]
no_license
#include<EEPROM.h> unsigned int read_bytes = 1000; void setup() { Serial.begin(115200); delay(5000); } void loop() { unsigned int i; for (i=0;i<read_bytes;i++) { EEPROM.write(i,0); delay(10); } Serial.print("Done formatting"); while(1); }
true
5191ee45d331a3a14504416d1834e6a90facf379
C++
NarutoCoder/CompetitveProgramming
/C++/Fundamentals/SalaryCount.cpp
UTF-8
562
3.296875
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; int main() { double basic_Salary; char allow; cin>>basic_Salary>>allow; int grade; if(allow == 'A'){ grade = 1700; }else if(allow == 'B'){ grade = 1500; }else{ grade = 1300; } double hra = basic_Salary * 0.2; double da = basic_Salary * 0.5; double pf = basic_Salary * 0.11; double total_Salary = hra + basic_Salary + da + grade - pf; int ans = round(total_Salary); cout<<ans<<endl; }
true
f2cfba9be5f2177c17b67c7c81e797f84017049c
C++
Torrizo/C-
/BinaryTree.cpp
WINDOWS-1252
2,291
3.484375
3
[]
no_license
#include<iostream> #include<queue> #include<stack> using namespace std; struct BinaryTreeNode { int m_value; struct BinaryTreeNode* m_left; struct BinaryTreeNode* m_right; }; struct BinaryTreeNode* CreateBinaryNode(int value) { struct BinaryTreeNode*pNode = new BinaryTreeNode(); pNode->m_value = value; pNode->m_left = nullptr; pNode->m_right = nullptr; return pNode; } void ConnectBinaryNode(struct BinaryTreeNode*Parent, struct BinaryTreeNode* lchild, struct BinaryTreeNode* rchild) { if (Parent != NULL) { Parent->m_left = lchild; Parent->m_right = rchild; } } void PrintBinaryNode(const struct BinaryTreeNode*node) { if (node != nullptr) { printf("node value is[%d]\n", node->m_value); } else { printf("this node is nullptr\n"); } } void PreorderTraverseTreeNonRec(BinaryTreeNode* pRoot) { std::stack<struct BinaryTreeNode*> stacknode; if (pRoot != nullptr) { stacknode.push(pRoot); while (!stacknode.empty()) { BinaryTreeNode* tmp = stacknode.top(); //ӡֵ printf("value is[%d]\n", tmp->m_value); stacknode.pop(); if (tmp->m_right) { stacknode.push(tmp->m_right); } if (tmp->m_left) { stacknode.push(tmp->m_left); } } } } void DestroyBinary(struct BinaryTreeNode*node) { if (node != nullptr) { struct BinaryTreeNode*pleft = node->m_left; struct BinaryTreeNode*pright = node->m_right; delete node; node = nullptr; if (pleft != nullptr) { DestroyBinary(pleft); } if (pright != nullptr) { DestroyBinary(pright); } } } int main(int argc, char*argv[]) { struct BinaryTreeNode* node1 = CreateBinaryNode(10); struct BinaryTreeNode* node2 = CreateBinaryNode(6); struct BinaryTreeNode* node3 = CreateBinaryNode(14); struct BinaryTreeNode* node4 = CreateBinaryNode(4); struct BinaryTreeNode* node5 = CreateBinaryNode(8); struct BinaryTreeNode* node6 = CreateBinaryNode(12); struct BinaryTreeNode* node7 = CreateBinaryNode(16); ConnectBinaryNode(node1, node2, node3); ConnectBinaryNode(node2, node4, node5); ConnectBinaryNode(node3, node6, node7); printf("preorder no rec start\n"); PreorderTraverseTreeNonRec(node1); system("pause"); return 0; }
true
609a8714266bbd4fb98051f19ccfd68ce08f9882
C++
alexandraback/datacollection
/solutions_2449486_1/C++/ltaravilse/B.cpp
UTF-8
2,269
2.53125
3
[]
no_license
#include<algorithm> #include<cmath> #include<cstdio> #include<iostream> #include<map> #include<queue> #include<set> #include<sstream> #include<string> #include<vector> #define forn(i,n) for(int i=0;i<(int)n;i++) #define dforn(i,n) for(int i=(int)n-1;i>=0;i--) #define all(v) v.begin(),v.end() using namespace std; int mapa[128][128]; int mapa2[128][128]; bool hayUno(int n, int m) { forn(i,n) forn(j,m) if(mapa2[i][j]==1) return true; return false; } bool calc(int n, int m) { while(hayUno(n,m)==true) { bool b = false; forn(i,n) { bool aux = true; forn(j,m) if(mapa2[i][j]==0) aux=false; if(aux==true) { bool c = false; forn(j,m) if(mapa2[i][j]==1) b = true; forn(j,m) mapa2[i][j] = 2; } } forn(i,m) { bool aux = true; forn(j,n) if(mapa2[j][i]==0) aux = false; if(aux==true) { bool c = false; forn(j,n) if(mapa2[j][i]==1) b = true; forn(j,n) mapa2[j][i] = 2; } } if(b == false && hayUno(n,m)==true) return false; else if(hayUno(n,m)==false) return true; } return true; } int main() { #ifdef ACMTUYO freopen("B-large.in","r",stdin); freopen("B-large.out","w",stdout); #endif int casos; cin >> casos; for(int casito = 1; casito <= casos; casito++) { int n,m; cin >> n >> m; forn(i,n) forn(j,m) cin >> mapa[i][j]; string res = "YES"; for(int h=99;h>=1;h--) { forn(i,n) forn(j,m) { if(mapa[i][j] <=h) mapa2[i][j] = 1; else mapa2[i][j] = 0; } if(calc(n,m)==false) res = "NO"; } cout <<"Case #"<< casito << ": "<< res <<endl; } }
true
2ed3c1c6787d3e2f5e8ceccf5abfbe7d484541bb
C++
frozenMustelid/pfsb
/src/pfMeta.hpp
UTF-8
1,798
2.84375
3
[]
no_license
#ifndef PFMETA_HPP #define PFMETA_HPP #include <string> using namespace std; /* I'd prefer it if all enums are referred to by specifying the enum it came * from. I think namespace is probably the wrong term for this, and something * about "scoped" seems like it could be somehow confusing. Whatever the term * for referring to enums as EnumName::ENUM_VALUE instead of just ENUM_VALUE is * what I mean to type. */ enum CreatureType {ABERRATION = 1, ANIMAL, CONSTRUCT, DRAGON, FEY, HUMANOID, MAGICAL_BEAST, MONSTROUS_HUMANOID, OOZE, OUTSIDER, PLANT, UNDEAD, VERMIN}; enum Size {FINE = 1, DIMINUTIVE, TINY, SMALL, MEDIUM, LARGE, HUGE, GARGANTUAN, COLOSSAL}; struct Abilities{ int str; int strMod; string displayStr; int dex; int dexMod; string displayDex; int con; int conMod; string displayCon; int intelligence; int intMod; string displayInt; int wis; int wisMod; string displayWis; int cha; int chaMod; string displayCha; }; struct AC { int armor = 0; int shield = 0; int dex = 0; int natural = 0; int dodge = 0; int deflection = 0; int sacred = 0; int profane = 0; int insight = 0; int luck = 0; int racial = 0; int size = 0; int trait = 0; int untyped = 0; int totalAc = 10; int flatFootAc; int touchAc; string breakdown; }; struct HitDice{ int d4 = 0; int d6 = 0; int d8 = 0; int d10 = 0; int d12 = 0; int totalHd; int racialHdCount; int bonus = 0; //Intended for flat bonuses, like a construct's size bonus. Bonus HP from CON or CHA (if undead) are calculated as needed. }; struct Maneuvers{ bool agileManuevers = false; int cmb; int cmd; string specialCmb; string specialCmd; }; struct Saves{ bool goodFort = false; bool goodReflex = false; bool goodWill = false; int fort; int reflex; int will; }; #endif
true
9c13fd7c47d0df51b7efbd875a948417cd8f0dda
C++
softdream/robot_underlying
/robot/rikirobot_stm32-keil/RosLibs/riki_msgs/Battery.h
UTF-8
1,617
2.59375
3
[]
no_license
#ifndef _ROS_riki_msgs_Battery_h #define _ROS_riki_msgs_Battery_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace riki_msgs { class Battery : public ros::Msg { public: typedef float _battery_type; _battery_type battery; Battery(): battery(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { float real; uint32_t base; } u_battery; u_battery.real = this->battery; *(outbuffer + offset + 0) = (u_battery.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_battery.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_battery.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_battery.base >> (8 * 3)) & 0xFF; offset += sizeof(this->battery); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { float real; uint32_t base; } u_battery; u_battery.base = 0; u_battery.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_battery.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_battery.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_battery.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->battery = u_battery.real; offset += sizeof(this->battery); return offset; } const char * getType(){ return "riki_msgs/Battery"; }; const char * getMD5(){ return "da7225c3562dd2b9b88bf15aa7eb6a9e"; }; }; } #endif
true
214af22c705f4ebf78e3295b776a5aa3ca6f2b05
C++
prankurgit/PUF_Toolkit
/PUF_Toolkit/PUF_Settings.cpp
UTF-8
31,892
2.90625
3
[]
no_license
#include "PUF_Settings.h" /* * PUF-ToolKit - Settings * * Author: Sebastian Schurig * * Setting Functions for the PUF-ToolKit * */ unsigned int SetInputLen(struct Item *item) /* * Function to calculate the input_length based on the offsets * make sure the offsets and it1->input_file_name are initialized before calling * this function. */ { FILE *fd; unsigned long filesize; // Open the specified file if((fd = fopen(item->input_file_name, "rb")) == NULL) return 12; // Get the filesize fseek(fd, 0, SEEK_END); filesize = ftell(fd); rewind(fd); // Go to the offset_begin position in the file fseek(fd, item->offset_begin, SEEK_SET); //check if both offset_begin dont exceed the filesize do { if ((item->offset_begin + item->offset_end) > filesize) { printf("offset_begin and offset_end exceeds filesize, set them again\n"); DefineOffSetLength(item); } } while ((item->offset_begin + item->offset_end) > filesize); //set the length to be read as the filesize - sum of offsets item->input_length = filesize - item->offset_begin - item->offset_end; printf("input_length : %lu\n", item->input_length); // Check if the chosen part of the PUF-Response is valid if((item->offset_begin+item->input_length) > filesize) return 13; fclose(fd); return 0; } void DefineMode(struct Item *it1) /* * Function to set the mode to 0 - file or 1 - directory */ { char oSet[12]; char *p; unsigned int ch, i = 0; unsigned int error = 0; while (true) { if(error) ErrorMessages(error, i); error = 0; if (fgets(oSet, sizeof(oSet), stdin)) { /* fgets succeeds, scan for newline character */ p = strchr(oSet, '\n'); if (p) { *p = '\0'; //check input if only digits are used for(i = 0; i < sizeof(oSet)-1; i++){ if(oSet[i] != '\0' && !isdigit(oSet[i])){ error = 1; break; } if(oSet[i] == '\0') i = sizeof(oSet); } if(error == 0){ // Set the mode ch = atol(oSet); if (ch != 0 && ch != 1) error = 1; else it1->HW_ENTP_mode = ch; printf("mode set to: %u\n", it1->HW_ENTP_mode); } } else { /* newline not found, flush stdin to end of line */ while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin) ); error = 2; } } else { /* fgets failed, handle error */ cin.clear(); error = 3; } if (!error) break; } } void DefineOffSetLength(struct Item *it1) /* * Function to get the 'offset_begin' and 'length' as user input * * Inputs: * item = pointer to the struct to store the necessary informations * * offset_begin = the amount of bytes (in decimal) that will be script from the beginning * Length = the mount of bytes that will be used (in decimal) */ { char oSet[12]; //char iLength[12]; char *p; unsigned int ch, i = 0; unsigned int error = 0; while(true){ if (error != 0) ClearScreen(); cout << "*******************************************************************************" << endl; cout << "* *" << endl; cout << "* Define the 'offsets' for the PUF-Response: *" << endl; cout << "* *" << endl; cout << "* 0 = use complete binary PUF-Response *" << endl; cout << "* 1 = the first byte will be skipped *" << endl; cout << "* 'x' = 'x' bytes from both ends of file will be skipped *" << endl; cout << "* *" << endl; cout << "*******************************************************************************" << endl; if(error) ErrorMessages(error, i); error = 0; cout << endl << "Type in the offset from beginning of file in bytes (as decimal number): "; if (fgets(oSet, sizeof(oSet), stdin)) { /* fgets succeeds, scan for newline character */ p = strchr(oSet, '\n'); if (p) { *p = '\0'; //check input if only digits are used for(i = 0; i < sizeof(oSet)-1; i++){ if(oSet[i] != '\0' && !isdigit(oSet[i])){ error = 1; break; } if(oSet[i] == '\0') i = sizeof(oSet); } if(error == 0){ // Set the offset_begin it1->offset_begin = atol(oSet); } } else { /* newline not found, flush stdin to end of line */ while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin) ); error = 2; } } else { /* fgets failed, handle error */ cin.clear(); error = 3; } cout << endl << "Type in the offset from end of the file in bytes (as decimal number): "; if (fgets(oSet, sizeof(oSet), stdin)) { /*fgets succeds scan for newline character*/ p = strchr(oSet, '\n'); if (p) { *p = '\0'; //check input if only digits are allowed for (i = 0; i < sizeof(oSet) - 1; i++) { if (oSet[i] != '\0' && !isdigit(oSet[i])) { error = 1; break; } if (oSet[i] == '\0') i = sizeof(oSet); } if (error == 0) it1->offset_end = atol(oSet); } else { /*newline char not found*/ while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin)); error = 2; } } else { /*fgets failed, handle error*/ cin.clear(); error = 3; } if(!error) break; } } void DefineFilename(struct Item *item, int option) /* * Define the filename * * Inputs: * item = pointer to the struct to store the necessary informations * option = definition if the input or output file will be specified * * Options: * 1 = input filename * 2 = output filename * 3 = input filename for Median and Average * 4 = output key filename * 5 = input HD filename */ { char *p; unsigned int ch; char name[52]; unsigned int error = 0; while(true){ ClearScreen(); cout << "*******************************************************************************" << endl; cout << "* *" << endl; if(option == 1) { cout << "* Define the 'Input-File-Name' for the PUF-Response *" << endl;} if(option == 2){ cout << "* Define the 'Output-File-Name' for the Results *" << endl;} if(option == 3) { cout << "* Define the 'Input-File-Name' for the Median and Average *" << endl;} cout << "* *" << endl; cout << "*******************************************************************************" << endl; cout << "* *" << endl; if(option == 1 || option == 3) { cout << "* If the file is in the current working directory: *" << endl;} if(option == 2){ cout << "* If the file should be stored in the current working directory: *" << endl;} cout << "* *" << endl; if(option == 1) { cout << "* -> Use only the filename = input_file1 *" << endl;} if(option == 2) { cout << "* -> Use only the filename = output_file1.txt *" << endl;} if(option == 3) { cout << "* -> Use only the filename = input_file1.txt *" << endl;} cout << "* *" << endl; if(option == 1 || option == 3) { cout << "* If the file is in an sub-folder of the current working directory: *" << endl;} if(option == 2) { cout << "* If the file should be stored in an sub-folder of the current directory: *" << endl;} cout << "* *" << endl; if(option == 1) { cout << "* -> Use the relative path and filename = device1/input_file1 *" << endl;} if(option == 2) { cout << "* -> Use the relative path and filename = device1/output_file1.txt *" << endl;} if(option == 3) { cout << "* -> Use the relative path and filename = device1/input_file1.txt *" << endl;} cout << "* *" << endl; if(option == 1 || option == 3) { cout << "* If the file is not in an sub-folder of the current working directory: *" << endl;} if(option == 2) { cout << "* If the file should be stored somewhere else: *" << endl;} cout << "* *" << endl; if(option == 1) { cout << "* -> Use the full path and filename = C:/User/Data/device1/input_file1 *" << endl;} if(option == 2) { cout << "* -> Use the full path and filename = C:/Data/device1/output_file1.txt *" << endl;} if(option == 3) { cout << "* -> Use the full path and filename = C:/Data/device1/input_file1.txt *" << endl;} cout << "* *" << endl; if(option == 3) { cout << "*******************************************************************************" << endl; cout << "* *" << endl; cout << "* NOTE: The input file for the Median and Average calculation *" << endl; cout << "* has to consist of plain numbers separated with a blank. *" << endl; cout << "* -> Integers and floating point numbers are allowed. *" << endl; cout << "* *" << endl; cout << "* Example: '1 42 0.739 79 0 ...' *" << endl; cout << "* *" << endl;} cout << "*******************************************************************************" << endl; if(error) ErrorMessages(error, 0); error = 0; cout << endl << "Type in the (Path and) Filename : "; if (fgets(name, sizeof(name), stdin)) { /* fgets succeeds, scan for newline character */ p = strchr(name, '\n'); if (p) { if(name[0] == '\n') error = 6; else { *p = '\0'; // Set input/ouput filename if (option == 1 || option == 3) strcpy (item->input_file_name,name); else if (option == 2) strcpy (item->output_file_name,name); } } else { /* newline not found, flush stdin to end of line */ while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin) ); error = 5; } } else { /* fgets failed, handle error */ cin.clear(); error = 3; } if(!error) break; } } void DefinePathname(struct Item *item, int option) /* * Define the pathname * * Inputs: * item = pointer to the struct to store the necessary informations * option = definition if one or more input paths will be specified * * Options: * 1 = one input path * 2 = more input paths */ { char *p; unsigned int ch; char name[102]; char path_numbers[4]; unsigned int number_of_paths = 1; unsigned int i = 0; unsigned int error = 0; bool amount_set = false; while(true){ ClearScreen(); cout << "*******************************************************************************" << endl; cout << "* *" << endl; if(option == 1){ cout << "* Define the 'Input-Path' for the PUF-Responses of the desired device *" << endl;} if(option == 2){ cout << "* Define the 'Input-Paths' for the PUF-Responses of the desired devices *" << endl;} cout << "* *" << endl; cout << "*******************************************************************************" << endl; cout << "* *" << endl; cout << "* If the folder is a sub-folder of the current working directory: *" << endl; cout << "* *" << endl; cout << "* -> Use the relative path = device1 *" << endl; cout << "* *" << endl; cout << "* If the folder is not a sub-folder of the current working directory: *" << endl; cout << "* *" << endl; cout << "* -> Use the full path = C:/User/Data/device1 *" << endl; cout << "* *" << endl; cout << "*******************************************************************************" << endl; if(error) ErrorMessages(error, i); error = 0; if(option == 2 && !amount_set){ cout << endl << "Type in how many different devices folder to use (min = 2, max = 99): "; if (fgets(path_numbers, sizeof(path_numbers), stdin)) { /* fgets succeeds, scan for newline character */ p = strchr(path_numbers, '\n'); if (p) { *p = '\0'; //check input if only digits are used for(i = 0; i < sizeof(path_numbers); i++){ if(path_numbers[i] != '\0' && !isdigit(path_numbers[i])){ error = 1; break; } if(path_numbers[i] == '\0') i = sizeof(path_numbers); } if(error == 0 && atol(path_numbers) > 1){ // Set the amount of paths number_of_paths = atol(path_numbers); error = 0; } else if(error == 0 && atol(path_numbers) == 0){ error = 7; } else if(error == 0 && atol(path_numbers) == 1){ error = 9; } } else { /* newline not found, flush stdin to end of line */ while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin) ); error = 8; } } else { /* fgets failed, handle error */ cin.clear(); error = 3; } if(!error) { amount_set = true; } } if(!error){ for(i = 0; i < number_of_paths; i++){ if(option == 1) cout << endl << "Type in the Path: "; if(option == 2) cout << endl << "Type in Path " << i+1 <<": "; if (fgets(name, sizeof(name), stdin)) { /* fgets succeeds, scan for newline character */ p = strchr(name, '\n'); if (p) { if(name[0] == '\n') { error = 6; break; } else { *p = '\0'; if (option == 1 && error == 0) { item->input_path_name.at(0) = name; } if (option == 2 && error == 0) { // Set the device paths if(i < item->input_path_name.size()) item->input_path_name.at(i) = name; else if(i >= item->input_path_name.size()) item->input_path_name.push_back(name); // handle the vector size if actual input is shorter then the one before if(i+1 == number_of_paths && item->input_path_name.size() > i+1 ){ item->input_path_name.erase(item->input_path_name.begin() + i+1, item->input_path_name.end()); } } } } else { /* newline not found, flush stdin to end of line */ while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin) ); error = 10; break; } } else { /* fgets failed, handle error */ cin.clear(); error = 3; break; } } if(!error) break; } } } /* * BCH-Encoder - Settings * * Author: Sebastian Schurig * * Settings Functions for the BCH-Encoder * */ void DefineFilename_BCH(struct Item *item, int option) /* * Define the filename * * Inputs: * item = pointer to the struct to store the necessary informations * option = definition if the input Key / PUF or output HD file will be specified * * Options: * 1 = input Key filename * 2 = input PUF filename * 3 = output HD filename * 4 = output Key filename * 5 = input HD filename */ { char *h; unsigned int ch; char name[52]; unsigned int error = 0; while(true){ ClearScreen(); cout << "*******************************************************************************" << endl; cout << "* *" << endl; if(option == 1) cout << "* Set the 'File-Name' of the file in which the Key is stored *" << endl; if(option == 2){ cout << "* Set the 'File-Name' of the PUF-Response *" << endl;} if(option == 3) { cout << "* Set the 'File-Name' of the file in which the HelperData will be stored *" << endl;} if(option == 4) { cout << "* Set the 'File-Name' of the file in which the decoded Key will be stored *" << endl;} if(option == 5) { cout << "* Set the 'File-Name' of the file in which the HelperData is stored *" << endl;} cout << "* *" << endl; cout << "*******************************************************************************" << endl; cout << "* *" << endl; if(option == 1 || option == 2 || option == 5) { cout << "* If the file is in the current working directory: *" << endl;} if(option == 3 || option == 4){ cout << "* If the file should be stored in the current working directory: *" << endl;} cout << "* *" << endl; if(option == 1) { cout << "* -> Use only the filename = key_file.txt *" << endl;} if(option == 2) { cout << "* -> Use only the filename = Stellaris_PUF1 *" << endl;} if(option == 3) { cout << "* -> Use only the filename = HelperData_1 *" << endl;} if(option == 4) { cout << "* -> Use only the filename = key_file.txt *" << endl;} if(option == 5) { cout << "* -> Use only the filename = HelperData_1 *" << endl;} cout << "* *" << endl; if(option == 1 || option == 2 || option == 5) { cout << "* If the file is in an sub-folder of the current working directory: *" << endl;} if(option == 3 || option == 4) { cout << "* If the file should be stored in an sub-folder of the current directory: *" << endl;} cout << "* *" << endl; if(option == 1) { cout << "* -> Use the relative path and filename = device1/key_file.txt *" << endl;} if(option == 2) { cout << "* -> Use the relative path and filename = device1/Stellaris_PUF1 *" << endl;} if(option == 3) { cout << "* -> Use the relative path and filename = device1/HelperData_1 *" << endl;} if(option == 4) { cout << "* -> Use the relative path and filename = device1/key_file.txt *" << endl;} if(option == 5) { cout << "* -> Use the relative path and filename = device1/HelperData_1 *" << endl;} cout << "* *" << endl; if(option == 1 || option == 2 || option == 5) { cout << "* If the file is not in an sub-folder of the current working directory: *" << endl;} if(option == 3 || option == 4) { cout << "* If the file should be stored somewhere else: *" << endl;} cout << "* *" << endl; if(option == 1) { cout << "* -> Use the full path and filename = C:/User/Data/device1/key_file.txt *" << endl;} if(option == 2) { cout << "* -> Use the full path and filename = C:/Data/device1/Stellaris_PUF1 *" << endl;} if(option == 3) { cout << "* -> Use the full path and filename = C:/Data/device1/HelperData_1 *" << endl;} if(option == 4) { cout << "* -> Use the full path and filename = C:/User/Data/device1/key_file.txt *" << endl;} if(option == 5) { cout << "* -> Use the full path and filename = C:/Data/device1/HelperData_1 *" << endl;} cout << "* *" << endl; cout << "*******************************************************************************" << endl; if(error) { ErrorMessages(error, 0, 0); ErrorMessages_decode(error, 0); } error = 0; cout << endl << "Type in the (Path and) Filename : "; if (fgets(name, sizeof(name), stdin)) { /* fgets succeeds, scan for newline character */ h = strchr(name, '\n'); if (h) { if(name[0] == '\n') error = 6; else { *h = '\0'; // Set input/ouput filename if (option == 1) strcpy (item->input_Key_name ,name); else if (option == 2) strcpy (item->input_PUF_name,name); else if (option == 3) strcpy (item->output_HD_name,name); else if (option == 4) strcpy (item->output_Key_name,name); else if (option == 5) strcpy (item->input_HD_name,name); } } else { /* newline not found, flush stdin to end of line */ while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin) ); error = 5; } } else { /* fgets failed, handle error */ cin.clear(); error = 3; } if(!error) break; } } void DefineSettings(struct Item *item, int option) /* * Function to get the 'offset' and 'Linear Repetition factor' as user input * * Inputs: * item = pointer to the struct to store the necessary informations * option = definition if the offset or LR factor will be specified * * Options: * 1 = Offset, the amount of bytes (in decimal) that will be skipped from the beginning * 2 = Linear Repetition factor should be 7 or 15 */ { char oSet[12]; char lr[4]; char *h; unsigned int ch, i = 0; unsigned int error = 0; if(option == 1){ while(true){ ClearScreen(); cout << "*******************************************************************************" << endl; cout << "* *" << endl; cout << "* Define the 'offset' for the PUF-Response: *" << endl; cout << "* *" << endl; cout << "* 0 = use the PUF-Response from beginning on *" << endl; cout << "* 1 = the first byte will be skipped *" << endl; cout << "* 'x' = the first 'x' bytes will be skipped *" << endl; cout << "* *" << endl; cout << "*******************************************************************************" << endl; if(error) ErrorMessages(error, i, 0); error = 0; cout << endl << "Type in the offset in bytes (as decimal number): "; if (fgets(oSet, sizeof(oSet), stdin)) { /* fgets succeeds, scan for newline character */ h = strchr(oSet, '\n'); if (h) { *h = '\0'; //check input if only digits are used for(i = 0; i < sizeof(oSet)-1; i++){ if(oSet[i] != '\0' && !isdigit(oSet[i])){ error = 1; break; } if(oSet[i] == '\0') i = sizeof(oSet); } if(error == 0){ // Set the offSet item->offSet = atol(oSet); break; } } else { /* newline not found, flush stdin to end of line */ while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin) ); error = 2; } } else { /* fgets failed, handle error */ cin.clear(); error = 3; } if(!error) break; } } else if(option == 2){ while(true){ ClearScreen(); cout << "*******************************************************************************" << endl; cout << "* *" << endl; cout << "* Define the factor for the Linear Repetition: *" << endl; cout << "* *" << endl; cout << "* 7 = each bit will be repeated seven times *" << endl; cout << "* 15 = each bit will be repeated fifteen times *" << endl; cout << "* *" << endl; cout << "*******************************************************************************" << endl; if(error) ErrorMessages(error, i, 0); error = 0; // Get "LR factor" as user input cout << endl << "Enter the Linear Repetition factor (7 or 15): "; if (fgets(lr, sizeof(lr), stdin)) { /* fgets succeeds, scan for newline character */ h = strchr(lr, '\n'); if (h) { if(lr[0] == '\n') error = 6; else { *h = '\0'; //check input if only digits are used for(i = 0; i < (signed)sizeof(lr)-1; i++){ if(lr[i] != '\0' && !isdigit(lr[i])){ error = 1; break; } if(lr[i] == '\0') i = sizeof(lr); } if(!error){ if(atoi(lr) == 7 || atoi(lr) == 15){ item->LR = atoi(lr); break; } else error = 4; } } } else { /* newline not found, flush stdin to end of line */ while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin) ); error = 2; } } else { /* fgets failed, handle error */ cin.clear(); error = 3; } } } }
true
7107df0d9cb982bec2cf52fcb0998975e1fa9c21
C++
Asega1996/POO
/Segovia_Gallardo_Alejandro/P4/usuario-pedido.hpp
UTF-8
766
2.65625
3
[]
no_license
#ifndef USUARIO_PEDIDO_HPP_ #define USUARIO_PEDIDO_HPP_ #include "usuario.hpp" #include "pedido.hpp" using namespace std; class Pedido; class Usuario; class Usuario_Pedido { public: typedef set<Pedido*> Pedidos; typedef map<Usuario*, Pedidos> UsuarioP; typedef map<Pedido*, Usuario*> PedidoU; void asocia(Usuario& usuario, Pedido& pedido) { usu_ped_[&usuario].insert(&pedido); ped_usu_[&pedido] = &usuario; } void asocia(Pedido& pedido, Usuario& usuario) { asocia(usuario, pedido); } Pedidos& pedidos(Usuario& usuario) { return usu_ped_.find(&usuario)->second; } Usuario* cliente(Pedido& pedido) { return ped_usu_.find(&pedido)->second; } private: UsuarioP usu_ped_; PedidoU ped_usu_; }; #endif
true
bbeacefa154add2d04b686767fa05fc724da9959
C++
cyendra/ACM_Training_Chapter_One
/还是汉诺塔/main.cpp
UTF-8
359
2.53125
3
[]
no_license
#include <iostream> #include <cstdio> using namespace std; int main() { int f[50][2]={0}; int n; f[1][0]=2; f[1][1]=1; while (scanf("%d",&n)) { for (int i=2;i<=n;i++) { f[i][0]=(f[i-1][0]+f[i-1][1])*2; f[i][1]=f[1][0]; } printf("%d\n",(f[n][0]+f[n][1])); } return 0; }
true
310de222b83bff93abb06ab3fc9c7dd4f7d2ea5e
C++
eytienne/esiee-cpp
/src/tp3/mystring.cpp
UTF-8
1,253
3.328125
3
[ "MIT" ]
permissive
#include "./mystring.hpp" #include <cstdio> #include <cstring> #include <iostream> #include <sstream> mystring::mystring(int len, const char *data) { this->len = len; this->data = new char[len]; strncpy(this->data, data, len); } mystring::mystring(const char *init) : mystring((int)strlen(init), init) {} mystring::mystring(const mystring &ms) : mystring(ms.len, ms.data) {} mystring::~mystring() {} string mystring::to_string() const { stringstream ret; char buf[len + 1]; snprintf(buf, len + 1, "%s", data); buf[len] = '\0'; ret << buf; return ret.str(); } void mystring::swap(mystring &rhs) { std::swap(len, rhs.len); std::swap(data, rhs.data); } template <typename T> mystring &mystring::operator=(const T &rhs) { mystring ret(rhs); swap(ret); return *this; } bool mystring::operator==(const mystring &rhs) const { if (this == &rhs) return true; if (len != rhs.len) return false; return strncmp(data, rhs.data, len) == 0; } mystring mystring::operator+(const mystring &rhs) const { mystring ret; ret = *this; strncmp(ret.data + len, rhs.data, rhs.len); ret.len += rhs.len; return ret; } const char &mystring::operator[](int idx) const { return data[idx]; } char &mystring::operator[](int idx) { return data[idx]; }
true
e21ce95bc69d11b923a533b143795ca31b9f33a9
C++
Rezarys/ProjetXML_1
/bus.h
UTF-8
562
3
3
[]
no_license
#ifndef BUS_H #define BUS_H #include <string> using namespace std; class Bus { private: string name; int nb_ports; int bandwith; string type; public: Bus(); Bus(string name, int nb_ports, int bandwith, string type); /** Accesseurs et mutateurs **/ string getName() const; void setName(const string &value); int getNb_ports() const; void setNb_ports(int value); int getBandwith() const; void setBandwith(int value); string getType() const; void setType(const string &value); }; #endif // BUS_H
true
99508f12341d8fcbdc002d60867ab722f8bb03b0
C++
KasiaS999/PO1
/lab6/src/Sum.cpp
UTF-8
236
3.21875
3
[]
no_license
#include "Sum.h" Sum :: Sum( Primitive& A, Primitive& B):_A(A), _B(B){} void Sum ::print() const { std::cout<<"("; _A.print(); std::cout<<"+"; _B.print(); std::cout<<")"; } float Sum ::v() const { return _A.v()+_B.v(); }
true
0106bd6da4634f203cd4c58af0f49fb71b553614
C++
Daratrixx/cpp-gl4-engine
/src/ScriptNode.h
UTF-8
1,382
2.625
3
[]
no_license
#ifndef SCRIPTNODE_H #define SCRIPTNODE_H #include "Types.h" union ScriptValue { Integer integer; Real real; String str; Point point; Region region; void* object; }; class ScriptNode { public: ScriptNode() { } ~ScriptNode() { } virtual ScriptNode* call(ScriptNode** parameter) { return this; } virtual ScriptValue getValue() { return 0; } }; class ScriptValueNode : public ScriptNode { ScriptValueNode() : ScriptNode() { } ScriptValueNode(ScriptValue value) : ScriptNode() { this->value = value; } ~ScriptValueNode(); virtual ScriptNode* call(ScriptNode** parameter) { return this; } virtual ScriptValue getValue() { return value; } private: ScriptValue value; }; class ScriptFunctionNode : public ScriptNode { ScriptValueNode() : ScriptNode() { } ScriptValueNode(ScriptValue(*function)(ScriptNode**)) : ScriptNode() { this->function = function; } ~ScriptValueNode(); virtual ScriptNode* call(ScriptNode** parameter) { value = function(parameter); return this; } virtual ScriptValue getValue() { return value; } private: ScriptValue value; ScriptValue(*function)(ScriptNode**); }; #endif /* SCRIPTNODE_H */
true