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
55896e5f029d0cc9afe360bd584871b779992aff
C++
CodingWD/course
/c/niuhongli/chapter02/ex2.21.cpp
UTF-8
170
3.25
3
[]
no_license
#include<iostream> int main() { int sum=0; for (int i=0; i!=10; ++i){ sum+=i; std::cout << " Sum from 0 to " << i << " is " << sum << std::endl; } return 0; }
true
b5eb63d784a671c0bfd8730e48284c626766146c
C++
anuin-cat/QG
/Code-1/duLinkList/duLinkedList.cpp
UTF-8
2,737
3.265625
3
[]
no_license
#include "../head/duLinkedList.h" using namespace std; /** * @name : Status InitList_DuL(DuLinkedList *L) * @description : initialize an empty linked list with only the head node * @param : L(the head node) * @return : Status * @notice : None */ Status InitList_DuL(DuLinkedList *L) { if(!L) return ERROR; *L = new DuLNode(); (*L) -> prior = (*L) -> next = nullptr; (*L) -> data = -1; return SUCCESS; } /** * @name : void DestroyList_DuL(DuLinkedList *L) * @description : destroy a linked list * @param : L(the head node) * @return : status * @notice : None */ void DestroyList_DuL(DuLinkedList *L) { DuLNode* temp1 = *L, * temp2 = nullptr; DuLNode* head = (*L) -> next; while(temp1) { temp2 = temp1; temp1 = temp1 -> next; if(temp1 == head) return; delete temp2; } } /** * @name : Status InsertBeforeList_DuL(DuLNode *p, LNode *q) * @description : insert node q before node p * @param : p, q * @return : status * @notice : None */ Status InsertBeforeList_DuL(DuLNode *p, DuLNode *q) { if(q == nullptr || p == nullptr) return ERROR; DuLNode* pr = p -> prior; q -> prior = pr; p -> prior = q; q -> next = p; if(pr) pr -> next = q; return SUCCESS; } /** * @name : Status InsertAfterList_DuL(DuLNode *p, DuLNode *q) * @description : insert node q after node p * @param : p, q * @return : status * @notice : None */ Status InsertAfterList_DuL(DuLNode *p, DuLNode *q) { if(!q || !p) return ERROR; DuLNode* next = p -> next; p -> next = q; q -> next = next; q -> prior = p; if(next) next -> prior = q; } /** * @name : Status DeleteList_DuL(DuLNode *p, ElemType *e) * @description : delete the first node after the node p and assign its value to e * @param : p, e * @return : status * @notice : None */ Status DeleteList_DuL(DuLNode *p, ElemType *e) { if(!p || !p -> next) return ERROR; DuLNode* next = p -> next, * next1 = next -> next; *e = next -> data; p -> next = next1; if(next1) next -> prior = p; delete next; return SUCCESS; } /** * @name : void TraverseList_DuL(DuLinkedList L, void (*visit)(ElemType e)) * @description : traverse the linked list and call the funtion visit * @param : L(the head node), visit * @return : Status * @notice : None */ void TraverseList_DuL(DuLinkedList L, void (*visit)(ElemType e)) { if(!L) return; DuLNode* head = L -> next; L = L -> next; while(L) { visit(L -> data); L = L -> next; if(L == head) return; } }
true
3d9fa4bfc7c3f4c842c5e70cae71959374d4459c
C++
jk793092/CPlusPlus
/CircularqueueusingArray.cpp
UTF-8
1,540
3.625
4
[]
no_license
#include<iostream> using namespace std; class CircularQ { private: int size; int front; int rear; int *A; public: CircularQ(){} ~CircularQ(){delete []A;} void display(); void create(); void enqueue(); int dequeue(); int isFull(); int isEmpty(); }; void CircularQ::display() { int i=(front+1)%size; while(i!=((rear+1)%size)) { cout<<A[i]<<" "; i=(i+1)%size; } cout<<endl; } void CircularQ::create() { cout<<"Enter size:"; cin>>size; A=new int[size]; front=0; rear=0; } void CircularQ::enqueue() { int x; cout<<"Enter no to enqueue:"; cin>>x; if((rear+1)%size == front) cout<<"Queue is full\n"; else { rear=(rear+1)%size; A[rear]=x; } } int CircularQ::dequeue() { int x=-1; if(front==rear) cout<<"Queue is Empty\n"; else { front=(front+1)%size; x=A[front]; } return x; } int CircularQ::isFull() { if((rear+1)%size==front) return 1; return 0; } int CircularQ::isEmpty() { if(front==rear) return 1; return 0; } int main() { CircularQ q1; q1.create(); q1.enqueue(); q1.enqueue(); // q1.enqueue(); cout<<q1.isFull()<<endl; /*cout<<q1.dequeue()<<endl; q1.display(); cout<<q1.dequeue()<<endl; q1.display(); cout<<q1.dequeue()<<endl; q1.display(); cout<<q1.isEmpty()<<endl;*/ q1.display(); return 0; }
true
d6ceba4e40b977d90b9d5474a715d31677c12944
C++
Keeqlin/HMM
/include/hmm.hpp
UTF-8
8,995
2.890625
3
[]
no_license
#ifndef HMM_HPP #define HMM_HPP #include <stdio.h> #include <stdlib.h> #include <time.h> #include <cstdlib> #include <ctime> #include <functional> #include <iostream> #include <list> #include <memory> #include <random> #include <vector> class SimpleHMM { public: struct Lambda { Lambda(std::vector<std::vector<double>> &A, std::vector<std::vector<double>> &B, std::vector<double> &PI) : A_(A), B_(B), PI_(PI) {} std::vector<std::vector<double>> &A_; // Transition matrix std::vector<std::vector<double>> &B_; // Emission matrix std::vector<double> &PI_; // Initial probability }; public: SimpleHMM(); std::vector<size_t> generate(const std::vector<std::vector<double>> &A, const std::vector<std::vector<double>> &B, const std::vector<double> &PI, size_t T); inline std::vector<size_t> generate(const Lambda &lambda, size_t T) { return generate(lambda.A_, lambda.B_, lambda.PI_, T); } double evaluate(std::vector<size_t> &observations, const Lambda &lambda); std::vector<size_t> decode(std::vector<size_t> &observations, const Lambda &lambda); template <typename T> void VecDisplay(const std::vector<T> &vec, const std::string &vecName) { } private: size_t getDataWithGivenProb(const std::vector<double> &prob); std::default_random_engine generator_; std::uniform_real_distribution<double> uniform_distribution_; }; class State { public: State() {} explicit State(size_t id) : id_(id) {} size_t id_; friend std::ostream &operator<<(std::ostream &out, const State &rhs) { out << rhs.id_; return out; } }; class Observation { public: Observation() {} explicit Observation(size_t id) : id_(id) {} size_t id_; friend std::ostream &operator<<(std::ostream &out, const Observation &rhs) { out << rhs.id_; return out; } }; inline size_t indexOf(size_t id) { return (id - 1); } class DataGenerator { public: DataGenerator(size_t N, size_t M) { generator_ = std::default_random_engine(time(NULL)); uniform_distribution_ = std::uniform_real_distribution<double>(0, 1); A_ = std::vector<std::vector<double>>(N, std::vector<double>(N, 0)); B_ = std::vector<std::vector<double>>(N, std::vector<double>(M, 0)); // srand(time(NULL)); srand(0); // Initialization of A; for (size_t i = 0; i < N; i++) { double random_A = 0.4 * rand() / (RAND_MAX + 1.0); double random_B = (0.9 - 0.6) * rand() / (RAND_MAX + 1.0) + 0.6; double norm_prob = 0; for (size_t j = 0; j < N; j++) { A_[i][j] = ((double)rand() / (RAND_MAX + 1.0)); if (A_[i][j] < random_A) { // if (A_[i][j]) { // A_[i][j] /= (rand() % (10 - 0 + 1) + 0); // } // A_[i][j] = ((double)rand() / (RAND_MAX + 1.0)); A_[i][j] = 0; } if (A_[i][j] > random_B) { A_[i][j] *= (rand() % (10 - 0 + 1) + 0); } norm_prob += A_[i][j]; } // normalization std::cout << "A[" << i << "]: "; for (size_t j = 0; j < N; j++) { if (A_[i][j]) { A_[i][j] /= norm_prob; } std::cout << A_[i][j] << ", "; } std::cout << std::endl; } // Initialization of B; for (size_t i = 0; i < N; i++) { double random_A = 0.4 * rand() / (RAND_MAX + 1.0); double random_B = (0.9 - 0.75) * rand() / (RAND_MAX + 1.0) + 0.75; double norm_prob = 0; for (size_t j = 0; j < M; j++) { B_[i][j] = (double)rand() / (RAND_MAX + 1.0); if (B_[i][j] < random_A) { // if (B_[i][j]) { // B_[i][j] /= (rand() % (10 - 0 + 1) + 0); // } B_[i][j] = 0; } if (B_[i][j] > random_B) { B_[i][j] *= (rand() % (10 - 0 + 1) + 0); } norm_prob += B_[i][j]; } // normalization std::cout << "B[" << i << "]: "; for (size_t j = 0; j < M; j++) { if (B_[i][j]) { B_[i][j] /= norm_prob; } std::cout << B_[i][j] << ", "; } std::cout << std::endl; } } void generate(size_t T, std::vector<std::shared_ptr<State>> &sPtr, std::vector<std::shared_ptr<Observation>> &oPtr) { std::vector<std::shared_ptr<State>> sPtr_(T); std::vector<std::shared_ptr<Observation>> oPtr_(T); size_t N = A_.size(); size_t M = B_.size(); // data generation basd on A_ and B_ sPtr_[0] = std::make_shared<State>(rand() % (N - 1 + 1) + 1); oPtr_[0] = std::make_shared<Observation>(getDataWithGivenProb(B_[indexOf(sPtr_[0]->id_)])); for (size_t i = 1; i < T; i++) { size_t prevStateId = sPtr_[i - 1]->id_; std::shared_ptr<State> statePtr = std::make_shared<State>(getDataWithGivenProb(A_[indexOf(prevStateId)])); sPtr_[i] = statePtr; oPtr_[i] = std::make_shared<Observation>(getDataWithGivenProb(B_[indexOf(statePtr->id_)])); } std::swap(sPtr, sPtr_); std::swap(oPtr, oPtr_); } const std::vector<std::vector<double>> &A() { return A_; } const std::vector<std::vector<double>> &B() { return B_; } private: size_t getDataWithGivenProb(const std::vector<double> &prob) { double rand_data = uniform_distribution_(generator_); double prob_accum = 0; size_t data = 0; for (size_t i = 0; i < prob.size(); i++) { prob_accum += prob[i]; if (rand_data <= prob_accum) { // The range of state is [1, sizeof(prob)] data = (i + 1); break; } } return data; } private: std::default_random_engine generator_; std::uniform_real_distribution<double> uniform_distribution_; std::vector<std::vector<double>> A_; // Transition matrix std::vector<std::vector<double>> B_; // Emission matrix }; class Viterbi { public: using ProbOfFn = std::function<double(size_t i, size_t j)>; Viterbi(ProbOfFn &A, ProbOfFn &B) : ProbOfTransition_(A), ProbOfEmission_(B) {} std::vector<size_t> decode(std::vector<std::shared_ptr<Observation>> &observationPtr, size_t N) { size_t T = observationPtr.size(); std::vector<std::vector<double>> delta(T, std::vector<double>(N, 0)); std::vector<std::vector<size_t>> psi(T, std::vector<size_t>(N, 0)); std::vector<size_t> hiddenState(T, 0); // Initialization for (size_t S_n = 1; S_n <= N; S_n++) { size_t O_m = observationPtr[0]->id_; delta[0][indexOf(S_n)] = ProbOfEmission_(S_n, O_m); psi[0][indexOf(S_n)] = 0; } // Recursion for (size_t t = 1; t < T; t++) { size_t O_m = observationPtr[t]->id_; for (size_t S_j = 1; S_j <= N; S_j++) { double maxDelta = 0; size_t maxHiddenState = 0; for (size_t S_i = 1; S_i <= N; S_i++) { double tempDelta = delta[t - 1][indexOf(S_i)] * ProbOfTransition_(S_i, S_j); if (maxDelta < tempDelta) { maxDelta = tempDelta; maxHiddenState = S_i; } } delta[t][indexOf(S_j)] = maxDelta * ProbOfEmission_(S_j, O_m); psi[t][indexOf(S_j)] = maxHiddenState; } } // Terminiation double lastProb = 0; for (size_t S_i = 1; S_i <= N; S_i++) { if (lastProb < delta[T - 1][indexOf(S_i)]) { lastProb = delta[T - 1][indexOf(S_i)]; hiddenState[T - 1] = S_i; } } // Path backtracking for (int t = T - 2; t >= 0; t--) { size_t hiddenStateIdx = indexOf(hiddenState[t + 1]); hiddenState[t] = psi[t + 1][hiddenStateIdx]; } return hiddenState; } // std::vector<size_t> onlineInitialDecode(std::vector<std::shared_ptr<Observation>> &observationPtr) { // } private: class CandidateState { public: void push(std::shared_ptr<State> &&ptr) { NodeList_.emplace_back(std::move(ptr)); } size_t size() { return NodeList_.size(); } std::list<std::shared_ptr<State>> NodeList_; }; ProbOfFn &ProbOfTransition_; ProbOfFn &ProbOfEmission_; std::list<std::shared_ptr<CandidateState>> hmmStates_; }; #endif // HMM_HPP
true
1ff4a7e3158af83e49dbae74c6af9966e8018212
C++
rollfatcat/ProblemSet
/演算法題型分類/STL練習題/set/f929.cc
UTF-8
1,018
3.34375
3
[]
no_license
/* 給定N格的初始值和Q次操作,輸出查詢時陣列中第一個0的位置? * 1 x : 將陣列中第一個值是0位置的數值設定為 x * 2 x : 將陣列中第 x 個位置的數值設定為0 * 3 : 輸出陣列中第一個值是0的位置 * 解題關鍵:set * 容器必須支援 找到最小值/刪除指定數字/插入數字 ... set */ #include<bits/stdc++.h> using namespace std; const int MaxN=1e6; const int MaxQ=1e5; int num[MaxN]; int main(){ int N, Q, opt ,x; set<int> memo; scanf("%d",&N); for(int i=0; i<N; i+=1){ scanf("%d",&num[i]); if(num[i]==0) memo.insert(i); } scanf("%d",&Q); while(Q-->0){ scanf("%d",&opt); switch(opt){ case 1: scanf("%d",&x); if(memo.empty()==0 and x!=0){ num[ *memo.begin() ]=x; memo.erase(memo.begin()); } break; case 2: scanf("%d",&x); if(num[x]!=0){ num[x]=0; memo.insert(x); } break; default: printf("%d\n",(memo.empty()==0)? *memo.begin(): -1); } } }
true
e444080b0d08c96edf74948a7980aaa22e82a683
C++
bonezuk/athena
/source/common/src/DebugOutput.cxx
UTF-8
4,833
2.75
3
[]
no_license
#include "common/inc/DebugOutput.h" #include "common/inc/Log.h" //------------------------------------------------------------------------------------------- namespace omega { namespace common { //------------------------------------------------------------------------------------------- // DebugOutputItem //------------------------------------------------------------------------------------------- DebugOutputItem::DebugOutputItem() : m_name("DebugOutputItem"), m_level(6), m_time() { m_time = TimeStamp::now(); } //------------------------------------------------------------------------------------------- DebugOutputItem::DebugOutputItem(const QString& name,tint lvl) : m_name(name), m_level(lvl), m_time() { m_time = TimeStamp::now(); } //------------------------------------------------------------------------------------------- DebugOutputItem::DebugOutputItem(const DebugOutputItem& rhs) : m_name(), m_level(6), m_time() { copy(rhs); } //------------------------------------------------------------------------------------------- void DebugOutputItem::copy(const DebugOutputItem& rhs) { m_name = rhs.m_name; m_level = rhs.m_level; m_time = rhs.m_time; } //------------------------------------------------------------------------------------------- const QString& DebugOutputItem::name() const { return m_name; } //------------------------------------------------------------------------------------------- tint DebugOutputItem::level() const { return m_level; } //------------------------------------------------------------------------------------------- const common::TimeStamp& DebugOutputItem::time() const { return m_time; } //------------------------------------------------------------------------------------------- const DebugOutputItem& DebugOutputItem::operator = (const DebugOutputItem& rhs) { if(this!=&rhs) { copy(rhs); } return *this; } //------------------------------------------------------------------------------------------- QString DebugOutputItem::printStamp() const { BString x; QString y; x = m_name.toLatin1().constData(); x += ": "; x += BString::Int(m_time.hour(),2,true); x += ":"; x += BString::Int(m_time.minute(),2,true); x += ":"; x += BString::Int(m_time.second(),2,true); x += "."; x += BString::Int(m_time.millisecond(),3,true); x += " - "; y = QString::fromLatin1(static_cast<const tchar *>(x)); return y; } //------------------------------------------------------------------------------------------- QString DebugOutputItem::printTime(const TimeStamp& t) const { BString x; QString y; x = common::BString::Int(t.minute(),2,true); x += ":"; x += common::BString::Int(t.second(),2,true); x += "."; x += common::BString::Int(t.microsecond(),6,true); y = QString::fromLatin1(static_cast<const tchar *>(x)); return y; } //------------------------------------------------------------------------------------------- QString DebugOutputItem::print() const { return printStamp(); } //------------------------------------------------------------------------------------------- // DebugOutput //------------------------------------------------------------------------------------------- DebugOutput *DebugOutput::m_instance = 0; //------------------------------------------------------------------------------------------- DebugOutput::DebugOutput(tint debugLevel) : m_debugLevel(debugLevel), m_mutex(), m_list() {} //------------------------------------------------------------------------------------------- DebugOutput::~DebugOutput() { m_instance = 0; } //------------------------------------------------------------------------------------------- DebugOutput& DebugOutput::instance(tint debugLevel) { if(m_instance==0) { m_instance = new DebugOutput(debugLevel); } return *m_instance; } //------------------------------------------------------------------------------------------- void DebugOutput::append(const DebugOutputItem& item) { if(item.level()>=m_debugLevel) { m_mutex.lock(); m_list.append(item.print()); m_mutex.unlock(); } } //------------------------------------------------------------------------------------------- void DebugOutput::print() { QStringList::const_iterator ppI; m_mutex.lock(); for(ppI=m_list.begin();ppI!=m_list.end();++ppI) { const QString& x = *ppI; Log::g_Log << x.toLatin1().constData() << c_endl; } m_list.clear(); m_mutex.unlock(); } //------------------------------------------------------------------------------------------- tint DebugOutput::level() const { return m_debugLevel; } //------------------------------------------------------------------------------------------- } // namespace common } // namespace omega //-------------------------------------------------------------------------------------------
true
7336b76c8633f00509f1ae2176533c262977a6e3
C++
alexgavrisyuk/Cocos2d-x___test-project
/PlayerBulletGraphicComponent.h
UTF-8
806
2.515625
3
[]
no_license
#ifndef __PLAYER_BULLET_GRAPHIC_COMPONENT_H__ #define __PLAYER_BULLET_GRAPHIC_COMPONENT_H__ #include "cocos2d.h" #include "GraphicComponent.h" using namespace std; using namespace cocos2d; class PlayerBulletGraphicComponent : public GraphicComponent { public: PlayerBulletGraphicComponent(int attack, const std::string& typeObject); PlayerBulletGraphicComponent(PlayerBulletGraphicComponent& bullet); virtual void Update(Monster& hero, GameScene& scene); virtual int GetAttack() const; virtual int GetHealth() const; virtual std::string GetTypeObject() const; virtual bool Dead(int wounded); void LoadBulletNormal(); void LoadBomb(); ~PlayerBulletGraphicComponent(); private: cocos2d::Point m_position; std::string m_typeObject; int m_attack; std::string m_strFilename; }; #endif
true
b20649433ce90824911a928fc74748e8e83d6d05
C++
donovan-PNW/jCS162
/completed/project1/project1.cpp
UTF-8
2,780
3.859375
4
[]
no_license
#include <iostream> #include <fstream> using namespace std; void carCategory(char nextChar, int& usCount, int& euroCount, int& japanCount); void weightClass(char nextChar, int& betweeen1And2, int& between2And3, int& between3And4, int& above4); int main() { int semiCount; int index; char letter; char nextChar; int usCount = 0; int euroCount = 0; int japanCount = 0; int betweeen1And2 = 0; int between2And3 = 0; int between3And4 = 0; int above4 = 0; //char carLine [1000] //TO DO: make an if/else statement for index 6 (weight) and 9 (category) //then for if, do a weight function, and for 9 do a category thing // make sure of these numbers //use .peek() to get next character ifstream inputFile; inputFile.open("cars.txt"); //Here I'm reading through each character to find semicolons //and then using the modulus operator to figure out what part of the data file I'm in while(!inputFile.eof()) { inputFile >> letter; nextChar = inputFile.peek(); if (letter == ';') { semiCount++; //consider switching these two index = semiCount % 8; //9 separate categories //cout << semiCount << index << endl; if (index == 0) { carCategory(nextChar, usCount, euroCount, japanCount); } else if (index == 5) { weightClass(nextChar, betweeen1And2, between2And3, between3And4, above4); } } } //cout << semiCount << endl << index << endl; cout << "CAR CATEGORY COUNT:" << endl; cout << "US: " << usCount << "\nEuropean: " << euroCount << "\nJapanese: " << japanCount << endl; cout << endl << endl << "WEIGHT CLASS COUNTS:" << endl; cout << "Cars between 1000 and 2000 lbs: " << betweeen1And2; cout << "\nCars between 2000 and 3000 lbs: " << between2And3; cout << "\nCars between 3000 and 4000 lbs: " << between3And4; cout << "\nCars above 4000 lbs: " << above4 << endl; return 0; } void carCategory(char nextChar, int& usCount, int& euroCount, int& japanCount) { if (nextChar == 'U') { usCount++; } else if (nextChar == 'E') { euroCount++; } else { japanCount++; } //cout << "supbro!" << endl << endl; //this is where you pull category //Again put this elsewhere. Pulls 1st character after last semicolon on line return; } void weightClass(char nextChar, int& betweeen1And2, int& between2And3, int& between3And4, int& above4) { //cout << " " << nextChar; switch (nextChar) { case '1': betweeen1And2++; break; case '2': between2And3++; break; case '3': between3And4++; break; default: above4++; break; } return; } // backup void carCategory(int index, char nextChar, int& usCount, int& euroCount, int& japanCount)
true
c73cd87378d454548bf0a9bbae93f20645645880
C++
lucasprimo375/Programming-Lab
/huffman_coding/utils.h
UTF-8
1,804
2.71875
3
[]
no_license
#ifndef UTILS_H #define UTILS_H #include <string> #include <unordered_map> #include <vector> #include "min_heap.h" #include "node.h" namespace Utils { void print_file(std::string file_name); std::unordered_map<char, int>* get_frequency_table(std::string file_name); void insert_characters(std::unordered_map<char, int>* frequency_table, char Char); void print_frequency_table(std::unordered_map<char, int>* frequency_table); MinHeap* build_frequency_min_heap( std::string file_name ); void generate_huffman_code( node* root, node* n, std::string* code, std::unordered_map<std::string, std::string>* code_map ); void print_code_map(std::unordered_map<std::string, std::string>* code_map); bool write_coded_file(std::unordered_map<std::string, std::string>* code_map, std::string file_name_to_encode, std::string output_file_name, node* treeRoot); std::string encode_string( std::unordered_map<std::string, std::string>* code_map, std::string string_to_encode ); void write_tree_to_file( std::ofstream& output_stream, node* treeRoot ); void write_tree(node* n, std::vector<char>& tree); bool write_string_to_file( std::string string, std::string output_file_name); std::unordered_map<std::string, std::string>* build_code_map( std::string file_to_decode ); void write_decoded_file( std::unordered_map<std::string, std::string>* code_map, std::string file_name_to_decode, std::string output_file_name ); std::string decode_string( std::unordered_map<std::string, std::string>* code_map, std::string string ); bool is_string_decodable( std::string string ); bool compare_files( std::string first, std::string second ); void decode( std::string file_name_to_decode, std::string output_file_name ); node* build_tree( std::string output_string, int& position, node* n ); }; #endif
true
03f207eadf6ac167e1b31053299020999de834b7
C++
twinsavitha/suresh-atu-c-sessions
/C++Sessions/Upload/STL/Stacks.cpp
UTF-8
533
3.765625
4
[]
no_license
/* * Stacks.cpp * * Created on: 24-Dec-2013 */ #include <iostream> #include <stack> int main() { std::stack<int> stObj; stObj.push(23); stObj.push(-7); stObj.push(0); std::cout << "The element at top is " << stObj.top() << "\n"; std::cout << "Number of elements in the stack is " << stObj.size() << "\n"; stObj.push(14); stObj.push(19); while (stObj.empty() == false) { std::cout << "Element retrieved from top is " << stObj.top() << "\n"; stObj.pop(); } return(0); }
true
483a940acbd2274e8232318acdc0beac90c4c011
C++
fengwang/larbed-refinement
/include/f/variate_generator/vg/distribution/gaussian_tail.hpp
UTF-8
3,552
2.515625
3
[]
no_license
/* vg -- random variate generator library Copyright (C) 2010-2012 Feng Wang (feng.wang@uni-ulm.de) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MGAUSSIAN_TAIL_HPP_INCLUDED_OIHJ3LKJAFS98UYH3KJHFAS9I8UHY2QR3OIUHFSIOUHEIUHY3 #define MGAUSSIAN_TAIL_HPP_INCLUDED_OIHJ3LKJAFS98UYH3KJHFAS9I8UHY2QR3OIUHFSIOUHEIUHY3 #include <f/variate_generator/vg/distribution/normal.hpp> #include <f/singleton/singleton.hpp> #include <cassert> namespace f { template < typename Return_Type, typename Engine > struct gaussian_tail : private normal<Return_Type, Engine> { typedef Return_Type return_type; typedef Engine engine_type; typedef normal<return_type, engine_type> normal_type; typedef typename normal_type::final_type final_type; typedef typename normal_type::seed_type seed_type; return_type a_; return_type variance_; engine_type& e_; explicit gaussian_tail( const return_type a = 0, const return_type variance = 1, const seed_type sd = 0 ) : a_( a ), variance_( variance ), e_( singleton<engine_type>::instance() ) { assert( variance > 0 ); e_.reset_seed( sd ); } return_type operator()() const { return do_generation( a_, variance_ ); } protected: return_type do_generation( const final_type A, const final_type Variance ) const { if ( Variance > A ) { return gaussian_tail_direct_impl( A, Variance ); } return rectangle_wedge_tail_method( A, Variance ); } private: return_type rectangle_wedge_tail_method( const final_type A, const final_type Variance ) const { const final_type s = A / Variance; for ( ;; ) { const final_type u = e_(); const final_type v = e_(); if ( final_type( 0 ) == u || final_type( 0 ) == v ) { continue; } const final_type x = std::sqrt( s * s - std::log( v ) ); if ( s >= x * u ) { return x * Variance; } } } return_type gaussian_tail_direct_impl( const final_type A, const final_type Variance ) const { const final_type s = A / Variance; for ( ;; ) { const final_type ans = normal<Return_Type, Engine>:: do_generation(); if ( ans >= s ) { return ans; } } } }; }//vg #endif//_GAUSSIAN_TAIL_HPP_INCLUDED_OIHJ3LKJAFS98UYH3KJHFAS9I8UHY2QR3OIUHFSIOUHEIUHY3
true
0a2484c80c850794969755f039d73685fb22b91e
C++
evilknivel/ESP_Windowsensor
/ATtiny/firmware.ino
UTF-8
2,318
2.671875
3
[]
no_license
#include <avr/sleep.h> #include <avr/interrupt.h> //Prototypen: void gotoSleep(void); #define esp_power 2 #define esp_ready 4 #define switch_state 1 #define sensor 3 volatile bool wakeup = false; bool statusSleep = true; bool boottime = false; void setup() { pinMode(sensor, INPUT); pinMode(esp_ready, INPUT_PULLUP); pinMode(esp_power, OUTPUT); digitalWrite(esp_power, LOW); pinMode(switch_state, OUTPUT); ADCSRA &= ~_BV(ADEN); //ADC ausschalten //Setzen der Register fuer Pin-Change-Interrupt Pin PB3 //Loeschen des Global Interrupt Enable Bits (I) im Status Register (SREG) SREG &= 0x7F; //entspricht "cli();" //Setze des Pin Change Interrupt Enable Bit GIMSK |= (1 << PCIE); //Setzen des Pin Change Enable Mask Bit 3 (PCINT3) ==> Pin PB3 PCMSK |= (1 << PCINT3); //Setzen des Global Interrupt Enable Bits (I) im Status Register (SREG) SREG |= 0x80; //entspricht "sei();" } void loop() { if (wakeup) { digitalWrite(switch_state, digitalRead(sensor)); digitalWrite(esp_power, HIGH); if (boottime) //ESPzeit geben um esp_ready auf low zu setzen. { delay(1000); boottime = false; } if (!digitalRead(esp_ready)) //timeout hinzufügen! { digitalWrite(esp_power, LOW); //pinMode(sensor, OUTPUT); wakeup = false; statusSleep = true; } } if (statusSleep) { gotoSleep(); statusSleep = false; boottime = true; } } //Attiny in den Schlafmodus setzen void gotoSleep() { pinMode(esp_power, INPUT); pinMode(switch_state, INPUT); //byte adcsra; //adcsra = ADCSRA; //ADC Control and Status Register A sichern //ADCSRA &= ~_BV(ADEN); //ADC ausschalten MCUCR |= (1 << SM1) & ~(1 << SM0); //Sleep Modus = Power Down MCUCR |= _BV(SE); //Sleep Enable setzen sleep_cpu(); //Schlafe .... MCUCR &= ~(1 << SE); //Sleep Disable setzen //ADCSRA = adcsra; //ADCSRA-Register rückspeichern pinMode(esp_power, OUTPUT); pinMode(switch_state, OUTPUT); pinMode(sensor, INPUT); pinMode(esp_ready, INPUT_PULLUP); } //Interrupt Serviceroutine (Pin-Change-Interrupt) ISR(PCINT0_vect) { wakeup = true; }
true
20282c571a41221579e9a568959fd010e266ccc4
C++
monowireless/Act_samples
/Unit_brd_CUE/Unit_CUE.cpp
UTF-8
3,442
2.5625
3
[]
no_license
#include <TWELITE> #include <CUE> bool b_activate_adc3_4 = false; /*** the setup procedure (called on boot) */ void setup() { auto&& cue = the_twelite.board.use<CUE>(); the_twelite.begin(); // here cue object is setup. } /*** run only once at the initial */ void begin() { auto&& cue = the_twelite.board.use<CUE>(); cue.led_one_shot(100); // flashing LED for 100ms. Serial << crlf << "--- CUE peripheral testing ---"; Serial << crlf << " s : sleep 10sec or MAGnet waking."; Serial << crlf << " a : start MOTion sensor and sleep, waking at capture finish."; Serial << crlf << " l : turn LED on for 1sec."; delay(100); } /*** on wake up */ void wakeup() { auto&& cue = the_twelite.board.use<CUE>(); cue.led_one_shot(100); // flashing LED for 100ms. Serial << crlf; if (the_twelite.is_wokeup_by_wktimer()) { Serial << "..waking up (WakeTimer)"; } else if (the_twelite.is_wokeup_by_dio(CUE::PIN_SNS_INT)) { Serial << "..waking up (MOTion INT)"; } else if (the_twelite.is_wokeup_by_dio(CUE::PIN_SNS_NORTH)) { Serial << "..waking up (MAGnet INT [N])."; } else if (the_twelite.is_wokeup_by_dio(CUE::PIN_SNS_SOUTH)) { Serial << "..waking up (MAGnet INT [S])"; } else { Serial << "..waking up (unknown source)."; } } /*** the loop procedure (called every event) */ void loop() { auto&& cue = the_twelite.board.use<CUE>(); if (Serial.available()) { int c = Serial.read(); if (c >= 0) { Serial << crlf << '[' << char_t(c) << '/' << int(millis() & 0xFFFF) << "] "; switch(c) { case 's': { Serial << "..gonna sleep for 10sec..."; // set an interrupt for MAGnet sensor. pinMode(CUE::PIN_SNS_OUT1, PIN_MODE::WAKE_FALLING); pinMode(CUE::PIN_SNS_OUT2, PIN_MODE::WAKE_FALLING); // perform sleep the_twelite.sleep(10000, false); } break; case 'l': { Serial << "..turn led on for 1000ms..."; cue.led_one_shot(1000); } break; case 'a': { Serial << "..start MOTion sensor and sleep..."; cue.sns_MC3630.begin(SnsMC3630::Settings( SnsMC3630::MODE_LP_14HZ, SnsMC3630::RANGE_PLUS_MINUS_4G, 8)); // begin MC3630 // perform sleep the_twelite.sleep(2000, false); } break; } } } // wait for MOTion sensor capture. if (cue.sns_MC3630.available()) { // stop FIFO capture cue.sns_MC3630.end(); Serial << crlf << "..MOTion data is ready." << " (ct=" << int(cue.sns_MC3630.get_que().size()) << ')'; // get all samples and average them. int32_t x = 0, y = 0, z = 0; for (auto&& v: cue.sns_MC3630.get_que()) { Serial << crlf << format(" X=%+05d Y=%+05d Z=%+05d", v.x, v.y, v.z); } // clear available flag cue.sns_MC3630.get_que().clear(); // clean up the queue } if (!(millis() & 0x3ff)) { // every 1sec ; } }
true
5fa270f351d5454d4a46d5d9b408a68018e0daea
C++
adriacb/ADS
/n_queens.cc
UTF-8
2,169
3.828125
4
[]
no_license
// snippet of a class to implement the n times n chess board for the n-queens problem #include<iostream> #include<vector> using namespace std; class Board { private: // insert the code of the representation here // representation of the board, MATRIX, booleans int n; vector<vector<int> > b; public: Board(int n): b(n, vector<int>(n)) { //b = vector<vector<int> > (n, vector<int>(n)); for (int i =0; i < n; ++i){ for(int j = 0; j < n; ++j){ b[i][j] = 0; } } print_c(n); } //void draw() const { //} void print_c(int n) { cout << "ChessBoard representation" << endl; for (int x =0; x < n; ++x){ for(int j = 0; j < n; ++j){ cout << b[x][j] << " "; } cout << endl; } } bool free(int row, int column) { for(int i=0; i < row; ++i){ if (b[i][column]) return false; } for(int j=0; j < column; ++j){ if(b[row][j]) return false; } for (int i=row, j=column; i>=0 && j>=0; i--, j--) if (b[i][j]) //check whether there is queen in the left upper diagonal or not return false; for (int i=row, j=column; j>=0 && i<b.size(); i--, j++) if (b[i][j]) //check whether there is queen in the left lower diagonal or not return false; // check the diagonals now return true; } void put_q(int row, int column){ b[row][column] = 1; } void remove_q(int row, int column){ b[row][column] = 0; } }; bool attempt(int row, Board& board, int size){ int i; if (row == size) return true; else{ for (i = 0; i < size; ++i){ if (board.free(row, i)){ board.put_q(row, i); bool s = attempt(row+1, board, size); if(s) return true; else board.remove_q(row, i); } } return false; } } int main(){ int N; cout << "Enter the number of Queens: "; cin >> N; Board ChessBoard(N); attempt(0, ChessBoard, N); ChessBoard.print_c(N); ; }
true
0e0a3a18f4b929df8cbd6cf2625f0f19c2573a15
C++
SovietDoge47/HW7
/driver.cpp
UTF-8
3,009
3.46875
3
[]
no_license
#include <iostream> #include <string> #include "myFunctions.hpp" #include "LinkedList.hpp" using namespace std; int main(int argc, char** argv) { //URL* u1 = new URL("https://api.hearthstonejson.com/v1/25770/enUS/cards.json"); //cout << u1->getContents() << endl; //string jsonString = "[{\"fname\":\"val1\", \"lname\": \"val2\", \"sums\":[1,2,3]},{\"fname\":\"val3\", \"lname\":\"val4\"}]"; //cout << jsonString << endl; //processJSONObject(jsonString, 0); LinkedList* ll = new LinkedList(); ll->addEnd(4); ll->addStart(5); ll->addEnd(6); ll->addEnd(8); ll->addEnd(2); ll->display(); int value = ll->removeEnd(); ll->display(); cout << value << endl; ll->addStart(12); ll->display(); int startValue = ll->removeStart(); ll->display(); cout << startValue << endl; return 0; } string processJSONObject(string json, int start) { if(json[start] == '[') { return processJSONArray(json, start); } else if(json[start] == '{') { //must be an json object string temp = ""; int countCurlyBraces = 1; for(int i = start+1; i < json.length(); i++) { if(json[i] == '{') { temp += '{'; string answer = processJSONObject(json, i); temp += answer; i += answer.length()+1; countCurlyBraces++; } else if(json[i] == '}') { countCurlyBraces--; if(countCurlyBraces == 0) { cout << temp << endl; return temp; } } else if(json[i] == '[') { temp += '['; string answer = processJSONArray(json, i); temp += answer; i += answer.length()+1; } if(i < json.length()) { temp = temp + json[i]; } } } } string processJSONArray(string json, int start) { string temp = ""; int countSquareBrackets = 1; //process contents of the array for(int i = start+1; i < json.length(); i++) { if(json[i] == '[') { string answer = processJSONArray(json, i); temp += answer; i += answer.length()+1; countSquareBrackets++; } else if(json[i] == ']') { countSquareBrackets--; if(countSquareBrackets == 0) { cout << temp << endl; return temp; //return temp; } } else if(json[i] == '{') { temp += '{'; string answer = processJSONObject(json, i); temp += answer; i += answer.length()+1; } if(i < json.length()) { temp = temp + json[i]; } } }
true
91a6fd512d87647dea156b57c02b1f8041a5f266
C++
motomoto95/cc1-rep1
/FIFA/Team.cpp
UTF-8
509
2.921875
3
[]
no_license
#include <iostream> #include <string> #include "Team.h" using namespace std; Team::Team(){ Tname=""; } Team::~Team(){ for (int i = 0; i < 11; ++i) { delete []equipo[i]; } delete []equipo; } Team::Team(string pname){ Tname=pname; } void Team::insertaPlayer(Player x){ for (int i = 0; i < 11; ++i) { equipo[i]=&x; } } void Team::imprimeEquipo(){ cout<<"Los integrantes del equipo ["<<Tname<<"] son:"<<endl; for (int i = 0; i < 11; ++i) { equipo[i]->print(); } }
true
6a892944e64e7c2cec364ff14a7cbd3507d8f8ed
C++
rojas70/learning_ros_noetic
/Part_3/example_opencv/src/find_connected_components.cpp
UTF-8
2,193
2.828125
3
[]
no_license
//test use of blob detection #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/core/utility.hpp> #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include <opencv2/highgui/highgui.hpp> static const std::string OPENCV_WINDOW = "Open-CV display window"; using namespace std; #include <iostream> using namespace cv; using namespace std; //hard-coded image sizes for testing Mat_<uchar> C(3,3); Mat_<int>labelImage(3,3); void blob_color(void) { //find the regions: labelImage will contain integers corresponding to blob labels int nLabels = connectedComponents(C, labelImage, 4); //4 vs 8 connected regions //print out the region labels: cout << "labelImage = " << endl << " " << labelImage << endl << endl; //colorize the regions and display them: std::vector<Vec3b> colors(nLabels); colors[0] = Vec3b(0, 0, 0);//background //assign random color to each region label for(int label = 1; label < nLabels; ++label){ colors[label] = Vec3b( (rand()&255), (rand()&255), (rand()&255) ); } Mat dst(C.size(), CV_8UC3); //create an image the same size as input image //for display image, assign colors to regions for(int r = 0; r < dst.rows; ++r){ for(int c = 0; c < dst.cols; ++c){ int label = labelImage.at<int>(r, c); Vec3b &pixel = dst.at<Vec3b>(r, c); pixel = colors[label]; } } //display the result imshow( "Connected Components", dst ); } int main(int argc, char** argv) { ros::init(argc, argv, "blob_finder"); ros::NodeHandle n; // //create bw image: C(0,0)=0; C(0,1)=0; C(0,2)=255; C(1,0)=0; C(1,1)=0; C(1,2)=0; C(2,0)=0; C(2,1)=255; C(2,2)=255; cout << "C = " << endl << " " << C << endl << endl; blob_color(); //find connected components and print and display them namedWindow( "Image", WINDOW_AUTOSIZE); namedWindow( "Connected Components", WINDOW_AUTOSIZE); imshow( "Image", C ); //display it waitKey(0); return 0; }
true
339179489aee6f9ed04a9d5aa3f1cb3eeb62ad12
C++
sanjeetboora/CppCompetitive
/InterviewPreparation/LeetcodeCompanywise/Amazon/FavoriteGenres.cpp
UTF-8
2,340
3.15625
3
[]
no_license
//https://leetcode.com/discuss/interview-question/373006 #include <bits/stdc++.h> using namespace std; unordered_map<string, list<string> > favoritegenre( unordered_map<string, list<string> > userMap, unordered_map<string, list<string> > genreMap) { unordered_map<string, list<string> > result; unordered_map<string, string> songsGenres; for (auto x : genreMap) { for (auto song : genreMap[x.first]) { songsGenres[song] = x.first; } } for (auto x : userMap) { unordered_map<string, int> temp; pair<int, list<string> > maximum = {0, {}}; for (auto song : userMap[x.first]) { if (!songsGenres.count(song)) { continue; } temp[songsGenres[song]]++; if (temp[songsGenres[song]] == maximum.first) { maximum.second.push_back(songsGenres[song]); } if (temp[songsGenres[song]] > maximum.first) { maximum = {temp[songsGenres[song]], {songsGenres[song]}}; } } result[x.first] = maximum.second; } return result; } int main(int argc, char const *argv[]) { unordered_map<string, list<string> > userSongs; unordered_map<string, list<string> > songGenres; userSongs["David"] = {"song1", "song2"}; userSongs["Emma"] = { "song3", "song4"}; unordered_map<string, list<string> > result = favoritegenre(userSongs, songGenres); for (auto x : result) { cout << x.first << ": "; for (auto song : result[x.first]) { cout << song << ", "; } cout << endl; } return 0; } // Input // userSongs = { // "David": ["song1", "song2", "song3", "song4", "song8"], // "Emma": ["song5", "song6", "song7"] // }, // songGenres = { // "Rock": ["song1", "song3"], // "Dubstep": ["song7"], // "Techno": ["song2", "song4"], // "Pop": ["song5", "song6"], // "Jazz": ["song8", "song9"] // } // Output: { // "David": ["Rock", "Techno"], // "Emma": ["Pop"] // } // userSongs["David"] = {"song1", "song2", "song3", "song4", "song8"}; // userSongs["Emma"] = {"song5", "song6", "song7"}; // songGenres["Rock"] = {"song1", "song3"}; // songGenres["Dubstep"] = {"song7"}; // songGenres["Techno"] = {"song2", "song4"}; // songGenres["Pop"] = {"song5", "song6"}; // songGenres["Jazz"] = {"song8", "song9"}; // Input: // userSongs = { // "David": ["song1", "song2"], // "Emma": ["song3", "song4"] // }, // songGenres = {} // Output: { // "David": [], // "Emma": [] // }
true
2581c53dc99434d627ac1d38d93c0274929763d7
C++
SushkovVA/rdevices
/RTemperatureSensorDHT/rtemperaturesensordht.cpp
UTF-8
1,349
2.625
3
[]
no_license
#include "iostream" #include "rtemperaturesensordht.h" #include "pi_2_dht_read.h" const int DHT_TYPE = 22; RTemperatureSensorDHT::RTemperatureSensorDHT(QString name, int gpioOut, QObject *parent) : RDevice(name, parent), gpioOutPin(gpioOut) { addParameter("Temperature", DEFAULT_VALUE, ValueType_double, "-100.", "100."); addParameter("Humidity", DEFAULT_VALUE, ValueType_int, "0", "100"); } void RTemperatureSensorDHT::updateTemperature() { float hum, temp; pi_2_dht_read(DHT_TYPE, gpioOutPin, &hum, &temp); RParameter* temperature = getParameter("Temperature"); if ( temperature != NULL ) temperature->setValue(QString::number(temp)); } void RTemperatureSensorDHT::updateHumidity() { float hum, temp; pi_2_dht_read(DHT_TYPE, gpioOutPin, &hum, &temp); RParameter* humidity = getParameter("Humidity"); if ( humidity != NULL ) humidity->setValue(QString::number(hum)); } void RTemperatureSensorDHT::updateData(QString nameParameter) { if (nameParameter == "") { updateTemperature(); updateHumidity(); } else { if ( ! isParameterExist(nameParameter) ) return; if (nameParameter == "Temperature") updateTemperature(); else if (nameParameter == "Humidity") updateHumidity(); } }
true
dec6f2eeaf8fc8ca67755cf8eecef6f1373e960e
C++
yenan2500254897/cppLearn
/cppPrimerLearn/test.cpp
UTF-8
718
3.5625
4
[]
no_license
#include<iostream> #include<algorithm> #include<vector> using namespace std; int main(){ int a[] = {1,2,3}; //不能用+连接字符串和数字 std::cout<<"a[] size is: " << sizeof(a)/sizeof(*a)<<std::endl; std::cout<<"hello world"<<std::endl; vector<int> test ; test.push_back(1); test.push_back(2); test.push_back(3); test.push_back(1); test.push_back(2); test.push_back(3); sort(test.begin(), test.end()); for(int item:test){ cout<<" "<<item<<" "; } cout<<endl; unique(test.begin(), test.end()); for(vector<int>::iterator iter = test.begin();iter!=test.end();iter++){ cout<<" "<< *iter<<" "; } cout<<endl; }
true
1adcbccedf59a7a0b725bfc5c12e1f6285acc7e0
C++
WenShihKen/uva
/Leetcode/Implement strStr().cpp
UTF-8
310
2.65625
3
[]
no_license
class Solution { public: int strStr(string haystack, string needle) { if (needle == "") return 0; const char *temp = strstr(haystack.c_str(), needle.c_str()); if (temp - haystack.c_str() < 0) return -1; return temp - haystack.c_str(); } };
true
9fd1e01c1eaf08e55eefa4c93299591199658a45
C++
seco/esp8266_and_arduino
/_61-mma-8452-promini/a-01-simple/a-01-simple.ino
UTF-8
1,014
2.609375
3
[]
no_license
#include <Wire.h> #include <MMA8452.h> MMA8452 accelerometer; void setup() { Serial.begin(115200); Serial.print(F("Initializing MMA8452Q: ")); Wire.begin(); bool initialized = accelerometer.init(); if (initialized) { Serial.println(F("ok")); accelerometer.setDataRate(MMA_100hz); accelerometer.setRange(MMA_RANGE_2G); } else { Serial.println(F("failed. Check connections.")); while (true) {}; } } void loop() { float x; float y; float z; accelerometer.getAcceleration(&x, &y, &z); Serial.print(x, 5); Serial.print(F(" ")); Serial.print(y, 5); Serial.print(F(" ")); Serial.print(z, 5); Serial.println(); delay(10); } /* Initializing MMA8452Q: ok 0.00586 0.00098 0.98730 0.00391 -0.00098 0.99219 0.00391 -0.00098 0.98535 0.00879 0.00098 0.98730 0.00586 0.00098 0.98535 0.00586 -0.00098 0.98828 0.00684 0.00000 0.98535 0.00391 -0.00098 0.98633 0.00781 -0.00195 0.98828 0.00391 0.00098 0.98535 0.00586 0.00000 0.98828 0.00293 0.00098 0.98633 0.00000 -0.00195 0.98730 */ */
true
e8140384925508f8df38b47234658d3c24e0ab78
C++
dscnsec/DSC-NSEC-Algorithms
/7. Dynamic Programming/lucky_pairs/lucky_pairs_merlin.cpp
UTF-8
1,828
3.421875
3
[]
no_license
/** * lucky_pairs_merlin.cpp * Find longest common subsequence in two strings * * Description- * Lets find longest common subsequence of two strings first * In order to find longest common subsequence, we need to form a 2D dp array * Any cell dp[i][j] denotes the longest common subsequence that can be formed using the 1st i letters of string 1 and 1st j letters of string 2 * the value at any cell dp[i][j] can be calculated using the formula * dp[i][j]=dp[i-1][j-1]+1 if a[i] and b[j] are equal * dp[i][j]=max(dp[i-1][j],dp[i][j-1]) if the two indices are not equal, * this is because we are choosing the maximum value that can be obtained from the previous indices of i and j respectively * After we have found the lcs, we need to know if the lcs is > or equal to 1/2 the length of the larger string * * Time Complexity-O(n*m) where n and m are lengths of string 1 and string 2 respectively * Space Complexity-O(n*m) * * @author [merlin](https://github.com/m-e-r-l-i-n) */ #include<bits/stdc++.h> using namespace std; void solve() { string a,b; cin>>a>>b; int n=a.length(),m=b.length(),i,j; int dp[n+1][m+1]; dp[0][0]=0; for(i=0;i<=n;i++) for(j=0;j<=m;j++) { if(i==0 || j==0) //base case where we can have no lcs if 1 string's size is 0 dp[i][j]=0; else if(a[i-1]==b[j-1]) //if they are equal, we can just add 1 to the previous value dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } int v=(max(n,m)+1)/2; //need the +1 for cases where max is odd if(dp[n][m]>=v) cout<<"YES"; else cout<<"NO"; cout<<"\n"; } int main() { int t; cin>>t; while(t--) { solve(); } return 0; } /* input- 2 abcde ace abcde afgh output- YES NO */
true
dac5ae08adb0303f0453b373d49418f32551abbf
C++
ij96/Honeywell_RSC
/example/example.ino
UTF-8
1,384
2.875
3
[ "MIT" ]
permissive
/* circuit: pin name pin number on Arduino DRDY 6 CS_EE 7 CS_ADC 8 MOSI (DIN) 11 MISO (DOUT) 12 SCK 13 */ #include "Honeywell_RSC.h" // pins used for the connection with the sensor // the other you need are controlled by the SPI library): #define DRDY_PIN 6 #define CS_EE_PIN 7 #define CS_ADC_PIN 8 // create Honeywell_RSC instance Honeywell_RSC rsc( DRDY_PIN, // data ready CS_EE_PIN, // chip select EEPROM (active-low) CS_ADC_PIN // chip select ADC (active-low) ); void setup() { // open serial communication Serial.begin(9600); // open SPI communication SPI.begin(); // allowtime to setup SPI delay(5); // initialse pressure sensor rsc.init(); // print sensor information Serial.println(); rsc.print_catalog_listing(); rsc.print_serial_number(); Serial.print(F("pressure range:\t\t")); Serial.println(rsc.pressure_range()); Serial.print(F("pressure minimum:\t")); Serial.println(rsc.pressure_minimum()); rsc.print_pressure_unit_name(); rsc.print_pressure_type_name(); Serial.println(); // measure temperature Serial.print(F("temperature: ")); Serial.println(rsc.get_temperature()); Serial.println(); delay(5); } void loop() { // measure pressure Serial.print(F("pressure: ")); Serial.println(rsc.get_pressure()); delay(1000); }
true
e534e617ccac9616438dddb0598ad858f7f07f90
C++
tinng95/Core-Scheduler
/OSAssignment1/OSAssignment1/Instruction.h
UTF-8
340
2.78125
3
[]
no_license
#pragma once #include <iostream> #include <string.h> using namespace std; class Instruction { public: Instruction(string instruction, int data); Instruction(); ~Instruction(); void setInstruction(string instruction); void setData(int data); string getInstruction(); int getData(); private: string instruction; int data = 0; };
true
4278c071e28411a63633d4e92044b40e630c10c6
C++
VMPR-21/Neydorff
/Experementator.h
UTF-8
1,424
2.578125
3
[]
no_license
#ifndef EXPEREMENTATOR_H #define EXPEREMENTATOR_H #include "IExperementator.h" #include <vector> #include "IRegressionCoefficientTable.h" class IExperimentTable; //абстрактный класс для восхождения по градиенту и поиска экстремума. class Experementator : public IExperementator { public: //запустить процесс восхождения и поиска экстремума. // table - таблица c данными. // isMax - true, если ищем максимум. иначе - false // isExtremFound - найден экстремум или нет, последняя точка или экстремум или точка в которой проводи эксперимент virtual std::vector<ExperimentPoint> calcStepYt(bool isMax, const IExperimentTable &table, ExperimentStepsDelegatePtr experimentDelegate, bool* isExtremFound); //Величина начального шага double h; //количесвто шагов unsigned int ch; //допустимое отклонение double dev; //Величина начального шага - h, количесвто шагов - ch, допустимое отклонение - dev Experementator(double h = 0.5, unsigned int ch = 7, double dev = 30); }; #endif // EXPEREMENTATOR_H
true
7fe82b1d001aff785b49300cf3326479bcd19479
C++
GabeOchieng/ggnn.tensorflow
/program_data/PKU_raw/61/1465.c
UTF-8
378
2.546875
3
[]
no_license
int F(int m) { int f[m],i; for(i=0;i<m;i++) { if(i==1||i==0) { f[i]=1; }else{ f[i]=f[i-1]+f[i-2]; } } return f[m-1]; } int main() { int n,j; scanf("%d",&n); int s[n],r[n]; for(j=0;j<n;j++) { scanf("%d",&s[j]); r[j]=F(s[j]); } for(j=0;j<n;j++) { printf("%d\n",r[j]); } return 0; }
true
d90f7f4f6cdf71c7e0c62e4de23912ee74ddd724
C++
fuhailin/show-me-cpp-code
/leetcode_cc/377.combination-sum-iv.cc
UTF-8
749
3.453125
3
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
#include <iostream> #include <vector> using namespace std; class Solution { public: int combinationSum4(vector<int>& nums, int target) { int n = nums.size(); //dp[i]表示容量为i的背包有几种组合方式 vector<int> dp(target + 1, 0); dp[0] = 1; for (int i = 1; i <= target; ++i) { for (int& num : nums) { if (num <= i && dp[i] + dp[i - num] < INT_MAX) { dp[i] += dp[i - num]; } } } return dp[target]; } }; int main(int argc, char const* argv[]) { Solution so; vector<int> test = {1, 2, 3}; int res = so.combinationSum4(test, 4); cout << "result: " << res << endl; return 0; }
true
035335c2f2ae46f87a48e29d270dbfff21dbb26f
C++
kai-zhang-er/multi-task-rpi2
/TD5/PosixThread.h
UTF-8
2,154
3.15625
3
[ "Apache-2.0" ]
permissive
/** * @file PosixThread.h * @author ZK * @brief * @version 0.1 * @date 2021-04-03 * * @copyright Copyright (c) 2021 * */ #ifndef POSIXTHREAD_H_INCLUDED_2021_04_03 #define POSIXTHREAD_H_INCLUDED_2021_04_03 #include <pthread.h> #include <exception> using namespace std; class PosixThread { public: /** * @brief Construct a new Posix Thread object * */ PosixThread(); /** * @brief Construct a new Posix Thread object * * @param posixId thread id */ PosixThread(pthread_t posixId); /** * @brief Destroy the Posix Thread object * */ ~PosixThread(); /** * @brief start the thread * * @param threadFunc handler function of the thread * @param threadArg arguments */ void start(void*(*threadFunc)(void*), void* threadArg); /** * @brief wait the thread stops * */ void join(); /** * @brief stop the thread after time interval * * @param timeout_ms time interval * @return true successfully stop * @return false failed */ bool join(double timeout_ms); /** * @brief Set the Scheduling object * * @param schedPolicy schedule policy * @param priority priority of current thread * @return true set successfully * @return false failed */ bool setScheduling(int schedPolicy, int priority); /** * @brief Get the Scheduling object * * @param pSchedPolicy schedule policy pointer * @param pPriority priority of current thread pointer * @return true get successfully * @return false failed */ bool getScheduling(int* pSchedPolicy, int* pPriority); public: class Exception:exception { public: /** * @brief define an exception when launching the thread * * @return const char* */ const char* threadException() const noexcept; }; private: pthread_t posixId; ///< thread id pthread_attr_t posixAttr; ///< attributes of the thread protected: bool isActive; ///< thread flag: active or inactive }; #endif
true
505e192732cb1b067c9194a4a0c4228b7076eb42
C++
cristeigabriel/basil
/tests/csgo.cc
UTF-8
2,487
2.671875
3
[ "WTFPL" ]
permissive
#include "../basil.hh" #include <iostream> #include <stdexcept> using namespace basil; int main() { try { // capture contents of process named "csgo.exe" in the process list basil::ctx obj("csgo.exe"); // print name and pid std::cout << "name: " << obj.get_name() << " pid: " << obj.get_pid().value() << '\n'; // store all modules obj.capture_all_modules(); // retrieve "client.dll", we assume it's present by retrieving value directly auto client = obj.get_module("client.dll").value(); // print start as an address and size std::cout << std::hex << "start: " << (uintptr_t)(client.start_) << " size: " << client.size_ << '\n'; // auto state = obj.write_module_memory("fastprox.dll", 0xB5210, 0x0); // if (state.first) { // std::cout << "succesfully wrote at said address.\n"; // } // read first memory page from client.dll, assume page is readable and that we won't have a partial copy by retrieving // value directly auto page = obj.read_module_memory<detail::page>("client.dll", 0x0).value(); // print first page for (auto b : page.first) { std::cout << b; } // find pointer to local player position in entity list constexpr std::array local_sig = {0x83, 0x3D, -1, -1, -1, -1, -1, 0x75, 0x68, 0x8B, 0x0D, -1, -1, -1, -1, 0x8B, 0x01}; auto local = obj.pattern_scan_module("client.dll", local_sig); // print health if (local.has_value()) { const auto read = obj.read_memory<uintptr_t>(local.value() + 2); if (read.has_value()) { const auto& [bytes, bytes_read] = read.value(); const auto read = obj.read_memory<uintptr_t>(bytes); if (read.has_value()) { const auto& [player, bytes_read] = read.value(); const auto read = obj.read_memory<int>(player + 0x100); if (read.has_value()) { auto [health, bytes_read] = read.value(); std::cout << "\nlocal health: " << std::dec << health; } } } } } catch (const std::exception& err) { // print and flush buffers std::cout << err.what() << std::endl; std::exit(EXIT_FAILURE); } return 0; }
true
c8fdbfd896498a0258105728a5c1b3007764a871
C++
HoloborodkoMykhailo/training
/IP_02_Holoborodko_dop_2/Source.cpp
UTF-8
3,336
3.265625
3
[]
no_license
/*Згенерувати цілочисельну матрицю Q (p x n), яка містить як додатні, так і від’ємні елементи із діапазону [-90, 90]. Серед рядків матриці, що містять від’ємні елементи на головній діагоналі, знайти "особливий" елемент матриці, вважаючи "особливим" елемент, сума цифр якого є максимальною.На основі зміненої матриці Q створити масив рядків K, кожен рядок якого - це послідовність, розділених пробілом, подвоєних чисел відповідного рядка матриці Q. У кожному рядку отриманого масиву рядків K видалити усі символи, що не є цифрами чи пробілом. */ #include<iostream> #include<iomanip> #include<ctime> #include<string> #include<cmath> using namespace std; int** createM(int p, int n); void showM(int** Q, int p, int n); int* find(int** Q, int p, int n, int& kilk); void showmas(int* mas, int kilk); int* rownumb(int** Q, int p, int n, int& kilk); int* speciall(int** Q, int* mas1, int* mas2, int p, int n, int kilk); int main() { int p, n, kilk = 0, kilk1 = 0; cout << "Enter p: "; cin >> p; cout << "Enter n: "; cin >> n; int** Q = createM(p, n); showM(Q, p, n); int* mas = find(Q, p, n, kilk); showmas(mas, kilk); int* mas1 = rownumb(Q, p, n, kilk1); showmas(mas1, kilk1); int* mas2 = speciall(Q, mas, mas1, p, n, kilk); showmas(mas2, kilk1); } int** createM(int p, int n) { srand(time(NULL)); int** Q = new int* [p]; for (int i = 0; i < p; i++) { Q[i] = new int[n]; for (int j = 0; j < n; j++) { Q[i][j] = rand() % 181 - 90; } } return Q; } void showM(int** Q, int p, int n) { for (int i = 0; i < p; i++) { for (int j = 0; j < n; j++) { cout << setw(5) << Q[i][j]; } cout << endl; } cout << endl; } int* find(int** Q, int p, int n, int& kilk) { int* mas = new int[p]; for (int i = 0; i < p; i++) { for (int j = 0; j < n; j++) { if ((i == j) && (Q[i][i] < 0)) { mas[kilk] = Q[i][j]; kilk++; } } } return mas; } void showmas(int* mas, int kilk) { for (int i = 0; i < kilk; i++) { cout << setw(5) << mas[i]; } cout << endl; } int* rownumb(int** Q, int p, int n, int& kilk) { int* mas = new int[p]; for (int i = 0; i < p; i++) { for (int j = 0; j < n; j++) { if ((i == j) && (Q[i][j] < 0)) { mas[kilk] = i + 1; kilk++; } } } return mas; } int* speciall(int** Q, int* mas1, int* mas2, int p, int n, int kilk) { int* mas = new int[kilk]; int MAX; for (int i = 0; i < kilk; i++) { int sum = 0; for (int j = 0; j < n; j++) { int elem = abs(Q[mas2[i] - 1][j]); while (elem != 0) { int a = elem % 10; sum += a; elem = elem / 10; } MAX = sum; break; } for (int j = 0; j < n; j++) { int sum1 = 0; int elem1 = abs(Q[mas2[i] - 1][j]); while (elem1 != 0) { int a = elem1 % 10; sum1 += a; elem1 = elem1 / 10; } int MAX1 = sum1; if (MAX1 >= MAX) { MAX = MAX1; } else continue; } mas[i] = MAX; } return mas; }
true
e52e02cb32a35a825ca9ddfc48957b404a4af1db
C++
ichsnn/algoritma
/pemilihan/UpahKaryawan1.cpp
UTF-8
923
3.3125
3
[]
no_license
#include <iostream> #include <string> int main() { //DEKLARASI const int JamNormal = 48; const int UpahLembur = 3000; std::string nama; char gol; int jjk; float lembur; int upahperjam; int upahtotal; //ALGORITMA std::cout<<"Nama : ";std::getline(std::cin, nama); std::cout<<"Golongan : ";std::cin>>gol; std::cout<<"Jumlah Jam Kerja : ";std::cin>>jjk; if(gol == 'A') upahperjam = 4000; else if(gol == 'B') upahperjam = 5000; else if(gol == 'C') upahperjam = 6000; else if(gol == 'D') upahperjam = 7000; if(jjk<=JamNormal) upahtotal = jjk*upahperjam; else { lembur = jjk - JamNormal; upahtotal = JamNormal*upahperjam + lembur*UpahLembur; } std::cout<<"Nama : "<<nama<<"\n"; std::cout<<"Golongan : "<<gol<<"\n"; std::cout<<"Upah : "<<upahtotal<<"\n"; return 0; }
true
b500c2d9f2ad80f8eded88442bf056f028e5b475
C++
GrahamDumpleton-abandoned/ose
/software/include/OTC/memory/arena.hh
UTF-8
6,354
2.890625
3
[ "LicenseRef-scancode-generic-exception", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
#ifndef OTC_MEMORY_ARENA_HH #define OTC_MEMORY_ARENA_HH /* // This file is part of the OSE C++ class library. // // Copyright 1993 OTC LIMITED // Copyright 1994-2004 DUMPLETON SOFTWARE CONSULTING PTY LIMITED */ #include <OTC/memory/mpobject.hh> #include <OTC/memory/align.hh> #ifdef __GNUG__ #if (__GNUC__ < 3) && (__GNUC__MINOR__ < 95) #pragma interface "OTC/memory/arena.hh" #endif #endif /* ------------------------------------------------------------------------- */ //! \internal //! \class OTC_ArenaBlock arena.hh OTC/memory/arena.hh //! //! \brief Class to keep track of arena block information. //! //! \author Graham Dumpleton class OSE_EXPORT OTC_ArenaBlock : public OTC_MPObject { public: OTC_ArenaBlock() {} ~OTC_ArenaBlock(); char* block; char* free; size_t size; size_t capacity; OTC_ArenaBlock* next; }; //! \class OTC_Arena arena.hh OTC/memory/arena.hh //! \ingroup memory_management //! //! \brief A memory allocator which concatenates requests into blocks. //! //! The \c OTC_Arena class implements a memory allocator which obtains blocks //! of memory using operator \c new and then parcels the memory out in //! pieces. All memory allocated must be released at the same time. One can //! release memory for reuse through the same arena without actually //! destroying the whole arena. //! //! \note If a request for memory greater than the block size is requested, //! it will be allocated directly from the free store. //! //! \note The default block size is 2040. A weird value calculated by looking //! at size of blocks allocated by GNU malloc and BSD malloc. Sun malloc used //! first fit, so the size doesn't matter too much when using it. //! //! \author Graham Dumpleton class OSE_EXPORT OTC_Arena { public: //! \name Arena Construction //@{ OTC_Arena(size_t theAlign=OTC_Alignment::ofDouble()); ///< Initialises the class. The block size ///< used for allocating memory will be 2040 ///< bytes unless overridden by the ///< environment variable \c ///< OTCLIB_ARENABLOCKSIZE. When the amount of ///< free space in a block falls below 16 ///< bytes, the class will stop trying to ///< allocate memory from that block. The slop ///< value can be overridden by setting the ///< environment variable \c ///< OTCLIB_ARENASLOPSIZE. Memory returned ///< will be aligned according to \a theAlign. ///< The default is to align memory to that ///< required by the type \c double. If \a ///< theAlign is 0 an exception is raised. OTC_Arena( size_t theBlockSize, size_t theSlop, size_t theAlign=OTC_Alignment::ofDouble() ); ///< Initialises the class. \a theBlockSize ///< should be the minimum amount of memory ///< allocated from the free store. When the ///< amount of free space in a block decreases ///< below \a theSlop, the class stops trying ///< to allocate from that block. Memory ///< returned will be aligned according to \a ///< theAlign. The default is to align memory ///< to that required by the type \c double. ///< If \a theAlign is 0 an exception is ///< raised. //@} //! \name Arena Destruction //@{ ~OTC_Arena(); ///< Returns all memory to the free store. //@} //! \name Arena Characteristics //@{ size_t blockSize() const { return blockSize_; } ///< Returns the size of the blocks being ///< allocated. size_t slop() const { return slop_; } ///< Returns the threshold which determines ///< when a block is full. That is, when a ///< block has less than this number of bytes ///< available, it is marked as full. size_t align() const { return align_; } ///< Returns the alignment constraint with ///< respect to the start of any memory ///< returned. //@} //! \name Memory Blocks //@{ //! \internal The following are calculated on request as it isn't //! anticipated that they would be used for anything other than debugging //! or performance analysis. size_t freeBlocks() const; ///< Returns the number of blocks allocated ///< which still have free space in them. size_t fullBlocks() const; ///< Returns the number of blocks allocated ///< which have been marked as full. size_t allocated() const { return allocated_; } ///< Returns the total number of bytes which ///< are in use across all blocks. Ie., sum of ///< the sizes of blocks returned by the ///< \c allocate() member function. //@} //! \name Memory Allocation //@{ void* allocate(size_t theSize); ///< Returns a piece of memory of size ///< \a theSize. void release(size_t theBlocks=1); ///< Indicates you are finished with the ///< memory that has been allocated by the ///< arena, but that you don't want to destroy ///< the arena just yet. \a theBlocks is the ///< maximum number of blocks you want the ///< arena to keep hold of. That is, this ///< number of blocks will not actually be ///< freed but will be available for reuse by ///< the arena. Blocks which were greater in ///< size than the specified block size will ///< not be kept. //@} private: OTC_Arena(OTC_Arena const&); // Do not define an implementation for this. OTC_Arena& operator=(OTC_Arena const&); // Do not define an implementation for this. void* allocateNewBlock(size_t theSize); ///< Allocates a new block of memory and ///< allocate \a theSize memory out of it. size_t blockSize_; ///< Minimum block size in which allocations ///< of free store memory should be made. size_t slop_; ///< When the amount of free space in a block ///< decreases below this amount we stop ///< trying to allocate more strings from it. size_t align_; ///< Memory alignment. OTC_ArenaBlock* full_; ///< The blocks of memory which are full. OTC_ArenaBlock* free_; ///< The blocks of memory which still hold ///< some free space. size_t allocated_; ///< Number of bytes which have been ///< allocated. }; /* ------------------------------------------------------------------------- */ #endif /* OTC_MEMORY_ARENA_HH */
true
4804ebd2ec529eb18841e2fc5fb3087eb4fe325d
C++
kfilipec/rasberrypi3
/switchInput.cpp
UTF-8
673
2.65625
3
[]
no_license
#include <iostream> #include <wiringPi.h> using namespace std; int switchState; #define GREEN 18 #define RED 15 #define switchInput 14 int main(){ wiringPiSetupGpio(); pinMode(GREEN, OUTPUT); pinMode(RED, OUTPUT); pinMode(switchInput, INPUT); while(1){ switchState= digitalRead(switchInput); if(switchState==0) { digitalWrite(GREEN, LOW); digitalWrite(RED, HIGH); delay(500); digitalWrite(RED, LOW); delay(500); } else if(switchState==1) { digitalWrite(RED, LOW); digitalWrite(GREEN, HIGH); delay(500); digitalWrite(GREEN, LOW); delay(500); } else { digitalWrite(RED, HIGH); digitalWrite(GREEN, HIGH); } } }
true
095a7e4f6086555428a831c7120fdcab2d849de7
C++
yinghaoawang/MIS
/src/Parser/SetStrCharParser.cpp
UTF-8
1,274
2.734375
3
[]
no_license
#include "SetStrCharParser.h" #include <cstring> SetStrCharParser::SetStrCharParser() {} Parser *SetStrCharParser::Clone() { return new SetStrCharParser(); } std::vector<Token> SetStrCharParser::Tokenize(Cache * const cache, const std::string &str) { std::vector<Token> tokens; std::vector<std::string> str_toks = split_line(str); remove_opname(str_toks); HasValidParamsCount(str_toks.size(), 3, 3); Token t1 = StrToTok(cache, str_toks.front()); Token t2 = StrToTok(cache, str_toks.at(1)); Token t3 = StrToTok(cache, str_toks.at(2)); if (!t1.IsVariable() || !t1.IsString() || !t2.IsReal() || !t3.IsChar()) { std::string str_err = "invalid type for str char operation"; throw std::runtime_error(str_err); } if (!cache->HasVariable(t1)) { std::string str_err = "variable " + std::string(t1.GetVariable()->GetName()) + " does not exist"; throw std::runtime_error(str_err); } int length = t1.GetVariable()->GetStrMaxSize(); if (length < t2.GetAsReal()) { std::string str_err = "variable index out of bounds: " + std::to_string(length) + " < " + std::to_string(t2.GetAsReal()); throw std::runtime_error(str_err); } tokens.push_back(t1); tokens.push_back(t2); tokens.push_back(t3); return tokens; }
true
d02fd5091fd5a59092dd9ccea402c2e7d60f8e40
C++
mRooky/Rooky
/Source/Platform/Vulkan/VulkanBase.cpp
UTF-8
598
2.5625
3
[]
no_license
/* * Base.cpp * * Created on: Aug 14, 2018 * Author: rookyma */ #include "VulkanBase.h" #include <cxxabi.h> #include <string> #include <cassert> #include <iostream> namespace Vulkan { Base::Base(void) = default; Base::~Base(void) = default; std::string Base::GetClassName(void) const { int status = 0; char* rtti = abi::__cxa_demangle(typeid(*this).name(), nullptr, nullptr, &status); std::string name = rtti; std::free(rtti); return name; } void Base::Destroy(void) { std::cout<< "Vulkan Destroy : " << GetClassName() << std::endl; delete this; } } /* namespace Vulkan */
true
b37858b40484e23165ef33d116194c71246e770f
C++
jingt06/cc3k
/cc3kCurses/potion.cc
UTF-8
323
2.53125
3
[]
no_license
#include "potion.h" #include "item.h" using namespace std; Potion::Potion() : isFromM(false){} const char Potion::getType(){ return 'P'; } const char Potion::getChar(){ return 'P'; } const bool Potion::getisFromM(){ return isFromM; } void Potion::setisFromM(bool change){ isFromM = change; } Potion::~Potion(){}
true
f6df59c9e5d8bd784776cc058b4665722b2e6c33
C++
Dhruvik-Chevli/Code
/CodeChef/strno.cpp
UTF-8
1,048
2.703125
3
[]
no_license
#include <iostream> #include<vector> #include<algorithm> #include<utility> #include<string> using namespace std; typedef long long int ll; #define EPS 1e-9 #define pb push_back #define FOR(i, a, b) for(ll i = a; i < b; i++) #define PI 3.1415926535897932384626433832795 #define MOD 1000000007 void solve(int n, int k) { vector<int> P; while (n%2 == 0) { P.push_back(2); n /= 2; } for (int i=3; i*i<=n; i=i+2) { while (n%i == 0) { n = n/i; P.push_back(i); } } if (n > 2) P.push_back(n); if (P.size() < k) { cout << "0" << endl; return; } // printing first k-1 factors cout<<"1"<<endl; // calculating and printing product of rest // of numbers } int main() { std::ios_base::sync_with_stdio(false); cin.tie(NULL); ll t; cin>>t; while(t--) { ll x,k; cin>>x>>k; ll count=0; solve(x,k); } return 0; }
true
dd2fa103671b2fbd22d57129561a17175f048116
C++
wenyi1994/Wissenschaftliches-Programmieren
/Uebung6/Planeten/particle_dynamics.cpp
UTF-8
5,144
2.984375
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <cmath> #include <vector> #include "particle.h" #include "verlet.h" using namespace std; //globale Variablen: particle *Teilchen; size_t ntot; // Deklarationen: void init_structure(string); void force_calculation(particle*const,const int ntot); void euler_dynamics(particle*const , const int ntot,const double dt); void ergebnis(const particle*const , const int ntot,const double time,ofstream &); // Energie berechnen void energy(const particle*const, const int ntot, const double time, ofstream &); // Hauptprogramm: int main(){ string filename; string ergfile; ofstream ergebnisdatei,energydatei; int nchoice; double time,time_max,dt; // Eingabe: cout<<"Anfangsbedingungen der Teilchen in Datei: "; cin >> filename; cout<<"Name fuer Ergebnisdatei: "; // f�r Ausgabe: cin >> ergfile; string enfile = "en_"+ergfile; ergebnisdatei.open(ergfile.c_str(),ios::out); energydatei.open(enfile.c_str(),ios::out); // Einlesen der Anfangsstruktur: init_structure(filename); // Simulationsparameter: cout<< "zu simulierende Zeitspanne:"; cin >> time_max; cout<< "Zeitschritt dt:"; cin >> dt; cout<<"Euler (1) oder Verlet (2) Integration: "; do{ cin >>nchoice; }while(nchoice<1 || nchoice>2); time=0; if(nchoice==1) { //EULER: while(time<time_max){ time+=dt; force_calculation(Teilchen,ntot); euler_dynamics(Teilchen,ntot,dt); ergebnis(Teilchen,ntot,time,ergebnisdatei); energy(Teilchen,ntot,time,energydatei); } } else if(nchoice==2) { //Verlet: Geschwindigkeits-St�rmer-Verlet init_verlet(Teilchen,ntot); while(time<time_max){ time+=dt; update_positions(Teilchen,ntot,dt); force_calculation(Teilchen,ntot); update_velocities(Teilchen,ntot,dt); ergebnis(Teilchen,ntot,time,ergebnisdatei); energy(Teilchen,ntot,time,energydatei); } } ergebnisdatei.close(); energydatei.close(); return 0; } // Definition der Funktionen //Euler Integration: void euler_dynamics(particle *const p,const int nmax,const double dt){ for(int i=0;i<nmax;i++){ // Position: for(int n=0;n<dim;n++){ p[i].pos[n]+=p[i].vel[n]*dt; } // Geschwindigkeit: for(int n=0;n<dim;n++){ p[i].vel[n]+=p[i].f[n]/p[i].m*dt; } } } // Kraftberechnung zwischen zwei Teilchen: actio-reactio ber�cksichtigen // Potenzial: -m1*m2*r_i/r3 void force_p1p2(particle *const p1, particle *const p2){ double r[dim],f[dim]; double r2; double fs; for(int i=0;i<dim;i++) r[i]=p2->pos[i]-p1->pos[i]; //Abstandsquadrat: r2=0.; for(int i=0;i<dim;i++) r2+=r[i]*r[i]; //force: skalarer Anteil: fs=p1->m*p2->m/(sqrt(r2)*r2); //Vektorieller Anteil for(int i=0;i<dim;i++){ f[i]=fs*r[i]; p1->f[i]+=f[i]; p2->f[i]-=f[i]; } } // Kraftberechnung: einfachste Methode Ausf�hren einer Doppelsumme // unter Ber�cksichtigung von actio=reaktio void force_calculation(particle *const Teilchen,const int nmax){ // setze alle Kr�fte auf Null: for(int i=0;i<nmax;i++) for(int n=0;n<dim;n++) Teilchen[i].f[n]=0.; for(int i=0;i<nmax-1;i++){ for(int j=i+1; j<nmax;j++){ // actio=reactio miteingebaut: // d.h. nur die H�lfte der Indexpaare (i,j) // muss ber�cksichtihgt werden. force_p1p2(&Teilchen[i],&Teilchen[j]); } } } // Einlesen der Startstruktur mit Anfangsbedingungen // (Geschwindigkeit) void init_structure(string filename){ size_t n; ifstream Datei; Datei.open(filename.c_str(),ios::in); if(Datei) { n=0; Datei >> ntot; cout<<ntot<<endl; Teilchen = new particle[ntot]; while(n<ntot){ // Struktur einlesen: f�r dim=2 geschrieben // (Verallgemeinerung: �bung) Datei >>Teilchen[n].m >> Teilchen[n].pos[0] >>Teilchen[n].pos[1]>>Teilchen[n].vel[0] >>Teilchen[n].vel[1]; n++; } } Datei.close(); } // OUTPUT Datei: void ergebnis(const particle *const p,const int nmax,const double time, ofstream &OUT){ OUT<<time<<" "; for(int i=0;i<nmax;i++){ for(int n=0;n<dim;n++) OUT<<p[i].pos[n]<<" "; for(int n=0;n<dim;n++) OUT<<p[i].vel[n]<<" "; } OUT<<endl; } void energy(const particle * const p, const int nmax, const double time, ofstream & file) { file<<time<<" "; double e=0.; for(int i=0;i<nmax;i++) { double e_kinetic = 0.; double e_potenzial = 0.; double v2 = 0.; double r2 = 0.; for(int n=0;n<dim;n++) { v2 += p[i].vel[n]*p[i].vel[n]; } e_kinetic = 0.5*p[i].m*v2; for(int j=0;j<nmax;j++) { if(j==i) continue; r2 = 0.; for(int n=0;n<dim;n++) { r2 += (p[i].pos[n]-p[j].pos[n])*(p[i].pos[n]-p[j].pos[n]); } e_potenzial -= p[i].m*p[j].m/sqrt(r2); } file<<i<<" "<<e_kinetic<<" "<<e_potenzial<<" "<<e; } file<<endl; }
true
5288c93eabee9d91566443a348e58a2db20637ae
C++
eliogovea/breakout
/include/breakout/core/state.hpp
UTF-8
1,922
2.953125
3
[]
no_license
#pragma once #include <iostream> #include <vector> #include <glm/glm.hpp> #include "util.hpp" namespace breakout::core { struct ball { glm::vec2 center; glm::float32 radius; glm::vec2 velocity; int32_t strength; }; struct brick { glm::vec2 center; glm::float32 width; glm::float32 height; int32_t strength; }; struct paddle { glm::vec2 center; glm::float32 velocity; glm::float32 width; glm::float32 height; int32_t strength; }; struct state { void update(glm::float32 delta); glm::float32 width; glm::float32 height; std::vector<paddle> paddles; std::vector<ball> balls; std::vector<brick> bricks; }; void state::update(glm::float32 delta) { for (auto& ball: balls) { if (ball.strength == 0) { continue; } ball.center += ball.velocity * delta; // check boundaries if (ball.center.y - ball.radius >= 0.5 * height) { ball.velocity.y = -ball.velocity.y; } if (ball.center.x - ball.radius <= -0.5 * width) { ball.velocity.x = -ball.velocity.x; } if (ball.center.x - ball.radius >= 0.5 * width) { ball.velocity.x = -ball.velocity.x; } for (auto& paddle: paddles) { if (paddle.strength == 0) { continue; } if (util::collide({ball.center, ball.radius}, {paddle.center, paddle.width, paddle.height})) { ball.velocity.y = -ball.velocity.y; } } for (auto& ball: balls) { if (ball.center.y + ball.radius < -height) { ball.strength = 0; } } for (auto& ball: balls) { if (ball.strength == 0) { continue; } for (auto& brick: bricks) { if (brick.strength == 0) { continue; } if (util::collide({ball.center, ball.radius}, {brick.center, brick.width, brick.height})) { brick.strength--; ball.velocity.y = -ball.velocity.y; } } } } } }
true
65b049716d5e391792a75a77f4b19e69e6022ca1
C++
seanjedi/Practice_Problems
/vectors.cpp
UTF-8
2,165
3.5625
4
[]
no_license
#include <iostream> #include <vector> #include <queue> #include <set> #include <unordered_map> using namespace std; void iterators(vector<int> example){ for (auto i = example.begin(); i != example.end(); ++i) cout << *i << " "; cout << "\nReverse" << endl; for (auto ir = example.rbegin(); ir != example.rend(); ++ir) cout << *ir << " "; cout << "\nOutput of crbegin and crend : "; for (auto ir = example.crbegin(); ir != example.crend(); ++ir) cout << *ir << " "; } void capacity(vector<int> ex){ cout << "Size : " << ex.size() << endl; cout << "Capacity : " << ex.capacity() << endl; cout << "Max_Size : " << ex.max_size() << endl; ex.resize(10, 0); cout << "Size : " << ex.size()<<endl; for (auto i = ex.begin(); i != ex.end(); ++i) cout << *i << " "; ex.shrink_to_fit(); cout << "\nVector elements are: "; for (auto it = ex.begin(); it != ex.end(); it++) cout << *it << " "; } void modifiers(vector<int> ex){ // ex.assign(1,10); ex.erase(ex.begin() + 2); ex.insert(ex.begin(), 5); for (auto it = ex.begin(); it != ex.end(); it++) cout << *it << " "; } void sliding_door(vector<int> arr){ set<int> quiz; for(int i = 0; i < arr.size(); i++){ quiz.insert(arr[i]); } int median = quiz.size()/2; cout << median << endl; auto itr = quiz.begin(); cout << *itr+median << endl; quiz.erase(*itr+median); for (itr = quiz.begin(); itr != quiz.end(); ++itr) { cout << '\t' << *itr; } } void longest_substring(vector<int> arr){ } void sets(vector<int> arr){ unordered_map<int, int> umap; for(int i = 0; i < arr.size(); i++) umap.insert(make_pair(arr[i], 1)); umap[1]++; umap[10]++; cout << umap[10] << endl; if (umap.find(3) == umap.end()) cout <<"not found" << endl; else cout << "Found " << endl; } int main() { vector<int> arr = {1,2,3,4,5,6}; vector<int> arr2 = {1,3,2,6,4,0}; // iterators(arr); // capacity(arr); // modifiers(arr); // sliding_door(arr2); sets(arr2); }
true
5c7fb5bea8deace7a208f1e6979b5d9d927f6658
C++
HaMinhThanh/SupperMarioBros3
/SupperMario/SupperMario/Camera.cpp
UTF-8
699
3
3
[]
no_license
#include "Camera.h" Camera::Camera(int width, int height) { Width = width; Height = height; Position = D3DXVECTOR3(0, 0, 0); } Camera::~Camera() { } void Camera::SetPosition(float x, float y) { SetPosition(D3DXVECTOR3(x, y, 0)); } void Camera::SetPosition(D3DXVECTOR3 pos) { Position = pos; } D3DXVECTOR3 Camera::GetPosition() { return Position; } RECT Camera::GetBound() { RECT bound; bound.left = Position.x - Width / 2; bound.right = bound.left + Width;; bound.top = Position.y - Height / 2; bound.bottom = bound.top + Height; return bound; } int Camera::GetWidth() { return Width; } int Camera::GetHeight() { return Height; }
true
1f8820293351325cd9ed972a5b382aa0401e567e
C++
cbrghostrider/Hacking
/leetcode/_001361_validateBTreeNodes.cpp
UTF-8
2,292
3.734375
4
[ "MIT" ]
permissive
class Solution { // For a binary tree to be valid: // // 1. EXACTLY 1 node has no parent. // 2. All other nodes have EXACTLY 1 parent. // 3. No node has more than 2 children. (Implicit in input format) // 4. If both left and right children exist, they must be different. Covered by 2. // 5. No cycle. // 6. Two different parents can't have the same child. Covered by 2. // // Easiest thing to do is: // 1. Find root (thing with no parent); if 0 or more than 1, then fail. // 2. Traverse root. // a. Make sure everything is visited. // b. Make sure nothing got visited twice. unordered_set<int> has_parent; unordered_set<int> visited; public: // returns true if there's a cycle bool visit(vector<int>& leftChild, vector<int>& rightChild, int i) { int lchild = leftChild[i]; int rchild = rightChild[i]; if (lchild != -1) { if (visited.find(lchild) != visited.end()) return true; visited.insert(lchild); bool v = visit(leftChild, rightChild, lchild); if (v) return true; } if (rchild != -1) { if (visited.find(rchild) != visited.end()) return true; visited.insert(rchild); bool v = visit(leftChild, rightChild, rchild); if (v) return true; } return false; } bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) { for (int i=0; i<n; i++) { int lchild = leftChild[i]; int rchild = rightChild[i]; if (lchild != -1) {has_parent.insert(lchild);} if (rchild != -1) {has_parent.insert(rchild);} } if (has_parent.size() != n-1) return false; int root = -1; for (int i=0; i<n; i++) { if (has_parent.find(i) == has_parent.end()) { root = i; break; } } visited.insert(root); if (visit(leftChild, rightChild, root)) return false; // check that everything is visited for (int i=0; i<n; i++) { if (visited.find(i) == visited.end()) return false; } return true; } };
true
025d18e2857cdeb2e731edf5d6ebc0605fc237bc
C++
github2mon/Data-Structure-and-Algorithm
/Data Structure/5. String/string.h
UTF-8
2,466
3.578125
4
[]
no_license
#pragma once class String { private: char* str; int len; public: String(); String(String& s); String(char* s) { *this = s; } ~String() { delete str; } String& operator=(String& s); String& operator=(char* s); int isEmpty() { return len == 0; } int length() { return len; } int comp(String s); String* concat(String& s); String* subString(int pos, int length); int insert(int pos, String& s); int delete(int pos, int length); }; String::String() { str = new char[1]; str[0] = '\0'; len = 0; } String::String(String& s) { str = new char[s.len + 1]; len = s.len; str[len] = '\0'; for (int i = 0; i < s.len; i++) str[i] = s.str[i]; } String& String::operator=(String& s) { if (this == &s) return *this; delete[] str; len = s.len; str = new char[len + 1]; str[len] = '\0'; for (int i = 0; i < s.len; i++) str[i] = s.str[i]; return *this; } String& String::operator=(char* s) { int len = sizeof(s) / sizeof(char); str = new char[len + 1]; str[len] = '\0'; for (int i = 0; i < len; i++) str[i] = s[i]; return *this; } int String::comp(String s) { for (int i = 0; i < len && i < s.len; i++) if (str[i] != s.str[i]) return str[i] - s.str[i]; return len - s.len; } String* String::concat(String& s) { String* p = new String(); delete[] p->str; p->str = new char[len + s.len + 1]; p->len = len + s.len; p->str[p->len] = '\0'; for (int i = 0; i < len; i++) p->str[i] = str[i]; for (int i = 0; i < s.len; i++) p->str[i + len] = s.str[i]; return p; } String* String::subString(int pos, int length) { if (pos<0 || pos>len || length<0 || length>len - pos + 1) return nullptr; String* sub = new String(); delete[] sub->str; sub->str = new char[length + 1]; sub->len = length; sub->str[length] = '\0'; for (int i = 0; i < length; i++) sub->str[i] = str[i + pos]; return sub; } int String::insert(int pos, String& s) { if (pos < 0 || pos > len) return 0; char* p = new char[len + s.len + 1]; if (!p) { cout << "memory overflow"; exit(0); } for (int i = 0; i < len; i++) p[i] = str[i]; delete[] str; str = p; p = nullptr; for (int i = pos; i < len - 1; i++) str[i + s.len] = str[i]; for (int i = 0; i < s.len; i++) str[pos + i] = s.str[i]; len += s.len; str[len] = '\0'; return 1; } int String::del(int pos, int length) { if (pos < 0 || pos > len - 1 || length < 0 || length > len - pos) return 0; for (int i = pos + length; i <= len; i++) str[i - length] = str[i]; return 1; }
true
5111657360804f5585880741106ab0d50025e8a7
C++
andyprowl/ape
/Ape/World/Scene/src/CameraSelector.cpp
UTF-8
4,841
2.765625
3
[]
no_license
#include <Ape/World/Scene/CameraSelector.hpp> #include <Ape/World/Scene/Scene.hpp> #include <Basix/Range/Search.hpp> #include <Basix/Range/Transform.hpp> #include <algorithm> #include <numeric> namespace ape { namespace { auto getAddressOfFirstCamera(Scene & scene) -> Camera const * { auto const & cameras = scene.getCameras(); if (cameras.empty()) { return nullptr; } return &cameras.front(); } auto asMutableCameraFromScene(Camera const & camera, Scene & scene) -> Camera & { auto const & cameras = scene.getCameras(); if (cameras.empty()) { throw CameraNotInScene{}; } if ((&camera < &cameras.front()) || (&camera > &cameras.back())) { throw CameraNotInScene{}; } auto const index = static_cast<int>(std::distance(&cameras.front(), &camera)); return scene.getCamera(index); } auto getAllMutableCamerasFromScene(Scene & scene) -> std::vector<Camera *> { auto const & scenecameras = scene.getCameras(); return transform(scenecameras, [&scene] (Camera const & camera) { return &asMutableCameraFromScene(camera, scene); }); } } // unnamed namespace CameraSelector::CameraSelector(Scene & scene) : scene{&scene} , firstCameraInScene{getAddressOfFirstCamera(scene)} , availableCameras{getAllMutableCamerasFromScene(scene)} , activeCameraIndex{tryGetFirstCameraIndex()} , cameraReallocationHandlerConnection{registerCamerReallocationHandler()} { } auto CameraSelector::getScene() const -> Scene & { return *scene; } auto CameraSelector::getAvailableCameras() const -> std::vector<Camera *> const & { return availableCameras; } auto CameraSelector::getActiveCamera() const -> Camera * { if (not activeCameraIndex) { return nullptr; } return availableCameras[*activeCameraIndex]; } auto CameraSelector::activateCamera(int const index) -> void { if (index >= static_cast<int>(availableCameras.size())) { throw BadCameraIndex{index}; } activeCameraIndex = index; onActiveCameraChanged.fire(getActiveCamera()); } auto CameraSelector::activateCamera(Camera const & camera) -> void { if (getActiveCamera() == &camera) { return; } auto & mutableCamera = asMutableCameraFromScene(camera, *scene); auto const it = basix::find(availableCameras, &mutableCamera); if (it == std::cend(availableCameras)) { availableCameras.push_back(&mutableCamera); } activeCameraIndex = static_cast<int>(std::distance(std::cbegin(availableCameras), it)); onActiveCameraChanged.fire(getActiveCamera()); } auto CameraSelector::activateNextCamera() -> void { if (not activeCameraIndex) { activeCameraIndex = tryGetFirstCameraIndex(); } else { auto const numOfCameras = static_cast<int>(availableCameras.size()); activeCameraIndex = (*activeCameraIndex + 1) % numOfCameras; } onActiveCameraChanged.fire(getActiveCamera()); } auto CameraSelector::activatePreviousCamera() -> void { if (not activeCameraIndex) { activeCameraIndex = tryGetLastCameraIndex(); } else { auto const numOfCameras = static_cast<int>(availableCameras.size()); activeCameraIndex = (*activeCameraIndex + numOfCameras - 1) % numOfCameras; } onActiveCameraChanged.fire(getActiveCamera()); } auto CameraSelector::deactivateCamera() -> void { activeCameraIndex = std::nullopt; onActiveCameraChanged.fire(nullptr); } auto CameraSelector::tryGetFirstCameraIndex() const -> std::optional<int> { if (availableCameras.empty()) { return std::nullopt; } return 0; } auto CameraSelector::tryGetLastCameraIndex() const -> std::optional<int> { if (availableCameras.empty()) { return std::nullopt; } return static_cast<int>(availableCameras.size() - 1); } auto CameraSelector::registerCamerReallocationHandler() -> basix::ScopedSignalConnection { return scene->onCameraReallocation.registerHandler([this] { restoreValidCameraReferences(availableCameras); firstCameraInScene = getAddressOfFirstCamera(*scene); }); } auto CameraSelector::restoreValidCameraReferences(std::vector<Camera *> & cameras) const -> void { std::transform( std::begin(cameras), std::end(cameras), std::begin(cameras), [this] (Camera const * const camera) { auto const index = getCameraIndexInOriginalContainer(*camera); return &(scene->getCamera(index)); }); } auto CameraSelector::getCameraIndexInOriginalContainer(Camera const & camera) const -> int { return static_cast<int>(std::distance(firstCameraInScene, &camera)); } } // namespace ape
true
69577030bdb2aaab4e86264bae7e72224cf30f63
C++
infotraining/cpp-17-2020-11-30
/any-variant/tests.cpp
UTF-8
4,379
3.578125
4
[]
no_license
#include <algorithm> #include <numeric> #include <iostream> #include <string> #include <vector> #include <any> #include <variant> #include "catch.hpp" using namespace std; TEST_CASE("any") { std::any anything; REQUIRE(anything.has_value() == false); anything = 3; anything = 3.14; anything = "text"s; anything = vector{1, 2, 3}; REQUIRE(anything.has_value()); SECTION("any_cast") { auto vec = std::any_cast<std::vector<int>>(anything); REQUIRE(vec == vector{1, 2, 3}); REQUIRE_THROWS_AS(std::any_cast<int>(anything), std::bad_any_cast); } SECTION("any_cast with pointer") { vector<int>* vec = std::any_cast<std::vector<int>>(&anything); REQUIRE(vec != nullptr); REQUIRE(*vec == vector{1, 2, 3}); REQUIRE(std::any_cast<int>(&anything) == nullptr); } SECTION("any + RTTI") { const type_info& type_desc = anything.type(); std::cout << type_desc.name() << "\n"; } } //////////////////////////////////// // wide interfaces class Observer { public: virtual void update(const std::any& sender, const string& msg) = 0; virtual ~Observer() = default; }; class TempMonitor { std::vector<Observer*> observes_; public: void notify() { for(const auto& o : observes_) o->update(this, std::to_string(get_temp())); } double get_temp() const { return 23.88; } }; class Logger : public Observer { public: void update(const std::any& sender, const string& msg) override { TempMonitor* const* monitor = std::any_cast<TempMonitor*>(&sender); if (monitor) (*monitor)->get_temp(); } }; ////////////////////////////////////////////////// ////////////////////////////////////////////////// struct NoDefaultConstructible { int value; NoDefaultConstructible(int v) : value {v} { } }; TEST_CASE("std::variant") { std::variant<int, double, std::string, std::vector<int>> v1; REQUIRE(std::holds_alternative<int>(v1)); REQUIRE(std::get<int>(v1) == 0); std::variant<std::monostate, NoDefaultConstructible, int> v2; REQUIRE(v2.index() == 0); v1 = 3.14; v1 = "text"s; v1 = vector{1, 2, 3}; REQUIRE(std::get<std::vector<int>>(v1) == vector{1, 2, 3}); REQUIRE_THROWS_AS(std::get<int>(v1), std::bad_variant_access); REQUIRE(std::get_if<int>(&v1) == nullptr); REQUIRE(*std::get_if<std::vector<int>>(&v1) == vector{1, 2, 3}); } struct Value { float v; Value(float v) : v {v} { } ~Value() { cout << "~Value(" << v << ")\n"; } }; struct Evil { string v; Evil(string v) : v {std::move(v)} { } Evil(Evil&& other) { throw std::runtime_error("42"); } }; TEST_CASE("valueless variant") { variant<Value, Evil> v {12.0f}; try { v.emplace<Evil>(Evil {"evil"}); } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } REQUIRE(v.valueless_by_exception()); REQUIRE(v.index() == std::variant_npos); } ///////////////////////// // visiting std::variant struct Printer { void operator()(int x) { std::cout << "int: " << x << "\n"; } void operator()(double x) { std::cout << "double: " << x << "\n"; } void operator()(const std::string& s) { std::cout << "string: " << s << "\n"; } }; template <typename... Closures> struct overload : Closures... { using Closures::operator()...; // since C++17 }; template<typename... Closures> overload(Closures...) -> overload<Closures...>; [[nodiscard]] std::variant<std::string, std::errc> load_content(const std::string& filename) { if (filename == "") return std::errc::bad_file_descriptor; return "content"s; } TEST_CASE("visiting variant") { std::variant<int, double, string> v1 = 3.14; std::visit(Printer{}, v1); auto printer = [](const auto& v) { std::cout << typeid(v).name() << " - " << v << "\n"; }; std::visit(printer, v1); // local_printer auto local_printer = overload { [](int x) { std::cout << "int: " << x << "\n"; }, [](double x) { std::cout << "double: " << x << "\n"; }, [](const std::string& s) { std::cout << "string: " << s << "\n"; } }; std::visit(local_printer, v1); }
true
92bd53f29cfa3aa29ce05b0f2816fd6fc8df6d64
C++
Rijutady/asciiArtGallery
/AsciiImage.cpp
WINDOWS-1250
2,424
3.40625
3
[]
no_license
#include "AsciiImage.h" AsciiImage::AsciiImage() { // Add defaults here title = ""; id = ""; name = ""; image = ""; categ = ""; url = ""; } bool AsciiImage::LoadImage(ifstream &file) { // get rid of empty line while (getline(file, title)) { if (title != " ") { break; } } // Load title getline(file, title); // Get ID file >> id; // Read image while (getline(file, image)) { if (image == "=====") { break; } else { picture[size] = image; size++; } } // Read URL file >> url; widthSize = 80; //Read Catagory file >> categ; // Maybe read a name file.ignore(); getline(file, name); //check if you reached the end of the file by using the eof() function: if (file.eof()) cout << "End of the file!Nothing left to read!" << endl; return true; } void AsciiImage::PrintImage(bool showTitle, bool showName, bool showID, bool showCateg, bool showURL) { // print boarder AsciiImage::PrintHorizontalBorder(); cout << "" << endl; // Print the image with the board and options if (showTitle == true) AsciiImage::PrintWithVerticalBorders(title); if (showID == true) AsciiImage::PrintWithVerticalBorders(id); for (int i = 0; i < size; i++) { AsciiImage::PrintWithVerticalBorders(picture[i]); } // one empty line AsciiImage::PrintWithVerticalBorders(" "); if (showURL == true) AsciiImage::PrintWithVerticalBorders(url); if (showCateg == true) AsciiImage::PrintWithVerticalBorders(categ); if (showName == true) { stringstream strst(name); strst >> firstName >> lastName; // stores first name in val1 and last name in val2 if (lastName != " ") { name = firstName + " " + lastName; } else if (firstName != " ") { name = firstName + " Unknown"; } else { name = "Unknown Unknown"; } AsciiImage::PrintWithVerticalBorders(name); } // print boarder AsciiImage::PrintHorizontalBorder(); cout << "" << endl; } void AsciiImage::PrintHorizontalBorder() { cout << setfill ('=') << setw (4 + widthSize); } void AsciiImage::PrintWithVerticalBorders(string s) { // Print the string s with "|" on both sides cout << "|"; cout << " "; cout << s; cout << setfill (' ') << setw (widthSize - s.length()); cout << " "; cout << "|" << endl; }
true
a130b34db4f95b2ba3622c5a2a5ecabcbae54bec
C++
wuerges/vlsi_verification
/cpp/test_harness.hpp
UTF-8
1,614
2.625
3
[]
no_license
template <typename P> void test_parser( char const* input, P const& p, bool full_match = true) { using boost::spirit::qi::parse; char const* f(input); char const* l(f + strlen(f)); if (parse(f, l, p) && (!full_match || (f == l))) std::cout << "ok" << std::endl; else std::cout << "fail" << std::endl; } template <typename P> void test_phrase_parser( char const* input, P const& p, bool full_match = true) { using boost::spirit::qi::phrase_parse; using boost::spirit::qi::ascii::space; char const* f(input); char const* l(f + strlen(f)); if (phrase_parse(f, l, p, space) && (!full_match || (f == l))) std::cout << "ok" << std::endl; else std::cout << "fail" << std::endl; } template <typename P, typename T> void test_parser_attr( char const* input, P const& p, T& attr, bool full_match = true) { using boost::spirit::qi::parse; char const* f(input); char const* l(f + strlen(f)); if (parse(f, l, p, attr) && (!full_match || (f == l))) std::cout << "ok" << std::endl; else std::cout << "fail" << std::endl; } template <typename P, typename T> void test_phrase_parser_attr( char const* input, P const& p, T& attr, bool full_match = true) { using boost::spirit::qi::phrase_parse; using boost::spirit::qi::ascii::space; char const* f(input); char const* l(f + strlen(f)); if (phrase_parse(f, l, p, space, attr) && (!full_match || (f == l))) std::cout << "ok" << std::endl; else std::cout << "fail" << std::endl; }
true
6bbdfdb51ca37c0ce70f5dd811018afc4e9be352
C++
jolin1337/opgl-Test-Projects
/floor/floor.cpp
UTF-8
1,561
2.671875
3
[]
no_license
/*** Floor example/test for Glut */ #include "mouse.h" #include "key.h" #include "floorTexture.h" bool texture = false, reflect = false, shadow = false; void redraw(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(texture) redrawFloor(); glutSwapBuffers(); } void settings(int v){ if(texture) floorSettings(v); } void update(){ glutPostRedisplay(); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL | GLUT_MULTISAMPLE); #if 0 /* In GLUT 4.0, you'll be able to do this an be sure to get 2 bits of stencil if the machine has it for you. */ glutInitDisplayString("samples stencil>=2 rgb double depth"); #endif glutCreateWindow("1337"); glutInitWindowSize(600, 600); glutFullScreen(); glutCreateMenu(settings); glutAddMenuEntry("----------------", M_NONE); int i; for (i=1; i<argc; i++) { if (!strcmp("texture", argv[i])) { initFloor(argc, argv); texture = true; } else if(!strcmp("reflect", argv[i])){ reflect = true; } else if(!strcmp("shadow", argv[i])){ shadow = true; } } glutAttachMenu(GLUT_RIGHT_BUTTON); if (shadow && glutGet(GLUT_WINDOW_STENCIL_SIZE) <= 1) { printf("dinoshade: Sorry, I need at least 2 bits of stencil.\n"); exit(1); } /* Register GLUT callbacks. */ glutDisplayFunc(redraw); glutMouseFunc(mouse); glutMotionFunc(motion); glutKeyboardFunc(key); glutSpecialFunc(special); glutIdleFunc(update); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }
true
fd03945a30e798c93dfa0d17ddb48499c725c158
C++
DanubeRS/INB371
/INB371_W3/src/Q4.cpp
UTF-8
2,074
3.90625
4
[]
no_license
/* GetDomain (c) Daniel Park 2013 Simple program to calculate the domain of a supplied array v0.1 ==== -Initial creation v1.0 ==== -Completed program */ #include <iostream> #include <cstdio> #include <cstdlib> using namespace std; //Function Prototypes void MinMax(int a[], int l, int &lower, int &upper); //Returns the minimum and maximum bounds of a passed array //Program Entry Point int main() { //Inform the user of the program: cout << "================================" << endl; cout << "| PrimeFinderTM |" << endl; cout << "================================" << endl; cout << "| (c) Daniel Park 2013 |" << endl; cout << "| ***INB371_S1_W3_Q1*** |" << endl; cout << "================================" << endl << endl; //Code derived from MinMax.cpp by Malcom Corney int min, max; // test arrays int values1[] = { 67, 78, 75, 70, 71, 80, 69, 86, 65, 54, 76, 78, 70, 68, 77 }; int values2[] = { 50 }; int values3[] = { 50, 50, 50, 50, 50, 50, 50}; MinMax(values1, sizeof values1 / sizeof values1[0], min, max); cout << "minimum = " << min << endl; cout << "maximum = " << max << endl; cout << endl; MinMax(values2, sizeof values2 / sizeof values2[0], min, max); cout << "minimum = " << min << endl; cout << "maximum = " << max << endl; cout << endl; MinMax(values3, sizeof values3 / sizeof values3[0], min, max); cout << "minimum = " << min << endl; cout << "maximum = " << max << endl; return 0; } /* Determines the domain of values within a specified array. Passed by reference. Length specified */ void MinMax(int a[], int l, int &lower, int &upper){ lower = a[0]; upper = a[0]; //Starting with the first element, compare hereon in //Iterate through the array for (int i = 1; i < l; i++){ if(a[i] < lower){ lower = a[i];} //Get the lower value if it is smaller if(a[i] > upper){ upper = a[i];} //Get the lower value if it is smaller } }
true
6903767d711a3a86d076d74ff85d4dc90f9d9c9a
C++
Anurag845/OOP
/temp6.cpp
UTF-8
615
3.625
4
[]
no_license
#include<iostream> using namespace std; template <class T1> class Base { T1 bdata; public: void getdata() { cout<<"Enter base data"<<endl; cin>>bdata; } void showdata() { cout<<"Base data is "<<bdata<<endl; } }; template <class T2> class Derived : public Base<T2> { T2 ddata; public: void getData() { cout<<"Enter derived data "<<endl; cin>>ddata; } void showData() { cout<<"Derived data is "<<ddata<<endl; } }; int main() { Derived <float> obd; obd.getData(); obd.showData(); obd.getdata(); obd.showdata(); return 0; }
true
2f56826d691bc82da1fc9f1e8ad78300c3ec7331
C++
AlishaKhoja/school-work
/es1037a-assignments/a1/main_a1.cpp
UTF-8
1,106
3.546875
4
[]
no_license
#include "Point.h" int main(){ Point c[4]; //Create array of 4 point objects c[1]= Point(7, 7); //Define the second point in the array to hold 7, 7 c[2]= Point(6, 5); //Define the third point in the array to hold 6, 5 Point *b[3]; //Create an array of 3 point pointers b[0]= c + 2; //First pointer holds address of third point b[1]= NULL; //Second pointer holds null value b[2]= new Point[3]; //Third pointer creates dynamic array of 3 point objects b[2][0]= Point(1, 1); //First dynamic point holds 1, 1 b[2][2]= Point(2,3); //Third dynamic point holds 2, 3 Point **d= &b[2]; //Create a point pointer pointer that holds the address of the third pointer Point *a= &b[2][1]; //Create a point pointer which holds the adress of the second dynamic pointer a= c+2; //Change a to hold the address of the third static point delete [] b[2]; //Delete the dynamic array b[2]= c+3; //Change the third pointer to the adress of the fourth static point b[0]= c+1; //Change the first pointer to the address of the second point d= NULL; //Change d to null value return 0; }
true
a6fc6b82fdcbe9988ec0ea2f2233083f167ea5a2
C++
abeaumont/competitive-programming
/cses/1622.cc
UTF-8
312
2.53125
3
[ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// https://cses.fi/problemset/task/1622/ #include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; sort(s.begin(), s.end()); vector<string> r; do r.push_back(s); while (next_permutation(s.begin(), s.end())); cout << r.size() << "\n"; for (string &s : r) cout << s << "\n"; }
true
420ef12d4657a3eacae96c1e228ac8efeaaa95a7
C++
Draouch/CCOMP
/FinalProject/Enemigo.cpp
UTF-8
2,408
2.65625
3
[]
no_license
#include "Enemigo.h" #include "Objeto.h" #include "Random.h" #include <SFML/Graphics.hpp> #include <iostream> #include <vector> using namespace sf; using namespace std; Enemigo::Enemigo(){ rect.setSize(Vector2f(dimensionx,dimensiony)); rect.setPosition(Vector2f(600,200)); sprite.setTextureRect(sf::IntRect((contadorpasos*dimensionx) + dimensionxStart, (dimensiony*0) + dimensionyStart, dimensionx, dimensiony)); } void Enemigo::update(){ sprite.setPosition(rect.getPosition()); } void Enemigo::updateMovimiento(){ if (direccion == 1){ //ARRIBA if (IrArriba == true){ rect.move(0,-velocidad); sprite.setTextureRect(sf::IntRect((contadorpasos*dimensionx) + dimensionxStart, (dimensiony*3) + dimensionyStart, dimensionx, dimensiony)); IrArriba = true; IrAbajo = true; IrIzquierda = true; IrDerecha = true; } } else if (direccion == 2){ //ABAJO if (IrAbajo == true){ rect.move(0,velocidad); sprite.setTextureRect(sf::IntRect((contadorpasos*dimensionx) + dimensionxStart, (dimensiony*0) + dimensionyStart, dimensionx, dimensiony)); IrArriba = true; IrAbajo = true; IrIzquierda = true; IrDerecha = true; } } else if (direccion == 3){ //IZQUIERDA if (IrIzquierda == true){ rect.move(-velocidad,0); sprite.setTextureRect(sf::IntRect((contadorpasos*dimensionx) + dimensionxStart, (dimensiony*1) + dimensionyStart, dimensionx, dimensiony)); IrArriba = true; IrAbajo = true; IrIzquierda = true; IrDerecha = true; } } else if (direccion == 4){ //DERECHA if (IrDerecha == true){ rect.move(velocidad,0); sprite.setTextureRect(sf::IntRect((contadorpasos*dimensionx) + dimensionxStart, (dimensiony*2) + dimensionyStart, dimensionx, dimensiony)); IrArriba = true; IrAbajo = true; IrIzquierda = true; IrDerecha = true; } } contadorpasos++; if(contadorpasos>=3){ contadorpasos = 0; } contador++; if (contador >= 10){ direccion = generarRandom(5); contador = 0; } }
true
51bd67d75e3c3d09204fd0504017132f094f69b4
C++
google/jsonnet
/third_party/rapidyaml/rapidyaml/ext/c4core/src/c4/ext/fast_float/tests/powersoffive_hardround.cpp
UTF-8
3,958
2.84375
3
[ "Apache-2.0", "MIT" ]
permissive
#include "fast_float/fast_float.h" #include <iostream> #include <random> #include <sstream> #include <vector> #if defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__) || defined(sun) || defined(__sun) // Anything at all that is related to cygwin, msys and so forth will // always use this fallback because we cannot rely on it behaving as normal // gcc. #include <locale> #include <sstream> // workaround for CYGWIN double cygwin_strtod_l(const char* start, char** end) { double d; std::stringstream ss; ss.imbue(std::locale::classic()); ss << start; ss >> d; if(ss.fail()) { *end = nullptr; } if(ss.eof()) { ss.clear(); } auto nread = ss.tellg(); *end = const_cast<char*>(start) + nread; return d; } float cygwin_strtof_l(const char* start, char** end) { float d; std::stringstream ss; ss.imbue(std::locale::classic()); ss << start; ss >> d; if(ss.fail()) { *end = nullptr; } if(ss.eof()) { ss.clear(); } auto nread = ss.tellg(); *end = const_cast<char*>(start) + nread; return d; } #endif std::pair<double, bool> strtod_from_string(const char *st) { double d; char *pr; #if defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__) || defined(sun) || defined(__sun) d = cygwin_strtod_l(st, &pr); #elif defined(_WIN32) static _locale_t c_locale = _create_locale(LC_ALL, "C"); d = _strtod_l(st, &pr, c_locale); #else static locale_t c_locale = newlocale(LC_ALL_MASK, "C", NULL); d = strtod_l(st, &pr, c_locale); #endif if (st == pr) { std::cerr << "strtod_l could not parse '" << st << std::endl; return std::make_pair(0, false); } return std::make_pair(d, true); } std::pair<float, bool> strtof_from_string(char *st) { float d; char *pr; #if defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__) || defined(sun) || defined(__sun) d = cygwin_strtof_l(st, &pr); #elif defined(_WIN32) static _locale_t c_locale = _create_locale(LC_ALL, "C"); d = _strtof_l(st, &pr, c_locale); #else static locale_t c_locale = newlocale(LC_ALL_MASK, "C", NULL); d = strtof_l(st, &pr, c_locale); #endif if (st == pr) { std::cerr << "strtof_l could not parse '" << st << std::endl; return std::make_pair(0.0f, false); } return std::make_pair(d, true); } bool tester() { std::random_device rd; std::mt19937 gen(rd()); for (int q = 18; q <= 27; q++) { std::cout << "q = " << -q << std::endl; uint64_t power5 = 1; for (int k = 0; k < q; k++) { power5 *= 5; } uint64_t low_threshold = 0x20000000000000 / power5 + 1; uint64_t threshold = 0xFFFFFFFFFFFFFFFF / power5; std::uniform_int_distribution<uint64_t> dis(low_threshold, threshold); for (size_t i = 0; i < 10000; i++) { uint64_t mantissa = dis(gen) * power5; std::stringstream ss; ss << mantissa; ss << "e"; ss << -q; std::string to_be_parsed = ss.str(); std::pair<double, bool> expected_double = strtod_from_string(to_be_parsed.c_str()); double result_value; auto result = fast_float::from_chars(to_be_parsed.data(), to_be_parsed.data() + to_be_parsed.size(), result_value); if (result.ec != std::errc()) { std::cout << to_be_parsed << std::endl; std::cerr << " I could not parse " << std::endl; return false; } if (result_value != expected_double.first) { std::cout << to_be_parsed << std::endl; std::cerr << std::hexfloat << result_value << std::endl; std::cerr << std::hexfloat << expected_double.first << std::endl; std::cerr << " Mismatch " << std::endl; return false; } } } return true; } int main() { if (tester()) { std::cout << std::endl; std::cout << "all ok" << std::endl; return EXIT_SUCCESS; } std::cerr << std::endl; std::cerr << "errors were encountered" << std::endl; return EXIT_FAILURE; }
true
04c07aa5aefe510a616990a7a7e4d6c6077e5822
C++
z1230601/BAKK_Prodanovic_Zaric_OBD
/OBDMiddleware/configurations/src/DatabaseXMLHandler.cpp
UTF-8
1,923
2.78125
3
[]
no_license
#include "DatabaseXMLHandler.h" DatabaseXMLHandler::DatabaseXMLHandler() { } DatabaseXMLHandler::~DatabaseXMLHandler() { } void DatabaseXMLHandler::handleNode(xmlpp::Node* node) { if(is_writing_) { writeHandleNode(node); } else { readHandleNode(node); } } void DatabaseXMLHandler::writeHandleNode(xmlpp::Node* node) { if(node->get_name().compare(ADDRESS_TAG) == 0) { setTextToNode(node, host_address_); } if(node->get_name().compare(USER_TAG) == 0) { setTextToNode(node, username_); } if(node->get_name().compare(PASSWORD_TAG) == 0) { setTextToNode(node, password_); } if(node->get_name().compare(DBNAME_TAG) == 0) { setTextToNode(node, dbname_); } } void DatabaseXMLHandler::readHandleNode(xmlpp::Node* node) { if(node->get_name().compare(ADDRESS_TAG) == 0) { host_address_ = getTextFromNode(node); } if(node->get_name().compare(USER_TAG) == 0) { username_ = getTextFromNode(node); } if(node->get_name().compare(PASSWORD_TAG) == 0) { password_ = getTextFromNode(node); } if(node->get_name().compare(DBNAME_TAG) == 0) { dbname_ = getTextFromNode(node); } } std::string DatabaseXMLHandler::getHostAddress() { return host_address_; } void DatabaseXMLHandler::setHostAddress(std::string host_address) { host_address_ = host_address; } std::string DatabaseXMLHandler::getDBName() { return dbname_; } void DatabaseXMLHandler::setDBName(std::string dbname) { dbname_ = dbname; } std::string DatabaseXMLHandler::getPassword() { return password_; } void DatabaseXMLHandler::setPassword(std::string password) { password_ = password; } std::string DatabaseXMLHandler::getUsername() { return username_; } void DatabaseXMLHandler::setUsername(std::string username) { username_ = username; }
true
dacbdd6e3276ad39ee4394e700cc7adeb49ca975
C++
ItsRico/cityevac_proto
/evac.cpp
UTF-8
11,263
2.546875
3
[]
no_license
#include <cstdlib> #include "evac.h" #include "EvacRunner.h" #include <math.h> using namespace std; int compare (const void * a, const void * b) { const Road* p = (Road*)a; const Road* q = (Road*)b; return ( q->peoplePerHour - p->peoplePerHour); } Evac::Evac(City *citie, int numCitie, int numRoads) : numCities(numCitie) { for(int i = 0; i < numCitie; i++) { RoadNode* tempRoads = new RoadNode[numRoads]; for(int j = 0; j < citie[i].roadCount; j++) { tempRoads[j].destinationCityID = citie[i].roads[j].destinationCityID; tempRoads[j].sourceID = i; tempRoads[j].peoplePerHour = citie[i].roads[j].peoplePerHour; tempRoads[j].ID = citie[i].roads[j].ID; tracker[tempRoads[j].ID] = tempRoads[j]; } //copy the roads qsort (tempRoads, citie[i].roadCount, sizeof(RoadNode), compare); //Q sort here CityNode tempCity(citie[i].ID, tempRoads, citie[i].x, citie[i].y, citie[i].population, citie[i].evacuees, citie[i].roadCount, false); graph.adjList[citie[i].ID] = tempCity; } //copy the city //cout << numCities << "\n"; //graph.print(numCities); } // Evac() void Evac::addBackFlow(int destination, int orig, int flow) { for(int i = 0; i < graph.adjList[destination].roadCount; i++) { RoadNode road = graph.adjList[destination].roads[i]; if(road.destinationCityID == orig) { graph.adjList[destination].roads[i].peoplePerHour += flow; } } } void Evac::evacuate(int *evacIDs, int numEvacs, EvacRoute *evacRoutes, int &routeCount) { routeCount = 0; int curDistance = 0; int furthestCity = -99; int sink = findFarestCity(evacIDs[0], curDistance, furthestCity, evacIDs[0]); int smallest = 999999; int* path = new int[200000]; int pathCount = 0; int t = 1; int total = 0; int offSet = 0; int initCount = 0; activeCities[sink] = true; while(true) {//finds first path int check = findPathTo(evacIDs[0], sink, -99, smallest, path, pathCount); if (check == 1) break; //evac maintence for(int i = 0; i < pathCount; i++) { evacRoutes[routeCount].roadID = path[i]; evacRoutes[routeCount].time = 1; evacRoutes[routeCount].numPeople = smallest; routeCount++; } total += smallest; smallest = 999999; offSet += pathCount; pathCount = 0; } graph.adjList[evacIDs[0]].population -= total; graph.adjList[sink].evacuees += total; cout << "city 1's pop is: " << graph.adjList[evacIDs[0]].population << "and it's evacuees is :" << graph.adjList[sink].evacuees << "which is at city: " << sink << endl; int orig = 0; while(graph.adjList[evacIDs[0]].population > 0 ) { t++; for(int i = initCount; i < offSet ;i++ ) { evacRoutes[routeCount].roadID = evacRoutes[i].roadID; evacRoutes[routeCount].time = t; evacRoutes[routeCount].numPeople = evacRoutes[i].numPeople; if(orig != evacRoutes[i].numPeople) { orig = evacRoutes[i].numPeople; graph.adjList[evacIDs[0]].population -= orig; graph.adjList[sink].evacuees += orig; cout << "city 1's pop is: " << graph.adjList[evacIDs[0]].population << " and it's evacuees is :" << graph.adjList[sink].evacuees << " which is at city: " << sink << endl; cout << "this many evacuees on this path: " << orig << endl; if(graph.adjList[sink].evacuees > graph.adjList[sink].population) {//we know our sinks max capacity has been reached by this iteration so we need to find a new sink graph.adjList[sink].evacuees -= orig; break; cout << "we fucked up but it's chill < << < << < < < " << endl; } if(graph.adjList[evacIDs[0]].population < 0) { cout << orig << graph.adjList[evacIDs[0]].population << endl; evacRoutes[routeCount].numPeople = orig + graph.adjList[evacIDs[0]].population; routeCount++; break; } } routeCount++; } } graph.adjList[sink].evacuees += graph.adjList[evacIDs[0]].population; cout << "city 1's pop is: " << graph.adjList[evacIDs[0]].population << " and it's evacuees is :" << graph.adjList[sink].evacuees << " which is at city: " << sink << endl; initCount += offSet; float loadFactor = (float) graph.adjList[5].population / graph.adjList[5].evacuees; if(loadFactor > .90) { //set that city to innactive activeCities[sink] = false; } //road maintenance for(int i = 0; i < numCities; i++) { for(int j = 0; j < graph.adjList[i].roadCount; j++) { tracker[graph.adjList[i].roads[j].ID] = graph.adjList[i].roads[j]; } } // cout << "******************************************\n"; curDistance = 0; furthestCity = -99; sink = findFarestCity(evacIDs[1], curDistance, furthestCity, evacIDs[1]); // cout << "BEFORE RUNNING NEXT THING BEFORE B4 "<<graph.adjList[5].population << endl; while(true) { int check = findPathTo(evacIDs[1], sink, evacIDs[1], smallest, path, pathCount); if (check == 1) break; //evac maintence for(int i = 0; i < pathCount; i++) { evacRoutes[routeCount].roadID = path[i]; evacRoutes[routeCount].time = t; evacRoutes[routeCount].numPeople = smallest; cout << evacRoutes[routeCount].numPeople << endl; routeCount++; } total += smallest; smallest = 999999; offSet += pathCount; pathCount = 0; } graph.adjList[evacIDs[1]].population -= total; /* orig = 0; int b = t; // cout << "BEFORE RUNNING NEXT THING "<<graph.adjList[5].evacuees << endl; while(t <= b + 1) { t++; cout << "INITCOUNT : " << initCount << endl; for(int i = initCount; i < offSet ;i++ ) { evacRoutes[routeCount].roadID = evacRoutes[i].roadID; evacRoutes[routeCount].time = t; evacRoutes[routeCount].numPeople = evacRoutes[i].numPeople; cout << graph.adjList[5].population << endl; if(orig != evacRoutes[i].numPeople) { orig = evacRoutes[i].numPeople; graph.adjList[evacIDs[1]].population -= orig; if(graph.adjList[evacIDs[1]].population < 0) { evacRoutes[routeCount].numPeople = orig + graph.adjList[evacIDs[1]].population; routeCount++; break; } } routeCount++; } } initCount += offSet; cout << t << endl; cout << graph.adjList[evacIDs[0]].evacuees << endl; */ } // evacuate int Evac::findPathTo(int cityID, int sink, int prevCity, int& smallest, int* paths, int& pathCount) { for(int i = 0; i < graph.adjList[cityID].roadCount; i++) { RoadNode roadToTake = graph.adjList[cityID].roads[i]; // cout << graph.adjList[5].population << endl; //cout << graph.adjList[5].evacuees << endl; if( roadToTake.destinationCityID == 5 && activeCities[roadToTake.destinationCityID] == 0 ) //if this is true, we need to find another path to our sink { for(int i = 0; i < graph.adjList[cityID].roadCount; i++) { cout <<"i COULD GO TO : " <<graph.adjList[cityID].roads[i].destinationCityID << " asdf "<< endl; } cout << activeCities[roadToTake.destinationCityID] << " destinationCityID : " << roadToTake.destinationCityID << endl; cout << "this city is full af and i cant use it" << endl; cout << graph.adjList[cityID].roadCount << endl; return 0; } if(roadToTake.destinationCityID == sink && tracker[roadToTake.ID].peoplePerHour > 0) { if(tracker[roadToTake.ID].peoplePerHour < smallest) { smallest = tracker[roadToTake.ID].peoplePerHour; } // cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`\n"; // cout << "SMALLEST: " << smallest << "\n"; // cout << "I took the path from city " << cityID << " to " << roadToTake.destinationCityID << " and took " << smallest << " people with me" <<"\n"; tracker[roadToTake.ID].peoplePerHour -= smallest; // cout << "I had: " << roadToTake.peoplePerHour << " and "; if(tracker[roadToTake.ID + 1].destinationCityID == cityID) { // cout << "my backflow was: " << tracker[roadToTake.ID + 1].peoplePerHour << "\n"; tracker[roadToTake.ID + 1].peoplePerHour += smallest; // cout << "now it is: " << tracker[roadToTake.ID + 1].peoplePerHour << "\n"; } else { // cout << "my backflow was: " << tracker[roadToTake.ID - 1].peoplePerHour << "\n"; tracker[roadToTake.ID - 1].peoplePerHour += smallest; // cout << "now it is: " << tracker[roadToTake.ID - 1].peoplePerHour << "\n"; } // cout << " now my forward flow is: " << tracker[roadToTake.ID].peoplePerHour << "\n"; // cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`\n"; //tracker[roadToTake.] paths[pathCount] = roadToTake.ID; pathCount++; return 0 ; } } graph.adjList[cityID].isVisited = true; RoadNode roadToTake = graph.adjList[cityID].roads[0]; int i = 0; while(roadToTake.destinationCityID == prevCity || tracker[roadToTake.ID].peoplePerHour <= 0 || graph.adjList[roadToTake.destinationCityID].isVisited) { roadToTake = tracker[graph.adjList[cityID].roads[i].ID]; if(i == graph.adjList[cityID].roadCount) { cout << "best possible path\n"; return 1; } i++; } if(tracker[roadToTake.ID].peoplePerHour < smallest) { smallest = tracker[roadToTake.ID].peoplePerHour; } paths[pathCount] = roadToTake.ID; pathCount++; int check = findPathTo(roadToTake.destinationCityID, sink, cityID, smallest, paths, pathCount); if(check == 1) { return 1; } //cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`\n"; //cout << "I took the path from city " << cityID << " to " << roadToTake.destinationCityID << " and took " << smallest << " people with me" <<"\n"; tracker[roadToTake.ID].peoplePerHour -= smallest; //cout << "I had: " << roadToTake.peoplePerHour << " and "; if(tracker[roadToTake.ID + 1].destinationCityID == cityID) { //cout << "my backflow was: " << tracker[roadToTake.ID + 1].peoplePerHour << "\n"; tracker[roadToTake.ID + 1].peoplePerHour += smallest; } else { //cout << "my backflow was: " << tracker[roadToTake.ID - 1].peoplePerHour << "\n"; tracker[roadToTake.ID - 1].peoplePerHour += smallest; } //cout << " now my forward flow is: " << tracker[roadToTake.ID].peoplePerHour << "\n"; //cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`\n"; return 0; } int Evac::findFarestCity(int cityID, int& curDistance, int& furthestCity, int origCity) { for(int i = 0; i< graph.adjList[cityID].roadCount; i++) { RoadNode roadToCheck = graph.adjList[cityID].roads[i]; int x = graph.adjList[roadToCheck.destinationCityID].x; int y = graph.adjList[roadToCheck.destinationCityID].y; int x2 = graph.adjList[origCity].x; int y2 = graph.adjList[origCity].y; int distance = sqrt((pow(x - x2, 2) + pow(y - y2, 2))); if(distance > curDistance) { curDistance = distance; furthestCity = roadToCheck.destinationCityID; findFarestCity(furthestCity, curDistance, furthestCity, origCity); } } return furthestCity; } //findFarestCity
true
0e48fedd30aeed146fafc1da2baf5d9d9d29faac
C++
dendisuhubdy/IntXLib4CPP
/IntXLib.Test/src/MulOpTest.h
UTF-8
2,174
2.953125
3
[ "MIT" ]
permissive
#define BOOST_TEST_MODULE MulOpTest #include "../IntX.h" #include "../Utils/Constants.h" #include <string> #include <fstream> #include <boost/test/included/unit_test.hpp> BOOST_AUTO_TEST_SUITE(MulOpTest) BOOST_AUTO_TEST_CASE(PureIntX) { BOOST_CHECK(IntX(3) * IntX(5) == IntX(15)); } BOOST_AUTO_TEST_CASE(PureIntXSign) { BOOST_CHECK(IntX(-3) * IntX(5) == IntX(-15)); } BOOST_AUTO_TEST_CASE(IntAndIntX) { BOOST_CHECK(IntX(3) * 5 == 15); } BOOST_AUTO_TEST_CASE(Zero) { BOOST_CHECK((IntX)0 * IntX(3) == 0); } BOOST_AUTO_TEST_CASE(Big) { vector<UInt32> temp1, temp2, tempRes; IntX int1, int2, intRes; temp1.resize(2); temp1[0] = 1; temp1[1] = 1; temp2.resize(2); temp2[0] = 1; temp2[1] = 1; tempRes.resize(3); tempRes[0] = 1; tempRes[1] = 2; tempRes[2] = 1; int1 = IntX(temp1, false); int2 = IntX(temp2, false); intRes = IntX(tempRes, false); BOOST_CHECK(int1 * int2 == intRes); } BOOST_AUTO_TEST_CASE(Big2) { vector<UInt32> temp1, temp2, tempRes; IntX int1, int2, intRes; temp1.resize(2); temp1[0] = 1; temp1[1] = 1; temp2.resize(1); temp2[0] = 2; tempRes.resize(2); tempRes[0] = 2; tempRes[1] = 2; int1 = IntX(temp1, false); int2 = IntX(temp2, false); intRes = IntX(tempRes, false); BOOST_CHECK(intRes == int1 * int2); BOOST_CHECK(intRes == int2 * int1); } BOOST_AUTO_TEST_CASE(Big3) { vector<UInt32> temp1, temp2, tempRes; IntX int1, int2, intRes; temp1.resize(2); temp1[0] = Constants::MaxUInt32Value; temp1[1] = Constants::MaxUInt32Value; temp2.resize(2); temp2[0] = Constants::MaxUInt32Value; temp2[1] = Constants::MaxUInt32Value; tempRes.resize(4); tempRes[0] = 1; tempRes[1] = 0; tempRes[2] = Constants::MaxUInt32Value - 1; tempRes[3] = Constants::MaxUInt32Value; int1 = IntX(temp1, false); int2 = IntX(temp2, false); intRes = IntX(tempRes, false); BOOST_CHECK(int1 * int2 == intRes); } BOOST_AUTO_TEST_CASE(Performance) { int i; vector<UInt32> temp1; IntX intX1, intX2; temp1.resize(2); temp1[0] = 0; temp1[1] = 1; intX1 = IntX(temp1, false); intX2 = intX1; i = 0; while (i < 1000) { intX2 = intX2 * intX1; ++i; } // end while BOOST_CHECK(true); } BOOST_AUTO_TEST_SUITE_END()
true
d3a55511cf23b114852ca6d90f5365b8aa79f6cd
C++
greenfox-zerda-sparta/nmate91
/week_06/11-24/Cars.hpp
UTF-8
332
2.78125
3
[]
no_license
#ifndef CARS_H #define CARS_H #include <iostream> #include <string> #include <vector> #include <time.h> using namespace std; class Cars { private: string name_of_the_car; string color_of_the_car; string plate_number; vector<string> car_types; vector<string> car_colors; public: Cars(); string get_car(); }; #endif
true
41d70878f53969e8ce6cec75b7774a8ed41da0f5
C++
stevealbertwong/coursework
/c_c++/socket-block-nonblock-timeout/select-timer-block/test_select.cc
UTF-8
4,146
2.765625
3
[]
no_license
/* no error checking for clean logic author: steven wong g++ -std=c++14 test_select.cc -o test_select // telnet establish tcp session telnet localhost 8888 telnet 127.0.0.1 8888 then type hello, hello will show up in every connected terminal */ #include <stdio.h> #include <string.h> //strlen #include <stdlib.h> #include <errno.h> #include <unistd.h> //close #include <arpa/inet.h> //close #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros #include <iostream> #define TRUE 1 #define FALSE 0 #define PORT 8888 #define MAXCLIENTS 30 // using namespace std; sockaddr_in fill_serveraddr(){ struct sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); return address; } // void send_all_connected_clients(){ // for(j = 0; j <= max_fd; j++) { // if (FD_ISSET(j, &masterfd)) { // // except the server and the guy that sent // if (j != server_socket && j != i) { // send(j, buffer, sizeof(buffer), 0); // } int main(int argc, char const *argv[]) { int opt = TRUE; // setsockopt() int addrlen, num_active_sockets, i , valread , sd, max_fd; int rf; // function's return flag int server_socket; // server socket() int client_socket; // accept() => client fds char buffer[1024]; // data buffer of 1K fd_set readfds; // set of client fds/connections in current select() fd_set masterfd; // set of all clients and server fds/sockets struct sockaddr_in serveraddr; // server address struct sockaddr_in clientaddr; // client address server_socket = socket(AF_INET , SOCK_STREAM , 0); setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)); serveraddr = fill_serveraddr(); ::bind(server_socket, (struct sockaddr *)&serveraddr, sizeof(serveraddr)); // socket bind to unique port listen(server_socket, 3); // 3 backlog == pending connections allowed incoming queue FD_ZERO(&masterfd); // clear the master and working sets FD_ZERO(&readfds); FD_SET(server_socket, &masterfd); // 1 server socket in master set max_fd = server_socket; // as only 1 server socket, it is max, later update w client sock while(1){ memcpy(&readfds, &masterfd, sizeof(masterfd)); // copy master set into working set // readfds = masterfd; // same as above num_active_sockets = select(max_fd + 1 , &readfds , NULL , NULL , NULL); // among all sockets(max_fd+1) if in readfds, update readfds for (i=0; i <= max_fd && num_active_sockets > 0; ++i){ // if socket is active if (FD_ISSET(i, &readfds)){ // for that active socket num_active_sockets--; if(i == server_socket){ // if its server socket => new client connections client_socket = accept(server_socket, NULL, NULL); // accept is blocking + spawning new client_fds std::cout << "new connections " << client_socket << std::endl; FD_SET(client_socket, &masterfd); // add new clients to master set if (client_socket > max_fd) max_fd = client_socket; // update max socket id } else{ // if existing connection => multiple new transfers rf = recv(i, buffer, sizeof(buffer), 0); // rf == byte received, recv() is blocking // if(rf == 0){ // getpeername(i , (struct sockaddr*)&clientaddr , sizeof(clientaddr)); // printf("Host disconnected , ip %s , port %d \n" , inet_ntoa(clientaddr.sin_addr) , ntohs(clientaddr.sin_port)); // } // send(i, buffer, sizeof(buffer), 0); // send back to sender buffer[rf] = '\0'; // clean garbage // send all peers for(int j = 0; j <= max_fd; j++) { if (FD_ISSET(j, &masterfd)) { // except the server and the guy that sent if (j != server_socket && j != i) { send(j, buffer, rf+1, 0); }}} } } } } return 0; }
true
7c05a79c859df1a38f5b645c5e693e79c6aa85da
C++
sunkaiiii/study_computer_science
/Algorithm_Exercises/字符串全排列.cpp
UTF-8
706
3.4375
3
[]
no_license
#include<iostream> #include<algorithm> void Permutation(char*); void Permutation(char*,char*); void Permutation(char *pStr) { if(pStr==NULL) return; Permutation(pStr,pStr); } void Permutation(char *pStr,char *pBegin) { if(*pBegin=='\0') { std::cout<<pStr<<std::endl; } else { for(char* pCh=pBegin;*pCh!='\0';++pCh) { char temp=*pCh; *pCh=*pBegin; *pBegin=temp; Permutation(pStr,pBegin+1); temp=*pCh; *pCh=*pBegin; *pBegin=temp; } } } int main() { char s[50]; std::cin>>s; std::string s2(s); Permutation(s); std::cout<<"\n"; do { std::cout<<s2<<std::endl; } while(std::next_permutation(s2.begin(),s2.end())); }
true
359c50cb1eb11666d78078f58a631e990344758c
C++
cp-shen/SimpleGF
/src/utils/Application.cpp
UTF-8
489
2.640625
3
[]
no_license
#include <SimpleGF/utils/Application.h> using namespace SimpleGF; Application::Application() { } Application::~Application() { } std::shared_ptr<Window> Application::_window = nullptr; void Application::init(int wWidth, int wHeight, const char* title) { _window = std::shared_ptr<Window>(new Window(wWidth, wHeight, title)); } void Application::terminate() { _window = nullptr; glfwTerminate(); } std::shared_ptr<Window> Application::getWindow() { return _window; }
true
505479cb03b49ed2b731e6b3e6cd09295706b4e5
C++
reactorlabs/ght-pipeline
/include/hash.h
UTF-8
2,010
3.15625
3
[]
no_license
#pragma once #include <cstdint> #include <string> #include <ostream> #include <cassert> template<unsigned BYTES> struct Hash { static_assert(BYTES % 4 == 0, "Invalid hash size"); Hash() = default; Hash(std::string const & hex) { assert(hex.size() == BYTES * 2); for (unsigned i = 0; i < BYTES; ++i) data_[i] = FromHex(hex[i * 2]) * 16 + FromHex(hex[i * 2 + 1]); } bool operator == (Hash<BYTES> const & other) const { for (unsigned i = 0; i < BYTES; ++i) if (data_[i] != other.data_[i]) return false; return true; } bool operator != (Hash<BYTES> const & other) const { for (unsigned i = 0; i < BYTES; ++i) if (data_[i] != other.data_[i]) return true; return false; } private: friend class std::hash<::Hash<BYTES>>; friend std::ostream & operator << (std::ostream & s, Hash<BYTES> const &h) { static const char dec2hex[16+1] = "0123456789abcdef"; for (int i = 0; i < BYTES; ++i) { s << dec2hex[(h.data_[i] >> 4) & 15]; s << dec2hex[(h.data_[i]) & 15]; } return s; } unsigned char data_[BYTES]; static unsigned char FromHex(char what) { return (what >= 'a') ? (what - 'a') + 10 : what - '0'; } }; namespace std { /** So that Hash can be key in std containers. */ template<unsigned BYTES> struct hash<::Hash<BYTES>> { std::size_t operator()(::Hash<BYTES> const & h) const { std::size_t result = 0; unsigned i = 0; for (; i < BYTES - 8; i += 8) result += std::hash<uint64_t>()(* reinterpret_cast<uint64_t const*>(h.data_+i)); for (; i < BYTES; ++i) result += std::hash<char>()(h.data_[i]); return result; } }; } typedef Hash<16> MD5; typedef Hash<20> SHA1;
true
4e37efddf5215a25b8ff60153908e6bb2bed4efb
C++
mavd09/notebook_unal
/Math/Simpson.cpp
UTF-8
670
2.921875
3
[]
no_license
/// Complexity: ????? /// Tested: Not yet inline lf simpson(lf fl, lf fr, lf fmid, lf l, lf r) { return (fl + fr + 4.0 * fmid) * (r - l) / 6.0; } lf rsimpson (lf slr, lf fl, lf fr, lf fmid, lf l, lf r) { lf mid = (l + r) * 0.5; lf fml = f((l + mid) * 0.5); lf fmr = f((mid + r) * 0.5); lf slm = simpson(fl, fmid, fml, l, mid); lf smr = simpson(fmid, fr, fmr, mid, r); if (fabs(slr - slm - smr) < eps) return slm + smr; return rsimpson(slm, fl, fmid, fml, l, mid) + rsimpson(smr, fmid, fr, fmr, mid, r); } lf integrate(lf l,lf r) { lf mid = (l + r) * .5, fl = f(l), fr = f(r), fmid = f(mid); return rsimpson(simpson(fl, fr, fmid, l, r), fl, fr, fmid, l, r); }
true
694f77c9bead27b9f4578e4d4fec95dc816fcdb3
C++
CoderName200/Lab7
/lab_7/lab_7/lab_7.cpp
UTF-8
5,093
3.375
3
[]
no_license
#include <iostream> using namespace std; template<typename T> void swap(T& a, T& b) { T c(std::move(a)); a = std::move(b); b = std::move(c); } template <class T> const T& max(const T& a, const T& b) { std::cout << "Вызванна шаблонная функция max" << std::endl; return (a < b) ? b : a; } char* maxchar(char* a, char* b) { std::cout << "Вызванна специализированная функция max(char*,char*) " << std::endl; return (a < b) ? b : a; } template <typename T1, typename T2> class Complex { private: T1 re; T2 im; // действительная и мнимая части public: // конструкторы Complex() { }; Complex(T1 r) { re = r; im = 0; } Complex(T1 r, T2 i) { re = r; im = i; } ~Complex() { } // оператор присваивания Complex& operator = (Complex& c) { re = c.re; im = c.im; return (*this); } // оператор += Complex& operator += (Complex& c) { re += c.re; im += c.im; return *this; } // оператор сложения Complex operator + (const Complex& c) { return Complex(re + c.re, im + c.im); } // оператор вычитания Complex operator - (const Complex& c) { return Complex(re - c.re, im - c.im); } friend ostream& operator<< (ostream& out, const Complex& c) { out << "(" << c.re << ", " << c.im << ")"; return out; } friend istream& operator>> (istream& in, Complex& c) { in >> c.re >> c.im; return in; } }; template <class T> class MATRIX { private: T** M; int m; int n; public: MATRIX() { n = m = 0; } MATRIX(int _m, int _n) { m = _m; n = _n; M = (T**) new T * [m]; for (int i = 0; i < m; i++) M[i] = (T*)new T[n]; } friend std::ostream& operator<<(std::ostream& out, const MATRIX& mat) { for (int i = 0; i < mat.m; i++) { cout << endl; for (int j = 0; j < mat.n; j++) cout << mat.M[i][j] << '\t'; } cout << endl; return cout; } friend std::istream& operator>>(std::istream& in, MATRIX& mat) { for (int i = 0; i < mat.m; i++) for (int j = 0; j < mat.n; j++) in >> mat.M[i][j]; return in; } MATRIX operator+(MATRIX mat) { if (this->n == mat.n and this->m == mat.m) { MATRIX res(mat.m, mat.n); for (int i = 0; i < res.m; i++) for (int j = 0; j < res.n; j++) res.M[i][j] = this->M[i][j] + mat.M[i][j]; return res; } } MATRIX operator-(MATRIX mat) { if (this->n == mat.n and this->m == mat.m) { MATRIX res(mat.m, mat.n); for (int i = 0; i < res.m; i++) for (int j = 0; j < res.n; j++) res.M[i][j] = this->M[i][j] - mat.M[i][j]; return res; } } template <class T1, class T2> friend MATRIX<double> operator+(MATRIX<T1> mat1, MATRIX<T2> mat2); template <class T1, class T2> friend MATRIX<double> operator-(MATRIX<T1> mat1, MATRIX<T2> mat2); }; template <class T1, class T2> MATRIX<double> operator+(MATRIX<T1> mat1, MATRIX<T2> mat2) { if (mat1.n == mat2.n and mat1.m == mat2.m) { MATRIX<double> res(mat2.m, mat2.n); for (int i = 0; i < res.m; i++) for (int j = 0; j < res.n; j++) res.M[i][j] = mat1.M[i][j] + mat2.M[i][j]; return res; } } template <class T1, class T2> MATRIX<double> operator-(MATRIX<T1> mat1, MATRIX<T2> mat2) { if (mat1.n == mat2.n and mat1.m == mat2.m) { MATRIX<double> res(mat2.m, mat2.n); for (int i = 0; i < res.m; i++) for (int j = 0; j < res.n; j++) res.M[i][j] = mat1.M[i][j] + mat2.M[i][j]; return res; } } int main() { setlocale(LC_ALL, "rus"); std::cout << "Hello World!\n"; int a = 5, b = 4; std::string c = "sss", d = "qqq"; //swap(a, b); swap(c, d); std::cout << a << "\t" << b << std::endl; std::cout << c << "\t" << d << std::endl; char q[10] = "Hello"; char z[] = "World"; std::cout << maxchar(z, q)<< endl; Complex<int, int> ch(1, 4); Complex <float, float> ch1(1.1, 2.3); Complex <float, float> ch2(1.2, 2.4); cout << ch << endl; cout << ch1 << endl; cout << ch1+ch2 << endl; MATRIX<int> M1(2, 2); cin >> M1; cout << M1 << endl; MATRIX<double> M2(2, 2); cin >> M2; cout << M2 << endl; cout << M1 + M2 << endl; cout << M1 - M2 << endl; }
true
75563cd18546f705f8f65948ac2140294766cc7f
C++
itiievskyi/42-CPP-Pool
/day00/ex01/Contact.class.cpp
UTF-8
2,709
2.546875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Contact.class.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: itiievsk <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/20 16:08:13 by itiievsk #+# #+# */ /* Updated: 2018/09/20 16:08:15 by itiievsk ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include <iomanip> #include "Contact.class.hpp" Contact::Contact(void) { return; } Contact::~Contact(void) { return; } std::string Contact::getFirstName(void) const { return this->_firstName; } std::string Contact::getLastName(void) const { return this->_lastName; } std::string Contact::getNickName(void) const { return this->_nickName; } std::string Contact::getLogin(void) const { return this->_login; } std::string Contact::getAddress(void) const { return this->_address; } std::string Contact::getEmail(void) const { return this->_email; } std::string Contact::getPhone(void) const { return this->_phone; } std::string Contact::getBirthday(void) const { return this->_birthday; } std::string Contact::getMeal(void) const { return this->_meal; } std::string Contact::getUnderwear(void) const { return this->_underwear; } std::string Contact::getSecret(void) const { return this->_secret; } void Contact::setFirstName(std::string firstName) { this->_firstName = firstName; } void Contact::setLastName(std::string lastName) { this->_lastName = lastName; } void Contact::setNickName(std::string nickName) { this->_nickName = nickName; } void Contact::setLogin(std::string login) { this->_login = login; } void Contact::setAddress(std::string address) { this->_address = address; } void Contact::setEmail(std::string email) { this->_email = email; } void Contact::setPhone(std::string phone) { this->_phone = phone; } void Contact::setBirthday(std::string birthday) { this->_birthday = birthday; } void Contact::setMeal(std::string meal) { this->_meal = meal; } void Contact::setUnderwear(std::string underwear) { this->_underwear = underwear; } void Contact::setSecret(std::string secret) { this->_secret = secret; }
true
7be3b293bbf1454b066283764e2fd19c2f16212b
C++
bxl295/m4extreme
/include/External/stlib/packages/ads/array/SparseArray1.ipp
UTF-8
19,119
3.109375
3
[ "BSD-2-Clause" ]
permissive
// -*- C++ -*- #if !defined(__ads_SparseArray1_ipp__) #error This file is an implementation detail of the class SparseArray. #endif namespace ads { // // Constructors etc. // // Construct a 1-D array sparse array from the values and indices. template<typename T> template<typename IndexForwardIter, typename ValueForwardIter> inline SparseArray<1, T>:: SparseArray(IndexForwardIter indicesBeginning, IndexForwardIter indicesEnd, ValueForwardIter valuesBeginning, ValueForwardIter valuesEnd, parameter_type nullValue) : Base(valuesBeginning, valuesEnd), _indices(indicesBeginning, indicesEnd), _null(nullValue) { assert(_indices.size() == size()); } // Rebuild a 1-D array sparse array from the values and indices. template<typename T> template<typename IndexForwardIter, typename ValueForwardIter> inline void SparseArray<1, T>:: rebuild(IndexForwardIter indicesBeginning, IndexForwardIter indicesEnd, ValueForwardIter valuesBeginning, ValueForwardIter valuesEnd, parameter_type nullValue) { Base::rebuild(valuesBeginning, valuesEnd); _indices.rebuild(indicesBeginning, indicesEnd); assert(_indices.size() == size()); _null = nullValue; } // Construct a 1-D sparse array from a 1-D dense array of possibly // different value type. template<typename T> template<typename T2, bool A> inline SparseArray<1, T>:: SparseArray(const Array<1, T2, A>& array, parameter_type nullValue) : // Start with an empty sparse array. Base(), _indices(), _null(nullValue) { operator=(array); } // Construct a 1-D sparse array from a vector of possibly // different value type. template<typename T> template<typename T2> inline SparseArray<1, T>:: SparseArray(const std::vector<T2>& array, parameter_type nullValue) : // Start with an empty sparse array. Base(), _indices(), _null(nullValue) { operator=(array); } // Assignment operator for dense arrays. template<typename T> template<typename T2, bool A> inline SparseArray<1, T>& SparseArray<1, T>:: operator=(const Array<1, T2, A>& array) { // The non-null indices and values. std::vector<int> indices; std::vector<value_type> values; // The array index range. const int iBegin = array.lbound(0); const int iEnd = array.ubound(0); // For each element in the dense array. for (int i = iBegin; i != iEnd; ++i) { // If the value is non-null. if (array(i) != _null) { // Record the index and value. indices.push_back(i); values.push_back(array(i)); } } // Rebuild the sparse array. rebuild(indices.begin(), indices.end(), values.begin(), values.end()); return *this; } // Assignment operator for vectors. template<typename T> template<typename T2> inline SparseArray<1, T>& SparseArray<1, T>:: operator=(const std::vector<T2>& array) { // The non-null indices and values. std::vector<int> indices; std::vector<value_type> values; // For each element in the vector. for (std::size_t i = 0; i != array.size(); ++i) { // If the value is non-null. if (array[i] != _null) { // Record the index and value. indices.push_back(i); values.push_back(array[i]); } } // Rebuild the sparse array. rebuild(indices.begin(), indices.end(), values.begin(), values.end()); return *this; } template<typename T> inline bool SparseArray<1, T>:: isNull(const int i) const { // Do a binary search to find the index. Array<1, int>::const_iterator j = std::lower_bound(_indices.begin(), _indices.end(), i); // If the index does not exist. if (j == _indices.end() || *j != i) { // The element is null. return true; } // If the index does exist, the element is non-null. return false; } template<typename T> inline typename SparseArray<1, T>::parameter_type SparseArray<1, T>:: operator()(const int i) const { // Do a binary search to find the index. Array<1, int>::const_iterator j = std::lower_bound(_indices.begin(), _indices.end(), i); // If the index does not exist. if (j == _indices.end() || *j != i) { // Return the null value; return _null; } // If the index does exist, return the value. return operator[](int(j - _indices.begin())); } template<typename T> template<typename T2, bool A> inline void SparseArray<1, T>:: fill(ads::Array<1, T2, A>* array) const { // First set all the elements to the null value. *array = getNull(); // Then fill in the non-null values. fillNonNull(array); } template<typename T> template<typename T2, bool A> inline void SparseArray<1, T>:: fillNonNull(ads::Array<1, T2, A>* array) const { // The range for the dense array. const int lb = array->lbound(0); const int ub = array->ubound(0); // Do a binary search to find the lower bound of the index range. // Index iterator. Array<1, int>::const_iterator ii = std::lower_bound(_indices.begin(), _indices.end(), lb); // Initialize the value iterator. typename Array<1, value_type>::const_iterator vi = begin() + (ii - _indices.begin()); // Loop over the index range. for (; ii != _indices.end() && *ii < ub; ++ii, ++vi) { (*array)(*ii) = *vi; } } template<typename T> inline void SparseArray<1, T>:: put(std::ostream& out) const { out << _null << '\n' << size() << '\n'; _indices.write_elements_ascii(out); write_elements_ascii(out); } template<typename T> inline void SparseArray<1, T>:: get(std::istream& in) { in >> _null; size_type s; in >> s; // Resize the indices array. _indices.resize(s); // Resize the values array. Base::rebuild(s); _indices.read_elements_ascii(in); read_elements_ascii(in); } // // Free functions // // Compute the sum of the two arrays. template<typename T> inline void computeSum(const SparseArray<1, T>& x, const SparseArray<1, T>& y, SparseArray<1, T>* result) { computeBinaryOperation(x, y, result, std::plus<T>()); } // Compute the difference of the two arrays. template<typename T> inline void computeDifference(const SparseArray<1, T>& x, const SparseArray<1, T>& y, SparseArray<1, T>* result) { computeBinaryOperation(x, y, result, std::minus<T>()); } // Compute the product of the two arrays. template<typename T> inline void computeProduct(const SparseArray<1, T>& x, const SparseArray<1, T>& y, SparseArray<1, T>* result) { computeBinaryOperation(x, y, result, std::multiplies<T>()); } // Use the binary function to compute the result. template<typename T, typename BinaryFunction> inline void computeBinaryOperation(const SparseArray<1, T>& x, const SparseArray<1, T>& y, SparseArray<1, T>* result, const BinaryFunction& function) { assert(x.getNull() == y.getNull()); const T Null = x.getNull(); std::vector<int> indices; std::vector<T> values; const int mEnd = x.size(); const int nEnd = y.size(); int i, j; T f; // Loop over the common index range. int m = 0, n = 0; while (m != mEnd && n != nEnd) { i = x.getIndices()[m]; j = y.getIndices()[n]; // If the first index is less. if (i < j) { f = function(x[m], Null); if (f != Null) { indices.push_back(i); values.push_back(f); } ++m; } // If the second index is less. else if (j < i) { f = function(Null, y[n]); if (f != Null) { indices.push_back(j); values.push_back(f); } ++n; } // If the indices are equal. else { f = function(x[m], y[n]); if (f != Null) { indices.push_back(i); values.push_back(f); } ++m; ++n; } } // Loop over the remaining indices of x. while (m != mEnd) { i = x.getIndices()[m]; f = function(x[m], Null); if (f != Null) { indices.push_back(i); values.push_back(f); } ++m; } // Loop over the remaining indices of y. while (n != nEnd) { j = y.getIndices()[n]; f = function(Null, y[n]); if (f != Null) { indices.push_back(j); values.push_back(f); } ++n; } // Build the result. result->rebuild(indices.begin(), indices.end(), values.begin(), values.end(), Null); } template<typename T> inline int countNonNullElementsInUnion(const SparseArray<1, T>& a, const SparseArray<1, T>& b) { Array<1, int>::const_iterator i = a.getIndices().begin(); const Array<1, int>::const_iterator i_end = a.getIndices().end(); Array<1, int>::const_iterator j = b.getIndices().begin(); const Array<1, int>::const_iterator j_end = b.getIndices().end(); int count = 0; // Loop over the common index range. for (; i != i_end && j != j_end; ++count) { if (*i < *j) { ++i; } else if (*j < *i) { ++j; } else { // *i == *j ++i; ++j; } } // Count any remaining elements from a and b. Only one of these terms // can be non-zero. count += int(i_end - i) + int(j_end - j); return count; } //--------------------------------------------------------------------------- // Operations with arrays and sparse arrays. //--------------------------------------------------------------------------- // += on the non-null elements. template<typename T1, bool A, typename T2> inline Array<1, T1, A>& operator+=(Array<1, T1, A>& x, const SparseArray<1, T2> & y) { typename SparseArray<1, T2>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, T2>::const_iterator v = y.begin(); const typename SparseArray<1, T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { x[*i] += *v; } return x; } // -= on the non-null elements. template<typename T1, bool A, typename T2> inline Array<1, T1, A>& operator-=(Array<1, T1, A>& x, const SparseArray<1, T2> & y) { typename SparseArray<1, T2>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, T2>::const_iterator v = y.begin(); const typename SparseArray<1, T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { x[*i] -= *v; } return x; } // *= on the non-null elements. template<typename T1, bool A, typename T2> inline Array<1, T1, A>& operator*=(Array<1, T1, A>& x, const SparseArray<1, T2> & y) { typename SparseArray<1, T2>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, T2>::const_iterator v = y.begin(); const typename SparseArray<1, T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { x[*i] *= *v; } return x; } // /= on the non-null elements. template<typename T1, bool A, typename T2> inline Array<1, T1, A>& operator/=(Array<1, T1, A>& x, const SparseArray<1, T2> & y) { typename SparseArray<1, T2>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, T2>::const_iterator v = y.begin(); const typename SparseArray<1, T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { #ifdef DEBUG_stlib assert(*v != 0); #endif x[*i] /= *v; } return x; } // %= on the non-null elements. template<typename T1, bool A, typename T2> inline Array<1, T1, A>& operator%=(Array<1, T1, A>& x, const SparseArray<1, T2> & y) { typename SparseArray<1, T2>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, T2>::const_iterator v = y.begin(); const typename SparseArray<1, T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { #ifdef DEBUG_stlib assert(*v != 0); #endif x[*i] %= *v; } return x; } // Perform x += a * y on the non-null elements. template<typename T1, bool A, typename T2, typename T3> inline void scaleAdd(Array<1, T1, A>* x, const T2 a, const SparseArray<1, T3> & y) { typename SparseArray<1, T3>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, T3>::const_iterator v = y.begin(); const typename SparseArray<1, T3>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { (*x)[*i] += a * *v; } } //--------------------------------------------------------------------------- // Operations with FixedArray's and sparse arrays. //--------------------------------------------------------------------------- // += on the non-null elements. template<int _N, typename _T1, typename _T2> inline FixedArray<_N, _T1>& operator+=(FixedArray<_N, _T1>& x, const SparseArray<1, _T2>& y) { typename SparseArray<1, _T2>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, _T2>::const_iterator v = y.begin(); const typename SparseArray<1, _T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { x[*i] += *v; } return x; } // -= on the non-null elements. template<int _N, typename _T1, typename _T2> inline FixedArray<_N, _T1>& operator-=(FixedArray<_N, _T1>& x, const SparseArray<1, _T2>& y) { typename SparseArray<1, _T2>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, _T2>::const_iterator v = y.begin(); const typename SparseArray<1, _T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { x[*i] -= *v; } return x; } // *= on the non-null elements. template<int _N, typename _T1, typename _T2> inline FixedArray<_N, _T1>& operator*=(FixedArray<_N, _T1>& x, const SparseArray<1, _T2>& y) { typename SparseArray<1, _T2>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, _T2>::const_iterator v = y.begin(); const typename SparseArray<1, _T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { x[*i] *= *v; } return x; } // /= on the non-null elements. template<int _N, typename _T1, typename _T2> inline FixedArray<_N, _T1>& operator/=(FixedArray<_N, _T1>& x, const SparseArray<1, _T2>& y) { typename SparseArray<1, _T2>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, _T2>::const_iterator v = y.begin(); const typename SparseArray<1, _T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { #ifdef DEBUG_stlib assert(*v != 0); #endif x[*i] /= *v; } return x; } // %= on the non-null elements. template<int _N, typename _T1, typename _T2> inline FixedArray<_N, _T1>& operator%=(FixedArray<_N, _T1>& x, const SparseArray<1, _T2>& y) { typename SparseArray<1, _T2>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, _T2>::const_iterator v = y.begin(); const typename SparseArray<1, _T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { #ifdef DEBUG_stlib assert(*v != 0); #endif x[*i] %= *v; } return x; } // Perform x += a * y on the non-null elements. template<int _N, typename _T1, typename _T2, typename _T3> inline void scaleAdd(FixedArray<_N, _T1>* x, const _T2 a, const SparseArray<1, _T3>& y) { typename SparseArray<1, _T3>::IndexConstIterator i = y.getIndicesBeginning(); typename SparseArray<1, _T3>::const_iterator v = y.begin(); const typename SparseArray<1, _T3>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { (*x)[*i] += a * *v; } } } // namespace ads namespace std { //--------------------------------------------------------------------------- // Operations with arrays and sparse arrays. //--------------------------------------------------------------------------- // += on the non-null elements. template<typename T1, typename T2> inline vector<T1>& operator+=(vector<T1>& x, const ads::SparseArray<1, T2> & y) { typename ads::SparseArray<1, T2>::IndexConstIterator i = y.getIndicesBeginning(); typename ads::SparseArray<1, T2>::const_iterator v = y.begin(); const typename ads::SparseArray<1, T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { x[*i] += *v; } return x; } // -= on the non-null elements. template<typename T1, typename T2> inline vector<T1>& operator-=(vector<T1>& x, const ads::SparseArray<1, T2> & y) { typename ads::SparseArray<1, T2>::IndexConstIterator i = y.getIndicesBeginning(); typename ads::SparseArray<1, T2>::const_iterator v = y.begin(); const typename ads::SparseArray<1, T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { x[*i] -= *v; } return x; } // *= on the non-null elements. template<typename T1, typename T2> inline vector<T1>& operator*=(vector<T1>& x, const ads::SparseArray<1, T2> & y) { typename ads::SparseArray<1, T2>::IndexConstIterator i = y.getIndicesBeginning(); typename ads::SparseArray<1, T2>::const_iterator v = y.begin(); const typename ads::SparseArray<1, T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { x[*i] *= *v; } return x; } // /= on the non-null elements. template<typename T1, typename T2> inline vector<T1>& operator/=(vector<T1>& x, const ads::SparseArray<1, T2> & y) { typename ads::SparseArray<1, T2>::IndexConstIterator i = y.getIndicesBeginning(); typename ads::SparseArray<1, T2>::const_iterator v = y.begin(); const typename ads::SparseArray<1, T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { #ifdef DEBUG_stlib assert(*v != 0); #endif x[*i] /= *v; } return x; } // %= on the non-null elements. template<typename T1, typename T2> inline vector<T1>& operator%=(vector<T1>& x, const ads::SparseArray<1, T2> & y) { typename ads::SparseArray<1, T2>::IndexConstIterator i = y.getIndicesBeginning(); typename ads::SparseArray<1, T2>::const_iterator v = y.begin(); const typename ads::SparseArray<1, T2>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { #ifdef DEBUG_stlib assert(*v != 0); #endif x[*i] %= *v; } return x; } // Perform x += a * y on the non-null elements. template<typename T1, typename T2, typename T3> inline void scaleAdd(vector<T1>* x, const T2 a, const ads::SparseArray<1, T3> & y) { typename ads::SparseArray<1, T3>::IndexConstIterator i = y.getIndicesBeginning(); typename ads::SparseArray<1, T3>::const_iterator v = y.begin(); const typename ads::SparseArray<1, T3>::const_iterator vEnd = y.end(); for (; v != vEnd; ++i, ++v) { (*x)[*i] += a * *v; } } }
true
f77c123807c74eb939294363b7286aa839151037
C++
FranciscoRomano/INFT561
/projects/INFT561/ConsoleCanvas.h
UTF-8
2,014
2.8125
3
[]
no_license
#pragma once /** Dependencies **********************************************************************************/ #include "Win32.Console.h" /** Declarations **********************************************************************************/ #include "default.h" #include "Buffer.h" class ConsoleCanvas { public: // public structs struct Dot { vec4 v1; vec4 c1; }; struct Text { char * cstring; vec4 v1; vec4 c1; }; struct Line { vec4 v1, v2; vec4 c1, c2; }; struct Triangle { vec4 v1, v2, v3; vec4 c1, c2, c3; }; // public defaults ~ConsoleCanvas(); ConsoleCanvas(int width, int height); // public functions void clear(); void render(); void render(Dot data); void render(Text data); void render(Line data); void render(Triangle data); const int getWidth(); const int getHeight(); private: // variables int m_width; int m_height; int m_length; Win32::Console console; Buffer<float> m_DBuffer; // protected functions void RASTERIZE(const ConsoleCanvas::Line& data); void RASTERIZE(const ConsoleCanvas::Triangle& data); void RASTERIZE(const ConsoleCanvas::Dot& data); void RASTERIZE(const ConsoleCanvas::Text& data); void RASTERIZE(const int& index, const float& r, const float& g, const float& b); void WORLD_TO_SCREEN(vec4& point); bool RASTERIZE_CHECK(int x, int y, float z, int index); void TRIANGLE_SORT_BY_Y(ConsoleCanvas::Triangle& data); void TRIANGLE_SORT_BY_Y(vec4* v, vec4* c); vec4 LERP(const vec4& a, const vec4& b, float t); }; /**************************************************************************************************/
true
0f10c5167a1db204fcca506be93b65afc6a122e7
C++
szp35/Usb-uart-serial-port-communication
/scketchArduino.ino
UTF-8
8,317
2.546875
3
[]
no_license
#define inbits 14 // число значений в массиве, который хотим получить #define b 50 //задержка в передаче между каналами microseconds 50 #define c 50 //задержка после передачи в мс //byte receivenew; byte indexsend; bool recievedflag; bool sendingflag; bool startflag; bool stopflag; bool pwmflag; bool flagone; bool flagtwo; byte indata[inbits]; // входящие данные byte pressures[16]; // массив давлений на отправку byte currents[16]; // массив токов на отправку byte pwms [8]; //byte timer [3]; unsigned long totaltime; unsigned long previousstarttimer=0; unsigned long sendtimer = 0; const long sendinterval = 2000; unsigned long previousMillis = 0; const long interval = 1000; //sizeof(incomingByte) void sendingpress() { //отправка давлений Serial.write(pressures[0]); Serial.write(pressures[1]); delayMicroseconds(b); Serial.write(pressures[2]); Serial.write(pressures[3]); delayMicroseconds(b); Serial.write(pressures[4]); Serial.write(pressures[5]); delayMicroseconds(b); Serial.write(pressures[6]); Serial.write(pressures[7]); delayMicroseconds(b); Serial.write(pressures[8]); Serial.write(pressures[9]); delayMicroseconds(b); Serial.write(pressures[10]); Serial.write(pressures[11]); delayMicroseconds(b); Serial.write(pressures[12]); Serial.write(pressures[13]); delayMicroseconds(b); Serial.write(pressures[14]); Serial.write(pressures[15]); delay(c); } void sendingcurr(){ //отправка токов отправляется после 4х отправок давлений Serial.write(252); delayMicroseconds(b); Serial.write(currents[0]); Serial.write(currents[1]); delayMicroseconds(b); Serial.write(currents[2]); Serial.write(currents[3]); delayMicroseconds(b); Serial.write(currents[4]); Serial.write(currents[5]); delayMicroseconds(b); Serial.write(currents[6]); Serial.write(currents[7]); delayMicroseconds(b); Serial.write(currents[8]); Serial.write(currents[9]); delayMicroseconds(b); Serial.write(currents[10]); Serial.write(currents[11]); delayMicroseconds(b); Serial.write(currents[12]); Serial.write(currents[13]); delayMicroseconds(b); Serial.write(currents[14]); Serial.write(currents[15]); Serial.write(252); delay(c); } void pressuretransform(byte index, unsigned int val){ // преобразование давлений для отправки byte ext; byte a; index=index << 1; constrain(index, 0, 15); val=map(val,0,1023,0,4095); constrain(val, 0, 4095); a = val >> 8; if(val<=255){ ext=val; }else if (val>255 && val<=511){ ext=val-256; }else if (val>511 && val<=767){ ext=val-512; }else if (val>767 && val<=1023){ ext=val-768; }else if (val>1023 && val<=1279){ ext=val-1024; }else if (val>1279 && val<=1535){ ext=val-1280; }else if (val>1535 && val<=1791){ ext=val-1536; }else if (val>1791 && val<=2047){ ext=val-1792; }else if (val>2047 && val<=2303){ ext=val-2048; }else if (val>2303 && val<=2559){ ext=val-2304; }else if (val>2559 && val<=2815){ ext=val-2560; }else if (val>2815 && val<=3071){ ext=val-2816; }else if (val>3071 && val<=3327){ ext=val-3072; }else if (val>3327 && val<=3583){ ext=val-3328; }else if (val>3583 && val<=3839){ ext=val-3584; }else if (val>3839 && val<=4095){ ext=val-3840; } pressures[index]= ext; index++; pressures[index]= a; } void sensread(){ //чтение аналоговых входов и отправка данных pressuretransform(0,analogRead (A0)); pressuretransform(1,analogRead (A1)); pressuretransform(2,analogRead (A2)); pressuretransform(3,analogRead (A3)); pressuretransform(4,analogRead (A4)); pressuretransform(5,analogRead (A5)); pressuretransform(6,analogRead (A6)); pressuretransform(7,analogRead (A7)); if (micros() - sendtimer >= sendinterval) { sendtimer+=sendinterval; indexsend++; if (indexsend==4){ indexsend=0; sendingcurr(); }else{ sendingpress(); } } } void parsing() {//парсинг входящих данных //Serial.print(Serial.available()); if (Serial.available() > 0) {//слушаем ком порт Serial.readBytes(indata, inbits); recievedflag=1; Serial.print("have 1 step"); Serial.print(inbits); } if (recievedflag==1&&indata[0]==116){//старт данных sendingflag=1; recievedflag=0; flagone = 1; } if(flagone == 1){ Serial.print("already have two"); Serial.print("have 2 step###############"); } if (recievedflag==1 && indata[0]==120 && indata[1]==0 && indata[2]==0){ Serial.print("have 3 step##############"); startflag=1; previousstarttimer = millis(); sendtimer= micros(); Serial.write(254); Serial.write(255); delayMicroseconds(b); Serial.write(254); Serial.write(255); delayMicroseconds(b); Serial.write(254); Serial.write(255); delayMicroseconds(b); Serial.write(254); Serial.write(255); delayMicroseconds(b); Serial.write(254); Serial.write(255); delayMicroseconds(b); Serial.write(254); Serial.write(255); delayMicroseconds(b); Serial.write(254); Serial.write(255); delayMicroseconds(b); Serial.write(254); Serial.write(255); recievedflag=0; flagtwo = 1; } if (flagtwo == 1){ Serial.print(" we have 2 flag already! "); } if (recievedflag==1&&indata[0]==120&&indata[1]==138&&indata[2]==2||stopflag==1&&startflag==0){ //sendingflag=0; stopflag=0; Serial.write(255); Serial.write(255); delayMicroseconds(b); Serial.write(255); Serial.write(255); delayMicroseconds(b); Serial.write(255); Serial.write(255); delayMicroseconds(b); Serial.write(255); Serial.write(255); delayMicroseconds(b); Serial.write(255); Serial.write(255); delayMicroseconds(b); Serial.write(255); Serial.write(255); delayMicroseconds(b); Serial.write(255); Serial.write(255); delayMicroseconds(b); Serial.write(255); Serial.write(255); recievedflag=0; } if (recievedflag==1&&indata[0]==84){//стоп данных, обнуление времени sendingflag=0; totaltime = 0; recievedflag=0; } if (recievedflag==1&&indata[0]==113){ pwms[0]=indata[1]; pwms[1]=indata[3]; pwms[2]=indata[5]; pwms[3]=indata[7]; pwmflag=1; recievedflag=0; } if (recievedflag==1&&indata[0]==81){ pwms[4]=indata[1]; pwms[5]=indata[3]; pwms[6]=indata[5]; pwms[7]=indata[7]; pwmflag=1; recievedflag=0; } if (recievedflag==1&&indata[0]==115&&indata[2]==0){ //timer[0]=indata[11]; //timer[1]=indata[12]; unsigned int intime; recievedflag=0; intime = indata[12] << 8; intime = intime+indata[11]; totaltime = totaltime+intime; } } void pwmsend() { if (pwms[0]>0||pwms[1]>0||pwms[2]>0||pwms[3]>0||pwms[4]>0||pwms[5]>0||pwms[6]>0||pwms[7]>0){ PORTB=B00100000; }else {PORTB=B00000000; } } void setup() { //Serial.begin(9600); Serial.begin(115200); Serial.print("Setup!!"); flagone = 0; flagtwo = 0; pinMode(13,OUTPUT); pinMode(3,OUTPUT); pinMode(5,OUTPUT); pinMode(6,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(11,OUTPUT); pinMode (A0, INPUT); pinMode (A1, INPUT); pinMode (A2, INPUT); pinMode (A3, INPUT); pinMode (A4, INPUT); pinMode (A5, INPUT); pinMode (A6, INPUT); pinMode (A7, INPUT); for (byte i = 1; i < 16; i=i+2) { currents[i]=16; } //currents[0]=255; } void loop() { //Serial.print("looper"); //Serial.write(254); //delayMicroseconds(b); //Serial.write(255); //delay(200); //if (startflag==1){ //if (millis() - previousstarttimer >= totaltime) { // startflag=0; // stopflag=1;}} // // parsing(); // // if (sendingflag==1){ // sensread(); // } // //if (pwmflag==1){ // pwmsend(); // pwmflag=0; //} sensread(); /* unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; Serial.print("time="); Serial.println(totaltime); //analogWrite(3,arr1[1]); /* for (byte i = 0; i < inbits; i++) { // выводим элементы массива Serial.print(indata[i]); Serial.print(" "); } Serial.println(); for (byte i = 0; i < 8; i++) { // выводим элементы массива Serial.print(pwms[i]); Serial.print(" "); }Serial.println(); }*/ }
true
86f129c0412f7d1e14c7f090f0c885a2e1c51eda
C++
DannyPhantom/City-Generation
/CityGeneration/DynamicRoadGeneration/Square.h
UTF-8
450
2.578125
3
[]
no_license
#pragma once #include <vector> #include "../Libraries/glm/glm.hpp" class Line; class Square { public: Square(); ~Square(); bool lineBelongsTo(Line *line); std::pair<Square*, Square*> splitByLine(Line *line); std::vector<Line *> getLines(); bool pointBelongsTo(glm::vec2 point); bool pointBelongsToInside(glm::vec2 point); void toggleDisabledSubdivision(); Line *top; Line *left; Line *right; Line *bottom; bool canBeSubdivided; };
true
3859ce120eee234d58b3d65a5ddc54db4accaf81
C++
dhruvvgandhi/IOT-PRACTICAL
/17SE02CE017-SECE4031-PRACTICAL-11-2.ino
UTF-8
1,565
3.03125
3
[ "MIT" ]
permissive
//L293D //Motor A const int motorPin1 = 5; // Pin 14 of L293 const int motorPin2 = 6; // Pin 10 of L293 //Motor B const int motorPin3 = 10; // Pin 7 of L293 const int motorPin4 = 9; // Pin 2 of L293 //This will run only one time. void setup(){ //Set pins as outputs pinMode(motorPin1, OUTPUT); pinMode(motorPin2, OUTPUT); pinMode(motorPin3, OUTPUT); pinMode(motorPin4, OUTPUT); //Motor Control - Motor A: motorPin1,motorpin2 & Motor B: motorpin3,motorpin4 //This code will turn Motor A clockwise for 2 sec. digitalWrite(motorPin1, HIGH); digitalWrite(motorPin2, LOW); digitalWrite(motorPin3, LOW); digitalWrite(motorPin4, LOW); delay(2000); //This code will turn Motor A counter-clockwise for 2 sec. digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, HIGH); digitalWrite(motorPin3, LOW); digitalWrite(motorPin4, LOW); delay(2000); //This code will turn Motor B clockwise for 2 sec. digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, LOW); digitalWrite(motorPin3, HIGH); digitalWrite(motorPin4, LOW); delay(2000); //This code will turn Motor B counter-clockwise for 2 sec. digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, LOW); digitalWrite(motorPin3, LOW); digitalWrite(motorPin4, HIGH); delay(2000); //And this code will stop motors digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, LOW); digitalWrite(motorPin3, LOW); digitalWrite(motorPin4, LOW); } void loop(){ }
true
1b231a742185444d0ed4e10f9a5d844807655d76
C++
muhammedzahit/Deitel_Solutions
/CPP_How_To_Program_Solutions/3.14 Employee Class/employee.cpp
UTF-8
1,475
3.84375
4
[]
no_license
/* #include <iostream> #include <string> class Employee{ private: std::string first_name; std::string last_name; int salary; public: explicit Employee(std::string name1,std::string name2,int salary); void setFirstName(); std::string getFirstName(); void setLastName(); std::string getLastName(); void setSalary(); int getSalary(); void yearlySalary(); void raiseSalary(); }; */ #include "employee.h" using namespace std; string name; int number; Employee::Employee(std::string firstName, std::string lastName, int salary) : first_name(firstName),last_name(lastName),salary(salary) { if (salary < 0){ cout << "Fault: Salary must not be under 0! New salary is 0" << endl ; salary = 0; } } void Employee::setFirstName() { cout << "Enter First Name:"; getline(cin,name); first_name = name; } string Employee::getFirstName() { return first_name; } void Employee::setLastName(){ cout << "Enter Last Name:"; getline(cin,name); last_name = name; } string Employee::getLastName(){ return last_name; } void Employee::setSalary() { cout << "Enter new salary:"; cin >> number; salary = number; } int Employee::getSalary() { return salary; } void Employee::yearlySalary() { cout << "Yearly Salary is : " << salary*12 << endl; } void Employee::raiseSalary() { cout << "Enter raising percent:"; cin >> number; salary = (salary*(100+number))/100; }
true
a24a3224d4811e44232f7b73e1f46e35b0fd95dc
C++
bxy09/HAC
/src/fscore/fscore.cpp
UTF-8
5,401
2.921875
3
[]
no_license
#include<iostream> #include<fstream> #include<vector> #include<string> #include<sstream> #include<cmath> using namespace std; struct class_node { int label; float num; float fscore; }; struct cluster_tree_node { vector<int> label; float num; }; void init_class(ifstream&, vector<struct class_node>&, vector<int>&); void init_cluster(ifstream&, vector<struct cluster_tree_node>&, vector<int>&); void init_nir(vector<struct class_node>&, vector<struct cluster_tree_node>&, float**); void init_recall(vector<struct class_node>&, vector<struct cluster_tree_node>&, float**, float**); void init_precision(vector<struct class_node>&, vector<struct cluster_tree_node>&, float**, float**); void init_fsc(int, int, float**, float**, float**); void class_fscore(vector<struct class_node>& label_class, vector<struct cluster_tree_node>& cluster, float** fsc, ofstream& fp_fscore); float Fscore(vector<struct class_node>&); int main(int argc, char* argv[]) { if(argc != 3){ cout << "usage: arg1 label, arg2 cluster_tree" << endl; } ifstream fp1(argv[1]); if(!fp1) { cout << "Cannot open file label!"; return 1; } ifstream fp2(argv[2]); if(!fp2) { cout << "Cannot open file class_tree_label!"; return 1; } ofstream fp_fscore("fscore"); vector<struct class_node> label_class; vector<int> doc_label; init_class(fp1, label_class, doc_label); vector<struct cluster_tree_node> cluster; init_cluster(fp2,cluster, doc_label); float ** nir = new float*[cluster.size()]; init_nir(label_class,cluster,nir); float **recall = new float*[cluster.size()]; float **precision = new float*[cluster.size()]; init_recall(label_class,cluster,nir,recall); init_precision(label_class,cluster,nir,precision); float **fsc =new float*[cluster.size()]; init_fsc(cluster.size(),label_class.size(),fsc,recall,precision); class_fscore(label_class,cluster,fsc, fp_fscore); float fscore; fscore = Fscore(label_class); fp_fscore << fscore << endl; return 0; } void init_class(ifstream& fp1, vector<struct class_node>& label_class, vector<int>& doc_label) { struct class_node temp; int label; while(fp1 >> label) { doc_label.push_back(label); vector<struct class_node>::iterator iter; for(iter = label_class.begin(); iter != label_class.end(); iter++) { if(iter->label == label) { iter->num ++; break; } } if(iter == label_class.end()) { temp.label = label; temp.fscore = 0; temp.num = 1; label_class.push_back(temp); } } } void init_cluster(ifstream& fp2, vector<struct cluster_tree_node>& cluster, vector<int>& doc_label) { string strin; int temp; while(getline(fp2,strin)) { struct cluster_tree_node a; a.num = 0; stringstream strs(strin); while(strs >> temp) { a.label.push_back(doc_label[temp]); //a.label.push_back(temp); a.num++; } cluster.push_back(a); } } void init_nir(vector<struct class_node>& label_class,vector<struct cluster_tree_node>& cluster,float** nir) { for(int i = 0; i < (int)cluster.size(); i++) { nir[i] = new float[label_class.size()]; for(int j = 0; j< (int)label_class.size(); j++) { nir[i][j] = 0; for(int k = 0; k < cluster[i].label.size(); k++) { if(cluster[i].label[k] == label_class[j].label) { nir[i][j] ++; } } } } } void init_recall(vector<struct class_node>& label_class, vector<struct cluster_tree_node>& cluster, float** nir, float** recall) { for(int i = 0; i < cluster.size(); i++) { recall[i] = new float[label_class.size()]; for(int j = 0; j < label_class.size(); j++) { recall[i][j] = nir[i][j] / label_class[j].num; } } } void init_precision(vector<struct class_node>& label_class, vector<struct cluster_tree_node>& cluster, float** nir, float** precision) { for(int i = 0; i < cluster.size(); i++) { precision[i] =new float[label_class.size()]; for(int j = 0; j < label_class.size(); j++) { precision[i][j] = nir[i][j] / cluster[i].num; } } } void init_fsc(int num1, int num2, float** fsc, float** recall, float** precision) { float EPSINON = (float)0.00001; for(int i = 0; i < num1; i++) { fsc[i] = new float[num2]; for(int j = 0; j < num2; j++) { if(fabs(recall[i][j]) < EPSINON && fabs(precision[i][j]) < EPSINON) { fsc[i][j] = 0; } else { fsc[i][j] = 2*recall[i][j]*precision[i][j]/(recall[i][j] + precision[i][j]); } } } } void class_fscore(vector<struct class_node>& label_class, vector<struct cluster_tree_node>& cluster, float** fsc, ofstream& fp_fscore) { float temp; int temp_i; for(int j = 0; j < label_class.size(); j++) { temp = 0; for(int i = 0; i < cluster.size(); i++) { if(fsc[i][j] > temp) { temp = fsc[i][j]; // temp_i = i; //print which node is selected for fscore } } label_class[j].fscore = temp; //fp_fscore << label_class[j].label << " " << label_class[j].num << " " << label_class[j].fscore << endl; //fp_fscore << temp_i+1 << ": "; //for(int k = 0; k < cluster[temp_i].label.size(); k++){ //print which node is selected for fscore // fp_fscore << cluster[temp_i].label[k] << " "; //} //fp_fscore << endl; } } float Fscore(vector<struct class_node>& label_class) { float n = 0; float fscore = 0; for(int i = 0; i < label_class.size(); i++) { n += label_class[i].num; fscore += label_class[i].fscore * label_class[i].num; } fscore = fscore / n; return fscore; }
true
6c670d9aee70c0d9792c7fbee5124d1cc44ce060
C++
cdsama/cdscript
/src_test/test_lexer_string.cpp
UTF-8
5,516
2.609375
3
[ "MIT" ]
permissive
// Copyright (c) 2019 chendi // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #include <iostream> #include <limits> #include <sstream> #include "catch2_ext.hpp" #include "lexer.hpp" using namespace cd; using namespace script; TEST_CASE("Lexer-String", "[core][lexer][string]") { std::istringstream code(R"#("hello"""'hello''')#"); auto lexer = Lexer::GetLexer(code); auto token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == "hello"); token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == ""); token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == "hello"); token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == ""); token = lexer->GetToken(); CHECK(token.type == Token::EndOfFile); } TEST_CASE("Lexer-String-EscapeCharacter", "[core][lexer][string]") { { std::istringstream code(R"#("\a\b\f\n\r\t\v\\\"\'")#"); auto lexer = Lexer::GetLexer(code); auto token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == "\a\b\f\n\r\t\v\\\"\'"); token = lexer->GetToken(); CHECK(token.type == Token::EndOfFile); } { std::istringstream code(R"#("\x48\x65\x6c\x6c\x6f \x57\x6f\x72\x6c\x64\x21")#"); auto lexer = Lexer::GetLexer(code); auto token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == "Hello World!"); token = lexer->GetToken(); CHECK(token.type == Token::EndOfFile); } { std::istringstream code(R"#("\0\72\101\108\108\111 \87\111\114\108\100\33\255")#"); auto lexer = Lexer::GetLexer(code); auto token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == std::string("\0Hello World!\xff", 14)); token = lexer->GetToken(); CHECK(token.type == Token::EndOfFile); } { std::istringstream code(R"#("\0725\x48TML5")#"); auto lexer = Lexer::GetLexer(code); auto token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == "H5HTML5"); token = lexer->GetToken(); CHECK(token.type == Token::EndOfFile); } } TEST_CASE("Lexer-String-Exception", "[core][lexer][string]") { { std::istringstream code("\"\n\""); auto lexer = Lexer::GetLexer(code); CHECK_THROWS_MATCHES(lexer->GetToken(), Exception, WhatEquals("incomplete string at line:1 column:2")); } { std::istringstream code("'\n'"); auto lexer = Lexer::GetLexer(code); CHECK_THROWS_MATCHES(lexer->GetToken(), Exception, WhatEquals("incomplete string at line:1 column:2")); } { std::istringstream code("\""); auto lexer = Lexer::GetLexer(code); CHECK_THROWS_MATCHES(lexer->GetToken(), Exception, WhatEquals("incomplete string at <eof>")); } { std::istringstream code("'"); auto lexer = Lexer::GetLexer(code); CHECK_THROWS_MATCHES(lexer->GetToken(), Exception, WhatEquals("incomplete string at <eof>")); } { std::istringstream code(R"#("\xxx")#"); auto lexer = Lexer::GetLexer(code); CHECK_THROWS_MATCHES(lexer->GetToken(), Exception, WhatEquals(R"#(unexpected character after '\x' line:1 column:4)#")); } { std::istringstream code(R"#("\256")#"); auto lexer = Lexer::GetLexer(code); CHECK_THROWS_MATCHES(lexer->GetToken(), Exception, WhatEquals(R"#(decimal escape too large near \256 line:1 column:6)#")); } { std::istringstream code(R"#("\p")#"); auto lexer = Lexer::GetLexer(code); CHECK_THROWS_MATCHES(lexer->GetToken(), Exception, WhatEquals(R"#(unexpected character after '\' line:1 column:3)#")); } } TEST_CASE("Lexer-String-Raw", "[core][lexer][string]") { { std::istringstream code(R"#(R"(\n)")#"); auto lexer = Lexer::GetLexer(code); auto token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == R"#(\n)#"); } { std::istringstream code(R"#(R"___(@)__)_______)___")#"); auto lexer = Lexer::GetLexer(code); auto token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == R"#(@)__)_______)#"); } { std::istringstream code(R"#(R"________________(\n)________________")#"); auto lexer = Lexer::GetLexer(code); auto token = lexer->GetToken(); CHECK(token.type == Token::String); CHECK(token.str() == R"#(\n)#"); } { std::istringstream code(R"#(R"_________________()_________________")#"); auto lexer = Lexer::GetLexer(code); CHECK_THROWS_MATCHES(lexer->GetToken(), Exception, WhatEquals(R"#(raw string delimiter longer than 16 characters : line:1 column:19)#")); } { std::istringstream code(R"#(R"@()@")#"); auto lexer = Lexer::GetLexer(code); CHECK_THROWS_MATCHES(lexer->GetToken(), Exception, WhatEquals(R"#(invalid character in raw string delimiter :@ line:1 column:3)#")); } { std::istringstream code(R"#(R"()@")#"); auto lexer = Lexer::GetLexer(code); CHECK_THROWS_MATCHES(lexer->GetToken(), Exception, WhatEquals(R"#(incomplete raw string at <eof>)#")); } }
true
a64c5d4d831c81d36637dde9f9f659e62259cc2b
C++
Michael-A-Berger/DailyProgrammer
/DP_Hard281/DP_Hard281/MS_Creator.h
UTF-8
768
3.171875
3
[ "MIT" ]
permissive
/* Context: https://www.reddit.com/r/dailyprogrammer/comments/50s3ax/ Created by Michael Berger */ #pragma once //Inclusions & Usings #include <iostream>; #include <ctime>; using std::cout; using std::endl; using std::cin; //The MS_Creator class class MS_Creator { //Public variables & methods public: MS_Creator(); ~MS_Creator(); void createRandomMap(int xSize, int ySize, int numMines); void printMap(); char** retrievePublicMap(); void revealSpace(int x, int y); bool isGameOver(); //Private variables & methods private: void placeMines(int numMines); void calcSpaces(); char** map; char** publicMap; bool gameOver = false; int mapWidth = 0; int mapHeight = 0; char mineChar = 'X'; char emptyChar = '-'; char hiddenChar = '?'; };
true
a17f50da893eb18fa79dd79a624e30d22d9d02a9
C++
usherfu/zoj
/zju.finished/2511.cpp
UTF-8
1,039
2.859375
3
[]
no_license
#include<iostream> #include<cmath> #include<vector> using namespace std; const double eps = 1e-8; struct Node { int no; double score; bool operator < (const Node&rhs) const { if( fabs(score - rhs.score) < eps) return no < rhs.no; return score > rhs.score; } }; struct cmp{ bool operator()(const Node&lhs, const Node&rhs)const { return lhs.no > rhs.no; } }; int N,M,K; vector<Node> t; void fun(){ t.reserve(M); for(int i=0;i<M;i++){ t[i].no = i + 1; t[i].score = 0; } double s; for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ scanf("%lf",&s); t[j].score += s; } } sort(t.begin(), t.begin() + M); sort(t.begin(), t.begin() + K, cmp()); for(int i=0;i<K;i++){ if(i==0){ printf("%d", t[i].no); } else { printf(" %d", t[i].no); } } printf("\n"); } int main(){ while(scanf("%d%d%d",&N,&M,&K) > 0){ fun(); } return 0; }
true
a54cd21194128570bd6ce21f03d7fc5ab1581293
C++
Psunu/SchoolProjectServer
/SchoolServer/MooIn/TestClient/main.cpp
UTF-8
2,262
2.8125
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <cstdio> #include <unistd.h> #include <arpa/inet.h> typedef int SOCKET; using namespace std; const char RASP = '0'; const char ANDROID = '1'; char name[10] = "박선우"; char status = '4'; typedef struct { char name[10]; char status; } Packet; int main(void) { sockaddr_in ServerAddr; memset(&ServerAddr, 0, sizeof(ServerAddr)); ServerAddr.sin_family = AF_INET; ServerAddr.sin_port = htons(8002); ServerAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); int type; cout << "Enter data type : "; cin >> type; if (type == 1) { int ClntNum = 0; cout << "Enter number of clients : "; cin >> ClntNum; SOCKET *clients = new SOCKET[ClntNum]; for (int i = 0; i < ClntNum; i++) { clients[i] = socket(AF_INET, SOCK_STREAM, 0); connect(clients[i], (sockaddr *)&ServerAddr, sizeof(ServerAddr)); printf("%s\n", name); if (i == 0) send(clients[i], &RASP, sizeof(RASP), 0); else send(clients[i], &ANDROID, sizeof(ANDROID), 0); char flag = '1'; send(clients[i], &flag, sizeof(flag), 0); send(clients[i], name, 9, 0); send(clients[i], &status, sizeof(status), 0); sleep(1); } for (int i = 1; i < ClntNum; i++) { Packet packet; memset(&packet, 0, sizeof(packet)); recv(clients[0], packet.name, 9, 0); recv(clients[0], &packet.status, sizeof(packet.status), 0); printf("Name: %s\n", packet.name); printf("Status: %d\n\n", packet.status); } for (int i = 0; i < ClntNum; i++) { close(clients[i]); } } else if (type == 2){ char flag = '2'; char id[16]; char pass[16]; cout << "Enter your ID : "; cin >> id; cout << "Enter your PW : "; cin >> pass; SOCKET client = socket(AF_INET, SOCK_STREAM, 0); connect(client, (sockaddr *)&ServerAddr, sizeof(ServerAddr)); send(client, &ANDROID, sizeof(RASP), 0); send(client, &flag, sizeof(flag), 0); send(client, id, sizeof(id), 0); send(client, pass, sizeof(pass), 0); char res = 0; char name[16]; recv(client, &res, sizeof(res), 0); if (res == 0) cout << "Login failed!" << endl; else { recv(client, name, sizeof(name), 0); cout << "Login Success!" << endl; cout << "Name : " << name << endl; } close(client); } }
true
e4df0f2dbfe1f76f9e59209f20557b53d7f5e0f1
C++
thegamer1907/Code_Analysis
/contest/1542578648.cpp
UTF-8
1,272
2.703125
3
[]
no_license
#include<bits/stdc++.h> #define fastio ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define PB push_back using namespace std; bool check(int arr[16], int pos, int m, vector<int> possib, int count){ // cout << count << " " << pos << " -- "; // for (auto el : possib) cout << " " << el; // cout << endl; if (pos >= (1 << m)) return false; int maksi = 0; for (auto el : possib) maksi = max(maksi, el); if (count > 0 && (maksi <= count / 2)) return true; bool result = false; for (int i = pos; i < (1 << m) && !result; i++){ // cout << "pos " << i << " " << arr[i] << endl; if (arr[i] > 0){ vector<int> temp(possib); for (int j = 0; j < m; j++){ // cout << ((i & (1 << j)) > 0) << " "; temp[j] += (i & (1 << j)) > 0; } // cout << endl; result = result || check(arr, i + 1, m, temp, count+1); } } return result; } int main(){ fastio; int n, m; cin >> n >> m; int occur[16]; memset(occur, 0, sizeof occur); int a; while (n--){ int temp = 0; for (int i = 0; i < m; i++){ cin >> a; temp += (a << i); } occur[temp]++; } vector<int> possib; for (int i = 0; i < m; i++) possib.PB(0); if (occur[0] > 0 || check(occur,0, m, possib, 0)) { cout << "YES\n"; } else { cout << "NO\n"; } return 0; }
true
394f2923822686b4c50871e1b8d1435edc6fa5da
C++
LeeJehwan/Power-C-Programming
/PART1/PART1/problem18.cpp
UHC
1,272
3.46875
3
[]
no_license
#include <iostream> #include <stdio.h> using namespace std; int strlen(char * str) { int cnt = 0; while (str[cnt] != '\0') { cnt++; } return cnt; } void strcpy(char * str1, char * str2) { int idx = 0; while (str2[idx] != '\0') { str1[idx] = str2[idx]; idx++; } str1[idx] = '\0'; } void swap_str(char *str1, char* str2) { char tmp[20]; strcpy(tmp, str1); strcpy(str1, str2); strcpy(str2, tmp); } int strcmp(char * str1, char * str2) { int idx = 0; while (str1[idx]) { if (str1[idx] != str2[idx]) break; idx++; } return str1[idx] - str2[idx]; } void strcat(char* str1, char* str2) { int len = strlen(str1); if(len != 0) str1[len++] = ' '; int idx = 0; while(str2[idx]){ str1[len++] = str2[idx++]; } str1[len] = '\0'; } int main() { char str1[20], str2[20], str3[20], str4[20]; char str[80] = ""; char* pstr[4] = { str1, str2, str3, str4 }; for (int i = 0; i < 4; i++){ cout << "ڿ Է " << i+1 << ": "; cin >> pstr[i]; } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3 - i; j++) { if (strcmp(pstr[j], pstr[j + 1]) > 0) { swap_str(pstr[j], pstr[j + 1]); } } } for (int i = 0; i < 4; i++) { strcat(str, pstr[i]); } cout << "ĵ ڿ: "; cout << str << endl; return 0; }
true
b79d9aa92d1aa87f6475a6d53de410f61c38c73a
C++
thekirjava/BSU
/Cryptography/Lab1/Vigenere.cpp
UTF-8
945
2.984375
3
[]
no_license
// // Created by JUSTONEIDEA on 19.09.2021. // #include "Vigenere.h" #include <utility> Vigenere::Vigenere(std::string keyword):keyword(std::move(keyword)) { } std::string Vigenere::encrypt(const std::string& data) const { return processString(data, 1); } std::string Vigenere::decrypt(const std::string &data) const { return processString(data, -1); } std::string Vigenere::processString(const std::string &data, int sign) const { std::string processed; processed.reserve(data.size()); for (int i = 0; i < data.size(); ++i) { if (!isalpha(data[i])) { processed.push_back(data[i]); continue; } int cur = data[i] - LANG_OFFSET; cur += (keyword[i % keyword.length()] - LANG_OFFSET) * sign; if (cur < 0) { cur += LANG_LENGTH; } cur %= LANG_LENGTH; processed.push_back(cur + LANG_OFFSET); } return processed; }
true
7c5df7a9c93fb2e9fc83ceef1129b9d7951c4ceb
C++
OlegSchwann/Technopark-algorithms
/3-й модуль/1 задание/CArcGraph.hpp
UTF-8
1,101
3.34375
3
[]
no_license
// Необходимо написать реализацию интерфейса IGraph: // CArcGraph, хранящий граф в виде одного массива пар {from, to}. // Очень медленно будет работать. #include "IGraph.hpp" #ifndef INC_1_CARCGRAPH_HPP #define INC_1_CARCGRAPH_HPP class CArcGraph : public IGraph { public: explicit CArcGraph(int n) : number_of_vertices(n) {} ~CArcGraph(){}; explicit CArcGraph(const IGraph &other); // Добавление ребра от from к to. void AddEdge(int from, int to) override; size_t VerticesCount() const override { return number_of_vertices; } std::vector<int> GetNextVertices(int vertex) const override; std::vector<int> GetPrevVertices(int vertex) const override; private: // массив начал и концов рёбер. std::vector<std::pair<int, int>> edge_array; bool isValidIndex(int index) const; // количество вершин в графе. size_t number_of_vertices; }; #endif //INC_1_CARCGRAPH_HPP
true
671fb992856e3f83b4f1248d08dcbe1054df03d4
C++
triffon/oop-2019-20
/labs/4/lab6 - files part 1/Source.cpp
UTF-8
2,047
3.3125
3
[ "MIT" ]
permissive
#include "Student.h" #include "StudentDynamic.h" #include <iostream> #include <fstream> #include <cassert> using namespace std; void assertEqual(const Student& s1, const Student& s2) { assert(strcmp(s1.getName(), s2.getName()) == 0); assert(s1.getFn() == s2.getFn()); } void assertEqual(const StudentDynamic& s1, const StudentDynamic& s2) { assert(strcmp(s1.getName(), s2.getName()) == 0); assert(s1.getFn() == s2.getFn()); } void testStudents(bool binary = false) { Student s1("Pe6o", 1002); Student s2("Pe6o2", 1000); const char* fileName = binary ? "students.dat" : "students.txt"; ofstream fileOut; if (binary) { fileOut.open(fileName, ios::binary); s1.serializeBinary(fileOut); s2.serializeBinary(fileOut); } else { fileOut.open(fileName); s1.serialize(fileOut); s2.serialize(fileOut); } fileOut.close(); ifstream fileIn; Student s3, s4; if (binary) { fileIn.open(fileName, ios::binary); s3.deserializeBinary(fileIn); s4.deserializeBinary(fileIn); } else { fileIn.open(fileName); s3.deserialize(fileIn); s4.deserialize(fileIn); } assertEqual(s1, s3); assertEqual(s2, s4); s3.print(); s4.print(); } void testDynamicStudents(bool binary = false) { StudentDynamic s1("Pe6o", 1002); StudentDynamic s2("Pe6o2", 1000); const char* fileName = binary ? "dynamicStudents.dat" : "dynamicStudents.txt"; ofstream fileOut; if (binary) { fileOut.open(fileName, ios::binary); s1.serializeBinary(fileOut); s2.serializeBinary(fileOut); } else { fileOut.open(fileName); s1.serialize(fileOut); s2.serialize(fileOut); } fileOut.close(); ifstream fileIn; StudentDynamic s3, s4; if (binary) { fileIn.open(fileName, ios::binary); s3.deserializeBinary(fileIn); s4.deserializeBinary(fileIn); } else { fileIn.open(fileName, ios::binary); s3.deserialize(fileIn); s4.deserialize(fileIn); } assertEqual(s1, s3); assertEqual(s2, s4); s3.print(); s4.print(); } int main() { testStudents(true); testStudents(); testDynamicStudents(true); testDynamicStudents(); }
true
40a838023a738891fe848ad7711afcd3a1b20e3c
C++
mmamyan/Virtual-Assembler-Interpreter
/Headers/Instruction.h
UTF-8
970
2.671875
3
[]
no_license
// // Created by Narek Hovhannisyan and/or Milena Mamyan on 10/14/18. // #ifndef VIRTUAL_MACHINE_OPCODEPARSER_H #define VIRTUAL_MACHINE_OPCODEPARSER_H #include "LanguageConstants.h" #include <cstdint> class Instruction { private: static const uint8_t REGISTERS_ORDER_MASK = 0b00000011; static const uint8_t JUMP_EXTENSION_MASK = 0b00111100; static const uint8_t DATA_SIZE_MASK = 0b11000000; /* Private members */ uint8_t opCode; uint8_t jumpExtension; uint8_t dataSize; uint8_t registersOrder; uint8_t register1; uint8_t register2; uint32_t literal; public: /* Constructing */ Instruction(uint64_t instructionCode); /* Public interface */ uint8_t getOpCode(); uint8_t getJumpExtension() const; uint8_t getDataSize() const; uint8_t getRegistersOrder() const; uint8_t getRegister1() const; uint8_t getRegister2() const; uint32_t getLiteral() const; }; #endif //VIRTUAL_MACHINE_OPCODEPARSER_H
true
3106a19de9fb9f1423193cc772f4e9db56739ca2
C++
sebastiaan1997/reflectxx
/src/parser/definition_base.hpp
UTF-8
948
2.890625
3
[]
no_license
#ifndef REFLECT_DEFINITION_BASE_HPP #define REFLECT_DEFINITION_BASE_HPP #include <string_view> namespace rf { class DefinitionBase { private: std::string_view _file; std::size_t _line_number; std::string_view _src; protected: constexpr DefinitionBase(std::string_view file, std::size_t line_number, std::string_view src): _file(file), _line_number(line_number), _src(src) { } [[nodiscard]] constexpr std::string_view src() const noexcept { return this->_src; } public: DefinitionBase() = delete; [[nodiscard]] constexpr std::string_view file() const noexcept { return this->_file; } [[nodiscard]] constexpr std::size_t line_number() const noexcept { return this->_line_number; } }; } #endif //REFLECT_DEFINITION_BASE_HPP
true
e1b23305617d978396c6344e5788140f5b429c73
C++
NazmulHasanMoon/OJ
/Random/cf-A. Anton and Danik-379-2.cpp
UTF-8
456
2.53125
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstring> #define sz 100005 using namespace std; char c[sz]; int main() { long int i,x,y,n; scanf("%ld",&n); getchar(); x=y=0; for(i=0;i<n;i++) { scanf("%c",&c[i]); if(c[i]=='A') x++; else y++; } if(x>y) printf("Anton\n"); else if(x<y) printf("Danik\n"); else printf("Friendship\n"); return 0; }
true
53a6d884509057b9221d5d7cbaf6828c79db57a3
C++
LievreAI/unreal-follow-lead-ai
/Source/FollowLeadAI/Player/PlayerCharacter.cpp
UTF-8
6,034
2.5625
3
[ "MIT" ]
permissive
#include "PlayerCharacter.h" #include "Camera/CameraComponent.h" #include "Components/InputComponent.h" #include "Components/CapsuleComponent.h" #include "Components/SkeletalMeshComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/SpringArmComponent.h" /** * Sets the default values for the PlayerCharacter. */ APlayerCharacter::APlayerCharacter() { // Load the resources needed for the PlayerCharacter. static ConstructorHelpers::FObjectFinder<USkeletalMesh>PlayerSkeletalMeshAsset(TEXT("SkeletalMesh'/Game/Mannequin/Character/Mesh/SK_Mannequin.SK_Mannequin'")); static ConstructorHelpers::FObjectFinder<UAnimBlueprint>PlayerAnimBlueprint(TEXT("AnimBlueprint'/Game/Blueprints/PlayerAnimBlueprint.PlayerAnimBlueprint'")); // Set the SkeletalMeshComponent to the Character's mesh and adjust its properties. PlayerSkeletalMesh = GetMesh(); PlayerSkeletalMesh->SetSkeletalMesh(PlayerSkeletalMeshAsset.Object); PlayerSkeletalMesh->SetRelativeLocationAndRotation(FVector(0.f, 0.f, -90.f), FRotator(0.f, -90.f, 0.f)); PlayerSkeletalMesh->SetAnimInstanceClass(PlayerAnimBlueprint.Object->GeneratedClass); // Create the SpringArmComponent and attach it to the RootComponent. PlayerCameraSpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("PlayerCameraSpringArm")); PlayerCameraSpringArm->TargetArmLength = 500.f; PlayerCameraSpringArm->bUsePawnControlRotation = true; PlayerCameraSpringArm->SetupAttachment(RootComponent); // Create the CameraComponent and attach it to the SpringArmComponent. PlayerCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("PlayerCamera")); PlayerCamera->bUsePawnControlRotation = false; PlayerCamera->SetupAttachment(PlayerCameraSpringArm, USpringArmComponent::SocketName); // Sets the capsule collider's size. GetCapsuleComponent()->InitCapsuleSize(40.f, 100.f); // Set the PlayerCharacter to not rotate when the controller rotates. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Set the default values for the PlayerCharacter's movement. GetCharacterMovement()->bOrientRotationToMovement = true; GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); GetCharacterMovement()->MaxWalkSpeed = WalkSpeed; // Set the PlayerCharacter to be the default player of the game. AutoPossessPlayer = EAutoReceiveInput::Player0; } /** * Called to bind functionality to input. * * @param PlayerInputComponent An Actor component for input bindings. */ void APlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { check(PlayerInputComponent); // Set up the methods to respond to the PlayerCharacter moving forward, backward, // left, and right. PlayerInputComponent->BindAxis("MoveForwardBackward", this, &APlayerCharacter::MoveForwardBackward); PlayerInputComponent->BindAxis("MoveLeftRight", this, &APlayerCharacter::MoveLeftRight); // Set the "TurnLeftRight" and "LookUpDown" axis inputs to control the yaw and pitch // of the camera. PlayerInputComponent->BindAxis("TurnLeftRight", this, &APlayerCharacter::AddControllerYawInput); PlayerInputComponent->BindAxis("LookUpDown", this, &APlayerCharacter::AddControllerPitchInput); // Set up the methods to respond to the sprint action input being pressed and released. PlayerInputComponent->BindAction("Sprint", IE_Pressed, this, &APlayerCharacter::SprintStart); PlayerInputComponent->BindAction("Sprint", IE_Released, this, &APlayerCharacter::SprintStop); // Set up the method to respond to the AllyLead action input being pressed. PlayerInputComponent->BindAction("AllyLead", IE_Pressed, this, &APlayerCharacter::LeadAction); } /** * Called when the PlayerCamera moves forward and backward. * * @param Value The axis value from the input. */ void APlayerCharacter::MoveForwardBackward(float Value) { // Return early if the Controller is a nullptr or the axis input value is zero. if (GetController() == nullptr || Value == 0.f) return; // Find the forward rotation. const FRotator Rotation = GetController()->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // Find the forward vector. const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); // Apply movement to the forward direction of the PlayerCharacter with a value // of `Value`. AddMovementInput(Direction, Value); } /** * Called when the PlayerCamera moves left and right. * * @param Value The axis value from the input. */ void APlayerCharacter::MoveLeftRight(float Value) { // Return early if the Controller is a nullptr or the `Value` is zero. if (GetController() == nullptr || Value == 0.f) return; // Find the right rotation. const FRotator Rotation = GetController()->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // Find the right direction. const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // Add movement to the right axis with a value of `Value`. AddMovementInput(Direction, Value); } /** * Called when the sprint input action button is pressed down and it sets the * `bIsSprinting` boolean to `true` so the animator knows to play the sprint animation. */ void APlayerCharacter::SprintStart() { bIsSprinting = true; if (GetCharacterMovement()) GetCharacterMovement()->MaxWalkSpeed = SprintSpeed; } /** * Called when the sprint input action button is pressed down and it sets the * `bIsSprinting` boolean to `false` so the animator knows to stop the sprint animation. */ void APlayerCharacter::SprintStop() { bIsSprinting = false; if (GetCharacterMovement()) GetCharacterMovement()->MaxWalkSpeed = WalkSpeed; } /** * Called when the "Lead" action input is pressed. */ void APlayerCharacter::LeadAction() { // Make the AllyCharacter lead the PlayerCharacter from the first waypoint to the // second waypoint and waiting for the PlayerCharacter to be in range. OnAllyLeadRequest.Broadcast(0, 1, true); }
true
57357313fad588c426b7b45c0c3f8b01a0a7a4c4
C++
student-leti/map_words
/main.cpp
UTF-8
1,524
3.21875
3
[]
no_license
#include <fstream> #include <iostream> #include <set> #include <map> #include <string> #define word_lenght 50 using namespace std; int main(){ char word[word_lenght]; int i = 0; map<string, int> vacebulary; set<int> count; set<string> words; set<string>::iterator it; string path; ifstream file; cout<< "Insert a text file dir:"; cin>>path; file.open(path); if(file.is_open()){ //get the first char in the file char c = file.get(); while (file.good()){ //checking if it is the white-space or punct if(!isspace(c) and !ispunct(c)){ word[i] = c; i++; word[i] = '\0'; } else{ if(word[0] != '\0'){ //checking if the word in the set it = words.find(word); if(it == words.end()){ words.insert(word); vacebulary[word]=1; } else{ vacebulary[word]+=1; } i = 0; //drop the the previuos word for(int j = 0; j < word_lenght; j++){ word[j]='\0'; } } } c = file.get(); } } else{ cout << "openning the file was failed" << endl; } file.close(); for(auto iter = vacebulary.begin(); iter!=vacebulary.end(); iter++){ count.insert(iter->second); } cout << "The text contains the next words:" << endl; for(auto iter_set = count.rbegin(); iter_set!=count.rend(); iter_set++){ for(auto iter_map = vacebulary.begin(); iter_map!=vacebulary.end(); iter_map++){ if(iter_map->second == *iter_set){ cout << iter_map->second << " => " << iter_map->first << endl; } } } return 0; }
true
104dd9d2c3c4450ed7d4fdfe1d3dddbf1d67aa33
C++
littlee1032/fkalg
/POJ/1239/main.cpp
UTF-8
1,824
2.875
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 90; char s[maxn]; int len, dpforward[maxn], dpbackward[maxn]; bool cmp(int s1, int t1, int s2, int t2); int main() { while(true) { scanf("%s", s); len = strlen(s); if(len == 1 && s[0] == '0') break; memset(dpforward, 0, sizeof(dpforward)); memset(dpbackward, 0, sizeof(dpbackward)); for(int i = 1; i < len; i++) { for(int j = 0; j < i; j++) { if(cmp(dpforward[j], j, j+1, i)) dpforward[i] = max(dpforward[i], j+1); } } int tlen = dpforward[len-1]; dpbackward[tlen] = len - 1; for(int i = tlen - 1; s[i] == '0'; i--) dpbackward[i] = len - 1; for(int i = tlen - 1; i >= 0; i--) { for(int j = i; j <= tlen - 1; j++) { if(cmp(i, j, j + 1, dpbackward[j+1])) dpbackward[i] = max(dpbackward[i], j); } } int pos = dpbackward[0], i = 0; while(i < len) { while(i <= pos && i < len) printf("%c", s[i++]); if(i < len) printf(","); pos = dpbackward[pos + 1]; } printf("\n"); } return 0; } bool cmp(int s1, int t1, int s2, int t2) { while(s[s1] == '0' && s1 <= t1) s1++; while(s[s2] == '0' && s2 <= t2) s2++; if(s1 > t1 && s2 > t2) return true; if((t1 - s1) > (t2 - s2)) return false; else if((t1 - s1) < (t2 - s2)) return true; else { for(int i = s1, j = s2; i <= t1; i++, j++) { if(s[i] > s[j]) return false; else if(s[i] < s[j]) return true; } } return false; }
true
58da83da0cc3073aa633dd7d9fea1ba395c6ba40
C++
qucphng0205/Ninja-Gaiden
/LearningDirectX2/Effect.cpp
UTF-8
408
2.609375
3
[]
no_license
#include "Effect.h" Effect::Effect(D3DXVECTOR3 position, float durationTime) { this->durationTime = durationTime; this->position = position; } bool Effect::Update(double dt) { //false will destroy this anim->Update(dt); if (anim->GetPercentTime() > durationTime) return false; return true; } void Effect::Render() { anim->Render(position); } Effect::~Effect() { delete anim; anim = NULL; }
true
37f6c9457316bec983f9a265bf0a7dccf0bafe17
C++
MinaPecheux/Advent-Of-Code
/2019/C++/src/day10.cpp
UTF-8
8,455
3.546875
4
[]
no_license
/** * \file day10.cpp * \brief AoC 2019 - Day 10 (C++ version) * \author Mina Pêcheux * \date 2019 * * [ ADVENT OF CODE ] (https://adventofcode.com) * --------------------------------------------- * Day 10: Monitoring Station * ============================================= */ #include <algorithm> #include <cmath> #include <map> #include "utils.hpp" // [ Util structs and definitions ] // -------------------------------- typedef struct { float angle; float distance; std::string pos; } AsteroidInfo; bool operator<(const AsteroidInfo& first, const AsteroidInfo& second) { if (first.angle > second.angle) { return false; } if (first.angle == second.angle) { return first.distance < second.distance; } return true; } typedef std::map<std::string,std::vector<AsteroidInfo> > SightsMap; // [ Input parsing functions ] // --------------------------- /** * \fn std::vector<std::string> parseData(std::string data) * \brief Parses the incoming data into a list of asteroids coordinates (in the * "x,y" format). * * \param data Provided problem data. * \return Parsed data. */ std::vector<std::string> parseData(std::string data) { std::vector<std::string> asteroids; std::vector<std::string> lines = strSplit(data, "\n"); int height = lines.size(); int width = lines[0].length(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (lines[y][x] == '#') { asteroids.push_back(strFormat("%d,%d", x, y)); } } } return asteroids; } /** * \fn float dist(std::string& p1, std::string& p2) * \brief Computes the angle between two 2D points using the atan2 and rotates * the result by 90° counterclockwise. * * \param p1 Coordinates of the first point (in the "x,y" string format). * \param p2 Coordinates of the second point (in the "x,y" string format). * \return Modified angle between the two 2D points. */ float angle(std::string& p1, std::string& p2) { int x1, y1, x2, y2; decomposeCoordinates(p1, x1, y1); decomposeCoordinates(p2, x2, y2); float m = 2.0 * M_PI; float a = fmod(atan2(y1 - y2, x1 - x2) - 0.5 * M_PI, m); return fmod(a + m, m); } /** * \fn float dist(std::string& p1, std::string& p2) * \brief Computes the Euclidean distance between two 2D points. * * \param p1 Coordinates of the first point (in the "x,y" string format). * \param p2 Coordinates of the second point (in the "x,y" string format). * \return Euclidean distance between the two 2D points. */ float dist(std::string& p1, std::string& p2) { int x1, y1, x2, y2; decomposeCoordinates(p1, x1, y1); decomposeCoordinates(p2, x2, y2); return sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)); } /** * \fn SightsMap prepareMap (std::string data) * \brief Computes all the other asteroids each asteroid in the map can "see" * with its angle, its distance to the reference asteroid and its position. * * \param asteroids List of asteroids to process. * \return Map of asteroid sights. */ SightsMap computeAsteroidSights (std::vector<std::string>& asteroids) { SightsMap sights; std::string tmp; for (auto ast1 : asteroids) { for (auto ast2 : asteroids) { if (ast1 == ast2) continue; // ignore same location // else compute angle and distance, and add asteroid sights[ast1].push_back({ angle(ast1, ast2), dist(ast1, ast2), ast2 }); } } return sights; } /** * \fn SightsMap prepareMap (std::string data) * \brief Reads the given data to prepare the map by computing the sights of * all the asteroids. * * \param data Data to parse into an asteroids map. * \return Map of asteroid sights. */ SightsMap prepareMap (std::string data) { std::vector<std::string> asteroids = parseData(data); return computeAsteroidSights(asteroids); } // [ Computation functions ] // ------------------------- /*------------------------------------------------------------------------------ Part I ------------------------------------------------------------------------------*/ /** * \fn int findBestAsteroid(SightsMap& sights, std::string& station) * \brief Finds the asteroid from which the station would see the greatest * number of asteroids. * * \param sights Sights of the asteroids in the neighborhood. * \param station Reference to the "best" station position (to fill). * \return Number of asteroids visible from the "best" asteroid. */ int findBestAsteroid(SightsMap& sights, std::string& station) { // associate the number of visible asteroids to the asteroid position and // return the best one, i.e. the position that "sees" the most asteroids std::string bestPos; int bestCount = -1, c; std::set<float> differentAngles; for (auto s : sights) { differentAngles.clear(); for (auto i : s.second) { differentAngles.insert(i.angle); } c = differentAngles.size(); if (c > bestCount) { bestPos = s.first; bestCount = c; } } station = bestPos; return bestCount; } /*------------------------------------------------------------------------------ Part II ------------------------------------------------------------------------------*/ /** * \fn void int processLaserVaporization(SightsMap& sights, std::string station) * \brief Computes the whole laser vaporization process given some coordinates * have been picked for the monitoring station. * * \param sights Sights of the asteroids in the neighborhood. * \param station Coordinates of the monitoring station (as an "x,y" string). */ int processLaserVaporization(SightsMap& sights, std::string station) { // get station sight std::vector<AsteroidInfo> sight = sights[station]; // sort the sights per angle, then per distance std::sort(sight.begin(), sight.end()); // roll the laser until 200 asteroids have been destroyed float lastAngle = -1.0; int idx, x, y; float a, d; for (int i = 0; i < 200; i++) { idx = 0; a = sight[idx].angle; while (a <= lastAngle && idx < sight.size()) { a = sight[idx].angle; if (a <= lastAngle) { idx++; } } a = sight[idx].angle; d = sight[idx].distance; decomposeCoordinates(sight[idx].pos, x, y); lastAngle = fmod(a, 2.0 * M_PI); } // compute the checksum for the position of the 200th destroyed asteroid return x * 100 + y; } // [ Base tests ] // -------------- /** * \fn void makeTests() * \brief Performs tests on the provided examples to check the result of the * computation functions is ok. */ void makeTests() { // Part I std::string station; SightsMap sights1 = prepareMap(".#..#\n.....\n#####\n....#\n...##"); assert(findBestAsteroid(sights1, station) == 8); SightsMap sights2 = prepareMap("......#.#.\n#..#.#....\n..#######.\n.#.#.###..\n.#..#.....\n..#....#.#\n#..#....#.\n.##.#..###\n##...#..#.\n.#....####"); assert(findBestAsteroid(sights2, station) == 33); SightsMap sights3 = prepareMap("#.#...#.#.\n.###....#.\n.#....#...\n##.#.#.#.#\n....#.#.#.\n.##..###.#\n..#...##..\n..##....##\n......#...\n.####.###."); assert(findBestAsteroid(sights3, station) == 35); SightsMap sights4 = prepareMap(".#..#..###\n####.###.#\n....###.#.\n..###.##.#\n##.##.#.#.\n....###..#\n..#.#..#.#\n#..#.#.###\n.##...##.#\n.....#.#.."); assert(findBestAsteroid(sights4, station) == 41); SightsMap sights5 = prepareMap(".#..##.###...#######\n##.############..##.\n.#.######.########.#\n.###.#######.####.#.\n#####.##.#.##.###.##\n..#####..#.#########\n####################\n#.####....###.#.#.##\n##.#################\n#####.##.###..####..\n..######..##.#######\n####.##.####...##..#\n.#####..#.######.###\n##...#.##########...\n#.##########.#######\n.####.#.###.###.#.##\n....##.##.###..#####\n.#.#.###########.###\n#.#.#.#####.####.###\n###.##.####.##.#..##"); assert(findBestAsteroid(sights5, station) == 210); // Part II assert(processLaserVaporization(sights5, station) == 802); } int main(int argc, char const *argv[]) { // check function results on example cases makeTests(); // get input data std::string dataPath = "../data/day10.txt"; std::string data = readFile(dataPath); SightsMap sights = prepareMap(data); std::string station; // Part I int solution1 = findBestAsteroid(sights, station); std::cout << "PART I: solution = " << solution1 << '\n'; // Part II int solution2 = processLaserVaporization(sights, station); std::cout << "PART II: solution = " << solution2 << '\n'; return 0; }
true
c95250e4236f1a991226d7dd96a01ef241a70cc2
C++
hpuxiaoqiang/coding
/DataStrcture/数据结构书中算法的实现/BasicOperate/ListQueue.cpp
GB18030
1,077
3.296875
3
[]
no_license
#include <iostream> #include <cstdio> #define OK 1 #define ERROR 0 typedef int ElemType; using namespace std; typedef struct QNode{ struct QNode *next; ElemType data; }QNode,*QueuePtr; typedef struct{ QueuePtr front; QueuePtr rear; }LinkQueue; //һյ int InitQueue(LinkQueue &Q){ Q.front = Q.rear = new QNode; Q.front->next = NULL; return OK; } int EnQueue(LinkQueue &Q,ElemType e){ QueuePtr p; p = new QNode; p->data = e; p->next = NULL; Q.rear->next = p; Q.rear = p; return OK; } int DeQueue(LinkQueue &Q,ElemType &e) { QueuePtr p; if(Q.front == Q.rear) return ERROR; p = Q.front->next;//pָͷԪأͷԪصĵַ e = Q.front->next->data;//ͷԪصֵ Q.front->next = p->next; if(Q.rear == p) Q.front = Q.rear;//һԪرɾβָָͷڵ㣬Ϊ //if(Q.front->next==NULL) Q.rear = Q.front;//ͷڵnextΪ delete p; return OK; } int GetHead(LinkQueue Q){ if(Q.front!=Q.rear) return Q.front->next->data; } int main(){ return 0; }
true
19ccd04fa22a677c2a80ac8e45e3d6f3ad88a6cc
C++
edwinsolisf/my_game_engine
/src/Vector.cpp
UTF-8
396
2.984375
3
[]
no_license
#include "Vector.h" namespace gmath { Vector<3>::Vector(const Vector<2>& other, const float& _z) { x = other.x; y = other.y; z = _z; } Vector<4>::Vector(const Vector<3>& other, const float& _w) { x = other.x; y = other.y; z = other.z; w = _w; } Vector<2> Vector<3>::ToVec2() const { return { x,y }; } Vector<3> Vector<4>::ToVec3() const { return { x, y, z }; } }
true
ca7b06a23731fd1a672613fb45487207327a1be1
C++
alexandraback/datacollection
/solutions_2692487_0/C++/sebii/motes.cpp
UTF-8
888
2.890625
3
[]
no_license
#include <algorithm> #include <iostream> #include <set> #include <vector> using namespace std; int solve(vector<int> motes, int A, int N) { int j = 0; while (j < N && motes[j] < A) { A += motes[j]; ++j; } int ans = N - j; if (A - 1 == 0) return ans; int ans2 = 0; while (j < N) { A += A - 1; ++ans2; while (j < N && motes[j] < A) { A += motes[j]; ++j; } ans = min(ans, ans2 + N - j); } return ans; } int main() { int T; cin >> T; int id = 1; while (T--) { int A, N; cin >> A >> N; vector<int> motes(N); for (int i = 0; i < N; ++i) cin >> motes[i]; sort(begin(motes), end(motes)); cout << "Case #" << id << ": " << solve(motes, A, N) << "\n"; ++id; } return 0; }
true
d083da31c52ec53a178cfc8ef7b521bc8cc1459c
C++
ar1kumar/rudeSalad
/moisture_sensor.ino
UTF-8
719
2.640625
3
[]
no_license
#include <LiquidCrystal.h> int Contrast=100; LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); analogWrite(6,Contrast); lcd.begin(16, 2); } void lcdMessage(String input, String input2){ lcd.clear(); lcd.setCursor(0, 0); lcd.print(input); if(input2){ delay(1000); lcd.clear(); lcd.setCursor(0, 0); lcd.print(input2); } } void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); Serial.println(sensorValue); delay(1000); if(sensorValue < 600){ lcdMessage("Thanks assface", "gtfo now"); }else{ lcdMessage("Feed me you scum", "I am hungry"); } }
true
dd1796c05cb31078a25189b1d960755c345d4ee9
C++
kocubinski/torque_sockets
/core/formatted_string_buffer.h
UTF-8
2,423
2.890625
3
[ "MIT" ]
permissive
// Copyright GarageGames. See /license/info.txt in this distribution for licensing terms. class formatted_string_buffer { public: formatted_string_buffer() { _dynamic_buffer = 0; _len = 0; } formatted_string_buffer(const char8 *fmt, ...) { va_list args; va_start(args, fmt); _dynamic_buffer = 0; format(fmt, args); } formatted_string_buffer(const char8 *fmt, void *args) { _dynamic_buffer = 0; format(fmt, args); } ~formatted_string_buffer() { memory_deallocate(_dynamic_buffer); } int32 format( const char8 *fmt, ... ) { va_list args; va_start(args, fmt); _dynamic_buffer = 0; return format(fmt, args); } int32 format(const char8 *fmt, va_list args) { if(_dynamic_buffer) { memory_deallocate(_dynamic_buffer); _dynamic_buffer = 0; } _len = vsnprintf(_fixed_buffer, sizeof(_fixed_buffer), fmt, args); if(_len < sizeof(_fixed_buffer)) return _len; _dynamic_size = sizeof(_fixed_buffer); for(;;) { _dynamic_size *= 2; _dynamic_buffer = (char8 *) memory_reallocate(_dynamic_buffer, _dynamic_size, false); _len = vsnprintf(_dynamic_buffer, _dynamic_size, fmt, args); if(_len < _dynamic_size) { // trim off the remainder of the allocation memory_reallocate(_dynamic_buffer, _len + 1, true); return _len; } } } bool copy(char8 *buffer, uint32 buffer_size) { assert(buffer_size > 0); if(buffer_size >= size()) { memcpy(buffer, c_str(), size()); return true; } else { memcpy(buffer, c_str(), buffer_size - 1); buffer[buffer_size - 1] = 0; return false; } } uint32 length() { return _len; }; uint32 size() { return _len + 1; }; const char8* c_str() { return _dynamic_buffer ? _dynamic_buffer : _fixed_buffer; } static int32 format_buffer(char8 *buffer, uint32 buffer_size, const char8 *fmt, ...) { va_list args; va_start(args, fmt); return format_buffer(buffer, buffer_size, fmt, args); } static int32 format_buffer(char8 *buffer, uint32 buffer_size, const char8 *fmt, va_list args) { assert(buffer_size > 0); int32 len = vsnprintf(buffer, buffer_size, fmt, args); buffer[buffer_size - 1] = 0; return len; } private: char8 _fixed_buffer[2048]; // Fixed size buffer char8* _dynamic_buffer; // Format buffer for strings longer than _fixed_buffer uint32 _dynamic_size; // Size of dynamic buffer uint32 _len; // Length of the formatted string };
true
e378d81b74a462bb9d162d0fef3159afb77db118
C++
apoorv-kulkarni/leetcode
/missingNumber.cpp
UTF-8
594
3.546875
4
[ "MIT" ]
permissive
// Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. // Example 1: // Input: [3,0,1] // Output: 2 // Example 2: // Input: [9,6,4,2,3,5,7,0,1] // Output: 8 // Note: // Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? #include <iostream> #include <vector> using namespace std; class Solution { public: int missingNumber(vector<int>& nums) { int miss = 0, i = 0; for (int num : nums) miss += ++i - num; return miss; } };
true
94b2b82d9098f390bd2f6a563f9619789de2b83b
C++
eriser/AudioLab
/AudioSynth/AudioSynth/FIFO.h
UTF-8
1,659
3.109375
3
[ "CC0-1.0" ]
permissive
// // FIFO.h // Synth_Osc2 // // Created by Ness on 8/20/15. // Copyright (c) 2015 Ness. All rights reserved. // #ifndef __Synth_Osc2__FIFO__ #define __Synth_Osc2__FIFO__ #include <stdio.h> class FIFO; class Node{ friend class FIFO; public: Node(float val):data(val),next(NULL){}; ~Node(){}; private: float data; Node* next; }; class FIFO{ public: FIFO():first(NULL),last(NULL),size(0){}; ~FIFO(); inline void enqueue(float val){ Node* newNode= new Node(val); if (isEmpty()) { first=last=newNode; }else{ last->next=newNode; last=newNode; } ++size; } inline float dequeue(){ float output; if (!isEmpty()) { Node *temp= first; output=first->data; if (first==last) { first=last=0; }else{ first=first->next; } --size; delete temp; }else{ printf("queue is empty\n"); output=0.0; } return output; } inline bool isEmpty(){return first==NULL;}; // void printFIFO(){ // if (!isEmpty()) { // Node* curr=first; // while (curr!=NULL) { // printf("%f -> ",curr->data); // curr=curr->next; // } // }else{ // printf("Queue is Empty"); // } // printf("\n"); // } private: Node *first; Node *last; public: int size; }; #endif /* defined(__Synth_Osc2__FIFO__) */
true
ddebd018196ce021e14f331f09ce7565886ba404
C++
RJ-Mitra/Programming101_CPP
/findLeastSubArrToSortFullArray.cpp
UTF-8
1,450
4.09375
4
[]
no_license
/*Given a list of numbers, find smallest the sub-array, which if sorted, will lead to the entire list getting sorted. Return length of the sub-array Approach 1: Sort the list and compare both lists. The part which is not matching is the required sub-array that needs to be sorted. Approach 2: (below) Find the least number which is in unsorted position from the left as well as the max number which is in unsorted position from the right. Then find and substract their original positions in the array from left and right and find the index difference between those two. */ #include <bits/stdc++.h> using namespace std; int getLenUnsortedPart(vector<int> vec){ int min_elm = 1000; int max_elm = -1000; //Finding the least unsorted element from left side for(int i=1;i<vec.size();++i){ if(vec[i]<vec[i-1]){ min_elm = min(min_elm,vec[i]); } } //Finding the max unsorted element from right side for(int i=vec.size()-2;i>=0;--i){ if(vec[i]>vec[i+1]){ max_elm = max(max_elm, vec[i]); } } int l=0, r=vec.size()-1; while(l<vec.size()){ if(vec[l] > min_elm) break; ++l; } while(r>=0){ if(vec[r] < max_elm) break; --r; } if(r-l<0) return 0; return r-l+1; } int main(){ vector<int> vec = {-1,2,6,4,8,10,9,14,15}; int res = getLenUnsortedPart(vec); cout<<"Length of unsorted part: "<<res<<endl; }
true
6a8d47589ad60b396a4990e663c0fbc6dce5169d
C++
Tomev/kMedoidsAlgorithm
/groupingAlgorithm/cluster.cpp
UTF-8
12,612
2.640625
3
[]
no_license
#include <clocale> #include <iostream> #include <math.h> #include <QDebug> #include "cluster.h" double cluster::_deactualizationParameter = 0.999; cluster::cluster(){} cluster::cluster(long index) : index(index) {} cluster::cluster(std::shared_ptr<sample> object, bool isMedoid) : object(object) { findRepresentative(); if(!isMedoid) this->setWeight(1); if(isMedoid) timestamp = -1; } cluster::cluster(long index, std::shared_ptr<sample> object, bool isMedoid) : index(index), object(object) { findRepresentative(); if(!isMedoid) this->setWeight(1); if(isMedoid) timestamp = -1; } bool cluster::representsObject() { //return subclusters.size() > 2; return object != nullptr; } std::string cluster::getClustersId() { std::string id; if(this->representsObject()) id = "O"; // For "object" else id = "C"; // For "cluster" id += std::to_string(index); return id; } bool cluster::hasSubcluster(std::shared_ptr<cluster> c) { for(std::shared_ptr<cluster> subcluster : subclusters) { if(c.get()->getClustersId() == subcluster.get()->getClustersId()) return true; if(subcluster.get()->hasSubcluster(c)) return true; } return false; } std::shared_ptr<sample> cluster::getObject() { if(representsObject()) return object; //if(representsObject()) return object.get(); else std::cout << "Cluster doesn't represent an object. Returning nullptr.\n"; return nullptr; } void cluster::getObjects(std::vector<std::shared_ptr<sample>>* target) { if(target == nullptr) { std::cout << "Target is a null pointer. Cannot return clusters objects.\n"; return; } if(this->representsObject()) // Check if cluster is singular object { target->push_back(this->getObject()); } else if(subclusters.size() > 0) // If it has subcluster get it's subclusters objects { for(std::shared_ptr<cluster> c : subclusters) c.get()->getObjects(target); } } void cluster::getSubclusters(std::vector<std::shared_ptr<cluster> > *target) { target->clear(); for(std::shared_ptr<cluster> c : subclusters) target->push_back(c); } void cluster::addSubcluster(std::shared_ptr<cluster> subcluster) { subclusters.push_back(subcluster); } long cluster::size() { if(subclusters.size() != 0) return subclusters.size(); if(representsObject() && weight != 0) return 1; return 0; } /** * @brief cluster::dimension * @return Dimension of the cluster. */ long cluster::dimension() { return representative->attributesValues.size(); } void cluster::setWeight(double weight) { this->weight = weight; } void cluster::setCWeight(double weight) { _computationWeight = weight; } double cluster::getWeight() { if(subclusters.size() == 0) return weight; double w = 0; for(std::shared_ptr<cluster> c : subclusters) w += c->getWeight(); return w; } double cluster::getCWeight() { return _computationWeight; } double cluster::getSquaredWeight() { if(subclusters.size() == 0) return weight * weight; double w = 0; for(std::shared_ptr<cluster> c : subclusters) w += pow(c->getWeight(), 2); return w; } cluster* cluster::getMedoid() { if(representsObject()) return this; //return this->medoid; return this->medoid.get(); } void cluster::setMedoid(std::shared_ptr<cluster> newMedoid) { medoid = newMedoid; //this->medoid = newMedoid; } std::shared_ptr<sample> cluster::getMean() { if(mean.get() == nullptr) findMean(); return mean; } void cluster::setMean(std::shared_ptr<sample> newMean) { mean = newMean; } std::unordered_map<std::string, double> cluster::getVariation() { if(subclusters.size() == 0) return variation; if(variation.size() == 0) findVariation(); return variation; } void cluster::setVariantion(std::unordered_map<std::string, double> variantion) { variation = variantion; } void cluster::setRepresentative(sample *newRepresentative) { representative = newRepresentative; } void cluster::findRepresentative() { if(representsObject()) representative = object.get(); } sample *cluster::getRepresentative() { findMean(); return mean.get(); //return representative; } void cluster::setTimestamp(double timestamp) { this->timestamp = timestamp; } double cluster::getTimestamp() { double ts = 0; if(subclusters.size() == 0) ts = timestamp; else if(subclusters.size() == 1){ return subclusters[0]->getTimestamp(); } else { for(auto c : subclusters){ ts += c->getTimestamp() * c->getWeight(); } ts /= getWeight(); } return ts; } void cluster::updatePrediction() { ++_j; //updateFinitePrediction(); updateInfinitePrediction(); updateLastPrediction(); } void cluster::updateFinitePrediction() { updateFinitePredictionMatrices(); updateFinitePredictionParameters(); } void cluster::updateInfinitePrediction() { updateInfinitePredictionMatrices(); updateInfinitePredictionParameters(); } void cluster::updateFinitePredictionMatrices() { int j = _j - 1; if(j == 0){ // Initialization _matrixDj = {{1, 0}, {0, 0}}; // Finite case _djVector = {_currentKDEValue, 0}; } else { // Update double deactualizationCoefficient = pow(_deactualizationParameter, j); _matrixDj[0][0] += deactualizationCoefficient; _matrixDj[0][1] += -j * deactualizationCoefficient; _matrixDj[1][0] += -j * deactualizationCoefficient; _matrixDj[1][1] += j * j * deactualizationCoefficient; _djVector[1] = _deactualizationParameter * (_djVector[1] - _djVector[0]); _djVector[0] = _deactualizationParameter * _djVector[0] + _currentKDEValue; } } void cluster::updateFinitePredictionParameters() { if(_j == 1){ // Initialization predictionParameters = {_currentKDEValue, 0}; } else { // Update double denominator = _matrixDj[0][0] * _matrixDj[1][1] - _matrixDj[1][0] * _matrixDj[0][1]; predictionParameters[0] = (_matrixDj[1][1] * _djVector[0] - _matrixDj[0][1] * _djVector[1]) / denominator; predictionParameters[1] = (_matrixDj[0][0] * _djVector[1] - _matrixDj[1][0] * _djVector[0]) / denominator; } } void cluster::updateLastPrediction() { _lastPrediction = predictionParameters[0]; _lastPrediction += predictionParameters[1] * _predictionsSteps; } double cluster::getLastPrediction() { if(representsObject() || index == -1) return _lastPrediction; double averageLastPrediction = 0; for(auto c : subclusters) averageLastPrediction += c->_lastPrediction * c->weight; double w = getWeight(); if(w > 0) averageLastPrediction /= w; return averageLastPrediction; } double cluster::getDeactualizationParameter() { if(representsObject()) return _deactualizationParameter; double averageDeactualizationParameter = 0; for(auto c : subclusters) averageDeactualizationParameter += c->_deactualizationParameter * c->weight; double w = getWeight(); if(w > 0) averageDeactualizationParameter /= w; return averageDeactualizationParameter; } std::vector<double> cluster::getPredictionParameters() { if(subclusters.size() == 0) return predictionParameters; double upperValue = 0; double lowerValue = 0; for(auto c : subclusters) { if(c->predictionParameters.size() == 0) continue; upperValue += c->predictionParameters[0] * c->weight; lowerValue += c->predictionParameters[1] * c->weight; } double w = getWeight(); if(w > 0){ upperValue /= w; lowerValue /= w; } return std::vector<double>({upperValue, lowerValue}); } std::vector<double> cluster::getDjVector() { if(subclusters.size() == 0) return _djVector; double upperValue = 0; double lowerValue = 0; for(auto c : subclusters) { upperValue += c->_djVector[0] * c->weight; lowerValue += c->_djVector[1] * c->weight; } double w = getWeight(); if(w > 0){ upperValue /= w; lowerValue /= w; } return std::vector<double>({upperValue, lowerValue}); } std::vector<std::vector<double> > cluster::getDjMatrix() { if(subclusters.size() == 0){ return _matrixDj; } std::vector<std::vector<double>> matrix = {{0, 0}, {0,0}}; double clusterWeight = getWeight(); for(auto c : subclusters){ for(int i = 0; i < 2; ++i){ for(int j = 0; j < 2; ++j){ matrix[i][j] += c->_matrixDj[i][j] * c->getWeight() / clusterWeight; } } } return matrix; } int cluster::getPrognosisJ() { if(subclusters.size() == 0) return _j; double j = 0; for(auto c : subclusters) j += c->_j * c->weight; j /= getWeight(); return (int) j; } void cluster::findMean() { if(this->representsObject()) mean = object; else findMeanFromSubclusters(); } void cluster::findMeanFromSubclusters() { double currentClusterWeight = 0; std::shared_ptr<sample> currentObject; std::unordered_map<std::string, double> numericAttributesData; std::unordered_map<std::string, std::unordered_map<std::string, double>> symbolicAttributesData; for(std::shared_ptr<cluster> sc : subclusters) { currentObject = sc->getObject(); currentClusterWeight = sc->getWeight(); // First initialize structures if they're not initialized if(numericAttributesData.size() + symbolicAttributesData.size() == 0) { for(auto kv : currentObject->attributesValues) { if((*(currentObject->attributesData))[kv.first]->getType() == "symbolic") symbolicAttributesData[kv.first][kv.second] = 0.0f; else numericAttributesData[kv.first] = 0.0f; } } // Being sure, that I now have data initialized to 0 I begin finding mean values for(auto kv : currentObject->attributesValues) { if((*(currentObject->attributesData))[kv.first]->getType() == "symbolic") symbolicAttributesData[kv.first][kv.second] = symbolicAttributesData[kv.first][kv.second] + currentClusterWeight; else numericAttributesData[kv.first] = numericAttributesData[kv.first] + currentClusterWeight * std::stod(kv.second); } } mean = std::shared_ptr<sample>(new sample()); mean->attributesData = subclusters[0]->getObject()->attributesData; double w = getWeight(); if(w > 0) for(auto kv : numericAttributesData) mean->attributesValues[kv.first] = std::to_string(kv.second / w); std::pair<std::string, double> symbolicAttributeValWeight; for(auto kv : symbolicAttributesData) { symbolicAttributeValWeight.second = 0; for(auto av : kv.second) { if(symbolicAttributeValWeight.second < av.second) { symbolicAttributeValWeight.second = av.second; symbolicAttributeValWeight.first = av.first; } } mean->attributesValues[kv.first] = symbolicAttributeValWeight.first; } } void cluster::findVariation() { if(mean.get() == nullptr) findMean(); variation.clear(); double w = getWeight(); double summaricSquaredWeight = getSquaredWeight(); double varCoefficient = w; varCoefficient /= (pow(w, 2) - summaricSquaredWeight); double updatedVariationValue = 0; // Initialize variation for(auto kv : mean->attributesValues) variation[kv.first] = 0; for(std::shared_ptr<cluster> sc : subclusters) { for(auto kv : sc->getObject()->attributesValues) { if((*(mean->attributesData))[kv.first]->getType() == "numerical") { updatedVariationValue = std::stod(kv.second); updatedVariationValue -= std::stod(mean->attributesValues[kv.first]); updatedVariationValue = pow(updatedVariationValue, 2); updatedVariationValue *= sc->getWeight(); updatedVariationValue += variation[kv.first]; variation[kv.first] = updatedVariationValue; } } } for(auto kv : variation) kv.second *= varCoefficient; } void cluster::updateInfinitePredictionMatrices() { int j = _j - 1; if(j == 0){ // Initialization _djVector = {_currentKDEValue, 0}; } else { // Update _djVector[1] = _deactualizationParameter * (_djVector[1] - _djVector[0]); _djVector[0] = _deactualizationParameter * _djVector[0] + _currentKDEValue; } } void cluster::updateInfinitePredictionParameters() { int j = _j - 1; if(j == 0){ predictionParameters = {_currentKDEValue, 0}; } else { double predictionDifference = _currentKDEValue - _lastPrediction; predictionParameters[0] += predictionParameters[1]; predictionParameters[0] += (1 - pow(_deactualizationParameter, 2)) * predictionDifference; predictionParameters[1] += pow(1 - _deactualizationParameter, 2) * predictionDifference; } }
true
e0459763e6857080f5d3446d63ee7635ca40a511
C++
Yappedyen/Helloworld
/13function.cpp
GB18030
2,265
3.984375
4
[]
no_license
#include<iostream> using namespace std; #include "swap.h" int add(int a, int b) //a,bΪβ { int sum; sum = a + b; return sum; } //ֵݣǺʱʵνֵβ //ֵʱβηı䣬Ӱʵ //Ҫֵʱдvoid void swap1(int num1, int num2) { int temp = num1; num1 = num2; num2 = temp; //return; ֵҪԲдreturn } //ʽ //޲޷ void test01() { cout << "޲޷" << endl; } //в޷ void test02(int a) { cout << "в޷" << endl; } //޲з int test03() { cout << "޲з" << endl; return 1; } //вз int test04(int num1) { cout << "вз" << endl; return num1; } // // ߱ƼεúʵԵ // ԶΣǺĶֻһΣ󣬶Ϳдmain()֮ //ȽϺʵֽбȽϣؽϴֵ // int max(int num1, int num2); // int max(int num1, int num2) { return num1 > num2 ? num1 : num2; } //ķļд //ôṹ //1.׺Ϊ.hͷļ //2.׺Ϊ.cppԴļ //3.ͷļд //4.ԴļдĶ //ʵֽ //int swap(int a, int b) //{ // int temp = a; // a = b; // b = temp; // return a, b; //} int main13() { /*ֵ (б) { ; returnʽ }*/ //ʵһӷݣӵĽҷ //﷨ () //abΪʵʲʵ //úʱʵεֵᴫݸβ int sum; int a = 10, b = 4; sum = add(a, b); cout << sum << endl; cout << "a" << a << endl; cout << "b" << b << endl; //int c = 0, d = 0; swap(a, b); //cout << "a" << c << endl; //cout << "b" << d << endl; test01(); test02(a); int num = test03(); cout << num << endl; int num2 = test04(a); cout << num2 << endl; cout << max(a, b) << endl; system("pause"); return 0; }
true