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
69f895a2b77e2cf6b5bb519394568ecc43ca7454
C++
ssoo2024/Programmers
/Problems[LV3]/[LV3]GPS.cpp
UTF-8
1,081
2.671875
3
[]
no_license
#include <vector> #include <algorithm> using namespace std; int g[201][201]; int dfs(int n, int pos, vector<int> &gps_log) { if (pos == 1) { return g[gps_log[pos]][1] ? 0 : 1000; } int ans = 1000; for (int i = pos; i > 0; i--) { if(i == 1) return g[gps_log[i]][gps_log[0]] ? 0 : 1000; else{ if (!g[gps_log[i]][gps_log[i - 1]]) { for (int j = 1; j <= n; j++) { if (g[gps_log[i]][j]) { int tmp = gps_log[i - 1]; gps_log[i - 1] = j; ans = min(ans, dfs(n, i - 1, gps_log) + 1); if (ans == 1) return 1; gps_log[i - 1] = tmp; } } return ans; } } } return 0; } int solution(int n, int m, vector<vector<int>> edge_list, int k, vector<int> gps_log) { int answer = 0; for (auto e : edge_list) g[e[0]][e[1]] = g[e[1]][e[0]] = 1; answer = dfs(n, k - 1, gps_log); return answer >= 1000 ? -1 : answer; }
true
680596eb184274899b5635b727ab3693b1cde2bf
C++
MillerRidgeway/OperatingSystems_W18
/Lab4/MemorySubsystemS2018/PhysicalMemory.h
UTF-8
2,840
3.34375
3
[]
no_license
/* Interface to physical memory * * File: PhysicalMemory.h * Author: Mike Goss <mikegoss@cs.du.edu> * * Created on June 29, 2017, 11:45 AM */ #ifndef MEM_PHYSICALMEMORY_H #define MEM_PHYSICALMEMORY_H #include "MemoryDefs.h" #include <cstddef> #include <vector> namespace mem { class PhysicalMemory { public: /** * Constructor * * @param size number of bytes of memory to allocate (must be a multiple * of 16) * @throws std::bad_alloc if insufficient memory */ PhysicalMemory(Addr size) : mem_data(size), byte_count(0) { }; ~PhysicalMemory() { } PhysicalMemory(const PhysicalMemory &other) = delete; // no copy constructor PhysicalMemory(PhysicalMemory &&other) = delete; // no move constructor /** * size - return size of physical memory * * @return number of bytes in physical memory */ Addr size() const { return mem_data.size(); } /** * get_byte - get a single byte from the specified address * * @param dest - destination byte pointer * @param address - address of data in memory */ void get_byte(uint8_t *dest, Addr address); /** * get_bytes - copy a range of bytes to caller buffer * * @param dest where to copy to * @param address source address * @param count number of bytes to copy */ void get_bytes(uint8_t *dest, Addr address, Addr count); /** * get_32 - get a 32 bit (4 byte) value * * @param dest where to copy to * @param address source address */ void get_32(uint32_t *dest, Addr address) { get_bytes(reinterpret_cast<uint8_t*>(dest), address, 4); } /** * put_byte - store a single byte to the specified address * * @param address - address of data in memory * @param data - data to store at address */ void put_byte(Addr address, uint8_t *data); /** * put_bytes - copy a range of bytes into physical memory * * @param address destination in physical memory * @param count number of bytes to copy * @param src source buffer */ void put_bytes(Addr address, Addr count, const uint8_t *src); /** * ValidateAddressRange - check that address range is valid, throw * PhysicalMemoryBoundsException if not. * @param address * @param count */ void ValidateAddressRange(Addr address, Addr count) const; /** * get_byte_count - return total number of bytes transferred so far * to/from physical memory. * * @return count of bytes transferred. */ uint64_t get_byte_count() const { return byte_count; } private: std::vector<uint8_t> mem_data; // Define counter for number of bytes transferred. Can be used as // pseudo-clock for ordering of cache entries. uint64_t byte_count; // increments by one for every request }; } // namespace mem #endif /* MEM_PHYSICALMEMORY_H */
true
abf4c9543fe64b709519399c53d37f6b203ea8bd
C++
spider3177/Lab-5
/q23.cpp
UTF-8
267
3.1875
3
[]
no_license
// first the library #include <iostream> using namespace std; int main(){ //declaring the variables int a; // asking for a number cout<< "Gimme any natural number "<<endl; cin>>a; //formulating while (a>0){ cout<<"Back it up "<< a<<endl; --a; } return 0; }
true
8adbe8028c80e7217f645c626538c154ea924dbd
C++
ebanjo-2/undicht_0.36
/undicht/engine/src/2D/animated_sprite.cpp
UTF-8
1,049
2.640625
3
[]
no_license
#include "animated_sprite.h" namespace undicht { AnimatedSprite::AnimatedSprite() { //ctor } AnimatedSprite::~AnimatedSprite() { //dtor } void AnimatedSprite::setAnimation(Animation2D* animation) { m_current_animation = animation; } void AnimatedSprite::setAnimationTime(float time) { m_animation_time = time; repeatAnimationTime(); } void AnimatedSprite::addAnimationTime(float time_offset) { m_animation_time += time_offset; repeatAnimationTime(); } int AnimatedSprite::getCurrentTextureID() { if(m_current_animation){ return m_current_animation->getTextureID(m_animation_time); } else { return -1; } } void AnimatedSprite::repeatAnimationTime() { float max_time = m_current_animation->getDuration(); while((m_animation_time > max_time) && ((m_animation_time - max_time) > 0)){ m_animation_time -= max_time; } } } // undicht
true
95282d0033471560c4703b83389bf2c4dd431a8c
C++
gbrlas/AVSP
/CodeJamCrawler/dataset/09_23662_49.cpp
UTF-8
555
2.5625
3
[]
no_license
#include <stdio.h> int main(){ int ecase,ecount; int en; char input[10000]; int info[1000]; int i,j,k; int ans; scanf("%d",&ecase); for(ecount=1;ecount<=ecase;ecount++){ scanf("%d",&en); for(i=0;i<en;i++){ scanf("%s",input); info[i]=0; for(j=0;j<en;j++) if(input[j]=='1') info[i]=j; } ans=0; for(i=0;i<en;i++){ for(j=i;j<en;j++) if(info[j]<=i) break; for(k=j;k>i;k--){ int t=info[k]; info[k]=info[k-1]; info[k-1]=t; ans++; } } printf("Case #%d: %d\n",ecount,ans); } return 0; }
true
3b88b21096ac3fac278b99b4e4f0eeacba30ef39
C++
PavelLab/mp2-lab6-TText
/mp2-lab6-test/TTextLink.cpp
WINDOWS-1251
1,655
2.984375
3
[]
no_license
#include "TTextLink.h" #include "TText.h" void* TTextLink::operator new(size_t size) { TTextLink *pLink = MemHeader.pFree; if (MemHeader.pFree != NULL) MemHeader.pFree = MemHeader.pFree->pNext; return pLink; } void TTextLink::operator delete(void *pM) { TTextLink *pLink = (TTextLink*)pM; pLink->pNext = MemHeader.pFree; MemHeader.pFree = pLink; } void TTextLink::IntMemSystem(int size) { // "" MemHeader.pFirst = (TTextLink*)new char[sizeof(TTextLink)*size]; MemHeader.pFree = MemHeader.pFirst; MemHeader.pLast = MemHeader.pFirst + (size - 1); TTextLink *pLink = MemHeader.pFirst; // for (int i = 0; i < size - 1; i++) { pLink->str[0]='\0'; pLink->pNext = pLink + 1; pLink++; } pLink->pNext = NULL; } void TTextLink::PrintFreeLink() { cout << "List of free links" << endl; for (TTextLink *pLink = MemHeader.pFree; pLink != NULL; pLink = pLink->pNext) { cout << pLink->str << endl; } } void TTextLink::MemCleaner(TText &txt) { // for (txt.Reset(); !txt.IsEnd(); txt.GoNext()) { string tmp = "&&&"; tmp += txt.GetLine(); txt.SetLine(tmp); } // for (TTextLink *pLink = MemHeader.pFree; pLink != NULL; pLink = pLink->pNext) { string tmp = "&&&"; tmp += pLink->str; strncpy_s(pLink->str, tmp.c_str(), 80); } // "" for (TTextLink *pLink = MemHeader.pFirst; pLink<=MemHeader.pLast; pLink++) { if (strstr(pLink->str, "&&&") != NULL) { strcpy_s(pLink->str, pLink->str + 3); } else { delete pLink; } } }
true
6d3ab523ab45d93e6f18a9fe995d093dfb901ab8
C++
shauuebbit/procon
/library/util/timer.hpp
UTF-8
1,723
3.375
3
[]
no_license
#pragma once #include <chrono> #include <stack> #include <vector> class Timer { private: std::stack<std::chrono::system_clock::time_point, std::vector<std::chrono::system_clock::time_point>> time_stack; public: Timer() = default; void start() { auto t = std::chrono::system_clock::now(); time_stack.push(t); } std::chrono::system_clock::duration elapse() { auto e = std::chrono::system_clock::now() - time_stack.top(); return e; } std::chrono::system_clock::duration stop() { auto e = this->elapse(); time_stack.pop(); return e; } long double elapse_as_nanoseconds() { return std::chrono::duration_cast<std::chrono::nanoseconds>(this->elapse()).count(); } long double elapse_as_microseconds() { return std::chrono::duration_cast<std::chrono::microseconds>(this->elapse()).count(); } long double elapse_as_milliseconds() { return std::chrono::duration_cast<std::chrono::milliseconds>(this->elapse()).count(); } long double elapse_as_seconds() { return std::chrono::duration_cast<std::chrono::seconds>(this->elapse()).count(); } long double stop_as_nanoseconds() { return std::chrono::duration_cast<std::chrono::nanoseconds>(stop()).count(); } long double stop_as_microseconds() { return std::chrono::duration_cast<std::chrono::microseconds>(stop()).count(); } long double stop_as_milliseconds() { return std::chrono::duration_cast<std::chrono::milliseconds>(stop()).count(); } long double stop_as_seconds() { return std::chrono::duration_cast<std::chrono::seconds>(stop()).count(); } };
true
3a1d1016dc939bc524be4fe7ba44ce3b0928f95a
C++
shnoh171/problem-solving
/backjoon-online-judge/9012-parenthesis/parenthesis.cpp
UTF-8
762
3.28125
3
[]
no_license
#include <iostream> #include <stack> #include <string> using namespace std; // https://www.acmicpc.net/problem/9012 // Not good coding style istream& is_correct_paren(istream& in, ostream& out); int main() { ios_base::sync_with_stdio(false); int num; cin >> num; for (int i = 0; i != num; ++i) is_correct_paren(cin, cout); return 0; } istream& is_correct_paren(istream& in, ostream& out) { string s; stack<int> st; cin >> s; string::size_type size = s.size(); for (string::size_type i = 0; i != size; ++i) { if (s[i] == '(') { st.push(i); } else { if (st.empty()) { out << "NO" << endl; return in; } else { st.pop(); } } } if (st.empty()) out << "YES" << endl; else out << "NO" << endl; return in; }
true
ab82df7cef02bdc9c5bde221e77608f9b53c4b87
C++
burns534/Terrain-generation
/Elements.h
UTF-8
17,393
2.8125
3
[]
no_license
// // Header.h // Game1 // // Created by Kyle Burns on 1/22/20. // Copyright © 2020 Kyle Burns. All rights reserved. // #ifndef Header_h #define Header_h #pragma once #include "NoiseMap.h" #include <fstream> #include "VectorUtility.h" std::ofstream outfile; class Elements { public: unsigned* indices; float* vertices; unsigned vertices_size; float * texCoords; unsigned texCoords_size; NoiseMap* nmap; unsigned triangle_number; vu::vec3 <double> * verts; vu::vec3 <double> * glmverts; float * normals; unsigned normal_number; float * randoms; vu::vec3 <double> * descent; int w,h; Elements(int width, int height) { outfile.open("log.txt"); // allocate arrays w = width; h = height; vertices = new float[3 * width * height]; // contains 12 byte objects storing (x,y,z) floats verts = new vu::vec3 <double> [width * height]; // vertex coordinates nmap = new NoiseMap(width, height); // perlin data randoms = new float[3 * width * height]; // (x,y,z) for each vertex texCoords = new float[2 * width * height]; // (x,y) for each vertex descent = new vu::vec3 <double> [width * height]; // one normal for each vertex texCoords_size = 2 * width * height * 4; triangle_number = 2 * ( width - 1 ) * ( height - 1 ); vertices_size = 3 * width * height * 4; // floats are 4 bytes //double correctionFactor = 0.0025f; // fill vertices with appropriate data unsigned index = 0; for ( int y = 0; y < height; y++) for ( int x = 0; x < width; x++, index += 3) { // need to put in device coords vertices[index] = (2.0f * x / (width - 1)) - 1.0f; verts[y * width + x].x = vertices[index]; // to make normal calculations simpler // already clamped to [0,1] // perlin z values smoothed by exponential function and then raised to 1.5 /* This was done to address the steep slope of the beaches/sand shoals on the map. */ vertices[index + 1] = exp(2.8 * nmap->noisemap[y*width + x]) / 20.0f; // 403 ~= e ^ 6 // if (vertices[index + 1] < 0.165f) // vertices[index + 1] = 0.1625f;// + (correctionFactor * nmap->n->OctavePerlin( x * 50.34f, y * 50.34f, 0, 8, .50, .003f)); // adds noise to water verts[y * width + x].y = vertices[index + 1]; //outfile << "(float (2.0f * y) / (height - 1) - 1.0f:" << (float) ( 2.0f * y) / (height - 1) - 1.0f << "\n"; vertices[index + 2] = (2.0f * y) / (height - 1) - 1.0f; verts[y * width + x].z = vertices[index + 2]; // clamp to [0,1); randoms[index] = (float)(rand() % 2048) / 2048; randoms[index + 1] = (float)(rand() % 2048) / 2048; randoms[index + 2] = (float)(rand() % 2048) / 2048; //std::cout << randoms[index] << "\n"; } indices = new unsigned[6 * (width-1) * (height-1)]; // 3 * 2 floats per "tile", w-1 * h-1 "tiles"" index = 0; for ( unsigned y = 0; y < height - 1; y++) for ( unsigned x = 0; x < width - 1; x++, index += 6) // to move through indices after each 2 triangles are added { // must make sure both triangle are generated clockwise for culling later // triangle 1, clockwise topleft->bottomright->bottomleft indices[index] = y * width + x; indices[index + 1] = (y + 1) * width + x + 1; indices[index + 2] = (y + 1) * width + x; // triangle 2, also clockwise bottomright->topleft->topright indices[index + 3] = (y + 1) * width + x + 1; indices[index + 4] = y * width + x; indices[index + 5] = y * width + x + 1; /* ADD TEXTURE VALUES HERE FOR GRASS TEXTURE */ } for ( unsigned y = 0; y < height ; y += 2) for ( unsigned x = 0; x < width ; x += 4) { /* This will mirror the texture for each tile and allow me to not need two VBO's or more complex techniques. Since it's grass, it shouldn't matter. */ texCoords[y * width + x] = 0.0f; // top left texCoords[y * width + x + 1] = 1.0f; texCoords[y * width + x + 2] = 1.0f; // top right texCoords[y * width + x + 3] = 1.0f; texCoords[(y+1) * width + x] = 0.0f; // bottom left texCoords[(y+1) * width + x + 1] = 0.0f; texCoords[(y+1) * width + x + 2] = 1.0f; // bottom right texCoords[(y+1) * width + x + 3] = 0.0f; } vu::vec3 <double> right, left, up, down, down_right, up_left, up_right, down_left; bool r, l, u, d, dr, ul; vu::vec3 <double> norm1, norm2, norm3, norm4, norm5, norm6; index = 0; normals = new float[3 * width * height]; vu::vec3 <double> tempFaces[8]; /* FIX calculate normals for each vector... and store it in normals array this is done by summing the cross product of surrouding face junctions for each vector... going to have poor edge conditions I imagine */ for ( int y = 0; y < height; y++ ) for ( int x = 0; x < width; x++, index += 3) { // try to make vector to each possible directipn u = d = r = l = ul = dr = false; if ( y - 1 >= 0 && x - 1 < width ) { up_left = verts[(y-1) * width + x - 1] - verts[y * width + x]; ul = true; } if ( y - 1 >= 0 ) { up = verts[(y-1) * width + x] - verts[y * width + x]; u = true; } if ( x - 1 >= 0 ) { left = verts[y * width + x - 1] - verts[y * width + x]; l = true; } if ( x + 1 < width ) { right = verts[y * width + x + 1] - verts[y * width + x]; r = true; } if ( y + 1 < height && x + 1 < width ) { down_right = verts[(y+1) * width + x + 1] - verts[y * width + x]; dr = true; } if ( y + 1 < height ) { down = verts[(y+1) * width + x] - verts[y * width + x]; d = true; } if ( y - 1 >= 0 && x + 1 < width ) up_right = verts[(y-1) * width + x + 1] - verts[y * width + x]; // up_right vertex if ( y + 1 < height && x - 1 >= 0 ) down_left = verts[(y+1) * width + x - 1] - verts[y * width + x]; // down left vertex // calculate each available face normal, minimum of two for the 4 corners, 3 for edges, otherwise all 6; if (u && ul) norm1 = up_left.cross(up) * -1; if (u && r) norm2 = up.cross(right) * -1; if (r && dr) norm3 = right.cross(down_right) * -1; if (dr && d) norm4 = down_right.cross(down) * -1; if (d && l) norm5 = down.cross(left) * -1; if (l && ul) norm6 = left.cross(up_left) * -1; // if(u && ul) norm1 = up_left.cross(up - verts[y * width + x]) * -1; // if(u && r) norm2 = up.cross(right - verts[y * width + x]) * -1; // if(r && dr) norm3 = right.cross(down_right - verts[y * width + x]) * -1; // if(dr && d) norm4 = down_right.cross(down - verts[y * width + x]) * -1; // if(d && l) norm5 = down.cross(left - verts[y * width + x]) * -1; // if(l && ul) norm6 = left.cross(up_left - verts[y * width + x]) * -1; // average these normals vu::vec3 <double> avg = norm1 + norm2 + norm3 + norm4 + norm5 + norm6; avg /= 6; //vu::vec3 <double> avg = (norm1); // this is why only the up vector affected the shading earlier // convert to unit length avg = avg.normalize(); // store in normals array normals[index] = avg.x; normals[index + 1] = avg.y; normals[index + 2] = avg.z; //outfile << "phong normal: " << avg << std::endl; // store direction vectors to adjacent vertices tempFaces[0] = up_left; tempFaces[1] = up; tempFaces[2] = right; tempFaces[3] = down_right; tempFaces[4] = down; tempFaces[5] = left; tempFaces[6] = up_right; tempFaces[7] = down_left; // will store the direction vector of greatest descent, which will be the velocity vector unsigned ind = 0; bool flag = true; for ( unsigned i = 0; i < 8; i++ ) { // if direction vector is less than current most downward if (tempFaces[i].y < tempFaces[ind].y && tempFaces[i].y < 0.0f ) { ind = i; flag = false; } } // store maximum descent vector descent[y * w + x] = tempFaces[ind]; // greatest descent for each vertex stored if (flag) descent[y * w + x].y = -37.0f; //outfile << "Up: " << up.x << ", " << up.y << ", " << up.z << std::endl; // outfile << "Descent values x,y,z: " << tempFaces[ind].x << ", " << tempFaces[ind].y << ", " << tempFaces[ind].z << "\n"; } //for ( int i = 0; i < 1; i++) Erosion(0.1f, 10.0f, 0.0001f, 0.05f); } ~Elements() { delete[] vertices; delete[] indices; delete[] verts; delete[] randoms; outfile.close(); } void Erosion(float alpha, float beta, float gamma, float threshold) { int currentx, currenty; vu::vec2 <int> direction; vu::vec3 <double> gravity(0.0f, -9.8f, 0.0f); float acceleration = 0.0f; float velocity = 0.0f; float drop = 0.0f; double sedimentLoad; // for each vertex for ( int y = 0; y < h; y ++ ) for ( int x = 0; x < w; x ++ ) { int count = 0; currenty = y; currentx = x; sedimentLoad = 0.0f; while(verts[currenty * w + currentx].y > 0.44f && currenty > 0 && currenty < h && currentx > 0 && currentx < w) // while we haven't hit water or done more than 20 iterations and won't access bad memory { // determine if there will be a false alarm // if (descent[currenty * w + currentx].y == -37.0f) // { // // there is no good descent; // break; // } // determine x direction of descent for next array access if (descent[currenty * w + currentx].x > 0) direction.x = 1; else if (descent[currenty * w + currentx].x < 0) direction.x = -1; else direction.x = 0; //outfile << "here: " << currentx << ", " << currenty << ", " << descent[currenty * w + currentx] << std::endl; // determine z direction of descent for next array access if (descent[currenty * w + currentx].z > 0) direction.y = 1; else if (descent[currenty * w + currentx].z < 0) direction.y = -1; else direction.y = 0; // calculate acceleration acceleration = gravity.dot(descent[currenty * w + currentx].normalize()); //outfile << "acceleration: " << acceleration << "descent: " << descent << "\n"; velocity = sqrt(velocity * velocity + 20.0f * acceleration) * (1.0f - alpha); // decrease velocity to simulate friction for each iteration outfile << "velocity: " << velocity << "\n"; // water droplet is no longer moving, drop sediment and terminate if (velocity < threshold) { verts[currenty * w + currentx].y += sedimentLoad; break; } drop = (beta - velocity) / beta; // decrease sediment load proportional to difference in velocity and beta // if ratio is positive then velocity is less than beta and we drop sediment // if ratio is negative then velocity is greater than beta and we pick up sediment vertices[3 * (currenty * w + currentx) + 1] += gamma * drop; verts[currenty * w + currentx].y += gamma * drop; // increase y value by gamma time the sediment drop calculated, deposition inversely proportional to velocity if ( gamma * drop > 0 ) sedimentLoad -= gamma * drop; //outfile << "gamma: " << gamma * drop << std::endl; // change y value of current vertex by 20%, hopefully enough to notice //vertices[3 * (currenty * w + currentx) + 1]; here: // set next vertex to check currenty += direction.y; currentx += direction.x; count++; } outfile << "Count: " << count << "\n"; } // glm::vec3 gravity = glm::vec3(0.0f, -9.8f, 0.0f); // float acceleration; // // will calculate the life of only one raindrop for each vertex on the map // double sedimentLoad = 0.01f; // float velocity = 0; // float drop = 0; // int ex, why; // // deltaX is 10m for each vertex // for ( int y = 0; y < h; y++ ) // for ( int x = 0; x < w; x++ ) // { // ex = x; // why = y; // while( verts[why * w + ex].y > 0.44f && sedimentLoad > threshold) // { // //outfile << glm::normalize(descent[why * w + ex]).x << ", " << glm::normalize(descent[why * w + ex]).y << ", " << glm::normalize(descent[why * w + ex]).z << "\n"; // // calculate acceleration- gravity projected in unit vector direction of greatest descent // float mag = sqrt(pow(descent[why * w + ex].x, 2) + pow(descent[why * w + ex].y, 2) + pow(descent[why * w + ex].z, 2)); // acceleration = glm::dot(descent[why * w + ex] / mag, gravity); // // // calculate magnitude of velocity // velocity = sqrt(velocity * velocity + 20.0f * acceleration) * (1.0f - alpha); // decrease velocity to simulate friction for each iteration // // drop = (beta - velocity) / beta; // decrease sediment load proportional to difference in velocity and beta // // if ratio is positive then velocity is less than beta and we drop sediment // // if ratio is negative then velocity is greater than beta and we pick up sediment // vertices[3 * (why * w + ex) + y] += gamma * drop; // increase y value by gamma time the sediment drop calculated, deposition inversely proportional to velocity // sedimentLoad -= gamma * drop; // // if (directions[y * w + x] == UP && why > 0) why--; // else if(directions[y * w + x] == RIGHT && ex < w - 1) ex++; // else if(directions[y * w + x] == DOWN_RIGHT && ex < w - 1 && why < h - 1) // { // ex++; why++; // } // else if(directions[y * w + x] == DOWN && why < h - 1) why++; // else if (directions[y * w + x] == LEFT && ex > 0) ex--; // else if ( ex > 0 && why > 0 ) // { // ex--; why--; // } // //ex = direction.x + verts[why * w + ex].x + why * w > 0 ? direction.x + verts[why * w + ex].x : -2; // new x position // //why = direction.z + verts[why * w + ex].z + why * w > 0 ? direction.z + verts[why * w + ex].z : -2; // new z position // } // } } }; #endif /* Header_h */
true
8a6ca6ae08ab9f663d90d4b55fcbae02d7afc9a5
C++
ashishpandey2600/Lab10
/Assignment2/q1.cpp
UTF-8
1,236
3.640625
4
[]
no_license
#include<iostream> #include<vector> using namespace std; class vectors{ public: vector<float> name; void create() { name.push_back(3.12); name.push_back(4.54); name.push_back(5.54); } void modify() {float store; cout<<"before modification"<<endl; for(int i=0;i<name.size();i++) { cout<<name[i]; cout<<endl; } cout<<"Enter your values to modify"<<endl; for(int i=0;i<name.size();i++) { cin>>name[i]; } cout<<"after modification"<<endl; for(int i=0;i<name.size();i++) { cout<<name[i]; cout<<endl; } } void multiply() { int num; cout<<"Enter the number to multiply"<<endl; cin>>num; for(int i=0;i<name.size();i++) { name[i]=name[i]*num; } } void display() { cout<<"("; for(int i=0;i<name.size();i++) { cout<<name[i]<<","; } cout<<")"; } }; int main() { vectors obj; obj.create(); obj.modify(); obj.multiply(); obj.display(); return 0; }
true
047668656f68e1dba1c64f3c00ea291e41c6d5e3
C++
jakubbaron/projecteuler
/0035/main.cpp
UTF-8
2,109
3.875
4
[]
no_license
#include <iostream> #include <set> #include <vector> #include <cmath> #include <algorithm> // The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. // // There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. // // How many circular primes are there below one million? auto string_to_int(const std::string& str) noexcept -> uint32_t { // normally we'd check if there are only 0-9 characters, but we assume that // we don't pass anything 'evil' uint32_t out = 0; static const std::vector<uint32_t> pows = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; for(int i = 0; i < str.length(); i++) { out += static_cast<uint32_t>(str[i] - '0') * pows[str.length() - i - 1]; } return out; } auto is_prime(int n) noexcept -> bool { for(int i = 2; i < sqrt(n) + 1; i++) { if (n % i == 0) { return false; } } return true; } auto primes_below(int n) noexcept -> const std::set<int> { std::set<int> primes; primes.emplace(2); for(int candidate = 2; candidate < n; candidate++) { if(is_prime(candidate)) { primes.emplace(candidate); } } return primes; } auto is_circular(int number, const std::set<int>& primes) noexcept -> bool { std::string s = std::to_string(number); for(int i = 0; i < s.size() - 1; i++) { std::rotate(s.begin(), s.begin() + 1, s.end()); if(!primes.count(string_to_int(s))) { return false; } } return true; } auto count_circular_primes_below(int n) noexcept -> size_t { static auto primes(primes_below(n)); size_t count = 0; for(const auto& prime: primes) { if(is_circular(prime, primes)) { //std::cout << "Circular prime: " << prime << std::endl; count++; } } return count; } int main(int argc, char** argv) { static constexpr auto upper_bound = 1000*1000; const auto result = count_circular_primes_below(upper_bound); std::cout << "Number of circular items below[" << upper_bound <<"]: " << result << std::endl; return EXIT_SUCCESS; }
true
64ef7b9370e6e59dfe89fa5b31912fd2b7a8e470
C++
NikeshMaharjan1217/Nikesh-Maharjan
/electricity bill.cpp
UTF-8
300
2.875
3
[]
no_license
#include<stdio.h> #include<conio.h> main() { int n,amt; printf("Enter the value of n:"); scanf("%d",&n); if(n<=80) { amt=1000; } else if(n<=150) { amt=1000+(n-80)*15; } else { amt=1000+70*15+(n-150)*20; } printf("Total bill amount is %d",amt); getch(); }
true
0d642a245d4b63d6a51e4c8865b8a7526f7e543d
C++
Inryu/algorithm
/BOJ/DFS BFS/14502 연구소.cpp
UTF-8
2,606
3.15625
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <queue> #include <cstring> using namespace std; int N,M; int map[10][10]; int tmpMap[10][10]; bool visited[10][10]; //BFS 용 int dr[4]={-1,0,1,0}; int dc[4]={0,1,0,-1}; int maxVal=-1; vector<pair<int,int>> threeWalls(3); //고른 3개의 벽 vector<pair<int,int>> emptySpace; void copyMap(){ for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ tmpMap[i][j]=map[i][j]; } } } //3. 안전 영역 구하기 void countSafeArea(){ int cnt=0; for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ if(tmpMap[i][j]==0) cnt++; } } maxVal=max(cnt,maxVal); } //2. 바이러스 퍼트리기 (BFS) void spreadVirus(){ copyMap(); //벽 3개 고른 거 세워주기 for(int i=0;i<3;i++){ int r=threeWalls[i].first; int c=threeWalls[i].second; tmpMap[r][c]=1; } memset(visited,false,sizeof(visited)); queue<pair<int,int>> q; //퍼질 바이러스들 넣어주기. for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ if(tmpMap[i][j]==2){ q.push({i,j}); visited[i][j]=true; } } } //퍼트리기 while(!q.empty()){ int r=q.front().first; int c=q.front().second; q.pop(); tmpMap[r][c]=2; for(int d=0;d<4;d++){ int nr=r+dr[d]; int nc=c+dc[d]; if(nr<0||nr>N-1||nc<0||nc>M-1||visited[nr][nc]||tmpMap[nr][nc]!=0) continue; q.push({nr,nc}); visited[nr][nc]=true; } } } //1. 벽 3개 고르기 (emptySpace에서 3개 구해야함) DFS void makeWall(int startIdx, int L){ if(L==3) { //3개 조합 구한 경우 spreadVirus(); countSafeArea(); return; } // 조합 구하기 for(int i=startIdx;i<emptySpace.size();i++){ int r=emptySpace[i].first; //🥲인덱스에 startIdx 그냥 넣는 실수🥲 int c=emptySpace[i].second; //🥲인덱스에 startIdx 그냥 넣는 실수🥲 threeWalls[L]=make_pair(r,c); //조합 저장 makeWall(i+1, L+1); //🥲인덱스에 startIdx 그냥 넣는 실수🥲 } } int main() { cin >> N >> M; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int val; cin >> val; map[i][j] = val; if (val == 0) emptySpace.push_back({i, j}); } } //조합 사용해서 emptySpace에서 3개 골라야 함. makeWall(0, 0); cout << maxVal << "\n"; }
true
8c9cda9a48ccc1484e1fe720d7dbea4191411e39
C++
UnsafePointer/opengl-renderer-tests-archived
/src/main.cpp
UTF-8
637
2.921875
3
[]
no_license
#include "Renderer.hpp" int main() { Renderer renderer = Renderer(); std::vector<Vertex> vertices = { Vertex(0.5f, -0.5f, 1.0f, 0.0f, 0.0f), Vertex(-0.5f, -0.5f, 0.0f, 1.0f, 0.0f), Vertex(0.0f, 0.5f, 0.0f, 0.0f, 1.0f) }; bool quit = false; while (!quit) { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { quit = true; } } renderer.addPolygon(vertices); renderer.prepareFrame(); renderer.render(); renderer.finishFrame(); } SDL_Quit(); return 0; }
true
42e2e950127bb36f513e84f11bf51dde387a82e2
C++
Huangxy0106/Renderer
/code/Part2/src/chapter7/depth_reciprocal/lib/include/GraphicsLibrary.h
UTF-8
1,062
2.703125
3
[ "Apache-2.0" ]
permissive
#ifndef _GRAPHICSLIBRARY #define _GRAPHICSLIBRARY #include <GraphicsDevice.h> #include <vector> #include <algorithm> #define ABS(x) ((x)>0?(x):-(x)) class Point4 { public: double X, Y, Z, W; std::vector<double> ValueArray;//本顶点属性集合,在多属性插值MultipleInterpolationArrayIn2D中使用 Point4(double x, double y, double z, double w); Point4 Normalize() const;//将其次坐标规范化后返回,齐次坐标变成三维坐标 Point4 Normalize_special() const;//将其次坐标规范化后返回,齐次坐标变成三维坐标,但是本函数计算后将会保留ω分量,而不是将其置为1 }; class GraphicsLibrary { public: GraphicsLibrary(GraphicsDevice& gd); ~GraphicsLibrary(); void clean_depth(double v);//用于批量设置深度缓冲区的值 void DrawTriangle(const Point4& sa, const Point4& sb, const Point4& sc, int ValueLength, COLORREF(*FragmentShader)(std::vector<double>& values));//ValueLength为顶点的属性值数量 private: GraphicsDevice& graphicsdevice; double *Z_Buffer;//深度缓冲区 }; #endif
true
5c70524c4cfe2ab79b250962b1b3c3cb6262c7c8
C++
salma77/Codeforces
/478A.cpp
UTF-8
214
2.84375
3
[]
no_license
#include <iostream> using namespace std; int main() { int x, sum = 0; for (int i = 0; i < 5; i++) { cin >> x; sum += x; } if (sum % 5 == 0 && sum != 0) cout << sum / 5; else cout << "-1"; return 0; }
true
88cdbadfe4c60374a79518a11d30697f5e9e5f8f
C++
JackCui001/Solutions_for_CodeForces
/A-Set/461A - Appleman and Toastman.cpp
UTF-8
370
2.78125
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> group; long long i,num,temp,sum=0,ans=0; cin>>num; for(i=0;i<num;i++) { cin>>temp; group.push_back(temp); sum+=temp; } sort(group.begin(),group.end()); ans=sum; for(i=0;i<num-1;i++) { ans+=sum; sum-=group[i]; } cout<<ans<<endl; return 0; }
true
4f2ff6bfc8f5937bcb78feac217dbd7f05d01428
C++
purvasingh96/HackerRank-solutions
/algorithm/implementation/Fair Rations.cpp
UTF-8
1,981
2.65625
3
[]
no_license
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int checkalleven(int a[], int n) { int i, flag=0; for(i=0;i<n;i++) { if(a[i]%2==0) { flag=1; } else{ flag=0; break; } } return flag; } int main(){ int n; cin >> n; int b[n]; for(int B_i = 0;B_i < n;B_i++){ cin >> b[B_i]; } int count=0; int k, index; if(checkalleven(b, n)) { cout<<"0"; } else{ for(k=0;k<n;k++) { if(b[k]%2!=0) { index=k; ++b[index]; ++count; if( index!=0 && b[index-1]%2!=0 ) { ++b[index-1]; ++count; } else if (b[index+1]%2!=0 && index!=0 && index!=n-1) { ++b[index+1]; ++count; } else if(index==n-1) { ++b[index-1]; ++count; } else { ++b[index+1]; ++count; } } } /*int j; for(j=0;j<n;j++) { cout<<b[j]<<" "; }*/ if(checkalleven(b, n)) { cout<<count; } else{ cout<<"NO"; } } return 0; }
true
59cdc7598b9776ac2af636908bc0be028dd22bde
C++
BrizziB/SerialKMeans
/cluster.h
UTF-8
1,451
3.140625
3
[]
no_license
// // Created by Boris on 13/03/2017. // #ifndef SERIALKMEANS_CLUSTER_H #define SERIALKMEANS_CLUSTER_H #include <iostream> #include <fstream> #include <string> #include <iterator> #include <algorithm> #include <vector> #include "Point.h" #include <list> class cluster{ private: Point centroid; std::vector<Point> points; int clusterID; public: cluster(Point* clusterCentroid, int id){ centroid = (*clusterCentroid); clusterID = id; } Point* getCentroid(){ return &centroid; } void deletePoints(){ points.clear(); }; void setCentroid(Point* point){ centroid = *point; } void setClusterID(int id){ clusterID=id; } int getClusterID(){ return clusterID; } void addPoint (Point point){ points.push_back(point); } void printPoints(){ /* std::cout<<"\nID di tutti i punti appartenenti al Cluster: "; std::cout<<clusterID; std::cout<<" __\n"; for (std::vector<Point>::iterator it=(points).begin(); it!=(points).end(); ++it){ //ad ogni cluster assegno un centroide std::cout<< it->getId()<<", "; };*/ std::cout<<"\n"; } void changeCentroidAttributes(std::vector<float> attributes){ centroid.setNewAttributes(attributes); } std::vector<Point> getPoints(){ return points; } }; #endif //SERIALKMEANS_CLUSTER_H
true
a0a508ce300537cafaf91212939b2629283f8103
C++
AlonsoCerpa/ComputerNetworks
/UDP_v1/dividir_en_bloques.h
UTF-8
1,633
3.375
3
[]
no_license
#include <vector> #include <fstream> #include <sstream> #include <iostream> using namespace std; int contar_caracteres(char const* filename) { FILE * f; int numero = 0; char caracter; f = fopen (filename, "r"); if (f == NULL) { return -1; } while (feof (f) == 0) { fscanf (f, "%c", &caracter); numero++; } fclose (f); return numero-2; } void imprimir_bloques(vector<vector<char>> &bloques, int columna, int fila) { cout <<endl; for (int i = 0; i < columna; ++i) { for (int j = 0; j < fila; ++j) { cout << bloques[i][j] << " "; } cout << "\n"; } cout << "\n"; } void dividir_archivo_en_bloques(char const* filename) { FILE *archivo = fopen(filename, "r+b"); int size; fseek(archivo,0,SEEK_END); size = ftell(archivo); fseek(archivo, 0, SEEK_SET); int read_size; char send_buffer[size]; read_size = fread(send_buffer, 1, sizeof(send_buffer)-1, archivo); send_buffer[size] = '\0'; for (int j = 0; j < size; ++j) { cout << send_buffer[j] << " "; } int numero_bytes = 8; int numero_letras = contar_caracteres(filename); int numero_bloques = numero_letras / numero_bytes; int modulo = numero_letras % numero_bytes; if (modulo != 0){ numero_bloques++; } cout<<endl; cout << "Matriz de: "<< numero_bloques <<" x "<<numero_bytes<<endl; vector<vector<char>> bloques(numero_bloques, vector<char>(numero_bytes, ' ')); int contador = 0; for (int i = 0; i < numero_bloques; ++i) { for (int j = 0; j < numero_bytes; ++j) { bloques[i][j] = send_buffer[contador]; contador++; } } imprimir_bloques(bloques, numero_bloques, numero_bytes); }
true
4351b54964c1064e6d6b0948521e64421849b7ec
C++
ttdyce/Dynamic-embedding-labeller
/selected-data/1775.cpp
UTF-8
1,138
3.0625
3
[]
no_license
#include <iostream> #include <stdio.h> #include <math.h> #include "../StateIntercept.cpp" #include <string.h> using namespace std; Intercept<int> s(Intercept<int> a, Intercept<int> b) { Intercept<int> intercepts[] = {Intercept<int>(0, 3), Intercept<int>(0, 2), Intercept<int>(0, 8), Intercept<int>(0, 5), Intercept<int>(0,7)}; StateIntercept state(intercepts, sizeof(intercepts) / sizeof(intercepts[0])); // Intercept<int> z = 0; == state[4]//sum(0, 3), if (a != 1 && b <= a) { for (state[1] = Intercept<int>(b, 2); state[1] <= a; ++state[1]) { if (a % state[1] == 0) { state[0] += s(a / state[1], state[1]); state[3] += state[0]; state[4] = 1; } } } else if (a == 1) { state[2] = 1; return 1; } return state[0]; } int main() { Intercept<int> intercepts[] = {Intercept<int>(0, 2), Intercept<int>(0, 4), Intercept<int>(0, 4)}; StateIntercept state(intercepts, sizeof(intercepts) / sizeof(intercepts[0])); // Intercept<int> n, a; cin >> state[1]; for (state[0] = Intercept<int>(0, 2); state[0] < state[1]; ++state[0]) { cin >> state[2]; cout << s(state[2], 2) << endl; } return 0; }
true
10dca1af77e48071619445a9ae920933951414f3
C++
JacobianDet/CompeteUp
/ecf41/tt.cpp
UTF-8
349
2.53125
3
[]
no_license
#include <bits/stdc++.h> int main(void) { int n,m; std::cin>>n>>m; int col[n+1]; memset(col,0,sizeof(col)); int ctr = 5000; for(int i=0;i<m;i++) { int x; std::cin>>x; col[x]++; } /*for(int i=1;i<=n;i++) std::cout<<col[i]<<"\n";*/ for(int i=1;i<=n;i++) { if(col[i] < ctr) ctr = col[i]; } std::cout<<ctr<<"\n"; return 0; }
true
f484fda86c175fb3565f3772f25cbababcb75143
C++
celestecote21/ray_tracer_cpp
/Material.hpp
UTF-8
429
2.703125
3
[]
no_license
#ifndef MATERIAL_H #define MATERIAL_H #include "Vec3.hpp" #include "Ray.hpp" #include "Hitable.hpp" // abstract class, une methode qui prend la ray recu, le dernier record (pour avoir le point, la normal..) // une ref vers un Vec pour l'attenuation et une ref vers la ray qui va sortir class Material{ public: virtual bool scatter(Ray& r_in, const hit_record_t& rec, Vec3& attenuation, Ray& new_ray) const = 0; }; #endif
true
17114f51439cc86536523e39b13aa922fd04ff79
C++
alicecaron/tpinf224
/tp1/Video.h
UTF-8
597
2.90625
3
[]
no_license
#ifndef VIDEO_H #define VIDEO_H #include "Multimedia.h" class Video : public Multimedia { private: float duree; public: Video(); Video(string _nom,int _date, string _path,float _duree); /** * @brief getDuree * @return * Récupérer la durée de la vidéo */ const virtual float getDuree() const; /** * @brief setDuree * @param _duree * Changer la valeur de la durée de la vidéo */ virtual void setDuree(float _duree); virtual void display() const; virtual void play()const; virtual ~Video(); }; #endif // VIDEO_H
true
bff512ccca84979617266e7db9ae38147c1fd81d
C++
WhiZTiM/coliru
/Archive2/4b/31ac15563e636f/main.cpp
UTF-8
789
2.828125
3
[]
no_license
#include <regex> #include <string> #include <iostream> int main() { const std::wstring str = L"We bought the grocer oil worth 2,48 drachmas. " "soap worth 94 drs. and rice worth 11,75 drachmas." "How much change will take from 7/8 of 50 drachmas?"; std::wregex integer(L"\\s[0-9]+\\s"); // whitespace, one or more dcimal digits, whitespace auto iter = std::wsregex_iterator( str.begin(), str.end(), integer ); const auto end = std::wsregex_iterator(); int sum = 0 ; for( ; iter != end; ++iter) { std::wcout << iter->str() << L'\n' ; sum += std::stoi( iter->str() ) ; } std::cout << "----\n" << sum << '\n' ; }
true
1280e18c7f3b6e3718a692c41a50e3eeff98e269
C++
BoChang11/ActionAndMotionPlanner
/src/MP/Action.hpp
UTF-8
1,285
2.796875
3
[]
no_license
#ifndef ABETARE__ACTION_HPP_ #define ABETARE__ACTION_HPP_ #include "Utils/Constants.hpp" #include "Utils/HashFn.hpp" #include <functional> namespace Abetare { struct Action { enum Type { TYPE_MOVE = 0, TYPE_MOVE_WITH_OBJECT = 1, TYPE_PICKUP = 2, TYPE_RELEASE = 3 }; Action(void) : m_type(TYPE_MOVE), m_idFromRoom(Constants::ID_UNDEFINED), m_idToRoom(Constants::ID_UNDEFINED), m_idDoor(Constants::ID_UNDEFINED), m_idObject(Constants::ID_UNDEFINED) { } ~Action(void) { } Type m_type; int m_idFromRoom; int m_idToRoom; int m_idDoor; int m_idObject; }; static inline bool operator==(const Action& lhs, const Action& rhs) { return lhs.m_type == rhs.m_type && lhs.m_idFromRoom == rhs.m_idFromRoom && lhs.m_idToRoom == rhs.m_idToRoom && lhs.m_idDoor == rhs.m_idDoor && lhs.m_idObject == rhs.m_idObject; } void ApplyAction(const int dsFrom[], const Action * const a, int dsTo[]); } namespace std { template<> struct hash<Abetare::Action> { size_t operator()(const Abetare::Action &a) const { return Abetare::StringHash((const char*)(&a), sizeof(a)); } }; } #endif
true
0524310a7d58e67da1a05a6f3150c6e707aa8147
C++
Ferdinand-vW/Hackerrank
/cpp/attending_workshops/main.cpp
UTF-8
1,773
3.734375
4
[]
no_license
#include<bits/stdc++.h> using namespace std; //Define the structs Workshops and Available_Workshops. //Implement the functions initialize and CalculateMaxWorkshops struct Workshop { int start_time; int duration; int end_time; }; struct Available_Workshops { int n; std::vector<Workshop> workshops; }; Available_Workshops* initialize(int start_time[],int duration[], int n) { std::vector<Workshop> workshops; for (int i = 0; i < n; i ++) { workshops.push_back( Workshop { start_time[i], duration[i], start_time[i] + duration[i] } ); } return new Available_Workshops { n, workshops }; } int CalculateMaxWorkshops(Available_Workshops* ptr) { auto av_ws = ptr->workshops; std::sort(av_ws.begin(),av_ws.end() ,[](Workshop &w1, Workshop &w2) { return w1.end_time < w2.end_time; }); std::vector<Workshop> maxWs; for (int i = 0; i < ptr->n; i++) { auto currWs = av_ws[i]; maxWs.push_back(currWs); bool isOverlapping = true; while (isOverlapping && i - 1 < ptr->n) { if (currWs.end_time > av_ws[i+1].start_time) { i++; } else { isOverlapping = false; } } } return maxWs.size(); } int main(int argc, char *argv[]) { int n; // number of workshops cin >> n; // create arrays of unknown size n int* start_time = new int[n]; int* duration = new int[n]; for(int i=0; i < n; i++){ cin >> start_time[i]; } for(int i = 0; i < n; i++){ cin >> duration[i]; } Available_Workshops * ptr; ptr = initialize(start_time,duration, n); cout << CalculateMaxWorkshops(ptr) << endl; return 0; }
true
8bf54b6947bc9b919eddd67966b67be0377fe8bf
C++
PingguSoft/ESP8266
/Bebop/utils.cpp
UTF-8
6,436
2.734375
3
[]
no_license
/* This project is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. see <http://www.gnu.org/licenses/> */ #include <Arduino.h> #include <stdarg.h> #include <Math.h> #include "common.h" #include "utils.h" void Utils::dump(u8 *data, u16 cnt) { u8 i; u8 b; u16 addr = 0; // Serial.printf("-- buf size : %d -- \n", cnt); while (cnt) { Serial.printf("%08x - ", addr); for (i = 0; (i < 16) && (i < cnt); i ++) { b = *(data + i); Serial.printf("%02x ", b); } Serial.printf(" : "); for (i = 0; (i < 16) && (i < cnt); i ++) { b = *(data + i); if ((b > 0x1f) && (b < 0x7f)) Serial.printf("%c", b); else Serial.printf("."); } Serial.printf("\n"); data += i; addr += i; cnt -= i; } } void Utils::printf(char *fmt, ... ) { char buf[256]; va_list args; va_start (args, fmt ); vsnprintf(buf, 256, fmt, args); va_end (args); //Serial.print(buf); } /* int Utils::power(int base, int exp){ int result = 1; while(exp) { result *= base; exp--; } return result; } char* Utils::ftoa(float num, uint8_t decimals) { // float to string; no float support in esp8266 sdk printf // warning: limited to 15 chars & non-reentrant // e.g., dont use more than once per os_printf call char buf[32]; int whole = num; int decimal = (num - whole) * power(10, decimals); if (decimal < 0) { // get rid of sign on decimal portion decimal -= 2 * decimal; } char pattern[32]; sprintf(pattern, "%%d.%%0%dd", decimals); sprintf(buf, pattern, whole, decimal); return (char *)buf; } char* Utils::ftoa(double num, uint8_t decimals) { // float to string; no float support in esp8266 sdk printf // warning: limited to 15 chars & non-reentrant // e.g., dont use more than once per os_printf call char buf[32]; int whole = num; int decimal = (num - whole) * power(10, decimals); if (decimal < 0) { // get rid of sign on decimal portion decimal -= 2 * decimal; } char pattern[32]; sprintf(pattern, "%%d.%%0%dd", decimals); sprintf(buf, pattern, whole, decimal); return (char *)buf; } */ static double PRECISIOND = 0.00000000000001; static float PRECISIONF = 0.001; static int MAX_NUMBER_STRING_SIZE = 32; char* Utils::dtoa(char *s, double n) { // handle special cases if (isnan(n)) { strcpy(s, "nan"); } else if (isinf(n)) { strcpy(s, "inf"); } else if (n == 0.0) { strcpy(s, "0"); } else { int digit, m, m1; char *c = s; int neg = (n < 0); if (neg) n = -n; // calculate magnitude m = log10(n); int useExp = (m >= 14 || (neg && m >= 9) || m <= -9); if (neg) *(c++) = '-'; // set up for scientific notation if (useExp) { if (m < 0) m -= 1.0; n = n / pow(10.0, m); m1 = m; m = 0; } if (m < 1.0) { m = 0; } // convert the number while (n > PRECISIOND || m >= 0) { double weight = pow(10.0, m); if (weight > 0 && !isinf(weight)) { digit = floor(n / weight); n -= (digit * weight); *(c++) = '0' + digit; } if (m == 0 && n > 0) *(c++) = '.'; m--; } if (useExp) { // convert the exponent int i, j; *(c++) = 'e'; if (m1 > 0) { *(c++) = '+'; } else { *(c++) = '-'; m1 = -m1; } m = 0; while (m1 > 0) { *(c++) = '0' + m1 % 10; m1 /= 10; m++; } c -= m; for (i = 0, j = m-1; i<j; i++, j--) { // swap without temporary c[i] ^= c[j]; c[j] ^= c[i]; c[i] ^= c[j]; } c += m; } *(c) = '\0'; } return s; } char* Utils::ftoa(char *s, float n) { // handle special cases if (isnan(n)) { strcpy(s, "nan"); } else if (isinf(n)) { strcpy(s, "inf"); } else if (n == 0.0) { strcpy(s, "0"); } else { int digit, m, m1; char *c = s; int neg = (n < 0); if (neg) n = -n; // calculate magnitude m = log10(n); int useExp = (m >= 14 || (neg && m >= 9) || m <= -9); if (neg) *(c++) = '-'; // set up for scientific notation if (useExp) { if (m < 0) m -= 1.0; n = n / pow(10.0, m); m1 = m; m = 0; } if (m < 1.0) { m = 0; } // convert the number while (n > PRECISIONF || m >= 0) { double weight = pow(10.0, m); if (weight > 0 && !isinf(weight)) { digit = floor(n / weight); n -= (digit * weight); *(c++) = '0' + digit; } if (m == 0 && n > 0) *(c++) = '.'; m--; } if (useExp) { // convert the exponent int i, j; *(c++) = 'e'; if (m1 > 0) { *(c++) = '+'; } else { *(c++) = '-'; m1 = -m1; } m = 0; while (m1 > 0) { *(c++) = '0' + m1 % 10; m1 /= 10; m++; } c -= m; for (i = 0, j = m-1; i<j; i++, j--) { // swap without temporary c[i] ^= c[j]; c[j] ^= c[i]; c[i] ^= c[j]; } c += m; } *(c) = '\0'; } return s; }
true
c9080b0cc169494f39b0400a36f6dd9c78a39cb0
C++
JMCeron/Arduino
/Energy_Shield/DemoConfigureRTC/Rtc.cpp
UTF-8
7,230
3.359375
3
[]
no_license
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include "Wire.h" #include "Rtc.h" /////////////////////////////////////// //public functions /** * 1) Sets the date and time on the ds1307 * 2) Starts the clock * 3) Sets hour mode to 24 hour clock * Assumes you're passing in valid numbers * @param char second * Seconds to assign to RTC * @param char minute * Minutes to assign to RTC * @param char hour * Hours to assign to RTC * @param char dayOfWeek * Day of week to assign to RTC * @param char dayOfMonth * Day of Month to assign to RTC * @param char month * Month to assign to RTC * @param char year * Year to assign to RTC (11 is 2011) * @return void */ void Rtc::SetDate(char second, // 0-59 char minute, // 0-59 char hour, // 1-23 char dayOfWeek, // 1-7 char dayOfMonth, // 1-28/29/30/31 char month, // 1-12 char year) // 0-99 { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(0); Wire.write(DecToBcd(second)); // 0 to bit 7 starts the clock Wire.write(DecToBcd(minute)); Wire.write(DecToBcd(hour)); // If you want 12 hour am/pm you need to set // bit 6 (also need to change readDateDs1307) Wire.write(DecToBcd(dayOfWeek)); Wire.write(DecToBcd(dayOfMonth)); Wire.write(DecToBcd(month)); Wire.write(DecToBcd(year)); Wire.endTransmission(); } /** * Class constructor that sets the date, Assumes you're passing in valid numbers. * @param char s * Seconds to assign to RTC * @param char m * Minutes to assign to RTC * @param char h * Hours to assign to RTC * @param char dow * Day of week to assign to RTC * @param char dom * Day of Month to assign to RTC * @param char mo * Month to assign to RTC * @param char y * Year to assign to RTC (11 is 2011) * @param char mask * After setting time, this mask is written to RTC to avoid future writings * @return void */ Rtc::Rtc(char s,char m,char h,char dow,char dom,char mo,char y,char mask){ Wire.begin(); if(ReadDs1307(0x08) != mask){ second = s; minute = m; hour = h; dayOfWeek = dow; dayOfMonth = dom; month = mo; year = y; SetDate(second, minute, hour, dayOfWeek, dayOfMonth, month, year);//send data to RTC chip } WriteDs1307(0x08,mask); } /** * Class constructor * don't set the date on the chip * @param none */ Rtc::Rtc(){ Wire.begin(); } /** * Return the date of last reading (using GetDate()) in a string * * @param none * @return a string containing the current date in format dd/mm/yyyy */ char* Rtc::Date() { char a[80]; char * buf=a; if(dayOfMonth < 10) *(buf++) = '0'; itoa(dayOfMonth,buf,10); buf+=strlen(buf); *(buf++) = '/'; if(month < 10) *(buf++) = '0'; itoa(month,buf,10); buf+=strlen(buf); strcpy(buf,"/20"); buf+=strlen(buf); itoa(year,buf,10); return a; } /** * Return the hour of last reading (using GetDate()) in a string * * @param none * @return a string containing the current time in format hh:mm:ss */ char* Rtc::Time() { char a[80]; char * buf=a; if(hour < 10) *(buf++) = '0'; itoa(hour,buf,10); buf+=strlen(buf); *(buf++) = ':'; if(minute < 10) *(buf++) = '0'; itoa(minute,buf,10); buf+=strlen(buf); *(buf++) = ':'; if(second < 10) *(buf++) = '0'; itoa(second,buf,10); return a; } /** * Gets the date and time from the ds1307 and save them into instance variables * * @param none * */ void Rtc::GetDate() { // Reset the register pointer Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(0); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, 7); // A few of these need masks because certain bits are control bits second = BcdToDec(Wire.read() & 0x7f); minute = BcdToDec(Wire.read()); hour = BcdToDec(Wire.read() & 0x3f); // Need to change this if 12 hour am/pm dayOfWeek = BcdToDec(Wire.read()); dayOfMonth = BcdToDec(Wire.read()); month = BcdToDec(Wire.read()); year = BcdToDec(Wire.read()); } /** * * * @param char address * @param char data * */ void Rtc::WriteDs1307(char address,char data) { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(address); Wire.write(data); Wire.endTransmission(); } /** * * * @param char address * @param char data * */ char Rtc::ReadDs1307(char address) { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(address); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, 1); return Wire.read(); } /** * float to ascii * * @param char *a * @param char f * @int precision * */ char * Rtc::ftoa(char *a, double f, int precision) { long p[] = { 0,10,100,1000,10000,100000,1000000,10000000,100000000 }; char *ret = a; long heiltal = (long)f; itoa(heiltal, a, 10); while (*a != '\0') a++; *a++ = '.'; long desimal = abs((long)((f - heiltal) * p[precision])); itoa(desimal, a, 10); return ret; } /////////////////////////////////////// //private functions // Convert normal decimal numbers to binary coded decimal char Rtc::DecToBcd(char val) { return ( (val/10*16) + (val%10) ); } // Convert binary coded decimal to normal decimal numbers char Rtc::BcdToDec(char val) { return ( (val/16*10) + (val%16) ); } unsigned long Rtc::UnixTime() { unsigned long days; unsigned int yr=year+2000; const unsigned long monthcount[] = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; /* Compute days */ days = (yr - 1970) * 365 + monthcount[month] + dayOfMonth - 1; /* Compute for leap year */ if(month <= 2) yr--; for ( ; yr >= 1970; yr--){ if (isleap((yr))) days++; // Serial.println("=)"); } /* Plus the time */ return second + 60 * (minute + 60 * (days * 24 + hour - GMT_OFFSET)); /* Number of days per month * unsigned long days; unsigned char yr=year; const unsigned long monthcount[] = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; /* Compute days * days = (2000+year - 1970) * 365 + monthcount[month] + dayOfMonth - 1; /* Compute for leap year * for (month <= 2 ? yr-- : 0; yr >= 1970; yr--) if (isleap(yr)) days++; /* Plus the time * return second + 60 * (minute + 60 * (days * 24 + hour - GMT_OFFSET)); Serial.println("----------------"); /* Number of days per month * unsigned long days; unsigned int yr=reloj.year+2000; const unsigned long monthcount[] = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; /* Compute days * days = (2000+reloj.year - 1970) * 365 + monthcount[reloj.month] + reloj.dayOfMonth - 1; Serial.println(days,DEC); Serial.println(yr,DEC); /* Compute for leap year * if(reloj.month <= 2) yr--; for ( ; yr >= 1970; yr--){ if (isleap((yr))) days++; // Serial.println("=)"); } Serial.println(yr,DEC); Serial.println(days,DEC); /* Plus the time * Serial.println(reloj.second + 60 * (reloj.minute + 60 * (days * 24 + reloj.hour - GMT_OFFSET)),DEC); Serial.println("----------------"); */ }
true
82f1927ee10fc08118ae2f8f995a02c581bfd1be
C++
biomorphs/DemoFramework
/tests/test_string_hash.cpp
UTF-8
875
3.015625
3
[]
no_license
/* DemoFramework Matt Hoyle */ #include "catch.hpp" #include "core/string_hashing.h" TEST_CASE("Simple string hashing correct", "[Core::StringHashing]") { SECTION("Null string is empty hash") { REQUIRE(Core::StringHashing::GetHash(nullptr) == Core::StringHashing::EmptyHash); } SECTION("Empty string is empty hash") { REQUIRE( Core::StringHashing::GetHash("") == Core::StringHashing::EmptyHash ); } SECTION("Different strings give different hashes") { auto stringHash0 = Core::StringHashing::GetHash("AString"); auto stringHash1 = Core::StringHashing::GetHash("ADifferentString"); REQUIRE(stringHash0 != stringHash1); } SECTION("Matching strings give same hash") { auto stringHash0 = Core::StringHashing::GetHash("Some random string"); auto stringHash1 = Core::StringHashing::GetHash("Some random string"); REQUIRE(stringHash0 == stringHash1); } }
true
6abac07021f7f59568c8975cd3e4305d9156cc83
C++
cesar-magana/Leet-Code
/0297. Serialize and Deserialize Binary Tree/serialize01.cpp
UTF-8
1,133
3.5
4
[]
no_license
// Encodes a tree to a single string. string serialize(TreeNode* root) { string res = ""; if (root == NULL) return res; res += to_string(root->val); makeSerialize(root->left, res); makeSerialize(root->right, res); return res; } void makeSerialize(TreeNode* root, string& res) { if (root == NULL) { res += ",#"; return; } res += "," + to_string(root->val); makeSerialize(root->left, res); makeSerialize(root->right, res); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if(data == "") return NULL; int index = 0; return makeDeserialize(data, index); } TreeNode* makeDeserialize(string& data, int & index) { if (data[index] == '#') { index++; if (index < data.size()) index++; return NULL; } //get value of current tree int p = index; while (data[p] != ',') p++; int value = stoi( data.substr(index, p - index) ); TreeNode * root = new TreeNode(value); index = p + 1; root->left = makeDeserialize(data, index); root->right = makeDeserialize(data, index); return root; }
true
767504cad9ad3eab754f6ccc8d8121d3c9b2532e
C++
ZimboPro/WTC
/3rdSemester/CPP/AbstractVM/Parse.cpp
UTF-8
5,546
2.78125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Parse.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lde-jage <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/27 06/19/11 by lde-jage #+# #+# */ /* Updated: 2018/06/27 06/19/11 by lde-jage ### ########.fr */ /* */ /* ************************************************************************** */ #include "Parse.hpp" #include <vector> #include <sstream> #include "Error.hpp" #include "Logic.hpp" #include <regex> Parse::Parse() {} Parse::Parse(Parse const & src) { *this = src; } Parse::~Parse() {} Parse & Parse::operator=(Parse const & src) { if (this != &src) { *this = src; } return (*this); } int Parse::countCommands(size_t *arr) { int cnt = 0; if (arr[12] == std::string::npos) { for (int i = 0; i < 12; i++) { if (arr[i] != std::string::npos) cnt++; } } else { for (int i = 0; i < 12; i++) { if (arr[i] != std::string::npos && arr[i] < arr[12]) cnt++; } } return cnt++; } size_t Parse::getComma(std::string const & command) { size_t ans; if (command.find(";;") == std::string::npos) return command.find(";"); else { ans = command.find(";"); size_t t = command.find(";;"); while (ans != std::string::npos && (ans == t || ans == t + 1)) { ans = command.find(";", ans + 1); } return ans; } } void getType(eOperandType & type, std::string t) { t = Logic::trim_copy(t); Logic::StrToUpper(t); if (t.compare("INT8") == 0) type = eOperandType::TypeInt8; else if (t.compare("INT16") == 0) type = eOperandType::TypeInt16; else if (t.compare("INT32") == 0) type = eOperandType::TypeInt32; else if (t.compare("FLOAT") == 0) type = eOperandType::TypeFloat; else if (t.compare("DOUBLE") == 0) type = eOperandType::TypeDouble; else throw Error::UnkownType(); } void Parse::MultipleWord(std::string const & command, eOperandType & type, std::string & val) { std::vector<std::string> words; std::string temp = command.substr(0, command.find(";")); temp = Logic::trim_copy(temp); std::regex form("(PUSH|ASSERT) (INT8|INT16|INT32|FLOAT|DOUBLE)\\s?\\(-?[[:digit:]]+(.?[[:digit:]]+)?\\)\\B"); if (!std::regex_match(temp, form)) throw Error::SyntaxError(); std::istringstream ss( temp ); while (!ss.eof()) // See the WARNING above for WHY we're doing this! { std::string x; // here's a nice, empty string getline( ss, x, ' ' ); // try to read the next field into it words.push_back(x); } if (words.size() < 2 || words.size() > 3) throw Error::SyntaxError(); size_t t; if (words.size() == 2) { t = words[1].find("("); getType(type, words[1].substr(0, t)); } else getType(type, words[1]); if (words.size() == 2) val = words[1].substr(t); else val = words[2]; val = Logic::trim_copy(val); val.erase(0, 1); val.erase(val.length() - 1, 1); if (val.length() == 0) throw Error::SyntaxError(); } int Parse::Command(std::string const & command, eOperandType & type, std::string & val) { size_t arr[13]; std::string str[] = {";;", "PUSH", "POP", "ADD", "SUB", "MUL", "DIV", "MOD", "DUMP", "ASSERT", "PRINT", "EXIT"}; std::string *temp = const_cast<std::string *>(&command); Logic::StrToUpper(*temp); arr[0] = temp->find(";;"); arr[1] = temp->find("PUSH"); arr[2] = temp->find("POP"); arr[3] = temp->find("ADD"); arr[4] = temp->find("SUB"); arr[5] = temp->find("MUL"); arr[6] = temp->find("DIV"); arr[7] = temp->find("MOD"); arr[8] = temp->find("DUMP"); arr[9] = temp->find("ASSERT"); arr[10] = temp->find("PRINT"); arr[11] = temp->find("EXIT"); arr[12] = getComma(*temp); int j = countCommands(arr); if (j == 1) { if (arr[12] != std::string::npos) { int i = 0; while (i < 12) { if (arr[i] != std::string::npos && arr[i] < arr[12]) break; i++; } if (i == 12) return (-1); if (i == 0 || i == 11) return (0); else if (i == 1 || i == 9) { MultipleWord(command, type, val); return i; } else return (i); } else { int i = 0; while (i < 12 && arr[i] == std::string::npos) i++; if (i == 0 || i == 11) return (0); else if (i == 1 || i == 9) { MultipleWord(command, type, val); return i; } else { std::vector<std::string> words; std::string temp = command.substr(0, command.find(";")); temp = Logic::trim_copy(temp); std::istringstream ss( temp ); while (!ss.eof()) // See the WARNING above for WHY we're doing this! { std::string x; // here's a nice, empty string getline( ss, x, ' ' ); // try to read the next field into it words.push_back(x); } if (words.size() > 1) throw Error::SyntaxError(); if (temp.compare(str[i]) != 0) throw Error::SyntaxError(); return (i); } } MultipleWord(command, type, val); } else if (j > 1) throw Error::SyntaxError(); else if (j == 0 && command.length() > 0 && (arr[12] == std::string::npos || arr[12] > 0)) throw Error::Unkown(); return (-1); }
true
e224413eab5c570f1f43eaa1bef40027ce44bd82
C++
ai5/gpsfish
/osl/core/osl/bits/align16New.cc
UTF-8
991
2.59375
3
[]
no_license
/* align16New.cc */ #include "osl/bits/align16New.h" #include <cassert> #include <cstdlib> void * osl::misc::Align16New::operator new(size_t size) { char *ptr = ::new char[size+Alignment]; for (int i=0; i<Alignment; ++i) { if (reinterpret_cast<unsigned long>(ptr + i + 1) % Alignment == 0) { *(ptr + i) = i + 1; // std::cerr << ">> " << (long)ptr << " => " << (long)(ptr + i + 1) << "\n"; return ptr + i + 1; } } assert(0); abort(); } void * osl::misc::Align16New::operator new[](size_t size) { return operator new(size); } void osl::misc::Align16New::operator delete(void *ptr, size_t /*size*/) { char *p = static_cast<char*>(ptr); int offset = *(p-1); ::delete(p - offset); // std::cerr << "<< " << (long)p << " => " << (long)(p - offset) << "\n"; } void osl::misc::Align16New::operator delete[](void *ptr, size_t size) { return operator delete(ptr, size); } // ;;; Local Variables: // ;;; mode:c++ // ;;; c-basic-offset:2 // ;;; End:
true
471c04d6229407587e64c8174f8a2ae8ae74c070
C++
w86763777/ACM_ICPC_codebook
/Source/Graph_Maximum_Cardinality_Matching.cpp
UTF-8
3,224
2.75
3
[]
no_license
#include <cstdio> #include <queue> #include <cstring> using namespace std; struct BlossomAlgorithm { private: // number of vertex, zero base static const int N = 205; int match[N]; int d[N]; queue<int> q; deque<int> path[N]; void label_one_side(int x, int y, int bi) { for(int i = bi+1; i < path[x].size(); i++) { int z = path[x][i]; if (d[z] == 1) { path[z] = path[y]; path[z].insert(path[z].end(), path[x].rbegin(), path[x].rend()-i); d[z] = 0; q.push(z); } } } bool BFS(int r) { for (int i = 0; i < n; ++i) path[i].clear(); path[r].push_back(r); memset(d, -1, sizeof(d)); d[r] = 0; while(!q.empty()) q.pop(); q.push(r); while (!q.empty()) { int x = q.front(); q.pop(); for (int y = 0; y < n; y++) if (map[x][y] && match[y] != y) if (d[y] == -1) if (match[y] == -1) { for (int i = 0; i + 1 < path[x].size(); i += 2) { match[path[x][i]] = path[x][i+1]; match[path[x][i+1]] = path[x][i]; } match[x] = y; match[y] = x; return true; } else { int z = match[y]; path[z] = path[x]; path[z].push_back(y); path[z].push_back(z); d[y] = 1; d[z] = 0; q.push(z); } else if (d[y] == 0) { int bi = 0; while (bi < path[x].size() && bi < path[y].size() && path[x][bi] == path[y][bi]) bi++; bi--; label_one_side(x, y, bi); label_one_side(y, x, bi); } } return false; } public: int max_match; int n; bool map[N][N]; void matchAll() { memset(match, -1, sizeof(match)); max_match = 0; for (int i = 0; i < n; i++) if (match[i] == -1) if (BFS(i)) max_match++; else match[i] = i; } void init() { memset(map, false, sizeof(map)); } void addedge(int u,int v) { map[u][v] = map[v][u] = true; } } solver; /** * Step: * solver.init(); * solver.n = n; * loop: * solver.addedge(i, j); */
true
23e634ce4c2be8885bd467c01c7502828d355019
C++
mfkiwl/FlyDog_SDR_GPS
/extensions/DRM/dream/MSC/logicalframe.h
UTF-8
2,243
3.03125
3
[ "MIT" ]
permissive
#ifndef LOGICALFRAME_H #define LOGICALFRAME_H /* * 3.1 * logical frame: data contained in one stream during 400 ms or 100 ms * 5.2 The channel coding of DRM is performed on logical frames of constant bit rate for any given combination of parameters. * 6.2.2 * The MSC contains between one and four streams. Each stream is divided into logical frames. Audio streams comprise compressed * audio and optionally they can carry text messages. Data streams may be composed of data packets, carrying information * for up to four "sub-streams". An audio service comprises one audio stream and optionally one to four data streams or * data sub-streams. A data service comprises one data stream or data sub-stream. * * Each logical frame generally consists of two parts, each with its own protection level. The lengths of the two parts * are independently assigned. Unequal error protection for a stream is provided by setting different protection levels to the two parts. * * For robustness modes A, B, C and D, the logical frames are each 400 ms long. If the stream carries audio, the logical frame * carries the data for one audio super frame. * * For robustness mode E, the logical frames are each 100 ms long. If the stream carries audio, the logical frame carries the data for either * the first or the second part of one audio super frame containing the audio information for 200 ms duration. Since, in general, the stream * may be assigned two protection levels, the logical frames carry precisely half of the bytes from each protection level. * The logical frames from all the streams are mapped together to form multiplex frames of the same duration, which are passed to the * channel coder. In some cases, the first stream may be carried in logical frames mapped to hierarchical frames. * * 6.5.1 * The text message (when present) shall occupy the last four bytes of the lower protected part of each logical frame * carrying an audio stream. The message is divided into a number of segments and UTF-8 character coding is used. * The beginning of each segment of the message is indicated by setting all four bytes to the value 0xFF. */ class LogicalFrame { public: LogicalFrame(); }; #endif // LOGICALFRAME_H
true
a48b5857d85162485b09a2a966c77f17bba54844
C++
yongyanghz/Last-mile-delivery-problem
/cainiao - 3.1/src/location.cpp
UTF-8
478
2.78125
3
[]
no_license
#include "location.h" location::location() { //ctor } location::~location() { //dtor } location::location(string s,double lng,double lat): id_(s),lng_(lng),lat_(lat){ } void location::setID(string str){ id_ = str; } string location::id(){ return id_; } void location::setLng(double value){ lng_ = value; } double location::lng(){ return lng_; } void location::setLat(double value){ lat_ = value; } double location::lat(){ return lat_; }
true
d7ece8502b8ac441aa0572513dfa2aa5a83f0033
C++
papicheng/offer-boom
/.vscode/linknode_insert.cpp
WINDOWS-1252
1,268
2.515625
3
[]
no_license
/*ܣ*/ #include<bits/stdc++.h> using namespace std; struct Node{ int val; Node* next; Node(int x): val(x){}; }; typedef struct Node Node; int mian(){ Node* pre, cur ,head; head = (Node*)malloc(sizeof(Node)) return 0; } int cnt = 0; queue<vector<int>> que; for(int i = 0; i < grid.size(); ++i){ for(int j = 0; j < grid[i].size(); ++j){ if(grid[i][j] == 2){ que.push({i, j}); } else if(grid[i][j] == 1){ cnt++; } } } int ans = 0; vector<vector<int>> dd = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; while(!que.empty()){ auto q = que.front(); que.pop(); for(auto d : dd){ int dx = q[0] + d[0]; int dy = q[1] + d[1]; if(dx < 0 || dx >= grid.size()) continue; if(dy < 0 || dy >= grid[0].size()) continue; if(grid[dx][dy] != 1) continue; grid[dx][dy] = grid[q[0]][q[1]] + 1; cnt--; que.push({dx, dy}); ans = grid[dx][dy] - 2; } } return (cnt == 0) ? ans : -1;
true
76420b803c0e617ccc68f212f2b063533388b3d0
C++
eitanshalev/Lion-King-Scar
/Lion King Scar/src/main.cpp
UTF-8
261
2.640625
3
[]
no_license
#include "Menu.h" #include <cstdlib> int main() { Menu menu; try { menu.run(); } catch (std::exception& ex) { std::cout << ex.what(); std::cout << "can not read this file!\n"; } return EXIT_SUCCESS; }
true
417acaf1c94229fe7bac73b410443eddb4885eaf
C++
demonsheart/C-
/rongyu/homework1/file/2018152086_1042_答案错误_605.cpp
UTF-8
662
3.140625
3
[]
no_license
#include<iostream> using namespace std; int compare(char* s,char*t){ int i,j,sum1=0,sum2=0; for(i=0;i<10;i++){ if(*(s+i)!='\0'&&*(t+i)!='\0'){ if(*(s+i)>*(t+i)){ sum1++; } else if(*(s+i)<*(t+i)){ sum2++; } } else if(*(s+i)=='\0'&&*(t+i)=='\0'){ break; } else if(*(s+i)=='\0'&&*(t+i)!='\0'){ return -1; } } // printf("%d %d\n",sum1,sum2); if(sum1==sum2){ return 0; } else if(sum1<sum2){ return -1; } else if(sum1>sum2) return 1; } int main(){ int t,flag; cin>>t; while(t--){ char *s=new char [100]; char *t=new char [100]; cin>>s; cin>>t; flag=compare(s,t); cout<<flag<<endl; } return 0; }
true
229ab9e47c6d11c06e7e96ecee9cbb563c30cde3
C++
arlechann/atcoder
/AtCoder/AtcoderBiginnersSelection/ABC086C.cpp
UTF-8
993
3.28125
3
[ "CC0-1.0" ]
permissive
#include<cstdio> #include<cstdlib> typedef struct{ int t; int x; int y; }Plan; int n; Plan plan[100000]; bool solve(void); int manhattan_distance(int x1, int y1, int x2, int y2); int main(void){ scanf("%d", &n); for(int i = 0; i < n; i++){ scanf("%d %d %d", &plan[i].t, &plan[i].x, &plan[i].y); } printf("%s\n", solve() ? "Yes" : "No"); return 0; } bool solve(void){ int t = 0; int x = 0; int y = 0; for(int next = 0; next < n; next++){ if(plan[next].t - t < manhattan_distance(plan[next].x, plan[next].y,x, y)){ return false; } if((plan[next].t - t) % 2 != manhattan_distance(x, y, plan[next].x, plan[next].y) % 2){ return false; } t = plan[next].t; x = plan[next].x; y = plan[next].y; } return true; } int manhattan_distance(int x1, int y1, int x2, int y2){ return abs(x1 - x2) + abs(y1 - y2); }
true
12dbfc77046f461db4d99666f26ef7f92f128f70
C++
YashavikaSingh/leetcodegrind
/804.cpp
UTF-8
1,063
3.0625
3
[]
no_license
#include <string> #include <vector> #include <map> #include <iostream> using namespace std; int uniqueMorseRepresentations(vector<string> &words) { int count = 0; vector<string> m{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; map<string, int> mp; map<string, int>::iterator it; vector<string> morse; for (int i = 0; i < words.size(); i++) { string word = ""; for (int j = 0; j < words[i].length(); j++) { int n = words[i][j]; int pos = n - 97; word += m[pos]; } mp[word]++; } for (it = mp.begin(); it != mp.end(); it++) { count++; } return count; } int main() { vector<string> ans; vector<string> words{"gin", "zen", "gig", "msg"}; cout<<uniqueMorseRepresentations(words); // for (int i = 0; i < ans.size(); i++) // cout << ans[i] << endl; return 0; }
true
b793c39210d6ff30773eaac9db9891cfbe258089
C++
noachain/dapp
/programs/globalfunction.h
UTF-8
728
2.84375
3
[]
no_license
#ifndef GLOBALFUNCTION_H #define GLOBALFUNCTION_H #include <iostream> #include <string> #include <vector> namespace globalFun { static std::vector<std::string> spliteStr_g(const std::string &strTol,const std::string &strSplite) { std::vector<std::string> retVect; if("" == strTol) { return retVect; } std::string strTmp = strTol+strSplite; size_t pos = strTmp.find(strSplite); size_t size = strTmp.size(); while(pos != std::string::npos) { std::string strSpliteTmp = strTmp.substr(0,pos); retVect.push_back(strSpliteTmp); strTmp = strTmp.substr(pos+1,size); pos = strTmp.find(strSplite); } return retVect; } } #endif // GLOBALFUNCTION_H
true
d3755dfb697c11cfcfe9a857eb933abe8d88c0cb
C++
SanD94/USACO
/shuttle/shuttle.cpp
UTF-8
1,635
2.921875
3
[]
no_license
/* ID: safaand1 PROG: shuttle LANG: C++11 */ #include <iostream> #include <cstdio> using namespace std; int N; char map[30]; int res[5000]; int cnt; int level; bool check(){ for(int i=0;i<N;i++) if(map[i]!='B' || map[i+N+1]!='W') return 0; return 1; } void swap(char &a, char &b){ a^=b; b^=a; a^=b; } bool DFS(int space){ if(check()) return 1; if(space && map[space-1]=='W') { swap(map[space-1], map[space]); if(DFS(space-1)) {res[cnt++] = space; return 1;} swap(map[space-1], map[space]); } if(map[space+1]=='B'){ swap(map[space], map[space+1]); if(DFS(space+1)) {res[cnt++] = space+2; return 1;} swap(map[space], map[space+1]); } if(map[space+1]=='W' && map[space+2]=='B'){ swap(map[space], map[space+2]); if(DFS(space+2)) {res[cnt++] = space+3; return 1;} swap(map[space], map[space+2]); } if(space>=2 && map[space-1]=='B' && map[space-2]=='W'){ swap(map[space], map[space-2]); if(DFS(space-2)) {res[cnt++]= space-1; return 1;} swap(map[space], map[space-2]); } return 0; } int main(){ freopen("shuttle.in", "r", stdin); freopen("shuttle.out", "w", stdout); cin >> N; for(int i=0;i<N;i++) {map[i]='W'; map[i+N+1]='B';} map[N]=' '; swap(map[N], map[N-1]); DFS(N-1); res[cnt++] = N; for(int i=0,j=1;i<cnt-1;i++,j++) { cout << res[cnt-i-1]; if(j!=20) cout << " "; else {cout << endl; j=0;} } cout << res[0] << endl; return 0; }
true
ea9bf9765f6bd9fb25076a89090977bca4b9b29d
C++
gagan86nagpal/SPOJ-200
/TWOSQRS/main.cpp
UTF-8
608
2.828125
3
[]
no_license
#include <iostream> #include <math.h> using namespace std; int main() { int t; cin>>t; while(t--) { long long n; cin>>n; long long a =0; long long b = sqrt(n)+1; bool flag = false; while(a<=b) { long long c = a*a + b*b; if(c ==n) { flag = true; break; } else if (c>n) b--; else a++; } if(flag) cout<<"Yes\n"; else cout<<"No\n"; } return 0; }
true
723e1a901e91336afa0bc4101cb23453905630c1
C++
rummansust/Codeforces-Contest
/Codeforces/Codeforces Round #181 (Div. 2)/B.cpp
UTF-8
3,963
2.59375
3
[]
no_license
#include <cstdio> #include <cmath> #include <algorithm> #include <iostream> #include <deque> #include <queue> #include <stack> #include <vector> #include <map> #include <cstdlib> #include <cstring> #include <string> #include <ctime> #include <sstream> #define clr(name,val) memset(name,val,sizeof(name)); #define EPS .000000001 #define ll long long #define psb(b) push_back(b) #define ppb() pop_back() #define oo 100000000000000000LL #define swap(x,y) {int t;t=x;x=y;y=t;} #define for_i(s,n) for(int i=s;i<n;i++) #define for_j(s,n) for(int j=s;j<n;j++) #define for_k(s,n) for(int k=s;k<n;k++) #define MAX 55 ///next_permutation next_permutation (s.begin(),s.end()) ///reverse(a,a+n); ///binary_search(first,last); ///vector erase v.erase(v.begin()+position); ///map map<int , int > data; ///map clear data.clear(); ///map iterator>>>> map <int,vector <int> >::const_iterator it; ///find an element in map (colour.find(nd)==colour.end());//if it return true this ///mean the element is'nt in the map. ///pass a vector to a funtion: funtion (vector <data type> &vector name); ///make_pair point=make_pair(i,j); ///access pair value point.first;point.second; using namespace std; ///int rr[]= {-1,-1,0,0,1,1}; ///int cc[]= {-1,0,-1,1,0,1}; ///int rr[]= {0,0,1,-1};/*4 side move*/ ///int cc[]= {-1,1,0,0};/*4 side move*/ ///int rr[]= {1,1,0,-1,-1,-1,0,1};/*8 side move*/ ///int cc[]= {0,1,1,1,0,-1,-1,-1};/*8 side move*/ ///int rr[]={1,1,2,2,-1,-1,-2,-2};/*night move*/ ///int cc[]={2,-2,1,-1,2,-2,1,-1};/*night move*/ struct edge { int parent,rank,member; }; vector<edge> dset(MAX); void makeset(int i) { dset[i].parent=i; dset[i].rank=0; dset[i].member=1; return; } int findset(int u) { if(dset[u].parent==u) return u; dset[u].parent=findset(dset[u].parent); } void unionset(int u,int v) { int up=findset(u); int vp=findset(v); if(dset[up].parent==dset[vp].parent) return; if(dset[up].rank<dset[vp].rank) { dset[up].parent=dset[vp].parent; dset[up].member=dset[vp].member=dset[up].member+dset[vp].member; } else { dset[vp].parent=dset[up].parent; dset[up].member=dset[vp].member=dset[up].member+dset[vp].member; if(dset[up].rank==dset[vp].rank) dset[up].rank=dset[up].rank+1; } return; } int main() { int n,m,u,v; map<int,vector<int> > data; map<int,int> data2; vector<int> vtr[30]; cin>>n>>m; for_i(0,n+1) makeset(i); for(int i=0;i<m;i++) { cin>>u>>v; unionset(u,v); } for(int i=1;i<=n;i++) { if(dset[findset(i)].member!=1) data[findset(i)].psb(i); } map<int,vector<int> > :: const_iterator it; for(it=data.begin();it!=data.end();it++) { if((it->second).size()>3) { cout<<-1<<endl; return 0; } } int k=0; for(it=data.begin();it!=data.end();it++) { for(int i=0;i<(it->second).size();i++) { vtr[k].psb((it->second)[i]); data2[(it->second)[i]]++; } k++; } queue<int> Q; for(int i=1;i<=n;i++) { if(data2.find(i)==data2.end()) Q.push(i); } for(int i=0;i<(n/3);i++) { if(vtr[i].size()<3); { for(int j=vtr[i].size();j<3;j++) { if(!Q.empty()) vtr[i].psb(Q.front()),Q.pop(); else break; } } } for(int i=0;i<(n/3);i++) { if(vtr[i].size()!=3) { cout<<-1<<endl; return 0; } } for(int i=0;i<(n/3);i++) { for(int j=0;j<vtr[i].size();j++) { if(j) cout<<" "; cout<<vtr[i][j]; } cout<<endl; } return 0; }
true
627908f3a7605e925a74725e84e73a6bf1f93960
C++
hzh0/LeetCode
/1584. 连接所有点的最小费用.cpp
UTF-8
1,453
2.71875
3
[]
no_license
class Solution { public: class Djset { public: vector<int> parents; int count; Djset(int n) { for (auto i = 0; i < n; ++i) { parents.push_back(i); } count = n; } int find(int num) { if (parents[num] != num) { parents[num] = find(parents[num]); } return parents[num]; } void Union(int num1, int num2) { int x = find(num1), y = find(num2); if (x != y) { parents[x] = y; count--; } } }; int minCostConnectPoints(vector<vector<int>>& points) { vector<vector<int>> v; int ans = 0; for (auto i = 0; i < points.size() - 1; ++i) { for (auto j = i + 1; j < points.size(); ++j) { v.push_back({ i,j,abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]) }); } } sort(v.begin(), v.end(), [](vector<int>& v1, vector<int>& v2) { return v1[2] < v2[2]; }); Djset ds(points.size()); int count = 0; for (auto i : v) { if (ds.find(i[0]) != ds.find(i[1])) { ds.Union(i[0], i[1]); ans += i[2]; } if (ds.count == 1) { return ans; } } return ans; } };
true
218b2add386ffa95acfd9907098ad2cbf023a59b
C++
caiji200/cs330Assignment5
/Process.cpp
UTF-8
1,514
3.21875
3
[]
no_license
#include "Process.h" Process::Process() { Priority = 0; processingTime = 0.0; burstTime = 0.0; processName = ""; }; Process::Process(int myPriority, float myProcessingTime, float myBurstTime, string myProcessName) { this->Priority = myPriority; this->processingTime = myProcessingTime; this->burstTime = myBurstTime; this->processName = myProcessName; }; void Process::setProcessingTime(float myProcessingTime) { processingTime = myProcessingTime; }; float Process::getProcessingTime() { return processingTime; }; float Process::getBurstTime() { return burstTime; } void Process::changeProcessingTime(float newProssingTime) { processingTime = newProssingTime; }; void Process::incrementBurstTime(float newBurstTime) { burstTime += newBurstTime; }; void Process::setPriority(int myPriority) { Priority = myPriority; }; int Process::getPriority() { return Priority; }; void Process::changePriority(int newPriority) { Priority = newPriority; }; string Process::getProcessName() { return processName; }; void Process::printProcee() { cout <<"Priority: "<<Priority << endl; cout <<"Processingtime: " << processingTime << endl; cout <<"Bursttime: " << burstTime << endl; cout <<"ProcessName: "<<processName <<endl; }; Process& Process::operator= (const Process& other) { this->processName = other.processName; this->burstTime = other.burstTime; this->Priority = other.Priority; this -> processingTime = other.processingTime; return *this; }
true
12f78eaec8799e1025ca19bc16ab757e50a26680
C++
dihesoyam/carder_on_c
/core/core.cpp
UTF-8
533
2.84375
3
[]
no_license
#include <iostream> #include "funcs.h" using std::cout; using std::endl; using std::cin; int launch() { int first, second, rnd_value, *value_address; start = true; if(start){ cout<<"Enter minimal value: "<<endl; cin>>first; cout<<"Enter value of scatter: "<<endl; cin>>second; rnd_value = getRandom(first,second); value_address = &rnd_value; cout<<"Random value: "<<rnd_value<< " at "<<value_address<<endl; start = false; restart(start); } return 0; }
true
4ef50bde101c99282b1d1d07d4e2d6135d626de8
C++
alanbu/tbx
/tbx/path.h
UTF-8
13,148
2.53125
3
[]
no_license
/* * tbx RISC OS toolbox library * * Copyright (C) 2010-2014 Alan Buckley All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <string> #include <vector> #include "kernel.h" #ifndef TBX_PATH_H #define TBX_PATH_H namespace tbx { /** * Special file type returned for a directory */ const int FILE_TYPE_DIRECTORY = 0x1000; /** * Special file type returned for an application directory. * i.e. a directory where the first character is a '!' */ const int FILE_TYPE_APPLICATION = 0x2000; /** * Class to handle the 5 byte times. * * The 5 byte time is used for time/date stamps on files * on RISCOS. It is the number of centi-seconds from * Midnight on 1st Jan 1900. */ class UTCTime { public: UTCTime(); UTCTime(long long csecs); UTCTime(unsigned int loadAddress, unsigned int execAddress); UTCTime(const UTCTime &other); UTCTime &operator=(const UTCTime &other); static UTCTime now(); std::string text() const; std::string text(const std::string &format) const; /** * Get the low 4 bytes of the UTC time * * @returns the low 4 bytes as a 32 bit integer */ unsigned int low_word() const {return (unsigned int)(_centiseconds & 0xFFFFFFFF);} /** * Get the high byte of the UTC time * * @return the 8 bits of the high byte */ unsigned char high_byte() const {return (unsigned char)((_centiseconds >> 32) & 0xFF);} /** * Get the UTC time as centiseconds * * @returns number of centiseconds since Midnight Jan 1st 1900 */ long long centiseconds() const {return _centiseconds;} /** * Pointer to start of time in memory. * This is used for calls to the OS that pass a UTC. */ unsigned char *buffer() {return (unsigned char *)&_centiseconds;} /** * Pointer to start of time in memory * This is used for calls to the OS that pass a UTC. */ unsigned char *buffer() const {return (unsigned char *)&_centiseconds;} protected: /** * Number of centiseconds since Midnight Jan 1st 1900 */ long long _centiseconds; }; class Path; /** * Class to hold the catalogue information for a file. */ class PathInfo { public: PathInfo(); PathInfo(const PathInfo &other); PathInfo &operator=(const PathInfo &other); bool operator==(const PathInfo &other); bool operator!=(const PathInfo &other); bool read(const Path &path); bool read_raw(const Path &path, bool calc_file_type); /*! Type of an object */ enum ObjectType { NOT_FOUND, /*!< Path does not exist on disc */ FILE, /*!< Path is a file */ DIRECTORY, /*!< Path is a directory */ IMAGE_FILE /*!< Path is an image file */ }; /*! Attributes of an object. 0 or more of these will be combined using the | operation. */ enum Attribute { OWNER_READ = 0x1, /*! Read access for owner */ OWNER_WRITE = 0x2, /*! Write access for owner */ OWNER_LOCKED = 0x8, /*! Object locked against owner deletion */ OTHER_READ = 0x10, /*! Read access for others */ OTHER_WRITE = 0x20, /*! Write access for others */ OTHER_LOCKED = 0x80 /*! Object locked against others deletion */ }; /** * Get the leaf name of the object the information if for * * @returns leaf name of the object */ const std::string &name() const {return _name;} // Object type ObjectType object_type() const; /*! Returns true if object exists on the file system */ bool exists() const {return (_object_type != NOT_FOUND);} /*! Returns true if object is a file on the file system */ bool file() const {return (_object_type == FILE);} /*! Returns true if object is a directory on the file system */ bool directory() const {return (_object_type == DIRECTORY);} /*! Returns true if object is am image file on the file system */ bool image_file() const {return (_object_type == IMAGE_FILE);} // File type format bool has_file_type() const; int file_type() const; int raw_file_type() const; UTCTime modified_time() const; // Load/Executable format bool has_load_address() const; unsigned int load_address() const; unsigned int exec_address() const; // All formats int length() const; int attributes() const; /** * Iterator used to iterate through a directory * * use the tbx::PathInfo::begin and tbx::PathInfo::end methods * to return this iterator */ class Iterator { protected: Iterator(const std::string &dirName, const char *wildCard); friend class PathInfo; public: Iterator(); ~Iterator(); Iterator(const Iterator &other); Iterator &operator=(const Iterator &other); bool operator==(const Iterator &other); bool operator!=(const Iterator &other); Iterator &operator++(); Iterator operator++(int); PathInfo &operator*(); PathInfo *operator->(); void next(); // Variables protected: PathInfo *_info; /*!< Information on item iterator is pointing to */ /** * Low level class to deal with the file iteration kernel calls */ class IterBlock { public: IterBlock(const std::string &dirName, const char *wildCard); ~IterBlock() {delete _dirName; delete _wildCard;} bool next(); /** * Return next record from iteration block */ const char *next_record() const {return _nextRecord;} bool info(PathInfo &info); /** * Increase reference count on this block */ void add_ref() {_ref++;} /** * Decrease reference count on this block. * * If the reference count reaches zero it will be deleted */ void release() {if (--_ref == 0) delete this;} // Variables int _ref; /*!< Reference count */ _kernel_swi_regs _regs; /*!< registers for swi calls */ char *_dirName; /*!< Directory name */ char *_wildCard; /*!< Wild card for searching */ enum {_readSize = 2048};/*!< Size of data to read with swi call */ char _readData[_readSize];/*!< Buffer for read data */ int _toRead; /*!< Bytes left to read */ char *_nextRecord; /*!< Next record in buffer */ } *_iterBlock; }; friend class Iterator::IterBlock; static PathInfo::Iterator begin(const Path &path, const std::string &wildCard); static PathInfo::Iterator begin(const Path &path); static PathInfo::Iterator end(); protected: std::string _name; /*!< Name of the file system object */ ObjectType _object_type; /*!< Object type */ unsigned int _load_address; /*!< Load address */ unsigned int _exec_address; /*!< Executable address */ int _length; /*!< Length of object */ int _attributes; /*!< object attributes */ int _file_type; /*!< object file type */ }; /** * Class to manipulate RISC OS file and directory path names. */ class Path { public: Path(); Path(const std::string &name); Path(const char *name); Path(const Path &other); Path(const Path &other, const std::string &child); Path(const Path &other, const char *name); virtual ~Path(); // Assignment Path &operator=(const Path &other); Path &operator=(const std::string &name); Path &operator=(const char *name); Path &set(const Path &other, const std::string &child); // Attributes /** * Get file name of path * * @returns file name */ const std::string &name() const {return _name;} operator const std::string&() const; operator const char *() const; Path child(const std::string &child) const; Path parent() const; Path &down(const std::string &child); Path &up(); void leaf_name(const std::string &child); std::string leaf_name() const; PathInfo::ObjectType object_type() const; bool path_info(PathInfo &info) const; bool raw_path_info(PathInfo &info, bool calc_file_type) const; bool exists() const; bool file() const; bool directory() const; bool image_file() const; // File information int file_type() const; bool file_type(int type); static int file_type(const std::string &file_name); static bool file_type(const std::string &file_name, int type); int raw_file_type() const; int attributes() const; bool attributes(int new_attributes); UTCTime modified_time() const; //TODO: bool modified_time(const UTCTime &utcTime); // Creation void create_file(int type) const; void create_directory() const; // Deletion void remove() const; // Simple renaming void rename(const std::string &new_name); /** * Enumeration to options for copy method. * * These flags can be combined */ enum CopyOption { COPY_RECURSE=1, // Recursively copy COPY_FORCE=2, // Overwrite destination if it already exists COPY_ALLOW_PRINT = 0x100u, // Allow copy to printer COPY_NO_ATTRIBUTES = 0x200u, // Don't copy attributes COPY_STAMP = 0x400u, // Reset date stamp COPY_STRUCTURE = 0x800u, // Copy directory structure but not files COPY_NEWER = 0x1000u, // Copy if newer then destination only COPY_LOOK = 0x4000u // Check destination first }; void copy(const std::string &copyto, unsigned int options = 0); void copy(const std::string &copyto, unsigned int options, void *buffer, unsigned int size); void move(const std::string &copyto, unsigned int options = 0); void move(const std::string &copyto, unsigned int options, void *buffer, unsigned int size); // Whole file loading/saving char *load_file(int *length = 0) const; void save_file(const char *data, int length, int file_type) const; bool set_current_directory() const; void canonicalise(); static std::string canonicalise(const std::string &path); bool canonical_equals(const tbx::Path &compare_to) const; bool canonical_equals(const std::string &compare_to) const; static Path temporary(const char *prefix = 0); //Operators /** * Iterator to step through files in a folder. * * This is return by the tbx::Path::begin and tbx::Path::end * methods. */ class Iterator { protected: Iterator(const std::string &dirName, const char *wildCard); friend class Path; public: Iterator(); ~Iterator() {if (_iterBlock) _iterBlock->release();} Iterator(const Iterator &other); Iterator &operator=(const Iterator &other); bool operator==(const Iterator &other); bool operator!=(const Iterator &other); Iterator &operator++(); Iterator operator++(int); /** * Get file name for current iterator * * @returns file name */ std::string &operator*() {return _name;}; /** * Get file name for current iterator * * @returns file name */ std::string *operator->() {return &_name;}; void next(); // Variables /** * Variable for current file name */ std::string _name; /** * Low level class to deal with the file iteration kernel calls */ class IterBlock { public: IterBlock(const std::string &dirName, const char *wildCard); ~IterBlock() {delete _dirName; delete _wildCard;} bool next(); /** * Get next name * * @returns next name found */ const char *next_name() const {return _nextName;} /** * Increase reference count on this block */ void add_ref() {_ref++;} /** * Decrease reference count on this block. * * If the reference count reaches zero it will be deleted */ void release() {if (--_ref == 0) delete this;} // Variables int _ref; /*!< Reference count */ _kernel_swi_regs _regs; /*!< registers for swi calls */ char *_dirName; /*!< Directory name */ char *_wildCard; /*!< Wild card for searching */ enum {_readSize = 2048};/*!< Size of data to read with swi call */ char _readData[_readSize];/*!< Buffer for read data */ int _toRead; /*!< Bytes left to read */ char *_nextName; /*!< Next name in the buffer */ } *_iterBlock; }; Path::Iterator begin(const std::string &wildCard); Path::Iterator begin(); Path::Iterator end(); protected: /** * File name this path refers to */ std::string _name; }; }; #endif // TBX_PATH_H
true
e841efabf2cfdf20f061b1b5adf17c9cc14554d8
C++
rlee32/standard-k-opt
/k-opt/fileio/PointSet.cpp
UTF-8
1,971
3.03125
3
[]
no_license
#include "PointSet.h" namespace fileio { PointSet::PointSet(const char* file_path) { std::cout << "\nReading point set file: " << file_path << std::endl; std::ifstream file_stream(file_path); if (not file_stream.is_open()) { std::cout << "ERROR: could not open file: " << file_path << std::endl; return; } size_t point_count{0}; // header. std::string line; while (not file_stream.eof()) { std::getline(file_stream, line); if (line.find("NODE_COORD_SECTION") != std::string::npos) // header end. { break; } if (line.find("DIMENSION") != std::string::npos) // point count. { std::string point_count_string = line.substr(line.find(':') + 1); point_count = std::stoi(point_count_string); std::cout << "Number of points according to header: " << point_count << std::endl; } } if (point_count == 0) { std::cout << "ERROR: could not read any points from the point set file." << std::endl; return; } // coordinates. while (not file_stream.eof()) { if (m_x.size() >= point_count) { break; } std::getline(file_stream, line); std::stringstream line_stream(line); primitives::point_id_t point_id{0}; line_stream >> point_id; if (point_id == m_x.size() + 1) { primitives::space_t value{0}; line_stream >> value; m_x.push_back(value); line_stream >> value; m_y.push_back(value); } else { std::cout << "ERROR: point id (" << point_id << ")does not match number of currently read points (" << m_x.size() << ")." << std::endl; } } std::cout << "Finished reading point set file.\n" << std::endl; } } // namespace fileio
true
c8d262d8f2f28fb8269be89eebb082b4e2269000
C++
pmeade/dragons
/src/HouseState.h
UTF-8
514
2.765625
3
[]
no_license
// // Created by Patrick Meade on 2019-03-26. // #ifndef DRAGONS_HOUSESTATE_H #define DRAGONS_HOUSESTATE_H #include <ostream> struct HouseState { uint8_t dimension; uint8_t number; uint32_t value; friend ostream &operator<<(ostream &os, const HouseState &state) { ios_base::fmtflags stream_state( os.flags() ); os << std::hex; os << state.dimension << state.number << state.value; os.flags( stream_state ); return os; } }; #endif //DRAGONS_HOUSESTATE_H
true
ccb0a4e87b00538090a0f73390ade1a76897c55a
C++
LuukSteeman/Themadevices-groep_7
/src/Gamemaster/controllers/transferController.hpp
UTF-8
1,019
3.171875
3
[]
no_license
#pragma once #include "../entity/damageStorage.hpp" #include "rtos.hpp" #include "transferController.hpp" #include "hwlib.hpp" #include "../boundary/usb.hpp" /* Transfer controller can be run by running run and giving it a task */ class TransferController { public: /** Create a transfer controller @param ds Reference to damage storige which should be transfered */ TransferController(DamageStorage &ds) : ds(ds){}; /** Run the transfer controller. This waits for a '\n'to be received and then sends data over serial @param task The task in which this controller is run. */ void run(rtos::task_base *task) { ds.addDamage(10,5); ds.addDamage(10,5); ds.addDamage(10,5); do { while (!hwlib::cin.char_available()) { task->sleep(10 * rtos::us); } } while (hwlib::cin.getc() != '\n'); USB::writeToUSB(ds); }; private: DamageStorage &ds; };
true
af3fac8cc666b166d4d0d432dda789573c887c77
C++
tkr987/NyaGadget
/GT_Kruskal.h
UTF-8
4,399
3.28125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; namespace NyaGadget { /*** クラスカル法ライブラリ ***/ struct GT_Kruskal { struct Edge { long long f = 0; // from vertex long long t = 0; // to vertex long long cost = 0; bool operator < (const Edge& r) { return cost < r.cost; } }; /** @brief 最小全域木の最小コストを求める @param lg 隣接リスト @note 計算量 O(ElogV) **/ static long long Run(vector<vector<pair<long long, long long>>>& lg) { vector<Edge> edge; for (long long f = 0; f < (long long)lg.size(); f++) { // 辺をコストでソート for (auto& e: lg[f]) edge.push_back({ f, e.first, e.second }); } sort(edge.begin(), edge.end()); long long res = 0; UnionFind uf((long long)lg.size() + 1); for (auto& e: edge) { if (uf.Find(e.f) != uf.Find(e.t)) { // 閉路にならなければ追加 uf.Union(e.f, e.t); res += e.cost; } } return res; } /*** UnionFindライブラリ ***/ struct UnionFindVertex { // 頂点を表現する構造体 long long self = 0; // 自分自身のインデックス long long root = 0; // 根のインデックス long long size = 0; // 自分が属している木のサイズ }; struct UnionFind { vector<UnionFindVertex> v; /** @brief コンストラクタ @param max 頂点数 @note [0-max)の素集合データ構造を作成する **/ UnionFind(long long max) { // [0-max]のデータ構造にするため、max+1でリサイズ v.resize(max); for (long long i = 0; i < max; i++) { // 各頂点の根を自分自身で初期化、木サイズは1 v[i].self = i; v[i].root = i; v[i].size = 1; } } /** @brief 根を検索する関数 @param i 根を検索する頂点インデックス @note 引数で指定された頂点の根を返す。 **/ long long Find(long long i) { if (i == v[i].root) return i; // 根の探索をすると同時に次からO(1)で根を参照できるようにする(経路圧縮) v[i].root = Find(v[i].root); return v[i].root; } /** @brief 頂点を併合する関数 @param i1 併合する頂点1 @param i2 併合する頂点2 @note 頂点i1を含む木と頂点i2を含む木を「サイズ優先で」併合する。 ただし、i1とi2が既に同じ木に属しているときは何もしない。 併合したときtrue、何もしなかったときfalseを返す。 サイズによる工夫により、計算量はアッカーマンの逆関数になる。 **/ bool Union(long long i1, long long i2) { long long root1 = Find(i1); long long root2 = Find(i2); // 既に同じ木に属しているときは何もしない if (root1 == root2) return false; // サイズの小さい木の根をサイズの大きい木の根に繋いで併合する if (v[root1].size < v[root2].size) { v[root1].root = root2; v[root2].size += v[root1].size; } else { v[root2].root = root1; v[root1].size += v[root2].size; } return true; } /** @brief 頂点を併合する関数 @param i1 併合する頂点1 @param i2 併合する頂点2 @param p 親指定 @note 頂点i1を含む木と頂点i2を含む木を「pを含む木を親として」併合する。 ただし、i1とi2が既に同じ木に属しているときは何もしない。 併合したときtrue、何もしなかったときfalseを返す。 計算量はO(logN)になり、アッカーマンの逆関数に比べて若干遅くなる。 **/ bool Union(long long i1, long long i2, long long p) { long long root1 = Find(i1); long long root2 = Find(i2); long long rootp = Find(p); // 既に同じ木に属しているときは何もしない if (root1 == rootp && root2 == rootp) return false; // 子の木を親の木へ併合する if (rootp == root1) { v[root2].root = rootp; v[rootp].size += v[root2].size; } else if (rootp == root2) { v[root1].root = rootp; v[rootp].size += v[root1].size; } else { v[root1].root = rootp; v[rootp].size += v[root1].size; v[root2].root = rootp; v[rootp].size += v[root2].size; } return true; } }; }; }
true
06cd099080f6186af0de2867feeb0a70fd22c8f0
C++
pdet/kaleidoscope
/src/include/ast/ExprAST.hpp
UTF-8
386
2.515625
3
[]
no_license
#pragma once #include "llvm/IR/BasicBlock.h" // Base Class for all expression nodes. class ExprAST{ public: virtual ~ExprAST() = default; // Value is an LLVM object used to represent SSA register // Its value is computed as the related instruction executes and it does not get a new value until // (and if) the instruction re-executes virtual llvm::Value *codegen() = 0; };
true
979deafa77688070e4023719be002e604abdc1a8
C++
FRENSIE/FRENSIE
/packages/monte_carlo/collision/electron/src/MonteCarlo_ElectronScatteringDistributionNativeFactoryHelpers.cpp
UTF-8
2,287
2.5625
3
[ "BSD-3-Clause" ]
permissive
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_ElectronScatteringDistributionNativeFactoryHelpers.cpp //! \author Luke Kersting //! \brief The electron scattering distribution native factory helpers definitions //! //---------------------------------------------------------------------------// // FRENSIE Includes #include "MonteCarlo_ElectronScatteringDistributionNativeFactoryHelpers.hpp" namespace MonteCarlo{ //----------------------------------------------------------------------------// // ****ELASTIC DISTRIBUTIONS**** //----------------------------------------------------------------------------// // Create a screened rutherford elastic distribution std::shared_ptr<const MonteCarlo::ScreenedRutherfordElasticElectronScatteringDistribution> createScreenedRutherfordElasticDistribution( const Data::ElectronPhotonRelaxationDataContainer& data_container ) { std::shared_ptr<const ScreenedRutherfordElasticElectronScatteringDistribution> distribution; ElasticElectronScatteringDistributionNativeFactory::createScreenedRutherfordElasticDistribution( distribution, data_container.getAtomicNumber() ); // Make sure the distribution was created correctly testPostcondition( distribution.use_count() > 0 ); return distribution; } //----------------------------------------------------------------------------// // ****ATOMIC EXCITATION DISTRIBUTION**** //----------------------------------------------------------------------------// //! Create a atomic excitation distribution std::shared_ptr<const AtomicExcitationElectronScatteringDistribution> createAtomicExcitationDistribution( const Data::ElectronPhotonRelaxationDataContainer& data_container ) { std::shared_ptr<const AtomicExcitationElectronScatteringDistribution> distribution; AtomicExcitationElectronScatteringDistributionNativeFactory::createAtomicExcitationDistribution( data_container, distribution ); return distribution; } } // end MonteCarlo namespace //---------------------------------------------------------------------------// // end MonteCarlo_ElectronScatteringDistributionNativeFactoryHelpers.cpp //---------------------------------------------------------------------------//
true
b41a307809913a5c4df75eab2b80ee081547c495
C++
tjt7a/VASim
/test/VASim/testExactStringMatch.cpp
UTF-8
2,059
3.234375
3
[]
permissive
#include "automata.h" #include "test.h" /** * Adds STEs to an automata to match an exact string. Simulates the automata on that string. Should obviously have one report at the end of simulation. */ using namespace std; string testname = "TEST_EXACT_MATCH"; string wrapWithBrackets(char c) { string str = string("[" + string(1,c) + "]"); return str; } /* * */ void addStringToAutomata(Automata *ap, string str, uint32_t *id_counter) { vector<STE*> stes; string charset = "["; // make STEs for(char c : str){ stes.push_back(new STE("__" + to_string(*id_counter) + "__", wrapWithBrackets(c), "none")); (*id_counter)++; } // Make first STE start stes[0]->setStart("all-input"); // Make last STE report stes[str.size() - 1]->setReporting(true); // add STEs to automata for(STE *ste : stes) { ap->rawAddSTE(ste); } // add edges between STEs for(int i = 0; i < str.size() - 1; i++){ ap->addEdge(stes[i], stes[i+1]); } } /* * */ int main(int argc, char * argv[]) { // Automata ap; ap.enableQuiet(); // global ID counter uint32_t id_counter = 0; // Add a an exact match string to the automata string str = "Jack"; addStringToAutomata(&ap, str, &id_counter); // get how many reports we've seen uint32_t numReports = ap.getReportVector().size(); //(this should be 0) if(numReports != 0) fail(testname); // enable report gathering for the automata ap.enableReport(); // initialize simulation ap.initializeSimulation(); // simulate the automata on the input string ap.simulate(reinterpret_cast<uint8_t*>(&str[0]), 0, str.size(), false); // print out how many reports we've seen numReports = ap.getReportVector().size(); //(this should be 1) if(numReports != 1) fail(testname); // if we haven't failed, pass the test pass(testname); }
true
2f5854aa7d334d2e620b3a77069eef33411552d9
C++
progdn/ProGDN-RVI
/src/progdn_core/ip_address_helper.h
UTF-8
480
2.671875
3
[]
no_license
#pragma once #include <boost/asio.hpp> namespace progdn { struct IP_Host { uint32_t host; IP_Host() = default; IP_Host(const char* serialized) { struct in_addr addr; if (!::inet_pton(AF_INET, serialized, &addr)) throw std::invalid_argument(std::string("\"") + serialized + "\" is not a valid IP"); host = boost::asio::detail::socket_ops::network_to_host_long(addr.s_addr); } }; }
true
e4359543c4ec9bf32294efcc9a481716fd883b6e
C++
YanaPatyuk/MyProjects
/Advanced programming 1-C++/ex7/src/server/src/Server.cpp
UTF-8
7,039
2.765625
3
[]
no_license
/* * Server.cpp * * Created on: 2 בדצמ׳ 2017 * Author: yanap */ #include "../include/Server.h" #include <unistd.h> Server::Server(int port, CommandManager *controller) : port(port), serverSocket(0), pool(10) { this->controller = controller; cout << "Server" << endl; this->stopGame = 0; } void Server::start() { // Create a socket point serverSocket = socket(AF_INET, SOCK_STREAM, 0); if (serverSocket == -1) { throw "Error opening socket"; } // Assign a local address to the socket struct sockaddr_in serverAddress; bzero((void *) &serverAddress, sizeof(serverAddress)); serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = INADDR_ANY; serverAddress.sin_port = htons(port); if (bind(serverSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) == -1) { throw "Error on binding"; } // Start listening to incoming connections listen(serverSocket, MAX_CONNECTED_CLIENTS); pthread_t end; pthread_t serverOperation; ClientArgs arg; arg.serverSocket = serverSocket; //no clients for now. arg.clientSocket = 0; //this argument used only for exit thread. arg.indexAtThreadArr = 0; //gameControl arg.controller = this->controller; //map of threads. arg.threadArr = &this->threads; arg.pool = &this->pool; //this thread in charge to regularly check "exit" input on the server in order to stop the server int rc = pthread_create(&end, NULL, CloseAllGames, (void *) &arg); if (rc) { cout << "Error: unable to create thread, " << rc << endl; return; } //this thread accept new clients and handles them. //first insert thread to list threads.insert(pair<int, pthread_t>(0, serverOperation)); rc = pthread_create(&serverOperation, NULL, ServerAcceptClients, (void *) &arg); if (rc) { cout << "Error: unable to create thread, " << rc << endl; return; } //wait the exit to stop void *status; pthread_join(end, &status); //stop the server-close servers socket. stop(); } void Server::stop() { close(serverSocket); } Server::~Server() { } int Server::ConnectNewClients() { struct sockaddr_in clientAddress; socklen_t clientAddressLen; int player = accept(serverSocket, (struct sockaddr *) &clientAddress, &clientAddressLen); cout << "Client 1 connected" << endl; if (player == -1) throw "Error on accept"; return player; } void Server::CloseClientSocket(int player) { //close clients socket. close(player); } void Server::SendMessageToClient(int player, char *massage) { int n = write(player, massage, sizeof(massage)); if (n == -1) { cout << "Error writing to socket" << endl; return; } else if (n == 0) { cout << "Client disconnected" << endl; return; } } char *Server::GetMessageFromClient(int player) { char massage[50]; char *buffer = massage; //read from client massage. int n = read(player, buffer, sizeof(buffer)); //if reading didnt work-return null/ if (n == -1) { cout << "Error reading point" << endl; return NULL; //if client disconnected-return null } else if (n == 0) { cout << "Client disconnected" << endl; return NULL; } //return massage from client. return buffer; } void *Server::HandleClient(void *clientArgs) { // break the struct back to parameters // cast back from void* to struct struct ClientArgs *playersInfo = (struct ClientArgs *) clientArgs; int client = playersInfo->clientSocket; CommandManager *control = playersInfo->controller; // Read massage from player. char msg[50]; char *buffer = msg; memset(msg, 0, 50); bool endReading = false; do { int n = read(client, msg, sizeof(msg)); if (n == -1) { cout << "Error reading point" << endl; pthread_exit(NULL); } else if (n == 0) { cout << "Client disconnected" << endl; pthread_exit(NULL); } //concert array to string. string massage(buffer); //split the massage to the command and values clients send. //value will be command and <gameName> if there's two of them or just command. string i; vector<string> vect; stringstream ss(massage); bool twoWords = false; while (ss >> i) { vect.push_back(i); if (ss.peek() == ' ') { ss.ignore(); twoWords = true; } } //create struct of arguments command will get. CommandInfo args; string command = vect.at(0).c_str(); if (twoWords) { string val = vect.at(1).c_str(); args.gameName = val; } args.clientSocket = client; // Execute the Command if (control->ExecuteCommand(command, args)) { endReading = true; } else { cout << "no such command" << endl; } } while (!endReading); } void *Server::ServerAcceptClients(void *clientArgs) { struct sockaddr_in clientAddress; socklen_t clientAddressLen; int threadCounter = 1; struct ClientArgs *playersInfo = (struct ClientArgs *) clientArgs; int serverSocket = playersInfo->serverSocket; ThreadPool *pool = playersInfo->pool; while (true) { cout << "Waiting for client connections..." << endl; // Accept a new client connection int playerNumber = accept(serverSocket, (struct sockaddr *) &clientAddress, &clientAddressLen); cout << "Client " << playerNumber << " connected" << endl; playersInfo->controller->AddPlayerSocket(playerNumber); struct ClientArgs cArgs; cArgs.clientSocket = playerNumber; cArgs.controller = playersInfo->controller; //create new task for player. Task *client = new Task(HandleClient, (void *) &cArgs); pool->addTask(client); } } void *Server::CloseAllGames(void *args) { cout << "In order to force close type: exit" << endl; struct ClientArgs *playersInfo = (struct ClientArgs *) args; CommandManager *control = playersInfo->controller; map<int, pthread_t> *threadMap = playersInfo->threadArr; ThreadPool *pool = playersInfo->pool; string checkToClose; bool stop = false; while (!stop) { cin >> checkToClose; if (checkToClose.compare("exit") == 0) { stop = true; control->End(); map<int, pthread_t>::const_iterator it; pool->terminate(); for (it = threadMap->begin(); it != threadMap->end(); it++) { pthread_cancel(it->second); } } else { cout << "you typed something, but it wasn't exit \n"; cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } }
true
aabb70139e8212b10c3d2393db9ce26ce0334d3f
C++
huangshengh/c-primer
/16.6/源.cpp
UTF-8
585
3.59375
4
[]
no_license
#include <iostream> #include <vector> #include <list> #include <string> // the same as std::begin template<typename T, unsigned size> T* begin_def(T(&arr)[size]) { return arr; } // the same as std::end template<typename T, unsigned size> T* end_def(T(&arr)[size]) //We usually don't use a function name which is the same as the function of standard libary //This should not be const { return arr + size; } int main() { std::string s[] = { "sssss","ss","ss","ssssszzzz" }; std::cout << *(begin_def(s) + 1) << std::endl; std::cout << *(end_def(s) - 1) << std::endl; return 0; }
true
2830705af377a78498c14de9343df7f38445a549
C++
HardwareIR/netlistDB
/src/serializer/serializer_io.cpp
UTF-8
1,948
2.734375
3
[ "MIT" ]
permissive
#include <netlistDB/serializer/serialization_io.h> #include <boost/filesystem/operations.hpp> namespace netlistDB { namespace serializer { void iSerializationIO::file_extension(const std::string & extension) { FILE_EXTENSION = extension; } void iSerializationIO::hierarchy_push(const std::string & name) { } void iSerializationIO::hierarchy_pop() { } iSerializationIO::~iSerializationIO() { } SerializeToStream::SerializeToStream(std::ostream & str) : _str(str) { } std::ostream & SerializeToStream::str() { return _str; } SerializeToFiles::SerializeToFiles(const std::string & root, bool to_top_dir, bool flat, bool do_clear_top) : root(root), to_top_dir(to_top_dir), flat(flat), top_clear(false), do_clear_top( do_clear_top) { if (not boost::filesystem::is_directory(this->root)) throw std::ios_base::failure( std::string("Not a accessible directory \"") + root + "\""); } std::ostream & SerializeToFiles::str() { return _str; } void SerializeToFiles::hierarchy_push(const std::string & name) { scope.push_back(name); boost::filesystem::path top_dir; if (not top_clear) { assert(scope.size() == 1); // clear or create the top directory if (to_top_dir) { top_dir = root / name; } else { top_dir = root; } if (do_clear_top) { boost::filesystem::remove_all(top_dir); boost::filesystem::create_directory(top_dir); } else { if (not boost::filesystem::is_directory(top_dir)) { boost::filesystem::create_directory(top_dir); } } top_clear = true; } else { if (flat) { if (to_top_dir) { top_dir = root / scope[0]; } else { top_dir = root; } } else { top_dir = root; for (auto & p : scope) { top_dir = top_dir / p; } } } auto of_name = top_dir / (name + FILE_EXTENSION); _str.open(of_name.string()); } void SerializeToFiles::hierarchy_pop() { scope.pop_back(); _str.close(); } SerializeToFiles::~SerializeToFiles() { _str.close(); } } }
true
66e91c7fcd54d072b60be72fda988d3d5ea454d5
C++
KaileyCozart/Data-Structures-Final-Project
/Emergency Room Simulation/Emergency Room Simulation/Doctor.h
UTF-8
948
3.09375
3
[]
no_license
#pragma once #ifndef DOCTOR_H_ #define DOCTOR_H_ #include "Random.h" #include "Staff.h" class Doctor : public Staff { private: int max_treatment_time = 20; int treatment_time = 0; int max_severity = 20; int start_time = 0; Random* my_random = new Random(); public: Doctor(); ~Doctor(); int get_max_severity() { return max_severity; } void set_treatment_time(int clock) { treatment_time = my_random->int_range(1, max_treatment_time); start_time = clock; } // If the doctor has finished treating the patient, remove pointer to patient and reset variables int update_staff(int clock) { if (start_time + treatment_time == clock && current_patient != NULL) { int result = clock - current_patient->arrival_time; current_patient = NULL; start_time = 0; treatment_time = 0; return result; } else return 0; } }; Doctor::Doctor() : Staff() {} Doctor::~Doctor() { delete[] my_random; } #endif DOCTOR_H_
true
7dac602b118701e554e0862543c4f062215d14a9
C++
egormkn/SDLXX
/examples/game/game.h
UTF-8
1,796
2.515625
3
[ "Zlib" ]
permissive
#ifndef SDLXX_GAME_H #define SDLXX_GAME_H #include <box2d/box2d.h> #include "Box2DDrawer.h" namespace sdlxx { class Game : public Scene { public: explicit Game() : Scene("The game") { b2Vec2 gravity(0.0f, 9.8f); world = std::make_unique<b2World>(gravity); b2BodyDef groundBodyDef; groundBodyDef.position.Set(3.5f, 15.0f); groundBody = world->CreateBody(&groundBodyDef); b2PolygonShape groundBox; groundBox.SetAsBox(3.0f, 2.0f); groundBody->CreateFixture(&groundBox, 0.0f); b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(5.0f, 4.0f); body = world->CreateBody(&bodyDef); b2PolygonShape dynamicBox; dynamicBox.SetAsBox(1.0f, 1.0f); b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; body->CreateFixture(&fixtureDef); } ~Game() { world->DestroyBody(groundBody); world->DestroyBody(body); body = nullptr; groundBody = nullptr; } protected: void OnActivate() override { Scene::OnActivate(); drawer = std::make_unique<Box2DDrawer>(GetContext()->renderer, 30.f); drawer->SetFlags(0xFF); world->SetDebugDraw(drawer.get()); } void OnDeactivate() override { world->SetDebugDraw(nullptr); drawer.reset(nullptr); Scene::OnDeactivate(); } public: bool HandleEvent(const Event& e) override { return ParentNode::HandleEvent(e); } void Update(Time dt) override { world->Step(dt.AsSeconds(), 6, 2); } void Render(Renderer& renderer) const override { world->DebugDraw(); } private: std::unique_ptr<b2World> world; std::unique_ptr<Box2DDrawer> drawer; b2Body* body = nullptr; b2Body* groundBody = nullptr; }; } // namespace sdlxx #endif // SDLXX_GAME_H
true
fe2c5b8deb3b0d71c222d1e649ee686ae66fe4fa
C++
dani125/Airline-Reservation-System
/Airplane/Airplane/Airplane/Airplane/Flight.h
UTF-8
976
2.6875
3
[]
no_license
#pragma once #include <iostream> #include <string> #include "AircraftSeat.h" using namespace std; const int totalSeat = 20; class Flight:public AircraftSeat { public: Flight(); ~Flight(); void setDeparture(string ); string getDeparture(); void setArrival(string); string getArrival(); void setDepartTime(string ); string getDepartTime(); void setArrivalTime(string ); string getArrivalTime(); void setFlightNumber(int ); int getFlightNumber(); void setAircraftType(string ); string getAircraftType(); void setFlighPoints(int); int getFlightPoints(); void setSeats(); void getSeats(); string displayFlightInfo(); void freeSeat(string); void seatTaking(string ); bool flightOverBook(); string checkAvailability(string ); private: string departure; string arrival; string departTime; string arrivalTime; int flightNumber; string airCraftType; int flightPoints; AircraftSeat allSeat[totalSeat]; };
true
fefa9f355413347c9b6210ecc561a8e3167fb746
C++
Vangasse/Huffman
/node.cpp
UTF-8
979
3.140625
3
[]
no_license
#include "node.h" unsigned char Node::getValue() const { return value; } void Node::setValue(unsigned char value) { this->value = value; } QByteArray Node::getElement() const { return element; } void Node::setElement(QByteArray element) { this->element = element; } int Node::getNumber() const { return number; } void Node::setNumber(int value) { number = value; } Node *Node::getLeft() const { return left; } void Node::setLeft(Node *value) { left = value; } Node *Node::getRight() const { return right; } void Node::setRight(Node *value) { right = value; } Node::Node(unsigned char value, int number) { this->value = value; this->number = number; this->left = 0; this->right = 0; } Node::Node(QByteArray element) { this->element = element; this->left = 0; this->right = 0; } Node::~Node() { } bool Node::isLeaf(){ if(left == 0 && right == 0){ return true; } return false; }
true
2dc0a51598ee4b21fc613d83d0b2d6c7f8b24712
C++
NLObedear/MagicCards
/Magic Cards Code/Custom_Game_GP/InGameStateManager.cpp
UTF-8
1,482
2.921875
3
[]
no_license
#pragma once #include <iostream> #include "GameStates.cpp" #include "InGameStates.cpp" #include "EndGame.cpp" #include "PlayerTurn.cpp" #include "ComputerTurn.cpp" class InGameStateManager { private: EndGame quitgame; PlayerTurn playert; ComputerTurn compt; Field* field; PlayerHealth* health; InGameStates* _current = nullptr; bool _running = true; GameStates _state = GameStates::MAIN_MENU; public: bool running() const { return _state != GameStates::DONE; } void update() { if (_state == GameStates::PLAYER_TURN) { _current = &playert; field = compt.getField(); health = compt.getHealth(); } else if (_state == GameStates::COMPUTER_TURN) { _current = &compt; field = playert.getField(); health = playert.getHealth(); } else if (_state == GameStates::QUIT) { _current = &quitgame; PlayerTurn pt; playert = pt; ComputerTurn ct; compt = ct; } _state = _current->update(field, health); } void render() { if (_state == GameStates::PLAYER_TURN) { _current = &playert; } else if (_state == GameStates::COMPUTER_TURN) { _current = &compt; } else if (_state == GameStates::QUIT) { _current = &quitgame; } _current->render(); } void SetSate(InGameStates* start) { _current = start; if (_current == &playert) { _state = GameStates::PLAYER_TURN; } else if (_current == &compt) { _state = GameStates::COMPUTER_TURN; } } PlayerTurn* setPlayer() { return &playert; } ComputerTurn* setComp() { return &compt; } };
true
2072c6ae88df9d2afcf90debe25c7e1a5b441184
C++
Hannna/robocupsslclient
/ robocupsslclient/Plays/KickOffPlay.cpp
UTF-8
2,404
2.546875
3
[]
no_license
/* * KickOffPlay.cpp * * Created on: 24-05-2011 * Author: maciek */ #include "KickOffPlay.h" KickOffPlay::KickOffPlay( std::string teamColor ): Play( teamColor, 3) { /*przygotowuje roboty do wykopu pilki ze srodka boiska * */ // void SimplePlay::prepareForKickOff(const Vector2D& kickoffPose){ /* LOG_INFO(log,"STARTING prepareForKickOff " <<this->teamColor); Pose robot0GoalPose(kickoffPose,0); // AbstractTactic * robot0Task = new PositionToStart( robot0GoalPose,robot0); AbstractTactic * robot0Task = new Pass(*robot0,robot1->getRobotID()); robot0Task->markParam( AbstractTactic::start_from_kickoff ); tactics.push_back( robot0Task ); //robot0Task->start(NULL); Pose target; Pose p; /* if( this->teamColor.compare("red") == 0){ if( Videoserver::redGoal == top ) p = Pose(1,1,0); else p = Pose(-1,-1,0); } else{ if( Videoserver::blueGoal == top ) p = Pose(1,1,0); else p = Pose(-1,-1,0); } Pose robot0GoalPose( this->appConfig.field.FIELD_MIDDLE_POSE + p ); AbstractTactic * robot0Task = new PositionToStart( robot0GoalPose,robot0); tactics.push_back( robot0Task ); */ /* if( this->teamColor.compare("red") == 0){ if( Videoserver::redGoal == top ) p = Pose (-1,1,0); else p = Pose(1,-1,0); } else{ if( Videoserver::blueGoal == top ) p = Pose (-1,1,0); else p = Pose(1,-1,0); } Pose robot1GoalPose( this->appConfig.field.FIELD_MIDDLE_POSE + p ); AbstractTactic * robot1Task = new PositionToStart( robot1GoalPose,robot1); tactics.push_back(robot1Task); if( this->teamColor.compare("red") == 0){ if( Videoserver::redGoal == top ){ p = Pose (0,-1,0); } else{ p = Pose(0,1,0); } } else{ if( Videoserver::blueGoal == top ){ p = Pose (0,-1,0); } else{ p = Pose(0,1,0); } } if( this->teamColor.compare("red") == 0){ target = Pose( Videoserver::getRedGoalMidPosition(),0) ; } else{ target = Pose( Videoserver::getBlueGoalMidPosition(),0) ; } Pose robot2GoalPose( target + p ); AbstractTactic * robot2Task = new PositionToStart( robot2GoalPose,robot2); tactics.push_back(robot2Task); std::list<AbstractTactic *>::iterator tactic = tactics.begin(); for( ; tactic!= tactics.end();tactic++ ){ (*tactic)->start(NULL); } } */ } KickOffPlay::~KickOffPlay() { // TODO Auto-generated destructor stub }
true
2cf73b4117e025a6eba735adc168456177dc2238
C++
sammyne/LeetCodeCpp
/406-Queue-Reconstruction-by-Height/main.cpp
UTF-8
1,282
3.40625
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> using namespace std; class Solution { public: using PairType = pair<int, int>; static vector<pair<int, int>> reconstructQueue(vector<pair<int, int>> &people) { sort(std::begin(people), std::end(people), [](const PairType &pr1, const PairType &pr2) { if (pr1.first == pr2.first) { return pr1.second <= pr2.second; } return pr1.first > pr2.first; }); for (size_t i{1}; i < people.size(); ++i) { size_t j = i; while ((j > 0) && (j != people[j].second)) { std::swap(people[j], people[j - 1]); --j; } } return vector<PairType>{std::begin(people), std::end(people)}; } }; int main() { vector<pair<int, int>> people{{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}}; auto peopleQueue = Solution::reconstructQueue(people); for (const auto &p:peopleQueue) { cout << p.first << ", " << p.second << endl; } return 0; }
true
fa8f80bc2d684de2571b88cc08e003e84992560d
C++
LucasFROGER/MyWork
/Engine/Engine/Lights/Light.h
UTF-8
1,105
2.828125
3
[]
no_license
#ifndef _LIGHT_H_ #define _LIGHT_H_ #include "../Core/Maths/Vector/Vec4.h" #include "../Core/Maths/Matrix/Mat4.h" namespace engine { namespace light { class Light { public: Light(); Light(const Light& other); ~Light(); void SetColor(engine::core::maths::Vec4 color); void SetIntensity(float intensity); void SetUnused(); const int GetId() const; engine::core::maths::Vec4 GetColor() const; float GetIntensity() const; bool IsUsed() const; void SetLight(engine::core::maths::Vec3 light); Light& operator=(const Light& other); protected: Light(int id, engine::core::maths::Vec4 light, engine::core::maths::Vec4 color, float intensity); engine::core::maths::Vec4 m_lightVec; engine::core::maths::Vec4 m_color; float m_intensity; bool m_used; bool padBool[3]; // align bool to shader's bool: 1b -> 4b int m_id; //use as a pad float pad0; engine::core::maths::Mat4 m_view; engine::core::maths::Mat4 m_projection; void SetView(); void SetProjection(); engine::core::maths::Vec4 GetLightVec() const; }; } } #endif
true
e6bda96cfd5baaa30214e53d8480c1a201675cb8
C++
cesar-magana/Leet-Code
/0416. Partition Equal Subset Sum/canPartition01.cpp
UTF-8
1,140
3.03125
3
[]
no_license
bool canPartition(vector<int>& arr) { int sum = accumulate(arr.begin(), arr.end(), 0); int n = arr.size(); if ( sum%2 == 1 ) return false; bool part[sum / 2 + 1][n + 1]; // initialize top row as true for (int i = 0; i < n+1; i++) part[0][i] = true; // initialize leftmost column, // except part[0][0], as 0 for (int i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in botton up manner for (int i = 1; i <= sum / 2; i++) { for (int j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } /* // uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) cout<<part[i][j]; cout<<endl; } */ return part[sum / 2][n]; }
true
e1deb1d6a86d0352a0686886ebbc00738fab1290
C++
wegatron/embedded_thin_shell
/src/volume_simulator/ui_lib/Render/AxisTorus.h
UTF-8
1,334
2.78125
3
[ "Apache-2.0" ]
permissive
#ifndef _AXISTORUS_H_ #define _AXISTORUS_H_ #include <boost/shared_ptr.hpp> #include <SelfRenderEle.h> #include <Selectable.h> namespace QGLVEXT{ /** * @class AxisTorus * */ class AxisTorus:public SelfRenderEle, public Selectable{ public: AxisTorus(){ selected_axis = -1; translation[0] = 0.0; translation[1] = 0.0; translation[2] = 0.0; scalor[0] = 1.0; scalor[1] = 1.0; scalor[2] = 1.0; } void translate(const double x,const double y, const double z){ this->translation[0] = x; this->translation[1] = y; this->translation[2] = z; } void scale(const double x,const double y, const double z){ this->scalor[0] = x; this->scalor[1] = y; this->scalor[2] = z; } void draw()const; int totalEleNum ()const{ return 8; } void drawWithNames ()const; void selectAxis(int a){ selected_axis = a; } int selectedAxis()const{ return selected_axis; } protected: void drawTorus(float x, float y, float z, float r, float g, float b)const; void drawAxis(float x, float y, float z, float r, float g, float b)const; void drawOriginal(float r, float g, float b)const; private: int selected_axis; double translation[3], scalor[3]; }; typedef boost::shared_ptr<AxisTorus> pAxisTorus; }//end of namespace #endif /* _AXISTORUS_H_ */
true
20e872e2576463bf809996f430f9bc20b5c7539e
C++
krath912/tmproj
/object.cpp
UTF-8
4,432
2.6875
3
[]
no_license
#include <algorithm> #include <string> #include "object.h" #include "event.h" #include "background.h" #include "mainwindow.h" //loads an object void Object::loadGame() { QFile data("data.txt"); if(data.open(QIODevice::ReadWrite)){ QString s = data.readLine(); QString str = data.readLine(); int x = str.toInt(); QString str2 = data.readLine(); int y = str2.toInt(); this->setType(s.toStdString()); this->setX(x); this->setY(y); } } CuriousCat::CuriousCat(QWidget *parent) { setX(50); setY(176); setW(75); setH(75); setType("CuriousCat"); catMovie = new QMovie(":/cat.gif"); cat = new QLabel(parent); cat->setMovie(catMovie); catMovie->start(); cat->setGeometry(50,176, 75, 75); cat->setScaledContents(true); cat->show(); } MadDog::MadDog() { setX(250); setY(177); setW(75); setH(75); setType("MadDog"); setHealthImpact(50); /*dogMovie = new QMovie(":/dog.gif"); dog = new QLabel(parent); dog->setMovie(dogMovie); dogMovie->start(); dog->setGeometry(250,177, 75, 75); dog->setScaledContents(true); //objects.push_back(dog); dog->show(); Obstacle& o = Obstacle::instance(); o.obstacles.push_back(dog);*/ } //saves a dog void MadDog::saveGame() { QFile data("data.txt"); if(data.open(QIODevice::ReadWrite)){ QTextStream out(&data); out << this->x << "\n"; out << this->y << "\n"; } } void MadDog::dogTimerHit() { /*for (unsigned int i = 0; i < spawnedEns.size(); i++) { QLabel * enemy = new QLabel; enemy = spawnedEns[i]; enemy->move(enemy->x() - 1, enemy->y()); if (enemy->geometry().intersects(cat->geometry()) && end == nullptr) { end = new QLabel(this); end->setText("YOU LOSE"); end->showFullScreen(); end->setGeometry(cat->x(),cat->y() - 75, 100,100); end->setScaledContents(true); end->show(); } }*/ } LawnMower::LawnMower() { setX(350); setY(198); setW(50); setH(50); setType("LawnMower"); setHealthImpact(25); /*QPixmap mowerPic(":/lawnmower2.png"); mower = new QLabel(parent); mower->setPixmap(mowerPic); mower->setGeometry(350, 198, 50,50); mower->setScaledContents(true); mower->show(); Obstacle& o = Obstacle::instance(); o.obstacles.push_back(mower); //objects.push_back(mower);*/ } //saves a lawnmower void LawnMower::saveGame() { QFile data("data.txt"); if(data.open(QIODevice::ReadWrite)){ QTextStream out(&data); out << this->x << "\n"; out << this->y << "\n"; } } //saves a hole void Hole::saveGame() { QFile data("data.txt"); if(data.open(QIODevice::ReadWrite)){ QTextStream out(&data); out << this->x << "\n"; out << this->y << "\n"; } } Hole::Hole() { setX(150); setY(208); setW(75); setH(300); setType("Hole"); setHealthImpact(100); /*QPixmap holePic(":/hole.png"); hole = new QLabel(parent); hole->setPixmap(holePic); hole->setGeometry(150, 208, 75,300); hole->setScaledContents(true); hole->show(); Obstacle& o = Obstacle::instance(); o.obstacles.push_back(hole);*/ //objects.push_back(hole); } //QLabel* Object::objectSpawner(QWidget *parent) /*{ QLabel * madDogLabel = new QLabel(parent); QMovie * dogMovie = new QMovie(":/dog.gif"); madDogLabel->setMovie(dogMovie); madDogLabel->setGeometry(100,100,50,50); madDogLabel->setScaledContents(true); dogMovie->start(); madDogLabel->show(); //objects.push_back(madDogLabel); QLabel* lawnMowerLabel = new QLabel(parent); QPixmap mower(":/lawnmower2.png"); lawnMowerLabel->setPixmap(mower); lawnMowerLabel->setGeometry(150, 100, 50,50); lawnMowerLabel->setScaledContents(true); lawnMowerLabel->show(); //objects.push_back(lawnMowerLabel); QLabel* holeLabel = new QLabel(parent); QPixmap hole(":/hole.png"); holeLabel->setPixmap(hole); holeLabel->setGeometry(200,100,20,50); holeLabel->setScaledContents(true); holeLabel->show(); //objects.push_back(holeLabel); //objects = {madDogLabel,lawnMowerLabel,holeLabel}; }*/
true
62a9c5637d943fe2a37b1467bdad4c0a8a40c05f
C++
mouqi123/c-_test
/fifth/fifth_1.cpp
UTF-8
1,415
3.65625
4
[]
no_license
/** * File Name: fifth.cpp * Author: mackie * Mail: mouqi562315905@qq.com * Created Time: 2017年04月23日 星期日 16时17分39秒 */ #include<iostream> using namespace std; class Frame { public : int weight; int ID; Frame(): weight(0), ID(0) { } friend istream& operator>>(istream& in, Frame* f) { in >> f->ID >> f->weight; return in; } }; class Cardoor { public : int doors; string color; Cardoor(): doors(0), color("") { }; friend istream& operator>>(istream& in, Cardoor* c) { in >> c->doors>> c->color; return in; } }; class Tyre { public : int tyres; Tyre(): tyres(0) { }; friend istream& operator>>(istream& in, Tyre* t) { in >> t->tyres; return in; } }; class Vehicle : public Frame, public Cardoor, public Tyre { friend ostream& operator<<(ostream& out, Vehicle& v) { out << "vehicle's ID is : " << v.ID <<endl; out << "vehicle's number of door : " << v.doors <<endl; out << "vehicle's number of tyres : " << v.tyres <<endl; return out; } }; int main() { Vehicle* vehicle = new Vehicle(); Frame* frame = vehicle; Cardoor* cardoor = vehicle; Tyre* tyre = vehicle; cout << "please input frame's ID and weight : "; cin >> frame; cout << "please input cardoor's number and color : "; cin >> cardoor; cout << "please input number of tyres : "; cin >> tyre; cout << *vehicle; }
true
ceecc827b819c6feeef15707e53e01249fb2f891
C++
Wsewlad/CPP_Piscine
/d07/ex02/main.cpp
UTF-8
2,738
3.015625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vfil <vfil@student.unit.ua> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/27 19:50:22 by vfil #+# #+# */ /* Updated: 2018/06/27 19:50:23 by vfil ### ########.fr */ /* */ /* ************************************************************************** */ #include "Array.hpp" #include <iostream> #include <string> int main(void) { Array<char*> empt; std::cout << "empt <char*> size: " << empt.size() << std::endl; try { empt[0] = const_cast<char*>("empty"); std::cout << empt[0] << std::endl; } catch (const std::out_of_range& oor) { std::cerr << "Out of Range error: " << oor.what() << std::endl; } /******************************************/ Array<char*> a(10); std::cout << "a <char*> size: " << a.size() << std::endl; try { for (int i = 0; i < 10; i++) a[i] = const_cast<char*>("char"); for (int i = 0; i < 10; i++) std::cout << a[i] << std::endl; } catch (const std::out_of_range& oor) { std::cerr << "Out of Range error: " << oor.what() << std::endl; } /******************************************/ Array<std::string> s(10); std::cout << "s <std::string> size: " << s.size() << std::endl; try { for (int i = 0; i < 10; i++) s[i] = "string"; for (int i = 0; i < 10; i++) std::cout << s[i] << std::endl; } catch (const std::out_of_range& oor) { std::cerr << "Out of Range error: " << oor.what() << std::endl; } /******************************************/ Array<char*> b; b = a; std::cout << "b <char*> (copy of a) size: " << b.size() << std::endl; try { for (int i = 0; i < 10; i++) std::cout << b[i] << std::endl; } catch (const std::out_of_range& oor) { std::cerr << "Out of Range error: " << oor.what() << std::endl; } /******************************************/ Array<int> ints(10); std::cout << "ints <int> size: " << ints.size() << std::endl; try { for (int i = 0; i < 10; i++) ints[i] = i; for (int i = 0; i < 10; i++) std::cout << ints[i] << std::endl; } catch (const std::out_of_range& oor) { std::cerr << "Out of Range error: " << oor.what() << std::endl; } return (0); }
true
02e5786efed72c91e278f31bb1d0c0206cb76f9f
C++
MarkOates/dungeon
/src/dungeon/models/naughty_list.cpp
UTF-8
4,933
2.84375
3
[]
no_license
#include <dungeon/models/naughty_list.hpp> //#include <framework/useful.hpp> NaughtyList::Kid::Kid(std::string name, int sprite_index, int scene_id, behavior_t behavior) : name(name) , scene_id(scene_id) , sprite_index(sprite_index) , behavior(behavior) , killed(false) {} behavior_t NaughtyList::Kid::get_behavior() { return behavior; } std::string NaughtyList::Kid::get_name() { return name; } int NaughtyList::Kid::get_sprite_index() { return sprite_index; } bool NaughtyList::Kid::is_naughty() { return behavior == BEHAVIOR_NAUGHTY; } bool NaughtyList::Kid::is_nice() { return behavior == BEHAVIOR_NICE; } bool NaughtyList::Kid::is_adult() { return behavior == BEHAVIOR_ADULT; } bool NaughtyList::Kid::is_alive() { return !killed; } NaughtyList::Kid NaughtyList::_build_kid(int scene_id) { static int behavior_distribution = -1; behavior_distribution += 1; behavior_distribution = behavior_distribution % 5; static bool boy_girl = true; boy_girl = !boy_girl; std::string name = ""; int sprite_index = -1; behavior_t behavior = BEHAVIOR_NAUGHTY; std::vector<behavior_t> non_adult_behaviors = { BEHAVIOR_NAUGHTY, BEHAVIOR_NICE }; switch(behavior_distribution) { case 0: case 2: behavior = BEHAVIOR_NAUGHTY; break; case 1: case 3: behavior = BEHAVIOR_NICE; break; case 4: sprite_index = _get_random_sprite_for_adult(); name = (boy_girl) ? kid_name_generator.get_boy_name() : kid_name_generator.get_girl_name(); behavior = BEHAVIOR_ADULT; break; } if (behavior != BEHAVIOR_ADULT) { if (boy_girl) { name = kid_name_generator.get_boy_name(); sprite_index = _get_random_sprite_for_boy(); } else { name = kid_name_generator.get_girl_name(); sprite_index = _get_random_sprite_for_girl(); } } return Kid(name, sprite_index, scene_id, behavior); } int NaughtyList::_get_random_sprite_for_boy() { std::vector<int> boy_sprites = {2, 4, 8, 9, 15, 16}; return random.get_random_element<int>(boy_sprites); } int NaughtyList::_get_random_sprite_for_girl() { std::vector<int> girl_sprites = {3, 5, 6, 11, 14, 17}; return random.get_random_element<int>(girl_sprites); } int NaughtyList::_get_random_sprite_for_adult() { std::vector<int> girl_sprites = {0, 1, 7, 10, 12, 13}; return random.get_random_element<int>(girl_sprites); } NaughtyList::NaughtyList() : kids() , kid_name_generator() { std::vector<std::pair<int, int>> scene_kids = { // {scene_id, num_of_kids} {1, 20}, {2, 3}, {3, 6}, {5, 1}, {6, 1}, {7, 25} }; // generate the kids for each scene for (unsigned i=0; i<scene_kids.size(); i++) { int scene_id = scene_kids[i].first; int num_kids = scene_kids[i].second; for (unsigned i=0; i<num_kids; i++) kids.push_back(_build_kid(scene_id)); } } std::vector<NaughtyList::Kid> NaughtyList::get_alive_kids_for_scene(int scene) { std::vector<Kid> results; for (auto &kid : kids) if (kid.is_alive() && kid.scene_id == scene) results.push_back(kid); return results; } int NaughtyList::get_num_alive_naughty_kids() { int count = 0; for (auto &kid : kids) if (kid.is_alive() && kid.behavior == BEHAVIOR_NAUGHTY) count++; return count; } int NaughtyList::get_num_alive_nice_kids() { int count = 0; for (auto &kid : kids) if (kid.is_alive() && kid.behavior == BEHAVIOR_NICE) count++; return count; } int NaughtyList::get_num_alive_adults() { int count = 0; for (auto &kid : kids) if (kid.is_alive() && kid.behavior == BEHAVIOR_ADULT) count++; return count; } int NaughtyList::get_num_total_naughty_kids() { int count = 0; for (auto &kid : kids) if (kid.behavior == BEHAVIOR_NAUGHTY) count++; return count; } int NaughtyList::get_num_total_nice_kids() { int count = 0; for (auto &kid : kids) if (kid.behavior == BEHAVIOR_NICE) count++; return count; } int NaughtyList::get_num_total_adults() { int count = 0; for (auto &kid : kids) if (kid.behavior == BEHAVIOR_ADULT) count++; return count; } bool NaughtyList::are_all_naughty_kids_killed() { if (get_num_alive_naughty_kids() == 0) return true; return false; } bool NaughtyList::are_any_nice_kids_killed() { if (get_num_alive_nice_kids() < get_num_total_nice_kids()) return true; return false; } bool NaughtyList::kill_kid_by_name(std::string name) { Kid *found_kid = nullptr; // find the kid for (auto &kid : kids) if (kid.name == name) { found_kid = &kid; break; } if (found_kid && found_kid->is_alive()) { found_kid->killed = true; return true; } return false; }
true
60774fcdee4048901d407a9fecd022fbef67a5c4
C++
github/codeql
/cpp/ql/src/jsf/4.10 Classes/AV Rule 95.cpp
UTF-8
400
3
3
[ "MIT" ]
permissive
enum Shape_color { red, green, blue }; class Shape { public: virtual void draw (Shape_color color = green) const; ... } class Circle : public Shape { public: virtual void draw (Shape_color color = red) const; ... } void fun() { Shape* sp; sp = new Circle; sp->draw (); // Invokes Circle::draw(green) even though the default } // parameter for Circle is red.
true
41c6f8aa9b0af5fb09a683bdb95eb88484717619
C++
viataazang/EchoLib
/eventfd/main.cpp
UTF-8
987
3.203125
3
[]
no_license
#include "EventfdThread.h" #include <iostream> #include <unistd.h> using namespace std; using namespace wd; /* ### eventfd函数 #include <sys/eventfd.h> int eventfd(unsigned int initval, int flags); * initval 初始的引用计数,为64位无符号整数 * flags 标志位,一般设置为0 eventfd的作用主要在于进程,线程间通信;通过向eventfd write信号,eventfd接收信号并作出相应的回应 ### eventfd 的封装 用多线程结合poll对eventfd进行监听,如果eventfd接收到信号那么就执行回调函数 */ struct Mytask { void process() { ::srand(::time(NULL)); int number = ::rand() % 100; cout << ">> thread " << pthread_self() << ": get a number = " << number << endl; } }; int main() { EventfdThread th(std::bind(&Mytask::process, Mytask())); th.start(); for (int i = 0; i < 3; i++) { th.wakeup(); sleep(1); } th.stop(); return 0; }
true
bbd0ab8ef57bb03752a727f4e38865813a63abb0
C++
vector-of-bool/let
/tests/parser.cpp
UTF-8
1,600
2.890625
3
[]
no_license
#include <let/parser.hpp> #include <let/parser/token.hpp> #include <catch/catch.hpp> TEST_CASE("Tokenize some strings", "[parser][tokenizer]") { auto str = "foo bar"; auto toks = let::ast::tokenize(str); CHECK(toks.size() == 2); str = "foo bar "; toks = let::ast::tokenize(str); REQUIRE(toks.size() == 2); { auto first = toks[0]; CHECK(first.string() == "foo"); CHECK(first.range().start == (let::ast::source_location{ 1, 1 })); CHECK(first.range().end == (let::ast::source_location{ 1, 4 })); auto second = toks[1]; CHECK(second.string() == "bar"); CHECK(second.range().start == (let::ast::source_location{ 1, 5 })); CHECK(second.range().end == (let::ast::source_location{ 1, 8 })); } str = "Cat 2 dog"; toks = let::ast::tokenize(str); REQUIRE(toks.size() == 3); { auto cat = toks[0]; auto two = toks[1]; auto dog = toks[2]; CHECK(cat.string() == "Cat"); CHECK(cat.range().start == (let::ast::source_location{ 1, 1 })); CHECK(cat.range().end == (let::ast::source_location{ 1, 4 })); CHECK(two.string() == "2"); CHECK(two.range().start == (let::ast::source_location{ 1, 5 })); CHECK(two.range().end == (let::ast::source_location{ 1, 6 })); CHECK(dog.string() == "dog"); CHECK(dog.range().start == (let::ast::source_location{ 1, 7 })); CHECK(dog.range().end == (let::ast::source_location{ 1, 10 })); } } TEST_CASE("Parse a simple literal", "[parser]") { let::parse_string("12"); }
true
1e5250a03b950112365a6560f9689fc316982fbf
C++
zevenrodriguez/mtec
/codeExamples/arduino/2280Spring16/buttonpress/buttonpress.ino
UTF-8
372
2.796875
3
[]
no_license
#define toggleSwitch 2 int toggleState = 0; boolean pressing = false; void setup() { Serial.begin(9600); pinMode(toggleSwitch, INPUT); } void loop() { toggleState = digitalRead(toggleSwitch); if (toggleState == HIGH) { pressing = true; } if (toggleState == LOW && pressing == true) { pressing = false; // Your action goes here } }
true
151cfdfd421b8d8655b3ad8a46486f7357012319
C++
vale2005/inviwo
/modules/labtopo/integrator.cpp
UTF-8
2,586
2.640625
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
/********************************************************************* * Author : Himangshu Saikia * Init : Wednesday, September 20, 2017 - 12:04:15 * * Project : KTH Inviwo Modules * * License : Follows the Inviwo BSD license model ********************************************************************* */ #include <labtopo/integrator.h> #include <labtopo/interpolator.h> namespace inviwo { Integrator::Integrator() {} vec2 Integrator::rk4(const Volume* vol, const vec2& position, float stepSize) { vec2 v1 = Interpolator::sampleFromField(vol, position); vec2 v1step = vec2(position.x+(stepSize/2.0)*v1.x, position.y+(stepSize/2.0)*v1.y); vec2 v2 = Interpolator::sampleFromField(vol, v1step); vec2 v2step = vec2(position.x+(stepSize/2.0)*v2.x, position.y+(stepSize/2.0)*v2.y); vec2 v3 = Interpolator::sampleFromField(vol, v2step); vec2 v3step = vec2(position.x+stepSize*v3.x, position.y+stepSize*v3.y); vec2 v4 = Interpolator::sampleFromField(vol, v3step); float xCoord = position.x + stepSize * (v1.x/6.0 + v2.x/3.0 + v3.x/3.0 + v4.x/6.0); float yCoord = position.y + stepSize * (v1.y/6.0 + v2.y/3.0 + v3.y/3.0 + v4.y/6.0); return vec2(xCoord, yCoord); } // TODO: Implementation of the functions defined in the header file integrator.h std::vector<vec2> Integrator::getWholeStreamlinePoints(const Volume* vol, vec2 startPoint, float stepSize){ //initialize vector for points along the stream line std::vector<vec2> streamlinePoints; //initialize startpoints vec2 currPointForward = startPoint; vec2 currPointBackward = startPoint; int MAX_POINT_COUNT = 500; vec2 nextPointBackward = rk4(vol, currPointBackward, stepSize*(-1.0)); int pointCount = 0; while(pointCount < MAX_POINT_COUNT && !(currPointBackward == nextPointBackward)){ streamlinePoints.push_back(nextPointBackward); currPointBackward = nextPointBackward; nextPointBackward = rk4(vol, currPointBackward, stepSize*(-1.0)); pointCount++; } std::reverse(streamlinePoints.begin(), streamlinePoints.end()); streamlinePoints.push_back(startPoint); vec2 nextPointForward = rk4(vol, currPointForward, stepSize); pointCount = 0; while(pointCount < MAX_POINT_COUNT && !(currPointForward == nextPointForward)){ streamlinePoints.push_back(nextPointForward); currPointForward = nextPointForward; nextPointForward = rk4(vol, currPointForward, stepSize); pointCount++; } return streamlinePoints; } } // namespace inviwo
true
729548d34955fa340ed960da76aaa4c230822ecb
C++
NicholasTanYuZhe/Tourist-Information-System
/Flight.cpp
UTF-8
2,415
3.421875
3
[]
no_license
/************************************* Program: Flight.cpp Course: OOPDS Year: 2015/16 Trimester 2 Name: NICHOLAS TAN YU ZHE ID: 1142701655 Lecture: TC102 Lab: TT04 Email: nicholas.290696@gmail.com Phone: 016-7768182 *************************************/ #include "Flight.h" Flight::Flight(int V) { this->V = V; adj = new LinkedStack<int>[V]; } void Flight::addEdge(int v, int w) { adj[v].push(w); // Add w to v’s list. } bool Flight::isReachable(int s, int d) { while (!flightStack.isEmpty()) //To make sure the flightStack is empty before proceeding flightStack.pop(); bool *visited = new bool[V]; // Mark all the vertices as not visited for (int i = 0; i < V; i++) visited[i] = false; LinkedStack<int> stack; //Create stack for DFS visited[s] = true; // Mark the current node as visited and push it stack.push(s); while (!stack.isEmpty()) { bool result = false; //To make sure if the adjacent city of the current city is all visited, pop out from the stack s = stack.peek(); flightStack.push(s); stack.pop(); while (!adj[s].isEmpty()) // Get all adjacent vertices of the poped vertex s { if (adj[s].peek() == d) // If this adjacent node is the destination node, then return true { stack.push(adj[s].peek()); flightStack.push(adj[s].peek()); return true; } if (!visited[adj[s].peek()]) // If a adjacent has not been visited, then mark it visited and push into stack { result = true; visited[adj[s].peek()] = true; stack.push(adj[s].peek()); adj[s].pop(); } else //If the city visited, then just pop and do not insert into the stack { adj[s].pop(); } } if(!result) //If the adjacent city is all visited and backtrack, pop the stack flightStack.pop(); } return false; //return false if DFS fail to reach destination city } int Flight::getStack() { return flightStack.peek(); } void Flight::removeStack() { flightStack.pop(); } bool Flight::isEmptyStack() { return flightStack.isEmpty(); }
true
b7523caf73a7150769c4f60d534318633eee570d
C++
rexdex/recompiler
/dev/external/wxWidgets-3.1.0/include/wx/msw/caret.h
UTF-8
1,432
2.546875
3
[ "MIT" ]
permissive
/////////////////////////////////////////////////////////////////////////////// // Name: wx/msw/caret.h // Purpose: wxCaret class - the MSW implementation of wxCaret // Author: Vadim Zeitlin // Modified by: // Created: 23.05.99 // Copyright: (c) wxWidgets team // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef _WX_CARET_H_ #define _WX_CARET_H_ class WXDLLIMPEXP_CORE wxCaret : public wxCaretBase { public: wxCaret() { Init(); } // create the caret of given (in pixels) width and height and associate // with the given window wxCaret(wxWindow *window, int width, int height) { Init(); (void)Create(window, width, height); } // same as above wxCaret(wxWindowBase *window, const wxSize& size) { Init(); (void)Create(window, size); } // process wxWindow notifications virtual void OnSetFocus(); virtual void OnKillFocus(); protected: void Init() { wxCaretBase::Init(); m_hasCaret = false; } // override base class virtuals virtual void DoMove(); virtual void DoShow(); virtual void DoHide(); virtual void DoSize(); // helper function which creates the system caret bool MSWCreateCaret(); private: bool m_hasCaret; wxDECLARE_NO_COPY_CLASS(wxCaret); }; #endif // _WX_CARET_H_
true
5932b5df8612877002d2710f2cf1b248ba9466f8
C++
mukundkedia/DSA
/Binary_Search_Tree/LCAinBST.cpp
UTF-8
818
3.671875
4
[]
no_license
//https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-bst/ #include <bits/stdc++.h> #include <iostream> using namespace std; struct Node { int data; struct Node *left, *right; }; Node * newNode(int k) { Node *temp = new Node; temp->data = k; temp->left = temp->right = NULL; return temp; } Node* LCA(Node *root, int n1, int n2) { if(!root){ return NULL; } if(root->data==n1 || root->data==n2){ return root; } else if(n1<root->data and n2>root->data){ return root; } else if(n1>root->data and n2<root->data){ return root; } else if(n1>root->data and n2>root->data){ return LCA(root->right,n1,n2); } else if(n1<root->data and n2<root->data){ return LCA(root->left,n1,n2); } }
true
9772f06dcaebf901fc1d6fe814a80b0af69eefa5
C++
MSurfer20/test2
/cpp-tizen/src/Attachments.h
UTF-8
3,332
2.9375
3
[]
no_license
/* * Attachments.h * * Dictionary containing details of a file uploaded by a user. */ #ifndef _Attachments_H_ #define _Attachments_H_ #include <string> #include "Attachments_messages.h" #include <list> #include "Object.h" /** \defgroup Models Data Structures for API * Classes containing all the Data Structures needed for calling/returned by API endpoints * */ namespace Tizen { namespace ArtikCloud { /*! \brief Dictionary containing details of a file uploaded by a user. * * \ingroup Models * */ class Attachments : public Object { public: /*! \brief Constructor. */ Attachments(); Attachments(char* str); /*! \brief Destructor. */ virtual ~Attachments(); /*! \brief Retrieve a string JSON representation of this class. */ char* toJson(); /*! \brief Fills in members of this class from JSON string representing it. */ void fromJson(char* jsonStr); /*! \brief Get The unique ID for the attachment. */ int getId(); /*! \brief Set The unique ID for the attachment. */ void setId(int id); /*! \brief Get Name of the uploaded file. */ std::string getName(); /*! \brief Set Name of the uploaded file. */ void setName(std::string name); /*! \brief Get A representation of the path of the file within the repository of user-uploaded files. If the `path_id` of a file is `{realm_id}/ab/cdef/temp_file.py`, its URL will be: `{server_url}/user_uploads/{realm_id}/ab/cdef/temp_file.py`. */ std::string getPathId(); /*! \brief Set A representation of the path of the file within the repository of user-uploaded files. If the `path_id` of a file is `{realm_id}/ab/cdef/temp_file.py`, its URL will be: `{server_url}/user_uploads/{realm_id}/ab/cdef/temp_file.py`. */ void setPathId(std::string path_id); /*! \brief Get Size of the file in bytes. */ int getSize(); /*! \brief Set Size of the file in bytes. */ void setSize(int size); /*! \brief Get Time when the attachment was uploaded as a UNIX timestamp multiplied by 1000 (matching the format of getTime() in JavaScript). **Changes**: Changed in Zulip 2.2 (feature level 22). This field was previously a floating point number. */ int getCreateTime(); /*! \brief Set Time when the attachment was uploaded as a UNIX timestamp multiplied by 1000 (matching the format of getTime() in JavaScript). **Changes**: Changed in Zulip 2.2 (feature level 22). This field was previously a floating point number. */ void setCreateTime(int create_time); /*! \brief Get Contains basic details on any Zulip messages that have been sent referencing this [uploaded file](/api/upload-file). This includes messages sent by any user in the Zulip organization who sent a message containing a link to the uploaded file. */ std::list<Attachments_messages> getMessages(); /*! \brief Set Contains basic details on any Zulip messages that have been sent referencing this [uploaded file](/api/upload-file). This includes messages sent by any user in the Zulip organization who sent a message containing a link to the uploaded file. */ void setMessages(std::list <Attachments_messages> messages); private: int id; std::string name; std::string path_id; int size; int create_time; std::list <Attachments_messages>messages; void __init(); void __cleanup(); }; } } #endif /* _Attachments_H_ */
true
a394e90a6daf4b6fbae554daacbfb4cdaadd3e8a
C++
Bietola/old
/SWars/Cannon.cpp
UTF-8
1,539
2.78125
3
[]
no_license
#include "Cannon.h" ///cannon functions //constructors Cannon::Cannon():Thing(),Builder(){ start(NULL,SHOOT_DUMMY); } Cannon::Cannon(Texture *t,COLLFACTION cf,SHOOT st,int hp,int cdam,double cs,Ship *proj):Thing(0,0,t,COLL_SHIP,cf,hp,cdam),Builder(proj,cs){ start(proj,st); } Cannon::Cannon(int x,int y,Texture *t,COLLFACTION cf,SHOOT st,int hp,int cdam,double cs,Ship *proj):Thing(x,y,t,COLL_SHIP,cf,hp,cdam),Builder(proj,cs){ start(proj,st); } //destructors Cannon::~Cannon(){ //!delete projectile; cout<<"destroying Cannon"<<endl; } //copy constructor Cannon::Cannon(Cannon &cannon){ *this=cannon; projectile=dynamic_cast<Ship*>(cannon.projectile->retClone()); model=projectile; } //thing virtual inheritance dedicated constructors Cannon::Cannon(Ship *proj,double cspeed,SHOOT st):Builder(proj,cspeed){ start(proj,st); } Cannon::Cannon(Ship *proj,int msx,int msy,double cspeed,SHOOT st):Builder(proj,msx,msy,cspeed){ start(proj,st); } //builder virtual inheritance dedicated constructors Cannon::Cannon(Ship *proj,SHOOT st){ start(proj,st); } //initialization void Cannon::start(Ship *proj,SHOOT st){ projectile=proj; shootType=st; } void Cannon::think(){ if(shootType==SHOOT_NOTHINK){ if(!isBuilding()) startBuilding(); } } void Cannon::act(){ if(buildTimer.getCycles()>=1000.0/chargeSpeed && canBuild){ //!NB Cannons don't check for collisions when building (unlike builders) build(); } }
true
af068f2bf6620030e9b24660c10b88addaa6ff57
C++
Svaught598/cppNES
/include/log.h
UTF-8
2,505
3.53125
4
[]
no_license
#ifndef NES_LOG #define NES_LOG #include <fstream> #include <iomanip> #include <iostream> class Logger { public: // Log types enum class logType { LOG_ERROR, LOG_WARNING, LOG_OPCODE, LOG_INFO, LOG_ENDLINE }; // Constructor explicit Logger (const char *fname = "nes_log.txt") { numWarnings = 0; numErrors = 0; myFile.open(fname); if (myFile.is_open()) { myFile << "NES emulator - Steven Vaught" << std::endl; myFile << "Log file created" << std::endl << std::endl; } } // Destructor ~Logger(){ if (myFile.is_open()) { myFile << std::endl << std::endl; // Report number of errors and warnings myFile << numWarnings << " warnings" << std::endl; myFile << numErrors << " errors" << std::endl; myFile.close(); } } // Overload << operator using log type friend Logger &operator << (Logger &logger, const logType l_type){ switch (l_type) { case Logger::logType::LOG_ERROR: logger.myFile << "[ERROR]: "; ++logger.numErrors; break; case Logger::logType::LOG_WARNING: logger.myFile << "[WARNING]: "; ++logger.numWarnings; break; case Logger::logType::LOG_OPCODE: logger.myFile << "[OPCODE]: "; break; case Logger::logType::LOG_INFO: logger.myFile << "[INFO]: "; break; case Logger::logType::LOG_ENDLINE: logger.myFile << std::endl; break; default: break; } return logger; } // Overload << operator using char* strings friend Logger &operator << (Logger &logger, const char *text) { logger.myFile << text; return logger; } friend Logger &operator << (Logger &logger, const std::string &text){ logger.myFile << text; return logger; } friend Logger &operator << (Logger &logger, const int &val){ if (val < 0x100){ logger.myFile << std::hex << std::setfill('0') << std::setw(2) << val; } else { logger.myFile << std::hex << std::setfill('0') << std::setw(4) << val; } return logger; } private: std::ofstream myFile; unsigned int numWarnings; unsigned int numErrors; }; #endif
true
94c33eeed0934d5abfd0858cbcc10eda85d65cde
C++
monder0116/CSE241
/backuparr- merge sort/templateArray.cpp
UTF-8
2,216
3.328125
3
[]
no_license
#include "templateArray.h" #ifndef TDA #define TDA template <class T> TempArray<T>::TempArray(const TempArray<T>& other):size(0),capasity(other.capasity){ arr=new T[capasity]; for(int i=0;i<other.size;i++) { arr[i]=other.arr[i]; ++size; } } template <class T> TempArray<T>::TempArray(const vector<T>& other):TempArray<T>(){ for (int i = 0; i < other.size(); ++i) { add(other[i]); } } template<class T> TempArray<T>& TempArray<T>::operator =(const TempArray<T>& other){ if(this==&other) return *this; if(other.capasity!=capasity) { capasity=other.capasity; delete [] arr; arr=new T[capasity]; } for(int i=0;i<other.size;i++) { arr[i]=other.arr[i]; } size=other.size; } template <class T> T& TempArray<T>::operator [](int index) { if(index<getSize() && index>=0){ return arr[index]; } throw Exception("Hatali index"); } template<class T> const T TempArray<T>::operator[](int index) const { if(index<getSize()&& index>=0){ return arr[index]; } throw Exception("Hatali index"); } template<class T> TempArray<T>& TempArray<T>::operator+=(const T& other){ add(other); return *this; } template<class T> void TempArray<T>::add(const T& other){ if(full()) recapasity(2); arr[size++]=other; } template<class T> void TempArray<T>::recapasity(int mult){ if(mult>0){ T *temp=arr; capasity*=mult; arr=new T[capasity]; for (int i = 0; i < getSize(); ++i) { arr[i]=temp[i]; } delete [] temp; } } template<class T> const TempArray<T> TempArray<T>::operator --(int ignore){ TempArray<T> temp(*this); --size; recapasity(1); return temp; } template<class T> const TempArray<T> TempArray<T>::operator +(const TempArray<T>& other)const{ TempArray<T> temp(other); for (int i = 0; i < getSize(); ++i) { temp.add(arr[i]); } return temp; } template<class T> const TempArray<T> TempArray<T>::operator()(int first,int last)const throw(Exception){ TempArray<T> temp; if(first>=0 && first<=last && last>=0 && last<=getSize()) { for (int i = first; i < last; ++i) { temp.add(arr[i]); } }else throw Exception("Geçersiz index aralığı"); return temp; } template<class T> TempArray<T>::~TempArray() { delete [] arr; } #endif
true
dd67a1ca786b58f74cc468b587eb0e279bf6079f
C++
GuillaumeElias/Little2DGame
/src/Objects/ElevatorObject.cpp
UTF-8
1,021
2.9375
3
[]
no_license
#include "Objects/ElevatorObject.h" ElevatorObject::ElevatorObject(SDL_Renderer* renderer, SDL_Window* window, int pX, int pY, LTextureFactory* lTextFact, int alt) : GameObject(renderer, window, pX, pY, lTextFact), initPosY(pY) { if(alt < 0){ //if disabled disabled = true; alt = abs(alt); } if(alt > 1){ //if altitude specified (enter any value bigger than 1) altitude=alt; } up = true; } ElevatorObject::~ElevatorObject() { //dtor } std::string ElevatorObject::getTextureName(){ return "elevator.png"; } int ElevatorObject::move(PlayerPosition* playerPos){ if(disabled) return 0; if(up){ posY-=1; if(posY < initPosY - altitude){ up = false; } if(playerPos->y > 0 && isPlayerAbove(playerPos)){ playerPos->y--; } }else{ posY+=1; if(posY >= initPosY || isPlayerBelow(playerPos)){ up = true; } } return 0; } void ElevatorObject::onCollision(){ }
true
883536f4290c519ecedca2964a586b39d57ded33
C++
pigranya1218/WinAPI-worms
/effectObject.h
UTF-8
833
2.71875
3
[]
no_license
#pragma once #include "object.h" class effectObject : public object { protected: image* _img; animation* _ani; bool _effectedGravity; bool _effectedPixel; void move(); bool movePixel(); public: void init(image* img, int fps, float x, float y, float width, float height, float angle, float power, bool effectedGravity, bool effectedPixel) { _img = img; _ani = new animation; _ani->init(img->getWidth(), img->getHeight(), img->getFrameWidth(), img->getFrameHeight()); _ani->setDefPlayFrame(false, false); _ani->setFPS(fps); _ani->start(); _x = x; _y = y; _width = width; _height = height; _angle = angle; _power = power; _effectedGravity = effectedGravity; _effectedPixel = effectedPixel; } virtual void release(); virtual void update(); virtual void render(); void moveEffect(); };
true
11e43fc655d0561adc126819dcc9e153aafc3105
C++
SteveBeaupre/Vortez3DEngine
/3ds Plugins/Model3DExport/Huffman Coder.h
UTF-8
4,294
2.515625
3
[]
no_license
#ifndef C_HUFFMAN_CODER_DLL_H #define C_HUFFMAN_CODER_DLL_H #ifdef __cplusplus #include <Windows.h> #include <Stdio.h> #include "SafeKill.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define ROOT_NODE 0 #define NORMAL_NODE 1 #define LEAF_NODE 2 // Our Stats struct struct StatsStruct { BYTE Char; UINT Frequency; struct StatsStruct *ChildNode; struct StatsStruct *ParentNode; }; class CStats { public: CStats(); ~CStats(); private: StatsStruct RootNode; void InitNode(StatsStruct *pNode, StatsStruct *pParentNode, BYTE ch); StatsStruct* GetLastNode(); StatsStruct* AddChildNode(StatsStruct *pNode, BYTE ch); bool RemoveChildNode(StatsStruct *pNode); void ExchangeNodes(StatsStruct *pNode1, StatsStruct *pNode2); void RemoveEmptyStats(); public: void Initialize(); void IncFrequency(BYTE Indx, DWORD Value = 1); void KillNodes(); UINT GetNodeCount(); void GetValue(BYTE Indx, BYTE *pChar, UINT *pFrequency); UINT SortStats(); void WriteStats(char *fname); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct BinCodeStruct { UINT Frequency; WORD BinCode; BYTE BitsCount; }; ////////////////////////// struct TreeStruct { UINT Frequency; BYTE Char; BYTE NodeType; WORD BinaryCode; struct TreeStruct *LeftChild; struct TreeStruct *RightChild; struct TreeStruct *Parent; }; struct TreeBaseNodeListStruct { TreeStruct NodeDat; struct TreeBaseNodeListStruct *Parent; struct TreeBaseNodeListStruct *Child; }; ///////////////////////////////////////////// struct PriorityQueueStruct { UINT Priority; BYTE Char; struct TreeStruct *pTreeNode; struct PriorityQueueStruct *ParentNode; struct PriorityQueueStruct *ChildNode; }; class CPriorityQueue { public: CPriorityQueue(); ~CPriorityQueue(); private: TreeBaseNodeListStruct TreeLeafsNode; PriorityQueueStruct RootNode; PriorityQueueStruct* GetLastNode(); void KillTreeNode(TreeStruct *pNode); void CombineTwoLowestFreqNodes(); bool RemoveFirstNode(); PriorityQueueStruct* InsertNode(UINT Priority, BYTE ch); public: UINT GetNodeCount(); void AddLastNode(UINT Priority, BYTE ch); void ClearNodes(); void BuildTree(); void KillTree(); TreeStruct* GetTreeRootNode(); DWORD GenBinCodes(BinCodeStruct *pBinCodes); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class CBitStream { public: CBitStream(); ~CBitStream(); private: BYTE *pBuffer; bool IsAllocated; bool AllocateExtraDWORD; DWORD BufSize; DWORD BufIndx; BYTE BitIndx; bool TestBit (WORD bitField, char bitNum){return (bitField & (1<<bitNum)) > 0;} void SetBit (BYTE* bitField, char bitNum){*bitField |= (1 << bitNum);} void ClearBit(BYTE* bitField, char bitNum){*bitField &= ~(1 << bitNum);} void UpdateCounters(BYTE BitsProcessed); public: void Allocate(DWORD Size); void Fill(BYTE* pBuf); void Erase(); void Free(); void Save(FILE *OutF); void EncodeNextChar(WORD wBinCode, BYTE bBitsCount); BYTE DecodeNextChar(TreeStruct *pRootNode); }; TreeStruct* GetBaseTreeNode(BYTE Indx); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class CHuffmanCoder { private: CStats Stats; CPriorityQueue PriorityQueue; public: #ifndef WIN64 DWORD EncodeToFile(BYTE* pBuffer, const DWORD BufferSize, FILE* OutF); DWORD DecodeFromFile(BYTE* pBuffer, const DWORD ExpectedBufferSize, FILE* InF); #else size_t EncodeToFile(BYTE* pBuffer, const size_t BufferSize, FILE* OutF); size_t DecodeFromFile(BYTE* pBuffer, const size_t ExpectedBufferSize, FILE* InF); #endif }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef WIN64 DWORD Encode(BYTE* pBuffer, const DWORD BufferSize, FILE* OutF); DWORD Decode(BYTE* pBuffer, const DWORD ExpectedBufferSize, FILE* InF); #else size_t Encode(BYTE* pBuffer, const size_t BufferSize, FILE* OutF); size_t Decode(BYTE* pBuffer, const size_t ExpectedBufferSize, FILE* InF); #endif #endif #endif //C_HUFFMAN_CODER_DLL_H
true
17b26889c89d5c031f84449418a1220a575a6b5b
C++
zzzlight/pat
/1087.cpp
GB18030
2,509
2.71875
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> #include<map> #include<string> using namespace std; const int inf=10000000; struct Node { int happiness; string name; int level; }node[400]; map<int,string> stringtoint; map<string,int> inttostring; int G[205][205]; int d[205]; bool vis[205]; int numofpath; int maxcost; int finalhappiness; double avehappiness; int potnum; int roadnum; vector<int> out,tempout; vector<int> pre[205]; void dfs(int final) //predfs->ѵ { if(final==0) { tempout.push_back(final); numofpath++; int costtemp=0; for(int i=tempout.size()-1;i>=0;i--) //-2Ҳ 0happinessʼΪ0 Ӱ { costtemp+=node[tempout[i]].happiness; } double tempavehappiness=costtemp*1.0/(tempout.size()-1); if(costtemp>maxcost) { maxcost=costtemp; avehappiness=tempavehappiness; out=tempout; } else if(costtemp==maxcost&&tempavehappiness>avehappiness) { avehappiness=tempavehappiness; out=tempout; } tempout.pop_back(); return ; } tempout.push_back(final); for(int i=0;i<pre[final].size();i++) { dfs(pre[final][i]); } tempout.pop_back(); return ; } void dijkstra(int start) { fill(d,d+205,inf); d[start]=0; for(int i=0;i<potnum;i++) { int u=-1; int min=inf; for(int j=0;j<potnum;j++) { if(vis[j]==false&&d[j]<min) { u=j;min=d[j]; } } if(u==-1) return; vis[u]=true; for(int v=0;v<potnum;v++) { if(vis[v]==false&&G[u][v]!=inf) { if(d[u]+G[u][v]<d[v]) { d[v]=d[u]+G[u][v]; pre[v].clear(); pre[v].push_back(u); } else if(d[u]+G[u][v]==d[v]) { pre[v].push_back(u); } } } } } int main() { fill(G[0],G[0]+205*205,inf); string start; cin>>potnum>>roadnum>>start; node[0].name=start; for(int i=1;i<potnum;i++) { cin>>node[i].name>>node[i].happiness; inttostring[node[i].name]=i; stringtoint[i]=node[i].name; } for(int j=0;j<roadnum;j++) { string temp1; string temp2; cin>>temp1>>temp2; int cost; cin>>cost; G[inttostring[temp1]][inttostring[temp2]]=cost; G[inttostring[temp2]][inttostring[temp1]]=cost; } dijkstra(0); int final=inttostring["ROM"]; dfs(final); printf("%d %d %d %d\n",numofpath,d[final],maxcost,int(avehappiness)); //ȡǿת cout<<node[0].name<<"->"; for(int i=out.size()-2;i>=0;i--) //-2-1dfs=0жбpop { cout<<stringtoint[out[i]]; if(i!=0) cout<<"->"; } }
true
912cba8f5c0111523d220b02a994ebe6259b0cea
C++
lc5313/Global-Illumination-Ray-Tracer
/Application.cpp
UTF-8
761
2.578125
3
[]
no_license
// // Created by lauren on 2/3/20. // #include "Application.h" #include "ObjectData.h" #include "Camera.h" //GLOBALS //background color is "cornflower blue" Color bgColor(0, 0.0, 1.0); void Application::letsGo(){ cout <<"hi" <<endl; //create a world and add objects to it World world = World(bgColor); for (int i = 0; i < N; i++){ world.add(objs[i]); } //create a camera Camera camera = Camera(); camera.render(world); cout << camera.viewFrame.size(); vector<unsigned char> data = camera.convertRBGValues(); cout << data.size() << endl; unsigned error = lodepng::encode("img.png", data, static_cast<unsigned int>(camera.wPixels), static_cast<unsigned int>(camera.hPixels)); cout << error << endl; }
true
d5de3caf3663079368d3219241322b10a83b8364
C++
TurtleShip/ProgrammingContests
/Solutions/LiveArchive/2007/South_America/3651/3651_WeekendLottery.cpp
UTF-8
963
2.5625
3
[]
no_license
#include <cstdio> #include <algorithm> using namespace std; const int maxN = 10010; const int maxC = 15; const int maxK = 110; int arr[maxK]; int main() { int N, C, K; while(scanf(" %d %d %d", &N, &C, &K) && !(N == 0 && C == 0 && K ==0)) { int minVal = 10000; for(int i=1; i <= K; i++) arr[i] = 0; while(N--) { int cur = 0; for(int i=0; i < C; i++) { scanf(" %d", &cur); arr[cur]++; } } for(int i=1; i <= K; i++) minVal = min(minVal, arr[i]); bool isFirst = true; for(int i=1; i <= K; i++) if(minVal == arr[i]) { if(isFirst) { printf("%d", i); isFirst = false; } else { printf(" %d", i); } } printf("\n"); } return 0; }
true
95853049b4462ca10d1cfc5fb17609461f77a46c
C++
rthanjappan/CPlusPlusCheckersGame
/CheckersAug192021.cpp
UTF-8
18,500
2.84375
3
[]
no_license
// Program : Checkers Game //programmer : Rosemol Thanjappan //Date : 11/24/2018 #include <iostream> #include <string> #include <cstring> #include <ctime> #include <Windows.h> #include "MMSystem.h" #include <vector> #include<fstream> #include <iomanip> using namespace std; class game { public: void mainLine(); private: int row;//current row int col;//current column int destRow;//destination row int destCol;//destination column char playerTurn; bool endFlag;//shows whether game ended string gameResults; long long clockTick; string currentActionTaken; bool newGame;//shows whether new game bool startFlag;//shows whether game started string cells[8][8];//the array that holds the game pieces int iTotalR, iTotalB;//total number of game pieces int dir;//direction to move bool flag;// the flag showing the game is playing int player;//which player is playing the game ifstream rulesFile;//ifstream object holding rules file ofstream logFile;//ofstream object holding log file ifstream inputLogFile;//ifstream object holding log file int toRow;//the row to move int toCol;//the column to move int jRow;//the row to jump int jCol;//the column to jump int rowLimit;//the limit of row boundry int colLimit;//the limit of column boundry string currentPiece;//the current playing piece red or black string currentKPiece;//the current King piece "B" or "R" string directions[4];//the 4 directions vector<int> vDirs;//the vector to hold directions bool bEndFlag;//the flag to read files // Member Modules void init(void); void gameMenu(void); void eoj(void); void displayMenu(void); int menuPic(void); void startGameOver(void); void displayBoard(void); void soundModule(int); char chooseStartPlayer(void); void makeAMove(void); void playerR_move(void); void playerB_move(void); bool checkGameOver(void); void writeStatsDataFile(string); void setBoard(); void writeIt(); void calculateValidDirections(int, int); void setOffset(int); bool isLegal(); void accumulate(); void OpenFile(void); bool showDirMenu(); void readRules(); void writeLogFile(string); bool checkForWinner(); void jumpOver(); void clearCell(int, int); void moveToTheCell(); bool isValidPiece(int, int); int getCoOrdinate(string); bool isLastRank(int); bool isValidBoundary(); bool isEmpty(int, int); bool isJumpable(); bool isOpponentPiece(); int displayDirMenu(); bool isValidDir(int); void displayScore(); bool makeFinalMove(); bool openLogFile(); void readLogFile(); }; int main(void) { game g1; g1.mainLine(); system("pause"); } void game::mainLine(void) { init(); while (endFlag == false) { gameMenu(); } eoj(); } void game::init(void) { clockTick = time(0); //initializing the number of pieces to 12 iTotalR = 12; iTotalB = 12; //setting the 4 directions directions[0] = "1 (Upper-Left Diagonal)"; directions[1] = "2 (Upper-Right Diagonal)"; directions[2] = "3 (Lower-Left Diagonal)"; directions[3] = "4 (Lower-Right Diagonal)"; // Setup other start items. endFlag = false; playerTurn = chooseStartPlayer(); gameResults = "No game results yet."; // Like a priming for the game. startFlag = false; setBoard(); startFlag = true; displayBoard(); soundModule(1); } void game::gameMenu(void) { int aPic = 1; displayMenu(); aPic = menuPic(); switch (aPic) { // Start the game over. case 1: startGameOver(); currentActionTaken = "Start the game over."; cout << currentActionTaken << endl; writeStatsDataFile("Start the game over."); break; case 2: playerR_move(); writeStatsDataFile("Make a move player R."); break; case 3: playerB_move(); writeStatsDataFile("Make a move player B."); break; case 4: displayBoard(); writeStatsDataFile("Display the current board"); break; case 5: checkForWinner(); writeStatsDataFile("Check for winner."); displayScore(); break; case 6: if (!checkForWinner()) { if (!checkGameOver()) { cout << "The game is not over yet." << endl; displayScore(); } } writeStatsDataFile("Check for end of game."); break; case 7://Displaying the rules bEndFlag = false; OpenFile(); while (!bEndFlag) { readRules(); } rulesFile.close(); writeStatsDataFile("Displaying the rules of the game."); system("pause"); break; case 8://Display log file system("cls"); logFile.close(); if (openLogFile()) { bEndFlag = false; while (!bEndFlag) { readLogFile(); } } system("pause"); inputLogFile.close(); break; case 10: endFlag = true; writeStatsDataFile("Ending the game."); break; default: cout << "No option picked." << endl; } } void game::OpenFile(void) { rulesFile.open("CheckersGameRules.txt"); if (rulesFile.fail()) { cout << "Checkers game rules file open failes" << endl; system("pause"); } return; } void game::readRules() { string str; if (!rulesFile.fail()) { getline(rulesFile, str); cout << str << endl; if (rulesFile.eof() == true) bEndFlag = true; else bEndFlag = false; } else { bEndFlag = true; } return; } void game::writeLogFile(string str) { logFile << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2) << setw(4) << (row + 1) << "," << setw(2) << col + 1 << " to " << setw(4) << destRow + 1 << "," << setw(2) << destCol + 1 << " " << str << endl; return; } bool game::openLogFile(void) { inputLogFile.open("stats.txt"); if (inputLogFile.fail()) { cout << "Checkers log file open fails" << endl; system("pause"); return false; } return true; } void game::readLogFile() { string str; if (!inputLogFile.fail()) { getline(inputLogFile, str); cout << str << endl; if (inputLogFile.eof() == true) bEndFlag = true; else bEndFlag = false; } else { bEndFlag = true; } return; } void game::eoj(void) { displayScore(); logFile.close(); cout << endl << "Game Over" << endl << endl; //soundModule(2); } void game::displayScore() { if (startFlag) { cout << "The player 1 (red) has " << iTotalR << " pieces left." << endl; cout << "The player 2 (black)has " << iTotalB << " pieces left." << endl; if (iTotalR == iTotalB) { cout << "Player 1 and player 2 has the same number of pieces left." << endl; cout << "It is not time to tell who is winning." << endl << endl; } else if (iTotalR > iTotalB) { cout << "\nPlayer 1 (red) is winning. " << endl; } else { cout << "\nPlayer 2 (black) is winning. " << endl; } } else { cout << "Game is not started yet." << endl; } system("pause"); } void game::displayMenu(void) { cout << "\nCheckers Game"; cout << "\nMenu Options"; cout << "\n******************************"; cout << "\n1. Start a new game."; cout << "\n2. Pick a move for player 1."; cout << "\n3. Pick a move for player 2."; cout << "\n4. Show the current checkers board."; cout << "\n5. Check for winner."; cout << "\n6. Check for game over status."; cout << "\n7. Display the rules."; cout << "\n8. Display the game log."; cout << "\n10. End the game."; cout << "\nEnter choice (1 - 10) ===> "; } void game::startGameOver(void) { // Setup other start items. endFlag = false; playerTurn = chooseStartPlayer(); gameResults = "No game results yet."; startFlag = false; //initializing the board setBoard(); startFlag = true; //displaying the board displayBoard(); //initializing the variables for start over iTotalR = 12; iTotalB = 12; soundModule(1); } int game::menuPic(void) { int pick; cin >> pick; system("cls"); return pick; } void game::setBoard() { string startBoard[8][8] = { {"#","r","#","r","#","r","#","r"}, {"r","#","r","#","r","#","r","#"}, {"#","r","#","r","#","r","#","r"}, {" ","#"," ","#"," ","#"," ","#"}, {"#"," ","#"," ","#"," ","#"," "}, {"b","#","b","#","b","#","b","#"}, {"#","b","#","b","#","b","#","b"}, {"b","#","b","#","b","#","b","#"} }; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { cells[i][j] = startBoard[i][j]; } } } void game::displayBoard(void) { long long howLong; howLong = time(0) - clockTick; system("cls"); cout << "The computer clock is at this many seconds: " << clockTick << endl; cout << "The game has been running for this many seconds: " << howLong << endl << endl; if (startFlag) { //if game had already started that is old game ,then display the board writeIt(); } else { //else this is a new game ,then reset the board and display setBoard(); writeIt(); } } void game::writeIt() { int bigcount; int counter; cout << " |----|----|----|----|----|----|----|----|" << endl; for (bigcount = 0; bigcount < 8; bigcount++) { cout << bigcount + 1 << " "; for (counter = 0; counter < 8; counter++) { cout << "| " << cells[bigcount][counter] << " "; } cout << "|" << endl << " |----|----|----|----|----|----|----|----|" << endl; } cout << " 1 2 3 4 5 6 7 8 " << endl; return; } //read the co-ordinates and direction and make move void game::makeAMove() { bool bFlag = false; cout << "Player " << player << "'s ( " << currentPiece << " ) turn : " << endl; while (!bFlag) { row = getCoOrdinate("row");//get the row value if (row == -999) { return; }//if -999 return to menu col = getCoOrdinate("column");//get the column value if (col == -999) { return; } bFlag = isValidPiece(row, col); } //checking whether there is any valid moves for the current piece selected //clearing the vector that holds valid directions vDirs.clear(); if (cells[row][col] == "r") { calculateValidDirections(3, 4); } else if (cells[row][col] == "b") { calculateValidDirections(1, 2); } else if (cells[row][col] == "R" || cells[row][col] == "B") { calculateValidDirections(1, 4); } //if the vector comes out empty there is no valid directions, //so another piece has to be selected if (vDirs.size() == 0) { cout << "There is no valid moves." << endl; cout << "Choose another piece." << endl; dir = 0; } else { if (showDirMenu()) { //if the row ,column and direction are valid make final move. makeFinalMove(); } } } char game::chooseStartPlayer(void) { char startPlayer; cout << "The Checkers Game " << endl; cout << "***********************************" << endl; cout << "Who would you like to start the game? :" << endl; cout << "Player \"r\" or Player \"b\" : "; cin >> startPlayer; return startPlayer; } void game::playerR_move(void) { player = 1; currentPiece = 'r'; currentKPiece = 'R'; makeAMove(); player = 2; currentPiece = 'b'; currentKPiece = 'B'; } void game::playerB_move(void) { player = 2; currentPiece = 'b'; currentKPiece = 'B'; makeAMove(); player = 1; currentPiece = 'r'; currentKPiece = 'R'; } void game::calculateValidDirections(int from, int to) { for (int i = from; i <= to; i++) { setOffset(i); if (isLegal()) { vDirs.push_back(i); } } } //calculating the off sets for 4 directions //toRow ,toCol the row and column to move //jRow,jCol the row and column to jump //rowLimit,colLimit the boundary limit of the move void game::setOffset(int dir) { switch (dir) { case 1://"1 (Upper-Left Diagonal) toRow = -1; toCol = -1; jRow = -2; jCol = -2; rowLimit = 0; colLimit = 0; break; case 2: //2 (Upper-Right Diagonal) toRow = -1; toCol = +1; jRow = -2; jCol = +2; rowLimit = 0; colLimit = 7; break; case 3: //3 (Lower-Left Diagonal) toRow = +1; toCol = -1; jRow = +2; jCol = -2; rowLimit = 7; colLimit = 0; break; case 4://4 (Lower-Right Diagonal) toRow = 1; toCol = 1; jRow = +2; jCol = +2; rowLimit = 7; colLimit = 7; break; default: break; } } //checks whether the move is legal bool game::isLegal() { if (isValidBoundary()) { if (isEmpty(row + toRow, col + toCol)) { return true; } if (isJumpable()) { if (isOpponentPiece()) { if (isEmpty(row + jRow, col + jCol)) { return true; } else { return false; } } } } return false; } //checks for valid boundary bool game::isValidBoundary() { return (row == rowLimit || col == colLimit) ? false : true; } //checks whether the cell is empty bool game::isEmpty(int r, int c) { return cells[r][c] == " " ? true : false; } //checks whether the boundary is legal for jumping over bool game::isJumpable() { return row == (rowLimit + 1) || col == (colLimit + 1) ? false : true; } //checks whether it is opponent piece bool game::isOpponentPiece() { return (cells[row + toRow][col + toCol] == currentPiece || cells[row + toRow][col + toCol] == currentKPiece) ? false : true; } //moves to the cell void game::moveToTheCell() { if (isLastRank(toRow)) { cells[row + toRow][col + toCol] = currentKPiece; } else { cells[row + toRow][col + toCol] = cells[row][col]; } destRow = row + toRow; destCol = col + toCol; clearCell(row, col); } //jump over the opponent void game::jumpOver() { if (isLastRank(jRow)) { cells[row + jRow][col + jCol] = currentKPiece; } else { cells[row + jRow][col + jCol] = cells[row][col]; } destRow = row + jRow; destCol = col + jCol; clearCell((row + toRow), (col + toCol)); clearCell(row, col); } //checks whether in the last rank bool game::isLastRank(int offset) { if (player == 1) { if ((row + offset) == 7) { return true; } } else if (player == 2) { if ((row + offset) == 0) { return true; } } return false; } //clears a cell void game::clearCell(int r, int c) { cells[r][c] = " "; } //reads row or column value from the user int game::getCoOrdinate(string str) { int value; bool bFlag = false; while (!bFlag) { cout << "Please enter the " << str << " value of the piece to move (1 to 8)(-999 for the menu) :"; cin >> value; if (value == -999) { flag = false; return -999; } while (value < 1 || value>8) { cout << "Error:Please enter the row value (1 to 8)(-999 for the menu) :"; cin >> value; if (value == -999) { flag = false; return -999; } } value = value - 1; return value; } } //checks for valid piece bool game::isValidPiece(int row, int col) { if (cells[row][col] == " " || cells[row][col] == "#") { cout << "There is no piece in that position." << endl; cout << "Choose another position." << endl; return false; } else if ((cells[row][col] == currentPiece) || (cells[row][col] == currentKPiece)) { return true; } else { cout << "Current player is : " << player << " and current piece is : " << currentPiece << endl; cout << "This is opponent's piece.Play your own piece." << endl; cout << endl; return false; } } //Displays directions menu bool game::showDirMenu() { cout << "Which Direction do you want to move?(-999 for the menu) " << endl; displayDirMenu(); if (dir == -999) { flag = false; return false; } setOffset(dir); } //checks whether valid direction bool game::isValidDir(int dir) { for (int i = 0; i < vDirs.size(); i++) { if (dir == vDirs[i]) { return true; } } return false; } //makes final move bool game::makeFinalMove() { if (isValidBoundary()) { if (isEmpty(row + toRow, col + toCol)) { moveToTheCell(); checkGameOver(); return true; } if (isJumpable()) { if (isOpponentPiece()) { if (isEmpty(row + jRow, col + jCol)) { jumpOver(); accumulate(); if (!checkForWinner()) { checkGameOver(); } return true; } } } } return false; } //calculates the pieces left void game::accumulate() { if (player == 1) { iTotalB -= 1; } else { iTotalR -= 1; } } // bool game::checkForWinner() { if (iTotalR == 0) { //endFlag = true; flag = false; cout << "\nThe winner is player 2 (black).\n" << endl; soundModule(2); return true; } else if (iTotalB == 0) { //endFlag = true; flag = false; cout << "\nThe winner is player 1 (red).\n" << endl; soundModule(2); return true; } else { return false; } } //displays direction menu int game::displayDirMenu() { if (vDirs.size() >= 1) { do { cout << directions[vDirs[0] - 1]; for (int i = 1; i < vDirs.size(); i++) { cout << " , " << directions[vDirs[i] - 1]; } cout << " : "; cin >> dir; if (dir == -999) { flag = false; return -999; } } while (!isValidDir(dir)); } } //checks for whether any valid moves left bool game::checkGameOver(void) { int status1 = 1; int status2 = 1; vDirs.clear(); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (cells[i][j] == "r") { row = i; col = j; calculateValidDirections(3, 4); } if (cells[i][j] == "R") { row = i; col = j; calculateValidDirections(1, 4); } } } if (vDirs.empty()) { status1 = 0; } vDirs.clear(); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (cells[i][j] == "b") { row = i; col = j; calculateValidDirections(1, 2); } if (cells[i][j] == "B") { row = i; col = j; calculateValidDirections(1, 4); } } } if (vDirs.empty()) { //cout << "The player 2 (black) has no legal moves." << endl; status2 = 0; } if (status1 == 0 && status2 == 0) { cout << "\nPlayer 1 and player 2 has no legal moves." << endl; cout << "Game is a tie.\n" << endl; soundModule(2); return true; } else if (status1 == 0) { cout << "\nThe player 1 (red) has no legal moves." << endl; cout << "Player 2 (black ) won the game.\n" << endl; soundModule(2); return true; } else if (status2 == 0) { cout << "\nThe player 2 (black ) has no legal moves." << endl; cout << "Player 1 (red) won the game.\n" << endl; soundModule(2); return true; } else { return false; } } void game::soundModule(int pick) { char song[60]; if (pick == 1) strcpy_s(song, "StartSound_Final.wav"); else strcpy_s(song, "EndGame.wav"); //PlaySound(TEXT(song), NULL, SND_ASYNC); } void game::writeStatsDataFile(string dataItem) { // Use this module to write stat data to stat.txt data file // Open file first (use append to setup for adding records to existing file) // Write data to file // Close data file long long currentTime; currentTime = time(0); logFile.open("stats.txt", ios::app); if (logFile.fail()) { cout << "Checkers log file open failes" << endl; system("pause"); } else { logFile << currentTime << " " << dataItem << endl; } logFile.close(); }
true
e566a114835947cbb0294b61bfba585941095ae7
C++
RishatIbrahimov/cpp-tasks
/06_pow.cpp
UTF-8
273
3.390625
3
[]
no_license
#include <iostream> using namespace std; // a^x int pow(int a, int x) { if (x == 0) { return 1; } int res = pow(a, x / 2); res *= res; if (x % 2 == 1) { res *= a; } return res; } int main() { int a, x; cin >> a >> x; cout << pow(a, x) << endl; return 0; }
true
f40e7961c7ccbca8353a3932b0cd9931b56c0cd7
C++
gracefullee/Practice_Programs
/largest_prime_factor.cpp
UTF-8
643
3.75
4
[]
no_license
#include <iostream> #include <cmath> using namespace std; bool isPrime(long int num); int main() { long int n; cout << "Please Enter an Integer : "; cin >> n; if(isPrime(n)==true) cout << "Largest Prime Number is ... " << n << endl; else{ while(n!=1){ for(long int i=0; i<=n; i++){ if(isPrime(i)==true){ if(n%i==0){ n = n/i; cout << i << " "; } } } cout << endl; } } return 0; } bool isPrime(long int num) { if(num==0||num==1) return false; if(num<0) return false; if(num==2) return true; for(int i=3; i< sqrt(num); i++){ if(num%i==0) return false; } return true; }
true
f05d683c8302f16656a481a3db3aa45493dfc84f
C++
carlesaraguz/aeodss
/src/model/activity/ActivityHandler.hpp
UTF-8
12,107
2.609375
3
[]
no_license
/***********************************************************************************************//** * Container and manager of activities known or generated by a single Agent. * @class ActivityHandler * @authors Carles Araguz (CA), carles.araguz@upc.edu * @date 2018-sep-26 * @version 0.1 * @copyright This file is part of a project developed by Nano-Satellite and Payload Laboratory * (NanoSat Lab) at Technical University of Catalonia - UPC BarcelonaTech. **************************************************************************************************/ #ifndef ACTIVITY_HANDLER_HPP #define ACTIVITY_HANDLER_HPP #include "prot.hpp" #include "Activity.hpp" #include "ActivityHandlerView.hpp" class ActivityHandler : public HasView, public ReportGenerator { public: /*******************************************************************************************//** * Constructs an activity handler for the agent pointed to by aptr. **********************************************************************************************/ ActivityHandler(Agent* aptr); /*******************************************************************************************//** * Updates the confirmation status of owned activities and internal state of this handler. This * function checks what is the current activity of the agent and stores information to * indirectly access it faster. **********************************************************************************************/ void update(void); /*******************************************************************************************//** * Determines whether there is an activity being executed by the agent. **********************************************************************************************/ bool isCapturing(void); /*******************************************************************************************//** * Determines whether two activities have overlapping intervals. **********************************************************************************************/ bool isOverlapping(std::shared_ptr<Activity> a, std::shared_ptr<Activity> b) const; /*******************************************************************************************//** * TODO **********************************************************************************************/ std::vector<std::shared_ptr<Activity> > checkOverlaps(std::shared_ptr<Activity> a, std::vector<std::shared_ptr<Activity> >& beta); /*******************************************************************************************//** * Returns the next activity of this agent (i.e. that which has a start time in the future, * w.r.t. `t`) or nullptr if there is none. * @param t The time to consider activities in the future. If not provided, the function * will assume t = VirtualTime::now(). **********************************************************************************************/ std::shared_ptr<Activity> getNextActivity(double t = -1.0) /* const */; /*******************************************************************************************//** * Returns the current activity of the agent if there is one. This function always returns a * valid pointer iff isCapturing returns true. Otherwise, nullptr is returned. **********************************************************************************************/ std::shared_ptr<Activity> getCurrentActivity(void) /* const */; /*******************************************************************************************//** * Get the last activity scheduled by this agent. This function always returns a valid pointer * iff the return of ActivityHandler::pending is greater than 0. Otherwise nullptr is returned. **********************************************************************************************/ std::shared_ptr<Activity> getLastActivity(void) /* const */; /*******************************************************************************************//** * Retrieves the list of pending activities (i.e. those that have not started and are not * discarded). **********************************************************************************************/ std::vector<std::shared_ptr<Activity> > getPending(void) /* const */; /*******************************************************************************************//** * Adds a new activity to the knowledge base. **********************************************************************************************/ void add(std::shared_ptr<Activity> pa); /*******************************************************************************************//** * Checks if an activity overlaps with others and decides whether to add it or not. **********************************************************************************************/ void add(std::shared_ptr<Activity> a, std::map<unsigned int, std::shared_ptr<Activity> >& beta); /*******************************************************************************************//** * Discards this activity (which has to be listed in the `owned` set). **********************************************************************************************/ void discard(std::shared_ptr<Activity> pa); /*******************************************************************************************//** * Counts the number of known activities for an agent identified with `aid`. * @param aid Agent identifier. **********************************************************************************************/ unsigned int count(std::string aid) const; /*******************************************************************************************//** * Gives the number of activities for the owning agent such that they end in the future and * have not been discarded. This effectively counts future activites as well as the on-going * one. **********************************************************************************************/ unsigned int pending(void) const; /*******************************************************************************************//** * Sets the Agent identifier for this handler. It propagates this information to the view. * @param aid Agent ID. **********************************************************************************************/ void setAgentId(std::string aid); /*******************************************************************************************//** * Creates an activity that is onwed by this agent. This function does not add the new activity * to the internal list, but only generates the object and assigns its trajectory. * @param a_pos A table with the trajectory for this activity where the index (double) is * the virtual time and the item (sf::Vector3f) is the propagated position of * the agent. **********************************************************************************************/ std::shared_ptr<Activity> createOwnedActivity( double t0, double t1, const std::map<double, sf::Vector3f>& a_pos, const std::vector<ActivityCell>& a_cells ); /*******************************************************************************************//** * Finds a list of activities that could be worth sharing with agent `aid`. **********************************************************************************************/ std::vector<std::shared_ptr<Activity> > getActivitiesToExchange(std::string aid); /*******************************************************************************************//** * Setter for the instrument aperture of the owner agent. **********************************************************************************************/ void setInstrumentAperture(float ap) { m_aperture = ap; } /*******************************************************************************************//** * Sets the pointer to the environment object of the agent that owns the activity handler. **********************************************************************************************/ void setEnvironment(std::shared_ptr<EnvModel> eptr) { m_env_model_ptr = eptr; } /*******************************************************************************************//** * Implements the HasView interface. **********************************************************************************************/ const sf::Drawable& getView(void) const override; /*******************************************************************************************//** * Configure whether the view should automatically be updated as new activities are added. **********************************************************************************************/ void autoUpdateView(bool auto_update = true); /*******************************************************************************************//** * Wrapper to ActivityHandlerView::display. **********************************************************************************************/ void displayInView(ActivityDisplayType adt, std::vector<std::pair<std::string, unsigned int> > filter = { }); /*******************************************************************************************//** * Erases activities that are older than the maximum revisit time (because they will never * contribute to payoffs in the future.) * @param remove_unsent Also removes activities that have not been shared with any other * agent. The removing of activities is performed at the lowest * possible level, i.e. activities are not discarded but removed * altogether from the knowledge base and the environment model. * This only applied to owned activities. * @param skip_list List of activities that are currently being sent and that cannot be * purged. **********************************************************************************************/ void purge(bool remove_unsent, std::set<int> skip_list); /*******************************************************************************************//** * Marks an owned activity as sent. If the activity is not owned or does not belong to the * knowledge base, it is ignored. **********************************************************************************************/ void markAsSent(int aid); private: std::map<double, unsigned int> m_act_own_lut; /* Activity LUT (own) indexed by start time. */ std::vector<std::shared_ptr<Activity> > m_activities_own; /* Unsorted. */ std::map<std::string, std::map<unsigned int, std::shared_ptr<Activity> > > m_activities_others; std::string m_agent_id; Agent* m_agent; bool m_update_view; ActivityHandlerView m_self_view; unsigned int m_activity_count; float m_aperture; std::shared_ptr<EnvModel> m_env_model_ptr; double m_report_output_time; /*******************************************************************************************//** * Re-builds an internal Look-Up-Table. **********************************************************************************************/ void buildActivityLUT(void); /*******************************************************************************************//** * Outputs state of the knowledge base in the report. **********************************************************************************************/ void report(void); }; #endif /* ACTIVITY_HANDLER_HPP */
true
2d6b9035e4047118fe564b18dbee01d0e7bf2d5c
C++
nitin-rajesh/cpp_projects
/MasterMind_proj/MasterMind_ultra.cpp
UTF-8
8,866
2.765625
3
[]
no_license
#include<iostream> #include<string.h> #include<time.h> #include<stdlib.h> #include<stdio.h> #define clear system("clear") //if cout<<"\033[2J\033[;H" doesn't work, use system("cls") #define line cout<<endl using namespace std; const int numberOfRows=12; struct Grid{ char pos[numberOfRows][4]; int red[numberOfRows]; int white[numberOfRows]; }board; struct BoardRow{ char values[5]; int possibleValues[4][8]; int red; int white; }rowList[numberOfRows]; struct ColourComplex{ int red; int white; }; bool solutionSet[8][8][8][8]; int firstPosInSolutionSet[4] = {-1,-1,-1,-1}; void holdOn(){ int time1, time2, j=0; cout<<"Thinking...."; line; time1=time(NULL); for(int i=0;;i++){ time2=time(new time_t); //cout<<endl<<time1<<endl<<time2; if(time2-time1==1){ //cout<<"."; j++; } if(j==4){ return; } } } void boardReset(); void boardPrint(); ColourComplex colorCount(int,char[],bool shouldChangeBoard); void rowGuesser(int); bool colourCompare(int row, char i, char j, char k, char l); void eliminateSolutions(int lastRowAnswered); void gamePlayBegins(); void printRules(); int main(){ char showRules, repCon; clear; cout<<"--MASTERMIND AI--"<<endl; cout<<endl<<"-Enter H for rules"<<endl<<"-Press enter to play"; line; showRules=getchar(); if(showRules=='h'||showRules=='H'){ printRules(); getchar(); } do{ fflush(stdin); gamePlayBegins(); cout<<"Enter R to play again"<<endl; fflush(stdin); cin>>repCon; }while(repCon=='r'||repCon=='R'); } void printRules(){ cout<<"- The computer picks a sequence of four numbers. The numbers range from 1 to 8"; getchar(); cout<<"- The objective of the game is to guess the exact positions of the numbers in the computer's sequence.\n"; cout<<"- A number can be used only once in a code sequence."; getchar(); cout<<"- After filling a line with your guesses and pressing Enter, the computer responses with the result of your guess.\n"; cout<<"-'R' (red) counts the numbers in your guess that are of the correct value and in correct position in the code sequence.\n"; cout<<"- 'W' (white) counts the numbers in your guess with the correct value but NOT in the correct position in the code sequence."; getchar(); cout<<"- You win the game when you manage to guess all the colors in the code sequence and when they all in the right position before running out of tries.\nPress enter to begin"; } void rowGuesser(int row){ //cout<<"Psst guess this:"; if(row==numberOfRows-1){ strcpy(rowList[row].values,"1234"); //cout<<1234<<endl; return; } eliminateSolutions(row+1); /*for(int i = 0; i < 4; ++i){ cout<<firstPosInSolutionSet[i]+1; } cout<<endl;*/ } void eliminateSolutions(int lastRowAnswered){ for(int i = 0; i < 4; ++i){ firstPosInSolutionSet[i] = -1; } for(int i = 0; i < 8; ++i){ for(int j = 0; j < 8; ++j){ for(int k = 0; k < 8; ++k){ for(int l = 0; l < 8; ++l){ if(!solutionSet[i][j][k][l]){ continue; } if(!colourCompare(lastRowAnswered,i+'1',j+'1',k+'1',l+'1')){ solutionSet[i][j][k][l] = false; } else if(firstPosInSolutionSet[0] == -1){ firstPosInSolutionSet[0] = i; firstPosInSolutionSet[1] = j; firstPosInSolutionSet[2] = k; firstPosInSolutionSet[3] = l; } else { } }}}} } void generateRandomAnswer(char answer[4]){ srand(time(new time_t)); answer[0] = rand()%8+'1'; for(int i = 1; i < 4; ++i){ answer[i] = rand()%(8-i)+'1'; for(int j = 0; j < i;++j){ if(answer[i]==answer[j]){ answer[i]++; j = -1; } } } } void gamePlayBegins(){ char answer[4]; generateRandomAnswer(answer); bool isWinner=false,isAI=false, showAns=false; for(int i = 0; i < 8; ++i){ for(int j = 0; j < 8; ++j){ for(int k = 0; k < 8; ++k){ for(int l = 0; l < 8; ++l){ if(i == j||i == k||i == l||j == k||j == l||k == l){ solutionSet[i][j][k][l] = false; } else { solutionSet[i][j][k][l] = true; } }}}} //cout<<"Answer- "; /*for(int i=0;i<4;i++) cin>>answer[i]; */ boardReset(); for(int row=numberOfRows-1;row>=0;row--){ fflush(stdin); boardPrint(); if(showAns){ cout<<"Answer: "; for(int i = 0; i<4;++i){ cout<<answer[i]; } } rowGuesser(row); /*for(int i = 0; i<4;++i){ cout<<answer[i]; }*/ cout<<endl; if(!isAI){ cout<<"Enter 'AI' for computer to solve it"; line; for(int i=0;i<4;i++){ /*if(row==x-1){ numMaker(row); board.pos[row][i]=rowList[row].pos[i]; continue; }*/ cin>>board.pos[row][i]; if((board.pos[row][0]=='A'||board.pos[row][0]=='a')&&(board.pos[row][1]='I'||board.pos[row][1]=='I')){ isAI=true; //rowList[row].values[i]=board.pos[row][i]; break; } } if(!showAns){ for(int i=0;i<4;i++){ if(board.pos[row][i]=='#') showAns=true; else showAns=false; } } if(isAI) break; } if(isAI) break; //cout<<endl<<isAI<<endl; isWinner=(colorCount(row,answer,true).red == 4); if(isWinner) break; } if(isAI){ boardReset(); for(int row=numberOfRows-1;row>=0;row--){ boardPrint(); holdOn(); rowGuesser(row); if(row==numberOfRows-1){ strcpy(board.pos[row],"1234"); } else{ for(int i = 0; i < 4; ++i){ board.pos[row][i]=firstPosInSolutionSet[i]+'1'; } } isWinner=(colorCount(row,answer,true).red == 4); if(isWinner) break; } } boardPrint(); if(isWinner&&(!showAns&&!isAI)) cout<<"You win!"; else{ if(isAI){ cout<<"AI wins!"; line; } else if(showAns){ cout<<"Breach detected"; line; } else{ cout<<"N00B@"; cout<<answer<<".com"<<endl; } } line; return ; } void boardReset(){ clear; //cout<<"? ? ? ?"<<endl; for(int i=0;i<numberOfRows;i++){ board.red[i]=0; board.white[i]=0; for(int j=0;j<4;j++){ board.pos[i][j]='*'; cout<<board.pos[i][j]<<" "; //Make this a loop //rowList[i].possibleValues[j]=0; } cout<<'\t'<<"R-"<<board.red[i]<<" W-"<<board.white[i]; line; } } void boardPrint(){ clear; cout<<"? ? ? ?"<<endl; for(int i=0;i<numberOfRows;i++){ //board.red[i]=0; //board.white[i]=0; for(int j=0;j<4;j++){ //board.pos[i][j]='*'; cout<<board.pos[i][j]<<" "; } cout<<'\t'<<"R-"<<board.red[i]<<" W-"<<board.white[i]<<'\t'; /*for(int j=0;j<4;j++) cout<<"Quo."<<j+1<<"\x1A"<<rowList[x].posVal[j]<<" "; */ line; } } ColourComplex colorCount(int row, char givenAnswer[4],bool shouldChangeBoard ){ //white bool skip; ColourComplex c; c.red = 0; c.white = 0; for(int i=0;i<4;i++){ skip=false; for(int j=0;j<4;j++){ if(givenAnswer[i]==board.pos[row][j]){ skip=true; c.white++; //board.white[row]++; } if(skip) break; } } //red for(int i=0;i<4;i++){ if(givenAnswer[i]==board.pos[row][i]){ c.red++; //board.red[row]++; } } c.white -= c.red; //board.white[row]-=board.red[row]; if(shouldChangeBoard){ board.red[row] = c.red; board.white[row] = c.white; } return c; } bool colourCompare(int row, char i, char j, char k, char l){ char possibleAnswer[4] = {i,j,k,l}; ColourComplex c = colorCount(row,possibleAnswer,false); return(c.red == board.red[row] && c.white == board.white[row]); }
true
883fbac0ab61cfcab47e1f588dd1bddd49e10c40
C++
corywelch/DigitalSystemsSYDE192-FunctionGenerator
/lab07/lab742/lab742.ino
UTF-8
1,537
2.953125
3
[]
no_license
int poll = 4; int i = 0; int j = 0; volatile int state = 1; void setup(){ pinMode(poll, INPUT); attachInterrupt(0, handler, CHANGE); Serial.begin(9600); } void loop(){ j = 0; //Polling pin 4 // Detect high if (digitalRead(poll) == HIGH){ // notify user Serial.println("Polling found pin 4 to be HIGH"); delay(500); // setup so that the program needs to count to 15 while (j<16){ // checks for no interrupt if ((state-1) == 0){ // starts counting for (j; j<16; j++){ // again checks for interrupt if ((state-1) == 1){ // notifys user that there is an interrupt Serial.println("Interrupt Detected stop counting"); // waits for change in the interrupt variable while ((state-1) == 1){ delay(100); } } // prints out the state of the for loop Serial.println(j); delay(500); } } } // notifys user that we are checking polling again after counting to 15 Serial.print("Check polling"); // when polling pin is low }else{ Serial.println("Polling LOW detected stop program"); // don't do anything until the pin is high while (digitalRead(poll) == LOW){ delay(10); } } Serial.println(i); i++; } void handler(){ // changes state state = (state%2)+1; delay(1000); }
true
e8c244008a2c194b5d96ae08be05cb3f6f45f40c
C++
smueksch/shared-memory-server
/src/client/client.cpp
UTF-8
1,521
3.34375
3
[ "Unlicense" ]
permissive
#include <cstdlib> // EXIT_SUCCESS #include <csignal> // SIGINT, signal #include <iostream> // cin, cout, endl #include <string> // string #include <fcntl.h> // O_WRONLY #include <sys/mman.h> // mmap, shm_open, PROT_WRITE #include <unistd.h> // ftruncate // Name of shared memory object. #define SHM_NAME "comm-file" // Size of shard memory object. // Give enough space to store 10 signed integers. #define SHM_SIZE 10 * sizeof(int) void handle_shutdown(int signal) { std::string response; std::cout << std::endl; do { std::cout << "Shutdown client? [y/n] "; std::cin >> response; if (response == "y" || response == "Y") { exit(EXIT_SUCCESS); } } while(response != "n" && response != "N"); } int main(int arg_c, char** arg_v) { // Set up shutdown handler to terminate program correctly. signal(SIGINT, handle_shutdown); // Create shared memory object, get file descriptor. // TODO: Check that a server is active and has created the shared memory! int shared_memory = shm_open(SHM_NAME, O_WRONLY, 0666); // Memory map the shared memory object. int* data = (int*)mmap(0, SHM_SIZE, PROT_WRITE, MAP_SHARED, shared_memory, 0); // Poll for new messages to send and store in shared memory. while(true) { std::cout << "Message to server: "; // TODO: Put checks that what is read from console is actually an // integer! std::cin >> data[0]; } return EXIT_SUCCESS; }
true
b4752f4feb82b0090b777ac6a72012bb940d829b
C++
boatshaman/HomemadeHardware
/firstInteraction_ATtiny85/sketch/tiny85_code.ino
UTF-8
242
2.578125
3
[]
no_license
void setup() { // put your setup code here, to run once: pinMode(4, INPUT); pinMode(2, OUTPUT); } void loop() { if(digitalRead(4) == HIGH){ digitalWrite(2, HIGH); }else{ digitalWrite(2, LOW); } delay(10); }
true