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
065a24f2618d29580a94630c4881f054d488ffb1
C++
adamthecreator369/SudokuSolver_
/SudokuSolver/main.cpp
UTF-8
1,166
3.8125
4
[]
no_license
#include <iostream> #include <fstream> #include <vector> #include "Puzzle.h" int main() { // Open file streams. std::ifstream fin("puzzle.txt"); std::ofstream fout("solutions.txt"); // Check input file. if (!fin) { std::cout << "Error - Nonexistent input file."; return -1; } // Used to store the puzzle board data. std::vector<std::vector<char>> puzzle_board; // Used to store a line of data from the input file. std::string line; // Read in input line by line until EOF. while (fin >> line) { // Used to store a single row of the puzzle board. std::vector<char> row; // Iterate through the line of data. for (char item : line) { // Add each character to the row. row.push_back(item); } // Add the row to the puzzle board. puzzle_board.push_back(row); } // Create the sudoku puzzle object. Puzzle sudoku_puzzle(puzzle_board); // Find and write all possible solutions to the output file, if any. sudoku_puzzle.print_all_solutions(fout); // Successfully exit the program. return 0; }
true
b553558349ff5057a0b9492bd4f7d26a71204b1e
C++
CoziestYew804/Projet_Modelisation
/Erreur.h
UTF-8
1,006
3.296875
3
[]
no_license
/** classe Erreur */ #ifndef ERREUR_H #define ERREUR_H using namespace std; #include <string> #include <iostream> #include <exception> class Erreur : public exception { public: string message; Erreur() : message("Erreur !"){} explicit Erreur (const string &messageErreur) : Erreur() { this->message += " " + messageErreur; } explicit Erreur (const char *messageErreur) : Erreur((string) messageErreur) {} /** * lance une exception si d est vide * */ inline static void testeNonVide(const void *d, const char * message); explicit operator string () const { return this->message; } virtual const char* what() const noexcept {return ((string)(*this)).c_str();} }; inline ostream & operator << (ostream & os, const Erreur & erreur) { return os << (string) erreur; } /** * lance une exception si d est vide * */ inline /*static*/ void Erreur::testeNonVide(const void *d, const char * message) { #ifdef DEBUG if ( !d ) throw Erreur(message); #endif } #endif // ERREUR_H
true
62194a8e033707c5f31e5ececcfdd5e043358d7b
C++
Kirby-Vong/Lab7
/main.cpp
UTF-8
741
2.65625
3
[]
no_license
#include <iostream> #include "factory.h" #include "div.hpp" #include "base.hpp" #include "sub.hpp" #include "add.hpp" #include "rand.hpp" #include "op.hpp" using namespace std; int main(int argv, char** argc) { // char* test_array[6]; //test_array[0] = "./calculator"; test_array[1] = "1"; test_array[2] = "+"; test_array[3] = "2"; test_array[4] = "\**"; test_array[5] = "3"; Factory* f = new Factory(); // Base* test = f->parse(test_array, 6); Base* test = f->parse(argc, argv); if(test == nullptr) { cout << "Error, is nullptr" << endl; } else { cout << "String: " << test->stringify() << endl; cout << "Evaluated string: " << test->evaluate() << endl; } return 0; }
true
245bf3a5168b857ba0d6453bd9cfe53117da3bb6
C++
cedricxie/CarND-Path-Planning-Project
/src/sensor.h
UTF-8
3,328
2.71875
3
[]
no_license
#ifndef ADD_SENSOR_INCLUDED #define ADD_SENSOR_INCLUDED using namespace std; void sensor_processing(vector<vector<double>> sensor_fusion, vector<vector<double>> &sensor_car_list_left, vector<vector<double>> &sensor_car_list_mid, vector<vector<double>> &sensor_car_list_right, double car_s){ //***************************************************// //Analyze Sensor Information //***************************************************// int sensor_list_size = sensor_fusion.size(); //cout << "Total number of cars in sensor list: " << sensor_list_size << endl; for (int i=0; i<sensor_list_size; i++){ //cout << sensor_fusion[i][0] << endl; double sensor_id = sensor_fusion[i][0]; double sensor_vx = sensor_fusion[i][3]; double sensor_vy = sensor_fusion[i][4]; double sensor_s = sensor_fusion[i][5]; double sensor_d = sensor_fusion[i][6]; double sensor_v = sqrt(sensor_vx*sensor_vx+sensor_vy*sensor_vy); if (sensor_d>8.0){ bool flag = true; for(int j=0; j<sensor_car_list_right.size(); j++){ if(sensor_s>sensor_car_list_right[j][1]){ sensor_car_list_right.insert(sensor_car_list_right.begin()+j, {sensor_id, sensor_s, sensor_d, sensor_v}); flag = false; break; } } if (flag==true){sensor_car_list_right.push_back({sensor_id, sensor_s, sensor_d, sensor_v});} } else if(sensor_d>4.0){ bool flag = true; for(int j=0; j<sensor_car_list_mid.size(); j++){ if(sensor_s>sensor_car_list_mid[j][1]){ sensor_car_list_mid.insert(sensor_car_list_mid.begin()+j, {sensor_id, sensor_s, sensor_d, sensor_v}); flag = false; break; } } if (flag==true){sensor_car_list_mid.push_back({sensor_id, sensor_s, sensor_d, sensor_v});} } else{ bool flag = true; for(int j=0; j<sensor_car_list_left.size(); j++){ if(sensor_s>sensor_car_list_left[j][1]){ sensor_car_list_left.insert(sensor_car_list_left.begin()+j, {sensor_id, sensor_s, sensor_d, sensor_v}); flag = false; break; } } if (flag==true){sensor_car_list_left.push_back({sensor_id, sensor_s, sensor_d, sensor_v});} } } if(dflag>=dflag_sensor_details) { cout << setw(25) << "Sensor Info for Right Lane" << endl; for(int i=0; i<sensor_car_list_right.size(); i++){ //for(int j=0; j<4; j++){ cout << sensor_car_list_right[i][j] << " ";} cout << sensor_car_list_right[i][1] - car_s<< " " <<sensor_car_list_right[i][2]<< " " <<sensor_car_list_right[i][3]; cout << endl; } cout << setw(25) << "Sensor Info for Mid Lane" << endl; for(int i=0; i<sensor_car_list_mid.size(); i++){ //for(int j=0; j<4; j++){cout << sensor_car_list_mid[i][j] << " ";} cout << sensor_car_list_mid[i][1] - car_s << " " <<sensor_car_list_mid[i][2]<< " " <<sensor_car_list_mid[i][3]; cout << endl; } cout << setw(25) << "Sensor Info for Left Lane" << endl; for(int i=0; i<sensor_car_list_left.size(); i++){ //for(int j=0; j<4; j++){ cout << sensor_car_list_left[i][j] << " ";} cout << sensor_car_list_left[i][1] - car_s<< " " <<sensor_car_list_left[i][2]<< " " <<sensor_car_list_left[i][3]; cout << endl; }} } #endif // ADD_SENSOR_INCLUDED
true
5419957ebd25b23942f1d8502632b913f5b7d36b
C++
C-Timm/CS_114
/Lab1/MyForm.cpp
UTF-8
1,135
2.640625
3
[]
no_license
#include "MyForm.h" using namespace Lab1; using namespace System; using namespace System::Windows::Forms; [STAThread] void Main(array<String^>^ args) { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); Lab1::MyForm form; Application::Run(%form); } System::Void MyForm::MyForm_Load(System::Object^ sender, System::EventArgs^ e) { g = pictureBox1->CreateGraphics(); bmp = gcnew Bitmap(L"sharkLogo.bmp"); seeImage = false; } //On Off button System::Void MyForm::button1_Click(System::Object^ sender, System::EventArgs^ e) { if (seeImage) { g->Clear(Color::White); } else { g->DrawImage(bmp, 0, 0); } DrawGrid(); seeImage = !seeImage; } //Grid Method void MyForm::DrawGrid() { System::Drawing::Point pt1, pt2; Pen^ pen = gcnew Pen(Color::Teal); int size = 35; int w = pictureBox1->Width; int h = pictureBox1->Height; int x = size; int y = size; while (y < h) { pt1 = Point(0, y); pt2 = Point(w, y); g->DrawLine(pen, pt1, pt2); y += size; } while (x < w) { pt1 = Point(x, 0); pt2 = Point(x, h); g->DrawLine(pen, pt1, pt2); x += size; } }
true
22b30895fbb558357c636f0038bae60819b4921d
C++
quee0849/DesignCPPRepo
/mains/PayFactoryMain.cpp
UTF-8
2,774
2.84375
3
[]
no_license
// // // payfactorymain.cpp // // /* Uses PayOff3.cpp PayOffBridge.cpp PayOffFactory.cpp PayOffRegistration.cpp */ #include <PayOff3.h> #include <PayOffConstructible.h> #include <PayOffBridge.h> #include <PayOffFactory.h> #include <SimpleMC8.h> #include <string> #include <iostream> using namespace std; //for Ex10.3 #include<ParkMiller.h> #include<Vanilla3.h> #include<MCStatistics.h> #include<ConvergenceTable.h> #include<AntiThetic.h> #include "MersTwister.h" int main() { double Expiry=1; //double Low,Up; double Spot=100; double Vol=0.15; double r=0.05; unsigned long NumberOfPaths=100000; double Strike[1]; Strike[0]=50; Strike[1]=200; std::string name; cout << "\npay-off name\n"; cin >> name; // cout << "Enter strike 1\n"; // cin >> Strike[0]; // //cout << "Enter strike 2 (for double barrier for example)\n"; //cin >> Strike[1]; // create an option of type name with give strike(s) from the factory PayOff* PayOffPtr = PayOffFactory::Instance().CreatePayOff(name,Strike); //now convert this payoffptr to a VanillaOption to plug in to SimpleMonteCarlo6 VanillaOption theOption(*PayOffPtr, Expiry); if (PayOffPtr != NULL) { // double Spot=100; //cout << "\nspot\n"; // cin >> Spot; cout << "\n PayOff with Spot " << Spot << " is "<< PayOffPtr->operator ()(Spot) << "\n"; cout << "\n PayOff with Spot " << Spot << " is "<< (*PayOffPtr)(Spot) << "\n"; // these two are the same. ParametersConstant VolParam(Vol); ParametersConstant rParam(r); StatisticsMean gatherer; ConvergenceTable gathererTwo(gatherer); RandomParkMiller generator(1); //RandomMersTwister generator(1); AntiThetic GenTwo(generator); //using the MC routine in SimpleMC8 - the first argument is of type VanillaOption so we have // converted PayOffPtr genearated by the factory to theOption - which is of type VanillaOption // (VanillaOption contains the expirty time as extra information) SimpleMonteCarlo6(theOption, Spot, VolParam, rParam, NumberOfPaths, gathererTwo, generator); // no Antithetic //GenTwo); // Antithetic vector<vector<double> > results =gathererTwo.GetResultsSoFar(); cout <<"\nFor the " << name << " price the results are \n"; for (unsigned long i=0; i < results.size(); i++) { for (unsigned long j=0; j < results[i].size(); j++) cout << results[i][j] << " "; cout << "\n"; } delete PayOffPtr; } double tmp; cin >> tmp; return 0; }
true
6d1bed6dfcc1aee6f607a90bd17e6e80cd60d375
C++
Mehulcoder/Leetcode
/3455.cpp
UTF-8
757
2.75
3
[]
no_license
class Solution { public: Solution() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); } string getHint(string secret, string guess) { unordered_multiset<char> s, s2; for (int i = 0; i < secret.size(); ++i) { s.insert(secret[i]); s2.insert(guess[i]); } int a = 0, b = 0; for (int i = 0; i < min(secret.size(), guess.size()); ++i) { if (secret[i] == guess[i]) { s.erase(s.find(secret[i])); s2.erase(s2.find(guess[i])); a++; } } for (int i = 0; i < guess.size(); ++i) { if (s.find(guess[i]) != s.end() && s2.find(guess[i]) != s2.end()) { b++; s.erase(s.find(guess[i])); s2.erase(s2.find(guess[i])); } } string ans = to_string(a) + "A" + to_string(b) + "B"; return ans; } };
true
d1edd8a64810241ac060f1b5d1ae244d027d2133
C++
cuber2460/acmlib07
/code/kamil/hull_kocium.cpp
UTF-8
2,121
2.59375
3
[]
no_license
// hull online inline TYP operator^(const P& a,const P& b){return real(a)*imag(b)-real(b)*imag(a);} inline TYP skret(const P& a,const P& b,const P& c){return ((c-a)^(b-a));} namespace Hull { P sr; int cw(const P& l) { TYP a = real(l), b = imag(l); if (b >= 0) return a >= 0 ? 1: 2; else return a <= 0 ? 3 : 4; } struct compare { bool operator() (const P& l, const P& r) const { int a = cw(l - sr), b = cw(r - sr); if (a != b) return a < b; TYP d = skret(l, sr, r); return d != 0 ? d > 0 : abs(l - sr) < abs(r - sr); } }; struct comp { bool operator() (const P& a, const P& b){ if(real(a) != real(b)) return real(a)<real(b); if(imag(a) != imag(b)) return imag(a)<imag(b); return false; } }; set<P, compare> hull; set<P, comp> ph; typedef set<P, compare>::iterator HI; void init_hull(vector<P> t) { sr = t[0] + t[1] + t[2]; sr = P(real(sr) / 3, imag(sr) / 3); FORE(it, t) hull.insert(*it); } HI prev(const HI& i) { HI j = i; if (i == hull.begin()) j = hull.end(); return --j; } HI next(const HI& i) { HI j = i; ++j; return j == hull.end() ? hull.begin() : j; } void hull_add(P p) { // Multiply by 3 to get good average inside point p *= 3; if (siz(hull) == 0) { if (siz(ph) >= 2 && skret(*ph.begin(), *ph.rbegin(), p) != 0) { vector<P> t; t.PB(*ph.begin()); t.PB(*ph.rbegin()); t.PB(p); init_hull(t); ph.clear(); } else ph.insert(p); return ; } HI i = hull.lower_bound(p), j, k; if (i == hull.end()) i = hull.begin(); j = prev(i); if (skret(*i, *j, p) >= 0) return; while (siz(hull) >= 3) { j = prev(i); k = prev(j); if (skret(*k, *j, p) >= 0 && skret(*i, *j, p) <= 0) { hull.erase(j); continue; } k = next(i); if (skret(*j, *i, p) >= 0 && skret(*k, *i, p) <= 0) { hull.erase(i); i = k; continue; } break; } hull.insert(p); } vector<P> get_hull() { return vector<P>(ALL(hull)); } }
true
628e92bae044cab095e388256024bf51f863615e
C++
codepongo/poll-windows
/examples/connect-fail.cpp
UTF-8
2,933
2.71875
3
[]
no_license
#include <stdio.h> #include <WinSock2.h> #include "poll.h" // // Taken from: https://curl.haxx.se/mail/lib-2012-07/0311.html // void TestSocketConnection(const char* aIPAddress, USHORT aPortNumber, INT aTimeout) { SOCKET lSOCKET = socket(AF_INET, // 2, // family SOCK_STREAM, // 1, // type IPPROTO_IP // 0 // protocol ); printf("\n" "\n" "lSOCKET is 0x%08X.\n", lSOCKET); unsigned long lFlags = 1; int lReturnValue = ioctlsocket(lSOCKET, FIONBIO, &lFlags); printf("ioctlsocket(FIONBIO, 1) returned %d.\n", lReturnValue); printf("connecting to %s, port %u.\n", aIPAddress, aPortNumber); sockaddr_in lsockaddr_in; lsockaddr_in.sin_family = AF_INET; lsockaddr_in.sin_addr.s_addr = inet_addr(aIPAddress); lsockaddr_in.sin_port = htons(aPortNumber); lReturnValue = connect(lSOCKET, (sockaddr*)&lsockaddr_in, sizeof(lsockaddr_in)); printf("connect() returned %d.\n", lReturnValue); int lWSAError = 0; if (lReturnValue == SOCKET_ERROR) { lWSAError = WSAGetLastError(); printf("WSAGetLastError() returned %d.\n", lWSAError); } if (lWSAError == WSAEWOULDBLOCK) { int lError = 0; int lErrorSize = sizeof(lError); int lPollCount = 0; while (lPollCount == 0 && lError == 0) { WSAPOLLFD lWSAPOLLFD; lWSAPOLLFD.fd = lSOCKET; lWSAPOLLFD.events = POLLWRNORM; lWSAPOLLFD.revents = 0; lPollCount = poll(&lWSAPOLLFD, 1, aTimeout); printf("\n" "WSAPoll(timeout=%dms) returned %d.\n" "lWSAPOLLFD.revents is 0x%02X\n", aTimeout, lPollCount, lWSAPOLLFD.revents); lReturnValue = getsockopt(lSOCKET, SOL_SOCKET, SO_ERROR, (char*)&lError, &lErrorSize); printf("getsockopt() returned %d, lError is %d.\n", lReturnValue, lError); } } lReturnValue = closesocket(lSOCKET); printf("\n" "closesocket() returned %d.\n", lReturnValue); } int main(int aArgumentCount, char* aArgumentValue[]) { printf("Hello, world!\n"); WORD lRequestedVersion = MAKEWORD(2, 2); WSADATA lWSADATA; int lReturnValue = WSAStartup(lRequestedVersion, &lWSADATA); printf("WSAStartup returned %d.\n", lReturnValue); INT lTimeout = -1; if (2 <= aArgumentCount) { lTimeout = atoi(aArgumentValue[1]); } TestSocketConnection("213.180.141.140", 443, lTimeout); TestSocketConnection("213.180.141.140", 8443, lTimeout); lReturnValue = WSACleanup(); printf("\n" "WSACleanup returned %d.\n", lReturnValue); printf("Bye, world!\n"); return 0; }
true
f68875491708b3164974f833349348c29ead2615
C++
MijaelTola/icpc
/pacificNorth18/solutions/LatinSquares/latinsquares_tgr.cpp
UTF-8
868
2.78125
3
[]
no_license
#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std ; int main() { int n ; cin >> n ; vector<string> b(n) ; for (int i=0; i<n; i++) cin >> b[i] ; string base = b[0] ; sort(base.begin(), base.end()) ; int islatin = 1 ; int isreduced = 1 ; if (b[0] != base) isreduced = 0 ; for (int i=0; i<n; i++) { string work = b[i] ; sort(work.begin(), work.end()) ; if (work != base) islatin = 0 ; for (int j=0; j<n; j++) work[j] = b[j][i] ; if (i == 0 && work != base) isreduced = 0 ; sort(work.begin(), work.end()) ; if (work != base) islatin = 0 ; } if (islatin && isreduced) cout << "Reduced" << endl ; else if (islatin) cout << "Not Reduced" << endl ; else cout << "No" << endl ; }
true
51c673e18e8d9ef74f39205258f9e6a5a89daef7
C++
mggavrilov/OOP-FMI-2016
/OOP_project_1_SI_1_2_61937/include/Flat.h
UTF-8
487
2.78125
3
[]
no_license
#ifndef FLAT_H #define FLAT_H #include "Estate.h" class Flat : public Estate { public: Flat(); Flat(string city, string address, string owner, double price, double area, int rooms, int floor); virtual ~Flat(); int getRooms() const; int getFloor() const; void setRooms(int rooms); void setFloor(int floor); void printEstate(); protected: private: int rooms; int floor; }; #endif // FLAT_H
true
8ad44af72ffb970c91895c8b032602d9a2e1b399
C++
vector9x4/cstart
/001_C_프로그램_시작하기.cpp
UTF-8
357
2.734375
3
[]
no_license
#include <stdio.h> int main(void) { printf("Hello Wrold"); } /* C 프로그램은 main 함수에서 시작되어 main 함수로 끝남. 따라서 반드시 하나의 main 함수를 포함해야 한다!! 곧, 다시 말해 main 함수 하나만으로 프로그램을 만들 수 있다! 한 함수의 시작과 끝은 중괄호 {}로 표시한다. */
true
d359b285dc013e1ca8309369eecbc147375aab72
C++
icrelae/cpp_primer
/3-string_vector_array/3.42_vector&array.cpp
UTF-8
379
3.390625
3
[]
no_license
/* 2016.09.18 23:40 * P_112 * copy vector to array */ #include <iostream> #include <vector> int main(int argc, char **argv) { int array[10] = {-1}; std::vector<int> vec = {0, 1, 2, 3, 4, 5}; for (std::vector<int>::size_type i = 0; i < vec.size(); ++ i) { array[i] = vec[i]; } for (int *p = array; p != std::end(array); ++ p) std::cout << *p << ' '; return 0; }
true
3cd065b576eb224bca5fe72e11fb5ec280816330
C++
usernamegenerator/leetcode
/LeetCodeCNExplore/leetcodeCNeasy/math/326isPowerOfThree.cpp
UTF-8
890
3.671875
4
[]
no_license
// https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/25/math/62/ /* 3的幂 给定一个整数,写一个函数来判断它是否是 3 的幂次方。 示例 1: 输入: 27 输出: true 示例 2: 输入: 0 输出: false 示例 3: 输入: 9 输出: true 示例 4: 输入: 45 输出: false 进阶: 你能不使用循环或者递归来完成本题吗? */ class Solution { public: /* bool isPowerOfThree(int n) { if (n == 0) return false; int temp = n; while (temp != 1) { if (temp % 3 != 0) { return false; } temp = temp / 3; } return true; } */ bool isPowerOfThree(int n) { // pow(3, 19) is the max power of three in the integer range return (n > 0 && (((int)pow(3, 19) % n) == 0)); } };
true
5529f9ed48a60110389efefe052ef64d029f03d1
C++
BBekker/teensyclock
/rtctiming.ino
UTF-8
1,230
2.625
3
[ "MIT" ]
permissive
#include <Time.h> #include <TimeLib.h> /////////// // RTC FUNCTIONS ////////// byte bcd2byte(byte bcd) { return (bcd & 0x0F) + ((bcd >> 4) *10); } byte bin2bcd(byte val) { return (val % 10) + ((val / 10) << 4); } //Update the external RTC void updateRTC(unsigned int _year,unsigned int _month,unsigned int _day,unsigned int _hour,unsigned int _min,unsigned int _sec) { Wire.beginTransmission(DS3231_ADDRESS); Wire.write((byte)0); // start at location 0 Wire.write(bin2bcd(_sec)); Wire.write(bin2bcd(_min)); Wire.write(bin2bcd(_hour)); Wire.write(bin2bcd(0)); Wire.write(bin2bcd(_day)); Wire.write(bin2bcd(_month)); Wire.write(bin2bcd(_year - 2000)); Wire.endTransmission(); } //Update the internal clock with the external RTC void updateTime() { Wire.beginTransmission(DS3231_ADDRESS); Wire.write((byte)0); Wire.endTransmission(); Wire.requestFrom(DS3231_ADDRESS, 7); uint8_t ss = bcd2byte(Wire.read() & 0x7F); uint8_t mm = bcd2byte(Wire.read()); uint8_t hh = bcd2byte(Wire.read()); Wire.read(); uint8_t d = bcd2byte(Wire.read()); uint8_t m = bcd2byte(Wire.read()); uint16_t y = bcd2byte(Wire.read()) + 2000; setTime(hh, mm, ss, d, m,y); //Get DS3231 time //setTime( }
true
899e51348ad80998ed7351c258c396623df5e18b
C++
Eng-RSMY/PorousMediaAnalysis
/Core/Headers/StlUtilities.h
UTF-8
12,856
3.171875
3
[ "MIT" ]
permissive
// Copyright (c) 2013 Vasili Baranau // Distributed under the MIT software license // See the accompanying file License.txt or http://opensource.org/licenses/MIT #ifndef Core_Headers_StlUtilities_h #define Core_Headers_StlUtilities_h #include <algorithm> #include <vector> #include "VectorUtilities.h" #include "Types.h" // Provides wrapper methods over stl that accept containers directly and operate over entire containers (e.g., sort the entire container). // In most cases you deal with entire containers, not a subrange of values. namespace Core { #define CONTAINER_VALUE_TYPE(TContainer)typename TContainer::value_type class StlUtilities { public: template<class TContainerSource, class TContainerTarget> static void Copy(const TContainerSource& source, TContainerTarget* target) { std::copy(source.begin(), source.end(), target->begin()); } template<class TContainerSource, class TContainerTarget> static void ResizeAndCopy(const TContainerSource& source, TContainerTarget* target) { target->resize(source.size()); std::copy(source.begin(), source.end(), target->begin()); } template<class TContainerX, class TContainerY> static bool Equals(const TContainerX& x, const TContainerY& y) { return std::equal(x.begin(), x.end(), y.begin()); } template<class TContainer> static size_t FindMinElementPosition(const TContainer& x) { typename TContainer::const_iterator minElementIt = std::min_element(x.begin(), x.end()); return minElementIt - x.begin(); } // Return by value. min is usually searched for in containers with numbers, so it is the easiest usage template<class TContainer> static CONTAINER_VALUE_TYPE(TContainer) FindMinElement(const TContainer& x) { typename TContainer::const_iterator minElementIt = std::min_element(x.begin(), x.end()); return *minElementIt; } template<class TContainer> static size_t FindMaxElementPosition(const TContainer& x) { typename TContainer::const_iterator maxElementIt = std::max_element(x.begin(), x.end()); return maxElementIt - x.begin(); } // Return by value. Maximum is usually searched for in containers with numbers, so it is the easiest usage template<class TContainer> static CONTAINER_VALUE_TYPE(TContainer) FindMaxElement(const TContainer& x) { typename TContainer::const_iterator maxElementIt = std::max_element(x.begin(), x.end()); return *maxElementIt; } template<class TIterator> static bool Contains(TIterator begin, TIterator end, const typename std::iterator_traits<TIterator>::value_type& item) { return std::find(begin, end, item) != end; } template<class TContainer> static bool Contains(const TContainer& vector, const CONTAINER_VALUE_TYPE(TContainer)& item) { return Contains(vector.begin(), vector.end(), item); } template<class TContainerTo, class TContainerValue> static void Append(const TContainerValue& value, TContainerTo* to) { to->insert(to->end(), value.begin(), value.end()); } template<class TContainer> static void Sort(TContainer* vector) { std::sort(vector->begin(), vector->end()); } template<class TContainer, class TComparer> static void Sort(TContainer* vector, TComparer comparer) { std::sort(vector->begin(), vector->end(), comparer); } template<class T> static void SortPermutation(const std::vector<T>& vector, std::vector<int>* permutation) { permutation->resize(std::distance(vector.begin(), vector.end())); VectorUtilities::FillLinearScale(0, permutation); IndexesComparer<T> comparer(vector); StlUtilities::Sort(permutation, comparer); } template<class T> static void Permute(const std::vector<T>& source, const std::vector<int>& permutation, std::vector<T>* target) { size_t length = std::distance(source.begin(), source.end()); std::vector<T>& targetRef = *target; targetRef.resize(length); for (size_t i = 0; i < length; ++i) { targetRef[i] = source[permutation[i]]; } } template<class TContainer> static void SortAndResizeToUnique(TContainer* vector) { std::sort(vector->begin(), vector->end()); typename TContainer::iterator lastElement = std::unique(vector->begin(), vector->end()); vector->resize(std::distance(vector->begin(), lastElement)); } template<class TContainer, class TComparer> static void SortByNthElement(TContainer* vector, std::size_t index, TComparer comparer) { std::nth_element(vector->begin(), vector->begin() + index, vector->end(), comparer); } template<class TContainer> static void SortByNthElement(TContainer* vector, std::size_t index) { std::nth_element(vector->begin(), vector->begin() + index, vector->end()); } template<class T> static void FindNthElementPermutation(const std::vector<T>& vector, std::size_t index, std::vector<int>* permutation) { permutation->resize(std::distance(vector.begin(), vector.end())); VectorUtilities::FillLinearScale(0, permutation); IndexesComparer<T> comparer(vector); StlUtilities::SortByNthElement(permutation, index, comparer); } template<class TContainerX, class TContainerY, class TContainerResult> static void FindSetIntersection(const TContainerX& x, const TContainerY& y, TContainerResult* result) { result->resize(std::max(x.size(), y.size())); typename TContainerResult::iterator intersectionEnd = std::set_intersection(x.begin(), x.end(), y.begin(), y.end(), result->begin()); result->resize(std::distance(result->begin(), intersectionEnd)); } template<class TBaseClass, class TClass> static TClass* FindObject(const std::vector<TBaseClass*>& vector) { FindObjectFunctor<TBaseClass, TClass> findObjectFunctor; typename std::vector<TBaseClass*>::const_iterator objectIterator = std::find_if(vector.begin(), vector.end(), findObjectFunctor); if (objectIterator == vector.end()) { return NULL; } TBaseClass* baseObject = *objectIterator; TClass* object = dynamic_cast<TClass*>(baseObject); return object; } template<class TBaseClass, class TClass> static TClass* RemoveObject(std::vector<TBaseClass*>* vector) { FindObjectFunctor<TBaseClass, TClass> findObjectFunctor; typename std::vector<TBaseClass*>::iterator objectIterator = std::find_if(vector->begin(), vector->end(), findObjectFunctor); if (objectIterator == vector->end()) { return NULL; } TBaseClass* baseObject = *objectIterator; TClass* object = dynamic_cast<TClass*>(baseObject); if (object != NULL) { vector->erase(objectIterator); } return object; } // Quickly remove in O(1): copy the last element to the index of the deleted element, pop the last element. template<class TContainer> static void QuicklyRemoveAt(TContainer* vector, std::size_t index) { TContainer& vectorRef = *vector; vectorRef[index] = vectorRef.back(); vectorRef.pop_back(); } // Quickly remove in O(1): copy the last element to the index of the deleted element, pop the last element. template<class TContainer> static void QuicklyRemove(TContainer* vector, const CONTAINER_VALUE_TYPE(TContainer)& item) { typedef CONTAINER_VALUE_TYPE(TContainer) TItemType; typename TContainer::iterator it = std::find(vector->begin(), vector->end(), item); if (it != vector->end()) { TItemType& itemRef = *it; itemRef = vector->back(); vector->pop_back(); } } template<class TContainer> static void Remove(TContainer* vector, const CONTAINER_VALUE_TYPE(TContainer)& item) { vector->erase(std::remove(vector->begin(), vector->end(), item)); } template<class TContainer> static void RemoveAt(TContainer* vector, int index) { vector->erase(vector->begin() + index); } template<class TContainer> static void Replace(TContainer* vector, const CONTAINER_VALUE_TYPE(TContainer)& oldItem, const CONTAINER_VALUE_TYPE(TContainer)& newItem) { std::replace(vector->begin(), vector->end(), oldItem, newItem); } template<class TContainer> static Nullable<size_t> GetLowerBoundIndex(const TContainer& vector, const CONTAINER_VALUE_TYPE(TContainer)& item) { typename TContainer::const_iterator it = std::lower_bound(vector.begin(), vector.end(), item); Nullable<size_t> result; result.hasValue = (it != vector.end()); if (result.hasValue) { result.value = std::distance(vector.begin(), it); } return result; } template<class TX, class TY, class TGetError> static TX DoBinarySearch(const TX& leftPoint, const TX& rightPoint, const TY& expectedValue, const TY& minAcceptedError, const TX& minStep, TGetError getError) { TX leftPointLocal = leftPoint; TX rightPointLocal = rightPoint; TY error; TX middlePoint = (leftPointLocal + rightPointLocal) * 0.5; TX step; do { TX middlePoint = (leftPointLocal + rightPointLocal) * 0.5; step = rightPointLocal - middlePoint; TY currentValue = getError(middlePoint); if (currentValue > expectedValue) { rightPointLocal = middlePoint; } else { leftPointLocal = middlePoint; } error = std::abs(currentValue - expectedValue); } while ((error > minAcceptedError) && (step > minStep)); return middlePoint; } private: template<class TBaseClass, class TClass, class TIterator> static TClass* FindObject(const std::vector<TBaseClass*>& vector, TIterator* iterator) { FindObjectFunctor<TBaseClass, TClass> findObjectFunctor; TIterator objectIterator = std::find_if(vector.begin(), vector.end(), findObjectFunctor); if (objectIterator == vector.end()) { return NULL; } TBaseClass* baseObject = *objectIterator; TClass* object = dynamic_cast<TClass*>(baseObject); return object; } // Classes private: template<class TBaseClass, class TClassToSearch> class FindObjectFunctor { public: bool operator()(TBaseClass* element) { TClassToSearch* object = dynamic_cast<TClassToSearch*>(element); return (object != NULL); } }; // template<class T> // class IndexesComparer // { // private: // const std::vector<T>* values; // // public: // IndexesComparer(const std::vector<T>& valuesArray) // { // this->values = &valuesArray; // }; // // bool operator()(int i, int j) // { // const std::vector<T>& valuesRef = *values; // return valuesRef[i] < valuesRef[j]; // }; // }; template<class T> class IndexesComparer { private: const std::vector<T>& values; public: IndexesComparer(const std::vector<T>& valuesArray) : values(valuesArray) { }; bool operator()(int i, int j) { return values[i] < values[j]; }; }; }; } #endif /* Core_Headers_StlUtilities_h */
true
050582705766c3b146d3be95e4b8b23e4665f4c5
C++
vadyacj/laba1
/lab8.cpp
UTF-8
4,426
3.25
3
[]
no_license
//Выделить слова из строк и записать их в массив. //Необходимо рассортировать массив слов по их длинам. #include <stdio.h> #include <stdlib.h> #include <malloc.h> void tolower(char* text, int n); void tohigher(char* text, int i); int main() { system("chcp 1251"); system("cls"); int i = 0, j = 0, n, k = 0, t, kk = 0, start = 0, flag = 0, finish = 0; char temp, * mas, * mas2; mas = (char*)calloc(1, sizeof(char)); // создание массивов printf("Введите предложения (в конце строки поставьте точку)\n"); while (1) { scanf_s("%c", &temp); //подготовка символа if (temp == '\n') { break; // выход тут } mas = (char*)realloc(mas, (j + 1) * sizeof(char)); //увеличить массив для ведения переменной mas[j] = temp; //ввод новой переменной j++; //подготовка следующего элемента } if (mas[j - 1] != ' ' || mas[j - 1] != '.') { mas = (char*)realloc(mas, (j + 1) * sizeof(char)); //если в конце не поставили точку, то ставим ее сами mas[j] = '.'; j++; } n = j; //узнаем сколько всего символов mas2 = (char*)malloc(j * sizeof(char)); printf("\n"); for (i = 0; i < n; i++) { if (mas[i] == '.') { mas2[k] = ' '; //заменяем точки на пробелы между слов k++; } else { mas2[k] = mas[i]; k++; } } for (j = 0; j < n; j++) { if (mas2[j] == ' ' && mas2[j + 1] == ' ') { t = j + 1; for (t; t < n; t++) //в этом цикле мы убираем пробелы, если их несколько подряд { mas2[t] = mas2[t + 1]; } n--; } } mas2 = (char*)realloc(mas2, n * sizeof(char)); //сокращаем строку, этим убирая лишние пробелы for (i = 0; i < n; i++) { mas[i] = ' '; //заполняем пробелами весь первый массив, чтобы не ставить пробелы между слов потом } for (j = 0; j < n; j++) { if (mas2[j] == ' ') //считаем кол-во пробелов, чтобы знать кол-во слов flag++; } temp = 0; t = 0; for (k = 0; k < flag; k++) //проходимся столько раз сколько слов в строке { for (j = 0; j < n; j++) { if (mas2[j] == ' ') { if (kk > temp) { start = j - kk; //запоминаем начало,конец и длину слова finish = j; temp = kk; } kk = 0; //обнуляем если пробел есть } else { kk++; //наращиваем длину } } for (start, t; start < finish; start++, t++) { mas[t] = mas2[start]; //переписываем самое длиное слово в пустой массив mas2[start] = ' '; //заменяем его пробелами в другом массиве, чтобы слово не повторялось } t++; //пропускаем символ (типо пробел) temp = 0; //обнуляем максимальную длину слова } mas[n - 1] = '.'; for (i = 0, t = 0; i < n; i++, t++) { mas2[t] = mas[i]; //переписываем все во второй массив по усл } tolower(mas2, n); //нижний регистр tohigher(mas2, 0); printf("Отсортированная строка по убыванию:\n"); for (k = 0; k < n; k++) { printf("%c", mas2[k]); } printf("\n"); free(mas); free(mas2); return 0; } void tolower(char* text, int n) { for (int i = 0; i < n; i++) { if (text[i] >= 'A' && text[i] <= 'Z') //в нижний регистр text[i] += 'z' - 'Z'; if (text[i] >= 'А' && text[i] <= 'Я') text[i] += 'я' - 'Я'; } } void tohigher(char* text, int i) { if (text[i] >= 'a' && text[0] <= 'z') //в верхний регистр text[i] += 'Z' - 'z'; if (text[i] >= 'а' && text[0] <= 'я') text[i] += 'Я' - 'я'; }
true
8c8f339bc3c9878c7937966cb6ff1d6d16bc80a6
C++
MiguelTornero/School
/Programming Fundamentals (C++)/RationalOperation/main.cpp
UTF-8
1,704
3.625
4
[]
no_license
#include <iostream> using namespace std; int iNumerator1, iDenominator1, iNumerator2, iDenominator2; char cOperation; int GCD (int x, int y) { if (y == 0) { return x; } return GCD(y, x%y); } void rationalOperation() { bool bValidCharacter = true; int iResultNumerator, iResultDenominator; switch (cOperation) { case '+': iResultDenominator = iDenominator1 * iDenominator2; iResultNumerator = iNumerator1 * iDenominator2 + iNumerator2 * iDenominator1; break; case '-': iResultDenominator = iDenominator1 * iDenominator2; iResultNumerator = iNumerator1 * iDenominator2 - iNumerator2 * iDenominator1; break; case '*': iResultDenominator = iDenominator1 * iDenominator2; iResultNumerator = iNumerator1 * iNumerator2; break; case '/': iResultDenominator = iDenominator1 * iNumerator2; iResultNumerator = iNumerator1 * iDenominator2; break; default: cout << "Not a valid character"; bValidCharacter = false; } if (bValidCharacter == true) { int iGCD = GCD(iResultDenominator, iResultNumerator); iResultDenominator /= iGCD; iResultNumerator /= iGCD; cout << iNumerator1 << "/" << iDenominator1 << " " << cOperation << " " << iNumerator2 << "/" << iDenominator2 << " = " << iResultNumerator << "/" << iResultDenominator; } } int main() { cin >> iNumerator1 >> iDenominator1 >> iNumerator2 >> iDenominator2 >> cOperation; if (iDenominator1 == 0 || iDenominator2 == 0) { cout << "Cannot divide by 0"; } else { rationalOperation(); } return 0; }
true
b76a73d01b36b54cf856bd083256f9de882a19ff
C++
VorkovN/Mini-Country
/Factory/include/FreightTrain.h
UTF-8
251
2.625
3
[]
no_license
#pragma once #include "CarsTypes.h" #include "City.h" #include "Train.h" class FreightTrain : public Train { public: FreightTrain(CarsTypes::Types cars_type, size_t cars_count); void move(City* city1, City* city2, size_t cars_count) override; };
true
903b37fb56f8873ea8548f7410d4956719a95698
C++
wobuchiroubao/paraCL
/lexer.h
UTF-8
5,640
2.734375
3
[]
no_license
#pragma once #include <cctype> #include <cstdlib> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "types_decl.h" namespace cplr { static const std::map<std::string, node_t> keyW_s = { {"print", node_t::PRINT}, {"if", node_t::IF}, {"else", node_t::ELSE}, {"do", node_t::DO}, {"while", node_t::WHILE}, {"true", node_t::BOOL_TRUE}, {"false", node_t::BOOL_FALSE} }; static const std::map<std::string, unOp_t> unOp_s = { {"!", unOp_t::LOGICAL_NEGATION} }; static const std::map<std::string, binOp_t> binOp_s = { {"=", binOp_t::ASSIGNMENT}, {"||", binOp_t::OR}, {"&&", binOp_t::AND}, {"==", binOp_t::EQUAL}, {"!=", binOp_t::NOT_EQUAL}, {"<", binOp_t::LESS}, {"<=", binOp_t::LESS_OR_EQUAL}, {">=", binOp_t::GREATER_OR_EQUAL}, {">", binOp_t::GREATER}, {"+", binOp_t::ADDITION}, {"-", binOp_t::SUBSTRACTION}, // in lexical analysis all '-' are recognised as binOp... {"*", binOp_t::MULTIPLICATION}, {"/", binOp_t::DIVISION} }; static std::map<std::string, size_t> IDs; class node { public: node(node_t type); virtual ~node(); node_t get_type() const; operator node_t() const; protected: node_t type_; }; class id final : public node { public: id(size_t id); size_t get_id() const; private: size_t id_; }; class intLit final : public node { public: intLit(int int_lit); int get_int() const; private: int int_lit_; }; class unOp final : public node { public: unOp(unOp_t op); unOp(const unOp& other); unOp_t get_op() const; private: unOp_t op_; }; class binOp final : public node { public: binOp(binOp_t op); binOp(const binOp& other); binOp_t get_op() const; private: binOp_t op_; }; class unKnw final : public node { public: unKnw(std::string str); const std::string& get_str() const; private: std::string str_; }; template <typename ForwardIterator> void skip_spaces(ForwardIterator& cur, ForwardIterator end) { while (cur != end && isspace(*cur)) { ++cur; } } template <typename ForwardIterator> std::shared_ptr<node> read_digit_token( ForwardIterator& cur, ForwardIterator end ) { std::string token; while (cur != end && isdigit(*cur)) { token.push_back(*cur); ++cur; } std::shared_ptr<node> ptr; ptr = std::make_shared<intLit>(stoi(token)); return ptr; } template <typename ForwardIterator> std::shared_ptr<node> read_id_keyword_token( ForwardIterator& cur, ForwardIterator end ) { std::string token; while (cur != end && (isalpha(*cur) || isdigit(*cur))) { token.push_back(*cur); ++cur; } std::shared_ptr<node> ptr; auto if_key = keyW_s.find(token); if (if_key != keyW_s.end()) { ptr = std::make_shared<node>(if_key->second); return ptr; } auto if_id = IDs.find(token); if (if_id != IDs.end()) { ptr = std::make_shared<id>(if_id->second); } else { size_t new_id = IDs.size(); IDs[token] = new_id; ptr = std::make_shared<id>(new_id); } return ptr; } bool isauxiliary(char c); template <typename ForwardIterator> std::shared_ptr<node> read_auxiliary_token(ForwardIterator& cur) { char c = *(cur++); std::shared_ptr<node> ptr; if (c == '{') { ptr = std::make_shared<node>(node_t::OPEN_BRACE); } else if (c == '}') { ptr = std::make_shared<node>(node_t::CLOSE_BRACE); } else if (c == '(') { ptr = std::make_shared<node>(node_t::OPEN_PARENTHESIS); } else if (c == ')') { ptr = std::make_shared<node>(node_t::CLOSE_PARENTHESIS); } else if (c == ';') { ptr = std::make_shared<node>(node_t::SEMICOLON); } else if (c == '?') { ptr = std::make_shared<node>(node_t::SCAN); } return ptr; } template <typename ForwardIterator> std::shared_ptr<node> read_op_token( ForwardIterator& cur, ForwardIterator end ) { std::string token; std::shared_ptr<node> ptr; token.push_back(*(cur++)); if (cur != end && ispunct(*cur)) { token.push_back(*cur); auto if_binop = binOp_s.find(token); if (if_binop != binOp_s.end()) { ptr = std::make_shared<binOp>(if_binop->second); ++cur; return ptr; } else { auto if_unop = unOp_s.find(token); if (if_unop != unOp_s.end()) { ptr = std::make_shared<unOp>(if_unop->second); ++cur; return ptr; } else { token.pop_back(); } } } auto if_binop = binOp_s.find(token); if (if_binop != binOp_s.end()) { ptr = std::make_shared<binOp>(if_binop->second); } else { auto if_unop = unOp_s.find(token); if (if_unop != unOp_s.end()) { ptr = std::make_shared<unOp>(if_unop->second); } else { while (cur != end && ispunct(*cur) && !isauxiliary(*cur)) { token.push_back(*(cur++)); } ptr = std::make_shared<unKnw>(token); } } return ptr; } template <typename ForwardIterator> std::shared_ptr<node> read_op_auxiliary_token( ForwardIterator& cur, ForwardIterator end ) { std::shared_ptr<node> ptr; if (isauxiliary(*cur)) { ptr = read_auxiliary_token(cur); } else { ptr = read_op_token(cur, end); } return ptr; } template <typename ForwardIterator> std::vector<std::shared_ptr<node>> tokenize( ForwardIterator begin, ForwardIterator end ) { std::vector<std::shared_ptr<node>> tokens_list; ForwardIterator cur = begin; while (cur != end) { skip_spaces(cur, end); if (isdigit(*cur)) { tokens_list.push_back(read_digit_token(cur, end)); } else if (isalpha(*cur)) { tokens_list.push_back(read_id_keyword_token(cur, end)); } else if (ispunct(*cur)) { tokens_list.push_back(read_op_auxiliary_token(cur, end)); } } return tokens_list; } }
true
14025cc7308484ece421193a24310e035b25d35a
C++
nfinnity/RPNCalculator
/dc.cpp
UTF-8
8,868
3.890625
4
[]
no_license
#include <cstdlib> #include <cctype> #include <iostream> #include <cstring> #include "stack.h" using namespace std; Stack<int> dc(20); /*-------------------------------------------- methodP() Pre: Nothing is printed to the screen. Post: Checks to see if the stack is empty. If it is not, then the value at the top of the stack is taken and printed out to the screen. No changes are made in the stack, and a new line is printed after this function call. */ void methodP() { if(!(dc.isEmpty())) cout << dc.top() << endl; } /*-------------------------------------------- methodN() Pre: Nothing is printed to the screen, and the stack is unaltered. Post: Checks to see if the stack is empty. If it is not, then the value at the top of stack is removed and printed to the screen. A new line is not added after this function call. */ void methodN() { if(!(dc.isEmpty())) cout << dc.topAndPop() << " "; } /*-------------------------------------------- methodF() Pre: Nothing is printed to the screen. Post: Makes a copy of the stack and checks to see if that copy is empty. If it is not, then a loop goes through each entry of the copy and removes and prints each value. The original is left unaltered. */ void methodF() { Stack<int> copy = dc; while (!(copy.isEmpty())) cout << copy.topAndPop() << endl; } /*-------------------------------------------- methodC() Pre: Nothing is printed to the screen. Post: Regardless of whether the stack is empty already or not, a call to the function makeEmpty() in stack.cpp is made to delete all entries. */ void methodC() { dc.makeEmpty(); } /*-------------------------------------------- methodD() Pre: The stack is unaltered and nothing is printed. Post: A duplicate of the current top value of the stack is made and pushed back onto the stack. */ void methodD() { if (!(dc.isEmpty())) dc.push(dc.top()); } /*-------------------------------------------- methodR() Pre: The stack is unaltered and nothing is printed. Post: The top two values of the stack are taken, reversed, and placed back into the stack. */ void methodR() { int top = dc.topAndPop(); int next = dc.topAndPop(); dc.push(top); dc.push(next); } /*-------------------------------------------- Pre: The stack is unaltered and nothing is printed. Post: The top two values in the stack are taken, summed, and the sum is placed back into the stack. */ void addition () { int first = dc.topAndPop(); int second = dc.topAndPop(); int sum = first + second; dc.push(sum); } /*-------------------------------------------- Pre: The stack is unaltered and nothing is printed. Post: The top two values of the stack are taken, and the first one popped is subtracted from the second one popped. The difference is added back onto the stack. */ void subtraction () { int first = dc.topAndPop(); int second = dc.topAndPop(); int difference = second - first; dc.push(difference); } /*-------------------------------------------- Pre: The stack is unaltered and nothing is printed. Post: The top two values of the stack are taken, and the second one popped is divided by the first one popped. The quotient is added back onto the stack. A divide by zero exception is added. */ void division () { int first = dc.topAndPop(); int second = dc.topAndPop(); if (first == 0) cout << "Exception-- CANNOT DIVIDE BY ZERO" << endl; else { int quotient = second/first; dc.push(quotient); } } /*-------------------------------------------- Pre: The stack is unaltered and nothing is printed. Post: The top two values of the stack are taken, the values are multiplied, and the product is then pushed onto the stack. */ void multiplication () { int first = dc.topAndPop(); int second = dc.topAndPop(); int product = first*second; dc.push(product); } /*-------------------------------------------- Pre: The stack is unaltered and nothing is printed. Post: The top two values of the stack are taken and the modulo operation is performed: second%first The remainder is then pushed back onto the stack. A divide by zero exception is also included. */ void modulo () { int first = dc.topAndPop(); int second = dc.topAndPop(); if (first == 0) cout << "Exception-- CANNOT DIVIDE BY ZERO" << endl; else { int result = second%first; dc.push(result); } } /*-------------------------------------------- Pre: The stack is unaltered and nothing is printed. Post: All of the values in the stack are removed and summed. The result is then pushed onto the stack. */ void methodT () { int sum = dc.topAndPop(); while (!(dc.isEmpty())) { int next = dc.topAndPop(); sum += next; } dc.push(sum); } /*-------------------------------------------- Pre: The stack is unaltered and nothing is printed. Post: All of the values in the stack are removed and multiplied together. The product is then pushed onto the stack. */ void methodM () { int product = dc.topAndPop(); while (!(dc.isEmpty())) { int next = dc.topAndPop(); product = product*next; } dc.push(product); } /*-------------------------------------------- Pre: A string from the user input is sent in. Post: The string is parsed through, separating digits, operators, negative symbol, and character commands. Whenever an operator, command, or negative symbol is encountered, the current value in string "number" is converted to an integer and pushed to the stack (if it is not empty). The appropriate function calls are made for each entry. If there is an invalid entry, then a "not valid entry" exception is called. */ void parseString(string input) { string number = ""; for (int i = 0; i < input.length(); i++) { char check = input.at(i); //Enters this branch if it is a lowercase letter. if (islower(check)) { if (number != "") { int pushValue = atoi(number.c_str()); dc.push(pushValue); number = ""; } switch (check) { case 'p' : { methodP(); break; } case 'n' : { methodN(); break; } case 'f' : { methodF(); break; } case 'c' : { methodC(); break; } case 'd' : { methodD(); break; } case 'r' : { methodR(); break; } case 'm' : { methodM(); break; } case 't' : { methodT(); break; } //This called when the letter entered does not match a command. default : cout << "Exception-- INVALID EXPRESSION, PLEASE RE-ENTER" << endl; } } //Checks to see if the ASCII value is equal to 43 (+). else if(int(check) == 43) { if (number != "") { int pushValue = atoi(number.c_str()); dc.push(pushValue); } addition(); number = ""; } //Checks to see if the ASCII value is equal to 45 (-). else if(int(check) == 45) { if (number != "") { int pushValue = atoi(number.c_str()); dc.push(pushValue); } subtraction(); number = ""; } //Checks to see if the ASCII value is equal to 42 (*). else if(int(check) == 42) { if (number != "") { int pushValue = atoi(number.c_str()); dc.push(pushValue); } multiplication(); number = ""; } //Checks to see if the ASCII value is equal to 47 (/). else if(int(check) == 47) { if (number != "") { int pushValue = atoi(number.c_str()); dc.push(pushValue); } division(); number = ""; } //Checks to see if the ASCII value is equal to 37 (%). else if(int(check) == 37) { if (number != "") { int pushValue = atoi(number.c_str()); dc.push(pushValue); } modulo(); number = ""; } //Checks to see if the ASCII value is equal to 95 (_). else if (int(check) == 95) { if (number != "") { int pushValue = atoi(number.c_str()); dc.push(pushValue); } number = "-"; } //Checks to see if the entry is a digit. //If it is, it is appended to the number string. else if(isdigit(check)) { number += check; } else if (isblank(check)) {} } //This is to cover the possibility that the last thing //entered into the string is an number. if (number != "") { int pushValue = atoi(number.c_str()); dc.push(pushValue); } } //Main is simply a while that takes user input, //makes a call to parse the string, and continues this //until the end of file is reached on standard input. int main() { while(1) { string input; cin >> input; parseString(input); } }
true
5f1cba4e8ffc4d43850ffed6c504dc9aa3fce100
C++
larrydalaw/IntelligentHome
/src/starencryption.h
UTF-8
845
2.890625
3
[]
no_license
#ifndef STARENCRYPTION_H #define STARENCRYPTION_H #include <QString> class StarEncryption { public: StarEncryption(); ~StarEncryption(); QString stringEncrypt(const QString &content, QString key);//加密任意字符串,中文请使用utf-8编码 QString stringUncrypt(const QString &content_hex, QString key);//解密加密后的字符串 private: char numToStr(int num);//将数字按一定的规律换算成字母 QByteArray strZoarium(const QByteArray &str);//按一定的规律加密字符串(只包含数字和字母的字符串) QByteArray unStrZoarium(const QByteArray &str);//按一定的规律解密字符串(只包含数字和字母的字符串) QByteArray fillContent(const QByteArray &str, int length);//将字符串填充到一定的长度 }; #endif // STARENCRYPTION_H
true
87dc83f31ef4a70355867bbaf88738f7a50e4328
C++
Bluscream/TS3PatchExtensions
/versionSpoofer/QtConfig.cpp
UTF-8
2,723
2.65625
3
[]
no_license
#include "QtConfig.h" #include "config.h" int getIndex(vector<pair<string, string>> vec, string value) { for (int i = 0; i < vec.size(); i++) { pair<string, string> pair = vec[i]; if (pair.first == value || pair.second == value) return i; } return 0; } QtConfig::QtConfig(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); Qt::WindowFlags flags = this->windowFlags(); this->setWindowFlags(flags &~ Qt::WindowMinMaxButtonsHint); this->setMinimumSize(this->size()); this->setMaximumSize(this->size()); updateCombos(); if (!config->foundCSV) { QMessageBox* notifyUserDialog = new QMessageBox(QMessageBox::Icon::Warning, "Missing CSV File", ("Missing File: " + config->directory + config->csvName + ". Download it from <a href='" + config->csvUrl + "'>here</a> or press the update button.").c_str(), QMessageBox::NoButton, parent); notifyUserDialog->setWindowIcon(QIcon()); notifyUserDialog->setAttribute(Qt::WA_DeleteOnClose); notifyUserDialog->show(); } } QtConfig::~QtConfig() { } void QtConfig::updateCombos() { ui.OSComboBox->clear(); ui.versionComboBox->clear(); for (auto os : config->OSList) ui.OSComboBox->addItem(QString(os.c_str())); //No need to add versions to other combo as the updateVersionCombo action gets triggered by the currentIndexChanged event here ui.OSComboBox->setCurrentIndex(std::find(config->OSList.begin(), config->OSList.end(), config->OS) - config->OSList.begin()); ui.versionComboBox->setCurrentIndex(getIndex(config->versionList[config->OS], config->version)); ui.customVersionBox->setChecked(config->useCustomOSVersion); ui.customOSLine->setText(QString::fromStdString(config->customOS)); ui.customVersionLine->setText(QString::fromStdString(config->customVersion)); } void QtConfig::updateVersionCombo(QString newOS) { vector<pair<string, string>> versions = config->versionList[newOS.toStdString().c_str()]; ui.versionComboBox->clear(); for (auto versionPair : versions) ui.versionComboBox->addItem(QString(versionPair.first.c_str())); } void QtConfig::saveToConfig() { config->useCustomOSVersion = ui.customVersionBox->isChecked(); if (!ui.customOSLine->text().isEmpty()) config->customOS = ui.customOSLine->text().toStdString(); if (!ui.customVersionLine->text().isEmpty()) config->customVersion = ui.customVersionLine->text().toStdString(); string OS = config->OSList[ui.OSComboBox->currentIndex()]; config->OS = OS; pair<string, string> versionPair = config->versionList[OS][ui.versionComboBox->currentIndex()]; config->version = versionPair.first; config->versionHash = versionPair.second; config->writeConfig(); } void QtConfig::updateCSV() { config->getCSV(); config->readCSV(); updateCombos(); }
true
ab6134e8f400598e9a34a81e8c35237a9cdb7a5b
C++
Creativeguru97/YoneLab
/PandaIslandIcedTea/heartrateSensorToArduino/heartrateSensorToArduino.ino
UTF-8
1,686
2.578125
3
[]
no_license
int pin = A0; unsigned char counter; unsigned long beatTimes[21]; unsigned long sub; unsigned int heart_rate = 0; unsigned int prev_heart_rate = 0; bool data_isValid = true; const int max_heartpulse_duty = 2500; void setup() { pinMode(pin, INPUT); // pinMode(start,INPUT_PULLUP); Serial.begin(115200); attachInterrupt(pin, interrupt, RISING); Serial.println("Done preparation"); } void loop() { if (heart_rate != prev_heart_rate) { prev_heart_rate = heart_rate; Serial.print("Heart Rate: "); Serial.println(heart_rate); } } void sum(){ if(data_isValid){ heart_rate = 1200000/(beatTimes[20] - beatTimes[0]); // Serial.print("Heart_rate_is:\t"); // Serial.println(heart_rate); } data_isValid = 1; } void interrupt(){ Serial.println("Looping"); beatTimes[counter] = millis(); // Serial.print("Heart_beat_time:\t"); // Serial.println(temp[counter]); if(counter == 0){ sub = beatTimes[counter] - beatTimes[20]; }else{ sub = beatTimes[counter] - beatTimes[counter - 1]; } Serial.print("Heart_beat_duration_time:\t"); Serial.println(sub); //If the pulse hasn't came in more than 2 secounds, initialize //the beatTimes and start measure again. if (sub > max_heartpulse_duty) { data_isValid = 0; //sign bit counter = 0; Serial.println("Heart rate measure error,test will restart!" ); initializeBeats(); } if(data_isValid){ if(counter == 20){ counter = 0; sum(); }else{ counter++; } }else{ counter = 0; data_isValid = 1; } } void initializeBeats(){ for(int i = 0; i < 20; i++) { beatTimes[i] = 0; } beatTimes[20] = millis(); }
true
2db40203caf9a88f260a51145aa217971fbdd39e
C++
nickjfree/renderer
/Engine/Rendering/RenderPassShadowMap.h
UTF-8
2,170
2.59375
3
[]
no_license
#ifndef __RENDER_PASS_SHADOWMAP__ #define __RENDER_PASS_SHADOWMAP__ /* * do shadow map rendering. */ auto AddShadowMapPass(FrameGraph& frameGraph, RenderContext* renderContext) { constexpr auto max_shadow_maps = 8; typedef struct PassData { // shadow maps RenderResource shadowMaps[8]; }PassData; auto renderInterface = renderContext->GetRenderInterface(); auto shadowMapPass = frameGraph.AddRenderPass<PassData>("shadowmap", [=](GraphBuilder& builder, PassData& passData) { // create all the shaow maps R_TEXTURE2D_DESC desc = {}; desc.Width = renderContext->FrameWidth; desc.Height = renderContext->FrameHeight; desc.ArraySize = 1; desc.CPUAccess = (R_CPU_ACCESS)0; desc.BindFlag = (R_BIND_FLAG)(BIND_DEPTH_STENCIL | BIND_SHADER_RESOURCE); desc.MipLevels = 1; desc.Usage = DEFAULT; desc.SampleDesc.Count = 1; desc.Format = FORMAT_R32_TYPELESS; desc.DebugName = L"shadowmap"; for (auto i = 0; i < max_shadow_maps; ++i) { passData.shadowMaps[i] = builder.Create("shadowmap", [=]() mutable { return renderInterface->CreateTexture2D(&desc); }); } }, [=](PassData& passData, CommandBuffer* cmdBuffer, RenderingCamera* cam, Spatial* spatial) { static Vector<Node*> lights; lights.Reset(); spatial->Query(cam->GetFrustum(), lights, Node::LIGHT); auto index = 0; for (auto iter = lights.Begin(); iter != lights.End(); iter++, index++) { auto light = (RenderLight*)(*iter); auto shadowMap = passData.shadowMaps[index].GetActualResource(); light->SetShadowMap(shadowMap); // set lights's depth buffer cmdBuffer->RenderTargets(nullptr, 0, shadowMap, false, true, renderContext->FrameWidth, renderContext->FrameHeight); auto lightCam = light->GetLightCamera(); // render in light's view static Vector<Node*> occluders; occluders.Reset(); spatial->Query(lightCam->GetFrustum(), occluders, Node::RENDEROBJECT); for (auto iter = occluders.Begin(); iter != occluders.End(); iter++) { auto occluder = (*iter); occluder->Render(cmdBuffer, R_STAGE_SHADOW, 0, lightCam, renderContext); } } }); return shadowMapPass; } #endif
true
6d8b6871ad97843f345dedce0d1d0dd296665470
C++
bstatcomp/math
/stan/math/prim/err/check_cholesky_factor_corr.hpp
UTF-8
1,704
2.859375
3
[ "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef STAN_MATH_PRIM_ERR_CHECK_CHOLESKY_FACTOR_CORR_HPP #define STAN_MATH_PRIM_ERR_CHECK_CHOLESKY_FACTOR_CORR_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/err/check_positive.hpp> #include <stan/math/prim/err/check_lower_triangular.hpp> #include <stan/math/prim/err/check_square.hpp> #include <stan/math/prim/err/check_unit_vector.hpp> namespace stan { namespace math { /** * Check if the specified matrix is a valid Cholesky factor of a * correlation matrix. * A Cholesky factor is a lower triangular matrix whose diagonal * elements are all positive. Note that Cholesky factors need not * be square, but require at least as many rows M as columns N * (i.e., M &gt;= N). * Tolerance is specified by <code>math::CONSTRAINT_TOLERANCE</code>. * @tparam T_y Type of elements of Cholesky factor * @param function Function name (for error messages) * @param name Variable name (for error messages) * @param y Matrix to test * @throw <code>std::domain_error</code> if y is not a valid Cholesky * factor, if number of rows is less than the number of columns, * if there are 0 columns, or if any element in matrix is NaN */ template <typename T_y> void check_cholesky_factor_corr( const char* function, const char* name, const Eigen::Matrix<T_y, Eigen::Dynamic, Eigen::Dynamic>& y) { check_square(function, name, y); check_lower_triangular(function, name, y); check_positive(function, name, y.diagonal()); for (int i = 0; i < y.rows(); ++i) { Eigen::Matrix<T_y, Eigen::Dynamic, 1> y_i = y.row(i).transpose(); check_unit_vector(function, name, y_i); } } } // namespace math } // namespace stan #endif
true
fdca4b8704e5c898139f6f3b0d6f9563fed29eed
C++
Stan994265/PCL-ICP-NDT
/pcl_ndt.cpp
UTF-8
5,648
2.546875
3
[]
no_license
#include <iostream> #include <string> #include <pcl/io/pcd_io.h> #include <pcl/io/ply_io.h> #include <pcl/point_types.h> #include <pcl/registration/ndt.h> #include <pcl/filters/approximate_voxel_grid.h> #include <pcl/visualization/pcl_visualizer.h> #include <boost/thread/thread.hpp> #include <pcl/console/time.h> typedef pcl::PointXYZ PointT; typedef pcl::PointCloud<PointT> PointCloudT; int main(int argc, char** argv) { //加载房间的第一次扫描 pcl::console::TicToc time; //申明时间记录 time.tic (); //time.tic开始 time.toc结束时间 pcl::PointCloud<pcl::PointXYZ>::Ptr target_cloud(new pcl::PointCloud<pcl::PointXYZ>); if (pcl::io::loadPCDFile<pcl::PointXYZ>("../data/0.pcd", *target_cloud) == -1) { PCL_ERROR("Couldn't read file 0.pcd \n"); return (-1); } std::cout << "Loaded " << target_cloud->size() << " data points from 0.pcd" << std::endl; //加载从新视角得到的房间的第二次扫描 pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud(new pcl::PointCloud<pcl::PointXYZ>); if (pcl::io::loadPCDFile<pcl::PointXYZ>("../data/1.pcd", *input_cloud) == -1) { PCL_ERROR("Couldn't read file 1.pcd \n"); return (-1); } std::cout << "Loaded " << input_cloud->size() << " data points from 1.pcd" << std::endl; //将输入的扫描过滤到原始尺寸的大概x0%以提高匹配的速度。 pcl::PointCloud<pcl::PointXYZ>::Ptr filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::ApproximateVoxelGrid<pcl::PointXYZ> approximate_voxel_filter; approximate_voxel_filter.setLeafSize(0.2, 0.2, 0.2); approximate_voxel_filter.setInputCloud(input_cloud); approximate_voxel_filter.filter(*filtered_cloud); std::cout << "Filtered cloud contains " << filtered_cloud->size() << " data points from 1.pcd" << std::endl; //初始化正态分布变换(NDT) pcl::NormalDistributionsTransform<pcl::PointXYZ, pcl::PointXYZ> ndt; //设置依赖尺度NDT参数 //为终止条件设置最小转换差异 ndt.setTransformationEpsilon(0.0001); //为More-Thuente线搜索设置最大步长 ndt.setStepSize(0.1); //设置NDT网格结构的分辨率(VoxelGridCovariance) ndt.setResolution(0.5); //设置匹配迭代的最大次数 ndt.setMaximumIterations(50); // 设置要配准的点云 ndt.setInputSource(input_cloud); //设置点云配准目标 ndt.setInputTarget(target_cloud); //计算需要的刚体变换以便将输入的点云匹配到目标点云 pcl::PointCloud<pcl::PointXYZ>::Ptr output_cloud(new pcl::PointCloud<pcl::PointXYZ>); ndt.align(*output_cloud); std::cout << "Normal Distributions Transform has converged:" << ndt.hasConverged() << " score: " << ndt.getFitnessScore() << std::endl; //使用创建的变换对未过滤的输入点云进行变换 pcl::transformPointCloud(*input_cloud, *output_cloud, ndt.getFinalTransformation()); cout<<ndt.getFinalTransformation()<<endl; time.toc (); //时间 cout<<"\n"<<time.toc ()<<endl; pcl::visualization::PCLVisualizer viewer ("NDT demo"); // 创建两个观察视点 int v1 (0); int v2 (1); viewer.createViewPort (0.0, 0.0, 0.5, 1.0, v1); viewer.createViewPort (0.5, 0.0, 1.0, 1.0, v2); // 定义显示的颜色信息 float bckgr_gray_level = 0.0; // Black float txt_gray_lvl = 1.0 - bckgr_gray_level; // 原始的点云设置为白色的 pcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_in_color_h (target_cloud, (int) 255 * txt_gray_lvl, (int) 255 * txt_gray_lvl, (int) 255 * txt_gray_lvl); viewer.addPointCloud (target_cloud, cloud_in_color_h, "cloud_in_v1", v1);//设置原始的点云都是显示为白色 viewer.addPointCloud (target_cloud, cloud_in_color_h, "cloud_in_v2", v2); // 转换后的点云显示为绿色 pcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_tr_color_h (input_cloud, 0, 255, 0); viewer.addPointCloud (input_cloud, cloud_tr_color_h, "cloud_tr_v1", v1); // ICP配准后的点云为红色 pcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_ndt_color_h (output_cloud, 255, 0, 0); viewer.addPointCloud (output_cloud, cloud_ndt_color_h, "cloud_ndt_v2", v2); //viewer.addCoordinateSystem (1.0); // 加入文本的描述在各自的视口界面 //在指定视口viewport=v1添加字符串“white 。。。”其中"icp_info_1"是添加字符串的ID标志,(10,15)为坐标16为字符大小 后面分别是RGB值 viewer.addText ("White: Original point cloud\nGreen: Matrix transformed point cloud", 10, 15, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "NDT_info_1", v1); viewer.addText ("White: Original point cloud\nRed: NDT aligned point cloud", 10, 15, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "NDT_info_2", v2); // viewer.addText (iterations_cnt, 10, 60, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "iterations_cnt", v2); // 设置背景颜色 viewer.setBackgroundColor (bckgr_gray_level, bckgr_gray_level, bckgr_gray_level, v1); viewer.setBackgroundColor (bckgr_gray_level, bckgr_gray_level, bckgr_gray_level, v2); // 设置相机的坐标和方向 viewer.setCameraPosition (-3.68332, 2.94092, 5.71266, 0.289847, 0.921947, -0.256907, 0); viewer.setSize (1280, 1024); // 可视化窗口的大小 while (!viewer.wasStopped()) { viewer.spinOnce(100); boost::this_thread::sleep(boost::posix_time::microseconds(100000)); } return (0); }
true
336f28751a43b59c213b84e02cecb0a323cca294
C++
mir-mirsodikov/An-Introduction-to-Programming-with-CPP
/chap 7/Chapter 7 Test - Question 1/Chapter 7 Test - Question 1/Source.cpp
UTF-8
206
2.828125
3
[]
no_license
//Mukhammad Mirsodikov - P2 #include <iostream> using namespace std; int main() { int num = 5; while (num <= 100) { cout << num << " "; num += 5; } cout << endl; system("pause"); return 0; }
true
5ba8243c69aa86b7437aeaaa8e2c48800d74cc98
C++
agapow/mesa-revenant
/src/TabDataReader.cpp
UTF-8
14,245
2.828125
3
[]
no_license
/** @file @author Paul-Michael Agapow Dept. Biology, University College London, WC1E 6BT, UK. <mail://p.agapow@ic.ac.uk> <http://www.agapow.net/code/sibil/> Part of MeSA <mail://mesa@agapow.net> <http://www.agapow.net/software/mesa/>. */ // *** INCLUDES #include "TabDataReader.h" #include "StreamScanner.h" #include "StringUtils.h" #include "MesaTypes.h" #include <iterator> using std::stringstream; using std::count; using std::string; using std::back_insert_iterator; using sbl::isFloat; using sbl::isWhole; using sbl::FormatError; using sbl::split; using sbl::beginsWith; // *** CONSTANTS & DEFINES // *** DEFINITIONS *******************************************************/ // *** LIFECYCLE *********************************************************/ // *** SERVICES **********************************************************/ /** Imports a tab-delimited file into the existing data. This functions produces a matrix of the input, strips and the row and column names and then splits the matrix into continuous and discrete components. Assume imported data is rows of species names followed by tab seperated data. Alll columns must be the same length. Parsing stops at the first blank line. */ void TabDataReader::read () { // configure scanner sbl::StreamScanner theScanner (mInStream); theScanner.SetComments ("", ""); theScanner.SetLineComment ("#"); // just check this is a a tab delimited file string theInLine; theScanner.ReadLine (theInLine); theScanner.Rewind(); // roll back to beginning if (count (theInLine.begin(), theInLine.end(), '\t') < 1) throw FormatError ("this isn't a tab-delimited file"); // now we can actually read the file // while the eof has not been reached while (theScanner) { string theCurrLine; theScanner.ReadLine (theCurrLine); sbl::eraseTrailingSpace (theCurrLine); // stop at blank lines. if (theCurrLine == "") break; // otherwise break into tokens stringvec_t theDataRow; back_insert_iterator<stringvec_t> theSplitIter (theDataRow); split (theCurrLine, theSplitIter, '\t'); // clean up the tokens for (stringvec_t::size_type i = 0; i < theDataRow.size(); i++) { sbl::eraseFlankingSpace (theDataRow[i]); } // pop the row into the matrix mDataMatrix.push_back (theDataRow); } // clean up & check correctness of data ... // 1. matrix contains data // 2. species names and at least 1 column of data given // 3. all rows the same length // 4. no null entries if (mDataMatrix.size() == 0) throw FormatError ("imported data matrix is empty"); if (mDataMatrix[0].size() < 2) throw FormatError ("imported data missing species names or data"); // set the correct type of data extractColNames (); extractRowNames(); extractFormat (); // report progress int theNumTaxa = mDataMatrix.size(); int theNumContTraits = mContColNames.size(); int theNumDiscTraits = mDiscColNames.size(); bool theSingleRow = (theNumTaxa == 1); stringstream theBuffer; theBuffer << "There " << (theSingleRow ? "is" : "are") << " " << theNumTaxa << " " << (theSingleRow ? "taxon" : "taxa") << " with " << theNumContTraits << " continuous " << ((theNumContTraits == 1)? "trait": "traits") << " and " << theNumDiscTraits << " discrete " << ((theNumDiscTraits == 1)? "trait": "traits") << " in the import data."; string theTmpString = theBuffer.str(); mProgressCb (kMsg_Progress, theTmpString.c_str()); } void TabDataReader::getData (DiscTraitMatrix& ioWrangler) { // two choices: there's stuff in the wrangler already or not int theNumOldTraits = ioWrangler.countChars(); int theNumNewTraits = mDiscColNames.size(); int theTotalNumTraits = theNumOldTraits + theNumNewTraits; int theNumOldTaxa = ioWrangler.countTaxa(); int theNumNewTaxa = 0; // calc later int theTotalNumTaxa = 0; // calc later // if there's none of the given datatype, get out of here if (theNumNewTraits == 0) return; // see what rows have to be added, assume all columns have to be added stringvec_t theNewRows; for (uint i = 0; i < mRowNames.size(); i++) { if (not ioWrangler.hasRowName (mRowNames[i].c_str())) theNewRows.push_back (mRowNames[i]); } theNumNewTaxa = theNewRows.size(); theTotalNumTaxa = theNumOldTaxa + theNumNewTaxa; // expand wrangler to fit new data, name new rows & cols ioWrangler.resize (theTotalNumTaxa, theTotalNumTraits); for (int i = 0; i < theNumNewTaxa; i++) { ioWrangler.setRowName (theNumOldTaxa + i, mRowNames[i].c_str()); } for (int i = 0; i < theNumNewTraits; i++) { if (mDiscColNames[i] == "") ioWrangler.setColName (theNumOldTraits + i, mDiscColNames[i].c_str()); } // stuff things into the the wrangler for (int i = 0 ; i < theNumNewTraits; i++) { for (uint j = 0; j < mDiscDataMatrix.size(); j++) { ioWrangler.getData (mRowNames[j].c_str(), theNumOldTraits + i) = mDiscDataMatrix[j][i]; } } } void TabDataReader::getData (ContTraitMatrix& ioWrangler) { // two choices: there's stuff in the wrangler already or not uint theNumOldTraits = ioWrangler.countChars(); uint theNumNewTraits = mContColNames.size(); uint theTotalNumTraits = theNumOldTraits + theNumNewTraits; uint theNumOldTaxa = ioWrangler.countTaxa(); uint theNumNewTaxa = 0; // calc later uint theTotalNumTaxa = 0; // calc later // if there's none of the given datatype, get out of here if (theNumNewTraits == 0) return; // see what rows have to be added, assume all columns have to be added stringvec_t theNewRows; for (uint i = 0; i < mRowNames.size(); i++) { if (not ioWrangler.hasRowName (mRowNames[i].c_str())) theNewRows.push_back (mRowNames[i]); } theNumNewTaxa = theNewRows.size(); theTotalNumTaxa = theNumOldTaxa + theNumNewTaxa; // expand wrangler to fit new data, name new rows & cols ioWrangler.resize (theTotalNumTaxa, theTotalNumTraits, 0); for (uint i = 0; i < theNumNewTaxa; i++) { // DBG_MSG (theNumOldTaxa << " " << i << " " << ioWrangler.countRows() << " " << mRowNames[i].c_str()); assert ((theNumOldTaxa + i) < ioWrangler.countRows()); ioWrangler.setRowName (theNumOldTaxa + i, mRowNames[i].c_str()); } for (uint i = 0; i < theNumNewTraits; i++) { assert ((theNumOldTraits + i) < ioWrangler.countCols()); if (mContColNames[i] != "") ioWrangler.setColName (theNumOldTraits + i, mContColNames[i].c_str()); } // stuff things into the the wrangler for (uint i = 0 ; i < theNumNewTraits; i++) { for (uint j = 0; j < mContDataMatrix.size(); j++) { ioWrangler.getData (mRowNames[j].c_str(), theNumOldTraits + i) = sbl::toDouble (mContDataMatrix[j][i]); } } } void TabDataReader::orderRows (stringvec_t& ioNames) //: sort the rows into the same order as these names { // Preconditions: assert (mRowNames.size() == mDataMatrix.size()); // check there is data for all taxa, & order data stringvec_t::size_type theNumTaxa = ioNames.size(); for (stringvec_t::size_type i = 0; i < theNumTaxa; i++) { // get original taxa name string theTaxaName = ioNames[i]; // look in data matrix stringmatrix_t::size_type j; for (j = 0; j < mDataMatrix.size(); j++) { if (theTaxaName == mRowNames[j]) break; } if (j == mDataMatrix.size()) // if the taxa name couldn't be found in the matrix { string theErrMsg ("couldn't find taxon \'"); theErrMsg += theTaxaName.c_str(); theErrMsg += "\' in the imported data matrix"; throw FormatError (theErrMsg.c_str()); } else // if it could found, strip the name off the data and stuff // it in a new data matrix, delete the old row. { //stringvec_t theDenamedRow (mDataMatrix[j].begin() + 1, // mDataMatrix[j].end()); //iFilteredData.push_back (theDenamedRow); //mDataMatrix.erase (mDataMatrix.begin() + j); swap (mRowNames[i], mRowNames[j]); swap (mDataMatrix[i], mDataMatrix[j]); } } } // *** UTILITY FUNCTIONS **************************************************/ /** Detect the format of the data read in and sort it appropriately. Note that we assume that column and row names have been stripped off already and that each column has the same sort of data. Columns that contain 1 or more floating point and 0 or more integer values are assumed to be continuous data. Columns that are entirely alphanumeric or integer are assumed to be discrete. Everything else is an error. */ void TabDataReader::extractFormat () //: detects the format of the data read in { uint theNumCols = mDataMatrix[0].size(); uint theNumRows = mDataMatrix.size(); // check that all rows have the same number of columns for (uint i = 0; i < mDataMatrix.size(); i++) { if (mDataMatrix[i].size() != theNumCols) throw FormatError ("imported data matrix has rows of unequal length"); } // for each column, establish what sort of data can be found there mColumnTypes.clear(); for (uint i = 0; i < theNumCols; i++) { traittype_t theOverallType; // test column name for clues string theColName = mColNames[i]; sbl::toLower (theColName); if (beginsWith (theColName, "site_")) { theOverallType = kTraittype_Continuous; } else if (beginsWith (theColName, "rich_")) { theOverallType = kTraittype_Continuous; } else if (beginsWith (theColName, "cont_")) { theOverallType = kTraittype_Continuous; } else if (beginsWith (theColName, "disc_")) { theOverallType = kTraittype_Discrete; } else { int theCountFloats, theCountInts, theCountAlpha, theCountOther; theCountFloats = theCountInts = theCountAlpha = theCountOther = 0; for (uint j = 0; j < theNumRows; j++) { if (mDataMatrix[j][i] == "") throw FormatError ("imported data matrix contains null entries"); traittype_t theCurrType = extractData (mDataMatrix[j][i]); if (theCurrType == kTraittype_Alpha) theCountAlpha++; else if (theCurrType == kTraittype_Float) theCountFloats++; else if (theCurrType == kTraittype_Int) theCountInts++; else theCountOther++; } // what type of data is in the column? /* Case 1. if there are alphanumeric strings and no floats, it must be discrete. If there are alphanumerics and floats, it must be a mistake. */ if (0 < theCountAlpha) { if (0 < theCountFloats) throw FormatError ("import column contains continuous and discrete data"); else theOverallType = kTraittype_Discrete; } /* Case 2. if there are floats and any number of ints, it must be continuous. */ else if (0 < theCountFloats) { assert (theCountAlpha == 0); theOverallType = kTraittype_Continuous; } /* Case 3. no floats, no alphanumeric so there must be ints and this must be a discrete file. Otherwise it's a mistake. */ else { if (0 < theCountInts) theOverallType = kTraittype_Discrete; else throw FormatError ("import does not contain meaningful data"); } } mColumnTypes.push_back (theOverallType); assert (mColumnTypes.size() == (uint) (i+1)); } /* Split up into submatrices by making two copies and stepping backwards along them and deleting the collumns that don't belong. */ mDiscDataMatrix = mDataMatrix; mContDataMatrix = mDataMatrix; mDiscColNames = mColNames; mContColNames = mColNames; for (int i = mColumnTypes.size() - 1; 0 <= i; i--) { switch (mColumnTypes[i]) { case kTraittype_Discrete: // so delete continuous copies mContColNames.erase (mContColNames.begin() + i); for (uint j = 0; j < mContDataMatrix.size(); j++) mContDataMatrix[j].erase(mContDataMatrix[j].begin() + i); break; case kTraittype_Continuous: // so delete discrete copies mDiscColNames.erase (mDiscColNames.begin() + i); for (uint j = 0; j < mDiscDataMatrix.size(); j++) mDiscDataMatrix[j].erase (mDiscDataMatrix[j].begin() + i); break; default: // should never get here assert (false); } } mDataMatrix.clear(); } traittype_t TabDataReader::extractData (string& iRawDataStr) //: what sort of information in in this string? { if (iRawDataStr == "?") return kTraittype_Missing; if (iRawDataStr == "-") return kTraittype_Gap; if (sbl::isFloat (iRawDataStr)) { //if (sbl::toDouble(iRawDataStr) < 0.0) // throw FormatError ("negative species richness not permitted"); //else return kTraittype_Float; } if (sbl::isWhole (iRawDataStr)) { //if (sbl::toLong(iRawDataStr) < 0) // throw FormatError ("negative species richness not permitted"); //else return kTraittype_Int; } return kTraittype_Alpha; } void TabDataReader::extractColNames () //: see if there are column names, remove from matrix & record them { // extract first row to see if there are column names bool theColsHaveNames = true; for (stringvec_t::size_type i = 1; i < mDataMatrix[0].size(); i++) { traittype_t theType = extractData (mDataMatrix[0][i]); if (theType != kTraittype_Alpha) { theColsHaveNames = false; break; } } // if the first row from the second element onwards has only // alphanumeric strings, then it has column titles. Stitch them into // the column names. Eliminate them from the matrix. if (theColsHaveNames) { mColNames.empty(); for (stringvec_t::size_type i = 1; i < mDataMatrix[0].size(); i++) mColNames.push_back (nexifyString (mDataMatrix[0][i].c_str())); mDataMatrix.erase (mDataMatrix.begin()); } else { // give them a bunch of empty names mColNames.resize (mDataMatrix[0].size(), string("")); } } void TabDataReader::extractRowNames () //: remove row names from matrix & record them // The row names must be there. Throw if they aren't { // These _must_ be there. mRowNames.empty(); for (stringmatrix_t::size_type i = 0; i < mDataMatrix.size(); i++) { traittype_t theType = extractData (mDataMatrix[i][0]); if (theType != kTraittype_Alpha) throw FormatError ("data file must contain taxa names"); else { // store the name and delete it from the matrix mRowNames.push_back (nexifyString (mDataMatrix[i][0].c_str())); (mDataMatrix[i]).erase ((mDataMatrix[i]).begin()); } } } // *** END ***************************************************************/
true
98624ac289ad46d94e63921b9a3801d208b39f3e
C++
obapa/MIPS_processor
/main.cpp
UTF-8
1,611
2.6875
3
[]
no_license
#include "processor.h" //for processor class #include "IO.h" //header for ioFile struct #include "ect.h" #include <iostream> #include <fstream> //filestream #include <sstream> //stringstream #include <string> //strings //TODO branching issue int main() { std::string x; bool debug = true; processor MIPS; ioFile IO; IO = IO.handleIO();//creates ioFile object with all the file info MIPS = IO.loadInput(IO, MIPS);//loads data into memory and registers, returns from CODE int n = 1;//counts instruction cycle do{ //std::cout << cycleNum(n++)<<std::endl; IO.print(cycleNum(n++)); MIPS.WB(); MIPS.MA(); MIPS.EX(); MIPS.ID(); MIPS.IF(); IO.print("\n"); }while(!MIPS.noCom());//check that there are no more command loaded anywhere if(debug){ IO.print("REGISTERS\n"); for (int i = 0; i < 32; i++){ if(MIPS.reg[i] != 0){//dont print 0s IO.print("R"+iToS(i)+" "+iToS(MIPS.reg[i])+"\n");//print reg values } } IO.print("MEMORY\n"); for (int i = 0; i < sizeof(MIPS.memory); i++){//its calling memset for somereason so giving error string if(MIPS.memory[i] != 0){//don't print 0s IO.print(iToS(i-3)+" "+iToS((int)MIPS.memory[i])+"\n"); //std::cout<< "M" << i << ": " << (int)MIPS.memory[i] <<std::endl; //DEBUG print mem values } } } //for (int i = 0; i < MIPS.instr.size(); i++) {cout << MIPS.instr[i] <<endl;} return 0; }
true
71f8d49191593f0c7a1bb61a22c3412311411103
C++
jonasvm/piratas-futuro-rpg
/aluno/solucoes/63_13.cpp
ISO-8859-1
537
3.078125
3
[]
no_license
/*Para seu azar sua bolsa rasgou e voc s percebeu ao ter atravessado a floresta toda. Muitos itens seus caram pelo caminho. Agora ter que fazer todo o caminho contrrio para encontr-los novamente. No total a floresta tem uma rea de 30x50km. Voc sabe que existe um item a cada 60,6Km2. Vasculhe toda a rea e descubra quantos itens voc perdeu. 1500 24*/ #include <iostream> #include <cmath> using namespace std; int main() { int area = 30*50; cout << floor(area/60.6); return 1; }
true
821954a44f69007a02ac74bb4c99182b33dd4cd0
C++
rdchan/CS2337work
/InClass2/include/Document.h
UTF-8
531
2.828125
3
[]
no_license
/* Rishi Chandna (rdc180001) Louis Fernandes (lef180000) */ #ifndef DOCUMENT_H #define DOCUMENT_H #include <string> #include <iostream> using namespace std; class Document { public: Document(); Document(string); virtual ~Document(); std::string Getcontent() const { return content; } void Setcontent(std::string val) { content = val; } friend std::ostream& operator<<(std::ostream&, const Document&); protected: private: std::string content; }; #endif // DOCUMENT_H
true
570e5d5b93f52e1c7f1401ff10a1e55a3a0e91d3
C++
adityalahiri/CPP-Code
/partialMax_csAcad.cpp
UTF-8
1,430
3.796875
4
[]
no_license
#include <iostream> #include <bits/stdc++.h> using namespace std; class Graph{ int V; std::vector<int> *adj; int cycle_flag = 0; int reached = 0; //private by default void DFSUtil(int v, bool visited[], int parent, int dest); public: Graph(int V); void addEdge(int v, int w); void DFS(int v, int dest); }; Graph::Graph(int V){ this->V = V; adj = new vector<int>[V]; } void Graph::addEdge(int v, int w){ adj[v].push_back(w); } void Graph::DFSUtil(int v, bool *visited,int parent, int dest){ visited[v] = true; cout<<v<<endl; parent = v; for(int i = 0; i < adj[v].size(); i++){ if(adj[v][i] == dest){ reached = 1; break; } if(!visited[adj[v][i]]) DFSUtil(adj[v][i], visited, parent,dest); else{ if(parent != adj[v][i]){ cycle_flag = 1; break; } } } } void Graph::DFS(int v, int dest){ bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; DFSUtil(v, visited, -1, dest); if(reached && !cycle_flag) cout<<1; else cout<<0; } int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); // g.addEdge(3, 3); cout << "Following is Depth First Traversal" " (starting from vertex 2) \n"; g.DFS(2,3); return 0; }
true
e19d1eadd3ec435796843ce8e889524d47dfd12b
C++
zhengjinwei123/cplusplus
/recastnav/src/Aoi/point2i.cpp
UTF-8
383
2.734375
3
[]
no_license
#include "Aoi/point2i.h" namespace aoi { Point2i::Point2i() { } Point2i::Point2i(int X, int Y) : x(X), y(Y) { } bool Point2i::operator==(const Point2i &other) const { if (x == other.x && y == other.y) return true; return false; } bool Point2i::operator!=(const Point2i &other) const { if (x != other.x || y != other.y) return true; return false; } }
true
13aa13776c4bed5a40a816dd4a42eb9b3d0111b1
C++
hverlin/lutin
/src/symboles/BlocDeclaration.h
UTF-8
977
2.84375
3
[]
no_license
#ifndef LUTIN_BLOCDECLARATION_H #define LUTIN_BLOCDECLARATION_H #include <TableDesSymboles.h> #include "Symbole.h" class BlocDeclaration : public Symbole { public: BlocDeclaration() : Symbole(BLOC_DECLARATION), suivant(nullptr) { } void setSuivant(BlocDeclaration *blocDeclaration) { this->suivant = blocDeclaration; } BlocDeclaration *getSuivant() const { return suivant; } virtual ~BlocDeclaration() { if (suivant != nullptr) { delete suivant; } } virtual void executer(TableDesSymboles *tableDesSymboles) = 0; virtual void afficher() = 0; virtual bool analyser(TableDesSymboles *tableDesSymboles) = 0; virtual void optimiser(TableDesSymboles *tableDesSymboles) = 0; virtual bool estVide() = 0; protected: BlocDeclaration(int id, unsigned ligne, unsigned colonne) : Symbole(id, ligne, colonne), suivant(nullptr) { } BlocDeclaration *suivant; }; #endif
true
90bf97869d13141bd1c2297864f22381fa5c8246
C++
ann234/PJH_BaekJoon
/Dynamic_Programming/main_2579.cpp
UHC
816
3.515625
4
[]
no_license
#include <iostream> #include <vector> using namespace std; int max(int a, int b) { return (a > b) ? a : b; } int main() { int N; cin >> N; vector<int> points(N + 1); for (int i = 1, val; i <= N; i++) { cin >> val; points[i] = val; } // step continuity, point // ¿ ִ ִ int** memory = new int*[N + 1]; for (int i = 0; i <= N; i++) memory[i] = new int[3]; // memory[i][j]: j ö i ִ memory[0][1] = 0; memory[0][2] = 0; memory[1][1] = points[1]; memory[1][2] = 0; for (int i = 2; i <= N; i++) { memory[i][1] = max(memory[i - 2][1], memory[i - 2][2]) + points[i]; memory[i][2] = memory[i - 1][1] + points[i]; } cout << max(memory[N][1], memory[N][2]) << endl; }
true
f36983bcf1cf9eb521887547dc29142ee665a70a
C++
z1908144712/ExamCode
/剑指Offer/剑指 Offer 46. 把数字翻译成字符串/main.cpp
UTF-8
529
3.21875
3
[]
no_license
#include <iostream> using namespace std; class Solution { public: int cnt = 0; int translateNum(int num) { translateNumHelper(num); return cnt; } void translateNumHelper(int num) { if (num < 10) { cnt++; return; } translateNumHelper(num / 10); int a = num % 100; if (a >= 10 && a <= 25) { translateNumHelper(num / 100); } } }; int main() { cout << Solution().translateNum(2005) << endl; return 0; }
true
f3e0339145962ed15c7ccd39559e3ce08ee62244
C++
ahmetberber/CSE241-FALL-2019
/HW04/functions.cpp
UTF-8
15,033
3.359375
3
[]
no_license
/* Ahmet Hilmi Berber */ /* 171044027 */ /* CSE241 HW04 */ #include <iostream> #include <vector> #include <string> #include "functions.h" using namespace std; namespace global { const unsigned int MAXCOURSELIMIT = 3; const unsigned int STARTHOUR = 9; /* assume that courses start at 9:00 AM */ const int FINISHHOUR = 17; /* assume that courses finish at 17:00 PM */ int tempCourseClassDelimeterG = 0; /* I'm using that variable at the arranging all courses timetables part */ const string wholeDays[] = {"MON", "TUE", "WED", "THU", "FRI"}; /* I'm using that variable at the arranging course timetables parts */ } // namespace global /* classroom clas constructor */ Classroom::Classroom(int ID, int capacity, string no) : classID(ID), classCapacity(capacity), classNo(no) { studentInRoom = 0; CoursesInClassroom = NULL; s_CoursesInClassroom = 0; } /* classroom clas copy constructor */ Classroom::Classroom(const Classroom &clss) { CoursesInClassroom = new Course[clss.s_CoursesInClassroom]; CoursesInClassroom = clss.CoursesInClassroom; s_CoursesInClassroom = clss.s_CoursesInClassroom; classID = clss.classID; classCapacity = clss.classCapacity; classNo = clss.classNo; studentInRoom = clss.studentInRoom; } /* classroom clas destructor */ Classroom::~Classroom() { delete CoursesInClassroom; CoursesInClassroom = NULL; } /* I spilted this function 2 parts. If there is a lesson at the given time, first part works, If there is no lesson, second part works */ void Classroom::enterClassroom(Student enterStudent, string day, int hour, bool flag) { /* the "flag" variable controls if there is a lesson at the given time or not */ bool stop = false; if (flag) { /* if there is a lesson, that means we should increment the attendance count of the appropiate course and student enters the class */ for (unsigned int i = 0; i < s_CoursesInClassroom && stop == false; i++) { for (unsigned int j = 0; j < CoursesInClassroom[i].enrolledStudents.size() && stop == false; j++) { if (CoursesInClassroom[i].enrolledStudents[j].studentID == enterStudent.studentID) { /* checking student id, entering the student in class, incrementing attendance count and print the student count in class */ CoursesInClassroom[i].enrolledStudents[j].attendanceCount++; CoursesInClassroom[i].enrolledStudents[j].isInClassroom = true; cout << ++studentInRoom << endl; stop = true; } } } } else { for (unsigned int i = 0; i < studentsInClass.size() && stop == false; i++) { if (studentsInClass[i].studentID == enterStudent.studentID) { /* checking student id, entering the student in class and print the student count in class */ studentsInClass[i].isInClassroom = true; cout << ++studentInRoom << endl; stop = true; } } } } /* this function works like the enterClassroom function for 2 parts. First part check if given student is in any course of class, second part check if given student is just in the class without taking attendance of any course */ bool Classroom::quitClassroom(Student quitStudent) { for (unsigned int i = 0; i < s_CoursesInClassroom; i++) { for (unsigned int j = 0; j < CoursesInClassroom[i].enrolledStudents.size(); j++) { if (CoursesInClassroom[i].enrolledStudents[j].studentID == quitStudent.studentID && CoursesInClassroom[i].enrolledStudents[j].isInClassroom) { /* checking student id and is he/she is in classroom, quiting the "enrolled" student in class and print the student count in class */ CoursesInClassroom[i].enrolledStudents[j].isInClassroom = false; cout << --studentInRoom << endl; return true; } } } for (unsigned int i = 0; i < studentsInClass.size(); i++) { if (studentsInClass[i].studentID == quitStudent.studentID && studentsInClass[i].isInClassroom) { /* checking student id and is he/she is in classroom, quiting the "not enrolled" student in class and print the student count in class */ studentsInClass[i].isInClassroom = false; cout << --studentInRoom << endl; return true; } } return false; } /* this function basically adding courses in the classes dynamically */ void Classroom::arrangeCoursesToClass(Course arrangingCourse) { Course *temp = new Course[s_CoursesInClassroom + 1]; for (unsigned int i = 0; i < s_CoursesInClassroom; i++) { temp[i] = CoursesInClassroom[i]; } temp[s_CoursesInClassroom] = arrangingCourse; s_CoursesInClassroom++; CoursesInClassroom = temp; } /* this function finds and and prints the student's attendance count of given course information */ void Classroom::takeAttendance(Course attendanceCourse) { for (unsigned int i = 0; i < s_CoursesInClassroom; i++) { if (CoursesInClassroom[i].courseID == attendanceCourse.courseID) { for (unsigned int j = 0; j < CoursesInClassroom[i].enrolledStudents.size(); j++) { cout << CoursesInClassroom[i].enrolledStudents[j].studentName << " " << CoursesInClassroom[i].enrolledStudents[j].attendanceCount << " - "; } } } } /* this function determines if there is a course at given time or not */ bool Classroom::detCourse(string day, int hour) { for (unsigned int i = 0; i < s_CoursesInClassroom; i++) { for (unsigned int j = 0; j < CoursesInClassroom[i].courseStartDay.size(); j++) { /* I firstly controlled day and then the hour. The given hour must be between the start and finish hours of the course */ if (CoursesInClassroom[i].courseStartDay[j] == day && (global::STARTHOUR + hour) >= CoursesInClassroom[i].courseStartTime[j] && (global::STARTHOUR + hour) < CoursesInClassroom[i].courseFinishTime[j]) { return true; } } } return false; } /* this function adds students to the classes for the students which have no lesson on the given time */ void Classroom::addStudentsToClass(vector<Student> stdss) { studentsInClass = stdss; } /* this function basicly takes a string which is the proff format in txt file and assigns them to the lecturer professions */ void Lecturer::trimLectProffs(string str) { int i = 0, j = 0, k = 0; string tempStr; while (str[i] != ',' && (unsigned int)i != str.length() + 1) { k = i; while (str[k] != ',' && (unsigned int)k != str.length()) { k++; } tempStr.resize(k - i); while (str[i] != ',' && (unsigned int)i != str.length()) { tempStr[j] = str[i]; i++, j++; } lectProffs.push_back(tempStr); tempStr.clear(); i++, j = 0; } } /* this function basicly takes the whole courses and professions ordered high to low value, and assigns them to this order */ void Lecturer::assignAllCoursesFromLect(vector<Course> &crss, string prfs, int prfsCnt) { for (unsigned int i = 0; i < lectProffs.size(); i++) { for (unsigned int j = 0; j < crss.size(); j++) { if (lectProffs[i] == prfs && crss[j].isTaken != true && lectTakenCourses.size() < global::MAXCOURSELIMIT) { crss[j].isTaken = true; lectTakenCourses.push_back(crss[j]); } } } } /* this function basicly takes the whole courses and professions and orders them high to low value and assings to the prfs and prfsCnt variables */ void Lecturer::detProffs(vector<string> &prffs, vector<int> &prffsCnt) { for (unsigned int i = 0; i < lectProffs.size(); i++) { bool flag = false; for (unsigned j = 0; j < prffs.size(); j++) { if (lectProffs[i] == prffs[j]) { prffsCnt[j]++; flag = true; } } if (flag == false) { prffs.push_back(lectProffs[i]); prffsCnt.push_back(1); } } } /* this function helps arranging to the timetables of classes (appropiate with setTimeTable function) */ void Lecturer::assignAllCoursesFromAllCourses(Course assig, vector<Course> &crss) { for (unsigned int i = 0; i < crss.size(); i++) { if (crss[i].courseID == assig.courseID) { crss[i] = assig; break; } } } /* this function basically helps the arranging timetables of courses */ void Lecturer::setTimeTable(int &startCount, int &dayCount, int &del, vector<Course> &crss) { for (unsigned int i = 0; i < lectTakenCourses.size(); i++) { if (startCount + lectTakenCourses[i].courseHours <= global::FINISHHOUR) { /* checking if the course day seperated two or not */ lectTakenCourses[i].courseClassDelimeter = del; lectTakenCourses[i].courseStartTime.push_back(startCount); lectTakenCourses[i].courseFinishTime.push_back(startCount + lectTakenCourses[i].courseHours); lectTakenCourses[i].courseStartDay.push_back(global::wholeDays[dayCount]); if (startCount + lectTakenCourses[i].courseHours == global::FINISHHOUR) { startCount = global::STARTHOUR; dayCount++; } else { startCount += lectTakenCourses[i].courseHours; } } else { /* one part of course at the end of day, the other part at the beginning of the next day */ int temp = global::FINISHHOUR - startCount; lectTakenCourses[i].courseStartTime.push_back(startCount); lectTakenCourses[i].courseFinishTime.push_back(global::FINISHHOUR); lectTakenCourses[i].courseStartDay.push_back(global::wholeDays[dayCount]); startCount = global::STARTHOUR; lectTakenCourses[i].courseStartTime.push_back(startCount); lectTakenCourses[i].courseFinishTime.push_back(startCount + (lectTakenCourses[i].courseHours - temp)); if (global::wholeDays[dayCount] == "FRI") { /* checking if we reached the end of week */ dayCount = 0; del++; lectTakenCourses[i].courseClassDelimeter = del; lectTakenCourses[i].courseStartDay.push_back(global::wholeDays[dayCount]); } else { lectTakenCourses[i].courseClassDelimeter = del; lectTakenCourses[i].courseStartDay.push_back(global::wholeDays[++dayCount]); } startCount += lectTakenCourses[i].courseHours - temp; } assignAllCoursesFromAllCourses(lectTakenCourses[i], crss); /* assigning arranged course to the lecturer's courses */ } } /* this function basicly show timetable and class information of all courses after arrangment is over */ void show(vector<Course> crss) { for (unsigned int i = 0; i < crss.size(); i++) { if (crss[i].courseClassID.size() > 1) { cout << "(" << crss[i].courseID << ")" << crss[i].courseName << " in "; for (unsigned int j = 0; j < crss[i].courseStartDay.size(); j++) { cout << crss[i].courseClassID[j] << " at " << crss[i].courseStartDay[j] << "_" << crss[i].courseStartTime[j] << "-" << crss[i].courseFinishTime[j]; if (j != crss[i].courseStartDay.size() - 1) cout << ", in "; } cout << endl; } else { cout << "(" << crss[i].courseID << ")" << crss[i].courseName << " in " << crss[i].courseClassID[crss[i].courseClassID.size() - 1] << " at "; for (unsigned int j = 0; j < crss[i].courseStartDay.size(); j++) { cout << crss[i].courseStartDay[j] << "_" << crss[i].courseStartTime[j] << "-" << crss[i].courseFinishTime[j] << ","; } cout << endl; } } cout << endl; }
true
c02851f267e12516c009bc245f28e9ac2028c661
C++
WhiZTiM/coliru
/Archive2/fd/3c55446bba3283/main.cpp
UTF-8
187
2.640625
3
[]
no_license
#include <iostream> #include <string> #include <sstream> int main(){ std::string x = "123.456"; double y; std::istringstream ss(x); ss >> y; std::cout << y << '\n'; }
true
2bdff13deb03338a2d903f4bce469e0ce1b23018
C++
aureus5/CPPproject
/AirplaneSensorCPPproject/ConstantSignal.h
UTF-8
316
2.5625
3
[]
no_license
#ifndef PROJECT2_CONSTANTSIGNAL_H #define PROJECT2_CONSTANTSIGNAL_H #include "Signal.h" #include "Time.h" namespace Project2 { class ConstantSignal:public Signal { public: ConstantSignal(double voltageOffset, Time &timeOffset); virtual double getVoltageAtTime(Time &t) const; }; } #endif
true
fca9cc01bdb86634289e42936c4a327af74950d6
C++
thekid123/FractionFile
/fraction.hpp
UTF-8
1,574
3.578125
4
[]
no_license
/************************************************************************* Blessing Alagba v223e376 Program 3 Description: This program implements a Fraction class it consists of the numerator and denominator It asks the user to enter two fractions and it calculates 7 options which is Add, Subtract, Multiplication, Division, Reduce the fraction and to find the decimal equvalent. It exits the program if a certain condition is met. Pseudo code:- class Name : Fraction Data: numerator - stores the numerator value denominator - stores the denominator value Mutator Function: simplify - it simplifies the fraction */ #ifndef Fraction_hpp #define Fraction_hpp #include <iostream> using namespace std; class Fraction { int numerator; int denominator; public: //default constructor Fraction(); //constructor Fraction(int n, int d); //Using the friend function friend Fraction operator+ (const Fraction&, const Fraction&); friend Fraction operator- (const Fraction&, const Fraction&); friend Fraction operator* (const Fraction&, const Fraction&); friend Fraction operator/ (const Fraction&, const Fraction&); friend ostream& operator << (ostream& output, Fraction&); friend istream& operator >> (istream& input, Fraction&); //finding the decimal equvalent double dec_equiv(); //finding the greatest common divisor double static gcd(int x, int y); //Mutator Function (simplifies the fraction) void simplify(); }; #endif
true
11e114bb236552128d6425c6f5665047a6d987b8
C++
pulkkinho/islandgame
/UI/gamestate.cpp
UTF-8
1,478
2.703125
3
[]
no_license
#include "gamestate.hh" #include "iostream" #include "igamerunner.hh" GameState::GameState(): Common::IGameState() { } enum GamePhase { MOVEMENT = 1, SINKING = 2, SPINNING = 3 }; GameState::~GameState() { } Common::GamePhase GameState::currentGamePhase() const { return _gamePhaseId; } int GameState::currentPlayer() const { return _playerInTurn; } void GameState::changeGamePhase(Common::GamePhase nextPhase) { _gamePhaseId = nextPhase; } void GameState::changePlayerTurn(int nextPlayer) { _playerInTurn = nextPlayer ; } void GameState::setrunner(std::shared_ptr<Common::IGameRunner> runneri) { runner = runneri; } void GameState::addPointsToPlayer(int playerId, int points) { int x = 0; for(auto pair : _playerPointVector){ if(playerId == pair.first){ _playerPointVector.at(x).second =_playerPointVector.at(x).second + points; pair.first = pair.second + points; } x = x + 1; } } void GameState::initializePlayerPointVector() { int amount = getrunner().get()->playerAmount(); int x = 1; while(x <= amount){//jälkimmäinen on pisteet _playerPointVector.push_back(std::make_pair(x,0)); x = x+1; } } std::vector<std::pair<int,int>> GameState::getPlayerPointVector() { return _playerPointVector; } int GameState::getPawnPerPlayer() { return _pawnPerPlayer; } std::shared_ptr<Common::IGameRunner> GameState::getrunner() { return runner; }
true
78fdd1cf81729b2f750b107a754b1106ec1e4a23
C++
hyunmock/modern_cpp
/rvalue.cpp
UTF-8
424
3.375
3
[]
no_license
#include <iostream> #include <string> void printString(const std::string & str) { std::cout<<str<<std::endl; } void printString(std::string && str) { std::cout<<str<<std::endl; } int main() { const std::string & lvalRef = std::string("hello"); std::string && rvalRef = std::string("world"); std::cout<<lvalRef<< " "<<rvalRef<<std::endl; std::string name{"hi!"}; printString("hello"); printString(name); }
true
eb1537364a1e84ec356dcc44c2666622323bc3bb
C++
andrewkpeterson/3d-engine
/src/platformer/PlatformerApplication.cpp
UTF-8
617
2.515625
3
[]
no_license
#include "PlatformerApplication.h" #include "PlatformerGameplayScreen.h" #include "PlatformerStartScreen.h" PlatformerApplication::PlatformerApplication() : Application() { m_screenmap["gameplay"] = std::make_shared<PlatformerGameplayScreen>(this); m_screenmap["start"] = std::make_shared<PlatformerStartScreen>(this); m_current_screen = m_screenmap["start"]; curr_screen_name = "start"; } PlatformerApplication::~PlatformerApplication() { } void PlatformerApplication::restart() { Application::restart(); m_current_screen = m_screenmap["start"]; resize(app_width, app_height); }
true
f0f310a542a76ee5f017403de6232b07fff15cf7
C++
dmalec/wumpus-for-picosystem
/game_types.hpp
UTF-8
341
2.546875
3
[ "MIT" ]
permissive
// Copyright(c) 2021 Dan Malec // // MIT License (see LICENSE file for details) #ifndef GAME_TYPES_HPP_INCLUDED_ #define GAME_TYPES_HPP_INCLUDED_ struct GamePoint { uint8_t x; uint8_t y; }; enum GameWall { NONE = 0x0000, WEST = 0x0001, NORTH = 0x0010, EAST = 0x0100, SOUTH = 0x1000 }; #endif // GAME_TYPES_HPP_INCLUDED_
true
55637bfd1ba89754eaf7b7ca57fd87b8dfb2cd6c
C++
sakharlina/PSTU_labs
/Лабораторная работа №18/Lab18.7/Class7_main.cpp
UTF-8
716
3.15625
3
[]
no_license
#include "Pair.h" #include "List.h" #include <iostream> using namespace std; void main() { cout << "SPISOK:\n"; List<int>A(5, 0); cin >> A; cout << A << endl; List<int>B(10, 1); cout << B << endl; B = A; cout << B << endl; cout << A[2] << endl; cout << "size = " << A() << endl; B = A + 10; cout << B << endl; Pair p1; cin >> p1; cout << p1; int k; cout << "\nk? "; cin >> k; Pair tmp(k, k); Pair p2; p2 = p1 + tmp; cout << p2; Pair p3; cin >> p3; cout << p3 << endl; List<Pair>C(5, p3); cin >> C; cout << C << endl; List<Pair>D(10, p3); cout << D << endl; D = C; cout << D << endl; cout << C[2] << endl; cout << "size = " << C() << endl; D = C + p3; cout << D << endl; }
true
1fb275540463cc84cc62437f210ebdc4d258428e
C++
Sameer-Arora/csl201
/Assignment3/main.cpp
UTF-8
1,469
3.25
3
[]
no_license
#include <iostream> #include <fstream> #include "mavl1.hpp" using namespace std; int main(){ MAVLTree tree; ifstream f; int k; string s; f.open("entries.txt"); f >> k >>s; //tree.insert(k,s); while(!f.eof()){ tree.insert(k,s); // tree.print(); f>>k>>s; // cout<<endl; } int choice=0; string val; int key=0,place; while(1){ cout<<"Please enter:- \n 1) to insert\n 2) to delete by key\n 3) to get the place of a key\n 4) to delete by place of​ ​ key\n 5) find value of key\n 6) for Tree size\n 0) to exit \n"; cin>>choice; switch(choice){ case 1: cout<<"Enter the (int)key and (string)value to insert :\n"; cin>>key>>val; tree.insert(key,val); break; case 2: cout<<"Enter the (int)key to delete :\n"; cin>>key; tree.remove(key); break; case 3: cout<<"Enter the (int)key to get place :\n"; cin>>key; cout<<"Place:-"<<tree.get_place(key)<<endl; break; case 4: cout<<"Enter the place to delete :\n"; cin>>place; tree.delete_by_place(place); break; case 5: cout<<"Enter the (int)key to find:\n"; cin>>key; cout<<"value of key is "<<tree.search(key)<<endl; break; case 6: cout<<"Size:- "<<tree.size()<<endl; break; case 0: break; default: cout<<"Please enter correct choice\n:";break; } if(choice==0)break; cout<<"Do you wish to continue:0) to quit any other integer to continue.\n"; cin>>choice; if(choice==0)break; } }
true
15a3993b0bac45b86899fc0c44c0900f69021579
C++
Gurman8r/arduino
/libraries/Timer/Timer.cpp
UTF-8
1,023
2.984375
3
[]
no_license
/* Timer.cpp * Author: Melody Gurman * Modified: 11/11/2018 * * * * * * * * * * * * * * * */ #include <Timer.h> #if defined(ARDUINO) #include <Arduino.h> #define DELTA_TIME millis #endif Timer::Timer() : m_paused(true) , m_elapsed(0) , m_max(0) , m_min(0) { } Timer::Timer(const Timer & copy) : m_paused(copy.m_paused) , m_elapsed(copy.m_elapsed) , m_max(copy.m_max) , m_min(copy.m_min) { } Timer::~Timer() { } Timer& Timer::start() { m_min = m_max = DELTA_TIME(); m_elapsed = 0; return pause(false); } Timer& Timer::reset() { return stop().start(); } Timer& Timer::stop() { m_elapsed = ((m_max = DELTA_TIME()) - m_min); return (*this); } Timer& Timer::pause(bool pause) { if (pause && !m_paused) { m_paused = true; m_elapsed = ((m_max = DELTA_TIME()) - m_min); } else if (!pause && m_paused) { m_paused = false; m_min = DELTA_TIME(); } return (*this); } const TimePoint & Timer::elapsed() const { if(!m_paused) { m_elapsed = (DELTA_TIME() - m_min.millis()); } return m_elapsed; }
true
25e780cbf6b5231e2fa250b1dc19ef52c4272571
C++
Nikhil-Vinay/DS_And_Algo
/Daily_Coding_Problem/find_word_in_matrix.cpp
UTF-8
1,913
3.671875
4
[]
no_license
/********* There is a given matrix, find a word in the matrix, if present return true **************/ /** Note: Word can be present in 8 directions - Left->Right, Right->Left, Top->Bottom, Bottom->Top, Top-Right(diagonal), Top-Left(Diagonal), Bottom-Right(Diagonal), Bottom-Left(Diagonal). */ /* In the below solution , we are just displaying the match count, for displaying the word at proper place, * we can have an auxiliary two d matrix of 0 or 1. We can populate matrix with 0 and 1 with each word match and * once full word match, we can display the original matrix with help of auxiliary matrix. * Auxiliary matrix resetting should be done accordingly in serach flow. */ #include<iostream> #include<bits/stdc++.h> #define DIRECTION_COUNT 8 using namespace std; int direction_x[DIRECTION_COUNT] = {1, -1, 0, 0, 1, -1, 1, -1}; int direction_y[DIRECTION_COUNT] = {0, 0, 1,-1, 1, 1,-1, -1}; int match_count = 0; template<size_t M, size_t N> void FindMatch(char(&matrix)[M][N], const char* word, int x, int y) { for(int i = 0; i < DIRECTION_COUNT; i++) { const char* temp_word = word; int temp_x = x, temp_y = y; while(temp_word[0] != '\0' && matrix[temp_x][temp_y] == temp_word[0] && (temp_x >= 0 && temp_x < N && temp_y >= 0 && temp_y < M)) { temp_x += direction_x[i]; temp_y += direction_y[i]; temp_word++; if(temp_word[0] == '\0') { match_count++; break; } } } } int main() { char matrix[4][4] = { {'a', 'c', 'a', 't' }, {'b', 'd', 'a', 'p' }, {'t', 'h', 'm', 't' }, {'c', 'a', 't', 'x' }}; const char* word = "thb"; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { FindMatch(matrix, word, i, j); } } cout<<"match count is: "<<match_count<<endl; return 0; }
true
b3025d837596a896e7249e55ab4f106d3f31cb34
C++
northmatt/Math-Modules
/First Project/First Project/Vector.cpp
UTF-8
4,080
3.6875
4
[]
no_license
#include "Vector.h" vec2::vec2() { } vec2::vec2(float _x, float _y) { x = _x; y = _y; } void vec2::Subtract(vec2 v2) { this->x -= v2.x; this->y -= v2.y; } void vec2::MultScalar(float s) { this->x *= s; this->y *= s; } void vec2::DivScalar(float s) { this->x /= s; this->y /= s; } float vec2::Dot(vec2 v2) { return x * v2.x + y * v2.y; } float vec2::GetMagnitude() { return sqrtf(x * x + y * y); } float vec2::GetMagnitudeSquared() { return x * x + y * y; } vec2 vec2::Normailize() { return *this / GetMagnitude(); } vec2 vec2::Project(vec2 b) { return b * (Dot(b) / b.GetMagnitudeSquared()); } vec2 vec2::Rotate(float rot) { double c{ cos(rot) }, s{ sin(rot) }; return vec2(x * c - y * s, x * s + y * c); } float vec2::operator[](int i) { //used for indexing //i == 0 then x //i == 1 then y return *hold[i]; } vec2 vec2::operator-() { return vec2(-x, -y); } vec2 vec2::operator+(vec2 v1) { return vec2(this->x + v1.x, this->y + v1.y); } vec2 vec2::operator-(vec2 v1) { return vec2(this->x - v1.x, this->y - v1.y); } vec2 vec2::operator*(float f) { return vec2(this->x * f, this->y * f); } vec2 vec2::operator/(float f) { return vec2(this->x / f, this->y / f); } vec3::vec3() { } vec3::vec3(float _x, float _y, float _z) { x = _x; y = _y; z = _z; } void vec3::Subtract(vec3 v2) { this->x -= v2.x; this->y -= v2.y; this->z -= v2.z; } void vec3::MultScalar(float f) { this->x *= f; this->y *= f; this->z *= f; } void vec3::DivScalar(float f) { this->x /= f; this->y /= f; this->z /= f; } float vec3::Dot(vec3 v2) { return x * v2.x + y * v2.y + z * v2.z; } float vec3::GetMagnitude() { return sqrtf(x * x + y * y + z * z); } float vec3::GetMagnitudeSquared() { return x * x + y * y + z * z; } vec3 vec3::Normailize() { return *this / GetMagnitude(); } vec3 vec3::Project(vec3 v2) { return v2 * (Dot(v2) / v2.GetMagnitudeSquared()); } vec3 vec3::RotateZ(float rot) { double c{ cos(rot) }, s{ sin(rot) }; return vec3(x * c - y * s, x * s + y * c, z); } float vec3::operator[](int i) { return *hold[i]; } vec3 vec3::operator-() { return vec3(-x, -y, -z); } vec3 vec3::operator+(vec3 v2) { return vec3(this->x + v2.x, this->y + v2.y, this->z + v2.z); } vec3 vec3::operator-(vec3 v2) { return vec3(this->x - v2.x, this->y - v2.y, this->z - v2.z); } vec3 vec3::operator*(float f) { return vec3(this->x * f, this->y * f, this->z * f); } vec3 vec3::operator/(float f) { return vec3(this->x / f, this->y / f, this->z / f); } vec4::vec4() { } vec4::vec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } void vec4::Subtract(vec4 v2) { this->x -= v2.x; this->y -= v2.y; this->z -= v2.z; this->w -= v2.w; } void vec4::MultScalar(float f) { this->x *= f; this->y *= f; this->z *= f; this->w *= f; } void vec4::DivScalar(float f) { this->x /= f; this->y /= f; this->z /= f; this->w /= f; } float vec4::Dot(vec4 v2) { return x * v2.x + y * v2.y + z * v2.z + w * v2.w; } float vec4::GetMagnitude() { return sqrtf(x * x + y * y + z * z + w * w); } float vec4::GetMagnitudeSquared() { return x * x + y * y + z * z + w * w; } vec4 vec4::Normalize(vec4 v2) { return *this / GetMagnitude(); } vec4 vec4::Project(vec4 v2) { return v2 * (Dot(v2) / v2.GetMagnitudeSquared()); } float vec4::operator[](int i) { return *hold[i]; } vec4 vec4::operator+(vec4 v2) { return vec4(this->x + v2.x, this->y + v2.y, this->z + v2.z, this->z + v2.w); } vec4 vec4::operator-(vec4 v2) { return vec4(this->x - v2.x, this->y - v2.y, this->z - v2.z, this->z - v2.w); } vec4 vec4::operator-() { return vec4(-this->x, -this->y, -this->z, -this->w); } vec4 vec4::operator*(float f) { return vec4(this->x * f, this->y * f, this->z * f, this->z * f); } vec4 vec4::operator/(float f) { return vec4(this->x / f, this->y / f, this->z / f, this->z / f); }
true
7976f34d225cd91f19af31ca242ae4a4f91da737
C++
DevTown/LackEnclosureControler
/_3DDruckerLichtundTempSteuerung/_3DDruckerLichtundTempSteuerung.ino
UTF-8
2,952
2.875
3
[]
no_license
#include <Arduino.h> /********************************************************************/ // First we include the libraries #include <OneWire.h> #include <DallasTemperature.h> #include <Wire.h> #include <LiquidCrystal_I2C.h> /********************************************************************/ // Data wire is plugged into pin 2 on the Arduino #define ONE_WIRE_BUS 2 /********************************************************************/ // Setup a oneWire instance to communicate with any OneWire devices // (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); /********************************************************************/ // Pass our oneWire reference to Dallas Temperature. DallasTemperature sensors(&oneWire); /********************************************************************/ // Setup LCD Display LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display /********************************************************************/ #define ventilatorPIN 10 #define fantoglePIN 3 bool fanon = false; void setup(void) { // start serial port Serial.begin(9600); Serial.println("3D Printing enclosure"); // Start up the library sensors.begin(); lcd.init(); //initialize the lcd //lcd.begin (16,2); lcd.backlight(); //open the backlight //define outputs pinMode(fantoglePIN,INPUT); pinMode(ventilatorPIN,OUTPUT); digitalWrite (ventilatorPIN, LOW); printLCD("3D Printing",0); printLCD("3D Printing",1); //digitalWrite (fantoglePIN, HIGH); //attachInterrupt(digitalPinToInterrupt(fantoglePIN),fantogle,HIGH); } void fantogle() { Serial.println("3fantogle"); if(fanon) { fanon=false; } else { fanon = true; } } void loop(void) { float temp = 0; // call sensors.requestTemperatures() to issue a global temperature // request to all devices on the bus /********************************************************************/ Serial.print(" Requesting temperatures..."); sensors.requestTemperatures(); // Send the command to get temperature readings Serial.println("DONE"); /********************************************************************/ temp = sensors.getTempCByIndex(0); Serial.print("Temp: " + String(temp) ); //Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"? // You can have more than one DS18B20 on the same bus. // 0 refers to the first IC on the wire printLCD("Temp: " + String(temp),0); //lcd.print("Temp: " + String(temp) ); if(digitalRead(fantoglePIN) == HIGH) { fantogle(); } // If temo gets to high we need the Fan if(temp>27 || fanon) { digitalWrite (ventilatorPIN, HIGH); printLCD("Fan: ON ",1); } else { digitalWrite (ventilatorPIN, LOW); printLCD("Fan: OFF",1); } delay(1000); } void printLCD(string message, int line) { lcd.setCursor(0,line); lcd.print(message); }
true
d4f089a7721f02ff864cf93fb8bd36a1ec746f71
C++
seojimin/c-plus-plus-language
/workshop/WS08/in_lab/SavingsAccount.cpp
UTF-8
1,284
3.34375
3
[]
no_license
// Workshop8 in_lab : cpp file // Name : Jimin Seo // Seneca E-mail : jseo22@myseneca.ca // Student number: 145803169 #include <iostream> #include "SavingsAccount.h" using namespace std; namespace sict { // Default constructor SavingsAccount::SavingsAccount() { interRate = 0.0; } //constructor receives a double holding the ***initial account balance*** and a double holding the interest rate to be applied to the balance SavingsAccount::SavingsAccount(double accBal, double inter) : Account(accBal) { if (inter > 0) { interRate = inter; } else { interRate = 0.0; } } //this modifier calculates the interest earned on the current balance and credits the account with that interest. void SavingsAccount::monthEnd() { Currentbal += (Currentbal * interRate); } //receives a reference to an ostream object and inserts the following output on separate lines to the object void SavingsAccount::display(ostream& ostr) const { if ((balance() >= 1.0) && (interRate >= 0.0)) { ostr << "Account type: Savings" << endl; ostr.setf(ios::fixed); ostr.precision(2); ostr << "Balance: $" << balance() << endl; ostr.setf(ios::fixed); ostr.precision(2); ostr << "Interest Rate (%): " << interRate * 100.0 << endl; ostr.unsetf(ios::fixed); } } }
true
f68bad42d980d22e84808d3631729b285d1972a4
C++
ewiggestriger/SSSQsim
/Entity.cpp
UTF-8
976
3.03125
3
[]
no_license
/* * Implementation for the Entity class. * * Created by Steve Kostoff on 2019-03-25. */ #include "Entity.h" int Entity::_nextID = 1; Entity::Entity(Time arrivalTime) { //assign a unique id to the entity and increment the id counter _id = _nextID++; //log the entity arrival time _arrivalTime = arrivalTime; } int Entity::GetID() { return _id; } Entity::Entity() { _id = _nextID++; } void Entity::setDepartureTime(Time departureTime) { //set the departure time _departureTime = departureTime; } void Entity::setServiceStartTime(Time serviceStartTime) { //set service start time and update its private variable _serviceStartTime = serviceStartTime; } Time Entity::getArrivalTime() { //return arrival time return _arrivalTime; } Time Entity::getDepartureTime() { //return the departure time return _departureTime; } Time Entity::getServiceStartTime() { //return the service time return _serviceStartTime; }
true
f8f2efa75dab8802b593793636698460c04a92ca
C++
benbenliu/Data-Structure-Code
/evil hangman/src/Hangman.h
UTF-8
903
3.03125
3
[]
no_license
/*This is the class definition of a hangman game object*/ #ifndef _hangman_h #define _hangman_h #include <unordered_map> #include <vector> #include <string> #include <iostream> #include <fstream> #include <set> using namespace std; class Hangman{ public: Hangman(string & dictionary); void updateCurrentList(); void setGuessTime(int g); void constructPatternMap(string & letter); bool validLength(int length) const; int getGuess() const; void printAttempts() const; void printListSize() const; void printPattern() const; bool validLetter(string & letter) const; bool judgeTheGame() const; void initializePattern(int L); private: int guess; unordered_map<int, set<string>> dict; set<string> current; unordered_map<string,set<string>> patternMap; unordered_map<string, int> patternCounter; set<string> letters; string currentPattern; string defaultPattern; }; #endif // _hangman_h
true
32b7d3b00a6e69f05eba9d62340ddf31c06c0808
C++
alexandraback/datacollection
/solutions_5658282861527040_1/C++/AlexAntonov/solution.cpp
UTF-8
1,052
2.953125
3
[]
no_license
#include <vector> #include <string> #include <map> #include <unordered_map> #include <fstream> #include <algorithm> #include <cassert> #include <iostream> #include <cstdint> using namespace std; struct Case{ int a, b, k; int64_t Solve() { if (a <= k || b <= k) return int64_t(a)*b; int64_t count = 0; for (int i = k; i < a; ++i) for (int j = k; j < b; ++j) if ((i&j) < k) ++count; return count + int64_t(k)*b + int64_t(k)*(int64_t(a) - k); } }; struct Input{ vector<Case> cases; Input(){ ifstream ifs("i"); assert(!ifs.bad()); int case_num; ifs >> case_num; cases.resize(case_num); for (int case_ind = 0; case_ind < case_num; ++case_ind) { Case& cas = cases[case_ind]; ifs >> cas.a >> cas.b >> cas.k; } } }; int main() { Input inp; ofstream ofs("o.txt"); for (size_t i = 0; i < inp.cases.size(); ++i) { int64_t answer = inp.cases[i].Solve(); ofs << "Case #" << (i+1) << ": " << answer << endl; } return 0; }
true
86a2ad16b960e6d40654f2d69054472b4c6b3d95
C++
rafam1899/ZooApplication
/ZooApplication/src/sources/model/Client.cpp
UTF-8
459
2.609375
3
[]
no_license
/* * Client.cpp * * Created on: 08/06/2021 * Author: Tiago Oliveira */ #include "Client.h" int Client::NUMBER = 0; Client::Client(int recint) { this->number = ++NUMBER; this->recintVisited = recint; } Date Client::getDate() { return date; } void Client::setDate(int day, int month, int year) { this->date; } int Client::getRecintVisited() { return recintVisited; } void Client::setRecintVisited(int recint) { this->recintVisited = recint; }
true
a76d4741b650b6e4545b54336735ff6d7fe2c98b
C++
elite-sheep/icpcarchive
/math/scut2017H.cpp
UTF-8
939
2.5625
3
[]
no_license
/************************************************************************* > File Name: scut2017H.cpp > Author: Yuchen Wang > Mail: wyc8094@gmail.com > Created Time: Sun Apr 30 13:27:51 2017 ************************************************************************/ #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<vector> #include<algorithm> using namespace std; const int maxn = 1e5+7; typedef long long ll; ll arr[maxn],h[maxn]; int t,n; int main() { freopen("input","r",stdin); int i; cin >> t; while(t--){ ll ans = 0; cin >> n; for(i=1;i<=n;i++){ scanf("%lld",&arr[i]); h[arr[i]] = i; } for(i=2;i<=n;i++){ ll now = h[i]; ll pre = h[i-1]; if(pre > now) ans += (now*(pre-now)-1); else ans += ((now-pre)*(n-now+1)-1); } if(h[1]>1)ans -= (1ll*(h[1]-1)*(h[1]-2)/2); if(h[1]<n)ans -= (1ll*(n-h[1]-1)*(n-h[1])/2); cout << ans << endl; } return 0; }
true
fbd18589dcd42db529251497a5c044e59a0ed134
C++
dmytrofrolov/Cpp
/Mega_project_list/01_Numbers/13_Distance_Between_Two_Cities/main.cpp
UTF-8
1,599
3.953125
4
[]
no_license
// Distance Between Two Cities - Calculates the distance between // two cities and allows the user to specify a unit of distance. // This program may require finding coordinates for the cities like latitude and longitude. // Dmytro Frolov #include <iostream> #include <cmath> const float EARTH_RADIUS = 6371; const double PI = 3.1415926535; const float DEGREES_IN_CIRCLE = 360; const float KILOMETERS_IN_MILE = 1.609344; double toRad(double angle); using namespace std; int main() { double latitude1 = 49.83, longitude1 = 24.01, latitude2 = 50.45, longitude2 = 30.52, distance = 0; cout << "To calculate distance of two cities\nit is necessary to input lat ang long\nfor both of them\n"; cout << "input latitude 1 : "; cin >> latitude1; cout << "input longitude 1 : "; cin >> longitude1; cout << "input latitude 2 : "; cin >> latitude2; cout << "input longitude 2 : "; cin >> longitude2; cout << "Do you want distance in kilometers - 1 or in miles - 2? \n(1 or 2): "; int units = 0; cin >> units; latitude1=toRad(latitude1); longitude1=toRad(longitude1); latitude2=toRad(latitude2); longitude2=toRad(longitude2); distance=acos(cos(latitude1)*cos(latitude2)*cos(longitude2-longitude1)+sin(latitude1)*sin(latitude2)); distance*=EARTH_RADIUS; cout << "Distance between cities = "; if(units==1) cout << distance << " kilometers." << endl; else cout << distance / KILOMETERS_IN_MILE << " miles." << endl; return 0; } double toRad(double angle) { return angle / DEGREES_IN_CIRCLE * PI * 2; }
true
6dd86e7715a02d3591fceef60b7417d979eecc11
C++
worldofjoni/friendlyConsole
/friendlyConsole/friendlyConsole.cpp
UTF-8
7,656
3.140625
3
[ "BSD-3-Clause" ]
permissive
// ################################################################# // # Library to easily change console colours and much more # // # by Jonatan Ziegler # // ################################################################# #pragma once #include "friendlyConsole.hpp" #include <Windows.h> #include <random> #include <chrono> namespace fc { // declares used variables static HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); static HWND hWindow = GetConsoleWindow(); //functions and structs for cout integration // use in ostream to set color Cmd color(Color color) { return { COLOR, color }; } // use in ostream to set Backgroundcolor Cmd backColor(Color color) { return { BACK_COLOR, color }; } // overloaded Operator for in ostram controll std::ostream& operator<<(std::ostream& os, Cmd cmd) { switch (cmd.action) { case COLOR: fc::setTextColor(cmd.value); break; case BACK_COLOR: fc::setBackgroundColor(cmd.value); break; } return os; } // function to set text color void setTextColor(Color color) { Color data; CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(hStdOut, &info); // gets current coler data = (info.wAttributes & 0xFFF0) | color; // adds wanted color SetConsoleTextAttribute(hStdOut, data); // changes new color } // function to set backgroundcolor void setBackgroundColor(Color color) { Color data; CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(hStdOut, &info); // gets current coler data = (info.wAttributes & 0xFF0F) | (color << 4); // adds wanted color SetConsoleTextAttribute(hStdOut, data); // changes new color } // function that clears the screen inline void clearScreen() { system("cls"); } // function taht clears the screen and sets it to a color void clearScreen(Color color) { setBackgroundColor(color); clearScreen(); } // sets the console title void setTitle(const char name[]) { SetConsoleTitleA(name); } // sets the actual cursor position (equivilent to gotoxy) void setCursorPos(int x, int y) { COORD pos; pos.X = x; pos.Y = y; SetConsoleCursorPosition(hStdOut, pos); } // sets the size of the window in pixel void setWindowSizePX(int width, int height) { RECT r; GetWindowRect(hWindow, &r); MoveWindow(hWindow, r.left, r.top, width, height, false); } // sets the size of the window in chars (and disables Scrolling) void setWindowSize(int width, int height, bool disableScrolling) { if (disableScrolling) { int width_ = (width * 8 + 40); int height_ = (height * 8 + 40); setWindowSizePX(width_, height_); COORD coord; coord.X = width; coord.Y = height; SetConsoleScreenBufferSize(hStdOut, coord); } else { width = (width * 40 + 184)/5; height = (height * 40 + 212)/5; setWindowSizePX(width, height); } } // sets the pos of the window void setWindowPos(int x, int y) { RECT r; GetWindowRect(hWindow, &r); MoveWindow(hWindow, x, y, r.right - r.left, r.bottom - r.top, false); } // returns a random Value int getRandom(int min, int max) { if (min > max) { int i = min; min = max; max = i; } int diff = max - min; std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution<std::mt19937::result_type> dist(0, diff); dist(rng); dist(rng); dist(rng); dist(rng); dist(rng); dist(rng); dist(rng); dist(rng); return dist(rng) + min; } // waits a specific amount of time void waitMs(int ms) { auto t1 = std::chrono::system_clock::now(); while (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - t1).count() < ms); } // waits a specific amout of time or until functionreturns true void waitMsWithInterupt(int ms, bool(*func)()) { auto t1 = std::chrono::system_clock::now(); while (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - t1).count() < ms) { if (func()) return; } } // overrides the given variables width the actual cursor Position void getCursorPosition(int& x, int& y) { CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(hStdOut, &info); x = info.dwCursorPosition.X; y = info.dwCursorPosition.Y; } // Hides Cursor void hideCursor() { CONSOLE_CURSOR_INFO info; GetConsoleCursorInfo(hStdOut, &info); info.bVisible = false; SetConsoleCursorInfo(hStdOut, &info); } // Shows Cursor void showCursor() { CONSOLE_CURSOR_INFO info; GetConsoleCursorInfo(hStdOut, &info); info.bVisible = true; SetConsoleCursorInfo(hStdOut, &info); } // beeps width Note as freq, default duration 300 void beep(int freq, int duration) { Beep(freq, duration); } // plays file at relative path void playSound(const char file[]) { PlaySoundA(file, NULL, SND_ASYNC); } // same as playSound, but repeats until stopSound void playSoundRepeat(const char file[]) { PlaySoundA(file, NULL, SND_ASYNC | SND_LOOP); } // same as playSound, but returns not until sound finished void playSoundWait(const char file[]) { PlaySoundA(file, NULL, SND_SYNC); } // stops playing sound void stopSound() { PlaySoundA(NULL, NULL, NULL); } // returns current path, Note: in VS *Debugger* this is NOT the .exe path! std::string getPath() { char* pszFileName = NULL; char path[200]; GetFullPathNameA(".", 200, path, &pszFileName); return std::string(path); } // opens file explorer at path void openExplorer(const char path[]) { ShellExecuteA(NULL, "explore", path, NULL, NULL, SW_SHOWDEFAULT); } void openExplorer(std::string path) { openExplorer(path.c_str()); } // opens default browser at url void openBrowser(const char url[]) { ShellExecuteA(NULL, "open", url, NULL, NULL, SW_SHOWDEFAULT); } void openBrowser(std::string url) { openBrowser(url.c_str()); } bool isKeyPressed(int key) { short s = GetKeyState(key); return (s & (1 << sizeof(short) * 8)); } bool isKeyPressed(char vKey) { int _key = VkKeyScanExA(vKey, LoadKeyboardLayoutA("0000080", NULL)); _key &= 0x00FF; // if is Key is Number (0-9) also convert to NumpadKey int key_alt = _key; if (key_alt >> 4 == 0x3) { key_alt &= 0x0F; key_alt |= 0x60; if (isKeyPressed(key_alt)) return true; } return isKeyPressed(_key); } void getFontSize(int& x, int& y) { CONSOLE_FONT_INFO info; bool b = GetCurrentConsoleFont(hStdOut, false, &info); COORD c = GetConsoleFontSize(hStdOut, info.nFont); x = c.X; y = c.Y; } bool setFont(const wchar_t font[32]) { CONSOLE_FONT_INFOEX info; info.cbSize = sizeof(info); if (!GetCurrentConsoleFontEx(hStdOut, false, &info)) return false; info.FontFamily = wcscmp(font, L"Terminal") == 0 ? 48 : 54; for (int i = 0; i < 32; i++) info.FaceName[i] = font[i]; if (!SetCurrentConsoleFontEx(hStdOut, false, &info)) return false; return true; } bool setFontSize(int width, int height) { CONSOLE_FONT_INFOEX info; info.cbSize = sizeof(info); if (!GetCurrentConsoleFontEx(hStdOut, false, &info)) return false; if (height == 0) // for only a size { info.dwFontSize.Y = width; } else // for width and height { info.dwFontSize.X = width; info.dwFontSize.Y = height; } if (!SetCurrentConsoleFontEx(hStdOut, false, &info)) return false; return true; } bool setBold(bool bold) { CONSOLE_FONT_INFOEX info; info.cbSize = sizeof(info); if (!GetCurrentConsoleFontEx(hStdOut, false, &info)) return false; info.FontWeight = bold ? 700 : 400; if (!SetCurrentConsoleFontEx(hStdOut, false, &info)) return false; return true; } }
true
27c136217aca0e96c87095fb08b46417b627c3d2
C++
REDE453/Practice
/test5/test5/test.cpp
GB18030
753
3.640625
4
[]
no_license
//һöжϸöǷƽ //ֻҪƽԣҪDz class Solution { public: int Depth(TreeNode* pRoot) { if (pRoot == nullptr) return 0; int leftDepth = Depth(pRoot->left); int rightDepth = Depth(pRoot->right); return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1; } bool IsBalanced_Solution(TreeNode* pRoot) { if (pRoot == nullptr) return true; int leftDepth = Depth(pRoot->left); int rightDepth = Depth(pRoot->right); //жϵǰ return abs(leftDepth - rightDepth) < 2 //ݹж && IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right); } };
true
9fea67f07d4554a6014f15673996f4fa5ae4b51b
C++
suhasjvrundavan/Data-Structures-Algorithm-in-CPP
/Mathemetics/printPrimeFactors.cpp
UTF-8
1,777
3.5625
4
[]
no_license
Sample Input: 12 Sample Output: 2 2 3 Solution: Naive Solution: #include <bits/stdc++.h> using namespace std; bool isPrime(int n) { if(n==1) return false; if(n==2 || n==3) return true; if(n%2 == 0 || n%3 == 0) return false; for(int i=5;i*i<=n;i=i+6) { if(n%i == 0 || n%(i+2) == 0) return false; } return true; } void primeFactors(int n) { for(int i=2;i<n;i++) { if(isPrime(i)) { int x=i; while(n%x ==0) { cout<<i<<" "; x=x*i; } } } } int main() { int n; cin>>n; primeFactors(n); return 0; } Optimised Solution: #include <bits/stdc++.h> using namespace std; void printPrimeFactors(int n) { if(n<=1) return; for(int i=2;i*i<=n;i++) { while(n%i==0) { cout<<i<<" "; n=n/i; } } if(n>1) cout<<n<<" "; } int main() { int n; cin>>n; printPrimeFactors(n); return 0; } Most Optimised Solution: #include <bits/stdc++.h> using namespace std; void printPrimeFactors(int n) { if(n<=1) return; while(n%2 == 0) { cout<<2<<" "; n=n/2; } while(n%3 == 0) { cout<<3<<" "; n=n/3; } for(int i=5;i*i<=n;i=i+6) { while(n%i==0) { cout<<i<<" "; n=n/i; } while(n%(i+2) ==0) { cout<<(i+2)<<" "; n=n/(i+2); } } if(n>3) cout<<n<<" "; } int main() { int n; cin>>n; printPrimeFactors(n); return 0; }
true
76259608a5c8ff369e412ce9e71e7db24f229fde
C++
FlandiaYingman/15-year-old-Konjac-wants-to-learn-OI
/15-year-old-Konjac/resolved/luogu/1032.cpp
UTF-8
2,053
3.15625
3
[]
no_license
//P1032 字串变换 #include <iostream> #include <string> #include <queue> #include <vector> #include <algorithm> #include <set> #include <fstream> using namespace std; struct transform_rule { string from, to; }; struct transform_string { string val; int transform_times; }; vector<transform_string> transform(const transform_string &s, const transform_rule &rule); void bfs(queue<transform_string> &q); string finish; vector<transform_rule> rules; set<string> appeared; //ifstream fin("testdata.in"); //#define cin fin int main() { string start; cin >> start >> finish; while (!cin.eof()) { string from, to; cin >> from >> to; if (!(from.empty() && to.empty())) { rules.push_back({from, to}); } } queue<transform_string> q; q.push({start, 0}); bfs(q); return 0; } void bfs(queue<transform_string> &q) { while (!q.empty()) { transform_string s = q.front(); q.pop(); if (s.transform_times > 10) { cout << "NO ANSWER!"; return; } if (s.val == finish) { cout << s.transform_times; return; } for (int i = 0; i < rules.size(); i++) { vector<transform_string> v = transform(s, rules[i]); for (int j = 0; j < v.size(); j++) { if (appeared.find(v[j].val) == appeared.end()) { appeared.insert(v[j].val); q.push(v[j]); } } } } cout << "NO ANSWER!"; return; } vector<transform_string> transform(const transform_string &s, const transform_rule &rule) { vector<transform_string> v; int times = s.transform_times + 1; string val = s.val; size_t pos = val.find(rule.from, 0); while (pos != string::npos) { string str(val); str.replace(pos, rule.from.length(), rule.to); v.push_back({str, times}); pos = val.find(rule.from, pos + rule.from.length()); } return v; }
true
4421c730dc8d7e88476f3c8212e7de4443ec4d90
C++
WYX11111/Data-Structures
/中缀表达式/中缀.cpp
GB18030
5,046
3.671875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 #define STACK_INIT_SIZE 100 typedef struct { double *elem; int top; int stacksize; } NUMStack; typedef struct { char *elem; int top; int stacksize; } CHARStack; void InitStack_NUM(NUMStack &S, int maxsize = STACK_INIT_SIZE) { S.elem = new double[maxsize]; S.top = -1; S.stacksize = maxsize; } void InitStack_CHAR(CHARStack &S, int maxsize = STACK_INIT_SIZE) { S.elem = new char[maxsize]; S.top = -1; S.stacksize = maxsize; } bool GetTop_NUM(NUMStack S, double &e) { if(S.top == -1) return FALSE; e = S.elem[S.top]; return TRUE; } bool GetTop_CHAR(CHARStack S, char &e) { if(S.top == -1) return FALSE; e = S.elem[S.top]; return TRUE; } void Push_NUM(NUMStack &S, double e) { S.top++; S.elem[S.top] = e; } void Push_CHAR(CHARStack &S, char e) { S.top++; S.elem[S.top] = e; } bool Pop_NUM(NUMStack &S, double &e) { if(S.top == -1) return FALSE; e = S.elem[S.top--]; return TRUE; } bool Pop_CHAR(CHARStack &S, char &e) { if(S.top == -1) return FALSE; e = S.elem[S.top]; S.top--; return TRUE; } bool StackEmpty_NUM(NUMStack S) { if(S.top == -1) return TRUE; else return FALSE; } bool StackEmpty_CHAR(CHARStack S) { if(S.top == -1) return TRUE; else return FALSE; } int StackLength_NUM(NUMStack S) { return (S.top + 1); } int StackLength_CHAR(CHARStack S) { return (S.top + 1); } int opmember(char c) { if(c == '+' || c == '-' || c == '*' || c == '/') return 1; if(c == '(' ) return 2; if(c == ')' ) return 3; else return 0; } int getpre(char c) //øȼ { if(c == '#' ) return -1; if(c == '(' ) return 0; if(c == '+' || c == '-') return 1; if(c == '*'|| c == '/') return 2; if(c == ')' ) return 3; } bool compare(char a,char b) { if(getpre(a) >= getpre(b)) return 1; else return 0; } bool isnum(char c) { if(c >= '0' && c <= '9')return 1; else return 0; } bool islogic(char *s) //жһʽǷϷ { int len = strlen(s); int l=0,r=0;//ڼ¼Ÿ if(opmember(s[0] == 1 || opmember(s[0]) == 3) )//ͷţϷ return 0; if(opmember(s[len-1]) == 1 || opmember(s[len-1] == 2)) //βţϷ return 0; for(int i=0; i<len-1; i++) { if(s[i]=='(') l++; if(s[i]==')') r++; if(opmember(s[i]) == 3 && isnum (s[i+1]) == 1 ) return 0; //źֱӽ֣Ϸ if(opmember(s[i]) == 1 && opmember(s[i+1]) == 1 ) return 0; //Ϸ if(opmember(s[i]) == 1 && opmember(s[i+1]) == 3 ) return 0; //ţϷ if(opmember(s[i]) == 2 && opmember(s[i+1]) == 3 ) return 0; //ŽţϷ if(isnum(s[i]) == 1 && opmember(s[i+1]) == 2) return 0; //ֺţϷ if(s[i]=='/' && s[i+1]=='0') return 0; //0Ϸ } if(s[len-1] == ')' ) r++; if(l != r) return 0; //ȣϷ return 1; } double operate(double a,char op,double b) { if(op == '+') return a+b; if(op=='-') return a-b; if(op=='*') return a*b; if(op=='/') return a/b; } void transform(CHARStack &op, char *suffix, char *s) { InitStack_CHAR(op); Push_CHAR(op,'#'); int i=0,k=0; char ch=s[0],c; while(!StackEmpty_CHAR(op)) { if(isnum(ch)) suffix[k++]=ch; else { suffix[k++]=' '; switch(ch) { case'(':Push_CHAR(op,ch);break; case')': { Pop_CHAR(op,c); while( c != '(' ) { suffix[k++]=c; Pop_CHAR(op,c); } break; } default: { while(GetTop_CHAR(op,c) && (compare(c,ch)) ) { suffix[k++] = c; Pop_CHAR(op,c); } if(ch!='#') Push_CHAR(op,ch); break; }//default }//switch }//else if(ch!='#'){ i++; ch=s[i]; } }//while suffix[k]='\0'; }//transform void calculate(NUMStack &num,char *suffix) { double num1,num2,num3,cur,ans; int flag; InitStack_NUM(num); int len = strlen(suffix),i = 0; while(i<len) { if(suffix[i] == ' ') { i++; continue; } else if(suffix[i]=='#') break; else { cur=0; flag=0; while(isnum(suffix[i])) { cur*=10; cur+=suffix[i++]-'0'; flag=1; } if(flag) { Push_NUM(num,cur); } if(suffix[i]==' ') { i++; continue; } if(opmember(suffix[i])==1) { Pop_NUM(num,num1); Pop_NUM(num,num2); num3=operate(num2,suffix[i++],num1); Push_NUM(num,num3); } } } Pop_NUM(num,ans); printf("%.2lf\n",ans); } int main() { NUMStack num; CHARStack op; char suffix[101],s[101]; while(scanf("%s",s)!='\0') { memset(suffix,0,sizeof(suffix)); int len=strlen(s); if(!islogic(s)) printf("ʽ!\n"); else { s[len]='#'; transform(op,suffix,s); calculate(num,suffix); } } return 0; }
true
3a2ee024ea94ce34819a1bc547c94c448a850cbe
C++
alu0100769609/aedaP1
/hpp/Queue.hpp
UTF-8
826
3.5625
4
[]
no_license
#include "Node.hpp" class Queue { private: Node* first_; //Pointer to the first element Node* last_; //Pointer to the last element public: Queue(void); //Constructor ~Queue(void); //Destructor bool empty(void); //Check if empty queue void setFirst(Node* first); //Set pointer to the first node Node* getFirst(void); //Get pointer to the first element void setLast(Node* last); //Set pointer to the last node Node* getLast(void); //Get pointer to the last element void setHead(TDATO element); //Set element from head void deleteLast(void); //Delete node from tail void printItems(void); //Print the queue of elements };
true
c165946567a4083cb7ab78f96f23d6445b334615
C++
BadHatHoffman/CSC195
/Containers/main.cpp
UTF-8
2,648
3.609375
4
[]
no_license
// Containers.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <array> #include <vector> #include <string> #include <list> #include <algorithm> using namespace std; typedef float currency; //using currency = double; void print(int* n, size_t count) { for (int i = 0; i < count; i++) { cout << n[i] << " "; } cout << endl; } void print(const array<int, 4>& na) { for (int i = 0; i < na.size(); i++) { cout << na[i] << " "; } cout << endl; } class Runner { public: Runner() {} Runner(string name, float time) : name(name), time(time) {} string getName() const { return name; } friend bool operator == (const Runner& runner, string name) { return (runner.name == name); } friend bool operator < (const Runner& runner1, const Runner& runner2) { return (runner1.time < runner2.time); } friend ostream& operator << (ostream& stream, const Runner& runner) { stream << runner.name << " " << runner.time << endl; return stream; } protected: string name; float time; }; int main() { auto i = 5; currency dollars = 4.65f; int n[] = { 1,2,3,4,5,6, 7}; cout << n[1] << endl; print(n, 7); array<int, 4> na = { 32,52,12,67 }; cout << na.size() << endl; cout << na.front() << endl; na.fill(0); print(na); cout << na.at(0) << endl; list<string> strings = {"hi " , "my " , "name ", "is ", "Ethan "}; strings.push_back("Hoffman "); auto iter = strings.begin(); iter = strings.erase(iter); iter++; cout << *iter << endl; strings.remove("name"); //strings.reverse(); //strings.sort(); for (string str : strings) { cout << str << ""; } cout << endl; vector<int> numbers { 1,7,3,8,4 }; vector<int>::iterator niter = find(numbers.begin(), numbers.end(), 3); cout << *niter << endl; numbers.erase(niter); sort(numbers.begin(), numbers.end(), greater<int>()); for (int i : numbers) { cout << i << " "; } cout << endl; for (auto iter = numbers.begin(); iter != numbers.end(); iter++) { cout << *iter << " "; } cout << endl; vector<Runner> runners = { { "felix", 5.2f} ,{"bolt", 4.5} ,{"johnson", 4.8} }; auto riter =find(runners.begin(), runners.end(), "bolt"); cout << (*riter).getName() << endl; sort(runners.begin(), runners.end()); for (Runner runner : runners) { cout << runner; } }
true
30997d9febd0da4070732ab93380cbacda4a8698
C++
Philpo/Cork
/src/Cork/Cork/CollisionResolver.h
UTF-8
738
3
3
[]
no_license
#pragma once #include <functional> #include "GameObject.h" #include "Message.h" typedef std::function<void(const GameObject&, const GameObject&)> ResolvingFunction; /** * static class to be handle collision resolution * reolving function must be passed in before use */ class CollisionResolver { public: CollisionResolver() = delete; CollisionResolver(CollisionResolver& toCopy) = delete; ~CollisionResolver() = delete; CollisionResolver& operator=(CollisionResolver& rhs) = delete; static void setResolvingFunction(ResolvingFunction func) { function = func; } static void resolveCollision(const GameObject& lhs, const GameObject& rhs) { if (function) function(lhs, rhs); } private: static ResolvingFunction function; };
true
5a4252a2afc18ed3d8e1df862bfcd6d8e4472c83
C++
Liurunex/Leetcode
/437_Path Sum III.cpp
UTF-8
815
3.40625
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int pathSum(TreeNode* root, int sum) { if (!root) return 0; int left_root = pathSum(root->left, sum); int right_root = pathSum(root->right, sum); int itself = helperdfs(root, sum, 0); return left_root + right_root + itself; } int helperdfs(TreeNode* node, int& target, int cursum) { if (!node) return 0; int sum = cursum + node->val; return (sum == target ? 1:0) + helperdfs(node->left, target, sum) + helperdfs(node->right, target, sum); } }; /* the idea: just do dfs to all subtree, that is we make dfs on both of left and right subtrees, * and sum them up */
true
fd436fabd75143cf66f3f790939668206efb2ac2
C++
inbei/libutl
/ubc/HostOS.h
UTF-8
3,800
2.53125
3
[ "MIT" ]
permissive
#pragma once //////////////////////////////////////////////////////////////////////////////////////////////////// #include <libutl/Array.h> #include <libutl/Pathname.h> //////////////////////////////////////////////////////////////////////////////////////////////////// UTL_NS_BEGIN; //////////////////////////////////////////////////////////////////////////////////////////////////// /** Abstraction for common OS functionality. \author Adam McKee \ingroup hostos */ //////////////////////////////////////////////////////////////////////////////////////////////////// class HostOS : public Object { UTL_CLASS_DECL_ABC(HostOS, Object); UTL_CLASS_DEFID; public: /** Set the current working directory. \param path new current working directory */ virtual void chdir(const Pathname& path) = 0; /** Become a system/daemon process. */ virtual void daemonInit() = 0; /// \name Process Management //@{ /** Run an executable with specified parameters. \return exit code of given executable \param path pathname of executable to run \param args parameters to run executable with */ virtual int run(const Pathname& path, const TArray<String>& args) = 0; /** A front-end for the virtual run(). From the given string, it determines the executable path and the parameters, and invokes run(path,args). If you want to pass a parameter that contains whitespace, you must enclose it in double quotes, just as you would do with the shell. \return exit code of command \param cmd command to execute */ int run(const String& cmd); //@} /// \name Sleeping //@{ /** Sleep for the given number of milliseconds. */ void msleep(uint64_t msec) const { usleep(msec * (uint64_t)1000); } /** Sleep for the given number of seconds. */ virtual void sleep(uint_t sec) const = 0; /** Sleep for the given number of seconds and microseconds. */ void sleep(uint_t sec, uint_t usec) const { sleep(sec); usleep(usec); } /** Sleep for the given number of microseconds. */ virtual void usleep(uint64_t usec) const = 0; /** Yield the processor to some other process that wants to run. */ virtual void yield() const; //@} /// \name Environment //@{ /** Get an environment variable. \return value of environment variable (empty string if undefined) */ virtual String getEnv(const String& envVarName) const = 0; /** Set an environment variable. \return old value of environment variable \param envVarName environment variable name \param envVarVal new value of environment variable */ virtual String setEnv(const String& envVarName, const String& envVarVal) = 0; /** Remove an environment variable. \return old value of environment variable \param envVarName environment variable name */ virtual String remEnv(const String& envVarName) = 0; //@} }; //////////////////////////////////////////////////////////////////////////////////////////////////// /** Global pointer to HostOS-derived object. \ingroup hostos */ #if UTL_HOST_TYPE == UTL_HT_UNIX class LinuxHostOS; extern LinuxHostOS* hostOS; #elif UTL_HOST_TYPE == UTL_HT_WINDOWS class WindowsHostOS; extern WindowsHostOS* hostOS; #else extern HostOS* hostOS; #endif //////////////////////////////////////////////////////////////////////////////////////////////////// UTL_NS_END; //////////////////////////////////////////////////////////////////////////////////////////////////// #if UTL_HOST_TYPE == UTL_HT_UNIX #include <libutl/LinuxHostOS.h> #else #include <libutl/WindowsHostOS.h> #endif
true
3372ac0b78dfe67d5855e0c3a84843c1ae20486a
C++
tanmay777/DSA-Implementations
/DynamicProgramming/fibonacci_dp.cpp
UTF-8
526
2.921875
3
[]
no_license
#include<iostream> #include<string> using namespace std; long memo[1000]; long fib(long n){ /* if(n==0) return 0; if(n==1) return 1; if(memo[n]!=-1) { return memo[n]; } long ans= (fib(n-1)+fib(n-2)); memo[n]=ans; return ans;*/ int dp[1000]={0}; dp[0]=0; dp[1]=1; for(int i=2;i<=n;i++) dp[i]=dp[i-1]+dp[i-2]; return dp[n]; } int main(void){ int n; cin>>n; for(int i=0;i<=1000;i++) memo[i]=-1; cout<<fib(n)<<endl; return 0; }
true
7e53304a4aee5524a43990a86c150b6cfe9c42e9
C++
alessioprestileo/ALEPCAD
/shaderhelper.cpp
UTF-8
774
3
3
[]
no_license
#include "shaderhelper.h" ShaderHelper::ShaderHelper() {} // Read a shader source from a file, // store the shader source in the input buffer // and return reference to the buffer const char* ShaderHelper::readShaderSrc(const char *pathToShader, std::vector<char> &buffer) { QFile file(pathToShader); if(!file.open(QIODevice::ReadOnly)) { QString message = "Error opening file "; message.append(QString(pathToShader)); QMessageBox::information(0, "Error", message); } QTextStream inStr(&file); while(!inStr.atEnd()) { char c; inStr >> c; buffer.push_back(c); } file.close(); buffer.push_back('\0'); const char *content = &buffer[0]; return content; }
true
b3b21bc064908bcc421e3a01aca628cd53ef2c91
C++
jk983294/CommonScript
/cpp/lib/gbench/multi_argument_bench.cpp
UTF-8
1,556
3.125
3
[]
no_license
#include <benchmark/benchmark.h> #include <vector> using namespace std; void transpose(vector<int> &matrix, int row, int column) { for (int i = 0; i < row * column; i++) { int targetPos = (i + (row * column - 1) * (i % row)) / row; while (targetPos < i) { targetPos = (targetPos + (row * column - 1) * (targetPos % row)) / row; } std::swap(matrix[i], matrix[targetPos]); } } void ConstructMatrix(vector<int> &matrix, int row, int column) { matrix.resize(row * column); for (int i = 0; i < row * column; ++i) { matrix[i] = i; } } /** * multi dimension argument */ void bench_matrix_transpose(benchmark::State &state) { vector<int> matrix; ConstructMatrix(matrix, state.range(0), state.range(1)); for (auto _ : state) { transpose(matrix, state.range(0), state.range(1)); } } BENCHMARK(bench_matrix_transpose) ->Args({1 << 8, 128}) ->Args({1 << 9, 128}) ->Args({1 << 10, 128}) ->Args({1 << 11, 128}) ->Args({1 << 8, 512}) ->Args({1 << 9, 512}) ->Args({1 << 10, 512}) ->Args({1 << 11, 512}); /** * use range */ // BENCHMARK(bench_matrix_transpose)->Ranges({{1<<8, 1<<11}, {128, 512}}); /** * for more complex patterns of inputs, passing a custom function */ // void CustomArguments(benchmark::internal::Benchmark* b) { // for (int i = 8; i <= 11; ++i) // for (int j = 128; j <= 512; j *= 2) // b->Args({1<<i, j}); //} // BENCHMARK(bench_matrix_transpose)->Apply(CustomArguments); BENCHMARK_MAIN();
true
e50be2725e73232b59814569dd8b8f81752daed6
C++
alexandraback/datacollection
/solutions_1483488_0/C++/Moldot/C_Recycled_Numbers.cpp
UTF-8
851
3.078125
3
[]
no_license
/* Grader: Codejam - Qualification Round 2012 C Recycled Numbers Varot Premtoon 14 Apr 2555 */ #include <cstdio> int ab[10000000]; int sol(int cse) { int i,j; int a,b; int x,y,num[10],n; long long sum = 0; scanf("%d %d",&a,&b); for(;a<=b;a++) { x = a; for(n=0;x>0;x/=10) num[n++] = x%10; for(j=0,y=0;j<n;j++) { for(i=j,x=0;i<j+n;i++) x = (x*10) + num[i%n]; if(x>y) y = x; } //printf("%d = %d\n",a,y); ab[y]++; } for(i=0;i<1000000;i++) { sum += (long long)(ab[i]*(ab[i]-1)) / 2; ab[i] = 0; } printf("Case #%d: %I64d\n",cse,sum); return 0; } int main() { int t,i; scanf("%d",&t); for(i=0;i<10000000;i++) ab[i] = 0; for(i=1;i<=t;i++) sol(i); return 0; }
true
df1f470fa1a894b29384ab09cc2ddf1532e8c3ce
C++
LeeGyeongHwan/Algorithm_Student
/SW_Expert_Academy/D1/sw_2056.cpp
UTF-8
1,317
3.03125
3
[]
no_license
/* 난이도 : D1 문제 번호 : 2056 문제 제목 : 연월일 달력 풀이 날짜 : 2020-02-03 Solved By Reamer */ #include <iostream> using namespace std; int main() { int testCase, month, day; string ymd, year; cin >> testCase; for (int i = 0; i < testCase; i++) { bool isvalid = true; string answer = ""; cin >> ymd; year = ymd.substr(0, 4); month = stoi(ymd.substr(4, 2)); day = stoi(ymd.substr(6, 2)); if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { if (!(day >= 1 && day <= 31)) isvalid = false; } else if (month == 4 || month == 6 || month == 9 || month == 11) { if (!(day >= 1 && day <= 30)) isvalid = false; } else if (month == 2) { if (!(day >= 1 && day <= 28)) isvalid = false; } else isvalid = false; if (!isvalid) answer = "-1"; else { answer += year + "/" + ymd.substr(4, 2) + "/" + ymd.substr(6, 2); } cout << "#" << (i + 1) << " " << answer << endl; } return 0; }
true
d8eb736fe540332b3811665fdd70689bafce8857
C++
andrewlegault/CPSC-585-Game-Project
/cpsc585/cpsc585/Waypoint.cpp
UTF-8
884
2.765625
3
[]
no_license
#include "Waypoint.h" Waypoint::Waypoint(IDirect3DDevice9* device) { radius = 20; drawable = new Drawable(WAYPOINT, "checker.dds", device); wpPosition = hkVector4(0,0,0); } Waypoint::~Waypoint(void) { } void Waypoint::setPosAndRot(float posX, float posY, float posZ, float rotX, float rotY, float rotZ) // In Radians { drawable->setPosAndRot(posX, posY, posZ, rotX, rotY, rotZ); wpPosition(0) = posX; wpPosition(1) = posY; wpPosition(2) = posZ; } void Waypoint::update() { // Do nothing } float Waypoint::getRadius() { return radius; } void Waypoint::setRadius(float newRadius) { radius = newRadius; } bool Waypoint::withinWaypoint(const hkVector4* position) { hkSimdReal distance = wpPosition.distanceTo(*position); hkBool32 distanceLessThanRadius = distance.isLess(radius); if(distanceLessThanRadius){ return true; } else{ return false; } }
true
2deb99b63f2e08b810a4a3d22d23feb3711dac1d
C++
stas/exorcyber
/ks/threadlib.h
UTF-8
600
2.796875
3
[]
no_license
#pragma once class thread { public: typedef void (*proc)(void* prm); private: void* lData; proc p; void start(void* prm); public: //create thread and start it thread(proc p, void* prm = NULL) : p((proc)p) { start(prm); } template<class T> thread(void (*p)(T* prm), T& prm) : p((proc)p) { start((void*)&prm); } template<class T> thread(void (*p)(T* prm)) : p((proc)p) { start(NULL); } ~thread() { if(running) abort(); } //args: number-of-threads, thread*, thread*, ... //returns: index of thread who woke up static int waitOne(int nt, ...); bool running; void abort(); void wait(); };
true
71232a551760d4bf137f1ce2440087acfd1b3741
C++
simhem1/Info2
/u1/a1/Simple_class.cpp
UTF-8
207
2.53125
3
[]
no_license
#include "Simple_class.hpp" Simple_class::Simple_class(int val) : data(val) { } Simple_class::~Simple_class(){ } int Simple_class::get(){ return data; } void Simple_class::set(int in){ data=in; }
true
40870bbacf484cbf346912d0634b5f945ffdea1b
C++
bbc/bbcat-audioobjects
/src/Playlist.h
UTF-8
8,796
2.796875
3
[ "MIT" ]
permissive
#ifndef __SIMPLE_PLAYLIST__ #define __SIMPLE_PLAYLIST__ #include <vector> #include <bbcat-base/ThreadLock.h> BBC_AUDIOTOOLBOX_START class SoundFileSamples; class Playlist { public: Playlist(); ~Playlist(); /*--------------------------------------------------------------------------------*/ /** Return whether the playlist is empty */ /*--------------------------------------------------------------------------------*/ bool Empty() const {return (list.size() == 0);} /*--------------------------------------------------------------------------------*/ /** Add file to list * * @note object will be DELETED on destruction of this object! */ /*--------------------------------------------------------------------------------*/ void AddFile(SoundFileSamples *file); /*--------------------------------------------------------------------------------*/ /** Clear playlist */ /*--------------------------------------------------------------------------------*/ void Clear(); /*--------------------------------------------------------------------------------*/ /** Enable/disable looping */ /*--------------------------------------------------------------------------------*/ void EnableLoop(bool enable = true) {loop_all = enable;} /*--------------------------------------------------------------------------------*/ /** Get whether looping is enabled */ /*--------------------------------------------------------------------------------*/ bool IsLoopEnabled() const {return loop_all;} /*--------------------------------------------------------------------------------*/ /** Enable/disable looping of each file */ /*--------------------------------------------------------------------------------*/ void EnableLoopFile(bool enable = true) {loop_file = enable;} /*--------------------------------------------------------------------------------*/ /** Get whether looping of each file is enabled */ /*--------------------------------------------------------------------------------*/ bool IsLoopFileEnabled() const {return loop_file;} /*--------------------------------------------------------------------------------*/ /** Enable/disable autoplay of each file */ /*--------------------------------------------------------------------------------*/ void EnableAutoPlay(bool enable) {autoplay = enable;} /*--------------------------------------------------------------------------------*/ /** Get whether autoplay of each file is enabled */ /*--------------------------------------------------------------------------------*/ bool IsAutoPlayEnabled() const {return autoplay;} /*--------------------------------------------------------------------------------*/ /** Pause/unpause audio */ /*--------------------------------------------------------------------------------*/ void PauseAudio(bool enable = true); /*--------------------------------------------------------------------------------*/ /** Get whether autoplay of each file is enabled */ /*--------------------------------------------------------------------------------*/ bool IsAudioPaused() const {return pause;} /*--------------------------------------------------------------------------------*/ /** Release playback of audio that is current held */ /*--------------------------------------------------------------------------------*/ void ReleasePlayback() {releaseplayback = true;} /*--------------------------------------------------------------------------------*/ /** Reset to start of playback list */ /*--------------------------------------------------------------------------------*/ void Reset(); /*--------------------------------------------------------------------------------*/ /** Move onto next file (or stop if looping is disabled) */ /*--------------------------------------------------------------------------------*/ void Next(); /*--------------------------------------------------------------------------------*/ /** Return whether the end of the playlist has been reached */ /*--------------------------------------------------------------------------------*/ bool AtEnd() const {return (it == list.end());} /*--------------------------------------------------------------------------------*/ /** Return current file or NULL if the end of the list has been reached */ /*--------------------------------------------------------------------------------*/ SoundFileSamples *GetFile(); /*--------------------------------------------------------------------------------*/ /** Return max number of audio channels of playlist */ /*--------------------------------------------------------------------------------*/ uint_t GetMaxOutputChannels() const; /*--------------------------------------------------------------------------------*/ /** Return number of objects in playlist */ /*--------------------------------------------------------------------------------*/ uint_t GetCount() const {return (uint_t)list.size();} /*--------------------------------------------------------------------------------*/ /** Return current playback position (in samples) */ /*--------------------------------------------------------------------------------*/ uint64_t GetPlaybackPosition() const; /*--------------------------------------------------------------------------------*/ /** Return length of playlist in samples */ /*--------------------------------------------------------------------------------*/ uint64_t GetPlaybackLength() const {return playlistlength;} /*--------------------------------------------------------------------------------*/ /** Set current playback position (in samples) * * @note setting force to true may cause clicks! * @note setting force to false causes a fade down *before* and a fade up *after* * changing the position which means this doesn't actually change the position straight away! */ /*--------------------------------------------------------------------------------*/ bool SetPlaybackPosition(uint64_t pos, bool force); /*--------------------------------------------------------------------------------*/ /** Return current index in playlist */ /*--------------------------------------------------------------------------------*/ uint_t GetPlaybackIndex() const; /*--------------------------------------------------------------------------------*/ /** Return maximum index in playlist * * @note this is ONE LESS than GetCount() */ /*--------------------------------------------------------------------------------*/ uint_t GetPlaybackCount() const; /*--------------------------------------------------------------------------------*/ /** Move to specified playlist index * * @note setting force to true may cause clicks! * @note setting force to false causes a fade down *before* and a fade up *after* * changing the position which means this doesn't actually change the position straight away! */ /*--------------------------------------------------------------------------------*/ bool SetPlaybackIndex(uint_t index, bool force); /*--------------------------------------------------------------------------------*/ /** Read samples into buffer * * @param dst destination sample buffer * @param channel offset channel to read from * @param channels number of channels to read * @param frames maximum number of frames to read * * @return actual number of frames read */ /*--------------------------------------------------------------------------------*/ uint_t ReadSamples(Sample_t *dst, uint_t channel, uint_t channels, uint_t frames); protected: /*--------------------------------------------------------------------------------*/ /** Set current playback position (in samples) */ /*--------------------------------------------------------------------------------*/ bool SetPlaybackPositionEx(uint64_t pos); protected: ThreadLockObject tlock; std::vector<SoundFileSamples *> list; std::vector<SoundFileSamples *>::iterator it; uint64_t filestartpos, playlistlength; uint64_t newposition; uint_t fadesamples; uint_t fadedowncount; uint_t fadeupcount; bool autoplay; bool loop_all; bool loop_file; bool pause; bool releaseplayback; bool positionchange; }; BBC_AUDIOTOOLBOX_END #endif
true
e7b428e1f0c8055a82b59300688d04af0f5395c1
C++
5l1v3r1/IEEE-Robotics
/ROBOT_2014/TestingGround/demo/lib/motors.h
UTF-8
1,541
3.28125
3
[]
no_license
#ifndef MOTORS_H #define MOTORS_H #include <Arduino.h> //Define the Pins---------- //Motor Pair 1 (ON THE LEFT SIDE) /* #define DIRECTION_LEFT 26 //Direction #define PWM_LEFT 3 //Speed //Motor Pair 2 (ON THE RIGHT SIDE) #define DIRECTION_RIGHT 28 //Direction #define PWM_RIGHT 4 //Speed */ //Enum for specifying direction to move in enum Direction { FORWARD = 1, BACKWARD }; //Enum for specifying the direction to turn in enum Turn { LEFT = 1, RIGHT }; //~Class for moving all of the motors at once class Motors { //================================================== //~~PIN INFORMATION================================= //================================================== /* Connections: - Pin 3 ---> PWM for left motors - Pin 8 ---> DIRECTION_LEFT - Pin 4 ---> PWM for right motors - Pin 9 ---> DIRECTION_RIGHT */ //================================================== public: void setup(unsigned short pwmPinLeft, unsigned short directionPinLeft, unsigned short pwmPinRight, unsigned short directionPinRight, unsigned int defaultSpeed); void motorsDrive(Direction motorsDirection); void motorsStop(); void motorsTurnLeft(); void motorsTurnRight(); void motorsTurn(Turn motorsTurn); //void motorsTurn(short leftPWM, short rightPWM); void motorsUTurn(); int speed; private: //void motorsTurn(short leftPWM, short rightPWM, Turn motorsTurn); unsigned short PWM_LEFT; unsigned short PWM_RIGHT; unsigned short DIRECTION_LEFT; unsigned short DIRECTION_RIGHT; }; #endif
true
2edebd9def4ca3b755942aa4e6f11cc867ceac8d
C++
andrewpeck/emu
/step/include/emu/step/TimingOptions.h
UTF-8
2,196
2.6875
3
[]
no_license
#ifndef __emu_step_TimingOptions_h__ #define __emu_step_TimingOptions_h__ #include "emu/step/Test.h" #include "emu/pc/TMB.h" #include <vector> #include <map> #include <string> namespace emu{ namespace step{ class Test; class TimingOptions{ public: TimingOptions( emu::step::Test *test ); emu::step::Test* test () { return test_; } bool doPeriodicDumps () const { return doPeriodicDumps_; } bool doSynchronizedDumps () const { return doSynchronizedDumps_; } bool synchronizeTestStart () const { return synchronizeTestStart_; } double dumpPeriodInSec () const { return dumpPeriodInSec_; } int spsTimingSignalsForDumps() const { return spsTimingSignalsForDumps_; } int spsTimingSignalsForStart() const { return spsTimingSignalsForStart_; } vector<emu::pc::TMB*> TMBs () const { return tmbs_; } string dumpDir () const { return dumpDir_; } string dumperName () const { return dumperName_; } #ifdef DIP string printTimingSignals( unsigned int signals ); #endif private: emu::step::Test *test_; bool doPeriodicDumps_; /// TRUE if dumps are to be done at a predefined rate bool doSynchronizedDumps_; /// TRUE if dumps are to be synchronized to an SPS timing signal bool synchronizeTestStart_; /// TRUE if the start of test is to coincide with an SPS timing signal double dumpPeriodInSec_; /// If dumps are to be done at a predefined rate, this should be their period in seconds. unsigned int spsTimingSignalsForDumps_; /// SPS timing signals that the dumps should be done at (see emu::step::Test::SPSTimingSignal_t for bit positions) int spsTimingSignalsForStart_; /// SPS timing signals that the test should start at (see emu::step::Test::SPSTimingSignal_t for bit positions) vector<emu::pc::TMB*> tmbs_; /// TMBs whose counters to dump. string dumpDir_; /// Name of directory to dump the TMB counters to. string dumperName_; /// Name of the dumper. }; } } #endif
true
0203ad6f93a0d101006f74b04790d767187eaae5
C++
czzCreator/daemon_with_boost_1_69
/console_boost_service_example/qcmd_pairs_dealer.h
UTF-8
5,673
2.578125
3
[]
no_license
#ifndef QCMD_PAIRS_DEALER_H #define QCMD_PAIRS_DEALER_H #include <QDebug> #include <QString> #include <string> #include <iostream> //实例化对象并且初始化 //每次再次调用无需重新定义stringstream类一个对象,只要清空再使用即可 //strStream.clear(); #include <sstream> #include "qmyglobal.h" /* * program options是一系列pair<name,value>组成的选项列表,它允许程序通过命令行或配置文件来读取这些参数选项. 主要组件 program_options的使用主要通过下面三个组件完成: 组件名 作用 options_description(选项描述器) 描述当前的程序定义了哪些选项 parse_command_line(选项分析器) 解析由命令行输入的参数 variables_map(选项存储器) 容器,用于存储解析后的选项 构造option_description对象和variables_map对象add_options()->向option_description对象添加选项 */ /// 关于该类介绍见下 /// http://www.radmangames.com/programming/how-to-use-boost-program_options#accessingOptionValues /// https://blog.csdn.net/cchd0001/article/details/43967451 /// https://blog.csdn.net/yahohi/article/details/9790921 #include <boost/program_options.hpp> #include <boost/filesystem.hpp> namespace cmd_parser { const size_t SUCCESS = 0; const size_t ERROR_IN_COMMAND_LINE = 1; const size_t ERROR_NOT_LOGGED_IN = 2; const size_t ERROR_CMD_NOT_COMPLETE = 3; const size_t ERROR_UNHANDLED_EXCEPTION = 4; } namespace cmd_type { const std::string LOGIN_WITH_NAME_CMD = "login with "; const std::string LOGIN_SUCESS = "login success. "; const std::string LOGIN_FAILED = "login failed. "; const std::string LOGIN_DENY = "login deny. "; const std::string PING_OK_FROM_SERVER = "ping ok from srv"; const std::string PING_CLIENT_LIST_CHANGE = "ping client_list_changed"; const std::string PING_OK_FROM_CLIENT = "ping ok from client"; } // linux 系统上 工具风格输入 class QCmd_pairs_dealer { typedef boost::program_options::options_description my_option_dealer; public: QCmd_pairs_dealer(void *parent); ~QCmd_pairs_dealer() { if(m_pPro_desc != NULL) { delete m_pPro_desc; m_pPro_desc = NULL; } clear_inner_argvs(); } //使用默认的 而非自定义 //QCmd_pairs_dealer(const QCmd_pairs_dealer& rhs); //QCmd_pairs_dealer & operator = (const QCmd_pairs_dealer& rhs); /// 服务端与客户端之间的报文解析 最好头部带上长度 要不然对方都不知道到底收多少才算完整 //解析来自客户端的字节流 size_t parse_cmd_from_client(const char * raw_str, size_t raw_str_len, std::string &output_result); //解析来自服务端的字节流 size_t parse_cmd_from_srv(const char * raw_str, size_t raw_str_len, std::string &output_result); //先得调用这个函数 才能接下来调用 下面的获取特定配置 size_t command_line_own_parser(const char * raw_str, std::string &output_result); static std::string get_login_with_command(){ return cmd_type::LOGIN_WITH_NAME_CMD; } static std::string get_login_success_command(){ return cmd_type::LOGIN_SUCESS; } static std::string get_login_failed_command(){ return cmd_type::LOGIN_FAILED; } static std::string get_login_deny_command(){ return cmd_type::LOGIN_DENY; } static std::string get_ping_ok_frm_srv_command(){ return cmd_type::PING_OK_FROM_SERVER; } static std::string get_ping_ok_frm_client_command() { return cmd_type::PING_OK_FROM_CLIENT; } static std::string get_ping_client_changed_command() { return cmd_type::PING_CLIENT_LIST_CHANGE; } // 取 'login with '后面的名字 static size_t get_name_frm_login_cmd(const std::string &original_cmd,size_t raw_byte_len,std::string &username) { size_t found = original_cmd.find(get_login_with_command()); if((found + get_login_with_command().size()) >= original_cmd.size() ) { username.clear(); return cmd_parser::ERROR_CMD_NOT_COMPLETE; } size_t name_len = raw_byte_len - get_login_with_command().size() - found; username = original_cmd.substr(found + get_login_with_command().size(),name_len); return cmd_parser::SUCCESS; } int get_pingpong_times() { return m_pingpong_times_max; } float get_reserve_float_value() { return m_reserve_float_v; } std::string get_app_version_info() { return m_app_version; } private: size_t covert_str_2_argvs(const char * raw_str); void clear_inner_argvs(); void set_app_version_info(const char * macro_app_ver_info){ m_app_version = macro_app_ver_info; } private: my_option_dealer *m_pPro_desc; std::string m_str_description; // 解析命令后存储的客户端 命令键值对 boost::program_options::variables_map m_cmd_variable_map; // 原始键值对值 空格分开 int argc; char **argv; // 服务端与客户端之间通讯 发送测试 pingpong 包次数 配置 int m_pingpong_times_max; int m_pingpong_counter; // 备用 float 参数 float m_reserve_float_v; // 程序版本信息 std::string m_app_version; // client json info 列表 std::vector<std::string> m_client_json_info; // 父对象 void *m_parent; }; #endif // QCMD_PAIRS_DEALER_H
true
fb78ee4d32e18e16c26a817d12986d6a4617fad6
C++
stereotype13/LeetCodePractice
/ImplementStrStr/ImplementStrStr/main.cpp
UTF-8
1,754
3.890625
4
[]
no_license
/* Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). */ #include <string> #include <queue> #include <iostream> using namespace std; class Solution { public: int strStr(string haystack, string needle) { if (needle.size() == 0) return 0; if (haystack.size() == 0) return -1; int needleIndex = 0; queue<int> startingIndices; for (int i = 0; i < haystack.size(); ++i) { if (haystack[i] == needle[0] && needleIndex != 0) startingIndices.push(i); if (haystack[i] == needle[needleIndex]) { ++needleIndex; if (needleIndex == needle.size()) return i - (needleIndex - 1); continue; } needleIndex = 0; if (!startingIndices.empty()) { i = startingIndices.front() - 1; startingIndices.pop(); } } return -1; } }; int main(int argc, char* argv[]) { Solution solution; string haystack1 = "hello", needle1 = "ll"; cout << solution.strStr(haystack1, needle1) << endl; string haystack2 = "aaaaa", needle2 = "baa"; cout << solution.strStr(haystack2, needle2) << endl; string haystack3 = "mississippi", needle3 = "issipi"; cout << solution.strStr(haystack3, needle3) << endl; string haystack4 = "mississippi", needle4 = "issip"; cout << solution.strStr(haystack4, needle4) << endl; cin.get(); return 0; }
true
aa1515569e82a8d0a2abd901b7a508006678e62d
C++
eunbiline98/project-arduino
/motor_limit_switch/motor_limit_switch.ino
UTF-8
1,414
2.5625
3
[]
no_license
int pbuttonPin = A1;// connect output to push button int pbuttonPin1 = A2;// connect output to push button int pbuttonPin2 = A3;// connect output to push button int relayPin = 13;// Connected to relay (LED) #define pin_cw 10 #define pin_cww 11 int sens_a = 0; int sens_b = 0; int hujan = 0; void setup() { // Robojax.com code and video tutorial for push button ON and OFF Serial.begin(9600); pinMode(pbuttonPin, INPUT_PULLUP); pinMode(pbuttonPin1, INPUT_PULLUP); pinMode(pbuttonPin2, INPUT_PULLUP); pinMode(pin_cw,OUTPUT); pinMode(pin_cww,OUTPUT); } void loop() { // Robojax.com code and video tutorial for push button ON and OFF int st = 0; sens_a = digitalRead(pbuttonPin);// read the push button value sens_b = digitalRead(pbuttonPin1); hujan = digitalRead(pbuttonPin2); if(st==0){ if(sens_a == HIGH && hujan == LOW){ Serial.println("motor down"); digitalWrite(pin_cww,HIGH); digitalWrite(pin_cw,LOW); } if(sens_a == LOW && hujan == LOW){ Serial.println("motor stop down"); digitalWrite(pin_cww,LOW); digitalWrite(pin_cw,LOW); } st = 1; } if(st==1){ if(sens_b == LOW && hujan == HIGH){ Serial.println("motor stop up"); digitalWrite(pin_cww,LOW); digitalWrite(pin_cw,LOW); } if(sens_b == HIGH && hujan == HIGH){ Serial.println("motor up"); digitalWrite(pin_cww,LOW); digitalWrite(pin_cw,HIGH); } st = 0; } }
true
9e841ac5b0f6537e93e60337e7e99a1ca190cafe
C++
sworsman31415926/linux_send_message
/DataStruct/StackAndQueue/2017-4-17/MinStack.hpp
UTF-8
1,131
3.640625
4
[]
no_license
/************************************** *文件说明:Push、Pop、Min操作均为O(1)的栈 *作者:高小调 *创建时间:2017年04月17日 星期一 18时48分35秒 *开发环境:Kali Linux/g++ v6.3.0 ****************************************/ #include<stack> #include<cassert> template<typename T> class MinStack{ public: //构造、拷贝构造、赋值运算符重载、析构略 public: void Push(const T &e); //入栈 void Pop(); //出栈 const T& Min(); //获取最小值 bool Empty(); //判断是否为空(测试使用) private: std::stack<T> _s; //栈 std::stack<T> _min; //最小值栈 }; //入栈 template<typename T> void MinStack<T>::Push(const T &e){ if(_min.empty() || _min.top() >= e){ _min.push(e); } _s.push(e); } //出栈 template<typename T> void MinStack<T>::Pop(){ if(_s.empty()){ assert(false); } if(_s.top() == _min.top()){ _min.pop(); } _s.pop(); } //获取当前栈中元素的最小值 template<typename T> const T &MinStack<T>::Min(){ if(_min.empty()){ assert(false); } return _min.top(); } template<typename T> bool MinStack<T>::Empty(){ return _s.empty(); }
true
f9cb757e3b7a50004f01289e8ce501b39eb45915
C++
mucahityuksel/c_vize_sorulari
/2017_algo_vize2.cpp
UTF-8
467
2.59375
3
[]
no_license
//dizideki degerler buyuk harf ise yerine * koy kucuk ise buyuk harfe cevir. #include "stdio.h" int main(int argc, char const *argv[]) { char metin[100]; int i; printf("bir metin giriniz:"); gets(metin); for(i=0;metin[i]!=NULL;i++) { if((metin[i]>='a')&& (metin[i]<='z')) { metin[i]-=32; } else if((metin[i]>='A')&&(metin[i])<='Z') { metin[i]+=32; metin[i]='*'; } printf("%c",metin[i]); } return 0; }
true
512e77e3b61dfe30de74cb45de89123e2bd81f7c
C++
dfortizgu/HerramientasComp
/Ejercicios/1.cpp
ISO-8859-1
1,601
3.34375
3
[]
no_license
#include <iostream> #include <cmath> double sin_pade(double x); double sin_aux(double u); double sinint(double x); //sinint calcula sin(x) para el intervalo [-pi/2;pi/2] con la aproximacin de Pade(que es donde funciona tal aproximacin) mientras que sin_aux cuenta el intervalo en que est x [-pi/2+n;pi/2+n] con n entero y calcula sin(x)) con sinint "llevando" a x a tal intervalo usando la periodicidad de la funcin seno int main(void) { std::cout.precision(16); // 16 decimal places std::cout.setf(std::ios::scientific); // use scientific notation double x = 0.01; while(x<=2*3.1415926535){ double error = std::fabs((std::sin(x)-sin_pade(x))/std::sin(x)); std::cout<<x<<"\t"<<error<<"\n"; x+=0.01; } return 0; } double sinint (double x){ if(std::fabs(x)<std::pow(10,-8)){ return x; }else if(std::fabs(x)>0.52359877598){ double u = x/3.0; return (3-4*sin_aux(u)*sin_aux(u))*sin_aux(u); }else { return sin_aux(x); } } double sin_pade(double x) { if(x<0){ int n = (x+3.1415926535/2.0)/3.1415926535; double npi = 3.1415926535*n; if(n%2==0){ return sinint(x+npi); }else{ return -sinint(x+npi); } }else{ int n = (x+3.1415926535/2.0)/3.1415926535; double npi = 3.1415926535*n; if(n%2==0){ return sinint(x-npi); }else{ return -sinint(x-npi); } } } double sin_aux(double u) { return u*((1.0-(29693.0/207636)*u*u+(34911.0/7613320)*std::pow(u,4)-(479249.0/11511339840)*std::pow(u,6))/(1.0+(1671.0/69212)*u*u+(97.0/351384)*std::pow(u,4)+(2623.0/1644477120)*std::pow(u,6))); }
true
020e57ea13fa936968fe68f60abaa4e4b2b98620
C++
TyRoXx/dogbox
/common/overloaded.h
UTF-8
208
2.59375
3
[ "MIT" ]
permissive
#pragma once namespace dogbox { template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template <class... Ts> overloaded(Ts...)->overloaded<Ts...>; }
true
b948516f1d25ad23b8a2637234241d961a5d9942
C++
xxvms/Library_V_Unique
/main.cpp
UTF-8
4,130
3.375
3
[]
no_license
#include <iostream> #include <vector> #include "Book.h" #include "Library.h" char menu(); int main() { Library library; std::vector<Book>book; char choice; do { choice = menu(); switch (choice) { case '1': { std::cout << "Max amount books in Library: "; unsigned int librarySize = 0; std::cin >> librarySize; book.resize(librarySize); std::cout << std::endl; std::cout << "Library capacity is " << book.capacity() << " books"<< std::endl; std::cout << std::endl; break; } case '2': { if (!book.empty()){ char howManyBooks = '0'; std::cout << "How many books do you want to add:"; std::cin >> howManyBooks; if ( howManyBooks > '0' && howManyBooks < '9'){ unsigned int books_to_add = howManyBooks - 48; //unsigned int books_to_add = static_cast<unsgined int>(howManyBooks - 48); for (size_t i = 0; i < books_to_add; i++) { book.at(i).add(); library.addBook2Lib(&book.at(i)); } }else { std::cout << std::endl; std::cout << "your input is not a number " << std::endl; std::cout << std::endl; break; } } else { std::cout << std::endl; std::cout << "Use option 1 to create library before adding books :)" << std::endl; std::cout << std::endl; break; } break; } case '3': { std::cout << "who are you?" << std::endl; std::cout << "press (L)ibrarian or (U)ser: "; char question = ' '; std::cin >> question; library.printBooksInLib(); std::cout << "Please type book ID of book you with to borrow: " << std::endl; unsigned int bookID{0}; std::cin >> bookID; bookID--;// -1 is offset for correct index library.borrow(bookID, &book.at(bookID), question); break; } case '4': { std::cout << "Return Book" << std::endl; std::cout << "who are you?" << std::endl; std::cout << "press (L)ibrarian or (U)ser: "; char question = ' '; std::cin >> question; library.returnBook(&book.at(0), question); break; } case '5': std::cout << "Print all books in library"; library.printBooksInLib(); break; case '6': std::cout << "User books: " << std::endl; library.printUserBooks(); break; case '7': std::cout << "Librarian books: " << std::endl; library.printLibrarianBooks(); break; default: std::cout << "smile its friday"; break; } }while (choice != '9'); return 0; } char menu() { char choice{' '}; std::cout << "Please make your selection" << std::endl; std::cout << "Press number: " << std::endl; std::cout << "1 - Set size of the Library" << std::endl; std::cout << "2 - Create book" << std::endl; std::cout << "3 - Borrow book" << std::endl; std::cout << "4 - Return book" << std::endl; std::cout << "5 - Print out all books" << std::endl; std::cout << "6 - Print books borrowed by user" << std::endl; std::cout << "7 - Print books borrowed by Librarian" << std::endl; std::cout << "9 - to Quit" << std::endl; std::cin >> choice; return choice; }
true
593e5b36d3248d3d3841f628887f0727840176cc
C++
salluru007/algos
/src/epi/designProb1.cpp
UTF-8
2,495
3.859375
4
[]
no_license
#include<iostream> #include<vector> #include<cmath> template<typename T> class Point{ public: T _x, _y; Point()=delete; //Point(T &x=T(),T &y = T()):_x(x), _y(y){} Point( T x, T y):_x(x),_y(y){ std::cout << "Constructed Point\n"; } //virtual float distance(Point &point){ float distance(Point &point){ float distance = 0.0; if(this != &point){ distance = sqrt(pow((_x-point._x),2)+ pow((_y-point._y),2)); std::cout << "In distance:" << distance << std::endl; } return distance; } }; template<typename T> class Point3D:Point<T>{ T _z; public: Point3D() = default; //Point3D(T &z = T()):_z(z){} Point3D(T x, T y, T z): Point<T>(x, y), _z(z){ std::cout << "Constructed Point3D\n"; } /*virtual*/ float distance(Point3D &point){ float distance = 0.0; if(this != &point){ distance = sqrt(pow((this->_x-point._x),2)+ pow((this->_y-point._y),2) + pow((_z-point._z),2) ); } return distance; } }; template<typename T, template<typename> class C> class PolyLine{ std::vector<C<T>> polyLines; public: PolyLine() = delete; PolyLine(C<T> point1, C<T> point2){ this->polyLines.push_back(point1); this->polyLines.push_back(point2); } float distance(){ float distance = 0.0; //iterators are pointers, they should access data through -> Point<int> * for(typename std::vector<C<T>>::iterator iter = polyLines.begin()+1; iter != polyLines.end(); ++iter){ //distance += polyLines[iter].distance(polyLines[iter-1]); C<T> point = *(iter-1); distance += iter->distance(point); std::cout << iter->distance(point) << std::endl; //std::cout << point._x << " " << point._y << std::endl; //std::cout << iter->_x << " " << iter->_y << std::endl; //std::cout << "The distance is:" << distance << std::endl; } return distance; } }; int main(){ Point<int> point(1,1); Point3D<int> point3d(1,1,1); //Firs the base constructor and then the derived constructor //PolyLine<int, Point2D> polyLine; PolyLine<int, Point> polyLine(Point<int>(1, 1), Point<int>(0, 1)); float distance = polyLine.distance(); std::cout << "The distance is:" << distance << std::endl; //PolyLine<int, Point3D> polyline3d; Call to a deleted destructed, compiler error PolyLine<int, Point3D> polyline3D(Point3D<int>(1,1,1), Point3D<int>(0,0,1)); distance = polyLine.distance(); std::cout << "The distance is:" << distance << std::endl; return 0; }
true
6eb0a298065ff24564558bd7ea0f1569687f9fb5
C++
XiaoxiongZheng/Algorithms
/leetcode/ValidParentheses.cpp
UTF-8
725
3.28125
3
[]
no_license
// // Created by zhengxx on 15/5/17. // /** * valid parentheses * https://leetcode.com/problems/valid-parentheses/ * time = O(n), space = O(n) */ #include <stack> #include <unordered_map> using namespace std; class Solution { public: bool isValid(string s) { stack<char> st; unordered_map<char, char> m; m['('] = ')'; m['['] = ']'; m['{'] = '}'; for (int i = 0; i < s.size(); i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') st.push(s[i]); else { if (st.empty() || m[st.top()] != s[i]) return false; st.pop(); } } return st.empty(); } };
true
b88fb2384b05691d2d08d98f3f8bb0baf021e91e
C++
vcvycy/ACMTemplate
/SuffixArray.cpp
GB18030
3,685
2.828125
3
[]
no_license
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> using namespace std; class SUFFIXARRAY { #define SLEN 201000 /* ֱú.solve(char s[],int charSetSize=128)s[]±0ʼ charSetSizeʾ0<=s[0]..s[n-1]<charSetSize0ΪַáСӰٶȡ */ /* sa[],rank[],height[i]±Ϊ1..n (1)sa[i] : ĺ׺Уiԭе± (2)rank[i] : ԭi׺ĺ׺±,sa[rank[i]]=i,rank[sa[i]]=i (3)height[i] : ĺ׺Уi׺͵i-1׺LCP(ǰ׺)height[i]=getlcp(sa[i-1],sa[i]) (4)getlcp(i,j): ԭУi׺͵j׺LCP */ private: int s[SLEN]; int t[SLEN], t2[SLEN], c[SLEN]; int n; // ַstrlen(s) static int lg[SLEN];//lg[i]=log2(i);ȡ int f[SLEN][25]; void clear(); // mΪֵַ1֮ǰúsn void build_sa(int m); void build_height(); void initlcp(); public: SUFFIXARRAY(); int sa[SLEN]; int rank[SLEN]; int height[SLEN]; void solve(char *a,int charSetSize); int getlcp(int l,int r);//׺ l,ͺ׺rlcp }; int SUFFIXARRAY::lg[SLEN]; SUFFIXARRAY::SUFFIXARRAY(){ memset(lg,0,sizeof(lg)); for (int i=2;i<=n;i<<=1)lg[i]=1; for (int i=1;i<=n;i++)lg[i]+=lg[i-1]; } void SUFFIXARRAY::build_height() { int i, j, k = 0; for(i = 0; i < n; i++) rank[sa[i]] = i; for(i = 0; i < n; i++) { if(k) k--; int j = sa[rank[i]-1]; while(s[i+k] == s[j+k]) k++; height[rank[i]] = k; } } void SUFFIXARRAY::initlcp(){ memset(f,0,sizeof(f)); for (int i=1;i<=n;i++)f[i][0]=height[i]; int m=lg[n]; for (int j=1;j<=m;j++) for (int i=1;i<=n;i++){ if ((i-1+(1<<j))>n)break; f[i][j]=min(f[i][j-1],f[i+(1<<(j-1))][j-1]); } } int SUFFIXARRAY::getlcp(int l,int r){//׺ l,ͺ׺rlcp if (l==r)return n-l+1; l=rank[l],r=rank[r]; if (l>r)swap(l,r);l++; int tot=lg[r-l+1]; return min(f[l][tot],f[r-(1<<(tot))+1][tot]); } void SUFFIXARRAY::build_sa(int m){ int i, *x = t, *y = t2; for(i = 0; i < m; i++) c[i] = 0; for(i = 0; i < n; i++) c[x[i] = s[i]]++; for(i = 1; i < m; i++) c[i] += c[i-1]; for(i = n-1; i >= 0; i--) sa[--c[x[i]]] = i; for(int k = 1; k <= n; k <<= 1) { int p = 0; for(i = n-k; i < n; i++) y[p++] = i; for(i = 0; i < n; i++) if(sa[i] >= k) y[p++] = sa[i]-k; for(i = 0; i < m; i++) c[i] = 0; for(i = 0; i < n; i++) c[x[y[i]]]++; for(i = 0; i < m; i++) c[i] += c[i-1]; for(i = n-1; i >= 0; i--) sa[--c[x[y[i]]]] = y[i]; swap(x, y); p = 1; x[sa[0]] = 0; for(i = 1; i < n; i++) x[sa[i]] = y[sa[i-1]]==y[sa[i]] && y[sa[i-1]+k]==y[sa[i]+k] ? p-1 : p++; if(p >= n) break; m = p; } } void SUFFIXARRAY::clear() { n = 0; memset(sa, 0, sizeof(sa)); } void SUFFIXARRAY::solve(char *a,int charSetSize=300){ n=strlen(a)+1; for (int i=0;i<n;i++)s[i]=a[i]; s[n]=0; build_sa(charSetSize+1); build_height(); n--; for (int i=1;i<=n;i++)sa[i]++; for (int i=n;i>=1;i--)rank[i]=rank[i-1]; initlcp(); } SUFFIXARRAY sa; char s[SLEN]="abcdefghij"; //s±0ʼ ,rank[1]ʾs[0]ʼĺ׺ int i,j,k,m,n; int main(){ scanf("%s",s); int m=strlen(s); s[m]=27; scanf("%s",s+m+1); n=strlen(s); sa.solve(s); int ans=0; for (i=2;i<=n;i++) if ((sa.sa[i-1]<=m&&sa.sa[i]>m)||(sa.sa[i-1]>m&&sa.sa[i]<=m)) ans=max(sa.height[i],ans); cout<<ans<<endl; return 0; }
true
897004fdf732c390f7a536fe7eeb59e388e637af
C++
molivo123/CPSC-350
/Assignment2350/Assignment2350.h
UTF-8
1,667
2.65625
3
[]
no_license
#include <iostream> #include <typeinfo> #include <fstream> #include <random> #include <string> #include <cmath> #include <unistd.h> //all of my includes using namespace std; //all of my namespaces //GoL class class GameOfLife{ public: GameOfLife();//default constructor ~GameOfLife();//deconstructor }; //class that is supposed to take in the parameters from either the user or the input to create an array class GameBoard{ public: GameBoard();//constructor ~GameBoard();//deconstructor //functions/methods void getRandomValues(); void getFileValues(); bool safeInt(int &output); void outputToFile(); void getInputInfo(); //vars int lengthK; int widthK; int width6; int length6; int probOfX; int i; int userRand6; string fileName; string textLine; ifstream userFile; int neighborCounter; double randNumUser; int RandVar; char pausesOrEnter; int j; int userRand; char ** RandBoard2 = NULL; char ** RandBoard = NULL; }; //created new class for each of the gamemodes //idea provided to me by the tutoring center class Classic{ public: Classic();//constructor ~Classic();//deconstructor //functions/methods void startClassic(); //vars int width; int length; int neighborCounter; char ** tempArr = NULL; }; class Mirror{ public: Mirror();//constructor ~Mirror();//deconstructor //functions/methods void startMirror(); //vars int neighborCount; char ** tempArr = NULL; }; class Doughnut{ public: Doughnut();//constructor ~Doughnut();//deconstructor //functions/methods void startDoughnut(); //vars int neighborCount; char ** tempArr = NULL; };
true
4aa58816e520207d1fc3fd32bfe4ccc5ccd785a1
C++
k911/bmp-compressor-12bit
/src/InputHandler.cpp
UTF-8
2,823
2.890625
3
[]
no_license
#include "InputHandler.h" #include "CText.h" #include <string> InputHandler::InputHandler(int argc, char ** argv) : DEFAULT_OPTION("input"), FILE_EXT(R"(((?:[^/]*/))*(.*)\.(\w+)$)") // FILE_EXT(R"(.*\/?(.*)\.(\w+)$)") // TODO: not "Raw string" { #ifdef _DEBUG std::cout << " -> [InputHandler]: Parsing input for executable '" << CText(argv[0], CText::Color::GREEN) << '\'' << std::endl; #endif // DEBUG std::string option = DEFAULT_OPTION; std::vector<std::string> arguments; size_t i = 1; while (true) { // add arguments if (i < static_cast<size_t>(argc) && argv[i][0] != '-') { arguments.push_back(argv[i]); } else { // try insert into map bool emplaced; std::unordered_map <std::string, std::vector<std::string>>::iterator it; std::tie(it, emplaced) = option_arguments.emplace(option, arguments); // when key exists update it if (!emplaced) { for (auto &a : arguments) (*it).second.push_back(a); } if (i == static_cast<size_t>(argc)) break; // clean arguments for new option arguments.clear(); option = argv[i]; option.erase(0, 1); } ++i; } } bool InputHandler::isset(const std::vector<std::string> &options) { for (const auto &opt : options) { if (option_arguments.count(opt) == 1) { used.emplace(opt); return true; } } return false; } bool InputHandler::isset(const char * option) { if (option_arguments.count(option) == 1) { used.emplace(option); return true; } return false; } std::vector<std::string> InputHandler::get(const std::string &option) { auto search = option_arguments.find(option); if (!used.count(option) && search != option_arguments.end()) { used.emplace(option); return std::move((*search).second); } return std::vector<std::string>(); } std::vector<std::string> InputHandler::get(const char * option) { return get(std::string(option)); } bool InputHandler::empty() const { return option_arguments.size() == used.size(); } std::tuple<bool, std::string, std::string, std::string> InputHandler::match_extensions(const std::string & filepath, const std::vector<std::string>& extensions) const { bool matched = false; std::smatch match; if (std::regex_match(filepath, match, FILE_EXT)) { std::string ext = match[3].str(); for (const auto &e : extensions) { if (ext == e) { matched = true; break; } } return std::make_tuple(matched, match[1].str(), match[2].str(), ext); } return std::make_tuple(matched, std::string(""), std::string(""), std::string("")); } void InputHandler::print(std::ostream & o) { o << "\n"; for (const auto &vec : option_arguments) { o << " -> " << CText(vec.first, CText::Color::CYAN) << std::endl; for (const auto &s : vec.second) { o << " - " << s << std::endl; } } o << std::endl; }
true
041ce612b7a5b713fa9de6386bab1ecf46ac0d3f
C++
HenrYxZ/Graphics
/project2/geom2.h
UTF-8
1,672
3.203125
3
[]
no_license
#include <math.h> #include <iostream> #ifndef __GEOM2_H__ #define __GEOM2_H__ // Alpha value used for determining initial magnitude #define ALPHA 1 // Arbitrary value for acceleration of balls in motion #define ACCELERATION -100 // Maximum speed per ball #define MAX_SPEED 200 using namespace std; // Handy geometry classes and functions // computes the distance between two two-dimensional points double distance(double xA, double yA, double xB, double yB); // computes the hypotenuse of a triangle formed by the x and y // values of a velocity double pythagorean(double x, double y); // Conversion between degrees and radians float RadtoDeg(float rad); float DegtoRad(float deg); // Velocity class class Velocity { public: double x; double y; Velocity(); Velocity(double x, double y); double getX() { return x; } double getY() { return y; } double getMagnitude() { return magnitude; } double getDirection() { return directionRad; } bool moving(double t); void setXY(double x, double y); void slow(double t); void reverse(); void scalarSelfProduct(double scalar); void print(); // operators Velocity operator-(const Velocity &other); private: float directionRad; double magnitude; void setMagnitude() { magnitude = ALPHA * pythagorean(x, y); } void setDirectionRad(); void updateXY(); }; double DotProduct(Velocity vA, Velocity vB); // Uses the dot product between two velocity vectors to compute // the angle between them. Returns an angle in radians. float AngleBetween(Velocity vA, Velocity vB); Velocity sumOfVelocities(Velocity vA, Velocity vB); Velocity scalarProduct(double scalar, Velocity v); #endif
true
fb8c56d4ac67c33e138f8dc72026a42cd39d5433
C++
JavierUR/lineFollowerSimulator-cpp
/version-2/paths.h
UTF-8
923
2.703125
3
[ "MIT" ]
permissive
#ifndef __PATHS_H__ #define __PATHS_H__ #include "odometry.h" #ifndef __AVR__ #include "arduino.h" #include "utils.h" #else #include <Arduino.h> #endif class PathPoint { private: // flags stores a packed representation of other information // included in a PathPoint. The LSB represents whether the robot // is expected to deviate from the line there, and the next three // bits represent robot speed 0...7 byte flags; public: double wrappedAngle; PathPoint(); bool getOffLine( void ); void setOffLine( bool offline ); byte getSpeed( void ); void setSpeed( byte speed ); }; class Path { public: Path(int length, bool useLeft); ~Path(); PathPoint *points; int allocatedPoints = 0; int usedPoints = 0; bool useLeftSensor = false; void writeOut( void ); bool attemptUpdate( Pose *pose ); PathPoint *getPoint( double distAlong ); }; #endif
true
26c31f4de648d75de4c66e85f8daf429010a686c
C++
simoliqta/Homework-SDA
/Homework 4 and some previous tasks/QueueUsingTwoStacks.cpp
UTF-8
2,906
3.484375
3
[]
no_license
#include<iostream> using namespace std; template<typename T> struct node { T data; node* next; }; template<typename T> class LStack { private: node<T>* topNode; void copy(node<T>* toCopy); void eraseStack(); void copyStack(LStack const&); public: LStack(); LStack(LStack const&); LStack& operator=(LStack const&); ~LStack(); bool empty() const; void push(T const& x); T pop(); T top() const; T findMax()const; }; template<typename T> LStack<T>::LStack() : topNode(nullptr) {} template<typename T> bool LStack<T>::empty() const { return topNode == nullptr; } template<typename T> void LStack<T>::push(T const& x) { node<T>* p = new node<T>; p->data = x; p->next = topNode; topNode = p; } template<typename T> T LStack<T>::pop() { if (empty()) { cerr << "empty stack!\n"; return 0; } node<T>* p = topNode; topNode = topNode->next; T x = p->data; delete p; return x; } template<typename T> T LStack<T>::top() const { if (empty()) { cerr << "empty stack!\n"; return 0; } return topNode->data; } template<typename T> void LStack<T>::eraseStack() { while (!empty()) { pop(); } } template<typename T> LStack<T>::~LStack() { eraseStack(); } template<typename T> void LStack<T>::copy(node<T>* toCopy) { if (toCopy == nullptr) return; copy(toCopy->next); push(toCopy->data); } template<typename T> void LStack<T>::copyStack(LStack const& ls) { topNode = nullptr; copy(ls.topNode); } template<typename T> LStack<T>::LStack(LStack const& ls) { copyStack(ls); } template<typename T> LStack<T>& LStack<T>::operator=(LStack const& ls) { if (this != &ls) { eraseStack(); copyStack(ls); } return *this; } template <typename T> class QueueUsingTwoStacks { LStack<T> PushStack; LStack<T> PopStack; public: void enqueue(T const &x); T dequeue(); T top() { return PushStack.top(); } }; template <typename T> void QueueUsingTwoStacks<T>::enqueue(T const &x) { while (!PushStack.empty()) { PopStack.push(PushStack.pop()); } PushStack.push(x); while (!PopStack.empty()) { PushStack.push(PopStack.pop()); } } template <typename T> T QueueUsingTwoStacks<T>::dequeue() { if (PushStack.empty()) { std::cout << "Queue is empty\n"; return T(); } return PushStack.pop(); } int main() { QueueUsingTwoStacks<int> queue; int number; int counter = 0; cin >> number; int* topPrint = new int[number]; for (int i = 0; i < number; i++) { int query; cin >> query; switch (query) { case 1: int x; cin >> x; queue.enqueue(x); break; case 2: queue.dequeue(); break; case 3: topPrint[counter] = queue.top(); counter++; break; } } for (int i = 0; i < counter; i++) { cout << topPrint[i] << std::endl; } return 0; }
true
0c98d7df48f2be48ee10c19ec9193a3d0ceeeae1
C++
GkWangBin/Method-of-Programming
/第二章-数组/寻找最小的k个数.cpp
UTF-8
5,751
3.921875
4
[]
no_license
/*题目:有n个整数,请找出其中最小的k个整数,要求时间复杂度尽可能低*/ /*首先可以使用先排序,再输出的策略。 *假设使用的是快速排序,时间复杂度为O(nlogn)+O(k)->O(nlogn)*/ #include<iostream> #include<Windows.h> using namespace std; void swap(int *a, int *b) { int tmp(*b); *b = *a; *a = tmp; } /* int partation(int *arr, int low, int high) { int pivot = arr[high]; int left(low), right(high - 1); while (left < right) { //while内部如果没有left与right大小的判断,可能会产生越界问题 while (left<right && arr[left] <= pivot) left++; while (left<right && arr[right] >= pivot) right--; if (left < right) { swap(arr + left, arr + right); } } //此时left==right if (arr[left] > arr[high]) { swap(arr + left, arr + high);//left == right return left; } //如果遇到2,1,4这种情况的话, else { return high; } } void quick_sort(int *arr, int low, int high) { if (low < high) { int pos = partation(arr, low, high); //这里出现过问题,如果是pos-1的话 quick_sort(arr, low, pos-1); quick_sort(arr, pos + 1, high); } } //交换是一个很麻烦的方式,虽然看着是从两边向中间同时进行扫描 */ //快速排序算法 int partation(int *arr, int low, int high) { int pivot = arr[high]; int left(low), right(high); while (left < right) { //while内部如果没有left与right大小的判断,可能会产生越界问题 while (left < right && arr[left] <= pivot)left++; arr[right] = arr[left]; while (left<right && arr[right] >= pivot) right--; arr[left] = arr[right]; } arr[left] = pivot; return left; } void quick_sort(int *arr, int low, int high) { if (low < high) { int pos = partation(arr, low, high); quick_sort(arr, low, pos - 1); quick_sort(arr, pos + 1, high); } } void all_sort(int arr[],int k) { quick_sort(arr, 0 , 9); for (int i = 0; i < k; i++) { cout << arr[i] << " "; } cout << endl; } /*还有一种思路,是将部分有序 *考虑冒泡的方式,冒泡排序,一次产生一个有序的数字。 *一般冒泡排序的时间复杂度为O(n2),但是在这里只要求找到。 *最小的k个数字,也就是外部循环边界是k,时间复杂度编程了O(nk). */ void bubble_sort(int arr[], int n, int k) { for (int i = 0; i < k; i++) { for (int j = n - 1; j>i; j--) { if (arr[j]<arr[j-1]) { swap(arr + j, arr + j - 1); } } cout << arr[i] << " "; } cout << endl; } /*一遍扫描的方式,首先假设数组中前k个数字即为所求,求出该段数组中的最大值max *从k开始向后扫描,每走一步与max做比较,如果小于max则替换max的值,继续向后扫描 *寻找最大值的时间复杂度为O(k),需要寻找(n-k)次最大值,即时间复杂度为O(k)+(n-k)O(k) *所以时间复杂度为O(nk) */ //该函数需要返回两个参数,最大值和最大值的位置,时间复杂度为O(k) int partation_max(int arr[], int k, int &max) { max = arr[0]; int pos(0); for (int i = 0; i < k; i++) { if (arr[i] > max) { max = arr[i]; pos = i; } } return pos; } void partation_sort(int arr[], int n,int k) { if (n < k) { return; } int max_num(arr[0]), pos(0); for (int i = k; i < n; i++) { pos = partation_max(arr, k, max_num); if (arr[i] < max_num) { swap(arr + i, arr + pos); } } for (int j = 0; j < k; j++) { cout << arr[j] << " "; } cout << endl; } /*可以将上边的方法中前k个使用堆排序的方式,建堆时间为O(k),每次搜索最大值的时间为O(logk), *所以时间复杂度为O(k)+(n-k)O(logk)->O(nlogk) */ #define LeftChild(i) (2 * ( i ) + 1) //下滤操作 void perc_down(int arr[], int i, int k) { int child; int tmp; for (tmp = arr[i]; LeftChild(i) < k; i = child) { child = LeftChild(i); if (child != k-1 && arr[child + 1] > arr[child]) { child++; } if (tmp < arr[child])//将小的父亲下滤 { arr[i] = arr[child]; } else//已经到了堆底,无法继续 { break; } } arr[i] = tmp; } //建立一个大顶堆 void build_heap(int arr[], int k) { int i; for ( i = k/2; i >= 0; i--) { perc_down(arr, i, k); } } void partation_sort_heap(int arr[], int n, int k) { if (n < k) { return; } for (int i = k; i < n; i++) { //每次扫描到一个新的数字后建堆 build_heap(arr, k); if (arr[i] < arr[0]) { swap(arr + i, arr + 0); } } for (int j = 0; j < k; j++) { cout << arr[j] << " "; } cout << endl; } /*线性选择算法:类似与快排。将数组中第k小的元素放在k-1的位置, *小于arr[k-1]的元素在其左侧,时间复杂度为O(n) */ void quick_sort_line(int *arr, int k, int low, int high) { if (low < high) { int pos = partation(arr, low, high); if (k <= pos) { quick_sort_line(arr, k, low, pos - 1); } else if (k > pos) { quick_sort_line(arr, k, pos + 1, high); } } } /*题目:给定一个数列a1,a2, a3, ...,an和m个三元组表示的查询,对于每个查询 *(i,j,k),输出ai,ai+1,...,aj的升序排列中的第k个数 */ void print_i_j_k(int arr[], int i, int j, int k) { if (j-i < k) { return ; } quick_sort_line(arr, k, i, j); cout << arr[i + k - 1]<<endl; } int main(void) { int arr[]{ 8, 1, 3, 4, 5, 10, 54, 7, 16, 6}; int k = 3; //all_sort(arr, k);//第二个参数为count-1; //bubble_sort(arr, 10, k);//第二个参数为数组大小,第三个参数是k //partation_sort(arr, 10, k);//输出的是无序的 //partation_sort_heap(arr, 10, k); //quick_sort_line(arr, 5, 0, 9); int i(1), j(5); print_i_j_k(arr, i, j, k); for (int p = i; p <= j; p++) { cout << arr[p] << " "; } cout << endl; system("pause"); return 0; }
true
bc430cfc0e765eec63224a8887c6c6be8b46b653
C++
gfiumara/libbiomeval
/src/include/be_time_timer.h
UTF-8
7,864
2.890625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/* * This software was developed at the National Institute of Standards and * Technology (NIST) by employees of the Federal Government in the course * of their official duties. Pursuant to title 17 Section 105 of the * United States Code, this software is not subject to copyright protection * and is in the public domain. NIST assumes no responsibility whatsoever for * its use by other parties, and makes no guarantees, expressed or implied, * about its quality, reliability, or any other characteristic. */ #ifndef __BE_TIME_TIMER_H__ #define __BE_TIME_TIMER_H__ #include <chrono> #include <cstdint> #include <functional> #include <be_time.h> namespace BiometricEvaluation { namespace Time { /** * @brief * This class can be used by applications to report * the amount of time a block of code takes to execute. * * @details * Applcations wrap the block of code in the Timer::start() * and Timer::stop() calls, then use Timer::elapsed() to * obtain the calculated time of the operation. * * @warning * Timers are not threadsafe and should only be used to time * operations within the same thread. */ class Timer { public: /** Clock type to use, aliased for easy replacement. */ using BE_CLOCK_TYPE = #ifdef __MIC__ std::chrono::monotonic_clock; #else std::chrono::steady_clock; #endif /* Ensure chosen clock increases monotonically */ static_assert(BE_CLOCK_TYPE::is_steady, "BE_CLOCK_TYPE is not a steady clock"); /** Constructor for the Timer object. */ Timer(); /** * @brief * Construct a timer and time a function immediately. * * @param func * A function to time immediately. * * @throw Error::StrategyError * Propagated from time(). */ Timer( const std::function<void()> &func); /** * @brief * Start tracking time. * * @throw Error::StrategyError * This object is currently timing an operation or an * error occurred when obtaining timing information. */ void start(); /** * @brief * Stop tracking time. * * @throw Error::StrategyError * This object is not currently timing an operation or * an error occurred when obtaining timing information. */ void stop(); /** * @brief * Get the elapsed time between calls to this object's * start() and stop() methods. * * @return * Elapsed time converted to the integral units * requested, which may experience loss of precision. * * @throw Error::StrategyError * Propagated from elapsedTimePoint(). * * @note * Values returned from this method are limited in * their precision by the resolution of BE_CLOCK_TYPE. * For example, if the clock's native resolution is in * nanoseconds, requesting a picoseconds * representation returns 1000 times the nanosecond * value, not the true value in picoseconds. * * @note * Returned values are limited by the semantics of C++'s * duration type, which reports only **whole** units. * For example, if a representation of hours was * requested, 0 would be returned for durations of less * than 3600s, and 1 would be returned for durations * of 3600s through and including 7199s. For floating * point approximations of representations, use * elapsedTimePoint() to obtain a std::chrono::duration * that uses a floating point type to store the count. */ template<typename Duration> std::uintmax_t elapsed() const { return (std::chrono::duration_cast<Duration>( this->elapsedTimePoint()).count()); } /** * @brief * Convenience method for printing elapsed time as a * string. * * @param displayUnits * Append the elapsed time units. * * @return * String representing the elapsed time. * * @throw Error::StrategyError * Propagated from elapsed<Duration>() or * units<Duration>(). * * @note * See the important note in elapsed(). */ template<typename Duration> std::string elapsedStr( bool displayUnits = false) const { const std::string ret{std::to_string( this->elapsed<Duration>())}; if (displayUnits) return (ret + Timer::units<Duration>()); return (ret); } /** * @return * Unit label for a particular duration. * * @throw Error::StrategyError * Unrecognized duration encountered and units cannot be * determined. */ template<typename Duration> static std::string units() { if ((Duration::period::num == std::chrono::nanoseconds::period::num) && (Duration::period::den == std::chrono::nanoseconds::period::den)) { return ("ns"); } else if ((Duration::period::num == std::chrono::microseconds::period::num) && (Duration::period::den == std::chrono::microseconds::period::den)) { return ("\xC2\xB5s"); } else if ((Duration::period::num == std::chrono::milliseconds::period::num) && (Duration::period::den == std::chrono::milliseconds::period::den)) { return ("ms"); } else if ((Duration::period::num == std::chrono::seconds::period::num) && (Duration::period::den == std::chrono::seconds::period::den)) { return ("s"); } else if ((Duration::period::num == std::chrono::minutes::period::num) && (Duration::period::den == std::chrono::minutes::period::den)) { return ("m"); } else if ((Duration::period::num == std::chrono::hours::period::num) && (Duration::period::den == std::chrono::hours::period::den)) { return ("h"); } else { throw BiometricEvaluation::Error:: StrategyError{"Unknown duration " "units"}; } } /** * @brief * Get the elapsed time between calls to this object's * start() and stop() methods. * * @return * Elapsed time. * * @throw Error::StrategyError * This object is currently timing an operation or an * error occurred when obtaining timing information. * * @seealso elapsed() * * @note * This method may be useful for obtaining floating * point representations of durations. For example, * `std::chrono::duration<double, std::milli>( * std::chrono::microseconds(1001599)).count()` * would return a `double` with the value 1001.599000, * the millisecond floating point representation of * 1001599 microseconds. */ std::common_type_t<BE_CLOCK_TYPE::time_point::duration, BE_CLOCK_TYPE::time_point::duration> elapsedTimePoint() const; /** * @brief * Record the runtime of a function. * * @param func * Function to time. * * @return * Reference to this class. * * @throw Error::StrategyError * Propagated from start() or stop(), and/or func * is nullptr. */ Timer& time( const std::function<void()> &func); private: /** * Whether or not start() has been called and stop() * has not yet been called() on this object. */ bool _inProgress; /** Point when start() was called */ BE_CLOCK_TYPE::time_point _start; /** Time when end() was called */ BE_CLOCK_TYPE::time_point _finish; }; /** * @brief * Output stream operator overload for Timer. * * @param s * Stream to append. * @param timer * Timer whose elapsed time in microseconds should be appended * to s. * * @return * s with value of elapsedStr() appended. * * @throw BE::Error::StrategyError * Propagated from elapsedStr(). */ std::ostream& operator<<( std::ostream &s, const Timer &timer); } } #endif /* __BE_TIME_TIMER_H__ */
true
4b680a579ae00e998ea69cf37314ae3c0a2f7d6c
C++
PhilippParis/BusinessManager
/ui/models/billtablemodel.cpp
UTF-8
2,538
2.609375
3
[]
no_license
#include "billtablemodel.h" BillTableModel::BillTableModel() { } bool BillTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role == Qt::CheckStateRole) { Bill::Ptr bill = m_data.at(index.row()); bill->setPayed(value.toInt() == Qt::Checked); emit billPayedStatusChanged(bill); emit dataChanged(index, index); } return true; } int BillTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return 6; } QVariant BillTableModel::data(const QModelIndex &index, int role) const { Bill::Ptr bill = m_data.at(index.row()); Customer::Ptr customer = bill->customer(); switch(role) { case Qt::TextColorRole: return bill->date().daysTo(QDate::currentDate()) >=7 && !bill->payed()? QColor(Qt::red) : QColor(Qt::black); break; case Qt::UserRole: return customer->fullName() + "\n" + customer->organisation(); break; case Qt::UserRole + 1: return bill->payed(); break; case Qt::CheckStateRole: if (index.column() == Payed) { return bill->payed()? Qt::Checked : Qt::Unchecked; } break; case Qt::DisplayRole: switch(index.column()) { case Nr: return bill->billNumber(); case Date: return bill->date(); case Org: return customer->organisation(); case Customer: return customer->fullName(); case Value: return QString::number(bill->totalPrice().value(), 'f', 2) + QString::fromUtf8("€"); } break; }; return QVariant(); } QVariant BillTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case Nr: return tr("Nr."); case Date: return tr("Date"); case Org: return tr("Organisation"); case Customer: return tr("Customer"); case Value: return tr("Value"); case Payed: return tr("Payed"); } } return QVariant(); } Qt::ItemFlags BillTableModel::flags(const QModelIndex &index) const { if (index.column() == Payed) { return QAbstractTableModel::flags(index) | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsEditable; } return QAbstractTableModel::flags(index); }
true
b41267a99862b336ef8ad682692fec7e03f87d4c
C++
AmrEsam0/Exercism
/cpp/phone-number/phone_number.cpp
UTF-8
511
2.859375
3
[]
no_license
#include "phone_number.h" namespace phone_number { phone_number::phone_number(string raw) { regex reg("[^\\d]"); phone = regex_replace(raw, reg, ""); if (phone.size() != 10) { if (phone.size() == 11 && phone[0] == '1') { phone = phone.substr(1); } else { phone = "0000000000"; } } } string phone_number::number() const { return phone; } string phone_number::area_code() const { return phone.substr(0, 3); } } // namespace phone_number
true
d8a23e55736a517479b449520a33c4026cd1b418
C++
Michal-Fularz/ProgrammingCourse
/ProgrammingCourse/lab_07_test_preparation/lab_07_library.cpp
UTF-8
1,755
3.84375
4
[ "MIT" ]
permissive
#include "lab_07_library.h" #include <cmath> #include <iostream> int modulo_1(int value, int dividend) { int quotient = value / dividend; int rest_of_division = value - quotient * dividend; return rest_of_division; } int modulo_2(int value, int dividend) { while (value >= dividend) { value -= dividend; } return value; } float calculate_average(int* values, int number_of_values) { int sum_of_values = 0; for (int i = 0; i < number_of_values; ++i) { sum_of_values += values[i]; } float average = (float)sum_of_values / number_of_values; return average; } float calculate_standard_deviation(int* values, int number_of_values) { float average = calculate_average(values, number_of_values); float sum_of_squared_differences = 0.0; for (int i = 0; i < number_of_values; ++i) { sum_of_squared_differences += pow(values[i] - average, 2); } float standard_deviation = sqrt(sum_of_squared_differences / number_of_values); return standard_deviation; } int potega(int liczba, int doPotegi) { int wynik = 1; if (doPotegi > 0) { wynik = liczba; for (int i = 1; i < doPotegi; i++) { wynik = wynik * liczba; } } return wynik; } void sort(int* arr, int arr_size) { for (int i = 0; i < arr_size; ++i) { for (int j = 0; j < (arr_size - 1); ++j) { if (arr[j] < arr[j + 1]) { std::swap(arr[j], arr[j + 1]); } } } } void print_array(int* arr, int arr_size) { for (int i = 0; i < arr_size; i++) { std::cout << arr[i] << ", "; } std::cout << std::endl; } float median(int* arr, int arr_size) { float result = 0; if (arr_size % 2 == 0) { result = ((float)arr[arr_size / 2 - 1] + (float)arr[arr_size / 2]) / 2; } else { result = (float)arr[arr_size / 2]; } return result; }
true