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
70078ac12649e7d9f4222947544e3b01493ff035
C++
ShuoWillWang/EE569_HW4
/C/Kmeans2_main.cpp
UTF-8
10,743
2.734375
3
[]
no_license
// EE 569 Homework #4 // date: Apr. 23th, 2017 // Name: Shuo Wang // ID: 8749390300 // email: wang133@usc.edu // Compiled on WINDOWS 10 with Visual C++ and Opencv 3.2 // solution for Problem 1 (c) The K-means for the second convolution layer // Directly open the Kmeans2.exe to run the program #include <iostream> #include <vector> #include <opencv2\opencv.hpp> #include <opencv2\highgui\highgui.hpp> #include <Windows.h> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <iterator> using namespace std; using namespace cv; Mat srcF(14 * 14 * 50000, 6, CV_32FC1, Scalar(0)); Mat srcFi(10 * 10 * 50000, 150, CV_32FC1, Scalar(0)); int a5[6] = { 0 }; int WriteData(string fileName, cv::Mat& matData) { int retVal = 0; ofstream outFile(fileName.c_str(), ios_base::out); if (!outFile.is_open()) { cout << "Fail to open. " << endl; retVal = -1; return (retVal); } if (matData.empty()) { cout << "Matrix is NULL" << endl; retVal = 1; return (retVal); } for (int r = 0; r < matData.rows; r++) { for (int c = 0; c < matData.cols; c++) { float data = matData.at<float>(r, c); outFile << data << "\t"; } outFile << endl; } return (retVal); } int LoadData(string fileName, cv::Mat& matData, int matRows = 0, int matCols = 0, int matChns = 0) { int retVal = 0; ifstream inFile(fileName.c_str(), ios_base::in); if (!inFile.is_open()) { cout << "Read Faliure. " << endl; retVal = -1; return (retVal); } istream_iterator<float> begin(inFile); istream_iterator<float> end; vector<float> inData(begin, end); cv::Mat tmpMat = cv::Mat(inData); size_t dataLength = inData.size(); if (matChns == 0)//channel number { matChns = 1; } if (matRows != 0 && matCols == 0) { matCols = dataLength / matChns / matRows; } else if (matCols != 0 && matRows == 0) { matRows = dataLength / matChns / matCols; } else if (matCols == 0 && matRows == 0) { matRows = dataLength / matChns; matCols = 1; } if (dataLength != (matRows * matCols * matChns)) { cout << "Default Output" << endl; retVal = 1; matChns = 1; matRows = dataLength; } matData = tmpMat.reshape(matChns, matRows).clone(); return (retVal); } int main() { int type; cout << "What thing do you want to do: 1) Save the data; 2) Load the data and compute: "; cin >> type; if (type == 1) { float Fil[6][75] = { 0 }; ifstream infile; infile.open("D:/EE569_Assignment/4/C++/Kmeans/x64/Debug/Weight_W.txt");//Load the weight number of the first layer float* ptr = &Fil[0][0]; while (!infile.eof()) { infile >> *ptr; ptr++; } infile.close(); Mat FILTER(6, 75, CV_32FC1); int bgr[75] = { 0 }; for (int i = 0; i < 25; i++) { bgr[i] = i + 50; bgr[i + 25] = i + 25; bgr[i + 50] = i + 0; } for (int n = 0; n < 6; n++) { for (int d = 0; d < 75; d++) { FILTER.at<float>(n, d) = Fil[n][bgr[d]]; } } //cout << FILTER << endl; for (int fol = 0; fol < 5; fol++) { for (int ima = 0; ima < 10000; ima = ima + 1) { char buffer[50]; _itoa(ima, buffer, 10); char file_address[5][56] = { "D:/EE569_Assignment/4/C++/CIFAR/x64/Debug/data_batch_1/", "D:/EE569_Assignment/4/C++/CIFAR/x64/Debug/data_batch_2/", "D:/EE569_Assignment/4/C++/CIFAR/x64/Debug/data_batch_3/", "D:/EE569_Assignment/4/C++/CIFAR/x64/Debug/data_batch_4/", "D:/EE569_Assignment/4/C++/CIFAR/x64/Debug/data_batch_5/" }; Mat src = imread(strcat(file_address[fol], strcat(buffer, ".jpg")));//open the image Mat srck(1, 75, CV_32FC1, Scalar(0)); Mat srcc((src.rows - 4) * (src.cols - 4), 6, CV_32FC1, Scalar(0)); Mat srccm(14 * 14, 6, CV_32FC1, Scalar(0)); int s0 = 0; for (int i = 2; i < src.rows - 2; i++) { for (int j = 2; j < src.cols - 2; j++) { int ss = 0; for (int m = -2; m < 3; m++) { for (int n = -2; n < 3; n++) { srck.at<float>(0, ss) = (float)src.at<Vec3b>(i + m, j + n)[0]; srck.at<float>(0, 25 + ss) = (float)src.at<Vec3b>(i + m, j + n)[1]; srck.at<float>(0, 50 + ss) = (float)src.at<Vec3b>(i + m, j + n)[2]; ss++; } } for (int n = 0; n < 6; n++) { float sum = 0; for (int k = 0; k < 75; k++) { sum = sum + srck.at<float>(0, k) * FILTER.at<float>(n, k);//calculate the initial output of first layer } srcc.at<float>(s0, n) = sum; } s0++; } } for (int j = 0; j < 6; j++) { for (int i0 = 0; i0 < 14; i0++) { for (int j0 = 0; j0 < 14; j0++) { Mat srcmax(2, 2, CV_32FC1); srcmax.at<float>(0, 0) = srcc.at<float>(28 * 2 * i0 + 2 * j0, j); srcmax.at<float>(0, 1) = srcc.at<float>(28 * 2 * i0 + 2 * j0 + 1, j); srcmax.at<float>(1, 0) = srcc.at<float>(28 * (2 * i0 + 1) + 2 * j0, j); srcmax.at<float>(1, 1) = srcc.at<float>(28 * (2 * i0 + 1) + 2 * j0 + 1, j); double maxi, mini; minMaxLoc(srcmax, &mini, &maxi); srccm.at<float>(14 * i0 + j0, j) = maxi;//max-pooling } } Mat mean(2, 2, CV_64FC1), stddev(2, 2, CV_64FC1); Mat srccmi(14 * 14, 1, CV_32FC1, Scalar(0)); for (int i = 0; i < 14 * 14; i++) { srccmi.at<float>(i, 0) = srccm.at<float>(i, j); } meanStdDev(srccmi, mean, stddev); for (int i = 0; i < 14 * 14; i++) { srccm.at<float>(i, j) = srccm.at<float>(i, j) - mean.at<double>(0, 0); } } //cout << srccm << endl; //system("pause"); for (int i = 0; i < 14 * 14; i++) { for (int j = 0; j < 6; j++) { srcF.at<float>(14 * 14 * (fol * 10000 + (int)ima) + i, j) = srccm.at<float>(i, j); } } } } string fileName = "D:/EE569_Assignment/4/C++/Kmeans2/x64/Debug/Raw_Data.txt";//save the input data of the second convolution layer WriteData(fileName, srcF); system("pause"); return 0; } else { string fileName = "D:/EE569_Assignment/4/C++/Kmeans2/x64/Debug/Raw_Data.txt"; LoadData(fileName, srcF, 14 * 14 * 50000, 6); //cout << srcF << endl; } int sa[50001] = { 0 }; for (int ima = 0; ima < 50000; ima++) { Mat srck(10 * 10, 150, CV_32FC1, Scalar(0)); Mat srcc(1, 150, CV_32FC1, Scalar(0)); int s0 = 0; for (int i = 2; i < 14 - 2; i = i + 1) { for (int j = 2; j < 14 - 2; j = j + 1) { int ss = 0; for (int m = -2; m < 3; m++) { for (int n = -2; n < 3; n++) { srcc.at<float>(0, ss) = srcF.at<float>(14 * 14 * ima + 14 * (i + m) + j + n, 0); srcc.at<float>(0, ss + 25) = srcF.at<float>(14 * 14 * ima + 14 * (i + m) + j + n, 1); srcc.at<float>(0, ss + 50) = srcF.at<float>(14 * 14 * ima + 14 * (i + m) + j + n, 2); srcc.at<float>(0, ss + 75) = srcF.at<float>(14 * 14 * ima + 14 * (i + m) + j + n, 3); srcc.at<float>(0, ss + 100) = srcF.at<float>(14 * 14 * ima + 14 * (i + m) + j + n, 4); srcc.at<float>(0, ss + 125) = srcF.at<float>(14 * 14 * ima + 14 * (i + m) + j + n, 5); ss++; } } Mat mean(2, 2, CV_64FC1), stddev(2, 2, CV_64FC1); meanStdDev(srcc, mean, stddev); if (stddev.at<double>(0, 0) >= 30.0)//filter the patch with small std { for (int s = 0; s < 150; s++) { srck.at<float>(s0, s) = srcc.at<float>(0, s); } s0++; } } } int sum = 0; for (int i = 0; i < ima + 1; i++) { sum = sum + sa[i]; } for (int i = 0; i < s0; i++) { for (int j = 0; j < 150; j++) { srcFi.at<float>(sum + i, j) = srck.at<float>(i, j); } } sa[ima + 1] = s0; //cout << s0 << endl; //system("pause"); } int summF = 0; for (int i = 1; i < 50001; i++) { summF = summF + sa[i]; } //cout << summF << endl; //system("pause"); int sumFF = (int)summF / 1; //system("pause"); Mat bestLabels(summF, 1, CV_32FC1); Mat center(16, 150, CV_32FC1); kmeans(srcFi, 16, bestLabels, TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 300, 1), 3, KMEANS_PP_CENTERS, center);//do the K-means cout << "The center is: " << endl; char *aaa = { "D:/EE569_Assignment/4/C++/Kmeans2/x64/Debug/Weight.txt" };//save the original centroid ofstream outfile; outfile.open(aaa); if (outfile.is_open()) { for (int n = 0; n < 16; n++) { for (int d = 0; d < 150; d++) { outfile << center.at<float>(n, d) << '\t'; } } } outfile.close(); cout << format(center, Formatter::FMT_PYTHON) << endl; float Fil2[16][150] = { 0 }; ifstream infile; infile.open("D:/EE569_Assignment/4/C++/Kmeans2/x64/Debug/Weight.txt"); float* ptr1 = &Fil2[0][0]; while (!infile.eof()) { infile >> *ptr1; ptr1++; } infile.close(); for (int n = 0; n < 16; n++) { double norm1 = 0, norm2 = 0, norm3 = 0, norm4 = 0, norm5 = 0, norm6 = 0; for (int i = 0; i < 150; i++) { norm1 = norm1 + (Fil2[n][i]); //norm2 = norm2 + abs(Fil2[n][25 + i]); //norm3 = norm3 + abs(Fil2[n][50 + i]); //norm4 = norm4 + abs(Fil2[n][75 + i]); //norm5 = norm5 + abs(Fil2[n][100 + i]); //norm6 = norm6 + abs(Fil2[n][125 + i]); } for (int i = 0; i < 150; i++) { Fil2[n][i] = Fil2[n][i] / norm1; //Fil2[n][25 + i] = Fil2[n][25 + i] / norm2; //Fil2[n][50 + i] = Fil2[n][50 + i] / norm3; //Fil2[n][75 + i] = Fil2[n][75 + i] / norm4; //Fil2[n][100 + i] = Fil2[n][100 + i] / norm5; //Fil2[n][125 + i] = Fil2[n][125 + i] / norm6; } } char *aaa1 = { "D:/EE569_Assignment/4/C++/Kmeans2/x64/Debug/Weight_W.txt" };//save the normalized centroid, which is the initialized parameter of the first layer //ofstream outfile; outfile.open(aaa1); if (outfile.is_open()) { for (int n = 0; n < 16; n++) { for (int d = 0; d < 150; d++) { outfile << Fil2[n][d] << '\t'; } } } outfile.close(); float Filaa[5][5][6][16] = { 0 }; for (int n = 0; n < 16; n++) { for (int s = 0; s < 6; s++) { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { Filaa[i][j][s][n] = Fil2[n][25 * s + 5 * i + j]; } } } } char *aaa11 = { "D:/EE569_Assignment/4/C++/Kmeans2/x64/Debug/Weight_Wa.txt" }; outfile.open(aaa11); if (outfile.is_open()) { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { for (int s = 0; s < 6; s++) { for (int n = 0; n < 16; n++) { outfile << Filaa[i][j][s][n] << '\t'; } } } } } outfile.close(); system("pause"); system("pause"); }
true
f904ee6542b1764b12a5da0e9e9aa7d1705d7709
C++
punkproger/Project-Euler
/Problem 52/main.cpp
UTF-8
945
3.34375
3
[]
no_license
#include <iostream> #include <string> #include <cmath> using ull = unsigned long long; size_t countDigits(ull number) { size_t digs{0}; do { ++digs; } while(number/=10); return digs; } bool haveSameNumbers(ull f_num, ull s_num) { int f_digs[10] = {0}; int s_digs[10] = {0}; while(f_num) { ++f_digs[f_num%10]; f_num /= 10; } while(s_num) { ++s_digs[s_num%10]; s_num /= 10; } for(int i = 0; i < 10; ++i) { if(f_digs[i] != s_digs[i]) { return false; } } return true; } bool isPermutedMultiple(ull number) { for(ull i = 2; i <= 6; ++i) { if(!haveSameNumbers(number, number * i)) { return false; } } return true; } int main() { ull current = 123; for(current;;++current) { if(countDigits(current) != countDigits(current * 6)) { current = pow(10, countDigits(current)); continue; } if(isPermutedMultiple(current)) { break; } } std::cout << current << std::endl; return 0; }
true
328eb3442e648fd5a68686b64df8dc118941a04e
C++
kangdaeki/windowsnetworkprogramming
/WinThread/ExThread2.cpp
UTF-8
559
2.796875
3
[]
no_license
#include <windows.h> #include <stdio.h> DWORD WINAPI MyThread(LPVOID arg) { while (1) ; return 0; } int main (int argc, char *argv[]) { SYSTEM_INFO si; GetSystemInfo(&si); fprintf(stdout, "# of CPUs = %d\n",(int)si.dwNumberOfProcessors); for (int i=0; i<(int)si.dwNumberOfProcessors; i++) { HANDLE hThread = CreateThread(NULL, 0, MyThread, NULL, 0, NULL); if (NULL == hThread) return 1; SetThreadPriority(hThread, THREAD_PRIORITY_TIME_CRITICAL); CloseHandle(hThread); } Sleep(1000); fprintf(stdout, "Running main()\n"); return 0; }
true
4c61242dca2df6133f3b3ab2423c5616638c5027
C++
atheros/arcade-paic
/paic.ino
UTF-8
8,417
2.765625
3
[]
no_license
#include <EEPROM.h> #include "Cmd.h" #define VERSION "1.0.0" // maximum input lines #define MAX_INPUT 12 // keyboard values char outputKeys[MAX_INPUT]; // pin numbers char inputPins[MAX_INPUT]; // the state of pressed buttons int16_t inputState = 0; // is debugging on bool debug = false; // has the serial connection been initialized int hasSerial = false; // controller name char controllerName[17]; void initPins() { // initialize pins for(int i = 0; i < MAX_INPUT; i++) { pinMode(inputPins[i], INPUT); digitalWrite(inputPins[i], HIGH); } } void loadDefaults() { inputPins[0] = 2; inputPins[1] = 3; inputPins[2] = 4; inputPins[3] = 5; inputPins[4] = 6; inputPins[5] = 7; inputPins[6] = 8; inputPins[7] = 9; inputPins[8] = 10; inputPins[9] = 16; inputPins[10] = 14; inputPins[11] = 15; outputKeys[0] = 'a'; outputKeys[1] = 'b'; outputKeys[2] = 'c'; outputKeys[3] = 'd'; outputKeys[4] = 'e'; outputKeys[5] = 'f'; outputKeys[6] = 'g'; outputKeys[7] = 'h'; outputKeys[8] = 'i'; outputKeys[9] = 'j'; outputKeys[10] = 'k'; outputKeys[11] = 'l'; strcpy(controllerName, "unnamed-ctrl"); initPins(); } void writeToEeprom() { int i; int checksum = 127; int offset = 0; for(i = 0; i < MAX_INPUT; i++) { EEPROM.write(offset, inputPins[i]); checksum = (checksum + inputPins[i]) % 255; offset++; } for(i = 0; i < MAX_INPUT; i++) { EEPROM.write(offset, outputKeys[i]); checksum = (checksum + outputKeys[i]) % 255; offset++; } for(i = 0; i < sizeof(controllerName); i++) { EEPROM.write(offset, controllerName[i]); checksum = (checksum + controllerName[i]) % 255; offset++; } EEPROM.write(offset, checksum); } void readFromEeprom() { int eChecksum; int i; int checksum = 127; int offset = 0; for(i = 0; i < MAX_INPUT; i++) { inputPins[i] = EEPROM.read(offset); checksum = (checksum + inputPins[i]) % 255; offset++; } for(i = 0; i < MAX_INPUT; i++) { outputKeys[i] = EEPROM.read(offset); checksum = (checksum + outputKeys[i]) % 255; offset++; } for(i = 0; i < sizeof(controllerName); i++) { controllerName[i] = EEPROM.read(offset); checksum = (checksum + controllerName[i]) % 255; offset++; } eChecksum = EEPROM.read(offset); if (eChecksum != checksum) { if (Serial) { Serial.print("Error: Checksum mismatch for EEPROM: "); Serial.print(eChecksum); Serial.print(" vs calculated "); Serial.println(checksum); } loadDefaults(); } else { initPins(); } } void cmdStore(int argc, char **argv) { if (argc != 1) { Serial.print("Error: store expects no arguments, but "); Serial.print(argc - 1); Serial.println(" given."); return; } writeToEeprom(); Serial.println("done."); } void cmdLoad(int argc, char **argv) { if (argc != 1) { Serial.print("Error: load expects no arguments, but "); Serial.print(argc - 1); Serial.println(" given."); return; } readFromEeprom(); Serial.println("done."); } void cmdDebug(int argc, char **argv) { if (argc == 1) { if (debug) { Serial.println("Debug is on."); } else { Serial.println("Debug is off."); } return; } if (argc != 2) { Serial.print("Error: debug expects 1 argument, but "); Serial.print(argc - 1); Serial.println(" given."); return; } if (strcmp(argv[1], "1") == 0) { debug = true; Serial.println("Debug on."); } else if (strcmp(argv[1], "0") == 0) { debug = false; Serial.println("Debug off."); } else { Serial.print("Error: debug expects argument 1 to be eighter 1 or 0, but found "); Serial.print(argv[1]); Serial.println("."); } } void cmdDefaults(int argc, char **argv) { if (argc != 1) { Serial.print("Error: store expects no arguments, but "); Serial.print(argc - 1); Serial.println(" given."); return; } loadDefaults(); Serial.println("done."); } void cmdButton(int argc, char **argv) { if (argc != 3) { Serial.print("usage: button input_num output_char"); Serial.print(argc - 1); Serial.println(" given."); return; } if (strlen(argv[2]) != 1) { Serial.println("Error: output_char must be a single character."); return; } int input = atoi(argv[1]); if (input < 0 || input > MAX_INPUT) { Serial.print("Error: input_num must be between 0 and "); Serial.print(MAX_INPUT); Serial.println("."); return; } outputKeys[input] = argv[2][0]; Serial.println("done."); } void cmdDump(int argc, char **argv) { char buff[16]; if (argc != 1) { Serial.print("Error: store expects no arguments, but "); Serial.print(argc - 1); Serial.println(" given."); return; } Serial.println(" # PIN CHAR"); for(int i = 0; i < MAX_INPUT; i++) { snprintf(buff, 16, "%2d %3d %4c\n", i, inputPins[i], outputKeys[i]); Serial.print(buff); } } void cmdName(int argc, char **argv) { if (argc == 1) { Serial.print("Controller name is "); Serial.print(controllerName); Serial.println("."); } else if (argc == 2) { if (strlen(argv[1]) > 16) { Serial.println("Error: Controller name must not exceed 16 characters."); return; } strcpy(controllerName, argv[1]); Serial.println("done."); } else { Serial.println("usage: name [new_name]"); } } void cmdHelp(int argc, char **argv) { Serial.println("button - change button configuration."); Serial.println("store - store current buttons setup in EEPROM memory."); Serial.println("load - loads buttons setup from EEPROM memory."); Serial.println("name - changes controller name."); Serial.println("defaults - replace current buttons setup with default values."); Serial.println("dump - dumps current buttons setup."); Serial.println("debug - changes debugging mode."); Serial.println("help - list commands."); } void setup() { cmdInit(115200); Keyboard.begin(); cmdAdd("store", cmdStore); cmdAdd("load", cmdLoad); cmdAdd("debug", cmdDebug); cmdAdd("defaults", cmdDefaults); cmdAdd("button", cmdButton); cmdAdd("dump", cmdDump); cmdAdd("name", cmdName); cmdAdd("help", cmdHelp); readFromEeprom(); } void loop() { int newState, oldState; // put your main code here, to run repeatedly: if (Serial && !hasSerial) { // serial just connected hasSerial = true; Serial.println("P.A.I.C. - Programmable Arcade Input Controller - version " VERSION); Serial.print("Controller name: "); Serial.println(controllerName); cmdPrompt(); } else if (!Serial && hasSerial) { // serial just disconnected hasSerial = false; cmdReset(); } if (Serial && hasSerial) { // serial is connected cmdPoll(); } for(int i = 0; i < MAX_INPUT; i++) { newState = digitalRead(inputPins[i]) == LOW ? 1 : 0; oldState = (inputState & (1 << i)) ? 1 : 0; if (newState == oldState) { // state didn't change, continue continue; } else if (newState == 1) { // key was pressed if (debug && Serial) { Serial.print(i); Serial.println(" was pressed"); } Keyboard.press(outputKeys[i]); inputState = inputState | (1 << i); } else if (oldState == 1) { // key was released if (debug && Serial) { Serial.print(i); Serial.println(" was released"); } Keyboard.release(outputKeys[i]); inputState = inputState & ~(1 << i); } } delay(20); }
true
b0c9b29bdb26110529d523eac9f833ecfd6f4a33
C++
arnisritins/Olimps
/pulkst.cpp
UTF-8
910
3.265625
3
[]
no_license
#include <fstream> #include <string> #include <sstream> using namespace std; bool same_chars(string str1, string str2){ int pos; for(int i = 0; i < 4; i++){ pos = str2.find(str1[i]); if(pos != -1) str2.erase(pos, 1); } return str2.size() == 0; } void plus_minute(int &h, int &m){ if(m == 59){ m = 0; h++; } else m++; if(h == 24) h = 0; } int main(){ int h, m; char delimiter; string str, start_time, end_time; ifstream in("pulkst.dat"); in >> str; in.close(); in.open("pulkst.dat"); in >> h >> delimiter >> m; in.close(); start_time = str.erase(2, 1); while(true){ plus_minute(h, m); ostringstream ss; ss.fill('0'); ss.width(2); ss << h; ss.fill('0'); ss.width(2); ss << m; end_time = ss.str(); if(same_chars(start_time, end_time)) break; } ofstream out("pulkst.rez"); out << end_time.insert(2, ":"); out.close(); return 0; }
true
fc4a1c5ee967194323d83805e714791c70dc6612
C++
Gerwand/opengrl
/OpenGRL/include/grl/track/TrackRecorderQueue.h
UTF-8
2,619
3.28125
3
[]
no_license
#pragma once #include <grl/track/TrackRecorder.h> #include <grl/track/TrackOffsets.h> namespace grl { /** * This implementation of the recorder is meant to be used as a buffer for * all points with possibility to quickly remove oldest point whenever newer one * must be added. */ class TrackRecorderQueue : private TrackRecorder { public: /** * Default constructor, doing nothing. */ TrackRecorderQueue(); /** * Constructor, which is initializing the recorder with the given parameters. * * @param minOffset Minimum offset of the point that is considered to be * added to the track. If the bufferLen > 1, the offset of the median * point is considered. * @param step How many frames will be buffered until the median from points is considered to be added to a track. * @param bufferLen Max number of points that can be saved in the recorder. * @param maxTrackSize Max size of the track queue. */ TrackRecorderQueue(float minOffset, uint8_t skip, size_t bufferLen, size_t maxTrackSize); /** * Clear the track saved in the recorder and reset recorder to the initial * state. */ void clear(); /** * Convert all currently buffered points into the Track<T>. * * @param[out] track to which the buffer should be saved. * @tparam T the type of the elements which are representing the track. */ template <typename T> void getTrack(Track<T> &track) const; /** * Add point to the recorder. This function will return flag which will * indicate what happened inside: * - grlRecorderPointBuffered - the point was successfully added to a buffer. * - grlRecorderPointAdded - the point was successfully added to a queue. * - grlRecorderPointSkipped - the point was skipped, because the distance wasn't big enough. * * @returns flag what happened with the point. */ RecorderState addPoint(Vec3f point) override; /** * Return number of points currently hold in the queue. * * @returns number of points in the queue */ size_t getTrackSize(); private: // For faster remove of the last/first points, use the dequeue instead // of TrackPoints, which is using the vector inside. std::deque<Vec3f> _trackPointsQueue; void enqueuePoint(Vec3f point); }; template <typename T> void TrackRecorderQueue::getTrack(Track<T> &track) const { track.clear(); for (auto it = _trackPointsQueue.cbegin(); it != _trackPointsQueue.cend(); ++it) track.addPoint(*it); } }
true
2e3ae837f8d67a0436b64c14fad41c8f407bd84e
C++
zhongershun/data-structure
/MyQueue/main.cpp
UTF-8
370
2.90625
3
[]
no_license
#include"MyQueue.h" #include"MyQueue.cpp" #include<iostream> using namespace std; int main() { MyQueue<int> Q; int n; cin>>n; int item; for (int i = 0; i < n; i++) { cin>>item; Q.append(item); } for (int i = 0; i < n; i++) { Q.serve(item); cout<<item<<"\t"; Q.retrieve(); } return 0; }
true
d8b0850a42b6a1c68d3c5cd5230274ad11d211a4
C++
Habil-Ndiamoun/420-W48-SF
/Module11_ESP32_ServeurWeb/AMOC_Module11_ServeurWebPrepExercices/include/Actionneur.h
UTF-8
343
2.671875
3
[ "CC0-1.0" ]
permissive
#pragma once #include <Arduino.h> class Actionneur { public: Actionneur(int const &p_id, String const& p_description); const String& description() const; int id() const; virtual void allumer() = 0; virtual void eteindre() = 0; virtual bool estAllume() const = 0; private: int m_id; String m_description; };
true
62d4dee80a001cc45ace6830c069b954fe65e47d
C++
Hepta4413/PLD_COMP
/src/Ligne.cpp
UTF-8
726
2.703125
3
[]
no_license
#include "Ligne.h" #include <iostream> using namespace std; Ligne::Ligne() { #ifdef MAP cout << "Appel au constructeur vide de Ligne" << endl; #endif typeContenu = _LIGNE; } void Ligne::AddLigneColonne(int ligne,int colonne) { #ifdef MAP cout << "Appel a la fonction AddLigneColonne de Ligne(int ligne, int colonne)" << endl; #endif this->ligne=ligne; this->colonne=colonne; } int Ligne::getLigne() { #ifdef MAP cout << "Appel a la fonction getLigne de Ligne" << endl; #endif return ligne; } int Ligne::getColonne() { #ifdef MAP cout << "Appel a la fonction getColonne de Ligne" << endl; #endif return colonne; } int Ligne::getSize() { return 0; } string Ligne::buildIR(CFG * cfg) { return ""; }
true
826c520a74f5bfed5342f6d12858883cd334314c
C++
LeeJehwan/Baekjoon-Online-Judge
/code/01644_소수의 연속합.cpp
UTF-8
768
2.53125
3
[]
no_license
#include <iostream> #include <set> #include <string> #include <vector> #include <algorithm> using namespace std; int prime[4000001]; bool count_p[4000001]; int cnt = 0; void eratos() { for (int i = 2; i <= 4000000; i++) { if (count_p[i] == false) prime[cnt++] = i; for (int j = i * 2; j <= 4000000; j += i) count_p[j] = true; } } int main() { ios::sync_with_stdio(false); cin.tie(NULL); eratos(); int n; cin >> n; int ans = 0; int i = 0, j = 0; long long sum = 0; while (1) { if (j == i + 1 && prime[i] > n) break; if (i == j) { sum += prime[j++]; } else if (sum > n) { sum -= prime[i++]; } else if (sum == n) { ans++; sum -= prime[i++]; } else if (sum < n) { sum += prime[j++]; } } cout << ans << endl; }
true
5aafc5bd9e5b1841c99c1e371179a0b985cac7f9
C++
xiaogaogaoxiao/SP-dock
/src/graph/patch.cpp
UTF-8
4,805
2.578125
3
[]
no_license
#include "../../inc/graph/patch.h" #include "../../inc/math/linalg.h" #include <iostream> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_access.hpp> #include <glm/gtx/string_cast.hpp> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_blas.h> //------------------------------------------------------------------- //-------------------------- INTERNAL ------------------------------- //------------------------------------------------------------------- static void build_vector_of_points(const std::vector<Node>& nodes, const std::vector<int>& patch, std::vector<glm::dvec3>& out) { for(auto it = patch.begin(); it != patch.end(); ++it) out.push_back( nodes[*it].get_pos() ); } static void least_evec_eval(const glm::dmat3 evec, const glm::dvec3 eval, glm::dvec3& least_evec, double& least_eval) { int least_i = 0; for(int i = 0; i < 3; i++) if( eval[i] < eval[least_i] ) least_i = i; least_eval = least_i; least_evec = glm::column(evec, least_i); } static void principal_component_analysis(const std::vector<glm::dvec3>& points, glm::dmat3& out_eigen_vec, glm::dvec3& out_eigen_val) { //3 rows, n columns int nrows = 3, ncolumns = points.size(); gsl_matrix* data = gsl_matrix_alloc(nrows, ncolumns); //Build matrix where each column is one of the points in region for(int i = 0; i < ncolumns; i++) { //Set column i with px, py and pz gsl_matrix_set(data, 0, i, points[i][0]); gsl_matrix_set(data, 1, i, points[i][1]); gsl_matrix_set(data, 2, i, points[i][2]); } //transpose matrix gsl_matrix* data_t = gsl_matrix_alloc(ncolumns, nrows); gsl_matrix_transpose_memcpy(data_t, data); //multiply matrices gsl_matrix* covar = gsl_matrix_calloc(3, 3); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, data, data_t, 0.0, covar); //eigendecompose covariance matrix gsl_eigen_symmv_workspace* eigen_aux = gsl_eigen_symmv_alloc(3); gsl_vector* eigen_val = gsl_vector_alloc(3); gsl_matrix* eigen_vec = gsl_matrix_alloc(3, 3); gsl_eigen_symmv(covar, eigen_val, eigen_vec, eigen_aux); //build final matrix -> TODO: do we need to transpose/invert? memcpy( glm::value_ptr(out_eigen_val), eigen_val->data, 3*sizeof(double) ); memcpy( glm::value_ptr(out_eigen_vec), eigen_vec->data, 9*sizeof(double) ); //delete pointers gsl_matrix_free(data); gsl_matrix_free(data_t); gsl_matrix_free(covar); gsl_matrix_free(eigen_vec); gsl_vector_free(eigen_val); gsl_eigen_symmv_free(eigen_aux); } //----------------------------------------------------------------------- //-------------------------- FROM PATCH.H ------------------------------- //----------------------------------------------------------------------- Patch::Patch(const glm::dvec3& normal, const std::vector<int>& nodes) { this->normal = normal; //capture patch by move semantics this->nodes = std::move(nodes); } void Patch::paint_patch(std::vector<Node>& graph, const glm::vec3& color) const { for(auto n = this->nodes.begin(); n != this->nodes.end(); ++n) graph[*n].set_color(color); } //TODO: So far, PCA is still useless, but we'll use it when aligning daisies //so to compute DRINK descriptor. Descriptor Patch::compute_descriptor(const std::vector<Node>& points) { //build vector with point positions std::vector<glm::dvec3> p; build_vector_of_points(points, this->nodes, p); //compute patches centroid; remember PCA must be done when //mean of all points is zero this->centroid = cloud_centroid(p); //translate centroid to origin for(auto it = p.begin(); it != p.end(); ++it) *it = *it - centroid; //PCA of translated cloud point glm::dmat3 eigen_vec; glm::dvec3 eigen_val; glm::dvec3 least_evec; double least_eval; principal_component_analysis(p, eigen_vec, eigen_val); least_evec_eval(eigen_vec, eigen_val, least_evec, least_eval); //first, totally naïve descriptor: just store "curvature" //as the relative variance in the direction of the least //eigenvector, i.e., the least eigenvalue divided by total. //Signal is important to know whether patch is convex or concave. double total = 0.0; for(int i = 0; i < 3; i++) total += eigen_val[i]; double curvature = least_eval / total; //Least eigenvalue doesn't necessarily point outside the //patch! (see Sorkine's book, pg. 55). This means we really need to //carry curvature information so to correctly compute descriptors! Convexity type = glm::dot( this->normal, this->curvature) > 0 ? CONCAVE : CONVEX; return (Descriptor){curvature, type}; } glm::dvec3 Patch::get_pos() const { return this->centroid; } glm::dvec3 Patch::get_normal() const { return this->normal; } glm::dvec3 Patch::get_curvature() const { return this->curvature; } void Patch::set_curvature(const glm::dvec3& c) { this->curvature = c; }
true
50773d8a2e1d5b1f311f33d917a377c6fd8964b5
C++
Amartaivan/nest_coding
/competitive/dp/ladder.cpp
UTF-8
739
3.3125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; #define long_t unsigned long long long_t calculate(int n, vector<long_t>& dp){ if (n < 3) return 1; if (dp[n - 1] == -1) dp[n - 1] = calculate(n - 1, dp); if (dp[n - 3] == -1) dp[n - 3] = calculate(n - 3, dp); dp[n] = dp[n - 1] + dp[n - 3]; return dp[n]; } /* Teacher's solution: long_t calculate(int n, vector<long_t>& dp){ if (dp[n] != -1) return dp[n]; if (n < 3) dp[n] = 1; else dp[n] = calculate(n - 1, dp) + calculate(n - 3, dp); return dp[n]; } */ int main(){ int n; cin >> n; vector<long_t> dp(n + 1, -1); cout << calculate(n, dp) << endl; return 0; }
true
b267bb175fb9c4f002ad116342cf5f9c7ff03d6e
C++
shendibrani/MGE_Phong
/src/mge/core/Timer.hpp
UTF-8
468
2.8125
3
[]
no_license
#ifndef TIME_H #define TIME_H #include <SFML/System.hpp> //Wrapper around sf::Clock to provide the elapsed time overall, and elapsed time since the last frame update class Timer { private: // data members static sf::Clock _clock; static float _currentTime; static float _deltaTime; private: // disable creation of time object Timer(){} public: // functons static void update(); static float now(); static float deltaTime(); }; #endif // TIME_H
true
fe58c99e245d5fd9d917c63b7ab157c88167ee81
C++
cnbeiyu/Algorithm
/LanQiaoExercise/02 字符串和日期/190228字符串反转.cpp
UTF-8
235
2.59375
3
[]
no_license
#include <cstdio> #include<cstring> char s[1000]; int main(int argc, char const *argv[]) { int len; scanf("%s", &s); len = strlen(s); printf("%d\n", len); for (int i = len - 1; i > -1; --i) { printf("%c", s[i]); } return 0; }
true
114f77781a27f6f9057cc6a882ec65fa334beb0d
C++
grtwall/kigs
/tools/BundleList/Sources/BundleList.cpp
UTF-8
4,228
2.671875
3
[ "MIT" ]
permissive
#include "BundleList.h" #include "ModuleThread.h" #include "Thread.h" #include <iostream> #include <windows.h> #include <stdlib.h> #include <fstream> void BundleList::usage() { std::cout << "Usage :" << std::endl; std::cout << "BundleList [-i inputPath] [ -o outputfile ]" << std::endl; std::cout << "-i inputPath : path of the directory to create bundle list. Default is \'.\'" << std::endl; std::cout << "-o outputFile : name of the bundlelist file to create. Default is \"files.bundle\"" << std::endl; } IMPLEMENT_CLASS_INFO(BundleList); IMPLEMENT_CONSTRUCTOR(BundleList) { } void BundleList::ProtectedInit() { // Base modules have been created at this point // lets say that the update will sleep 1ms SetUpdateSleepTime(1); CoreCreateModule(ModuleThread, nullptr); // retreive args kstl::vector<kstl::string>::iterator itArgs = mArgs.begin(); // skip app name itArgs++; for (; itArgs != mArgs.end(); itArgs++) { kstl::string& current = (*itArgs); if (current.at(0) == '-') { char argtype = current.at(1); switch (argtype) { case 'i': { // in already there if (mStartPath != "./") { usage(); continue; // exit } itArgs++; mStartPath = (*itArgs); } break; case 'o': { // out already there if (mFilename != "files.bundle") { usage(); continue; // exit } itArgs++; mFilename = (*itArgs); } break; } } } // check for valid path char pathend = mStartPath[mStartPath.length() - 1]; if((pathend != '\\') && ((pathend != '/'))) { mStartPath += "/"; } if (mFilename == "") { usage(); } else { SP<Thread> bundlethread = KigsCore::GetInstanceOf("bundleThread", "Thread"); mThread = bundlethread; bundlethread->setMethod(this, "CreateBundle"); bundlethread->Init(); } } void BundleList::ProtectedUpdate() { std::cout << "Processed file count : " << mBundle.size() << std::endl; if (mBundleIsDone) { mNeedExit = true; mThread = nullptr; } } void BundleList::ProtectedClose() { WriteBundleList(); CoreDestroyModule(ModuleThread); } void BundleList::CreateBundle() { mBundle.clear(); RecursiveInitFileList(mStartPath, mStartPath.length()); mBundleIsDone = true; } void BundleList::RecursiveInitFileList(std::string startDirectory, int cropFilePath) { HANDLE hFind; // Iterate through dirs std::vector<std::string> subDirectoryList; subDirectoryList.clear(); WIN32_FIND_DATAA wfd; std::string search = startDirectory + "*"; hFind = ::FindFirstFileA(search.c_str(), &wfd); if (hFind != INVALID_HANDLE_VALUE) { do { std::string asciifilename = wfd.cFileName; // FIRST check if its a dir if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // only valid directory if (!(asciifilename[0] == '.')) { subDirectoryList.push_back(startDirectory + asciifilename + "/"); } } else { if (!(asciifilename[0] == '.')) { std::string croppedPath = startDirectory.substr(cropFilePath, startDirectory.length() - cropFilePath); if (mBundle.find(asciifilename) != mBundle.end()) { mBundle[asciifilename].push_back(croppedPath); } else { std::vector<std::string> toAdd; toAdd.push_back(croppedPath); mBundle[asciifilename] = toAdd; } } } } while (::FindNextFileA(hFind, &wfd)); ::FindClose(hFind); } // recurse now unsigned int i; for (i = 0; i < subDirectoryList.size(); i++) { RecursiveInitFileList(subDirectoryList[i], cropFilePath); } } void BundleList::WriteBundleList() { std::ofstream fichier(mFilename, std::ios::out | std::ios::trunc); if (fichier) { std::map<std::string, std::vector<std::string> >::const_iterator IT = mBundle.begin(); while (IT != mBundle.end()) { fichier << IT->first; const std::vector<std::string>& currentVector = IT->second; std::vector<std::string>::const_iterator ITVector = currentVector.begin(); while (ITVector != currentVector.end()) { fichier << ";" << *ITVector; ++ITVector; } ++IT; fichier << std::endl; } //Parse de la liste fichier.close(); } else { std::cerr << "Can't open file " << mFilename << std::endl; } }
true
fcbbde69b333adf20f89d68a5c75fde11b7a4bc4
C++
ofthedove/cecs130
/Lab 10/GameBoard.cpp
UTF-8
3,275
3.328125
3
[]
no_license
#include "GameBoard.h" #include <iostream> GameBoard::GameBoard() { for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { board[i][j] = ' '; } } gameOver = false; whoWon = ' '; } GameBoard::~GameBoard() { } bool GameBoard::checkMoveValid(int xCord, int yCord) { if(board[xCord][yCord] == ' ') { return true; } else { return false; } } bool GameBoard::makeMove(int xCord, int yCord, bool XTurn) { if( checkMoveValid(xCord, yCord) ) { if( XTurn ) { board[xCord][yCord] = 'X'; } else { board[xCord][yCord] = 'O'; } return true; } else { return false; } } bool GameBoard::isGameOver() { if(gameOver) { return true; } switch (board[0][0]) { case 'X' : if( ( board[1][0] == 'X' && board[2][0] == 'X' ) || ( board[0][1] == 'X' && board[0][2] == 'X' ) || ( board[1][1] == 'X' && board[2][2] == 'X' ) ) { gameOver = true; whoWon = 'X'; return true; } break; case 'O' : if( ( board[1][0] == 'O' && board[2][0] == 'O' ) || ( board[0][1] == 'O' && board[0][2] == 'O' ) || ( board[1][1] == 'O' && board[2][2] == 'O' ) ) { gameOver = true; whoWon = 'O'; return true; } break; } switch (board[1][1]) { case 'X' : if( ( board[1][0] == 'X' && board[1][2] == 'X' ) || ( board[0][1] == 'X' && board[2][1] == 'X' ) || ( board[0][2] == 'X' && board[2][0] == 'X' ) ) { gameOver = true; whoWon = 'X'; return true; } break; case 'O' : if( ( board[1][0] == 'O' && board[1][2] == 'O' ) || ( board[0][1] == 'O' && board[2][1] == 'O' ) || ( board[0][2] == 'O' && board[2][0] == 'O' ) ) { gameOver = true; whoWon = 'O'; return true; } break; } switch (board[2][2]) { case 'X' : if( ( board[0][2] == 'X' && board[1][2] == 'X' ) || ( board[2][0] == 'X' && board[2][1] == 'X' ) || ( board[0][0] == 'X' && board[1][1] == 'X' ) ) { gameOver = true; whoWon = 'X'; return true; } break; case 'O' : if( ( board[0][2] == 'O' && board[1][2] == 'O' ) || ( board[2][0] == 'O' && board[2][1] == 'O' ) || ( board[0][0] == 'O' && board[1][1] == 'O' ) ) { gameOver = true; whoWon = 'O'; return true; } break; } if(isDraw()) { return true; } return false; } bool GameBoard::isDraw() { bool draw = true; for(int i = 0; i<3; i++){ for(int j = 0; j<3; j++){ if (board[i][j] == ' ') { draw = false; } } } return draw; } char GameBoard::getWhoWon() { return whoWon; } void GameBoard::printBoard() const { using std::cout; using std::endl; cout << "\t\t\t" << "_" << board[0][0] << "_|_" << board[1][0] << "_|_" << board[2][0] << "_" << endl; cout << "\t\t\t" << "_" << board[0][1] << "_|_" << board[1][1] << "_|_" << board[2][1] << "_" << endl; cout << "\t\t\t" << " " << board[0][2] << " | " << board[1][2] << " | " << board[2][2] << " " << endl; return; } void GameBoard::printBoardLin(int line) const { using namespace std; switch(line) { case 1: cout << "_" << board[0][0] << "_|_" << board[1][0] << "_|_" << board[2][0] << "_" ; break; case 2: cout << "_" << board[0][1] << "_|_" << board[1][1] << "_|_" << board[2][1] << "_" ; break; case 3: cout << " " << board[0][2] << " | " << board[1][2] << " | " << board[2][2] << " " ; break; default: break; } return; }
true
1b3ffab784dba13f3bb6a3722b38f74edd52abb3
C++
samiratzn/patent-classification
/parse.cpp
UTF-8
3,889
2.546875
3
[]
no_license
#include <pugixml.hpp> #include <sqlite3x-master/sqlite3x.hpp> #include <iostream> #include <string> #include <thread> #include <future> #include <vector> #include <boost/program_options.hpp> #include <xmlpatentparser.hpp> #include <pftapsparser.h> using namespace std; using namespace sqlite3x; // because it uses prefixes namespace po = boost::program_options; vector<Patent> readOneFile(string filename) { vector<Patent> patents = XMLPatentParser::parseXML(filename); if (patents.empty()) { return PFTAPSParser::parseText(filename); } return patents; } /** * Parse each of the XML files and insert them into the database */ int main(int argc, const char * argv[]) { // Option Management po::options_description visible("Options"); visible.add_options() ("help", "produce help message") ("database,d", po::value<string>()->default_value("patent.db")->value_name("filename"), "Patent sqlite database"); po::options_description actual; actual.add(visible).add_options() ("command", po::value< string >(), "Run mode") ("input-filename", po::value< vector<string> >(), "Input XML files, from CLEF or USPTO"); po::positional_options_description p; p.add("command", 1); p.add("input-filename", -1); po::variables_map varmap; po::store(po::command_line_parser(argc, argv). options(actual).positional(p).run(), varmap); po::notify(varmap); if (varmap.count("help")) { cerr << "Usage: patent store <document> [document ..]" << endl << visible << endl; return 1; } if (not (varmap.count("command") && varmap["command"].as<string>() == "store") ) { cerr << "Invalid command. Available commands: 'store'" << endl << "Usage: patent store <document> [document ..]" << endl << visible << endl; return 1; } if (not (varmap.count("input-filename"))) { cerr << "Missing input files." << endl << "Usage: patent store <document> [document ..]" << endl << visible << endl; return 1; } // Database setup sqlite3_connection conn(varmap["database"].as<string>().c_str()); conn.setbusytimeout(60000); conn.executenonquery("PRAGMA synchronous=0;"); sqlite3_command insert_patent(conn, "INSERT OR REPLACE INTO patents (id, abstract, description, title, claims, uspc, ipc, cpc, ecla) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"); sqlite3_command insert_log(conn, "INSERT INTO log (id, filename, success, message) VALUES (?, ?, ?, ?);"); // Load each patent file for (string filename : varmap["input-filename"].as< vector<string> >()) { // Load each included patent for (Patent& p : readOneFile(filename)) { insert_log.bind(1, p.getId()); insert_log.bind(2, filename); if(p.success()) { insert_patent.bind(1, p.getId()); insert_patent.bind(2, p.getAbstract()); insert_patent.bind(3, p.getDescription()); insert_patent.bind(4, p.getTitle()); insert_patent.bind(5, p.getClaims()); insert_patent.bind(6, p.uspc); insert_patent.bind(7, p.ipc); insert_patent.bind(8, p.cpc); insert_patent.bind(9, p.ecla); insert_patent.executenonquery(); insert_log.bind(3, 1); insert_log.bind(4, ""); //cout << "Parse succeeded on " << filename << endl; } else { insert_log.bind(3, 0); insert_log.bind(4, p.getErrorLog()); //cout << "Parse failed on " << filename << endl; } insert_log.executenonquery(); } cout << "Parsed " << filename << endl; } }
true
7f11d589da61d01a7d139a362e354f434894fe3a
C++
sugawaray/filemanager
/record_readers.h
UTF-8
1,162
2.921875
3
[ "MIT" ]
permissive
#ifndef __RECORD_READERS_H__ #define __RECORD_READERS_H__ #include <sqlite3.h> #include "record_receiver.h" namespace ml { namespace db { template<class T, class U> class Record_collector : public Record_receiver { public: Record_collector(T inserter, const U& converter) : inserter(inserter), converter(converter) { } bool receive(sqlite3_stmt* record) { *inserter = converter(record); ++inserter; return true; } private: T inserter; const U& converter; }; template<class T, class U> inline Record_collector<T, U> Record_collector_fun(T inserter, const U& converter) { return Record_collector<T, U>(inserter, converter); } template<class T, class U> class Record_reader : public Record_receiver { public: Record_reader(T& target, const U& converter) : target(target), converter(converter) { } bool receive(sqlite3_stmt* record) { target = converter(record); return false; } private: T& target; const U& converter; }; template<class T, class U> inline Record_reader<T, U> Record_reader_fun(T& target, const U& converter) { return Record_reader<T, U>(target, converter); } } // db } // ml #endif // __RECORD_READERS_H__
true
6f67d81bc46dade1e6ab4970d35f85c588c8cce5
C++
Arozzal/TowerDefenseGame
/TowerDefeneseGame/Map.cpp
UTF-8
3,975
2.953125
3
[]
no_license
#include "Map.hpp" Map::Map(int sizex, int sizey, std::string path) { this->sizex = sizex; this->sizey = sizey; data = new byte[sizex * sizey]; memset(data, 0, sizex * sizey * sizeof(byte)); data[3] = 1; isused = new bool[sizex * sizey]; memset(isused, 0, sizex * sizey * sizeof(bool)); if (path != "") { maptexture.loadFromFile(path); mapsprite.setTexture(maptexture); } } byte Map::getTileId(int x, int y) { byte id = 0; if (at(x, y-1, true) == 0){ id |= 0b1; } if (at(x + 1, y, true) == 0) { id |= 0b10; } if (at(x, y + 1, true) == 0) { id |= 0b100; } if (at(x - 1, y, true) == 0) { id |= 0b1000; } return id; } byte Map::getTileIdWatter(int x, int y) { byte id = 0; if (at(x - 1, y, true) == 0) { if (at(x, y - 1, true) == 0) { id = 0; }else if (at(x, y + 1, true) == 0) { id = 6; } else { id = 3; } return id; }else if (at(x + 1, y, true) == 0) { if (at(x, y - 1, true) == 0) { id = 2; } else if (at(x, y + 1, true) == 0) { id = 8; } else { id = 5; } return id; } else { if (at(x, y - 1, true) == 0) { id = 1; } else if (at(x, y + 1, true) == 0) { id = 7; } else { id = 4; } return id; } return byte(); } sf::Sprite & Map::getTileById(int id) { int xpos = id % 4; int ypos = id / 4; mapsprite.setTextureRect({ xpos * 16, ypos * 16, 16, 16 }); return mapsprite; } sf::Sprite & Map::getTileById(int id, sf::Sprite & tex, int frame) { int xpos = id % 3; int ypos = id / 3; tex.setTextureRect({ xpos * 16 + frame * 16 * 3, ypos * 16, 16, 16 }); return tex; } void Map::load(byte* arr, int sizex, int sizey) { delete[] data; delete[] isused; this->sizex = sizex; this->sizey = sizey; data = new byte[sizex * sizey]; for (int y = 0; y < sizey; y++) { for (int x = 0; x < sizex; x++) { if (arr[y * sizex + x] >= '0') arr[y * sizex + x] -= '0'; std::cout << arr[y * sizex + x]; data[y * sizex + x] = arr[y * sizex + x]; } std::cout << std::endl; } std::cout << std::endl; isused = new bool[sizex * sizey]; memset(isused, 0, sizex * sizey * sizeof(bool)); } void Map::setSize(int x, int y) { Map(x,y); } void Map::iterateOverMap(std::function<void(int x, int y)> function) { for (int y = 0; y < getYSize(); y++) { for (int x = 0; x < getXSize(); x++) { function(x, y); } } } bool Map::isColliding(Map & map, sf::FloatRect & box, sf::Vector2i pos) { for (int x = 0; x < 2; x++) { for (int y = 0; y < 2; y++) { if (map(pos.x + x, pos.y + y) != 0) { if (box.intersects(sf::FloatRect( (pos.x + x) * 16,(pos.y + y) * 16,16,16 ))) return true; } } } return false; } bool Map::isOutside(int x, int y) { return (x < 0 || x > getXSize() || y < 0 || y > getYSize()); } bool Map::isUsed(int x, int y, int xlength, int ylength) { for (int fx = 0; fx < xlength; ++fx) { for (int fy = 0; fy < ylength; ++fy) { if (isOutside(x + fx, y + fy)) return true; if (isValidePosition(x + fx, y + fy) == false) return true; if (isused[(y + fy) * sizex + (x + fx)]) return true; } } return false; } void Map::useField(int x, int y, bool use, int xlength, int ylength) { for (int fx = 0; fx < xlength; ++fx) { for (int fy = 0; fy < ylength; ++fy) { isused[(fy + y) * sizex + (fx + x)] = use; } } } byte & Map::operator()(int x, int y) { if (x < 0 || x > getXSize() || y < 0 || y > getYSize()) { std::cout << "Map: outside Array range X: " << x << " Y: " << y << std::endl; return nullbyte; } return data[y * sizex + x]; } bool Map::isValidePosition(int x, int y) { if (at(x, y) == 1 || at(x, y) == 3) return true; return false; } byte Map::at(int x, int y, bool noerr) { if (x < 0 || x >= getXSize() || y < 0 || y >= getYSize()) { if(noerr == false) std::cout << "Map: outside Array range X: " << x << " Y: " << y << std::endl; return -1; } return data[y * sizex + x]; } Map::~Map() { delete[] data; delete[] isused; }
true
8f1fdf726dbf8aadc631414258bdc23c22c3822a
C++
InsightSoftwareConsortium/ITK
/Modules/ThirdParty/MetaIO/src/MetaIO/src/tests/testMeta7Line.cxx
UTF-8
1,887
3.046875
3
[ "IJG", "Zlib", "LicenseRef-scancode-proprietary-license", "SMLNJ", "BSD-3-Clause", "BSD-4.3TAHOE", "LicenseRef-scancode-free-unknown", "Spencer-86", "LicenseRef-scancode-llnl", "FSFUL", "Libpng", "libtiff", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", ...
permissive
#include <iostream> #include <metaLine.h> int main(int, char *[]) { std::cout << "Creating test file ..."; auto * Line = new MetaLine(3); Line->ID(0); LinePnt * pnt; unsigned int i; for (i = 0; i < 10; i++) { pnt = new LinePnt(3); pnt->m_X[0] = static_cast<float>(0.2); pnt->m_X[1] = i; pnt->m_X[2] = i; pnt->m_V[0][0] = static_cast<float>(0.3); pnt->m_V[0][1] = i; pnt->m_V[0][2] = i; pnt->m_V[1][0] = static_cast<float>(0.4); pnt->m_V[1][1] = i + 1; pnt->m_V[1][2] = i + 1; Line->GetPoints().push_back(pnt); } std::cout << "Writing test file ..."; Line->BinaryData(true); Line->Write("myLine.meta"); std::cout << "done" << std::endl; std::cout << "Reading test file ..."; Line->Clear(); Line->Read("myLine.meta"); MetaLine LineRead("myLine.meta"); MetaLine LineCopy(&LineRead); std::cout << "PointDim = " << LineCopy.PointDim() << std::endl; std::cout << "NPoints = " << LineCopy.NPoints() << std::endl; std::cout << "ElementType = " << LineCopy.ElementType() << std::endl; Line->PrintInfo(); MetaLine::PointListType list = Line->GetPoints(); MetaLine::PointListType::const_iterator it = list.begin(); i = 0; while (it != list.end()) { std::cout << "Point #" << i++ << ":" << std::endl; std::cout << "position = "; for (unsigned int d = 0; d < 3; d++) { std::cout << (*it)->m_X[d] << " "; } std::cout << std::endl; std::cout << "First normal = "; for (unsigned int d = 0; d < 3; d++) { std::cout << (*it)->m_V[0][d] << " "; } std::cout << std::endl; std::cout << "Second normal = "; for (unsigned int d = 0; d < 3; d++) { std::cout << (*it)->m_V[1][d] << " "; } std::cout << std::endl; ++it; } delete Line; std::cout << "done" << std::endl; return EXIT_SUCCESS; }
true
032500a0f6d043f846717587971f3c2a66b406e8
C++
ahmad-saeed/arduino
/checkButtonsAndLEDs/checkButtonsAndLEDs.ino
UTF-8
951
2.59375
3
[]
no_license
const int LED1 = 9 ; const int LED2 = 10 ; const int LED3 = 11 ; const int LED4 = 12 ; const int button1 = 5 ; const int button2 = 6 ; const int button3 = 7 ; const int button4 = 8 ; boolean isButton4Up = true; void setup() { // put your setup code here, to run once: pinMode(LED1,OUTPUT); pinMode(LED4 ,OUTPUT); pinMode(button1 ,INPUT); pinMode(button4 ,INPUT); Serial.begin(9600); pinMode(13 ,OUTPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(13,HIGH); if (digitalRead(button1)!=HIGH){ digitalWrite(LED1,HIGH); Serial.write("1"); Serial.println(); delay(100);} else{digitalWrite(LED1,LOW);} if (digitalRead(button4)==HIGH && isButton4Up == true) {digitalWrite(LED4,HIGH); Serial.write("4"); Serial.println(); isButton4Up = false; } else if (digitalRead(button4) == LOW) { isButton4Up = true; digitalWrite(LED4,LOW); delay(100); } }
true
15683db0b9e1484e5c0cd99a744b5a93ab5d8bb6
C++
rileyzzz/TrainzMapFiles
/TrainzMapFiles/GNDFile.cpp
UTF-8
11,095
2.71875
3
[]
no_license
#include "GNDFile.h" #include <stdio.h> #include <iostream> #include <iomanip> GNDFile::GNDFile(const char* path) { IOArchive Arch(path, IODirection::Import); Serialize(Arch); } GNDFile::~GNDFile() { } bool GNDFile::Serialize(IOArchive& Ar) { if (Ar.IsSaving()) { Ar.Serialize("GND", 3); } else { char ReadHeader[4] = { 0x00 }; Ar.Serialize(&ReadHeader[0], 3); if (strcmp(ReadHeader, "GND") != 0) { printf("Failed to read chunk GND\n"); return false; } } uint8_t version = 11; Ar << version; printf("GND version %u\n", version); if (version == 21) { uint32_t unknown1 = 0; uint32_t unknown2 = 0; Ar << unknown1; Ar << unknown2; } uint32_t sectionCount = sections.size(); Ar << sectionCount; printf("%u ground sections\n", sectionCount); if (Ar.IsLoading()) sections.resize(sectionCount); for (uint32_t i = 0; i < sectionCount; i++) { GroundSection& section = sections[i]; Ar << section.originH; Ar << section.originV; if (version > 11) Ar.Serialize(section.sectionType, 4); if (version < 21) { //section data Ar << section.vertexOffset; if (version < 16) Ar << section.minimapOffset; if (version < 12) section.minimapResoulution = 128; } else { Ar << section.unknown0; Ar << section.unknown1; auto& textureTable = section.data.TextureTable; uint32_t numTextures = textureTable.size(); Ar << numTextures; if (Ar.IsLoading()) textureTable.resize(numTextures); for (uint32_t tex = 0; tex < numTextures; tex++) { TextureElement& element = textureTable[tex]; //Ar << element.usage; Ar << element.texture._low; Ar << element.texture._high; } } printf("Ground section %d %d type %s offset %u, unknowns: %u, %u\n", section.originH, section.originV, section.sectionType, section.vertexOffset, section.unknown0, section.unknown1); } printf("diurnal begin %d\n", (int)Ar.tell()); //read diurnal table if (version >= 7) { if (version >= 13) { int32_t NegativeOne = -1; Ar << NegativeOne; assert(NegativeOne == -1); } uint32_t diurnalTableVersion = 1; if(version >= 13) Ar << diurnalTableVersion; printf("Diurnal table version %u\n", diurnalTableVersion); uint32_t keyframeCount = diurnalTable.keyframes.size(); Ar << keyframeCount; Ar << diurnalTable.CloudKUID._low; Ar << diurnalTable.CloudKUID._high; printf("Cloud kuid %s\n", diurnalTable.CloudKUID.KUIDstr().c_str()); Ar << diurnalTable.rainValue; printf("time of day offset %d\n", (int)Ar.tell()); Ar << diurnalTable.timeOfDay; printf("Rain %d, time of day %f\n", diurnalTable.rainValue, diurnalTable.timeOfDay); printf("begin diurnal table %d\n", (int)Ar.tell()); if (Ar.IsLoading()) diurnalTable.keyframes.resize(keyframeCount); for (uint32_t i = 0; i < keyframeCount; i++) { DiurnalKeyframe& keyframe = diurnalTable.keyframes[i]; Ar << keyframe.time; Ar << keyframe.sunLightColor; Ar << keyframe.ambientLightColor; //good if (version != 9 && version != 13) Ar << keyframe.unknown1; Ar << keyframe.fogColor; if(version > 13) Ar << keyframe.fogDensity; Ar << keyframe.dayNight; //if (version != 13) Ar << keyframe.sky0; Ar << keyframe.sky1; Ar << keyframe.sky2; printf("Diurnal keyframe time %f, fogdensity %f, daynight %f\n", keyframe.time, keyframe.fogDensity, keyframe.dayNight); } printf("diurnal end %d\n", (int)Ar.tell()); if(version == 21) Ar << diurnalTable.unknown0; if (version > 11) { Ar << diurnalTable.date; Ar << diurnalTable.windStrength; Ar << diurnalTable.snowlineHeight; } printf("Wind strength %f, snowline height %f\n", diurnalTable.windStrength, diurnalTable.snowlineHeight); } printf("end diurnal table %d\n", (int)Ar.tell()); //chump data here if (version == 21) { printf("chump begin %d\n", (int)Ar.tell()); Ar.ignore(0x10); } if (version >= 11) Ar << WaterColor; if (version >= 9 && version != 11) { Ar << WaterKUID._low; Ar << WaterKUID._high; printf("Water kuid %s\n", WaterKUID.KUIDstr().c_str()); } if (version == 9) { Ar << UnknownKUID._low; Ar << UnknownKUID._high; printf("Unknown kuid %s\n", UnknownKUID.KUIDstr().c_str()); } if (version >= 8 && version < 14) { //ruler data } printf("texture table %d\n", (int)Ar.tell()); if (version < 13) { //texture table std::vector<TextureElement> TextureTable; SerializeTextureTable(Ar, TextureTable); for (uint32_t i = 0; i < sectionCount; i++) { uint32_t sectionIndex = sectionCount - 1 - i; GroundSection& section = sections[sectionIndex]; GroundSectionData& data = section.data; data.TextureTable = TextureTable; } Ar << GridTex._low; Ar << GridTex._high; printf("Grid kuid %s\n", GridTex.KUIDstr().c_str()); } //return true; for (uint32_t i = 0; i < sectionCount; i++) { uint32_t sectionIndex = sectionCount - 1 - i; GroundSection& section = sections[sectionIndex]; GroundSectionData& data = section.data; if (version < 21) { //seek to section data Ar.seek(section.vertexOffset, std::ios::beg); if (strcmp(section.sectionType, "sceS") == 0) { //classic section if (version >= 13) SerializeTextureTable(Ar, data.TextureTable); SerializeWaterDataTable(Ar, data); SerializeClassicVertexTable(Ar, version, data); } else if (strcmp(section.sectionType, "5ceS") == 0) { //quad section printf("quad section\n"); } else printf("Unknown section type at index %u!\n", sectionIndex); } else { std::string dir = Ar.getFilepath(); dir = dir.substr(0, dir.find_last_of("\\/") + 1); IOArchive mapFile(dir + "mapfile_" + std::to_string(section.originH) + "_" + std::to_string(section.originV) + ".gnd", Ar.IsLoading() ? IODirection::Import : IODirection::Export); printf("file dir %s\n", mapFile.getFilepath().c_str()); char mapHeader[4] = { 0x15, 0x00, 0x00, 0x00 }; mapFile.Serialize(mapHeader, 4); if (strcmp(section.sectionType, "sceS") == 0) { //classic section //texture table SerializeTextureTable(mapFile, data.TextureTable); SerializeWaterDataTable(mapFile, data); printf("data start %d\n", (int)mapFile.tell()); SerializeClassicVertexTable(mapFile, version, data); } else if (strcmp(section.sectionType, "5ceS") == 0) { //quad section printf("quad section\n"); } else printf("Unknown section type at index %u!\n", sectionIndex); } printf("Read section %u\n", sectionIndex); } printf("data end %d\n", (int)Ar.tell()); return true; } void GNDFile::SerializeTextureTable(IOArchive& Ar, std::vector<TextureElement>& table) { uint32_t maxGTextures = table.size(); Ar << maxGTextures; printf("maxgtextures %u\n", maxGTextures); printf("archive location %d\n", (int)Ar.tell()); //assert(false); if (Ar.IsLoading()) table.resize(maxGTextures); for (uint32_t tex = 0; tex < maxGTextures; tex++) { TextureElement& element = table[tex]; Ar << element.usage; if (element.usage != 0.0f) { Ar << element.texture._low; Ar << element.texture._high; } printf("texture kuid %s\n", element.texture.KUIDstr().c_str()); } printf("tex end %d\n", (int)Ar.tell()); } void GNDFile::SerializeWaterDataTable(IOArchive& Ar, GroundSectionData& data) { uint32_t waterDataCount = data.waterData.size(); Ar << waterDataCount; if (Ar.IsLoading()) data.waterData.resize(waterDataCount); printf("water count %u\n", waterDataCount); for (uint32_t water = 0; water < waterDataCount; water++) { WaterDataElement& element = data.waterData[water]; Ar << element.h; Ar << element.v; Ar << element.height; //printf("water height %f\n", element.height); } } void GNDFile::SerializeClassicVertexTable(IOArchive& Ar, uint8_t version, GroundSectionData& data) { uint32_t vertexTableCount = 76 * 76; data.vertexTable.resize(vertexTableCount); for (uint32_t vert = 0; vert < vertexTableCount; vert++) { GroundVertexElement& element = data.vertexTable[vert]; if (Ar.IsLoading()) { int8_t identifier = Ar.peek(); //Ar << identifier; //printf("begin vertex run %d\n", (int)Ar.tell()); if (identifier == '\375' || identifier == '\376') { Ar.ignore(1); //onetex { GroundVertexData vertData; Ar << vertData.texID; if (version >= 2) Ar << vertData.RotSc; element.data.push_back(vertData); } if (identifier == '\375') { Ar << element.height; if (version >= 11 && version < 13) //version >= 12 SerializeNormal(Ar, element.normal); else element.staleNormals = true; //weird tangent-like data if (version == 9) Ar.ignore(3); } } else { //printf("begin vertex run %d\n", (int)Ar.tell()); //assert(false); int iterCount = 0; while (identifier != '\377') { GroundVertexData vertData; Ar << vertData.texID; Ar << vertData.texAmount; if (version >= 2) Ar << vertData.RotSc; element.data.push_back(vertData); identifier = Ar.peek(); iterCount++; }// while (identifier != '\377'); //'\377' //printf("finish vertex run %d, %d\n", iterCount, (int)Ar.tell()); //assert(false); Ar.ignore(1); Ar << element.height; if (version >= 11 && version < 13) //version >= 12 NORMALS ARENT IN 13, 21 SerializeNormal(Ar, element.normal); else element.staleNormals = true; //weird tangent-like data if (version == 9) Ar.ignore(3); //printf("height %f\n", element.height); //assert(false); } } else { //TODO pick the best structure given the vertex data } //printf("finish vertex run %d\n", (int)Ar.tell()); //assert(false); } if (Ar.IsLoading() && version < 11 || version >= 13) { constexpr int dx = 1; constexpr int dy = 1; //generate normal data for (int y = 2; y < 75; y++) { for (int x = 2; x < 75; x++) { GroundVertexElement& vert = data.GetVertex(x, y); if (vert.staleNormals) { float dfdx = (data.GetVertex(x + dx, y).height - data.GetVertex(x - dx, y).height) / (2.0f * dx * 10.0f); float dfdy = (data.GetVertex(x, y + dy).height - data.GetVertex(x, y - dy).height) / (2.0f * dy * 10.0f); float normal[3] = { -dfdx, -dfdy, 1.0f }; //float normal[3] = { -1.0f / dfdx, -1.0f / dfdy, 1.0f }; //float normal[3] = { 0.0f, 0.0f, 1.0f }; Normalize(normal); memcpy(vert.normal, normal, sizeof(normal)); } } } } } void GNDFile::SerializeNormal(IOArchive& Ar, float* normal) { uint8_t packed[3] = { (int8_t)(normal[0] / 127.0f), (int8_t)(normal[1] / 127.0f), (int8_t)(normal[2] / 127.0f) }; Ar << packed; if (Ar.IsLoading()) { normal[0] = (float)packed[0] / 127.0f; normal[1] = (float)packed[1] / 127.0f; normal[2] = (float)packed[2] / 127.0f; } } inline void GNDFile::Normalize(float* vec) { float magnitude = sqrtf(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]); if (magnitude <= 0.0f) return; vec[0] /= magnitude; vec[1] /= magnitude; vec[2] /= magnitude; }
true
17723b9c688ebcd3811f0f2c6a9c6a00203fe43c
C++
Kh4ster/chess
/tests/unit_tests/possible_move_test.cc
UTF-8
2,330
2.640625
3
[]
no_license
#include "gtest/gtest.h" #include "chess_engine/board/chessboard.hh" #include "parsing/perft_parser/perft-parser.hh" #include "chess_engine/board/move-generation.hh" using namespace board; using namespace move_generation; using namespace std; /* TEST(PossibleMove, Queen) { // This is the subject example Chessboard board = Chessboard("8/8/8/3Q4/8/8/8/8"); auto moves = generate_moves(board, PieceType::QUEEN); EXPECT_EQ(27, moves.size()); board = Chessboard("7Q/8/8/8/8/8/8/8"); moves = generate_moves(board, PieceType::QUEEN); EXPECT_EQ(21, moves.size()); board = Chessboard("6P1/8/8/3Q4/8/8/8/8"); moves = generate_moves(board, PieceType::QUEEN); EXPECT_EQ(26, moves.size()); board = Chessboard("6P1/8/8/1P1Q4/4P3/8/8/8"); moves = generate_moves(board, PieceType::QUEEN); EXPECT_EQ(20, moves.size()); board = Chessboard("3p2P1/8/4p3/1P1Q4/8/8/8/4P3"); moves = generate_moves(board, PieceType::QUEEN); EXPECT_EQ(23, moves.size()); board = Chessboard("8/8/8/8/4R3/8/7p/6pQ"); moves = generate_moves(board, PieceType::QUEEN); EXPECT_EQ(4, moves.size()); board = Chessboard("3b3P/8/5Q2/P7/3p4/2Q2R2/1P6/8"); moves = generate_moves(board, PieceType::QUEEN); EXPECT_EQ(15 + 18, moves.size()); } TEST(PossibleMove, Pawn) { Chessboard board = Chessboard("8/4P3/8/8/8/8/8/8"); auto moves = generate_pawn_moves(board); EXPECT_EQ(4, moves.size()); board = Chessboard("2ppp1p1/PPPPPP2/7P/8/8/8/8/8"); moves = generate_pawn_moves(board); EXPECT_EQ(4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 1, moves.size()); } */ // TODO FIX TEST(PossibleMove, Castling) { std::vector<Move> res; Chessboard board = Chessboard(parse_perft("r3k2r/pppppppp/8/8/8/8/PPPPPPPP/R3K2R w KQkq - 0 1 1")); generate_king_moves(board, res); EXPECT_EQ(4, res.size()); } /* TEST(PossibleMove, EnPassant) { Chessboard board = Chessboard(parse_perft("8/8/8/4Pp2/8/8/8/8 w - f6 0 1 1")); auto moves = generate_pawn_moves(board); EXPECT_EQ(2, moves.size()); board = Chessboard(parse_perft("1p5p/P6P/8/3Pp3/8/8/8/8 w - e6 0 1 1")); moves = generate_pawn_moves(board); EXPECT_EQ(10, moves.size()); } */ int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
170ff3c871efddc929cd9153d0227e8f92c4d650
C++
jford22/sigpro
/include/TxRxMeta.h
UTF-8
4,932
2.890625
3
[]
no_license
#pragma once #include "Constants.h" // This Class Should Contain Information about The Transmit Waveform, it's timing and the receive window enum Modulation { LFM, NLFM, DPC, TEST}; class TxRxMeta { private: // Transmit (TX) Parameters double tx_start_time_seconds; double tx_stop_time_seconds; double tx_start_frequency_GHz; double tx_stop_frequency_GHz; double tx_bandwidth_MHz; double tx_power_watts; Modulation wf_modulation; // Receive (RX) Parameters double rx_window_start_time_seconds; double rx_window_stop_time_seconds; double rx_bandwidth_MHz; double rx_window_rangeBin_resolution_meters; double rx_window_planned_doppler_Khz; long rx_window_front_padding_bins; long rx_window_back_padding_bins; public: TxRxMeta(); ~TxRxMeta(); // Getters double get_tx_start_time_seconds() const {return tx_start_time_seconds;}; double get_tx_stop_time_seconds() const { return tx_stop_time_seconds;}; double get_tx_start_frequency_GHz()const { return tx_start_frequency_GHz;}; double get_tx_stop_frequency_GHz() const { return tx_stop_frequency_GHz;}; double get_tx_bandwidth_MHz() const { return tx_bandwidth_MHz;}; double get_tx_power_watts() const { return tx_power_watts;}; Modulation get_wf_modulation() const { return wf_modulation;}; double get_rx_window_start_time_seconds() const { return rx_window_start_time_seconds;}; double get_rx_window_stop_time_seconds() const { return rx_window_stop_time_seconds;}; double get_rx_bandwidth_MHz() const { return rx_bandwidth_MHz;}; double get_rx_window_rangeBin_resolution_meters() const { return rx_window_rangeBin_resolution_meters;}; double get_rx_window_planned_doppler_Khz() const { return rx_window_planned_doppler_Khz;}; long get_rx_window_front_padding_bins() const { return rx_window_front_padding_bins;}; long get_rx_window_back_padding_bins() const { return rx_window_back_padding_bins;}; // Simple Calculated Getters double get_tx_pulsewidth_sec() const { return tx_stop_time_seconds - tx_start_time_seconds;}; double get_pulse_center_freq_GHz() const { return (tx_start_frequency_GHz + tx_stop_frequency_GHz) / 2.0;}; double get_pulse_start_on_target_seconds() const { return (tx_start_time_seconds + rx_window_start_time_seconds) / 2.0;}; double get_pulse_stop_on_target_seconds() const { return (tx_stop_time_seconds + rx_window_stop_time_seconds) / 2.0;}; double get_pulse_start_range_meters() const { return (rx_window_start_time_seconds - tx_start_time_seconds) * LIGHTSPEED_m_p_sec;}; double get_pulse_stop_range_meters() const { return (rx_window_stop_time_seconds - tx_stop_time_seconds) * LIGHTSPEED_m_p_sec;}; // Setters void set_tx_start_time_seconds(double tx_start_time_seconds_in) {tx_start_time_seconds = tx_start_time_seconds_in;}; void set_tx_stop_time_seconds( double tx_stop_time_seconds_in) {tx_stop_time_seconds = tx_stop_time_seconds_in;}; void set_tx_start_frequency_GHz( double tx_start_frequency_GHz_in) {tx_start_frequency_GHz = tx_start_frequency_GHz_in;}; void set_tx_stop_frequency_GHz(double tx_stop_frequency_GHz_in) {tx_stop_frequency_GHz = tx_stop_frequency_GHz_in;}; void set_tx_bandwidth_MHz(double tx_bandwidth_MHz_in) {tx_bandwidth_MHz = tx_bandwidth_MHz_in;}; void set_tx_power_watts(double tx_power_watts_in) {tx_power_watts = tx_power_watts_in;}; void set_wf_modulation(Modulation wf_modulation_in) {wf_modulation = wf_modulation_in;}; // Receive (RX) Parameters void set_rx_window_start_time_seconds(double rx_window_start_time_seconds_in) {rx_window_start_time_seconds = rx_window_start_time_seconds_in;}; void set_rx_window_stop_time_seconds(double rx_window_stop_time_seconds_in) {rx_window_stop_time_seconds = rx_window_stop_time_seconds_in;}; void set_rx_bandwidth_MHz(double rx_bandwidth_MHz_in) {rx_bandwidth_MHz = rx_bandwidth_MHz_in;}; void set_rx_window_rangeBin_resolution_meters(double rx_window_rangeBin_resolution_meters_in) {rx_window_rangeBin_resolution_meters = rx_window_rangeBin_resolution_meters_in;}; void set_rx_window_planned_doppler_Khz(double rx_window_planned_doppler_Khz_in) {rx_window_planned_doppler_Khz = rx_window_planned_doppler_Khz_in;}; void set_rx_window_front_padding_bins(long rx_window_front_padding_bins_in) {rx_window_front_padding_bins = rx_window_front_padding_bins_in;}; void set_rx_window_back_padding_bins(long rx_window_back_padding_bins_in) {rx_window_back_padding_bins = rx_window_back_padding_bins_in;}; };
true
63b59a874cf59b8f71a31b9f0f9efb50d9a74d9c
C++
Daineeeng/Practice
/토마토.cpp
UTF-8
1,551
2.828125
3
[]
no_license
#include <iostream> #include <queue> using namespace std; char graph[50][50]; int visit[50][50]; int dx[] = { -1,1,0,0 }; int dy[] = { -1,1,0,0 }; int R, C, moveCnt; queue<pair<int, int>> hedge_q; queue<pair<int, int>> water_q; void bfs() { while (!hedge_q.empty()) { int wq_size = water_q.size(); while (wq_size--) { int cx = water_q.front().first; int cy = water_q.front().second; water_q.pop(); for (int k = 0; k < 4; k++) { int nx = cx + dx[k]; int ny = cy + dy[k]; if (0 <= nx && nx < R && 0 <= ny && ny < C && graph[nx][ny] == '.') { graph[nx][ny] = '*'; water_q.push({ nx,ny }); } } } int hq_size = hedge_q.size(); moveCnt++; while (hq_size--) { int cx = hedge_q.front().first; int cy = hedge_q.front().second; visit[cx][cy] = 1; hedge_q.pop(); if (graph[cx][cy] == 'D') { cout << moveCnt - 1 << '\n'; return; } for (int k = 0; k < 4; k++) { int nx = cx + dx[k]; int ny = cy + dy[k]; if (0 <= nx && nx < R && 0 <= ny && ny < C && !visit[nx][ny] && graph[nx][ny] == '.') { hedge_q.push({ nx,ny }); visit[nx][ny] = 1; } } } } cout << "KAKTUS" << '\n'; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); freopen("input.txt", "r", stdin); cin >> R >> C; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { cin >> graph[i][j]; if (graph[i][j] == '*') { water_q.push({ i,j }); } else if (graph[i][j] == 'S') { hedge_q.push({ i,j }); } } } bfs(); return 0; }
true
9ba15e001bc4d696a55bf4892e8f4a9fa49e6869
C++
pekashy/mini-java-compiller
/src/SymbolTree/ScopeNode.cpp
UTF-8
1,182
2.65625
3
[]
no_license
#include <SymbolTree/ScopeNode.h> #include <SymbolTree/Scope.h> std::shared_ptr<ScopeNode> ScopeNode::Create(const std::shared_ptr<ScopeNode>& pParentNode) { auto ptr = std::shared_ptr<ScopeNode>(new ScopeNode(pParentNode)); ptr->Init(); return ptr; } std::shared_ptr<ScopeNode> ScopeNode::CreateBasicOuterScope() { auto ptr = std::shared_ptr<ScopeNode>(new ScopeNode()); ptr->Init(); return ptr; } void ScopeNode::AddChild(const std::shared_ptr<ScopeNode>& pChild) { m_arrChildred.push_back(pChild); } std::shared_ptr<ScopeNode> ScopeNode::GetParent() const { return m_pParentNode; } std::shared_ptr<Scope> ScopeNode::Get() const { return m_pScope; } ScopeNode::ScopeNode(const std::shared_ptr<ScopeNode>& pParentNode) : m_pParentNode(pParentNode) {} ScopeNode::ScopeNode() : m_pParentNode(nullptr) {} void ScopeNode::Init() { m_pScope = Scope::Create(shared_from_this()); if(m_pParentNode) { m_pParentNode->AddChild(shared_from_this()); } } std::shared_ptr<const Scope> ScopeNode::FindScopeWhichContains(const Symbol& symbol) const { if(m_pParentNode == nullptr) { return nullptr; } return m_pParentNode->Get()->FindScopeWhichContains(symbol); }
true
4b94a9822fff1ea1c209b6e18519c248fb746186
C++
Sparksidy/A-star-Pathfinding
/Pathfinding/Pathfinding/Source/AStar.cpp
UTF-8
6,907
2.90625
3
[]
no_license
#include <Stdafx.h> #include <iostream> #include <movement.h> #include "AStar.h" AStar::AStar() { //Initialize the lists } AStar::~AStar() { //Clear the open and closed lists _ClosedList.clear(); _OpenList.clear(); } bool AStar::FindAStarPath( Node* start, Node* end, WaypointList& waypointList) { //TODO: If straight line path then dont do pathfinding :SLO //Push the starting node first start->List = OPEN_LIST; _OpenList.push_back(start); while (!_OpenList.empty()) { //Pop cheapest node off the Open list Node* current_node = PopCheapestNode(); if (current_node->xPos == end->xPos && current_node->yPos == end->yPos) { //Reconstruct Path CalculatePathFromGoal(*start, *current_node, waypointList); return true; } int xDX = 0; int yDY = 0; //Explore all the neighbours of the node for (int i = 0; i < dir; i++) { xDX = current_node->xPos + dx[i]; yDY = current_node->yPos + dy[i]; //Range Checking or if its not in closed list then use the node if (!(xDX < 0 || xDX > (MAP_X_SIZE -1) || yDY < 0 || yDY > (MAP_Y_SIZE -1) || CheckInClosedList(xDX, yDY) || g_terrain.IsWall(yDY, xDX))) { //Generate a new node if not in open or closed list Node node; node.xParent = current_node->xPos; node.yParent = current_node->yPos; node.xPos = xDX; node.yPos = yDY; node.TotalCost = 0; node.givenCost = 0; //Check for diagnols and ignore them if ((dx[i] != 0 && dy[i] != 0)) { node.givenCost = current_node->givenCost + 1.414f; if (g_terrain.IsWall(current_node->yPos + dy[i], current_node->xPos) || g_terrain.IsWall(current_node->yPos, current_node->xPos + dx[i])) { continue; } } else { node.givenCost = current_node->givenCost + 1.0f; } //Calculate the H Cost float hCost = OctileHCost(node, *end); //Final Cost node.TotalCost = node.givenCost + (hCost * _hueristicWeight); /*Check if the node is already in the open or closed list*/ Node* open_Node = FindInOpenList(xDX, yDY); Node* close_Node = FindInClosedList(xDX, yDY); //If the node is already in open list if (open_Node) { // if the new node is cheaper if (node.TotalCost < open_Node->TotalCost) { //Take the expensive node in OpenList off the list open_Node->List = NONE; _OpenList.remove(open_Node); //Put the new one in the list node.List = OPEN_LIST; _OpenList.push_back(new Node(node)); g_terrain.SetColor(node.yPos, node.xPos, DEBUG_COLOR_BLUE); } } else if (close_Node) { if (node.TotalCost < close_Node->TotalCost) { //Take the expensive node in Closed List off the list close_Node->List = NONE; _ClosedList.remove(close_Node); //Put the new one in the list node.List = OPEN_LIST; _OpenList.push_back(new Node(node)); g_terrain.SetColor(node.yPos, node.xPos, DEBUG_COLOR_BLUE); } } else { //If not in the open list or closed list then add it to the open list and update the enum value node.List = OPEN_LIST; _OpenList.push_back(new Node(node)); g_terrain.SetColor(node.yPos, node.xPos, DEBUG_COLOR_BLUE); } } } //After exploring the neighbours of the current node push it to the closed list current_node->List = CLOSED_LIST; _ClosedList.push_back(current_node); g_terrain.SetColor(current_node->yPos, current_node->xPos, DEBUG_COLOR_YELLOW); } //If openList empty, then no path possible if (_OpenList.empty()) return false; } Node* AStar::PopCheapestNode() { float minCost = INT_MAX; Node* node; std::list<Node*>::iterator iterator; for (iterator = _OpenList.begin(); iterator != _OpenList.end(); ++iterator) { if ((*iterator)->TotalCost < minCost) { minCost = (*iterator)->TotalCost; node = (*iterator); } } //Remove it from the openList and use it to explore node->List = NONE; _OpenList.remove(node); return node; } float AStar::OctileHCost(Node& current, Node& goal) { int cur_x = current.xPos; int cur_y = current.yPos; int goal_x = goal.xPos; int goal_y = goal.yPos; int xDiff = abs(goal_x - cur_x); int yDiff = abs(goal_y - cur_y); float a = min(xDiff, yDiff) * sqrt(2); float b = max(xDiff, yDiff); float c = min(xDiff, yDiff); float dist = a + b - c; return dist; } float AStar::EuclideanHCost(Node * current, Node * goal) { int cur_x = current->xPos; int cur_y = current->yPos; int goal_x = goal->xPos; int goal_y = goal->yPos; int xDiff = goal_x - cur_x; int yDiff = goal_y - cur_y; float dist = sqrt((xDiff * xDiff) + (yDiff * yDiff)); return dist; } Node* AStar::FindInOpenList(int x, int y) { std::list<Node*>::const_iterator iterator; Node* node; for (iterator = _OpenList.begin(); iterator != _OpenList.end(); ++iterator) { //If the nodes are same then return the node from the list if ((*iterator)->xPos == x && (*iterator)->yPos == y) { node = (*iterator); return node; } } return nullptr; } Node* AStar::FindInClosedList(int x, int y) { if (!_ClosedList.empty()) { std::list<Node*>::iterator iterator; Node* node; for (iterator = _ClosedList.begin(); iterator != _ClosedList.end(); ++iterator) { //If the nodes are same return the node from the list if ((*iterator)->xPos == x && (*iterator)->yPos == y) { node = (*iterator); return node; } } } return nullptr; } bool AStar::CheckInClosedList(int x, int y) { if (!_ClosedList.empty()) { std::list<Node*>::iterator iterator; for (iterator = _ClosedList.begin(); iterator != _ClosedList.end(); ++iterator) { //If the nodes are equal if ((*iterator)->xPos == x && (*iterator)->yPos == y) { return true; } } } return false; } bool AStar::CheckInOpenList(int x, int y) { if (!_OpenList.empty()) { std::list<Node*>::iterator iterator; for (iterator = _OpenList.begin(); iterator != _OpenList.end(); ++iterator) { //If the nodes are equal if ((*iterator)->xPos == x && (*iterator)->yPos == y) { return true; } } } return false; } void AStar::CalculatePathFromGoal(Node& start, Node & end, WaypointList & list) { Node current = end; while (current.xPos != start.xPos || current.yPos != start.yPos) { D3DXVECTOR3 spot = g_terrain.GetCoordinates(current.yPos, current.xPos); list.push_back(spot); //g_terrain.SetColor(current.yPos, current.xPos, DEBUG_COLOR_YELLOW); Node* node = FindInClosedList(current.xParent, current.yParent); if (node) { current.xPos = node->xPos; current.yPos = node->yPos; current.xParent = node->xParent; current.yParent = node->yParent; } else { g_terrain.SetColor(current.yPos, current.xPos, DEBUG_COLOR_RED); } } list.reverse(); }
true
33574dc09b978436953a99988ac559cdfe707f37
C++
WajeehAlbasha/first-c--projects
/C++ dönem 1 Odevleri/C_g181210552_2/C_g181210552_2.cpp
UTF-8
4,064
2.75
3
[]
no_license
//*************************** //* SAKARYA ÜNİVERSİTESİ //* BİLGİSAYAR VE BİLİŞİM BİLİMLERİ FAKÜLTESİ //* BİLGİSAYAR MÜHENDİSLİĞİ BÖLÜMÜ //* ÖĞRENCİ NUMARASI => g181210552 //* ÖĞRENCİNİN ADI => wajeeh bacha //* ÖDEV NUMARASI => 1.1 //* DERS GRUBU => C //* //* //* //* //**************************** #include <iostream> #include <iomanip> #include<string.h> using namespace std; //değişkenler tanımlama int i, j, a, b, random, random1, random2; bool benzersiz = true; const int satir = 5; const int sutun = 10; //matris tanımlama int litters[satir][sutun]; int main() { srand(time(NULL));//bastırdığımız random harflerin kapatıp açtığımızda yenilenmesi için cout << "random harfler:" << endl << endl; //matrisi dödüren döngü for (i = 0; i < satir; i++) { for (j = 0; j < sutun; j++) {//sutunları bir büyük bir küçük harflı olacak şekilde random harf basamak için if döngü if (j % 2 == 0)//eğer sutun sayısının ikiye bölmesi 0 ise { do { random1 = rand() % 26 + 65;//random büyük harfları üreten fonksyon for (a = 0; a < satir; a++)//satırları arttırarak devam eden for döngü { for (b = 0; b < sutun; b++)//sutunları arttırarak devam eden for döngü { //basılan harfın benzeri yoksa random harfı matrise ata benzersiz = true; if (litters[a][b] == random1) {//basılan harfın benzeri varsa dönen a ve b yi satir ve sutun //sayısına eşitleyerek döngüden çıkmasını sağlayan fonksyon benzersiz = false; b = sutun; a = satir; } } } } while (!benzersiz);//bastırdığımız random harfları random 1'e atıyoruz litters[i][j] = random1; } else { do { random2 = rand() % 26 + 97;//random küçük harfları üreten fonksyon for (a = 0; a < satir; a++)//satırları arttırarak devam eden for döngü { for (b = 0; b < sutun; b++)//sutunları arttırarak devam eden for döngü {//basılan harfın benzeri yoksa random harfı matrise ata benzersiz = true; if (litters[a][b] == random2) { //basılan harfın benzeri varsa dönen a ve b yi satir ve sutun //sayısına eşitleyerek döngüden çıkmasını sağlayan fonksyon benzersiz = false; b = sutun; a = satir; } } } } while (!benzersiz);//bastırdığımız random harfları random 2'e atıyoruz litters[i][j] = random2; } } } for (i = 0; i < satir; i++)//matrisi basan for döngüsü { for (j = 0; j < sutun; j++) { cout << setw(2) << (char)litters[i][j] ;//matrisi chara dünüştürerek harf olarak yazar } cout << endl; } cout << endl << "A'dan z'ye harfler:" << endl << endl; for (int i = 0; i < satir; i++) //harfları A'dan z'ye sıralayan döngü { for (int j = 0; j < sutun; j++) { int m = i; int n = j + 1; while (true) { //10. sutundeki harfı sıraladıktan sonra bir sonraki satıra geçmeyi sağlayan döngü if (n == 10) { n = 0; m++; if (m == 5) break;//5. satıra geldiğinde dur } //n'i arttırarak harfları birbirine karşılaştırır ve farfları sıralar //yukardaki if döngü sayesinde 10. sutunden sonra bir sonraki satıra gelir //ve karşılaştırmaya devam eder if (litters[i][j] > litters[m][n]) std::swap(litters[i][j], litters[m][n]); n++; } } } for (i = 0; i < satir; i++)//random atılan harfların sıralandıktan sonra ekrana basar { for (j = 0; j < sutun; j++) { cout << setw(2) << (char)litters[i][j] ;//matrisi chara dünüştürerek harf olarak yazar } cout << endl; } system("pause"); return 0; }
true
5a9216535e3a6f1ada84b4af85475c9889f5e239
C++
huhuhu1092/test-server
/SEHome/seengine/src/game/cchess/SE_Pipe.cpp
UTF-8
4,984
2.640625
3
[]
no_license
#include "SE_Pipe.h" #include <string.h> #include <stdarg.h> #include <stdio.h> #include "SE_Log.h" #include "SE_Application.h" #include "SE_ChessCommand.h" #include "./base/pipe.h" #if defined(WIN32) const int PATH_SEPERATOR = '\\'; #else const int PATH_SEPERATOR = '/'; #endif //static PipeStruct pipeStd; SE_PipeStruct::SE_PipeStruct() { nReadEndInput = 0; nReadEndOutput = 0; memset(szBufferInput, 0 , SE_LINE_INPUT_MAX_CHAR); memset(szBufferOutput, 0, SE_LINE_OUTPUT_MAX_CHAR); } static bool writeContentToBuffer(char* buffer, int readStart, int bufferSize, const char* content, int size) { if(!content) return false; if(readStart + size >= bufferSize) return false; memcpy(buffer + readStart, content, size); return true; } void SE_PipeStruct::WriteToInputPipe(const char* content, int size) { bufferInputMutex.lock(); bool ret = writeContentToBuffer(szBufferInput, nReadEndInput, SE_LINE_INPUT_MAX_CHAR, content, size); if(ret) { nReadEndInput += size; if(nReadEndInput > SE_LINE_INPUT_MAX_CHAR) nReadEndInput = SE_LINE_INPUT_MAX_CHAR; } bufferInputMutex.unlock(); } static int readLineFromBuffer(char* buffer, int bufferSize, char* output) { char* lpFeedEnd = NULL; int nFeedEnd = 0; if(!output) return 0; lpFeedEnd = (char*)memchr(buffer, '\n', bufferSize); if(lpFeedEnd == NULL) { output[0] = '\0'; return 0; } else { nFeedEnd = lpFeedEnd - buffer; memcpy(output, buffer, nFeedEnd); output[nFeedEnd] = '\0'; nFeedEnd++; bufferSize -= nFeedEnd; memcpy(buffer, buffer + nFeedEnd, bufferSize); lpFeedEnd = (char*)strchr(output, '\r'); if(lpFeedEnd) { *lpFeedEnd = '\0'; } return nFeedEnd; } } void SE_PipeStruct::ReadLineFromInputPipe(char* output) { bufferInputMutex.lock(); int size = readLineFromBuffer(szBufferInput, nReadEndInput, output); nReadEndInput -= size; bufferInputMutex.unlock(); /* char* lpFeedEnd = NULL; int nFeedEnd = 0; if(!output) return; lpFeedEnd = (char*)memchr(szBufferInput, '\n', nReadEnd); if(lpFeedEnd == NULL) { output[0] = '\0'; return; } else { nFeedEnd = lpFeedEnd - szBuffer; memcpy(output, szBufferInput, nFeedEnd); output[nFeedEnd] = '\0'; nFeedEnd++; nReadEnd -= nFeedEnd; memcpy(szBufferInput, szBuffer + nFeedEnd, nReadEnd); lpFeedEnd = (char*)strchr(output, '\r'); if(lpFeedEnd) { *lpFeedEnd = '\0'; } } */ } void SE_PipeStruct::WriteToOutputPipe(const char* content, int size) { bufferOutputMutex.lock(); bool ret = writeContentToBuffer(szBufferOutput, nReadEndOutput, SE_LINE_INPUT_MAX_CHAR, content, size); if(ret) { nReadEndOutput += size ; if(nReadEndOutput > SE_LINE_OUTPUT_MAX_CHAR) nReadEndOutput = SE_LINE_OUTPUT_MAX_CHAR; } bufferOutputMutex.unlock(); } void SE_PipeStruct::ReadLineFromOutputPipe(char* output) { bufferOutputMutex.lock(); int size = readLineFromBuffer(szBufferOutput, nReadEndOutput, output); nReadEndOutput -= size; bufferOutputMutex.unlock(); } /////////////////////////////////////// SE_PipeStruct sepipeStd; bool pipeInputReadLine(char* output) { if(!output) return false; sepipeStd.ReadLineFromInputPipe(output); if(output[0] == '\0') return false; else return true; } void pipeInputWrite(const char* format, ...) { char buf[SE_LINE_OUTPUT_MAX_CHAR]; memset(buf, 0, SE_LINE_OUTPUT_MAX_CHAR); va_list ap; va_start(ap, format); vsnprintf(buf, SE_LINE_OUTPUT_MAX_CHAR, format, ap); va_end(ap); buf[SE_LINE_OUTPUT_MAX_CHAR - 1] = 0; int size = strlen(buf); sepipeStd.WriteToInputPipe(buf, size); } bool pipeOutputReadLine(char* output) { if(!output) return false; sepipeStd.ReadLineFromOutputPipe(output); if(output[0] == '\0') return false; else return true; } void pipeOutputWrite(const char* format, ...) { char buf[SE_LINE_OUTPUT_MAX_CHAR]; memset(buf, 0, SE_LINE_OUTPUT_MAX_CHAR); va_list ap; va_start(ap, format); vsnprintf(buf, SE_LINE_OUTPUT_MAX_CHAR, format, ap); va_end(ap); buf[SE_LINE_OUTPUT_MAX_CHAR - 1] = 0; int size = strlen(buf); sepipeStd.WriteToOutputPipe(buf, size); LOGI("### write to pipe output : %s ####\n", buf); std::string command = buf; std::string::size_type pos = command.find("bestmove"); if(pos != std::string::npos) { command.erase(pos, 8); std::string str = SE_Util::trim(command.c_str()); SE_ChessAIResponse* c = new SE_ChessAIResponse(SE_Application::getInstance()); c->command = str; c->color = "b"; SE_Application::getInstance()->postCommand(c); } } void pipeOpen() { //pipeStd.Open(); }
true
2b3ac1b1e6beb4f960199c773986bf778d67adba
C++
GeorgeNav/Learning
/C++/ProgrammingFundamentalsI_1336/LAB 5/PROJECTS/Task2 and 3 Chapter 5/Task2 and 3 Chapter 5/Source.cpp
UTF-8
1,043
3.09375
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; int main() { const int SENTINEL = -1; signed int count, dataItems; double dollars, total, average; ifstream infile; infile.open("C:\GOOGLE DRIVE\SCHOOL\LONESTAR\PROGRAMMING FUNDAMENTALS I 1336\LABS\LAB 5\PROJECTS\Task2 and 3 Chapter 5\Salesdata.txt"); count = 0; dollars = 0; total = 0; average = 0; dataItems = 0; do { cout << "What is the positive amount for this item: "; cin >> dataItems; }while ( dataItems < 0 ); cout << "\n"; cout << "Enter -1 to finish..." << "\n"; do { count += 1; cout << "What is the amount for this item #" << count << ": "; cin >> dollars; cout << "\n"; if ( dollars != -1 ) { total += dollars; } }while ( count != dataItems && dollars != SENTINEL ); // SENTINEL: }while ( dollars != SENTINEL ); average = total / dataItems; cout << "Total amount: " << total << "\n"; cout << "Average: " << average << "\n"; system("pause"); return 0; }
true
295779c6b3e59318af3083a8ab9da54eb546de03
C++
xh286/leetcode
/228-Summary-Ranges/solution.cpp
UTF-8
975
3.15625
3
[]
no_license
class Solution { private: void insertRange(vector<string>& ret, int start, int end) { ostringstream ss; // assert(end>=start); ss << start; if(end>start) ss << "->" << end; ret.push_back(ss.str()); } public: vector<string> summaryRanges(vector<int>& nums) { // Keep start & end values. If next is end+1, then update end. // If not, then insert start & end pair. If start == end, only insert one. // After loop complete, process last pair. int n = nums.size(); vector<string> ret; if(n==0) return ret; int start, end; start = end = nums[0]; for(int i=1; i<n; i++) { if(nums[i] == end+1) end++; else { insertRange(ret, start, end); start = end = nums[i]; } } insertRange(ret, start, end); return ret; } };
true
e1d495e7636b6353e5dce2d72ca86b1f23feb1ef
C++
5fe6eb50c7aa19f9/OJ
/zj/b417.cpp
UTF-8
1,535
2.65625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> using namespace std; struct Quest{ int i,l,r; }; int sep; int data[100000]; Quest quest[1000000]; int ans[1000000][2]; char buff[10000000]; int cnt[1000000]; int num[1000000]; int l,r,biggest; bool cmp(Quest &a,Quest &b){ if(a.l/sep!=b.l/sep)return a.l<b.l; return a.r<b.r; } inline void add(int i){ num[cnt[data[i]]]--; cnt[data[i]]++; num[cnt[data[i]]]++; biggest=max(biggest,cnt[data[i]]); } inline void sub(int i){ num[cnt[data[i]]]--; cnt[data[i]]--; num[cnt[data[i]]]++; if(!num[biggest])biggest--; } int main(){ int n,m,i,j,k; scanf("%d %d",&n,&m); sep=sqrt(n); for(i=0;i<n;i++)scanf("%d",data+i); scanf("%*c%[^eof]",buff); for(i=j=k=m=0;buff[i];i++){ if(buff[i]>='0'&&buff[i]<='9'){ j=(j<<3)+(j<<1)+buff[i]-'0'; }else{ if(k==0){ quest[m].i=m; quest[m].l=j-1; k=1; }else{ quest[m++].r=j; k=0; } j=0; } } sort(quest,quest+m,cmp); l=0; r=1; cnt[data[0]]=num[1]=biggest=1; for(i=0;i<m;i++){ while(l<quest[i].l)sub(l++); while(l>quest[i].l)add(--l); while(r<quest[i].r)add(r++); while(r>quest[i].r)sub(--r); ans[quest[i].i][0]=biggest; ans[quest[i].i][1]=num[biggest]; } for(i=0;i<m;i++){ printf("%d %d\n",ans[i][0],ans[i][1]); } }
true
d8d652845a5bf0516071ebce9502031166a49e80
C++
metux/chromium-suckless
/v8/src/identity-map.h
UTF-8
2,971
2.640625
3
[ "BSD-3-Clause", "SunPro", "bzip2-1.0.6" ]
permissive
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_IDENTITY_MAP_H_ #define V8_IDENTITY_MAP_H_ #include "src/base/functional.h" #include "src/handles.h" namespace v8 { namespace internal { // Forward declarations. class Heap; class Zone; // Base class of identity maps contains shared code for all template // instantions. class IdentityMapBase { protected: // Allow Tester to access internals, including changing the address of objects // within the {keys_} array in order to simulate a moving GC. friend class IdentityMapTester; typedef void** RawEntry; IdentityMapBase(Heap* heap, Zone* zone) : heap_(heap), zone_(zone), gc_counter_(-1), size_(0), mask_(0), keys_(nullptr), values_(nullptr) {} ~IdentityMapBase(); RawEntry GetEntry(Object* key); RawEntry FindEntry(Object* key); void Clear(); private: // Internal implementation should not be called directly by subclasses. int LookupIndex(Object* address); int InsertIndex(Object* address); void Rehash(); void Resize(); RawEntry Lookup(Object* key); RawEntry Insert(Object* key); int Hash(Object* address); base::hash<uintptr_t> hasher_; Heap* heap_; Zone* zone_; int gc_counter_; int size_; int mask_; Object** keys_; void** values_; }; // Implements an identity map from object addresses to a given value type {V}. // The map is robust w.r.t. garbage collection by synchronization with the // supplied {heap}. // * Keys are treated as strong roots. // * SMIs are valid keys, except SMI #0. // * The value type {V} must be reinterpret_cast'able to {void*} // * The value type {V} must not be a heap type. template <typename V> class IdentityMap : public IdentityMapBase { public: IdentityMap(Heap* heap, Zone* zone) : IdentityMapBase(heap, zone) {} // Searches this map for the given key using the object's address // as the identity, returning: // found => a pointer to the storage location for the value // not found => a pointer to a new storage location for the value V* Get(Handle<Object> key) { return Get(*key); } V* Get(Object* key) { return reinterpret_cast<V*>(GetEntry(key)); } // Searches this map for the given key using the object's address // as the identity, returning: // found => a pointer to the storage location for the value // not found => {nullptr} V* Find(Handle<Object> key) { return Find(*key); } V* Find(Object* key) { return reinterpret_cast<V*>(FindEntry(key)); } // Set the value for the given key. void Set(Handle<Object> key, V v) { Set(*key, v); } void Set(Object* key, V v) { *(reinterpret_cast<V*>(GetEntry(key))) = v; } // Removes all elements from the map. void Clear() { IdentityMapBase::Clear(); } }; } // namespace internal } // namespace v8 #endif // V8_IDENTITY_MAP_H_
true
51bf29a8fea728eff06bccb5c90a045589271493
C++
Ryan-rsm-McKenzie/CommonLibSSE
/include/RE/B/BSTCaseInsensitiveStringMap.h
UTF-8
492
2.5625
3
[ "MIT" ]
permissive
#pragma once #include "RE/N/NiTStringMap.h" namespace RE { // 28 template <class T> class BSTCaseInsensitiveStringMap : public NiTStringMap<T> { private: using base = NiTStringMap<T>; public: using key_type = typename base::key_type; virtual ~BSTCaseInsensitiveStringMap(); // 00 // override (NiTStringMap<T>) std::uint32_t hash_function(key_type a_key) const override; // 01 bool key_eq(key_type a_lhs, key_type a_rhs) const override; // 02 }; }
true
a1f60f9eb74472141971ad587c65c269c6cee203
C++
tomazos/wt
/database/sqlite/sqlite_test.cc
UTF-8
1,221
2.625
3
[]
no_license
#include "database/sqlite/connection.h" #include <boost/filesystem.hpp> #include "core/env.h" #include "core/file_functions.h" #include "core/must.h" #include "gtest/gtest.h" namespace database { namespace sqlite { TEST(Sqlite3Test, Connection) { filesystem::path source_root = GetEnv("SOURCE_ROOT"); filesystem::path english_words_path = source_root / "database/sqlite/testdata/english-words.txt"; filesystem::path tmpfile = filesystem::temp_directory_path() / filesystem::unique_path(); { Connection db(tmpfile); db(R"( create table words( word string ) )"); db("begin"); Statement insert = db.Prepare("insert into words (word) values (?)"); Scan(GetFileContents(english_words_path), "\n", [&](string_view word) { insert.BindText(1, word); insert.Execute(); insert.Reset(); }); db("end"); Statement select = db.Prepare(R"( select word from words where word like '%oo%' order by length(word) desc limit 10 )"); while (select.Step()) { EXPECT_GT(select.ColumnText(0).size(), 7u); } } filesystem::remove(tmpfile); } } // namespace sqlite } // namespace database
true
6bfc32fd2cdb4d87f3386fac36fcd312a65f4ffd
C++
bence7999/OOP_CPP
/OOP_CPP/ChapterThirteen.cpp
UTF-8
21,839
4.25
4
[]
no_license
#include "ChapterThirteen.h" using namespace std; namespace ChapterThirteen { /// 13.1 Polymorphism: a simple example // Write a program to study polymorphism. Use the following specifications: Create a base class called creatures. // It should have a constructor and method move to tell about how that creature moves. The data member should be a character array for storing the name of the creature. class Creatures { public: char name[40]; Creatures(char *p); void move(); }; class Bird : public Creatures { int speed; public: void move(); Bird(int n, char * p); }; class Pet : public Creatures { int speed; public: void move(); Pet(int n, char * p); }; void Poly1() { cout << "<-- - poly1.cpp--->" << endl; Bird Parrot(5, "Mithu Miyan"); Parrot.move(); Pet Cat(1, "Pussy"); Cat.move(); } Creatures::Creatures(char *p) { strcpy_s(name, p); } void Creatures::move() { cout << "I am " << name << endl; cout << "I can move!" << endl; } Bird::Bird(int n, char *p) : Creatures(p) // Note 1 { speed = n; } void Bird::move() { cout << "I am a bird." << endl; cout << " My name is : " << name << endl; cout << " My Flying speed is : " << speed << endl; } Pet::Pet(int n, char *p) : Creatures(p){ speed = n; } void Pet::move() { cout << "I am a Cat." << endl; cout << " My name is : " << name << endl; cout << " My Running speed is : " << speed << endl; } /// 13.2 Polymorphism using pointer to objects // Rewrite Program 13.1 "poly1.cpp" using pointers to derived class objects. class Creatures2 { public: char name[40]; Creatures2(char*p); void move(); }; class Bird2 : public Creatures2 { int speed; public: void move(); Bird2(int n, char * p); }; class Pet2 : public Creatures2 { int speed; public: void move(); Pet2(int n, char * p); }; void Poly2() { cout << "<-- - poly2.cpp--->" << endl; Bird2 *Parrot = new Bird2(5, "Mithu Miyan"); Parrot->move(); Pet2 *Cat = new Pet2(1, "Pussy"); Cat->move(); } Creatures2::Creatures2(char *p) { strcpy_s(name, p); } void Creatures2::move() { cout << "I am " << name << endl; cout << "I can move!" << endl; } Bird2::Bird2(int n, char *p) : Creatures2(p) // Note 1 { speed = n; } void Bird2::move() { cout << "I am a bird." << endl; cout << " My name is : " << name << endl; cout << " My Flying speed is : " << speed << endl; } Pet2::Pet2(int n, char *p) : Creatures2(p) { speed = n; } void Pet2::move() { cout << "I am a Cat." << endl; cout << " My name is : " << name << endl; cout << " My Running speed is : " << speed << endl; } /// 13.3 Twist hero se joker ban jana padta hai // Write a program allowing base class pointer to point to derived class object. class Joker { protected: char name[20]; public: Joker(char *p); //{strcpy(name, p)} void show(); }; class Hero : public Joker { public: Hero(char * p2); void show(); }; void Hero1() { cout << " << -- - hero1.cpp--->" << endl; Joker * bptr; //BC pointer pointing to BC Hero * dptr; // DC pointer dptr = new Hero("Raj Kapoor"); //DC pointer pointing to DC object cout << "DC pointer pointing to DC object" << endl; dptr->show(); // hero = joker ; NOTE! compilation error bptr = dptr; //BC pointer pointing to DC cout << "BC pointer pointing to DC object" << endl; bptr->show(); } Joker::Joker(char *p) { strcpy_s(name, p); } void Joker::show() { cout << "Joker = " << name << endl; } Hero::Hero(char * p2) :Joker(p2) {// no code here } void Hero::show() { cout << "Hero = " << name << endl; } /// 13.5.1 Run time polymorphism in action /// 13.4 The twist removed // Write a program to show that when base class pointer point to the derived class, method from the derived class is executed, if method in the base class is virtual. class Joker2 { protected: char name[20]; public: Joker2(char *p); //{strcpy(name, p)} virtual void show(); // note 1 }; class Hero2 : public Joker2 { public: Hero2(char * p2); void show(); }; void Hero_2() { cout << " << -- - hero2.cpp--->" << endl; Joker2 * bptr; //BC pointer pointing to BC Hero2 * dptr; // DC pointer dptr = new Hero2("Raj Kapoor"); //DC pointer pointing to DC object cout << "DC pointer pointing to DC object" << endl; dptr->show(); // hero = joker ; NOTE! compilation error bptr = dptr; //BC pointer pointing to DC cout << "BC pointer pointing to DC object" << endl; bptr->show(); // } Joker2::Joker2(char *p) { strcpy_s(name, p); } void Joker2::show() { cout << " Joker = " << endl; } Hero2::Hero2(char * p2) :Joker2(p2) { // no code required here } void Hero2::show() { cout << " Hero = " << name << endl; } /// 13.8 THE CLIMAX: ARRAY OF DERIVED CLASS OBJECTS /// 13.5 Array of derived class objects // Calculate the salary of a worker, staff and officer. Use base class Employee. Use the concept of array of base class pointer. typedef char string15[15]; class Employee //abstract base class { protected: float basic; public: int type; virtual void calpay() = 0; }; class Worker : public Employee { string15 name; float gross; public: Worker(string15 s1, float amt); void calpay(); }; class Staff : public Employee { string15 name; float gross; public: Staff(string15 s1, float amt); void calpay(); }; class Officer : public Employee { string15 name; float gross; public: Officer(string15 s1, float amt); void calpay(); }; void Arrobj3() { cout << " << -- - arrobj3.cpp--->" << endl; Employee *eptr[3]; eptr[0] = new Worker("tandlekar", 10000); eptr[1] = new Staff("Wahgmare", 20000); eptr[2] = new Officer("bhole", 30000); cout << "Polymorphism of calpay() demonstrated" << endl; cout << " Category : Name: Pay " << endl; for (int i = 0; i < 3; i++) eptr[i]->calpay(); } Worker::Worker(string15 s1, float amt) { type = 0; // hard coded in the constructor strcpy_s(name, s1); basic = amt; } Staff::Staff(string15 s1, float amt) { type = 1; strcpy_s(name, s1); basic = amt; } Officer::Officer(string15 s1, float amt) { type = 2; strcpy_s(name, s1); basic = amt; } void Worker::calpay() { gross = basic * 1.5 + 1000 /*HRA*/; cout << setw(7) << type << setw(13) << name << setw(10) << gross << endl; } void Staff::calpay() { gross = basic * 1.5 + 2000 /*HRA*/; cout << setw(7) << type << setw(13) << name << setw(10) << gross << endl; } void Officer::calpay() { gross = basic * 1.5 + 4000 /*HRA*/; cout << setw(7) << type << setw(13) << name << setw(10) << gross << endl; } /// 13.10.1 A class with virtual function can be instantiated /// 13.6 Moving output // Write a program to demonstrate the following: // 1. A class with virtual function can be instantiated. Such virtual function can also be executed. // 2. With virtual function in the base class, derived class object executes the function of its own class. void delay(long N); // function prototype class Creatures3 { public: char name[40]; Creatures3(char *p); virtual void move(); }; class Bird3 : public Creatures3 { int speed; public: void move(); Bird3(int n, char * p); }; class Pet3 : public Creatures3 { int speed; public: void move(); Pet3(int n, char * p); }; void Vbase3() { cout << " << -- - vbase3.cpp--->" << endl; Creatures3 *ptr1; ptr1 = new Creatures3("somebody"); ptr1->move(); Bird3 *Parrot; Parrot = new Bird3(5, "Mithu Miyan"); Pet3 * Cat; Cat = new Pet3(1, "Pussy"); ptr1 = Parrot; ptr1->move(); ptr1 = Cat; ptr1->move(); } Creatures3::Creatures3(char *p) { strcpy_s(name, p); } void Creatures3::move() { cout << "*** Hello world!"; cout << " I am " << name; cout << " I can move! ***" << endl; } Bird3::Bird3(int n, char *p) : Creatures3(p) { speed = n; } void Bird3::move() { cout << "I am a bird : My name is : " << name << endl; cout << " My Flying speed is : " << speed << endl; int i; for (i = 5; i < 30; i++) { _putch('*'); delay(10000 / speed); //delay is inversely proportional to speed _putch(' '); } cout << endl; } Pet3::Pet3(int n, char *p) : Creatures3(p) { speed = n; } void Pet3::move() { int i; cout << "I am a Cat : My name is : " << name << endl; cout << " My Running speed is : " << speed << endl; for (i = 5; i < 30; i++) { _putch('#'); delay(10000 / speed); // delay is inversely proportional to speed _putch(' '); } cout << endl; } void delay(long N) { long i, j, k; float x = 0; for (j = 0; j < N; j++) for (i = 0; i < 5000; i++) x = x / 7; } /// 13.10.2 Class shape /// 13.7 Polymorphism – perimeter of shapes // Design a polymorphic class hierarchy for closed shapes such as circle, rectangle and triangle. // Also write a polymorphic function that calculates perimeter of these shapes. Write a program to test these classes. // circle rectangle and triangle. Perimeter of these shapes. // #define M_PI 3.14159265358979323846 // pi class Shape { public: virtual void perimeter() = 0; }; class Rectangle : public Shape { private: int x1, y1, x2, y2; float peri; public: Rectangle(int a, int b, int c, int d); void perimeter(); }; class Circle : public Shape { private: int x0, y0, rad; float peri; public: Circle(int a, int b, int r); void perimeter(); }; class Triangle : public Shape { private: int x1, y1, x2, y2, x3, y3; float peri; public: Triangle(int a, int b, int c, int d, int e, int f); void perimeter(); }; void Shape1() { cout << " << -- - shape1.cpp--->" << endl; Shape *shp[3]; shp[0] = new Rectangle(0, 0, 4, 4); shp[0]->perimeter(); shp[1] = new Circle(0, 0, 4); shp[1]->perimeter(); shp[2] = new Triangle(2, 2, 4, 4, 2, 4); shp[2]->perimeter(); } Rectangle::Rectangle(int a, int b, int c, int d) { x1 = a; y1 = b; x2 = c; y2 = d; } void Rectangle::perimeter() { peri = 2 * abs(x2 - x1) + 2 * abs(y2 - y1); cout << "perimeter of Rectangle is : " << peri << endl; } Circle::Circle(int a, int b, int r) { x0 = a; y0 = b; rad = r; } void Circle::perimeter() { //peri = 2 * geo::M_PI * rad; //cout << "perimeter of Circle is : " << peri << endl; } Triangle::Triangle(int a, int b, int c, int d, int e, int f) { x1 = a; y1 = b; x2 = c; y2 = d; x3 = e; y3 = f; } void Triangle::perimeter() { peri = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)) + sqrt((x3 - x2)*(x3 - x2) + (y3 - y2)*(y3 - y2)) + sqrt((x1 - x3)*(x1 - x3) + (y1 - y3)*(y1 - y3)); cout << "perimeter of triangle is : " << peri << endl; } /////////////////////////// //// TASKS //// /////////////////////////// // 1. What is the difference between static and dynamic binding? // 2. Differentiate between early binding and late binding. // 3. Object-oriented programming is programming with Polymorphism. Justify this with a good example. // 4. Can a derived class pointer point to base class object? Can a base class pointer point to derived class object? // 5. How is polymorphism achieved at run time? Explain with C++ coding. // 6. Explain the use of virtual functions with an example in the situation, where base class pointer points to derived class object. // 7. Write down all the rules with respect to virtual functions. // 8. What are pure virtual functions? Can classes having such functions be instantiated? // 9. What are abstract classes? Can such classes be instantiated? // 10. What is the use of an array of base class pointers? // 11. Discuss advantages and disadvantages of “array of base class pointers” // 12. Why member functions are not virtual by default? // 13. Study the concept of “interface” from java language. Can this concept be implemented (directly or indirectly) in C++? // 14. Define base class Window with virtual function show(). Let TextWindow and SplWindow classes inherit class window. // Class SplWindow is TextWindow with title bar. Write a program to demonstrate that pointer to class Window can display a text or special window. class Window { public: Window(); ~Window(); virtual void show(); private: }; Window::Window() { } Window::~Window() { } class TextWindow: public Window { public: TextWindow(); ~TextWindow(); void show(); private: }; TextWindow::TextWindow() { } TextWindow::~TextWindow() { } class SplWindow: public Window { public: SplWindow(); ~SplWindow(); void show(); private: }; SplWindow::SplWindow() { } SplWindow::~SplWindow() { } void PointerToBase() { Window *ptr; ptr = new Window(); ptr->show(); ptr = new TextWindow(); ptr->show(); ptr = new SplWindow(); ptr->show(); } void Window::show() { cout << "This is a base Window!" << endl; } void TextWindow::show() { cout << "This is an inherited TextWindow!" << endl; } void SplWindow::show() { cout << "This is an inherited SplWindow!" << endl; } // 15. Imagine a publishing company that markets both book and audiocassette version to its works. // Create a class publication that stores the title (a string) and price (type float) of a publication. // From this class derive two classes: book, which adds a page count (type int); and tape, which adds a playing time in minutes (type float). // Each of these three classes should have a getdata() function to gets its data from the user at the keyboard, and a putdata() function to display its data. // Write a main( ) program in C++ to test the book and tape classes by creating instances of them, asking the user to fill in data with getdata(), and then displaying the data with putdata(). class Publication { public: Publication(); ~Publication(); string getTitle(); void setTitle(string); float getPrite(); void setPrice(float); private: string title; float price; }; Publication::Publication() { } Publication::~Publication() { } class Book: public Publication { public: Book(); ~Book(); int getPageCount(); void setPageCount(int); private: int page_count; }; Book::Book() { } Book::~Book() { } class Tape: public Publication { public: Tape(); ~Tape(); float getPlayingTime(); void setPlayingTime(float); private: float playing_time; }; Tape::Tape() { } Tape::~Tape() { } void TestPublic() { Book *b1 = new Book(); b1->setTitle("This is a Titile"); b1->setPrice(1500); b1->setPageCount(345); Tape *t1 = new Tape(); t1->setTitle("Best Songs"); t1->setPrice(1450); t1->setPlayingTime(1.50); cout << "title: " << b1->getTitle() << endl; cout << "price: " << b1->getPrite() << endl; cout << "Page Count: " << b1->getPageCount() << endl; cout << "title: " << t1->getTitle() << endl; cout << "price: " << t1->getPrite() << endl; cout << "Playing Time: " << t1->getPlayingTime() << endl; } void Publication::setTitle(string t) { title = t; } string Publication::getTitle() { return title; } void Publication::setPrice(float p) { price = p; } float Publication::getPrite() { return price; } void Book::setPageCount(int pc) { page_count = pc; } int Book::getPageCount() { return page_count; } void Tape::setPlayingTime(float pt) { playing_time = pt; } float Tape::getPlayingTime() { return playing_time; } // 16. Write a class employee with two functions get_data() and put_data() to read the name and number of employee and display them, respectively. // Drive two classes, one manager and other scientist. In manager class add one more variable title. In scientist class add more variable publication and display them. class Employee2 { public: Employee2(); ~Employee2(); void get_data(); void put_data(string, int); private: string name; int number; }; Employee2::Employee2() { } Employee2::~Employee2() { } void Employee2::get_data() { cout << "name: " << name << endl; cout << "number: " << number << endl; } void Employee2::put_data(string pname, int pnumber) { name = pname; number = pnumber; } class Manager: public Employee2 { public: Manager(string); ~Manager(); void show(); private: string title; }; Manager::Manager(string t) { title = t; } Manager::~Manager() { } void Manager::show() { cout << "title: " << title << endl; } class Scientist: public Employee2 { public: Scientist(int); ~Scientist(); void show(); private: int publication; }; Scientist::Scientist(int p) { publication = p; } Scientist::~Scientist() { } void Scientist::show() { cout << "publication: " << publication << endl; } void TestOfEmployee2() { Manager *mg1 = new Manager("title1"); mg1->put_data("name 1", 10); Scientist *sc1 = new Scientist(2010); sc1->put_data("name2", 20); mg1->get_data(); mg1->show(); sc1->get_data(); sc1->show(); } // 17. Write a program in C++ that contains a class derived from base. The base class should have a virtual function show() and it should be overridden. // Try to call show() from the constructor of the base class and display the result. class BaseClass { public: BaseClass(); ~BaseClass(); virtual void show() = 0; private: }; BaseClass::BaseClass() { //show(); } BaseClass::~BaseClass() { } class DrivenClass: public BaseClass { public: DrivenClass(); ~DrivenClass(); void show() { cout << "this is a drive class" << endl; } private: }; DrivenClass::DrivenClass() { } DrivenClass::~DrivenClass() { } void TestVirtualOverridenFunc() { DrivenClass *dc = new DrivenClass(); // Linker error } // 18. Design a polymorphic class hierarchy for students of university. They are two types of students: day scholars and hostellers. // Assume that day scholars are having 30% fee concession (as they are not availing hostel facilities). Write a program to test this class. // Hint: Let “Student” be the abstract base class with method fee as pure virtual function. The derived classes may be named as Std_Dscho and Std_Host. class Student { public: Student(string, string, int); ~Student(); virtual void show() = 0; virtual float buy(int) = 0; string name; string department; int age; int price = 150; }; Student::Student(string n, string d, int a) { name = n; department = d; age = a; } Student::~Student() { } class Std_Dscho : public Student { public: Std_Dscho(string, string, int, string); ~Std_Dscho(); void show(); float buy(int money); private: string home_city; float conces = 0.3; }; Std_Dscho::Std_Dscho(string n, string d, int a, string h): Student(n, d, a) { home_city = h; } Std_Dscho::~Std_Dscho() { } class Std_Host : public Student { public: Std_Host(string, string, int, string); ~Std_Host(); void show(); float buy(int money); private: string hostel_name; float conces = 1.0; }; Std_Host::Std_Host(string n, string d, int a, string h): Student(n, d, a) { hostel_name = h; } Std_Host::~Std_Host() { } void TestStudents() { Std_Dscho *ds = new Std_Dscho("Endre", "Info", 28, "Kiralyhago"); Std_Host *hs = new Std_Host("Viktor", "Mernok", 26, "Gyori u"); cout << "buy: " << ds->buy(15000) << endl; ds->show(); cout << "buy: " << hs->buy(15000) << endl; hs->show(); } void Std_Dscho::show() { cout << "name: " << name << " department: " << department << " age: " << age << endl; cout << "home_city: " << home_city << endl; } void Std_Host::show() { cout << "name: " << name << " department: " << department << " age: " << age << endl; cout << "hostel_name: " << hostel_name << endl; } float Std_Dscho::buy(int money) { return money / (price * conces); } float Std_Host::buy(int money) { return money / (price * conces); } // 19. Design a polymorphic class hierarchy for closed shapes such as circle, rectangle and triangle. Also write a polymorphic function that calculates area of these shapes. // Write a program to test these classes. class Shape2 { public: Shape2(); ~Shape2(); virtual void area() = 0; }; Shape2::Shape2() { } Shape2::~Shape2() { } class Circle2: public Shape2 { public: Circle2(int, int, int); ~Circle2(); void area(); private: int radius; int x; int y; }; Circle2::Circle2(int r, int xc, int yc) { radius = r; x = xc; y = yc; } Circle2::~Circle2() { } class Rectangle2: Shape2 { public: Rectangle2(int, int, int, int, int, int, int, int); ~Rectangle2(); void area(); private: int x1, y1, x2, y2, x3, y3, x4, y4; }; Rectangle2::Rectangle2(int a, int b, int c, int d, int e, int f, int g, int h) { x1 = a; y1 = b; x2 = c; y2 = d; x3 = e; y3 = f; x4 = g; y4 = h; } Rectangle2::~Rectangle2() { } class Triangle2: public Shape2 { public: Triangle2(int, int, int, int, int, int); ~Triangle2(); void area(); private: int x1, y1, x2, y2, x3, y3; }; Triangle2::Triangle2(int a, int b, int c, int d, int e, int f) { x1 = a; y1 = b; x2 = c; y2 = d; x3 = e; y3 = f; } Triangle2::~Triangle2() { } void TestShape2() { } void Circle2::area() { //float area = radius * radius * M_PI; //cout << "area of circle: " << area << endl; } void Rectangle2::area() { float a = (y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1); float b = (y3 - y2) * (y3 - y2) + (x3 - x2) * (x3 - x2); float area = a * b; cout << "area of rectangle: " << area << endl; } void Triangle2::area() { float h = 1; float base = (y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1); float area = 0.5 * base * h; cout << "area of triangle: " << area << endl; } }
true
53fa09556bb020452ec881920883826842b4cd6e
C++
colinblack/game_server
/server/app/data/MineManager.cpp
UTF-8
4,968
2.609375
3
[]
no_license
/* * MineManager.cpp * * Created on: 2016-11-15 * Author: dawx62fac */ #include "MineManager.h" #include "DataInc.h" MineHole::MineHole() : uid_(0), level_(0), donate_cnt_(0) { } void MineHole::Reset() { uid_ = 0; level_ = 0; donate_cnt_ = 0; memset(donate_user_, 0, sizeof(donate_user_)); memset(name_, 0, sizeof(name_)); } bool MineHole::IsDonateFull() const { int cnt = 0; if (level_ == 0) { cnt = MineCfgWrap().GetKingdomDonateCnt(); } else { cnt = MineCfgWrap().GetNormalDonateCnt(level_); } if (cnt > DONATE_CNT_MAX) { error_log("mine_cfg_donate_cnt_error. %d", cnt); throw std::runtime_error("mine_cfg_donate_cnt_error"); } return (cnt == donate_cnt_); } bool MineHole::IsDonated(unsigned uid) const { for (int i = 0; i < (int)donate_cnt_; i++) { if (donate_user_[i] == uid) { return true; } } return false; } void MineHole::Donate(unsigned uid) { if (! IsOpen()) { throw std::runtime_error("the_mine_not_open"); } if (IsDonated(uid)) { throw std::runtime_error("already_donated"); } donate_user_[donate_cnt_ ++] = uid; } bool MineHole::IsOpen() const { return uid_ > 0; } void MineHole::Open(unsigned uid, const std::string& name, int exp) { if (uid_ > 0 && uid > 0) { throw std::runtime_error("the_mine_already_open"); } if (name.size() >= BASE_NAME_LEN) { throw std::runtime_error("name_too_long"); } uid_ = uid; if (exp >= 0) { level_ = MineCfgWrap().Exp2Level(exp); } else { level_ = 0; } donate_cnt_ = 0; memset(donate_user_, 0, sizeof(donate_user_)); memset(name_, 0, sizeof(name_)); memcpy(name_, name.c_str(), name.size()); } //////////////////////////////////////////////////////////////////////////////// const MineHole& MineKingdom::MineNoramlHoleIndex(unsigned index) const { if (index >= NORMAL_MINE_HOLE_CNT) { throw std::runtime_error("normal_mine_index_params_error"); } return normal_[index]; } MineHole& MineKingdom::MineNoramlHoleIndex(unsigned index) { if (index >= NORMAL_MINE_HOLE_CNT) { throw std::runtime_error("normal_mine_index_params_error"); } return normal_[index]; } void MineKingdom::AddRecord(const MineRecord& record) { if (record_ptr_ >= MINE_RECORD_MAX) { RomoveRecord(0, 10); } record_[record_ptr_++] = record; } void MineKingdom::RomoveRecord(unsigned index, unsigned nCnt) { if (record_ptr_ <= (int)index) { return ; } int mv_cnt = record_ptr_ - index - nCnt; if (mv_cnt <= 0) { record_ptr_ = index; return ; } memmove(record_ + index, record_ + index + nCnt, mv_cnt * sizeof(MineRecord)); record_ptr_ -= nCnt; } bool MineKingdom::IsMineMaster(unsigned uid) { for (int i = 0; i < NORMAL_MINE_HOLE_CNT; i++) { if (normal_[i].Uid() == uid) { return true; } } return false; } void MineKingdom::AddOpenNoramlMineRecord(unsigned uid , const std::string& operate , const MineHole& hole) { MineRecord record(e_OpenHole, 0); record.SetOperate(operate); record.SetParams(0, uid); record.SetParams(1, 0); record.SetParams(2, hole.Level()); AddRecord(record); } void MineKingdom::AddOpenKingdomMineRecord(unsigned uid , const std::string& operate) { MineRecord record(e_OpenHole, 1); record.SetOperate(operate); record.SetParams(0, uid); record.SetParams(1, 0); AddRecord(record); } void MineKingdom::AddNormalDonateRecord(unsigned uid , const std::string& operate, const MineHole& hole) { MineRecord record(e_Donate, 0); record.SetOperate(operate); record.SetTarget(hole.Name()); record.SetParams(0, uid); record.SetParams(1, hole.Uid()); record.SetParams(2, hole.Level()); record.SetParams(3, hole.DonateCnt()); record.SetParams(4, MineCfgWrap().GetNormalDonateCnt(hole.Level())); AddRecord(record); } void MineKingdom::AddKingdomDonateRecord(unsigned uid , const std::string& operate) { MineRecord record(e_Donate, 1); record.SetOperate(operate); record.SetParams(0, uid); record.SetParams(1, 0); AddRecord(record); } void MineKingdom::AddNormalHarvestRecord(const MineHole& hole, int val) { MineRecord record(e_MinersHarvest, 0); record.SetOperate(hole.Name()); record.SetParams(0, hole.Uid()); record.SetParams(1, 0); record.SetParams(2, hole.Level()); record.SetParams(3, val); AddRecord(record); } void MineKingdom::AddKingdomHarvestRecord(const MineHole& hole, int val) { MineRecord record(e_MinersHarvest, 1); record.SetOperate(hole.Name()); record.SetParams(0, hole.Uid()); record.SetParams(1, 0); record.SetParams(2, val); AddRecord(record); } void MineKingdom::AddKingdomRewardRecord(unsigned uid , const std::string& operate, int val) { MineRecord record(e_MineReward, 1); record.SetOperate(operate); record.SetParams(0, uid); record.SetParams(1, 0); record.SetParams(2, val); AddRecord(record); } void MineKingdom::FullMessage(::google::protobuf::RepeatedPtrField< ::ProtoMine::MineRecord >* obj) { for (int i = 0; i < record_ptr_; i++) { record_[i].FullMessage(obj->Add()); } }
true
4600130cc595989c3223772d1cadc85b3d789721
C++
chenxiaohui/leetcode
/leetcode/TrappingRainWater.cpp
UTF-8
507
3.109375
3
[]
no_license
/* Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! */ #include "common.h" class Solution { public: }; Solution s; TEST(TrappingRainWater, normal) { }
true
885e3ffa322fb7ccf7327c646c18a2a79873ec86
C++
MorgFost96/School-Projects
/Data Structures/Labs/LinearSearch/LinearSearch.cpp
UTF-8
1,299
3.90625
4
[]
no_license
#include <iostream> #include <iomanip> using namespace std; int main() { int num; //User Input of Array Size cout << "Enter in a Number: "; cin >> num; int array[1000]; int i, key; for (int z = 0; z < num; z++) { cout << "Enter " << z << " Number: "; cin >> array[z]; } //Index for (int x = 0; x < num; x++) { cout << "Array[ " << x << " ] = "; cout << array[x] << endl; } //User enter's in a number and it will display the Index of where it's found cout << "Enter Key to find in the Array: "; cin >> key; //this loop is used to have the local variable 'i' used for (i = 0; i < num; i++) { if (key == array[i]) { cout << "Key found at the Index: " << i << endl; break; } } //it will then print a double Found Index Key or NOT FOUND in the Array if (i != num) { cout << "Key Found at the Index: " << i << endl; } else { cout << "Key Not Found in Array " << endl; } system("PAUSE"); return -1; } //Enter in a Number : 5 //Enter 0 Number : 20 //Enter 1 Number : 3 //Enter 2 Number : 21 //Enter 3 Number : 10 //Enter 4 Number : 6 //Array[0] = 20 //Array[1] = 3 //Array[2] = 21 //Array[3] = 10 //Array[4] = 6 //Enter Key to find in the Array : 10 //Key found at the Index : 3 //Key Found at the Index : 3 //Press any key to continue . . .
true
6b2d29ab82303de709e5b6885ebd9bc5bcb8b98f
C++
madhok/Craftsmanship
/Arrays/Rotation_ntimes.cpp
UTF-8
991
3.921875
4
[]
no_license
/* Given a sorted array which is rotated 'N' times. Find the value of 'N'. Input: The first line contains an integer T, depicting total number of test cases. Then following T lines contains an integer N depicting the size of array and next line followed by the value of array. Output: Print the value of 'n'. Constraints: 1 ≤ T ≤ 40 1 ≤ N ≤ 100 0 ≤ A[i] ≤ 100 Example: Input 2 5 5 1 2 3 4 5 1 2 3 4 5 Output 1 0 */ #include <iostream> using namespace std; int n_rotation(int* A, int size) { if(size == 0) return 0; int prev = A[0]; int ncount=0; for(int i=1;i<size;++i) { if(prev>A[i]) { ncount =i; } prev = A[i]; } return ncount; } int main() { //code int n; cin >>n; while(n) { n--; int size; cin >> size; int A[size]; for(int i = 0;i<size;++i) { int val; cin>>val; A[i] = val; } cout << n_rotation(A, size) << endl; } return 0; }
true
3e49a3ddab3517260a93077c367af876cdec9b63
C++
biqar/interviewbit
/Tree Data Structure/Level order/ZigZag Level Order Traversal BT/zigzag_levelorder.cpp
UTF-8
1,542
3.015625
3
[ "MIT" ]
permissive
// // Created by Islam, Abdullah Al Raqibul on 11/26/19. // /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ vector<vector<int> > Solution::zigzagLevelOrder(TreeNode* A) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details vector<vector<TreeNode*> > tr; vector<TreeNode*> t, c; vector<vector<int> > ret; vector<int> v; int turn = 0; v.push_back(A->val); ret.push_back(v); t.push_back(A); tr.push_back(t); while(true) { t = tr[turn]; v.clear(); c.clear(); int sz = t.size(); if(sz == 0) break; for(int i=0; i<sz; i+=1) { if(t[i]->left != NULL) { c.push_back(t[i]->left); } if(t[i]->right != NULL) { c.push_back(t[i]->right); } } sz = c.size(); if(sz == 0) break; if(turn%2 == 0) { for(int i=sz-1; i>=0; i-=1) { v.push_back(c[i]->val); } } else { for(int i=0; i<sz; i+=1) { v.push_back(c[i]->val); } } ret.push_back(v); tr.push_back(c); turn += 1; } return ret; }
true
3c4ec770279979f87188d040e24a66d3fa0de154
C++
shubhampathak09/dynamic-programming-and-arrays
/CP guide/reverse a linked list.cpp
UTF-8
761
3.328125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; struct node { int data; struct node*next; node(int data) { this->data=data; next=NULL; } }; struct node* reverse(struct node*root) { struct node*curr=root; struct node*temp=NULL; struct node*prev=NULL; while(curr!=NULL) { temp=curr->next; curr->next=prev; prev=curr; curr=temp; } return prev; } //void printlist() int main() { struct node*head=new node(1); head->next=new node(2); head->next->next=new node(3); head->next->next->next=new node(4); struct node*temp=head; while(temp!=NULL) { cout<<temp->data<<" "; temp=temp->next; } cout<<endl; struct node*ne=reverse(head); while(ne!=NULL) { cout<<ne->data<<" "; ne=ne->next; } }
true
f762bf1f2596540b7480d766304795a2595450b9
C++
danineamati/RoboticsDitchDay2019
/LCDDisplayCode/LCDDisplayCode.ino
UTF-8
1,688
3.171875
3
[]
no_license
#include <Wire.h> #include <LiquidCrystal_PCF8574.h> #include "LCD_functions.h" LiquidCrystal_PCF8574 lcd(0x27); // set the LCD address to 0x27 for a 16 chars and 2 line display int show; void setup() { int error; Serial.begin(115200); Serial.println("LCD..."); // See http://playground.arduino.cc/Main/I2cScanner Wire.begin(); Wire.beginTransmission(0x27); //Your LCD Address error = Wire.endTransmission(); Serial.print("Start Up Status: "); Serial.print(error); if (error == 0) { Serial.println(": LCD found."); } else { Serial.println(": LCD not found."); } lcd.begin(16, 2); // initialize the lcd show = 0; } void loop() { // Test left shift text if (true) { dispTextShift(lcd, "Hello World!", "From your man :)"); delay(1000); lcd.setBacklight(0); delay(400); lcd.setBacklight(255); } // Test Scrolling Text without parsings if (true) { dispTextScroll(lcd, "Hello World from an LCD. From your main man :). Welcome to Arduino Land!"); delay(1000); lcd.setBacklight(0); delay(400); lcd.setBacklight(255); } // Test String Comprehension if (false) { int numWords = countWords("1 2 3 4 5 6"); dispTextSimplest(lcd, String(numWords), ""); String words[numWords]; parseString("1 2 3 4 5 6", numWords, words); for (int i = 0; i < numWords; ++ i) { Serial.println(words[i]); } } // Test Scrolling Text WITH parsing if (true) { dispWordsScroll(lcd, "Hello World from an LCD. From your main man :). Welcome to Arduino Land"); delay(1000); lcd.setBacklight(0); delay(400); lcd.setBacklight(255); } delay(2000); }
true
362a8317f639882ab8fbae2dc944d3ae724827a6
C++
wangfuli217/ld_note
/cheatsheet/ops_doc-master/Service/cfaq/example_c/timer/LinkList.h
UTF-8
1,531
2.765625
3
[]
no_license
/** * @brief: Ò»¸ö°üÀ¨¶¨Ê±Æ÷½áµãµÄË«ÏòÁ´±í * Ò»¸öÂÖ×Ó£¬²å²Û´óСΪm_size,±íʾÿһ¸ö²å²Û¶¼ÓÐÒ»¸öË«ÏòÁ´±í¡£ * * @Author:Expter * @date: 03/01/2010 */ #ifndef __LINK_LIST_H_ #define __LINK_LIST_H_ #include "TypeDef.h" #include "tools.h" /// /// Ò»¸öÂÖ×Ó,Ò»¸öÑ­»·¶ÓÁÐ /// /// class CLinkList { public: CLinkList(void); CLinkList( int size ); ~CLinkList(void); /// /// ³õʼ»¯ /// void init(); /// /// ÈÃÖ¸ÕëÖ¸Ïò×Ô¼º /// void init_list_self( int index); /// /// °Ñnews²åÈëµ½prev,nextÖ®¼ä /// void insert_listnode(ListNode *news , ListNode* prev , ListNode* next); /// /// ²åÈëµ½Á´±íÍ· /// void insert_head( ListNode* news , ListNode* head ); /// /// ²åÈëµ½Á´±íβ /// void insert_tail( ListNode* news , ListNode* head ); /// /// ɾ³ý½Úµã /// void list_del( ListNode* list); /// /// µÃµ½¸ÄÂÖ×Óתµ½µÚ¼¸¸ö²å²Û /// int GetIndex( ) const { return m_index ;} /// /// ¸üÐÂÂÖ×ӵIJå²Û /// void SetIndex(int idx) { m_index = idx ;} /// /// µÃµ½ÂÖ×Ó²å²ÛµÄÖ¸Õë /// ListNode* GetNode(int index) const; private: /// /// ÂÖ×ӵIJå²ÛÊý×é /// ListNode *m_List; /// /// ÂÖ×Óµ±Ç°×ªµ½µÄË÷Òý /// int m_index; /// /// ÂÖ×Ó´óС /// int m_Size; }; #endif
true
792f4a2e99741b7cff4164ac7682448c8c65baeb
C++
jainsourav43/DSA
/dsa/General Questions/hw 3.cpp
UTF-8
695
3.109375
3
[]
no_license
#include<iostream> using namespace std; int maxe=0,mini,avg,sum1=0;int k=0; void sum(int *p,int s) { if(s==0) {cout.setf(ios::fixed); cout.precision(2); cout<<"average\n"<<float(sum1)/k<<endl; return ; } else { k++; if((*p)> maxe) { maxe=*p; } if((*p)<mini) { mini=*p; } sum1=sum1+*p; sum(p+1, s-1); } } int main() { int n; cout<<"Enter the no. of elements\n"; cin>>n; int i,j,k; int a[n]; for(i=0;i<n;i++) { cin>>a[i]; } mini=a[0]; cout.setf(ios::fixed); cout.precision(2); sum(a,n); cout<<"Minimum =" <<mini<<endl; cout<<"Maximum = "<<maxe<<endl; cout<<"Sum ="<<sum1<<endl; return 0; }
true
0e72009cfe3884579931fdeeae312fafa5351d5d
C++
JuliaYu2002/HunterDE
/Comp Sci 135+136/box.cpp
UTF-8
657
3.359375
3
[]
no_license
// Author: Julia Yu // Date: February 23, 2020 // Course: CSCI-135 // Instructor: Prof. Maryash // Assignment: Lab 4A #include <iostream> using namespace std; int main(){ int width, height; cout << "Enter width: "; cin >> width; cout << "Enter height: "; cin >> height; cout << endl << "Shape: " << endl; for (int i = 0; i < height; i++){ //Loop for the height of the box for (int j = 0; j < width; j++){ //Loop for the width of the box cout << "*"; //Prints * for each row } cout << endl; //When it reaches the end of the row, it starts a new line } return 0; }
true
abd5020f7094244731907f0f60966e0deb6a6bbb
C++
hantengx/LeetCode
/src/string/ReverseInteger.h
UTF-8
427
2.796875
3
[]
no_license
// // Created by hanteng on 2018/9/9. //给定一个 32 位有符号整数,将整数中的数字进行反转。 // //示例 1: // //输入: 123 //输出: 321 // // 示例 2: // //输入: -123 //输出: -321 // //示例 3: // //输入: 120 //输出: 21 #ifndef LEETCODE_REVERSEINTEGER_H #define LEETCODE_REVERSEINTEGER_H class ReverseInteger { public: static int reverse(int x); }; #endif //LEETCODE_REVERSEINTEGER_H
true
1bd6f1b53a33774d1417392eb0b01f18eb31939e
C++
MasterWangdaoyong/My-C--Primer-Plus
/Learn/程序清单 6-6.cpp
UTF-8
731
3.078125
3
[]
no_license
// more and // 程序清单 6-6.cpp // C++ Primer Plus // // Created by 王道勇 on 2017/5/29. // Copyright © 2017年 王道勇. All rights reserved. // #include <iostream> const char * qualify[4] = { "10,000-meber race.\n", "mud tug-of-war.\n", "masters canoe jousting.\n", "pie-throwing festival.\n" }; int main() { using namespace std; int age; cout << "Enter your age in years: "; cin >> age; int index; if (age > 17 && age < 35) index = 0; else if (age >= 35 && age < 50) index = 1; else if (age >= 50 && age < 65) index = 2; else index = 3; cout << "You qualify for the " << qualify[index]; return 0; }
true
891bd93e21ff458c1cd86697ef6866ba9e9b6217
C++
vlongle/HuffmanCompression
/Encoder/HuffmanEncoder.h
UTF-8
880
2.859375
3
[]
no_license
// // Encoder.h // // // Created by Le Nguyen VIet Long on 3/13/18. // #ifndef Encoder_h #define Encoder_h #include "HuffmanPriorityQueue.h" #include <map> // Implemementation of Queue needed for BFS tranversal // Because the implementation of Queue is quite short, it's included in the header #define CAPACITY 9999 class Queue{ public: Node* dQueue; int head; // the current USED top of the dArray int tail; // the first UNUSED element Queue(){ dQueue = new Node[CAPACITY]; head = 0; tail = 0; } void enqueue(Node incoming){ dQueue[tail] = incoming; tail +=1; } Node dequeue(){ head +=1; return dQueue[head-1]; } }; class Encoder{ public: int* size; Node* readInData(std::string filePath); std::map<std::string, std::string> BFSTranversal(Node topNode); }; #endif /* Encoder_h */
true
d2e598f43d863bf4767421cddf5c30793f14bffd
C++
BlueHorn07/ProblemSolving
/solutions/BAEKJOON/9020.cpp
UTF-8
772
3
3
[]
no_license
#include<bits/stdc++.h> #define MAX 10005 using namespace std; bool isPrime[MAX]; void goldbach() { int n; scanf("%d", &n); for (int i = 2; i <= n / 2 + 1; i++) { if (!isPrime[i]) continue; // prime이 아니라면, 패스 for (int j = i + i; j <= n; j += i) { isPrime[j] = false; } } int ans = 2; for (int i = 2; i <= n / 2; i++) { if (!isPrime[i]) continue; // prime이 아니면 패스 if (!isPrime[n - i]) continue; // conjugate가 prime이 아니면 패스 ans = i; } printf("%d %d\n", ans, n - ans); } int main() { int T; scanf("%d", &T); fill_n(isPrime, MAX, true); isPrime[0] = false; isPrime[1] = false; for (int t = 0; t < T; t++) { goldbach(); } return 0; }
true
5a6443ba9de10e6c4b4a8e2fe878635dc2eaeb4b
C++
jjzhang166/BOSS_ExternalLibs
/BOSS/Identifier/BesDetectorID.cxx
UTF-8
2,202
2.5625
3
[]
no_license
#include "Identifier/BesDetectorID.h" #include <iostream> #include <stdio.h> #include <assert.h> BesDetectorID::BesDetectorID(void) : m_MdcId(BesDetectorID::MDC_ID), m_TofId(BesDetectorID::TOF_ID), m_EmcId(BesDetectorID::EMC_ID), m_MucId(BesDetectorID::MUC_ID), m_HltId(BesDetectorID::HLT_ID), m_MrpcId(BesDetectorID::MRPC_ID) { } BesDetectorID::~BesDetectorID(void) { } bool BesDetectorID::is_mdc (const Identifier& id) const { Identifier::value_type value = id.get_value(); return ((value & MDC_MASK) >> MDC_INDEX) == MDC_ID ? true : false; } bool BesDetectorID::is_tof (const Identifier& id) const { Identifier::value_type value = id.get_value(); return ((value & TOF_MASK) >> TOF_INDEX) == TOF_ID ? true : false; } bool BesDetectorID::is_emc (const Identifier& id) const { Identifier::value_type value = id.get_value(); return ((value & EMC_MASK) >> EMC_INDEX) == EMC_ID ? true : false; } bool BesDetectorID::is_muc (const Identifier& id) const { Identifier::value_type value = id.get_value(); return ((value & MUC_MASK) >> MUC_INDEX) == MUC_ID ? true : false; } bool BesDetectorID::is_hlt (const Identifier& id) const { Identifier::value_type value = id.get_value(); return ((value & HLT_MASK) >> HLT_INDEX) == HLT_ID ? true : false; } bool BesDetectorID::is_mrpc (const Identifier& id) const { Identifier::value_type value = id.get_value(); return ((value & MRPC_MASK) >> MRPC_INDEX) == MRPC_ID ? true : false; } Identifier BesDetectorID::mdc(void) const { Identifier id = Identifier( m_MdcId << MDC_INDEX ); return id; } Identifier BesDetectorID::tof(void) const{ Identifier id = Identifier( m_TofId << TOF_INDEX ); return id; } Identifier BesDetectorID::emc(void) const { Identifier id = Identifier( m_EmcId << EMC_INDEX ); return id; } Identifier BesDetectorID::muc(void) const { Identifier id = Identifier( m_MucId << MUC_INDEX ); return id; } Identifier BesDetectorID::hlt(void) const { Identifier id = Identifier( m_HltId << HLT_INDEX ); return id; } Identifier BesDetectorID::mrpc(void) const { Identifier id = Identifier( m_MrpcId << MRPC_INDEX ); return id; }
true
070631ac98cfb482d8d904167fbff325c5c0f9af
C++
MBU-Team/OpenMBU
/engine/source/gfx/gfxResource.h
UTF-8
2,267
2.625
3
[]
no_license
//----------------------------------------------------------------------------- // Torque Game Engine Advanced // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- #ifndef _GFX_GFXRESOURCE_H_ #define _GFX_GFXRESOURCE_H_ #include "platform/types.h" class GFXDevice; /// Mixin for the purpose of tracking GFX resources owned by a GFXDevice. /// /// There are many types of resource that are allocated from a GFXDevice that /// must be participatory in device resets. For instance, all default pool /// DirectX resources have to be involved when the device resets. Render /// targets in all APIs need to unbind themselves when resets happen. /// /// This system is also handy for accounting purposes. For instance, we may /// want to traverse all registered VBs, IBs, Textures, or RTs in order to /// determine what, if any, items are still allocated. This can be used in /// leak reports, memory usage reports, etc. class GFXResource { private: friend class GFXDevice; GFXResource *mPrevResource; GFXResource *mNextResource; GFXDevice *mOwningDevice; /// Helper flag to check new resource allocations bool mFlagged; public: GFXResource(); ~GFXResource(); /// Registers this resource with the given device void registerResourceWithDevice(GFXDevice *device); /// When called the resource should destroy all device sensitive information (e.g. D3D resources in D3DPOOL_DEFAULT virtual void zombify()=0; /// When called the resource should restore all device sensitive information destroyed by zombify() virtual void resurrect()=0; /// The resource should put a description of itself (number of vertices, size/width of texture, etc.) in buffer virtual void describeSelf(char* buffer, U32 sizeOfBuffer) = 0; inline GFXResource *getNextResource() const { return mNextResource; } inline GFXResource *getPrevResource() const { return mPrevResource; } inline GFXDevice *getOwningDevice() const { return mOwningDevice; } inline bool isFlagged() { return mFlagged; } inline void setFlag() { mFlagged = true; } inline void clearFlag() { mFlagged = false; } }; #endif
true
920558362826934f75fdb8194f541a3bb7c688ab
C++
mghosal10/Design-Analysis-And-Algorithms
/Programming Assignment 6/BinarySearchTree/BST.cpp
UTF-8
4,875
3.578125
4
[]
no_license
#include <iostream> //#include <iomanip> using namespace std; #include "BST.h" //--- Definition of constructor BST::BST() : myRoot(0) {} bool BST::empty() const { return myRoot == 0; } bool BST::search(const int & item) const { BinNode * locptr = myRoot; bool found = false; while (!found && locptr != 0) { if (item < locptr->data) // descend left locptr = locptr->left; else if (locptr->data < item) // descend right locptr = locptr->right; else // item found found = true; } return found; } void BST::insert(const int & item) { BinNode * locptr = myRoot; // search pointer BinNode * parent = 0; // pointer to parent of current node bool found = false; // indicates if item already in BST while (!found && locptr != 0) { parent = locptr; if (item < locptr->data) // descend left locptr = locptr->left; else if (locptr->data < item) // descend right locptr = locptr->right; else // item found found = true; } if (!found) { // construct node containing item locptr = new BinNode(item); if (parent == 0) // empty tree myRoot = locptr; else if (item < parent->data ) // insert to left of parent parent->left = locptr; else // insert to right of parent parent->right = locptr; } else cout << "Item already in the tree\n"; } void BST::delete_node(const int & item) { BinNode * locptr = myRoot; BinNode * parent = 0; bool found = false; while (!found && locptr != 0) { if (item < locptr->data) // descend left { parent = locptr; locptr = locptr->left; } else if (locptr->data < item) // descend right { parent = locptr; locptr = locptr->right; } else // item found { found = true; } } if(found) { // for nodes that have no children if(locptr->left == 0 && locptr->right == 0) { if(locptr != myRoot) { if(parent->left == locptr) { parent->left = 0; } else { parent->right = 0; } free(locptr); } else { myRoot = 0; } } // for nodes that have 2 children else if(locptr->left && locptr->right) { parent = locptr; child = locptr->left; while (child->right != 0) { parent = child; child = child->right; } if(parent == locptr) { locptr->data = child->data; locptr->left = child->left; } else { locptr->data = child->data; parent->right = child->left; } } // for nodes that have one child else { BinNode * single_child = locptr->left ? locptr->left : locptr->right; if(locptr != myRoot) { if(locptr == parent->left) { parent->left = single_child; } else { parent->right = single_child; } } else { myRoot = single_child; } free(locptr); } } else { cout << "Node not found!"; } } void BST::preOrder_call() { preOrder(myRoot); } void BST::inOrder_call() { inOrder(myRoot); } void BST::postOrder_call() { postOrder(myRoot); } int BST::countNodes_call() { int counted = countNodes(myRoot); counted = counted - 1; return counted; } void BST::preOrder(BinNode * bin) { if(bin != 0) { cout << bin->data << " "; preOrder(bin->left); preOrder(bin->right); } } void BST::inOrder(BinNode * bin) { if(bin != 0) { inOrder(bin->left); cout << bin->data << " "; inOrder(bin->right); } } void BST::postOrder(BinNode * bin) { if(bin != 0) { postOrder(bin->left); postOrder(bin->right); cout << bin->data << " "; } } int BST::countNodes(BinNode * bin) { int count = 1; if(bin == 0) { return count; } else { count = countNodes(bin->left); count = count + countNodes(bin->right); } return count; }
true
73c65f2ca289db9acfdd85b401a8388e3cd5c059
C++
Dwarfius/GP1
/Coursework/cSettings.cpp
UTF-8
1,689
3.25
3
[]
no_license
#include "cSettings.h" #include <iostream> #include <fstream> #include <string> #pragma warning(disable : 4244) using namespace std; cSettings* cSettings::singleton = 0; cSettings::cSettings() { //basic settings drawBackground = true; volume = 0.5f; memset(scores, 0, sizeof(scores)); Deserialize(); //attempt to get up to date settings } void cSettings::Serialize() { fstream file("settings.txt", ios::out | ios::trunc); //open up the file for clean write file << to_string(drawBackground) << endl; //write down the settings file << to_string(volume) << endl; for (int i = 0; i < 10 && scores[i] != 0; i++) //don't write out end zeroes file << to_string(scores[i]) << endl; file.close(); } void cSettings::Deserialize() { fstream file("settings.txt", ios::in); //open up for reading if (!file.is_open()) //if doesn't exist, fall back to basic settings return; string line; //otherwise, parse it int i = 0; while (getline(file, line)) { if (i == 0) drawBackground = line == "1"; else if (i == 1) volume = atof(line.c_str()); else scores[i - 2] = atoi(line.c_str()); i++; } file.close(); } void cSettings::AddScore(int score) //add score while still keeping it sorted { for (int i = 0; i < 10; i++) { if (score > scores[i]) { SwapDown(scores[i], i + 1); scores[i] = score; Serialize(); return; } } } //utility - recursion to push scores down void cSettings::SwapDown(int val, int index) { if (index == 10 || val == 0) return; SwapDown(scores[index], index + 1); scores[index] = val; } //resetting of scores and writing them down void cSettings::ClearScores() { memset(scores, 0, sizeof(scores)); Serialize(); }
true
3b076088ec22344b68f380ed0524e353d2396704
C++
taku-xhift/labo
/c++/boost/Mutex/WriteLockWithOtherThreadRead.cpp
UTF-8
971
2.703125
3
[ "MIT" ]
permissive
 #include <iostream> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/shared_mutex.hpp> #include <Windows.h> typedef boost::shared_mutex Mutex; typedef boost::shared_lock<Mutex> ReadLock; typedef boost::upgrade_lock<Mutex> UpLock; typedef boost::upgrade_to_unique_lock<Mutex> WriteLock; Mutex mutex_; int resource = 0; void read() { ReadLock read(mutex_); std::cerr << "Read...\n"; //UpLock uplock(mutex_); Sleep(2000); std::cerr << "resource => " << resource << "\n"; std::cerr << "End!\n"; } void write() { UpLock uplock(mutex_); WriteLock write(uplock); resource = 100; std::cerr << "resource => " << resource << "\n"; std::cerr << "writen !\n"; } int main() { boost::thread threadRead(boost::ref(*read)); boost::thread threadWrite(boost::ref(*write)); threadRead.join(); threadWrite.join(); }
true
86c88d4b85b9c32446ba61a8284a0fac9f859832
C++
powellm123/letsmakeagame
/LetsMakeAGame/src/DateTime.h
UTF-8
1,525
3.140625
3
[]
no_license
#pragma once #include <time.h> #include <iostream> struct DateTime { int year; int month; int day; int hour; int minute; int second; static DateTime Now() { time_t theTime = time(0); tm *atm = new tm(); localtime_s(atm, &theTime); DateTime dt; dt.year = atm->tm_year; dt.month = atm->tm_mon; dt.day = atm->tm_mday; dt.hour = atm->tm_hour; dt.minute = atm->tm_min; dt.second = atm->tm_sec; return dt; } static DateTime Today() { time_t theTime = time(0); tm *atm = new tm(); localtime_s(atm, &theTime); DateTime dt; dt.year = atm->tm_year; dt.month = atm->tm_mon; dt.day = atm->tm_mday; return dt; } DateTime& operator=(const DateTime &arg) { if (this != &arg) { year = arg.year; month = arg.month; day = arg.day; hour = arg.hour; minute = arg.minute; second = arg.second; } } DateTime& operator-(const DateTime& other) { DateTime dt; dt.year = this->year - other.year; dt.month = this->month - other.month; dt.day = this->day - other.day; dt.hour = this->hour - other.hour; dt.minute = this->minute - other.minute; dt.second = this->second - other.second; return dt; } std::ostream& operator<<(std::ostream& os) { os << year << "/" << month << "/" << day << "T" << hour << ":" << minute << ":" << second; // write obj to stream return os; } std::istream& operator>>(std::istream& is) { char dk; is >> year >> dk >> month >> dk >> day >> dk >> hour >> dk >> minute >> dk >> second; return is; } };
true
d26defcad819c1f9df7bb826f555b58ee49aac35
C++
malirod/cpputils
/src/core/general_error.h
UTF-8
827
2.671875
3
[ "MIT" ]
permissive
// Copyright [2018] <Malinovsky Rodion> #pragma once #include <string> #include <system_error> namespace rms { namespace core { enum class GeneralError { Success, InternalError, WrongCommandLine, StartupFailed, }; class ErrorCategory : public std::error_category { public: const char* name() const noexcept override; std::string message(int error_value) const override; static const std::error_category& get(); protected: ErrorCategory() = default; }; std::error_condition make_error_condition(GeneralError error) noexcept; std::error_code make_error_code(GeneralError error) noexcept; } // namespace core } // namespace rms // Register for implicit conversion to error_condition namespace std { template <> struct is_error_condition_enum<rms::core::GeneralError> : public true_type {}; } // namespace std
true
d106b75b0b56348e6b71feaf34deda985a179de3
C++
viZu/nasca
/src/main/resources/root_helper.h
UTF-8
818
2.828125
3
[ "Apache-2.0" ]
permissive
#ifndef ROOT_HELPER_H #define ROOT_HELPER_H #include <string> #include <sstream> #include <vector> #include <fstream> #include <memory> std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::shared_ptr<std::vector<std::string> > splitString(const std::string &s, char delim) { std::vector<std::string> *elems = new std::vector<std::string>(); split(s, delim, *elems); return std::shared_ptr<std::vector<std::string>>(elems); } std::string readFile(const std::string filename) { std::ifstream t(filename); std::stringstream buffer; buffer << t.rdbuf(); return buffer.str(); } #endif
true
ce995190075518f6a253ec4959b57e977809e5f9
C++
dodo0095/Color-Balancing2015
/src/graph.cpp
UTF-8
23,895
3.203125
3
[]
no_license
#include "graph.h" #include <iostream> #include <fstream> #include <queue> #include <algorithm> #include <cmath> #include <limits> #include <bitset> #include <stdlib.h> #include <time.h> #include <assert.h> using namespace std; //把input。x1 y1 x2 y2放進來 void Graph::addNode( Node* nptr) { nodesMap[nptr->id]=nptr; nodes.push_back(nptr); } //////////開始畫圖graph/////////////////////////// //graph套件。 檢查二個點xy座標。有沒有連再一起 bool NodeCompByX(const Node* A, const Node* B ) { if(A->lb_x < B->lb_x) return true; else return false; } void Graph::sortNodesByX() { sort(nodes.begin(), nodes.end(), NodeCompByX); } bool NodeCompByY(const Node* A, const Node* B ) { if(A->lb_y < B->lb_y) return true; else return false; } void Graph::sortNodesByY() { sort(nodes.begin(), nodes.end(), NodeCompByY); } bool Node::overlap(Node* n,const int & alpha,const int & beta) //從最左邊開始到最右 邊 { int check_lb_y=lb_y-beta; int check_ru_x=ru_x+alpha; int check_ru_y=ru_y+beta; //cout<<id<<" calling overlap on "<<n->id<<endl; if ((n->lb_x>=lb_x)&&(n->lb_x<=check_ru_x)) { if (((n->lb_y>=check_lb_y)&&(n->lb_y<=check_ru_y))//left bottom inside ||((n->ru_y>=check_lb_y)&&(n->ru_y<=check_ru_y)))//left upper inside { if ((n->lb_x>=ru_x)&&((n->lb_y>=ru_y)||(n->ru_y<=lb_y))) { //cout<<"invalid !!"<<endl; return false; } return true; } else if ((n->lb_y<=check_lb_y)&&(n->ru_y>=check_ru_y))// be included return true; } return false; } // 根據題目的alpha,beta 創造出圖 void Graph::constructAll() { sortNodesByX(); unsigned int j=0; for (unsigned int i=0;i<nodes.size();++i) { j=i+1; for (;j<nodes.size();++j) { //cout<<i<<" calling "<<j<<endl; if((nodes[j]->lb_x)>nodes[i]->ru_x+alpha) { break; } if (nodes[i]->overlap(nodes[j],alpha,beta)) { Edge *e = new Edge(nodes[i], nodes[j]); edges.push_back(e); nodes[i]->edge.push_back(e); nodes[j]->edge.push_back(e); } } } } //////////dfs/////////////////////////// //開始用algorihm走圖形。 這邊使用DFS void Graph::init() //初始化 { map<int, Node *>::iterator itN; for ( itN = nodesMap.begin() ; itN != nodesMap.end() ; itN++ ) { Node *node = (*itN).second; node->traveled = false; node->prev = 0; node->color = -1;//把所有點node 都用尚未探訪 } } void Graph::sortEdgesOfNode() // 把edge排列 { map<int, Node *>::iterator it; for ( it = nodesMap.begin() ; it != nodesMap.end() ; it++ ) { Node *node = (*it).second; node->sortEdge(); } } bool NodeCompByID( const Node* A, const Node* B ){ if ( A->id < B->id ) return true; else return false; } bool edgeComp( const Edge* A, const Edge* B ){ if ( (*A) < (*B) ) return true; return false; } void Node::sortEdge() //用edge排列 { sort(edge.begin(), edge.end(), edgeComp); } void Graph::sortNodesByID() //用id排列 { sort(nodes.begin(), nodes.end(), NodeCompByID); } void Graph::dfs() { init(); int edgenum=0, group_num = 0; sortEdgesOfNode(); sortNodesByID(); for(unsigned int i=0;i<nodes.size();++i) { if(!(nodes[i] -> traveled)) { Group* group = new Group; dfsvisit(nodes[i], group_num, group); groups.push_back(group); // 出來的解果會幫忙分群。 相同froup的會放在同一群 ++group_num; } } } void Graph::dfsvisit(Node* u, int group_num, Group* group) { u -> group_id = group_num; u->traveled = true; group -> groupNodes.push_back(u); for(unsigned int i = 0; i < u -> edge.size(); ++i) { Node* near = u -> edge[i] -> getNeighbor(u); if (near->traveled == false) { dfsvisit(near, group_num, group); } } } //////////////////開始給顏色//////////////////////// Node * Edge::getNeighbor(Node *n) { if ( node[0] == n ) return node[1]; if ( node[1] == n ) return node[0]; return 0; } void Graph::colorgraph() { colored_graph=0; init(); for(unsigned int i=0;i<groups.size();i++) { Node* sourcenode=groups[i]->groupNodes[0]; queue<Node*> nodesque; sourcenode->color=0; sortEdgesOfNode(); nodesque.push(sourcenode); bool stop=false; while (nodesque.empty()==false&&stop==false) { Node * u=nodesque.front(); if(0==u->color) { for(unsigned int k=0;k<u->edge.size();++k) { Node* near= u->edge[k]->getNeighbor(u); if (-1==near->color) { near->color=1; nodesque.push(near); } else if(0==near->color) { Group* temp=groups[i]; groups[i]=groups[colored_graph]; groups[colored_graph]=temp; colored_graph++; stop=true; break; } } } else if(1==u->color) { for(unsigned int k=0;k<u->edge.size();++k) { Node* near= u->edge[k]->getNeighbor(u); if (-1==near->color) { near->color=0; nodesque.push(near); } else if(1==near->color) { Group* temp=groups[i]; groups[i]=groups[colored_graph]; groups[colored_graph]=temp; colored_graph++; stop=true; break; } } } nodesque.pop(); } } } //////////////////////input讀上下界//////////////////////////// //////////////////////上下界存在B_top B_bottom B_right left裡面//////////////////////////// void Graph::getboxsize() { for(unsigned int i=colored_graph;i<groups.size();i++) { for(unsigned int j=0;j<groups[i]->groupNodes.size();j++) { //lb_x,lb_y,ru_x,ru_y if(groups[i]->groupNodes[j]->ru_y>B_top) B_top=groups[i]->groupNodes[j]->ru_y; if(groups[i]->groupNodes[j]->lb_y<B_bottom) B_bottom=groups[i]->groupNodes[j]->lb_y; if(groups[i]->groupNodes[j]->ru_x>B_right) B_right=groups[i]->groupNodes[j]->ru_x; if(groups[i]->groupNodes[j]->lb_x<B_left) B_left=groups[i]->groupNodes[j]->lb_x; } } } //////////////////////////把windows一個一個切開///////////////////////////// void Graph::mapping() { int B_length=B_right-B_left; //得知整個邊界寬 int B_width=B_top-B_bottom; //得知整個邊界的長度 ////////把window 按照omega大小切出來 for(int i=0;i<ceil(static_cast<double>(B_length)/omega);i++){ vector<Window*> a; for(int j=0;j<ceil(static_cast<double>(B_width)/omega);j++){ Window *w=new Window; a.push_back(w); } windows.push_back(a); } //////一個一個windows去看對照//////////看每個點屬於哪個window//////////////// for(unsigned int i=colored_graph;i<groups.size();i++){ for(unsigned int j=0;j<groups[i]->groupNodes.size();j++){ int x1=groups[i]->groupNodes[j]->lb_x; int x2=groups[i]->groupNodes[j]->ru_x; int y1=groups[i]->groupNodes[j]->lb_y; int y2=groups[i]->groupNodes[j]->ru_y; int x1_sec=(x1-B_left)/omega;//x1,x2,y1,y2 in which DSW int y1_sec=(y1-B_bottom)/omega; vector <int> x; vector <int> y; //x component int k=1; x.push_back(x2-x1);//x[0] int x_tail=x1; while ( x2>omega*(k+x1_sec)+B_left){ x[k-1]=(x1_sec+k)*omega+B_left-x_tail; x.push_back(x2-(x1_sec+k)*omega-B_left); x_tail=omega*(x1_sec+k)+B_left; k++; } //y component k=1; y.push_back(y2-y1);//y[0] int y_tail=y1; while ( y2>omega*(k+y1_sec)+B_bottom){ y[k-1]=(y1_sec+k)*omega+B_bottom-y_tail; y.push_back(y2-(y1_sec+k)*omega-B_bottom); y_tail=omega*(y1_sec+k)+B_bottom; k++; } if(B_length%omega!=0){ if(x2>B_right-omega){ if(x2>((B_right-B_left)/omega)*omega+B_left) { if(x1<B_right-omega) { x[x.size()-1]=x2+omega-B_right; } else{ x[x.size()-1]=x2-x1; } } else { if(x1<B_right-omega) { x.push_back(x2+omega-B_right); } else{ x.push_back(x2-x1); } } } } if(B_width%omega!=0){ if(y2>B_top-omega){ if(y2>((B_top-B_bottom)/omega)*omega+B_bottom){//(y2-y1)/omega= number of y's DW -1 if(y1<B_top-omega){ y[y.size()-1]=y2+omega-B_top; }else{ y[y.size()-1]=y2-y1; } }else{ if(y1<B_top-omega){ y.push_back(y2+omega-B_top); }else{ y.push_back(y2-y1); } } } } for(unsigned int p=0;p<x.size();p++){ for(unsigned int q=0;q<y.size();q++){ windows[x1_sec+p][y1_sec+q]->windowNodes.push_back(groups[i]->groupNodes[j]);//variable check windows[x1_sec+p][y1_sec+q]->area.push_back(x[p]*y[q]); } } } } } /////////////////////先給每個group一個初始的顏色。並且算出density////////////////////////// bool compare (pair <int,int> i,pair <int,int> j) { return (i.second<j.second); } bool grpcompare (pair <Group*,int> i,pair <Group*,int> j) { return (i.second<j.second); } bool wincompare (Window* i,Window* j) { return (i->wgroups.size()<j->wgroups.size()); } void Graph::windowcalc_grparea() { for(unsigned int i=0;i<windows.size();i++) { for (unsigned int j = 0; j < windows[i].size(); ++j) { vector< pair<int,int> > v; for(unsigned int k=0;k<windows[i][j]->windowNodes.size();k++) { pair <int,int> group(k,windows[i][j]->windowNodes[k]->group_id); v.push_back(group); } if(v.size()>0) { sort(v.begin(),v.end(),compare); windows[i][j]->wgroups.push_back(v[0].second); int color=(0==windows[i][j]->windowNodes[v[0].first]->color) ?1:-1; windows[i][j]->wgroupsarea.push_back(windows[i][j]->area[v[0].first]*color); for(unsigned int k=1;k<v.size();k++) { if(v[k].second!=v[k-1].second) { windows[i][j]->wgroups.push_back(v[k].second); windows[i][j]->wgroupsarea.push_back(0); } int color=(0==windows[i][j]->windowNodes[v[k].first]->color) ?1:-1; windows[i][j]->wgroupsarea[windows[i][j]->wgroupsarea.size()-1]+=windows[i][j]->area[v[k].first]*color; } } } } } void Graph::greedycolor() { for(unsigned int i=0;i<windows.size();i++) { for (unsigned int j = 0; j < windows[i].size(); ++j) { averagecolor(i,j); } } } void Graph::averagecolor(int x,int y) { vector<pair <int,int> > v; int avgcolor=0; for(unsigned int i=0;i<windows[x][y]->wgroups.size();i++) { pair <int,int> area (i,windows[x][y]->wgroupsarea[i]); if(groups[windows[x][y]->wgroups[i]]->locked) { int inv= (!groups[windows[x][y]->wgroups[i]]->invert) ?1:-1; avgcolor+=windows[x][y]->wgroupsarea[i]*inv; } v.push_back(area); } sort(v.begin(),v.end(),compare); for(int i=v.size()-1;i>=0;i--) { int id=windows[x][y]->wgroups[v[i].first]; if(!groups[id]->locked) { if(avgcolor<=0) { if(windows[x][y]->wgroupsarea[v[i].first]<0) groups[id]->invert=true; avgcolor+=windows[x][y]->wgroupsarea[v[i].first]; } else { if(windows[x][y]->wgroupsarea[v[i].first]>=0) groups[id]->invert=true; avgcolor-=windows[x][y]->wgroupsarea[v[i].first]; } groups[id]->locked=true; } } vector<Window*> sortbygrp; for(unsigned int i=0;i<windows.size();i++) { for (unsigned int j = 0; j < windows[i].size(); ++j) { sortbygrp.push_back(windows[i][j]); } } sort(sortbygrp.begin(),sortbygrp.end(),wincompare); for(unsigned int i=0;i<sortbygrp.size();i++) { ptaveragecolor(sortbygrp[i]); } } void Graph::ptaveragecolor(Window* win) { vector<pair <int,int> > v; int avgcolor=0; for(unsigned int i=0;i<win->wgroups.size();i++) { pair <int,int> area (i,win->wgroupsarea[i]); if(groups[win->wgroups[i]]->locked) { int inv= (!groups[win->wgroups[i]]->invert) ?1:-1; avgcolor+=win->wgroupsarea[i]*inv; } v.push_back(area); } sort(v.begin(),v.end(),compare); for(int i=v.size()-1;i>=0;i--) { int id=win->wgroups[v[i].first]; if(!groups[id]->locked) { if(avgcolor<=0) { if(win->wgroupsarea[v[i].first]<0) groups[id]->invert=true; avgcolor+=win->wgroupsarea[v[i].first]; } else { if(win->wgroupsarea[v[i].first]>=0) groups[id]->invert=true; avgcolor-=win->wgroupsarea[v[i].first]; } groups[id]->locked=true; } } } void Graph::reset() { for(size_t i=0;i<groups.size();i++) { groups[i]->locked=false; groups[i]->invert=false; } } void Graph::saveState() { lastState.clear(); for (unsigned int j=colored_graph;j<groups.size();++j) { if (groups[j]->invert) lastState.push_back(true); else lastState.push_back(false); } } ///////////////////////////////////輸出////////////////////////////// void Graph::output(ofstream &fout ){ int count=0; int B_length=B_right-B_left; int B_width=B_top-B_bottom; for(int j=0;j<ceil(static_cast<double>(B_width)/omega);j++){//x for(int i=0;i<ceil(static_cast<double>(B_length)/omega);i++){//y int red_area=0; int blue_area=0; for(unsigned int k=0;k<windows[i][j]->windowNodes.size();k++){ if(windows[i][j]->windowNodes[k]->color==1){ if(groups[windows[i][j]->windowNodes[k]->group_id]->invert==0){ red_area+=windows[i][j]->area[k]; }else{//invert:red -> blue blue_area+=windows[i][j]->area[k]; } }else if(windows[i][j]->windowNodes[k]->color==0){ if(groups[windows[i][j]->windowNodes[k]->group_id]->invert==0){ blue_area+=windows[i][j]->area[k]; }else{//invert:blue -> red red_area+=windows[i][j]->area[k]; } } } ///////////////////////////////////先輸出windows////////////////////////////// int D_left=B_left+i*omega; int D_right=D_left+omega; int D_down=B_bottom+j*omega; int D_up=D_down+omega; //x most right if(D_right>B_right){ D_right=B_right; D_left=B_right-omega; } //y most up if(D_up>B_top){ D_up=B_top; D_down=B_top-omega; } count++; fout<<"WIN["<<count<<"]="<<D_left<<","<<D_down<<","<<D_right<<","<<D_up<<"("<<float(red_area*100)/float(omega*omega)<<" "<<float(blue_area*100)/float(omega*omega)<<")"<<endl; cout<<"WIN["<<count<<"]="<<D_left<<","<<D_down<<","<<D_right<<","<<D_up<<"("<<float(red_area*100)/float(omega*omega)<<" "<<float(blue_area*100)/float(omega*omega)<<")"<<endl; } } ///////////////////////////////////再來輸出會被排除掉的group////////////////////////////// for(int i=0;i<colored_graph;i++){ fout<<"GROUP"<<endl; for(unsigned int j=0;j<groups[i]->groupNodes.size();j++){ fout<<"NO["<<j+1<<"]="<<groups[i]->groupNodes[j]->lb_x<<","<<groups[i]->groupNodes[j]->lb_y<<","<<groups[i]->groupNodes[j]->ru_x<<","<<groups[i]->groupNodes[j]->ru_y<<endl; cout<<"NO["<<j+1<<"]="<<groups[i]->groupNodes[j]->lb_x<<","<<groups[i]->groupNodes[j]->lb_y<<","<<groups[i]->groupNodes[j]->ru_x<<","<<groups[i]->groupNodes[j]->ru_y<<endl; } } for(unsigned int i=colored_graph;i<groups.size();i++){ fout<<"GROUP"<<endl; cout<<"GROUP"<<endl; vector <int> red; vector <int> blue; for(unsigned int j=0;j<groups[i]->groupNodes.size();j++){ if (groups[i]->invert==false) { if(groups[i]->groupNodes[j]->color==1){ red.push_back(j); } else{ blue.push_back(j); } } else{ if(groups[i]->groupNodes[j]->color==1){ blue.push_back(j); } else{ red.push_back(j); } } } ///////////////////////////////////輸出二種顏色的group////////////////////////////// for(unsigned int j=0;j<red.size();j++) { fout<<"CA["<<j+1<<"]="<<groups[i]->groupNodes[red[j]]->lb_x<<","<<groups[i]->groupNodes[red[j]]->lb_y<<","<<groups[i]->groupNodes[red[j]]->ru_x<<","<<groups[i]->groupNodes[red[j]]->ru_y<<endl; cout<<"CA["<<j+1<<"]="<<groups[i]->groupNodes[red[j]]->lb_x<<","<<groups[i]->groupNodes[red[j]]->lb_y<<","<<groups[i]->groupNodes[red[j]]->ru_x<<","<<groups[i]->groupNodes[red[j]]->ru_y<<endl; } for(unsigned int j=0;j<blue.size();j++) { fout<<"CB["<<j+1<<"]="<<groups[i]->groupNodes[blue[j]]->lb_x<<","<<groups[i]->groupNodes[blue[j]]->lb_y<<","<<groups[i]->groupNodes[blue[j]]->ru_x<<","<<groups[i]->groupNodes[blue[j]]->ru_y<<endl; cout<<"CB["<<j+1<<"]="<<groups[i]->groupNodes[blue[j]]->lb_x<<","<<groups[i]->groupNodes[blue[j]]->lb_y<<","<<groups[i]->groupNodes[blue[j]]->ru_x<<","<<groups[i]->groupNodes[blue[j]]->ru_y<<endl; } } } //////以下是graph的套件///////////// Matrix::Matrix(const int & m, const int & n) { rows=m; columns=n; data = new int* [m]; for ( int i=0;i<m;++i) { data[i]=new int [n]; Row* newrow = new Row(i,0.0); rowsVec.push_back(newrow); rowsMap[i]=newrow; //double score=i; for (int j=0;j<n;++j) { data[i][j]=rand()%2; } } mutate_column = new double [n]; b_column = new double [n]; updateProb(); } Matrix::~Matrix() { if (data!=NULL) { for ( int i=0;i<rows;++i) { if (data[i]!=NULL) { delete [] data[i]; } } delete [] data; } if (mutate_column!=NULL) delete mutate_column; if (b_column!=NULL) delete b_column; } void Matrix::updateProb() { b_board.clear(); int normalize=(1+rows)*rows/2; for ( int j=0;j<columns;++j) { int accum=0; for ( int i=0;i<rows;++i) { accum+=(rows-i)*data[i][j]; } //pj1 in the paper mutate_column[j]=static_cast<double> (accum)/normalize; //bj in paper without normalize double thenum = 1.0-fabs(1.0-mutate_column[j]-0.5)-fabs(mutate_column[j]-0.5); b_column[j]=1.0-fabs(1.0-mutate_column[j]-0.5)-fabs(mutate_column[j]-0.5); b_board.push_back(pair<double, int>(thenum,j)); } } //score_board contains row num and the row's score void Matrix::setRowscore(const int & row_num,const float & score) { rowsMap[row_num]->row_score=score; } void Matrix::mogaR() { //sortRowByScore(); sort(b_board.begin(),b_board.end()); for ( int i=0;i<floor(4*rows/5);++i) { double x=((double) rand() / (RAND_MAX)); double ai=static_cast<double> (i)/(rows-1); if (x<0) cout<<"GG"<<endl; if (x< ai) { assert(i!=0); int now_row = rowsVec[i]->row_id; int k=floor(ai*columns); if (k<0) cout<<"error"<<endl; // cout<<"is changing"<<k<<" loci"<<endl; for (int j=0;j<k;++j) { int now_col = b_board[j].second; int tochange=0; if (data[now_row][now_col]==0) tochange=1; else tochange=0; data[now_row][now_col]=tochange; } } } for (int i=floor(4*rows/5);i<rows;++i) { //cout<<"Row "<<rowsVec[i]->row_id<<"is randoming"<<endl; for (int j=0;j<columns;++j) { data[i][j]=rand()%2; } } updateProb(); } void Matrix::mogaC() { sortRowByScore(); sort(b_board.begin(),b_board.end()); for (int i=0;i<columns;++i) { double y=((double) rand() / (RAND_MAX)); //double ai=static_cast<double> (i)/(score_board.size()-1); if(y<b_column[i]) { int w=floor(b_column[i]*rows); if (w<0) cout<<"error"<<endl; for (int j=rows-w;j<rows;++j) { int now_row=rowsVec[j]->row_id; int tochange=0; if (data[now_row][i]==0) tochange=1; else tochange=0; data[now_row][i]=tochange; } } } updateProb(); } void Matrix::print() { sortRowByScore(); cout<<endl; cout<<endl; cout<<"Matrix : "<<endl; for (int i=0;i<rows;++i) { cout<<"row "<<i<<" :"; for ( int j=0;j<columns;++j) { cout<<data[i][j]<<" "; } cout<<endl; } cout<<"mutate_column "; for ( int j=0;j<columns;++j) { cout<<mutate_column[j]<<" "; } cout<<endl; cout<<"b_column "; for (int j=0;j<columns;++j) { cout<<b_column[j]<<" "; } cout<<endl; cout<<"IN rowsVec"<<endl; for (unsigned int i=0;i<rowsVec.size();++i) { cout<<"Row is "<<rowsVec[i]->row_id<<endl; cout<<"Score is "<<rowsVec[i]->row_score<<endl; } cout<<endl; } bool RowCompByScore(const Row* a,const Row* b) { if (a->row_score > b->row_score) return true; else return false; } void Matrix::sortRowByScore() { sort(rowsVec.begin(),rowsVec.end(),RowCompByScore); } Edge::Edge(Node *a, Node *b) { if ( a->id <= b->id ) { node[0] = a; node[1] = b; } else { node[0] = b; node[1] = a; } } bool Edge::operator < (const Edge& rhs) const{ int id1a = node[0]->id; int id1b = node[1]->id; int id2a = rhs.node[0]->id; int id2b = rhs.node[1]->id; if ( id1a == id2a ) return id1b < id2b; if ( id1a == id2b ) return id1b < id2a; if ( id1b == id2a ) return id1a < id2b; if ( id1b == id2b ) return id1a < id2a; return true; } Node::Node(const int& i,const int& l_x,const int& l_y,const int& r_x,const int& r_y) { id = i; traveled = false; color = -1;// not colored prev = 0; lb_x=l_x; lb_y=l_y; ru_x=r_x; ru_y=r_y; } void Node::addEdge(Edge *e) { edge.push_back(e); } int Node::areaCalc() { return (ru_x-lb_x)*(ru_y-lb_y); } void Graph::printall() { cout << endl << "Shape area :" << endl << endl; map<int, Node *>::iterator itN; for ( itN = nodesMap.begin() ; itN != nodesMap.end() ; itN++ ) { cout << (*itN).second -> id << ": " << (*itN).second -> areaCalc() << endl; } cout << endl << "Edges :" << endl << endl; for (unsigned int i = 0; i < edges.size(); ++i) { cout << "edge " << i << " is " << edges[i] -> node[0] -> id << " -- " << edges[i] -> node[1] -> id << endl; } cout << endl << "Groups of the graph: " << endl << endl; for(unsigned int i = 0; i < groups.size(); ++i) { if(groups[i] != NULL) { groups[i] -> printGroup(); } } } Graph::Graph(const string& n,const int& alp,const int& be,const int& ome) { name = n; alpha = alp; beta = be; omega = ome; colored_graph=0; B_top=numeric_limits<int>::min(); B_bottom=numeric_limits<int>::max(); B_right=numeric_limits<int>::min(); B_left=numeric_limits<int>::max(); } Graph::~Graph() { vector<Edge *>::iterator itE; for ( itE = edges.begin() ; itE != edges.end() ; itE++ ) { if (*itE!=NULL) { delete (*itE); (*itE) = 0; } } map<int, Node *>::iterator itN; for ( itN = nodesMap.begin() ; itN != nodesMap.end() ; itN++ ) { if ((*itN).second!=NULL) {delete (*itN).second; (*itN).second = 0;} } vector<Node *>::iterator itN2; for ( itN2 = nodes.begin() ; itN2 != nodes.end() ; itN2++ ) { (*itN2) = 0; } } bool NodeCompByD( const Node* A, const Node* B ){ if ( A->edge.size() > B->edge.size() ) return true; else if (A->edge.size() == B->edge.size()) { if (A->id < B->id) return true; else return false; } else return false; } void Graph::sortNodesByDegree() { sort(nodes.begin(), nodes.end(), NodeCompByD); } Node * Graph::getNodeById(const int& id) { return nodesMap[id]; } Group::~Group() { for(unsigned int i = 0; i < groupNodes.size(); ++i) { if(groupNodes[i] != NULL) { delete groupNodes[i]; groupNodes[i] = NULL; } } } void Group::printGroup() { for(unsigned int i = 0; i < groupNodes.size(); ++i) { cout << "group " << groupNodes[i] -> group_id << ": shape " << groupNodes[i] -> id << endl; } cout << endl; } void Group::calcgrouparea() { for(size_t i=0;i<groupNodes.size();i++) { grparea+=groupNodes[i]->area; } }
true
8c374cbaa2674d159d81dab6bf273ceb8e8a6273
C++
MannyP31/CompetitiveProgrammingQuestionBank
/Recursion/All_indices_of_element.cpp
UTF-8
1,463
3.609375
4
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// CPP program to find all indices of a number #include <bits/stdc++.h> using namespace std; // A recursive function to find all indices of a number in array. int allIndexes(int input[], int size, int x, int output[]) { // If size of array is 0 then return 0 if (size == 0) { return 0; } // recursion int smallAns = allIndexes(input + 1,size - 1, x, output); // If the element at first index is equal to x then add 1 to the array values and shift them right by 1 step if (input[0] == x) { for (int i = smallAns - 1; i >= 0; i--) { output[i + 1] = output[i] + 1; } // Put the start index in front // of the array output[0] = 0; smallAns++; } else { // If the element at index 0 is not equal to x then add 1 to the array values and no need to shift array. for (int i = smallAns - 1; i >= 0; i--) { output[i] = output[i] + 1; } } return smallAns; } // Function to find all indices of a number void AllIndexes(int input[], int n, int x) { int output[n]; int size = allIndexes(input, n, x, output); for (int i = 0; i < size; i++) { cout << output[i] << " "; } } // Driver Code int main() { int n,arr[1000],x; cin>>n; for(int i=0;i<n;i++){ cin>>arr[i]; } cin>>x; // Function call AllIndexes(arr, n, x); return 0; }
true
7ce01c4e31484a55115117deecf5c4b4a7dc57df
C++
ko19951231/Sdorica_AI
/enemy.cpp
UTF-8
6,852
3.046875
3
[]
no_license
#include "enemy.h" #include "state.h" #include <iostream> using namespace std; void Enemy::init(int s, state *st) { this->stage = s; this->game = st; if(this->stage == 0){ this->init_amount = this->amount = 3; this->enemies[0].setEnemy(0); this->enemies[1].setEnemy(0); this->enemies[2].setEnemy(0); } else if(this->stage == 1){ this->init_amount = this->amount = 3; this->enemies[0].setEnemy(1); this->enemies[1].setEnemy(1); this->enemies[2].setEnemy(2); } else if(this->stage == 2){ this->init_amount = this->amount = 1; this->enemies[0].setEnemy(3); } else if(this->stage == 3){ this->init_amount = this->amount = 1; this->enemies[0].setEnemy(4); } else if(this->stage == 4){ this->init_amount = this->amount = 2; this->enemies[0].setEnemy(5); this->enemies[1].setEnemy(2); } this->selectedEnemyIndex = 0; } void Enemy::setSelectedIndex(int index){ if(!this->enemies[index].isDead()) this->selectedEnemyIndex = index; } float Enemy::get_hurt(int index, float hurt) { //if the enemy is dead, then return if(this->enemies[index].isDead()) return 0; float value = this->enemies[index].getDamage(hurt); if(this->enemies[index].isDead()){ this->amount--; checkSelectedEnemyState(); } return value; } float Enemy::get_hurt_first(float hurt){ return get_hurt(getFirstIndex(), hurt); } float Enemy::get_hurt_selected(float hurt){ return get_hurt(this->selectedEnemyIndex, hurt); } float Enemy::get_hurt_all(float hurt){ float value = 0; for(int i = 0 ; i < init_amount; i++){ value += get_hurt(i, hurt); } return value; } //Add the "easy harm" state to the selected enemy void Enemy::addEasyHarmSelected(int round){ this->enemies[selectedEnemyIndex].addEasyHarm(round); } //Add the "easy harm" state to the first enemy void Enemy::addEasyHarmFirst(int round){ this->enemies[getFirstIndex()].addEasyHarm(round); } void Enemy::update(){ for(int i = 0 ; i < init_amount; i++) if(!this->enemies[i].isDead()) this->enemies[i].update(); } void Enemy::attack(){ for(int i = 0 ; i < init_amount; i++){ //if the enemy's CD is downcounting to 0 //Add back the CD time and attack if((this->enemies[i].getCD() <= 0) && !this->enemies[i].isDead()){ if(this->enemies[i].getKind() == 0){ float atk = this->enemies[i].attack(); this->game->PlayerHurtFirst(atk); } else if(this->enemies[i].getKind() == 1){ float atk = this->enemies[i].attack(); this->game->PlayerHurtAll(atk); } else if(this->enemies[i].getKind() == 2){ for(int j = 0 ; j < init_amount ; j++){ if(!this->enemies[j].isDead()) this->enemies[j].addShieldTransferLevel(); } } else if(this->enemies[i].getKind() == 3){ float atk = this->enemies[i].attack(); this->game->PlayerHurtFirst(atk); this->enemies[i].setTransferShield(1); } else if(this->enemies[i].getKind() == 4){ float atk = this->enemies[i].attack(); this->game->PlayerHurtFirst(atk); this->enemies[i].addShield(554); } else if(this->enemies[i].getKind() == 5){ float atk = this->enemies[i].attack(); this->game->PlayerHurtLess(atk); this->enemies[i].setTransferShield(1); this->enemies[i].addShield(350); } this->enemies[i].recoverCD(); } } } int Enemy::getAmount(){ return this->amount; } int Enemy::getStage(){ return this->stage; } bool Enemy::nextStage(){ //no more enemies -> go to the next stage /*if(this->amount == 0) { if(this->stage == 4) return false; return true; }*/ return true; } void Enemy::go_next_stage(){ if(this->amount == 0) { if(this->stage<4) this->stage = this->stage + 1; init(this->stage, this->game); } } int Enemy::getFirstIndex(){ //Check the "first" enemy int index; for(index = 0 ; index < init_amount; index++) if(!this->enemies[index].isDead()) break; return index; } void Enemy::print() { for(int i = 0;i < init_amount ; i++){ if(this->selectedEnemyIndex == i) printf("*"); printf("%d: Monster%d: HP %f, Shield %f, CD %d\n", i, this->enemies[i].getKind(), this->enemies[i].getHP(), this->enemies[i].getShield(), this->enemies[i].getCD()); } puts("=============="); } void Enemy::updateSelectedIndex(){ this->selectedEnemyIndex = getFirstIndex(); } void Enemy::checkSelectedEnemyState(){ if(enemies[selectedEnemyIndex].isDead()) updateSelectedIndex(); } int Enemy::getSelectedEnemyIndex(){ return this->selectedEnemyIndex; } void Enemy::assign(const Enemy &e){ this->stage = e.stage; this->init_amount = e.init_amount; this->amount = e.amount; this->selectedEnemyIndex = e.selectedEnemyIndex; for(int i = 0 ; i < 3; i++){ this->enemies[i].assign(e.enemies[i]); } } void Enemy::set_state(simple_state& s){ init(s.stage - 1, this->game); int enemy_index = 0; //Assign to corresponding enemy data for(int i = 0 ; i < s.amount; i++){ while(this->enemies[enemy_index].getKind() != s.kind[i]){ //the corresponding place enemy is dead this->enemies[enemy_index].setHP(-100); this->enemies[enemy_index].setShield(0); enemy_index++; } this->enemies[enemy_index].setHP((s.e_HP[i] * 2 + 1) * this->enemies[enemy_index].getMAXHP() / 8.0); this->enemies[enemy_index].setShield((s.shield[i]) * this->enemies[enemy_index].getMAXHP() / 4.0); this->enemies[enemy_index].setCD(s.CD[i]); this->enemies[enemy_index].setShieldTransferLevel(s.shieldTransfer_level[i]); this->enemies[enemy_index].setTransferShield(s.transferShield[i]); int num[3] = {0}; for(int j = 0 ; j < 3 ; j++) num[i] = s.p_strengthen[i][j]; this->enemies[enemy_index].setEasyHarm(num); enemy_index++; } for(; enemy_index < 3 ; enemy_index++){ this->enemies[enemy_index].setHP(-100); this->enemies[enemy_index].setShield(0); } }
true
41481c49b66437267ca4546b0055a85c8be7ada1
C++
skaupper/cpp-telegrambot
/include/telegram/Command.h
UTF-8
1,474
2.546875
3
[]
no_license
#ifndef COMMAND_H_ #define COMMAND_H_ #include <functional> #include <string> #include "jsonserializer/Generated.h" #include "CommandException.h" namespace telegram { enum class CallType { NOTHING = 0, DIRECT = 1, INDIRECT = 2, QUIT = 4 }; enum class CallReason { NOTHING = 0, MESSAGE = 1, EDITED_MESSAGE = 2, INLINE_QUERY = 4, INLINE_RESULT = 8, CALLBACK_QUERY = 16 // ... }; class TelegramBot; class Command { public: typedef std::function<void(TelegramBot *, const structures::Update &)> FunctionType; private: std::string name; protected: TelegramBot *bot; FunctionType directFunction; public: Command(TelegramBot *bot, const std::string &name); Command(TelegramBot *bot, const std::string &name, FunctionType); virtual ~Command(); std::string GetName() const; bool operator()(const telegram::structures::Update &, CallReason, CallType); virtual void Setup(); virtual bool OnDirect(const telegram::structures::Update &); virtual bool OnIndirect(const telegram::structures::Update &); virtual bool OnQuit(const telegram::structures::Update &); }; } #endif // COMMAND_H_
true
454a17b07f32801179861f147a75d268c45e6a6c
C++
zhengjinwei123/cplusplus
/recastnav/inc/Aoi/room.h
GB18030
4,814
2.921875
3
[]
no_license
#pragma once #ifndef _AOI_ROOM_H__ #define _AOI_ROOM_H__ #include "player.h" #include "point3f.h" #include "defines.h" #include <unordered_map> #include <assert.h> namespace aoi { template<typename PLAYER_TYPE,typename MONSTER_TYPE,typename PLAYER_ID_TYPE,typename MONSTER_ID_TYPE> class Room { using tPlayerMap = std::unordered_map<PLAYER_ID_TYPE,PLAYER_TYPE*>; using tMonsterMap = std::unordered_map<MONSTER_ID_TYPE, MONSTER_TYPE*>; typedef void(*tPlayerEventCallbackFunc)(PLAYER_ID_TYPE, PLAYER_ID_TYPE,const Point3f&, EAGENT_MOVE_EVENT_TYPE); typedef void(*tMonsterEventCallbackFunc)(PLAYER_ID_TYPE, PLAYER_ID_TYPE, const Point3f&, EMONSTER_EVENT_TYPE); public: Room(unsigned id, PLAYER_TYPE* owner = nullptr) : m_id(id), m_ownerPtr(owner) { m_playerMap.insert(std::pair<PLAYER_ID_TYPE, PLAYER_TYPE*>(m_ownerPtr->GetId(), m_ownerPtr)); } ~Room() { Clean(); } public: inline const unsigned GetTotalPlayers() const { return m_playerVec.size();} inline const unsigned GetTotalMonsters() const { return m_enemyMap.size(); } inline const PLAYER_TYPE* GetOwner() const { return m_ownerPtr; } inline void SetOwner(PLAYER_TYPE* owner) { m_ownerPtr = owner; } // ҽ뷿,㲥 void PlayerEnter(PLAYER_TYPE* player, tPlayerEventCallbackFunc func) { tPlayerMap::iterator itFind = m_playerMap.find(player->GetId()); if (itFind != m_playerMap.end()) { return; } m_playerMap.insert(std::pair<PLAYER_ID_TYPE, PLAYER_TYPE*>(player->GetId(), player)); tPlayerMap::iterator it = m_playerMap.begin(); for (; it != m_playerMap.end(); ++it) { if (it->second->GetId() == player->GetId()) { continue; } (*func)(it->second->GetId(), player->GetId(),player->GetPosition(), EAMET_ENTER_SCENE); } } // 뿪,㲥 void PlayerLeave(PLAYER_ID_TYPE id, tPlayerEventCallbackFunc func) { tPlayerMap::iterator itFind = m_playerMap.find(id); if (itFind == m_playerMap.end()) { return; } delete itFind->second; itFind->second = nullptr; m_playerMap.erase(itFind); Point3f position; tPlayerMap::iterator it = m_playerMap.begin(); for (; it != m_playerMap.end(); ++it) { (*func)(it->second->GetId(), itFind->second->GetId(),position, EAMET_LEAVE_SCENE); } } // ƶ㲥 void PlayerMove(PLAYER_ID_TYPE id, Point3f& position, tPlayerEventCallbackFunc func) { tPlayerMap::iterator itFind = m_playerMap.find(id); if (itFind == m_playerMap.end()) { return; } Point3f position; tPlayerMap::iterator it = m_playerMap.begin(); for (; it != m_playerMap.end(); ++it) { if (it->second->GetId() == id) { continue; } (*func)(it->second->GetId(), itFind->second->GetId(), position, EAMET_MOVE_SCENE); } } // ƶ㲥,֪ͨ void MonsterMove(MONSTER_ID_TYPE id, Point3f& position, tMonsterEventCallbackFunc func) { tMonsterMap::iterator itMonsterFind = m_monsterMap.find(id); if (itMonsterFind == m_monsterMap.end()) { return; } tPlayerMap::iterator it = m_playerMap.begin(); for (; it != m_playerMap.end(); ++it) { // Ҫ֪ͨ if (it->second->GetId() == m_ownerPtr->GetId()) { continue; } (*func)(it->second->GetId(), id, position, EMET_MOVE_SCENE); } } // void MonsterDead(MONSTER_ID_TYPE id, tMonsterEventCallbackFunc func) { tMonsterMap::iterator itMonsterFind = m_monsterMap.find(id); if (itMonsterFind == m_monsterMap.end()) { return; } delete itMonsterFind->second; itMonsterFind->second = nullptr; m_monsterMap.erase(itMonsterFind); Point3f position; tPlayerMap::iterator it = m_playerMap.begin(); for (; it != m_playerMap.end(); ++it) { // Ҫ֪ͨ if (it->second->GetId() == m_ownerPtr->GetId()) { continue; } (*func)(it->second->GetId(), id, position, EMET_DEAD_SCENE); } } //عϢ void InitMonster() { } inline const unsigned GetId() const { return m_id; } private: // ٷ void Clean() { tPlayerMap::iterator it = m_playerMap.begin(); for (; it != m_playerMap.end(); ++it) { delete it->second; it->second = nullptr; } m_ownerPtr = nullptr; m_playerMap.clear(); tMonsterMap::iterator itm = m_monsterMap.begin(); for (; itm != m_monsterMap.end(); ++itm) { delete itm->second; itm->second = nullptr; } m_monsterMap.clear(); } private: unsigned m_id; // id PLAYER_TYPE* m_ownerPtr;// tPlayerMap m_playerMap;// Ϣб tMonsterMap m_monsterMap;// б }; } #endif // !_AOI_ROOM_H__
true
e44b66fae2ac2398be1d52db39e2a0e1b6a4239e
C++
OarabileMwiya/HacktoberFest2020-1
/Basic Programs/generate_string.cpp
UTF-8
325
3.25
3
[]
no_license
//This program generates a string of given length. #include<bits/stdc++.h> using namespace std; int main(){ int len; cout<<"Enter the length of string to be generated : "; cin>>len; string s=""""; for(int i=0;i<len;i++){ int x=rand()%26; char c='a'+x; s+=c; } cout<<s; }
true
af05cf893bf52e954a143b14a6e8e788c6ed91f0
C++
trmrsh/cpp-colly
/src/read_molly_head.cc
UTF-8
9,316
2.984375
3
[]
no_license
#include <fstream> #include <vector> #include <string> #include "trm/subs.h" #include "trm/header.h" #include "trm/colly.h" /** * read_molly_head reads in the headers and arc poly * (if set) of a molly spectrum. It assumes that the stream is * just positioned at the start of the header and leves it just * as the data record starts. This routine reads in the header items * in a virtually unaltered format (exception: any "Epoch"s are corrected * to "Equinox" and "DEC" to "Dec"). If you want a nicer format, * use rejig_molly_head, but note that write_molly_head expects * unvarnished headers. read_molly_head also returns a string array * which shows the original storage order of the molly headers and can be used by * write_molly_head in order to write out an almost-untouched version of the header. * * A directory called Xtra is created which stores a few extras, * such as the number of pixels and the start and end wavelengths. * * \param ist the input file stream which must have been opened in binary mode * \param head the header to read into. It will be cleared at the start of the function * \param original vector of string names in the original * order in which the header items were loaded (since they are stored * alphabetically in 'head') * \param warn true to print warnings of header items not found * although expected; false to suppress these warnings * \return The routine comes back with false if the end of file is * encountered. It throws Colly_Error objects if serious * errors are encountered. These contain messages that can be * printed. */ namespace Colly { std::string convert_molly_to_header(std::string name); } bool Colly::read_molly_head(std::ifstream& ist, Subs::Header& head, std::vector<std::string>& original, bool warn){ int fcode, npix, narc, nchar, ndoub, nintr, nfloat; char units[17]; int j, nstart; head.clear(); // clear the header original.clear(); // clear the std::string std::vector if(!(ist.read((char *)&nstart, sizeof(int)))) return false; if(nstart != 44) throw Colly_Error("Colly::read_molly_head: First 4 bytes != 44"); if(!(ist.read((char *)&fcode,sizeof(int)))) throw Colly_Error("Colly::read_molly_head: Error reading fcode"); if(!(ist.read(units,16))) throw Colly_Error("Colly::read_molly_head: Error reading units"); units[16] = 0; if(!(ist.read((char *)&npix,sizeof(int)))) throw Colly_Error("Colly::read_molly_head: Error reading npix"); if(!(ist.read((char *)&narc,sizeof(int)))) throw Colly_Error("Colly::read_molly_head: Error reading narc"); try{ head.set("Xtra", new Subs::Hdirectory("Extra information on spectrum")); head.set("Xtra.FCODE", new Subs::Hint(fcode,"molly format code")); head.set("Xtra.UNITS", new Subs::Hstring(units, "Flux units")); head.set("Xtra.NPIX", new Subs::Hint(npix,"Number of pixels")); head.set("Xtra.NARC", new Subs::Hint(narc, "Number of arc coefficients")); } catch(std::string s){ if(warn) std::cerr << s << std::endl; } #ifdef DEBUG std::cerr << "FCODE = " << fcode << ", UNITS = " << units << ", NPIX = " << npix << std::endl; #endif if(!(ist.read((char *)&nchar,sizeof(int)))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading nchar"); if(!(ist.read((char *)&ndoub,sizeof(int)))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading ndoub"); if(!(ist.read((char *)&nintr,sizeof(int)))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading nintr"); if(!(ist.read((char *)&nfloat,sizeof(int)))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading nfloat"); if(!(skip_bytes(ist,2*sizeof(int)))) throw Colly::Colly_Error("Colly::read_molly_head: Error skipping bytes after first record"); #ifdef DEBUG std::cerr << "NCHAR = " << nchar << ", NDOUB = " << ndoub << ", NINTR = " << nintr << ", NFLOAT = " << nfloat << std::endl; #endif // Read in header item names, convert them to the right // format (no whitespace) char hname[17]; hname[16] = 0; std::vector<std::string> cname(nchar); for(j=0; j<nchar; j++){ if(!(ist.read(hname,16))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading char header name"); cname[j] = convert_molly_to_header(hname); original.push_back(cname[j]); } // Read double with a few corrections std::vector<std::string> dname(ndoub); for(j=0; j<ndoub; j++){ if(!(ist.read(hname,16))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading double header name"); dname[j] = convert_molly_to_header(hname); if(dname[j] == "DEC") dname[j] = "Dec"; if(dname[j] == "EQUINOX" || dname[j] == "Epoch") dname[j] = "Equinox"; original.push_back(dname[j]); } std::vector<std::string> iname(nintr); for(j=0; j<nintr; j++){ if(!(ist.read(hname,16))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading int header name"); iname[j] = convert_molly_to_header(hname); original.push_back(iname[j]); } std::vector<std::string> fname(nfloat); for(j=0; j<nfloat; j++){ if(!(ist.read(hname,16))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading float header name"); fname[j] = convert_molly_to_header(hname); original.push_back(fname[j]); } if(!(skip_bytes(ist,2*sizeof(int)))) throw Colly::Colly_Error("Colly::read_molly_head: Error skipping bytes after header names"); #ifdef DEBUG std::cerr << "Read header item names" << std::endl; #endif // Now read and set the values, chopping // trailing blanks from strings. char citem[33]; citem[32] = 0; for(j=0; j<nchar; j++){ if(!(ist.read(citem,32))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading char item values"); for(int k=31; k>=0; k--) if(citem[k] == ' ') citem[k] = 0; else break; head.set(cname[j], new Subs::Hstring(citem)); } double d; for(j=0; j<ndoub; j++){ if(!(ist.read((char *)&d,sizeof(double)))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading double item values"); head.set(dname[j], new Subs::Hdouble(d)); } int i; for(j=0; j<nintr; j++){ if(!(ist.read((char *)&i,sizeof(int)))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading int item values"); head.set(iname[j], new Subs::Hint(i)); } float f; for(j=0; j<nfloat; j++){ if(!(ist.read((char *)&f,sizeof(float)))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading float item values"); head.set(fname[j], new Subs::Hfloat(f)); } if(!(skip_bytes(ist,2*sizeof(int)))) throw Colly::Colly_Error("Colly::read_molly_head: Error skipping bytes after reading header item values"); #ifdef DEBUG std::cerr << "Read header item values" << std::endl; #endif if(narc != 0){ double arc[abs(narc)]; if(!(ist.read((char *)&arc,abs(narc)*sizeof(double)))) throw Colly::Colly_Error("Colly::read_molly_head: Error reading arc coefficients"); double w1 = 0., w2 = 0.; for(i=0; i<abs(narc); i++){ w1 += arc[i]*pow(0.5/double(npix),i); w2 += arc[i]*pow((npix+0.5)/double(npix),i);; } if(w1 > w2) std::swap(w1,w2); if(narc < 0){ w1 = exp(w1); w2 = exp(w2); } double disp = (w2-w1)/npix; head.set("Xtra.ARC", new Subs::Hdvector(std::vector<double>(arc,arc+abs(narc)), "Arc coefficients")); head.set("Xtra.WLO", new Subs::Hdouble(w1, "Lower wavelength (A, at pixel 0.5)")); head.set("Xtra.WHI", new Subs::Hdouble(w2,"Upper wavelength (A, at pixel npix+0.5)")); head.set("Xtra.DISP", new Subs::Hdouble(disp,"Dispersion (A/pix)")); #ifdef DEBUG std::cerr << "Read arc coefficients" << std::endl; #endif } // skip bytes at end of record if(!(skip_bytes(ist,sizeof(int)))) throw Colly::Colly_Error("Colly::read_molly_head: Error skipping bytes after reading arc coefficients"); // A few corrections ... // Correct for UTC >= 24. try{ double utc = head["UTC"]->get_double(); if(utc >= 24.){ Subs::Header::Hnode* dhit = head.find("Day"); Subs::Header::Hnode* mhit = head.find("Month"); Subs::Header::Hnode* yhit = head.find("Year"); int day = dhit->value->get_int(); int month = mhit->value->get_int(); int year = yhit->value->get_int(); utc -= 24.; Subs::Time time(day,Subs::Date::Month(month),year,utc); time.add_day(1); dhit->value->set_value(time.day()); mhit->value->set_value(int(time.month())); yhit->value->set_value(time.year()); head["UTC"]->set_value(utc); } } catch(const std::string& s){ if(warn) std::cerr << s << std::endl; } return true; } namespace Colly { std::string convert_molly_to_header(std::string name){ std::string::size_type n1 = name.find_first_not_of(" \t"); if(n1 == std::string::npos) throw Colly::Colly_Error("Blank name in std::string convert_molly_to_header(std::string)"); std::string::size_type n2 = name.find_last_not_of(" \t"); name = name.substr(n1,n2-n1+1); std::string::size_type p; while((p = name.find(" ")) != std::string::npos) name.replace(p,1,"_"); while((p = name.find("\t")) != std::string::npos) name.replace(p,1,"_"); return name; } }
true
a64d8a2af06bd6f21186fa464aefd67006632f8c
C++
HoYoungChun/Algorithm_PS
/Data_Structure/BOJ_15828.cpp
UTF-8
501
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int N; cin >> N; // 라우터 내부의 버퍼의 크기 queue<int> que; while(true){ int input; cin >> input; if(input == -1) break; else if(input == 0){ que.pop(); } else if(que.size()<N){ que.push(input); } } if(que.empty()) cout<<"empty"<<"\n"; while(!que.empty()){ cout<< que.front()<< ' '; que.pop(); } return 0; }
true
01469c0a8bebcaef8a5356d0cd07d1d71631e7fe
C++
sguazt/boost-ublasx
/boost/numeric/ublasx/operation/which.hpp
UTF-8
3,765
2.53125
3
[ "BSL-1.0" ]
permissive
/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */ /** * \file boost/numeric/ublasx/operation/which.hpp * * \brief Find the positions of the elments of a given container which satisfy * a given unary predicate. * * \author Marco Guazzone (marco.guazzone@gmail.com) * * <hr/> * * Copyright (c) 2010, Marco Guazzone * * Distributed under the Boost Software License, Version 1.0. (See * accompwhiching file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_NUMERIC_UBLASX_OPERATION_WHICH_HPP #define BOOST_NUMERIC_UBLASX_OPERATION_WHICH_HPP #include <boost/numeric/ublas/detail/config.hpp> #include <boost/numeric/ublas/expression_types.hpp> #include <boost/numeric/ublas/traits.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublasx/operation/num_columns.hpp> #include <boost/numeric/ublasx/operation/num_rows.hpp> #include <boost/numeric/ublasx/operation/size.hpp> #include <functional> //TODO: implement the 'which' operation for matrix expressions namespace boost { namespace numeric { namespace ublasx { using namespace ::boost::numeric::ublas; //@{ Declarations /** * \brief Find the positions of the elments of the given vector expression * which satisfy the given unary predicate. * \tparam VectorExprT The type of the vector expression. * \tparam UnaryPredicateT The type of the unary predicate functor. * \param ve The vector expression over which check for the predicate. * \param p The unary predicate functor: must accept one argument and return * a boolean value. * \return A vector of positions of the elements of the given vector * expression which satisfy the given predicate; an empty vector, if no element * satisfies the given predicate. * * \author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt; */ template <typename VectorExprT, typename UnaryPredicateT> vector<typename vector_traits<VectorExprT>::size_type> which(vector_expression<VectorExprT> const& ve, UnaryPredicateT p); /** * \brief Find the positions of the non-zero elments of the given vector * expression. * \tparam VectorExprT The type of the vector expression. * \param ve The vector expression over which check for existence of non-zero * elements. * \return A vector of positions of the non-zero elements of the given vector * expression; an empty vector, if no non-zero element is found. * * \note The test for zero equality is done in the strong sense, that is by not * using which tolerance. * For checking for "weak" zero equality between a given tolerance use the * two-argument version of this function with an appropriate predicate. * * \author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt; */ template <typename VectorExprT> vector<typename vector_traits<VectorExprT>::size_type> which(vector_expression<VectorExprT> const& ve); //@} Declarations //@{ Definitions template <typename VectorExprT, typename UnaryPredicateT> BOOST_UBLAS_INLINE vector<typename vector_traits<VectorExprT>::size_type> which(vector_expression<VectorExprT> const& ve, UnaryPredicateT p) { typedef typename vector_traits<VectorExprT>::size_type size_type; vector<size_type> res; size_type n = size(ve); size_type j = 0; for (size_type i = 0; i < n; ++i) { if (p(ve()(i))) { res.resize(res.size()+1); res(j++) = i; } } return res; } template <typename VectorExprT> BOOST_UBLAS_INLINE vector<typename vector_traits<VectorExprT>::size_type> which(vector_expression<VectorExprT> const& ve) { typedef typename vector_traits<VectorExprT>::value_type value_type; return which(ve, ::std::bind2nd(::std::not_equal_to<value_type>(), 0)); } //@} Definitions }}} // Namespace boost::numeric::ublasx #endif // BOOST_NUMERIC_UBLASX_OPERATION_WHICH_HPP
true
e7acea062278c124053f2ae1c7ca6033f6dd05c2
C++
SoC-OpenGL/soc-assignment-1-ritik02mandal
/Assignment 1/Q1/Disk.cpp
UTF-8
2,643
2.546875
3
[]
no_license
#include "GL_Framework/gl_framework.hpp" #include "Shader/shader_util.hpp" #include <math.h> const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 800; float points[]={0.8f,0.8f,0.0,0.8f,-0.8f,0.0f,-0.8f,0.8f,0.0f,-0.8f,-0.8f,0.0f,0.8f,-0.8f,0.0f,-0.8f,0.8f,0.0f}; GLuint shaderProgram; GLuint vbo, vao; void initShadersGL(void) { std::string vertex_shader_file("Shader/simple_vs.glsl"); std::string fragment_shader_file("Shader/disk_simple_fs.glsl"); std::vector<GLuint> shaderList; shaderList.push_back(opengl::LoadShaderGL(GL_VERTEX_SHADER, vertex_shader_file)); shaderList.push_back(opengl::LoadShaderGL(GL_FRAGMENT_SHADER, fragment_shader_file)); shaderProgram = opengl::CreateProgramGL(shaderList); } void initVertexBufferGL(void) { glGenBuffers (1, &vbo); glBindBuffer (GL_ARRAY_BUFFER, vbo); glBufferData (GL_ARRAY_BUFFER, 2*3*3* sizeof (float), points, GL_STATIC_DRAW); glGenVertexArrays (1, &vao); glBindVertexArray (vao); glEnableVertexAttribArray (0); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); } void renderGL(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(shaderProgram); glBindVertexArray (vao); glDrawArrays(GL_TRIANGLES, 0, 6); } int main(int argc, char** argv) { GLFWwindow* window; glfwSetErrorCallback(opengl::error_callback); if (!glfwInit()) return -1; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "A Disk", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; GLenum err = glewInit(); if (GLEW_OK != err) { std::cerr<<"GLEW Init Failed : %s"<<std::endl; } std::cout<<"Vendor: "<<glGetString (GL_VENDOR)<<std::endl; std::cout<<"Renderer: "<<glGetString (GL_RENDERER)<<std::endl; std::cout<<"Version: "<<glGetString (GL_VERSION)<<std::endl; std::cout<<"GLSL Version: "<<glGetString (GL_SHADING_LANGUAGE_VERSION)<<std::endl; glfwSetKeyCallback(window, opengl::key_callback); glfwSetFramebufferSizeCallback(window,opengl::framebuffer_size_callback); glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); opengl::initGL(); initShadersGL(); initVertexBufferGL(); while (glfwWindowShouldClose(window) == 0) { renderGL(); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; }
true
e43f2bd931dcf06311ceeb6e98529deba12af983
C++
menisadi/Assignment2
/src/Printer.cpp
UTF-8
2,805
2.75
3
[]
no_license
/* * Printer.cpp * * Created on: Dec 2, 2014 * Author: Ofer Caspi */ #include "Printer.h" Printer::Printer() { } Printer::Printer(const Printer& printer) { } Printer& Printer::operator=(const Printer& printer) { return *this; } Printer::~Printer() { } void Printer::print(int currentTimeSlice) { int maxNumOfCars = 4; Car* car = NULL; string temp; ostringstream streamTemp; int tempInt; map<string, Roads*>::iterator it; for(int i = 0; i < 1; i++) {cout << '\n';} printf("%-18s%d\n", "Time:", global_SimulationTime); printf("\n%-18s", "Green time left:"); for(it = RoadsMap->begin(); it != RoadsMap->end(); it++) { tempInt = JunctionsMap->find(it->second->getEndJnc())->second->getTimeSliceByAppeared(); JunctionsMap->find(it->second->getEndJnc())->second->setForPrinterNumTimesAppearedPlusOne(); if(tempInt == 0) {printf("%-11s", "0");} else {printf("%-11d", tempInt);} } for(it = RoadsMap->begin(); it != RoadsMap->end(); it++) { JunctionsMap->find(it->second->getEndJnc())->second->setForPrinterNumTimesAppearedZero(); } printf("\n%-18s", "Speed:"); for(it = RoadsMap->begin(); it != RoadsMap->end(); it++) { tempInt = it->second->getBaseSpeed(); printf("%-11d", tempInt); } printf("\n%-18s", "End junction:"); for(map<string, Junctions*>::iterator iv = JunctionsMap->begin(); iv != JunctionsMap->end(); iv++) { for(int p = 0; p < (iv->second->getRoadsInJunction()->size()) ; p++) { temp = iv->second->getIdJunction(); printf("%-11s", temp.c_str()); maxNumOfCars = max(maxNumOfCars,(*iv->second->getRoadsInJunction())[p]->getNumOfCarInside()); } } printf("\n"); for(int i = 0; i < maxNumOfCars; i++) { printf("%-18s", "Cars:"); for(map<string, Junctions*>::iterator iv = JunctionsMap->begin(); iv != JunctionsMap->end(); iv++) { for(int p = 0; p < (iv->second->getRoadsInJunction()->size()) ; p++) { if( !((*iv->second->getRoadsInJunction())[p]->getCarsInRoad()->empty()) && ((*iv->second->getRoadsInJunction())[p]->getCarsInRoad()->size() > i) ) { car = (*((*iv->second->getRoadsInJunction())[p]->getCarsInRoad()))[i]; streamTemp.str(""); if(car != NULL) {streamTemp << car->getID() << "(" << car->getLocation() << "," << car->getCondition() << ")";} else {streamTemp << "^";} printf("%-11s", streamTemp.str().c_str()); } else{printf("%-11s","");} } } printf("\n"); } printf("%-18s", "Start junction:"); for(map<string, Junctions*>::iterator iv = JunctionsMap->begin(); iv != JunctionsMap->end(); iv++) { for(int p = 0; p < (iv->second->getRoadsInJunction()->size()) ; p++) { temp = (*iv->second->getRoadsInJunction())[p]->getBaginJnc(); printf("%-11s", temp.c_str()); } } for(int i = 0; i < 2; i++) {cout << '\n';} }
true
7d530180f66583ecfaf94cfed7d60df933ade156
C++
barrylawson/cmsc240_f2018_lab6_cyan
/VectorTester.cpp
UTF-8
10,252
3.671875
4
[]
no_license
#include <iostream> #include "IntegerVector.h" #include "DoubleVector.h" #include "CharacterVector.h" #include <exception> #include <string> #include <stdexcept> int main() { IntegerVector iv; DoubleVector dv; CharacterVector cv; //------------------------------------------------------------------------- std::cout << "--------------" << std::endl; std::cout << "IntegerVector:" << std::endl; std::cout << "------------------------------------" << std::endl; std::cout << "----Testing put(index, value)-------" << std::endl; std::cout << "------------------------------------" << std::endl; std::cout << "Inputting value 65 at index 5 " << std::endl; iv.put(65, 5); std::cout << "Inputting value 70 " << std::endl; iv.put(70); std::cout << "Inputting value 81 " << std::endl; iv.put(81); std::cout << "Inputting value 89 " << std::endl; iv.put(89); std::cout << std::endl; std::cout << "-------Displaying values of iv-------" << std::endl; for(int i = 0; i < iv.size(); i++){ std::cout << iv.get(i) << '\t'; } std::cout << std::endl; std::cout << "iv should have values: " << "[65, 70 , 81, 89]" << std::endl; std::cout << std::endl; std::cout << "------------------------------------" << std::endl; std::cout << "----------Testing size--------------" << std::endl; std::cout << "------------------------------------" << std::endl; std::cout << "The size of iv should be: 4" << std::endl; std::cout << "iv size is: " << iv.size() << std::endl; std::cout << std::endl; //For get function std::cout << "------------------------------------" << std::endl; std::cout << "-----------Testing get--------------" << std::endl; std::cout << "------------------------------------" << std::endl; try{ std::cout << "Getting value at index 2 " << std::endl; std::cout <<iv.get(2) << std::endl; std::cout << "Value at index 2 should be: [80] " << std::endl; std::cout << std::endl; std::cout << "Getting value of at index 40 " << std::endl; std::cout << "Get value at index: [Index should be out of range] " << iv.get(40) << std::endl; } //Catching out of bounds exception catch(const std::out_of_range& e){ std::cout << e.what() << '\n'; } //------------------------------------------------------------------------- // test CharacterVector: put, get, size, out_of_range std::cout << std::endl; std::cout << "----------------" << std::endl; std::cout << "CharacterVector:" << std::endl; std::cout << "----------------" << std::endl; // add try-catch for get try { std::cout << "--------------------------------" << std::endl; std::cout << "Testing cv.put('a', 0) method" << std::endl; cv.put('a', 0); std::cout << "cv = " << cv.get(0) << " [a]" << std::endl; std::cout << "--------------------------------" << std::endl; std::cout << "Testing cv.size() method" << std::endl; std::cout << "size of cv = " << cv.size() << " [1]" << std::endl; std::cout << "--------------------------------" << std::endl << std::endl; std::cout << "--------------------------------" << std::endl; std::cout << "Testing cv.put('b', 1) method" << std::endl; cv.put('b', 1); std::cout << "cv = " << cv.get(0) << cv.get(1) << " [ab]" << std::endl; std::cout << "--------------------------------" << std::endl; std::cout << "Testing cv.size() method" << std::endl; std::cout << "size of cv = " << cv.size() << " [2]" << std::endl; std::cout << "--------------------------------" << std::endl << std::endl; std::cout << "--------------------------------" << std::endl; std::cout << "Testing cv.put('b', 0) method" << std::endl; cv.put('b', 0); std::cout << "cv = " << cv.get(0) << cv.get(1) << " [bb]" << std::endl; std::cout << "--------------------------------" << std::endl; std::cout << "Testing cv.size() method" << std::endl; std::cout << "size of cv = " << cv.size() << " [2]" << std::endl; std::cout << "--------------------------------" << std::endl << std::endl; std::cout << "--------------------------------" << std::endl; std::cout << "Testing invalid index with cv.get(2)" << std::endl; std::cout << "cv = " << cv.get(0) << cv.get(1) << cv.get(2)<< std::endl; std::cout << "--------------------------------" << std::endl << std::endl; } catch(std::exception& e) { std::cout << "The following exception was thrown: " << e.what() << std::endl; std::cout << "--------------------------------" << std::endl << std::endl; } //------------------------------------------------------------------------- // test DoubleVector: put, get, size, out_of_range std::cout << std::endl; std::cout << "-------------" << std::endl; std::cout << "DoubleVector:" << std::endl; std::cout << "-------------" << std::endl; // std::cout << "Testing default constructor" << std::endl; // for ( int i = 0; i < dv.size(); i++) // { // std::cout << dv.get(i); // } // std::cout <<"[]"<< std::endl; // std::cout << dv.size() << "[0]" << std::endl; // std::cout << "-------------" << std::endl; std::cout << "Testing put(value)" << std::endl; dv.put(71.11); for ( int i = 0; i < dv.size(); i++) { std::cout << dv.get(i)<<'\t'; } std::cout <<"[71.11]"<< std::endl; std::cout << dv.size() << "[1]" << std::endl; dv.put(72.22); for ( int i = 0; i < dv.size(); i++) { std::cout << dv.get(i)<<'\t'; } std::cout <<"[71.11 72.22]"<< std::endl; std::cout << dv.size() << "[2]" << std::endl; std::cout << "-------------" << std::endl; std::cout << "Testing put(value, index)" << std::endl; dv.put(73.33, 5); for ( int i = 0; i < dv.size(); i++) { std::cout << dv.get(i) << '\t'; } std::cout <<"[71.11 72.22 73.33]"<< std::endl; std::cout << dv.size() << "[3]" << std::endl; dv.put(74.44,0); for ( int i = 0; i < dv.size(); i++) { std::cout << dv.get(i)<< '\t'; } std::cout <<"[74.44 72.22 73.33]"<< std::endl; std::cout << dv.size() << "[3]" << std::endl; std::cout << "-------------" << std::endl; std::cout << "Testing get" << std::endl; std::cout << dv.get(0) << "[74.44]" << std::endl; std::cout << dv.get(1) << "[72.22]" << std::endl; try { std::cout<< dv.get(10) << std::endl; } catch (std::exception& e) { std::cerr << "exception caught: " << e.what() << '\n'; } std::cout << "-------------" << std::endl; std::cout << "Testing size" << std::endl; std::cout << dv.size() << "[3]" << std::endl; //------------------------------------------------------------------------- // using empty IntegerVector, test appending cv & dv from above IntegerVector iv2; std::cout << std::endl; std::cout << "Appending DoubleVector " << std::endl; std::cout << "--------------------------" << std::endl; std::cout << "appended-to IntegerVector:" << std::endl; std::cout << "--------------------------" << std::endl; std::cout << std::endl; iv2.appendDoubleVector(dv); for(int i = 0; i < iv2.size(); i++){ std::cout << iv2.get(i) << std::endl; } std::cout << "[74.44 72.22 73.33 should be 74, 72, 73]" << std::endl; std::cout << "Appending CharacterVector " << std::endl; std::cout << std::endl; iv2.appendCharacterVector(cv); for(int i = 0; i < iv2.size(); i++){ std::cout << iv2.get(i) << std::endl; } std::cout << std::endl; std::cout << "-------Final Result ------" << std::endl; std::cout << "[74, 72, 73, b (98), b (98)]" << std::endl; std::cout << std::endl; //------------------------------------------------------------------------- // using empty CharacterVector, test appending iv & dv from above CharacterVector cv2; std::cout << "----------------------------" << std::endl; std::cout << "appended-to CharacterVector:" << std::endl; std::cout << "----------------------------" << std::endl; std::cout << "--------------------------------" << std::endl; std::cout << "Testing cv2.appendIntegerVector(iv) method" << std::endl; cv2.appendIntegerVector(iv); std::cout << cv2.get(0) << "[A]" << std::endl; std::cout << cv2.get(1) << "[F]" << std::endl; std::cout << cv2.get(2) << "[Q]" << std::endl; std::cout << cv2.get(3) << "[Y]" << std::endl; std::cout << "--------------------------------" << std::endl; std::cout << "Testing cv2.size() method" << std::endl; std::cout << "size of cv2 = " << cv2.size() << " [4]" << std::endl; std::cout << "--------------------------------" << std::endl << std::endl; std::cout << "--------------------------------" << std::endl; std::cout << "Testing cv2.appendDoubleVector(dv) method" << std::endl; cv2.appendDoubleVector(dv); std::cout << cv2.get(4) << "[J]" << std::endl; std::cout << cv2.get(5) << "[H]" << std::endl; std::cout << cv2.get(6) << "[I]" << std::endl; std::cout << "--------------------------------" << std::endl; std::cout << "Testing cv2.size() method" << std::endl; std::cout << "size of cv2 = " << cv2.size() << " [7]" << std::endl; std::cout << "--------------------------------" << std::endl << std::endl; //------------------------------------------------------------------------- // using empty DoubleVector, test appending iv & cv from above DoubleVector dv2; std::cout << std::endl; std::cout << "-------------------------" << std::endl; std::cout << "appended-to DoubleVector:" << std::endl; std::cout << "-------------------------" << std::endl; dv2.appendIntegerVector( iv ); for ( int i = 0; i < dv2.size(); i++) { std::cout << dv2.get(i)<< ','; } std::cout << "[65,70,81,89]"<<std::endl; dv2.appendCharacterVector( cv ); for ( int i = 0; i < dv2.size(); i++) { std::cout << dv2.get(i)<< ','; } std::cout << "[65,70,81,89,98(b),98(b)]"<<std::endl; //------------------------------------------------------------------------- return 0; }
true
c9ef2e4aaf5ed5ffa8a9f8a37c205b0ea2f9de38
C++
sandeepgupta007/ACinCP
/Strings/RomanToIntger.cpp
UTF-8
896
3.078125
3
[]
no_license
int value(char r){ if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1; } int Solution::romanToInt(string A) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details int ans=0; for (int i=0;i<A.length()-1;i++){ int val1 = value(A[i]); int val2 = value(A[i+1]); if(val1 >= val2){ ans+=(val1); } else{ ans-=(val1); } } ans+=(value(A[A.length()-1])); return ans; }
true
9c462c47ef0c92c21786d58c7dab253b6f8c30f4
C++
Nanoteck137/Seek
/Seek/Source/Seek/UI/Transition/ValueDriver.cpp
UTF-8
899
2.671875
3
[ "MIT" ]
permissive
#include "SeekPCH.h" #include "Seek/UI/Transition/ValueDriver.h" namespace Seek { ValueDriver::ValueDriver(float length) : m_Length(length), m_StartTime(0) {} ValueDriver::ValueDriver(float startTime, float length) : m_StartTime(startTime), m_Length(length) { } float ValueDriver::Update(float deltaTime) { m_CurrentTime += deltaTime; if (m_CurrentTime < m_StartTime) { m_CurrentValue = CalculateValue(0); return m_CurrentValue; } float totalTime = m_Length + m_StartTime; if (m_CurrentTime >= totalTime) { m_CurrentTime = fmod(m_CurrentTime, totalTime); m_FirstPeriodDone = true; } float relativeTime = (m_CurrentTime - m_StartTime) / m_Length; m_CurrentValue = CalculateValue(relativeTime); return m_CurrentValue; } }
true
e41a9bfbb0e5e0f2031571ff9405f9963cbc22e0
C++
Shanghai-/3DGameEnginesFinal
/src/engine/components/ColEllipsoid.cpp
UTF-8
656
2.5625
3
[]
no_license
#include "ColEllipsoid.h" #include "engine/graphics/Graphics.h" #include "engine/components/CTransform.h" ColEllipsoid::ColEllipsoid(std::shared_ptr<GameObject> parent, glm::vec3 radii) : Component(parent), m_radii(radii) { } ColEllipsoid::~ColEllipsoid() { } void ColEllipsoid::drawWireframe() { Graphics *g = Graphics::getGlobalInstance(); auto thisTrans = getParent()->getComponent<CTransform>(); std::cout << glm::to_string(m_radii) << std::endl; g->clearTransform(); g->translate(thisTrans->pos); g->scale(m_radii * 2.f); g->drawShape("wire_sphere"); } glm::vec3 ColEllipsoid::getRadii() { return m_radii; }
true
3136f88d7a32a007b5f5103955edd38bdc70d511
C++
Anubhav12345678/competitive-programming
/MINSWAPSTOGROUPALLONESTOGETHERVVVVVIMPGFG.cpp
UTF-8
1,351
3.828125
4
[]
no_license
// C++ program to find minimum swaps // required to group all 1's together #include <iostream> #include <limits.h> using namespace std; // Function to find minimum swaps // to group all 1's together int minSwaps(int arr[], int n) { int noOfOnes = 0; // find total number of all in the array for (int i = 0; i < n; i++) { if (arr[i] == 1) noOfOnes++; } // length of subarray to check for int x = noOfOnes; int maxOnes = INT_MIN; // array to store number of 1's upto // ith index int preCompute[n] = {0}; // calculate number of 1's upto ith // index and store in the array preCompute[] if (arr[0] == 1) preCompute[0] = 1; for (int i = 1; i < n; i++) { if (arr[i] == 1) { preCompute[i] = preCompute[i - 1] + 1; } else preCompute[i] = preCompute[i - 1]; } // using sliding window technique to find // max number of ones in subarray of length x for (int i = x - 1; i < n; i++) { if (i == (x - 1)) noOfOnes = preCompute[i]; else noOfOnes = preCompute[i] - preCompute[i - x]; if (maxOnes < noOfOnes) maxOnes = noOfOnes; } // calculate number of zeros in subarray // of length x with maximum number of 1's int noOfZeroes = x - maxOnes; return noOfZeroes; } // Driver Code int main() { int a[] = {1, 0, 1, 0, 1}; int n = sizeof(a) / sizeof(a[0]); cout << minSwaps(a, n); return 0; }
true
8055ecd016627eb726babb34e8b1ab596d9e8e86
C++
emmerich-research/new-contaminant-detection
/libstorage/database.cpp
UTF-8
3,014
2.5625
3
[]
no_license
#include "storage.hpp" #include "database.hpp" #include <libutil/util.hpp> NAMESPACE_BEGIN namespace storage { static Storage init_storage(const std::string& path) { using namespace sqlite_orm; fs::path p = path; auto parent_path = p.parent_path(); if (!parent_path.empty()) fs::create_directory(parent_path); return sqlite_orm::make_storage( path, sqlite_orm::make_table( "IMAGES", sqlite_orm::make_column("ID", &schema::Image::id, autoincrement(), primary_key()), sqlite_orm::make_column("HASH", &schema::Image::hash, unique()), sqlite_orm::make_column("YEAR", &schema::Image::year), sqlite_orm::make_column("MONTH", &schema::Image::month), sqlite_orm::make_column("DAY", &schema::Image::day), sqlite_orm::make_column("HOUR", &schema::Image::hour), sqlite_orm::make_column("MINUTE", &schema::Image::minute), sqlite_orm::make_column("SECOND", &schema::Image::second), sqlite_orm::make_column("SKU_CARD", &schema::Image::sku_card), sqlite_orm::make_column("SKU_NUMBER", &schema::Image::sku_number), sqlite_orm::make_column("SKU_PROD_DAY", &schema::Image::sku_prod_day), sqlite_orm::make_column("TRAY_BARCODE", &schema::Image::tray_barcode), sqlite_orm::make_column("LID_BARCODE", &schema::Image::lid_barcode), sqlite_orm::make_column("BATCH_ID", &schema::Image::batch_id), sqlite_orm::make_column("INFECTION_ID", &schema::Image::infection_id))); } Database::Database() {} Database::~Database() {} InternalDatabase::InternalDatabase(const std::string& path) : path_{std::move(path)}, storage_{init_storage(path)} { storage().sync_schema(); } InternalDatabase::~InternalDatabase() {} schema::Image InternalDatabase::get(const schema::Hash& hash) { using namespace sqlite_orm; auto images = storage().select(&schema::Image::id, where(is_equal(&schema::Image::hash, hash))); return storage().get<schema::Image>(images[0]); } void InternalDatabase::insert(const schema::Image& image) { storage().insert(image); } schema::Image InternalDatabase::first() { using namespace sqlite_orm; auto users = storage().get_all<schema::Image>(limit(1)); return users.front(); } void InternalDatabase::remove(const schema::Hash& hash) { using namespace sqlite_orm; storage().remove_all<schema::Image>( where(is_equal(&schema::Image::hash, hash))); } int InternalDatabase::num_entries() { return storage().count<schema::Image>(); } bool InternalDatabase::empty() { return num_entries() == 0; } bool InternalDatabase::check(const storage::schema::Hash& hash) { using namespace sqlite_orm; auto images = storage().select(&schema::Image::hash, where(is_equal(&schema::Image::hash, hash))); return images.size() == 1; } } // namespace storage NAMESPACE_END
true
2b27a28061028b621099fa22c0afe000018ea98b
C++
AlfavilleLM/souliss
/frame/vNet/feelbrave/vNet_example1_chibi_TX/vNet_example1_chibi_TX.ino
UTF-8
1,461
2.65625
3
[]
no_license
/* vNet Example 1, Data Transmission A standard Node (TX) send data to a device out of its subnet (RX), data are sent via the SuperNode (SN). The received message is printed-out by RX node, you can see the message IN/OUT activating the VNET_DEBUG functionality. *************************Definitions************************* Configuration file Parameter vNet_Config.h #define VNET_SUPERNODE 0 vNet_Config.h #define VNET_MEDIA1_ENABLE 0 vNet_Config.h #define VNET_MEDIA2_ENABLE 1 vNet_Config.h #define VNET_MEDIA3_ENABLE 0 vNet_Config.h #define VNET_MEDIA4_ENABLE 0 vNet_Config.h #define VNET_MEDIA5_ENABLE 0 Only if debug on serial port is required, vNet_Config.h #define VNET_DEBUG 1 */ #include "Souliss.h" #include "Typicals.h" #include <SPI.h> // Message to sent over network byte msg1[] = "Stevm scarz"; byte msg2[] = "a ftient!"; void setup() { Serial.begin(9600); // setup the USART vNet_Init(); // init the vNet layer vNet_SetAddress(0x6612, 2); // set the node address vNet_SetSubnetMask(0xFF00, 2); // set the node subnet mask vNet_SetMySuperNode(0x6601, 2); // set the associated supernode } void loop() { // We're going to add 1 to the message length to handle the terminating null // character for a string '/0'. vNet_SendData(0x6501, msg1, 11, 0x10); // send msg1 delay(5000); vNet_SendData(0x6501, msg2, 12, 0x10); // send msg2 delay(5000); }
true
dbe5d789f957212dc513cb5ab85d68bec3047ce4
C++
robert333/steiner_trees
/source/steiner_trees/SteinerTreeCut.cpp
UTF-8
2,301
2.84375
3
[]
no_license
#include "SteinerTreeCut.hpp" namespace steiner_trees { SteinerTreeCut::SteinerTreeCut(graph::Graph const& graph, graph::Net const& net) : _graph(graph), _net(net), _characteristic_vector(graph.num_nodes(), false) { while (not is_valid()) { next_characteristic_vector(); } } bool SteinerTreeCut::next() { do { next_characteristic_vector(); } while (not is_valid() and not is_zero_characteristic_vector()); return not is_zero_characteristic_vector(); } bool SteinerTreeCut::is_valid() const { std::vector<graph::NodeId> const nodes_within_cut = compute_nodes_within_cut(); return not helper::contains(nodes_within_cut, _net.terminal(0)) and not helper::are_disjoint(nodes_within_cut, _net.terminals()); } std::vector<graph::NodeId> SteinerTreeCut::compute_nodes_within_cut() const { std::vector<graph::NodeId> nodes_within_cut; for (graph::NodeId node_id = 0; node_id < _graph.num_nodes(); ++node_id) { if (_characteristic_vector.at(node_id)) { nodes_within_cut.push_back(node_id); } } return nodes_within_cut; } std::vector<graph::EdgeId> SteinerTreeCut::compute_outgoing_edges() const { assert(is_valid()); std::vector<graph::NodeId> const nodes_within_cut = compute_nodes_within_cut(); std::vector<graph::EdgeId> outgoing_edges; for (graph::NodeId const& node_id : nodes_within_cut) { graph::Node const& node = _graph.node(node_id); for (graph::EdgeId const& edge_id : _graph.is_directed() ? node.outgoing_edges() : node.incident_edges()) { graph::Edge const& edge = _graph.edge(edge_id); if (not helper::contains(nodes_within_cut, edge.opposite(node_id))) { outgoing_edges.push_back(edge_id); } } } return outgoing_edges; } std::string SteinerTreeCut::to_string() const { return helper::to_string(compute_nodes_within_cut(), "nodes_within_cut"); } void SteinerTreeCut::next_characteristic_vector() { for (std::size_t i = 0; i < _characteristic_vector.size(); ++i) { _characteristic_vector.at(i) = not _characteristic_vector.at(i); if (_characteristic_vector.at(i)) { break; } } } bool SteinerTreeCut::is_zero_characteristic_vector() { for (std::size_t i = 0; i < _characteristic_vector.size(); ++i) { if (_characteristic_vector.at(i)) { return false; } } return true; } } // namespace steiner_trees
true
f94f53c65d2524102d6f5d9c611d5f3eb06a61c2
C++
lukasz-m-maciejewski/arcimboldo
/qml-ver/src/TargetDirectoryGenerator.cpp
UTF-8
1,067
2.84375
3
[]
no_license
#include "TargetDirectoryGenerator.hpp" TargetDirectoryGenerator::TargetDirectoryGenerator(QObject* parent) : QObject(parent) { connect(this, &TargetDirectoryGenerator::currentDirectoryChanged, this, &TargetDirectoryGenerator::onCurrentDirectoryChanged); } QString TargetDirectoryGenerator::currentDirectory() const { return m_currentDirectory; } void TargetDirectoryGenerator::setCurrentDirectory(QString currentDirectory) { if (m_currentDirectory == currentDirectory) return; m_currentDirectory = currentDirectory; emit currentDirectoryChanged(); } QString TargetDirectoryGenerator::targetDirectory() const { return m_targetDirectory; } void TargetDirectoryGenerator::setTargetDirectory(QString targetDirectory) { if (m_targetDirectory == targetDirectory) return; m_targetDirectory = targetDirectory; emit targetDirectoryChanged(); } void TargetDirectoryGenerator::onCurrentDirectoryChanged() { m_targetDirectory = m_currentDirectory + "/selected/"; emit targetDirectoryChanged(); }
true
9b855aef3ca98685efa2fbcbd81377953994aace
C++
scriptkid23/design-ftp-client
/include/tcpclient.h
UTF-8
614
2.65625
3
[ "MIT" ]
permissive
#ifndef _TCP_CLIENT_H_ #define _TCP_CLIENT_H_ #include "tcpsocket.h" class TcpClient { protected: TcpSocket localsocket; bool connected; public: TcpClient(); bool isConnected() { return connected;} bool open(const string& serverHost, unsigned short port); bool open(const string& serverHost, const string& port); void sendStringRequest(const string& request); void sendDataBuffer(const char* buffer, unsigned int bufLen); int recvGetLine(char* buf,unsigned int maxLen); int recvDataBuffer(char* buffer, unsigned int bufLen); void close(); }; #endif // _TCP_CLIENT_H_
true
0b195b92772dd9d831a1274d2bb18d7f508513e4
C++
DanielVillena/2-EVA
/ANTONIO HITGUB/PRINTF Y SCANF.cpp
ISO-8859-1
635
3.515625
4
[]
no_license
#include <stdio.h> //nombre de la biblioteca es = siempre int main(){ int num1 = 10; char mensaje[] = "Hola"; //char es usado para guardar palabra printf("%s, soy el nmero %d. \n", num1, mensaje); //printf es = a cout. %s=num1 porque lo pone al final y %d=mensaje return 0; } %d numero entero %f numero real %c caracter %s cadena de texto #include <stdio.h> int main(){ char nombre[12]; printf("Introduce tu nombre: "); fflush(stdout); //Vaciar el buffer de salida scanf("%s",nombre); //scanf sirve para obtener una variable del usuario printf("Hola, %s :)\n", nombre); return 0; }
true
8bea2bf649ad036d7d0cab8b9bb120dc429eb77a
C++
libp2p/cpp-libp2p
/src/basic/varint_prefix_reader.cpp
UTF-8
1,557
2.515625
3
[ "MIT", "Apache-2.0" ]
permissive
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include <libp2p/basic/varint_prefix_reader.hpp> namespace libp2p::basic { namespace { constexpr uint8_t kHighBitMask = 0x80; // just because 64 == 9*7 + 1 constexpr uint8_t kMaxBytes = 10; } // namespace void VarintPrefixReader::reset() { value_ = 0; state_ = kUnderflow; got_bytes_ = 0; } VarintPrefixReader::State VarintPrefixReader::consume(uint8_t byte) { if (state_ == kUnderflow) { bool next_byte_needed = (byte & kHighBitMask) != 0; uint64_t tmp = byte & ~kHighBitMask; switch (++got_bytes_) { case 1: break; case kMaxBytes: if (tmp > 1 || next_byte_needed) { state_ = kOverflow; return state_; } [[fallthrough]]; default: tmp <<= 7 * (got_bytes_ - 1); break; } value_ += tmp; if (!next_byte_needed) { state_ = kReady; } } else if (state_ == kReady) { return kError; } return state_; } VarintPrefixReader::State VarintPrefixReader::consume( gsl::span<const uint8_t> &buffer) { size_t consumed = 0; State s(state_); for (auto byte : buffer) { ++consumed; s = consume(byte); if (s != kUnderflow) { break; } } if (consumed > 0 && (s == kReady || s == kUnderflow)) { buffer = buffer.subspan(consumed); } return s; } } // namespace libp2p::basic
true
79d4a8f5504561c32a4de8394a5c291bf5f364c1
C++
arangodb/arangodb
/3rdParty/boost/1.78.0/libs/spirit/example/lex/lexer_debug_support.cpp
UTF-8
3,439
2.578125
3
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode...
permissive
// Copyright (c) 2001-2011 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #define BOOST_SPIRIT_LEXERTL_DEBUG 1 #include <boost/spirit/include/lex_lexertl.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/phoenix.hpp> namespace lex = boost::spirit::lex; namespace qi = boost::spirit::qi; namespace phoenix = boost::phoenix; /////////////////////////////////////////////////////////////////////////////// template <typename Lexer> struct language_tokens : lex::lexer<Lexer> { language_tokens() { tok_float = "float"; tok_int = "int"; floatlit = "[0-9]+\\.[0-9]*"; intlit = "[0-9]+"; ws = "[ \t\n]+"; identifier = "[a-zA-Z_][a-zA-Z_0-9]*"; this->self = ws [lex::_pass = lex::pass_flags::pass_ignore]; this->self += tok_float | tok_int | floatlit | intlit | identifier; this->self += lex::char_('='); } lex::token_def<> tok_float, tok_int; lex::token_def<> ws; lex::token_def<double> floatlit; lex::token_def<int> intlit; lex::token_def<> identifier; }; /////////////////////////////////////////////////////////////////////////////// template <typename Iterator> struct language_grammar : qi::grammar<Iterator> { template <typename Lexer> language_grammar(language_tokens<Lexer> const& tok) : language_grammar::base_type(declarations) { declarations = +number; number = tok.tok_float >> tok.identifier >> '=' >> tok.floatlit | tok.tok_int >> tok.identifier >> '=' >> tok.intlit ; declarations.name("declarations"); number.name("number"); debug(declarations); debug(number); } qi::rule<Iterator> declarations; qi::rule<Iterator> number; }; /////////////////////////////////////////////////////////////////////////////// int main() { // iterator type used to expose the underlying input stream typedef std::string::iterator base_iterator_type; // lexer type typedef lex::lexertl::actor_lexer< lex::lexertl::token< base_iterator_type, boost::mpl::vector2<double, int> > > lexer_type; // iterator type exposed by the lexer typedef language_tokens<lexer_type>::iterator_type iterator_type; // now we use the types defined above to create the lexer and grammar // object instances needed to invoke the parsing process language_tokens<lexer_type> tokenizer; // Our lexer language_grammar<iterator_type> g (tokenizer); // Our parser // Parsing is done based on the token stream, not the character // stream read from the input. std::string str ("float f = 3.4\nint i = 6\n"); base_iterator_type first = str.begin(); bool r = lex::tokenize_and_parse(first, str.end(), tokenizer, g); if (r) { std::cout << "-------------------------\n"; std::cout << "Parsing succeeded\n"; std::cout << "-------------------------\n"; } else { std::string rest(first, str.end()); std::cout << "-------------------------\n"; std::cout << "Parsing failed\n"; std::cout << "stopped at: \"" << rest << "\"\n"; std::cout << "-------------------------\n"; } std::cout << "Bye... :-) \n\n"; return 0; }
true
a51c6c8dc100ca27b744eb6244431f84a9e3b17c
C++
ccquan/C-program-exercises
/5.13-字符串连接.cpp
GB18030
511
3.359375
3
[]
no_license
#include <stdio.h> #include <string.h> int main() { int i, j = 0; char str1[20] = {"ַ1"}; char str2[20] = {"ַ2"}; char new_str[40]; // һѭȻжiiѭstr1ٽstr2ֵֵnew_str for(i = 0; i < (strlen(str1) + strlen(str2)); i++) { if(i < strlen(str1)) { new_str[i] = str1[i]; } else { new_str[i] = str2[j]; j++; } } // ӡ for(i = 0; i < strlen(new_str); i++) { printf("%c", new_str[i]); } }
true
3c7721c1f5ab019b101822e03a6a42d1ae0fdd1e
C++
HenryTraynor/Bike-Computer
/bikeComputer.ino
UTF-8
1,302
2.65625
3
[]
no_license
#include <Arduino.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <LiquidCrystal.h> const int hallPin=2; const double circumference=84.823; //in const int rs = 12, en = 11, d4 = 6, d5 = 5, d6 = 4, d7 = 3; int totalRev=0; double distance=0; int timeAtLastRev=0; double velocity=0.0; double distance2; double velocity2; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); void setup() { // put your setup code here, to run once: Serial.begin(9600); lcd.begin(16, 2); lcd.print("yo"); lcd.setCursor(13,0); lcd.print("mph"); lcd.setCursor(11,1); lcd.print("miles"); } double findDistance() { distance=circumference*totalRev; //in distance=distance/12; //ft distance=distance/5280; //mi return distance; } double findVelocity() { velocity=circumference/(millis()-timeAtLastRev); //in/ms timeAtLastRev=millis(); velocity=velocity/63360; //mi/ms velocity=velocity*3666666; //mph return velocity; } void loop() { // put your main code here, to run repeatedly: if (analogRead(1)<=3 && millis()-timeAtLastRev>170) { totalRev++; distance2=findDistance(); velocity2=findVelocity(); lcd.setCursor(0,0); lcd.print(velocity2); lcd.setCursor(0,1); lcd.print(distance2); } }
true
520837e824f0e32a069c1708089936396a2232b1
C++
zmichaels11/gloopcpp
/gloop/enums/src/blend_func.cpp
UTF-8
1,256
2.78125
3
[]
no_license
#include "blend_func.hpp" #include <iostream> namespace gloop { namespace enums { std::ostream& operator<<(std::ostream& os, blend_func enumval) { switch (enumval) { case blend_func::ZERO: return os << "ZERO"; case blend_func::ONE: return os << "ONE"; case blend_func::SRC_COLOR: return os << "SRC_COLOR"; case blend_func::ONE_MINUS_SRC_COLOR: return os << "ONE_MINUS_SRC_COLOR"; case blend_func::DST_COLOR: return os << "DST_COLOR"; case blend_func::ONE_MINUS_DST_COLOR: return os << "ONE_MINUS_DST_COLOR"; case blend_func::SRC_ALPHA: return os << "SRC_ALPHA"; case blend_func::ONE_MINUS_SRC_ALPHA: return os << "ONE_MINUS_SRC_ALPHA"; case blend_func::DST_ALPHA: return os << "DST_ALPHA"; case blend_func::ONE_MINUS_DST_ALPHA: return os << "ONE_MINUS_DST_ALPHA"; case blend_func::CONSTANT_COLOR: return os << "CONSTANT_COLOR"; case blend_func::ONE_MINUS_CONSTANT_COLOR: return os << "ONE_MINUS_CONSTANT_COLOR"; case blend_func::CONSTANT_ALPHA: return os << "CONSTANT_ALPHA"; case blend_func::ONE_MINUS_CONSTANT_ALPHA: return os << "ONE_MINUS_CONSTANT_ALPHA"; default: return os << "UNKNOWN"; } } } }
true
e48d18f0ea2a6ec06b874c4e3aebec352d6f44ef
C++
anagma/ofxTimebasedControl
/ofxTimebasedControlExample/src/ofApp.cpp
UTF-8
3,231
2.703125
3
[]
no_license
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ frameRate = 60; ofBackground(0, 0, 0); ofSetVerticalSync(false); ofSetFrameRate(frameRate); ofSetLogLevel(OF_LOG_NOTICE); ofSetRectMode(OF_RECTMODE_CENTER); ofNoFill(); ofEnableBlendMode(OF_BLENDMODE_ADD); degreeInFrame = 0; // initialize timebased control to 0 degreeInTime.set(0); // to 360, in 30 sec degreeInTime.start(360, 30000); ofAddListener(degreeInTime.timelineDone, this, &ofApp::repeat); // when time is done, repeat it. } //-------------------------------------------------------------- void ofApp::repeat(){ // repeat it degreeInTime.set(0); degreeInTime.start(360, 30000); // 30 sec ofLogNotice() << "timeline done, repeat it"; } //-------------------------------------------------------------- void ofApp::update(){ // if the frame rate is 60 strictly, it must be 360 in 30 sec. degreeInFrame += 0.2; if (degreeInFrame > 360) { degreeInFrame -= 360; } } //-------------------------------------------------------------- void ofApp::draw(){ // in frame glPushMatrix(); glTranslated(ofGetWidth()/3, ofGetHeight()/2, 0); ofSetColor(255, 128); for(int i=0; i<20; i++){ glRotated(degreeInFrame, 0, 0, 1); ofRect(0, 0, (20-i)*10, (20-i)*10); } glPopMatrix(); // in time glPushMatrix(); glTranslated(ofGetWidth()/3*2, ofGetHeight()/2, 0); ofSetColor(255, 128); for(int i=0; i<20; i++){ glRotated(degreeInTime.get(), 0, 0, 1); ofRect(0, 0, (20-i)*10, (20-i)*10); } glPopMatrix(); // status ofSetColor(255); ofDrawBitmapString("in frame", ofGetWidth()/3-100, ofGetHeight()/4); ofDrawBitmapString("in time", ofGetWidth()/3*2-100, ofGetHeight()/4); ofDrawBitmapString("frame rate: "+ofToString(ofGetFrameRate()), 20, 20); ofDrawBitmapString("elapsed time: "+ofToString(ofGetElapsedTimeMillis()), 20, 40); ofDrawBitmapString("press left to decrease frame rate, right to increse frame rate", 20, 60); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if(key == OF_KEY_LEFT){ frameRate-=10; if(frameRate < 10){ frameRate = 10; } ofSetFrameRate(frameRate); }else if(key == OF_KEY_RIGHT){ frameRate+=10; if(frameRate > 60){ frameRate = 60; } ofSetFrameRate(frameRate); } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
true
7cc593489f0f33b4c143041ae070822b2d541398
C++
santospdaniel/techreach-c-assignment-pub
/src/Loader.cpp
UTF-8
2,859
2.703125
3
[]
no_license
#include <c-assignment/Loader.hpp> #include <c-assignment/LoadersProcessor.hpp> #include <c-assignment/Processor.hpp> #include <c-assignment/FcCommand.hpp> #include <c-assignment/OutCommand.hpp> #include <c-assignment/RdtCommand.hpp> #include <c-assignment/RfcCommand.hpp> #include <sstream> namespace cassign { const std::string Loader::MESSAGE_COMMAND_PROCESSED = "Command processing took: "; const std::string Loader::MESSAGE_PROCESSING_UNITS = " seconds."; const std::string Loader::MESSAGE_UNKNOWN_COMMAND = "Unknown command!"; const std::string Loader::MESSAGE_PROCESSOR_BUSY = "Processor is currently busy."; Loader::Loader(cassign::LoadersProcessor* loadersProcessor) : m_loadersProcessor(loadersProcessor) { m_commands.push_back(std::make_shared<FcCommand>(FcCommand(dynamic_cast<CommandResources*>(m_loadersProcessor)))); m_commands.push_back(std::make_shared<OutCommand>(OutCommand(dynamic_cast<CommandResources*>(m_loadersProcessor)))); m_commands.push_back(std::make_shared<RdtCommand>(RdtCommand(dynamic_cast<CommandResources*>(m_loadersProcessor)))); m_commands.push_back(std::make_shared<RfcCommand>(RfcCommand(dynamic_cast<CommandResources*>(m_loadersProcessor)))); } void Loader::initialize() { for each(std::shared_ptr<Command> command in m_commands) { command->initialize(); } } void Loader::promptUser(std::istream* istream) { std::string userInput; *istream >> userInput; if (!userInput.empty()) //improve local CPU cache as probably the user input something. { cassign::ProcResult procResult = m_loadersProcessor->process(userInput); switch (procResult.procStatus) { case ProcStatus::PROCRESULT_UNKNOWN_CMD: dynamic_cast<DateLogger*>(m_loadersProcessor->getDateLogger())->writeLog(MESSAGE_UNKNOWN_COMMAND); dynamic_cast<OutLogger*>(m_loadersProcessor->getOutLogger())->writeLogFunc(MESSAGE_UNKNOWN_COMMAND); break; case ProcStatus::PROCRESULT_BUSY: dynamic_cast<OutLogger*>(m_loadersProcessor->getOutLogger())->writeLogFunc(MESSAGE_PROCESSOR_BUSY); break; case ProcStatus::PROCRESULT_PROCESSING: break; default: throw std::exception("Requesting to process a command resulted in an unknown processor result!"); } } } void Loader::processCallback(ProcResult procResult) const { if (procResult.procStatus == ProcStatus::PROCRESULT_PROCESSED) { if (procResult.procTime > 0) { std::ostringstream oss; oss.precision(2); oss << MESSAGE_COMMAND_PROCESSED << std::fixed << procResult.procTime << MESSAGE_PROCESSING_UNITS; dynamic_cast<FunctionalLogger*>(m_loadersProcessor->getFunctionalLogger())->writeLogFunc(oss.str()); dynamic_cast<OutLogger*>(m_loadersProcessor->getOutLogger())->writeLogFunc(oss.str()); } } else { throw std::exception("Unexpected command process status in callback."); } } }
true
c7e0948d1a8ac257e85011e8e4adf7db94fb86cd
C++
Icay12/LeetCode
/Cpp/200_NumberofIslands.cpp
UTF-8
4,433
3.171875
3
[]
no_license
//DFS public: int numIslands(vector<vector<char>>& grid) { int res = 0; if(grid.size() == 0 || grid[0].size() == 0 ) return res; for(int i = 0 ; i < grid.size(); ++i) { for(int j = 0; j < grid[0].size(); ++j) { if(grid[i][j] == '1') { res += 1; DFS(grid, i, j); } } } return res; } void DFS(vector<vector<char>>& grid, int i, int j) { grid[i][j] = '0'; if(i - 1 >= 0 && grid[i-1][j] == '1') DFS(grid, i-1, j); if(j - 1 >= 0 && grid[i][j-1] == '1') DFS(grid, i, j-1); if(i+1 < grid.size() && grid[i+1][j] == '1') DFS(grid, i+1, j); if(j+1 < grid[0].size() && grid[i][j+1] == '1') DFS(grid, i, j+1); } }; //BFS class Solution { public: int numIslands(vector<vector<char>>& grid) { int res = 0; if(grid.size() == 0 || grid[0].size() == 0 ) return res; for(int i = 0 ; i < grid.size(); ++i) { for(int j = 0; j < grid[0].size(); ++j) { if(grid[i][j] == '1') { res += 1; BFS(grid, i, j); } } } return res; } void BFS(vector<vector<char>>& grid, int i, int j) { queue<vector<int>> q; q.push({i,j}); grid[i][j] = '0'; while(!q.empty()) { int i = q.front()[0]; int j = q.front()[1]; // grid[i][j] = '0'; //if put it here, a neighbor will be visited a lot of times q.pop(); if(i - 1 >= 0 && grid[i-1][j] == '1') { q.push({i-1, j}); grid[i-1][j] = '0'; //should put it here } if(j - 1 >= 0 && grid[i][j-1] == '1') { q.push({i,j-1}); grid[i][j-1] = '0'; //should put it here } if(i+1 < grid.size() && grid[i+1][j] == '1') { q.push({i+1,j}); grid[i+1][j] = '0'; //should put it here } if(j+1 < grid[0].size() && grid[i][j+1] == '1') { q.push({i,j+1}); grid[i][j+1] = '0'; //should put it here } } } }; // Union Find class UF { private: int *id; int *rank; int count; public: UF(int N) { count = N; id = new int[N]; rank = new int[N]; for(int i = 0; i < N; ++i) { id[i] = i; rank[i] = 0; } } ~UF() { delete [] id; delete [] rank; } int getCount() { return count; } int find(int p) { while(p != id[p]) { id[p] = id[id[p]]; p = id[p]; } return p; } bool isConnected(int a, int b) { return find(a) == find(b); } void connect(int a, int b) { int i = find(a); int j = find(b); if(i == j) return; if(rank[i] > rank[j]) id[j] = i; else if(rank[j] > rank[i]) id[i] = j; else { id[i] = j; rank[j]++; } count--; } }; class Solution { public: int numIslands(vector<vector<char>>& grid) { if(grid.size() == 0 || grid[0].size() == 0 ) return 0; int n = grid.size(); int m = grid[0].size(); UF uf(n*m+1); for(int i = 0 ; i < n; ++i) { for(int j = 0; j < m; ++j) { if(grid[i][j] == '1') { if(i - 1 >= 0 && grid[i-1][j] == grid[i][j]) uf.connect(i*m+j, (i-1)*m+j); if(i + 1 < n && grid[i+1][j] == grid[i][j]) uf.connect(i*m+j, (i+1)*m+j); if(j - 1 >= 0 && grid[i][j-1] == grid[i][j]) uf.connect(i*m+j, i*m+j-1); if(j + 1 < m && grid[i][j+1] == grid[i][j]) uf.connect(i*m+j, i*m+j+1); } else { uf.connect(i*m+j, n*m); } } } return uf.getCount()-1; } };
true
f118c248bbc1f702438e8dcc158f3acedd1d23fa
C++
labodejuguete/gamelin
/sketchbook/gamelin_USB_comentado/gamelin_USB_comentado.ino
UTF-8
4,269
2.578125
3
[]
no_license
/* _____ _ __ _ _ _____ ____ / ____| | |/_/ | | | |/ ____| _ \ | | __ __ _ _ __ ___ ___| |_ _ __ | | | | (___ | |_) | | | |_ |/ _` | '_ ` _ \ / _ \ | | '_ \ | | | |\___ \| _ < | |__| | (_| | | | | | | __/ | | | | | | |__| |____) | |_) | \_____|\__,_|_| |_| |_|\___|_|_|_| |_| \____/|_____/|____/ por el Laboratorio de Juguete https://github.com/labodejuguete/gamelin/blob/master/README.md https://laboratoriodejuguete.com/ PINOUT: A: D0(PWM) B: D2/A1 C: D1(PWM) D: D4/A2/USB- E: D3/A3/USB+ F: D5/A0 */ int freq[]= {65,69,78,98,104,116,131,139,156, 196,208,233,262,277,311,392,415, 466,523,554,622,784,831,932,1046, 1109,1244,1568,1661,1865,2093,2217, 2489,3136,3322,3729}; // variable de tipo array (matriz) donde guardo las //frecuencias a ejecutar. Luego las buscaré por su ubicación // o número de índice dentro del array. int disparo[]= {1,5,25,50,100,200,400,800,1600}; // variable de tipo array (matriz) donde guardo los //intervalos de tiempo (expresados en milisegundos) //entre los "disparos" de cada tono. Luego los //buscaré por su ubicación o número de índice dentro //del array. int cobre; // variable en la que alojaremos el valor que entrega el contacto con la placa. int pote; // variable donde alojaremos el valor del potenciómetro A3. void setup() { //ésto se ejecuta sólo una vez pinMode(0, OUTPUT); // declaro el pin A (D0) como salida . } void loop() { //ésto se ejecuta continuamente... pote= analogRead (A2); //leo el valor numérico que entrega elvoltaje resultante //de mi contacto con la placa y lo asigno a esta variable. cobre = analogRead(A3); //leo el valor numérico que entrega elvoltaje resultante //de la posición de la perilla del pote A3 y lo asigno a //esta variable. int val1 = map(cobre, 0, 899, 35, 0); //variable donde asigno el resultado de escalar //los valores guardados en la variable cobre //a la cantidad de valores de frecuencia guardados //en el array freq[]. int val2= map(pote, 0, 1023, 8, 0); //variable donde asigno el resultado de escalar //los valores guardados en la variable pote //a la cantidad de valores de tiempo guardados //en el array disparo[]. if (cobre < 900){ // si se toca el cobre de la placa... tone (0, freq[val1]); // ejecutar en pin A(D0) la frecuencia del array freq[] //cuya ubicación esté alojada en la variable val1. delay (disparo[val2]); //esperar la cantidad de milisegundos del array disparo[] // cuya ubicación esté alojada en la variable val2. } else{ // si no se toca el cobre de la placa... noTone (0); //silenciar el pin A (D0). } } /* Octavas, notas y frecuencias correspondientes expresadas en números enteros: C C# D D# E F F# G G# A A# B 16 , 17 , 18 , 19 , 21 , 22 , 23 , 25 , 26 , 27 , 28 , 31 33 , 36 , 37 , 39 , 41 , 44 , 46 , 49 , 52 , 55 , 58 , 62 65 , 69 , 73 , 78 , 82 , 87 , 92 , 98 , 104 , 110 , 116 , 123 139 , 139 , 147 , 156 , 165 , 175 , 185 , 196 , 208 , 220 , 233 , 247 262 , 277 , 294 , 311 , 330 , 349 , 370 , 392 , 415 , 440 , 466 , 494 523 , 554 , 587 , 622 , 659 , 698 , 740 , 784 , 831 , 880 , 932 , 987 1047 , 1109 , 1175 , 1245 , 1319 , 1397 , 1480 , 1568 , 1661 , 1760 , 1865 , 1976 2093 , 2217 , 2349 , 2489 , 2637 , 2794 , 2960 , 3136 , 3322 , 3520 , 3729 , 3951 4186 , 4435 , 4699 , 4978 , 5274 , 5588 , 5920 , 6272 , 6645 , 7040 , 7459 , 7902 */
true
e24574638c93d406dac46f0eeaa8619d4fe1226d
C++
Stephenhua/CPP
/interview_Code/Code/DiDi-8-30-1.cpp
UTF-8
788
3.34375
3
[]
no_license
/* 题目:在字符串中找出4位整数; */ #include <iostream> #include <vector> #include <cmath> using namespace std; int Find4Int( string str) { int maxLen = -1; int start = 0 ; int tempIndex = 0 ; for(int i = 0 ; i< str.length() ;i ++){ if( str[i] >'0' && str[i] <= '9'){ int tempLen = 0 ; tempIndex = i ; while( str[i] >='0' && str[i] <= '9'){ i++; tempLen++; } if( tempLen == 4 ){ start= tempIndex ; return start; } } } return -1 ; } int main( int argc, char* argv[]){ string s = "abcd0123d12345fs"; int res = Find4Int(s); cout << res << endl; system("pause"); return 0 ; }
true
8e9656154171b832c5875ec3393f0be7fb4434d7
C++
zhangyiwen5512/myleetcode
/cleetcode/headers/mergeKLists.h
UTF-8
1,707
3.234375
3
[]
no_license
// // Created by zhangyiwen on 2020/12/11. // #ifndef CLEETCODE_MERGEKLISTS_H #define CLEETCODE_MERGEKLISTS_H #include <vector> #include <queue> /* * 给你一个链表数组,每个链表都已经按升序排列。 * 请你将所有链表合并到一个升序链表中,返回合并后的链表。 * 输入:lists = [[1,4,5],[1,3,4],[2,6]] * 输出:[1,1,2,3,4,4,5,6] * [ * 1->4->5, * 1->3->4, * 2->6 * ] * 将它们合并到一个有序链表中得到。 * 1->1->2->3->4->4->5->6 * * 输入:lists = [[]] * 输出:[] * * 输入:lists = [] * 输出:[] * k == lists.length * 0 <= k <= 10^4 * 0 <= lists[i].length <= 500 * -10^4 <= lists[i][j] <= 10^4 * lists[i] 按 升序 排列 * lists[i].length 的总和不超过 10^4 * * l和head指向空node * 构建小根堆,以每个列表第一个元素 * 得到这个最小元素n = p.top() * l.next = lists[n] * lists[n] = lists[n].next放入队列 * l = l.next * */ class mergeKLists { public: ListNode* Solution(std::vector<ListNode*>& lists) { struct cmp { bool operator() ( ListNode* a, ListNode* b ){ return a->val > b->val; } }; auto l = new ListNode(0, nullptr); auto head = l; std::priority_queue<ListNode*, std::vector<ListNode*>, cmp> p; for (int i = 0; i < lists.size(); ++i) { if (lists[i]) p.push(lists[i]); } while (!p.empty()){ auto temp = p.top(); p.pop(); l->next = temp; l = l->next; if (temp->next) p.push(temp->next); } return head->next; } }; #endif //CLEETCODE_MERGEKLISTS_H
true
e8b9d521e4d735a22cd5b4036848a38b6e693c14
C++
dormon/prj
/boxes/StructDescription.h
UTF-8
805
2.671875
3
[]
no_license
#pragma once #include<vector> #include"Defines.h" #include"TypeDescription.h" class StructDescription: public TypeDescription{ public: std::vector<TypeId>elementsTypes; StructDescription(std::string const&name,std::vector<TypeId>const&elements):TypeDescription(name,STRUCT){ PRINT_CALL_STACK(name,elements); assert(this!=nullptr); this->elementsTypes = elements; } ~StructDescription(){ PRINT_CALL_STACK(); } virtual void construct(void*ptr,std::shared_ptr<TypeRegister>const&tr)const override; virtual void destroy(void*ptr,std::shared_ptr<TypeRegister>const&tr)const override; virtual size_t byteSize(std::shared_ptr<TypeRegister>const&tr)const override; virtual std::string str(std::shared_ptr<TypeRegister>const&tr)const override; };
true
ce9545cbe27edc16cf1365ee4356553f111b42e6
C++
cxy229/dshomework
/graph/src/Graph.h
UTF-8
4,421
3.625
4
[]
no_license
/* * Graph.h * * Created on: Dec 17, 2015 * Author: cxy229 */ #ifndef GRAPH_H_ #define GRAPH_H_ #include<iostream> #include<iomanip>//声明一些流操作符 using namespace std; //最大权值 #define MAXWEIGHT 100 //用邻接矩阵实现图 class Graph { public: //numV顶点数,isWeighted是否带权值,isDirected是否有向 Graph(int numV, bool isWeighted , bool isDirected ); //建图 void createGraph(); ~Graph(); //获取顶点数 int GetVernums() { return numV; } //获取边数 int GetEdgeS() { return numE; } //设定给定边的权值 void setEdgeWeight(int start, int end, int weight); //打印邻接矩阵 void printAdjacentMatrix(); //检查输入 bool check(int i, int j, int w=1 ); private: //是否带权 bool isWeighted; //是否有向 bool isDirected; //顶点数 int numV; //边数 int numE; //邻接矩阵 int **matrix;//指向邻接矩阵的指针 }; //构造方法,numV顶点数,isWeighted是否带权值,isDirected是否有向 Graph::Graph(int numV, bool isWeighted , bool isDirected ) { this->numV = numV; this->isWeighted = isWeighted; this->isDirected = isDirected; this->numE = 0; matrix = new int *[numV];//指针数组 int i, j; for (i = 0; i < numV; i++) matrix[i] = new int[numV]; //对图进行初始化 if (!isWeighted)//无权图 { //所有权值初始化为0 for (i = 0; i < numV; i++) { for (j = 0; j < numV; j++) matrix[i][j] = 0; } } else //有权图 { //所有权值初始化为最大权值 for (i = 0; i < numV; i++) { for (j = 0; j < numV; j++) matrix[i][j] = MAXWEIGHT; } } } //建图 void Graph::createGraph() { cout << "输入边数:"; while (cin >> numE && numE < 0) cout << "输入有误!,重新输入 "; int i, j, w; this->numE = numE; if (!isWeighted) //无权图 { if (!isDirected) //无向图 { cout << "输入每条边的起点和终点:\n"; for (int k = 0; k < numE; k++) { cin >> i >> j; while (!check(i, j)) { cout << "输入的边不对!重新输入\n"; cin >> i >> j; } matrix[i][j] = matrix[j][i] = 1; } } else //有向图 { cout << "输入每条边的起点和终点:\n"; for (int k = 0; k < numE; k++) { cin >> i >> j; while (!check(i, j)) { cout << "输入的边不对!重新输入\n"; cin >> i >> j; } matrix[i][j] = 1; } } } else //有权图 { if (!isDirected) //无向图 { cout << "输入每条边的起点、终点和权值:\n"; for (int k = 0; k < numE; k++) { cin >> i >> j >> w; while (!check(i, j, w)) { cout << "输入的边不对!重新输入\n"; cin >> i >> j >> w; } matrix[i][j] = matrix[j][i] = w; } } else //有向图 { cout << "输入每条边的起点、终点和权值:\n"; for (int k = 0; k < numE; k++) { cin >> i >> j >> w; while (!check(i, j, w)) { cout << "输入的边不对!重新输入\n"; cin >> i >> j >> w; } matrix[i][j] = w; } } } } //析构方法 Graph::~Graph() { int i = 0; for (i = 0; i < numV; i++) delete[] matrix[i]; delete[] matrix; } //设置指定边的权值 void Graph::setEdgeWeight(int start, int end, int weight) { if (isWeighted)//有权图 { while (!check(start, end, weight)) { cout << "输入不正确,重新输入边的起点,终点和权值" << endl; cin >> start >> end >> weight; } if (isDirected) matrix[start][end] = weight; else matrix[start][end] = matrix[start][end] = weight; } else//无权图 { while (!check(start, end, 1)) { cout << "输入不正确,重新输入边的起点和终点" << endl; cin >> start >> end; } if (isDirected) matrix[start][end] = (weight!=0)?1:0; else matrix[start][end] = matrix[end][start] = (weight!=0)?1:0; } } //检查输入是否有误 bool Graph::check(int i, int j, int w ) { if (i >= 0 && i < numV && j >= 0 && j<numV && w>0 && w <= MAXWEIGHT) return true; else return false; } //打印邻接矩阵 void Graph::printAdjacentMatrix() { int i, j; cout.setf(ios::left); cout << setw(4) << " "; for (i = 0; i < numV; i++) cout << setw(4) << i; cout << endl; for (i = 0; i < numV; i++) { cout << setw(4) << i; for (j = 0; j < numV; j++) cout << setw(4) << matrix[i][j]; cout << endl; } } #endif /* GRAPH_H_ */
true
c2c2e6ef4a7095353f0b411d6328a8046f61dfbe
C++
Driven-Mad/PGAG
/PGAG_ASS/PGAG_ASS/Camera.h
UTF-8
811
3.09375
3
[]
no_license
#ifndef CAMERA_H #define CAMERA_H //------------------------------------------------------------------ /// \file Camera.h /// \author Lloyd Phillips /// \brief This is the Camera class //------------------------------------------------------------------ #include "Vec2.h" class Camera{ public: /// \brief Constructor Camera(); /// \brief destructor ~Camera(); /// \brief Updates the camera /// \brief Update Function based on position void update(Vec2 P); /// \brief Draw Function /// \brief Draws Camera to the screen void draw(); /// \brief gets the position of the camera /// \returns a Vec2 of position of the camera, returns x, y Vec2 getPos(); private: Vec2 position; ///<Position of the Camera in form of X, Y int levelWid , levelLen, winWid; /// <Level/Window sizes }; #endif ///!CAMERA_H
true
c70ccb1a175bc1819937a48deb4afa1618d221f0
C++
SeanHorner/cpp
/financial_simulator/monthlyFinancials.hpp
UTF-8
2,452
3.546875
4
[]
no_license
/** * Creator: Sean Horner * Date: 03/11/2020 * Updated: 03/23/2020 * Purpose: This is the header file defining the monthlyFinancials class type, * used to hold monthly expenditures. * Requires: None **/ #ifndef monthlyFinancials_HPP #define monthlyFinancials_HPP #include <iostream> #include <string> using std::string; using std::cout; class monthlyFinancials { private: double rent; double utilities; double groceries; double gasoline; double entertainment; double income; double savingsCut; public: monthlyFinancials() { rent = 0; utilities = 0; groceries = 0; entertainment = 0; income = 0; savingsCut = 0; } //Set and get methods for the rent variable void setRent(double num) { rent = num; } double getRent() { return rent; } //Set and get variables for the utilities variable void setUtilities(double num) { utilities = num; } double getUtitlities() { return utilities; } //Set and get variables for the groceries variable void setGroceries(double num) { groceries = num; } double getGroceries() { return groceries; } //Set and get variables for the gasoline variable void setGasoline(double num) { gasoline = num; } double getGasoline() { return gasoline; } //Set and get variables for the entertainment variable void setEntertainment(double num) { entertainment = num; } double getEntertainment() { return entertainment; } //Set and get variables for the income variable void setIncome(double num) { income = num; } double getIncome() { return income; } //Set and get variables for the savingsCut variable void setSavingsCut(double num) { savingsCut = num; } double getSavingsCut() { return savingsCut; } //Method for printing monthly financial variables void printStatement() { cout << " Income: " << "\033[32m" << income * (1 - savingsCut) << "\033[0m\n" << " Savings: " << "\033[32m" << income * savingsCut << "\033[0m\n" << " Rent: " << "\033[31m" << rent << "\033[0m\n" << " Utilities: " << "\033[31m" << utilities << "\033[0m\n" << " Groceries: " << "\033[31m" << groceries << "\033[0m\n" << " Gas : " << "\033[31m" << gasoline << "\033[0m\n" << " Entertainment: " << "\033[31m" << entertainment << "\033[0m\n\n"; } }; #endif
true
a67d52ba5721e254523cc87106b653484ff06bc5
C++
bn90207/Fuji_log_parser
/score_matrix/sources/score_matrix.cpp
UTF-8
8,009
2.84375
3
[]
no_license
#include<iostream> #include<fstream> #include<dirent.h> #include<string> #include<vector> #include<sys/stat.h>//stat(), S_ISDIR() #include<algorithm>//remove_if, find #include<boost/filesystem.hpp>//remove_all #include <unistd.h>//rmdir #include"windows.h"//CreateDirectory using namespace std; string dest_path = "D:\\Project\\template_matching\\Fuji Log\\classifier\\result"; bool is_dir(string); int get_dir_list(string, vector<string>&); int get_tif_number(string); void read_score(string, string, int, int, vector< vector<double> >&); void output_score(string, int, vector< vector<double> >&); void remove_old_group(string); void group(string, int, vector< vector<double> >&); //void remove_all(string); bool is_dir(string path) { struct stat sb; if(stat(path.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) return true; return false; } int get_dir_list(string path, vector<string>& dir_list) { //Check wether the path represent a directory. if(is_dir(path)) { DIR* dir; struct dirent* ent; if((dir = opendir(path.c_str())) != NULL) { while((ent = readdir(dir)) != NULL) { string file_name = ent->d_name; if(file_name == "." || file_name == ".."){} else if(is_dir(path+"\\"+file_name)) dir_list.push_back(path+"\\"+file_name); } } } else return -1; return 0; } int get_tif_number(string path) { DIR *dir; struct dirent *ent; int tif_number = 0; if((dir = opendir(path.c_str())) != NULL) { while((ent = readdir(dir)) != NULL) { string file_name = ent->d_name; if(file_name.find(".tif") != string::npos) ++tif_number; } } return tif_number; } void read_score(string path, string file_name, int template_number, int total_number, vector< vector<double> >& score_mat) { ifstream score_log; score_log.open((path+"\\"+file_name).c_str()); if(score_log) { cout << "read " << path << "\\" << file_name << " success." << endl; string row; //Throw out the header getline(score_log, row); int image_number; double score; //Get score for each template; while(getline(score_log, row))//Since we seperate numbers by comma, we can't use "while(score_log >> i && score_log >> j)" to retrieve image-number and score in the same row. { size_t pos = row.find(','); image_number = stoi(row.substr(0, pos)); score = stod(row.substr(pos+1)); score_mat[image_number][template_number] = score; } } else cout << "read " << path << "\\" << file_name << "fail." << endl; score_log.clear(); return; } void output_score(string path, int total_number, vector< vector<double> >& score_mat) { ofstream out_mat; out_mat.open((path+"\\score_matrix.csv").c_str()); for(int row=0; row<=total_number; ++row) { for(int col=0; col<=total_number; ++col) col==total_number? out_mat<<score_mat[row][col]: out_mat<<score_mat[row][col]<<","; out_mat << endl; } out_mat.close(); } /* void remove_all(string path) { DIR *dir; struct dirent *ent; if((dir = opendir(path.c_str())) != NULL) { while((ent = readdir(dir)) != NULL) { string file_name = ent->d_name; if(file_name == "." || file_name == ".."){} else if(is_dir(path+"\\"+file_name)) remove_all(path+"\\"+file_name); else remove((path+"\\"+file_name).c_str()); } } rmdir(path.c_str()); }*/ void remove_old_group(string path) { DIR *dir; struct dirent *ent; if((dir = opendir(path.c_str())) != NULL) { while((ent = readdir(dir)) != NULL) { string file_name = ent->d_name; if(file_name.find("group") != string::npos) { boost::filesystem::remove_all(boost::filesystem::path(path+"\\"+file_name)); /* if(is_dir(path+"\\"+file_name)) remove_all((path+"\\"+file_name).c_str()); else remove((path+"\\"+file_name).c_str()); */ } } } return; } void group(string path, int total_number, vector< vector<double> >& score_mat) { remove_old_group(path); int group_number = 0; double threshold = 0.9; vector<int> ungroup_member; ungroup_member.reserve(total_number); for(int i=1; i<score_mat.size(); ++i) ungroup_member.push_back((int)score_mat[0][i]); while(ungroup_member.size() > 0) { ++group_number; vector<int> group_member; group_member.reserve(ungroup_member.size()); //Initailize group_member; for(vector<int>::iterator iter=ungroup_member.begin(); iter!=ungroup_member.end(); ++iter) group_member.push_back(*iter); //Remove the objects with score comparing to subject less than threshold. for(vector<int>::iterator subject=group_member.begin(); subject!=group_member.end(); ++subject) { for(vector<int>::iterator object=subject+1; object!=group_member.end(); ++object) { if(score_mat[*subject][*object] < threshold || score_mat[*object][*subject] < threshold) object = group_member.erase(object) - 1;//erase() will return an iterator pointing to the element followed the removed one. } } //Create an matrix to store similar members. vector< vector<double> > group_mat(group_member.size()+1, vector<double>(group_member.size()+1)); for(int col=0; col<=group_member.size(); ++col) { for(int row=0; row<=group_member.size(); ++row) { if(col == 0 && row == 0) continue; else if(col == 0 || row == 0)//Fill the first row and column. group_mat[row][col] = group_member[row+col-1]; else group_mat[row][col] = score_mat[group_member[row-1]][group_member[col-1]]; } } //Output group matrix. string dir = path+"\\group_"+to_string(group_number); CreateDirectory(dir.c_str(), NULL); ofstream out_mat; out_mat.open((dir+"\\group_"+to_string(group_number)+".csv").c_str()); for(int row=0; row<group_mat.size(); ++row) { for(int col=0; col<group_mat.size(); ++col) col==group_mat.size()-1? out_mat<<group_mat[row][col]: out_mat<<group_mat[row][col]<<","; out_mat << endl; } out_mat.close(); //Create a directory to store similar mark for(vector<int>::iterator iter=group_member.begin(); iter!=group_member.end(); ++iter) { ifstream source; source.open((path+"\\"+to_string(*iter)+".tif").c_str(), ios_base::binary); ofstream dest; dest.open((dir+"\\"+to_string(*iter)+".tif").c_str(), ios_base::binary); dest << source.rdbuf(); source.close(); dest.close(); } //Remove grouped member from ungroup member. ungroup_member.erase(remove_if(ungroup_member.begin(), ungroup_member.end(), [&](int member){ return find(group_member.begin(), group_member.end(), member)!=group_member.end(); }), ungroup_member.end()); group_member.clear(); } } int main(){ vector<string> dir_list; dir_list.reserve(8);//Do not use resize. it may cause problem when iterating vector if the elements pushed in were less than the resize() reserved. get_dir_list(dest_path, dir_list); for(vector<string>::iterator iter=dir_list.begin(); iter!=dir_list.end(); ++iter) { cout << *iter << endl; //Create a 2D vector to store score for each template. int mark_number = get_tif_number(*iter); vector< vector<double> > score_mat(mark_number+1, vector<double>(mark_number+1));//Use vector is much better than array because in the spirit of array its size should be fixed in compiling time. for(int i=1; i<=mark_number; ++i)//Initialize first row and column. Remeber the column index represents the template and the row index is the image. { score_mat[i][0] = i; score_mat[0][i] = i; } //Read each score-logs for(int i=1; i<=mark_number; ++i) { string score_log = to_string(i) + "(score).csv"; read_score(*iter, score_log, i, mark_number, score_mat); } output_score(*iter, mark_number, score_mat); group(*iter, mark_number, score_mat); }//After leaving the block, vector would be automatically released. }
true
a4a1d389c3d64b19394e1760d28a7b697e5fc57c
C++
utec-cs-aed-2021-2/circular-array-IsaacVera10
/circulararray.h
UTF-8
3,927
3.859375
4
[]
no_license
#include <iostream> using namespace std; template <class T> class CircularArray { private: T *array; int capacity; int back, front; public: CircularArray(); CircularArray(int _capacity); virtual ~CircularArray(); void push_front(T data); void push_back(T data); void insert(T data, int pos); T pop_front(); T pop_back(); bool is_full(); bool is_empty(); int size(); void clear(); T &operator[](int); void sort(); bool is_sorted(); void reverse(); string to_string(string sep=" "); private: int next(int); int prev(int); }; template <class T> CircularArray<T>::CircularArray() { CircularArray(0); } template <class T> CircularArray<T>::CircularArray(int _capacity) { this->array = new T[_capacity]; this->capacity = _capacity; this->front = this->back = -1; } template <class T> CircularArray<T>::~CircularArray() { delete[] array; } template <class T> int CircularArray<T>::prev(int index) { return (index == 0) ? capacity - 1 : index - 1; } template <class T> int CircularArray<T>::next(int index) { return (index + 1) % capacity; } template <class T> string CircularArray<T>::to_string(string sep) { string result = ""; for (int i = 0; i < size(); i++) result += std::to_string((*this)[i]) + sep; return result; } //AGREGADO template<class T> T & CircularArray<T>::operator[](int iterator){ return array[iterator]; } template <class T> int CircularArray<T>::size(){ if(back<front) return capacity-((front-back)-1); else if(front==-1 && back==-1) return 0; else return (back-front)+1; } template<class T> bool CircularArray<T>::is_empty(){ return this->front == -1; } template<class T> bool CircularArray<T>::is_full(){ return next(back)==front; } template<class T> void CircularArray<T>::push_back(T data){ //Tal vez ponga un resize() if(front == -1 && back==-1)//si es vacío front=back=0; else if(is_full()==true) throw("it's full"); else back = next(back); array[back]=data; } template<class T> void CircularArray<T>::push_front(T data){ if(front == -1 && back==-1)//si es vacío front=back=0; else if(is_full()==true) throw("it's full"); else if(front==0 && back!=(capacity-1)){ for(int i=back;i>=front;i--) { array[i + 1] = array[i]; } back=next(back);} else front = prev(front); array[front]=data; } template<class T> T CircularArray<T>::pop_front(){ if(front==back) front = back=-1; else //for (int i = 0; i < size(); i++)array[i]=array[i+1]; front=next(front); } template<class T> T CircularArray<T>::pop_back(){ if(front==back)front = back=-1; else back=prev(back); } template<class T> void CircularArray<T>::insert(T data, int pos){ if(is_full()==false){ for(int i=back;i>=pos;i--){ array[i+1]=array[i]; } back=next(back); array[pos]=data; } else throw("it's full"); } template<class T> void CircularArray<T>::sort(){//SHELL SORT for(int jump=size()/2; jump>0; jump/=2){ for(int i=jump; i<size();i++){ int temp = array[i]; int j; for(j=i;j>=jump && array[j-jump]>temp;j-=jump) array[j]=array[j-jump]; array[j]=temp; } } } template<class T> bool CircularArray<T>::is_sorted(){ bool valor=true; for(int i=0;i<size()-1;i++){ if(array[i]>array[i+1]) valor=false; } return valor; } template<class T> void CircularArray<T>::reverse(){ int j=size()-1; for(int i=0;i<j;i++,j--){ int temp=array[i]; array[i]=array[j]; array[j]=temp; } } template<class T> void CircularArray<T>::clear(){ front=back=-1; }
true
5eb742fed63a2956fd82ace0e4dbc33761a01d19
C++
dcheng289/Class-Projects
/Twitter-Data-Structures/tweet.cpp
UTF-8
1,855
3.609375
4
[]
no_license
#include "tweet.h" #include "heap.h" /*struct Hashtag { string text; int val; Hashtag(string a, int b) : text(a), val(b) {}; bool operator == (Hashtag& other) { return text == other.text; } void operator *=(int other) { val++; } }; struct HashtagComp { bool operator()(Hashtag a, Hashtag b) { return (a.val > b.val); } };*/ Tweet::Tweet() { } // Constructor Tweet::Tweet(User* user, DateTime& time, std::string& text) { user_ = user; userName = user->name(); timeStamp = time; tweetText = text; store_hashTags(tweetText); } DateTime const & Tweet::time() const { return timeStamp; } std::string const & Tweet::text() const { return tweetText; } std::vector<std::string> Tweet::hashTags() const { return hashtags; } bool Tweet::operator<(const Tweet& other) const { return timeStamp < other.time(); } std::ostream& operator<<(std::ostream& os, const Tweet& t) { os << t.time() << " " << t.name() << t.text(); return os; } User* Tweet::user() const { return user_; } std::string const & Tweet::name() const { return userName; } // Member Helper methods // Stores all the hashtags in this tweet into a private member vector void Tweet::store_hashTags(std::string tweet) { capitalize(tweet); std::istringstream ss(tweet); std::string temp; getline(ss, temp, '#'); // Get rid of first hashtag while (!ss.eof()) { getline(ss, temp, ' '); hashtags.push_back(temp); //Hashtag h(temp); //heap_->push(h); getline(ss, temp, '#'); } } // Capitalizes the hashtags so it is case-insensitive std::string Tweet::capitalize(std::string& input) { for (unsigned int i = 0; i < input.size(); i++) { if (isupper(input[i])) { input[i] = tolower(input[i]); } } return input; }
true
d22c3f0bbfafecf0f11a94c5525fac2af6ab3d3a
C++
erikfritas/Hacktoberfest2021
/Recursive Reverse of Linked List.cpp
UTF-8
5,987
3.78125
4
[]
no_license
#include <iostream> #include <list> using namespace std; class node { public: int data; // one pointer to the next node node *next; // parameterized constructor for taking data stored node (int d) { data = d; next = NULL; } }; void InsertAtHead (node * &head, int d) { if (head == NULL) { head = new node (d); // new --> return the address of memory allocated dynamically return; // when you create a new node, next field automatically will be NULL } node *n = new node (d); n->next = head; head = n; } // function to print the linked list void print (node * head) { while (head != NULL) { cout << head->data << " --> "; // update head jab tak NULL na aa jae head = head->next; } cout << "NULL" << endl; } int length(node* head) { int count = 0; while(head != NULL) { count++; head = head -> next; } return count; } void InsertAtTail(node*& head, int data) { // if this function runs without node so handle case if(head == NULL) { head = new node(data); return; } node* tail = head; while(tail -> next != NULL) { tail = tail -> next; } tail -> next = new node(data); return; } void InsertInMiddle (node * &head, int d, int p) { // handle the corner case if (head == NULL || p == 0) { // linked list is not present // simply insert at the head InsertAtHead(head, d); return; } else if(p > length(head)) { InsertAtTail(head, d); } else // insert at middle { // you need to reach the temp node by taking (p-1) jumps int jump = 1; // starting the jump from head node* temp = head; while(jump <= (p-1)) { // temp ke paas next node ka address aa jaega means jump temp = temp -> next; jump++; } // you are standing at node jaha insert karna hai // create a new node node* n = new node(d); // where the value of 4 will come in new node // from the temp node --> value 2 vaali node se n -> next = temp -> next; // value 2 vaali node, pointer uska new node (value 3) // ki position/ address store krega to make a link temp -> next = n; } } void deleteHead(node*& head) { if(head == NULL) { // no element, so just return return; } node* temp = head -> next; delete head; // still head main meh rhega becoz main meh head hai humara head = temp; // temp is local variable, so it will get destroyed after function call } node* take_input(node*&head) { int data; cin >> data; // pass by reference toh no need //node* head = NULL; while(data!= -1) { InsertAtHead(head, data); cin >> data; } return head; } node* take_input2() { // keep a data pointer int data; // you take input and keep on inputting data from user cin >> data; // create a head cz add data in Linked List node* head = NULL; while(data!= -1) { // InsertAtHead(head, data); InsertAtTail(head, data); cin >> data; } return head; } // operator overloading for simple print ostream& operator<< (ostream &os, node* head) { // print the entire linked list print(head); return os; } istream& operator >> (istream &is, node*& head) { // head is equated becoz return type of input is node* head = take_input2(); return is; } void reverse(node*&head) { node* current = head; node* prev = NULL; node* next = NULL; while(current!=NULL) { // store the node data 2 otherwise lost ho jaega if current -> next = prev kiya next = current -> next; // nodes direction are changed current -> next = prev; // now before incrementing the current, store 2 otherwise gyb address prev = current; // for traversal current = next; // or use current = next; // current = next se address lose toh prev zruri // current = current -> next se iterate } // update the head // current is time, NULL par hai head = prev; } node* RecursiveReverse(node* head) { if(head -> next == NULL || head == NULL) { return head; } node* shead = RecursiveReverse(head -> next); node* temp = shead; while(temp -> next != NULL) { temp = temp -> next; } head -> next = NULL; temp -> next = head; // return small head return shead; } node* OptimizeRecursiveReverse(node* head) { if(head -> next == NULL || head == NULL) { return head; } // in recursive case, you need to make a call on smaller part of list // ask recursion to do reverse on smaller part node* shead = RecursiveReverse(head -> next); // it gives you small head // directly pta hai hume node* temp = head -> next; // or head -> next -> next = head head -> next = NULL; temp -> next = head; // return small head return shead; } int main () { // till -1 nhi aa jaata insert in list node* head = NULL; cin >> head; cout << "List is: "; cout << head; head = OptimizeRecursiveReverse(head); cout << "Reverse list: "; cout << head; return 0; } /* OUTPUT 1 2 3 4 5 -1 List is: 1 --> 2 --> 3 --> 4 --> 5 --> NULL Reverse list: 5 --> 4 --> 3 --> 2 --> 1 --> NULL */
true
eb4a97f01715bd68e04b82cf7e034a400aa3c469
C++
SterbenDa/NYOJ-Linda
/STL练习/找球号(一)/Untitled1.cpp
WINDOWS-1252
666
2.96875
3
[]
no_license
#include "cstdio" #include "set" using namespace std; int main(){ int n,m,a,i; set<int> s; scanf("%d%d",&m,&n); for(i=0;i<m;i++) { scanf("%d",&a); s.insert(a); } for(i=0;i<n;i++){ scanf("%d",&a); if(s.count(a)==0) printf("NO\n"); else printf("YES\n"); } s.clear(); return 0; } /*ʱ #include "cstdio" #include "set" using namespace std; int main(){ int n,m,a,i; set<int> s; while(scanf("%d%d",&m,&n)==2){ for(i=0;i<m;i++) { scanf("%d",&a); s.insert(a); } for(i=0;i<n;i++){ scanf("%d",&a); if(s.count(a)==0) printf("NO\n"); else printf("YES\n"); } s.clear(); } return 0; }*/
true