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
4af1451f9c5b154f49eea67efd915c27d4212e8e
C++
Juan14-mart/Tarea-I
/Ejercicio_003.cpp
UTF-8
347
3.015625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main () { int a,b,c; printf ("Ingrese el numero"); scanf ("%d",&a); b=a%2; if (b==0){ printf("El numero es par"); }if(b>0) { printf ("El numero es impar\n"); c=a%3; if(c==0){ printf ("El numero es divisible entre 3"); }else{ printf ("El numero no es divisible entre 3"); } } }
true
1d97825017dffb75c1eac3ca680b16be7f055b52
C++
andrewreeman/SpectralSuite
/shared/utilities.cpp
UTF-8
1,735
2.984375
3
[ "BSD-3-Clause", "Unlicense" ]
permissive
#include "utilities.h" namespace utilities { int ms2Samps(int ms, int sRate) { return ms * (sRate / 1000); } int wrap(int index, int limit) { if (index < 0) { return index + limit; } else { return index % limit; } } void car2Pol(std::vector<Cpx> cpxIn, PolarVector& polOut, int size){ for(int i=0; i<size; ++i){ polOut[i].m_mag = abs(cpxIn[i]); polOut[i].m_phase = arg(cpxIn[i]); } } void pol2Car(const PolarVector& polarIn, std::vector<Cpx>& cpxOut, int size){ const long invertedindexMax = (size * 2) - 1; float mag; float phase; long invertedIndex; for(int i=0; i<size; ++i){ mag = polarIn[i].m_mag; phase = polarIn[i].m_phase; cpxOut[i] = std::polar(mag, phase); //and perform the reflection here. invertedIndex = invertedindexMax - (long)i; cpxOut[invertedIndex] = 0.f; } } Polar<FftDecimal> interp_Polar(const Polar<FftDecimal>* v, int lim, float i, bool wrap = false) { if (wrap){ while( (int)i > lim) i -= float(lim); } float t; float r = modff(i, &t); int n = int(t); Polar<FftDecimal> polOut; if ( n< lim-1){ polOut.m_mag = (1.0f-r)*v[n].m_mag + (r)*v[n+1].m_mag; polOut.m_phase = (1.0f-r)*v[n].m_phase + (r)*v[n+1].m_phase; return polOut; } polOut.m_mag = 0.f; polOut.m_phase = 0.f; return polOut; } void emptyPolar(PolarVector& inOutPol) { Polar<FftDecimal> empty(0.f, 0.f); std::fill(inOutPol.begin(), inOutPol.end(), empty); } }
true
cadeed59cd92834c238cd37f748a3dd3f6ee6716
C++
sauloandradegames/EDA
/Dlist.h
UTF-8
1,193
3.328125
3
[]
no_license
// Dlist.h // Cabecalho: lista duplamente encadeada #ifndef DLIST_H #define DLIST_H #include "Dnode.h" class Dlist { private: /*---------------------------- ATRIBUTOS -----------------------------*/ Dnode *head; // Ponteiro para o primeiro elemento da lista (cabeca da lista) public: /*--------------------------- CONSTRUTORES ---------------------------*/ Dlist(); // Construtor padrao de lista /*------------------------ METODOS: GET E SET ------------------------*/ Dnode* getHead(); // Retorna o node da cabeca da lista void setHead(Dnode* destination); // Configura a cabeca da lista /*--------------------------- METODOS: CRUD --------------------------*/ int insert(int new_value); // insere novo valor no fim da lista, se nao existir int remove(int value); // remove valor da lista, se existir int search(int value); // busca valor na lista int update(int old_value, int new_value); // troca old_value por new_value, se existir int isEmpty(); // verifica se a lista esta vazia void printList(); // imprime valores da lista a partir da cabeca da lista; void printListDesc(); // imprime valores da lista a partir do final da lista }; #endif // DLIST_H
true
0e870db333a34cf2425949f51f823ac3b7c7d605
C++
GEMINEM98/LeetCode
/[编程题]解读密码/[编程题]解读密码/test.cpp
UTF-8
472
2.703125
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 // https://www.nowcoder.com/questionTerminal/16fa68271ee5448cafd504bb4a64b482 // write your code here cpp #include<iostream> #include<vector> #include<string> using namespace std; int main() { string s = ""; while (getline(cin, s)) { vector<int> v; for (int i = 0; i < s.length(); ++i) { if (s[i] >= '0'&&s[i] <= '9') v.push_back(s[i] - '0'); } for (auto e : v) { cout << e; } cout << endl; } return 0; }
true
8b457d674cc17bed20f869f11cad3457b8b49f37
C++
ponomarr85/OPPO123
/references_table.cpp
UTF-8
1,686
2.796875
3
[]
no_license
#include "references_table.h" #include <QVBoxLayout> #include <QDateTime> #include <QLineEdit> ReferencesTable::ReferencesTable(bool isEditable, int workerId, References *references, QWidget *parent) : QWidget(parent) { this->references = references; this->workerId = workerId; QVBoxLayout *mainLayout = new QVBoxLayout; table = new QTableView; table->setModel(references); mainLayout->addWidget(table); for (int i = 0; i < references->rowCount(QModelIndex()); ++i) { Reference reference = references->get(i); if (reference.workerId() != workerId) { table->hideRow(i); } } addButton = new QPushButton(tr("Добавить справку")); connect(addButton, &QPushButton::released, this, &ReferencesTable::handleClickAddButton); if (isEditable == true) { mainLayout->addWidget(addButton); } else { table->setEditTriggers(QAbstractItemView::NoEditTriggers); } setLayout(mainLayout); } ReferencesTable::~ReferencesTable() { delete table; delete addButton; } void ReferencesTable::handleClickAddButton() { int maxNumber = 0; for (int i = 0;i < references->rowCount(QModelIndex()); i++) { Reference reference = references->get(i); if (reference.number() > maxNumber) { maxNumber = reference.number(); } } Reference reference; reference.setNumber(maxNumber + 1); reference.setWorkerId(workerId); reference.setCreatedDate(QDateTime::currentDateTime().toString(("dd.MM.yyyy HH:mm:ss"))); // Записываем текущую дату и время references->add(reference); }
true
3193f99d16a356e3990a728fe477f288a6ed2d34
C++
paddygoat/Weather-Station
/Arduino/rain.cpp
UTF-8
856
2.96875
3
[]
no_license
#include <Arduino.h> const int rainPin = A0; int rainValuex1 = 0; int rainReading =0; void setupRain() { rainReading = analogRead(rainPin); // If rain detected, capacitor discharges. Serial.println(""); Serial.print("rainReading 0: "); Serial.println(rainReading); } void rainDetect() { // Capacitor is charged from the red LED pin D0. delay(50); rainReading = analogRead(rainPin); // If rain detected, capacitor discharges. Serial.println(""); Serial.print("rainReading 1: "); Serial.print(rainReading); if (rainReading < 80) { rainValuex1++; } Serial.print(" rainValuex1: "); Serial.println(rainValuex1); Serial.println(""); if( rainValuex1 >0 ) { digitalWrite(1,HIGH); // Yellow LED } else { digitalWrite(1,LOW); // Yellow LED } }
true
3e42ffa712169a3f2faec92408b22f13674887fa
C++
bryan0806/Arduino
/bt_recv/bt_recv.ino
UTF-8
385
2.78125
3
[]
no_license
int iLedPin=13; void setup() { // put your setup code here, to run once: pinMode(iLedPin,OUTPUT); Serial.begin(38400); } void loop() { // put your main code here, to run repeatedly: while(Serial.available()){ char cCmd=Serial.read(); Serial.println(cCmd); if(cCmd=='o'){ digitalWrite(iLedPin,HIGH); }else if(cCmd=='c'){ digitalWrite(iLedPin,LOW); } } }
true
d13cbed98d89c76c48ed2291f44365b36f562207
C++
JamesAhsam/ConwaysGameofLife
/SOILTEST/main.cpp
UTF-8
6,126
2.859375
3
[]
no_license
// // main.cpp // Game of Life BBC // // Created by James Ahsam on 06/02/2019. // Copyright © 2019 James Ahsam. All rights reserved. // #include "main.h" int mousex = 0; int mousey = 0; int font; bool leftclick; bool leftclick_flag; bool rightclick; bool rightclick_flag; bool paused = true; int fps = 60; float fpsMult = 60.0f / (float)fps; int framerate = 1000 / fps; int windowx = 640; //our screen size int windowy = 480; float screenmultx = 1.0; //the pixel to pixel value. e.g. 2 world mean for every 1 pixel in the view it occupys 2 pixels on the display. float screenmulty = 1.0; World* world; //Renderes the pause menu void renderPauseMenu(){ if(!paused) //so as to not display if paused return; drawtext(font, "Paused", 0, 0, 16, 16); drawtext(font, " WASD - Move Cursor", 5, 25, 12, 12); drawtext(font, "ARROWS - Move Map", 5, 40, 12, 12); drawtext(font, " F - Toggle", 5, 55, 12, 12); drawtext(font, " SPACE - Pause", 5, 70, 12, 12); drawtext(font, "Q or E - Change Speed", 5, 85, 12, 12); } //This long method is to build a long string with any datat we wan't at the bottom. void renderInterface(){ char worldData[100] = "("; char worldX[16]; sprintf(worldX, "%d", world->getCursorX()); char worldY[16]; sprintf(worldY, "%d", world->getCursorY()); strcat(worldData, worldX); strcat(worldData, ", "); strcat(worldData, worldY); strcat(worldData, ")"); if(world->getNodeActive(world->getCursorX(), world->getCursorY())) strcat(worldData, " on."); else strcat(worldData, " off."); strcat(worldData, " SPEED: "); char waitFrames[16]; sprintf(waitFrames, "%f", ((float)world->getWaitFrames())/((float)fps)); strcat(worldData, waitFrames); strcat(worldData, " seconds."); drawtext_centre(font, worldData, windowx/2, windowy-16, 12, 12); } void draw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); enable2d((int)windowx, (int)windowy); // this initialised the OpenGL model view to work as expected in 2d. //initialise using forward rendering. Not preferred, just works for this situation. glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_BLEND); //Our opacity filter glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); world->render(); renderPauseMenu(); renderInterface(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); glutSwapBuffers(); } void update(int value) { world->update(value); glutTimerFunc(framerate, update, 0); draw(); } //This handles mouse input - is not used during this demo void basic_mouse_func(int button, int state, int x, int y){ if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){ if(leftclick_flag == false && leftclick == true) leftclick_flag = true; else leftclick_flag = false; leftclick = true; } if(button == GLUT_LEFT_BUTTON && state == GLUT_UP){ leftclick_flag = false; leftclick = false; } if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN){ if(rightclick_flag == false && rightclick == true) rightclick_flag = true; else rightclick_flag = false; rightclick = true; } if(button == GLUT_RIGHT_BUTTON && state == GLUT_UP){ rightclick_flag = false; rightclick = false; } } //This is our controls void processNormalKeys(unsigned char key, int x, int y) { if(key == 113)//Q world->increaseSpeed(); if(key == 101)//E world->decreaseSpeed(); if(key == 97)//A world->moveCursor(-1, 0); if(key == 100)//D world->moveCursor(1, 0); if(key == 119)//W world->moveCursor(0, -1); if(key == 115)//S world->moveCursor(0, 1); if(key == 102)//F to select world->select(); if(key == 32)//Space paused = !paused; if (key == 27) //Escape exit(0); } void processSpecialKeys(int key, int x, int y) { switch(key) { case GLUT_KEY_LEFT : world->addPosition(-8, 0); break; case GLUT_KEY_RIGHT : world->addPosition(8, 0); break; case GLUT_KEY_DOWN : world->addPosition(0, 8); break; case GLUT_KEY_UP : world->addPosition(0, -8); break; } } void initGame(){ //load the font texture font = LoadTexture("textures", "font_oswald.png"); //load the world and set it to the middle of the current view world = new World(50, 50); world->setPosition(windowx/2-world->getBoundWidth()/2, windowy/2-world->getBoundHeight()/2); } //If you recieve deprecation errors, this is because Mac has stopped supporting OpenGL in favor of metal. See https://developer.apple.com/macos/whats-new/ int main(int argc, char** argv) { glutInit(&argc, argv); //inits OpenGL glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); //Sets the display mode glutInitWindowSize(windowx, windowy); //Sets the screen size glutCreateWindow("Conway's Game of Life"); //Creates the window context for the current OS glClearColor(0.0f, 0.0f, 0.0f, 1.0f); //Sets the backround color glutDisplayFunc(draw); //defines the function we need to call everytime we want to draw glutTimerFunc(framerate, update, 0); //defines the function we need to call everytime we need to do logic at the given rate "framerate" glutMouseFunc(&basic_mouse_func); //The function we call when mouse input glutSpecialFunc(&processSpecialKeys); //The function we call when special keys are pressed e.g. The arrows glutKeyboardFunc(&processNormalKeys); //The function we call when nomal keyboard keys are pressed e.g. WASD //glutReshapeFunc(resizeWindow); //On resize function - I normally add this but felt it wasn't necessary initGame(); //initialise the game glutMainLoop(); //give opengl control return 0; }
true
a981e22d4f0252f3981708c2e41a6589b6f83f74
C++
TangXiaofui/LeetCode-txh
/Ch02/2.1/2.1.16.cpp
UTF-8
490
3.546875
4
[]
no_license
#include <iostream> #include <vector> using namespace std; class Solution{ public: void PlusOne(vector<int> &num) { int temp = 1; vector<int>::reverse_iterator it; for(it = num.rbegin();it != num.rend();it++) { *it += temp; temp = *it / 10; *it = *it % 10; } if(temp) num.insert(num.begin(),temp); } }; int main(int argc,char *argv[]) { vector<int> num = {9,9,9,9,9}; Solution s; s.PlusOne(num); for(auto i : num) cout << i ; cout << endl; return 0; }
true
7392bb08ac4acb3e2bbe8f404855d9c8f6114d99
C++
vppatil/temVijMods
/src/ecodomain/horizon/Moss.h
UTF-8
610
2.625
3
[]
no_license
/*! \file */ #ifndef MOSS_H_ #define MOSS_H_ #include "../layer/MossLayer.h" class Moss{ public: Moss(); ~Moss(); int num; // num of moss layers int type; // moss types: 1: sphagnum; 2: feathermoss; 3: other (including lichen) double dmossc; // dead moss C (kg/m2), which not included in SOM, is always in the last moss layer; // AND, used as a tracker to determine if a moss horizon exists. double thick; // in meter double dz[MAX_MOS_LAY]; void setThicknesses(int soiltype[], double soildz[],const int & soilmaxnum); }; #endif /*MOSS_H_*/
true
609444b5f1cec22e6ced584d6800695191b417ae
C++
EosBandi/TeensyRadio
/golay.cpp
UTF-8
2,508
2.65625
3
[]
no_license
/// /// @file golay23.c /// /// golay 23/12 error correction encoding and decoding /// #include <stdarg.h> #include "radio.h" #include "golay23.h" // intermediate arrays for encodeing/decoding. Using these // saves some interal memory that would otherwise be needed // for pointers static uint8_t g3[3], g6[6]; // encode 3 bytes data into 6 bytes of coded data // input is in g3[], output in g6[] static void golay_encode24(void) { uint16_t v; uint16_t syn; v = g3[0] | ((uint16_t)g3[1] & 0x0F) << 8; syn = golay23_encode[v]; g6[0] = syn & 0xFF; g6[1] = (g3[0] & 0x1F) << 3 | syn >> 8; g6[2] = (g3[0] & 0xE0) >> 5 | (g3[1] & 0x0F) << 3; v = g3[2] | ((uint16_t)g3[1] & 0xF0) << 4; syn = golay23_encode[v]; g6[3] = syn & 0xFF; g6[4] = (g3[2] & 0x1F) << 3 | syn >> 8; g6[5] = (g3[2] & 0xE0) >> 5 | (g3[1] & 0xF0) >> 1; } // encode n bytes of data into 2n coded bytes. n must be a multiple 3 // encoding takes about 6 microseconds per input byte void golay_encode(uint8_t n, uint8_t * in, uint8_t * out) { while (n >= 3) { g3[0] = in[0]; g3[1] = in[1]; g3[2] = in[2]; golay_encode24(); out[0] = g6[0]; out[1] = g6[1]; out[2] = g6[2]; out[3] = g6[3]; out[4] = g6[4]; out[5] = g6[5]; in += 3; out += 6; n -= 3; } } // decode 6 bytes of coded data into 3 bytes of original data // input is in g6[], output in g3[] // returns the number of words corrected (0, 1 or 2) static uint8_t golay_decode24(void) { uint16_t v; uint16_t syn; uint16_t e; uint8_t errcount = 0; v = (g6[2] & 0x7F) << 5 | (g6[1] & 0xF8) >> 3; syn = golay23_encode[v]; syn ^= g6[0] | (g6[1] & 0x07) << 8; e = golay23_decode[syn]; if (e) { errcount++; v ^= e; } g3[0] = v & 0xFF; g3[1] = v >> 8; v = (g6[5] & 0x7F) << 5 | (g6[4] & 0xF8) >> 3; syn = golay23_encode[v]; syn ^= g6[3] | (g6[4] & 0x07) << 8; e = golay23_decode[syn]; if (e) { errcount++; v ^= e; } g3[1] |= (v >> 4) & 0xF0; g3[2] = v & 0xFF; return errcount; } // decode n bytes of coded data into n/2 bytes of original data // n must be a multiple of 6 // decoding takes about 4 microseconds per input byte // the number of 12 bit words that required correction is returned uint8_t golay_decode(uint8_t n, uint8_t * in, uint8_t * out) { uint8_t errcount = 0; while (n >= 6) { g6[0] = in[0]; g6[1] = in[1]; g6[2] = in[2]; g6[3] = in[3]; g6[4] = in[4]; g6[5] = in[5]; errcount += golay_decode24(); out[0] = g3[0]; out[1] = g3[1]; out[2] = g3[2]; in += 6; out += 3; n -= 6; } return errcount; }
true
67d27df647a8ba949691a82d47f8ba7387eb08a8
C++
bahlo-practices/pa
/semester1/practice4/exercise1/myerror.h
UTF-8
347
2.5625
3
[ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * File: myerror.h * Author: * * Created on 31. Oktober 2012, 10:42 */ #ifndef ERROR_H #define ERROR_H #include <iostream> #include <stdexcept> using std::string; using std::runtime_error; using namespace std; void error (string s) {throw runtime_error(s);} void error (string s1, string s2) {error (s1+s2);} #endif /* ERROR_H */
true
d4d102d6150638958a274c2d489262ab909cee78
C++
mbrzecki/julian
/src/marketData/ForwardCurve.hpp
UTF-8
2,380
3.1875
3
[]
no_license
#ifndef JULIAN_FORWARDCURVE_HPP #define JULIAN_FORWARDCURVE_HPP #include <vector> #include <utils/SmartPointer.hpp> #include <mathematics/interpolation/interpolation.hpp> #include <dates/date.hpp> #include <dates/yearFractions/yearFraction.hpp> #include <utils/utils.hpp> #include <boost/serialization/export.hpp> namespace julian { /** * @file ForwardCurve.hpp * @brief File contains definition of forward curve class. */ /** \ingroup marketdata * \brief The class implements the forward curve. * * The forward curve is a function graph in finance that defines the prices at which a contract for future delivery or payment can be concluded today. * The forward curve can represent prices of commodity, equity of fx forwards. * * Object is defined by set of dates and prices. To calculate the forward price on date that is not a grid date, interpolation is applied. * */ class ForwardCurve { public: ForwardCurve(); ForwardCurve(const Date as_of_date, const SmartPointer<Interpolation>& interpolation,const SmartPointer<YearFraction>& yf, const std::vector<Date>& dates, const std::vector<double>& prices); double getForwardPrice(Date d); std::vector<Date> getDates(); friend std::ostream& operator<<(std::ostream&, ForwardCurve&); friend class boost::serialization::access; private: template<class Archive> void serialize(Archive & ar, const unsigned int); Date as_of_date_; /*!< @brief date on which the curve is valid.*/ SmartPointer<Interpolation> interpolation_; /*!< @brief Interpolation method*/ SmartPointer<YearFraction> yf_; /*!< @brief Year fraction convention changes dates into continuous time*/ std::vector<Date> dates_; /*!< @brief Grid dates*/ std::vector<double> time_; /*!< @brief Continuous time calculated on basis of grid dates*/ std::vector<double> prices_; /*!< @brief Forward prices associated with dates*/ }; /** \brief interface used by Boost serialization library */ template<class Archive> void ForwardCurve::serialize(Archive & ar, const unsigned int){ ar & BOOST_SERIALIZATION_NVP( as_of_date_); ar & BOOST_SERIALIZATION_NVP(interpolation_); ar & BOOST_SERIALIZATION_NVP(yf_); ar & BOOST_SERIALIZATION_NVP(dates_); ar & BOOST_SERIALIZATION_NVP(prices_); } } #endif /* FORWARDEQUITYCURVE_HPP */
true
782a1100459d72509c691e400abc0a1d70e93b9c
C++
mRooky/Rooky
/Source/Core/Math/MathViewport.h
UTF-8
1,704
2.671875
3
[]
no_license
/* * RenderViewport.hpp * * Created on: Mar 14, 2019 * Author: rookyma */ #ifndef SOURCE_CORE_RENDER_RENDERVIEWPORT_HPP_ #define SOURCE_CORE_RENDER_RENDERVIEWPORT_HPP_ #include "MathRect.h" #include "MathExtent3.h" namespace Math { class Viewport { public: Viewport(void) = default; ~Viewport(void) = default; public: inline Viewport(const Rect2Di& rect) { SetOffset(rect.offset); SetExtent(rect.extent); } inline Viewport(const Extent2Di& extent) { SetExtent(extent); } inline Viewport(const Extent3Di& extent) { SetExtent(extent.width, extent.height); } public: inline void SetOffset(const Vector2i& offset) { this->x = static_cast<float>(offset.x); this->y = static_cast<float>(offset.y); } inline void SetOffset(int32_t x, int32_t y) { this->x = static_cast<float>(x); this->y = static_cast<float>(y); } public: inline void SetExtent(const Extent2Di& extent) { this->width = static_cast<float>(extent.width); this->height = static_cast<float>(extent.height); } inline void SetExtent(const Extent3Di& extent) { this->width = static_cast<float>(extent.width); this->height = static_cast<float>(extent.height); } inline void SetExtent(int32_t width, int32_t height) { this->width = static_cast<float>(width); this->height = static_cast<float>(height); } public: inline Vector2i GetOffset(void) const { return Vector2i(x, y); } inline Extent2Di GetExtent(void) const { return Extent2Di(width, height); } public: float x = 0.0f; float y = 0.0f; float width = 0.0f; float height = 0.0f; float minDepth = 0.0f; float maxDepth = 1.0f; }; } #endif /* SOURCE_CORE_RENDER_RENDERVIEWPORT_HPP_ */
true
8ca112ebf7f9bb11d7ac14da9a51bc3d8fc30643
C++
saulius/croaring-rs-testgen
/cpp/src/main.cpp
UTF-8
1,031
2.609375
3
[]
no_license
#include <roaring.hh> #include <assert.h> #include <climits> #include <iostream> #include <fstream> int main() { Roaring64Map outBitmap; // write for (uint64_t i = 100; i < 1000; i++) { outBitmap.add(i); } outBitmap.add((uint64_t) UINT_MAX); outBitmap.add((uint64_t) ULLONG_MAX); uint64_t size = outBitmap.getSizeInBytes(); char *outBuffer = new char[size]; size_t bytesWritten = outBitmap.write(outBuffer); std::ofstream outfile("testcpp.bin", std::ios::binary); outfile.write(outBuffer, size); outfile.close(); delete[] outBuffer; // read - verify char* inBuffer = new char[bytesWritten]; std::ifstream infile("testcpp.bin", std::ifstream::binary); infile.read(inBuffer, bytesWritten); Roaring64Map inBitmap = Roaring64Map::read(inBuffer); infile.close(); for (uint64_t i = 100; i < 1000; i++) { assert(inBitmap.contains(i)); } inBitmap.contains((uint64_t) UINT_MAX); inBitmap.contains((uint64_t) ULLONG_MAX); }
true
d4841a0b64563445645af02d99b74888569bbf16
C++
joajasi/FifoBasedList
/List.h
UTF-8
204
2.75
3
[]
no_license
typedef struct Node { int val; Node* next; } Node; class List { public: List(Node* head, Node* tail); void push(int val); void pop(); void show(); private: Node* head; Node* tail; };
true
29131768ce0682fc0d285efb7b6794f96472f3bf
C++
paulsammut/learn
/learn_cpp/extra0/ex03/main.cpp
UTF-8
1,722
4.21875
4
[]
no_license
// Function Pointer Extra Lesson! // http://www.newty.de/fpt/intro.html // Lesson 2.8 How to use Arrays as Function Pointers! // // #include <iostream> using namespace std; // type-definition: 'pt2Member' now can be used as type typedef int (TMyClass::*pt2Member)(float, char, char); // illustrate how to work with an array of member function pointers void Array_Of_Member_Function_Pointers() { cout << endl << "Executing 'Array_Of_Member_Function_Pointers'" << endl; // define arrays and ini each element to NULL, <funcArr1> and <funcArr2> are // arrays with 10 pointers to member functions which return an int and take // a float and two char // first way using the typedef pt2Member funcArr1[10] = {NULL}; // 2nd way of directly defining the array int (TMyClass::*funcArr2[10])(float, char, char) = {NULL}; // assign the function's address - 'DoIt' and 'DoMore' are suitable member // functions of class TMyClass like defined above in 2.1-4 funcArr1[0] = funcArr2nd //use an array of function pointers in C and C++. The first way uses a typedef, the second way directly defines the array. It's up to you which way you prefer. [1] = &TMyClass::DoIt; funcArr1[1] = funcArr2[0] = &TMyClass::DoMore; /* more assignments */ // calling a function using an index to address the member function pointer // note: an instance of TMyClass is needed to call the member functions TMyClass instance; cout << (instance.*funcArr1[1])(12, 'a', 'b') << endl; cout << (instance.*funcArr1[0])(12, 'a', 'b') << endl; cout << (instance.*funcArr2[1])(34, 'a', 'b') << endl; cout << (instance.*funcArr2[0])(89, 'a', 'b') << endl; }
true
bbde39ba8412166022a6a3ad1f46e090a40d644d
C++
andreasbuetler/ChurchSketch2
/churchSketch_DistanceVariable/churchSketch_DistanceVariable.ino
UTF-8
3,818
2.78125
3
[]
no_license
/* Things to implement/problems: - endStopper: Tempo, Stops when Endstopper == true - reading pir when on the Top >> if movmement add delay - set position after endStop() == true - set final variables */ #include <dummy.h> #include <Arduino.h> #include <analogWrite.h> #define pirInputPin 27 #define motorPinL 5 #define motorPinR 18 #define poti1InputPin 34 #define poti2InputPin 35 #define endStopPin 25 const long maxMotorDistance = 700000; const long minMotorDistance = 200000; const int motorTime = 40; const int waitingTime = 3; int motorSpeed = 2000; long motorDistance = 1000; boolean motorDirection = true; boolean movement = false; boolean endStop = false; void setup() { pinMode(endStopPin, INPUT_PULLDOWN); pinMode(pirInputPin, INPUT); Serial.begin(9600); initializing(); //Serial.println("SETUP!"); } void loop() { endStopper(); //Serial.println(endStop); movement = pirRead(pirInputPin); if (movement) { //Serial.println("MOVEMENT!"); motorDirection = true; BalloonRiseAndFall(); delay(waitingTime * 1000); } } void endStopper() { endStop = false; if (digitalRead(endStopPin) == LOW) { endStop = false; } if (digitalRead(endStopPin) == HIGH) { endStop = true; //Serial.println("ENDSTOP"); stopMotor(); setStartPosition(); } } void setDistance() { motorDistance = map(analogRead(poti1InputPin), 1, 4094, minMotorDistance, maxMotorDistance); } //void setMotorSpeed() { // motorSpeed = map(analogRead(poti1InputPin), 0, 4095, 0, 255); //} void initializing() { //Serial.println("initializing...."); driveMotor(1, 1, 255); //driveMotor(0,3,200); stopMotor(); while (endStop == false) { driveMotor(0, 1, 255); } } void driveMotor(boolean dir, int duration, int tempo) { //Serial.println("DRIVE"); duration = duration * 1000; if (dir == 1) { for (int i = 0; i <= duration; i++) { endStopper(); analogWrite(motorPinR, 0); analogWrite(motorPinL, tempo); if (endStop == true) { //setStartPosition(); i = duration; } delay(1); } } if (dir == 0) { for (int k = 0; k <= duration; k++) { endStopper(); analogWrite(motorPinL, 0); analogWrite(motorPinR, tempo); if (endStop == true) { //setStartPosition(); k = duration; } delay(1); } } } void BalloonRiseAndFall() { //Serial.println("START TO RISE"); motorDirection = 1; setDistance(); motorSpeed = calculateSpeed(motorTime, motorDistance); Serial.println(motorSpeed); driveMotor(1, motorTime, motorSpeed); stopMotor(); delay(waitingTime * 1000); while(pirRead(pirInputPin)){ delay(waitingTime*1000); } Serial.println("START TO FALL"); motorDirection = !motorDirection; driveMotor(0, motorTime*1.2, motorSpeed); stopMotor(); //Serial.println("BACK TO BOTTOM"); motorDirection = !motorDirection; } boolean pirRead(int PinToRead) { if (digitalRead(PinToRead) == HIGH) { return true; } else { return false; } } int calculateSpeed(int duration, int distance) { int calculatedSpeed = distance / duration; Serial.println("Speed: "+calculatedSpeed); return map(calculatedSpeed, minMotorDistance / duration, maxMotorDistance / duration, 150, 254); } void stopMotor() { //driveMotor(0, 0, 0); analogWrite(motorPinR, 0); analogWrite(motorPinL, 0); } void setStartPosition() { if (endStop) { //Serial.println("correction"); for (int e=0;e<=100;e++){ analogWrite(motorPinR, 0); analogWrite(motorPinL, 200); } analogWrite(motorPinR, 0); analogWrite(motorPinL, 0); //delay(500); //endStop = false; //loop(); //driveMotor(1, 5, 200); } }
true
d4f6b372b952547b272fad6b5629070c20ac5989
C++
Daibingh/MyAlgoLearning
/算法与数据结构/cpp_leetcode/012 整数转罗马数字/main.cpp
UTF-8
1,707
3.328125
3
[]
no_license
#include "utils.hpp" using namespace std; /* - 第二种写法更优 */ class Solution { public: string intToRoman(int num) { unordered_map<int, string> strMap = {{1, "I"},{5, "V"}, {10, "X"}, {50, "L"}, {100, "C"}, {500, "D"}, {1000, "M"}, {4, "IV"}, {40, "XL"}, {400, "CD"}, {9, "IX"}, {90, "XC"}, {900, "CM"}}; vector<int> w{1000,900,500,400,100,90,50,40,10,9,5,4,1}; string res; int m; for (auto& t: w) { if (t>num) continue; m = num / t; // 除法 num %= t; printf("%d, %s, %d\n", m, strMap[t].c_str(), num); for (auto i=0;i<m;++i) res += strMap[t]; if (num==0) break; } return res; } }; class Solution2 { public: string intToRoman(int num) { string result; vector<int> store = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; vector<string> strs = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; int storeSize = int(store.size()); //贪心法 for (int i = 0; i < storeSize; i++) { while (num >= store[i]) { result.append(strs[i]); // 减法 num -= store[i]; } if (num==0) break; } return result; } }; // 作者:pinku-2 // 链接:https://leetcode-cn.com/problems/integer-to-roman/solution/zheng-shu-zhuan-luo-ma-shu-zi-cshi-xian-liang-chon/ // 来源:力扣(LeetCode) // 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 int main() { cout<<Solution2().intToRoman(3999)<<endl; }
true
3d25d382b79ed9a268322760f177d14512052ed1
C++
linzhangfeng/MuMuQiPai
/jianlimajiang/CardPool_ReadJson.cpp
UTF-8
2,420
2.8125
3
[]
no_license
#include "CardPool_ReadJson.h" #include <fstream> #include <iostream> #include <stdlib.h> using namespace std; CardPool_ReadJson::CardPool_ReadJson():m_MaxCount(0) { } CardPool_ReadJson::~CardPool_ReadJson() { } void CardPool_ReadJson::ReadJsonFile(std::string str_file_name) { m_TestFileName = str_file_name; ifstream ifs; ifs.open(m_TestFileName.data() , std::ios::binary); if ( !ifs ) { cout << "open failed" << endl; } Json::Reader json_read; Json::Value rootValue; if ( !json_read.parse(ifs , rootValue ) ) { return; } ParseJsonValue(rootValue); ifs.close(); } void CardPool_ReadJson::ParseJsonValue(Json::Value &data) { Json::Value _max_count = data["MaxCount"]; if (_max_count.isInt() ) { m_MaxCount = _max_count.asInt(); } Json::Value arryobj = data["CardPool"]; for ( size_t i = 0 ; i < arryobj.size() ; ++i ) { if (arryobj[i].isString()) { ParseOneRecord(arryobj[i].asString()); } } } void CardPool_ReadJson::ParseOneRecord(std::string record) { string str_tmp; while (record.length() ) { size_t pos = record.find(','); str_tmp = record.substr(0, pos ); while (str_tmp[0] == ' ' || str_tmp[0] == '\n' || str_tmp[0] == '\t' || str_tmp[0] == '\r') { str_tmp = str_tmp.substr(1); } str_tmp = str_tmp.substr(2); m_CardData.Add(Atoi(str_tmp,16)); if ( record.length() == 1 ) { break; } else { record = record.substr(pos + 1); } } } _tint32 CardPool_ReadJson::GetTestCard(_uint8 *pout, _uint32 out_size) { if ( m_CardData.Size() == 0 ) { return 0; } if (_uint32( m_CardData.Size()) < out_size ) { out_size = _uint32(m_CardData.Size()); } for (_uint32 i = 0 ; i < out_size ; ++i ) { pout[i] = m_CardData[i]; } return out_size; } _uint32 CardPool_ReadJson::GetMaxCount() { return m_MaxCount; } _uint32 CardPool_ReadJson::Atoi(const std::string num, int base) { _uint32 ret = 0; _uint32 tbase = 1; _uint32 rmove = 0; switch (base) { case 2: rmove = 1; break; case 8: rmove = 3; break; case 16: rmove = 4; break; default: return 0; } for (int i = num.length() - 1; i >= 0; --i) { if (num[i] <= '9' && num[i] >= '0') { ret = ret + (num[i] - '0')* tbase; tbase = tbase << rmove; } else { return 0; } } return ret; }
true
967c03e84342ebd46c129d37a91df15d350e59ea
C++
derisan/stl
/Day17/Day17/Source2.cpp
UTF-8
450
3.203125
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include "../../String.h" using namespace std; template<typename Iter, typename T> Iter my_find(Iter first, Iter last, const T& value) { while(first != last) { if(value == *first) { return first; } ++first; } return last; } int main() { vector<String> v{"123", "4567", "abc"}; auto p = find(v.begin(), v.end(), "abcd"); if(p != v.end()) { cout << *p << endl; } }
true
0ed083ac4f077cf249067eb86bea7d7f900c7d35
C++
gganis/xrdping
/xrdping.cc
UTF-8
9,249
2.59375
3
[]
no_license
#include <errno.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/times.h> //______________________________________________________________________________ // Prototypes int getsocket(struct hostent *h, int); void printhelp(); int recvn(int sock, void *buffer, int length); int sendn(int sock, const void *buffer, int length); //______________________________________________________________________________ // The client request structure typedef struct { int first; int second; int third; int fourth; int fifth; } clnt_HS_t; //______________________________________________________________________________ // The body received after the first handshake's header typedef struct { int msglen; int protover; int msgval; } srv_HS_t; static int verbose = 0; //______________________________________________________________________________ int main(int argc, char **argv) { // Non-blocking check for a PROOF service at 'url' // Return // 0 if a XProofd (or Xrootd) daemon is listening at 'url' // 1 if nothing is listening on the port (connection cannot be open) // 2 if something is listening but not XProofd (or Xrootd) // 3 PROOFD (or ROOTD) is listening at 'url' // Check arguments if (argc <= 1) { fprintf(stderr,"%s: at least one argument must be given!\n", argv[0]); printhelp(); exit(1); } // Extract URL and port from the URL, if any int port = -1; char *sport = 0, *url = 0; bool chk_xpd = 1; for (int i = 1; i < argc; i++) { if (argv[i]) { if (!strcmp(argv[i], "xproofd") || !strcmp(argv[i], "xpd")) { chk_xpd = 1; } else if (!strcmp(argv[i], "xrootd") || !strcmp(argv[i], "xrd")) { chk_xpd = 0; } else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) { printhelp(); exit(0); } else if (!strcmp(argv[i], "-v")) { verbose = 1; } else if (!strcmp(argv[i], "-nv")) { verbose = -1; } else if (!strcmp(argv[i], "-p")) { if (argv[i+1]) { i++; port = atoi(argv[i]); } } else { // This the URL url = new char[strlen(argv[i])+1]; strcpy(url, argv[i]); sport = (char *) strchr(url, ':'); if (sport) { *sport = 0; sport++; } } } } if (port < 0) { if (sport) { port = atoi(sport); } else if (chk_xpd) { port = 1093; } else { port = 1094; } } if (verbose > 0) fprintf(stderr, "Testing service at %s:%u ...\n", url, port); struct hostent *h = gethostbyname(url); if (!h) { if (verbose > -1) fprintf(stderr,"%s: unknown host '%s'\n",argv[0],url); exit(1); } // Get socket and listen to it int sd = getsocket(h,port); if (sd == -1) { if (verbose > -1) fprintf(stderr,"%s: problems creating socket ... exit\n",argv[0]); exit(1); } // Send the first bytes clnt_HS_t initHS; memset(&initHS, 0, sizeof(initHS)); int len = sizeof(initHS); if (chk_xpd) { initHS.third = (int)htonl((int)1); if (sendn(sd, &initHS, len) != len) { if (verbose > -1) fprintf(stderr,"%s: problems sending first set of handshake bytes\n",argv[0]); exit(2); } // These 8 bytes are need by 'rootd/proofd' and discarded by XRD/XPD int dum[2]; dum[0] = (int)htonl((int)4); dum[1] = (int)htonl((int)2012); if (sendn(sd, &dum[0], sizeof(dum)) != sizeof(dum)) { if (verbose > -1) fprintf(stderr,"%s: problems sending second set of handshake bytes\n",argv[0]); exit(2); } } else { initHS.fourth = (int)htonl((int)4); initHS.fifth = (int)htonl((int)2012); if (sendn(sd, &initHS, len) != len) { if (verbose > -1) fprintf(stderr,"%s: problems sending handshake bytes\n",argv[0]); exit(2); } } // Read first server response int type; len = sizeof(type); int nr = 0; if ((nr = recvn(sd, &type, len)) != len) { // 4 bytes if (verbose > -1) fprintf(stderr, "%s: 1st: wrong number of bytes read: %d (expected: %d)\n", argv[0], nr, len); exit(2); } // To host byte order type = ntohl(type); // Check if the server is the eXtended proofd if (type == 0) { srv_HS_t xbody; len = sizeof(xbody); if ((nr = recvn(sd, &xbody, len)) != len) { // 12(4+4+4) bytes if (verbose > -1) fprintf(stderr, "%s: 2nd: wrong number of bytes read: %d (expected: %d)\n", argv[0], nr, len); exit(2); } xbody.protover = ntohl(xbody.protover); xbody.msgval = ntohl(xbody.msglen); xbody.msglen = ntohl(xbody.msgval); } else if (type == 8) { // Standard proofd if (verbose > -1) fprintf(stderr, "%s: server is %s\n", argv[0], (chk_xpd ? "PROOFD" : "ROOTD")); exit(3); } else { // We don't know the server type if (verbose > -1) fprintf(stderr, "%s: unknown server type: %d\n", argv[0], type); exit(2); } // Done exit(0); } // Auxilliary functions //______________________________________________________________________________ int getsocket(struct hostent *h, int port) { int sd, rc; struct sockaddr_in localAddr, servAddr; servAddr.sin_family = h->h_addrtype; memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length); servAddr.sin_port = htons(port); /* create socket */ sd = socket(AF_INET, SOCK_STREAM, 0); if(sd < 0) { if (verbose > -1) perror("cannot open socket "); return -1; } /* bind any port number */ localAddr.sin_family = AF_INET; localAddr.sin_addr.s_addr = htonl(INADDR_ANY); localAddr.sin_port = htons(0); rc = bind(sd, (struct sockaddr *) &localAddr, sizeof(localAddr)); if(rc < 0) { if (verbose > -1) perror("error "); return -1; } /* connect to server */ rc = connect(sd, (struct sockaddr *) &servAddr, sizeof(servAddr)); if(rc < 0) { if (verbose > -1) perror("cannot connect "); return -1; } return sd; } //______________________________________________________________________________ int sendn(int sock, const void *buffer, int length) { // Send exactly length bytes from buffer. if (sock < 0) return -1; int n, nsent = 0; const char *buf = (const char *)buffer; for (n = 0; n < length; n += nsent) { if ((nsent = send(sock, buf+n, length-n, 0)) <= 0) { if (verbose > -1) perror("problems sending "); return nsent; } } return n; } //______________________________________________________________________________ int recvn(int sock, void *buffer, int length) { // Receive exactly length bytes into buffer. Returns number of bytes // received. Returns -1 in case of error. if (sock < 0) return -1; int n, nrecv = 0; char *buf = (char *)buffer; for (n = 0; n < length; n += nrecv) { while ((nrecv = recv(sock, buf+n, length-n, 0)) == -1 && errno == EINTR) errno = 0; // probably a SIGCLD that was caught if (nrecv < 0) { if (verbose > -1) perror("problems receiving "); return nrecv; } else if (nrecv == 0) break; // EOF } return n; } //______________________________________________________________________________ void printhelp() { // Help function fprintf(stderr, "\n"); fprintf(stderr, " xrdping: ping xproofd (or xrootd) service on remote host\n"); fprintf(stderr, "\n"); fprintf(stderr, " Syntax:\n"); fprintf(stderr, " xrdping host[:port] [xrootd|xrd] [-p port] [-v|-nv] [-h|--help]\n"); fprintf(stderr, "\n"); fprintf(stderr, " host: hostname where service should be running\n"); fprintf(stderr, " xrd, xrootd: check for an xrootd service instead of xproofd\n"); fprintf(stderr, " port: port (at hostname) where service should be listening; port specification\n"); fprintf(stderr, " via the '-p' switch has priority\n"); fprintf(stderr, " -v: switch-on some verbosity\n"); fprintf(stderr, " -nv: switch-off all verbosity (errors included)\n"); fprintf(stderr, " -h, --help: print this screen\n"); fprintf(stderr, "\n"); fprintf(stderr, " Return: 0 the required service accepts connections at given host and port\n"); fprintf(stderr, " 1 no service running at the given host and port\n"); fprintf(stderr, " 2 a service accepts connections at given host and port but most likely\n"); fprintf(stderr, " is not of the required type (failure occured during handshake)\n"); fprintf(stderr, " 3 service at given host and port is PROOFD (or ROOTD)\n"); fprintf(stderr, "\n"); }
true
a396ae45b4249584264d1d450b118c137da1403c
C++
tirtawr/arduino-sketches
/uno-stepper/uno-stepper.ino
UTF-8
2,095
2.8125
3
[ "MIT" ]
permissive
#define STEPPER_PIN_1 9 #define STEPPER_PIN_2 10 #define STEPPER_PIN_3 11 #define STEPPER_PIN_4 12 int step_number = 0; void setup() { pinMode(STEPPER_PIN_1, OUTPUT); pinMode(STEPPER_PIN_2, OUTPUT); pinMode(STEPPER_PIN_3, OUTPUT); pinMode(STEPPER_PIN_4, OUTPUT); } void loop() { oneStep(true); delay(2); } void oneStep(bool isClockwise) { if(isClockwise) { switch(step_number) { case 0: digitalWrite(STEPPER_PIN_1, HIGH); digitalWrite(STEPPER_PIN_2, LOW); digitalWrite(STEPPER_PIN_3, LOW); digitalWrite(STEPPER_PIN_4, LOW); break; case 1: digitalWrite(STEPPER_PIN_1, LOW); digitalWrite(STEPPER_PIN_2, HIGH); digitalWrite(STEPPER_PIN_3, LOW); digitalWrite(STEPPER_PIN_4, LOW); break; case 2: digitalWrite(STEPPER_PIN_1, LOW); digitalWrite(STEPPER_PIN_2, LOW); digitalWrite(STEPPER_PIN_3, HIGH); digitalWrite(STEPPER_PIN_4, LOW); break; case 3: digitalWrite(STEPPER_PIN_1, LOW); digitalWrite(STEPPER_PIN_2, LOW); digitalWrite(STEPPER_PIN_3, LOW); digitalWrite(STEPPER_PIN_4, HIGH); break; } } else { switch(step_number) { case 0: digitalWrite(STEPPER_PIN_1, LOW); digitalWrite(STEPPER_PIN_2, LOW); digitalWrite(STEPPER_PIN_3, LOW); digitalWrite(STEPPER_PIN_4, HIGH); break; case 1: digitalWrite(STEPPER_PIN_1, LOW); digitalWrite(STEPPER_PIN_2, LOW); digitalWrite(STEPPER_PIN_3, HIGH); digitalWrite(STEPPER_PIN_4, LOW); break; case 2: digitalWrite(STEPPER_PIN_1, LOW); digitalWrite(STEPPER_PIN_2, HIGH); digitalWrite(STEPPER_PIN_3, LOW); digitalWrite(STEPPER_PIN_4, LOW); break; case 3: digitalWrite(STEPPER_PIN_1, HIGH); digitalWrite(STEPPER_PIN_2, LOW); digitalWrite(STEPPER_PIN_3, LOW); digitalWrite(STEPPER_PIN_4, LOW); } } step_number++; if(step_number > 3) { step_number = 0; } }
true
433a2f5ba4b7743c1f7b6d4f951afe189893f00d
C++
KalimovAleksey/Kalimov1
/Kalimov_dz_aip/hw_4/main.cpp
UTF-8
403
3.65625
4
[]
no_license
#include <iostream> #include <math.h> /*Вычислите значение выражения:|x| + x^5, если x=−2. Ответ: -30*/ int main() { float x; float c; std::cout<< "|x| + x^5, if x=−2. Answer: -30" <<std::endl; std::cout<< "Enter number" <<std::endl; std::cin>> x ; c=abs(x)+(x*x*x*x*x); std::cout<< "|x| + x^5= " << c <<std::endl; }
true
7cc5a2ae97569076dae19430d8dc0abed2cc3625
C++
apoorv-j/Data-Structures-Cpp
/strings/testString.cpp
UTF-8
435
3.328125
3
[]
no_license
#include <iostream> #include <algorithm> #include <string.h> using namespace std; bool isPalindrome(string &s) { string rev = s; reverse(rev.begin(), rev.end()); return s == rev; } int main() { int n; cin >> n; string arr; for (int i = 0; i < n; i++) { int x; cin >> x; arr.append(to_string(x)); } cout << arr; cout << boolalpha << isPalindrome(arr); return 0; }
true
15511d172e84a7bda7e0049fdb7ff51cb16e964b
C++
Flytte/flytte
/backend/drone_ros_ws/src/drone_app/include/common/Pose.hpp
UTF-8
720
3.265625
3
[ "BSD-3-Clause" ]
permissive
#ifndef POSE_HPP_ #define POSE_HPP_ #include <iostream> /** * Describes a pose, that is a 6D vector with 3 position coordinates * as well as 3 orientation values. */ struct Pose { Pose(double posX = 0, double posY = 0, double posZ = 0, double rotX = 0, double rotY = 0, double rotZ = 0) : posX(posX), posY(posY), posZ(posZ), rotX(rotX), rotY(rotY), rotZ(rotZ) {} Pose& operator+=(const Pose& other); Pose operator+(const Pose& other) const; friend std::ostream& operator<<(std::ostream& out, const Pose& p); double posX; double posY; double posZ; double rotX; double rotY; double rotZ; }; #endif /* POSE_HPP_ */
true
fa3ee32035b5e7ba5d47614dcabb7ff658a13ec0
C++
congdeptrainhat/OLP_Training
/C++/Bai20.cpp
UTF-8
1,433
3.828125
4
[]
no_license
#include <bits/stdc++.h> using namespace std; struct Point { int x, y; void input() { cin >> x >> y; } float distance(Point p) { return sqrt(pow(p.x - x, 2) + pow(p.y - y, 2)); } }; struct Circle { Point center; int R; void input() { // Cái này gọi là "Nạp chồng phương thức". // Phương thức là một hàm, nhưng hàm này là "thuộc tính" của 1 class hoặc 1 struct // Khi có 2 phương thức trùng tên nhau sẽ sinh ra hiện tượng "Nạp chồng phương thức" // center.input() -> phương thức input này là của struct Point vì biến center có kiểu là Point // Phương thức input trong struct Circle sẽ gọi đến phương thức input trong lớp Point để nhập giá trị cho biến center center.input(); cin >> R; } bool isIntersect(Circle c) { float R_distance = center.distance(c.center); return (R_distance < (R + c.R)) ? true : false; }; }; int main() { int n, x, y, R, count = 0; cin >> n; Circle C[n]; for (int i = 0; i < n; i++) { C[i].input(); } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (C[i].isIntersect(C[j])) { count++; } } } cout << count << endl; }
true
897c0e0716c3c42ff126dd0b0594ac3aaaf82a46
C++
JacquesDonnelly/advent-of-code-2020
/src/day_13.cpp
UTF-8
1,011
3.015625
3
[]
no_license
#include "day_13.h" int day_13_part_1_main(std::string file_input){ BusNotes bus_notes = read_bus_notes(file_input); int min_wait_time = std::numeric_limits<int>::max(); int selected_bus_id = std::numeric_limits<int>::max(); for (Bus bus : bus_notes.busses){ int wait_time = bus.id - (bus_notes.earliest % bus.id); std::cout << wait_time << std::endl; if (wait_time < min_wait_time){ min_wait_time = wait_time; selected_bus_id = bus.id; } } return min_wait_time * selected_bus_id; } BusNotes read_bus_notes(std::string file_input){ std::vector<std::string> lines = load_strings_from_file(file_input); int earliest = std::stoi(lines[0]); auto bus_id_strings = split_string_by_delimiter(lines[1], ","); std::vector<Bus> busses; for (auto id : bus_id_strings){ if (id != "x"){ Bus bus; bus.id = std::stoi(id); busses.push_back(bus); } } BusNotes result; result.earliest = earliest; result.busses = busses; return result; }
true
81c7a63ef91e59f80b309a81f89b441013ab0f35
C++
GeneralStudy/studymuduo
/reactor/Timer.h
UTF-8
739
2.703125
3
[]
no_license
#ifndef MUDUO_NET_TIMER_H #define MUDUO_NET_TIMER_H #include <boost/noncopyable.hpp> #include "../datetime/Timestamp.h" #include "Callbacks.h" namespace muduo { class Timer: boost::noncopyable { public: Timer(const TimerCallback& cb, Timestamp when, double interval): m_callback(cb), m_expiration(when), m_inteval(interval), m_repeat(interval > 0.0) { } void run() const { m_callback(); } Timestamp expiration() const { return m_expiration; } bool repeat() const { return m_repeat; } void restart(Timestamp now); private: const TimerCallback m_callback; Timestamp m_expiration; const double m_inteval; const bool m_repeat; }; } #endif
true
139deac476b018cf59f084383d00d9c0d5353b56
C++
vxl/vxl
/contrib/mul/pdf1d/pdf1d_gaussian_sampler.cxx
UTF-8
3,236
2.515625
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
// This is mul/pdf1d/pdf1d_gaussian_sampler.cxx //: // \file // \author Tim Cootes // \brief Sampler class for univariate Gaussian classes. #include "pdf1d_gaussian_sampler.h" #include <cassert> #ifdef _MSC_VER # include "vcl_msvc_warnings.h" #endif #include <pdf1d/pdf1d_gaussian.h> //======================================================================= // Dflt ctor //======================================================================= pdf1d_gaussian_sampler::pdf1d_gaussian_sampler(): rng_(9667566ul) { } //======================================================================= // Destructor //======================================================================= pdf1d_gaussian_sampler::~pdf1d_gaussian_sampler() = default; //======================================================================= // Method: is_a //======================================================================= std::string pdf1d_gaussian_sampler::is_a() const { return std::string("pdf1d_gaussian_sampler"); } //======================================================================= // Method: is_class //======================================================================= bool pdf1d_gaussian_sampler::is_class(std::string const& s) const { return pdf1d_sampler::is_class(s) || s==pdf1d_gaussian_sampler::is_a(); } //======================================================================= // Method: clone //======================================================================= pdf1d_sampler* pdf1d_gaussian_sampler::clone() const { return new pdf1d_gaussian_sampler(*this); } //======================================================================= void pdf1d_gaussian_sampler::reseed(unsigned long seed) { rng_.reseed(seed); } //======================================================================= //: Set model for which this is an instance // Error check that it is an axis gaussian. void pdf1d_gaussian_sampler::set_model(const pdf1d_pdf& model) { assert(model.is_class("pdf1d_gaussian")); // cannot use dynamic_cast<> without rtti - PVr // rtti currently turned off pdf1d_sampler::set_model(model); } //======================================================================= double pdf1d_gaussian_sampler::sample() { const auto & gauss = static_cast<const pdf1d_gaussian &>(model()); return gauss.mean() + gauss.sd()*rng_.normal(); } //: Fill x with samples possibly chosen so as to represent the distribution // 5 or fewer samples requested, they are spaced out equally. void pdf1d_gaussian_sampler::regular_samples(vnl_vector<double>& x) { int n = x.size(); if (n>5) { pdf1d_sampler::regular_samples(x); return; } // Strictly should select samples so that CDF(x) is equally spread in [0,1] const auto & gauss = static_cast<const pdf1d_gaussian &>( model()); double lim = gauss.sd()*(n-1)/2.0; double mean = gauss.mean(); for (int i=0;i<n;++i) x[i] = mean+lim * (2*(double(i)/(n-1))-1); } //======================================================================= //: Return a reference to the pdf model // This is properly cast. const pdf1d_gaussian& pdf1d_gaussian_sampler::gaussian() const { return static_cast<const pdf1d_gaussian&>( model()); }
true
aabef9d63d67ed5aecdf3d0171b43cd3b5e71bc4
C++
TLaviron/mehetia
/src/vulkan_mehetia/utilities.cpp
UTF-8
2,364
2.6875
3
[ "MIT" ]
permissive
#include "vulkan_mehetia/utilities.h" #include <string> namespace vulkan_mehetia { VkResult resultCheck(VkResult _result, std::string_view _sourceFile, int32_t _line) { std::string errorMessage(_sourceFile); errorMessage += ":" + std::to_string(_line) + " "; switch (_result) { case VK_SUCCESS: errorMessage += "Success"; break; case VK_NOT_READY: errorMessage += "Not ready"; break; case VK_TIMEOUT: errorMessage += "Timeout"; break; case VK_EVENT_SET: errorMessage += "Event set"; break; case VK_EVENT_RESET: errorMessage += "Event reset"; break; case VK_INCOMPLETE: errorMessage += "Incomplete"; break; case VK_ERROR_OUT_OF_HOST_MEMORY: errorMessage += "Out of host memory"; break; case VK_ERROR_OUT_OF_DEVICE_MEMORY: errorMessage += "Out of device memory"; break; case VK_ERROR_INITIALIZATION_FAILED: errorMessage += "Initialization failed"; break; case VK_ERROR_DEVICE_LOST: errorMessage += "Device lost"; break; case VK_ERROR_MEMORY_MAP_FAILED: errorMessage += "Memory map failed"; break; case VK_ERROR_LAYER_NOT_PRESENT: errorMessage += "Layer not present"; break; case VK_ERROR_EXTENSION_NOT_PRESENT: errorMessage += "Extension not present"; break; case VK_ERROR_FEATURE_NOT_PRESENT: errorMessage += "Feature not present"; break; case VK_ERROR_INCOMPATIBLE_DRIVER: errorMessage += "Not ready"; break; case VK_ERROR_TOO_MANY_OBJECTS: errorMessage += "Too many objects"; break; case VK_ERROR_FORMAT_NOT_SUPPORTED: errorMessage += "Format not supported"; break; case VK_ERROR_FRAGMENTED_POOL: errorMessage += "Fragmented pool"; break; case VK_ERROR_OUT_OF_POOL_MEMORY: errorMessage += "Out of pool memory"; break; case VK_ERROR_INVALID_EXTERNAL_HANDLE: errorMessage += "Invalid external handle"; break; default: errorMessage += "Undocumented error (" + std::to_string(_result) + ")"; break; } if (_result < 0) { throw VulkanError(errorMessage); } return _result; } } // namespace vulkan_mehetia
true
7aec1fe9c8568fe51a05348d5821d08666cec80e
C++
senior-bull/google-benchmark-tutorial
/source/core/try_catch_overhead.cpp
UTF-8
604
2.515625
3
[]
no_license
#include <benchmark/benchmark.h> #include <vector> #include <string> #include <exception> #include <cstdint> using namespace std; int doSome() { if (std::rand() < 0) { throw 2; } return 1; } static void TryCatch(benchmark::State& state) { for (auto _ : state) { try { benchmark::DoNotOptimize(doSome()); } catch (std::exception &e) { } } } BENCHMARK(TryCatch); static void NoTryCatch(benchmark::State& state) { for (auto _ : state) { benchmark::DoNotOptimize(doSome()); } } BENCHMARK(NoTryCatch); BENCHMARK_MAIN();
true
7872de85ef9c0b8304c3e42d796cb2bb24a38fa9
C++
geetheshtg/Octabrix
/LED_Serial/LED_Serial.ino
UTF-8
259
2.59375
3
[]
no_license
int incomingByte = 0; void setup() { pinMode(13,OUTPUT); Serial.begin(115200); } void loop() { incomingByte = Serial.read(); if(incomingByte=='0') { digitalWrite(13,LOW); } else if(incomingByte=='1') { digitalWrite(13,HIGH); } }
true
4ff3f273b883fd2898a622f5ef8feed4881666d2
C++
fys445089968/qt-magic_tower-21-
/dialogwindow.cpp
UTF-8
40,209
2.578125
3
[]
no_license
#include "dialogwindow.h" #include "ui_dialogwindow.h" DialogWindow::DialogWindow(QWidget *parent) : QWidget(parent), ui(new Ui::DialogWindow) { ui->setupUi(this); Count_Num = 0; Init(); } void DialogWindow::Init() { Hide_Window(); if(Braver.Dialog_state_num == 0)//首次和仙子对话 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r ……"); } else if(Braver.Dialog_state_num == 1)//拿到十字架后和仙子对话 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r 仙子,我已经将那个十字架找到了。"); } else if(Braver.Dialog_state_num == 2)//2楼老头 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r 您已经得救了!"); } else if(Braver.Dialog_state_num == 3)//2楼商人 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r 您已经得救了!"); } else if(Braver.Dialog_state_num == 4)//首次和小偷对话 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r 你已经得救了!"); } else if(Braver.Dialog_state_num == 5)//拿到榔头和小偷对话 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r 哈,快看!我找到了什么"); } else if(Braver.Dialog_state_num == 14)//15楼老头 { this->ui->graphicsView_old->show(); this->ui->textBrowser->setText("神秘老人:\r 你好,勇敢的孩子,你终于来到这了。"); } else if(Braver.Dialog_state_num == 15)//15楼商人 { this->ui->graphicsView_red->show(); this->ui->textBrowser->setText("商人:\r 啊哈,欢迎你的到来。我这里有一件对你来说"); } else if(Braver.Dialog_state_num == 16)//和16楼老头对完话和仙子对话 { this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙子:\r 嗯?!你手里的那个东西是什么?"); } else if(Braver.Dialog_state_num == 17)//和16楼老头对话 { this->ui->graphicsView_old->show(); this->ui->textBrowser->setText("神秘老人:\r 年轻人,你终于来了"); } else if(Braver.Dialog_state_num == 18)//和16楼魔王对话 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r ……"); } else if(Braver.Dialog_state_num == 19)//和17楼魔王对话 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r 大魔头,你的死期到了!"); } else if(Braver.Dialog_state_num == 20)//和公主对话 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r 公主,你得救了!"); } else if(Braver.Dialog_state_num == 21)//和16楼魔王死后对话 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r 快把公主交出来!"); } else if(Braver.Dialog_state_num == 22)//和19楼魔王死后对话 { this->ui->graphicsView_devil19->show(); this->ui->textBrowser->setText("冥灵魔王:\r 看不出来你还有两下子,有本领的话来21楼。"); } else if(Braver.Dialog_state_num == 23)//和21楼魔王死后对话 { this->ui->graphicsView_devil19->show(); this->ui->textBrowser->setText("冥灵魔王:\r 啊……\r 怎么可能,我怎么可能"); } if(Braver.Dialog_state_num == 24)//首次和22楼仙子对话 { this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙子:\r 做的很好,现在你已经将那个可恶的冥灵魔王"); } if(Braver.Dialog_state_num == 25)//集齐灵杖后22楼仙子对话 { this->ui->graphicsView_braver->show(); this->ui->textBrowser->setText("勇士:\r 快看,我找到所有的灵杖了"); } //space闪烁效果 int k =0; int count =0; space_timer = new QTimer(this); space_timer->start(); space_timer->setInterval(400); connect(space_timer,&QTimer::timeout,this,[=]()mutable{ count++; if(count % 2 ==0) k =255; else { k = 75; } ui->textBrowser_2->setTextColor(QColor(255,255,255,k)); ui->textBrowser_2->setText("--space--"); }); this->ui->textBrowser->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->ui->textBrowser->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ImgFairy = QImage(":/Graphics/Characters/001-npc01.png").copy(0, 96, 32, 32).scaled(48,48,Qt::KeepAspectRatioByExpanding ); ImgBraver= QImage(":/Graphics/Characters/002-Braver01.png").copy(0, 0, 32, 32).scaled(48,48,Qt::KeepAspectRatioByExpanding ); ImgThief = QImage(":/Graphics/Characters/001-npc01.png").copy(0, 64, 32, 32).scaled(48,48,Qt::KeepAspectRatioByExpanding ); ImgNpcOld = QImage(":/Graphics/Characters/001-npc01.png").copy(0, 0, 32, 32).scaled(48,48,Qt::KeepAspectRatioByExpanding ); ImgNpcRed = QImage(":/Graphics/Characters/001-npc01.png").copy(0, 32, 32, 32).scaled(48,48,Qt::KeepAspectRatioByExpanding ); ImgDevil16 = QImage(":/Graphics/Characters/010-Monster08.png").copy(0,0,32,32).scaled(48,48,Qt::KeepAspectRatio); ImgDevil19 = QImage(":/Graphics/Characters/004-Monster02.png").copy(0,96,32,32).scaled(48,48,Qt::KeepAspectRatio); ImgPrincess = QImage(":/Graphics/Characters/001-npc02.png").copy(0, 96, 32, 32).scaled(48,48,Qt::KeepAspectRatioByExpanding ); //仙女头像 QGraphicsScene *scene_fairy = new QGraphicsScene; scene_fairy->addPixmap(QPixmap::fromImage(ImgFairy)); this->ui->graphicsView_fairy->setScene(scene_fairy); this->ui->graphicsView_fairy->setStyleSheet("background:transparent;border:none;"); //勇士头像 QGraphicsScene *scene_braver = new QGraphicsScene; scene_braver->addPixmap(QPixmap::fromImage(ImgBraver)); this->ui->graphicsView_braver->setScene(scene_braver); this->ui->graphicsView_braver->setStyleSheet("background:transparent;border:none;"); //小偷头像 QGraphicsScene *scene_thief = new QGraphicsScene; scene_thief->addPixmap(QPixmap::fromImage(ImgThief)); this->ui->graphicsView_thief->setScene(scene_thief); this->ui->graphicsView_thief->setStyleSheet("background:transparent;border:none;"); //老头头像 QGraphicsScene *scene_old = new QGraphicsScene; scene_old->addPixmap(QPixmap::fromImage(ImgNpcOld)); this->ui->graphicsView_old->setScene(scene_old); this->ui->graphicsView_old->setStyleSheet("background:transparent;border:none;"); //商人头像 QGraphicsScene *scene_red = new QGraphicsScene; scene_red->addPixmap(QPixmap::fromImage(ImgNpcRed)); this->ui->graphicsView_red->setScene(scene_red); this->ui->graphicsView_red->setStyleSheet("background:transparent;border:none;"); //16楼魔王头像 QGraphicsScene *scene_devil16 = new QGraphicsScene; scene_devil16->addPixmap(QPixmap::fromImage(ImgDevil16)); this->ui->graphicsView_devil16->setScene(scene_devil16); this->ui->graphicsView_devil16->setStyleSheet("background:transparent;border:none;"); //19楼魔王头像 QGraphicsScene *scene_devil19 = new QGraphicsScene; scene_devil19->addPixmap(QPixmap::fromImage(ImgDevil19)); this->ui->graphicsView_devil19->setScene(scene_devil19); this->ui->graphicsView_devil19->setStyleSheet("background:transparent;border:none;"); // 公主头像 QGraphicsScene *scene_princess = new QGraphicsScene; scene_princess->addPixmap(QPixmap::fromImage(ImgPrincess)); this->ui->graphicsView_princess->setScene(scene_princess); this->ui->graphicsView_princess->setStyleSheet("background:transparent;border:none;"); } void DialogWindow::Hide_Window() { this->ui->graphicsView_fairy->hide(); this->ui->graphicsView_thief->hide(); this->ui->graphicsView_old->hide(); this->ui->graphicsView_red->hide(); this->ui->graphicsView_braver->hide(); this->ui->graphicsView_devil16->hide(); this->ui->graphicsView_devil19->hide(); this->ui->graphicsView_princess->hide(); } void DialogWindow::keyPressEvent(QKeyEvent *event) { if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 0) //空格键且状态0(首次和仙女对话) { Count_Num ++ ; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 你醒了!"); } else if(Count_Num == 2) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r ……\r 你是谁?我在那里?"); } else if(Count_Num == 3) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 我是这里的仙子,刚才你被这里的小怪打昏了。"); } else if(Count_Num == 4) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r ……\r 剑,剑,我的剑呢?"); } else if(Count_Num == 5) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 你的剑被他们抢走了,我只来得及将你救出来。"); } else if(Count_Num == 6) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r 那公主呢?我是来救公主的。"); } else if(Count_Num == 7) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 公主还在里面,你这样进去是打不过里面的小怪的。"); } else if(Count_Num == 8) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r 那怎么办,我答应了国王一定要把公主救出来的,那我现在应该怎"); } else if(Count_Num == 9) { this->ui->textBrowser->setText("勇士:\r么办呢?"); } else if(Count_Num == 10) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 放心吧,我把我的力量借给你,你就可以打赢这些小怪了。"); } else if(Count_Num == 11) { this->ui->textBrowser->setText("仙女:\r 不过,你得先帮我去找一样东西,找到了再来这里找我。"); } else if(Count_Num == 12) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r 找东西?找什么东西?"); } else if(Count_Num == 13) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 是一个十字架,中间有一颗红色的宝石。"); } else if(Count_Num == 14) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r 那东西有什么用吗?"); } else if(Count_Num == 15) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 我本来是这座塔的守护者,可不久前,从北方来了一批恶魔,他们"); } else if(Count_Num == 16) { this->ui->textBrowser->setText("仙女:\r占领了这座塔,并将我的魔力封在了这个十字架中,如果你能将它带"); } else if(Count_Num == 17) { this->ui->textBrowser->setText("仙女:\r出塔来,那我的魔力就会慢慢恢复,到那时我便可以把力量借给你去"); } else if(Count_Num == 18) { this->ui->textBrowser->setText("仙女:\r救公主了。要记住:只有用我的魔力才可以打开二十一层的门。"); } else if(Count_Num == 19) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r ……\r 好吧,我试试看。"); } else if(Count_Num == 20) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 刚才我去看过了,你的剑被放在三楼,你的盾在五楼上,而那个十"); } else if(Count_Num == 21) { this->ui->textBrowser->setText("仙女:\r字架被放在七楼。要到七楼,你得先取回你的剑和盾。"); } else if(Count_Num == 22) { this->ui->textBrowser->setText("仙女:\r 另外,在塔的其他楼层上,还有一些存放了好几百年的宝剑和宝物"); } else if(Count_Num == 23) { this->ui->textBrowser->setText("仙女:\r如果得到它们,对于你对付这里的怪物将有很大的帮助。"); } else if(Count_Num == 24) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r ……\r 可是,我怎么进去呢?"); } else if(Count_Num == 25) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 我这里有三把钥匙,你先拿去,在塔里还有很多这样的钥匙。"); } else if(Count_Num == 26) { this->ui->textBrowser->setText("仙女:\r 你一定要珍惜使用。勇敢去去吧,勇士!"); //这里地图要刷新显示钥匙增加了 Braver.key1 += 1; Braver.key2 += 1; Braver.key3 += 1; emit Update_State(); } else if(Count_Num == 27) { Count_Num = 0; Hide_Window(); space_timer->stop(); Braver.Speak_Fairy = true; emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 1) //空格键且状态1(拿到十字架后和仙女对话) { Count_Num++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 你做的很好。\r 那么,现在我就开始授予"); } else if(Count_Num == 2) { this->ui->textBrowser->setText("仙女:\r 你更强的力量。\r 唵嘛呢叭咪吽!"); } else if(Count_Num == 3) { this->ui->textBrowser->setText("仙女:\r 好了,我已经将你现在的能力提升了!"); } else if(Count_Num == 4) { this->ui->textBrowser->setText("仙女:\r 记住,如果你没有足够的能力的话,不要去第二十一层!"); } else if(Count_Num == 5) { this->ui->textBrowser->setText("仙女:\r 在那一层里,你所有宝物的法力都会失去作用!"); } else if(Count_Num == 6) { Count_Num = 0; space_timer->stop(); Hide_Window(); Braver.hp *= 1.3; Braver.atk *= 1.3; Braver.def *= 1.3; Braver.Summit_Cross = true; emit Update_State(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 16) //空格键且状态16(和16楼老头对过话后和仙女对话) { Count_Num++; if(Count_Num == 1) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r 这个?这个是一个老人交给我的,是他让我带它来"); } else if(Count_Num == 2) { this->ui->textBrowser->setText("勇士:\r 找你的。他说你知道它的来历和作用。"); } else if(Count_Num == 3) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 这是以前的圣者留下来的。他们一共有三个,你这个叫"); } else if(Count_Num == 4) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 心之魔杖,应该还有一个镶有蓝宝石的“冰之灵杖和镶有红宝石的"); } else if(Count_Num == 5) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 炎之灵杖,如果不把他们找齐的话天下会大乱的。"); } else if(Count_Num == 6) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r 好,那我就去把他们全部找到!"); } else if(Count_Num == 7) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Update_State(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 2) //空格键且状态2(和2楼老头对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_old->show(); this->ui->textBrowser->setText("神秘老头:\r 哦,我的孩子,真是太感谢你了"); } else if(Count_Num == 2 ) { this->ui->textBrowser->setText("神秘老头:\r 这个地方又脏又坏,我真是快呆不下去了。"); } else if(Count_Num == 3 ) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_old->hide(); this->ui->textBrowser->setText("勇士:\r 快走吧,我还得救被关在这里的公主。"); } else if(Count_Num == 4 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_old->show(); this->ui->textBrowser->setText("神秘老头:\r 哦,你是来救公主的,为了表示对你的感谢,"); } else if(Count_Num == 5 ) { this->ui->textBrowser->setText("神秘老头:\r 这个东西就送给你吧,这还是我年轻时候用过的。"); } else if(Count_Num == 6 ) { this->ui->textBrowser->setText("神秘老头:\r 拿着它去解救公主吧!"); } else if(Count_Num == 7) { Count_Num = 0; space_timer->stop(); Hide_Window(); Braver.atk += 30; emit Update_State(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 3) //空格键且状态3(和2楼商人对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_red->show(); this->ui->textBrowser->setText("商人:\r 哦,是嘛!真是太感谢你了!"); } else if(Count_Num == 2 ) { this->ui->textBrowser->setText("商人:\r 我是个商人,不知道为什么被抓到这里来了。"); } else if(Count_Num == 3 ) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_red->hide(); this->ui->textBrowser->setText("勇士:\r 快走吧,现在您已经自由了。"); } else if(Count_Num == 4 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_red->show(); this->ui->textBrowser->setText("商人:\r 哦,对对对,我已经自由了。"); } else if(Count_Num == 5 ) { this->ui->textBrowser->setText("商人:\r 那这个东西就给你吧,本来是准备卖钱的。"); } else if(Count_Num == 6 ) { this->ui->textBrowser->setText("商人:\r 相信他对你一定很有帮助!"); } else if(Count_Num == 7) { Count_Num = 0; space_timer->stop(); Hide_Window(); Braver.def += 30; emit Update_State(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 4) //空格键且状态4(首次和小偷对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_thief->show(); this->ui->textBrowser->setText("小偷:\r 啊,那真是太好了,我又可以在这里面寻宝了!"); } else if(Count_Num == 2) { this->ui->textBrowser->setText("小偷:\r 哦,我还没有自我介绍,我叫杰克,是这附近有名的小偷,什么金银财"); } else if(Count_Num == 3) { this->ui->textBrowser->setText("小偷:\r 宝我样样都偷过。不过这次运气可不太好,刚进来就被抓了。"); } else if(Count_Num == 4) { this->ui->textBrowser->setText("小偷:\r 现在你帮我打开了门,那我就帮你做一件事吧。"); } else if(Count_Num == 5) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_thief->hide(); this->ui->textBrowser->setText("勇士:\r 快走吧,外面还有很多怪物,我可能顾不上你。"); } else if(Count_Num == 6) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_thief->show(); this->ui->textBrowser->setText("小偷:\r 不,不,不会有事的。快说吧,叫我做什么?"); } else if(Count_Num == 7) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_thief->hide(); this->ui->textBrowser->setText("勇士:\r ……\r 你会开门吗?"); } else if(Count_Num == 8) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_thief->show(); this->ui->textBrowser->setText("小偷:\r 那当然。"); } else if(Count_Num == 9) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_thief->hide(); this->ui->textBrowser->setText("勇士:\r 那就请你帮我打开第二层的门吧!"); } else if(Count_Num == 10) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_thief->show(); this->ui->textBrowser->setText("小偷:\r 那个简单,不过,如果你能帮我找到一把嵌了红"); } else if(Count_Num == 11) { this->ui->textBrowser->setText("小偷:\r 宝石的铁榔头的话,我还帮你打通第十八层的路。"); } else if(Count_Num == 12) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_thief->hide(); this->ui->textBrowser->setText("勇士:\r 嵌了红宝石的铁榔头?\r 好吧,那我帮你找找。"); } else if(Count_Num == 13) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_thief->show(); this->ui->textBrowser->setText("小偷:\r 非常感谢,一会我便会将第二层的门打开。"); } else if(Count_Num == 14) { this->ui->textBrowser->setText("小偷:\r 如果你找到那个铁榔头的话,还是来这里找我!"); } else if(Count_Num == 15) { Count_Num = 0; space_timer->stop(); Hide_Window(); Braver.Speak_Thief = true; emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 5) //空格键且状态5(拿到榔头和小偷对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_thief->show(); this->ui->textBrowser->setText("小偷:\r 太好了,这个东西果然在这里!"); } else if(Count_Num == 2) { this->ui->textBrowser->setText("小偷:\r 好吧,我这就去帮你修好第18层的路面。"); } else if(Count_Num == 3) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 15) //空格键且状态15(和15楼商人对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_red->show(); this->ui->textBrowser->setText("商人:\r 非常好的宝物,只要你出得起500块,我就卖给你。"); } else if(Count_Num == 2 ) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_red->hide(); this->ui->textBrowser->setText("勇士:\r 好的,成交"); } else if(Count_Num == 3) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Update_State(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 14) //空格键且状态14(和15楼老头对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_old->show(); this->ui->textBrowser->setText("神秘老头:\r 我将给你一个非常好的宝物,他可以使你的攻击"); } else if(Count_Num == 2 ) { this->ui->textBrowser->setText("神秘老头:\r 力提升120点,但这必须用你的500点经验来换取。"); } else if(Count_Num == 3 ) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_old->hide(); this->ui->textBrowser->setText("勇士:\r 好吧,那就将那把剑给我吧。"); } else if(Count_Num == 4) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Update_State(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 17) //空格键且状态17(和16楼老头对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_old->hide(); this->ui->textBrowser->setText("勇士:\r ……"); } else if(Count_Num == 2 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_old->show(); this->ui->textBrowser->setText("神秘老头:\r 我已经快封不住他了,请你将这个东西交给彩蝶。"); } else if(Count_Num == 3 ) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_old->hide(); this->ui->textBrowser->setText("勇士:\r 您怎么了?"); } else if(Count_Num == 4 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_old->show(); this->ui->textBrowser->setText("神秘老头:\r 快去吧,再迟就来不及了"); } else if(Count_Num == 5) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 18) //空格键且状态18(和16楼魔王对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_devil16->show(); this->ui->textBrowser->setText("红衣魔王:\r 停止吧!愚蠢的人类!"); } else if(Count_Num == 2 ) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_devil16->hide(); this->ui->textBrowser->setText("勇士:\r 该停止的是你!魔王。快说,公主关在哪里?"); } else if(Count_Num == 3 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_devil16->show(); this->ui->textBrowser->setText("红衣魔王:\r 呵!你先打败我再说吧。"); } else if(Count_Num == 4) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 19) //空格键且状态19(和17楼魔王对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_devil19->show(); this->ui->textBrowser->setText("冥灵魔王:\r 哈哈哈省略号\r 你也真是有意思,别以"); } else if(Count_Num == 2 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_devil19->show(); this->ui->textBrowser->setText("冥灵魔王:\r 为蝶仙给你点力量就能打败我,你还早着呢!"); } else if(Count_Num == 3) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 20) //空格键且状态20(和公主对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_princess->show(); this->ui->textBrowser->setText("公主:\r 啊,你是来救我得嘛?"); } else if(Count_Num == 2 ) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_princess->hide(); this->ui->textBrowser->setText("勇士:\r 是的,我现在就带你离开。"); } else if(Count_Num == 3 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_princess->show(); this->ui->textBrowser->setText("公主:\r 不,我还不想走。"); } else if(Count_Num == 4 ) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_princess->hide(); this->ui->textBrowser->setText("勇士:\r 请你快随我出去吧!"); } else if(Count_Num == 5 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_princess->show(); this->ui->textBrowser->setText("公主:\r 我不要就这样走,我要看着那个恶魔被杀死!"); } else if(Count_Num == 6 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_princess->show(); this->ui->textBrowser->setText("公主:\r 等你杀了那个恶魔我就和你一起出去!"); } else if(Count_Num == 7 ) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_princess->hide(); this->ui->textBrowser->setText("勇士:\r 大恶魔?我已经杀死了一个魔王。"); } else if(Count_Num == 8 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_princess->show(); this->ui->textBrowser->setText("公主:\r 你杀死的是一个小头目,真正的魔王非常厉害,请你一定要杀死他。"); } else if(Count_Num == 9 ) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_princess->hide(); this->ui->textBrowser->setText("勇士:\r 好,那你等我好消息!"); } else if(Count_Num == 10) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 21) //空格键且状态21(和16楼魔王死后对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_devil16->show(); this->ui->textBrowser->setText("红衣魔王:\r 你等着,我的老大会给我报仇的"); } else if(Count_Num == 2 ) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_devil16->show(); this->ui->textBrowser->setText("红衣魔王:\r 公主正在被嘿嘿嘿呢,哈哈哈哈!"); } else if(Count_Num == 3) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 22) //空格键且状态22(和19楼魔王死后对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_devil19->show(); this->ui->textBrowser->setText("冥灵魔王:\r 在那里,你就可以见识到我的真正实力了!"); } else if(Count_Num == 2) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 23) //空格键且状态23(和21楼魔王死后对话) { Count_Num ++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_devil19->show(); this->ui->textBrowser->setText("冥灵魔王:\r 会被你打败呢!\r 不,不要这样……"); } else if(Count_Num == 2) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 24) //空格键且状态24(和22楼仙女对话) { Count_Num++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙子:\r 给杀了,快去找另外的两根“灵杖”吧,找齐了以后"); } else if(Count_Num == 2) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 把他们一起交给我,我帮你解开最后的封印!"); } else if(Count_Num == 3) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 记住,如果不把封印解开的话,最底层的怪物你永远打不过!"); } else if(Count_Num == 4) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Update_State(); emit Exit(); this->close(); } } else if(event->key() == Qt::Key_Space && Braver.Dialog_state_num == 25) //空格键且状态25(找到灵杖后和22楼仙女对话) { Count_Num++; if(Count_Num == 1) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙子:\r 嗯,不错,现在我们可以解除这里面的封印了"); } else if(Count_Num == 2) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 那我们开始吧!玛尼玛尼哄!"); } else if(Count_Num == 3) { this->ui->graphicsView_braver->show(); this->ui->graphicsView_fairy->hide(); this->ui->textBrowser->setText("勇士:\r ……"); } else if(Count_Num == 4) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r ……\r 好了,我已经将他们三个力量注入了,但你要记住:"); } else if(Count_Num == 5) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 没有足够的实力之前,千万不要进入那个花形门。"); } else if(Count_Num == 6) { this->ui->graphicsView_braver->hide(); this->ui->graphicsView_fairy->show(); this->ui->textBrowser->setText("仙女:\r 一旦你进入那个花形门,你就再也回不来了!"); } else if(Count_Num == 7) { Count_Num = 0; space_timer->stop(); Hide_Window(); emit Update_State(); emit Exit(); this->close(); } } } DialogWindow::~DialogWindow() { delete ui; }
true
efac9fd76a1a73f50423e41d271fd39ad30f21ae
C++
WhiZTiM/coliru
/Archive2/2d/485ad0d852eb2d/main.cpp
UTF-8
3,970
3.515625
4
[]
no_license
#include <iostream> #include <string> #include <memory> #include <stdexcept> struct person : std::enable_shared_from_this<person> { virtual ~person() = default ; virtual std::string name() const { return "'" + name_ + "'" ; } protected: person() = default; explicit person ( const std::string& name ) : name_(name) {} private: std::string name_ ; // non-copyable and non-moveable; always acces via references or (smart) pointers person( const person& ) = delete ; person& operator= ( const person& ) = delete ; }; struct person_proxy : person { static std::shared_ptr<person_proxy> make( const std::shared_ptr<person>& p ) { return std::shared_ptr<person_proxy>( new person_proxy(p) ); } std::shared_ptr<person_proxy> rebind( const std::shared_ptr<person>& p ) { show( std::cout << "before rebind: " << this << " => " ); // test if( is_cyclic(p) ) throw std::logic_error( "cyclic; can't be proxy for itself" ) ; actual = p; show( std::cout << "after rebind: " << this << " => " ) ; // test return std::dynamic_pointer_cast<person_proxy>( shared_from_this() ) ; } virtual std::string name() const override { return actual->name(); } private: std::shared_ptr<person> actual; explicit person_proxy( const std::shared_ptr<person>& p ) : actual( p ) {} void show( std::ostream& stm ) { #ifndef NDEBUG stm << actual.get() ; auto p = std::dynamic_pointer_cast<person_proxy>(actual) ; if(p) p->show( stm << " => " ) ; else stm << '\n' ; #endif // NDEBUG } bool is_cyclic( const std::shared_ptr<person>& p ) const { auto pp = std::dynamic_pointer_cast<person_proxy>(p) ; if( pp && ( pp.get() == this ) ) return true ; else return pp ? is_cyclic( pp->actual ) : false ; } }; struct girl : person { static std::shared_ptr<person_proxy> make( const std::string& name ) { return person_proxy::make( std::shared_ptr<girl>( new girl(name) ) ) ; } ~girl() { std::cout << "girl::destructor: " << girl::name() << ' ' << this << '\n' ; } private: girl( const std::string& name ) : person( name ) { std::cout << "girl::constructor: " << girl::name() << ' ' << this << '\n' ; } girl( const char* name ) : person( name ) { std::cout << "girl::constructor: " << girl::name() << ' ' << this << '\n' ; } }; struct catman : person { static std::shared_ptr<person_proxy> make( const std::string& name ) { return person_proxy::make( std::shared_ptr<catman>( new catman(name) ) ) ; } ~catman() { std::cout << "catman::destructor: " << catman::name() << ' ' << this << '\n' ; } private: catman( const std::string& name ) : person( name ) { std::cout << "catman::constructor: " << catman::name() << ' ' << this << '\n' ; } catman( const char* name ) : person( name ) { std::cout << "catman::constructor: " << catman::name() << ' ' << this << '\n' ; } }; int main() { auto a = girl::make( "alice" ); std::cout << "+++ " << a->name() << " +++\n\n" ; auto b = catman::make( "the cheshire catman" ); a->rebind(b) ; std::cout << "+++ " << a->name() << " +++\n\n" ; auto c = girl::make( "the queen of hearts" ); auto d = a->rebind(c) ; std::cout << "+++ " << a->name() << " +++\n\n" ; try { d->rebind(a) ; } catch( const std::exception& e ) { std::cerr << "***** error: " << e.what() << '\n' ; } auto a1 = a ; try { c->rebind(a1) ; } catch( const std::exception& e ) { std::cerr << "***** error: " << e.what() << '\n' ; } std::cout << "+++ " << a->name() << " +++\n\n" ; }
true
c98c2cea8bfec176629bf2ce0107c78b699af0fe
C++
HesslerY/exafmm-t
/tests/p2p_helmholtz.cpp
UTF-8
2,910
2.5625
3
[ "BSD-3-Clause" ]
permissive
#include <algorithm> #include <random> #include <type_traits> #include "exafmm_t.h" #include "helmholtz.h" #include "timer.h" using namespace exafmm_t; void helmholtz_kernel(RealVec& src_coord, ComplexVec& src_value, RealVec& trg_coord, ComplexVec& trg_value, complex_t wavek) { complex_t I = std::complex<real_t>(0., 1.); int nsrcs = src_coord.size() / 3; int ntrgs = trg_coord.size() / 3; for (int i=0; i<ntrgs; ++i) { complex_t potential = 0; cvec3 gradient = complex_t(0,0); for (int j=0; j<nsrcs; ++j) { vec3 dx; for (int d=0; d<3; ++d) { dx[d] = trg_coord[3*i+d] - src_coord[3*j+d]; } real_t r2 = norm(dx); if (r2!=0) { real_t r = std::sqrt(r2); complex_t potential_ij = std::exp(I * wavek * r) * src_value[j] / r; potential += potential_ij; for (int d=0; d<3; ++d) { gradient[d] += (wavek*I/r - 1/r2) * potential_ij * dx[d]; } } } trg_value[4*i] += potential / (4*PI); trg_value[4*i+1] += gradient[0] / (4*PI); trg_value[4*i+2] += gradient[1] / (4*PI); trg_value[4*i+3] += gradient[2] / (4*PI); } } int main(int argc, char **argv) { Args args(argc, argv); int n_max = 20001; int n = std::min(args.numBodies, n_max); HelmholtzFmm fmm; fmm.wavek = complex_t(5.,10.); // initialize sources and targets print("numBodies", n); RealVec src_coord(3*n); RealVec trg_coord(3*n); ComplexVec src_value(n); ComplexVec trg_value(4*n, 0); ComplexVec trg_value_simd(4*n, 0); std::random_device rd; std::mt19937 engine(rd()); std::uniform_real_distribution<real_t> dist(-1.0, 1.0); auto gen = [&dist, &engine]() { return dist(engine); }; std::generate(src_coord.begin(), src_coord.end(), gen); std::generate(trg_coord.begin(), trg_coord.end(), gen); std::generate(src_value.begin(), src_value.end(), [&gen]() { return complex_t(gen(), gen()); }); // direct summation start("non-SIMD P2P"); helmholtz_kernel(src_coord, src_value, trg_coord, trg_value, fmm.wavek); stop("non-SIMD P2P"); start("SIMD P2P Time"); fmm.gradient_P2P(src_coord, src_value, trg_coord, trg_value_simd); stop("SIMD P2P Time"); // calculate error double p_diff = 0, p_norm = 0; double g_diff = 0, g_norm = 0; for (int i=0; i<n; ++i) { p_norm += std::norm(trg_value[4*i]); p_diff += std::norm(trg_value[4*i]-trg_value_simd[4*i]); for (int d=1; d<4; ++d) { g_norm += std::norm(trg_value[4*i+d]); g_diff += std::norm(trg_value[4*i+d]-trg_value_simd[4*i+d]); } } double p_err = sqrt(p_diff/p_norm); double g_err = sqrt(g_diff/g_norm); print("Potential Error", p_err); print("Gradient Error", g_err); double threshold = std::is_same<float, real_t>::value ? 1e-6 : 1e-12; assert(p_err < threshold); assert(g_err < threshold); return 0; }
true
38a9325f2de9ee4263456de78a7d54de5b57335f
C++
chriskarlsson/1DV433
/1DV433.S5.L13_BlackJack/11DV433.S5.L13_BlackJack/Blackjack.cpp
UTF-8
26,169
3.125
3
[ "MIT" ]
permissive
//----------------------------------------------------------------------- // File: Blackjack.cpp // Summary: Blackjack game // Version: 1.1 // Owner: Christoffer Karlsson //----------------------------------------------------------------------- // Log: 2017-12-30 File created by Christoffer. Initial version only // available for Windows. // 2018-01-07 Version 1.1. Bug fix. //----------------------------------------------------------------------- // Preprocessor directives #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #include <iostream> #include <iomanip> #include <cstring> #include <Windows.h> #include "Blackjack.h" using namespace std; const int NUMBER_OF_CARDS_IN_DECK = 52; const int BLACKJACK = 21; //----------------------------------------------------------------- // void blackjack() // // Summary: A game of blackjack // Returns: - //----------------------------------------------------------------- void blackjack() { // Enable memory leak flags _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); do { int numberOfPlayers; Player *players = nullptr; int markersPerPlayer; int numberOfCards; int *cards = nullptr; int *dealerCards = nullptr;; int numberOfDealerCards = 0; // Setup all needed input setup(players, numberOfPlayers, markersPerPlayer, cards, numberOfCards); // Play while there are still players and those want to ccontinue playing do { placeBets(players, numberOfPlayers); dealCards(players, numberOfPlayers, dealerCards, numberOfDealerCards, cards, numberOfCards); play(players, numberOfPlayers, dealerCards, numberOfDealerCards, cards, numberOfCards); } while (numberOfPlayers > 0 && userYesOrNo("One more round?")); // Explain why the game ended if (numberOfPlayers == 0) { cout << "All players were eliminated." << endl; } // Cleanup delete[] cards; delete[] dealerCards; delete[] players; } while (userYesOrNo("One more game?")); } //----------------------------------------------------------------- // void setup(Player *&players, int &numberOfPlayers, int &markersPerPlayer, int *&cards, int &numberOfCards) // // Summary: Prepare the players and deck needed to play // Returns: - //----------------------------------------------------------------- void setup(Player *&players, int &numberOfPlayers, int &markersPerPlayer, int *&cards, int &numberOfCards) { numberOfPlayers = getIntegerFromUser("How many players?"); markersPerPlayer = getIntegerFromUser("How many markers per player?"); // Create players and give the their markers setupPlayers(players, numberOfPlayers, markersPerPlayer); // Setup the deck that is to be used unsigned int numberOfDecks = getIntegerFromUser("How many decks are to be used?"); numberOfCards = numberOfDecks * NUMBER_OF_CARDS_IN_DECK; getShuffledDeck(cards, numberOfCards); } //----------------------------------------------------------------- // unsigned int getIntegerFromUser(const char *question) // // Summary: Poses a question to the user and returns the answer as an integer // Returns: A positive integer //----------------------------------------------------------------- unsigned int getIntegerFromUser(const char *question) { unsigned int value; while (true) { // Pose question and read answer cout << question << ": "; cin >> value; if (cin.fail()) { // Explain what went wrong cout << "Invalid input. Please enter a positive integer." << endl; // Clear error cin.clear(); // Clear input (this has to be done after error clearing) cin.ignore(MAX_READ_INPUT_LENGTH, '\n'); } else { // Clear input cin.ignore(MAX_READ_INPUT_LENGTH, '\n'); return value; } } } //----------------------------------------------------------------- // void setupPlayers(Player *&players, int numberOfPlayers, int markersPerPlayer) // // Summary: Creates players and assigns markers and identifying number // Returns: - //----------------------------------------------------------------- void setupPlayers(Player *&players, int numberOfPlayers, int markersPerPlayer) { try { players = new Player[numberOfPlayers]; } catch (bad_alloc) { // Explain the issue and the terminate with error code 1 cout << "Failed to allocate memory. Exiting ..." << endl; exit(1); } // Assign markers and id to each player for (int i = 0; i < numberOfPlayers; i++) { players[i].id = i + 1; players[i].markers = markersPerPlayer; } } //----------------------------------------------------------------- // void getShuffledDeck(int *&cards, int &numberOfCards) // // Summary: Populates the deck and allows the user to shuffle it // Returns: - //----------------------------------------------------------------- void getShuffledDeck(int *&cards, int &numberOfCards) { try { cards = new int[numberOfCards]; } catch (bad_alloc) { // Explain the issue and the terminate with error code 1 cout << "Failed to allocate memory. Exiting ..." << endl; exit(1); } // Assign values to each card for (int i = 0; i < numberOfCards; i++) { cards[i] = i + 1; } // Allow the user to choose how many times the deck should be shuffled do { cout << "Shuffling ..." << endl; shuffleDeck(cards, numberOfCards); } while (userYesOrNo("Shuffle one more time?")); } //----------------------------------------------------------------- // void shuffleDeck(int *&cards, int &numberOfCards) // // Summary: Emulates shuffling of the deck // Returns: - //----------------------------------------------------------------- void shuffleDeck(int *&cards, int &numberOfCards) { // Seed random number generator srand(time(NULL)); // Split deck somewhere in the two middle quartiles int firstPartSize = numberOfCards / 4 + rand() % (numberOfCards / 2); int secondPartSize = numberOfCards - firstPartSize; // Create two arrays to hold the cards while shuffling int *firstDeckPart; int *secondDeckPart; try { firstDeckPart = new int[firstPartSize]; secondDeckPart = new int[secondPartSize]; } catch (bad_alloc) { // Explain the issue and the terminate with error code 1 cout << "Failed to allocate memory. Exiting ..." << endl; exit(1); } // Put first half of deck in first array int i; for (i = 0; i < firstPartSize; i++) { firstDeckPart[i] = cards[i]; } // Put second half of deck in second array for (int j = 0; j < secondPartSize; i++, j++) { secondDeckPart[j] = cards[i]; } // Shuffle for (int deckIndex = 0, partOneIndex = 0, partTwoIndex = 0; deckIndex < numberOfCards; deckIndex++) { // Get a random 0 or 1 bool random = rand() % 2 - 1; // If random is 1, use card from 1 array if possible if ((random && partOneIndex < firstPartSize) || partTwoIndex >= secondPartSize) { cards[deckIndex] = firstDeckPart[partOneIndex++]; } else { cards[deckIndex] = secondDeckPart[partTwoIndex++]; } } // Cleanup delete[] firstDeckPart; delete[] secondDeckPart; } //----------------------------------------------------------------- // bool userYesOrNo(char *question) // // Summary: Asks the user the supplied question. // Returns: True if the answer isn't n or N. //----------------------------------------------------------------- bool userYesOrNo(const char *question) { char input[MAX_READ_INPUT_LENGTH]; // Ask the user if program should re-run and read input cout << endl << question << " (Y/n): "; cin.getline(input, MAX_READ_INPUT_LENGTH); cout << endl; // Check if answer is negative auto answer = toupper(input[0]) != 'N'; return answer; } //----------------------------------------------------------------- // void placeBets(Player *&players, int numberOfPlayers) // // Summary: Asks each user how much to bet // Returns: - //----------------------------------------------------------------- void placeBets(Player *&players, int numberOfPlayers) { for (int i = 0; i < numberOfPlayers; i++) { placeBet(players[i]); } } //----------------------------------------------------------------- // void placeBet(Player &player) // // Summary: Asks user how much to bet // Returns: - //----------------------------------------------------------------- void placeBet(Player &player) { while (true) { // Ask user how much to bet cout << "Player " << player.id << endl; int bet = getIntegerFromUser("How much markers to bet?"); // Make sure user has enough markers if (bet > player.markers) { cout << "Player only has " << player.markers << endl; } else { // Move markers from markers to bet player.bet = bet; player.markers -= bet; return; } } } //----------------------------------------------------------------- // void dealCards(Player *&players, int &numberOfPlayers, int *&dealerCards, int &numberOfDealerCards, int *&cards, int &numberOfCards) // // Summary: Deal players and dealer 2 cards each // Returns: - //----------------------------------------------------------------- void dealCards(Player *&players, int &numberOfPlayers, int *&dealerCards, int &numberOfDealerCards, int *&cards, int &numberOfCards) { const int NUMBER_OF_CARDS = 2; for (int i = 0; i < NUMBER_OF_CARDS; i++) { // Deal one card to each player for (int j = 0; j < numberOfPlayers; j++) { dealCard(players[j].cards, players[j].numberOfCards, cards, numberOfCards); } // Deal one card to the dealer dealCard(dealerCards, numberOfDealerCards, cards, numberOfCards); } } //----------------------------------------------------------------- // void dealCard(int *&receiverCards, int &numberOfReceiverCards, int *&cards, int &numberOfCards) // // Summary: Takes a card from the top of the deck and gives it to the receiver // Returns: - //----------------------------------------------------------------- void dealCard(int *&receiverCards, int &numberOfReceiverCards, int *&cards, int &numberOfCards) { // Make sure that there are cards in the deck if (numberOfCards <= 0) { cout << "Dealer is out of cards. Adding new deck ..." << endl; delete[] cards; numberOfCards = NUMBER_OF_CARDS_IN_DECK; getShuffledDeck(cards, numberOfCards); } // Take card from top of deck int card = pop(cards, numberOfCards); // Give it to the receiver push(card, receiverCards, numberOfReceiverCards); } //----------------------------------------------------------------- // void push(int card, int *&cards, int &numberOfCards) // // Summary: Place the card at the beginning of the array // Returns: - //----------------------------------------------------------------- void push(int card, int *&cards, int &numberOfCards) { // Create temp variables int *newArray; const int NEW_SIZE = numberOfCards + 1; try { // Allocate memory newArray = new int[NEW_SIZE]; } catch (bad_alloc) { // Explain the issue and the terminate with error code 1 cout << "Failed to allocate memory. Exiting ..." << endl; exit(1); } // Place the card first newArray[0] = card; // Copy all values from the old array to the new array for (int i = 0; i < numberOfCards; i++) { newArray[i + 1] = cards[i]; } // Cleanup old array if (cards != nullptr) { delete[] cards; } // Point old to the temp values cards = newArray; numberOfCards = NEW_SIZE; } //----------------------------------------------------------------- // int pop(int *&cards, int &numberOfCards) // // Summary: Removes the first card from the array // Returns: The card as an integer //----------------------------------------------------------------- int pop(int *&cards, int &numberOfCards) { // Create temp variables int *newArray; const int NEW_SIZE = numberOfCards - 1; if (NEW_SIZE > 0) { try { // Allocate memory newArray = new int[NEW_SIZE]; } catch (bad_alloc) { // Explain the issue and the terminate with error code 1 cout << "Failed to allocate memory. Exiting ..." << endl; exit(1); } // Copy all values from the old array to the new array for (int i = 0; i < NEW_SIZE; i++) { newArray[i] = cards[i + 1]; } } else { newArray = nullptr; } // Take the first card const int POPPED = cards[0]; // Cleanup delete[] cards; // Point old to the temp values cards = newArray; numberOfCards = NEW_SIZE; return POPPED; } //----------------------------------------------------------------- // void play(Player *&players, int &numberOfPlayers, int *&dealerCards, int &numberOfDealerCards, int *&cards, int &numberOfCards) // // Summary: The game play // Returns: - //----------------------------------------------------------------- void play(Player *&players, int &numberOfPlayers, int *&dealerCards, int &numberOfDealerCards, int *&cards, int &numberOfCards) { // Let all players choose how many cards to take for (int i = 0; i < numberOfPlayers; i++) { printTable(players, numberOfPlayers, dealerCards, numberOfDealerCards, i); while (bestValue(players[i].cards, players[i].numberOfCards) < BLACKJACK && userYesOrNo("Hit?")) { dealCard(players[i].cards, players[i].numberOfCards, cards, numberOfCards); printTable(players, numberOfPlayers, dealerCards, numberOfDealerCards, i); } } // Deal cards to dealer until at least 17 int dealerScore = bestValue(dealerCards, numberOfDealerCards); const int DEALER_STOP_SCORE = 17; while (dealerScore < DEALER_STOP_SCORE) { dealCard(dealerCards, numberOfDealerCards, cards, numberOfCards); dealerScore = bestValue(dealerCards, numberOfDealerCards); } // Calculate how much each player win for (int i = 0; i < numberOfPlayers; i++) { players[i].win = calculateWin(players[i].cards, players[i].numberOfCards, players[i].bet, dealerScore, numberOfDealerCards); players[i].markers += players[i].win; } // Print the table with the round score printTable(players, numberOfPlayers, dealerCards, numberOfDealerCards, -1, false, true); // Cleanup delete[] dealerCards; dealerCards = nullptr; numberOfDealerCards = 0; // Delete player if out of markers and otherwise prepare it for next round int i = 0; while (i < numberOfPlayers) { if (players[i].markers == 0) { cout << endl << "Player " << players[i].id << " was eliminated." << endl; deletePlayer(players, numberOfPlayers, i); } else { players[i].prepareNewRound(); i++; } } } //----------------------------------------------------------------- // int calculateWin(int *cards, int numberOfCards, int bet, int dealerScore, int numberOfDealerCards) // // Summary: Calculates if and how much the player win // Returns: Win as integer //----------------------------------------------------------------- int calculateWin(int *cards, int numberOfCards, int bet, int dealerScore, int numberOfDealerCards) { int const DRAW_LIMIT = 20; int const PLAYER_SCORE = bestValue(cards, numberOfCards); // Calculate win if (PLAYER_SCORE <= BLACKJACK) { if (dealerScore < PLAYER_SCORE || dealerScore > BLACKJACK) { if (PLAYER_SCORE == BLACKJACK && numberOfCards == 2) { return bet * 1.5; // Blackjack } else { return bet * 2; // Player beat dealer } } else if (dealerScore == PLAYER_SCORE) { if (dealerScore < DRAW_LIMIT) { return 0; // Dealer wins draw lower than 20 } else if (dealerScore == BLACKJACK && numberOfDealerCards > 2 && numberOfCards == 2) { return 1.5 * bet; // Player blackjack beats dealer 21 } else { return bet; // Draw yields the money back } } else { return 0; // Dealer beats player } } else { return 0; // Player goes over 21 } } //----------------------------------------------------------------- // void deletePlayer(Player *&players, int &numberOfPlayers, int playerIndex) // // Summary: Deletes player from player array // Returns: - //----------------------------------------------------------------- void deletePlayer(Player *&players, int &numberOfPlayers, int playerIndex) { // Create temp array Player *newPlayers; try { newPlayers = new Player[numberOfPlayers - 1]; } catch (bad_alloc) { // Explain the issue and then terminate with error code 1 cout << "Failed to allocate memory. Exiting ..." << endl; exit(1); } // Copy players to the new array for (int newIndex = 0, oldIndex = 0; oldIndex < numberOfPlayers; oldIndex++) { if (oldIndex != playerIndex) { newPlayers[newIndex] = players[oldIndex]; newIndex++; } } numberOfPlayers--; // Free memory delete[] players; // Point array to the new array players = newPlayers; } //----------------------------------------------------------------- // void printTable(Player *&players, int &numberOfPlayers, int *&dealerCards, int numberOfDealerCards, int activePlayer, bool printOnlyFirstDealerCard, bool printRoundScore) // // Summary: Prints the whole table // Returns: - //----------------------------------------------------------------- void printTable(Player *&players, int &numberOfPlayers, int *&dealerCards, int numberOfDealerCards, int activePlayer, bool printOnlyFirstDealerCard, bool printRoundScore) { // Clear the screen system("cls"); const int COLUMN_WIDTH = 9; const int MIDDLE = COLUMN_WIDTH * numberOfPlayers / 2; const int MAX_CARD_STRING_LENGTH = 4; // Print dealer cards in the middle printDealerCards(dealerCards, numberOfDealerCards, printOnlyFirstDealerCard, MIDDLE, MAX_CARD_STRING_LENGTH); // Print the player cards printPlayerCards(players, numberOfPlayers, activePlayer, COLUMN_WIDTH, MAX_CARD_STRING_LENGTH); // Print the current score if wanted if (printRoundScore) { printScore(players, numberOfPlayers, COLUMN_WIDTH); } } //----------------------------------------------------------------- // void printDealerCards(int *&dealerCards, int numberOfDealerCards, bool printOnlyFirstDealerCard, int middlePosition) // // Summary: Prints the dealer cards // Returns: - //----------------------------------------------------------------- void printDealerCards(int *&dealerCards, int numberOfDealerCards, bool printOnlyFirstDealerCard, const int MIDDLE_POSITION, const int MAX_CARD_STRING_LENGTH) { cout << setw(MIDDLE_POSITION) << "Dealer" << endl; // Print the cards int cardIndex = 0; do { char *card = new char[MAX_CARD_STRING_LENGTH]; getCard(dealerCards[cardIndex++], card, MAX_CARD_STRING_LENGTH); cout << setw(MIDDLE_POSITION) << card << endl; delete[] card; } while (!printOnlyFirstDealerCard && cardIndex < numberOfDealerCards); cout << endl; } //----------------------------------------------------------------- // void printPlayerCards(Player *&players, int &numberOfPlayers, int activePlayer, int columnWidth) // // Summary: Prints the players cards // Returns: - //----------------------------------------------------------------- void printPlayerCards(Player *&players, int &numberOfPlayers, int activePlayer, const int COLUMN_WIDTH, const int MAX_CARD_STRING_LENGTH) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); const int YELLOW = 14; const int WHITE = 15; // Print player identifier const char *PLAYER_STRING = " Player"; const int SPACE_LEFT_FOR_NUMBER = COLUMN_WIDTH - strlen(PLAYER_STRING); for (int i = numberOfPlayers - 1; i >= 0; i--) { cout << PLAYER_STRING << setw(SPACE_LEFT_FOR_NUMBER) << players[i].id; } cout << endl; // Print cards int cardIndex = 0; bool allCardsPrinted; do { allCardsPrinted = true; for (int i = numberOfPlayers - 1; i >= 0; i--) { // Check if there are more cards after the current if (players[i].numberOfCards > (cardIndex + 1)) { allCardsPrinted = false; } // Get the card as a string char output[4]; if (players[i].numberOfCards > cardIndex) { getCard(players[i].cards[cardIndex], output, MAX_CARD_STRING_LENGTH); } else { // No card is an empty string strcpy_s(output, sizeof output, ""); } // Print card if (i == activePlayer) { // Print cards as yellow to inform the user which the current player is SetConsoleTextAttribute(hConsole, YELLOW); cout << setw(COLUMN_WIDTH) << output; SetConsoleTextAttribute(hConsole, WHITE); } else { cout << setw(COLUMN_WIDTH) << output; } } cout << endl; cardIndex++; } while (!allCardsPrinted); cout << endl; } //----------------------------------------------------------------- // void printScore(Player *&players, int numberOfPlayers, int columnWidth) // // Summary: Prints the players score // Returns: - //----------------------------------------------------------------- void printScore(Player *&players, int numberOfPlayers, int columnWidth) { const char *WIN_STRING = " Win:"; const int SPACE_LEFT_FOR_WIN = columnWidth = strlen(WIN_STRING); const char *TOT_STRING = " Tot:"; const int SPACE_LEFT_FOR_TOT = columnWidth = strlen(TOT_STRING); // Print win for (int i = numberOfPlayers - 1; i >= 0; i--) { cout << WIN_STRING << setw(SPACE_LEFT_FOR_WIN) << players[i].win; } cout << endl; // Print markers for (int i = numberOfPlayers - 1; i >= 0; i--) { cout << TOT_STRING << setw(SPACE_LEFT_FOR_TOT) << players[i].markers; } cout << endl; } //----------------------------------------------------------------- // int bestValue(int *&cards, int &numberOfCards) // // Summary: Calculates the best value for a set of cards (closest // to but lower or equal to 21) // Returns: The value as an integer //----------------------------------------------------------------- int bestValue(int *&cards, int &numberOfCards) { int total = 0; int aces = 0; // Calculate the sum and the number of aces for (int i = 0; i < numberOfCards; i++) { int rank = getRank(cards[i]); total += rank; if (rank == 11) { aces++; } } // Convert aces from 11 to 1 if needed while (total > BLACKJACK && aces > 0) { total -= 10; aces--; } return total; } //----------------------------------------------------------------- // int getRank(int card) // // Summary: Calculates the rank (value) for a card // Returns: The value as an integer //----------------------------------------------------------------- int getRank(int card) { int rank = card % 13; if (rank < 1) // King { return 10; } else if (rank < 2) // Ace { return 11; } else if (rank < 11) // 2-10 { return rank; } else // Jack and Queen { return 10; } } //----------------------------------------------------------------- // void getCard(int card, char *outCard) // // Summary: Converts the card integer value to a string. The string // outCard has to be able to hold at least 4 char // Returns: - //----------------------------------------------------------------- void getCard(int card, char *outCard, const int MAX_CARD_STRING_LENGTH) { // Suit switch (card % 4) { case 0: strcpy_s(outCard, MAX_CARD_STRING_LENGTH, "S"); // Spades break; case 1: strcpy_s(outCard, MAX_CARD_STRING_LENGTH, "C"); // Club break; case 2: strcpy_s(outCard, MAX_CARD_STRING_LENGTH, "H"); // Heart break; case 3: strcpy_s(outCard, MAX_CARD_STRING_LENGTH, "D"); // Diamond break; } // Rank const int VALUE = card % 13; switch (VALUE) { case 0: strcat_s(outCard, MAX_CARD_STRING_LENGTH, "K"); break; case 1: strcat_s(outCard, MAX_CARD_STRING_LENGTH, " "); break; case 11: strcat_s(outCard, MAX_CARD_STRING_LENGTH, "J"); break; case 12: strcat_s(outCard, MAX_CARD_STRING_LENGTH, "Q"); break; default: int const MAX_RANK_LENGTH = 3; char temp[MAX_RANK_LENGTH]; _itoa_s(VALUE, temp, MAX_RANK_LENGTH, 10); strcat_s(outCard, MAX_CARD_STRING_LENGTH, temp); break; } }
true
55f314f8589a021cae727a4db3a613f7e304c819
C++
simmon2014/RuiLi
/ansys/Tolerance.cpp
GB18030
4,954
2.609375
3
[]
no_license
// Tolerance.cpp : ʵļ // #include "stdafx.h" #include "Tolerance.h" #include "Psapi.h" #include <tlhelp32.h> // CTolerance CTolerance::CTolerance() { m_PageCount=0; } CTolerance::~CTolerance() { this->RemovePage(); } // CTolerance Ա int CTolerance::Load() { _Application ExcelApp; Workbooks wbsMyBooks; _Workbook wbMyBook; Worksheets wssMysheets; _Worksheet wsMysheet; Range rgMyRge; if (!ExcelApp.CreateDispatch("Excel.Application",NULL)) { AfxMessageBox("Excelʧ!"); exit(1); } ExcelApp.put_Visible(FALSE); //ģļĵ char path[MAX_PATH]; GetSystemDirectory(path,MAX_PATH); CString strPath = path; strPath += "\\"; wbsMyBooks.AttachDispatch(ExcelApp.get_Workbooks(),true); wbMyBook.AttachDispatch(wbsMyBooks.Add(_variant_t(strPath))); //õWorksheets wssMysheets.AttachDispatch(wbMyBook.get_Worksheets(),true); CString str=""; int pageIndex=1; int pageCount=20; pageCount=wssMysheets.get_Count(); this->RemovePage(); while(pageIndex<=pageCount) { ExcelPage * page=new ExcelPage; wsMysheet.AttachDispatch(wssMysheets.get_Item(_variant_t(pageIndex)),true); rgMyRge.AttachDispatch(wsMysheet.get_Cells(),true); str=rgMyRge.get_Item(_variant_t((long)1),_variant_t((long)1)); if(str=="") break; page->strArray.RemoveAll(); page->Name=str; for(int i=1;i<60;i++) { str=rgMyRge.get_Item(_variant_t((long)2),_variant_t((long)i)); if(str=="") {page->cols=i-1;break;} } for(int i=2;i<60;i++) { str=rgMyRge.get_Item(_variant_t((long)i),_variant_t((long)1)); if(str=="") {page->rows=i-2;break;} } for(int i=2;i<=page->rows+1;i++) { for(int j=1;j<=page->cols;j++) { str=rgMyRge.get_Item(_variant_t((long)i),_variant_t((long)j)); page->strArray.Add(str); } } m_PageArray.Add(page); pageIndex++; } m_PageCount=pageIndex-1; wbsMyBooks.Close(); ExcelApp.Quit(); rgMyRge.ReleaseDispatch(); wsMysheet.ReleaseDispatch(); wssMysheets.ReleaseDispatch(); wbMyBook.ReleaseDispatch(); wbsMyBooks.ReleaseDispatch(); ExcelApp.ReleaseDispatch(); this->KillExcel(); return 1; } int CTolerance::RemovePage() { ExcelPage * page; for(int i=0;i<m_PageArray.GetSize();i++) { page=m_PageArray[i]; page->strArray.RemoveAll(); delete page; } m_PageArray.RemoveAll(); return 1; } int CTolerance::GetCols(int PageIndex) { if(PageIndex<=0||PageIndex>m_PageCount) return 0; return m_PageArray[PageIndex]->cols; } int CTolerance::GetRows(int PageIndex) { if(PageIndex<=0||PageIndex>m_PageCount) return 0; return m_PageArray[PageIndex]->rows; } CString CTolerance::GetRowName(int PageIndex,int row) { if(PageIndex<=0||PageIndex>m_PageCount) return ""; int cols=m_PageArray[PageIndex]->cols; int rows=m_PageArray[PageIndex]->rows; if(row<0||row>=rows) return ""; CString str=""; str=m_PageArray[PageIndex]->strArray[row*cols+0]; return str; } CString CTolerance::GetCellString(int PageIndex,int row,int col) { if(PageIndex<=0||PageIndex>m_PageCount) return ""; int cols=m_PageArray[PageIndex]->cols; int rows=m_PageArray[PageIndex]->rows; if(row<0||row>=rows) return ""; if(col<0||col>=cols) return ""; CString str=""; str=m_PageArray[PageIndex]->strArray[row*cols+col]; return str; } int CTolerance::KillExcel() { PROCESSENTRY32 pe32; pe32.dwSize = sizeof(pe32); HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); if(hProcessSnap == INVALID_HANDLE_VALUE) { AfxMessageBox("CreateToolhelp32Snapshotʧ"); return 0; } BOOL bMore = ::Process32First(hProcessSnap,&pe32); CStringArray strArray; CArray<DWORD,DWORD> PIDArray; while(bMore) { strArray.Add(pe32.szExeFile); PIDArray.Add(pe32.th32ProcessID); bMore = ::Process32Next(hProcessSnap,&pe32); } ::CloseHandle(hProcessSnap); DWORD processID,selectID; int status=0; FILETIME ft1,ft2,ft3,ft4; FILETIME oldft; CString str; HANDLE hProcess; for(int i=0;i<PIDArray.GetSize();i++) { str=strArray[i]; if(str.MakeUpper()!="EXCEL.EXE") continue; processID=PIDArray[i]; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,processID); if(GetProcessTimes(hProcess,&ft1,&ft2,&ft3,&ft4)==FALSE) return 0; if(status==0) { status=1; selectID=processID; oldft.dwHighDateTime=ft1.dwHighDateTime; oldft.dwLowDateTime=ft1.dwLowDateTime; }else { int result; result=CompareFileTime(&ft1,&oldft); if(result==1) { selectID=processID; oldft.dwHighDateTime=ft1.dwHighDateTime; oldft.dwLowDateTime=ft1.dwLowDateTime; } } CloseHandle(hProcess); } if(status==0) return 0; hProcess=NULL; hProcess = OpenProcess(PROCESS_TERMINATE,FALSE,selectID); if(hProcess != NULL) { //ֹ TerminateProcess(hProcess,0); ::CloseHandle(hProcess); } return 1; }
true
139be9c0e721a147a91012ddf2641ae324fb507f
C++
Benner727/SquareRPG
/Sandbox/src/Game/World/Map/Cell.h
UTF-8
592
2.84375
3
[ "Apache-2.0" ]
permissive
#pragma once #include "Game/World/Map/Tile.h" #include "Game/World/Map/GroundItem.h" class Cell : public Square::GameObject { private: std::shared_ptr<Tile> mTile; std::vector<std::shared_ptr<GroundItem>> mGroundItems; public: Cell(std::shared_ptr<Tile> tile = nullptr, std::vector<std::shared_ptr<Item>> groundItems = {}); ~Cell() = default; inline std::shared_ptr<Tile> GetTile() const { return mTile; } inline std::vector<std::shared_ptr<GroundItem>>& GetGroundItems() { return mGroundItems; } void AddGroundItem(std::shared_ptr<Item> item); void Update(); void Render(); };
true
f9bdfb77ca379660cb042f1a4bb1e94de5366907
C++
Kose-i/Euclear_Project
/clear_box/Problem039.cpp
UTF-8
661
2.796875
3
[]
no_license
#include <iostream> #include <vector> #include <map> using namespace std; int main() { int n {1000}; map<int, int> mp_square; for (int i=1;i<=n;++i) mp_square[i*i] = i; map<int, int> mp; for (int a=1;a<=n;++a) { for (int b=1;b<=n;++b) { if (n*n < a*a + b*b) break; if (mp_square[a*a + b*b] == 0) continue; if (a + b + mp_square[a*a + b*b] <= n) ++mp[a+b+mp_square[a*a+b*b]]; } } int ans {}; int ans_max {}; for (const auto& e : mp) { if (ans_max < e.second) { ans = e.first; ans_max = e.second; } } cout << ans << '\n'; }
true
025de63d439312bddb31cec082db5cd894e9b599
C++
J0RDYL33/arcade-top-down-shooter
/JC_GameProgramming_Assignment/JC_EnemyList.cpp
UTF-8
1,018
2.796875
3
[]
no_license
#include "JC_EnemyList.h" JC_EnemyList::JC_EnemyList() { SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, "EnemyList constructed with Param(%p)", this); } JC_EnemyList::~JC_EnemyList() { //printf("EnemyList destroyed with Param(%p)", this); } void JC_EnemyList::Init(SDL_Renderer* aRenderer) { //Construct 10 enemies for (int i = 0; i < 10; i++) { JC_Enemy newEnemy; newEnemy.Init(aRenderer); aListOfEnemies.push_back(newEnemy); } } void JC_EnemyList::Update(int px, int py) { if (timeBetweenSpawns > 0) timeBetweenSpawns--; else { timeBetweenSpawns = startTimeBetweenSpawns; aListOfEnemies[currentEnemy].SpawnIn(); currentEnemy++; } if (currentEnemy % aListOfEnemies.size() == 0) currentEnemy = 0; for (int i = 0; i < aListOfEnemies.size(); i++) aListOfEnemies[i].Update(px, py); } void JC_EnemyList::Render(SDL_Renderer* aRenderer) { //Render each of the active bullets for (int i = 0; i < aListOfEnemies.size(); i++) aListOfEnemies[i].Render(aRenderer); }
true
725985fe97fb79770c3a04d85439c60c8166e6af
C++
TheSheepKing/Swords-Scrolls-and-Knuckles
/source/PyEvaluate.cpp
UTF-8
2,536
2.90625
3
[]
no_license
#include <algorithm> #include "PyEvaluate.hpp" PyEvaluate::PyEvaluate(std::vector<Player> &players, std::vector<Enemy> &enemies, Terrain &terrain) : players(players), enemies(enemies), terrain(terrain), attack(false) { } Vect<2u, double> PyEvaluate::closestPlayer(Vect<2u, double> pos) const { auto it (std::min_element(players.begin(), players.end(), [pos](Player const &a, Player const &b) { return ((pos - a.pos).length2() < (pos - b.pos).length2() && (pos - a.pos).length2() != 0); })); return (it == players.end() ? pos : (*it).pos); } Vect<2u, double> PyEvaluate::closestEnemy(Vect<2u, double> pos) const { auto it (std::min_element(enemies.begin(), enemies.end(), [pos](Enemy const &a, Enemy const &b) { return ((pos - a.pos).length2() < (pos - b.pos).length2() && (pos - a.pos).length2() != 0); })); return (it == enemies.end() ? pos : (*it).pos); } Vect<2u, double> PyEvaluate::furtherPlayer(Vect<2u, double> pos) const { auto it (std::max_element(players.begin(), players.end(), [pos](Player const &a, Player const &b) { return ((pos - a.pos).length2() < (pos - b.pos).length2() && (pos - a.pos).length2() != 0); })); return (it == players.end() ? pos : (*it).pos); } Vect<2u, double> PyEvaluate::followRightWall(Vect<2u, double> pos) const { bool walls[9]; bool table[4]; for (int i(0), j(0); j < 3; i++) { walls[i + 3 * j] = terrain.getTile(pos + Vect<2u, double>{static_cast<double>(i - 1), static_cast<double>(j - 1)}).isSolid; if (i == 2) { i = -1; j += 1; } } if ((table[0] = (walls[5] && !walls[7])) || (table[1] = (walls[7] && !walls[3])) || (walls[3] && !walls[1])) { if (table[0]) return (pos + Vect<2u, double>{0.0, 1.0}); else if (table[1]) return (pos + Vect<2u, double>{-1.0, 0.0}); else return (pos + Vect<2u, double>{0.0, -1.0}); } else if ((table[2] = (walls[1] && !walls[5])) || (table[3] = (walls[2] && !walls[5])) || (walls[8] && !walls[7])) { if (table[2]) return (pos + Vect<2u, double>{1.0, 0.0}); else if (table[3]) return (pos + Vect<2u, double>{1.0, 0.0}); else return (pos + Vect<2u, double>{0.0, 1.0}); } else { if (walls[6] && !walls[3]) return (pos + Vect<2u, double>{-1.0, 0.0}); else if (walls[0] && !walls[1]) return (pos + Vect<2u, double>{0.0, -1.0}); else return (pos + Vect<2u, double>{1.0, 0.0}); } }
true
3c715cad744345b92590c4178be8479acd03357e
C++
loangodard/projet-cpp-raytracing
/source/vector3f.cpp
UTF-8
1,815
3.765625
4
[]
no_license
#include "vector3f.h" Vector3f::Vector3f(float x_, float y_, float z_){ x=x_; y=y_; z=z_; } Vector3f::Vector3f(const Vector3f & v){ x=v.get_x(); y=v.get_y(); z=v.get_z(); } float Vector3f::get_x() const{ return x; } float Vector3f::get_y() const{ return y; } float Vector3f::get_z()const { return z; } void Vector3f::print_vector() const { std::cout << '(' << x << ';' << y << ';' << z <<')'<<std::endl; } float operator*(const Vector3f & v1, const Vector3f & v2){ float x_r = v1.get_x()*v2.get_x(); float y_r = v1.get_y()*v2.get_y(); float z_r = v1.get_z()*v2.get_z(); return (x_r+y_r+z_r); } Vector3f operator*(float a, const Vector3f & v2){ return (Vector3f(a*v2.get_x(),a*v2.get_y(),a*v2.get_z())); } Vector3f operator+(const Vector3f & v1, const Vector3f & v2){ return Vector3f(v1.get_x()+v2.get_x(),v1.get_y()+v2.get_y(),v1.get_z()+v2.get_z()); } Vector3f operator-(const Vector3f & v1, const Vector3f & v2){ Vector3f a = v1; Vector3f b = (-1)*v2; return(a+b); } Vector3f operator/(const Vector3f & v2,float a){ if(a == 0) throw("Error, 0 division"); return(v2*(1/a)); } float norme(const Vector3f & v1){ return(sqrt(v1*v1)); } Vector3f vectoriel(const Vector3f & u, const Vector3f & v){ return Vector3f( u.get_y()*v.get_z()-u.get_z()*v.get_y(), u.get_z()*v.get_x()-u.get_x()*v.get_z(), u.get_x()*v.get_y()-u.get_y()*v.get_x() ); } Vector3f get_normalized(const Vector3f & v){ float n = sqrt(v*v); Vector3f r = Vector3f(v.get_x()/n,v.get_y()/n,v.get_z()/n); return r; } // int main(){ // Vector3f width = Vector3f(2,2,0); // Vector3f height = Vector3f(3,2,0); // Vector3f normal = vectoriel(width,height); // Vector3f normalized = get_normalized(normal); // normalized.print_vector(); // std::cout << norme(normalized) << std::endl; // return 0; // }
true
d0f849f3751ecd717cab542994e88a7293a02adc
C++
agerasev/hypertrace
/kernel/ocl/material/test/modifier.cpp
UTF-8
2,786
2.875
3
[ "Apache-2.0", "MIT" ]
permissive
#ifdef UNITTEST #include "../transparent.hh" struct ColoredTransparent { // Transparent inner; color3 color; }; __global const Transparent *colored_transparent__inner__gc(__global const ColoredTransparent *self) { return NULL; } #define $Self ColoredTransparent #define $self colored_transparent #define $Material Transparent #define $material transparent #include "../colored.inl" #undef $Self #undef $self #undef $Material #undef $material struct EmissiveTransparent { // Transparent inner; color3 emission; }; __global const Transparent *emissive_transparent__inner__gc(__global const EmissiveTransparent *self) { return NULL; } #define $Self EmissiveTransparent #define $self emissive_transparent #define $Material Transparent #define $material transparent #include "../emissive.inl" #undef $Self #undef $self #undef $Material #undef $material #include <gtest/gtest.h> class ModifierTest : public testing::Test { protected: TestRng<real3> vrng = TestRng<real3>(0xDCAB); TestRng<color3> colrng = TestRng<color3>(0xDCBA); }; TEST_F(ModifierTest, colored) { Context ctx; for (int i = 0; i < TEST_ATTEMPTS; ++i) { real3 normal = vrng.unit(); real3 dir = vrng.unit(); color3 color = colrng.uniform(); if (dot(normal, dir) > 0.0) { dir = -dir; } LightLocal light { LightBase { color, false }, dir }; float3 emission(0.0f); ColoredTransparent material; material.color = colrng.uniform(); bool b = colored_transparent_interact(&material, &ctx, normal, &light, &emission); ASSERT_TRUE(b); ASSERT_EQ(emission, approx(float3(0.0f))); ASSERT_EQ(light.direction, approx(dir)); ASSERT_EQ(light.base.intensity, approx(color * material.color)); } } TEST_F(ModifierTest, emissive) { Context ctx; for (int i = 0; i < TEST_ATTEMPTS; ++i) { real3 normal = vrng.unit(); real3 dir = vrng.unit(); color3 color = colrng.uniform(); color3 base = colrng.uniform(); if (dot(normal, dir) > 0.0) { dir = -dir; } LightLocal light { LightBase { color, false }, dir }; float3 emission = base; EmissiveTransparent material; material.emission = colrng.uniform(); bool b = emissive_transparent_interact(&material, &ctx, normal, &light, &emission); ASSERT_TRUE(b); ASSERT_EQ(emission, approx(base + color * material.emission)); ASSERT_EQ(light.direction, approx(dir)); ASSERT_EQ(light.base.intensity, approx(color)); } } #endif // UNITTEST
true
893af8a7426e2f111e58bb2668a064b6cdf5c377
C++
wendybalaja/Syntax-Error-Recovery
/parse.cpp
UTF-8
20,634
2.71875
3
[]
no_license
#include <iostream> #include <cstdlib> #include <iterator> #include <string> #include "scan.h" #include <set> #include <map> #include <list> using namespace std; /* Dictionary: SL - stmt_list S -stmt */ /* construct treeNode struct to build AST tree */ class treeNode{ public: string value; list<treeNode> nodes; treeNode(string v, list<treeNode> n){ value = v; nodes = n; } }; const string names[] = {"read", "write", "id", "literal", "gets", "add", "sub", "mul", "div", "lparen", "rparen", "eof","if","while", "end","eqeq","neq","gt","st","gtq","stq"}; static token input_token; static bool isError; static map<string,set<token> > first; static map<string,set<token> > follow; static set<string> eps; static list<treeNode> emptyL; static treeNode * root = new treeNode("program",emptyL); static treeNode * emptyN = new treeNode("",emptyL); static bool isValidProgram = true; void generate_eps(){ eps = {"SL","TT","FT"}; } void generate_first(); void generate_follow(); void program (); treeNode* stmt_list (treeNode* input_node); treeNode* stmt (); treeNode* expr (); treeNode* cond(); treeNode* term_tail (treeNode* input_node); treeNode* term (); treeNode* factor_tail (treeNode* input_node); treeNode* factor (); treeNode* add_op (); treeNode* mul_op (); treeNode* rela_op(); string match(token expected); void error_recovery(string str); void generate_first(){ first.insert(pair<string, set<token>>("P", {t_id, t_read, t_write, t_if, t_while, t_eof})); first.insert(pair<string, set<token>>("SL", {t_id, t_read, t_write, t_if, t_while})); first.insert(pair<string, set<token>>("S", {t_id, t_read, t_write, t_if, t_while})); first.insert(pair<string, set<token>>("C", {t_lparen, t_id, t_literal})); first.insert(pair<string, set<token>>("E", {t_lparen, t_id, t_literal})); first.insert(pair<string, set<token>>("T", {t_lparen, t_id, t_literal})); first.insert(pair<string, set<token>>("F", {t_lparen, t_id, t_literal})); first.insert(pair<string, set<token>>("TT", {t_add, t_sub})); first.insert(pair<string, set<token>>("FT", {t_mul, t_div})); first.insert(pair<string, set<token>>("ro", {t_eqeq, t_neq, t_gt, t_st, t_gtq, t_stq})); first.insert(pair<string, set<token>>("ao", {t_add, t_sub})); first.insert(pair<string, set<token>>("mo", {t_mul, t_div})); } void generate_follow(){ follow.insert(pair<string, set<token>>("P", {})); follow.insert(pair<string, set<token>>("SL", {t_end, t_eof})); follow.insert(pair<string, set<token>>("S", {t_id, t_read, t_write, t_if, t_while, t_eof, t_end})); follow.insert(pair<string, set<token>>("C", {t_id, t_read, t_write, t_if, t_while, t_end})); follow.insert(pair<string, set<token>>("E", {t_id, t_read, t_write, t_if, t_while, t_eof, t_eqeq, t_neq, t_gt, t_st, t_gtq, t_stq, t_end, t_rparen})); follow.insert(pair<string, set<token>>("T", {t_add, t_sub, t_id, t_read, t_write, t_if, t_while, t_eof, t_eqeq, t_neq, t_gt, t_st, t_gtq, t_stq, t_end, t_rparen})); follow.insert(pair<string, set<token>>("F", {t_mul, t_div, t_add, t_sub, t_id, t_read, t_write, t_if, t_while, t_eof, t_eqeq, t_neq, t_gt, t_st, t_gtq, t_stq, t_end, t_rparen})); follow.insert(pair<string, set<token>>("TT", {t_id, t_read, t_write, t_if, t_while, t_eof, t_eqeq, t_neq, t_gt, t_st, t_gtq, t_stq, t_end, t_rparen})); follow.insert(pair<string, set<token>>("FT", {t_add, t_sub, t_id, t_read, t_write, t_if, t_while, t_eof, t_eqeq, t_neq, t_gt, t_st, t_gtq, t_stq, t_end, t_rparen})); follow.insert(pair<string, set<token>>("ro", {t_id, t_literal, t_lparen})); follow.insert(pair<string, set<token>>("ao", {t_id, t_literal, t_lparen})); follow.insert(pair<string, set<token>>("mo", {t_id, t_literal, t_lparen})); }; /* //Functions to help print the syntax trees including preIndent, postIndent, and prefix string postIndent(string str, int tab){ for(int i = 0; i <= tab; i++){ str += " "; } return str; } string preIndent(string str, int tab){ for(int i = 0; i <= tab; i++){ str = " " + str; } return str; } string prefix(string str, string tail){ if(tail == "") return str; for (int i = 0; i < tail.length(); ++i){ if(tail[i] == ' '){ return tail.substr(0,i)+" "+ str +" "+ tail.substr(i+1, tail.length() - i); } } return "prefix error"; } //check if t is in the set[] int contains(token t, token set[]){ int i = 0; while(set[i]){ if (t == set[i++]) { return 1; } } return 0; } */ void error (string statement) { cout << "found in follow sets, keep excuting, i.e.inserted nonterminal " +statement << "\n"; // cout << "Error detected: "<< names[input_token] << "\n"; return; } string match (token expected) { if (input_token == expected) { cout << "matched " << names[input_token] << "\n"; //treeNode node = new treeNode(value, nodes); string value = ""; if (input_token == t_id){ value.append("id "); value.append("\""); value.append(token_image); value.append("\""); }else if(input_token == t_literal){ value.append("num "); value.append("\""); value.append(token_image); value.append( "\""); } else{ //value.append(names[input_token]); value.append(token_image); } value = " "+value; input_token = scan(); return value; }else if(input_token == t_eof){ return ""; } else{ cout << "token not matched. \n"; throw "match error"; }; } void program () { error_recovery("P"); switch (input_token) { case t_id: case t_read: case t_write: case t_if: case t_while: case t_eof:{ if(isError){ cout << "deleted tokens found matching token in P \n"; } cout << "predict program --> stmt_list eof\n"; list<treeNode> list; treeNode * node = new treeNode("8u",list); root->nodes.push_back((*stmt_list(node))); //stmt_list (); treeNode endNode = * new treeNode(match(t_eof),emptyL); //root->nodes.push_back(endNode); //match (t_eof); break; } // MEIWEN: adding if and while conditions default: error ("P"); } } /* tree printing function */ string printTree (treeNode * root){ if((root->nodes).empty()){ return "(" + root->value + ")"; } string str=""; if(root->value.compare( "8u")!=0){ str = "(" + root->value; } else{ str = "["; } for(treeNode child : root-> nodes){ str = str + printTree(&child); } if(root->value.compare( "8u")!=0){ str = str + ")"; }else{ str = str + "]"; } return str; } treeNode* stmt_list (treeNode* input_node) { error_recovery("SL"); switch (input_token) { case t_id: case t_read: case t_if: case t_while: case t_write:{ cout << "predict stmt_list --> stmt stmt_list\n"; input_node->nodes.push_back((*stmt())); //(*stmt_list(input_node))); //stmt (); //stmt_list (); //break; return stmt_list(input_node); } case t_end: case t_eof: cout << "predict stmt_list --> epsilon\n"; return input_node; /* epsilon production */ default: { error ("SL"); return input_node; } } } treeNode* stmt () { error_recovery("S"); switch (input_token) { case t_id:{ if(isError){ cout << "deleted tokens found matching token in S \n"; } cout << "predict stmt --> id gets expr\n"; treeNode * idNode = new treeNode(match(t_id),emptyL); treeNode * getsNode = new treeNode(match(t_gets),emptyL); // treeNode * node = new treeNode("",emptyL); getsNode->nodes.push_front(*idNode); getsNode->nodes.push_back(*expr()); //match (t_id); //match (t_gets); //expr (); return getsNode; } case t_read:{ if(isError){ cout << "deleted tokens found matching token in S \n"; } cout << "predict stmt --> read id\n"; treeNode * readNode = new treeNode(match(t_read),emptyL); treeNode * idNode = new treeNode(match(t_id),emptyL); treeNode * node = new treeNode("",emptyL); node->nodes.push_front(*readNode); node->nodes.push_back(*idNode); // match (t_read); // match (t_id); // break; return node; } case t_write:{ if(isError){ cout << "deleted tokens found matching token in S \n"; } cout << "predict stmt --> write expr\n"; treeNode * node = new treeNode("",emptyL); treeNode * writeNode = new treeNode(match(t_write),emptyL); node->nodes.push_front(*writeNode); node->nodes.push_back((*expr())); // match (t_write); // expr (); // break; return node; } case t_if:{ if(isError){ cout << "deleted tokens found matching token in S \n"; } cout << "predict stmt --> if c sl end\n"; list<treeNode> l; list<treeNode> l2; treeNode * node = new treeNode("",l); treeNode * SLnode = new treeNode("8u",l2); treeNode * ifNode = new treeNode(match(t_if),emptyL); node->nodes.push_front(*ifNode); node->nodes.push_back((*cond ())); node->nodes.push_back((*stmt_list(SLnode))); treeNode * endNode = new treeNode(match(t_end),emptyL); node->nodes.push_back(*endNode); //match(t_if); //cond (); //stmt_list(); //match( ";t_end); return node;} case t_while:{ if(isError){ cout << "deleted tokens until found matching token in S \n"; } cout << "predict stmt --> while c sl end\n"; list<treeNode> l; list<treeNode> l2; treeNode * node = new treeNode("",l2); treeNode * SLnode = new treeNode("8u",l); treeNode * whileNode = new treeNode(match(t_while),emptyL); node->nodes.push_front(*whileNode); node->nodes.push_back((*cond ())); node->nodes.push_back((*stmt_list(SLnode))); treeNode * endNode = new treeNode(match(t_end),emptyL); node->nodes.push_back(*endNode); //match(t_while); //cond(); //stmt_list(); //match(t_eof); return node; } default:{ error ("S"); return emptyN; } } } treeNode* expr () { error_recovery("E"); switch (input_token) { case t_id: case t_literal: case t_lparen:{ if(isError){ cout << "deleted found matching token in E \n"; } cout << "predict expr --> term term_tail\n"; // term (); // term_tail (); // break; return term_tail(term()); } default: { error ("E"); return emptyN; } } } treeNode* cond (){ error_recovery("C"); switch(input_token){ case t_id: case t_literal: case t_lparen:{ if(isError){ cout << "deleted found matching token in C \n"; } treeNode expNode = ((*expr())); treeNode * node = rela_op(); node->nodes.push_front(expNode); node->nodes.push_back((*expr())); // expr(); // rela_op(); // expr(); // break; return node; } default : { error ("C"); return emptyN; } } } treeNode* term_tail (treeNode* input_node) { error_recovery("TT"); switch (input_token) { case t_add: case t_sub:{ cout << "predict term_tail --> add_op term term_tail\n"; treeNode * node = add_op(); node->nodes.push_front(*input_node); node->nodes.push_back((*term_tail(term()))); return node; // add_op (); // term (); // term_tail (); // break; } case t_rparen: case t_id: case t_read: case t_write: case t_if: case t_while: case t_eqeq: case t_gt: case t_st: case t_neq: case t_gtq: case t_stq: case t_end: case t_eof:{ if(isError){ cout << "deleted found matching token in TT \n"; } cout << "predict term_tail --> epsilon\n"; return input_node; /* epsilon production */ } default:{ error ("TT"); return emptyN; } } } treeNode* term () { error_recovery("T"); switch (input_token) { case t_id: case t_literal: case t_lparen:{ if(isError){ cout << "deleted found matching token in T \n"; } cout << "predict term --> factor factor_tail\n"; // factor (); // factor_tail (); // break;} return factor_tail(factor()); } default: { error ("T"); return emptyN; } } } treeNode* factor () { error_recovery("F"); switch (input_token) { case t_id :{ if(isError){ cout << "deleted found matching token in FT \n"; } cout << ("predict factor --> id\n"); treeNode * node = new treeNode(match(t_id), emptyL); return node; } case t_literal: { if(isError){ cout << "deleted found matching token in FT \n"; } cout << ("predict factor --> literal\n"); treeNode * node = new treeNode(match(t_literal), emptyL); return node; } case t_lparen:{ if(isError){ cout << "deleted found matching token in FT \n"; } cout << ("predict factor --> lparen expr rparen\n"); treeNode * nodeFront = new treeNode(match(t_lparen),emptyL); treeNode * nodeEnd = new treeNode(match(t_rparen), emptyL); list<treeNode> nodeList; nodeList.push_front(*nodeFront); nodeList.push_back(*nodeEnd); treeNode * node = new treeNode("",nodeList); return node; } default:{ error ("F"); return emptyN; } } } treeNode* factor_tail (treeNode* input_node) { error_recovery("FT"); switch (input_token) { case t_mul: case t_div:{ printf ("predict factor_tail --> mul_op factor factor_tail\n"); treeNode * node = mul_op(); node->nodes.push_front(*input_node); node->nodes.push_back((*factor_tail(factor()))); return node; } case t_add: case t_sub: case t_rparen: case t_id: case t_read: case t_eqeq: case t_gt: case t_st: case t_neq: case t_gtq: case t_stq: case t_while: case t_if: case t_end: case t_write: case t_eof: if(isError){ cout << "deleted found matching token in FT \n"; } cout << "predict factor_tail --> epsilon\n"; return input_node; /* epsilon production */ default:{ error ("FT"); return emptyN; } } } treeNode* add_op () { error_recovery("ao"); switch (input_token) { case t_add:{ if(isError){ cout << "deleted found matching token in ao \n"; } cout << ("predict add_op --> add\n"); treeNode * node = new treeNode(match(t_add), emptyL); return node; } case t_sub:{ if(isError){ cout << "deleted found matching token in ao \n"; } cout << ("predict add_op --> sub\n"); treeNode * node = new treeNode(match(t_sub), emptyL); return node; } default:{ error ("ao"); return emptyN; } } } treeNode* mul_op () { error_recovery("mo"); switch (input_token) { case t_mul:{ if(isError){ cout << "deleted found matching token in mo \n"; } cout << ("predict mul_op --> mul\n"); treeNode * node = new treeNode(match(t_mul), emptyL); return node; } case t_div:{ if(isError){ cout << "deleted found matching token in mo \n"; } cout << ("predict mul_op --> div\n"); treeNode * node = new treeNode(match(t_div), emptyL); return node; } default: { error ("mo"); return emptyN; } } } treeNode* rela_op() { error_recovery("ro"); switch (input_token){ case t_eqeq:{ if(isError){ cout << "deleted found matching token in ro \n"; } cout << ("predict rela_op --> eqeq\n"); treeNode * node = new treeNode(match(t_eqeq), emptyL); return node; } case t_neq:{ if(isError){ cout << "deleted found matching token in ro \n"; } cout << ("predict rela_op --> neq\n"); treeNode * node = new treeNode(match(t_neq), emptyL); return node; } case t_gt:{ if(isError){ cout << "deleted found matching token in ro \n"; } cout << ("predict rela_op --> gt\n"); treeNode * node = new treeNode(match(t_gt), emptyL); return node; } case t_st:{ if(isError){ cout << "deleted found matching token in ro \n"; } cout << ("predict rela_op --> st\n"); treeNode * node = new treeNode(match(t_st), emptyL); return node; } case t_gtq:{ if(isError){ cout << "deleted found matching token in ro \n"; } cout << ("predict rela_op --> gta\n"); treeNode * node = new treeNode(match(t_gtq), emptyL); return node; } case t_stq:{ if(isError){ cout << "deleted found matching token in ro \n"; } cout << ("predict rela_op --> stq\n"); treeNode * node = new treeNode(match(t_stq), emptyL); return node; } default:{ error("ro"); return emptyN; }; } } void error_recovery(string statement){ if(!(first.at(statement).count(input_token) || eps.count(statement))){ cout << "error \n"; while(!(first.at(statement).count(input_token) || follow.at(statement).count(input_token) || input_token == t_eof)) { cout << "delete token " + names[input_token] << "\n"; input_token = scan(); } isValidProgram = false; isError = true; return; } isError = false; } int main () { generate_first(); generate_follow(); generate_eps(); input_token = scan (); program(); if(isValidProgram)cout << printTree(root); }
true
2030b38c7d861d5cf140ae331079fb7fa50f4a92
C++
0214sh7/procon-library
/algorithm/slide minimum.cpp
UTF-8
429
2.765625
3
[]
no_license
std::vector<long long> slide_minimum(std::vector<long long> A,int K){ std::vector<long long> R; int N = A.size(); std::deque<int> D; for(int i=0;i<N;i++){ while(!D.empty() && A[D.back()]>=A[i]){D.pop_back();} D.push_back(i); if(i-K+1>=0){ R.push_back(A[D.front()]); if(D.front()==i-K+1){ D.pop_front(); } } } return R; }
true
608ce4d845ebb7b12591ee1ce453630b928f2883
C++
danielfinke/cpsc425
/ASTLiteralNode.h
UTF-8
986
2.625
3
[]
no_license
/* * File: ASTLiteralNode.h * Author: daniel * * Created on October 8, 2013, 9:08 AM */ #ifndef ASTLITERALNODE_H #define ASTLITERALNODE_H #include "ASTExpressionNode.h" /*ASTLiteral Node represents literals in the language, such as 4 or true. * It is a subclass of ASTExpressionNode and overrides the print method. * the node only keeps track of the value * of the literal, such as 4 or true. if the type (inherited from expressionnode) * is boolean, the value will be 0 or 1, if its num, it will be the integer value */ class ASTLiteralNode : public ASTExpressionNode { public: ASTLiteralNode(); ASTLiteralNode(const ASTLiteralNode& orig); ASTLiteralNode& operator= (const ASTLiteralNode &rhs); virtual ~ASTLiteralNode(); void semAnalyze(); void semAnalyze(bool restrictIdents); void scopeAnalyze(); string genQuadruples(); ASTLiteralNode * calc(); void printNode(int indent, ostream * output); private: }; #endif /* ASTLITERALNODE_H */
true
a8c918c230db64c755c3df7c16916e3d086e167e
C++
adam4321/Final-maze
/Empty.cpp
UTF-8
1,556
2.8125
3
[]
no_license
/*********************************************************************** ** Program name: Maze Game ** Author: Adam Wright ** Date: 5/30/2019 ** Description: File that implements the Empty derived class ***********************************************************************/ #include "Empty.hpp" /********************************************************************* ** Description: Function that prints the image for the Dinosaur class ** ascii art from https://www.asciiart.eu/art-and-design/mazes *********************************************************************/ void Empty::printImg() { cout << R"( ______________ |\ ___________ /| | | /|,| | | | | | |,x,| | | | | | |,x,' | | | | | |,x , | | | | |/ | | | | | /] , | | | | [/ () | | | | | | | | | | | | | | | | | | | ,' | | | | ,' | | |_|,'_________|_| )"; } /********************************************************************* ** Description: Method that runs the room's action *********************************************************************/ void Empty::action(Character &player) { cout << "This room is empty...Nothing to see here..."; cout << endl << endl; cout << "Press enter to move along"; cout << endl << endl << endl; char temp = 'x'; cin.clear(); cin.ignore(); while (temp != '\n') { cin.get(temp); } }
true
0a969597d915bc6407ebaf9f711f80e5a4239d3d
C++
Wolframe/SMERP
/src/logLevel.cpp
UTF-8
1,016
2.703125
3
[]
no_license
// // logLevel.cpp // #include "logLevel.hpp" #include <string> #include <boost/algorithm/string.hpp> namespace _SMERP { LogLevel::Level LogLevel::str2LogLevel( const std::string str ) { std::string s = boost::algorithm::to_upper_copy( str ); boost::algorithm::trim( s ); if( s == "DATA" ) return LogLevel::LOGLEVEL_DATA; else if( s == "TRACE" ) return LogLevel::LOGLEVEL_TRACE; else if( s == "DEBUG" ) return LogLevel::LOGLEVEL_DEBUG; else if( s == "INFO" ) return LogLevel::LOGLEVEL_INFO; else if( s == "NOTICE" ) return LogLevel::LOGLEVEL_NOTICE; else if( s == "WARNING" ) return LogLevel::LOGLEVEL_WARNING; else if( s == "ERROR" ) return LogLevel::LOGLEVEL_ERROR; else if( s == "SEVERE" ) return LogLevel::LOGLEVEL_SEVERE; else if( s == "CRITICAL" ) return LogLevel::LOGLEVEL_CRITICAL; else if( s == "ALERT" ) return LogLevel::LOGLEVEL_ALERT; else if( s == "FATAL" ) return LogLevel::LOGLEVEL_FATAL; else return LogLevel::LOGLEVEL_UNDEFINED; } } // namespace _SMERP
true
eaac64e3091a39fbdfcb1e229e70472205d5639c
C++
arnabxero/online-judges-problem-solutions
/Codeforces/Contests/0675/A.cpp
UTF-8
534
2.59375
3
[]
no_license
// Problem name: Infinite Sequence // Problem link: https://codeforces.com/contest/675/problem/A // Submission link: https://codeforces.com/contest/675/submission/25079517 #include <iostream> using namespace std; typedef long long ll; int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll a, b, c, r, k; cin >> a >> b >> c; if(!c) r = 0, k = (a == b ? 1 : -1); else r = (b - a) % c, k = (b - a) / c; //cout << r << endl; cout << ((!r && k >= 0) ? "YES" : "NO"); return 0; }
true
3d226d97aeac896594ec6f4b011903b755ac5e8f
C++
thejasonhsu/Exercises
/fibonaccidriver.cpp
UTF-8
691
3.6875
4
[]
no_license
//===========fibonaccidriver.cpp============== //takes as in put an integer and calls on the function fibonacci //======= =================================== //Returns the nth number of the fibonacci sequence // ========================================================= #include <iostream> #include <stdlib.h> #include <cassert> using namespace std; //Declaration of function so it can appear in the main body of code before it //is defined double Fibonacci( int n); //main body of code int main() { cout<< "Input the nth term sought in the sequence:> "; int n; cin>> n; cout<< " The term in the fibonacci sequence is " << Fibonacci(n) << endl; return 0; }
true
627b4f422814e52d8cae48a4308d439ecfb74d63
C++
dr0pdb/External-Merge-Sort
/src/utils.cpp
UTF-8
1,121
3.796875
4
[ "Apache-2.0" ]
permissive
#include <utils.h> /* Generates a random text file with the name and the size provided as arguments. */ void generate_random_text_file(std::string file_name, int file_size) { std::ofstream created_file; created_file.open(file_name.c_str()); int current_size = 0; // stores the current size of the generated file. int word_size; // stores the size of the random word generated. int number; // stores the current number being written in the generated file. while(current_size < file_size) { word_size = 1 + rand()%10; // prevents accidentally surpassing the desired file size. while(current_size + word_size > file_size) { word_size = 1 + rand()%10; } for (int i = 0; i < word_size; ++i) { number = rand(); // assign a random number. created_file << number; } } created_file.close(); std::cout<<file_name<<" has been successfully generated\n"; } FILE* openFile(std::string file_name, char* mode) { FILE* fp = fopen(file_name.c_str(), mode); if (fp == NULL) { perror("Error while opening the file.\n"); exit(EXIT_FAILURE); } return fp; }
true
a5b7349d509cec1b2ccbaf089e527aafb8fd34ce
C++
oligagne/GreenLight
/GL.Objects/light.h
UTF-8
490
2.578125
3
[]
no_license
#ifndef LIGHT_H #define LIGHT_H #include <string> #include "coordinates.h" using namespace std; class Coordinates; class Light { public: Light(); ~Light(); public: void SetId(string id); void SetDescription(string description); void SetCoordinates(Coordinates intersection); string GetId(); string GetDescription(); Coordinates* GetCoordinates(); private: string _id; string _description; Coordinates* _intersection; }; #endif // LIGHT_H
true
eda2dd2af7d878ba419dd0baa0bc51344db77254
C++
xXHachimanXx/Grafos
/includes/Grafo.h
UTF-8
928
2.6875
3
[ "MIT" ]
permissive
using namespace std; class Grafo { public: int vertices; //numero de vertices int arestas; //numero de arestas int ** matriz; //matriz de adjascência (int) float ** fmatriz; //matriz de adjascência (float) int componentes; //numero de componentes conectados ~Grafo(); //destrutor Grafo(int vertices, int arestas); //construtor Grafo(int vertices); //construtor Grafo(); //construtor void inicializar(); //inicializador void conectarVertices(char v1, char v2); void printMatriz(); void buscaEmProfundidade(int vertice, bool visitados[]); void mostrarComponentes(); void gerarSaida(int caso, Grafo* grafo); int charToIndex(char v); char indexToChar(int v); //overload de operador friend ostream & operator << (ostream &out, Grafo* &grafo); };
true
e0deb9b7abca97f671e0c44f71796615cbe193e8
C++
JitenWhatever/CSES-Problem-Set
/Graph Algorithms/Round Trip II.cpp
UTF-8
2,305
3.328125
3
[]
no_license
/* Time limit: 1.00 s Memory limit: 512 MB Byteland has n cities and m flight connections. Your task is to design a round trip that begins in a city, goes through one or more other cities, and finally returns to the starting city. Every intermediate city on the route has to be distinct. Input The first input line has two integers n and m: the number of cities and flights. The cities are numbered 1,2,…,n. Then, there are m lines describing the flights. Each line has two integers a and b: there is a flight connection from city a to city b. All connections are one-way flights from a city to another city. Output First print an integer k: the number of cities on the route. Then print k cities in the order they will be visited. You can print any valid solution. If there are no solutions, print "IMPOSSIBLE". Constraints 1≤n≤10^5 1≤m≤2⋅10^5 1≤a,b≤n Example Input: 4 5 1 3 2 1 2 4 3 2 3 4 Output: 4 2 1 3 2 */ #include<bits/stdc++.h> using namespace std; #define ll long long #define ar array const ll MAX=1e5; vector<ll> graph[MAX]; vector<ll> par, visi; void dfs(int u) { if(visi[u] == 2) { return ; } visi[u] = 1; for(int v : graph[u]) { if(visi[v] == 1) { par[v] = u; vector<ll> path; path.push_back(u); while(path[0] != par[u]) { u = par[u]; path.push_back(u); } path.push_back(path[0]); reverse(path.begin(), path.end()); cout<<path.size()<<"\n"; for(ll p : path) { cout<<p + 1<<" "; } exit(0); } else { if(visi[v] == 0) { par[v] = u; dfs(v); } } } visi[u] = 2; } int main() { ll n, m; cin>>n>>m; par = vector<ll>(n, -1); visi = vector<ll>(n, 0); for(int edge = 0; edge < m; ++edge) { ll u, v; cin>>u>>v; --u, --v; graph[u].push_back(v); } for(int node = 0; node < n; ++node) { if(visi[node] == 0) { dfs(node); } } cout<<"IMPOSSIBLE\n"; return 0; }
true
643eeaedf06fc53ae28db6ca948c01242e29d8cb
C++
VPintaric/AdventOfCode2019
/d03/s02.cpp
UTF-8
3,953
3.5
4
[]
no_license
#include <iostream> #include <vector> #include <sstream> #include <limits> struct Line { int first, second, common, steps; }; void fillFirstWireLinesData( std::vector< Line > &vertical, std::vector< Line > &horizontal ) { std::string inputLine; std::getline( std::cin, inputLine ); std::stringstream ss( inputLine ); char direction; int distance; int curx = 0, cury = 0; int steps = 0; while ( ss ) { ss >> direction; ss >> distance; ss.ignore( 1 ); // ignore the comma switch ( direction ) { case 'R': horizontal.push_back( { curx, curx + distance, cury, steps } ); curx += distance; break; case 'L': horizontal.push_back( { curx, curx - distance, cury, steps } ); curx -= distance; break; case 'U': vertical.push_back( { cury, cury + distance, curx, steps } ); cury += distance; break; case 'D': vertical.push_back( { cury, cury - distance, curx, steps } ); cury -= distance; break; default: std::cerr << "Crash and burn" << std::endl; } steps += distance; } } bool isBetween( int n, int first, int second ) { if ( first < second ) { return n >= first && n <= second; } else { return n >= second && n <= first; } } int main() { std::vector< Line > vertical, horizontal; fillFirstWireLinesData( vertical, horizontal ); int closestCrossingSteps = std::numeric_limits< int >::max(); std::string inputLine; std::getline( std::cin, inputLine ); std::stringstream ss( inputLine ); int curx = 0, cury = 0; char direction; int distance; int steps = 0; while ( ss ) { ss >> direction; ss >> distance; ss.ignore( 1 ); // ignore the comma Line secondWireLine{}; switch ( direction ) { case 'R': secondWireLine = Line{ curx, curx + distance, cury, steps }; curx += distance; break; case 'L': secondWireLine = Line{ curx, curx - distance, cury, steps }; curx -= distance; break; case 'U': secondWireLine = Line{ cury, cury + distance, curx, steps }; cury += distance; break; case 'D': secondWireLine = Line{ cury, cury - distance, curx, steps }; cury -= distance; break; default: std::cerr << "Crash and burn" << std::endl; } steps += distance; std::vector< Line > *firstWireLines; if ( direction == 'R' || direction == 'L' ) { firstWireLines = &vertical; } else { firstWireLines = &horizontal; } for ( auto &firstWireLine : *firstWireLines ) { if ( isBetween( firstWireLine.common, secondWireLine.first, secondWireLine.second ) && isBetween( secondWireLine.common, firstWireLine.first, firstWireLine.second )) { if ( firstWireLine.common != 0 || secondWireLine.common != 0 ) { auto crossingStepsFirstLine = firstWireLine.steps + std::abs( firstWireLine.first - secondWireLine.common ); auto crossingStepsSecondLine = secondWireLine.steps + std::abs( secondWireLine.first - firstWireLine.common ); auto crossingSteps = crossingStepsFirstLine + crossingStepsSecondLine; closestCrossingSteps = std::min( crossingSteps, closestCrossingSteps ); } } } } std::cout << closestCrossingSteps << std::endl; return 0; }
true
584eab797aa977b5c029c6c9bd27b9c6e380f15d
C++
thien926/Thien
/UPCoder/CH25.cpp
UTF-8
260
2.53125
3
[]
no_license
#include <iostream> using namespace std; typedef unsigned long long int ll; ll n; void nhap(){ cin >> n; } void solve(){ if(n % 2 == 0 || n % 5 == 0) cout << "Có"; else cout << "Không"; } int main(){ nhap(); solve(); return 0; }
true
037f921fc8649a86860b11e6ca143090421928c9
C++
small-cat/myCode_repository
/statusCheck/src/dbmanager/DBManager.cpp
UTF-8
10,241
2.8125
3
[]
no_license
/************************************************** > File name: DBManager.cpp > Author: wzhenyu > mail: > Create Time: 2016-03-28 14:44 ****************************************************/ #include "dbmanager/DBManager.h" #include <stdlib.h> /*********************************************************** * 函数名: CDBManager::CDBManager() * 函数功能: 构造函数 * 参数说明: * 返回值说明: * 涉及到的表: * 作者: wzhenyu * 时间: 2016-03-28 15:12 ***********************************************************/ CDBManager::CDBManager() { m_mysqlRes = NULL; m_DBHost = NULL; m_DBUserName = NULL; m_DBPassWord = NULL; m_DBName = NULL; m_DBPort = 0; InitDB(); } /*********************************************************** * 函数名: CDBManager::~CDBManager() * 函数功能: 析构函数 * 参数说明: * 返回值说明: * 涉及到的表: * 作者: wzhenyu * 时间: 2016-03-28 15:15 ***********************************************************/ CDBManager::~CDBManager() { if (NULL != m_mysqlRes) { mysql_free_result(m_mysqlRes); m_mysqlRes = NULL; } mysql_close(&m_mysqlHandle); if (NULL != m_DBHost) { free(m_DBHost); m_DBHost = NULL; } if (NULL != m_DBUserName) { free(m_DBUserName); m_DBUserName = NULL; } if (NULL != m_DBPassWord) { free(m_DBPassWord); m_DBPassWord = NULL; } if (NULL != m_DBName) { free(m_DBName); m_DBName = NULL; } } /*********************************************************** * 函数名: CDBManager::InitDB() * 函数功能: * 参数说明: * 返回值说明: * 涉及到的表: * 作者: wzhenyu * 时间: 2016-03-28 15:27 ***********************************************************/ void CDBManager::InitDB() { char host[32] = {0}; char username[32] = {0}; char password[32] = {0}; char dbname[32] = {0}; int port = 0; /* 临时变量 */ int i_length = 0; DUMPSYSLOG(INFO, "DBManager", "CDBManager", "InitDB", "DB Manager Start, line %d", __LINE__); DUMPSYSLOG(INFO, "DBManager", "CDBManager", "InitDB", "Get Config Start, line %d", __LINE__); /* 获取配置参数 */ CConfigManager* conf = new CConfigManager(); conf->GetValue(DOWNCHECK_CONFIG_INI, "DBManager", "dbhost", host); conf->GetValue(DOWNCHECK_CONFIG_INI, "DBManager", "dbusername", username); conf->GetValue(DOWNCHECK_CONFIG_INI, "DBManager", "dbpassword", password); conf->GetValue(DOWNCHECK_CONFIG_INI, "DBManager", "dbname", dbname); conf->GetValue(DOWNCHECK_CONFIG_INI, "DBManager", "dbport", port); /* Get host start */ if (strlen(host) == 0) /* host的值可能是 '\0' */ { DUMPSYSLOG(DEBUG, "DBManager", "CDBManager", "InitDB", "can not get host value, use default [localhost], line %d", __LINE__); int length = strlen("localhost") + 1; m_DBHost = (char*)malloc(sizeof(char)*length); ERRPRINT(m_DBHost==NULL, goto ERR1, 0, "DBManager#CDBManager#InitDB#malloc failed, line %d", __LINE__); DUMPSYSLOG(ERROR, "DBManager", "CDBManager", "InitDB", "malloc failed, line %d", __LINE__); strncpy(m_DBHost, "localhost", length-1); m_DBHost[length-1] = '\0'; } else { int length = strlen(host) + 1; m_DBHost = (char*)malloc(sizeof(char)*length); if (NULL == m_DBHost) { DUMPSYSLOG(ERROR, "DBManager", "CDBManager", "InitDB", "malloc failed. line %d", __LINE__); ERRPRINT(m_DBHost==NULL, goto ERR1, 0, "DBManager#CDBManager#InitDB#malloc failed, line %d", __LINE__); } strncpy(m_DBHost, host, length-1); m_DBHost[length-1] = '\0'; DUMPSYSLOG(DEBUG, "DBManager", "CDBManager", "InitDB", "host is [%s]", host); } /* Get host end */ /* Get username start */ ERRPRINT(strlen(username) == 0, goto ERR2, 0, "DBManager#CDBManager#InitDB#username can not be null, line %d", __LINE__); i_length = strlen(username); m_DBUserName = (char*)malloc(sizeof(char)*(i_length + 1)); if (NULL == m_DBUserName) { DUMPSYSLOG(ERROR, "DBManager", "CDBManager", "InitDB", "malloc failed. line %d", __LINE__); ERRPRINT(NULL==m_DBUserName, goto ERR2, 0, "DBManager#CDBManager#InitDB#malloc failed, line %d", __LINE__); } strncpy(m_DBUserName, username, i_length); m_DBUserName[i_length] = '\0'; DUMPSYSLOG(DEBUG, "DBManager", "CDBManager", "InitDB", "username is [%s]", username); /* Get username end */ /* Get password start */ if (strlen(password) == 0) { m_DBPassWord = NULL; DUMPSYSLOG(DEBUG, "DBManager", "CDBManager", "InitDB", "password is [NULL], line %d", __LINE__); } else { i_length = strlen(password); m_DBPassWord = (char*)malloc(sizeof(char)*(i_length + 1)); if (NULL == m_DBPassWord) { DUMPSYSLOG(ERROR, "DBManager", "CDBManager", "InitDB", "malloc failed. line %d", __LINE__); ERRPRINT(NULL==m_DBPassWord, goto ERR3, 0, "DBManager#CDBManager#InitDB#malloc failed, line %d", __LINE__); } strncpy(m_DBPassWord, password, i_length); m_DBPassWord[i_length] = '\0'; DUMPSYSLOG(DEBUG, "DBManager", "CDBManager", "InitDB", "password is [%s]", password); } /* Get password end */ /* Get db name start */ if (strlen(dbname) == 0) { m_DBName = NULL; DUMPSYSLOG(DEBUG, "DBManager", "CDBManager", "InitDB", "password is [NULL], line %d", __LINE__); } else { i_length = strlen(dbname); m_DBName = (char*)malloc(sizeof(char)*(i_length + 1)); if (NULL == m_DBName) { DUMPSYSLOG(ERROR, "DBManager", "CDBManager", "InitDB", "malloc failed. line %d", __LINE__); ERRPRINT(NULL==m_DBName, goto ERR4, 0, "DBManager#CDBManager#InitDB#malloc failed, line %d", __LINE__); } strncpy(m_DBName, dbname, i_length); m_DBName[i_length] = '\0'; DUMPSYSLOG(DEBUG, "DBManager", "CDBManager", "InitDB", "dbname is [%s]", dbname); } /* Get db name end */ /* Get port start */ m_DBPort = (UINT)port; /* Get port end */ delete conf; /* 初始化数据库句柄 */ mysql_init(&m_mysqlHandle); DUMPSYSLOG(INFO, "DBManager", "CDBManager", "InitDB", "Get Config End, line %d", __LINE__); return; ERR4: if (NULL != m_DBPassWord) { free(m_DBPassWord); m_DBPassWord = NULL; } ERR3: if (NULL != m_DBUserName) { free(m_DBUserName); m_DBUserName = NULL; } ERR2: if (NULL != m_DBHost) { free(m_DBHost); m_DBHost = NULL; } ERR1: exit(EXIT_FAILURE); } /*********************************************************** * 函数名: bool ConnectDB() * 函数功能: * 参数说明: * 返回值说明: * 涉及到的表: * 作者: wzhenyu * 时间: 2016-03-28 15:17 ***********************************************************/ bool CDBManager::ConnectDB() { DUMPSYSLOG(INFO, "DBManager", "CDBManager", "ConnectDB", "Connect to MySql, line %d", __LINE__); if (!mysql_real_connect(&m_mysqlHandle, m_DBHost, m_DBUserName, m_DBPassWord, m_DBName, m_DBPort, NULL, 0)) { DUMPSYSLOG(ERROR, "DBManager", "CDBManager", "ConnectDB", "Failed to connect to mysql, errno: %u, error: %s", mysql_errno(&m_mysqlHandle), mysql_error(&m_mysqlHandle)); ERRPRINT(1, return false, 0, "DBManager#CDBManager#ConnectDB#Failed to connect to mysql, Error %u : %s, line %d", mysql_errno(&m_mysqlHandle), mysql_error(&m_mysqlHandle), __LINE__); } return true; } /*********************************************************** * 函数名: bool CDBManager::QueryDB(const char* statement) * 函数功能: 查询数据库 select * 参数说明: 查询 SQL 语句 * 返回值说明: 返回结果集 * 涉及到的表: CD.CM_RES_LIFECYCLE, CD.CM_RES_IDENTITY * sql 语句样例: * SELECT t2.identity,t1.resource_id,t1.so_date,UNIX_TIMESTAMP(t1.valid_date) valid_date,UNIX_TIMESTAMP(t1.expire_date) expire_date,t1.os_sts_dtl FROM cm_res_lifecycle_0 t1 JOIN cm_res_identity_0 t2 ON t1.resource_id = t2.resource_id AND t1.os_sts_dtl IN (2,4) ORDER BY t1.so_date; * * 作者: wzhenyu * 时间: 2016-03-28 19:18 ***********************************************************/ bool CDBManager::QueryDB(const char* statement) { int flag = mysql_real_query(&m_mysqlHandle, statement, (unsigned long)strlen(statement)); /* 0表示成功,非0表示出错 */ if (flag) { DUMPSYSLOG(ERROR, "DBManager", "CDBManager", "QueryDB", "Query [%s] failed, errno: %u, error: %s", statement, mysql_errno(&m_mysqlHandle), mysql_error(&m_mysqlHandle)); ERRPRINT(1, return false, 0, "BDManager#CDBManager#QueryDB#Query failed, errno : %u, error: %s", mysql_errno(&m_mysqlHandle), mysql_error(&m_mysqlHandle)); } DUMPSYSLOG(DEBUG, "DBManager", "CDBManager", "QueryDB", "Query [%s] success", statement); if (m_mysqlRes != NULL) { mysql_free_result (m_mysqlRes); m_mysqlRes = NULL; } m_mysqlRes = mysql_store_result(&m_mysqlHandle); if (NULL == m_mysqlRes) { if (mysql_field_count(&m_mysqlHandle) == 0) { DUMPSYSLOG(INFO, "DBManager", "CDBManager", "QueryDB", "Sql is not select, line %d", __LINE__); ERRPRINT(1, return false, 0, "DBManager#CDBManager#QueryDB#Sql is not select, line %d", __LINE__); } else { DUMPSYSLOG(ERROR, "DBManager", "CDBManager", "QueryDB", "Query [%s] failed, errno: %u, error: %s", statement, mysql_errno(&m_mysqlHandle), mysql_error(&m_mysqlHandle)); ERRPRINT(1, return false, 0, "BDManager#CDBManager#QueryDB#Query failed, errno : %u, error: %s", mysql_errno(&m_mysqlHandle), mysql_error(&m_mysqlHandle)); } } return true; } bool CDBManager::SetTimeZone(const char* time_zone) { char stat[64] = {0}; sprintf (stat, "set time_zone = \"%s\";", time_zone); int flag = mysql_real_query (&m_mysqlHandle, stat, (unsigned long)strlen (stat)); if (flag) { DUMPSYSLOG(ERROR, "DBManager", "CDBManager", "QueryDB", "Query [%s] failed, errno: %u, error: %s", stat, mysql_errno(&m_mysqlHandle), mysql_error(&m_mysqlHandle)); ERRPRINT(1, return false, 0, "BDManager#CDBManager#SetTimeZone#Query failed, errno : %u, error: %s", mysql_errno(&m_mysqlHandle), mysql_error(&m_mysqlHandle)); } return true; } /*********************************************************** * 函数名: CDBManager::GetResult() * 函数功能: 获取结果集 * 参数说明: * 返回值说明: 返回查询结果集 * 涉及到的表: * 作者: wzhenyu * 时间: 2016-03-28 20:15 ***********************************************************/ MYSQL_RES* CDBManager::GetResult() { return m_mysqlRes; }
true
375601acec0c53442dae0ddc67e64980e8a6d331
C++
1779296311/leetcode
/19.cpp
UTF-8
863
2.9375
3
[]
no_license
/********************************************* * ------------------------ * ------------------------ * file name: 19.cpp * author : @ JY * date : 2019--09--27 **********************************************/ #include <iostream> #include <stdlib.h> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *tmp = new ListNode(0); tmp->next = head; ListNode *right = tmp; ListNode *left = tmp; for(int i=0; i<n; i++){ left = left->next; } while(left->next){ left = left->next; right = right->next; } right->next = right->next->next; return tmp->next; } };
true
29cfea5ddf83d95865246baf8c0e3ee5f6a332f1
C++
BorisSchaeling/boost-meta-programming-2020
/22_concepts_for_template_parameters/main.cpp
UTF-8
368
3.4375
3
[ "BSL-1.0" ]
permissive
#include <iostream> template <typename T> concept negatable = requires(T v) { -v; }; template <typename T> concept dereferencable = requires(T v) { *v; }; template <negatable T> void print(T t) { std::cout << t << '\n'; } template <dereferencable T> void print(T t) { std::cout << *t << '\n'; } int main() { int i{ 1 }; print(i); int* p{ &i }; print(p); }
true
03a7b31754844416e81fc75523baa78488c113ad
C++
enci/Raymond
/Raymond/Source/Light.cpp
UTF-8
928
2.78125
3
[ "MIT" ]
permissive
#include "Light.h" #include "Utils.h" using namespace glm; using namespace Raymond; LightInfo PointLight::GetLightInfo(const glm::vec3& position) { LightInfo info; //vec3 direction = (Position + RandomOnUnitSphere() * Radius) - position; vec3 direction = Position - position; info.Distance = length(direction); direction /= info.Distance; info.Ray = Ray(position, direction); const float& r = info.Distance - Radius; const float intensity = Intensity / (r*r); //const float frac = (info.Distance / Radius + 1); //const float intensity = Intensity / (frac * frac); info.Color = this->Color * intensity; return info; } LightInfo DirecionalLight::GetLightInfo(const glm::vec3& position) { LightInfo info; vec3 direction = -normalize(Direction); direction += RandomOnUnitSphere() * Radius; info.Distance = FLT_MAX; info.Ray = Ray(position, direction); info.Color = this->Color * Intensity; return info; }
true
92e35fbef5c0c7ccbc4f4c2824a62f997ff60697
C++
sambennion/CS_236_Lab4
/UndefinedStringAutoma.cpp
UTF-8
1,149
2.84375
3
[]
no_license
// // Created by Samuel Bennion on 2/1/21. // #include "UndefinedStringAutoma.h" int UndefinedStringAutoma::Start(const string &input) { // bool isMatch = true; inputRead = 0; this->newLines = 0; if(input.at(0) == '\''){ inputRead++; return s0(input); } else{ return 0; } } int UndefinedStringAutoma::s0(const string &input){ while((input.at(inputRead) != '\'' && inputRead < (int)input.size()) || isDoubleQuote(input)) { if (input.at(inputRead) == '\n') { this->newLines++; //cout << this->newLines << endl; } if (isDoubleQuote((input))) { inputRead++; } inputRead++; if(inputRead == (int)input.length()){ //newLines--; return inputRead; } } if(input.at(inputRead) == '\''){ inputRead++; return 0; } return 0; } bool UndefinedStringAutoma::isDoubleQuote(const string input){ if((int)input.size() > inputRead+2){ if(input.at(inputRead) == '\'' && input.at(inputRead+1) == '\''){ return true; } } return false; }
true
36388034766db1f7cd03b4b5280fbca8a54f6476
C++
YipengUva/cpp_primer_solutions
/chapter6_functions/main.cpp
UTF-8
1,268
3.453125
3
[]
no_license
#include <iostream> #include <string> using namespace std; class Sales_data { private: /* data */ public: string bookNo; unsigned units_sold = 0; double revenue = 0.0; string isbn() const { return this->bookNo; } Sales_data& combine(const Sales_data&); double avg_price() const; Sales_data(/* args */); ~Sales_data(); }; double Sales_data::avg_price() const { if(units_sold) return revenue/units_sold; else return 0; } Sales_data& Sales_data::combine(const Sales_data &rhs) { units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } ostream &print(ostream&, const Sales_data&); istream &read(istream&, Sales_data&); istream &read(istream &is, Sales_data &item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; item.revenue = price * item.units_sold; return is; } ostream &print(ostream &os, const Sales_data&item) { } void swap(int &v1, int&v2) { if(v1 == v2){ return; } int tmp = v2; v2 = v1; v1 = tmp; } int main() { void (*pf)(int &, int &); pf = &swap; int v1 = 10; int v2 = 100; (*pf)(v1, v2); cout << v1 << " " << v2 << endl; return 0; }
true
6e4cfc3a75f1b8bee9fbec03bdb864cd3c383ff4
C++
aikudo/compiler
/src/ocfiles/scannertest/53-insertionsort.oc.cpp
UTF-8
1,664
2.859375
3
[]
no_license
# 1 "ocfiles/53-insertionsort.oc" # 1 "<command-line>" # 1 "ocfiles/53-insertionsort.oc" # 1 "ocfiles/oclib.oh" 1 # 30 "ocfiles/oclib.oh" void __assert_fail (string expr, string file, int line); void putb (bool b); void putc (char c); void puti (int i); void puts (string s); void endl (); int getc (); string getw (); string getln (); string[] getargv (); void exit (int status); # 7 "ocfiles/53-insertionsort.oc" 2 int strcmp (string s1, string s2) { int index = 0; bool contin = true; while (contin) { char s1c = s1[index]; char s2c = s2[index]; int cmp = ord s1c - ord s2c; if (cmp != 0) return cmp; if (s1c == '\0') contin = false; index = index + 1; } return 0; } void insertion_sort (int size, string[] array) { int sorted = 1; while (sorted < size) { int slot = sorted; string element = array[slot]; bool contin = true; while (contin) { if (slot == 0) { contin = false; }else if (strcmp (array[slot - 1], element) <= 0) { contin = false; }else { array[slot] = array[slot - 1]; slot = slot - 1; } } array[slot] = element; sorted = sorted + 1; } } void print_array (string label, int size, string[] array) { endl (); puts (label); puts (":\n"); int index = 0; while (index < size) { puts (array[index]); endl (); index = index + 1; } } string[] argv = getargv (); int argc = 0; while (argv[argc] != null) argc = argc + 1; print_array ("unsorted", argc, argv); insertion_sort (argc, argv); print_array ("sorted", argc, argv);
true
2d684c39144fd5907768a981ff7192bc893d185e
C++
favedit/MoCross3d
/Source/Cross/Common/MoCommon/FStreamBlockPool.cpp
GB18030
3,280
2.65625
3
[]
no_license
#include "MoCmPipe.h" MO_NAMESPACE_BEGIN //============================================================ // <T>컺п顣</T> //============================================================ FStreamBlockPool::FStreamBlockPool(){ _capacity = 0; _blockCapacity = 0; MO_CLEAR(_pAllocator); _pBlocks = MO_CREATE(FStreamBlockList); } //============================================================ // <T>п顣</T> // // @param capacity //============================================================ FStreamBlockPool::~FStreamBlockPool(){ Reset(); MO_DELETE(_pBlocks); } //============================================================ // <T>ռһܵ顣</T> // // @return ܵ //============================================================ FStreamBlock* FStreamBlockPool::Alloc(){ FStreamBlock* pBlock = NULL; //............................................................ _locker.Enter(); // TInt blockCount = _pBlocks->Count() + 1; TInt capacity = _blockCapacity * (blockCount + 1); if(capacity > _capacity){ MO_ERROR(TC("Capacity is too small. (capacity=%d, block_capacity=%d, block_count=%d, block_alloc=%d)"), _capacity, _blockCapacity, blockCount, capacity); }else{ // ռһֿ pBlock = _pAllocator->Alloc(); _pBlocks->Push(pBlock); } _locker.Leave(); //............................................................ return pBlock; } //============================================================ // <T>ͷһܵ顣</T> // // @param pBlock ܵ //============================================================ void FStreamBlockPool::Free(FStreamBlock* pBlock){ MO_ASSERT(pBlock); //............................................................ _locker.Enter(); // ͷŷֿ if(_pBlocks->Contains(pBlock)){ _pBlocks->Remove(pBlock); _pAllocator->Free(pBlock); }else{ MO_ERROR(TC("Free block is not exists. (capacity=%d, block_capacity=%d, block_count=%d)"), _capacity, _blockCapacity, _pBlocks->Count()); } _locker.Leave(); //............................................................ } //============================================================ // <T>ݡ</T> // // @return //============================================================ TBool FStreamBlockPool::Reset(){ _locker.Enter(); // ͷڴ TListIteratorC<FStreamBlock*> iterator = _pBlocks->IteratorC(); while(iterator.Next()){ FStreamBlock* pBlock = *iterator; _pAllocator->Free(pBlock); } _pBlocks->Clear(); _locker.Leave(); return ETrue; } //============================================================ // <T>Ϣ</T> // // @param pTrack //============================================================ void FStreamBlockPool::Track(MString* pTrack){ pTrack->AppendFormat(TC("Buffered queue dump. (capacity=%d\n"), _capacity); TListIteratorC<FStreamBlock*> iterator = _pBlocks->IteratorC(); while(iterator.Next()){ FStreamBlock* pBlock = *iterator; pTrack->Append(TC(" ")); pBlock->Track(pTrack); pTrack->Append(TC("\n")); } } MO_NAMESPACE_END
true
a2e71453805bc5b4abe00d59171d87772e41aef4
C++
ryannuti/PoNNg
/paddle.cpp
UTF-8
338
2.75
3
[]
no_license
#include "paddle.h" using namespace std; Paddle::Paddle(float x) { this->position = new Point(x, 0.0); } Point* Paddle::getPos() { return this->position; } void Paddle::setY(float y) { this->position->set(this->position->getX(), y + this->offset); } void Paddle::randOffset() { this->offset = rand() % 100 / 100.0 * 70 - 35; }
true
71101963e746cd8617fd7687c715fc82726596dd
C++
bartoszWesolowski/university-projects
/openGL/OpenGL/OpenGLTutorial1/ball.cpp
UTF-8
633
3
3
[]
no_license
#include "ball.h" #include <iostream> Ball::~Ball() { } void Ball::moveBall() { m_transform->getPos().x += velX; m_transform->getRot().z -= velX * 1000; if (m_transform->getPos().x > maxX || m_transform->getPos().x < 0.0f) { velX *= -1.0; } } void Ball::moveInACircle(float radius) { m_transform->getPos().x = startPosition.x + cosf(2 * PI * currentTime / loopDuration) * radius; //std::cout << "X: " << m_transform->getPos().x << "\n"; m_transform->getPos().z = startPosition.z + sinf(2 * PI * currentTime / loopDuration) * radius; //std::cout << "Z: " << m_transform->getPos().z << "\n"; currentTime += deltaTime; }
true
5e040a5b38a95cd05ffe792da960f28a302e863f
C++
JsKim4/BOJ-BaekJoon-Online-judge-
/cpp/2000/2700/P2738.cpp
UTF-8
468
2.578125
3
[]
no_license
#include<iostream> #pragma warning (disable:4996) using namespace std; // 2738 행렬 덧셈 int a1[100][100], a2[100][100]; int main(){ int n, m; cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> a1[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> a2[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << a1[i][j] + a2[i][j]<<" "; } cout << endl; } }
true
6f8e6b510ce7c2abd9eef7bdb5f5500385c640cc
C++
jrondanv/algo
/library/Graph/hungarian.cpp
UTF-8
1,619
2.734375
3
[ "Unlicense" ]
permissive
// Entrada: nh, nm, número de vértices nos lados esquerdo e direito // dist[h][m], custo das arestas // Saída: h[], par do vértice i do lado esquerdo int augment(int curman) { int i,j; vm[curman] = mark; for (int i = 0; i < nh; i++) { if (newdist[curman][i] == 0 && m[i] == -1) { m[i] = curman; h[curman] = i; return 1; } } for (int i = 0; i < nh; i++) { if (newdist[curman][i] == 0 && vh[i] != mark) { vh[i] = mark; if (augment(m[i])) { h[curman] = i; m[i] = curman; return 1; } } } return 0; } int hungarian() { for (int i = 0; i < nm; i++) for (int j = 0; j < nh; j++) newdist[i][j]=dist[i][j]; mark = 0; for (int i =0 ; i < nm; i++) { vm[i] = 0; h[i] = -1; } for (int i =0 ; i < nh; i++) { vh[i] =0; m[i] = -1; } for (int k = 0; k < nm; k++) { mark++; while (!augment(k)) { int minc = 1000000000; for (int i = 0; i < nm; i++) if (vm[i] == mark) { for (int j = 0; j < nh; j++) if (vh[j] != mark && newdist[i][j] != 0 && newdist[i][j] < minc) { minc = newdist[i][j]; } } for (int i = 0; i < nm; i++) if (vm[i] == mark) { for (int j = 0; j < nh; j++) newdist[i][j] -= minc; } for (int j = 0; j < nh; j++) if (vh[j] == mark) { for (int i = 0; i < nm; i++) newdist[i][j] += minc; } mark++; } } int ans =0 ; for (int i = 0; i < nm; i++) ans += dist[i][h[i]]; return ans; }
true
8d1d6faac881ae1cfe2c1427bec104da9aebff63
C++
jsjose/katas-Cpp
/countDuplicates.cpp
UTF-8
1,729
2.828125
3
[ "Apache-2.0" ]
permissive
#include <iostream> #include <stdio.h> // using namespace std; size_t duplicateCount(const std::string& in); // helper for tests size_t duplicateCount(const char* in) { int i, n; size_t rc = 0; int dup[26+33+4+6] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0}; // 26 letters, 65 A 90 Z 97 a 122 z // 32 to 64 included // 123 to 126 included // 91 to 96 included for (i = 0; i < strlen(in); ++i) { n = int(in[i]); if (n>=65 && n<=90) { dup[n-65+33]++; } else if (n>=97 && n<=122) { dup[n-97+33]++; } else if (n>=32 && n<=64) { dup[n-32]++; } else if (n>=123 && n<=126) { dup[n-64+6]++; } else if (n>=91 && n<=96) { dup[n-91+59]++; } } for (i=0; i<26+33+4+6; ++i) { if (dup[i]>1) { rc++; } } return rc; } Describe(sample_Tests) { It(small_Tests) { Assert::That(duplicateCount(" "), Equals(0)); Assert::That(duplicateCount(""), Equals(0)); Assert::That(duplicateCount("asdfghjkl;'\\"), Equals(0)); Assert::That(duplicateCount("asdfghjkl;'\\'"), Equals(1)); Assert::That(duplicateCount("aabbcde"), Equals(2)); Assert::That(duplicateCount("aabBcde"), Equals(2)); Assert::That(duplicateCount("Indivisibility"), Equals(1)); Assert::That(duplicateCount("Indivisibilities"), Equals(2)); } };
true
948852039a57a600ff981b15c296c99baf7d32f9
C++
lyh458/InteractionModels_DemoCode
/src/iModGripper/c_interface.cpp
UTF-8
3,317
2.71875
3
[]
no_license
#include "gripper/GripperController.h" #if defined(__cplusplus) extern "C" { #endif extern void GC_init(void) __attribute__((constructor)); extern void GC_term(void) __attribute__((destructor)); GripperController *gripper = NULL; //! Library Constructor void GC_init() { if (gripper == NULL) { gripper = new GripperController(); } } //! Destructor void GC_term(void) { delete gripper; } /** * connect lib to gripper * @param bool result optional return value */ void GC_connect(bool &result) { result = gripper->connect(); } void GC_isConnected(bool &connected) { connected = gripper->isConnected(); } /** * read single register as unsigned int * @param addr register-addr * @param unsigned int result return value */ void GC_getValue(int addr, unsigned int &result) { result = gripper->getValue(addr); } /** * read single register as unsigned int * @param addr register-addr * @param unsigned int result return value */ void GC_getInputValue(int addr, unsigned int &result) { result = gripper->getInputValue(addr); } /** * write single register * @param addr register-addr * @param value value * @param int result optional return value */ void GC_setValue(int reg_addr, int value, int &result) { result = gripper->setValue(reg_addr, value); } /** * open gripper * @param openTo range from 0 to 255 * @return bool */ void GC_openGripper(int openTo = 255) { gripper->open(openTo); } /** * close gripper * @param closeTo range from 0 to 255 * @return bool */ void GC_closeGripper(int closeTo = 255) { gripper->close(closeTo); } /** * get current gripper open-value * @param result returns unsigned int */ void GC_getOpenGripper(unsigned int &result) { result = gripper->getOpen(); } /** * get current gripper close-value * @param result returns unsigned int */ void GC_getCloseGripper(unsigned int &result) { result = gripper->getClose(); } /** * init gripper * @return bool */ void GC_initGripper() { gripper->init(); } /** * set and get speed for next operation * @param speed of grippe in range from 0 = 22mm/s to 255 = 110mm/s * @return current speed */ void GC_setSpeed(int speed = -1) { gripper->speed(speed); } /** * set and get force for next operation * @param force of grippe in range from 0 = 15N to 255 = 60N * @return current force */ void GC_setForce(int force = -1) { gripper->force(force); } /** * blocks future actions by sleeping until current action finished * @param initMode see: hasFinished() method * @param seconds minimum time to wait (1 should be fine) */ void GC_wait(bool initMode = false) { gripper->wait(initMode); } /** * check if gripper has finished current action * @param initMode check if initialiazation of gripper has finished if set, else check for all stops * @return bool */ void GC_hasFinished(bool &finished, bool initMode = false) { finished = gripper->hasFinished(initMode); } /** * returns if gripper has object detected * @param contactOnly returns object-based interruptions if true, else returns if gripper has stopped motion generally * @return bool */ void GC_hasObjectDetected(bool &detected , bool contactOnly = true) { detected = gripper->hasObjectDetected(contactOnly); } #if defined(__cplusplus) } #endif
true
96dbc42a1b44fa86a78e272fdb60900478590547
C++
Maserhe/LeetCode
/55.跳跃游戏.cpp
UTF-8
874
3.09375
3
[]
no_license
/* * @lc app=leetcode.cn id=55 lang=cpp * * [55] 跳跃游戏 */ // @lc code=start class Solution { public: /* 方法一, 差一个用例。 vector<bool> st; bool dfs(vector<int>& nums, int index) { if (index == nums.size() - 1) return true; for (int i = 1; i <= nums[index]; i ++ ) { if (index + i >= nums.size()) continue; if (st[index + i]) continue; st[index + i] = true; if (dfs(nums, index + i)) return true; } return false; } */ bool canJump(vector<int>& nums) { if (nums.size() < 2) return true; int cover = nums[0]; for (int i = 1; i <= cover; i ++ ) { cover = max(cover, nums[i] + i); if (cover >= nums.size() - 1) return true; } return false; } }; // @lc code=end
true
36ad217f6e2a5dd79f76439358264c9b12030d8a
C++
ongbe/midas
/midas_ctp/midas/CtpConfig.cpp
UTF-8
3,459
2.65625
3
[]
no_license
#include "CtpProcess.h" #include "utils/FileUtils.h" /** * first check env value, then check config value * if still not found, change config path to lower case * if still not found ,then use default value and log warning */ template <typename T> T get_cfg_value(const string& root, const char* key, const T& defaultValue = T()) { T envValue = Config::instance().getenv<T>(key, defaultValue); if (envValue != defaultValue) return envValue; auto path = root + "." + key; T configValue = Config::instance().get<T>(path, defaultValue); if (configValue != defaultValue) return configValue; configValue = Config::instance().get<T>(to_lower_case(path), defaultValue); if (configValue == defaultValue) { MIDAS_LOG_WARNING("config entry not found for " << key); } return configValue; } bool CtpProcess::configure() { const string root{"ctp"}; const string dbRoot{root + ".mysql"}; data->brokerId = get_cfg_value<string>(root, "brokerId"); data->investorId = get_cfg_value<string>(root, "investorId"); data->password = get_cfg_value<string>(root, "password"); data->tradeFront = get_cfg_value<string>(root, "tradeFront"); data->marketFront = get_cfg_value<string>(root, "marketFront"); data->dataDirectory = get_cfg_value<string>(root, "dataDirectory"); data->tradeFlowPath = data->dataDirectory + "/tradeFlowPath/"; data->marketFlowPath = data->dataDirectory + "/marketFlowPath/"; string tradingHourCfgPath = get_cfg_value<string>(root, "tradingHourCfgPath"); if (!check_file_exists(tradingHourCfgPath.c_str())) { MIDAS_LOG_ERROR(tradingHourCfgPath << " Trading Hour Cfg not exist!"); return false; } else { data->tradeStatusManager.load_trade_session(tradingHourCfgPath); } if (!check_file_exists(data->tradeFlowPath.c_str())) { MIDAS_LOG_ERROR(data->tradeFlowPath << " trade flow path not exist!"); return false; } if (!check_file_exists(data->marketFlowPath.c_str())) { MIDAS_LOG_ERROR(data->marketFlowPath << " market flow path not exist!"); return false; } if (data->brokerId.empty()) { MIDAS_LOG_ERROR("empty brokerId!"); return false; } if (data->investorId.empty()) { MIDAS_LOG_ERROR("empty investorId!"); return false; } if (data->password.empty()) { MIDAS_LOG_ERROR("empty password!"); return false; } if (data->tradeFront.empty()) { MIDAS_LOG_ERROR("empty tradeFront!"); return false; } if (data->marketFront.empty()) { MIDAS_LOG_ERROR("empty marketFront!"); return false; } DaoManager::instance().account.ip = get_cfg_value<string>(dbRoot, "ip"); DaoManager::instance().account.userName = get_cfg_value<string>(dbRoot, "userName"); DaoManager::instance().account.password = get_cfg_value<string>(dbRoot, "password"); if (!DaoManager::instance().test_connection()) { MIDAS_LOG_ERROR("database connection failed!"); return false; } MIDAS_LOG_INFO("using config" << '\n' << "brokerId: " << data->brokerId << '\n' << "investorId: " << data->investorId << '\n' << "tradeFront: " << data->tradeFront << '\n' << "marketFront: " << data->marketFront << '\n'); return true; }
true
a05800d9283dcd82f23b09cfe1a61a711aae4f7d
C++
xtrm0/PO-LEIC-2015
/P08/CPP/main.cpp
UTF-8
651
3.9375
4
[ "WTFPL" ]
permissive
#include "Cat.hpp" int main() { //1) cria dois gatos (“Tareco” com 2 anos e “Pantufa” com 6 meses); Cat *g1, *g2; g1 = new Cat(24, "Tareco"); g2 = new Cat(6, "Pantufas"); //2) escreve os gatos para um std::stringstream stringstream ss; ss << *g1 << *g2; //3) cria dois gatos não inicializados; Cat *g3, *g4; g3 = new Cat; g4 = new Cat; //4) recupera os dois primeiros gatos do stream para os objectos recém criados (que não estavam inicializados) ss >> *g3 >> *g4; //6) apresenta-os na saída (std::cout) cout << *g3; cout << *g4; //free memory: delete g1; delete g2; delete g3; delete g4; }
true
1c8b355bdee932ae9d8d1e22309e7f32bf45b8dd
C++
mtbehisseste/intelligent_surveillance
/lab1-rgb_to_hsv_log_and_invlog/rgb-to-hsv-log-and-invlog.cpp
UTF-8
2,164
2.578125
3
[]
no_license
#include "opencv2/opencv.hpp" #include <vector> #include <math.h> using namespace cv; using namespace std; int main() { Mat img = imread("lena.jpg"); imshow("jpg", img); Mat hsvImg; cvtColor(img,hsvImg,CV_BGR2HSV); int h = img.rows; int w = img.cols; Mat hsvImgSp[3]; split(hsvImg, hsvImgSp); imshow("h.jpg", hsvImgSp[0]); imshow("s.jpg", hsvImgSp[1]); imshow("v.jpg", hsvImgSp[2]); imwrite("h.jpg", hsvImgSp[0]); imwrite("s.jpg", hsvImgSp[1]); imwrite("v.jpg", hsvImgSp[2]); Mat logHsvImgSp0 = Mat::zeros(h, w, CV_32FC1); Mat logHsvImgSp1 = Mat::zeros(h, w, CV_32FC1); Mat logHsvImgSp2 = Mat::zeros(h, w, CV_32FC1); for (int i = 0; i < h; i++){ for (int j = 0; j < w; j++){ logHsvImgSp0.at<float>(i, j) = 32 * ((log(hsvImgSp[0].at<uchar>(i, j) + 1) / log(2))); logHsvImgSp1.at<float>(i, j) = 32 * ((log(hsvImgSp[1].at<uchar>(i, j) + 1) / log(2))); logHsvImgSp2.at<float>(i, j) = 32 * ((log(hsvImgSp[2].at<uchar>(i, j) + 1) / log(2))); } } imwrite("H-log.jpg", logHsvImgSp0); imwrite("S-log.jpg", logHsvImgSp1); imwrite("V-log.jpg", logHsvImgSp2); logHsvImgSp0 /= 255; logHsvImgSp1 /= 255; logHsvImgSp2 /= 255; imshow("H-log.jpg", logHsvImgSp0); imshow("S-log.jpg", logHsvImgSp1); imshow("V-log.jpg", logHsvImgSp2); Mat inlogHsvImgSp0 = Mat::zeros(h, w, CV_32FC1); Mat inlogHsvImgSp1 = Mat::zeros(h, w, CV_32FC1); Mat inlogHsvImgSp2 = Mat::zeros(h, w, CV_32FC1); for (int i = 0; i < h; i++){ for (int j = 0; j < w; j++){ inlogHsvImgSp0.at<float>(i, j) = (pow(2, (hsvImgSp[0].at<uchar>(i, j) / 32.0))) - 1; inlogHsvImgSp1.at<float>(i, j) = (pow(2, (hsvImgSp[1].at<uchar>(i, j) / 32.0))) - 1; inlogHsvImgSp2.at<float>(i, j) = (pow(2, (hsvImgSp[2].at<uchar>(i, j) / 32.0))) - 1; } } imwrite("H-invlog.jpg", inlogHsvImgSp0); imwrite("V-invlog.jpg", inlogHsvImgSp2); imwrite("S-invlog.jpg", inlogHsvImgSp1); inlogHsvImgSp0 /= 255; inlogHsvImgSp1 /= 255; inlogHsvImgSp2 /= 255; imshow("H-invlog.jpg", inlogHsvImgSp0); imshow("S-invlog.jpg", inlogHsvImgSp1); imshow("V-invlog.jpg", inlogHsvImgSp2); waitKey(0); return 0; }
true
baffb922000d2fbe5dc138041d6c76cf1725ab96
C++
Phinease/OpenCV-Learning
/week3-cpp/implementationOfMorphologicalOperations.cpp
UTF-8
2,709
2.859375
3
[]
no_license
#include <iostream> #include "dataPath.hpp" #include <opencv2/opencv.hpp> #include <opencv2/core.hpp> #include <time.h> using namespace std; using namespace cv; int main() { Mat demoImage = Mat::zeros(Size(10, 10), CV_8U); cout << demoImage << endl; imshow("image", demoImage); waitKey(0); demoImage.at<uchar>(0, 1) = 1; demoImage.at<uchar>(9, 0) = 1; demoImage.at<uchar>(8, 9) = 1; demoImage.at<uchar>(2, 2) = 1; demoImage(Range(5, 8), Range(5, 8)).setTo(1); cout << demoImage << endl; imshow("image", demoImage * 255); waitKey(0); Mat element = getStructuringElement(MORPH_CROSS, Size(3, 3)); cout << element; int ksize = element.size().height; int height, width; height = demoImage.size().height; width = demoImage.size().width; int border = ksize / 2; Mat paddedDemoImage = Mat::zeros(Size(height + border * 2, width + border * 2), CV_8UC1); copyMakeBorder(paddedDemoImage, paddedDemoImage, border, border, border, border, BORDER_CONSTANT, 0); Mat bitOR; for (int h_i = border; h_i < height + border; h_i++) { for (int w_i = border; w_i < width + border; w_i++) { if (demoImage.at<uchar>(h_i - border, w_i - border)) { cout << "White Pixel Found @ " << h_i << "," << w_i << endl; cout << paddedDemoImage(Range(h_i - border, h_i + border + 1), Range(w_i - border, w_i + border + 1)) << endl; cout << "ELEMENT: " << endl << element << endl; bitwise_or(paddedDemoImage(Range(h_i - border, h_i + border + 1), Range(w_i - border, w_i + border + 1)), element, bitOR); cout << bitOR << endl; cout << paddedDemoImage(Range(h_i - border, h_i + border + 1), Range(w_i - border, w_i + border + 1)) << endl; bitOR.copyTo(paddedDemoImage(Range(h_i - border, h_i + border + 1), Range(w_i - border, w_i + border + 1))); cout << paddedDemoImage << endl; imshow("image", paddedDemoImage * 255); waitKey(0); } } } // Crop out the original dimension from the padded output image Mat dilatedImage = paddedDemoImage(Range(border, border + height), Range(border, border + width)); imshow("image", dilatedImage * 255); waitKey(0); Mat dilatedEllipseKernel; dilate(demoImage, dilatedEllipseKernel, element); cout << dilatedEllipseKernel << endl; imshow("image", dilatedEllipseKernel * 255); waitKey(0); return 0; }
true
012dbf4efc68a4095e3499fbd3d184f33b7ec2c9
C++
IvanShevchenko135/ForCFU
/Алгоритмы и структуры данных/Первый семестр/12) Разные/ВA_12.cpp
UTF-8
796
2.765625
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> using namespace std; int main() { int hours, minutes, T; string time; cin >> T; while (T--) { cin >> time; hours = (int)(time[0] - '0'); if (hours != 0) { hours *= 10; } int tmp; tmp = (int)(time[1] - '0'); hours += tmp; minutes = (int)(time[3] - '0'); if (minutes != 0) { minutes *= 10; } tmp = (int)(time[4] - '0'); minutes += tmp; if (hours == 12) hours = 0; if (minutes != 0) hours = 12 - hours - 1; else hours = 12 - hours; minutes = 60 - minutes; if (minutes == 60) minutes = 0; if (hours == 0) hours = 12; if (hours < 10) cout << 0; cout << hours; cout << ":"; if (minutes < 10) cout << 0; cout << minutes << endl; } //ssystem("pause"); return 0; }
true
32c90931301c503cc1a769efd3bf7fafb5879fbf
C++
flavmodan/school_projects
/bancnote.cpp
UTF-8
923
2.671875
3
[]
no_license
#include <iostream> using namespace std; int n,sol[101],counter=1; int monezi[]={5,10,20,25}; void print(int v[],int k){ for(int i=k;i>=0;i--){ cout<<v[i]<<" "; } cout<<endl; } int sum(int v[],int k){ int total=0; for(int i=0;i<=k;i++){ total=total+v[i]; } return total; } int Min[100],mk=10000000; void update(int v[],int k){ for(int i=0;i<=k;i++){ Min[i]=v[i]; } } void bkt(int sol[],int k){ for(int i=4;i>=0;i--){ sol[k]=monezi[i]; if(k==0){ bkt(sol,k+1); }else{ if(sol[k]<=sol[k-1] && k<=n){ if(sum(sol,k)==n){ if(k<mk){ update(sol,k); mk=k; } cout<<"sol found "; counter++; print(sol,k); cout<<endl; }else{ bkt(sol,k+1); } } } } } int main(){ cin>>n; bkt(sol,0); cout<<"optimum sol ";print(Min,mk); cout<<counter; }
true
040327441f6b91bbc6c3bbcf179d45a10e2188cb
C++
ShahzadHafeez/My_Alpha
/assn1.cpp
UTF-8
4,428
2.921875
3
[]
no_license
#include <iostream> #include <fstream> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> #include<unistd.h> #include <cstring> using namespace std; void merge(int arr[], int L[], int R[], int n1,int n2,int l) { int i=0, j=0, k=l; while (i < n1 && j < n2) { if (L[i] < R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void mergeSort(int arr[], int l, int r) { if (l < r) { pid_t pid=0; pid_t pid2=0; int fd[2]; int fd2[2]; int piped = pipe(fd); int piped1 = pipe(fd2); int m = l+(r-l)/2; // mergeSort(arr, l, m); //mergeSort(arr, m+1, r); int n1 = m - l + 1; int n2 = r - m; int L[n1], R[n2]; for (int i = 0; i < n1; i++) //left array L[i] = arr[l + i]; for (int j = 0; j < n2; j++) //right array R[j] = arr[m + 1+ j]; //close(fd[0]); //left array to pipe write(fd[1], L, n1*sizeof(int)); // close(fd[1]); // close(fd2[0]); //right array to pipe2 write(fd2[1],R, n2*sizeof(int)); // close(fd2[1]); pid=fork(); if (pid<0) cout<<"fork error"<<endl; else if(pid==0) { if (n1<=2) { int array_receive[n1]; read(fd[0], array_receive, n1*sizeof(int)); // close(fd[0]); for(int i=0;i<n1;i++) if(array_receive[0]>array_receive[1]){ int temp=array_receive[0]; array_receive[0]=array_receive[1]; array_receive[1]=temp; } // close(fd[0]); write(fd[1],array_receive, n1*sizeof(int)); // close(fd[1]); } sleep(10);exit(0); } else { //wait(NULL); ////////////////////////////////////////////////////////// pid2=fork(); if (pid2<0) cout<<"fork error at pid2"<<endl; else if (pid==0) { if (n2<=2) { int array_receive[n2]; close(fd2[1]); read(fd2[0], array_receive, n2*sizeof(int)); close(fd2[0]); if(array_receive[0]>array_receive[1]){ int temp=array_receive[0]; array_receive[0]=array_receive[1]; array_receive[1]=temp; } close(fd2[0]); write(fd2[1],array_receive, n2*sizeof(int)); close(fd2[1]); } sleep(10);exit(0); } else { //wait(NULL); ///////////////////////////////////////////////////////// close(fd[1]); read(fd[0], L, n1*sizeof(int)); close(fd[0]); for (int t=0;t<n1;t++) cout<<L[t]<<" "<<endl;; cout<<endl; close(fd2[1]); read(fd2[0], R, n2*sizeof(int)); close(fd2[0]); for (int t=0;t<n1;t++) cout<<R[t]<<" "<<endl; cout<<endl; merge(arr, L, R, n1,n2,l); cout<<"after merge"<<endl; for (int t=0;t<n1+n2;t++) cout<<arr[t]<<" "<<endl; cout<<endl; } } } } int main() { int arr[]={'3','2','0','1'}; mergeSort(arr,0,3); return 0; }
true
ef545af654a469b2ea7440de123016168665a6b9
C++
AdityaRana-01/Bunk_Planner
/Subject.h
UTF-8
656
2.703125
3
[]
no_license
// // Created by Aditya Rana on 13-01-2020. // #ifndef BUNK_PLANNER_SUBJECT_H #define BUNK_PLANNER_SUBJECT_H #include <iostream> class Subject { public: Subject(); std::string get_name_of_subject(); static void set_min_attendance_percentage(int); void add_class_attended(); void add_class_missed(); void calc_percent_attendance(); double get_percent_attendance(); private: static int min_attendance_percentage; std::string name_of_subject; unsigned num_of_classes; unsigned num_of_classes_attended; double percent_of_attendance; }; int Subject::min_attendance_percentage = 0; #endif //BUNK_PLANNER_SUBJECT_H
true
d44d523698f3a77af20a917b72565ebbb5c83454
C++
Plopounet13/GAP
/LevelGenerator/Instance/Vec3.h
UTF-8
3,490
2.96875
3
[]
no_license
#ifndef Vec3_h #define Vec3_h #include <iostream> #include "../../WorldGenerator/geometrie.h" template <class T> class Vec3 { T x; T y; T z; public: Vec3(); Vec3(const Vec3<T>& v); Vec3(const Point& p); Vec3(T v); Vec3(T mx, T my, T mz); void rotate(const Vec3<float>& dr); void rotate(float cosx, float cosy, float cosz, float sinx, float siny, float sinz); T getx() const{ return x; } T gety() const{ return y; } T getz() const{ return z; } /** * Calcule le produit scalaire avec b */ T scalar(const Vec3<T>& b) const; /** * Opérateur de produit vectoriel */ Vec3<T> operator^(const Vec3<T>& b) const; /** * Opérateur d'addition vecteur/vecteur */ Vec3<T> operator+ (const Vec3<T>& b) const; /** * Opérateur d'addition vecteur/scalaire * Ajoute le scalaire à chaque coordonnée. */ Vec3<T> operator+ (const T& b) const; /** * Opérateur de soustraction vecteur/vecteur */ Vec3<T> operator- (const Vec3<T>& b) const; /** * Opérateur de soustraction vecteur/scalaire * Soustrait le scalaire à chaque coordonnée. */ Vec3<T> operator- (const T& b) const; /** * Opérateur d'opposé */ Vec3<T> operator- () const; /** * Opérateur de multiplication vecteur/vecteur * Multiplie les coordonnées une à une. */ Vec3<T> operator* (const Vec3<T>& b) const; /** * Opérateur de multiplication vecteur/scalaire * Multiplie par le scalaire chaque coordonnée. */ Vec3<T> operator* (const T& b) const; /** * Opérateur de division vecteur/vecteur * Divise les coordonnées une à une. */ Vec3<T> operator/ (const Vec3<T>& b) const; /** * Opérateur de division vecteur/scalaire * Divise par le scalaire chaque coordonnée. */ Vec3<T> operator/ (const T& b) const; /** * Opérateur d'addition vecteur/vecteur */ Vec3<T>& operator+= (const Vec3<T>& b); /** * Opérateur d'addition vecteur/scalaire * Ajoute le scalaire à chaque coordonnée. */ Vec3<T>& operator+= (const T& b); /** * Opérateur de soustraction vecteur/vecteur */ Vec3<T>& operator-= (const Vec3<T>& b); /** * Opérateur de soustraction vecteur/scalaire * Soustrait le scalaire à chaque coordonnée. */ Vec3<T>& operator-= (const T& b); /** * Opérateur de division vecteur/vecteur * Divise les coordonnées une à une. */ Vec3<T>& operator/= (const Vec3<T>& b); /** * Opérateur de division vecteur/scalaire * Divise par le scalaire chaque coordonnée. */ Vec3<T>& operator/= (const T& b); /** * Opérateur de multiplication vecteur/vecteur * Multiplie les coordonnées une à une. */ Vec3<T>& operator*= (const Vec3<T>& b); /** * Opérateur de multiplication vecteur/scalaire * Multiplie par le scalaire chaque coordonnée. */ Vec3<T>& operator*= (const T& b); /** * Opérateur de comparaison vecteur/vecteur * Deux vecteurs sont égaux si leurs coordonnées sont égales une à une. */ bool operator== (const Vec3<T>& b) const; /** * Opérateur d'affichage d'un vecteur * Print une coordonnée par ligne. */ friend std::ostream& operator<< (std::ostream& out, const Vec3<T>& v){ out << v.x << std::endl; out << v.y << std::endl; out << v.z; return out; } /** * Opérateur de lecture d'un vecteur * Lis les coordonnées sur le stream. */ friend std::istream& operator>> (std::istream& in, Vec3<T>& v){ in >> v.x >> v.y >> v.z; return in; } }; #endif /* Vec3_h */
true
0f3d516e8f7190e7a64453bce9b27a912d5fd85b
C++
Naveed-Naqi/Cool-Questions
/OSTest.cpp
UTF-8
246
2.96875
3
[]
no_license
#include<iostream> #include<unistd.h> #include <sys/types.h> using namespace std; int main() { pid_t pid; pid = fork(); if (pid > 0) { cout << "I am a parent\n"; } else if (pid == 0) { cout << "I am a child\n"; } return 0; }
true
1c6f8f9805738c7408dfdbdaed30acb4c3c60d30
C++
NCAR/lrose-core
/codebase/apps/Radx/src/RadxModelQc/Clutter2dQualFilter.hh
UTF-8
1,129
2.65625
3
[ "BSD-3-Clause" ]
permissive
/** * @file Clutter2dQualFilter.hh * @brief The clutter 2 dimensional quality filter * @class Clutter2dQualFilter * @brief The clutter 2 dimensional quality filter */ #ifndef CLUTTER2D_QUAL_FILTER_H #define CLUTTER2D_QUAL_FILTER_H #include <string> #include <vector> class RadxAppRayLoopData; class RadxRay; class RayxData; class Clutter2dQualFilter { public: /** * Constructor */ inline Clutter2dQualFilter() {} /** * Destructor */ inline ~Clutter2dQualFilter() {} /** * Perform filter on input, write to last arg * * output = SCR*(1-exp(-scale*|VEL|*1.5 + WIDTH*0.5)) * * @param[in] scr 'SCR' input field * @param[in] vel velocity input field * @param[in] width width input field * @param[in] scale param * @param[in] vr_shape param * @param[in] sw_shape param * @param[out] output Where to store filter output * @return true if successful * */ bool filter(const RayxData &scr, const RayxData &vel, const RayxData &width, double scale, double vr_shape, double sw_shape, RadxAppRayLoopData *output); private: }; #endif
true
a0dc8cd62e3c502ffa644771ef200cc97828e9a0
C++
jamilligioielli/LG1-LinguagemC
/Lista4Vetores/Lista4SalaExer7.cpp
UTF-8
323
2.75
3
[]
no_license
#include<stdio.h> #include<conio.h> int main () { int a[10], b[10], o, m; printf ("Entre com 9 numeros:\n"); for (o=0; o<10; o++) { scanf ("%d", &a[o]); m=9-o; b[m]=a[o]; } printf ("\n os valores invertidos:\n"); for (m=0; m<10; m++) { printf ("%d \n", b[m]); } getch (); return 0; }
true
d9c0a5c9efd06a06f121e447d55033fb317c5072
C++
usamanadeemrm7/LARAVELC
/tx.hpp
UTF-8
1,863
3.046875
3
[]
no_license
#ifndef TRANSACTION_H #define TRANSACTION_H #include <iostream> #include <string> #include <vector> #include <memory> #include <stdexcept> #include "json.hh" using json = nlohmann::json; class Transaction { public: Transaction(string txhash, string chash, string vhash); string gettxhash(void); string getchash(void); string getvhash(void); void totxString(void); json toJSON(void); private: string txhash; string chash; string vhash; // string getMerkleRoot(const vector<string> &merkle); }; // Constructor Transaction::Transaction(string txhash, string chash, string vhash) { printf("\nInitializing Transaction: %d ---- Hash: %s \n", txhash.c_str()); this->txhash = txhash; this->chash = chash; this->vhash = vhash; } string Transaction::gettxhash(void) { return this->txhash; } string Transaction::getchash(void) { return this->chash; } string Transaction::getvhash(void) { return this->vhash; } // Prints Tx data void Transaction::totxString(void) { string txdataString; for (int i = 0; i < txhash.size(); i++) txdataString += txhash[i] + ", "; printf("\n-------------------------------\n"); printf("Transaction Hash: %s\nC Hash: %s\nV Hash: %s", txhash, this->txhash.c_str(), this->chash.c_str(), vhash.c_str()); printf("\n-------------------------------\n"); } json Transaction::toJSON(void) { json j; j["txhash"] = this->txhash; j["chash"] = this->chash; j["vhash"] = this->vhash; return j; } std::string random_string() { std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); std::random_device rd; std::mt19937 generator(rd()); std::shuffle(str.begin(), str.end(), generator); return str.substr(0, 32); // assumes 32 < number of characters in str } #endif
true
8439e848f806ba2a83d48a959c84af21e94e5711
C++
yaspoon/SearchGraphs
/branch-search-src/include/Pair.h
UTF-8
747
3.359375
3
[]
no_license
/*Pair.h Brock York 14840261 AMI 300 Assignment Greedy Search Pair object implemented as a template class It is used to pass back more then on object upon return It can hold upto two different objects whose type are declared when the pair is created i.e Pair<Vertex, bool> will create a pair that holds a vertex in first and boolean in second */ #ifndef PAIR_H #define PAIR_H template <class T, class U> class Pair { public: Pair() { } virtual ~Pair() { } T first; //Has no accessors everyone has direct access if they hold the object U second;//It's not good by programming standards but it works well it's a very simple object protected: private: }; #endif // PAIR_H
true
20b699847e3f913e90d9bea1ec3f2c2abcf4bf07
C++
fsamuels/highschool-coursework
/linux.davidson.cc.nc.us/student/public/WITHDEST.CPP
UTF-8
558
3.375
3
[]
no_license
#include "withdest.h" #include <iostream.h> // for cout #include <string.h> // for strlen and strcpy withDestructor::withDestructor(char* initText) { my_chars = new char[strlen(initText) + 1]; strcpy(my_chars, initText); cout << "In constructor, my_chars: '" << my_chars << "'" << endl; } withDestructor::~withDestructor() { cout << "'" << my_chars << "' will be deleted by this destructor" << endl; delete [ ] my_chars; // Memory allocated with my_chars = new char[strlen(initText)+1]; // has now been returned back to the free store. }
true
b1322807f165d42a8bdc8b2c4953327fab950600
C++
dwelman/mod1
/src/Map.class.cpp
UTF-8
413
2.625
3
[]
no_license
#include <Map.class.h> Map::Map(int x, int y) { this->x = x; this->y = y; } Map::addPoint(float x, float y, float z) { this.points.push_back(new Point(x, y, z)); this->countPoints++; } Map::addPoint(float x, float y, float z, int reinterpolate) { this.points.push_back(new Point(x, y, z)); this->countPoints++; if (reinterpolate == M_REINTERPOLATE) { reinterpolate(); } } Map::reinterpolate() { }
true
4bb152e2c2a129789417b6d24e5334508d376fc6
C++
algbio/br-index-mems
/src/utils.hpp
UTF-8
1,722
2.890625
3
[]
no_license
#ifndef INCLUDED_BRI_UTILS_HPP #define INCLUDED_BRI_UTILS_HPP #include "definitions.hpp" namespace bri { std::string get_time(ulint time){ std::stringstream ss; if(time>=3600){ ulint h = time/3600; ulint m = (time%3600)/60; ulint s = (time%3600)%60; ss << time << " seconds. ("<< h << "h " << m << "m " << s << "s" << ")"; }else if (time>=60){ ulint m = time/60; ulint s = time%60; ss << time << " seconds. ("<< m << "m " << s << "s" << ")"; }else{ ss << time << " seconds."; } return ss.str(); } uchar bitsize(ulint x) { if (x == 0) return 1; return 64 - __builtin_clzll(x); } //parse pizza&chilli patterns header: void header_error(){ std::cout << "Error: malformed header in patterns file" << std::endl; std::cout << "Take a look here for more info on the file format: http://pizzachili.dcc.uchile.cl/experiments.html" << std::endl; exit(0); } ulint get_number_of_patterns(std::string header){ ulint start_pos = header.find("number="); if (start_pos == std::string::npos or start_pos+7>=header.size()) header_error(); start_pos += 7; ulint end_pos = header.substr(start_pos).find(" "); if (end_pos == std::string::npos) header_error(); ulint n = std::atoi(header.substr(start_pos).substr(0,end_pos).c_str()); return n; } ulint get_patterns_length(std::string header){ ulint start_pos = header.find("length="); if (start_pos == std::string::npos or start_pos+7>=header.size()) header_error(); start_pos += 7; ulint end_pos = header.substr(start_pos).find(" "); if (end_pos == std::string::npos) header_error(); ulint n = std::atoi(header.substr(start_pos).substr(0,end_pos).c_str()); return n; } }; #endif /* BRI_UTILS_HPP */
true
55166532cba205379feef583c3ba693384b92a03
C++
bharatm11/beginner_tutorials
/src/talker.cpp
UTF-8
1,737
2.8125
3
[ "BSD-3-Clause" ]
permissive
// "Copyright [2018] <Bharat Mathur>" /** @file talker.cpp * @brief talker.cpp is a node publishes a string to chatter topic * * @author Bharat Mathur (bharatm11) * @bug No known bugs. * @copyright GNU Public License. */ #include <ros/console.h> #include <sstream> #include "std_msgs/String.h" #include "ros/ros.h" #include "beginner_tutorials/ModifyString.h" std::stringstream ss; int freqRate = 20; /**@brief This function is a callback function to change the output string. * @param[in] &req is the ROS service request. * @param[out] &res is a ROS service response. * @return bool */ bool change(beginner_tutorials::ModifyString::Request &req, beginner_tutorials::ModifyString::Response &res) { ss.str(" "); if (req.num == 1) { res.name = "Now change to: Bharat"; ss<< " Bharat "; } else { res.name = "Now change to: Bharat Mathur 007"; ss<< " Bharat Mathur 007 "; } return true; } int main(int argc, char **argv) { ros::init(argc, argv, "talker"); ros::NodeHandle n; n.getParam("freq" , freqRate); ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); ros::ServiceServer service = n.advertiseService("ModifyString", change); ros::Rate loop_rate(freqRate); ROS_WARN("Default freq of 20Hz will be used if freq is not passed"); int count = 0; if (ros::ok()) { while (ros::ok()) { std_msgs::String msg; msg.data = ss.str(); ROS_INFO("%s", msg.data.c_str()); ROS_DEBUG("Publishing msgs"); chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); ++count; } } else { ROS_FATAL("Talker not initialized"); } return 0; }
true
0486611ab239e30cd1261214531a872e1fe5bb0d
C++
lxyzzzZZZ/practice
/剑指/5.8/5.8/源.cpp
GB18030
1,971
3.875
4
[]
no_license
#include <iostream> #include <stack> #include <queue> #include <deque> using namespace std; struct BinaryTreeNode { int val; BinaryTreeNode* left; BinaryTreeNode* right; }; //ջѹ뵯 static bool IsPoporder(const int* pPush, const int* pPop, int length) { if (pPush == nullptr && pPop == nullptr && length == 0) { return true; } bool flag = false; if (pPush != nullptr && pPop != nullptr && length > 0) { const int* pPushNext = pPush; const int* pPopNext = pPop; stack<int> ret; while (pPopNext - pPop < length) { //ѹѹ븨ջ ֱջԪصڵеջ while (ret.empty() || ret.top() != *pPopNext) { if (pPushNext - pPush == length) { break; } ret.push(*pPushNext); pPushNext++; } //ѹջȫѹ븨ջ ûҵ뵯ջȵԪfalse if (ret.top() != *pPopNext) { break; } ret.pop(); pPopNext++; } //Ϊ ԪȫΪtrue if (pPopNext - pPop == length && ret.empty()) { flag = true; } } return flag; } // void PrintFromTopBottom(BinaryTreeNode* Treeroot) { if (Treeroot == nullptr) { return; } //öдȡĽڵ deque<BinaryTreeNode*> ret; //ڵβ ret.push_back(Treeroot); while (ret.size() > 0) { //һڵ洢ǰڵ BinaryTreeNode* pNode = ret.front(); //Ϊͷݽ ɾ ֤˳ȷ //ұڱҽڵ ret.pop_front(); cout << pNode->val << " "; //pNodeӽڵβ if (pNode->left) { ret.push_back(pNode->left); } if (pNode->right) { ret.push_back(pNode->right); } } } int main() { int a[] = { 1,2,3,4,5 }; int b[] = { 4,6,3,2,1 }; cout << IsPoporder(a, b, 5) << endl; system("pause"); return 0; }
true
f982550022242238aee8e10b639edd38ad598c6f
C++
droidroot1995/DAFE_CPP_014
/implementation_vector/vector/vector19.cpp
UTF-8
3,120
3.171875
3
[]
no_license
#include "../vector/vector19.hpp" #include <exception> template <typename T, typename A> Vector19<T, A>::Vector19(int s) { if (s < 0) throw std::bad_alloc(); elem = alloc.allocate(s); space = s; sz = s; } template <typename T, typename A> Vector19<T, A>::Vector19(const Vector19<T, A> &v) { elem = alloc.allocate(v.capacity()); sz = v.size(); space = v.capacity(); for (int i = 0; i < sz; ++i) elem[i] = v[i]; } template <typename T, typename A> Vector19<T, A>::Vector19(std::initializer_list<T> ilt) { sz = space = ilt.size(); elem = alloc.allocate(space); int i = 0; auto inter = ilt.begin(); while (inter != ilt.end()) { elem[i] = *inter; inter++; i++; } } template <typename T, typename A> Vector19<T, A>::Vector19(Vector19 &&v) { sz = v.size(); space = v.capacity(); elem = v.elem; } template <typename T, typename A> void Vector19<T, A>::push_back(T value) { if (space == 0) reserve(8); else if (sz == space) reserve(2 * space); alloc.construct(&elem[sz], value); sz++; } template <typename T, typename A> void Vector19<T, A>::reserve(int newalloc) { if (newalloc < 0) throw std::bad_alloc(); if (newalloc <= sz) throw std::bad_alloc(); T *ptr = alloc.allocate(newalloc); for (int i = 0; i < sz; ++i) alloc.construct(&ptr[i], elem[i]); for (int i = 0; i < sz; ++i) alloc.destroy(&elem[i]); alloc.deallocate(elem, space); elem = ptr; space = newalloc; } template <typename T, typename A> void Vector19<T, A>::resize(int newsize) { if (newsize <= sz) return; if (newsize <= space) { sz = newsize; return; } reserve(newsize); sz = newsize; } template <typename T, typename A> int Vector19<T, A>::capacity() const { return space; } template <typename T, typename A> int Vector19<T, A>::size() const { return sz; } template <typename T, typename A> T &Vector19<T, A>::at(int n) { if (n >= sz || n < 0) throw std::out_of_range("at"); return elem[n]; } template <typename T, typename A> const T &Vector19<T, A>::at(int n) const { if (n >= sz || n < 0) throw std::out_of_range("at"); return elem[n]; } template <typename T, typename A> Vector19<T, A> &Vector19<T, A>::operator=(const Vector19<T, A> &v) { T *ptr = alloc.allocate(v.capacity()); for (int i = 0; i < v.size(); i++) { ptr[i] = v.at(i); } for (int i = 0; i < sz; ++i) alloc.destroy(&elem[i]); alloc.deallocate(elem, space); elem = ptr; sz = v.size(); space = v.capacity(); return *this; } template <typename T, typename A> Vector19<T, A> &Vector19<T, A>::operator=(Vector19<T, A> &&v) { space == v.capacity(); sz = v.size(); elem = v.elem; return *this; } template <typename T, typename A> const T Vector19<T, A>::operator[](int index) const { return elem[index]; } template <typename T, typename A> T &Vector19<T, A>::operator[](int index) { return elem[index]; }
true
d58de60276a82747b648e75ccf3ae92878e352fd
C++
masa-k0101/Self-Study_Cpp
/Cp7/7-2-1_trainning.cpp
UTF-8
687
3.390625
3
[]
no_license
#include<iostream> namespace A { class samp { //デフォルトでプライベート int a; protected: //sampについてはプライベートのまま int b; public: int c; samp(int n, int m) { a = n; b = m; } int geta() { return a; } int getb() { return b; } }; } main() { A::samp ob(10,20); //ob.b = 99; エラー bはプロテクトなのでプライベート ob.c = 30; //OK cはパブリック std::cout << ob.geta() << ' '; std::cout << ob.getb() << ' ' << ob.c << "\n"; return 0; }
true
cd73a595bc1bee73d720921d5a2db36db7273a85
C++
greyfrog/DFSM_SIM
/Testbed/Testbed.h
UTF-8
2,012
2.65625
3
[]
no_license
/* * Testbed.h * * Created on: Jun 27, 2021 * Author: Nutzer */ /*! \file Testbed.h * \brief Definition der Klasse Testbed * \author Thai Nguyen, Dung Tran * \date 2020 */ #include "../source/Clock.h" #include "../source/Constant.h" #include "../network/Network.h" #include "../plot/BMPPlot.h" #include "../plot/simplebmp/simplebmp.h" #ifndef TESTBED_TESTBED_H_ #define TESTBED_TESTBED_H_ /*! \class Testbed * \brief Modelliert ein Pruefstand. Diese Stellt Signalquellen, Taktsignale zur Verfuegung. Testbed uebernimmt die Simulation */ class Testbed { private: Network network_; /**< Network*/ std::map<std::string, Clock> clock_;/**< Rechecktquelle des Networks*/ std::map<std::string, Constant> constant_; /**< Konstantquelle des Networks*/ public: /*! \brief Konstruktor des Testbed * \param a_network Ein Network */ Testbed(const Network &a_network); /*! \brief Hinzufuegen die Konstantquelle des Networks * \param a_inputName Network Input * \param a_voltage gewuenschte Spannung * \return false wenn Input Name schon existiert ist, sonst hinzufuegen Konstantquelle und return true */ bool addConstantSource(const std::string &a_inputName, const sgnl::Volt a_voltage); /*! \brief Hinzufuegen die Rechteckquelle des Networks * \param a_inputName Network Input * \param a_phase Phase der Rechteckquelle * \param a_period Periode der Rechteckquelle * \return false wenn Input Name schon existiert ist, sonst hinzufuegen Rechteckquelle und return true */ bool addClockSource(const std::string &a_inputName, const sgnl::Nanoseconds a_period, const sgnl::Nanoseconds a_phase); /*! \brief Das Network muss einen Simulationsschritt durchfuehren koennen. * \param a_duration Simulationsdauer */ void simulationstep(const sgnl::Nanoseconds a_duration); /*! \brief Check ob Input Name gueltig ist * \return bool true wenn Name gueltig, sonst false */ bool assert_InputValid(const std::string &a_inputName) const; }; #endif /* TESTBED_TESTBED_H_ */
true
458c244eabb4003f105d76d94f042b9746ca64d1
C++
aleksandraniksic/MATF-ConstructCrusade
/src/init_platforms.hpp
UTF-8
8,331
2.8125
3
[]
no_license
#ifndef INIT_PLATFORMS_HPP #define INIT_PLATFORMS_HPP void init_platforms_and_enemies(std::vector<BigPlatform> &big_platforms, PlayerClass &player, Sprite &platform_sprite, std::vector<ImpEnemyClass> &imps, std::vector<WitchEnemyClass> &witches, std::vector<BatsyEnemyClass> &bats, Sprite &imp_sprite, Sprite &fireball_sprite, Sprite &witch_sprite, Sprite &poison_sprite, Sprite &batsy_sprite, Sprite &sonic_sprite, Sprite &platform_sprite_level_1, Sprite &gold_sprite ){ int platform_distance = 800; int fixed_platform_height = 500; int platform_height_offset = 140; //level 0 - height 500 - width from -4800 to 4000 for(int j = -3; j < 6; j++){ big_platforms.push_back(BigPlatform(platform_distance*j, fixed_platform_height, 8 + rand() % 3, platform_sprite_level_1, 2)); player.num_of_platforms_++; if(rand() % 101 < 35 && j > 1) imps.push_back(ImpEnemyClass(fireball_sprite, imp_sprite, gold_sprite, big_platforms[player.num_of_platforms_-1].platform_right_ - 100, big_platforms[player.num_of_platforms_-1].platform_top_ - 60, big_platforms[player.num_of_platforms_-1].platform_left_, big_platforms[player.num_of_platforms_-1].platform_right_)); else if(rand() % 101 < 35 && j > 1) bats.push_back(BatsyEnemyClass(batsy_sprite, sonic_sprite, gold_sprite, big_platforms[player.num_of_platforms_-1].platform_right_ - 100, big_platforms[player.num_of_platforms_-1].platform_top_ - 76, big_platforms[player.num_of_platforms_-1].platform_left_, big_platforms[player.num_of_platforms_-1].platform_right_)); } //stairs to level 1 for(int j = 1; j < 6; j++){ big_platforms.push_back(BigPlatform(6.3*platform_distance + platform_distance/2.5*(pow((-1),j)), fixed_platform_height - j*platform_height_offset , 7 + rand() % 3, platform_sprite_level_1, 2)); player.num_of_platforms_++; if(rand() % 101 < 25) imps.push_back(ImpEnemyClass(fireball_sprite, imp_sprite, gold_sprite, big_platforms[player.num_of_platforms_-1].platform_right_ - 100, big_platforms[player.num_of_platforms_-1].platform_top_ - 60, big_platforms[player.num_of_platforms_-1].platform_left_, big_platforms[player.num_of_platforms_-1].platform_right_)); else if(rand() % 101 < 25 && j > 1) bats.push_back(BatsyEnemyClass(batsy_sprite, sonic_sprite, gold_sprite, big_platforms[player.num_of_platforms_-1].platform_right_ - 100, big_platforms[player.num_of_platforms_-1].platform_top_ - 76, big_platforms[player.num_of_platforms_-1].platform_left_, big_platforms[player.num_of_platforms_-1].platform_right_)); } //level 1 - height -200 - width from 4000 to 0 int level_1_height = fixed_platform_height - 5*platform_height_offset; for(int j = 5; j > 0; j--){ big_platforms.push_back(BigPlatform(platform_distance*j, level_1_height, 8 + rand() % 3, platform_sprite_level_1, 3)); player.num_of_platforms_++; if(rand() % 101 < 25) imps.push_back(ImpEnemyClass(fireball_sprite, imp_sprite, gold_sprite, big_platforms[player.num_of_platforms_-1].platform_right_ - 100, big_platforms[player.num_of_platforms_-1].platform_top_ - 60, big_platforms[player.num_of_platforms_-1].platform_left_, big_platforms[player.num_of_platforms_-1].platform_right_)); else if(rand() % 101 < 25 && j > 1) bats.push_back(BatsyEnemyClass(batsy_sprite, sonic_sprite, gold_sprite, big_platforms[player.num_of_platforms_-1].platform_right_ - 100, big_platforms[player.num_of_platforms_-1].platform_top_ - 76, big_platforms[player.num_of_platforms_-1].platform_left_, big_platforms[player.num_of_platforms_-1].platform_right_)); } //stairs to level 0 for(int j = -1 ; j > -6; j--){ big_platforms.push_back(BigPlatform(platform_distance*j,level_1_height - j*platform_height_offset, 8 + rand() % 3, platform_sprite_level_1, 2)); player.num_of_platforms_++; } //level 0 again - height 500 - this is gonna be a special area at some point big_platforms.push_back(BigPlatform(platform_distance*(-7), fixed_platform_height, 25, platform_sprite_level_1, 2)); player.num_of_platforms_++; witches.push_back(WitchEnemyClass(witch_sprite, poison_sprite, gold_sprite, big_platforms[player.num_of_platforms_-1].platform_right_ - 100, big_platforms[player.num_of_platforms_-1].platform_top_ - 108, big_platforms[player.num_of_platforms_-1].platform_left_, big_platforms[player.num_of_platforms_-1].platform_right_)); //stairs to level 2 for(int j = 0 ; j > -6; j--){ big_platforms.push_back(BigPlatform(platform_distance*j,level_1_height + j*platform_height_offset, 8 + rand() % 3, platform_sprite_level_1, 4)); player.num_of_platforms_++; } for(int j = -4; j < 1; j++){ big_platforms.push_back(BigPlatform(platform_distance*j,level_1_height + (-6)*platform_height_offset + -(j+4)*platform_height_offset, 8 + rand() % 3, platform_sprite_level_1, 4)); player.num_of_platforms_++; } //level 2 - height -1600 int level_2_height = level_1_height - 10*platform_height_offset; big_platforms.push_back(BigPlatform(platform_distance, level_2_height, 25, platform_sprite_level_1, 4)); player.num_of_platforms_++; witches.push_back(WitchEnemyClass(witch_sprite, poison_sprite, gold_sprite, big_platforms[player.num_of_platforms_-1].platform_right_ - 100, big_platforms[player.num_of_platforms_-1].platform_top_ - 108, big_platforms[player.num_of_platforms_-1].platform_left_, big_platforms[player.num_of_platforms_-1].platform_right_)); //2050 for(int j = 1; j < 6; j++){ big_platforms.push_back(BigPlatform(2450 + platform_distance/2.5*(pow((-1),j)), -1600 - j*platform_height_offset , 7 + rand() % 3, platform_sprite_level_1, 5)); player.num_of_platforms_++; } big_platforms.push_back(BigPlatform(-platform_distance, -1600 - 5*platform_height_offset, 50, platform_sprite_level_1, 5)); player.num_of_platforms_++; std::cout << "plat num: " << player.num_of_platforms_ << std::endl; } #endif // INIT_PLATFORMS_HPP
true
7f425fe213441e509e52ca516b9ec633b4520954
C++
JoshRWinter/win
/win/include/win/Targa.hpp
UTF-8
474
2.65625
3
[]
no_license
#pragma once #include <win/Stream.hpp> namespace win { class Targa { public: Targa(); Targa(Stream); Targa(const Targa&) = delete; Targa(Targa&&) = default; void operator=(const Targa&) = delete; Targa &operator=(Targa&&) = default; int width() const; int height() const; int bpp() const; const unsigned char *data() const;; private: void load_image_bytes(Stream&); unsigned short w, h; unsigned char bits; std::unique_ptr<unsigned char[]> bytes; }; }
true
fbb3e26b123ffc2a32880018f21f15c22b9270f9
C++
vstdio/ood
/Command/Editor/EditorTests/ImageFileStorageMock.h
WINDOWS-1251
1,163
3.09375
3
[ "MIT" ]
permissive
#pragma once #include "../IImageFileStorage.h" // : // class ImageFileStorageMock : public IImageFileStorage { public: ImageFileStorageMock(std::ostream* output = nullptr) : m_output(output) { } std::string AddImage(const std::string& imagePath)override { m_copyFlags.emplace(imagePath, true); return imagePath; } void Delete(const std::string& path)override { if (m_output) { *m_output << "Delete " << path; } } void CopyTo(const std::string& documentPath)const override { for (auto& pair : m_copyFlags) { auto& path = pair.first; auto& copyFlag = pair.second; if (m_output && copyFlag) { *m_output << path << " copied to " << documentPath; } } } void SetCopyFlag(const std::string& filePath, bool copyFlag)override { auto found = m_copyFlags.find(filePath); if (found != m_copyFlags.end()) { found->second = copyFlag; } } private: std::ostream* m_output; std::unordered_map<std::string, bool> m_copyFlags; };
true
f387d9d9ca9a149b3c0da58d90f751a627caab71
C++
INF112-Programacao2/20202-team-2
/cliente.cpp
UTF-8
737
2.96875
3
[]
no_license
#include <iostream> #include <string> #include "cliente.h" Cliente::Cliente(int id, std::string nome, std::string telefone, std::string endereco) : _id(id), _nome(nome), _telefone(telefone), _endereco(endereco) {} int Cliente::getId(){ return _id; } void Cliente::setId(int id){ _id = id; } std::string Cliente::getNome(){ return _nome; } void Cliente::setNome(std::string nome){ _nome = nome; } std::string Cliente::getTelefone(){ return _telefone; } void Cliente::setTelefone(std::string telefone){ _telefone = telefone; } std::string Cliente::getEndereco(){ return _endereco; } void Cliente::setEndereco(std::string endereco){ _endereco = endereco; }
true
f9ea3741dbf884044fd966468e6f9b60da96c84c
C++
bluespeck/OakVR
/src/Core/ResourceManager/EmptyResource.h
UTF-8
582
2.65625
3
[ "MIT" ]
permissive
// this is a placeholder resource, used to keep track of // a resource through the loading process; under normal // circumstances, it shouldn't be used in user code #pragma once #include "ResourceManager/IResource.h" namespace oakvr { class EmptyResource : public IResource { public: EmptyResource(const oakvr::StringId &id): IResource(id) { m_type = "EmptyResource"; } ~EmptyResource() {} protected: virtual auto Init() -> void{}; virtual auto Load() -> void{}; virtual auto Reload() -> void{}; virtual auto Release() -> void{}; }; } // end namespace oakvr
true
76e8c838107db1e696a59e51fc07e12eab7a66dd
C++
omya2003/SEM-III
/nmimsmarks.cpp
UTF-8
1,613
3.421875
3
[]
no_license
#include <iostream> #include <conio.h> using namespace std; class TEE; class ICA { float math; float oop; float se; float ds; public: void readIcaMarks(void) { cout << "\n\nENTER ICA MARKS" << endl; cout << "\nEnter ICA Marks obtained in Maths: "; cin >> math; cout << "Enter ICA Marks obtained in OOP: "; cin >> oop; cout << "Enter ICA Marks obtained in SE: "; cin >> se; cout << "Enter ICA Marks obtained in DS: "; cin >> ds; } friend void calculate(ICA, TEE); }; class TEE { float math; float oop; float se; float ds; public: void readTeeMarks() { cout << "\n\nENTER TEE MARKS" << endl; cout << "\nEnter TEE Marks obtained in Maths: "; cin >> math; cout << "Enter TEE Marks obtained in OOP: "; cin >> oop; cout << "Enter TEE Marks obtained in SE: "; cin >> se; cout << "Enter TEE Marks obtained in DS: "; cin >> ds; } friend void calculate(ICA, TEE); }; void calculate(ICA I, TEE T) { cout << "\n\nRESULT OF CANDIDATE:" << endl; cout << "\nTotal marks in Maths: " << I.math + T.math << endl; cout << "Total marks in OOP: " << I.oop + T.oop << endl; cout << "Total marks in SE: " << I.se + T.se << endl; cout << "Total marks in DS: " << I.ds + T.ds << endl << endl; } int main() { TEE T; ICA I; I.readIcaMarks(); T.readTeeMarks(); calculate(I, T); getch(); }
true