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
deeb07704a6399c87bdd6ac4b3d82adf20b94941
C++
0JASQUE0/Course_work-sem2
/Курсовая работа/EdmondsKarp.cpp
UTF-8
2,748
3.21875
3
[]
no_license
#include "EdmondsKarp.h" #include <string> #include <fstream> #include "queue.h" void vertexesSearch(LinkedList<char>* listOfCities, ifstream& fin) { string str; char tempChar; int counter, index; while (!fin.eof()) { getline(fin, str); counter = 0; for (size_t i = 0; i < str.size(); i++) { tempChar = str[i++]; index = listOfCities->find(tempChar); if (index == -1) { listOfCities->push_back(tempChar); } counter++; if (counter == 2) { break; } if (str[i] != ' ') { throw("Incorrect input"); } } } } void matrixFilling(LinkedList<char>* listOfVertexes, ifstream& fin, int** capacityMatrix) { string str; char tempChar; int indexI, indexJ; int counter; while (!fin.eof()) { getline(fin, str); counter = 0; for (size_t i = 0; i < str.size(); i++) { tempChar = str[i++]; if (counter == 0) { indexI = listOfVertexes->find(tempChar); } if (counter == 1) { indexJ = listOfVertexes->find(tempChar); } if (counter == 2) { if (int(tempChar) < int('0') || int(tempChar) > int('9')) { throw("Incorrect input"); } else { capacityMatrix[indexI][indexJ] = int(tempChar) - int('0'); } } counter++; } } } bool breadthFirstSearch(int** flowMatrix, int source, int target, int* parent, size_t size) { bool* visitedVertexes = new bool[size]; for (size_t i = 0; i < size; i++) { visitedVertexes[i] = false; } Queue<int> queue; queue.push(source); visitedVertexes[source] = true; parent[source] = -1; while (!queue.empty()) { int currentVertex = queue.first(); queue.pop(); for (size_t i = 0; i < size; i++) { if (visitedVertexes[i] == false && flowMatrix[currentVertex][i] > 0) { queue.push(i); parent[i] = currentVertex; visitedVertexes[i] = true; } } } return visitedVertexes[target]; } int EdmondsKarpAlgorithm(int** capacityMatrix, int source, int target, size_t size) { int currentVertex; int** flowMatrix = new int* [size]; for (size_t i = 0; i < size; i++) { flowMatrix[i] = new int[size]; } for (size_t i = 0; i < size; i++) { for (size_t j = 0; j < size; j++) { flowMatrix[i][j] = capacityMatrix[i][j]; } } int* parent = new int[size]; int maxFlow = 0; int pathFlow; while (breadthFirstSearch(flowMatrix, source, target, parent, size)) { pathFlow = 1e9; for (int i = target; i != source; i = parent[i]) { currentVertex = parent[i]; if (pathFlow > flowMatrix[currentVertex][i]) { pathFlow = flowMatrix[currentVertex][i]; } } for (int i = target; i != source; i = parent[i]) { currentVertex = parent[i]; flowMatrix[currentVertex][i] -= pathFlow; flowMatrix[i][currentVertex] += pathFlow; } maxFlow += pathFlow; } return maxFlow; }
true
4339ec5c065c9bcc819d3d170cd8e5f11c899612
C++
welshimeat/Self_Study
/알고리즘/Backjoon/일반/2206_벽부수고이동하기.cpp
UTF-8
1,404
2.515625
3
[]
no_license
#include <iostream> #include <queue> #include <tuple> using namespace std; int N, M, visited[1001][1001][2]; char map[1001][1001]; int direction_x[4] = { 1, -1, 0, 0 }, direction_y[4] = { 0, 0, 1, -1 }; queue<tuple<int, int, int, bool>> q; void bfs(); int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> N >> M; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { cin >> map[i][j]; } } bfs(); return 0; } void bfs() { q.push({ 1, 1, 1, false }); visited[1][1][false] = 1; while (!q.empty()) { int x = get<0>(q.front()); int y = get<1>(q.front()); int dist = get<2>(q.front()); bool used = get<3>(q.front()); q.pop(); if (x == N && y == M) { cout << dist << '\n'; return; } for (int i = 0; i < 4; i++) { int new_x = x + direction_x[i]; int new_y = y + direction_y[i]; if (new_x >= 1 && new_x <= N && new_y >= 1 && new_y <= M) { if (map[new_x][new_y] == '0' && (!visited[new_x][new_y][used] || visited[new_x][new_y][used] > dist + 1)) { q.push({ new_x, new_y, dist + 1, used }); visited[new_x][new_y][used] = dist + 1; } else if (used == false && map[new_x][new_y] == '1' && (!visited[new_x][new_y][!used] || visited[new_x][new_y][!used] > dist + 1)) { q.push({ new_x, new_y, dist + 1, !used }); visited[new_x][new_y][!used] = dist + 1; } } } } cout << -1 << '\n'; }
true
a6deb96e018bad205a1d23bb63a1829435154756
C++
PancrasL/cpp-algorithms
/cpp-algorithms/PTA练习题/图/最短路径/A1003-Emergency(BellmanFord).cpp
UTF-8
2,351
3.0625
3
[ "MIT" ]
permissive
#include <queue> #include <set> #include <vector> #include <iostream> using namespace std; #define MAX_NODE 510 struct ArcNode { int v; //邻接点 int len; //邻接边长度 ArcNode(int v1, int len1) : v(v1) , len(len1){}; }; int N, M, C1, C2; vector<vector<ArcNode> > G(MAX_NODE); vector<int> cityRescues(MAX_NODE); //城市i的营救人员个数 vector<int> routeNum(MAX_NODE, 0); //从源点到i的最短路径的条数 vector<int> len(MAX_NODE, 0x3f3f3f3f); //源点到i的最短距离 vector<int> totalRescues(MAX_NODE, 0); //从源点到i的营救人员的个数 set<int> preNode[MAX_NODE]; void relax(int a, int b, int c) { int newLen = len[a] + c;//源点经由a到达b的距离 int newRescues = totalRescues[a] + cityRescues[b];//源点经由a到达b的营救人员的个数 if (newLen < len[b]) { //更新距离 len[b] = newLen; //更新路径数 preNode[b].clear(); preNode[b].insert(a); routeNum[b] = routeNum[a]; //更新营救人员个数 totalRescues[b] = newRescues; }else if(newLen == len[b]){ //更新路径数 preNode[b].insert(a); routeNum[b] = 0; for(set<int>::iterator it = preNode[b].begin();it!=preNode[b].end();it++){ routeNum[b] += routeNum[*it]; } //更新营救人员的个数 if(newRescues > totalRescues[b]){ totalRescues[b] = newRescues; } } } void bellmanFord() { //初始化 len[C1] = 0; routeNum[C1] = 1; totalRescues[C1] = cityRescues[C1]; //对每条边执行N-1次松弛操作 for (int i = 0; i < N - 1; i++) { for (int v = 0; v < N; v++) { //对于所有的边执行松弛操作 for (int k = 0; k < G[v].size(); k++) { relax(v, G[v][k].v, G[v][k].len); } } } } int main(void) { cin >> N >> M >> C1 >> C2; //每个城市的营救人员个数 for (int i = 0; i < N; i++) { cin >> cityRescues[i]; } //道路信息 for (int i = 0; i < M; i++) { int c1, c2, L; cin >> c1 >> c2 >> L; G[c1].push_back(ArcNode(c2, L)); G[c2].push_back(ArcNode(c1, L)); } //求解最短路径 bellmanFord(); cout << routeNum[C2] << ' ' << totalRescues[C2] << endl; }
true
d164b2d73118da48f0de27148c0c65dbdf94e445
C++
lshoon123/DataStructor
/hw7.cpp
UHC
5,139
3.171875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> FILE *inp_fp, *oup_fp; struct TreeNode { int num; struct TreeNode *R, *L; }; void Insert(struct TreeNode **T, int n) { //struct TreeNode *newNode ,*temp; while (1) { if ((*T) == NULL) { (*T) = (struct TreeNode*)malloc(sizeof(struct TreeNode)); (*T)->num = n; (*T)->L = NULL; (*T)->R = NULL; break; } else { if ((*T)->num>n) { T = &((*T)->L); } else if ((*T)->num<n) { T = &((*T)->R); } } } } void preorder(struct TreeNode *T) { if (T == NULL) {} else if (T->L != NULL&&T->R != NULL) { fprintf(oup_fp, "%d ", T->num); preorder(T->L); preorder(T->R); } else if (T->L == NULL) { fprintf(oup_fp, "%d ", T->num); preorder(T->R); } else if (T->R == NULL) { fprintf(oup_fp, "%d ", T->num); preorder(T->L); } } int RDelete(struct TreeNode **T, struct TreeNode **parents, int n) { int max = 0, min = 0, x, y; struct TreeNode *temp, *rp, *lp, *child; if ((*T) == NULL) { fprintf(oup_fp, "error"); return 1; } else if ((*T)->num == n) { //ϳ if ((*T)->L == NULL && (*T)->R == NULL) { if ((*parents)->L != NULL || (*parents)->R != NULL) { if ((*parents)->L != NULL && (*parents)->L->num == n) { (*parents)->L = NULL; } else if ((*parents)->R != NULL && (*parents)->R->num == n) { (*parents)->R = NULL; } } else if ((*parents)->L == NULL && (*parents)->R == NULL) { *parents = NULL; } } //1 else if ((*T)->R == NULL || (*T)->L == NULL) { if ((*T)->R != NULL) { child = (*T)->R; } else if ((*T)->L != NULL) { child = (*T)->L; } if ((*parents) != NULL) { if ((*parents)->L != NULL && (*parents)->L->num == n) { (*parents)->L = child; } else if ((*parents)->R != NULL && (*parents)->R->num == n) { (*parents)->R = child; } else if ((*parents)->num == n) { *parents = child; } } } //ΰ else if ((*T)->L != NULL && (*T)->R != NULL) { temp = (*T); temp = temp->R; max = temp->num; rp = (*T); while (temp->L != NULL) { rp = temp; temp = temp->L; max = temp->num; } RDelete(&rp, &rp, max); (*T)->num = max; } } else if ((*T)->num>n) { RDelete(&((*T)->L), T, n); } else if ((*T)->num<n) { RDelete(&((*T)->R), T, n); } } int LDelete(struct TreeNode **T, struct TreeNode **parents, int n) { int max = 0, min = 0, x, y; struct TreeNode *temp, *rp, *lp, *child; if ((*T) == NULL) { fprintf(oup_fp, "error"); return 1; } else if ((*T)->num == n) { //ϳ if ((*T)->L == NULL && (*T)->R == NULL) { if ((*parents)->L != NULL || (*parents)->R != NULL) { if ((*parents)->L != NULL && (*parents)->L->num == n) { (*parents)->L = NULL; } else if ((*parents)->R != NULL && (*parents)->R->num == n) { (*parents)->R = NULL; } } else if ((*parents)->L == NULL && (*parents)->R == NULL) { *parents = NULL; } } //1 else if ((*T)->R == NULL || (*T)->L == NULL) { if ((*T)->R != NULL) { child = (*T)->R; } else if ((*T)->L != NULL) { child = (*T)->L; } if ((*parents) != NULL) { if ((*parents)->L != NULL && (*parents)->L->num == n) { (*parents)->L = child; } else if ((*parents)->R != NULL && (*parents)->R->num == n) { (*parents)->R = child; } else if ((*parents)->num == n) { *parents = child; } } } //ΰ else if ((*T)->L != NULL && (*T)->R != NULL) { temp = (*T); temp = temp->L; max = temp->num; rp = (*T); while (temp->R != NULL) { rp = temp; temp = temp->R; max = temp->num; } LDelete(&rp, &rp, max); (*T)->num = max; } } else if ((*T)->num>n) { LDelete(&((*T)->L), T, n); } else if ((*T)->num<n) { LDelete(&((*T)->R), T, n); } } void Search(struct TreeNode **T, int n) { while (1) { if ((*T) == NULL) { fprintf(oup_fp, "error"); break; } else if ((*T)->num == n) { fprintf(oup_fp, "%d", (*T)->num); break; } else { if ((*T)->num>n) { fprintf(oup_fp, "%d ", (*T)->num); T = &((*T)->L); } else if ((*T)->num<n) { fprintf(oup_fp, "%d ", (*T)->num); T = &((*T)->R); } } } } int main() { int n, i, plag = 0; int x = 0; int sw = 0; int k = 0; char cc = ' ', ch[5]; struct TreeNode *Tree; inp_fp = fopen("hw7.inp", "r"); oup_fp = fopen("hw7.out", "w"); Tree = NULL; for (i = 0; i<5; i++) { fscanf(inp_fp, "%c", &ch[i]); } if (ch[0] == 'l') { plag = 0; } else { plag = 1; } while (cc != '\n') { fscanf(inp_fp, "%d%c", &n, &cc); Insert(&Tree, n); } preorder(Tree); while (1) { fscanf(inp_fp, "%c%d\n", &cc, &n); if (cc == 'D') { if (plag == 0) { // fprintf(oup_fp, "\n"); LDelete(&Tree, &Tree, n); if (k != 1) { preorder(Tree); } } else if (plag == 1) { // fprintf(oup_fp, "\n"); k = RDelete(&Tree, &Tree, n); if (k != 1) { preorder(Tree); } } } else if (cc == 'S') { fprintf(oup_fp, "\n"); Search(&Tree, n); } else { break; } } fprintf(oup_fp, "\n*"); }
true
42772070cf8f57f4b93af4e07eb2b24822828fa8
C++
mmalenta/bitsnbobs
/paf/struct_test.cpp
UTF-8
627
3.1875
3
[]
no_license
#include <iostream> using std::cout; using std::endl; struct obs_time { int ref_s; int start_s; int frame_s; }; void print_struct(obs_time frame) { cout << frame.ref_s << " " << frame.start_s << " " << frame.frame_s << endl; } int main(void) { obs_time start{2000,350}; obs_time some1{2000, 350, 10}; obs_time some2{2000, 350, 20}; obs_time *gulp_times = new obs_time[4]; gulp_times[0] = start; gulp_times[1] = some1; gulp_times[2] = some2; cout << gulp_times->ref_s << " " << (gulp_times + 1)->frame_s << " " << gulp_times[2].frame_s << endl; print_struct({start.ref_s, start.start_s, 10}); return 0; }
true
7d7ef36ae147cda0dfa39e12d6a3f1e82396793a
C++
euanmcmen/GPCWGame
/GPCWGame/cModel.cpp
UTF-8
3,383
2.9375
3
[]
no_license
#include "cModel.h" //Constructor for model. cModel::cModel() { } // +++++++++++++++++++++++++++++++++++++++++++++ // Setters // +++++++++++++++++++++++++++++++++++++++++++++ void cModel::setPosition(glm::vec3 mdlPosition) { m_mdlPosition = m_mdlScale; } void cModel::setRotation(GLfloat mdlRotation) { m_mdlRotation = mdlRotation; } void cModel::setAxis(glm::vec3 axis) { m_axis = axis; } void cModel::setDirection(glm::vec3 mdlDirection) { m_mdlDirection = mdlDirection; } void cModel::setSpeed(float mdlSpeed) { m_mdlSpeed = mdlSpeed; } void cModel::setIsActive(bool mdlIsActive) { m_IsActive = mdlIsActive; } //Set the model dimensions to the largest dimension of the model. void cModel::setMdlDimensions(mdlDimensions mdlDims) { m_Dimensions = mdlDims; m_mdlRadius = largestDimension(mdlDims.s_mdlheight, mdlDims.s_mdlWidth, mdlDims.s_mdldepth) / 2; } void cModel::setMdlRadius(float mdlRadius) { m_mdlRadius = mdlRadius; } void cModel::setScale(glm::vec3 mdlScale) { m_mdlScale = mdlScale; } // +++++++++++++++++++++++++++++++++++++++++++++ // Getters // +++++++++++++++++++++++++++++++++++++++++++++ glm::vec3 cModel::getPosition() { return m_mdlPosition; } GLfloat cModel::getRotation() { return m_mdlRotation; } glm::vec3 cModel::getAxis() { return m_axis; } glm::vec3 cModel::getDirection() { return m_mdlDirection; } float cModel::getSpeed() { return m_mdlSpeed; } bool cModel::isActive() { return m_IsActive; } mdlDimensions cModel::getMdlDimensions() { return m_Dimensions; } float cModel::getMdlRadius() { return m_mdlRadius; } glm::vec3 cModel::getScale() { return m_mdlScale; } void cModel::setTextureID(GLuint theTextureID) { m_TextureID = theTextureID; } //Determines collision. //Uses squared values to avoid sqrt function. bool cModel::SphereSphereCollision(glm::vec3 otherPosition, float otherRadius) { const float squaredSumRadius = pow((m_mdlRadius + otherRadius), 2); return (squaredSumRadius > squaredDistance(otherPosition)); } //Returns the squared distance between this object and the other object. float cModel::squaredDistance(glm::vec3 otherPosition) { return pow((otherPosition.x - m_mdlPosition.x), 2) + pow((otherPosition.y - m_mdlPosition.y), 2) + pow((otherPosition.z - m_mdlPosition.z), 2); } //Find the largest of the 3 dimensions. float cModel::largestDimension(float height, float width, float depth) { float currentMax = 0; //If the length is larger than current max, set currentMax to length. if (height > currentMax) currentMax = height; //Same for width. if (width > currentMax) currentMax = width; //And depth. if (depth > currentMax) currentMax = depth; //Return current. return currentMax; } //Check if model is out of render view, also known as the "killzone" bool cModel::isInKillzone() { return m_mdlPosition.z > KILLZONE_Z; } /* ================================================================= Attach the input manager to the sprite ================================================================= */ void cModel::attachInputMgr(cInputMgr* inputMgr) { m_InputMgr = inputMgr; } /* ================================================================= Attach the sound manager to the sprite ================================================================= */ void cModel::attachSoundMgr(cSoundMgr* soundMgr) { m_SoundMgr = soundMgr; } cModel::~cModel() { }
true
dabfc7db3f69635304ea23409bf3dc29459fe231
C++
rdeiaco/leetcode
/bit_count.cpp
UTF-8
352
3.09375
3
[]
no_license
#include <vector> class Solution { public: vector<int> countBits(int num) { int i, j; int count; std::vector<int> result; for (i = 0; i <= num; i++) { count = 0; for (j = 0; j < 32; j++) { if ((i>>j) & 0x1) { count++; } } result.push_back(count); } return result; } };
true
6ccbb6afd8de29932c84cf4f978f2c77737db4a9
C++
wolass/platereader
/software/four_sensors/four_sensors.ino
UTF-8
3,761
2.75
3
[]
no_license
/* FILE: TSL235 AUTHOR: Wojciech Francuzik DATE: 2016 07 20 PURPOSE: prototype TSL235R monitoring Digital Pin layout Wemos D1 mini ============================= D0 IRQ 0 - to TSL235R D5 IRQ 1 D6 IRQ 2 D7 IRQ 3 D8 LED0 D1 LED1 D2 LED2 D3 LED3 TSL235R pinout from left to right PIN 1 - GND PIN 2 - VDD - 5V PIN 3 - SIGNAL */ // setting up the variable names volatile unsigned long cnt[4]; //this is for counting the pulses from thefirst sensor unsigned long oldcnt[4]; // this is for the last measurement of the first sensor int t = 100; // this is for measuring time unsigned long last; // to store last meaurment time in milliseconds from starting the device //assign names to sensors and leds this has to be sound iwth the pinout from controller int S[] = {2, 3, 18, 19}; int L[] = {48, 46, 44, 42}; //int pair[] = {0, 1, 2, 3}; unsigned long hz[4]; void irq0() //this function counts the pulses from the first sensor { cnt[0]++; } void irq1() //this function counts the pulses from the first sensor { cnt[1]++; } void irq2() //this function counts the pulses from the first sensor { cnt[2]++; } void irq3() //this function counts the pulses from the first sensor { cnt[3]++; } /////////////////////////////////////////////////////////////////// // // SETUP // void setup() { Serial.begin(115200); // communication set to 115200 Serial.println("START, Beginning of the FILE"); // First comment in the serial monitor Serial.println("S0, S1, S2, S3"); // First comment in the serial monitor pinMode(S[0], INPUT); // set the sensor0 pin to input pinMode(S[1], INPUT); // set the sensor0 pin to input pinMode(S[2], INPUT); // set the sensor0 pin to input pinMode(S[3], INPUT); // set the sensor0 pin to input pinMode(L[0], OUTPUT); // set the LED1 pin to output pinMode(L[1], OUTPUT); // set the LED1 pin to output pinMode(L[2], OUTPUT); // set the LED1 pin to output pinMode(L[3], OUTPUT); // set the LED1 pin to output digitalWrite(S[0], HIGH); digitalWrite(S[1], HIGH); digitalWrite(S[2], HIGH); digitalWrite(S[3], HIGH); attachInterrupt(0, irq0, RISING); // this function attach interrupt is here to consistently count pulses. attachInterrupt(1, irq1, RISING); // this function attach interrupt is here to consistently count pulses. attachInterrupt(2, irq2, RISING); // this function attach interrupt is here to consistently count pulses. attachInterrupt(3, irq3, RISING); // this function attach interrupt is here to consistently count pulses. } /////////////////////////////////////////////////////////////////// // // MAIN LOOP // void loop() { if (millis() - last >= 10000) { // if time from the last measurment is over 1 minute = run! last = millis(); for (int i = 0; 1 < 4; ++i) { hz[i] = counter(i); } Serial.print(hz[0]); Serial.print(";"); Serial.print(hz[1]); Serial.print(";"); Serial.print(hz[2]); Serial.print(";"); Serial.print(hz[3]); Serial.print("\n"); } } unsigned long counter(int p){ digitalWrite(L[p],HIGH); delay(50); // cli();//disable interrupts // cnt[p] = 0; // sei();//enable interrupts // delay(t); // cli();//disable interrupts // long result = cnt[p]*1000/t; // here we add the t variable to always get Hz. // sei();//enable interrupts // digitalWrite(L[p],LOW); // delay(50); Serial.print(p); Serial.print(",=-> "); Serial.print(cnt[p]); Serial.print(", "); hz[p] = cnt[p]; delay(t); //Serial.print(t); //Serial.print(", "); hz[p] = cnt[p]-hz[p]; //Serial.print(p); Serial.print(", "); Serial.print(hz[p]); Serial.print("\n"); Serial.print(millis()); delay(100); //return result; } // END OF FILE
true
c7e4f5ff156e883aa26247baf4177b440d138a69
C++
keishi/ShadeKit
/Camera.h
UTF-8
1,951
2.625
3
[]
no_license
/* * Camera.h * ShadeKit * * Created by Keishi Hattori on 5/6/10. * Copyright 2010 Keishi Hattori. All rights reserved. * */ #ifndef Camera_h #define Camera_h #include "Scene.h" #include "Image.h" namespace ShadeKit { class Camera { public: Camera(unsigned int width, unsigned int height) : m_width(width) , m_height(height) , m_aspect((float)width / (float)height) , m_eye(0.0f, 0.0f, -8.0f) , m_xDirection(1.0f, 0.0f, 0.0f) , m_yDirection(0.0f, 1.0f, 0.0f) , m_zDirection(0.0f, 0.0f, 1.0f) , m_FOVY(20.0f) , m_zNear(3.0f) , m_renderShadow(1) , m_renderReflection(1) , m_renderHighlight(1) , m_backgroundColor(kColorBlack) { } Scene& scene() { return m_scene; } HitInfo raytrace(Ray& ray, Color *acc, int level); Image render(); void setZNear(float z) { m_zNear = z; } void setFOVY(float FOVY) { m_FOVY = FOVY; } void setEye(const Vector3& e) { m_eye = e; } void setLookat(const Vector3& c) { m_zDirection = c.normalized(); m_xDirection = m_yDirection.cross(m_zDirection).normalize(); } void setUp(const Vector3& u) { m_yDirection = u.normalized(); m_xDirection = m_yDirection.cross(m_zDirection).normalize(); } void setRenderShadow(bool b) { m_renderShadow = b; } void setRenderReflection(bool b) { m_renderReflection = b; } private: unsigned int m_width, m_height; float m_aspect; Vector3 m_eye; Vector3 m_xDirection; Vector3 m_yDirection; Vector3 m_zDirection; float m_FOVY; float m_zNear; Scene m_scene; bool m_renderShadow; bool m_renderReflection; bool m_renderHighlight; Color m_backgroundColor; }; } #endif
true
62471a43322ca1f0be1a8be444d54a26424a9342
C++
tritao/flood
/inc/Core/Concurrency.h
UTF-8
4,782
2.546875
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
/************************************************************************ * * Flood Project © (2008-201x) * Licensed under the simplified BSD license. All rights reserved. * ************************************************************************/ #pragma once #include "Core/API.h" #include "Core/Event.h" #include "Core/Pointers.h" #include <vector> NAMESPACE_EXTERN_BEGIN //-----------------------------------// /** * A thread is the entity within a process that can be scheduled for * execution. All threads of a process share its virtual address space * and system resources. */ enum class ThreadPriority { Low, Normal, High }; struct Thread; typedef Delegate2<Thread*, void*> ThreadFunction; struct API_CORE Thread { void* Handle; volatile bool IsRunning; ThreadPriority Priority; ThreadFunction Function; void* Userdata; }; API_CORE Thread* ThreadCreate(Allocator*); API_CORE void ThreadDestroy(Thread*); API_CORE bool ThreadStart(Thread*, ThreadFunction, void*); API_CORE bool ThreadJoin(Thread*); API_CORE bool ThreadPause(Thread*); API_CORE bool ThreadResume(Thread*); API_CORE bool ThreadSetPriority(Thread*, ThreadPriority); API_CORE void ThreadSetName(Thread*, const char* name); typedef scoped_ptr<Thread, ThreadDestroy> ThreadPtr; #define pThreadCreate(alloc, ...) CreateScopedPtr(ThreadCreate, alloc, \ __VA_ARGS__) //-----------------------------------// /** * A mutex is used in concurrent programming to avoid the simultaneous * use of a common resource, such as a global variable, by pieces of * computer code called critical sections. */ struct API_CORE Mutex; API_CORE Mutex* MutexCreate(Allocator*); API_CORE void MutexDestroy(Mutex*); API_CORE void MutexInit(Mutex*); API_CORE void MutexLock(Mutex*); API_CORE void MutexUnlock(Mutex*); typedef scoped_ptr<Mutex, MutexDestroy> MutexPtr; #define pMutexCreate(alloc, ...) CreateScopedPtr(MutexCreate, alloc, \ __VA_ARGS__) //-----------------------------------// struct API_CORE Condition; API_CORE Condition* ConditionCreate(Allocator*); API_CORE void ConditionDestroy(Condition*); API_CORE void ConditionInit(Condition*); API_CORE void ConditionWait(Condition*, Mutex*); API_CORE void ConditionWakeOne(Condition*); API_CORE void ConditionWakeAll(Condition*); typedef scoped_ptr<Condition, ConditionDestroy> ConditionPtr; #define pConditionCreate(alloc, ...) CreateScopedPtr(ConditionCreate, \ alloc, __VA_ARGS__) //-----------------------------------// /** * Synchronizes access to variables that are shared by multiple threads. * Operations on these variables are performed atomically. * Remarks: On Windows this should be aligned to 32-bits. */ typedef volatile int32 Atomic; API_CORE int32 AtomicRead(volatile Atomic* atomic); API_CORE int32 AtomicWrite(volatile Atomic* atomic, int32 value); API_CORE int32 AtomicAdd(volatile Atomic* atomic, int32 value); API_CORE int32 AtomicIncrement(volatile Atomic* atomic); API_CORE int32 AtomicDecrement(volatile Atomic* atomic); //-----------------------------------// /** * Tasks provide an higher level interface to concurrency than threads. * They can be managed by the engine and grouped in different hardware * threads. */ struct Task; typedef Delegate1<Task*> TaskFunction; struct API_CORE Task { int16 group; int16 priority; TaskFunction callback; void* userdata; }; API_CORE Task* TaskCreate(Allocator*); API_CORE void TaskDestroy(Task*); API_CORE void TaskRun(Task*); typedef scoped_ptr<Task, TaskDestroy> TaskPtr; #define pTaskCreate(alloc, ...) CreateScopedPtr(TaskCreate, alloc, \ __VA_ARGS__) enum class TaskState { Added, Started, Finished }; struct API_CORE TaskEvent { Task* task; TaskState state; }; //-----------------------------------// NAMESPACE_EXTERN_END // Workaround for template cyclic dependency. #include "Core/ConcurrentQueue.h" NAMESPACE_EXTERN_BEGIN //-----------------------------------// struct API_CORE TaskPool { std::vector<Thread*> Threads; ConcurrentQueue<Task*> Tasks; ConcurrentQueue<TaskEvent> Events; Event1<TaskEvent> OnTaskEvent; bool IsStopping; }; API_CORE TaskPool* TaskPoolCreate(Allocator*, int8 Size); API_CORE void TaskPoolDestroy(TaskPool*); API_CORE void TaskPoolAdd(TaskPool*, Task*, uint8 Priority); API_CORE void TaskPoolUpdate(TaskPool*); typedef scoped_ptr<TaskPool, TaskPoolDestroy> TaskPoolPtr; #define pTaskPoolCreate(alloc, ...) CreateScopedPtr(TaskPoolCreate, \ alloc, __VA_ARGS__) //-----------------------------------// NAMESPACE_EXTERN_END
true
bac1b9ea66af901dac64bda0cbddbb488784c94f
C++
rjw57/Frontier.Engine
/Source/Rendering/Scene/Transform/FTTransformScale.h
UTF-8
538
2.625
3
[ "MIT" ]
permissive
#pragma once #include <Rendering/Scene/Transform/FTTransform.h> class FTTransformScale : public FTTransform { public: FTTransformScale() : scale_(0, 0, 0) { } void setScale(const glm::vec3& scale) { scale_ = scale; transform_matrix.getData()[0][0] = scale.x; transform_matrix.getData()[1][1] = scale.y; transform_matrix.getData()[2][2] = scale.z; transform_dirty_ = true; } const glm::vec3& getScale() { return scale_; } protected: glm::vec3 scale_; };
true
52147615e81b357b373001a6409f133ed0ccacf6
C++
pritesh1/C-programspractice
/Alternate characters.cpp
UTF-8
542
2.78125
3
[]
no_license
# This is a program for solving the alternate characters challenge on hackerrank #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { char a[10000]; int n,w,count,r,output[100],i,j; scanf("%d", &r); for(j=1;j<=r;j++){ scanf("%s",&a); w=strlen(a); count=0; for (i=1;i<=w;i++){ if(a[i]==a[i-1]){ count=count+1; } output[j]= count; } } for(j=1;j<=r;j++){ printf("%d\n",output[j]); } //printf("%s",a); return 0; }
true
fd8a53f9d256a6df08d3e31a8c8abd5c675a980f
C++
gstggsstt/rubbish-minisql
/MiniSQL/fileManager.h
UTF-8
1,147
2.8125
3
[]
no_license
#pragma once #include "minisql.h" #include "blockNode.h" #include <fstream> #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <map> using namespace std; class fileManager { // Records filename and its file pointer. class fileNode { public: string fileName; FILE *fp; // Open file, if file does not exist, create new one. void open() { fopen_s(&fp,fileName.c_str(), "rb+"); if (fp == NULL) fopen_s(&fp,fileName.c_str(), "wb+"); } // Close file stream. void close() { if (fp) fclose(fp); } // Copy constructor fileNode(const fileNode & temp) { fileName = temp.fileName; fp = temp.fp; } fileNode(string fn="") { fileName = fn; fp = NULL; } ~fileNode() { if (fp) fclose(fp); } }; public: map<string, fileNode> M; // Read a block from file to memory. // pair<FileName, BlockNumber> --TO--> BlockData blockNode readIn(pair<string, int> id); // Write a block back to file. // pair<FileName, BlockNumber>, BlockData void writeBack(pair<string, int> id, blockNode nd); fileManager(); ~fileManager(); };
true
cc5d43d79072923956dcbcb3f445872248221315
C++
fangxing1996/LearnLinux
/Epoll/Client.cpp
UTF-8
1,561
2.59375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <arpa/inet.h> #include <string.h> using namespace std; #define DEST_PORT 1500 #define DEST_IP "127.0.0.1" #define BUFFSIZE 1024 int main(){ int sockfd, new_fd; struct sockaddr_in dest_addr; char sendData[BUFFSIZE]; char recvData[BUFFSIZE]; fd_set readfd; struct timeval timeout; int max; int ret; if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ cout << "socket error!" << endl; return -1; } dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(DEST_PORT); dest_addr.sin_addr.s_addr = inet_addr(DEST_IP); bzero(&(dest_addr.sin_zero), 8); if(connect(sockfd, (struct sockaddr*)&dest_addr, sizeof(struct sockaddr)) < 0){ cout << "connect error!" << endl; close(sockfd); return -1; } while(true){ timeout.tv_sec = 1; timeout.tv_usec = 0; FD_ZERO(&readfd); FD_SET(sockfd, &readfd); FD_SET(fileno(stdin), &readfd); max = sockfd > fileno(stdin) ? sockfd : fileno(stdin); if(select(max + 1, &readfd, NULL, NULL, &timeout) == 0) continue; if(FD_ISSET(sockfd, &readfd)){ ret = recv(sockfd, recvData, BUFFSIZE, 0); cout << "server: " << recvData << endl; } if(FD_ISSET(fileno(stdin), &readfd)){ scanf("%s",sendData); if(strcmp(sendData, "quit") == 0) break; if(send(sockfd, sendData, BUFFSIZE, 0) == -1){ printf("send error!\n"); } } } close(sockfd); return 0; }
true
c0be09c18aebe69a6dc834a11f7302663163a998
C++
xiaozhuanli/OOP345
/w05/w05_home/Movie.cpp
UTF-8
1,235
2.984375
3
[]
no_license
// Name:Luciana Gonzaga Altermann // Seneca Student ID:129855185 // Seneca email:lgonzaga-altermann // Date of completion: 02/16/2020 // // I confirm that the content of this file is created by me, // with the exception of the parts provided to me by my professor. #include <string> #include <iostream> #include <iomanip> #include "Movie.h" using namespace std; namespace sdds { Movie::Movie() { m_title = '\0'; m_year = 0; m_description = '\0'; } const std::string& Movie::title() const { return m_title; } Movie::Movie(const std::string& strMovie) { int title = strMovie.find(','); m_title = strMovie.substr(0, title); m_title.erase(0, m_title.find_first_not_of(" ")); m_title.erase(m_title.find_last_not_of(" ") + 1); int year = strMovie.find(',', title + 1); m_year = stod(strMovie.substr(title + 1, year - title - 1)); int description = strMovie.find('.', year + 1); m_description.append(strMovie.substr(year + 1, description - year + 1)); m_description.erase(0, m_description.find_first_not_of(" ")); } std::ostream& operator<<(std::ostream& os, const Movie& movie) { os << setw(40) << movie.m_title << " | " << setw(4) << movie.m_year << " | " << movie.m_description << endl; return os; } }
true
d51ac33270fce562eb206c448328dc2a3661569a
C++
itstrangvu/B6B32KAB
/4SQUARE.cpp
UTF-8
6,346
3.328125
3
[]
no_license
/* * Author: Vu Thien Trang * Date created: 22. 11. 2017 * Subject: B6B32KAB * Faculty: SIT FEL CTU */ #include <string> #include <sstream> #include <iostream> #include <vector> #include <algorithm> #define DELIMITER "**QQQ**" #define DELIMITER_SIZE 7 using namespace std; vector<vector<char> > defaultTable = { {'A', 'B', 'C', 'D', 'E'}, {'F', 'G', 'H', 'I', 'J'}, {'K', 'L', 'M', 'N', 'O'}, {'P', 'R', 'S', 'T', 'U'}, {'V', 'W', 'X', 'Y', 'Z'} }; // Generates table for the key vector<vector<char> > generateTable(const string& key) { string a = "ABCDEFGHIJKLMNOPRSTUVWXYZ"; string k = move(key); char letter; int row, col; vector<vector<char> > t(5, vector<char>(5, ' ')); for (row = 0; row < 5; ++row) { for (col = 0; col < 5; ++col) { if (k.length()) { letter = k[0]; t[row][col] = k[0]; a.erase(remove(a.begin(), a.end(), letter), a.end()); k.erase(remove(k.begin(), k.end(), letter), k.end()); } else { t[row][col] = a.at(0); a.erase(0,1); } } } return t; } // Prints out given table void printTable (const vector<vector<char>>& t){ for (const auto &row : t) { for (const auto &c : row) clog << c << ' '; clog << endl; } return; } // Parses line into individual words vector<string> parseLine(const string& str) { vector<string> divided; stringstream ss(str); string word; while (ss >> word) divided.push_back(word); return divided; } // Splits a string by delimiter and retrieves both keywords pair<string, string> getKeywords(const string& s) { size_t pos; string first, second; pair<string, string> keywords; if ((pos = s.find(DELIMITER)) != string::npos) { first = (pos == 0) ? "" : s.substr(0, pos); second = ((pos + DELIMITER_SIZE) == s.length()) ? "" : s.substr((pos + DELIMITER_SIZE), string::npos); } transform(first.begin(), first.end(), first.begin(), ::toupper); transform(second.begin(), second.end(), second.begin(), ::toupper); return {first, second}; } // Formats input for algorithm string formatInput(const vector<string>& vec) { string s; // Concatenate strings from vector for (size_t i = 2; i != vec.size(); ++i) s += vec[i]; // Remove non-alpha s.erase(remove_if(s.begin(), s.end(), [](char c) {return !isalpha(c);}), s.end()); // Lowercase to uppercase transform(s.begin(), s.end(), s.begin(), ::toupper); // Remove Q letter s.erase(remove(s.begin(), s.end(), 'Q'), s.end()); // Add letter X if the length is odd if (s.length() % 2 != 0) s += 'X'; return s; } pair<int, int> getPosition(const vector<vector<char> >& t, const char& ch) { int row, col; for (row = 0; row < 5; ++row) { for (col = 0; col < 5; ++col) { if (t[row][col] == ch) return {row, col}; } } return {0,0}; } // Squeeze string squish(const vector<vector<char> >& r, const vector<vector<char> >& l, const string& digram) { string output; char digram1 = digram[0]; char digram2 = digram[1]; pair<int, int> a = getPosition(defaultTable, digram1); pair<int, int> b = getPosition(defaultTable, digram2); char one = r[a.first][b.second]; char two = l[b.first][a.second]; output = one; output += two; // FIRST LETTER = r [row of first in default][column of second in default] // Second letter = l [ row of second in default] [column of first in default] return output; } // Encrypting function string encrypt(const pair<string, string>& keys, const string& input ) { int i; stringstream ss; string output, digram; vector<vector<char> > r = generateTable(keys.first); vector<vector<char> > l = generateTable(keys.second); for (i = 0; i < input.length(); i += 2 ) { digram = input.substr(i, 2); output += squish(r, l, digram); } for (int i = 1; i < output.length(); i++) { if (i%5 == 0) ss << ' '; ss << output[i]; } return ss.str(); } // Squeeze string desquish(const vector<vector<char> >& r, const vector<vector<char> >& l, const string& digram) { string output; char digram1 = digram[0]; char digram2 = digram[1]; pair<int, int> a = getPosition(r, digram1); pair<int, int> b = getPosition(l, digram2); // FIRST LETTER = r [row of first in default][column of second in default] char one = defaultTable[a.first][b.second]; // Second letter = l [ row of second in default] [column of first in default] char two = defaultTable[b.first][a.second]; output = one; output += two; return output; } // Decrypting function string decrypt(const pair<string, string>& keys, const string& input ) { int i; string output, digram; vector<vector<char> > r = generateTable(keys.first); vector<vector<char> > l = generateTable(keys.second); for (i = 0; i < input.length(); i += 2 ) { digram = input.substr(i, 2); output += desquish(r, l, digram); } return output; } // Main function int main(int argc, char **argv) { string line, formatted, output; // Read line after line while (!cin.eof()) { getline(cin, line); vector<string> divided = parseLine(line); if (divided.at(0) == "end") break; // Skip wrong input line if (divided.size() < 3 || ((divided.at(0) != "e") && (divided.at(0) != "d"))) continue; // clog << "------------------------------" << endl; // Retrieve keys pair<string, string> keys = getKeywords(divided.at(1)); // clog << keys.first << " is the first key" << endl; // clog << keys.second << " is the second key" << endl; // // Create squares // vector<vector<char> > rightUpper = generateTable(keys.first); // vector<vector<char> > leftBottom = generateTable(keys.second); // // Format input formatted = formatInput(divided); // clog << "Formatted input is: " << formatted << endl; // clog << "Default table is: " << endl; // printTable(defaultTable); // clog << "Right upper table is: " << endl; // printTable(rightUpper); // clog << "Left bottom table is: " << endl; // printTable(leftBottom); // clog << "------------------------------" << endl; //Encrypt or decrypt if (divided.at(0) == "e") { output = encrypt(keys, formatted); cout << output << endl; } else { output = decrypt(keys, formatted); cout << output << endl; } } return 0; }
true
c2fa1719da2fa753980d33c788ad98e846485659
C++
singhashish-26/Leetcode
/Algorithms/Linked List/convert-binary-number-in-a-linked-list-to-integer.cpp
UTF-8
640
3.328125
3
[]
no_license
#https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int getDecimalValue(ListNode* head) { ListNode* temp =head; int l = 0; while(temp != NULL) { l++; temp=temp->next; } temp= head; int ans=0; while(temp != NULL) { ans+=(temp->val * pow(2,--l)); temp=temp->next; } return ans; } };
true
9f495a5843e34cf0c3f1d5512b29e31a5d5d6af0
C++
mirek190/x86-android-5.0
/external/lldb/include/lldb/Host/Condition.h
UTF-8
4,517
2.703125
3
[ "NCSA" ]
permissive
//===-- Condition.h ---------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef liblldb_DBCondition_h_ #define liblldb_DBCondition_h_ #if defined(__cplusplus) #include <pthread.h> #include "lldb/Host/Mutex.h" namespace lldb_private { class TimeValue; //---------------------------------------------------------------------- /// @class Condition Condition.h "lldb/Host/Condition.h" /// @brief A C++ wrapper class for pthread condition variables. /// /// A class that wraps up a pthread condition (pthread_cond_t). The /// class will create a pthread condition when an instance is /// constructed, and detroy it when it is destructed. It also provides /// access to the standard pthread condition calls. //---------------------------------------------------------------------- class Condition { public: //------------------------------------------------------------------ /// Default constructor /// /// The default constructor will initialize a new pthread condition /// and maintain the condition in the object state. //------------------------------------------------------------------ Condition (); //------------------------------------------------------------------ /// Destructor /// /// Destroys the pthread condition that the object owns. //------------------------------------------------------------------ ~Condition (); //------------------------------------------------------------------ /// Unblock all threads waiting for a condition variable /// /// @return /// The return value from \c pthread_cond_broadcast() //------------------------------------------------------------------ int Broadcast (); //------------------------------------------------------------------ /// Unblocks one thread waiting for the condition variable /// /// @return /// The return value from \c pthread_cond_signal() //------------------------------------------------------------------ int Signal (); //------------------------------------------------------------------ /// Wait for the condition variable to be signaled. /// /// The Wait() function atomically blocks the current thread /// waiting on this object's condition variable, and unblocks /// \a mutex. The waiting thread unblocks only after another thread /// signals or broadcasts this object's condition variable. /// /// If \a abstime is non-NULL, this function will return when the /// system time reaches the time specified in \a abstime if the /// condition variable doesn't get unblocked. If \a abstime is NULL /// this function will wait for an infinite amount of time for the /// condition variable to be unblocked. /// /// The current thread re-acquires the lock on \a mutex following /// the wait. /// /// @param[in] mutex /// The mutex to use in the \c pthread_cond_timedwait() or /// \c pthread_cond_wait() calls. /// /// @param[in] abstime /// An absolute time at which to stop waiting if non-NULL, else /// wait an infinite amount of time for the condition variable /// toget signaled. /// /// @param[out] timed_out /// If not NULL, will be set to true if the wait timed out, and // false otherwise. /// /// @see Condition::Broadcast() /// @see Condition::Signal() //------------------------------------------------------------------ int Wait (Mutex &mutex, const TimeValue *abstime = NULL, bool *timed_out = NULL); protected: //------------------------------------------------------------------ // Member variables //------------------------------------------------------------------ pthread_cond_t m_condition; ///< The condition variable. //------------------------------------------------------------------ /// Get accessor to the pthread condition object. /// /// @return /// A pointer to the condition variable owned by this object. //------------------------------------------------------------------ pthread_cond_t * GetCondition (); }; } // namespace lldb_private #endif // #if defined(__cplusplus) #endif
true
91925f1b89258ec68ab2f7dbedd828c9186b0888
C++
rishit-singh/Hacktoberfest2021
/Algorithms/Searching/linearSearch.cpp
UTF-8
369
3.234375
3
[]
no_license
#include<iostream> using namespace std; int linearSearch(int a[],int n,int k){ for(int i = 0; i < n; i++){ if (a[i] == k){ return i; } } return -1; } int main(){ int n; cin>>n; int a[n]; for(int i = 0; i < n; i++){ cin>>a[i]; } int k; cin>>k; cout<<linearSearch(a,n,k)<<endl; }
true
6a70ab4d1d54d4c4cd5590672052132da2bcc390
C++
kittenchilly/tf2_bot_detector
/tf2_bot_detector/Networking/GithubAPI.h
UTF-8
973
2.59375
3
[ "MIT" ]
permissive
#pragma once #include "Version.h" #include <mh/coroutine/task.hpp> #include <optional> #include <string> namespace tf2_bot_detector { class IHTTPClient; } namespace tf2_bot_detector::GithubAPI { struct NewVersionResult { bool IsReleaseAvailable() const { return m_Stable.has_value(); } bool IsPreviewAvailable() const { return m_Preview.has_value(); } bool IsError() const { return !IsReleaseAvailable() && !IsPreviewAvailable() && m_Error; } bool IsUpToDate() const { return !IsReleaseAvailable() && !IsPreviewAvailable(); } std::string GetURL() const { if (IsPreviewAvailable()) return m_Preview->m_URL; if (IsReleaseAvailable()) return m_Stable->m_URL; return {}; } struct Release { Version m_Version; std::string m_URL; }; bool m_Error = false; std::optional<Release> m_Stable; std::optional<Release> m_Preview; }; [[nodiscard]] mh::task<NewVersionResult> CheckForNewVersion(const IHTTPClient& client); }
true
5290d774a70d54fe6864ce1575d93f3bb5be3b9f
C++
lamorakde/Computer-Vision
/source/Red Color Pixels Extraction/red color pixels extraction.cpp
GB18030
1,468
2.90625
3
[]
no_license
#include "czh_binary_CV.h" #include <opencv2/core.hpp> #include <iostream> #include <fstream> using namespace std; using namespace cv; int main() { // Ϣ cout << "************************************************************************************************************************\n"; cout << "\t\t\tProgram information:\n"; cout << "\t\tThis program is going to extract the red color pixels.\n\n"; cout << "************************************************************************************************************************\n\n"; // õͼϢ cout << "Enter the input image name:"; string fileName, srcFileName; getline(cin, fileName); srcFileName = fileName + ".ppm"; Mat srcImage = imread(srcFileName); cout << "Input image name:\t" << srcFileName << endl << "Image size:\t\t" << srcImage.cols << "*" << srcImage.rows << endl << "Image pixels:\t\t" << srcImage.cols*srcImage.rows << endl << "Image type:\t\t" << srcImage.type() << endl; // ʱϢ¼㷨ʹʱ double time = static_cast<double>(getTickCount()); // ʼ㷨 Mat dst(srcImage.size(), CV_8UC1); czh_extractColor(srcImage, dst, RED); czh_imwrite(dst, fileName); // Ϣʱ time = ((double)getTickCount() - time) / getTickFrequency(); cout << "Program finished:\t" << time << " second used.\n" << endl; waitKey(); system("pause"); }
true
537ac45b37893119110895f3a1af0553b5a6af6b
C++
saucisse-royale/kudasai
/src/VulkanSwapchain.cpp
UTF-8
9,134
2.53125
3
[ "MIT" ]
permissive
#include "VulkanSwapchain.hpp" #include "VulkanContext.hpp" #include "VulkanHelper.hpp" #include <algorithm> namespace kds { VulkanSwapchain::VulkanSwapchain(VulkanContext* vulkanContext) noexcept : _vulkanContext{ vulkanContext } , _swapchain{ vkDestroySwapchainKHR, _vulkanContext->_device, _swapchain, nullptr } { } void VulkanSwapchain::init() noexcept { queryCapabilities(); pickSurfaceFormat(); setImageCount(); setSwapchainExtent(_vulkanContext->_contextConfig.windowConfig.width, _vulkanContext->_contextConfig.windowConfig.height); create(); retrieveImages(); createImageViews(); } void VulkanSwapchain::queryCapabilities() noexcept { auto& physicalDevice = _vulkanContext->_physicalDevice; auto& surface = _vulkanContext->_surface; auto result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &_capabilities); KDS_CHECK_RESULT(result, "Failed to get physical device surface capabilities\n"); uint32_t surfaceFormatsCount{}; result = vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &surfaceFormatsCount, nullptr); KDS_CHECK_RESULT(result, "Failed to get physical device surface formats\n"); _surfaceFormats.resize(surfaceFormatsCount); result = vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &surfaceFormatsCount, _surfaceFormats.data()); KDS_CHECK_RESULT(result, "Failed to get physical device surface formats\n"); uint32_t presentModesCount{}; result = vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModesCount, nullptr); KDS_CHECK_RESULT(result, "Failed to get physical device surface present modes\n"); _presentModes.resize(presentModesCount); result = vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModesCount, _presentModes.data()); KDS_CHECK_RESULT(result, "Failed to get physical device surface present modes\n"); } void VulkanSwapchain::setImageCount(uint32_t imageCount) noexcept { if (imageCount > _capabilities.maxImageCount) { std::cerr << "KDS ERROR: Tried to set swapchain image count higher than what is supported, default count is set...\n"; setImageCount(); return; } else if (imageCount < _capabilities.minImageCount) { std::cerr << "KDS ERROR: Tried to set swapchain image count lower than what is supported, default count is set...\n"; setImageCount(); return; } _imageCount = imageCount; } void VulkanSwapchain::setImageCount() noexcept { uint32_t imageCount{ _capabilities.minImageCount + 1 }; if (_capabilities.maxImageCount > 0 && imageCount > _capabilities.maxImageCount) { imageCount = _capabilities.maxImageCount; } _imageCount = imageCount; } void VulkanSwapchain::pickSurfaceFormat() noexcept { if (_surfaceFormats.size() == 0) { std::cerr << "KDS FATAL: No surface formats found, try to query swapchain capabilities first\n"; exit(1); } // Formats may be undefined, default initialize it then if (_surfaceFormats.size() == 1 && _surfaceFormats[0].format == VK_FORMAT_UNDEFINED) { _surfaceFormat = { VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }; return; } // Currently seeking only for R8G8B8A8 color space for (auto const& surfaceFormat : _surfaceFormats) { if (surfaceFormat.format == VK_FORMAT_R8G8B8A8_UNORM) { _surfaceFormat = surfaceFormat; return; } } // Default initialization if the requested format is not found _surfaceFormat = _surfaceFormats[0]; } VkPresentModeKHR VulkanSwapchain::pickPresentMode() noexcept { if (_presentModes.size() == 0) { std::cerr << "KDS FATAL: No present modes found, try to query available present modes first\n"; exit(1); } for (auto&& presentMode : _presentModes) { if (presentMode & VK_PRESENT_MODE_MAILBOX_KHR) { return presentMode; } } for (auto&& presentMode : _presentModes) { if (presentMode & VK_PRESENT_MODE_FIFO_KHR) { return presentMode; } } return _presentModes[0]; ; } void VulkanSwapchain::setSwapchainExtent(size_t width, size_t height) noexcept { size_t maxWidth{ _capabilities.maxImageExtent.width }, minWidth{ _capabilities.minImageExtent.width }; size_t maxHeight{ _capabilities.maxImageExtent.height }, minHeight{ _capabilities.minImageExtent.height }; // Resize the swapchain if the requested extend does not fit if (width > maxWidth) { width = maxWidth; } else if (width < minWidth) { width = minWidth; } if (height > maxHeight) { height = maxHeight; } else if (height < minHeight) { height = minHeight; } _swapchainExtent.width = width; _swapchainExtent.height = height; } void VulkanSwapchain::retrieveImages() noexcept { auto result = vkGetSwapchainImagesKHR(_vulkanContext->_device, _swapchain, &_imageCount, nullptr); KDS_CHECK_RESULT(result, "Failed to get swapchain images\n"); _swapchainImages.resize(_imageCount); result = vkGetSwapchainImagesKHR(_vulkanContext->_device, _swapchain, &_imageCount, _swapchainImages.data()); KDS_CHECK_RESULT(result, "Failed to get swapchain images\n"); } void VulkanSwapchain::createImageViews() noexcept { _swapchainImageViews.resize(_imageCount); for (size_t i{}; i < _imageCount; ++i) { _swapchainImageViews[i].setDeleter(vkDestroyImageView, _vulkanContext->_device, _swapchainImageViews[i], nullptr); VkImageViewCreateInfo imageViewInfo{}; imageViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; imageViewInfo.image = _swapchainImages[i]; imageViewInfo.format = _surfaceFormat.format; imageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; imageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; imageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; imageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; imageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; imageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; imageViewInfo.subresourceRange.layerCount = 1; imageViewInfo.subresourceRange.baseArrayLayer = 0; imageViewInfo.subresourceRange.levelCount = 1; imageViewInfo.subresourceRange.baseMipLevel = 0; auto result = vkCreateImageView(_vulkanContext->_device, &imageViewInfo, nullptr, _swapchainImageViews[i].reset()); KDS_CHECK_RESULT(result, "Failed to create an image view."); } } void VulkanSwapchain::create() noexcept { auto& surface = _vulkanContext->_surface; auto& deviceQueueConfig = _vulkanContext->_contextConfig.deviceQueueConfig; std::vector<uint32_t> indices{}; indices.push_back(deviceQueueConfig.graphicsQueueInfos.index); // We want only UNIQUE indices in the array if (std::find(indices.begin(), indices.end(), deviceQueueConfig.computeQueueInfos.index) == indices.end()) { indices.push_back(deviceQueueConfig.computeQueueInfos.index); } if (std::find(indices.begin(), indices.end(), deviceQueueConfig.transferQueueInfos.index) == indices.end()) { indices.push_back(deviceQueueConfig.transferQueueInfos.index); } if (std::find(indices.begin(), indices.end(), deviceQueueConfig.sparseBindingQueueInfos.index) == indices.end()) { indices.push_back(deviceQueueConfig.sparseBindingQueueInfos.index); } VkSwapchainCreateInfoKHR swapchainInfo{}; swapchainInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; swapchainInfo.surface = surface; swapchainInfo.minImageCount = _capabilities.minImageCount; swapchainInfo.imageFormat = _surfaceFormat.format; swapchainInfo.imageColorSpace = _surfaceFormat.colorSpace; swapchainInfo.imageExtent = _swapchainExtent; swapchainInfo.imageArrayLayers = 1; swapchainInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; swapchainInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swapchainInfo.presentMode = pickPresentMode(); swapchainInfo.clipped = VK_TRUE; swapchainInfo.preTransform = _capabilities.currentTransform; if (indices.size() == 1) { swapchainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } else { swapchainInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; swapchainInfo.queueFamilyIndexCount = indices.size(); swapchainInfo.pQueueFamilyIndices = indices.data(); } swapchainInfo.oldSwapchain = _swapchain; VkSwapchainKHR newSwapchain{}; auto result = vkCreateSwapchainKHR(_vulkanContext->_device, &swapchainInfo, nullptr, &newSwapchain); KDS_CHECK_RESULT(result, "Failed to create a swapchain."); _swapchain = newSwapchain; } void VulkanSwapchain::recreate() noexcept { setSwapchainExtent(_vulkanContext->_contextConfig.windowConfig.width, _vulkanContext->_contextConfig.windowConfig.height); create(); } } // namespace kds
true
6185a63c9108b8ae1345ab6c3dbc35f1814e1529
C++
Ranjiahao/DocumentSearcher
/searcher/searcher.h
UTF-8
1,731
2.8125
3
[]
no_license
#pragma once #include <stdint.h> #include <string> #include <vector> #include <unordered_map> #include "cppjieba/Jieba.hpp" namespace searcher { /* * 索引模块 * */ // 用于构建正排索引 struct DocInfo { int64_t doc_id; std::string title; std::string url; std::string content; }; // 用于构建倒排索引 struct Weight { int64_t doc_id; int weight; std::string word; }; // 倒排拉链 typedef std::vector<Weight> InvertedList; // 表示整个索引结构,并向外部提供API class Index { public: Index(); // 查正排,返回指针,NULL表示未找到 const DocInfo* GetDocInfo(int64_t doc_id); // 查倒排,返回指针,NULL表示未找到 const InvertedList* GetInvertedList(const std::string& key); // 构建索引 bool Build(const std::string& input_path); // 分词函数 void CutWord(const std::string& input, std::vector<std::string>* output); private: // 构造正排索引 DocInfo* BuildForward(const std::string& line); // 构造倒排索引 void BuildInverted(const DocInfo& doc_info); // 正排索引,数组下标就对应到doc_id std::vector<DocInfo> forward_index; // 倒排索引,使用一个hash表示映射关系 std::unordered_map<std::string, InvertedList> inverted_index; cppjieba::Jieba jieba; }; /* * 搜索模块 * */ class Searcher { public: Searcher() : index(new Index()) {} bool Init(const std::string& input_path); bool Search(const std::string& query, std::string* results); private: Index* index; // 生成文章描述 std::string GenerateDesc(const std::string& content, const std::string& word); }; } // namespace searcher
true
5fd067b1889f4fdeb116eeabc7d6968992cc1c90
C++
sjhuang26/competitive-programming
/usaco-trainer/fact4.cpp
UTF-8
539
2.578125
3
[]
no_license
/* ID: sjhuang1 PROG: fact4 LANG: C++11 */ #include<iostream> #include<fstream> #include<vector> using namespace std; int main(){ freopen("fact4.in","r",stdin); freopen("fact4.out","w",stdout); int N;cin>>N; int lastd=1; int a=0,b=0; for(int i=1;i<=N;++i){ int x=i; while(x%2==0)x/=2,++a; while(x%5==0)x/=5,++b; lastd=(lastd*x)%10; } if(a>b)for(int i=0;i<a-b;++i)lastd=(lastd*2)%10; if(b>a)for(int i=0;i<b-a;++i)lastd=(lastd*5)%10; cout<<lastd<<'\n'; return 0; }
true
1fd2ff86934a9988ef8f302f69bc7cf6fc93027c
C++
ishibustim/rd_view
/src/pnm_display.cc
UTF-8
2,644
2.96875
3
[]
no_license
#include <fstream> #include <iomanip> #include <sstream> #include <string> #include "color.h" #include "pnm_display.h" #include "rd_error.h" using std::string; using std::ofstream; using std::ostringstream; using std::setfill; using std::setw; static color** pixelGrid; static int frameNumber; static color bgColor(0, 0, 0); extern string display_name; extern int display_xSize; extern int display_ySize; int pnm_init_display(void) { pixelGrid = new color*[display_xSize]; for(int i = 0; i < display_xSize; i++) { pixelGrid[i] = new color[display_ySize]; }//end for return RD_OK; }//end pnm_init_display int pnm_end_display(void) { for(int i = 0; i < display_xSize; i++) { delete pixelGrid[i]; }//end for delete pixelGrid; return RD_OK; }//end pnm_end_display int pnm_init_frame(int frame) { frameNumber = frame; for(int i = 0; i < display_xSize; i++) { for(int j = 0; j < display_ySize; j++) { pixelGrid[i][j].setColor(bgColor); }//end for }//end for return RD_OK; }//end pnm_init_frame int pnm_end_frame(void) { ostringstream filename; filename.str(); filename << display_name << "-" << setfill('0') << setw(4) << frameNumber << ".ppm"; ofstream outFile; outFile.open(filename.str().c_str()); if(outFile) { outFile << "P6\n" << display_xSize << " " << display_ySize << "\n255\n"; for(int y = 0; y < display_ySize; y++) { for(int x = 0; x < display_xSize; x++) { outFile.put(pixelGrid[x][y].red * 255.999); outFile.put(pixelGrid[x][y].green * 255.999); outFile.put(pixelGrid[x][y].blue * 255.999); }//end for }//end for }//end if outFile.close(); return RD_OK; }//end pnm_end_frame int pnm_write_pixel(int x, int y, const float rgb[]) { float r = rgb[0]; float g = rgb[1]; float b = rgb[2]; if(x >= 0 && x < display_xSize && y >= 0 && y < display_ySize) pixelGrid[x][y].setColor(r, g, b); return RD_OK; }//end pnm_write_pixel int pnm_read_pixel(int x, int y, float rgb[]) { if(x >= 0 && x < display_xSize && y >= 0 && y < display_ySize) { rgb[0] = pixelGrid[x][y].red; rgb[1] = pixelGrid[x][y].green; rgb[2] = pixelGrid[x][y].blue; }//end if return RD_OK; }//end pnm_read_pixel int pnm_set_background(const float rgb[]) { float r = rgb[0]; float g = rgb[1]; float b = rgb[2]; bgColor.setColor(r, g, b); return RD_OK; }//end pnm_set_background int pnm_clear(void) { for(int i = 0; i < display_xSize; i++) { for(int j = 0; j < display_ySize; j++) { pixelGrid[i][j].setColor(bgColor); }//end for }//end for return RD_OK; }//end pnm_clear
true
5296f8416cd5e59b15845e173876fedb81f98171
C++
webfrogs/leetcode-solutions
/448/448.cpp
UTF-8
781
3.34375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> result; if (nums.empty()) { return result; } int n = nums.size(); for (int i=0; i < n; i++) { while (nums[nums[i]-1] != nums[i]) { swap(nums[nums[i]-1], nums[i]); } } for (int i=0; i<n; i++) { if (nums[i] != i+1) { result.push_back(i+1); } } return result; } }; int main(int argc, char* argv[]) { vector<int> input({4,3,2,7,8,2,3,1}); Solution sol; for (auto i: sol.findDisappearedNumbers(input)) { cout<<i<<","; } return 0; }
true
63ad6a241e0ea3425b458e6fecf808d59d06b7d3
C++
cpprev/Big-num-calculator
/src/main.cc
UTF-8
2,586
2.921875
3
[]
no_license
#include <iostream> #include <vector> #include "lexer/lexing.hh" #include "lexer/token.hh" #include "parser/parsing.hh" #include "parser/ast_visit.hh" #include "parser/ast.hh" #include "utils/input_error.hh" #include "utils/string_op.hh" #include "utils/options.hh" /// 'base' Global variable int base = 10; int main (int argc, char *argv[]) { /// Options parsing Options options(argc, argv); base = options.base; /// Input error handling std::string error_msg; if (not is_valid_operation(options.operation.c_str(), error_msg)) { std::cout << "[Input Error] " << error_msg << std::endl; return 1; } while (true) { std::string operation; if (options.interactive) { std::getline (std::cin, operation); if (operation == "q" or operation == "quit" or operation == "stop") { std::cout << "Quitting\n"; break; } } else { /// The operation string operation = options.operation; } if (not is_valid_base(operation.c_str(), error_msg)) { std::cout << "[Input Error] " << error_msg << std::endl; if (not options.interactive) return 1; else continue; } /// Remove useless characters (spaces, ...) remove_useless_characters(operation); /// Puts 0 before negative numbers to make it easier later on add_zeroes(operation); /// Lexing std::vector<lexer::t_token> tokens = lexer::lex(operation); /// AST Building std::shared_ptr<parser::t_ast> ast = parser::parse(tokens, error_msg); /// Parsing error if (not ast) { std::cout << "[Parsing Error] " << error_msg << std::endl; if (not options.interactive) return 1; else continue; } /// Logging if (options.verbose) { parser::pretty_print_ast2(ast, 80); //parser::pretty_print_ast(ast, 0, 5); /*lexer::pretty_print_tokens(tokens); std::cout << operation << std::endl;*/ } /// AST Visiting visiter::visit(ast); /// Final logging std::string result = ast->get_token().get_value(); remove_zeroes(result); std::cout << "\033[1;36m" << "= " << result << "\033[0m" << std::endl; if (not options.interactive) break; } return 0; }
true
fc3608dc7d26f924c5025fc7d2fa5649dfa619d4
C++
19MH1A0536/Programs
/main (3).cpp
UTF-8
728
3.25
3
[]
no_license
/****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <iostream> using namespace std; int main() { int num,count=0; cout<<"enter n value"; cin>>num; for(int i=1;i<num/2;i++) { if(num%i==0) { count++; } } if(count==1) { cout<<num<<" is PRIME number"; } else { cout<<num<<" is NOT PRIME number"; } return 0; }
true
9c6d01ebe33c94318549a560fedc401d35df5a2a
C++
OpenHardware23/Contest-archive
/UVA Online Judge/10139 - Factovisors.cpp
UTF-8
974
2.921875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; vector<pii> canonica(int n) { vector<pii> out; for (int i = 2; i * i <= n; i++) if (!(n % i)) { int e = 0; while (!(n % i)) { n /= i; e++; } out.push_back(pii(i, e)); } if (n != 1) out.push_back(pii(n, 1)); return out; } bool divisible(int n, vector<pii> v) { for (int i = 0; i < v.size(); i++) { int s = 0; for (long long p = v[i].first; p <= n; p *= v[i].first) s += n / p; if (s < v[i].second) return false; } return true; } int main() { ios_base::sync_with_stdio(0); cin.tie(); int m, n; while (cin >> n >> m) { if (m && (n >= m || divisible(n, canonica(m)))) cout << m << " divides " << n << "!\n"; else cout << m << " does not divide " << n << "!\n"; } }
true
6858c30c02f3481c4ca7f92efe37b918b2735b95
C++
AnuragJain23/other-problems
/sudokusolver.cpp
UTF-8
1,927
2.96875
3
[]
no_license
/****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <bits/stdc++.h> using namespace std; bool canplace(int sudoku[][9],int i,int j,int num,int n) { for(int digit=0;digit<n;digit++) { if(sudoku[digit][j]==num || sudoku[i][digit]==num) return false; } int k=sqrt(n); int sx=(i/k)*k; int sy=(j/k)*k; for(int x=sx;x<sx+k;x++) { for(int y=sy;y<sy+k;y++) { if(sudoku[x][y]==num) return false; } } return true; } bool solvesudoku(int sudoku[][9],int i,int j,int n) { if(i==n) { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cout<<sudoku[i][j]<<", "; } cout<<endl; } return true; } if(j==n) return solvesudoku(sudoku,i+1,0,n); if(sudoku[i][j]!=0) return solvesudoku(sudoku,i,j+1,n); for(int num=1;num<=n;num++) { if(canplace(sudoku,i,j,num,n)) { sudoku[i][j]=num; bool aagesolvehoga=solvesudoku(sudoku,i,j+1,n); if(aagesolvehoga==true) return true; } } sudoku[i][j]=0; return false; } int main() { int sudoku[9][9]= { {5,3,0,0,7,0,0,0,0}, {6,0,0,1,9,5,0,0,0}, {0,9,8,0,0,0,0,6,0}, {8,0,0,0,6,0,0,0,3}, {4,0,0,8,0,3,0,0,1}, {7,0,0,0,2,0,0,0,6}, {0,6,0,0,0,0,2,8,0}, {0,0,0,4,1,9,0,0,5}, {0,0,0,0,8,0,0,7,9}, }; solvesudoku(sudoku,0,0,9); return 0; }
true
579fad4769269dc048c02b6c1a9a6e56dcc873f8
C++
mohistH/sqlite3_database_helper
/databaseHelper/hloghelper.cpp
UTF-8
2,697
2.75
3
[]
no_license
#include "hloghelper.h" #include <QObject> #include <QDir> #include <QApplication> #include <cstdarg> #include <QByteArray> HLogHelper::HLogHelper() { m_FileLogName = QString(""); } // 初始化创建文件并打开文件 int HLogHelper::HInit(QString strFilePre) { int len = strFilePre.length(); QString fileName(""); // 设置文件名 // 1、若strFilePre不为空 if (0 < len) { // 获取当前日期 QString date = m_DateTime.currentDateTime().toString("yyyy_MM_dd_hh_mm_ss_zzz"); fileName = strFilePre + QString("_") + date; } else { // QString date = m_DateTime.currentDateTime().toString("yyyy_MM_dd_hh_mm_ss_zzz"); fileName = date; } m_FileLogName = fileName + QString("_.log"); // 2、打开文件 // 若当前exe所在目录下不存在 HLog文件夹,则创建 QString logPath = QApplication::applicationDirPath() + QString("/HLog/"); QDir dir(logPath); if (false == dir.exists()) { dir.mkdir(logPath); } // 构造文件 m_FileLogName = logPath + m_FileLogName; m_File.setFileName(m_FileLogName); bool openFlag = m_File.open(QIODevice::Text | QIODevice::Truncate | QIODevice::WriteOnly | QIODevice::Append); if (false == openFlag) { return 1; } m_LogTextStream.setDevice(&m_File); return 0; } // 关闭文件 int HLogHelper::HUnInit() { bool isExist = m_File.exists(m_FileLogName); // 若不存在 if (false == isExist) { return 1; } // 文件存在,检查文件是否已经打开 bool hasOepned = m_File.isOpen(); // 文件打开了 if (true == hasOepned) { m_File.flush(); m_File.close(); } return 0; } // 日志记录前带日期 int HLogHelper::HLogTime(QString str...) { // 获取当前日期 QString date = m_DateTime.currentDateTime().toString("yyyy_MM_dd hh_mm_ss_zzz:"); QByteArray ba = (date + str).toLocal8Bit(); char *pArr = ba.data(); va_list al; va_start(al, pArr); QString strResult = QString::vasprintf(pArr, al); va_end(al); m_LogTextStream << strResult << endl; m_LogTextStream.flush(); return 0; } // 日志前不带日期 int HLogHelper::HLog(QString str...) { QByteArray ba = str.toLocal8Bit(); char *pArr = ba.data(); va_list al; va_start(al, pArr); QString strResult = QString::vasprintf(pArr, al); va_end(al); m_LogTextStream << strResult << endl; m_LogTextStream.flush(); return 0; }
true
dee686a4ef382d1d65f8f0e76810f31f7ca39d06
C++
rahulmak92/Cplusplus-practise
/CPPPractise_Seaman_Problem/SetOfIntegers.cpp
UTF-8
1,972
3.84375
4
[]
no_license
#include "SetOfIntegers.h" #include<iostream> using namespace std; Set::Set() { count=0; size=0; elements= new int[size]; } Set::Set(int given_size) { size=given_size; count=0; elements= new int[size]; } Set::Set(const Set &obj) //copy constructor { count=obj.count; size=obj.size; elements=new int[size]; for(int i=0;i<size;i++) { elements[i]=obj.elements[i]; } } void Set::insert(int val) { if(!check(val)) { if(count<=size) { elements[count]=val; count++; } else if(count>size) { cout<<"Size exceeded!!"<<endl; } } else { cout<<endl<<val<<" already exists!"<<endl; } } bool Set::check(int val) const { int cnt=0; while(cnt<size) { if(elements[cnt]==val) { return true; } cnt++; } return false; } void Set::displaySet() { cout<<endl; cout<<"there are "<<count <<" elements in Set!"; cout<<endl<<"< "; for(int i=0;i<count;i++) { cout<<elements[i]<<","; } cout<<">"<<endl; } Set::~Set() { delete [] elements; } Set Set::operator+(const Set &right) { int new_size=size+right.size; Set result(new_size); for(int i=0;i<count;i++) { result.insert(elements[i]); } for(int i=0;i<right.count;i++) { result.insert(right.elements[i]); } return result; } Set Set::operator=(const Set &right) { int *old=elements; size=right.size; elements=new int[size]; count=right.count; for(int i=0;i<right.size;i++) { elements[i]=right.elements[i]; } delete [] old; return *this; } Set Set::operator*(const Set &right) { Set result(right.size); for(int j=0;j<right.size;j++) { for(int i=0;i<size;i++) { if(elements[i]==right.elements[j]) { result.insert(right.elements[j]); } } } return result; } Set Set::operator -(const Set &right) { Set result(size); Set temp = *this * right; for(int i=0;i<temp.size;i++) { for(int j=0;j<size;j++) { if(elements[j]!=temp.elements[i]) { result.insert(elements[j]); } } } delete [] temp.elements; return result; }
true
a04a105899ba073a361dc087f80e8e8c48a77859
C++
zhoutong12589/u_log
/queue_T.h
UTF-8
1,221
2.984375
3
[]
no_license
#include <iostream> #include <list> #include <thread> #include <mutex> #ifndef _H_QUEUE_T_ #define _H_QUEUE_T_ namespace COMM { using namespace std; static mutex g_queue_mutex; //队列模板 template<class T> class CQueue_T { public: CQueue_T() { m_max_len = 1024; } ~CQueue_T(){} int put(T* t) { //提供线程互斥 std::lock_guard<std::mutex> lock(g_queue_mutex); if(m_queue.size() < m_max_len) { m_queue.push_back(t); return 0; } else { return -1; } }; T* get() { std::lock_guard<std::mutex> lock(g_queue_mutex); if(m_queue.size() > 0) { T* t = m_queue.front(); m_queue.pop_front(); return t; } else { return nullptr; } }; int length() { std::lock_guard<std::mutex> lock(g_queue_mutex); return m_queue.size(); }; int set_max_len(int max = 1024) { m_max_len = max; return 0; } private: list<T*> m_queue; int m_max_len; //队列最大长度 }; } #endif //_H_QUEUE_T_
true
84ee9cd6895ff9a36e8a9047ddfcb26a08e6f5e2
C++
yichizhng/CS174
/marching.cc
UTF-8
7,156
2.984375
3
[]
no_license
// (Crude) implementation of fast marching #include <queue> #include <vector> #include <limits> #include <cmath> #include <cfloat> #include "main.hh" #include <iostream> using namespace std; extern int nvertices, ntriangles; extern double *pos; extern Triangle **tris; extern vector<int> vertset; class vert_dist { public: int v; // Corresponding vertex double dist; bool operator<(const vert_dist &rhs) const { return dist>rhs.dist; // Yes, I know that's reversed; we want the smallest } vert_dist(int x, double d) : v(x),dist(d) {} }; vector<vert_dist> *edges; vector<int> *triadjs; vector<bool> alive; static inline double len(double x, double y, double z) { return sqrt( (x*x) + (y*y) + (z*z) ); } void setupmarch() { // Sets up the edge vector alive = vector<bool>(nvertices, false); edges = new vector<vert_dist>[nvertices]; triadjs = new vector<int>[nvertices]; for (int i = 0; i < ntriangles; ++i) { Triangle *tri = tris[i]; triadjs[tri->vertices[0]].push_back(i); triadjs[tri->vertices[1]].push_back(i); triadjs[tri->vertices[2]].push_back(i); double dx1, dx2, dy1, dy2, dz1, dz2; dx1 = pos[3*tri->vertices[1]] - pos[3*tri->vertices[0]]; dy1 = pos[3*tri->vertices[1]+1] - pos[3*tri->vertices[0]+1]; dz1 = pos[3*tri->vertices[1]+2] - pos[3*tri->vertices[0]+2]; dx2 = pos[3*tri->vertices[2]] - pos[3*tri->vertices[0]]; dy2 = pos[3*tri->vertices[2]+1] - pos[3*tri->vertices[0]+1]; dz2 = pos[3*tri->vertices[2]+2] - pos[3*tri->vertices[0]+2]; // There are plenty of ways of calculating the cotangents from here, // mostly involving trigonometric identities. Since we're going to need // side lengths anyway, let's use those. double a = len(dx1-dx2, dy1-dy2, dz1-dz2); double b = len(dx2, dy2, dz2); double c = len(dx1, dy1, dz1); // Add the six (!) edges edges[tri->vertices[0]].push_back(vert_dist(tri->vertices[2],b)); edges[tri->vertices[0]].push_back(vert_dist(tri->vertices[1],c)); edges[tri->vertices[1]].push_back(vert_dist(tri->vertices[0],c)); edges[tri->vertices[1]].push_back(vert_dist(tri->vertices[2],a)); edges[tri->vertices[2]].push_back(vert_dist(tri->vertices[1],a)); edges[tri->vertices[2]].push_back(vert_dist(tri->vertices[0],b)); } } priority_queue<vert_dist> q; void march(double *dists) { // Uses the fast marching algorithm to calculate distances // outputting into dists for (int i = 0; i < nvertices; ++i) { dists[i] = numeric_limits<double>::infinity(); } for (int i = 0; i < vertset.size(); ++i) { dists[vertset[i]] = 0; // And update all adjacent vertices; these are now "close" for (int j = 0; j < edges[i].size(); ++j) { if (edges[i][j].dist < dists[edges[i][j].v]) dists[edges[i][j].v] = edges[i][j].dist; } alive[vertset[i]] = true; } for (int i = 0; i < nvertices; ++i) { if ((dists[i] != 0) && (dists[i] != numeric_limits<double>::infinity())) { q.push(vert_dist(i,dists[i])); //cerr << i << endl; } } while(!q.empty()) { vert_dist x = q.top(); q.pop(); alive[x.v] = true; cerr << x.v << ' ' << x.dist << endl; // Get all adjacent _triangles_ and update through them for (int i = 0; i < triadjs[x.v].size(); ++i) { Triangle *tri = tris[triadjs[x.v][i]]; if (alive[tri->vertices[0]] && alive[tri->vertices[1]] && alive[tri->vertices[2]]) continue; // This triangle is already done double dx1, dx2, dy1, dy2, dz1, dz2; dx1 = pos[3*tri->vertices[1]] - pos[3*tri->vertices[0]]; dy1 = pos[3*tri->vertices[1]+1] - pos[3*tri->vertices[0]+1]; dz1 = pos[3*tri->vertices[1]+2] - pos[3*tri->vertices[0]+2]; dx2 = pos[3*tri->vertices[2]] - pos[3*tri->vertices[0]]; dy2 = pos[3*tri->vertices[2]+1] - pos[3*tri->vertices[0]+1]; dz2 = pos[3*tri->vertices[2]+2] - pos[3*tri->vertices[0]+2]; // There are plenty of ways of calculating the cotangents from here, // mostly involving trigonometric identities. Since we're going to need // side lengths anyway, let's use those. double a = len(dx1-dx2, dy1-dy2, dz1-dz2); double b = len(dx2, dy2, dz2); double c = len(dx1, dy1, dz1); // There's some casework here which we eliminate by sorting everything // by distance int cpy[3]; cpy[0] = tri->vertices[0]; cpy[1] = tri->vertices[1]; cpy[2] = tri->vertices[2]; if (cpy[0] < cpy[1]) { if (cpy[1] < cpy[2]) { // Already sorted } else if (cpy[0] < cpy[2]) { // 0,2,1 double tmp = c; c = b; b = tmp; tri->vertices[1] = cpy[2]; tri->vertices[2] = cpy[0]; } else { // 2,0,1 double tmp = a; a = c; c = b; b = tmp; tri->vertices[0] = cpy[2]; tri->vertices[1] = cpy[0]; tri->vertices[2] = cpy[1]; } } else { // 1,0 if (cpy[0] < cpy[2]) { // 1,0,2 double tmp = a; a = b; b = tmp; tri->vertices[1] = cpy[0]; tri->vertices[0] = cpy[1]; } // In the other cases our new point is the farthest and there's no // point in updating :) else { continue; } } if ( (!alive[tri->vertices[2]]) && dists[tri->vertices[1]] != numeric_limits<double>::infinity()) { double costheta = (a*a + b*b - c*c)/(2*a*b); if (costheta>1) costheta=1; if (costheta<0) // Fudging for right triangles; if it's _actually_ // negative you'll get what you deserve costheta = DBL_MIN; double sintheta = sqrt(1-costheta*costheta); bool topush = (dists[tri->vertices[2]] == numeric_limits<double>::infinity()); // Using the terminology from Sethian and Kimmel, we now // have that A is vertices[0], B is vertices[1], and C // is vertices[2] // Theta is the angle at 2 double u = dists[tri->vertices[1]] - dists[tri->vertices[0]]; double t; double aa = a*a + b*b - 2*a*b*costheta; double bb = 2*b*u*(a*costheta-b); double cc = b*b*(u*u-a*a*sintheta*sintheta); if (bb*bb >= 4*aa*cc) { t = (sqrt(bb*bb - 4*aa*cc) - bb) / (2*aa); // Check that our conditions for t hold (that the update // occurs from inside the triangle) if ((u<t) && (a*costheta < (b*(t-u)/t)) && ((b*(t-u)/t) < (a/costheta))) { // Update is valid if (t < dists[tri->vertices[2]]) dists[tri->vertices[2]] = t; } } // Try the other two updates too while we're at it if (dists[0] + b < dists[tri->vertices[2]]) { dists[tri->vertices[2]] = dists[0] + b; } if (dists[1] + a < dists[tri->vertices[2]]) { dists[tri->vertices[2]] = dists[1] + a; } if (topush) q.push(vert_dist(tri->vertices[2],dists[tri->vertices[2]])); } else { // Since we have two infinities what we need to do is obvious dists[tri->vertices[1]] = dists[tri->vertices[0]] + c; dists[tri->vertices[2]] = dists[tri->vertices[0]] + b; q.push(vert_dist(tri->vertices[1], dists[tri->vertices[1]])); q.push(vert_dist(tri->vertices[2], dists[tri->vertices[2]])); } tri->vertices[0] = cpy[0]; tri->vertices[1] = cpy[1]; tri->vertices[2] = cpy[2]; } } /* for (int i = 0; i < nvertices; ++i) { cerr << i << dists[i] << endl; } */ }
true
e725361b85eb21341feba4b4a7edba5b609ac204
C++
danielalpert/ASM-Tetris
/Final/Final/data.inc
UTF-8
2,713
2.671875
3
[]
no_license
.data Point STRUCT ;a point with coordinates x, y x DWORD ? y DWORD ? Point ends Tetromino STRUCT ;a tetromino of type (kind), position (pos), and orientation (rot) kind DWORD ? ;kind includes a number representing a type of tetromino: ;1-O 2-I 3-T 4-L 5-J 6-S 7-Z pos Point<> rot DWORD 1 ;rot contains a number representing an orientation: ;1-north 2-east 3-south 4-west Tetromino ends Row STRUCT ;a row including an array of 10 blocks blocks DWORD 10 DUP(0) ;each block contains number representing a type of mino: ;0-empty 1-yellow 2-blue 3-pink 4-orange 5-purple 6-green 7-red 8-surface (not drawn, just for collision) Row ends Bag STRUCT ;a bag containing a random order of the 7 tetrominos (tetrs), the current tetromino in the bag (curr) ;and a pointer to the next bag's location in the RAM (nextBag) tetrs DWORD 7 DUP(?) ;each tetr contains a number representing type of tetromino curr DWORD 0 nextBag DWORD ? Bag ends redMinoLoc byte "C:\Users\Daniel\source\repos\Final\Final\Minos\Red.bmp",0 greenMinoLoc byte "C:\Users\Daniel\source\repos\Final\Final\Minos\Green.bmp",0 blueMinoLoc byte "C:\Users\Daniel\source\repos\Final\Final\Minos\Blue.bmp",0 yellowMinoLoc byte "C:\Users\Daniel\source\repos\Final\Final\Minos\Yellow.bmp",0 pinkMinoLoc byte "C:\Users\Daniel\source\repos\Final\Final\Minos\Pink.bmp",0 orangeMinoLoc byte "C:\Users\Daniel\source\repos\Final\Final\Minos\Orange.bmp",0 purpleMinoLoc byte "C:\Users\Daniel\source\repos\Final\Final\Minos\Purple.bmp",0 redLineLoc byte "C:\Users\Daniel\source\repos\Final\Final\Images\red_line.bmp",0 gridLineHorLoc byte "C:\Users\Daniel\source\repos\Final\Final\Images\grid_line_horizontal.bmp",0 gridLineVerLoc byte "C:\Users\Daniel\source\repos\Final\Final\Images\grid_line_vertical.bmp",0 switchLoc byte "C:\Users\Daniel\source\repos\Final\Final\Images\switch.bmp",0 korobeinikiLoc byte "C:\Users\Daniel\source\repos\Final\Final\Korobeiniki.wav",0 lockLoc byte "C:\Users\Daniel\source\repos\Final\Final\Sounds\Lock.wav",0 clearLoc byte "C:\Users\Daniel\source\repos\Final\Final\Sounds\LineClear.wav",0 moveLoc byte "C:\Users\Daniel\source\repos\Final\Final\Sounds\Move.wav",0 rotLoc byte "C:\Users\Daniel\source\repos\Final\Final\Sounds\Rotate.wav",0 gameOverLoc byte "C:\Users\Daniel\source\repos\Final\Final\Sounds\GameOver.wav",0 redLine Img<> gridLineHor Img<> gridLineVer Img<> switchi Img<> minos Img 7 DUP(<>) matrix Row 22 DUP(<>) tetr Tetromino<> bag1 Bag<> bag2 Bag<> currentBag Bag<> gameFlowThrId DWORD ? keyHandThrId DWORD ? randomcntThrId DWORD ? bgMusicThrId DWORD ? fallTime DWORD ? gameOver DWORD ? temp DWORD ? falltimedec DWORD ?
true
38515afb22edec0a098bb5493e21d9bda602b180
C++
samchon/framework
/cpp/samchon/templates/parallel/ParallelClientArrayMediator.hpp
UTF-8
1,489
2.65625
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include <samchon/API.hpp> #include <samchon/templates/parallel/ParallelSystemArrayMediator.hpp> #include <samchon/templates/external/ExternalClientArray.hpp> namespace samchon { namespace templates { namespace parallel { /** * Mediator of Parallel Processing System, a server accepting slave clients. * * The {@link ParallelClientArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} * class, opening a server accepting {@link ParallelSystem parallel clients} as a **master**. * * Extends this {@link ParallelClientArrayMediator} and overrides below methods creating child {@link ParallelSystem} * object. After the overridings, open server with {@link open open()} method and connect to * {@link IParallelServer parallel servers} through the {@link connect connect()} method. If you want this server to * follow web-socket protocol, then overrides {@link WebServer} virtually. * * #### [Inherited] {@link ParallelSystemArrayMediator} * @copydetails parallel::ParallelSystemArrayMediator */ template <class System = ParallelSystem> class ParallelClientArrayMediator : public ParallelSystemArrayMediator<System>, public external::ExternalClientArray<System> { public: /** * Default Constructor. */ ParallelClientArrayMediator() : ParallelSystemArrayMediator<System>(), external::ExternalClientArray<System>() { }; virtual ~ParallelClientArrayMediator() = default; }; }; }; };
true
78dda9e57d19cc749c33c0afd9bc72f5be4c4869
C++
anik-chy/OnlineJudges
/URI/MATHEMATICS/UOJ_1214 Above Average.cpp
UTF-8
793
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define ll long long int #define pb push_back int main() { int c; vector<int> vct; cin >> c; while(c--) { int n, temp, sum = 0, counter = 0; cin >> n; for(int i=0;i<n;i++) { cin >> temp; vct.pb(temp); sum += temp; } double avg = (double)sum/(double)n; for(int i=0;i<n;i++) { if(vct[i]>avg) { counter++; } } double result = (((double)counter*100.0)/(double)n); //cout<<"Avg: " << avg <<"\tCounter: "<< counter <<"\tResult: "<< result<< endl; cout << fixed << setprecision(3) << result <<"%"<<endl; vct.clear(); } return 0; }
true
fe5b2f96862d6bebffbe38b878f55ad34e27355b
C++
aldebaran/libqi
/tests/qi/test_eventloop.cpp
UTF-8
8,865
2.875
3
[]
permissive
#include <condition_variable> #include <mutex> #include <gtest/gtest.h> #include <qi/eventloop.hpp> #include <src/eventloop_p.hpp> #include <ka/macro.hpp> #include "test_future.hpp" int ping(int v) { if (v>= 0) return v; else throw std::runtime_error("Invalid argument "); } static const auto gEventLoopName = "TestEventLoop"; TEST(EventLoop, EventLoopCanPostWithDuration) { std::mutex m; std::condition_variable cv; auto cb = [&] { std::unique_lock<std::mutex> l{m}; cv.notify_one(); }; qi::EventLoop loop{ gEventLoopName, 1 }; { std::unique_lock<std::mutex> l{m}; KA_WARNING_PUSH() KA_WARNING_DISABLE(4996, deprecated-declarations) // ignore use of deprecated overloads. loop.post(cb, qi::MilliSeconds{1}); KA_WARNING_POP() ASSERT_EQ(std::cv_status::no_timeout, cv.wait_for(l, std::chrono::milliseconds{100})); } } TEST(EventLoop, EventLoopCanAsyncDelay) { qi::EventLoop loop{ gEventLoopName, 1 }; loop.asyncDelay([] {}, qi::MilliSeconds{ 1 }).value(100); } TEST(EventLoop, asyncNoop) { qi::async([]{}).value(100); } TEST(EventLoop, async) { static const qi::MilliSeconds SMALL_CALL_DELAY{ 20 }; static const qi::MilliSeconds BIG_CALL_DELAY{ 200 }; static const int VALID_VALUE = 42; static const auto makeValidValue = [] { return 42; }; static const auto makeError = [] { throw std::runtime_error("Voluntary Fail"); }; qi::EventLoop& el = *qi::getEventLoop(); { auto f = el.asyncDelay(makeValidValue, BIG_CALL_DELAY); EXPECT_FALSE(f.isFinished()); f.wait(); EXPECT_FALSE(f.hasError()); EXPECT_EQ(f.value(), VALID_VALUE); } { auto f = el.asyncDelay(makeValidValue, BIG_CALL_DELAY); EXPECT_FALSE(f.isFinished()); EXPECT_NO_THROW(f.cancel()); EXPECT_EQ(f.wait(), qi::FutureState_Canceled); } { auto f = el.asyncDelay(makeError, BIG_CALL_DELAY); EXPECT_FALSE(f.isFinished()); f.wait(); EXPECT_TRUE(f.hasError()); } // We cannot guarantee the minimum delay that an async call will take, but we can guarantee that it will // be systematically after the specified delay. { const auto beginTime = qi::SteadyClock::now(); auto callTime = beginTime; auto f = el.asyncDelay([&]{ callTime = qi::SteadyClock::now(); }, SMALL_CALL_DELAY); f.wait(); // This test will timeout if it's not called in a reasonable time EXPECT_TRUE(f.isFinished()); const auto timeUntilCall = callTime - beginTime; EXPECT_TRUE(timeUntilCall >= SMALL_CALL_DELAY); } { const auto beginTime = qi::SteadyClock::now(); auto callTime = beginTime; auto f = el.asyncAt([&] { callTime = qi::SteadyClock::now(); }, qi::SteadyClock::now() + SMALL_CALL_DELAY); f.wait(); // This test will timeout if it's not called in a reasonable time EXPECT_TRUE(f.isFinished()); const auto timeUntilCall = callTime - beginTime; EXPECT_TRUE(timeUntilCall >= SMALL_CALL_DELAY); } qi::async([]{}).value(); } TEST(EventLoop, asyncFast) { qi::EventLoop* el = qi::getEventLoop(); for (int i = 0; i < 10; ++i) { qi::Future<int> f = el->async(get42); f.wait(); } } // Algorithm: // 1) Set the eventloop maximum number of tries after max thread count // has been reached. // 2) Register a callback that will be run when this maximum number of // timeouts has been reached, and that will raise a flag. // 3) Spam the eventloop until the flag is raised, and record the distinct // successive thread counts. // 4) Check that the thread count has raised up to the max. TEST(EventLoopAsio, CannotGoAboveMaximumThreadCount) { using namespace qi; const int minThreadCount = 1; const int maxThreadCount = 8; const int threadCount = 4; const bool spawnOnOverload = true; // 1) Set max tries and create eventloop // It's ugly to set the value via an environment variable, but the current API // doesn't allow to do it another way. const std::string oldMaxTimeouts = os::getenv("QI_EVENTLOOP_MAX_TIMEOUTS"); os::setenv("QI_EVENTLOOP_MAX_TIMEOUTS", "1"); auto _ = ka::scoped([&]() { os::setenv("QI_EVENTLOOP_MAX_TIMEOUTS", oldMaxTimeouts.c_str()); }); EventLoopAsio ev{threadCount, minThreadCount, maxThreadCount, "youp", spawnOnOverload}; // 2) Register callback std::atomic<bool> emergencyCalled{false}; ev._emergencyCallback = [&]() { emergencyCalled.store(true); }; // 3) Spam eventloop and record distinct thread counts // We're going to keep track of the thread counts. std::vector<int> threadCounts{threadCount}; auto postTask = [](EventLoopAsio& ev) { ev.asyncCall(Duration{0}, []() { std::this_thread::sleep_for(std::chrono::milliseconds{100}); }); }; auto pushIfDistinctThreadCount = [&threadCounts](const EventLoopAsio& ev) { const auto n = ev.workerCount(); if (n != threadCounts.back()) { threadCounts.push_back(n); } }; // Spam the eventloop until the thread count goes up to the maximum. while (!emergencyCalled.load()) { postTask(ev); pushIfDistinctThreadCount(ev); std::this_thread::sleep_for(std::chrono::milliseconds{10}); } // 4) Check that the thread counts have gone up to the max auto b = threadCounts.begin(); auto e = threadCounts.end(); // The range must not be empty. ASSERT_NE(b, e); // The thread counts must have gone up. ASSERT_TRUE(std::is_sorted(b, e)); // We must have reached the maximum thread count. ASSERT_EQ(maxThreadCount, *(e-1)); } // We check that the eventloop gets bigger when overloaded, then shrinks when // idle. TEST(EventLoopAsio, DynamicShrinking) { using namespace qi; const int minThreadCount = 2; const int maxThreadCount = 8; const int threadCount = 4; const bool spawnOnOverload = true; EventLoopAsio ev{threadCount, minThreadCount, maxThreadCount, "youp", spawnOnOverload}; // We're going to keep track of the thread counts. std::vector<int> threadCounts{threadCount}; // Spam the eventloop until the thread count goes up to the maximum. while (ev.workerCount() != maxThreadCount) { ev.asyncCall(Duration{0}, []() { std::this_thread::sleep_for(std::chrono::milliseconds{100}); }); std::this_thread::sleep_for(std::chrono::milliseconds{10}); } auto pushIfDistinctThreadCount = [&threadCounts](EventLoopAsio const& ev) { const auto n = ev.workerCount(); if (n != threadCounts.back()) { threadCounts.push_back(n); } }; // Wait until the thread count goes back down to the minimum, recording the // distinct thread counts. while (ev.workerCount() != minThreadCount) { pushIfDistinctThreadCount(ev); std::this_thread::sleep_for(std::chrono::milliseconds{10}); } pushIfDistinctThreadCount(ev); // Check that the recorded distinct thread counts strictly increase, then // strictly decrease. auto b = threadCounts.begin(); auto e = threadCounts.end(); // [b, i) is the increasing sub-range. auto i = std::is_sorted_until(b, e); // i must be in (b, e-1), i.e. sub-ranges must not be empty. ASSERT_LT(b, i); ASSERT_LT(i, e); // We must have peaked at the maximum thread count. ASSERT_EQ(maxThreadCount, *(i-1)); // [i, e) must decrease. ASSERT_TRUE(std::is_sorted(i, e, std::greater<int>{})); // We must have gone down to the minimum thread count. ASSERT_EQ(minThreadCount, *(e-1)); } TEST(EventLoop, posInBetween) { using qi::detail::posInBetween; // percent ASSERT_EQ( 0, posInBetween( 0, 0, 100)); ASSERT_EQ( 10, posInBetween( 0+3, 10+3, 100+3)); ASSERT_EQ( 50, posInBetween( 0, 50, 100)); ASSERT_EQ( 90, posInBetween( 0+35, 90+35, 100+35)); ASSERT_EQ(100, posInBetween( 0, 100, 100)); ASSERT_EQ(100, posInBetween( 0-100, 100-100, 100-100)); // range of a single value ASSERT_EQ(100, posInBetween( 0, 0, 0)); ASSERT_EQ(100, posInBetween(10,10,10)); ASSERT_EQ(100, posInBetween(-3,-3,-3)); // small ranges ASSERT_EQ( 0, posInBetween(0, 0, 2)); ASSERT_EQ( 50, posInBetween(0, 1, 2)); ASSERT_EQ(100, posInBetween(0, 2, 2)); ASSERT_EQ( 0, posInBetween(0+5, 0+5, 2+5)); ASSERT_EQ( 50, posInBetween(0-7, 1-7, 2-7)); ASSERT_EQ(100, posInBetween(0+5, 2+5, 2+5)); ASSERT_EQ( 0, posInBetween(0, 0, 3)); ASSERT_EQ( 33, posInBetween(0, 1, 3)); ASSERT_EQ( 66, posInBetween(0+7, 2+7, 3+7)); ASSERT_EQ(100, posInBetween(0, 3, 3)); ASSERT_EQ( 0, posInBetween( 0, 0, 4)); ASSERT_EQ( 25, posInBetween( 0, 1, 4)); ASSERT_EQ( 50, posInBetween( 0, 2, 4)); ASSERT_EQ( 75, posInBetween( 0, 3, 4)); ASSERT_EQ(100, posInBetween( 0+12, 4+12, 4+12)); ASSERT_EQ( 20, posInBetween(0, 1, 5)); ASSERT_EQ( 80, posInBetween(0, 4, 5)); ASSERT_EQ( 20, posInBetween(0-6, 1-6, 5-6)); ASSERT_EQ( 80, posInBetween(0+6, 4+6, 5+6)); }
true
077f561a610eba92ab904544db96cebc07aae56d
C++
ivanmilov/IdTemplate
/idTemplate.h
UTF-8
1,282
3.6875
4
[]
no_license
/** Template for creation numeric based ids. Usage: Instead of 'typedef' and 'using' where you can use wrong type: typedef Int32 StateID; using RemoteID = UInt32; foo(StateID){...} ... RemoteID rId; foo(rId); // wrong! you can use this: using SomeId = IdTemplate<uint32_t, struct SomeTag>; using SomeAnotherId = IdTemplate<int, struct SomeAnotherTag>; bar(SomeId){...} ... SomeAnotherId anotherId; bar(anotherId); // will not compile */ #pragma once #include <type_traits> template <typename T, typename Tag, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type> class IdTemplate { public: IdTemplate(): value(0){} IdTemplate(T value): value(value){} inline operator T() const { return value; } inline bool operator<(const IdTemplate& other) { return value < other.value; } inline bool operator==(const IdTemplate& other) { return value == other.value; } inline bool operator!=(const IdTemplate& other) const { return value != other.value; } IdTemplate operator++(int) { value++; return *this; } // TODO: feel free to implement other operators :) private: T value; };
true
3503880754b0cd5edfe54734d04bba93cb9c9561
C++
walethesolution/CS246
/Iteration_2/Iteration_2.cpp
UTF-8
1,595
3.515625
4
[]
no_license
#include <iostream> #include <ctime> #include <cstdlib> #include <assert.h> using namespace std; void minimum(int arr[], int size){ int minimum = arr[0]; for(int i=1; i < size - 1; i++){ if(arr[i] < minimum){ minimum = arr[i]; } } cout<<"Minimum = "<<minimum; } void swap(int &x, int &y){ int temp; temp = x; x = y; y = temp; } void swapN(int arr[], int n, int size){ int i=0; while( i < n-i-1){ swap(arr[i], arr[n-i-1]); i++; } for(int i=0; i<size; i++){ cout<<arr[i]<<" "; } } void candyCrush(); int main(){ int arr[] = {1,2,3,4,5,6,7,8,9}; int size = sizeof(arr)/ sizeof(arr[0]); // minimum(arr,size); // swapN(arr, 3, size); candyCrush(); return 0; } void candyCrush(){ int size = 25; char arr[size]; char option[] = "ORY"; srand(time(NULL)); for(int i=0; i< size; i++){ int random = rand() % 2 + 0; arr[i] = option[random]; } cout<<"Initial Array:\n"; for(int i=0; i<size; i++){ cout<<arr[i]<<" "; } cout<<"\n\n"; int i=0; int count = 1; int check = 0; while(i<size-2){ assert(i+2<size); if( (arr[i] == arr[i+1]) && (arr[i] == arr[i+2]) ){ if(count == 1) cout<<"Initial Index where there is a repetition is "<<i<<endl; arr[i] = 'X'; arr[i+1] = 'X'; arr[i+2] = 'X'; count--; check++; } i++; } cout<<"Final Array:\n"; for(int i=0; i<size; i++){ cout<<arr[i]<<" "; } }
true
b64d02b9f327e81c6beb54dbd9e3ca1b3e1441ad
C++
dufufeisdu/algorithms
/Leecode/cpp/numberAddNumber.cpp
UTF-8
2,044
3.515625
4
[]
no_license
//Leecode #2 number add number #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* initialList(int *a, int len){ ListNode* l = new ListNode(*a); ListNode* temp = l; len--; while(len>0){ temp->next = new ListNode(*(++a)); temp = temp->next; len--; } return l; }; class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int carry = 0; ListNode* l3 =new ListNode(-1); ListNode* tempL3 = l3; while(l1&&l2){ int add = l1->val+l2->val; add+=carry; if(add>=10){ carry = 1; add-=10; }else{ carry = 0; } tempL3->next = new ListNode(add); l1 = l1->next; l2 = l2->next; tempL3 = tempL3->next; } while (l1) { int add = l1->val+carry; if(add==10){ carry = 1; add = 0; }else{ carry = 0; } l1=l1->next; tempL3->next = new ListNode(add); tempL3 = tempL3->next; } while (l2) { int add = l2->val+carry; if(add==10){ carry = 1; add = 0; }else{ carry = 0; } l2 = l2->next; tempL3->next = new ListNode(add); tempL3 = tempL3->next; } if(carry==1){ tempL3 ->next = new ListNode(1); } return l3->next; } }; int main () { int l1[] = {2,4,3}; int l2[] = {5,6,4}; ListNode* ln1; ListNode* ln2; ln1 = initialList(l1,3); ln2 = initialList(l2,3); Solution s1; ListNode *result = s1.addTwoNumbers(ln1, ln2); while (result!=nullptr) { cout<<result->val<<endl; result = result->next; } return 0; }
true
0a1de69cb2a6ac53882f2308bb784bf4f8204a52
C++
Dwyguy/TravelingSalesman
/TravelingSalesman/MatrixGraph.cpp
UTF-8
1,000
3.1875
3
[]
no_license
#include "MatrixGraph.h" using namespace std; MatrixGraph::MatrixGraph(unsigned num_nodes) { M.resize(num_nodes); for(int x = 0; x < num_nodes; x++) { M[x].resize(num_nodes); for(int y = 0; y < num_nodes; y++) M[x][y] = 0; } num_edges = 0; } MatrixGraph::~MatrixGraph() { } void MatrixGraph::addEdge(NodeID u, NodeID v, EdgeWeight weight) { if(u != v) { M[u][v] = weight; M[v][u] = weight; } else M[u][v] = 0; num_edges++; } EdgeWeight MatrixGraph::weight(NodeID u, NodeID v) const { if(M[u][v] != 0) return M[u][v]; else return 0; } std::list<NWPair> MatrixGraph::getAdj(NodeID u) const { list<NWPair>* nodeList = new std::list<NWPair>(); for(int x = 0; x < M.size(); x++) if(M[u][x] != 0) nodeList->push_back(make_pair(x, M[u][x])); return *nodeList; } unsigned MatrixGraph::degree(NodeID u) const { return getAdj(u).size(); } unsigned MatrixGraph::size() const { return M.size(); } unsigned MatrixGraph::numEdges() const { return num_edges; }
true
10833a60195e0e57f866a2770f737d170bcd626a
C++
scgroot/ThorsSerializer
/src/Serialize/test/SerSetTest.cpp
UTF-8
868
2.8125
3
[ "MIT" ]
permissive
#include "gtest/gtest.h" #include "JsonThor.h" #include "SerUtil.h" #include <algorithm> namespace TS = ThorsAnvil::Serialize; TEST(SerSetTest, serialize) { std::set<int> data{34,24,8,11,2}; std::stringstream stream; stream << TS::jsonExport(data); std::string result = stream.str(); result.erase(std::remove_if(std::begin(result), std::end(result), [](char x){return ::isspace(x);}), std::end(result)); EXPECT_EQ(result, R"([2,8,11,24,34])"); } TEST(SerSetTest, deSerialize) { std::set<int> data; std::stringstream stream(R"([5,6,8,101,123])"); stream >> TS::jsonImport(data); EXPECT_TRUE(data.find(5) != data.end()); EXPECT_TRUE(data.find(6) != data.end()); EXPECT_TRUE(data.find(8) != data.end()); EXPECT_TRUE(data.find(101) != data.end()); EXPECT_TRUE(data.find(123) != data.end()); }
true
c0dc9bb9d92bc4372d2cd08e345d4ac3b9f27890
C++
MakinoRuki/TopCoder
/SRM706Div1Easy.cpp
UTF-8
2,092
2.5625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <algorithm> #include <queue> #define N 22 #define inf 1000000000 #define mp make_pair using namespace std; int dx[4] = {-1, 1, 0, 0}; int dy[4] = {0, 0, -1, 1}; class MovingCandies { public: int n, m; int dp[N][N][N * N]; bool vis[N][N][N * N]; int minMoved(vector<string> t) { n = t.size(); m = t[0].size(); int c = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (t[i][j] == '#') c++; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { for (int k = 0; k <= c; ++k) { dp[i][j][k] = inf; } } } queue<pair<pair<int, int>, int> > Q; memset(vis, false, sizeof(vis)); if (t[0][0] == '.') { dp[0][0][0] = 1; vis[0][0][0] = true; Q.push(mp(mp(0, 0), 0)); } else { dp[0][0][1] = 0; vis[0][0][1] = true; Q.push(mp(mp(0, 0), 1)); } while (!Q.empty()) { pair<pair<int, int>, int> cur = Q.front(); Q.pop(); int i = cur.first.first; int j = cur.first.second; int k = cur.second; vis[i][j][k] = false; for (int d = 0; d < 4; ++d) { int ni = i + dx[d]; int nj = j + dy[d]; if (ni >= 0 && ni < n && nj >= 0 && nj < m) { if (t[ni][nj] == '.') { if (k + dp[i][j][k] + 1 <= c) { if (dp[i][j][k] + 1 < dp[ni][nj][k]) { dp[ni][nj][k] = dp[i][j][k] + 1; if (!vis[ni][nj][k]) { vis[ni][nj][k] = true; Q.push(mp(mp(ni, nj), k)); } } } } else { if (k + dp[i][j][k] + 1 <= c) { if (dp[ni][nj][k + 1] > dp[i][j][k]) { dp[ni][nj][k + 1] = dp[i][j][k]; if (!vis[ni][nj][k + 1]) { vis[ni][nj][k + 1] = true; Q.push(mp(mp(ni, nj), k + 1)); } } } } } } } int ans = inf; for (int i = 0; i <= c; ++i) { if (dp[n - 1][m - 1][i] < inf && i + dp[n - 1][m - 1][i] <= c) { ans = min(ans, dp[n - 1][m - 1][i]); } } return (ans >= inf ? -1 : ans); } };
true
0ad47e743c1f67fa3192df4b5948abc905f52a5a
C++
benolson/projectOR
/Code/qt/ProjectOR/imageGrabber.cpp
UTF-8
2,673
2.640625
3
[]
no_license
#include "imageGrabber.h" #include <QImage> #include <windows.h> #include <fstream> #include <iostream> void ImageGrabberStartLoop(int imageWidth, int imageHeight, IplImage** image, QMutex* cameraLock) { // Images to capture the frame from video or camera or from file CvCapture* capture = cvCaptureFromCAM(CV_CAP_ANY); // If loaded succesfully, then: if( capture ) { unsigned long iterations = 0; // Capture from the camera. while (1) { // check to exit if (iterations % 20 == 0) { char buffer[8]; std::ifstream f("shutDownThread.bin", std::ios::binary); f.read(buffer,1); f.close(); // Release the images, and capture memory if (buffer[0] != '0') { cvReleaseCapture( &capture); return; } } cameraLock->lock(); *image = cvQueryFrame(capture); // If the frame does not exist, quit the loop if( !*image ) break; cvFlip(*image, 0, 0 ); cvCvtColor(*image,*image,CV_BGR2RGB); cameraLock->unlock(); //cvSaveImage(fileName, frame); Sleep(60); iterations++; } } } ///////////////////////////////////// ImageGrabber ////////////////////////////////////////////// ImageGrabber::ImageGrabber(IplImage** image, QMutex* cameraLock, QObject* parent) : QObject(parent) { m_image = image; m_cameraLock = cameraLock; } void ImageGrabber::saveCameraImage(Image& image) { image.width = width(); image.height = height(); image.data = new char[3*image.width*image.height]; lockCamera(); memcpy(image.data, (*m_image)->imageData, image.width*image.height*3); unlockCamera(); } IplImage* ImageGrabber::saveCameraImageIplImage() { IplImage* out = cvCreateImage(cvSize(width(),height()), IPL_DEPTH_8U, 1); lockCamera(); cvCvtColor(*m_image, out, CV_RGB2GRAY); unlockCamera(); return out; } void ImageGrabber::saveCameraImageToDisk() { lockCamera(); cvFlip(*m_image, 0, 0 ); cvSaveImage("cameraScreenshot.png", *m_image); cvFlip(*m_image, 0, 0 ); unlockCamera(); } void ImageGrabber::saveImageToDisk(Image& img, char* fileName) { QImage qIMG((unsigned char*)img.data, img.width, img.height, QImage::Format_RGB888); qIMG.save(fileName, QString("png").toAscii()); } void ImageGrabber::saveImageToDiskIplImage(IplImage* img, char* fileName) { cvSaveImage(fileName, img); }
true
fbc9627e02b5b48638adbc4dd5179d8ac04e503d
C++
matheustguimaraes/lapisco-training
/src/Topico_45.cpp
UTF-8
2,888
2.65625
3
[]
no_license
#include <iostream> #if (defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__) || defined(__WINDOWS__) || (defined(__APPLE__) & defined(__MACH__))) #include <cv.h> #include <highgui.h> #else #include <opencv/cv.h> #include <opencv/highgui.h> #endif #include <cvblob.h> using namespace std; using namespace cv; using namespace cvb; void getAutoBlobImages(IplImage *img) { IplImage *cannyImg, *labelImg, *blobImg; CvBlobs blobs; CvContourPolygon *polygon, *simplePolygon; CvRect rectangle; int count = 0; char nameBlobUnit[100] = {0}; long int area, maxValueX, minValueX, maxValueY, minValueY; cannyImg = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1); blobImg = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 3); labelImg = cvCreateImage(cvGetSize(cannyImg), IPL_DEPTH_LABEL, 1); cvCvtColor(img, cannyImg, CV_RGB2GRAY); cvCanny(cannyImg, cannyImg, 127, 255, 3); cvLabel(cannyImg, labelImg, blobs); cvFilterByArea(blobs, 430, 435); cvZero(blobImg); for (CvBlobs::const_iterator iterator = blobs.begin(); iterator != blobs.end(); ++iterator) { cvRenderBlob(labelImg, (*iterator).second, cannyImg, blobImg, CV_BLOB_RENDER_COLOR); cvRenderBlob(labelImg, (*iterator).second, cannyImg, blobImg, CV_BLOB_RENDER_BOUNDING_BOX); polygon = cvConvertChainCodesToPolygon(&(*iterator).second->contour); simplePolygon = cvSimplifyPolygon(polygon, 0.1); cvRenderContourPolygon(simplePolygon, blobImg, CV_RGB(0, 255, 0)); rectangle = cvRect((*iterator).second->minx, (*iterator).second->miny, ((*iterator).second->maxx - (*iterator).second->minx), (*iterator).second->maxy - (*iterator).second->miny); cvSetImageROI(blobImg, rectangle); sprintf(nameBlobUnit, "blob %d", count); cvShowImage(nameBlobUnit, blobImg); area = (*iterator).second->area; maxValueX = (*iterator).second->maxx; minValueX = (*iterator).second->minx; maxValueY = (*iterator).second->maxy; minValueY = (*iterator).second->miny; printf("blob %d:\n", count + 1); printf("\twidth : %3.ld pixels\n", maxValueX - minValueX); printf("\theight : %3.ld pixels\n", maxValueY - minValueY); printf("\tarea : %3.ld pixels\n\n", area); count++; cvResetImageROI(blobImg); delete polygon; delete simplePolygon; } cvShowImage("image with colored square blobs", blobImg); cvReleaseImage(&img); cvReleaseImage(&cannyImg); cvReleaseImage(&labelImg); cvReleaseImage(&blobImg); cvReleaseBlobs(blobs); } int main() { IplImage *img = cvLoadImage("../samples/paint.jpg", CV_LOAD_IMAGE_COLOR); cvShowImage("original image", img); getAutoBlobImages(img); cvWaitKey(0); return 0; }
true
89c4f995d9b32b87b00a94c2308ae3eca6dd6698
C++
les-3-loustiques/CHIC-pocs
/Blazz/semester_projects/esp8266/test_sparkfun/test_sparkfun.ino
UTF-8
888
2.6875
3
[]
no_license
#include "myWifiFunctions.h" #include <ESP8266WebServer.h> #define ESP8266_LED 5 // the blue led myWifi wiObject; const char *ssid = "UPC616BF3F"; const char *pass = "etW5aaf8Gbnk"; ESP8266WebServer server(80); void handleRoot() { server.send(200, "text/html", "<h1>You are connected</h1>"); } void ledOn(){ server.send(200, "text/html", "<h1>LED on</h1>"); digitalWrite(ESP8266_LED, LOW); } void ledOff(){ server.send(200, "text/html", "<h1>LED off</h1>"); digitalWrite(ESP8266_LED, HIGH); } void setup() { pinMode(ESP8266_LED, OUTPUT); Serial.begin(9600); // setup the serial communication for debuging wiObject.setupWifi(ssid,pass); // setup the wifi connection server.on("/", handleRoot); server.on("/led_on", ledOn); server.on("/led_off", ledOff); server.begin(); Serial.println("HTTP server started"); } void loop() { server.handleClient(); }
true
35fb3fe648d31c88a1b3f16b6d5f3d9272855bb3
C++
MsNahid/Uri-Problem-Solution
/1144.cpp
UTF-8
499
2.859375
3
[]
no_license
#include <iostream> #include <cstdio> #include <cmath> using namespace std; int main(){ int n, i, j, k, val, sqr, volume; scanf("%d", &n); for(i = 1; i <= n; i++){ val = i, sqr = i * i, volume = i * i * i; for(j = 1; j <= 2; j++){ if(j == 1){ printf("%d %d %d\n", val, sqr, volume); }else{ printf("%d %d %d\n", val, sqr + 1, volume + 1); } } } return 0; }
true
a18921c9e8d7936f0b4ba712aa0acdd7d854efec
C++
bifrurcated/LearningCpp
/FileWork/FileWork.cpp
UTF-8
1,006
3.515625
4
[]
no_license
#include <iostream> #include <string> #include <fstream> #include "MyException.h" using namespace std; /* Создание собсвенных исключений */ void PrintException(int value) { if (value < 0) { throw exception("Число меньше нуля!"); } if (value == 1) { throw MyException("Число равно 1!", value); } cout << "Переменная = " << value << endl; } int main() { setlocale(LC_ALL, "RU"); try{ PrintException(1); } catch (MyException& ex) { cout << "Блок 1 Мы поймали: " << ex.what() << endl; cout << "Состояние данных: " << ex.GetDataState() << endl; } catch (const exception& ex) { cout << "Блок 2 Мы поймали: " << ex.what() << endl; } catch (...) { //сюда мы поймаем всё что бросить exception //данное исключение должно быть в конце cout << "Блок 3 Что-то пошло не так!" << endl; } return 0; }
true
05a1cc7898dfaa2d3678ea944c83ef77e92f08a9
C++
joaoreiser/Cplusplus
/Pointers_Smart/Unique_Pointer.cpp
UTF-8
2,830
3.8125
4
[]
no_license
#include <iostream> #include <vector> #include <string> #include <memory> using std::cout; using std::endl; using std::cin; using std::vector; using std::string; /* UNIQUE POINTER (unique_ptr) -> unique. Can only have one unique_prt pointing to the object on the heap -> owns what it points to -> cannot be copied or assigned -> CAN be moved -> when pointer is destroyed, the content is destroyed too */ /* { std::unique_prt<int> p1{new int{100}}; cout << *p1 << endl; //100 *p1 = 200; cout << *p1 << endl; //200 } //destroyed automatically when out of scope -> USEFUL METHODS ptr_name.get(); -> return the address ptr_name.reset(); -> nullptr if(ptr_name){} -> verifies if the pointer is initialized (not nullptr) -> IMPORTANT DETAILS vector<std::unique_prt<int>> vec; std::unique_prt<int> ptr {new int{100}}; vec.push_back(ptr); //ERROR - copy not allowed vec.push_back(std::move(ptr)); //OK -> MORE EFFICIENT UNIQUE_PTR CREATION std::unique_ptr<int> p1 = make_unique<int>(100); std::unique_prt<Account> p2 = make_unique<Account>("Joao", 1000); auto p3 = make_unique<Player>("Hero", 100, 100); //three variations of make_unique use for unique_prt creation //no need of NEW keyword */ class Test{ private: int data; public: Test() : data{0}{cout << "Constructor" << endl;} Test(int data) : data{data}{cout << "Constructor2: " << data << endl;} int get_data() const {return data;} ~Test(){cout << "Destructor: " << data << endl;} }; int main() { Test *ptr1 = new Test(1000); std::unique_ptr<Test> ptr2 = std::make_unique<Test>(2000); std::unique_ptr<Test> ptr3{new Test{3000}}; auto ptr4 = std::make_unique<Test>(4000); cout << ptr1->get_data() << endl; cout << ptr2->get_data() << endl; cout << ptr3->get_data() << endl; cout << ptr4->get_data() << endl; std::unique_ptr<Test> ptr5; ptr5 = std::move(ptr4); ////when the pointer is moved to a new position, ////the old position will be automatically null if(!ptr4){ //if ptr4 is nullptr cout << "ptr4 is null. ptr5 is: " << ptr5->get_data() << endl; } ////without delete, ptr2 will never be destroyed (Memory Leak) ////ptr1 destructor is automatically called delete ptr1; //std::unique_ptr<Account> p_c_account = std::make_unique<Checking_Account>("Joao", 1000); //vector<std::unique_prt<Account>> vec; -> vector of unique pointers of Account //vec.push_back(make_unique<Checking_Account>("Joao", 5000); -> create and append pointer to vec //vec.push_back(make_unique<Savings_Account>("John", 4000, 2); -> create and append pointer to vec //vec.push_back(make_unique<Trust_Account>("Jack", 3000, 3); -> create and append pointer to vec ////=> v NEEDS TO BE BY REFERENCE (&), BECAUSE //// NO COPY IS ALLOWED //for(const auto &v : vec){ // cout << *v << endl; //} return 0; }
true
a9f6a5a46e05e45f0eeffb5590c2063bbff5e92a
C++
gotonis/HybridAnn
/NeuralNet.cpp
UTF-8
1,847
2.78125
3
[]
no_license
#include <cmath> #include <iostream> #include <cstdlib> #include <cstdio> #include <vector> #include "Neuron.hpp" #include "NeuralNet.hpp" using namespace std; vector<float> NeuralNet::evaluate(vector<float> input){ vector<float> t1 = input; vector<float> t2; vector<Neuron*> current; for(int i=0;i<layers.size();i++){ t2 = vector<float>(); current = layers[i]; for(int j=0;j<sizes[i];j++){ t2.push_back(current[j]->activation(t1)); } t1 = t2; } return t2; } void NeuralNet::train(vector<float> input, vector<float> output){ vector<vector<float> > temp = vector<vector<float> >(); temp.push_back(input); vector<Neuron*> current; vector<float> t1; vector<float> t2; for(int i=0;i<layers.size();i++){ t1 = temp[i]; t2 = vector<float>(); current = layers[i]; for(int j=0;j<sizes[i];j++){ t2.push_back(current[j]->activation(t1)); } temp.push_back(t2); //printf("evaluated layer %i\n",i); } vector<float> costs = vector<float>(); for(int i=0;i<output.size();i++){ costs.push_back(t2[i]-output[i]); } //printf("calculated costs\n"); vector<float> temp3; vector<float> temp4; for(int j=layers.size()-1;j>=0;j--){ //printf("costs for layer %i are ", j); /* for(int s=0;s<costs.size();s++){ printf("%f ",costs[s]); } printf("\n"); */ current = layers[j]; temp3 = vector<float>(temp[j].size(),0); for(int i=0;i<current.size();i++){ //printf("adjusting neuron %i of layer %i\n", i, j); temp4 = current[i]->getPrevDCDAs(temp[j],costs[i]); //printf("got DCDAs\n"); for(int k=0;k<temp3.size();k++){ //printf("%i, %u, %u\n",k, temp3.size(),temp4.size()); temp3[k]+=temp4[k]; //printf("%i\n",k); } current[i]->update(temp[j],costs[i]); } costs = temp3; } }
true
31f671e5a4920834585a12b79dc10611781baaad
C++
gauravsingh9891/Projects
/matrix.cpp
UTF-8
905
3.546875
4
[]
no_license
#include<iostream> #include<conio.h> using namespace std; class Matrix { private: int a[5][5],i,j,m,d1_sum,d2_sum; public: Matrix() //Default constructor { d1_sum=0; d2_sum=0; } void calculate() { cout<<"\n Enter the size of Matrix :"; cin>>m; cout<<"\n Enter the element of matrix in row wise : \n\n"; for(i=0;i<m;i++) { for(j=0;j<m;j++) { cin>>a[i][j]; } } for(i=0;i<m;i++) { for(j=0;j<m;j++) { if(i==j) d1_sum+=a[i][j]; if(i+j==(m-1)) d2_sum+=a[i][j]; } } } void display() { cout<<"\nElements of Matrix : \n"; for(i=0;i<m;i++) { for(j=0;j<m;j++) { cout<<a[i][j]<<"\t"; } cout<<endl; } cout<<"\n The sum of 1st diagonal elements : "<<d1_sum; cout<<"\n The sum of 2nd diagonal elements : "<<d2_sum; } }; main() { Matrix obj; obj.calculate(); obj.display(); getch(); }
true
40718c3cb859acfac424cdabf0423f9930f478f2
C++
MarTecs/CppProgramming
/c++ prime第5版/3/3.2/3.2.2/3_2_Test.cpp
UTF-8
353
3.09375
3
[ "MIT" ]
permissive
#include<iostream> #include<string> using namespace std; /** * 编写一段程序从标准输入中一次读入一整行 * @param argc [description] * @param argv [description] * @return [description] */ int main(int argc, char const *argv[]) { string line; while ( getline(cin, line) ) { cout << line << endl; } return 0; }
true
20449557efe05c0a973161fc25ac1943ea842bb3
C++
asyhirfn/OS_GroupProject
/src/PAGE_REPLACEMENT_ALGORITHM.cpp
UTF-8
6,437
3.203125
3
[]
no_license
#include<iostream> #include <iomanip> #include <string> #include <fstream> #include<bits/stdc++.h> using namespace std; struct node { char data; node *next; }; class lru_alg { int frame,count,fault; node *front,*rear; public: lru_alg() { front=rear=NULL; fault=count=0; } void page_fault(); }; void lru_alg::page_fault() { int flag=0,choose; const int size = 23; int num[size]; cout<< "Please choose your case(1-3): "; cin>>choose; switch(choose){ case 1: { ifstream input; input.open("../InputPart2/inputfile1.txt"); ofstream output; output.open("../OutputPart2/outputfile1.txt"); for(int x=0; x<size; x++){ input >> num[x]; } frame = num[0]; for(int i=1;i<size;i++){ if(num[i]==' ') continue; if(front==NULL){ front=rear=new node; front->data=num[i]; front->next=NULL; fault=count=1; } else{ node *temp=front,*prev=NULL; while(temp!=NULL){ if(temp->data==num[i]){ flag=1; if(prev==NULL){ rear=rear->next=front; front=front->next; rear->next=NULL; } else if(temp!=rear){ prev->next=temp->next; rear=rear->next=temp; temp->next=NULL; } break; } prev=temp; temp=temp->next; } if(flag==0){ if(count==frame){ rear=rear->next=front; front=front->next; rear->data=num[i]; rear->next=NULL; } else{ rear=rear->next=new node; rear->data=num[i]; rear->next=NULL; count++; } fault++; } flag=0; } } cout<<"Number of page faults : "<<fault; output<<"Case 1: " <<fault<<endl; } break; case 2: { ifstream input; input.open("../InputPart2/inputfile2.txt"); ofstream output; output.open("../OutputPart2/outputfile2.txt"); for(int x=0; x<size; x++){ input >> num[x]; } frame = num[0]; for(int i=1;i<size;i++){ if(num[i]==' ') continue; if(front==NULL){ front=rear=new node; front->data=num[i]; front->next=NULL; fault=count=1; } else{ node *temp=front,*prev=NULL; while(temp!=NULL){ if(temp->data==num[i]){ flag=1; if(prev==NULL){ rear=rear->next=front; front=front->next; rear->next=NULL; } else if(temp!=rear){ prev->next=temp->next; rear=rear->next=temp; temp->next=NULL; } break; } prev=temp; temp=temp->next; } if(flag==0){ if(count==frame){ rear=rear->next=front; front=front->next; rear->data=num[i]; rear->next=NULL; } else{ rear=rear->next=new node; rear->data=num[i]; rear->next=NULL; count++; } fault++; } flag=0; } } cout<<"Number of page faults : "<<fault; output<<"Case 2: " <<fault<<endl; } break; case 3: { ifstream input; input.open("../InputPart2/inputfile3.txt"); ofstream output; output.open("../OutputPart2/outputfile3.txt"); for(int x=0; x<size; x++){ input >> num[x]; } frame = num[0]; for(int i=1;i<size;i++){ if(num[i]==' ') continue; if(front==NULL){ front=rear=new node; front->data=num[i]; front->next=NULL; fault=count=1; } else{ node *temp=front,*prev=NULL; while(temp!=NULL){ if(temp->data==num[i]){ flag=1; if(prev==NULL){ rear=rear->next=front; front=front->next; rear->next=NULL; } else if(temp!=rear){ prev->next=temp->next; rear=rear->next=temp; temp->next=NULL; } break; } prev=temp; temp=temp->next; } if(flag==0){ if(count==frame){ rear=rear->next=front; front=front->next; rear->data=num[i]; rear->next=NULL; } else{ rear=rear->next=new node; rear->data=num[i]; rear->next=NULL; count++; } fault++; } flag=0; } } cout<<"Number of page faults : "<<fault; output<<"Case 3: " <<fault<<endl; } break; }; } int main() { lru_alg page; page.page_fault(); return 0; }
true
8abe82fb5f6b63176cddcb1e9c1c36f435849306
C++
fourstix/QwiicSerLCD
/examples/Example14-ShowFirmwareVersion/Example14-ShowFirmwareVersion.ino
UTF-8
1,233
2.765625
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "Beerware" ]
permissive
/* SerLCD Library - Show the firmware version Gaston Williams - August 29, 2018 This sketch prints the device's firmware version to the screen. The circuit: SparkFun RGB OpenLCD Serial display connected through a Sparkfun Qwiic adpater to an Ardruino with a Qwiic shield or a Sparkfun Blackboard with Qwiic built in. The Qwiic adapter should be attached to the display as follows: Display / Qwiic Cable Color GND / Black RAW / Red SDA / Blue SCL / Yellow Note: If you connect directly to a 5V Arduino instead, you *MUST* use a level-shifter to convert the i2c voltage levels down to 3.3V for the display. This code is based on the LiquidCrystal code originally by David A. Mellis and the OpenLCD code by Nathan Seidle at SparkFun. License: This example code is in the public domain. */ #include <Wire.h> #include <SerLCD.h> //Click here to get the library: http://librarymanager/All#SparkFun_SerLCD SerLCD lcd; // Initialize the library with default I2C address 0x72 void setup() { Wire.begin(); lcd.begin(Wire); //Set up the LCD for I2C } void loop() { lcd.command(','); //Send the comma to display the firmware version //Firmware will be displayed for 500ms so keep re-printing it delay(500); }
true
0c15f7105848174005d4c93471af5c0087cf1738
C++
kiorisyshen/newbieGameEngine
/Framework/Geometries/Geometry.cpp
UTF-8
2,282
2.578125
3
[ "MIT" ]
permissive
#include "Geometry.hpp" using namespace newbieGE; void Geometry::CalculateTemporalAabb(const Matrix4X4f &curTrans, const Vector3f &linvel, const Vector3f &angvel, float timeStep, Vector3f &temporalAabbMin, Vector3f &temporalAabbMax) const { //start with static aabb GetAabb(curTrans, temporalAabbMin, temporalAabbMax); float temporalAabbMaxx = temporalAabbMax[0]; float temporalAabbMaxy = temporalAabbMax[1]; float temporalAabbMaxz = temporalAabbMax[2]; float temporalAabbMinx = temporalAabbMin[0]; float temporalAabbMiny = temporalAabbMin[1]; float temporalAabbMinz = temporalAabbMin[2]; // add linear motion Vector3f linMotion = linvel * timeStep; ///@todo: simd would have a vector max/min operation, instead of per-element access if (linMotion[0] > 0.0f) temporalAabbMaxx += linMotion[0]; else temporalAabbMinx += linMotion[0]; if (linMotion[1] > 0.0f) temporalAabbMaxy += linMotion[1]; else temporalAabbMiny += linMotion[1]; if (linMotion[2] > 0.0f) temporalAabbMaxz += linMotion[2]; else temporalAabbMinz += linMotion[2]; //add conservative angular motion float angularMotion = Length(angvel) * GetAngularMotionDisc() * timeStep; Vector3f angularMotion3d({angularMotion, angularMotion, angularMotion}); temporalAabbMin = Vector3f({temporalAabbMinx, temporalAabbMiny, temporalAabbMinz}); temporalAabbMax = Vector3f({temporalAabbMaxx, temporalAabbMaxy, temporalAabbMaxz}); temporalAabbMin = temporalAabbMin - angularMotion3d; temporalAabbMax = temporalAabbMax + angularMotion3d; } void Geometry::GetBoundingSphere(Vector3f &center, float &radius) const { Matrix4X4f tran; BuildIdentityMatrix(tran); Vector3f aabbMin, aabbMax; GetAabb(tran, aabbMin, aabbMax); radius = Length(aabbMax - aabbMin) * 0.5f; center = (aabbMin + aabbMax) * 0.5f; } float Geometry::GetAngularMotionDisc() const { Vector3f center; float disc = 0.0f; GetBoundingSphere(center, disc); disc += Length(center); return disc; }
true
e0c0243bdf5115d64929b1494f2419e31dc5db34
C++
adamheald13/AvlTree
/main.cpp
UTF-8
2,983
3.578125
4
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include "City.h" #include "UnorderedArray.h" #include "AvlTree.h" using namespace std; void readFile(); void readTestData(); void deletionTest(); void findCitiesInProximity(int x, int y, int distance); UnorderedArray array; AvlTree* avlTree = new AvlTree(); int inputs[100][3]; int numberOfTests; int numberOfCities; int main() { readFile(); readTestData(); for(int i = 0; i < numberOfTests; i++) { findCitiesInProximity(inputs[i][0], inputs[i][1], inputs[i][2]); } cout << "----- Comparisons -----" << endl; //comparison numbers based on the insertion in the trees when they are created cout << "Number of comparisons for insertion on UnorderedArray: " << array.getInsertComparisons() << endl; cout << "Number of comparisons for insertion on AvlTree: " << avlTree->getInsertComparisons() << endl; //delete every other city from data structures and report # of comps deletionTest(); } void findCitiesInProximity(int x, int y, int distance) { //TODO UnorderedArray cout << "----- Near Cities in UnorderedArray -----" << endl; array.findNearCitites(x, y, distance); cout << endl; //TODO AvlTree cout << "----- Near Cities in AvlTree -----" << endl; avlTree->findNearCitites(avlTree->getRoot(), numberOfCities, x, y, distance); cout << endl; } void readFile() { ifstream cityFile("data5R.txt"); string line; string name; int x; int y; numberOfCities = 0; if(cityFile.is_open()) { while(getline(cityFile, line)) { istringstream iss(line); iss >> name >> x >> y; array.insert(City(name, x, y)); avlTree->insert(City(name, x, y), avlTree->rootNode); numberOfCities++; } cityFile.close(); } } void readTestData() { ifstream testFile("lab5_testR.txt"); string line; int x; int y; int distance; numberOfTests = 0; if(testFile.is_open()) { while(getline(testFile, line)) { istringstream iss(line); iss >> x >> y >> distance; inputs[numberOfTests][0] = x; inputs[numberOfTests][1] = y; inputs[numberOfTests][2] = distance; numberOfTests++; } testFile.close(); } } void deletionTest() { ifstream cityFile("data5R.txt"); string line; string name; int x; int y; numberOfCities = 0; if(cityFile.is_open()) { while(getline(cityFile, line)) { istringstream iss(line); iss >> name >> x >> y; array.insert(City(name, x, y)); avlTree->insert(City(name, x, y), avlTree->rootNode); numberOfCities++; if(numberOfCities % 2 == 0) { array.deleteByName(name); avlTree->deleteByName(name, avlTree->rootNode); } } cityFile.close(); } cout << "Number of comparisons for deletion on UnorderedArray: " << array.getDeleteComparisons() << endl; cout << "Number of comparisons for deletion on AvlTree: " << avlTree->getDeleteComparisons() << endl; }
true
88132981354444f843be68b6edfb79369e7b9c6a
C++
Garanyan/msu_cpp_spring_2017
/Bezsudnova/Game/Weapon.h
UTF-8
1,567
3.109375
3
[]
no_license
#pragma once class Weapon { public: virtual WeaponType getWeaponType() = 0; virtual int getPower(ArmorType armor_) = 0; virtual ~Weapon(){} }; class Sword : public Weapon { public: WeaponType getWeaponType(void); int getPower(ArmorType armor_); }; class Hammer: public Weapon { public: WeaponType getWeaponType(void); int getPower(ArmorType armor_); }; class Shovel: public Weapon { public: WeaponType getWeaponType(void); int getPower(ArmorType armor_); }; class Bow: public Weapon { public: WeaponType getWeaponType(void); int getPower(ArmorType armor_); }; //sword WeaponType Sword::getWeaponType(void) { return WeaponType::Sword; }; int Sword::getPower(ArmorType armor_) { switch(armor_) { case ArmorType::Chain: return 15; case ArmorType::Lats : return 10; } return 0; }; //hammer WeaponType Hammer::getWeaponType(void) { return WeaponType::Hammer; }; int Hammer::getPower(ArmorType armor_) { switch(armor_) { case ArmorType::Chain: return 15; case ArmorType::Lats : return 10; } return 0; }; //shovel WeaponType Shovel::getWeaponType(void) { return WeaponType::Shovel; }; int Shovel::getPower(ArmorType armor_) { switch(armor_) { case ArmorType::Chain: return 10; case ArmorType::Lats : return 15; } return 0; }; //bow WeaponType Bow::getWeaponType(void) { return WeaponType::Bow; } int Bow::getPower(ArmorType armor_) { switch(armor_) { case ArmorType::Chain: return 10; case ArmorType::Lats : return 15; } return 0; }
true
a43e08343b2b23fd1476c89dd7da46a6c1d3f3bf
C++
zhutou82/JSEngine2.0
/JSEngine2.0/src/JSEngine/Graphics/Meterial.h
UTF-8
838
2.578125
3
[]
no_license
#pragma once #include <vector> #include "glm/glm.hpp" #include "JSEngine/Core/Core.h" #include "JSEngine/Graphics/Texture.h" #include "JSEngine/Graphics/Shader.h" namespace JSEngine { class Material { public: Material(const Ref<Shader>& shader); float GetShinese() const { return m_Shinese; } void SetShinese(float val) { m_Shinese = val; } void AddTexture(const Ref<Texture>& texture) { m_TextureVec.push_back(texture); } const Ref<Shader>& GetShader() const { return m_Shader; } void Bind() const; public: static Ref<Material> Create(const Ref<Shader>& shader); private: float m_Shinese = 32.f; uint32_t m_ID; std::vector<Ref<Texture>> m_TextureVec; Ref<Shader> m_Shader; }; }
true
5c57f5eed96ca7800b6f09825bd490f11c0b26c4
C++
wchunl/CompilerDesign
/asg5/emit.cpp
UTF-8
17,115
2.6875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <cstring> #include <string.h> #include <unordered_map> #include <iostream> #include "emit.h" #include "string_set.h" #include "lyutils.h" #include "sym_table.h" using namespace std; unordered_map<const char*, const char*> structmap; FILE* emit_file; int while_nr = -1; int if_nr = -1; int register_nr = 0; int string_nr = 0; // Whether or not a label was already printed previously bool lbl = false; void emit(FILE* outfile, astree* root, int depth){ emit_file = outfile; if (root== NULL) return; switch(root->symbol){ case TOK_STRUCT: emit_struct(root); break; case TOK_FUNCTION: emit_function(root); break; case TOK_VARDECL: emit_global_vars(root); break; default : for (astree* child: root->children) emit(outfile, child, depth + 1); break; } } // still need one case for type struct IDENT void emit_struct(astree* root){ for(auto* field: root->children){ switch(field->symbol){ case TOK_IDENT: pln(); fprintf(emit_file,".struct %s\n", field->lexinfo->c_str()); break; case TOK_INT: pln(); fprintf(emit_file,".field int %s\n", field->children[0]->lexinfo->c_str()); break; default: pln(); fprintf(emit_file,".field ptr %s\n", field->children[0]->lexinfo->c_str()); break; } } pln(); fprintf(emit_file,"%s\n",".end"); } //not done with struct IDENT void emit_function(astree* root){ for(auto* child: root->children){ switch(child->symbol){ case TOK_TYPE_ID: { int len = child->children[1]->lexinfo->length(); if(child->children[0]->symbol == TOK_VOID){ fprintf(emit_file,"%s:", child->children[1]->lexinfo->c_str()); for(int i=0;i<9-len;i++) fprintf(emit_file," "); fprintf(emit_file,".function\n"); }else if(child->children[0]->symbol == TOK_INT){ fprintf(emit_file,"%s:", child->children[1]->lexinfo->c_str()); for(int i=0;i<9-len;i++) fprintf(emit_file," "); fprintf(emit_file,".function int\n"); }else{ fprintf(emit_file,"%s:", child->children[1]->lexinfo->c_str()); for(int i=0;i<9-len;i++) fprintf(emit_file," "); fprintf(emit_file,".function\n"); } break; } case TOK_PARAM: emit_param(child); break; case TOK_BLOCK: emit_local_vars(child); emit_block(child); break; } } pln(); fprintf(emit_file,"%s\n",".end"); } // Need to emit the var_decl inside the block node in function first, // then we can parse the actual expr to see if it is simple or not void emit_local_vars(astree* root) { for(auto* child: root->children) { if (child->symbol == TOK_VARDECL) { // Print identifier and type if(child->children[0]->symbol == TOK_INT){ fprintf(emit_file,"%-10s.local int %s\n","", child->children[1]->lexinfo->c_str()); }else{ fprintf(emit_file,"%-10s.local ptr %s\n","", child->children[1]->lexinfo->c_str()); } } } } //not done because of struct IDENT void emit_param(astree* root){ for(auto* child: root->children){ if(child->children[0]->symbol == TOK_INT){ fprintf(emit_file,"%-10s.param int %s\n","", child->children[1]->lexinfo->c_str()); }else{ fprintf(emit_file,"%-10s.param ptr %s\n","", child->children[1]->lexinfo->c_str()); } } } // TOK_VARDECL and expressions checked in emit_expr() void emit_block(astree* root){ for(auto* child: root->children){ switch(child->symbol){ case TOK_RETURN : pln(); fprintf(emit_file,"return %s\n", child->children[0]->lexinfo->c_str()); pln(); fprintf(emit_file,"return \n"); break; case TOK_CALL : emit_call(child); break; case TOK_IFELSE : // fallthrough case TOK_IF : if_nr++; emit_if(child); break; case TOK_WHILE : while_nr++; emit_while(child); break; case TOK_BLOCK : emit_block(child); break; default: emit_expr(child); } } } void emit_call(astree* root) { // If call has args if (root->children.size() > 1) { // If call args are not simple if(root->children[1]->children.size() > 0) { // If multi args? emit_expr(root->children[1]); pln(); fprintf(emit_file,"%s($t%d:i)\n", root->children[0]->lexinfo->c_str(), register_nr++); } else { // If is simple pln(); fprintf(emit_file,"%s(%s)\n", root->children[0]->lexinfo->c_str(), root->children[1]->lexinfo->c_str()); } } else { // If no args provided pln(); fprintf(emit_file,"%s()\n", root->children[0]->lexinfo->c_str()); } } void emit_if(astree* root) { // Save the if_nr for this if loop int this_if_nr = if_nr; // Print if label plbl(); fprintf(emit_file,".if%d: ", this_if_nr); // Generate expression for boolean emit_expr(root->children[0]); // Print goto if not... pln(); fprintf(emit_file,"goto .el%d if not $t%d:i\n", this_if_nr, register_nr++); // If there is a block, emit it if(root->children[1]->symbol == TOK_BLOCK){ plbl(); fprintf(emit_file,".th%d: ", this_if_nr); emit_block(root->children[1]); // fprintf(emit_file,"block\n"); }else{ // Else emit the statement plbl(); fprintf(emit_file,".th%d: ", this_if_nr); emit_expr(root->children[1]); // fprintf(emit_file,"statement\n"); } // If there is a third arg if (root->children.size() == 3) { // Print the else label plbl(); fprintf(emit_file,".el%d: ", this_if_nr); // Lexinfo of third arg const char* str = root->children[2]->lexinfo->c_str(); // Comparing the lexinfo of TOK_IFELSE if (strcmp(str, "if") == 0) { // if arg is an else if if_nr++; emit_if(root->children[2]); } else if (strcmp(str, "(") == 0) { // if arg is a call emit_call(root->children[2]); } else if (strcmp(str, "=") == 0) { // if arg is an asg emit_asg_expr(root->children[2],0); } else if (strcmp(str, "{") == 0) { // if arg is a block emit_block(root->children[2]); } } // Print the if end plbl(); fprintf(emit_file,".fi%d: ", this_if_nr); } // Generate code for while, need to rewrite (test 23) void emit_while(astree* root){ // Save the while_nr for this while loop int this_while_nr = while_nr; // Print while label plbl(); fprintf(emit_file,".wh%d: ", this_while_nr); // Generate expression for boolean emit_expr(root->children[0]); // Print goto if not... pln(); fprintf(emit_file,"goto .od%d if not $t%d:i\n", this_while_nr, register_nr++); // If there is a block, emit it if(root->children[1]->symbol == TOK_BLOCK){ plbl(); fprintf(emit_file,".do%d: ", this_while_nr); emit_block(root->children[1]); }else{ // Else emit the statement plbl(); fprintf(emit_file,".do%d: ", this_while_nr); emit_expr(root->children[1]); } // Print the while end plbl(); fprintf(emit_file,".od%d: ", this_while_nr); } /////////////////////////////////// //// EXPRESSIONS //// /////////////////////////////////// // Read a node if it is an expression void emit_expr(astree* root){ switch(root->symbol) { case '+' : // fallthrough case '-' : // fallthrough case '/' : // fallthrough case '*' : // fallthrough case '%' : // fallthrough case '<' : // fallthrough case TOK_LE : // fallthrough case '>' : // fallthrough case TOK_NE : // fallthrough case TOK_EQ : // fallthrough case TOK_GE : emit_bin_expr(root); break; case TOK_NOT : emit_unary_expr(root); break; case TOK_VARDECL : emit_asg_expr(root, 1); break; case '=' : emit_asg_expr(root, 0); break; case TOK_IDENT : // fallthrough case TOK_INTCON : // fallthrough case TOK_STRINGCON : // fallthrough case TOK_NULLPTR : pln(); fprintf(emit_file,"$t%d:i = %s\n", register_nr, root->lexinfo->c_str()); break; case TOK_CALL : emit_call(root); break; case TOK_ARROW : emit_arrow_expr(root); break; case TOK_ALLOC : emit_alloc_expr(root); break; case TOK_INDEX : emit_array_expr(root); break; } } // Generate code for an assignment expression ("=" or vardecl) // start is the number of the node to start from // start for vardecl is 1 and for "=" it is 0 void emit_asg_expr(astree*root, int start) { if (start == 1 && root->children[0]->symbol == TOK_PTR) { structmap.insert({root->children[1]->lexinfo->c_str(), root->children[0]->children[0]->lexinfo->c_str()}); } // If node is not nested if(root->children[start+1]->children.size() == 0) { // If left is an array if (root->children[start]->symbol == TOK_INDEX) { pln(); fprintf(emit_file,"%s[%s * :p] = %s\n", root->children[start]->children[0]->lexinfo->c_str(), root->children[start]->children[1]->lexinfo->c_str(), root->children[start+1]->lexinfo->c_str()); // If left is a pointer } else if (root->children[start]->symbol == TOK_ARROW) { pln(); fprintf(emit_file,"%s->%s.%s = %s\n", root->children[start]->children[0]->lexinfo->c_str(), gsn(root->children[start]->children[0]->lexinfo->c_str()), root->children[start]->children[1]->lexinfo->c_str(), root->children[start+1]->lexinfo->c_str()); } else { pln(); fprintf(emit_file,"%s = %s\n", root->children[start]->lexinfo->c_str(), root->children[start+1]->lexinfo->c_str()); } } else { // If node is nested, traverse it // Emit the expression emit_expr(root->children[start+1]); // If left is an array if (root->children[start]->symbol == TOK_INDEX) { pln(); fprintf(emit_file,"%s[%s * :p] = $t%d:i\n", root->children[start]->children[0]->lexinfo->c_str(), root->children[start]->children[1]->lexinfo->c_str(), register_nr++); // If left is a pointer } else if (root->children[start]->symbol == TOK_ARROW) { pln(); fprintf(emit_file,"%s->%s.%s = $t%d:i\n", root->children[start]->children[0]->lexinfo->c_str(), gsn(root->children[start]->children[0]->lexinfo->c_str()), root->children[start]->children[1]->lexinfo->c_str(), register_nr++); } else { pln(); fprintf(emit_file,"%s = $t%d:i\n", root->children[start]->lexinfo->c_str(), register_nr++); // Increment register number } } } // Generate binary expression code void emit_bin_expr(astree* root) { // If "+" and "-" are unary if(root->children.size() == 1) { emit_unary_expr(root); return; } // the last is not working here astree* last = root->children[root->children.size() - 1]; // If reached deepest node if(last->children.size() == 0) { // If left is an array if (root->children[0]->symbol == TOK_INDEX) { pln(); fprintf(emit_file,"$t%d:i = %s[%s * :p]\n", register_nr++, root->children[0]->children[0]->lexinfo->c_str(), root->children[0]->children[1]->lexinfo->c_str()); pln(); fprintf(emit_file,"$t%d:i = $t%d:i %s %s\n", register_nr, register_nr - 1, root->lexinfo->c_str(), root->children[1]->lexinfo->c_str()); // If left is a pointer } else if (root->children[0]->symbol == TOK_ARROW) { pln(); fprintf(emit_file,"$t%d:p = %s->%s.%s\n", register_nr++, root->children[0]->children[0]->lexinfo->c_str(), gsn(root->children[0]->children[0]->lexinfo->c_str()), root->children[0]->children[1]->lexinfo->c_str()); pln(); fprintf(emit_file,"$t%d:i = $t%d:i %s %s\n", register_nr, register_nr - 1, root->lexinfo->c_str(), root->children[1]->lexinfo->c_str()); } else { pln(); fprintf(emit_file,"$t%d:i = %s %s %s\n", register_nr, root->children[0]->lexinfo->c_str(), root->lexinfo->c_str(), root->children[1]->lexinfo->c_str()); } } else { // Else keep traversing emit_expr(last); pln(); fprintf(emit_file,"$t%d:i = $t%d:i %s %s\n", register_nr + 1, register_nr, root->lexinfo->c_str(), root->children[1]->lexinfo->c_str()); register_nr++; } } // Generate unary expression code void emit_unary_expr(astree* root) { // If reached deepest node if(root->children[0]->children.size() == 0) { pln(); fprintf(emit_file,"$t%d:i = %s %s\n", register_nr, root->lexinfo->c_str(), root->children[0]->lexinfo->c_str()); } else { // Else keep traversing emit_expr(root->children[0]); pln(); fprintf(emit_file,"$t%d:i = %s $t%d:i\n", register_nr + 1, root->lexinfo->c_str(), register_nr); register_nr++; } } void emit_array_expr(astree* root) { pln(); fprintf(emit_file,"$t%d:p = %s[%s * :p]\n", register_nr, root->children[0]->lexinfo->c_str(), root->children[1]->lexinfo->c_str()); } void emit_alloc_expr(astree* root) { // fprintf(emit_file,"unimpl alloc, lexinfo = %s \n", // root->lexinfo->c_str()); switch(root->children[0]->symbol){ case TOK_STRING: pln(); fprintf(emit_file,"malloc(%lu)\n",sizeof(int)); break; case TOK_ARRAY: //if array type is int if(strcmp(root->children[1]->lexinfo->c_str(),"int")==0){ pln(); fprintf(emit_file,"malloc(4 * sizeof int)\n"); }else{ pln(); fprintf(emit_file,"malloc(4 * sizeof ptr)\n"); } break; case TOK_TYPE_ID://for struct pln(); fprintf(emit_file,"malloc (size of struct %s)\n", root->children[0]->lexinfo->c_str()); break; } } void emit_arrow_expr(astree* root) { pln(); fprintf(emit_file,"$t%d:p = %s->%s.%s\n", register_nr, root->children[0]->lexinfo->c_str(), gsn(root->children[0]->lexinfo->c_str()), root->children[1]->lexinfo->c_str()); } //Generate global variable code void emit_global_vars(astree* root){ if(root->children[0]->symbol == TOK_INT){ pln(); fprintf(emit_file,"%s:.global int %s\n", root->children[1]->lexinfo->c_str() ,root->children[2]->lexinfo->c_str()); }else if(root->children[0]->symbol == TOK_STRING){ pln(); fprintf(emit_file,".s%d:\"%s\"\n", string_nr,root->children[2]->lexinfo->c_str()); string_nr++; }else{ pln(); fprintf(emit_file,"%s:.global ptr %s\n", root->children[1]->lexinfo->c_str(), root->children[2]->lexinfo->c_str()); } } // Called everytime a label is printed. // This function ensures that there wont be two labels // right after one another by printing a newline between them void plbl() { if (lbl) fprintf(emit_file,"\n"); lbl = true; } // Called everytime anything other than a label is printed // prints 10 spaces if not on same line as a label void pln() { if (!lbl) fprintf(emit_file,"%-10s",""); lbl = false; } // Retrieves the struct name associated with the given key node const char* gsn(const char* key) { auto i = structmap.find(key); if (i != structmap.end()) { return i->second; } return "null"; }
true
e7f988536a03c4fd3cf5db625d47743b53457495
C++
eVillain/StruggleBox
/StruggleBox/Engine/Rendering/RenderUtils.h
UTF-8
2,448
2.625
3
[]
no_license
#ifndef RenderUtils_h #define RenderUtils_h /* ---------------------------- * * OpenGL GBuffer STUFF * * ---------------------------- */ class RenderUtils { public: static GLuint GenerateTextureRGBAF(GLuint width, GLuint height, const GLvoid* data = NULL) { GLuint returnTexture = -1; glGenTextures(1, &returnTexture); glBindTexture(GL_TEXTURE_2D, returnTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, data); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); return returnTexture; } static GLuint GenerateTextureDepth(GLuint width, GLuint height) { GLuint returnTexture = -1; glGenTextures(1, &returnTexture); glBindTexture(GL_TEXTURE_2D, returnTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, width, height, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); glBindTexture(GL_TEXTURE_2D, 0); return returnTexture; } static GLuint GenerateTextureNormal(GLuint width, GLuint height) { GLuint returnTexture = -1; glGenTextures(1, &returnTexture); glBindTexture(GL_TEXTURE_2D, returnTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); glBindTexture(GL_TEXTURE_2D, 0); return returnTexture; } }; #endif
true
8e9aaa3747c96470f1f3ecb99bbbf2d5acd6b43d
C++
shoukna/MyTest
/TheFallingLeaves.cpp
UTF-8
605
2.640625
3
[]
no_license
#include<cstdio> #include<iostream> #include<cstdio> #include<string> #include<sstream> #include<string> using namespace std; const int maxn=1000; int sum[maxn]; void build(int p){ int v; cin>>v; if(v==-1) return; sum[p]=sum[p]+v; build(p-1);build(p+1); } bool init(){ int v; cin>>v; if(v==-1) return false; memset(sum,0,sizeof(sum)); sum[maxn/2]=v; build(maxn/2-1);build(maxn/2+1); return true; } int main(){ int kase=0; while(init()){ int i=0; while(sum[i]==0) i++; cout<<"Case "<<kase++<<":\n"<<sum[i++]; while(sum[i]!=0) cout<<" "<<sum[i++]; cout<<"\n"; } return 0; }
true
448b0571da54cebade46ae7e91231c71624b0ca2
C++
bensont/BensonMooneyGoldstein
/Homework_3/simulation.cpp
UTF-8
3,903
3.265625
3
[]
no_license
#include "tool.h" #include "store.h" #include "customers.h" #include "timecounter.h" #include "customerFactory.h" #include "rentalFactory.h" #include <iostream> #include <queue> #include <time.h> #include "rentalList.h" void BuildStore(Store* t,int prc,std::string cat){ for(int i = 0;i<4;i++){ Tool* testTool = Tool::Create(prc,cat+std::to_string(i+1)); t->ReturnTool(testTool); } } void DayCycle(Store* t,std::queue<Customer*>* c,int curDate){ Customer* cust; while(!c->empty()){ cust = c->front(); c->pop(); if(cust->canRent()){ cust->purchaseTools(t,curDate); } } } //The store (pointer), customer list (pointer for ease), and current date void NightCycle(Store* t, std::vector<Customer*>* c,RentalList* rlist,int curDate){ std::vector<Rental*> returnedTools; for(int i = 0; i< c->size();i++){ returnedTools = c->at(i)->returnTools(rlist,curDate); //std::cout << "hit customer "<< std::to_string(i+1) << std::endl; //make sure it isn't null if(returnedTools.size() != 0){ for(int x = 0; x <returnedTools.size();x++){ rentalFactory::returnTools(t,returnedTools.at(x)); } } } } int main(){ //seed random srand(time(NULL)); //Create main time TimeCounter time(35); //start by building a store Store store; //now we give the store a bunch of tools BuildStore(&store,5,"painting"); BuildStore(&store,7,"concrete"); BuildStore(&store,6,"plumbing"); BuildStore(&store,8,"woodwork"); BuildStore(&store,4,"yardwork"); //create a bunch of customers std::vector<Customer*> customers; //vector to hold customers to process std::queue<Customer*> custqueue; //create the first 3 customers customers.push_back(CustomerFactory::createCasual("cust1")); customers.push_back(CustomerFactory::createBusiness("cust2")); customers.push_back(CustomerFactory::createRegular("cust3")); //fill the rest randomly for(int i = 3;i<10;i++){ customers.push_back(CustomerFactory::createRandom("cust"+std::to_string(i+1))); } //Create a rentallist RentalList rentalList; //If logger is in debug mode also print this if(Logger::isDebug()){ store.PrintStore(); for(int i = 0; i<customers.size();i++){ customers.at(i)->display(); } } //day night cycle while(!time.IsDone()){ if(time.IsDay()){ int r; for(int i = 0; i<customers.size();i++){ r = rand() % 3; //customers have a 1/3 chance of going to store if(r == 0){ custqueue.push(customers.at(i)); } } DayCycle(&store,&custqueue,time.get_day()); //actually deal with customers at store time.AdvanceDay(); //move to night of same day } else{ NightCycle(&store,&customers,&rentalList,time.get_day()); //since every customer needs to check every day, no queue time.AdvanceDay(); //move to day of following morning } } Logger::print("Completed Rentals",message); rentalList.displayLog(); Logger::print("Outstanding Rentals",message); for(int i = 0; i<customers.size();i++){ //std::cout << "?"<< std::endl; customers.at(i)->display(); } //display money earned store.displayRevenue(time.get_day()); //Current number of store Logger::print("Final Store inventory of "+std::to_string(store.NumberOfTools())+" items",message); store.PrintStore(); //time.get_day(); //clean up step //Need to make sure things are cleaned up store.CleanUp(); //clean each customer up customers.clear(); //rental list is self cleaning return 0; }
true
ce9182f40a72720fe59e5999ad1f5359827e0ad8
C++
GregWagner/Learning-Modern-C-Plus-Plus
/Beginning_C_Plus_Plus/Chapter_02_Introducing_Fundamental_Types_of_Data/Examples/Example_01.cpp
UTF-8
418
3.953125
4
[]
no_license
/* * Example 1 Chapter 2 * Writing values of variables to the screen */ #include <iostream> int main() { int apple_count {15}; int orange_count {5}; int total_fruit {apple_count + orange_count}; std::cout << "The value of apple_count is " << apple_count << '\n' << "The value of orange_count is " << orange_count << '\n' << "The value of total_fruit is " << total_fruit << '\n'; }
true
55cff5311e285b53c0bc42e69783623bc280ba27
C++
mofywong/libhal
/brocast/BrocastDevice.cc
UTF-8
1,452
2.5625
3
[ "Apache-2.0" ]
permissive
#include <string> #include "BrocastDevice.hh" BrocastDevice::BrocastDevice() { gst_play_handle = NULL; } BrocastDevice::~BrocastDevice() { this->DevClose(); printf("GpsDevice\n"); } // bool BrocastDevice::DevOpen(const std::string& device) { return true; } //无法检测是否在线,总是返回true,兼容 bool BrocastDevice::Heartbeat() { return true; } bool BrocastDevice::DevClose() { this->Stop(NULL); return true; } bool BrocastDevice::Play(std::string file, void* output) { bool ok = false; if (file.empty()) return ok; if ((gst_play_handle = gst_play_handle_new(GST_PLAY_FILESRC)) && gst_play_set_paraments(gst_play_handle, file.c_str())) { gst_play_start(gst_play_handle, NULL); ok = true; printf("play %s finnash\n", file.c_str()); gst_play_release(gst_play_handle); gst_play_handle = NULL; } return ok; } bool BrocastDevice::Pause(void* output) { if (gst_play_handle) return gst_play_pause(gst_play_handle); else return false; } bool BrocastDevice::Continue(void* output) { if (gst_play_handle) return gst_play_continue(gst_play_handle); else return false; } bool BrocastDevice::Stop(void* output) { if (gst_play_handle) { gst_play_pause(gst_play_handle); gst_play_release(gst_play_handle); gst_play_handle = NULL; } return true; }
true
a87c386b425c35a2234135449e93694874942667
C++
FollyEngine/wemos
/lib/neopixel/helpers.cpp
UTF-8
3,040
3.203125
3
[]
no_license
#include "helpers.h" // this function sets all the pixels in a group to the same colour void leds_set(CRGB *leds, uint len, uint8_t R, uint8_t G, uint8_t B) { fill_solid(leds, len, CRGB(R, G, B)); FastLED.show(); } uint8_t currentColours[3]; typedef struct { const char* name; CRGB colour; } colour_def; // from https://learn.adafruit.com/sparkle-skirt/code-battery // Here is where you can put in your favorite colors that will appear! // just add new {nnn, nnn, nnn}, lines. colour_def myFavoriteColors[] = { {"gold", CRGB::Gold}, {"blue", CRGB::Blue}, {"orange", CRGB::Orange}, {"purple", CRGB::Purple}, {"green", CRGB::Green}, {"off", CRGB::Black}, {"white", CRGB::White}, {"red", CRGB::Red}, {"yellow", CRGB::Yellow}, {"pink", CRGB::Pink} }; #define FAVCOLORS 11u int dim = 20; int moredim = 4; int colour = 3; void updateColourRGB(CRGB *leds, uint len, int red, int green, int blue) { red = red / moredim; green = green / moredim; blue = blue / moredim; leds_set(leds, len, red, green, blue); currentColours[0] = red; currentColours[1] = green; currentColours[2] = blue; } void updateColour(CRGB *leds, uint len, const char * colourName) { for (uint i = 0; i < FAVCOLORS; i++) { if (strcmp(colourName, myFavoriteColors[i].name) == 0) { colour = i; break; } } Serial.printf("Asked for %s, got %s\n", colourName, myFavoriteColors[colour].name); fill_solid(leds, len, myFavoriteColors[colour].colour); FastLED.show(); } // from https://learn.adafruit.com/neopixel-pixie-dust-bag/arduino-code #define DELAY_MILLIS 10 // how long each light stays bright for, smaller numbers are faster #define DELAY_MULT 8 // Randomization multiplier on the delay speed of the effect bool oldState = HIGH; //sets the initial variable for counting touch sensor button pushes void pixie_dust(CRGB *leds, uint len, int bright, unsigned long twinkleDelay) { //color (0-255) values to be set by cycling touch switch, initially GOLD uint8_t red = currentColours[0]; uint8_t green = currentColours[1]; uint8_t blue = currentColours[2]; //sparkling int p = random(len-1); //select a random pixel leds[p] = CRGB(red*bright, green*bright, blue*bright); FastLED.show(); delay(twinkleDelay * random(DELAY_MULT) ); //delay value randomized to up to DELAY_MULT times longer leds[p] = CRGB(red, green, blue); FastLED.show(); delay(twinkleDelay * random(DELAY_MULT) ); //delay value randomized to up to DELAY_MULT times longer } // Fadeout... starts at bright white and fades to almost zero void fadeout(CRGB *leds, uint len) { // swap these two loops to spin around the LEDs for (uint16_t fade = 255; fade > 0; fade = fade - 17) { for (uint16_t i = 0; i < len; i++) { // now we will 'fade' it in steps leds[i] = CRGB(fade, fade, fade); } FastLED.show(); delay(5); // milliseconds } // now make sure they're all set to 0 for (uint16_t i = 0; i < len; i++) { leds[i] = CRGB(0, 0, 0); } FastLED.show(); }
true
f6c762aa28b2637ca2ed986a9fa5085fd356c5b9
C++
RIckyBan/competitive-programming
/AtCoder/BeginnerContest/014/AtColor.cpp
UTF-8
612
2.78125
3
[]
no_license
#include <iostream> #include <cmath> #include <algorithm> using namespace std; #define ll long long int N, a, b, Arr[1000005] = {0}, ans, low = 0; void show_Array(){ for(int i = 0; i < low; i++) cout << Arr[i] << " "; cout << endl; } int main(){ cin >> N; for(int i = 0; i < N; i++){ cin >> a >> b; Arr[a] += 1; Arr[b+1] -=1; low = max(low, b+1); } // show_Array(); ans = Arr[0]; for(int i = 1; i <= low; i++){ Arr[i] += Arr[i-1]; ans = max(ans, Arr[i]); } // show_Array(); cout << ans << endl; }
true
ac5d97d731b8306e93aaa1d239d6d574af90ddb8
C++
silvianaim02/CPP-NAIM
/gradebook.cpp
UTF-8
620
2.875
3
[]
no_license
/*Fungsi definisi untuk kelas gradebook yang memecahkan Program kelas rata-rata dengan counter-dikontrol pengulangan */ #include <iostream> #include "GradeBook.h" //include definisi dari kelas GradeBook using name space std; //Konstruktor menginisialisasi coursename dengan string yang diberikan sebagai argumen GradeBook (string name) { setCoursename(nama); //memvalidasi dan menyimpan courseName }//akhiri konstruktor GradeBook //fungsi untuk memasang courseName; //Memastikan bahwa nama kursus memiliki paling 25 karakter void GradeBook :: setCourseName(string name) { if(nama.ukuran()) }
true
745784df1e0e57efa771960e86329b439bab9b07
C++
chengyongyuan/yanetlib
/src/net/poller.h
UTF-8
2,757
2.671875
3
[ "MIT" ]
permissive
#ifndef YANETLIB_NET_POLLER_H #define YANETLIB_NET_POLLER_H //This file implment a sys poller. currently: select //and epoll is implemented. epoll is default for linux //other system we just use select now (I don't think //we will use other unix like system in short future. // //colincheng 2014/06/29 // //TODO //1. Refactor C version REDIS, decouple dependence (DONE) //2. remove hardcode MAX_POLL_SIZE #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <string> #include <vector> namespace yanetlib { namespace net { #define YANET_MAX_POLL_SIZE 4*1024 #define YANET_NONE 0 #define YANET_READABLE 1 #define YANET_WRITABLE 2 #define YANET_MASK (YANET_READABLE | YANET_WRITABLE) class Poller { public: //Init Poller //RETURN: 0:ok, -1:erro virtual int InitPoller() = 0; //Add a event to the poller //RETURN: 0:ok, -1:erro virtual int AddEvent(int fd, int mask) = 0; //Delete a event from the poller //RETURN: true: Del All Event(read&write), false: still have //some event to poll virtual bool DelEvent(int fd, int mask) = 0; //Poll for avaiable events. //put readable event in 'readable vec.', writeable //event in 'writeable vec.' virtual void PollEvent(struct timeval* tvp, std::vector<int>* readable, std::vector<int>* writeable) = 0; //Get poller name virtual std::string GetName() const = 0; virtual ~Poller() { } }; class Selecter : public Poller { public: //poller private data struct InternalData; //Constructor Selecter(); ~Selecter(); int InitPoller(); int AddEvent(int fd, int mask); bool DelEvent(int fd, int mask); void PollEvent(struct timeval* tvp, std::vector<int>* readable, std::vector<int>* writeable); std::string GetName() const { return "Selecter"; } private: //diable copy Selecter(const Selecter&); void operator=(const Selecter&); InternalData* data_; }; class Epoller : public Poller { public: //Poller private data struct InternalData; Epoller(); ~Epoller(); int InitPoller(); int AddEvent(int fd, int mask); bool DelEvent(int fd, int delmask); void PollEvent(struct timeval* tvp, std::vector<int>* readable, std::vector<int>* writeable); std::string GetName() const { return "Epoller"; } private: //disable copy Epoller(const Epoller&); void operator=(const Epoller&); InternalData* data_; }; } //namespace net } //namespace yanetlib #endif //poller.h
true
5091a64203ffb7fc60b5938b9ff09920a61f0770
C++
shawnshuailin/Myleetcode
/3sum_closest.cpp
UTF-8
2,691
2.875
3
[]
no_license
//run time 20ms int threeSumClosest(vector<int>& nums, int target) { std::sort(nums.begin(), nums.end()); return target - sumClosestRst(nums, target, 3, nums.size()); } int sumClosestRst(vector<int>& nums, int target, int iRemain, int iMaxIdx) { int iCurClosestRst, iCurClosestRstAbs; if (iRemain == 1) { iCurClosestRst = 0; if (iMaxIdx > 0) { if (target <= nums[0]) { iCurClosestRst= target - nums[0]; iCurClosestRstAbs = std::abs(iCurClosestRst); } else if (target >= nums[iMaxIdx - 1]) { iCurClosestRst= target - nums[iMaxIdx - 1]; iCurClosestRstAbs = std::abs(iCurClosestRst); } else { int iMaxBoundIdx = iMaxIdx - 1; int iMinBoundIdx = 0; while (1) { if (iMaxBoundIdx - iMinBoundIdx <= 1) break; int iCurIdx = (iMaxBoundIdx + iMinBoundIdx) / 2; if (target == nums[iCurIdx]) { return 0; } else if (target < nums[iCurIdx]) { iMaxBoundIdx = iCurIdx; } else if (target > nums[iCurIdx]) { iMinBoundIdx = iCurIdx; } } iCurClosestRst= target - nums[iMaxBoundIdx]; iCurClosestRstAbs = std::abs(iCurClosestRst); if (std::abs(target - nums[iMinBoundIdx]) < iCurClosestRstAbs) { iCurClosestRst = target - nums[iMinBoundIdx]; } } } return iCurClosestRst; } iCurClosestRstAbs = -1; int iCurBranchRst; int iLastNum = nums[iMaxIdx - 1]; iCurBranchRst = sumClosestRst(nums, target - iLastNum, --iRemain, --iMaxIdx); if (iCurBranchRst == 0) return 0; if (iCurClosestRstAbs < 0 || std::abs(iCurBranchRst) < iCurClosestRstAbs) { iCurClosestRst = iCurBranchRst; iCurClosestRstAbs = std::abs(iCurBranchRst); } if (iMaxIdx > iRemain) { iCurBranchRst = sumClosestRst(nums, target, iRemain + 1, iMaxIdx); if (iCurBranchRst == 0) return 0; if (std::abs(iCurBranchRst) < iCurClosestRstAbs) { iCurClosestRst = iCurBranchRst; iCurClosestRstAbs = std::abs(iCurBranchRst); } } return iCurClosestRst; }
true
e1512d0df3e48d459cdd49783358f75259793a74
C++
abpwrs/ece-5490-sp19
/inclass/inclass1-abpwrs/ic2/ic2.cxx
UTF-8
1,072
2.921875
3
[ "MIT" ]
permissive
#include "itkImage.h" #include "itkImageFileReader.h" #include <iostream> // Based off of // https://itk.org/ITKExamples/src/IO/ImageBase/ReadAnImage/Documentation.html int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " myFile.nii.gz"; std::cerr << std::endl; return EXIT_FAILURE; } const std::string file_name = argv[1]; const unsigned int Dimension = 3; using PixelType = unsigned char; using ImageType = itk::Image<PixelType, Dimension>; using ReaderType = itk::ImageFileReader<ImageType>; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(file_name); reader->Update(); ImageType::Pointer image = reader->GetOutput(); std::cout << "Origin: " << image->GetOrigin() << std::endl; std::cout << "Spacing: " << image->GetSpacing() << std::endl; ImageType::RegionType region = image->GetLargestPossibleRegion(); std::cout << "Size: " << region.GetSize() << std::endl; return EXIT_SUCCESS; }
true
da769b2b33614700b5eabc4449e3da7ca0810a0d
C++
git-vault/CBCompiler
/Runtime/cb_image.cpp
UTF-8
777
2.5625
3
[]
no_license
#include "image.h" #include "systeminterface.h" #include "error.h" Image *CBF_makeImage(int w, int h) { Image *img = new Image(w, h); return img; } Image *CBF_loadImage(CBString str) { Image *img = Image::load(str); if (!img && sys::errorMessagesEnabled()) { error(LString(U"LoadImage failed! \"%1\"").arg(str)); } return img; } void CBF_drawImage(Image *img, float x, float y) { img->draw(x, y); } void CBF_maskImage(Image *img, int r, int g, int b) { img->mask(al_map_rgb(r, g, b)); } void CBF_maskImage(Image *img, int r, int g, int b, int a) { img->mask(al_map_rgba(r, g, b, a)); } void CBF_drawToImage(Image *img) { img->activate(); } int CBF_imageWidth(Image *img) { return img->width(); } int CBF_imageHeight(Image *img) { return img->height(); }
true
b02eb82d149f97b6909ce33d8ea2e637a5329d0e
C++
ILLLIGION/FileSystem
/include/file.hpp
UTF-8
138
2.5625
3
[]
no_license
#include "iostream" #include "string" struct File { public: std::string name; File(std::string name1): name(name1) {}; ~File() {}; };
true
d0b7527b3320f529d2655aba1b4b787fcbd3bddf
C++
Gnob/algorithm
/boj_lecture/day3/contest_or_intern.cpp
UTF-8
562
2.65625
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <cstring> using namespace std; int main() { int N, M, K, cnt = 0; cin >> N >> M >> K; if (N >= 2 * M) { cnt = M; N = N - 2 * M; M = 0; } else { cnt = N/2; M = M - cnt; N = N - 2 * cnt; } while (K-- > 0) { if (M > 0) { M--; continue; } if (N > 0) { N--; continue; } cnt--; N += 2; } cout << cnt; return 0; }
true
5794b57bfb9b0a6a5f3099cc308c087630c993d8
C++
EuiSeong-Moon/Algorithm
/Baekjoon/View.cpp
UTF-8
585
2.96875
3
[]
no_license
#include <iostream> using namespace std; int arr[1000]; int max_value(int a, int b, int c, int d) { if (a < b) a = b; if (c < d) c = d; if (a < c) a = c; return a; } int main(void) { for (int test = 0; test < 10; test++) { int N,buf,answer=0; cin >> N; for (int i = 0; i < N; i++) { cin >> buf; arr[i] = buf; } for (int i = 2; i < N-2; i++) { int max=max_value(arr[i - 2], arr[i - 1], arr[i + 1], arr[i + 2]); int values = arr[i] - max; if (values > 0) answer += values; } cout << "#" << test + 1 << " " << answer << endl; } return 0; }
true
1edcce462a7afdb695579378275ebdc33d6e2e3c
C++
DepthDeluxe/DCPU-16
/DCPU-16/InterruptQueue.cpp
UTF-8
999
3.234375
3
[]
no_license
#ifndef INTERRUPT_QUEUE_CPP #define INTERRUPT_QUEUE_CPP #include "InterruptQueue.h" InterruptQueue::InterruptQueue() { head = 0; count = 0; } BOOL InterruptQueue::EnQueue(UINT16 item) { // fail if the queue has gotten too large if (count == INTERRUPT_QUEUE_MAX_SIZE) return FALSE; // get the next array value past the tail int tail = (head + count) % INTERRUPT_QUEUE_MAX_SIZE; // save the message and increase the count messages[tail] = item; count++; return TRUE; } UINT16 InterruptQueue::DeQueue() { // return -1 if the queue is empty if (isEmpty()) return 0xffff; UINT16 returnValue = messages[head]; // decrement the count and increment the head, if it has reached the end of the array, go back to start count--; head++; if (head == INTERRUPT_QUEUE_MAX_SIZE) head = 0; return returnValue; } BOOL InterruptQueue::isEmpty() { return count == 0; } UINT InterruptQueue::Length() { return count; } #endif
true
5590dee383fda2cf289ca0250d853a5d13de56c5
C++
meowosaurus/Nebula_Engine
/Nebula_Engine/Transform.cpp
UTF-8
1,272
3.015625
3
[]
no_license
#include "Transform.h" void Transform::Init() { pos = glm::vec3(); rota = glm::vec3(); scale = glm::vec3(); } void Transform::Update() { } void Transform::SetPosition(glm::vec3 position) { pos = position; } void Transform::SetPosition(float x, float y, float z) { rota = glm::vec3(x, y, z); } void Transform::SetRotation(glm::vec3 rotation) { rota = rotation; } void Transform::SetRotation(float x, float y, float z) { rota = glm::vec3(x, y, z); } void Transform::SetScale(glm::vec3 scale) { this->scale = scale; } void Transform::SetScale(float x, float y, float z) { scale = glm::vec3(x, y, z); } void Transform::Rotate(glm::vec3 rotation) { rota += rotation; } void Transform::Rotate(float x, float y, float z) { rota += glm::vec3(x, y, z); } void Transform::LookAt(glm::vec3 pos) { rota = pos; } void Transform::LookAt(glm::vec2 pos) { rota = glm::vec3(pos.x, pos.y, 0.0f); } void Transform::LookAt(float x, float y, float z) { rota = glm::vec3(x, y, z); } float Transform::GetDegrees() { return degrees; } void Transform::SetDegrees(float degrees) { this->degrees = degrees; } glm::vec3 Transform::GetPosition() { return pos; } glm::vec3 Transform::GetRotation() { return rota; } glm::vec3 Transform::GetScale() { return scale; }
true
1b599b02fb35941a4cff6a7766ff58ecc4270dc6
C++
miusang/code
/algorithm/sort/bucket_sort/bucket_sort.cpp
UTF-8
1,750
3.53125
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <vector> using std::vector; void array_print(int *nums, int len) { for (int i = 0; i < len; i++) { printf("%d ", nums[i]); } printf("\n"); } void insert_sort(vector<int> &nums) { int i, j; for (i = nums.size() - 1; i > 0; i--) { j = i; int tmp = nums[i - 1]; while (j < nums.size() && nums[j] < tmp) { nums[j - 1] = nums[j]; j++; } nums[j - 1] = tmp; } for (i = 0; i < nums.size(); i++) { printf("%d ", nums[i]); } printf("\n"); } int main(int argc, char *argv[]) { if (argc < 2) { return 0; } int len = atoi(argv[1]); int *nums = new int[len]; for (int i = 0; i < len; i++) { nums[i] = rand() % 300; } array_print(nums, len); // 1. put elements of nums into bucket. int max_val = nums[0]; int min_val = nums[0]; for (int i = 1; i < len; i++) { if (max_val < nums[i]) { max_val = nums[i]; } if (min_val > nums[i]) { min_val = nums[i]; } } int bucket_step = len; int bucket_count = (max_val - min_val) / bucket_step + 1; vector<int> *buckets = new vector<int>[bucket_count]; for (int i = 0; i < len; i++) { int bucket_index = (nums[i] - min_val) / bucket_step; buckets[bucket_index].push_back(nums[i]); } for (int i = 0; i < bucket_count; i++) { insert_sort(buckets[i]); } int k = 0; for (int i = 0; i < bucket_count; i++) { for (int j = 0; j < buckets[i].size(); j++) { nums[k] = buckets[i][j]; k++; } } array_print(nums, len); return 0; }
true
2305e22071fe8b6d78ddc392aca41a1dd06aa767
C++
f13rce/KFA-KilledFromAfar
/KFAClient/Source/utils/NetworkSimulator.h
UTF-8
1,110
2.5625
3
[]
no_license
#ifndef _NETWORKSIMULATOR_H_ #define _NETWORKSIMULATOR_H_ #include <cstdint> #include <memory> #include <list> #include "data/messages/NetcodeMessages.h" namespace Net13 { class NetworkSimulator { public: NetworkSimulator(); ~NetworkSimulator(); void Update(); void ProcessMessage(std::shared_ptr<Messages::Message> apMessage, uint16_t aConnectionID, bool aStoreACK); void StartSimulation(const uint32_t acMinimumDelayMS, const uint32_t acRandomDelayMS, const float acPacketLossPct, const float acPacketDuplicationPct); void StopSimulation(); const bool IsSimulating() const; private: void SendMessages(bool aForceSend = false); bool m_simulating; uint32_t m_minimumDelay; uint32_t m_randomDelay; uint32_t m_packetLoss; // Percentage * 1000 (is easier with rand()) uint32_t m_packetDuplication; // Percentage * 1000 (is easier with rand()) struct ModifiedMessage { std::shared_ptr<Messages::Message> pMessage; uint16_t connectionID; bool storeACK; int32_t sendTime; // clock() + delay }; std::list<ModifiedMessage> m_messagesToSend; }; } #endif
true
3f05271b24bcf7632d616117d54bc1fbc387066b
C++
weimingtom/voiceprint
/asrplus-engine/ivector/plda.cc
UTF-8
3,741
2.625
3
[]
no_license
/* * plda.cc * * Created on: Mar 28, 2018 * Author: tao */ #include "ivector/plda.h" #include "util/math.h" #include <fstream> float Plda::TransformIvector(const PldaConfig &config, const Vector &ivector, int32 num_examples, Vector *transformed_ivector) const{ Vector tmp(ivector), tmp_out(ivector.Dim()); assert(ivector.Dim() == Dim() && transformed_ivector->Dim() == Dim()); float normalization_factor; transformed_ivector->CopyFromVec(offset_); transformed_ivector->AddMatVec(1.0, transform_, kNoTrans, ivector, 1.0); if (config.simple_length_norm) normalization_factor = sqrt(transformed_ivector->Dim()) / transformed_ivector->Norm(2.0); else normalization_factor = GetNormalizationFactor(*transformed_ivector, num_examples); if (config.normalize_length) transformed_ivector->Scale(normalization_factor); return normalization_factor; } float Plda::LogLikelihoodRatio(const Vector &transformed_train_ivector, int32 n, const Vector &transformed_test_ivector)const{ //std::cout<<"the sum value of transformed_train_ivector is: "<<transformed_train_ivector.Sum()<<std::endl; //std::cout<<"the sum value of transformed_test_ivector is :"<<transformed_test_ivector.Sum()<<std::endl; int32 dim = Dim(); float loglike_given_class, loglike_without_class; { // work out loglike_given_class. // "mean" will be the mean of the distribution if it comes from the // training example. The mean is \frac{n \Psi}{n \Psi + I} \bar{u}^g // "variance" will be the variance of that distribution, equal to // I + \frac{\Psi}{n\Psi + I}. Vector mean(dim); Vector variance(dim); for (int32 i = 0; i < dim; i++) { mean(i) = n * psi_(i) / (n * psi_(i) + 1.0) * transformed_train_ivector(i); variance(i) = 1.0 + psi_(i) / (n * psi_(i) + 1.0); } float logdet = variance.SumLog(); Vector sqdiff(transformed_test_ivector); sqdiff.AddVec(-1.0, mean); sqdiff.ApplyPow(2.0); variance.InvertElements(); loglike_given_class = -0.5 * (logdet + M_LOG_2PI * dim + VecVec(sqdiff, variance)); } { // work out loglike_without_class. Here the mean is zero and the variance // is I + \Psi. Vector sqdiff(transformed_test_ivector); // there is no offset. sqdiff.ApplyPow(2.0); Vector variance(psi_); variance.Add(1.0); // I + \Psi. double logdet = variance.SumLog(); variance.InvertElements(); loglike_without_class = -0.5 * (logdet + M_LOG_2PI * dim + VecVec(sqdiff, variance)); } float loglike_ratio = loglike_given_class - loglike_without_class; return loglike_ratio; } void Plda::ComputeDerivedVars() { assert(Dim() > 0); offset_.Resize(Dim()); offset_.AddMatVec(-1.0, transform_, kNoTrans, mean_, 0.0); } void Plda::Read(std::ifstream &is, bool binary){ ExpectToken(is, binary, "<Plda>"); mean_.Read(is, binary); transform_.Read(is, binary); psi_.Read(is, binary); ExpectToken(is, binary, "</Plda>"); ComputeDerivedVars(); } float Plda::GetNormalizationFactor(const Vector &transformed_ivector, int32 num_examples) const{ assert(num_examples > 0); Vector transformed_ivector_sq(transformed_ivector.Dim()); transformed_ivector_sq.CopyFromVec(transformed_ivector); transformed_ivector_sq.ApplyPow(2.0); Vector inv_covar(psi_); inv_covar.Add(1.0 / num_examples); inv_covar.InvertElements(); float dot_prod = VecVec(inv_covar, transformed_ivector_sq); return sqrt(Dim() / dot_prod); }
true
81dbe6572a1d122dcb753ace69fee4efadaccc7a
C++
keshav-kabra/DataStructures
/tempCodeRunnerFile.cpp
UTF-8
325
3.46875
3
[]
no_license
void bubbleup(int *a, int son ) { while(son!=0) { int dad = (son-1)/2; // cout<<"\nson is "<<a[son]<<"and dad is "<<a[dad]; if(a[dad] > a[son]) { swap(&a[dad], &a[son]); // cout<<" value is swaped"; } else return; son = dad; } }
true
2b82d26536efcc2d9e0dc4c1ceb107e262340363
C++
rhasan/problem-solving-practice
/problem-solving-cpp/simple-in-one-directory/uva-11799.cpp
UTF-8
396
2.84375
3
[]
no_license
#include <stdio.h> #include <limits> // std::numeric_limits using namespace std; int main() { int T, N, c, max; int NEG_INF = numeric_limits<int>::min(); scanf("%d", &T); for(int tc = 1; tc <= T; tc++) { scanf("%d", &N); max = NEG_INF; for(int i = 0; i < N; i++) { scanf("%d", &c); if(max < c) { max = c; } } printf("Case %d: %d\n", tc, max); } return 0; }
true
e8ea6bcecf3a07b9ce2aaf9c4f1b00ff6f340a6d
C++
nikhilmoray/Data_structure
/Singly_linklist.cpp
UTF-8
5,314
3.296875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }*head; void insert(int data) { struct node* newnode = (struct node *) calloc(1, sizeof(struct node)); newnode->data = data; if(head == NULL) { head = newnode; newnode->next = NULL; } else { #if 0 newnode->next = head; head = newnode; #else struct node *last = head; while(last->next != NULL) last = last->next; last->next = newnode; #endif } } /* Insert with recurrtion */ void insert(struct node **ptr, int data) { if(*ptr == NULL) { struct node *newnode = new (struct node); newnode->next = NULL; newnode->data = data; *ptr = newnode; } else { insert((&(*ptr)->next), data); } } struct node *newnode(int data) { struct node *curr = new struct node; curr->data = data; curr->next = NULL; return curr; } void insertatN(int data, int pos) { struct node *curr = head; // Insert at head if(!pos && curr) { struct node *curr = newnode(data); curr->next = head; head = curr; } // Insert rest wehere else { // Go one step back to get the exact pos --pos; while(pos) { --pos; if(curr != NULL) curr = curr->next; else return; } struct node *tmp = curr->next; curr->next = newnode(data); curr->next->next = tmp; } } bool deletenode(int data) { char ret = 1, flag = 0; struct node *prev = NULL; struct node *tmphead = head; while(tmphead != NULL) { if(tmphead->data == data) { if(prev != NULL) prev->next = tmphead->next; else head = tmphead->next; flag = 1; } prev = tmphead; tmphead = tmphead->next; } if(flag) ret = 0; return ret; } void reverselist(void) { struct node *prev = NULL; struct node *curr = head; struct node *nxt = NULL; while(curr != NULL) { nxt = curr->next; curr->next = prev; prev = curr; curr = nxt; } head = prev; } struct node *reverseklist(struct node *head, int k) { struct node *prev = NULL; struct node *curr = head; struct node *nxt = NULL; int i = k; while(curr != NULL && i > 0) { nxt = curr->next; curr->next = prev; prev = curr; curr = nxt; --i; } if(nxt) head->next = reverseklist(nxt, k); return prev; } void printlist(void) { struct node *tmp = head; while(tmp != NULL) { printf("##%d\n", tmp->data); tmp = tmp->next; } } int findmiddle(void) { struct node *fastptr = head; struct node *slowptr = head; while(fastptr != NULL && fastptr->next != NULL) { fastptr = fastptr->next->next; slowptr = slowptr->next; } return slowptr->data; } struct node *findloop(void) { struct node *fastptr = head; struct node *slowptr = head; int flag = 0; while(fastptr->next != NULL) { fastptr = fastptr->next->next; slowptr = slowptr->next; if(fastptr == slowptr) { flag = 1; break; } } if(!flag) slowptr = NULL; return slowptr; } void addloop(void) { struct node *tmp = head; while(tmp != NULL) { if(tmp->data == 4) { tmp->next = head; break; } tmp = tmp->next; } } void removeloop(void) { struct node *loopnode = findloop(); struct node *tmp = loopnode; while(tmp->next != loopnode) { tmp = tmp->next; } tmp->next = NULL; } void listsort(void) { struct node *curr = head; struct node *currplus = NULL; while(curr != NULL) { currplus = curr->next; while(currplus != NULL) { if(curr->data > currplus->data) { int tmp = curr->data; curr->data = currplus->data; currplus->data = tmp; } currplus = currplus->next; } curr = curr->next; } } int main() { int delnum; insert(1); insert(2); insert(3); insert(4); printlist(); printf("##########\n"); insertatN(6, 2); printlist(); deletenode(1); reverselist(); printf("\n\n"); printlist(); delnum = findmiddle(); printf("MIDDLE : %d\n", delnum); /* Added for testing purpose */ addloop(); struct node *loopnode = findloop(); printf("LoopNode : %d\n", loopnode->data); removeloop(); printlist(); return 0; }
true
bba4e6dc2886617e5eb3c10db2f3d57ba365ba27
C++
didix21/DesignPatterns
/FactoryPattern/AbstractFactoryPattern/FactoryPizza/src/NYPizzaStore.cpp
UTF-8
1,004
3.09375
3
[ "Apache-2.0" ]
permissive
#include "NYPizzaStore.hpp" NYPizzaStore::NYPizzaStore() { } NYPizzaStore::~NYPizzaStore() { } std::unique_ptr<Pizza> NYPizzaStore::createPizza(std::string type) { std::unique_ptr<Pizza> pizza{nullptr}; std::unique_ptr<PizzaIngredientFactory> ingredientFactory = std::make_unique<NYPizzaIngredientFactory>(); if (type == "cheese") { pizza = std::make_unique<CheesePizza>(ingredientFactory); pizza->setName("New York Style Cheese Pizza"); } else if (type == "pepperoni") { pizza = std::make_unique<PepperoniPizza>(ingredientFactory); pizza->setName("New York Style Pepperoni Pizza"); } else if (type == "clam") { pizza = std::make_unique<ClamPizza>(ingredientFactory); pizza->setName("New York Style Clam Pizza"); } else if (type == "veggie") { pizza = std::make_unique<VeggiePizza>(ingredientFactory); pizza->setName("New York Style Veggi Pizza"); } return pizza; }
true
0cd0209e55e0817ceb64e0604b0757ed9ba15f25
C++
liuqipei/ns3-dtn-mestrado
/model/bp-creation-timestamp.h
UTF-8
1,548
2.59375
3
[ "MIT" ]
permissive
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ #ifndef BP_CREATION_TIMESTAMP_H #define BP_CREATION_TIMESTAMP_H #include <stdint.h> #include <iostream> #include "ns3/buffer.h" #include "ns3/nstime.h" using namespace std; namespace ns3 { namespace bundleProtocol { /** * \ingroup bundle * * \brief Implements a timestamp holding creation time and a sequence number. * * */ class CreationTimestamp { public: CreationTimestamp (); explicit CreationTimestamp (uint64_t time, uint64_t sequence); // explicit CreationTimestamp (Time time, uint64_t sequence); CreationTimestamp (const CreationTimestamp& timestamp); virtual ~CreationTimestamp (); Time GetTime () const; uint64_t GetSeconds () const; uint64_t GetSequence () const; uint64_t GetSerializedSize () const; uint64_t Serialize (uint8_t *buffer) const; static CreationTimestamp Deserialize (uint8_t const*buffer); uint64_t Serialize (Buffer::Iterator& start) const; static CreationTimestamp Deserialize (Buffer::Iterator& start); bool operator == (const CreationTimestamp& other) const; bool operator != (const CreationTimestamp& other) const; bool operator < (const CreationTimestamp& other) const; bool operator > (const CreationTimestamp& other) const; uint64_t m_time; private: uint64_t m_sequence; static Time m_previousTime; static uint64_t m_previousSeq; }; ostream& operator<< (ostream& os, const CreationTimestamp& timestamp); }} // namespace bundleProtocol, ns3 #endif /* BP_CREATION_TIMESTAMP_H */
true
6625211d3f32af6590f7ff92286596c8ed258bc8
C++
C-SWARM/pgfem-3d-input-stack
/preprocessor/include/initial_conditions.h
UTF-8
3,073
2.546875
3
[ "BSD-3-Clause" ]
permissive
/* -*- mode: c++; -*- */ /* HEADER */ /** * AUTHORS: * Aaron Howell * Matt Mosby * Ivan Viti */ #pragma once #ifndef CON3D_IC_H #define CON3D_IC_H #include "t3d_model.h" #include <cstdlib> #include <vector> #include <iostream> #include "structures.h" /** * \brief Base IC object. * * Contains the boundary condition information. */ template<typename T> class BaseIC { public: BaseIC():_ic(){}; void set_ic(const std::vector<T> &ic); void set_ic_0(T x0); void set_ic_1(T x1); void set_ic_2(T x2); void set_ic_3(T x3); void set_ic_4(T x4); void set_ic_5(T x5); const std::vector<T>& ic() const; T ic_0() const; T ic_1() const; T ic_2() const; T ic_3() const; T ic_4() const; T ic_5() const; std::vector<T> _ic; }; /** * \brief IC object for model entities. */ template<typename T> class ModelIC : public BaseIC<T> { public: ModelIC():_model(-1,-1){} void set_model_type(const size_t t); void set_model_id(const size_t i); size_t model_type() const; size_t model_id() const; T3dModel model() const; void read(std::istream &in); void write(std::ostream &out) const; static bool compare_model(const ModelIC<T> &a, const ModelIC<T> &b); //Human readable Stuff std::vector <double> grabT3d(std::vector<double> claw); void putIC(Input_Data inputs, int i, int physics); private: T3dModel _model; }; // I/O operators template<typename T> inline std::istream& operator>>(std::istream &lhs, ModelIC<T> &rhs){rhs.read(lhs); return lhs;} template<typename T> inline std::ostream& operator<<(std::ostream &lhs, const ModelIC<T> &rhs){rhs.write(lhs); return lhs;} /** * \brief IC object for nodes. */ template<typename T> class NodeIC : public BaseIC<T> { public: NodeIC():_node_id(-1) {} void set_node_id(size_t i); size_t node_id() const; void write(std::ostream &out) const; static bool compare_node_id(const NodeIC<T> &a, const NodeIC<T> &b); private: size_t _node_id; }; // I/O operators template<typename T> inline std::ostream& operator<<(std::ostream &lhs, const NodeIC<T> &rhs){rhs.write(lhs); return lhs;} /** * \brief Container for all model entity boundary conditions. */ template<typename T> class ModelICList : public std::vector< ModelIC<T> > { public: void read(std::istream &in); void write(std::ostream &out) const; void sort_model(); }; // I/O operators template<typename T> inline std::istream& operator>>(std::istream &lhs, ModelICList<T> &rhs){rhs.read(lhs); return lhs;} template<typename T> inline std::ostream& operator<<(std::ostream &lhs, const ModelICList<T> &rhs){rhs.write(lhs); return lhs;} /** * \brief Container for all nodal boundary conditions. */ template<typename T> class NodeICList : public std::vector< NodeIC<T> > { public: void write(std::ostream &out) const; void sort_node_id(); void write_replacements(Input_Data inputs, int physics, std::ofstream &out); }; // I/O operator template<typename T> std::ostream& operator<<(std::ostream &lhs, const NodeICList<T> &rhs){rhs.write(lhs); return lhs;} #endif
true
37caee6d09e75bfb87b5aa552d64201de7d23de0
C++
goodspeed24e/Programming
/Effective STL/estl-examples/43-1.cpp
UTF-8
3,215
3.28125
3
[ "MIT" ]
permissive
// // Example from ESTL Item 43 // // Fails under MSVC/native lib (mem_fun_ref problem) // #include <string> #include <iostream> #include <list> #include <deque> #include "ESTLUtil.h" #include "Widget.h" // C API: this function takes a pointer to an array of at most arraySize // doubles and writes data to it. It returns the number of doubles written. size_t fillArray(double *pArray, size_t arraySize) { size_t i; for (i = 0; i < arraySize; i++) pArray[i] = i; return i; } int main() { using namespace std; using namespace ESTLUtils; list<Widget> lw; lw.push_back(Widget(1)); lw.push_back(Widget(2)); lw.push_back(Widget(3)); lw.push_back(Widget(4)); for (list<Widget>::iterator i = lw.begin(); i != lw.end(); ++i) { i->redraw(); } for_each(lw.begin(), lw.end(), // see Item 41 for info mem_fun_ref(&Widget::redraw)); // on mem_fun_ref { for (list<Widget>::iterator i = lw.begin(); i != lw.end(); ++i) { i->redraw(); } } for_each(lw.begin(), lw.end(), // this call evaluates mem_fun_ref(&Widget::redraw)); // lw.end() exactly once //////////////////////////////////////////////////////////////////// const int maxNumDoubles = 10; double data[maxNumDoubles]; // create local array of // max possible size deque<double> d; // create deque, put d.push_back(2.5); // data into it d.push_back(3.7); d.push_back(-191.5); d.push_back(2.2360679); deque<double> save_d = d; printContainer("deque initially: ", d); size_t numDoubles = fillArray(data, maxNumDoubles); // get array data from API { for (size_t i = 0; i < numDoubles; ++i) { // for each i in data, d.insert(d.begin(), data[i] + 41); // insert data[i]+41 at the } // front of d; this code } // has a bug! printContainer("deque after inserts: ", d); ///////////////////////////////////////////////////////////////////////// d = save_d; printContainer("\ndeque initialized again: ", d); { deque<double>::iterator insertLocation = d.begin(); // remember d's for (size_t i = 0; i < numDoubles; ++i) { // insert data[i]+41 d.insert(insertLocation++, data[i] + 41); // at insertLocation, then } // increment } // insertLocation; this // code is also buggy! printContainer("deque after inserts, 2nd try: ", d); ///////////////////////////////////////////////////////////////////////// d = save_d; printContainer("\ndeque initialized yet again: ", d); { deque<double>::iterator insertLocation = d.begin(); // as before for (size_t i = 0; i < numDoubles; ++i) { // update insertLocation insertLocation = // each time insert is d.insert(insertLocation, data[i] + 41); // called to keep the ++insertLocation; // iterator valid, then } // increment it } printContainer("deque after inserts, 3rd try: ", d); d = save_d; printContainer("\ndeque initialized yet again: ", d); transform(data, data + numDoubles, // copy all elements inserter(d, d.begin()), // from data to the front bind2nd(plus<double>(), 41)); // of d, adding 41 to each printContainer("deque after transform: ", d); return 0; }
true
8c37c06590449aba399ab64477585fbaba794f59
C++
ClubEngine/PLT
/client/mouseinput/main.cpp
UTF-8
6,928
2.84375
3
[]
no_license
#include <iostream> #include <SFML/Graphics.hpp> #include <cmath> using namespace std; int main() { bool mouseispressed; struct selected { sf::Vector2i p1; sf::Vector2i p2; }; float aux; selected selected; float a = -10.0; float b = -10.0; float c = -10.0; float d = -10.0; int width =800; int height =600; int map[width/10][height/10]; for (int i = 0 ; i < width/10 ; i++) { for (int j = 0 ; j < height/10 ; j++) { map[i][j] = 0; } }; sf::RenderWindow window(sf::VideoMode(width,height), "mouseInput",sf::Style::Default); window.setKeyRepeatEnabled(false); sf::RectangleShape cursor(sf::Vector2f(10,10)); sf::RectangleShape herbe(sf::Vector2f(10,10)); herbe.setFillColor(sf::Color(0,255,0)); herbe.setOutlineThickness(0.5); herbe.setOutlineColor(sf::Color::White); cursor.setFillColor(sf::Color(255,0,0,127)); cursor.setOutlineThickness(0.5); cursor.setOutlineColor(sf::Color::White); sf::Texture grid; if (!grid.loadFromFile("grid.png", sf::IntRect(0,0,width,height))) { return 1; } sf::Sprite gridsprite; gridsprite.setTexture(grid); sf::Event event; while (window.isOpen()) { while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); /* sf::Vector2i mpos = sf::Mouse::getPosition(window); if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { cout << "Mouse cliked at : " << "(" << mpos.x << "," << mpos.y << ")" << endl; } */ if (event.type == sf::Event::MouseButtonPressed) { mouseispressed = true; cout << "Mouse clicked at : " << "(" << event.mouseButton.x << "," << event.mouseButton.y << ")" << endl; cout << "corresponding to : " << "(" << floor((float)event.mouseButton.x/10.0) << "," << floor((float)event.mouseButton.y/10.0) << ")" << endl; a = floor((float)event.mouseButton.x/10.0)*10.0; b = floor((float)event.mouseButton.y/10.0)*10.0; cout << "a = " << a << "," << " b = " << b << endl; selected.p1.x = a; selected.p1.y = b; selected.p2.x = a+10; selected.p2.y = b+10; /* while (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { c = floor(sf::Mouse::getPosition(window).x/10.0)*10.0; d = floor(sf::Mouse::getPosition(window).y/10.0)*10.0; }; cout << "c = " << c << "," << " d = " << d << endl; */ } if (mouseispressed && sf::Event::MouseMoved) { c = ceil(sf::Mouse::getPosition(window).x/10.0)*10.0; d = ceil(sf::Mouse::getPosition(window).y/10.0)*10.0; cout << "c = " << c << "," << " d = " << d << endl; selected.p2.x = c; selected.p2.y = d; } if (event.type == sf::Event::MouseButtonReleased) { if (selected.p1.x > selected.p2.x) { aux = selected.p1.x; selected.p1.x = selected.p2.x; selected.p2.x = aux; } if (selected.p1.y > selected.p2.y) { aux = selected.p1.y; selected.p1.y = selected.p2.y; selected.p2.y = aux; } if (selected.p2.x > width){ selected.p2.x = width; } if (selected.p2.y > height){ selected.p2.y = height; } if (selected.p1.x < 0){ selected.p1.x = 0; } if (selected.p1.y < 0){ selected.p1.y = 0; } mouseispressed = false; } /*if (sf::Keyboard::isKeyPressed(sf::Keyboard::H)){ cout << "coucou" << selected.p1.x << "," << selected.p2.x << ","<< selected.p1.y << ","<< selected.p2.y << "." ; for (int i = selected.p1.x ; i <= selected.p2.x ; i++) { for (int j = selected.p1.y ; j <= selected.p2.y ; j++) { map[i][j] = 1; } } }*/ if (event.type == sf::Event::KeyPressed){ if (event.key.code == sf::Keyboard::H) { cout << "coucou" << selected.p1.x << "," << selected.p2.x << ","<< selected.p1.y << ","<< selected.p2.y << "." <<endl ; for (int i = selected.p1.x/10 ; i < selected.p2.x/10 ; i++) { for (int j = selected.p1.y/10 ; j < selected.p2.y/10 ; j++) { cout << "toto" << i << "," << j <<endl ; cout << "toto" << map[i][j] <<endl ; map[i][j] = 1; } } } /* if (event.text.unicode < 128) { cout << event.text.unicode; switch (event.text.unicode) { case 104: { for (int i = selected.p1.x ; i <= selected.p2.x ; i++) { for (int j = selected.p1.y ; j <= selected.p2.y ; j++) { map[i][j] = 1; } } cout << "h pressed"; break; } } }*/ } } window.clear(sf::Color::White); for (int i = 0 ; i < width/10 ; i++) { for (int j = 0 ; j < height/10 ; j++) { switch (map[i][j]) { case 1: { sf::RectangleShape herbe(sf::Vector2f(10,10)); herbe.setFillColor(sf::Color(50,200,50)); //herbe.setOutlineThickness(0.5); //herbe.setOutlineColor(sf::Color::White); herbe.setPosition(sf::Vector2f(i*10, j*10)); window.draw(herbe); break; } } } }; window.draw(gridsprite); cursor.setSize((sf::Vector2f)(selected.p2-selected.p1)); cursor.setPosition((sf::Vector2f)selected.p1); window.draw(cursor); window.display(); } return 0; }
true
f744e1b59c56b0e8b1707625f9fdfab846d35e54
C++
spirali/rain
/cpp/tasklib/src/connection.cpp
UTF-8
2,395
2.90625
3
[ "MIT" ]
permissive
#include "connection.h" #include <errno.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include "log.h" tasklib::Connection::Connection() { int s = ::socket(PF_UNIX, SOCK_STREAM, 0); if (!s) { log_errno_and_exit("Cannot create unix socket"); } this->socket = s; } tasklib::Connection::~Connection() { close(socket); } void tasklib::Connection::connect(const char *socket_path) { struct sockaddr_un server_addr; bzero(&server_addr, sizeof(server_addr)); server_addr.sun_family = AF_UNIX; strncpy(server_addr.sun_path, socket_path, sizeof(server_addr.sun_path) - 1); if (::connect(socket, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { log_errno_and_exit("Cannot connect to unix socket"); } } static void send_all(int socket, const unsigned char *data, size_t len) { while (len > 0) { int i = ::send(socket, data, len, 0); if (i < 1) { tasklib::log_errno_and_exit("Sending data failed"); } data += i; len -= i; } } void tasklib::Connection::send(const unsigned char * data, size_t len) { // TODO: Fix this on big-endian machines uint32_t size = len; send_all(socket, reinterpret_cast<const unsigned char*>(&size), sizeof(uint32_t)); send_all(socket, data, len); } std::vector<char> tasklib::Connection::receive() { const size_t READ_AT_ONCE = 128 * 1024; for(;;) { auto sz = buffer.size(); if (sz >= sizeof(uint32_t)) { // TODO: fix this on big-endian machines uint32_t *len_ptr = reinterpret_cast<uint32_t*>(&buffer[0]); size_t len = *len_ptr + sizeof(uint32_t); if (sz >= len) { std::vector<char> result(buffer.begin() + sizeof(uint32_t), buffer.begin() + len); buffer.erase(buffer.begin(), buffer.begin() + len); return result; } } buffer.resize(sz + READ_AT_ONCE); int r = ::read(socket, &buffer[sz], READ_AT_ONCE); if (r < 0) { tasklib::log_errno_and_exit("Reading data failed"); } if (r == 0) { logger->critical("Connection to server closed"); exit(1); } buffer.resize(sz + r); } }
true
2407d244174a698aa52c6c8c38a86e6498707f29
C++
jairoM26/crazyDuckHunt
/Logic/LogicDucks/Duck.cpp
UTF-8
2,808
3.234375
3
[]
no_license
/* * Duck.cpp * * Created on: Aug 3, 2015 * Author: pablo */ #include "Duck.h" using namespace std; /** * El parametro "Vida" se basa en la cantidad de balas que puede * recibir el pato, el cual se va a ir reduciendo con cada bala recibida. * El parametro PuntosQueAporta se va a mantener constante y va * a depender de cada pato. * El parametro Probabilidad va a ir cambiando con cada cambio de nivel * @param pDuckType: es un índice que refleja la naturaleza de cada pato. */ Duck::Duck(int pDuckType) { // TODO Auto-generated constructor stub _duckType = pDuckType; setDuckValues(_duckType); _movement = new Move(_duckType); setId(); } Duck::~Duck() { // TODO Auto-generated destructor stub } void Duck::setDuckValues(int pduck_type){ switch(_duckType){ //De acuerdo al tipo de pato se le asignan los valores correspondientes. case 1: this->_life = VIDAPATOCOLORADO ; this->_pointsToGive = PUNTOSPATOCOLORADO; this->_probability = PROBABILIDADINICIALPATOCOLORADO; break; case 3: this->_life = VIDATARROCANELO ; this->_pointsToGive = PUNTOSTARROCANELO; this->_probability = PROBABILIDADINICIALTARROCANELO; break; case 2: this->_life = VIDAPATOSALVAJE; this->_pointsToGive = PUNTOSPATOSALVAJE; this->_probability = PROBABILIDADINICIALPATOSALVAJE; break; case 4: this->_life = VIDAYAGUASAPIQUIRROJO; this->_pointsToGive = PUNTOSYAGUASAPIQUIRROJO; this->_probability = PROBABILIDADINICIALYAGUASAPIQUIRROJO; break; default: this->_life = VIDAGANSODEHAWAI; this->_pointsToGive = PUNTOSGANSODEHAWAI; this->_probability = PROBABILIDADINICIALGANSODEHAWAI; } } void Duck::releaseProbability(){ this->_probability = _probability + AUMENTOPROBABILIDAD; /* * Dado que en la mayoría de los casos los patos aumentan de probabilidad, * y sólo uno la disminuye, por motivos de eficiencia se decidió que to - * dos la aumentaran y el que la disminuye que acople el método. */ } /** * Retorna la vida del pato * @return _life */ int Duck::getLife(){ return _life; } /** * Se utiliza una función aleatorioa que retorne un número entre 0 y el límite * (100 en este caso) con el fin de utilizar dicho número como un identificador * y evitar así que dos o más patos tengan el mismo identificador. */ void Duck::setId(){ srand(unsigned(time(0))); this->_id = rand()%100; } /** * */ void Duck::reduceLife(){ this->_life = _life - 1; //Puesto que están en función de las balas que aguanta. } /** * * @return */ int Duck::getPointsToGive(){ return _pointsToGive; } /** * * @return */ float Duck::getProbability(){ return _probability; } /** * * @return */ int Duck::getDuckType(){ return this->_duckType; } Move* Duck::getMoveObject(){ return _movement; }
true
bff7f0574928b4626055294f2f53fb9e43d31373
C++
johannes-riesterer/Curvature
/Utils.cpp
UTF-8
7,749
2.828125
3
[ "MIT" ]
permissive
/* * File: Utils.cpp * Author: johannes * * Created on 11. August 2014, 10:17 */ #include "Utils.h" struct Smooth_old_vertex { Point_3 operator()(const Vertex& v) const { CGAL_precondition((CGAL::circulator_size(v.vertex_begin()) & 1) == 0); std::size_t degree = CGAL::circulator_size(v.vertex_begin()) / 2; double alpha = (4.0 - 2.0 * std::cos(2.0 * CGAL_PI / degree)) / 9.0; Vector_3 vec = (v.point() - CGAL::ORIGIN) * (1.0 - alpha); HV_circulator h = v.vertex_begin(); do { vec = vec + (h->opposite()->vertex()->point() - CGAL::ORIGIN) * alpha / static_cast<double> (degree); ++h; CGAL_assertion(h != v.vertex_begin()); // even degree guaranteed ++h; } while (h != v.vertex_begin()); return (CGAL::ORIGIN + vec); } }; myColor geometryUtils::HSVtoRGB(int H, double S, double V) { //enforce assumptions for HSV if (H > 300) { H = 300; } if (H < 0) { H = 0; } if (S > 1.0) { S = 1.0; } if (S < 0) { S = 0.0; } if (V > 1) { V = 1.0; } if (V < 0) { V = 0.0; } double R; double G; double B; double C = V*S; double X = C * (1 - fabs(fmod(H / 60.0, 2) - 1)); double m = V - C; if (H <= 60) { R = 1; G = 1; B = 0; } /* if(H <60 && H>30) { R = C; G = X; B = 0; } */ if (H < 120 && H >= 60) { R = X; G = C; B = 0; } if (H < 180 && H >= 120) { R = 0; G = C; B = X; } if (H < 240 && H >= 180) { R = 0; G = X; B = C; } if (H < 300 && H >= 240) { R = X; G = 0; B = C; } if (H <= 360 && H >= 300) { R = C; G = 0; B = X; } myColor color; color.R = R + m; color.G = G + m; color.B = B + m; return color; }; double geometryUtils::computeVoronoiArea(Vertex_handle vertex) { double voronoiArea = 0.0; Vertex_circulator j; j = vertex->vertex_begin(); do { Point_3 p11 = j->vertex()->point(); Point_3 p12 = j->next()->vertex()->point(); Point_3 p13 = j->next()->next()->vertex()->point(); Vector_3 v11 = p13 - p12; Vector_3 v12 = p11 - p12; v11 = v11 / sqrt(CGAL::to_double(v11.squared_length())); v12 = v12 / sqrt(CGAL::to_double(v12.squared_length())); double alpha = acos(CGAL::to_double(v11 * v12)); Point_3 p22 = j->opposite()->vertex()->point(); Point_3 p23 = j->opposite()->next()->vertex()->point(); Vector_3 v21 = p11 - p23; Vector_3 v22 = p22 - p23; v21 = v21 / sqrt(CGAL::to_double(v21.squared_length())); v22 = v22 / sqrt(CGAL::to_double(v22.squared_length())); double beta = acos(CGAL::to_double(v21 * v22)); Vector_3 x = p13 - p11; double length = CGAL::to_double(x.squared_length()); voronoiArea += (1.0 / 8.0) * (1.0 / tan(alpha) + 1.0 / tan(beta)) * length; } while (++j != vertex->vertex_begin()); return voronoiArea; }; double geometryUtils::computeLocalGaussCurvature(Vertex_handle vertex) { double gaussCurvature = 0.0; double vA = computeVoronoiArea(vertex); double sumTheta = 0.0; Vertex_circulator j; j = vertex->vertex_begin(); do { Point_3 p1 = j->vertex()->point(); Point_3 p2 = j->prev()->vertex()->point(); Point_3 p3 = j->next()->vertex()->point(); Vector_3 v1 = p2 - p1; Vector_3 v2 = p3 - p1; v1 = v1 / sqrt(CGAL::to_double(v1.squared_length())); v2 = v2 / sqrt(CGAL::to_double(v2.squared_length())); sumTheta += acos(CGAL::to_double(v1 * v2)); } while (++j != vertex->vertex_begin()); gaussCurvature = (2 * 3.1415926 - sumTheta) / vA; return gaussCurvature; }; void geometryUtils::computeGaussCurvature(Polyhedron* P) { for (Facet_iterator i = P->facets_begin(); i != P->facets_end(); i++) { int e = 0; Halfedge_around_facet_circulator edge = i->facet_begin(); do { i->kappa[e] = computeLocalGaussCurvature(edge->vertex()); int H = floor(i->kappa[e] * geometryUtils::kappaMax + 180); // std::cout << H; // std::cout << " "; i->color[e] = HSVtoRGB(H, 1.0, 1.0); e++; } while (++edge != i->facet_begin()); // std::cout << edge->kappa; // std::cout << " "; } }; void geometryUtils::subdivide_create_center_vertex(Polyhedron& P, Facet_iterator f) { Vector_3 vec(0.0, 0.0, 0.0); std::size_t order = 0; HF_circulator h = f->facet_begin(); do { vec = vec + (h->vertex()->point() - CGAL::ORIGIN); ++order; } while (++h != f->facet_begin()); CGAL_assertion(order >= 3); // guaranteed by definition of polyhedron Point_3 center = CGAL::ORIGIN + (vec / static_cast<double> (order)); Halfedge_handle new_center = P.create_center_vertex(f->halfedge()); new_center->vertex()->point() = center; } void geometryUtils::subdivide_flip_edge(Polyhedron& P, Halfedge_handle e) { Halfedge_handle h = e->next(); P.join_facet(e); P.split_facet(h, h->next()->next()); } void geometryUtils::subdivide(Polyhedron& P) { if (P.size_of_facets() == 0) return; // We use that new vertices/halfedges/facets are appended at the end. std::size_t nv = P.size_of_vertices(); Vertex_iterator last_v = P.vertices_end(); --last_v; // the last of the old vertices Edge_iterator last_e = P.edges_end(); --last_e; // the last of the old edges Facet_iterator last_f = P.facets_end(); --last_f; // the last of the old facets Facet_iterator f = P.facets_begin(); // create new center vertices do { geometryUtils::subdivide_create_center_vertex(P, f); } while (f++ != last_f); std::vector<Point_3> pts; // smooth the old vertices pts.reserve(nv); // get intermediate space for the new points ++last_v; // make it the past-the-end position again std::transform(P.vertices_begin(), last_v, std::back_inserter(pts), Smooth_old_vertex()); std::copy(pts.begin(), pts.end(), P.points_begin()); Edge_iterator e = P.edges_begin(); // flip the old edges ++last_e; // make it the past-the-end position again while (e != last_e) { Halfedge_handle h = e; ++e; // careful, incr. before flip since flip destroys current edge geometryUtils::subdivide_flip_edge(P, h); }; CGAL_postcondition(P.is_valid()); }; void geometryUtils::renderPolyhedron(Polyhedron * pmesh) { glBegin(GL_TRIANGLES); for (Facet_iterator i = pmesh->facets_begin(); i != pmesh->facets_end(); i++) { Halfedge_around_facet_circulator j = i->facet_begin(); glColor3d(i->color[0].R, i->color[0].G, i->color[0].B); glVertex3d(CGAL::to_double(j->vertex()->point().x()), CGAL::to_double(j->vertex()->point().y()), CGAL::to_double(j->vertex()->point().z())); glColor3d(i->color[1].R, i->color[1].G, i->color[1].B); glVertex3d(CGAL::to_double(j->next()->vertex()->point().x()), CGAL::to_double(j->next()->vertex()->point().y()), CGAL::to_double(j->next()->vertex()->point().z())); glColor3d(i->color[2].R, i->color[2].G, i->color[2].B); glVertex3d(CGAL::to_double(j->next()->next()->vertex()->point().x()), CGAL::to_double(j->next()->next()->vertex()->point().y()), CGAL::to_double(j->next()->next()->vertex()->point().z())); } glEnd(); }
true
53466914d10daee6a212b45f29904b6f8cefd439
C++
Kelinago/qua-vis-services
/include/quavis/vk/memory/buffer.h
UTF-8
1,905
2.875
3
[ "MIT" ]
permissive
#ifndef QUAVIS_BUFFER_H #define QUAVIS_BUFFER_H #include "quavis/vk/device/logicaldevice.h" #include "quavis/vk/memory/allocator.h" #include "quavis/vk/debug.h" #include <vulkan/vulkan.h> namespace quavis { /** * A wrapper around the VkBuffer struct. */ class Buffer { public: /** * Creates a new buffer on the device. If staging is enabled, a staging buffer * will be created that is used for transfer between the host and the buffer * memory. * * If staging is enabled the buffer will be allocated using the following * flags: * * VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT * * If staging disabled the memory will be initialized with * * VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT * * VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT * * VK_MEMORY_PROPERTY_HOST_COHERENT_BIT */ Buffer( LogicalDevice* logical_device, Allocator* allocator, uint32_t size, VkBufferUsageFlags usage_flags, bool staging = true ); /** * Destroys the buffer and all it's associated memory regions. */ ~Buffer(); /** * Writes data to the buffer. * Synchronization is responsibility of the caller. */ void SetData(void* data, VkQueue queue); /** * Retreives data from the buffer. * Synchronization is responsibility of the caller. */ void* GetData(VkQueue queue); /** * The VkBuffer object to be used in Vulkan methods */ VkBuffer vk_handle; /** * The buffer size */ uint32_t size; private: bool staging_ = false; VkDeviceMemory vk_memory_; VkDeviceMemory vk_staging_memory_; VkBuffer vk_staging_buffer_; LogicalDevice* logical_device_; Allocator* allocator_; const VkMemoryPropertyFlags staging_property_flags_ = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; }; } #endif
true
4e631a5b024eb21f8320d039b5492f2fc2d45560
C++
jchryssanthacopoulos/ArduinoBot
/RobotBrain/ReadControls.ino
UTF-8
2,967
3.203125
3
[]
no_license
/* * readControls.ino * * This file contains functions to parse control data */ #include "RobotDefines.h" /* * Parse servo control */ void readServo(char receivedChar) { // Serial.println(isReadingServo); if (receivedChar == servoChar) { // Serial.println("SERVO Path 1"); resetAllControlVars(); isReadingServo = true; } else if (isAlpha(receivedChar) && servoDataSize) { // Serial.println("SERVO Path 2"); receivedServoData = true; } else if (isReadingServo) { // Serial.println("SERVO Path 3"); if (receivedChar == '/' || receivedChar == '?') { servoData[servoDataSize++] = '.'; } else { servoData[servoDataSize++] = receivedChar; } } } /* * Parse auto flag */ void readAutoFlag(char receivedChar) { if (receivedChar == autoFlagChar) { // Serial.println("AUTO FLAG Path 1"); resetAllControlVars(); isReadingAutoFlag = true; } else if (isAlpha(receivedChar) && autoFlagDataSize) { // Serial.println("AUTO FLAG Path 2"); receivedAutoFlagData = true; } else if (isReadingAutoFlag) { // Serial.println("AUTO FLAG Path 3"); autoFlagData[autoFlagDataSize++] = receivedChar; } } /* * Parse joystick controls */ void readJoystickData(char receivedChar) { if (receivedChar == joystickXChar) { // Serial.println("JOYSTICK Path 1"); resetAllControlVars(); isReadingX = true; isReadingY = false; } else if (receivedChar == joystickYChar && isReadingX) { // Serial.println("JOYSTICK Path 2"); isReadingY = true; isReadingX = false; } else if (isAlpha(receivedChar) && xDataSize && yDataSize) { // Serial.println("JOYSTICK Path 3"); receivedJoystickData = true; } else if (isReadingX) { // Serial.println("JOYSTICK Path 4"); if (receivedChar == '/' || receivedChar == '?') { joystickXData[xDataSize++] = '.'; } else { joystickXData[xDataSize++] = receivedChar; } } else if (isReadingY) { // Serial.println("JOYSTICK Path 5"); if (receivedChar == '/' || receivedChar == '?') { joystickYData[yDataSize++] = '.'; } else { joystickYData[yDataSize++] = receivedChar; } } } void resetAllControlVars() { // reset all control variables resetServoVars(); resetAutoFlagVars(); resetJoystickVars(); } void resetServoVars() { // reset global servo variables servoDataSize = 0; isReadingServo = false; receivedServoData = false; memset(servoData, 0, sizeof(servoData)); } void resetAutoFlagVars() { // reset global autoFlag variables autoFlagDataSize = 0; isReadingAutoFlag = false; receivedAutoFlagData = false; memset(autoFlagData, 0, sizeof(autoFlagData)); } void resetJoystickVars() { // reset global joystick variables xDataSize = 0; yDataSize = 0; isReadingX = false; isReadingY = false; receivedJoystickData = false; memset(joystickXData, 0, sizeof(joystickXData)); memset(joystickYData, 0, sizeof(joystickYData)); }
true
f1f561805feb2da631aac73c5c56771d76a145fc
C++
StrongAl258/repos
/Lavanya's code/Lavanya's code/Source.cpp
UTF-8
2,373
3.234375
3
[]
no_license
#include <iostream> #include <Windows.h> #include <ctime> #include <cstdlib> #include <stdlib.h> #define MAX_THREADS 2 using namespace std; HANDLE hThreads[MAX_THREADS]; // # of threads DWORD id[MAX_THREADS]; // array of thread ids DWORD waiter; int in = 0, out = 0, buffcount = 0; // used to check how much items are in buffer int counter = 0; // counter until limit int cl, buffsize; // counter limit, to be declared later on and changed in the threads // later change in program itself to be buffer size int* buffer; DWORD WINAPI randomProducer(LPVOID n) { // producer thread while (counter < cl) { while (buffcount == buffsize) { ; } // while buffer is full, do nothing int r = rand(); cout << "\nGenerated random number: " << r << endl; buffer[in] = r; counter++; cout << "Counter is changed by producer: " << counter << endl; in = (in + 1) % buffsize; buffcount++; } cout << "Producer thread terminating..." << endl; return (DWORD)n; } DWORD WINAPI randomConsumer(LPVOID n) { // consumer thread while (counter < cl) { while (buffcount == 0) { ; } // while buffer is empty, do nothing. cout << "Consuming number: " << buffer[out] << endl; out = (out + 1) % buffsize; counter++; cout << "Counter is changed by consumer: " << counter << endl; buffcount--; } cout << "Consumer thread terminating..." << endl; return (DWORD)n; } int main(int argc, char* argv[]) { if (argc != 3) { // error if 2+ or 2- inputs are entered cout << "TWO INPUTS REQUIRED.\nUSAGE:<PROGRAM NAME> <BUFFERSIZE> <COUNTERLIMIT>\n\nEXITING PROGRAM...\n"; system("pause"); return -1; } srand(time(0)); // initialize randomization cout << "Counter input: " << argv[2] << endl; cl = atoi(argv[2]); // set counterlimit to cl cout << "Counter limit set to " << cl << endl; buffsize = atoi(argv[1]); buffer = new int[buffsize]; // dynamically set the buffer size based on user input hThreads[0] = CreateThread(NULL, 0, randomProducer, (LPVOID)counter, NULL, &id[0]); //thread 1 for randomProducer hThreads[1] = CreateThread(NULL, 0, randomConsumer, (LPVOID)counter, NULL, &id[1]); //thread 2 for randomConsumer waiter = WaitForMultipleObjects(MAX_THREADS, hThreads, TRUE, INFINITE); // wait for our threads to stop for (int i = 0; i < MAX_THREADS; i++) { CloseHandle(hThreads[i]); } system("pause"); return 0; }
true
c3607be79b70adb5cf7dc858b626b464196187f8
C++
chaabaj/CPPLibrary
/CoreLibrary/TypeInfo.cpp
UTF-8
992
2.828125
3
[]
no_license
#include "CoreLibrary/Type/TypeInfo.hpp" TypeInfo::TypeInfo() : _info(NULL) { } TypeInfo::TypeInfo(const std::type_info &info) : _info(&info) { } TypeInfo::TypeInfo(const TypeInfo &info) : _info(info._info) { } bool TypeInfo::before(const TypeInfo &info) const { return this->_info->before(*info._info); } std::string TypeInfo::name() const { return std::string(_info->name()); } bool TypeInfo::operator!=(const TypeInfo &info) const { return (*_info != *info._info); } bool TypeInfo::operator<(const TypeInfo &info) const { return this->before(info); } bool TypeInfo::operator>(const TypeInfo &info) const { return !(this->before(info)); } bool TypeInfo::operator>=(const TypeInfo &info) const { return (*this == info || *this > info); } bool TypeInfo::operator<=(const TypeInfo &info) const { return (*this == info || *this < info); } bool TypeInfo::operator==(const TypeInfo &info) const { return (_info == info._info); }
true
61cfb80e7cd50501840f14150bb5bf95efe9bb4f
C++
zhangchunbao515/leetcode
/leetcode-04/solutions/cpp/0748.cpp
UTF-8
674
3.296875
3
[]
no_license
class Solution { public: string shortestCompletingWord(string licensePlate, vector<string>& words) { string ans; vector<int> map(26); for (char c : licensePlate) if (isalpha(c)) map[tolower(c) - 'a']++; int min = INT_MAX; for (string& word : words) { if (word.length() >= min) continue; if (!isMatch(word, map)) continue; min = word.length(); ans = word; } return ans; } private: bool isMatch(string& word, vector<int>& map) { vector<int> wordMap(26); for (char c : word) wordMap[c - 'a']++; for (int i = 0; i < 26; i++) if (wordMap[i] < map[i]) return false; return true; } };
true
3ca887a982bb01840612f9d30a84d81f98248d84
C++
blankspacer155/lab5
/lab5_2.cpp
UTF-8
1,414
3.4375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; double deg2rad(double n) { return n*M_PI/180; } double rad2deg(double n) { return n*180/M_PI; } double findXComponent(double l1,double l2,double a1,double a2) { return (l1*cos(a1))+(l2*cos(a2)); } double findYComponent(double l1,double l2,double a1,double a2) { return (l1*sin(a1))+(l2*sin(a2)); } double pythagoras(double xcomp,double ycomp) { return sqrt(pow(xcomp,2)+ pow(ycomp,2)); } void showResult(double l,double deg) { cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; cout<<"Length of the resultant vector = "<<l<<endl; cout<<"Direction of the resultant vector (deg) = "<<deg<<endl; cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; } int main(){ double l1,l2,a1,a2,xcomp,ycomp,result_vec_length,result_vec_direction; cout << "Enter length of the first vector: "; cin >> l1; cout << "Enter direction of the first vector (deg): "; cin >> a1; cout << "Enter length of the second vector: "; cin >> l2; cout << "Enter direction of the second vector (deg): "; cin >> a2; a1 = deg2rad(a1); a2 = deg2rad(a2); xcomp = findXComponent(l1,l2,a1,a2); ycomp = findYComponent(l1,l2,a1,a2); result_vec_length = pythagoras(xcomp,ycomp); result_vec_direction = rad2deg(atan2(ycomp,xcomp)); showResult(result_vec_length,result_vec_direction); }
true
c6be66a80b132847dd6635d4c3de2d960e7a2d6c
C++
DTSCode/Cx
/src/cx-debug/expression.cpp
UTF-8
3,193
3.328125
3
[]
no_license
/** Executor (expressions) * exec_expression.cpp * * Executes Cx expressions */ #include "exec.h" #include "common.h" /** execute_expression Execute an expression (binary relational * operators = < > <> <= and >= ). * * @return: ptr to expression's type object */ cx_type *cx_executor::execute_expression(void) { cx_type *p_operand1_type; // ptr to first operand's type cx_type *p_operand2_type; // ptr to second operand's type cx_type *p_result_type; // ptr to result type cx_token_code op; // operator // Execute the first simple expression. p_result_type = execute_simple_expression(); // If we now see a relational operator, // execute the second simple expression. if (token_in(token, tokenlist_relation_ops)) { op = token; p_operand1_type = p_result_type->base_type(); p_result_type = p_boolean_type; get_token(); p_operand2_type = execute_simple_expression()->base_type(); execute_relational(op, p_operand1_type, p_operand2_type); } return p_result_type; } /** execute_simple_expression Execute a simple expression * (unary operators + or - * and binary operators + - * and OR). * * @return: ptr to expression's type object */ cx_type *cx_executor::execute_simple_expression(void) { cx_type *p_operand_type; // ptr to operand's type cx_type *p_result_type; // ptr to result type cx_token_code op; // operator cx_token_code unary_op = tc_plus; // unary operator // Unary + or - if (token_in(token, tokenlist_unary_ops)) { unary_op = token; get_token(); } // Execute the first term. p_result_type = execute_term(); switch (unary_op) { case tc_minus: unary_negate(p_result_type); break; case tc_bit_NOT: unary_bit_not(p_result_type); break; default: break; } // Loop to execute subsequent additive operators and terms. while (token_in(token, tokenlist_add_ops)) { op = token; //p_result_type = p_result_type->base_type(); get_token(); p_operand_type = execute_expression(); p_result_type = execute_additive(op, p_result_type, p_operand_type); } return p_result_type; } /** execute_term Execute a term (binary operators * / * % and &&). * * @return: ptr to term's type object */ cx_type *cx_executor::execute_term(void) { cx_type *p_operand_type; // ptr to operand's type cx_type *p_result_type; // ptr to result type cx_token_code op; // operator // Execute the first factor. p_result_type = execute_factor(); // Loop to execute subsequent multiplicative operators and factors. while (token_in(token, tokenlist_mul_ops)) { op = token; p_result_type = p_result_type->base_type(); get_token(); p_operand_type = execute_factor()->base_type(); p_result_type = execute_multiplicative(op, p_result_type, p_operand_type); } return p_result_type; }
true
c80025b4c3d37d0194a71bae3c9454335621f9e9
C++
Vakicherla-Sudheethi/BecomeCoder
/recursion.cpp
UTF-8
288
3.109375
3
[]
no_license
//recursion #include<iostream> #include<bits/stdc++.h> using namespace std; void fun1(int n)//accepts n elements { if(n<=0) { return; } cout<<"hello"<<"\n"; fun1(n-1);//recursion call } int main() { int n=5;//this repeats n no.of times fun1(n); return 0; }
true
225b9812bdc58a762ec7a6e3b00b97202a8ec795
C++
laannss/rolling
/Assignment2/Assignment2/LinkedList.h
UTF-8
1,182
3.46875
3
[]
no_license
#include <iostream> #include <assert.h> using namespace std; #ifndef LLIST #define LLIST typedef int ListElement; class LinkedList { public: //Default Constructor LinkedList(); //Copy Constructor. LinkedList(const LinkedList & original); //Destructor ~LinkedList(); //Assignment Operation for LinkedList objects. const LinkedList & operator= (const LinkedList & rightHandSide); //Get Nth Function ListElement GetNth(int a)const; /*----------------------------------------------------------------- First half will be left in the list that is calling the function. Second half will be stored in the list that is calling the function. ------------------------------------------------------------------*/ void split(LinkedList & secondList); //Check if empty bool empty() const; //Inserts value at the end of linked list. void insert(const ListElement & value); //Display contents of the linked list void display(ostream & out) const; //Node Clas class Node { public: ListElement data; Node * next; Node(ListElement value, Node * address = 0) : data(value), next(address) {} }; typedef Node * NodePointer; NodePointer head; }; #endif
true