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
5d3651db36c3f941cf3a4aeb0f40fcd61fe87109
C++
Sunspawn/CollegeHomework
/Assignment4/src/Standing.cpp
UTF-8
388
2.59375
3
[]
no_license
/* * Standing.cpp * * Created on: 22 May 2019 * Author: nikolay */ #include "Standing.h" Standing::Standing(std::string name, std::string cName, float weight, float height, float width, int year, std::string style): Painting(name,cName,weight,height,width,year,style) {} Standing::~Standing() {} float Standing::floorArea() const { return Painting::wallArea() / 2; }
true
d3ba422e682a73eab1f7bc5a57ee54427856cd5f
C++
elsys/oop
/materials/2019-2020/consultations/2019-11-28/doctor/surgeon.cc
UTF-8
816
3.09375
3
[]
no_license
#include "surgeon.hh" #include <cstring> Surgeon::Surgeon( std::string name, unsigned int experience, char const* speciality) : Doctor(name, experience), speciality(new char[strlen(speciality) + 1]) { strcpy(this->speciality, speciality); } Surgeon::Surgeon(Surgeon const& other) : Doctor(other), speciality(new char[strlen(other.speciality) + 1]) { strcpy(speciality, other.speciality); } Surgeon& Surgeon::operator=(Surgeon const& other) { if (this == &other) { return *this; } (Doctor)*this = (Doctor const&)other; delete[] speciality; speciality = new char[strlen(other.speciality) + 1]; strcpy(speciality, other.speciality); return *this; } Surgeon::~Surgeon() { delete[] speciality; } char const* Surgeon::get_speciality() const { return speciality; }
true
3da56ba393a98c322d68a3191de78f04dc12879a
C++
siklosid/co-cluster
/src/Similarity/KernelSimilarity.cpp
UTF-8
4,660
2.53125
3
[]
no_license
#include "KernelSimilarity.h" #include <math.h> #include <fstream> #include <utility> using std::pair; KernelSimilarity::~KernelSimilarity() { log_status("Ending Kernel similarity"); delete local_info_; } void KernelSimilarity::Init() { local_info_ = new LocalInfo<KernelItemInfo, KernelClusterInfo, KernelCoClusterInfo>(); local_info_->Init(NULL, // row_item_info NULL, // col_item_info new vector<KernelClusterInfo>(global_info_->GetNumRowClusts()), // row_clust_info NULL, // col_clust_info NULL); // co_cluster_info } void KernelSimilarity::InitIter(bool row_view) { log_dbg("InitIter: %s", row_view?"true":"false"); real_iter_ = false; local_info_->SetRowView(row_view); data_->SetRowView(row_view); tmp_clust_info_ = new vector<KernelClusterInfo>(global_info_->GetNumRowClusts()); } double KernelSimilarity::SimilarityToCluster(const uint32_t &node_id, const uint32_t &clust_id) { log_dbg("Measuring the similarity of node: %u to cluster: %u", node_id, clust_id); uint32_t num_elements = local_info_->GetRowClusterInfo(clust_id).num_elements_; if (num_elements == 0) { //log_warn("Cluster: %u is empty", clust_id); return numeric_limits<double>::infinity(); } uint32_t act_medoid = local_info_->GetRowClusterInfo(clust_id).act_medoid_; return data_->GetItem(node_id, act_medoid);; } double KernelSimilarity::SimilarityToBiCluster(const uint32_t &node_id, const uint32_t &clust_id) { log_dbg("Measuring the similarity of node: %u to cluster: %u", node_id, clust_id); log_assert("Function SimilarityToBiCluster is not implemented in KernelSimilarity"); return 0.0; // Just to avoid warning } double KernelSimilarity::VectorSimilarityToCluster(const vector<double> &data, const uint32_t &clust_id) { log_dbg("Measuring the similarity of vector to cluster: %u", clust_id); uint32_t num_elements = local_info_->GetRowClusterInfo(clust_id).num_elements_; if (num_elements == 0) { log_warn("Cluster: %u is empty", clust_id); return numeric_limits<double>::infinity(); } uint32_t act_medoid = local_info_->GetRowClusterInfo(clust_id).act_medoid_; return data[act_medoid]; } void KernelSimilarity::AddNodeToCluster(const uint32_t &node_id, const uint32_t &cluster_id) { real_iter_ = true; log_dbg("Adding node: %u to cluster: %u", node_id, cluster_id); data_mutex_.Lock(); (*tmp_clust_info_)[cluster_id].num_elements_++; vector<pair<uint32_t, double> >::iterator it = (*tmp_clust_info_)[cluster_id].medoid_vals_.begin(); vector<pair<uint32_t, double> >::iterator it_end = (*tmp_clust_info_)[cluster_id].medoid_vals_.end(); // uint32_t orig_id = (node_id - node_id%8)/8; // If our kernel is not quadratic bool is_medoid_candid = false; double own_sum; if (node_id < data_->GetNumCols()) { is_medoid_candid = true; own_sum = 0.0; } else { own_sum = numeric_limits<double>::max(); } double min_sum = numeric_limits<double>::max(); uint32_t min_id = 0; for (; it != it_end; ++it) { // uint32_t other_orig_id = (it->first - it->first%8)/8; if (it->second != numeric_limits<double>::max()) { it->second += data_->GetItem(node_id, it->first); if (it->second < min_sum) { min_sum = it->second; min_id = it->first; } } if (is_medoid_candid) { own_sum += data_->GetItem(it->first, node_id); } } if (own_sum < min_sum) { min_sum = own_sum; min_id = node_id; } (*tmp_clust_info_)[cluster_id].medoid_vals_.push_back(pair<uint32_t, double>(node_id, own_sum)); (*tmp_clust_info_)[cluster_id].min_medoid_ = min_id; data_mutex_.Unlock(); } void KernelSimilarity::AddVectorToCluster(const vector<double> &avg, const uint32_t &cluster_id) { log_dbg("Adding vector to cluster: %u", cluster_id); log_assert("Function AddVectorToCluster is not implemented in KernelSimilarity"); } void KernelSimilarity::FinishIter() { if (real_iter_) { for (uint32_t clust_id = 0; clust_id < global_info_->GetNumRowClusts(); ++clust_id) { (*tmp_clust_info_)[clust_id].act_medoid_ = (*tmp_clust_info_)[clust_id].min_medoid_; } local_info_->SwapClusterInfo(tmp_clust_info_); //if (do_bicluster_) local_info_->SwapCoClusterInfo(tmp_co_clust_info_); } else { delete tmp_clust_info_; //if (do_bicluster_) delete tmp_co_clust_info_; } } void KernelSimilarity::Finish() {}
true
270eea571f17a2e94d7eb7a631bc4b1927e80f06
C++
ModischFabrications/PC_CTRL
/RF24_Debug_Board/lib/HomeNet/HomeNet.cpp
UTF-8
1,298
2.9375
3
[]
no_license
#include "HomeNet.h" void HomeNet::print_payload(HomeNet::payload &pl){ Serial.println(F("-- Payload is: --")); Serial.print(F("\n From Node: ")); Serial.print(pl.from_node); Serial.print(F("\n To Node: ")); Serial.print(pl.to_node); Serial.print(F("\n category: ")); Serial.print(pl.category); Serial.print(F("\n function: ")); Serial.print(pl.function); Serial.print(F("\n parameter: ")); Serial.print(pl.parameter); Serial.println(F("\n-----------------")); } bool HomeNet::add(uint8_t category, uint8_t function, f_node p_function){ if (counter >= rows_dict) return false; dict[counter][0] = category; dict[counter][1] = function; dict_f[counter] = &p_function; counter++; return true; } void HomeNet::translate(payload &pl){ if (counter == 0) { Serial.println(F("No entries in dictionary")); return; } // find category and function uint8_t index = (uint8_t)-1; for (uint8_t i = 0; i <= counter; i++){ if ((pl.category == dict[i][0]) && (pl.function == dict[i][1])){ index = i; break; // no need to search further } } if (index != (uint8_t) -1){ // access index in function list & call (*dict_f[index])(pl.parameter); } else{ Serial.println(F("Invalid command code")); } }
true
2b130dffa5b8f6da0976078e5265ededfd76a7ba
C++
flytigerw/Computer
/Codes/Pratice/code6.cpp
UTF-8
2,674
3.515625
4
[]
no_license
#include <iostream> #include <unistd.h> #include "myArray.h" using namespace std; bool duplicate(int numbers[],int size,int* dup){ //参数检查 if(numbers == nullptr || size <= 0) return false; for(int i=0;i<size;i++){ if(numbers[i] == i) continue; if(numbers[numbers[i]] == numbers[i]){ *dup = numbers[i]; return true; } swap(numbers[i],numbers[numbers[i]]); } return false; } void duplicate2(int numbers[],int size,int* res){ //用数组建立散列表 for(int i=0;i<size;i++) res[numbers[i]]++; } int countRange(const int numbers[],int size,int beg,int end){ int count = 0; for(int i=0;i<size;i++){ if(numbers[i] >= beg && numbers[i] <= end) ++count; } return count; } //不能改变原数组,也不能进进行 bool duplicate3(const int numbers[],int size,int* dup){ //简单题,进行参数检查 if(numbers == nullptr || size <= 0) return false; int beg = 1; int end = size-1; int mid = 0; int count = 0; while(beg <= end){ mid = (beg+end) / 2; count = countRange(numbers,size,beg,mid); if(beg == mid){ //在右半边找到 if(count <= 1) ++beg; break; } if(count > (mid-beg+1)) end = mid; else beg = mid+1; } *dup = beg; return true; } using t = int (*) [4]; bool FindIn2DArray(t matrix,int rows,int cols,int num){ if(matrix == nullptr || rows<=0 || cols<=0 ) return false; int rx = 0,ry = cols - 1; while(rx <rows && ry >= 0){ if(matrix[rx][ry] == num) return true; if(matrix[rx][ry] > num){ --ry; }else{ ++rx; } } return false; } //字符串的替换 //len 为字符串的最大容量 void replaceBlank(char* str,int len){ if(str == nullptr || len<= 0) return; int blanks = 0; int size = 0; while(str[size++] != 0) if(str[size] == ' ') ++blanks; int newSize = size+2*blanks; if(newSize >= len) return; int p1 = size - 1,p2 = newSize - 1; while(p1 >= 0){ if(str[p1] != ' '){ str[p2--] = str[p1]; }else{ str[p2--] = '0'; str[p2--] = '2'; str[p2--] = '%'; } p1--; } } int main(){ int a[] = {2,3,1,0,2,5,3}; int b[] = {2,3,5,4,3,2,6,7}; int c[4][4] = { {1,2,8,9}, {2,4,9,12}, {4,7,10,13}, {6,8,11,15}, }; int res[7]={0}; int x = 0; duplicate2(a,7,res); for(auto i : res) cout << i << ' '; cout << endl; cout << duplicate(a,7,&x) << "--"<<x << endl; cout << duplicate3(b,8,&x) << "--" << x << endl; cout << FindIn2DArray(c,4,4,10) << endl; }
true
144169f4c586e658f5ed2b36baaa52b9b9b3efa1
C++
ilanit1/matala7
/TicTacToe.cpp
UTF-8
2,938
3.28125
3
[]
no_license
#include "TicTacToe.h" TicTacToe::TicTacToe(int dim) { m_board.init_Board(dim); win=false; turn= true; m_winner= nullptr; } Board TicTacToe::play( Player& p1, Player& p2) { m_board='.'; win=false; p1.setChar('X'); p2.setChar('O'); turn=true; m_winner=&p2; while(!win){ if(isfull()) return m_board; if(turn){ try { vector<int> v; v = p1.play(m_board); if (m_board[v] == p2.myChar) throw std::string("Illegal Player"); m_board[v]='X'; check(v); if(win) { m_winner = &p1; } } catch (...){ m_winner=&p2; win=true; return m_board; } } else{ try { vector<int> v; v = p2.play(m_board); if (m_board[v] == p1.myChar) throw std::string("Illegal Player"); m_board[v]='O'; check(v); if(win){ m_winner=&p2; } } catch (...){ m_winner=&p1; win=true; return m_board; } } } return m_board; } void TicTacToe::check(vector<int> vector1){ char move; switch (turn){ case true: move='X'; break; case false: move='O'; break; } int counter =0; for (int i = 0; i <m_board.size(); i++) { vector <int> v={vector1.at(0),vector1.at(1)}; v.at(0)=i; if(move==m_board[v].get_p())counter++; } if(counter==m_board.size()){ win=true; return; } counter=0; for (int i = 0; i <m_board.size(); i++) { vector <int> v={vector1.at(0),vector1.at(1)}; v.at(1)=i; if(move==m_board[v].get_p())counter++; } if(counter==m_board.size()){ win=true; return; } counter=0; for (int i = 0; i <m_board.size(); i++) { vector <int> v={0,0}; v.at(1)=i; v.at(0)=i; if(move==m_board[v].get_p())counter++; } if(counter==m_board.size()){ win=true; return; } counter=0; for (int i = 0; i <m_board.size(); i++) { vector <int> v={0,0}; v.at(1)=m_board.size()-1-i; v.at(0)=i; if(move==m_board[v].get_p())counter++; } if(counter==m_board.size()){ win=true; return; } turn=!turn; } bool TicTacToe::isfull() const{ for (int i = 0; i <m_board.size() ; ++i) { for (int j = 0; j <m_board.size() ; ++j) { if(m_board[{i,j}].get_p()=='.')return false; } } return true; }
true
1823d6a1c575cf90399f12d0562b0e624196b939
C++
Meem0/cs488
/A5/Collider.cpp
UTF-8
1,273
2.875
3
[]
no_license
#include "Collider.h" #include "cs488-framework/OpenGLImport.hpp" #include "Utility.hpp" using namespace glm; Collider::Collider(glm::vec2 position, float radius) : m_position(position) , m_radius(radius) { } void Collider::debugDraw() const { #if RENDER_DEBUG glColor3f(0, 1.0f, 0); glBegin(GL_LINES); float x = m_position.x; float y = 1000.0f; float z = m_position.y; float r = m_radius; float a = glm::sqrt((r * r) / 2); glVertex3f(x - r, -y, z); glVertex3f(x - r, y, z); glVertex3f(x + r, -y, z); glVertex3f(x + r, y, z); glVertex3f(x, -y, z + r); glVertex3f(x, y, z + r); glVertex3f(x, -y, z + r); glVertex3f(x, y, z + r); glVertex3f(x - a, -y, z - a); glVertex3f(x - a, y, z - a); glVertex3f(x - a, -y, z + a); glVertex3f(x - a, y, z + a); glVertex3f(x + a, -y, z - a); glVertex3f(x + a, y, z - a); glVertex3f(x + a, -y, z + a); glVertex3f(x + a, y, z + a); glEnd(); #endif } bool Collider::collide(glm::vec2 position, float radius) const { float minDistance = radius + m_radius; float distance = Util::distanceSquared(position, m_position); return distance < (minDistance * minDistance); } glm::vec2 Collider::getPosition() const { return m_position; } float Collider::getRadius() const { return m_radius; }
true
6c19534e4fc72dc04a604c8d782ea96b545e20fc
C++
youarefree123/408-DataStructure
/src/2019年/408_2019.cpp
UTF-8
1,907
3.75
4
[ "Apache-2.0" ]
permissive
#include <stdio.h> #include <time.h> #include <stdlib.h> typedef struct node { int data; struct node* next; }NODE; //初始化一个链表,用到了随机数 NODE* init_List(){ NODE* L = (NODE*)malloc(sizeof(NODE));//头节点初始化 NODE* ss = L;//用于操纵的指针 L->next = NULL; srand((unsigned)time(NULL)); int n = 3+rand()%22; for(int i = 0; i < n; i++){ NODE* T = (NODE*)malloc(sizeof(NODE));//头节点初始化 T->data = i+1; //录入数据 T->next = NULL; //初始化结点 ss->next = T; ss = ss->next; //将新结点插入到链表最后 } return L; } void put_List(NODE* L){ NODE* s = L; while(s->next != NULL){ printf("%d ",s->next->data); s = s->next; } printf("\n"); } //核心代码 void change_List(NODE* L){ NODE *p,*q,*r,*s; //四个个用于操作链表的指针; p = q = L; //指向头节点 /* 找到后半部分链表,得到中间结点(中间结点的next就是后半链表的头节点)*/ while(q->next != NULL){ //p指向中间结点,p指向后半链表头结点 p = p->next;//p 走一步 q = q->next; if(q->next != NULL) q = q->next;//q走两步(如果链表长度为单数的话走第一步的时候已经走完了,所以需要判断) } q = p->next;//q指向后半链表头节点 /* 后半部分链表倒置*/ p->next = NULL; while(q != NULL){ r = q->next; q->next = p->next; p->next = q; q = r; } /* 结点交错插入*/ s = L->next; //s指向前半段第一个数据点 q = p->next; //q指向后半段第一个数据点 p->next = NULL; while(q != NULL){ r = q->next; q->next = s->next; s->next = q; s = q->next; q = r; } } int main() { NODE* L; L = init_List();//得到一个初始化的链表 printf("原链表的顺序为:\n"); put_List(L);//输出 printf("转换过后的链表顺序为:\n"); change_List(L); //改变链表顺序 put_List(L);//输出 return 0; }
true
0d8e99dfcae6f1b87282399a6ca81b8c593b945e
C++
mchalek/euler
/solved/p056/p56.cpp
UTF-8
901
3.375
3
[]
no_license
#include<iostream> #include<cstring> using namespace std; int main(void) { int a0; int maxa = 0; int maxb = 0; int maxsum = 0; int digits[200]; int dsum; int carry; int prod; int AMIN = 2; int AMAX = 100; int BMAX = 100; for(int a = AMIN; a <= AMAX; a++) { memset(digits, 0, 200*sizeof(int)); a0 = a; for(int k = 0; k < 3; k++) { digits[k] = a0 % 10; a0 /= 10; } for(int b = 2; b <= BMAX; b++) { carry = 0; for(int l = 0; l < 200; l++) { prod = digits[l]*a + carry; digits[l] = prod % 10; carry = prod / 10; } dsum = 0; for(int j = 0; j < 200; j++) dsum += digits[j]; //cout << a << "^" << b << " => " << dsum << endl; if(dsum > maxsum) { maxsum = dsum; maxa = a; maxb = b; } } } cout << maxa << "^" << maxb << " yields digital sum " << maxsum << endl; }
true
ea9016658f38945fd9685de28ec89323015d7d52
C++
kobe24o/LeetCode
/algorithm/leetcode379.cpp
UTF-8
955
3.34375
3
[]
no_license
class PhoneDirectory { unordered_set<int> unused, used; int tel; public: /** Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ PhoneDirectory(int maxNumbers) { for(int i = 0; i < maxNumbers; ++i) unused.insert(i); } /** Provide a number which is not assigned to anyone. @return - Return an available number. Return -1 if none is available. */ int get() { if(unused.empty()) return -1; tel = *unused.begin(); unused.erase(*unused.begin()); used.insert(tel); return tel; } /** Check if a number is available or not. */ bool check(int number) { return unused.find(number) != unused.end();//没有用过 } /** Recycle or release a number. */ void release(int number) { used.erase(number); unused.insert(number); } };
true
18d74bb344d3a996d3a6287f3b881ccf75921088
C++
20k/color_proposal_implementation
/src/tests/slow_sRGB.hpp
UTF-8
1,743
2.859375
3
[]
no_license
#pragma once #include <color.hpp> struct slow_sRGB_space { static inline constexpr temporary::matrix_3x3 impl_linear_to_XYZ = color::sRGB_parameters::linear_to_XYZ; static inline constexpr temporary::matrix_3x3 impl_XYZ_to_linear = color::sRGB_parameters::XYZ_to_linear; }; struct slow_sRGB_model { float r = 0; float g = 0; float b = 0; constexpr slow_sRGB_model(){} constexpr slow_sRGB_model(float _r, float _g, float _b) { r = _r; g = _g; b = _b; } }; struct slow_linear_sRGBA_color : color::basic_color<slow_sRGB_space, slow_sRGB_model, color::float_alpha> { constexpr slow_linear_sRGBA_color(float _r, float _g, float _b, float _a) { r = _r; g = _g; b = _b; a = _a; } constexpr slow_linear_sRGBA_color(){} }; template<typename A1, typename A2> constexpr inline void color_convert(const color::basic_color<color::XYZ_space, color::XYZ_model, A1>& in, color::basic_color<slow_sRGB_space, slow_sRGB_model, A2>& out) { auto transformed = temporary::multiply(slow_sRGB_space::impl_XYZ_to_linear, temporary::vector_1x3{in.X, in.Y, in.Z}); out.r = transformed.a[0]; out.g = transformed.a[1]; out.b = transformed.a[2]; color::alpha_convert(in, out); } template<typename A1, typename A2> constexpr inline void color_convert(const color::basic_color<slow_sRGB_space, slow_sRGB_model, A1>& in, color::basic_color<color::XYZ_space, color::XYZ_model, A2>& out) { auto transformed = temporary::multiply(slow_sRGB_space::impl_linear_to_XYZ, temporary::vector_1x3{in.r, in.g, in.b}); out.X = transformed.a[0]; out.Y = transformed.a[1]; out.Z = transformed.a[2]; color::alpha_convert(in, out); }
true
db1aac29e0062f11f5fbe0f7a5f00792ceb36702
C++
MaelQuemard/Compilation
/src/foretGenerateur.cpp
UTF-8
5,533
2.96875
3
[]
no_license
#include "foretGenerateur.hpp" foretGenerateur::foretGenerateur() { this->foret["s"] = genA1(); this->foret["n"] = genA2(); this->foret["e"] = genA3(); this->foret["t"] = genA4(); this->foret["f"] = genA6(); } OperationElementaire* foretGenerateur::genA1() { OperationElementaire* n = new Atom("n", 0, NTER); OperationElementaire* fleche = new Atom("->", 0, TER); OperationElementaire* e = new Atom("e", 0, NTER); OperationElementaire* virgule = new Atom(",", 1, TER); OperationElementaire* ptvirgule = new Atom(";", 0, TER); OperationElementaire* conc1 = new Conc(n, fleche); OperationElementaire* conc2 = new Conc(conc1, e); OperationElementaire* conc3 = new Conc(conc2, virgule); OperationElementaire* star = new Star(conc3); OperationElementaire* conc4 = new Conc(star, ptvirgule); return conc4; } OperationElementaire* foretGenerateur::genA2() { OperationElementaire* idnter = new Atom("IDNTER", 2, TER); return idnter; } OperationElementaire* foretGenerateur::genA3() { OperationElementaire* t = new Atom("t",0,NTER); OperationElementaire* plus = new Atom("+",0,TER); OperationElementaire* t2 = new Atom("t", 3, NTER); OperationElementaire* conc1 = new Conc(plus,t2); OperationElementaire* star = new Star(conc1); OperationElementaire* conc2 = new Conc(t, star); return conc2; } OperationElementaire* foretGenerateur::genA4() { OperationElementaire* f = new Atom("f",0,NTER); OperationElementaire* point = new Atom(".",0,TER); OperationElementaire* f2 = new Atom("f", 4, NTER); OperationElementaire* conc1 = new Conc(point, f2); OperationElementaire* star = new Star(conc1); OperationElementaire* conc2 = new Conc(f, star); return conc2; } OperationElementaire* foretGenerateur::genA5() { OperationElementaire* idnter = new Atom("IDNTER", 5, TER); OperationElementaire* elter = new Atom("ELTER",5, TER); OperationElementaire* parOuvre = new Atom("(", 0, TER); OperationElementaire* crochetOuvre = new Atom("[", 0, TER); OperationElementaire* crochetFerme = new Atom("]", 6, TER); OperationElementaire* parFerme = new Atom(")", 0, TER); OperationElementaire* unOuvre = new Atom("(/", 0, TER); OperationElementaire* unFerme = new Atom("/)", 7, TER); OperationElementaire* conc1 = new Conc(parOuvre,idnter); OperationElementaire* conc2 = new Conc(crochetOuvre,idnter); OperationElementaire* conc3 = new Conc(unOuvre,idnter); OperationElementaire* conc4 = new Conc(conc1,parFerme); OperationElementaire* conc5 = new Conc(conc2,crochetFerme); OperationElementaire* conc6 = new Conc(conc3,unFerme); OperationElementaire* union1 = new Union(conc5,conc6); OperationElementaire* union2 = new Union(conc4,union1); OperationElementaire* union3 = new Union(elter,union2); OperationElementaire* union4 = new Union(idnter,union3); //std::cout << union4e->toString(0) << '\n'; return union4; } OperationElementaire* foretGenerateur::genA6() { OperationElementaire* idnter = new Atom("IDNTER", 5, TER); OperationElementaire* elter = new Atom("ELTER",5, TER); OperationElementaire* parOuvre = new Atom("(", 0, TER); OperationElementaire* crochetOuvre = new Atom("[", 0, TER); OperationElementaire* crochetFerme = new Atom("]", 6, TER); OperationElementaire* parFerme = new Atom(")", 0, TER); OperationElementaire* unOuvre = new Atom("(/", 0, TER); OperationElementaire* unFerme = new Atom("/)", 7, TER); OperationElementaire* e = new Atom("e", 0, NTER); /*OperationElementaire* union1 = new Union(idnter, elter); OperationElementaire* conc1 = new Conc(e, parFerme); OperationElementaire*conc2 = new Conc(parOuvre, conc1); OperationElementaire* union2 = new Union(union1, conc2); OperationElementaire* conc3 = new Conc(e, crochetFerme); OperationElementaire* conc4 = new Conc(crochetOuvre, conc3); OperationElementaire* union3 = new Union(union2, conc4); OperationElementaire* conc5 = new Conc(e, unFerme); OperationElementaire* conc6 = new Conc(unOuvre, conc5); OperationElementaire* union4 = new Union(union3, conc6); */ /*OperationElementaire* conc1 = new Conc(unOuvre, e); OperationElementaire* conc2 = new Conc(conc1, unFerme); OperationElementaire* conc3 = new Conc(crochetOuvre, e); OperationElementaire* conc4 = new Conc(conc3, crochetFerme); OperationElementaire* union1 = new Union(conc2, conc4); OperationElementaire* conc5 = new Conc(parOuvre, e); OperationElementaire* conc6 = new Conc(conc5, parFerme); OperationElementaire* union2 = new Union(union1, conc6); OperationElementaire* union3 = new Union(union2, elter); OperationElementaire* union4 = new Union(union3, idnter); */ OperationElementaire* union1 = new Union(idnter, elter); OperationElementaire* conc1 = new Conc(e, parFerme); OperationElementaire* conc2 = new Conc(parOuvre, conc1); OperationElementaire* union2 = new Union(union1, conc2); OperationElementaire* conc3 = new Conc(e, crochetFerme); OperationElementaire* conc4 = new Conc(crochetOuvre, conc3); OperationElementaire* union3 = new Union(union2, conc4); OperationElementaire* conc5 = new Conc(e, unFerme); OperationElementaire* conc6 = new Conc(unOuvre, conc5); OperationElementaire* union4 = new Union(union3, conc6); return union4; } map<string, OperationElementaire*> foretGenerateur::getForet() { return this->foret; }
true
c597e2e28a65821cbc9356c497c7617cadd41940
C++
Laerke91/PCSS-Project
/Server/GameManager.h
UTF-8
1,584
2.953125
3
[]
no_license
#ifndef gameManager_H #define gameManager_H #include "Hero.h" #include "Enums.h" #include "CPU.h" using namespace std; class GameManager { private: bool attacksAreEqual; bool isP1Effective; int dmgBonus = 5; public: Hero player1; CPU player2; //Constructor GameManager(); //Getters, setters bool getAttacksAreEqual(); bool getIsP1Effective(); Hero getPlayer1(); void setPlayer1(Hero newPlayer1); CPU getPlayer2(); void setPlayer2(CPU newPlayer2); int getDmgBonus(); void setDmgBonus(int damage); //Function for starting the game void resolveCombat(); AttackType inputToType(string input); void setUpPlayers(); //Functions used for resolving the game bool checkAttacksAreEqual(); //Checks if the attacks are of the same type, fx. strong and strong string attackEffectiveMessage(); //Returns a message with which attack is effective bool attackIsEffective(AttackType at1, AttackType at2); //Determines which attack is effective against the other according to the weapon triangle void checkAttackEffectiveness(); //Resolved the attack effectiveness if the attack is effective and not equal void calcIncomingDamage(); //Calculates the incoming damage to each player bool isGameConcluded(); //Checks if either player has reached 0 hp bool isGameDraw(); string announceWinnerMsg(); }; #endif // match_H
true
6f88c6597124b4106f5f6738054a0ebd19b194b8
C++
kapil8882001/Coding-Practice-1
/C++ Solutions/Stack & Queue & Heap/LC692_TopKFrequentWords.cpp
UTF-8
2,146
3.5
4
[]
no_license
// Top K Frequent Words /* Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first. Example 1: Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 Output: ["i", "love"] Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order. Example 2: Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 Output: ["the", "is", "sunny", "day"] Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively. Note: You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Input words contain only lowercase letters. Follow up: Try to solve it in O(n log k) time and O(n) extra space. */ //beat 99.87% class Solution { public: typedef pair<int, string> node; struct compare { bool operator()(const node& p1, const node& p2){ if (p1.first == p2.first) { return p1.second < p2.second; } return p1.first > p2.first; } }; vector<string> topKFrequent(vector<string>& words, int k) { vector<string> ans; if (k == 0 || words.empty()) return ans; unordered_map<string, int> count; for (int i = 0; i < words.size(); ++i) { ++count[words[i]]; } priority_queue<node, vector<node>, compare> minHeap; for (auto& pair: count){ //very important if (minHeap.size() == k && pair.second < minHeap.top().first) { continue; } minHeap.push(make_pair(pair.second, pair.first)); if (minHeap.size() > k) { minHeap.pop(); } } while(!minHeap.empty()) { string temp = minHeap.top().second; minHeap.pop(); ans.insert(ans.begin(), temp); } return ans; } };
true
e4e9833f72b5fbca58d06d2e4c7b866cf727230a
C++
pandey7ajay/Covid
/ConsoleApplication1/CovidManagement.cpp
WINDOWS-1250
7,199
3.375
3
[]
no_license
#include<iostream> #include<conio.h> #include<string.h> #include<stdlib.h> using namespace std; // define maximum number of patients in a queue #define MAXPATIENTS 2 // define structure for patient data struct patient { char FirstName[50]; char LastName[50]; char ID[20]; }; // define class for queue class queue { public: queue(void); int AddPatientAtEnd(patient p); int AddPatientAtBeginning(patient p); patient GetNextPatient(void); int RemoveDeadPatient(patient* p); void OutputList(void); char DepartmentName[50]; private : int NumberOfPatients; patient List[MAXPATIENTS]; }; // declare member functions for queue queue::queue() { // constructor NumberOfPatients = 0; } int queue::AddPatientAtEnd(patient p) { // adds a normal patient to the end of the queue. // returns 1 if successful, 0 if queue is full. if (NumberOfPatients >= MAXPATIENTS) { // queue is full return 0; } // put in new patient else List[NumberOfPatients] = p; NumberOfPatients++; return 1; } int queue::AddPatientAtBeginning(patient p) { // adds a critically ill patient to the beginning of the queue. // returns 1 if successful, 0 if queue is full. int i; if (NumberOfPatients >= MAXPATIENTS) { // queue is full return 0; } // move all patients one position back in queue for (i = NumberOfPatients - 1; i >= 0; i--) { List[i + 1] = List[i]; } // put in new patient List[0] = p; NumberOfPatients++; return 1; } patient queue::GetNextPatient(void) { // gets the patient that is first in the queue. // returns patient with no ID if queue is empty int i; patient p; if (NumberOfPatients == 0) { // queue is empty strcpy_s(p.ID, ""); return p; } // get first patient p = List[0]; // move all remaining patients one position forward in queue NumberOfPatients--; for (i = 0; i < NumberOfPatients; i++) { List[i] = List[i + 1]; } // return patient return p; } int queue::RemoveDeadPatient(patient* p) { // removes a patient from queue. // returns 1 if successful, 0 if patient not found int i, j, found = 0; // search for patient for (i = 0; i < NumberOfPatients; i++) { if (_stricmp(List[i].ID, p->ID) == 0) { // patient found in queue *p = List[i]; found = 1; // move all following patients one position forward in queue NumberOfPatients--; for (j = i; j < NumberOfPatients; j++) { List[j] = List[j + 1]; } } } return found; } void queue::OutputList(void) { // lists entire queue on screen int i; if (NumberOfPatients == 0) { cout << "Queue is empty" << endl;; } else { for (i = 0; i < NumberOfPatients; i++) { cout << " " << List[i].FirstName; cout << " " << List[i].LastName; cout << endl; cout << " " << List[i].ID; cout << endl; } } } // declare functions used by main: patient InputPatient(void) { // this function asks user for patient data. patient p; cout << "Please enter data for new patient\nFirst name : "; cin.getline(p.FirstName, sizeof(p.FirstName)); cout << "\nLast name : "; cin.getline(p.LastName, sizeof(p.LastName)); cout << "\nPatientID : "; cin.getline(p.ID, sizeof(p.ID)); // check if data valid if (p.FirstName[0] == 0 || p.LastName[0] == 0 || p.ID[0] == 0) { // rejected strcpy_s(p.ID, ""); cout << "Error : Data not valid.Operation cancelled." << endl;; _getch(); } return p; } void OutputPatient(patient* p) { // this function outputs patient data to the screen if (p == NULL || p->ID[0] == 0) { cout << "No patient" << endl;; return; } else cout << "Patient data : " << endl;; cout << "First name : " << p->FirstName << endl;; cout << "Last name : " << p->LastName << endl;; cout << "PatientID : " << p->ID << endl;; } int ReadNumber() { // this function reads an integer number from the keyboard. // it is used because input with cin >> doesnt work properly! char buffer[20]; cin.getline(buffer, sizeof(buffer)); return atoi(buffer); } void DepartmentMenu(queue* q) { // this function defines the user interface with menu for one department int choice = 0, success; patient p; while (choice != 6) { // clear screen system("CLS"); // print menu cout << "Welcome to department : " << q->DepartmentName <<endl; cout << "Please enter your choice : " << endl; cout << "1: Add normal patient" << endl; cout << "2: Add critically ill patient" << endl; cout << "3: Take out patient for operation" << endl; cout << "4: Remove dead patient from queue" << endl; cout << "5: List queue" << endl; cout << "6: Change department or exit" << endl; // get user choice choice = ReadNumber(); // do indicated action switch (choice) { case 1: // Add normal patient p = InputPatient(); if (p.ID[0]) { success = q->AddPatientAtEnd(p); system("CLS"); if (success) { cout << "Patient added :" << endl;; } else { // error cout << "Error : The queue is full.Cannot add patient : " << endl;; } OutputPatient(&p); cout << "Press any key" << endl;; _getch(); } break; case 2: // Add critically ill patient p = InputPatient(); if (p.ID[0]) { success = q->AddPatientAtBeginning(p); system("CLS"); if (success) { cout << "Patient added :" << endl;; } else { // error cout << "Error : The queue is full.Cannot add patient : " << endl;; } OutputPatient(&p); cout << "Press any key" << endl;; _getch(); } break; case 3: // Take out patient for operation p = q->GetNextPatient(); system("CLS"); if (p.ID[0]) { cout << "Patient to operate :" << endl;; OutputPatient(&p); } else { cout << "There is no patient to operate." << endl;; } cout << "Press any key" << endl;; _getch(); break; case 4: // Remove dead patient from queue p = InputPatient(); if (p.ID[0]) { success = q->RemoveDeadPatient(&p); system("CLS"); if (success) { cout << "Patient removed :" << endl;; } else { // error cout << "Error : Cannot find patient :" << endl;; } OutputPatient(&p); cout << "Press any key" << endl;; _getch(); } break; case 5: // List queue system("CLS"); q->OutputList(); cout << "Press any key" << endl;; _getch(); break; } } } // main function defining queues and main menu void main() { int i, MenuChoice = 0; // define three queues queue departments[2]; // set department names strcpy_s(departments[0].DepartmentName, "Non covid Ward"); strcpy_s(departments[1].DepartmentName, "Covid Ward"); while (MenuChoice != 4) { // clear screen system("CLS"); // print menu cout << "Manage Your Patients\n"; cout << "Please enter your choice :\n"; for (i = 0; i < 2; i++) { // write menu item for department i cout << " " << (i + 1) << ": " << departments[i].DepartmentName<<endl; } cout << " 3: Exit"<<endl; // get user choice MenuChoice = ReadNumber(); // is it a department name? if (MenuChoice >= 1 && MenuChoice <= 2) { // call submenu for department // (using pointer arithmetics here:) DepartmentMenu(departments + (MenuChoice - 1)); } else if (MenuChoice == 3) exit(0); } }
true
8c61a0ff0e9276b2bc9d20ac858af34f84b0cb18
C++
yusuke-matsunaga/ym-cell
/include/ym/ClibPin.h
UTF-8
5,238
2.640625
3
[]
no_license
#ifndef YM_CLIBPIN_H #define YM_CLIBPIN_H /// @file ym/ClibPin.h /// @brief ClibPin のヘッダファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2023 Yusuke Matsunaga /// All rights reserved. #include "ym/ClibHandle.h" #include "ym/logic.h" BEGIN_NAMESPACE_YM_CLIB ////////////////////////////////////////////////////////////////////// /// @ingroup ClibGroup /// @class ClibPin ClibPin.h "ym/ClibPin.h" /// @brief セルのピンを表すクラス ////////////////////////////////////////////////////////////////////// class ClibPin : public ClibHandle { public: /// @brief 空のコンストラクタ /// /// 不正値となる. ClibPin() = default; /// @brief 内容を指定したコンストラクタ ClibPin( const ClibLibraryPtr& library, ///< [in] ライブラリ SizeType id ///< [in] ID番号 ) : ClibHandle{library, id} { } /// @brief デストラクタ ~ClibPin() = default; public: ////////////////////////////////////////////////////////////////////// /// @name 共通属性 /// @{ ////////////////////////////////////////////////////////////////////// /// @brief ピン名を返す. string name() const; /// @brief 方向を返す. ClibDirection direction() const; /// @brief 入力ピンの時に true を返す. /// /// direction() == ClibDirection::input と等価 bool is_input() const; /// @brief 出力ピンの時に true を返す. /// /// direction() == ClibDirection::output と等価 bool is_output() const; /// @brief 入出力ピンの時に true を返す. /// /// direction() == ClibDirection::inout と等価 bool is_inout() const; /// @brief 内部ピンの時に true を返す. /// /// direction() == ClibDirection::internal と等価 bool is_internal() const; /// @brief ピン番号を返す. /// /// このピンを持つセルを cell とすると. /// pin = cell.pin(pin_id); /// pin_id = pin.pin_id() /// が成り立つ. SizeType pin_id() const; ////////////////////////////////////////////////////////////////////// /// @} ////////////////////////////////////////////////////////////////////// public: ////////////////////////////////////////////////////////////////////// /// @name 入力ピンの属性 /// @{ ////////////////////////////////////////////////////////////////////// /// @brief 入力ピン番号を返す. /// /// 入力ピンもしくは入出力ピンの時のみ意味を持つ. /// このピンを持つセルを cell とすると. /// pin = cell.input(iid); /// iid = pin.input_id() /// が成り立つ. SizeType input_id() const; /// @brief 負荷容量を返す. ClibCapacitance capacitance() const; /// @brief 立ち上がり時の負荷容量を返す. ClibCapacitance rise_capacitance() const; /// @brief 立ち下がり時の負荷容量を返す. ClibCapacitance fall_capacitance() const; ////////////////////////////////////////////////////////////////////// /// @} ////////////////////////////////////////////////////////////////////// public: ////////////////////////////////////////////////////////////////////// /// @name 出力ピンの属性 /// @{ ////////////////////////////////////////////////////////////////////// /// @brief 出力ピン番号を返す. /// /// 出力ピンもしくは入出力ピンの時のみ意味を持つ. /// このピンを持つセルを cell とすると. /// pin = cell.output(oid); /// oid = pin.output_id() /// が成り立つ. SizeType output_id() const; /// @brief 最大ファンアウト容量を返す. ClibCapacitance max_fanout() const; /// @brief 最小ファンアウト容量を返す. ClibCapacitance min_fanout() const; /// @brief 最大負荷容量を返す. ClibCapacitance max_capacitance() const; /// @brief 最小負荷容量を返す. ClibCapacitance min_capacitance() const; /// @brief 最大遷移時間を返す. ClibTime max_transition() const; /// @brief 最小遷移時間を返す. ClibTime min_transition() const; /// @brief 論理式を返す. /// /// 定義されていない場合には Expr::is_invalid() == true となる式を返す. Expr function() const; /// @brief tristate 条件式を返す. /// /// 定義されていない場合には Epxr::is_invalid() == true となる式を返す. Expr tristate() const; ////////////////////////////////////////////////////////////////////// /// @} ////////////////////////////////////////////////////////////////////// public: ////////////////////////////////////////////////////////////////////// /// @name 内部ピンの属性 /// @{ ////////////////////////////////////////////////////////////////////// /// @brief 内部ピン番号を返す. /// /// 内部ピンの時のみ意味を持つ. SizeType internal_id() const; ////////////////////////////////////////////////////////////////////// /// @} ////////////////////////////////////////////////////////////////////// }; END_NAMESPACE_YM_CLIB #endif // YM_CLIBCELLPIN_H
true
f8e453e92a3e5721cdd9cb428842fce4b220c5ee
C++
DaftMat/Waters
/src/Minimal-Engine/ShaderPrograms/StaticShader.cpp
UTF-8
2,621
2.796875
3
[]
no_license
// // Created by mathis on 01/06/2020. // #include "StaticShader.hpp" #include <Minimal-Engine/Material/Material.hpp> void StaticShader::setMaterial(const Material &material, const std::string &name) const { /// Textures for (int i = 0; i < material.textures().size(); ++i) { setInt(name + "." + material.textures()[i].name(), i); } /// Int settings for (auto &setting : material.settings<int>()) { setInt(name + "." + setting.name, setting.data); } /// Bool settings for (auto &setting : material.settings<bool>()) { setBool(name + "." + setting.name, setting.data); } /// Float settings for (auto &setting : material.settings<float>()) { setFloat(name + "." + setting.name, setting.data); } /// Vec2 settings for (auto &setting : material.settings<glm::vec2>()) { setVec2(name + "." + setting.name, setting.data); } /// Vec3 settings for (auto &setting : material.settings<glm::vec3>()) { setVec3(name + "." + setting.name, setting.data); } /// Vec4 settings for (auto &setting : material.settings<glm::vec4>()) { setVec4(name + "." + setting.name, setting.data); } /// Mat2 settings for (auto &setting : material.settings<glm::mat2>()) { setMat2(name + "." + setting.name, setting.data); } /// Mat3 settings for (auto &setting : material.settings<glm::mat3>()) { setMat3(name + "." + setting.name, setting.data); } /// Mat4 settings for (auto &setting : material.settings<glm::mat4>()) { setMat4(name + "." + setting.name, setting.data); } } void StaticShader::addLight(const PointLight &light) { std::string index = std::to_string(m_numPointLights++); setVec3("pointLights[" + index + "].position", light.position()); setVec3("pointLights[" + index + "].color", light.color()); setFloat("pointLights[" + index + "].intensity", light.intensity()); setInt("numPointLights", m_numPointLights); } void StaticShader::addLight(const DirectLight &light) { std::string index = std::to_string(m_numDirectLights++); setVec3("directLights[" + index + "].direction", light.direction()); setVec3("directLights[" + index + "].color", light.color()); setInt("numDirectLights", m_numDirectLights); } void StaticShader::clearLights() { m_numPointLights = 0; m_numDirectLights = 0; setInt("numPointLights", m_numPointLights); setInt("numDirectLights", m_numDirectLights); } void StaticShader::setSkybox(const Skybox &skybox) const { setMaterial(skybox.material(), "skybox"); }
true
5c4114a53b5a5ea611016a0b47c64eeac1d8e8a8
C++
Moyuers/Codeup-practise
/1015-Maxtin.cpp
GB18030
759
3.4375
3
[]
no_license
#include <stdio.h> //1015. /*Ŀ 㹹һN*Nľ󣬵ijеԪΪijij˻ij1ʼ ĵһΪһCʾĸ ȻCвÿΪһN1<=N<=9ʾ ÿһ룬ľ 2 1 4 1 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16*/ int main(){ int m,n; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%d",&m); for(int j=1;j<=m;j++){ for(int k=1;k<=m;k++){ printf("%d ",j*k); } printf("\n"); } } return 0; }
true
fe404b28dabc2b5c07621182c583ba4a580ddac2
C++
AxelLavielle/Barde
/Software/Source/MidiManager/AMidiManager.hh
UTF-8
1,393
2.546875
3
[]
no_license
/* ============================================================================== AMidiManager.h Created: 7 Mar 2017 5:25:06pm Author: Anthony ============================================================================== */ #ifndef AMIDIMANAGER_HH_INCLUDED #define AMIDIMANAGER_HH_INCLUDED #include "IMidiManager.hpp" class AMidiManager : public IMidiManager { public: AMidiManager(); virtual ~AMidiManager(); virtual void noteOn(const int channel, const int noteNumber, const float velocity, const double time) noexcept = 0; virtual void noteOn(const Instrument &instument, const int noteNumber, const float velocity, const double time) noexcept = 0; virtual void noteOff(const int channel, const int noteNumber, const float velocity, const double time) noexcept = 0; virtual void noteOff(const Instrument &instrument, const int noteNumber, const float velocity, const double time) noexcept = 0; virtual Midi createMidi(const double time) = 0; virtual void writeToFile(const std::string &filePath) = 0; virtual void setTempo(const unsigned int bpm, const double time = 0) = 0; virtual void changeInstrument(const int channel, const int instrumentNb, const double time) = 0; virtual void changeInstrument(const Instrument &instrument, const double time) = 0; protected: Midi _midi; }; #endif // AMIDIMANAGER_HH_INCLUDED
true
42bebadaa23f073665e73a3b53b44e1b007d8c1f
C++
sinkerdPhoutthavong/Arduino-IoT
/SMDHT22/src/main.cpp
UTF-8
2,551
2.96875
3
[]
no_license
#include <Arduino.h> #include "DHT.h" #include <Adafruit_Sensor.h> #define inDHT 8 // what digital pin we're connected to #define outDHT 9 // Uncomment whatever type you're using! //#define DHTTYPE DHT11 // DHT 11 #define inDHTTYPE DHT22 // DHT 22 (AM2302), AM2321 #define outDHTTYPE DHT22 //#define DHTTYPE DHT21 // DHT 21 (AM2301) // Define status variable to stall the realtime data from inDHT & outDHT float inHumdStatus = .0; float outHumdStatus = .0; float inTempStatus = .0; float outTempStatus = .0; // Connect pin 1 (on the left) of the sensor to +5V // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 // to 3.3V instead of 5V! // Connect pin 2 of the sensor to whatever your DHTPIN is // Connect pin 4 (on the right) of the sensor to GROUND // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor // Initialize DHT sensor. // Note that older versions of this library took an optional third parameter to // tweak the timings for faster processors. This parameter is no longer needed // as the current DHT reading algorithm adjusts itself to work on faster procs. DHT dht1(inDHT, inDHTTYPE); DHT dht2(outDHT, outDHTTYPE); void setup() { Serial.begin(115200); Serial.println("DHTxx test!"); dht1.begin(); dht2.begin(); } void loop() { // Wait a few seconds between measurements. delay(2000); // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) inHumdStatus = dht1.readHumidity(); outHumdStatus = dht2.readHumidity(); // Read temperature as Celsius (the default) inTempStatus = dht1.readTemperature(); outTempStatus = dht2.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true) //float f = dht1.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(inHumdStatus) || isnan(inTempStatus)) { Serial.println("Failed to read from Inside DHT22 sensor!"); return; } if (isnan(outHumdStatus) || isnan(outTempStatus)) { Serial.println("Failed to read from Outside DHT22 sensor!"); return; } Serial.print("Inside Humidity: \t"); Serial.print(inHumdStatus); Serial.print(" %\t\t"); Serial.print("Inside Temperature: \t"); Serial.print(inTempStatus); Serial.println(" *C "); Serial.print("Outside Humidity: \t"); Serial.print(outHumdStatus); Serial.print(" %\t\t"); Serial.print("Outside Temperature: \t"); Serial.print(outTempStatus); Serial.println(" *C "); }
true
13e8608fea217d619ead00a80de177c5a507438f
C++
sighingnow/bad
/include/bad/common.hh
UTF-8
2,609
2.921875
3
[]
no_license
#ifndef BAD_COMMON_HH #define BAD_COMMON_HH #include <algorithm> // std::max #include <cstddef> // std::size_t, std::ptrdiff_t #include <utility> // std::integer_sequence #include "attributes.hh" /// \file /// \brief common definitions, shared across all modules /// /// other modules may extend this functionality, and add more things here, /// but this offers a place for small things that have no good home, or /// which rarely require the full power of their 'proper' home. // /// \author Edward Kmett /// \defgroup common_group common /// \brief common definitions, shared across all modules /// \{ /// \namespace bad /// \brief top level namespace namespace bad { using std::size_t; using std::ptrdiff_t; /// inferrable `std::integral_constant`, used to encode lists as heterogenous lists /// \ingroup common_group template <auto x> using constant = std::integral_constant<decltype(x), x>; /// shorthand for `std::integer_sequence` /// \ingroup common_group template <class T, T... is> using iseq = std::integer_sequence<T, is...>; /// \ref iseq with type inference, so long as there is at least one argument /// \ingroup common_group template <auto... xs> using aseq = iseq<std::common_type_t<decltype(xs)...>, xs...>; /// A \ref iseq "sequence" of `size_t` "sizes". used to store dimensions. a.k.a. `std::index_sequence` /// \ingroup common_group template <size_t... is> using seq = iseq<size_t, is...>; /// A \ref iseq "sequence" of `ptrdiff_t` "signed distances". Used to store strides. /// \ingroup common_group template <ptrdiff_t... is> using sseq = iseq<ptrdiff_t, is...>; /// A compile-time string as a type of \ref iseq "sequence". `char` is an integral type in C++. /// \ingroup common_group template <char...cs> using str = iseq<char, cs...>; #ifdef __clang__ #ifndef ICC // icpc is a lying liar that lies #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu-string-literal-operator-template" #endif #elif defined __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wgnu-string-literal-operator-template" #endif /// allows `decltype("foo"_str)` to return the type `str<'f','o','o'>` /// \ingroup common_group template <class T, T...cs> BAD(hd,const) str<cs...> operator""_str() noexcept { return {}; } #ifdef __clang__ #ifndef ICC #pragma clang diagnostic pop #endif #elif defined __GNUC__ #pragma GCC diagnostic pop #endif /// if-then-else /// \ingroup common_group template <bool B, class T, class E> using ite = std::conditional_t<B,T,E>; } /// \} #endif
true
688f86720f5c76f8234c823e741633f75fa9513d
C++
Koios1143/Algorithm-Code-Saved
/TOJ/toj29.cpp
UTF-8
688
2.8125
3
[]
no_license
#include<iostream> using namespace std; int main() { int t; cin>>t; string s,s2; bool YN=0; for(int i=0,n ; i<t ; i++) { YN=0; cin>>s; cin>>n; for(int j=0,flag=-1 ; j<n ; j++) { cin>>s2; for(int k=0 ; k<s.size() ; k++) { if(s2[0]==s[k]) { flag=k; break; } } if(flag==-1) { cout<<"n"<<endl; } else { for(int l=1 ; l<s2.size() ; l++) { if(s2[l]!=s[flag+l]) { YN=0; break; } else { YN=1; } } } if(YN==1) { cout<<"y"<<endl; } else { cout<<"n"<<endl; } } } return 0 ; }
true
2487f53e2ce95570bfddf5f3dd006cebf762a5cb
C++
sebicarhat/Cplusplus
/Urionlinejudge - projects/Square Matrix III/main.cpp
UTF-8
908
2.59375
3
[]
no_license
#include <iostream> #include<algorithm> using namespace std; int main() { int n,i,j,x,y,a[100][100],aux,k,c,h; cin>>n; while(n!=0) { x=1; k=0; for(i=1;i<=n;++i) //crearea matricei { y=x; for(j=1;j<=n;++j) {a[i][j]=y; y*=2;} x*=2; } aux=a[n][n]; while(aux>0){k++;aux/=10;} //nr de cifre al celui mai mare nr din matrice for(i=1;i<=n;++i) { for(j=1;j<=n;++j) { c=0; aux=a[i][j]; while(aux>0){c++;aux/=10;} //nr de cifre al valorii lui a[i][j] for(h=0;h<k-c;++h)cout<<" "; cout<<a[i][j]; if(j!=n)cout<<" "; } cout<<"\n"; } cout<<"\n"; cin>>n; } return 0; }
true
ece6b6874f27e72f4c0de39b6b8ed8502a57abd5
C++
BlurEffect/SquadAI
/SquadAI/ColliderFactory.h
UTF-8
458
2.625
3
[]
no_license
/* * Kevin Meergans, SquadAI, 2014 * ColliderFactory.h * Class with a static member function serving as factory function * for different types of colliders. */ #ifndef COLLIDER_FACTORY_H #define COLLIDER_FACTORY_H // Includes #include "Collider.h" #include "CircleCollider.h" #include "AxisAlignedRectangleCollider.h" class ColliderFactory { public: static Collider* CreateCollider(ColliderType type, void* pColliderData); }; #endif // COLLIDER_FACTORY_H
true
4801613ddd08a86f5131d3917e8ce850689a57bc
C++
venkycode/OOAD_Project
/admin.h
UTF-8
49,432
3.125
3
[]
no_license
#include <sqlite3.h> #include <chrono> #include <ctime> #include <bits/stdc++.h> #include <unistd.h> #include "checks.h" #include "PasswordGenerator.h" #include "forgotPassword.h" #include "sha256.h" // System state is used to store current count of shopkeepers // delivery persons and Customers and also the current product count and also // the current order count which helps in providing new id's typedef struct systemState { int shopKeeperCount, deliveryPersonCount, CustomerCount; int OrderCount, productCount; } systemState; systemState state; string temporaryID; // also helps in adding transactions. profile temporaryProfile; // helps in editing profile. string add; // helps in adding to the sql transactions. order temporaryOrder; // helps in getting info about order vector<int> tempOrderofCustomer; // helps in retriecing the customer's order from sql. int temporaryOrderID; // used in assigning the order to the delivery person class admin { public: sqlite3 *DB; // sql database pointer. int exit; // exit helps in identifying the error when performing different sql operations. string data; // helps in passing certain operation while performing different sql operations. char *messaggeError; // helps in identifying different sql errors. product *global_inventory_array; // array to load the complete data from data file. map<string, set<int>> global_inven_map; //mapping from product name to product fstream global_inve_file; // pointer for the file which stores the inventory. map<string, set<int>> personal_inventory; // shopkeeper id mapped to vector of productsID owned by him map<int, product> productId_to_product; // map from product id to its contents. admin(){ loadDatabase(); // loads database into local memory as soon as admin is loaded. assignUnassignedOrders(); //assigns uniassigned orders if possible to unassigned delivery personnel on start of code. } // callback helps in displaying the contents of user transaction from sql. static int callback(void *data, int argc, char **argv, char **azColName) { for (int i = 0; i < argc; i++) printf("%s = %s", azColName[i], argv[i] ? argv[i] : "NULL"); return 0; } // get_ID helps in retrieving user ID from user_map sql. static int get_ID(void *data, int argc, char **argv, char **azColName) { temporaryID = argv[0] ? argv[0] : "#"; return 0; } // get_information helps in extracting information from person sql to load locally. static int get_information(void *data, int argc, char **argv, char **azColName) { temporaryProfile.name = argv[1]; temporaryProfile.surname = argv[2]; temporaryProfile.email = argv[3]; temporaryProfile.address = argv[4]; temporaryProfile.contact = argv[5]; temporaryProfile.username = argv[6]; temporaryProfile.password = argv[7]; return 0; } // helps in getting information from Order sql. static int get_info_Order(void *data, int argc, char **argv, char **azColName) { temporaryOrder.OrderID = argv[0]; temporaryOrder.order_ = argv[1]; temporaryOrder.customerID = argv[2]; temporaryOrder.remainingTime = argv[3]; temporaryOrder.other_details = argv[4]; return 0; } // returns order details when called. order extactOrderInfo(string orderID){ temporaryOrder.customerID = "#"; string query = "SELECT * FROM ALL_ORDERS_DB WHERE ORDER_ID = \'" + orderID + "\';"; int exit = sqlite3_exec(DB, query.c_str(), get_info_Order, NULL, NULL); if (exit != SQLITE_OK) logStream <<__func__<< "Error SELECT" << endl; else { logStream << "Operation OK!" << endl; } return temporaryOrder; } // helps in updating time left for a product to arrive in sql. void updateTime(string orderID, string remainingTime){ string query = "UPDATE ALL_ORDERS_DB set TIME_LEFT = \'" + remainingTime + "\' WHERE ORDER_ID = \'" + orderID + '\''; int exit = sqlite3_exec(DB, query.c_str(), callback, NULL, NULL); logStream<<query<<endl; if (exit != SQLITE_OK) logStream << "Error SELECT" << endl; else { logStream << "Operation OK!" << endl; } } // creats databse if it is not already present. void createDataBase() { int exit = 0; exit = sqlite3_open("userDatabase.db", &DB); //creats sql database if not already present. if (exit) { logStream << "Error open DB " << sqlite3_errmsg(DB) << endl; // logstream logs error if there is an issue creating table. std::exit(1); // exits the code if there is error. } else logStream << "Created Database Successfully!" << std::endl; string sql = "CREATE TABLE PERSON(" "ID TEXT PRIMARY KEY NOT NULL, " "NAME TEXT NOT NULL, " "SURNAME TEXT NOT NULL, " "EMAIL_ID TEXT NOT NULL, " "ADDRESS CHAR(50), " "CONTACT_NO TEXT NOT NULL," "USERNAME TEXT NOT NULL," "PASSWORD TEXT NOT NULL);"; string sql2 = "CREATE TABLE USER_TRANSACTION(" "ID TEXT PRIMARY KEY NOT NULL, " "TRANSACTIONS TEXT NOT NULL );"; string sql3 = "CREATE TABLE USER_MAP(" "USERNAME TEXT PRIMARY KEY NOT NULL, " "ID TEXT NOT NULL );"; string sql4 = "CREATE TABLE BLACKLISTED(" "USERNAME TEXT PRIMARY KEY NOT NULL );"; string sql5 = "CREATE TABLE ASSIGNED_ORDER(" "ID TEXT PRIMARY KEY NOT NULL, " "ORDER_ID TEXT NOT NULL );"; string sql6 = "CREATE TABLE WISHLIST(" "ID TEXT PRIMARY KEY NOT NULL, " "ITEMS TEXT NOT NULL );"; string sql7 = "CREATE TABLE ALL_ORDERS_DB(" "ORDER_ID TEXT PRIMARY KEY NOT NULL, " "ORDER_ TEXT NOT NULL, " "CUSTOMER_ID TEXT NOT NULL, " "TIME_LEFT TEXT NOT NULL, " "OTHER_DETAILS TEXT NOT NULL );"; string sql8 = "CREATE TABLE UNASSIGNED_DELIVERY_PERSON(" "ID TEXT PRIMARY KEY NOT NULL );"; string sql9 = "CREATE TABLE UNASSIGNED_ORDERS(" "ORDER_ID TEXT PRIMARY KEY NOT NULL );"; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); exit = sqlite3_exec(DB, sql2.c_str(), NULL, 0, &messaggeError); exit = sqlite3_exec(DB, sql3.c_str(), NULL, 0, &messaggeError); exit = sqlite3_exec(DB, sql4.c_str(), NULL, 0, &messaggeError); exit = sqlite3_exec(DB, sql5.c_str(), NULL, 0, &messaggeError); exit = sqlite3_exec(DB, sql6.c_str(), NULL, 0, &messaggeError); exit = sqlite3_exec(DB, sql7.c_str(), NULL, 0, &messaggeError); exit = sqlite3_exec(DB, sql8.c_str(), NULL, 0, &messaggeError); exit = sqlite3_exec(DB, sql9.c_str(), NULL, 0, &messaggeError); // the above commands create tables if not alredy created. if (exit == SQLITE_OK) { logStream << "Error Create Table" << endl; sqlite3_free(messaggeError); } else logStream << "Table created Successfully" << endl; } // helps in getting name for user when given an ID. static int get_name(void *data, int argc, char **argv, char **azColName) { temporaryID = argv[1]; return 0; } // retrieves the name of the user from the sql table using ID. string nameFromId(string id) { temporaryID = "#"; // '#' is returned if id is not present in the databse. string query = "SELECT * FROM PERSON WHERE ID = \'" + id + "\';"; int rc = sqlite3_exec(DB, query.c_str(), get_name, NULL, NULL); if (rc != SQLITE_OK) logStream << __func__<<"Error select" << "\n"; else logStream<< __func__ << "Operation OK" << "\n"; return temporaryID; // temporaryID stores the name if found in the database. } // adds unassigned order to an sql table so that it could be assigned to a delivery // as soon as any are free. void add_unassginedOrder(string orderId){ string temp = '\'' + orderId + "\'"; string sql("INSERT INTO UNASSIGNED_ORDERS VALUES(" + temp + ");"); exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); // adds the order to the database. If not possible logs an error in logStream. if (exit != SQLITE_OK) { logStream << "Error Insert " << messaggeError << endl; sqlite3_free(messaggeError); } else logStream << "Record inserted Successfully!" << endl; } // helps in retrieving order of users using the USERID from sql. static int get_Order(void *data, int argc, char **argv, char **azColName) { temporaryID = argv[0]; return 0; } // returns a single unassigned order if possible else returns -1. int get_unassignedOrder(){ temporaryID = "-1"; string sql("SELECT * FROM UNASSIGNED_ORDERS;"); int rc = sqlite3_exec(DB, sql.c_str(), get_Order, NULL, NULL); if (rc != SQLITE_OK) logStream << "Error select" << "\n"; else logStream << "Operation OK" << "\n"; // -1 is returned if there are no unassigned orders. return stoi(temporaryID); // temporaryID stores an unassigned orderID. } // deletes unassigned orderid from its sql database if it is assigned to some delivery person. void delete_unassignedOrder(string orderId){ string sql = "DELETE FROM UNASSIGNED_ORDERS WHERE ORDER_ID = \'" + orderId + "\';"; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); // logs an error in logStream if it was not possible or the orderID was not present in the table. // else logs that the operation was successful. if (exit != SQLITE_OK) { logStream << "Error DELETE" << endl; sqlite3_free(messaggeError); } else logStream << "Record deleted Successfully from PERSON!" << endl; } // helps in retriving the address of any user from its respective sql table. static int get_address(void *data, int argc, char **argv, char **azColName) { temporaryID = argv[0]; return 0; } // returns the address of any user given its userID. // returns '#' if the ID is not present in the database. string addressFromId(string id) { temporaryID = "#"; string query = "SELECT ADDRESS FROM PERSON WHERE ID = \'" + id + "\';"; int rc = sqlite3_exec(DB, query.c_str(), get_address, NULL, NULL); if (rc != SQLITE_OK) logStream << "Error select" << "\n"; else logStream << "Operation OK" << "\n"; return temporaryID; // temporaryID contains the address if the ID is found in the database. } // loads both the databases i.e. the sql database and also the file handling database // into the local memory or creates them if they were already not present in the database // it also loads the log file and the password backdoor for read and write and also the // system state into the memory and transfers all the data from the file to local memory // in order to process them excepting the data of sql which provides for fast search // and also the data of the log file and password backdoor which were not required locally void loadDatabase() { createDataBase(); passwordBackdoor.open("passwordBackdoor.txt",ios::out|ios::app); global_inve_file.open("global_inventory_db", ios::in); if (!global_inve_file.is_open()) { global_inve_file.open("global_inventory_db", ios::out); global_inve_file.close(); global_inve_file.open("global_inventory_db", ios::in); } // loads all the inventory locally to the global inventory array. ifstream sysfile; sysfile.open("systemState", ios::in); sysfile.read((char *)&state, sizeof(systemState)); sysfile.close(); // loads the data of system state then closes the file. logStream<<"systemState(cus,shop,del,...) "<<state.CustomerCount<<" "<< state.shopKeeperCount<<" "<<state.deliveryPersonCount<<" "<<state.productCount<<\ " "<<state.OrderCount<<endl; global_inve_file.seekg(0, ios::end); int fileSize = global_inve_file.tellg(); logStream << fileSize << endl; global_inve_file.seekg(0, ios::beg); int size = fileSize / sizeof(product); global_inventory_array = (product *)malloc(size * sizeof(product)); logStream << global_inve_file.tellg() << endl; global_inve_file.read((char *)global_inventory_array, fileSize); logStream << "size " << size << endl; // logs every detail in the log file for the admin for (int i = 0; i < size; ++i) { global_inven_map[global_inventory_array[i].product_name].insert(global_inventory_array[i].product_id); personal_inventory[global_inventory_array[i].shopkeeper_id].insert(global_inventory_array[i].product_id); productId_to_product[global_inventory_array[i].product_id] = (global_inventory_array[i]); } // loads all the data of the global inventory in different local entities. // then closes all the files. global_inve_file.close(); } // Inserts a new user in the sql database i.e. userMap and also person etc. string Insert(string name, string surname, string email, string address, string username, string password, string contact, enum typeOfUser type) { string id = ""; if (type == Customer) { id = 'C' + to_string(state.CustomerCount++); } else if (type == deliveryPerson) { id = 'D' + to_string(state.deliveryPersonCount++); } else { id = 'S' + to_string(state.shopKeeperCount++); } passwordBackdoor<<username<<" "<<password<<endl; // puts the password in the password backdoor password = sha256(password); // hashes the password so as to protect the password from theft string temp1 = '\'' + id + "\',\'" + name + "\',\'" + surname + "\',\'" + email + "\',\'" + address + "\',\'" + contact + "\',\'" + username + "\',\'" + password + '\''; string temp = '\'' + username + '\'' + ',' + '\'' + id + '\''; string temp2 = '\'' + id + "\',\'\'"; string sql("INSERT INTO PERSON VALUES(" + temp1 + ");"); string sql1("INSERT INTO USER_MAP VALUES(" + temp + ");"); string sql2("INSERT INTO USER_TRANSACTION VALUES(" + temp2 + ");"); exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Insert " << messaggeError << endl; sqlite3_free(messaggeError); // logs error in the log file if the insertion was not possible. } else logStream << "Record inserted Successfully!" << endl; exit = sqlite3_exec(DB, sql1.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Insert " << messaggeError << endl; sqlite3_free(messaggeError); } else logStream << "Record inserted Successfully!" << endl; exit = sqlite3_exec(DB, sql2.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Insert " << messaggeError << endl; sqlite3_free(messaggeError); } else logStream << "Record inserted Successfully!" << endl; // finally this function returns the user's unique id to the caller. return id; } // checks if the username and password exist in the sql database // and also returns the details of the user for local use if it did exist. profile authenticate(string username, string password) { string query = "SELECT ID FROM USER_MAP WHERE USERNAME = \'" + username + "\';"; int rc = sqlite3_exec(DB, query.c_str(), get_ID, NULL, NULL); string tmp = temporaryID; if (rc != SQLITE_OK || temporaryID == "#" || isBlackListed(username)) { printHeader(); cout << fgred << "\t\t\t\t\t\t\t\t\t\tINCORRECT Username or Password!!!!" << endl; // displays if not present in the database. temporaryProfile.name = "#"; return temporaryProfile; } else { logStream << "Operation OK!" << endl; } temporaryProfile.id = tmp; query = "SELECT * FROM PERSON WHERE ID = \'" + tmp + "\';"; sqlite3_exec(DB, query.c_str(), get_information, NULL, NULL); if (temporaryProfile.password != password) { delayBy(0); printHeader(); cout << fgred << "\t\t\t\t\t\t\t\t INCORRECT Username or Password" << endl; // displays incorrect password if the username was present but the password // did not match with the information. cout << endl; temporaryProfile.name = "#"; return temporaryProfile; } // temporaryProfile contains the details of the user as provided by // the database if it existed in the database else it contains garbage // values while temporaryProfile.name = '#' to identify that it did not // exist in the database. return temporaryProfile; } // deletes ID from the database completely if the user wishes bool deleteID(string id, string username) { // it destroys the complete data of the user from person and // usermap and also its transactions from user_transactions printHeader(); cout<<fgred<<printtabs(9)<<"Are you sure you want to delete your account?(Y/n)"<<endl; cout<<fgblue<<printtabs(9)<<">>"; string response; cin>>response; if(response!="Y"&&response!="y") return 0; // RETURNS 0 if the user opts to not delete his id. string sql = "DELETE FROM PERSON WHERE ID = \'" + id + "\';"; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error DELETE" << endl; sqlite3_free(messaggeError); } else logStream << "Record deleted Successfully from PERSON!" << endl; sql = "DELETE FROM USER_TRANSACTION WHERE ID = \'" + id + "\';"; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error DELETE" << endl; sqlite3_free(messaggeError); } else logStream << "Record deleted Successfully from USER_TRANSACTION!" << endl; sql = "DELETE FROM USER_MAP WHERE USERNAME = \'" + username + "\';"; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error DELETE" << endl; sqlite3_free(messaggeError); } else logStream << "Record deleted Successfully from USER_MAP!" << endl; // returns 1 if the id was successfully deleted from the database. return 1; } // changeProfile helps in editing the sql databases using the given information. void changeProfile(string id, string name, string surname, string email, string address, string username, string password, string contact) { string sql = "DELETE FROM PERSON WHERE ID = \'" + id + "\';"; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error DELETE" << endl; sqlite3_free(messaggeError); } else logStream << "Record deleted Successfully!" << endl; string temp1 = '\'' + id + "\',\'" + name + "\',\'" + surname + "\',\'" + email + "\',\'" + address + "\',\'" + contact + "\',\'" + username + "\',\'" + password + '\''; string sql1("INSERT INTO PERSON VALUES(" + temp1 + ");"); exit = sqlite3_exec(DB, sql1.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Insert" << endl; sqlite3_free(messaggeError); } else logStream << "Record inserted Successfully!" << endl; } // editProfile gives option to change the profile of User. // it also returns the current profile profile editProfile(string id,profile& profileToEdit) { // This function step wise gives option to the user to edit // different aspects of his profile. printHeader(); char check; if(id[0]=='S'){ cout <<fggreen<<printtabs(8)<< "Do you wish to change your shop name?(Y/n) :: "<<fgblue; cin >> check; if (check == 'Y' || check == 'y') { printInputField(); string new_name; cin >> new_name; profileToEdit.name = new_name; } } else{ cout <<fggreen<<printtabs(8)<< "Do you wish to change your name?(Y/n) :: "<<fgblue; cin >> check; if (check == 'Y' || check == 'y') { printInputField(); string new_name; cin >> new_name; profileToEdit.name = new_name; } cout << fggreen<<printtabs(8)<< "Do you wish to change your Surname?(Y/n) :: "<<fgblue; cin >> check; if (check == 'Y' || check == 'y') { printInputField(); string new_surname; cin >> new_surname; profileToEdit.surname = new_surname; } } cout << fggreen<<printtabs(8)<< "Do you wish to change your Email ID?(Y/n) :: "<<fgblue; cin >> check; if (check == 'Y' || check == 'y') { printInputField(); string new_email; cin >> new_email; while (!isEmailCorrect(new_email)) { cout <<fggreen<<printtabs(8)<< "Enter a valid Email address(Only IIT Jodhpur official email addresses are considered valid) "; cin >> new_email; } profileToEdit.email = new_email; } cout <<fggreen<<printtabs(8)<< "Do you wish to change your address?(Y/n) :: "<<fgblue; cin >> check; if (check == 'Y' || check == 'y') { printInputField(); string new_address;//cin>>new_address; getline(cin,new_address); getline(cin,new_address); profileToEdit.address = new_address; } cout <<fggreen<<printtabs(8)<< "Do you wish to change your Contact number?(Y/n) :: "; cin >> check; if (check == 'Y' || check == 'y') { printInputField(); string new_contact; cin >> new_contact; while (!isContactCorrect(new_contact)) { cout <<fggreen<<printtabs(8)<< "Enter a valid contact number"; cin >> new_contact; } profileToEdit.contact = new_contact; } cout <<fggreen<<printtabs(8)<< "Do you wish to change your Password?(Y/n) :: "; cin >> check; if (check == 'Y' || check == 'y') { printInputField(); string new_password, confirm_new_password; cin >> new_password; cout << printtabs(8) << "Confirm Password: "; cin >> confirm_new_password; while (!(isPasswordCorrect(new_password) && confirm_new_password == new_password)) { cout << "Enter a valid Password: "; cin >> new_password; cout << "Confirm Password: "; cin >> confirm_new_password; } // hashes the password and also stores the new password // in the passwordBackdoor. passwordBackdoor << profileToEdit.username << ' ' << profileToEdit.password<<endl; profileToEdit.password = sha256(new_password); } // calls changeProfile to edit information in the database. changeProfile(id, profileToEdit.name, profileToEdit.surname, profileToEdit.email, profileToEdit.address, profileToEdit.username, profileToEdit.password, profileToEdit.contact); // returns the edited profile for local use. return profileToEdit; } // helps in editing the remaining delivery time in the database static int update(void *data, int argc, char **argv, char **azColName) { string tmp1 = ""; if (argv[0] != NULL) tmp1 = argv[0]; string tmp = tmp1 + add; string sql = "UPDATE USER_TRANSACTION set TRANSACTIONS = \'" + tmp + "\' WHERE ID = \'" + temporaryID + '\''; temporaryID = sql; return 0; } // adds Transaction in the database void addTransaction(string id, bool isPaid, int moneyTransferred, int orderID, string payment_mode, string timeOfOrder, string paymentUsing) { string temp = "Using "; if (payment_mode == "CASH ON DELIVERY") temp = ""; string query = "SELECT TRANSACTIONS FROM USER_TRANSACTION WHERE ID = \'" + id + "\';"; add = to_string(orderID) + " | " + (isPaid ? "Paid" : "Refunded") + " | " + to_string(moneyTransferred) + " | " + payment_mode + " | " + temp + paymentUsing + " | " + timeOfOrder + "\n"; temporaryID = id; sqlite3_exec(DB, query.c_str(), update, NULL, NULL); exit = sqlite3_exec(DB, temporaryID.c_str(), callback, NULL, &messaggeError); if (exit != SQLITE_OK) { logStream << "SQL error: " << messaggeError <<endl; sqlite3_free(messaggeError); // logs error in the log file if it was not possible to add the transaction } else { logStream<< "Operation done successfully\n"; } } // helps in retrieving the data of transaction from the database. static int get_transaction(void *data, int argc, char **argv, char **azColName) { // the information is pushed in vector named tempOrderofCustomer tempOrderofCustomer.clear(); int len = strlen(argv[0]); bool fl = 1; string temp=""; for(int i=0; i<len; ++i){ if(argv[0][i] == '\n'){ fl=1; continue; } if(argv[0][i] == ' ' && fl){ fl=0; tempOrderofCustomer.push_back(stoi(temp)); temp = ""; } if(fl){ temp+=argv[0][i]; } } return 0; } // returns vector of the orderd product of any user. vector<int> orderIdsofCustomer(string id){ string query = "SELECT TRANSACTIONS FROM USER_TRANSACTION WHERE ID = \'" + id + "\';"; int exit = sqlite3_exec(DB, query.c_str(), get_transaction, NULL, NULL); if (exit != SQLITE_OK) logStream << "Error SELECT" << endl; else { logStream << "Operation OK!" << endl; } return tempOrderofCustomer; } // It displays all the transactions of any user given the userID. void showTransaction(string id) { string query = "SELECT TRANSACTIONS FROM USER_TRANSACTION WHERE ID = \'" + id + "\';"; int exit = sqlite3_exec(DB, query.c_str(), callback, NULL, NULL); if (exit != SQLITE_OK) logStream << "Error SELECT" << endl; else { logStream << "Operation OK!" << endl; } } // finds the username from the sql database. static int check_username(void *data, int argc, char **argv, char **azColName) { temporaryID = argv[0]; return 0; } // checks if the username had been already taken in the database. // as we need a unique username for different personnel. // returns 1 if the username had been taken else returns 0. bool isUsernameTaken(string username) { temporaryID = "#"; string query = "SELECT * FROM USER_MAP WHERE USERNAME = \'" + username + "\';"; sqlite3_exec(DB, query.c_str(), check_username, NULL, NULL); // only checks if username is taken or not i.e. returns 0 only if it is taken if (temporaryID != "#") return 1; else return 0; } // Inserts new entity into the database. string signUp(profile addToDatabase) { return Insert(addToDatabase.name, addToDatabase.surname, addToDatabase.email, addToDatabase.address, addToDatabase.username, addToDatabase.password, addToDatabase.contact, addToDatabase.type); } // function for the admin of the application. // helps in adding people as blacklisted if the abuse the system. void addToBlacklist(string username) { string sql("INSERT INTO BLACKLISTED VALUES(\'" + username + "\');"); exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Insert " << messaggeError << endl; sqlite3_free(messaggeError); } else logStream << "Record inserted Successfully!" << endl; } // checks if the user is blacklisted or is good to go // returns 1 if blacklisted else 0. bool isBlackListed(string username) { temporaryID = "#"; string query = "SELECT * FROM BLACKLISTED WHERE USERNAME = \'" + username + "\';"; exit = sqlite3_exec(DB, query.c_str(), check_username, NULL, NULL); return temporaryID != "#"; } // inserts new product in the inventory void insertProduct(product productToInsert) { productId_to_product[productToInsert.product_id] = productToInsert; } // sends the new password email to the user's registered // email id if the username exists in the database. // and also edits the profile in the database. void forgotPassword(string username) { string new_password = PasswordGenerator(); string message = "Your new Password is : " + new_password; string query = "SELECT ID FROM USER_MAP WHERE USERNAME = \'" + username + "\';"; sqlite3_exec(DB, query.c_str(), get_ID, NULL, NULL); query = "SELECT * FROM PERSON WHERE ID = \'" + temporaryID + "\';"; sqlite3_exec(DB, query.c_str(), get_information, NULL, NULL); temporaryProfile.password = new_password; sendPasswordToEmail(temporaryProfile.email, new_password); new_password=sha256(new_password); changeProfile(temporaryID, temporaryProfile.name, temporaryProfile.surname, temporaryProfile.email, temporaryProfile.address, temporaryProfile.username, temporaryProfile.password, temporaryProfile.contact); } // assigns order to delivery person and also adds the information // in the database. void assign_order(string id, int orderID) { string temp = '\'' + id + "\',\'" + to_string(orderID) + '\''; string sql("INSERT INTO ASSIGNED_ORDER VALUES(" + temp + ");"); exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Insert " << messaggeError << endl; sqlite3_free(messaggeError); } else logStream << "Record inserted Successfully!" << endl; } // removes the assigned order from a delivery Person if the order has // reached its desired destination and also edits the sql database. void finish_order(string id) { string sql = "DELETE FROM ASSIGNED_ORDER WHERE ID = \'" + id + "\';"; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error DELETE" << endl; sqlite3_free(messaggeError); } else logStream << "Record deleted Successfully from PERSON!" << endl; } // checks if a delivery Person is available or not. static int check_avail(void *data, int argc, char **argv, char **azColName) { temporaryID = argv[1]; return 0; } // returns the assigned order ID of the delivery person in question // if none were assigned it returns -1. int AssignedOrderId(string id) { temporaryID = "-1"; string query = "SELECT * FROM ASSIGNED_ORDER WHERE ID = \'" + id + "\';"; sqlite3_exec(DB, query.c_str(), check_avail, NULL, NULL); return stoi(temporaryID); } // helps in getting the wishlist information from the sql database. static int get_wishList(void *data, int argc, char **argv, char **azColName) { temporaryID = argv[1]; return 0; } // deleteWishlist deletes the wishlist of the user in qustion from the database. void deleteWishList(string id) { string sql = "DELETE FROM WISHLIST WHERE ID = \'" + id + "\';"; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error DELETE" << endl; sqlite3_free(messaggeError); } else logStream << "Record deleted Successfully from PERSON!" << endl; } // insert wishlist of some user with its information. void insertWishList(string id, string wishlist) { string temp = '\'' + id + "\',\'" + wishlist + '\''; string sql("INSERT INTO WISHLIST VALUES(" + temp + ");"); ; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Insert " << messaggeError << endl; sqlite3_free(messaggeError); } else logStream << "Record inserted Successfully!" << endl; } // appends to the wishlist of some user. void addToWishList(string id, string name) { temporaryID = ""; string query = "SELECT * FROM WISHLIST WHERE ID = \'" + id + "\';"; sqlite3_exec(DB, query.c_str(), get_wishList, NULL, NULL); if (temporaryID.size() != 0) deleteWishList(id); temporaryID += "#" + name; insertWishList(id, temporaryID); } // return the wishlist of a user in the form of a set of strings set<string> returnWishlist(string id) { temporaryID = ""; string query = "SELECT * FROM WISHLIST WHERE ID = \'" + id + "\';"; sqlite3_exec(DB, query.c_str(), get_wishList, NULL, NULL); string tmp = ""; set<string> wishlist; for (auto i : temporaryID) { if (i != '#') tmp += i; else wishlist.insert(tmp), tmp = ""; } if (tmp.size() != 0) wishlist.insert(tmp); return wishlist; } // helps in editing the wishlist of a user void changeWishList(string id, set<string> new_wishlist) { deleteWishList(id); for (auto i : new_wishlist) { addToWishList(id, i); } } // helps in retrieving the time left for some order to reach its // desired location from the sql database. static int get_Status(void *data, int argc, char **argv, char **azColName) { temporaryID = ""; for(int i=0;i<8;++i)temporaryID.push_back(argv[3][i]); return 0; } // returns the time left in the form of a string in the // format (days:hours:minutes). // it returns (??:??:??) if the delivery person has not yet updated the time remaining. string get_orderStatus(string id){ temporaryID = "#"; string query = "SELECT * FROM ALL_ORDERS_DB WHERE ORDER_ID = \'" + id + "\';"; exit = sqlite3_exec(DB, query.c_str(), get_Status, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Operation " << messaggeError << endl; sqlite3_free(messaggeError); } else logStream << "Operation done Successfully!" << endl; return temporaryID; } // insert the details of the order in the sql database. void insertOrder(string id, vector<pair<int,int>> curOrder, string payementUsing, string payementMode, string curTime, string customerId, string time_remaining){ string product_ids = "",tempOrder=""; for(auto i: curOrder){ product_ids += "[" "Product ID : "+ to_string(i.first) + " | " + "Quantity Ordered : "+to_string(i.second) + "] "; } tempOrder += "[" + payementMode +"] "; if(payementUsing.length())tempOrder += "["+payementUsing+"] "; tempOrder += "["+curTime+"]"; string temp = '\'' + id + "\',\'" + product_ids + "\',\'" + customerId + "\',\'" + time_remaining + "\',\'" + tempOrder + '\''; string sql("INSERT INTO ALL_ORDERS_DB VALUES(" + temp + ");");; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Insert " << messaggeError << endl; sqlite3_free(messaggeError); } else logStream << "Record inserted Successfully!" << endl; } // deletes the Order from the desired sql database table // when the order is completed void deleteOrder(string id){ string sql = "DELETE FROM ALL_ORDERS_DB WHERE ORDER_ID = \'" + id + "\';"; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error DELETE" << endl; sqlite3_free(messaggeError); } else logStream << "Record deleted Successfully from PERSON!" << endl; } // it finds an unassigned delivery person so as to assign him some order. static int findUnassigned(void *data, int argc, char **argv, char **azColName) { temporaryID = argv[0]; return 0; } // returns the id of the unassigned delivery person from the database // if not possible returns '#' string find_unassigned_deliveryPerson() { temporaryID = "#"; string sql("SELECT * FROM UNASSIGNED_DELIVERY_PERSON;"); exit = sqlite3_exec(DB, sql.c_str(), findUnassigned, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Insert " << messaggeError << endl; sqlite3_free(messaggeError); } else logStream << "Record inserted Successfully!" << endl; return temporaryID; // It is '#' if everyone is assigned. } // deletes delivery person from the database table of unassigned delivery person // if he has been alloted an order. void delete_unassigned_deliveryPerson(string id) { string sql = "DELETE FROM UNASSIGNED_DELIVERY_PERSON WHERE ID = \'" + id + "\';"; exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error DELETE" << endl; sqlite3_free(messaggeError); } else logStream << "Record deleted Successfully from PERSON!" << endl; } // Adds new entry to the sql database of unassigned delivery persons void insert_unassigned_deliveryPerson(string id) { string sql("INSERT INTO UNASSIGNED_DELIVERY_PERSON VALUES(\'" + id + "\');"); exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError); if (exit != SQLITE_OK) { logStream << "Error Insert " << messaggeError << endl; sqlite3_free(messaggeError); } else logStream << "Record inserted Successfully!" << endl; } // Assigns orders in waiting, if any to the available delivery persons, if any void assignUnassignedOrders(){ while(1){ string tempDeliveryPerson = find_unassigned_deliveryPerson(); // finds available delivery person, if any int tempOrderId = get_unassignedOrder(); if(tempDeliveryPerson == "#" || tempOrderId == -1)break; delete_unassigned_deliveryPerson(tempDeliveryPerson); /* deletes that delivery person from database of available delivery persons */ delete_unassignedOrder(to_string(tempOrderId)); /* deletes the corresponding order from the sql database of orders in waiting */ assign_order(tempDeliveryPerson, tempOrderId); } } // A function which takes care of entire payment procedure void payment(vector<pair<product, int>> Cart, enum mode payment_mode, string contact, string id) { printHeader(); cout<<endl; auto current_clock = chrono::system_clock::now(); time_t cur_time = std::chrono::system_clock::to_time_t(current_clock); string currentTime = ctime(&cur_time); // Gives the real time of transaction string tempMode = ""; int totalCost = 0; for (auto currentProduct : Cart) { productId_to_product[currentProduct.first.product_id].rating++; productId_to_product[currentProduct.first.product_id].count -= currentProduct.second; totalCost += (currentProduct.first.price + currentProduct.first.deliveryCharge) * currentProduct.second; } cout<<printtabs(8)<<fggreen << "Total Cost = " << totalCost << endl; string cardNumber, expiry_Date, Cvv, paymentUsing = ""; char choice; switch (payment_mode) { case cashOnDelivery: tempMode = "CASH ON DELIVERY"; break; case onlineBanking: cout<<printtabs(8)<<fggreen << "Enter card number (****-****-****-****)" << endl; do { cin >> cardNumber; } while (!isCorrectCardNumber(cardNumber)); paymentUsing = cardNumber; cout <<printtabs(8)<<fggreen<< "Enter Expiry Date (mm/yy)" << endl; do { cin >> expiry_Date; } while (!isCorrectDate(expiry_Date)); cout<<printtabs(8)<<fggreen << "Enter Cvv (***)" << endl; do { cin >> Cvv; } while (isCorrectCvv(Cvv)); tempMode = "ONLINE BANKING"; break; case Paytm: cout<<printtabs(8)<<fggreen << "Do you wish to use your current number(Y/n): " << contact << endl; cin >> choice; if (!(choice == 'Y' || choice == 'y')) { do { cin >> contact; } while (isContactCorrect(contact)); } paymentUsing = contact; tempMode = "PAYTM"; break; case GooglePay: cout<<printtabs(8)<<fggreen << "Do you wish to use your current number(Y/n): " << contact << endl; cin >> choice; if (!(choice == 'Y' || choice == 'y')) { do { cin >> contact; } while (isContactCorrect(contact)); } paymentUsing = contact; tempMode = "GOOGLE PAY"; break; default: logStream << "No such banking option" << endl; break; } int orderID1 = state.OrderCount++; // Assigns ID to the order cout<<printtabs(8)<<fggreen << id << " " << orderID1 << " " << tempMode << " " << paymentUsing << endl; addTransaction(id, 1, totalCost, orderID1, tempMode, currentTime, paymentUsing); //Adds to the user transaction database string deliveryPersonID=find_unassigned_deliveryPerson(); // finds available delivery person, if any vector<pair<int,int>>tempOrder; for(auto y:Cart)tempOrder.push_back({y.first.product_id, y.second}); insertOrder(to_string(orderID1),tempOrder, paymentUsing,tempMode,currentTime, id,"????????"); // inserts order to the sql database of all orders if(deliveryPersonID=="#"){ // i.e. no delivery person is available add_unassginedOrder(to_string(orderID1)); // adds the order to the database of unassigned orders } else{ assign_order(deliveryPersonID, orderID1); // Assigns order to the given delivery person delete_unassigned_deliveryPerson(deliveryPersonID); /* deletes the corresponding delivery person from the database of available delivery persons */ } } // Adds the product to shopkeeper's personal inventory void addToInventory(product productToAdd) { personal_inventory[productToAdd.shopkeeper_id].insert(productToAdd.product_id); productId_to_product[productToAdd.product_id] = productToAdd; global_inven_map[productToAdd.product_name].insert(productToAdd.product_id); } // Changes the quantity of products in shopkeeper's personal inventory void changeProductCount(int productID, int changedCount) { productId_to_product[productID].count = changedCount; } // Changes the price of products in shopkeeper's personal inventory void changeProductPrice(int productID, int changedPrice) { productId_to_product[productID].price = changedPrice; } // debugging function void setSystemState(int cusCnt, int shpCnt, int delCnt, int prodCnt, int OrdCnt) { remove("systemState"); fstream file; file.open("systemState", ios::out); systemState madeUpState; madeUpState.CustomerCount = cusCnt; madeUpState.shopKeeperCount = shpCnt; madeUpState.deliveryPersonCount = delCnt; madeUpState.OrderCount = OrdCnt; madeUpState.productCount = prodCnt; file.write((char *)&madeUpState, sizeof(systemState)); file.close(); } // A class destructor which dumps new data into corresponding files ~admin() { global_inventory_array = (product *)malloc(productId_to_product.size() * sizeof(product)); int index = 0; for (auto i : productId_to_product) { global_inventory_array[index] = i.second; index++; } remove("global_inventory_db"); global_inve_file.open("global_inventory_db", ios::out); global_inve_file.write((char *)global_inventory_array, productId_to_product.size() * sizeof(product)); global_inve_file.close(); remove("systemState"); fstream outSysState; outSysState.open("systemState", ios::out); outSysState.write((char *)&state, sizeof(systemState)); outSysState.close(); } };
true
0f18b87947c7310da86dc6ecefe9a3890572d5e8
C++
yzq986/cntt2016-hw1
/TC-SRM-559-div1-500/Remilia.cpp
GB18030
1,135
2.5625
3
[]
no_license
#include <algorithm> using namespace std; struct HatRack{ int n, mmm, sz[51]; bool e[51][51]; void fafafa(int u, int v){e[u][v]=e[v][u]=1;} // size void gsz(int u, int ff){ sz[u]=1; for(int v=0;v<n;++v) if(e[u][v] && v^ff)gsz(v,u),sz[u]+=sz[v]; } long long gao(int u, int ff, int id){ mmm=max(mmm,id); vector<int> erz; for(int v=0;v<n;++v)if(e[u][v] && v^ff)erz.push_back(v); // Ϸ if(erz.size()>2)return 0; // Ҷ if(erz.size()==0)return 1; // ̬Ψһ if(erz.size()==2 && sz[erz[0]]<sz[erz[1]])swap(erz[0],erz[1]); long long ret=1; // ԵĴ for(int i=0;i<erz.size();++i)ret*=gao(erz[i],u,id*2+i); // ҿɽ if(erz.size()>1 && sz[erz[0]]==sz[erz[1]])ret*=2; return ret; } long long countWays(vector<int> edge_u, vector<int> edge_v){ n=edge_u.size()+1; if(n==2)return 2; for(int i=0;i+1<n;++i)fafafa(--edge_u[i],--edge_v[i]); long long ans = 0; // öٸ for(int i=0;i<n;++i){ gsz(i,-1); mmm=0; long long tmp=gao(i,-1,1); // ==nζűųɹ if(mmm==n)ans+=tmp; } return ans; } };
true
19ae91d4d2ce5dacb65231b9b4b190409d33d020
C++
lhp3851/CPPDemo
/C++Demo/Vector/VectorDemo.cpp
UTF-8
1,153
3.25
3
[]
no_license
// // VectorDemo.cpp // C++Demo // // Created by lhp3851 on 2018/12/30. // Copyright © 2018 Jerry. All rights reserved. // #include "VectorDemo.hpp" #include <iostream> #include <vector> using namespace std; //函数 template<typename T> void printer(const T& val) { cout << val << endl; } //仿函数 template<typename T> struct functor { void operator()(const T& obj) { cout << obj << endl; } }; //Lambda void lambdaPrinter(const vector<int>& valList) { for_each(valList.cbegin(), valList.cend(), [](const int& val)->void{cout << val << endl; }); } //init void init(){ vector<int> v1; int a[4] = {0,1,2,3}; vector<int> v5(5,*(a)); cout << sizeof(v5) << "\n" << v5.size() << endl; v5.pop_back(); v5.push_back(5); //迭代器 // for (auto iter = v5.begin(); iter != v5.end(); iter ++) { // cout << *(iter) << endl; // } // for_each(v5.begin(), v5.end(), printer<int>); // for_each(v5.begin(), v5.end(), functor<int>()); // lambdaPrinter(v5); //区间遍历 for (auto val: v5) { cout << val << endl; } }
true
55aaeabd3faaeef50acb1550a51dd9f101f86493
C++
pdxjohnny/cplusplus
/3/gen.h
UTF-8
3,547
3.234375
3
[]
no_license
/* Author: John Andersen Date: 11/5/2014 Description: General functions I always use */ #include <cstring> #include <cstdlib> #include <cstdio> #include <iostream> #include <cctype> #include <sys/ioctl.h> #include <unistd.h> #ifndef GEN #define GEN 1 // General functions I always use namespace gen { // So I don't have to define in every program const unsigned int STRING_SIZE = 255; // A class for naming functions // class functions; // Capitalises the first letter of every word void capitalize( char *cap_me ); // Make every letter in a string lowercase void tolower( char * lower ); // Capitalises every letter in a string void toupper( char * cap_me ); // Capitalises a char by reference void toupper( char & cap_me ); // Clears a string void strclr( char *clear ); // Removes all instances of a character in a string void remove_char( char * input, char remove_char ); // Removes all of a leading charater void remove_leading( char * input, char remove_char ); // Removes all whitespace in a string void remove_whitespace( char * input ); // Removes all double, triple, etc spaces void remove_multi_whitespace( char * input ); // Calls remove_multi_whitespace and capitalize void error_check( char * input ); // Splits a line into two baised on the delim void split_line( const char * line, char * first, char * second, const char delim ); // Askes yes or no, true if yes / y bool confirm(); // Prints "ask" then gets a response and stores it in "response" void get_line( const char * ask, char * response, unsigned int response_size ); // Checks if the string is a number data type bool number( char * string ); // Checks if all values in a string are numbers bool is_int( char * string ); // Checks if all values in a string are numbers or decimal point bool is_float( char * string ); // Counts the occurences of a char in a string int count( char * string, const char delim ); // Formats csv columns void add_to_csv( int column_position, int column_count, char * string, char * add, const char delim ); // Creates a line across the screen void line( const char character ); // Forks off and returns true if its the child int thread( void ); // Adds up the ascii values of chars in an string int strval( char * string ); // Selects appropriate function to call or exits // bool handle_input( gen::functions ); } namespace color { const char normal[] = "\e[m"; const char black[] = "\e[30m"; const char red[] = "\e[31m"; const char green[] = "\e[32m"; const char yellow[] = "\e[33m"; const char purple[] = "\e[34m"; const char pink[] = "\e[35m"; const char blue[] = "\e[36m"; const char grey[] = "\e[90m"; const char lightred[] = "\e[91m"; const char lightgreen[] = "\e[92m"; const char lightyellow[] = "\e[93m"; const char lightpurple[] = "\e[94m"; const char lightpink[] = "\e[95m"; const char lightblue[] = "\e[96m"; } namespace highlight { const char normal[] = "\e[m"; const char black[] = "\e[40m"; const char red[] = "\e[41m"; const char green[] = "\e[42m"; const char yellow[] = "\e[44m"; const char purple[] = "\e[44m"; const char pink[] = "\e[45m"; const char blue[] = "\e[46m"; const char grey[] = "\e[100m"; const char lightred[] = "\e[101m"; const char lightgreen[] = "\e[102m"; const char lightyellow[] = "\e[103m"; const char lightpurple[] = "\e[104m"; const char lightpink[] = "\e[105m"; const char lightblue[] = "\e[106m"; } #endif
true
15cdecad709ed861971354be1a90c3dbe66767da
C++
FunkMonkey/Bound
/Wrapping/Spidermonkey/SpidermonkeyWrapper/include/wrap_helpers/wrap_helpers_x.hpp
UTF-8
888
2.78125
3
[]
no_license
#ifndef WRAP_HELPERS_X_HPP #define WRAP_HELPERS_X_HPP #include <jsapi.h> #include "exceptions.hpp" /** * @namespace jswrap * Contains helper functions for wrapping SpiderMonkey */ namespace jswrap { /** * Checks the number of arguments and throws exception if wrong * * \param given Given number of arguments * \param expected Expected number of arguments */ static void checkNumberOfArguments_x(int given, int expected) { if(given != expected) throw exception("Wrong number of arguments"); } /** * Checks the minimum number of arguments and throws exception if less * * \param given Given number of arguments * \param expected Expected number of arguments */ static void checkMinNumberOfArguments_x(int given, int expected) { if(given < expected) throw exception("Wrong number of arguments"); } } #endif // WRAP_HELPERS_X_HPP
true
444b5b474ab15c663e2341078d083f6a84e804d2
C++
tenegon/genetic-algorithm
/realindividual.cpp
UTF-8
2,805
3.03125
3
[]
no_license
#include "realindividual.h" RealIndividual::RealIndividual(uint t): Individual(t), genes(std::vector<double>(t, 0.0f)), sum(0.0f) { } RealIndividual::~RealIndividual() { } double RealIndividual::getGene(const uint &i) const { if(i < t){ return genes.at(i); } else{ return 0.0f; } } void RealIndividual::setGene(const uint &i, const double &gene) { if(i < t){ sum += gene - genes.at(i); genes.at(i) = gene; } } void RealIndividual::set(Individual *individual) { RealIndividual *real = dynamic_cast<RealIndividual*>(individual); Individual::set(individual); for(uint i = 0; i < t && i < real->getT(); i++){ setGene(i, real->getGene(i)); } sum = real->getSum(); } Individual *RealIndividual::clone() { RealIndividual *individual = new RealIndividual(t); individual->set(this); return individual; } bool RealIndividual::isBetter(Individual *individual) { return fitness < individual->getFitness(); } bool RealIndividual::operator<(const RealIndividual &right) const { return Individual::operator <(right); } bool RealIndividual::operator==(const RealIndividual &right) const { if(Individual::operator ==(right)){ for(uint i = 0; i < t && i < right.getT(); i++){ if(genes.at(i) != right.getGene(i)){ return false; } } return true; } else{ return false; } } bool RealIndividual::operator!=(const RealIndividual &right) const { if(Individual::operator !=(right)){ for(uint i = 0; i < t && i < right.getT(); i++){ if(genes.at(i) == right.getGene(i)){ return false; } } return true; } else{ return false; } } bool RealIndividual::operator>(const RealIndividual &right) const { return Individual::operator >(right); } void RealIndividual::print(std::ostream &os) const { Individual::print(os); os << "\t\t"; uint rt = genes.size(); for(uint i = 0; i < rt; i++){ double gene = genes.at(i); os << gene << "\t"; } os << sum; } std::string RealIndividual::header() const { std::string os(""); os += Individual::header() + "\t"; uint rt = genes.size(); os += "{"; for(uint i = 0; i < rt; i++){ os += "[" + std::to_string(i) + "]"; if(i < rt - 1){ os += ",\t"; } } os += "}\t"; os += "sum"; return os; } double RealIndividual::getSum() const { return sum; } void RealIndividual::setSum(double value) { sum = value; } std::vector<double> RealIndividual::getGenes() const { return genes; } void RealIndividual::setGenes(const std::vector<double> &value) { genes = value; }
true
8d83d0f06ea1e068fc47ad30cd0bd732beb1c9c5
C++
junior-2016/Compiler
/Util.h
UTF-8
1,129
2.953125
3
[]
no_license
// // Created by junior on 19-4-17. // #ifndef COMPILER_UTIL_H #define COMPILER_UTIL_H #include "Compiler.h" namespace Compiler { /** * 判断数值(NUM型)TokenString的具体类型(10进制/16进制/8进制/浮点), * 主要有两个用途: * 一是用于打印NUM Token的信息; * 二是在后面语法分析的时候要真正cast数据的时候判断用. */ enum class NUM_TYPE { DECIMAL, OCT, HEX, FLOAT, DOUBLE }; // 为了限制bool类型取值,建立一个BOOL枚举,取代C语言的bool类型 enum class BOOL { TRUE = true, FALSE = false }; typedef struct empty_struct { } null_t; // 空类型 typedef BOOL bool_t; typedef int32_t int_t; typedef float float_t; typedef double double_t; typedef char char_t; typedef std::string string_t; typedef std::shared_ptr<string_t> string_ptr; inline string_ptr make_string_ptr(const string_t &str) { return std::make_shared<string_t>(str); } NUM_TYPE getNumType(const string_t &tokenString); } #endif //COMPILER_UTIL_H
true
a5e7cbebc18672f1976f097c92b081709c7024dd
C++
FluorineDog/doglib
/doglib/common/iter.h
UTF-8
2,475
3.25
3
[]
no_license
#pragma once #include <unistd.h> #include <type_traits> #include <iterator> namespace doglib { namespace common { template <typename T> class DataIter { public: using difference_type = ssize_t; using value_type = T; using pointer = T*; using reference = T&; using iterator_category = std::random_access_iterator_tag; static_assert(std::is_integral<T>::value, "support integer only"); DataIter(T data) : data(data) {} const T& operator*() const { return data; } DataIter<T>& operator++() { ++data; return *this; } DataIter<T> operator++(int) { auto x = *this; ++data; return std::move(x); } DataIter<T>& operator--() { --data; return *this; } DataIter<T> operator--(int) { auto x = *this; --data; return std::move(x); } // that's why everyone loves spaceship operator bool operator!=(const DataIter<T>& t) const { return data != t.data; } bool operator<(const DataIter<T>& t) const { return data < t.data; } bool operator==(const DataIter<T>& t) const { return !(*this != t); } bool operator>(const DataIter<T>& t) const { return t < *this; } bool operator<=(const DataIter<T>& t) const { return !(t < *this); } bool operator>=(const DataIter<T>& t) const { return !(*this < t); } // for random access, in case for binary search ssize_t operator-(const DataIter<T>& t) const { return data - t.data; } DataIter<T>& operator+=(ssize_t n) { data += (T)n; return *this; } DataIter<T>& operator-=(ssize_t n) { data -= (T)n; return *this; } DataIter<T> operator+(ssize_t n) const { auto tmp = *this; tmp += (T)n; return tmp; } DataIter<T> operator-(ssize_t n) const { auto tmp = *this; tmp -= (T)n; return tmp; } private: T data; }; template <typename T> auto make_iter(T x) -> DataIter<T> { return DataIter<T>(x); } } // namespace common } // namespace doglib //namespace std{ //template <typename T> //// template <> //struct iterator_traits< doglib::common::DataIter<T>> { // using difference_type = ssize_t; // using value_type = T; // using pointer = T*; // using reference = T&; // using iterator_category = std::random_access_iterator_tag; //}; //}
true
0b48bb858142a7244eaed4c8d8199b44cdac3231
C++
shuklasaharsh/DSA-CPP
/DSA-CPP/CodingBlocks/String-Challenges/9.cpp
UTF-8
2,816
3.90625
4
[]
no_license
/* Prateek is an extremely gifted student. He is great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He is not only smart but extraordinarily fast!. One day Prateek was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The i-th digit of the answer is 1 if and only if the i-th digit of the two given numbers differ. In the other case the i-th digit of the answer is 0. Prateek made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate. Input Format The first line contains an integer t , the no. of testcases. There are two inputs in each line. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. Constraints The length of each number doesn't exceed 100. Output Format Write t lines — the corresponding answer to the corresponding input. Do not omit the leading 0s. Sample Input 1 10111 10000 Sample Output 00111 Explanation For the given example, Let str1 = "10111" and str2 = "10000", Value at first position of str1 is 1 and first position str2 is 1, hence according to the rule there will be 0 at the first position of the final ans.Similarly, for second position the value at second position of both of the strings is 0,so , there will be 0 at the second position of the final ans.Similarly, for third position the value at third position of str1 is 1 and str2 is 0,so , there will be 1 at the third position of the final ans and So, on. */ #include <iostream> #include <string> #include <cstring> using namespace std; void actualMain() { string s; getline(cin, s); string str1 = s.substr(0,s.find(" ")); string str2 = s.substr(s.find(" ")+1); for (int i = 0; i < str1.length(); i++) { if (str1[i]==str2[i]) { cout << 0; } else { cout << 1; } } cout << endl; } int main() { int test; cin >> test; cin.get(); for (int i = 0 ; i < test; i++) { actualMain(); } return 0; }
true
f7cd4b218c723941f9568b71a977b9c9fa4830a8
C++
wjddlsy/Algorithm
/Baekjoon/baek_2503_숫자야구/main.cpp
UTF-8
1,163
2.96875
3
[]
no_license
#include <iostream> #include <vector> #include <map> #include <set> #include <tuple> using namespace std; bool isRight(const string& q, const string& n, int s, int b) { int ns=0, nb=0; for(int i=0; i<3; ++i) { for(int j=0; j<3; ++j) { if(n[i] == q[j]) { i==j? ns++ : nb++; } } } return s==ns && nb==b; } int main() { int N; cin>>N; vector<tuple<string, int, int>> games(N); for(auto && [q, s, b]:games) { cin >> q >> s>> b; } int ret = 0; for(int i=1; i<=9; ++i) { for(int j=1; j<=9; ++j) { for(int k=1; k<=9; ++k) { if(i==j || i==k || j==k) continue; string n = to_string(i) + to_string(j) + to_string(k); bool flag = true; for(auto && [q, s, b]:games) { if(!isRight(q, n, s, b)) { flag = false; break; } } ret += flag; } } } cout<<ret; //std::cout << "Hello, World!" << std::endl; return 0; }
true
e0b2b434b840bb397fd152e0c2366860d362c6ae
C++
gkikola/optionpp
/test/tst_result_iterator.cpp
UTF-8
4,579
2.546875
3
[ "BSL-1.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/* Option++ -- read command-line program options * Copyright (C) 2017-2020 Greg Kikola. * * This file is part of Option++. * * Option++ is free software: you can redistribute it and/or modify * it under the terms of the Boost Software License version 1.0. * * Option++ 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 * Boost Software License for more details. * * You should have received a copy of the Boost Software License * along with Option++. If not, see * <https://www.boost.org/LICENSE_1_0.txt>. */ /* Written by Greg Kikola <gkikola@gmail.com>. */ #include <catch2/catch.hpp> #include <optionpp/parser.hpp> #include <optionpp/result_iterator.hpp> using namespace optionpp; TEST_CASE("result_iterator") { parser p; p["help"].short_name('?') .description("Output a usage message and exit."); p['V'].long_name("version") .description("Output the version number and exit."); p["extended-regexp"].short_name('E') .description("Interpret patterns as extended regular expressions"); p["regexp"].short_name('e').argument("PATTERNS", true) .description("Use PATTERNS as the patterns."); p['f'].long_name("file").argument("FILE", true) .description("Obtain PATTERNS from FILE."); p["ignore-case"].short_name('i') .description("Ignore case distinctions in patterns."); SECTION("non_option_iterator") { auto result = p.parse("cmd1 -Eif file.txt cmd2 --version cmd3"); auto it = non_option_iterator{result}; auto it_end = end(it); REQUIRE_THROWS_WITH(*it_end, "tried to dereference a nullptr"); REQUIRE(it->original_text == "cmd1"); REQUIRE_FALSE(it->is_option); REQUIRE((it++)->original_text == "cmd1"); REQUIRE(it->original_text == "cmd2"); REQUIRE_FALSE(it->is_option); REQUIRE((it++)->original_text == "cmd2"); REQUIRE(it->original_text == "cmd3"); REQUIRE_FALSE(it->is_option); REQUIRE((it++)->original_text == "cmd3"); REQUIRE(it == it_end); REQUIRE(it_end == it); REQUIRE(it_end == it_end); REQUIRE(it == it); REQUIRE_THROWS_WITH(*it, "tried to dereference past-the-end iterator"); REQUIRE((it--) == it_end); REQUIRE(it->original_text == "cmd3"); REQUIRE((it--)->original_text == "cmd3"); REQUIRE(it->original_text == "cmd2"); REQUIRE((--it)->original_text == "cmd1"); } SECTION("non_option_const_iterator") { const auto result = p.parse("--file output.txt command another command --ignore-case"); auto it = non_option_const_iterator{result}; auto it_end = end(it); REQUIRE_THROWS_WITH(*it_end, "tried to dereference a nullptr"); REQUIRE(it != it_end); REQUIRE(it->original_text == "command"); REQUIRE_FALSE(it->is_option); REQUIRE((++it)->original_text == "another"); REQUIRE_FALSE(it->is_option); REQUIRE((++it)->original_text == "command"); REQUIRE_FALSE(it->is_option); REQUIRE(++it == it_end); REQUIRE(it == it_end); REQUIRE(it_end == it); REQUIRE(it_end == it_end); REQUIRE(it == it); REQUIRE_THROWS_WITH(*it, "tried to dereference past-the-end iterator"); REQUIRE((--it)->original_text == "command"); REQUIRE(it != it_end); REQUIRE(it_end != it); } SECTION("option_iterator") { auto result = p.parse("cmd1 -Eif file.txt cmd2 --version cmd3"); auto it = option_iterator{result}; auto it_end = end(it); REQUIRE_THROWS_WITH(*it_end, "tried to dereference a nullptr"); REQUIRE(it != it_end); REQUIRE(it->original_text == "-E"); REQUIRE((++it)->original_text == "-i"); REQUIRE((++it)->original_text == "-f file.txt"); REQUIRE((++it)->original_text == "--version"); REQUIRE(++it == it_end); REQUIRE_THROWS_WITH(*it, "tried to dereference past-the-end iterator"); } SECTION("option_const_iterator") { const auto result = p.parse("--file output.txt command another command --ignore-case"); auto it = option_const_iterator{result}; auto it_end = end(it); REQUIRE_THROWS_WITH(*it_end, "tried to dereference a nullptr"); REQUIRE(it != it_end); REQUIRE(it->original_text == "--file output.txt"); REQUIRE((++it)->original_text == "--ignore-case"); REQUIRE(++it == it_end); REQUIRE_THROWS_WITH(*it, "tried to dereference past-the-end iterator"); REQUIRE(--it != it_end); REQUIRE(it->original_text == "--ignore-case"); REQUIRE((it--)->original_text == "--ignore-case"); REQUIRE(it->original_text == "--file output.txt"); } }
true
1bbebe67491903c3aed8c2e08b16fa95c1db84f5
C++
Sriram-96/SPOJ
/HACKRNDM.cpp
UTF-8
381
2.71875
3
[]
no_license
# include<bits/stdc++.h> using namespace std; int main() { int n,k,i,element; cin>>n>>k; int a[n]; unordered_set<int> hashmap; for(i=0;i<n;i++) { cin>>a[i]; hashmap.insert(a[i]); } int count=0; for(i=0;i<n;i++) { if(hashmap.count(a[i]-k) == 1) { count++; } if(hashmap.count(a[i]+k) == 1) { count++; } } cout<<count/2; }
true
a0e130bc23a09d3f9363679310b84c38bdb83648
C++
CJHMPower/Fetch_Leetcode
/data/Submission/253 Meeting Rooms II/Meeting Rooms II_1.cpp
UTF-8
1,191
2.921875
3
[]
no_license
//-*- coding:utf-8 -*- // Generated by the Fetch-Leetcode project on the Github // https://github.com/CJHMPower/Fetch-Leetcode/ // 253 Meeting Rooms II // https://leetcode.com//problems/meeting-rooms-ii/description/ // Fetched at 2018-07-24 // Submitted 5 months ago // Runtime: 15 ms // This solution defeats 8.0% cpp solutions /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: int minMeetingRooms(vector<Interval>& intervals) { if (intervals.empty()) { return 0; } sort(intervals.begin(), intervals.end(), [](Interval& a, Interval& b) { return a.start < b.start; }); vector<vector<Interval>> room; room.push_back({intervals[0]}); for (int i = 1; i < intervals.size(); i++) { int j = 0; for (; j < room.size(); j++) { if (room[j].back().end <= intervals[i].start) { room[j].push_back(intervals[i]); break; } } if (j >= room.size()) { room.push_back({intervals[i]}); } } return room.size(); } };
true
1ffa24e72715137911ab9dc37045e795fd576897
C++
andresthor/eda031_projekt
/src/connection/exceptions/ngdoesnotexistexception.h
UTF-8
684
2.6875
3
[]
no_license
/* --------------------------------------------------------------------------- ** Project for the course EDA031 at Lunds University, spring 2016. ** ** ngdoesnotexistexception.h ** ** Exception to be thrown when the client tries to access a non-existant ** newsgroup. ** ** Authors: Andres Saemundsson, Anton Friberg, Oscar Gunneson ** -------------------------------------------------------------------------*/ #ifndef NG_DOES_NOT_EXIST_EXCEPTION_H #define NG_DOES_NOT_EXIST_EXCEPTION_H #include <string> struct NGDoesNotExistException{ NGDoesNotExistException(std::string ngId) { msg = "The newsgroup with id " + ngId + " does not exist."; } std::string msg; }; #endif // NG_DOES_NOT_EXIST_EXCEPTION_H
true
33382842e5bf781ba0c487772709cdd2c622d2b5
C++
venture21/raspberryPiEx
/qt5/CustomWidget/exRadioButton/main.cpp
UTF-8
958
2.65625
3
[]
no_license
#include <QApplication> #include <QWidget> #include <QRadioButton> #include <QButtonGroup> void DrawRadioButton(); int main(int argc, char *argv[]) { QApplication a(argc, argv); DrawRadioButton(); return a.exec(); } void DrawRadioButton() { QWidget *widget = new QWidget(0); QButtonGroup *bg = new QButtonGroup(widget); // &1 : & 를 붙일 경우 ALT + 1 을 단축키로 지정 할 수 있다. QRadioButton *rb1 = new QRadioButton("라디오 옵션 &1", widget); rb1->move(10,10); bg->addButton(rb1); QRadioButton *rb2 = new QRadioButton("라디오 옵션 &2", widget); rb2->move(10,30); bg->addButton(rb2); QRadioButton *rb3 = new QRadioButton("라디오 옵션 &3", widget); rb3->move(10,50); bg->addButton(rb3); QRadioButton *rb4 = new QRadioButton("라디오 옵션 &4", widget); rb4->move(10,70); bg->addButton(rb4); widget->resize(150,110); widget->show(); }
true
c68277e5306a54265cc02d44e70bb58e621d4756
C++
ToTYToT/learn_c-
/c++_009/String.cc
UTF-8
2,724
3.375
3
[]
no_license
/// /// @file String.cc /// @author lemon(haohb13@gmail.com) /// @date 2016-10-26 09:59:43 /// #include <string.h> #include <iostream> using std::ostream; using std::istream; using std::cin; using std::cout; using std::endl; class String { friend ostream & operator<<(ostream & os, const String & rhs); friend istream & operator>>(istream & is, String & rhs); public: String(); String(const char * pstr); String(const String & rhs); ~String(); String & operator=(const String & rhs); String & operator=(const char * rhs); String & operator+=(const String & rhs); String & operator+=(const char * rhs); private: char * _pstr; }; String::String() : _pstr(new char[1]) { cout << "String()" << endl; } String::String(const char * pstr) : _pstr(new char[strlen(pstr) + 1]) { strcpy(_pstr, pstr);//深拷贝 cout << "String(const char *)" << endl; } String::String(const String & rhs) : _pstr(new char[strlen(rhs._pstr) + 1]) { strcpy(_pstr, rhs._pstr); cout << "String(const String &)" << endl; } String::~String() { delete [] _pstr; cout << "~String()" << endl; } String & String::operator=(const String & rhs) { //strcpy(_pstr, rhs._pstr); if(this != & rhs) //1. 自复制 { delete [] _pstr;//2. 删除左操作数指针所指向的原来的空间 _pstr = new char[strlen(rhs._pstr) + 1];//3. 再去复制右操作数的内容, 执行的是深拷贝 strcpy(_pstr, rhs._pstr); } return *this; } String & String::operator=(const char * rhs) { *this = String(rhs); return *this; } String & String::operator+=(const String & rhs) { int size = strlen(_pstr) + strlen(rhs._pstr) + 1; char * tmp = new char [size];//1. 先开辟足够大的空间 strcpy(tmp, _pstr);//2. 然后再把左操作数的内容复制过来 strcat(tmp, rhs._pstr);//3. 最后再把右操作数的内容复制过来 delete [] _pstr;//4. 释放左操作数原来开辟的空间 _pstr = tmp;//5. 再将左操作数的指针指向最新开辟空间 return *this; } // 代码复用 String & String::operator+=(const char * rhs) { *this += String(rhs); return *this; } ostream & operator<<(ostream & os, const String & rhs) { os << rhs._pstr; return os; } istream & operator>>(istream & is, String & rhs) { char buff[65535];// 1. 先开辟一个缓冲区,栈空间 memset(buff, 0, sizeof(buff)); //is >> buff; is.getline(buff, sizeof(buff));//2. 考虑空格 delete [] rhs._pstr;//3. 释放右操作数原来的空间 rhs._pstr = new char[strlen(buff) + 1]; strcpy(rhs._pstr, buff);//4. 再去进行深拷贝 return is; } int main(void) { String s1; cout << s1 << endl; String s2 = "hello"; String s3 = "world"; s2 += s3; //cout << s2 << endl; cin >> s2; cout << s2 << endl; }
true
abc0daf132caf52f7c4c1aaa52f6a6694e92b09d
C++
lucasbivar/object-oriented-programming
/U2A4/7/Imovel.cpp
UTF-8
371
3.09375
3
[]
no_license
#include "Imovel.h" Imovel::Imovel(string address, double price) { setAddress(address); setPrice(price < 0 ? 0 : price); } void Imovel::setAddress(string address){ this->address = address; } string Imovel::getAddress() const { return address; } void Imovel::setPrice(double price){ this->price = price; } double Imovel::getPrice() const { return price; }
true
1aa2053d6b869545c1e693b3cf3bbb16c5a133f2
C++
skyformat99/text
/include/boost/text/detail/iterator.hpp
UTF-8
20,654
3.375
3
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
#ifndef BOOST_TEXT_DETAIL_ITERATOR_HPP #define BOOST_TEXT_DETAIL_ITERATOR_HPP #include <iterator> namespace boost { namespace text { namespace detail { struct const_reverse_char_iterator; struct reverse_char_iterator { using value_type = char; using difference_type = int; using pointer = char *; using reference = char &; using iterator_category = std::random_access_iterator_tag; constexpr reverse_char_iterator() noexcept : ptr_(nullptr) {} explicit constexpr reverse_char_iterator(char * ptr) noexcept : ptr_(ptr) {} constexpr char * base() const noexcept { return ptr_ + 1; } constexpr reference operator*() const noexcept { return *ptr_; } constexpr value_type operator[](difference_type n) const noexcept { return ptr_[-n]; } BOOST_TEXT_CXX14_CONSTEXPR reverse_char_iterator & operator++() noexcept { --ptr_; return *this; } BOOST_TEXT_CXX14_CONSTEXPR reverse_char_iterator operator++(int)noexcept { reverse_char_iterator retval = *this; --ptr_; return retval; } BOOST_TEXT_CXX14_CONSTEXPR reverse_char_iterator & operator+=(difference_type n) noexcept { ptr_ -= n; return *this; } BOOST_TEXT_CXX14_CONSTEXPR reverse_char_iterator & operator--() noexcept { ++ptr_; return *this; } BOOST_TEXT_CXX14_CONSTEXPR reverse_char_iterator operator--(int)noexcept { reverse_char_iterator retval = *this; ++ptr_; return retval; } BOOST_TEXT_CXX14_CONSTEXPR reverse_char_iterator & operator-=(difference_type n) noexcept { ptr_ += n; return *this; } friend constexpr bool operator==( reverse_char_iterator lhs, reverse_char_iterator rhs) noexcept { return lhs.ptr_ == rhs.ptr_; } friend constexpr bool operator!=( reverse_char_iterator lhs, reverse_char_iterator rhs) noexcept { return lhs.ptr_ != rhs.ptr_; } friend constexpr bool operator<(reverse_char_iterator lhs, reverse_char_iterator rhs) noexcept { return rhs.ptr_ < lhs.ptr_; } friend constexpr bool operator<=( reverse_char_iterator lhs, reverse_char_iterator rhs) noexcept { return rhs.ptr_ <= lhs.ptr_; } friend constexpr bool operator>(reverse_char_iterator lhs, reverse_char_iterator rhs) noexcept { return lhs.ptr_ < rhs.ptr_; } friend constexpr bool operator>=( reverse_char_iterator lhs, reverse_char_iterator rhs) noexcept { return lhs.ptr_ <= rhs.ptr_; } inline constexpr bool operator==(const_reverse_char_iterator rhs) const noexcept; inline constexpr bool operator!=(const_reverse_char_iterator rhs) const noexcept; inline constexpr bool operator<(const_reverse_char_iterator rhs) const noexcept; inline constexpr bool operator<=(const_reverse_char_iterator rhs) const noexcept; inline constexpr bool operator>(const_reverse_char_iterator rhs) const noexcept; inline constexpr bool operator>=(const_reverse_char_iterator rhs) const noexcept; friend BOOST_TEXT_CXX14_CONSTEXPR reverse_char_iterator operator+(reverse_char_iterator lhs, difference_type rhs) noexcept { return lhs += rhs; } friend BOOST_TEXT_CXX14_CONSTEXPR reverse_char_iterator operator+(difference_type lhs, reverse_char_iterator rhs) noexcept { return rhs += lhs; } friend BOOST_TEXT_CXX14_CONSTEXPR reverse_char_iterator operator-(reverse_char_iterator lhs, difference_type rhs) noexcept { return lhs -= rhs; } friend BOOST_TEXT_CXX14_CONSTEXPR reverse_char_iterator operator-(difference_type lhs, reverse_char_iterator rhs) noexcept { return rhs -= lhs; } friend constexpr difference_type operator-(reverse_char_iterator lhs, reverse_char_iterator rhs) noexcept { return rhs.ptr_ - lhs.ptr_; } private: char * ptr_; friend struct const_reverse_char_iterator; }; struct const_reverse_char_iterator { using value_type = char; using difference_type = int; using pointer = char const *; using reference = char const; using iterator_category = std::random_access_iterator_tag; constexpr const_reverse_char_iterator() noexcept : ptr_(nullptr) {} explicit constexpr const_reverse_char_iterator( char const * ptr) noexcept : ptr_(ptr) {} constexpr const_reverse_char_iterator( reverse_char_iterator rhs) noexcept : ptr_(rhs.ptr_ + 1) {} constexpr char const * base() const noexcept { return ptr_; } constexpr reference operator*() const noexcept { return *(ptr_ - 1); } constexpr value_type operator[](difference_type n) const noexcept { return ptr_[-n - 1]; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_char_iterator & operator++() noexcept { --ptr_; return *this; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_char_iterator operator++(int)noexcept { const_reverse_char_iterator retval = *this; --ptr_; return retval; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_char_iterator & operator+=(difference_type n) noexcept { ptr_ -= n; return *this; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_char_iterator & operator--() noexcept { ++ptr_; return *this; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_char_iterator operator--(int)noexcept { const_reverse_char_iterator retval = *this; ++ptr_; return retval; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_char_iterator & operator-=(difference_type n) noexcept { ptr_ += n; return *this; } friend constexpr bool operator==( const_reverse_char_iterator lhs, const_reverse_char_iterator rhs) noexcept { return lhs.ptr_ == rhs.ptr_; } friend constexpr bool operator!=( const_reverse_char_iterator lhs, const_reverse_char_iterator rhs) noexcept { return lhs.ptr_ != rhs.ptr_; } friend constexpr bool operator<( const_reverse_char_iterator lhs, const_reverse_char_iterator rhs) noexcept { return rhs.ptr_ < lhs.ptr_; } friend constexpr bool operator<=( const_reverse_char_iterator lhs, const_reverse_char_iterator rhs) noexcept { return rhs.ptr_ <= lhs.ptr_; } friend constexpr bool operator>( const_reverse_char_iterator lhs, const_reverse_char_iterator rhs) noexcept { return lhs.ptr_ < rhs.ptr_; } friend constexpr bool operator>=( const_reverse_char_iterator lhs, const_reverse_char_iterator rhs) noexcept { return lhs.ptr_ <= rhs.ptr_; } inline constexpr bool operator==(reverse_char_iterator rhs) const noexcept; inline constexpr bool operator!=(reverse_char_iterator rhs) const noexcept; inline constexpr bool operator<(reverse_char_iterator rhs) const noexcept; inline constexpr bool operator<=(reverse_char_iterator rhs) const noexcept; inline constexpr bool operator>(reverse_char_iterator rhs) const noexcept; inline constexpr bool operator>=(reverse_char_iterator rhs) const noexcept; friend BOOST_TEXT_CXX14_CONSTEXPR const_reverse_char_iterator operator+(const_reverse_char_iterator lhs, difference_type rhs) noexcept { return lhs += rhs; } friend BOOST_TEXT_CXX14_CONSTEXPR const_reverse_char_iterator operator+(difference_type lhs, const_reverse_char_iterator rhs) noexcept { return rhs += lhs; } friend BOOST_TEXT_CXX14_CONSTEXPR const_reverse_char_iterator operator-(const_reverse_char_iterator lhs, difference_type rhs) noexcept { return lhs -= rhs; } friend BOOST_TEXT_CXX14_CONSTEXPR const_reverse_char_iterator operator-(difference_type lhs, const_reverse_char_iterator rhs) noexcept { return rhs -= lhs; } friend constexpr difference_type operator-( const_reverse_char_iterator lhs, const_reverse_char_iterator rhs) noexcept { return rhs.ptr_ - lhs.ptr_; } private: char const * ptr_; friend struct reverse_char_iterator; }; inline constexpr bool reverse_char_iterator:: operator==(const_reverse_char_iterator rhs) const noexcept { return ptr_ == rhs.ptr_ - 1; } inline constexpr bool reverse_char_iterator:: operator!=(const_reverse_char_iterator rhs) const noexcept { return ptr_ != rhs.ptr_ - 1; } inline constexpr bool reverse_char_iterator:: operator<(const_reverse_char_iterator rhs) const noexcept { return rhs.ptr_ - 1 < ptr_; } inline constexpr bool reverse_char_iterator:: operator<=(const_reverse_char_iterator rhs) const noexcept { return rhs.ptr_ - 1 <= ptr_; } inline constexpr bool reverse_char_iterator:: operator>(const_reverse_char_iterator rhs) const noexcept { return ptr_ < rhs.ptr_ - 1; } inline constexpr bool reverse_char_iterator:: operator>=(const_reverse_char_iterator rhs) const noexcept { return ptr_ <= rhs.ptr_ - 1; } inline constexpr bool const_reverse_char_iterator:: operator==(reverse_char_iterator rhs) const noexcept { return ptr_ == rhs.ptr_ - 1; } inline constexpr bool const_reverse_char_iterator:: operator!=(reverse_char_iterator rhs) const noexcept { return ptr_ != rhs.ptr_ - 1; } inline constexpr bool const_reverse_char_iterator:: operator<(reverse_char_iterator rhs) const noexcept { return rhs.ptr_ - 1 < ptr_; } inline constexpr bool const_reverse_char_iterator:: operator<=(reverse_char_iterator rhs) const noexcept { return rhs.ptr_ - 1 <= ptr_; } inline constexpr bool const_reverse_char_iterator:: operator>(reverse_char_iterator rhs) const noexcept { return ptr_ < rhs.ptr_ - 1; } inline constexpr bool const_reverse_char_iterator:: operator>=(reverse_char_iterator rhs) const noexcept { return ptr_ <= rhs.ptr_ - 1; } struct const_repeated_chars_iterator { using value_type = char; using difference_type = std::ptrdiff_t; using pointer = char const *; using reference = char const; using iterator_category = std::random_access_iterator_tag; constexpr const_repeated_chars_iterator() noexcept : first_(nullptr), size_(0), n_(0) {} constexpr const_repeated_chars_iterator( char const * first, difference_type size, difference_type n) noexcept : first_(first), size_(size), n_(n) {} constexpr reference operator*() const noexcept { return first_[n_ % size_]; } constexpr value_type operator[](difference_type n) const noexcept { return first_[(n_ + n) % size_]; } BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator & operator++() noexcept { ++n_; return *this; } BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator operator++(int)noexcept { const_repeated_chars_iterator retval = *this; ++*this; return retval; } BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator & operator+=(difference_type n) noexcept { n_ += n; return *this; } BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator & operator--() noexcept { --n_; return *this; } BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator operator--(int)noexcept { const_repeated_chars_iterator retval = *this; --*this; return retval; } BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator & operator-=(difference_type n) noexcept { n_ -= n; return *this; } friend constexpr bool operator==( const_repeated_chars_iterator lhs, const_repeated_chars_iterator rhs) noexcept { return lhs.first_ == rhs.first_ && lhs.n_ == rhs.n_; } friend constexpr bool operator!=( const_repeated_chars_iterator lhs, const_repeated_chars_iterator rhs) noexcept { return !(lhs == rhs); } friend constexpr bool operator<( const_repeated_chars_iterator lhs, const_repeated_chars_iterator rhs) noexcept { return lhs.first_ == rhs.first_ && lhs.n_ < rhs.n_; } friend constexpr bool operator<=( const_repeated_chars_iterator lhs, const_repeated_chars_iterator rhs) noexcept { return lhs == rhs || lhs < rhs; } friend constexpr bool operator>( const_repeated_chars_iterator lhs, const_repeated_chars_iterator rhs) noexcept { return rhs < lhs; } friend constexpr bool operator>=( const_repeated_chars_iterator lhs, const_repeated_chars_iterator rhs) noexcept { return lhs <= rhs; } friend BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator operator+( const_repeated_chars_iterator lhs, difference_type rhs) noexcept { return lhs += rhs; } friend BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator operator+( difference_type lhs, const_repeated_chars_iterator rhs) noexcept { return rhs += lhs; } friend BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator operator-( const_repeated_chars_iterator lhs, difference_type rhs) noexcept { return lhs -= rhs; } friend BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator operator-( difference_type lhs, const_repeated_chars_iterator rhs) noexcept { return rhs -= lhs; } friend constexpr difference_type operator-( const_repeated_chars_iterator lhs, const_repeated_chars_iterator rhs) noexcept { return lhs.n_ - rhs.n_; } private: char const * first_; difference_type size_; difference_type n_; }; struct const_reverse_repeated_chars_iterator { using value_type = char; using difference_type = std::ptrdiff_t; using pointer = char const *; using reference = char const; using iterator_category = std::random_access_iterator_tag; constexpr const_reverse_repeated_chars_iterator() noexcept : base_() {} explicit constexpr const_reverse_repeated_chars_iterator( const_repeated_chars_iterator it) noexcept : base_(it) {} constexpr const_repeated_chars_iterator base() const { return base_; } BOOST_TEXT_CXX14_CONSTEXPR reference operator*() const noexcept { return *(base_ - 1); } constexpr value_type operator[](difference_type n) const noexcept { return base_[-n - 1]; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_repeated_chars_iterator & operator++() noexcept { --base_; return *this; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_repeated_chars_iterator operator++(int)noexcept { const_reverse_repeated_chars_iterator retval = *this; --base_; return retval; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_repeated_chars_iterator & operator+=(difference_type n) noexcept { base_ -= n; return *this; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_repeated_chars_iterator & operator--() noexcept { ++base_; return *this; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_repeated_chars_iterator operator--(int)noexcept { const_reverse_repeated_chars_iterator retval = *this; ++base_; return retval; } BOOST_TEXT_CXX14_CONSTEXPR const_reverse_repeated_chars_iterator & operator-=(difference_type n) noexcept { base_ += n; return *this; } friend constexpr bool operator==( const_reverse_repeated_chars_iterator lhs, const_reverse_repeated_chars_iterator rhs) noexcept { return lhs.base_ == rhs.base_; } friend constexpr bool operator!=( const_reverse_repeated_chars_iterator lhs, const_reverse_repeated_chars_iterator rhs) noexcept { return !(lhs == rhs); } friend constexpr bool operator<( const_reverse_repeated_chars_iterator lhs, const_reverse_repeated_chars_iterator rhs) noexcept { return rhs.base_ < lhs.base_; } friend constexpr bool operator<=( const_reverse_repeated_chars_iterator lhs, const_reverse_repeated_chars_iterator rhs) noexcept { return rhs.base_ <= lhs.base_; } friend constexpr bool operator>( const_reverse_repeated_chars_iterator lhs, const_reverse_repeated_chars_iterator rhs) noexcept { return rhs.base_ > lhs.base_; } friend constexpr bool operator>=( const_reverse_repeated_chars_iterator lhs, const_reverse_repeated_chars_iterator rhs) noexcept { return rhs.base_ >= lhs.base_; } friend BOOST_TEXT_CXX14_CONSTEXPR const_reverse_repeated_chars_iterator operator+( const_reverse_repeated_chars_iterator lhs, difference_type rhs) noexcept { return lhs += rhs; } friend BOOST_TEXT_CXX14_CONSTEXPR const_reverse_repeated_chars_iterator operator+( difference_type lhs, const_reverse_repeated_chars_iterator rhs) noexcept { return rhs += lhs; } friend BOOST_TEXT_CXX14_CONSTEXPR const_reverse_repeated_chars_iterator operator-( const_reverse_repeated_chars_iterator lhs, difference_type rhs) noexcept { return lhs -= rhs; } friend BOOST_TEXT_CXX14_CONSTEXPR const_reverse_repeated_chars_iterator operator-( difference_type lhs, const_reverse_repeated_chars_iterator rhs) noexcept { return rhs -= lhs; } friend constexpr difference_type operator-( const_reverse_repeated_chars_iterator lhs, const_reverse_repeated_chars_iterator rhs) noexcept { return rhs.base_ - lhs.base_; } private: const_repeated_chars_iterator base_; }; }}} #endif
true
2ea624d96e128f2b1ff0fa8d3d7d956955be524e
C++
9sheng/leetcode
/19.remove-nth-node-from-end-of-list.cpp
UTF-8
1,103
3.5
4
[]
no_license
#include "testharness.h" #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { if (head == NULL || n <= 0) return head; if (head->next == NULL && n > 0) return NULL; ListNode* ptr = head; for (int i = 0; i < n; i++) { // if (ptr == NULL) return head; ptr = ptr->next; } if (ptr == NULL) return head->next; ListNode* ptrToRm = head; while (ptr->next != NULL) { ptr = ptr->next; ptrToRm = ptrToRm->next; } if (ptrToRm->next != NULL) ptrToRm->next = ptrToRm->next->next; // we should delete ptrToRm return head; } }; TEST(Solution, test) { ListNode n1(1); ListNode n2(2); n1.next = &n2; ListNode* ptr = removeNthFromEnd(&n1, 2); while (ptr != NULL) { std::cout << ptr->val << std::endl; ptr = ptr->next; } ASSERT_EQ(2, 1+1); }
true
5bdfb424840de0d049b8b91d9f28123e9893a5d1
C++
igorsan98v2/digitTempLCD
/LBTemp.ino
UTF-8
2,895
2.78125
3
[]
no_license
#include <MsTimer2.h> class LedControl{ private: byte *pins; byte *comPins; byte numbers[10] = { B11111100, B11000000, B10011111, B11001110, B11100010, B01101110, B01111110, B11000100, B11111110, B11101110}; bool isAnnode; int8_t forPINS; int8_t forCOMs; byte number[5]={0,0,0,0,0}; void parseToLED(int num){ for(int i=4;i>=0;i--){ number[i] = num%10; num = num/10; } } void showNumber(int num){ for(int i=0;i<7;i++){ //Аннод - лоу ,катод - хай if(bitRead(numbers[num],7-i)==forPINS){ digitalWrite(pins[i],HIGH); } else{ digitalWrite(pins[i],LOW); } } } void changeComPin(){ static byte i=0; static bool OFF=(isAnnode)?LOW:HIGH; for(int j=0;j<5;j++){ if(j!=i){ digitalWrite(comPins[j],OFF); } else{ digitalWrite(comPins[j],forCOMs); } } if(++i==5){ i=0; } } public: LedControl(byte *pins ,byte *comPins,bool isAnnodCom ){ this->pins = new byte[7]; this->comPins = new byte[5]; for(byte i=0;i<7;i++){ this->pins[i] = pins[i]; } for(byte i=0;i<5;i++){ this->comPins[i] =comPins[i]; } isAnnode=isAnnodCom; if(isAnnode){ forPINS=LOW; forCOMs=HIGH; } else { forPINS=HIGH; forCOMs=LOW; } } void showValue(int num) { parseToLED(num); for(int i=0;i<5;i++){ showNumber(number[i]); changeComPin(); delay(5); } } }; class TempSensor{ private: byte readPin; public: TempSensor(byte readPin){ this->readPin=readPin; } float getValue(){ int reading = analogRead(readPin); float voltage = reading * 5.0; voltage /= 1024.0; float temperatureC = (voltage - 0.5) * 100 ; return temperatureC; } }; // переменная для хранения значения текущей цифры int value = 1234; // byte pins[7]={2,3,4,5,6,7,8}; //byte comPins[5]={9,10,11,12,13}; byte pins[7]={2,3,4,5,6,7,8}; byte comPins[5]={10,11,12,13,9};//9-посл 10 е // byte comPins[5]={10,11,12,13,9};//9-посл 10 е LedControl *lc; TempSensor *temp; void updateValue(){ value= temp->getValue(); } void setup() { for(int i=0;i<7;i++){ pinMode(pins[i],OUTPUT); } for(int i=0;i<5;i++){ pinMode(comPins[i],OUTPUT); } lc = new LedControl(pins,comPins,false); temp = new TempSensor(A1); MsTimer2::set(500, updateValue); // задаем период прерывания по таймеру 500 мс MsTimer2::start(); // Сконфигурировать контакты как выходы } void loop() { lc->showValue(value); }
true
4234389446d230b592a4abf5079a30b54cfa0510
C++
jinwookh/fileproject2
/ConsoleApplication1/member.h
UTF-8
1,267
2.859375
3
[]
no_license
#pragma once #include <iostream> #include <string> #include "delim.h" #define MEMBERID 10 #define MEMBERPASS 10 #define MEMBERPHONE 13 #define MEMBERMILEAGE 10 #define STDMAXBUF 256 using namespace std; class Member { string id; string password; string name; string phoneNumber; string address; char mileage[10]; public: Member(); Member(const string new_id); Member(const Member & s); Member & operator = (const Member &s); bool operator == (const Member &s); bool operator != (const Member &s); friend istream & operator >> (istream &is, Member &s); friend ostream & operator << (ostream &os, Member &s); string bring_id() { return id; } void update_id(const string new_id) { id = new_id; } void update_name(const string new_name) { name = new_name; } void update_password(const string new_number) { password =new_number; } void update_phoneNumber(const string new_phoneNumber) { phoneNumber = new_phoneNumber; } void update_address(const string new_address) { address = new_address; } void update_mileage(const char *new_mileage) { memcpy(mileage, new_mileage, 10); } bool Pack(IOBuffer & Buffer) const; bool Unpack(IOBuffer &); }; istream & operator >> (istream &is, Member &s); ostream & operator << (ostream &is, Member &s);
true
974310493b5c74cf5668d379a82ac701889f23bd
C++
mdqyy/FeatureDetection
/libTracking/src/tracking/DensityPositionExtractor.cpp
UTF-8
2,406
2.921875
3
[]
no_license
/* * DensityPositionExtractor.cpp * * Created on: 19.07.2012 * Author: poschmann */ #include "tracking/DensityPositionExtractor.h" #include "tracking/Rectangle.h" #include <iostream> namespace tracking { DensityPositionExtractor::DensityPositionExtractor(int bandwidth) : invertedBandwidth(1.0 / bandwidth), invertedBandwidthProduct(invertedBandwidth * invertedBandwidth * invertedBandwidth) {} DensityPositionExtractor::~DensityPositionExtractor() {} boost::optional<Sample> DensityPositionExtractor::extract(const vector<Sample>& samples) { if (samples.size() == 0) return boost::optional<Sample>(); // compute start value (mean) double x = 0; double y = 0; double s = 0; for (vector<Sample>::const_iterator sit = samples.begin(); sit < samples.end(); ++sit) { x += sit->getX(); y += sit->getY(); s += sit->getSize(); } Sample point((int)(x / samples.size() + 0.5), (int)(y / samples.size() + 0.5), (int)(s / samples.size() + 0.5)); Sample oldPoint; // iteratively compute densest point x = 0, y = 0, s = 0; int i = 0; double weightSum = 0; do { oldPoint = point; for (vector<Sample>::const_iterator sit = samples.begin(); sit < samples.end(); ++sit) { double weight = sit->getWeight() * getScaledKernelValue(*sit, point); x += weight * sit->getX(); y += weight * sit->getY(); s += weight * sit->getSize(); weightSum += weight; } point.setX((int)(x / weightSum + 0.5)); point.setY((int)(y / weightSum + 0.5)); point.setSize((int)(s / weightSum + 0.5)); ++i; } while (i < 100 && point.getX() != oldPoint.getX() && point.getY() != oldPoint.getY() && point.getSize() != oldPoint.getSize()); if (i >= 100) std::cerr << "too many iterations: (" << point.getX() << ", " << point.getY() << ", " << point.getSize() << ") <> (" << oldPoint.getX() << ", " << oldPoint.getY() << ", " << oldPoint.getSize() << ")" << std::endl; point.setWeight(computeDensity(samples, point)); return optional<Sample>(point); } double DensityPositionExtractor::computeDensity(const vector<Sample>& samples, const Sample& position) { double kernelValueSum = 0; double weightSum = 0; for (vector<Sample>::const_iterator sit = samples.begin(); sit < samples.end(); ++sit) { kernelValueSum += sit->getWeight() * getScaledKernelValue(*sit, position); weightSum += sit->getWeight(); } return kernelValueSum / weightSum; } } /* namespace tracking */
true
83ff2226dfddf2228c9c014528c75ea1a77e42e9
C++
pasolano/pong
/src/player.cpp
UTF-8
3,262
3.296875
3
[]
no_license
#include <string> #include "player.h" // constructor Player::Player(sf::RenderWindow &app, Game &gameObj) { this->window = &app; this->game = &gameObj; // define score if (!this->font.loadFromFile("../data/font.ttf")) { throw "Failed to load font from file"; } this->scoreText.setFont(this->font); this->scoreText.setCharacterSize(30); this->scoreText.setFillColor(sf::Color::White); this->scoreText.setStyle(sf::Text::Regular); this->scoreText.setPosition(10, 10); this->scoreText.setString("0 0"); }; // tells game logic the player's inputs void Player::update() { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) this->game->playerInput = Up; else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) this->game->playerInput = Down; else this->game->playerInput = None; if (sf::Keyboard::isKeyPressed(sf::Keyboard::R)) this->game->restart(); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) this->window->close(); }; // draws any drawable object to current window void Player::draw(sf::Drawable &drawable) { this->window->draw(drawable); }; // calls draw() on all of our objects for the player view void Player::drawAll() { this->scoreText.setString(std::to_string(this->game->score.first) + " " + std::to_string(this->game->score.second)); this->draw(this->scoreText); this->draw(this->game->playerPaddle.shape); this->draw(this->game->aiPaddle.shape); this->draw(this->game->ball.shape); for (int i = 0; i < this->game->obstacles.size(); i++) { this->draw(this->game->obstacles.at(i)->shape); } }; // draws the message saying who won the game void Player::gameOver(int whoWon) { sf::Text gameOverMsg; gameOverMsg.setFont(this->font); gameOverMsg.setCharacterSize(80); gameOverMsg.setFillColor(sf::Color::White); gameOverMsg.setStyle(sf::Text::Regular); gameOverMsg.setPosition(15, 15); std::string winner; if (whoWon) winner = "AI"; else winner = "Player"; gameOverMsg.setString(winner + " won!\nPress \'r\' to restart\nPress \'q\' to quit"); this->draw(gameOverMsg); }; // make sound if the passed flag is true // game logic owns the flags and changes when collisions occur void Player::makeSound(std::string filename, bool &flag) { if (flag) { static sf::SoundBuffer buffer; if (!buffer.loadFromFile("../data/" + filename + ".wav")) throw "Could not load sound"; static sf::Sound sound; sound.setBuffer(buffer); sound.play(); flag = false; } } // call sound() on all of our sounds and flags from game logic void Player::sounds() { this->makeSound("beep", this->game->coll); this->makeSound("ping", this->game->playerScored); this->makeSound("error", this->game->aiScored); } // method that updates entire player view // called from main loop void Player::updateView() { auto score = this->game->score; if (score.first >= 11) this->gameOver(0); // 0 means player won else if (score.second >= 11) this->gameOver(1); // 1 means AI won else { this->sounds(); this->drawAll(); } };
true
2b4ccf406e5d9af471cfca2271a93b86a864816b
C++
vitoraugustoa/AlgoritmoEstruturaDeDados
/RotasOnibus.cpp
ISO-8859-1
6,852
3.203125
3
[]
no_license
#include <stdlib.h> #include <stdbool.h> #include <stdio.h> #include <conio.h> #include <iostream> // Estrutura da Lista typedef struct dadosrota{ char parada[30]; } DadosRota; typedef struct norota { DadosRota dado; struct norota* proxima; }NoRota; typedef struct listaderotas{ int tamanho; NoRota* cabeca; }ListaDeRotas; // Fim da Estrutura // Headers ListaDeRotas* criaLista(); // Cria Nova Lista bool listaVazia(ListaDeRotas* lista); // Verifica se a lista esta vazia void inseriRota(ListaDeRotas* lista, DadosRota dados); // Adiciona uma Rota no inicio void apagaRota(ListaDeRotas* lista); // Apaga uma Rota no Inicio void mostraRotas(ListaDeRotas* lista); // Exibi a lista de rotas NoRota* retornaNoDeIndice(ListaDeRotas* lista, int indice); // retorna um N de uma rota Atraves de um Indice int retornaIndiceDeNo(ListaDeRotas* lista, NoRota* rota); // Retorna um Indice atraves de um N de uma rota void apagaDeIndice(ListaDeRotas* lista, int indice); // Apaga uma Rota Atraves de um Indice void mostraMenu(); // Mostra o Menu do sistema int tratarOpcao(int* opcao); // tratar opcao digitada pelo usuario // Fim Headers // Funes ListaDeRotas* criaLista(){ ListaDeRotas* novaLista = (ListaDeRotas *) malloc(sizeof(ListaDeRotas)); // Alocando espao para nova Lista novaLista->tamanho = 0; // Inicializa o tamanho da nova lista como 0 novaLista->cabeca = NULL; // cabea da lista inicia apontando para VAZIO ! return novaLista; // Retorna a nova lista criada } bool listaVazia(ListaDeRotas* lista){ return(lista->tamanho == 0); // retorna V ou F } void inseriRota(ListaDeRotas* lista, DadosRota dado){ NoRota* novaRota = (NoRota *) malloc(sizeof(NoRota)); // Alocando espao para o novo N de uma rota novaRota->dado = dado; // Adicionando o novo dado novaRota->proxima = lista->cabeca; // o proximo da nova rota , aponta para onde a cabea estava apontando lista->cabeca = novaRota; // cabea da lista agora aponta para a nova rota lista->tamanho ++; // incrementando o tamanho da rota system("cls"); printf("\n Nova Rota inserida com sucesso ! \n"); } void apagaRota(ListaDeRotas* lista){ if(!listaVazia(lista)){ // se a lista no estiver vazia faz: NoRota* ponteiroAuxiliar = lista->cabeca; // ponteiro recebe o primeiro intem da lista lista->cabeca = ponteiroAuxiliar->proxima; // cabea recebe o proximo do primeiro intem; free(ponteiroAuxiliar); // liberamos o espao do primeiro intem lista->tamanho --; //decrementando o tamanho da rota }else{ printf("\n A lista J esta VAZIA !! \n"); // se estiver vazia } } void mostraRotas(ListaDeRotas* lista){ if(!listaVazia(lista)){ // se a lista no estiver vazia faz : NoRota* ponteiroAuxiliar = lista->cabeca; // ponteiro recebe o primeiro intem da lista int indice = 0; while(ponteiroAuxiliar != NULL){ // enquanto o ponteiro no for vazio printf("Rota %d - %s \n",indice, ponteiroAuxiliar->dado.parada); // imprimi o indice , e o valor indice++; ponteiroAuxiliar = ponteiroAuxiliar->proxima; } }else{ printf("\n A lista esta VAZIA !! \n"); // se estiver vazia } } NoRota* retornaNoDeIndice(ListaDeRotas* lista, int indice){ if(!listaVazia(lista)){ // se lista no estiver vazia if(indice >= 0 && indice < lista->tamanho){ // e se o indice dado for valido faz: NoRota* ponteiro = lista->cabeca; // ponteiro recebe o primeiro intem da lista for(int i = 0; i < indice; i++){ // equanto i for menor que o indice dado faz: ponteiro = ponteiro->proxima; // ponteiro recebe o proximo dele mesmo } return ponteiro; // retorna o ponteiro encontrado } }else{ printf("\n A lista esta VAZIA !! \n"); // se estiver vazia return NULL; // retorna vazio } } int retornaIndiceDeNo(ListaDeRotas* lista, NoRota* rota){ if(rota != NULL){ // se rota passada no estiver vazia ! NoRota* ponteiroAux = lista->cabeca; // ponteiro recebe o primeiro item da lista int indice = 0; // inicializa o indice como 0 while(rota != NULL && rota != ponteiroAux){ // rota no pode estar vazia e tem que ser diferente da rota passada ponteiroAux = ponteiroAux->proxima; // dessa maneira percorremos toda a lista indice++; // indice incrementado } if(ponteiroAux != NULL){ // se o ponteio no estiver vazio return indice; // retorna o indice } else{ return -1; } } printf("\n Rota no existente !! \n"); // se a rota passada for NULL , logo no existe return -1; } void apagaDeIndice(ListaDeRotas* lista, int indice){ if(indice >= 0 && indice < lista->tamanho){ // verifica se indice passado valido if(indice == 0){ // se indice passado for 0 , logo usuario quer apagar o primeiro da lista apagaRota(lista); // usamos ento a funo apaga rota e passamos a lista }else{ NoRota* rotaAtual = retornaNoDeIndice(lista, indice); // pegamos a rota atual atraves do indice dado if(rotaAtual != NULL){ // se rota atual no estiver vazia NoRota* rotaAnterior = retornaNoDeIndice(lista, indice - 1); // pegamos rotaAnterior , diminuindo indice passado por - 1 rotaAnterior->proxima = rotaAtual->proxima; // o proximo da rota anterior ,vai receber o proximo da rota Atual free(rotaAtual); // liberamos a rota Atual lista->tamanho --; // decrementando o tamanho da lista system("cls"); printf("\n Rota apagada com sucesso ! \n"); } } }else{ printf("\n Indice No existente !! \n"); // se indice no estiver na rota return; } } void mostraMenu(){ printf("---------- Sistema Rotas de Onibus ---------- \n"); printf("\n-------------MENU----------------------------- \n"); printf("\n 1 - MOSTRAR ROTAS \n"); printf("\n 2 - ADICIONAR ROTA \n"); printf("\n 3 - EXCLUIR ROTA \n"); printf("\n 4 - SAIR \n"); } int tratarOpcao(int* opcao){ while(*opcao > 4 || *opcao < 1){ printf("\n Opcao Invalida ! Digite novamente : "); scanf("%d", &(*opcao)); } return *opcao; } // Fim Funes using namespace std; int main(){ // Variaveis int opcao = 0; ListaDeRotas* novaLista = criaLista(); NoRota* rota; DadosRota novoDado; int indice = 0; char novarota[30]; // Fim Variaveis while(opcao != 5){ mostraMenu(); scanf("%d",&opcao); tratarOpcao(&opcao); switch(opcao){ case 1: system("cls"); mostraRotas(novaLista); break; case 2: system("cls"); printf("Digite a nova rota que deseja adicionar : "); scanf("%s",&novoDado.parada); inseriRota(novaLista,novoDado); break; case 3: system("cls"); printf("Digite o indice da rota que deseja apagar : "); scanf("%d",&indice); apagaDeIndice(novaLista, indice); break; case 4: opcao = 5; break; } } getch(); }
true
bcc448ea875aa8ff7f7998e869d9d8390bead702
C++
zhukangli/mooc
/patBasic/1004.cpp
UTF-8
522
2.78125
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; int main() { int n; cin >> n; string name, no; int score; string maxName, maxNo; int maxScore = 0; string minName, minNo; int minScore = 100; for (int i = 0; i < n;i++) { cin >> name >> no >> score; if (score > maxScore) { maxScore = score; maxName = name; maxNo = no; } if (score < minScore) { minScore = score; minName = name; minNo = no; } } cout << maxName << " " << maxNo<<endl; cout << minName << " " << minNo; }
true
0b37c867da0e53c3979bc94ca377e3eb1d3ee4a1
C++
CodingZwen/FairyOfLife
/AnimatedSprite.h
ISO-8859-3
1,893
2.65625
3
[]
no_license
#pragma once #include "Animation_extended.h" #include <iostream> class AnimatedSprite : public sf::Drawable, public sf::Transformable { bool firstanimationdone = false; public: sf::Transform myTransform; //explicite konstruktoiren mssen immer mit klammer aufgerufen werden explicit AnimatedSprite(sf::Time frameTime = sf::seconds(0.2f), bool paused = false, bool looped = true); void update(sf::Time deltaTime); void setAnimation(const Animation_extended& animation); void setFrameTime(sf::Time time); void play(); void play(const Animation_extended& animation); void pause(); void stop(); void setLooped(bool looped); void setColor(const sf::Color& color); const Animation_extended* getAnimation() const; const void setTexture(sf::Texture &spriteSheet); sf::FloatRect getLocalBounds() const; sf::FloatRect getGlobalBounds() const; bool isLooped() const; bool isPlaying() const; bool firstAnimationDone() { return firstanimationdone; } sf::Time getFrameTime() const; void setFrame(std::size_t newFrame, bool resetTime = true); void setRot(float rotation); //void playOnceAnddoNextAnimation(); //own void setCurrentAnimation(std::string animationName); void insertAnimation(sf::IntRect StartRect, unsigned int Amount, const sf::Texture& texture,std::string nameOfAnimation); unsigned int getAnimationAmount(); private: std::map<std::string, Animation_extended> AnimationPool; const Animation_extended* m_animation; sf::Time m_frameTime; sf::Time m_currentTime; std::size_t m_currentFrame; bool m_isPaused; bool m_isLooped; //diese texture wird immer gesetzt und in der draw funktion verwendet //Texture kommt vom m_animation pointer const sf::Texture* m_texture; sf::Vertex m_vertices[4]; virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; };
true
df0e922fbcbf23c6d6bb09b425282636311d319b
C++
monman53/online_judge
/AtCoder/ABC/053/b.cpp
UTF-8
581
2.515625
3
[]
no_license
// header {{{ #include <bits/stdc++.h> using namespace std; // {U}{INT,LONG,LLONG}_{MAX,MIN} #define ALPHABET (26) #define INF INT_MAX #define MOD (1000000007LL) using LL = long long; // }}} int main() { std::ios::sync_with_stdio(false); string s;cin >> s; int n = s.size(); int l, r; for(int i=0;i<n;i++){ if(s[i] == 'A'){ l = i; break; } } for(int i=n-1;i>=0;i--){ if(s[i] == 'Z'){ r = i; break; } } cout << r-l+1 << endl; return 0; }
true
77c8d51b54566b83c36bea024e5a065cb5312fb2
C++
lvniqi/STM32F4xx_DSP_StdPeriph_Lib_V1.3.0
/Project/TEST_ADC_2_soft/String_L.cpp
UTF-8
2,775
2.859375
3
[]
no_license
#include "String_L.h" void String_L::String_L_ASCII_Init(u16 x,u16 y,char* d,LCD_PLACE_TYPE type,u16 color){ isShow = false; this->y = y; string.type = _LCD_STRING_ASCII; string.string.ascii = d; u16 t_len = strlen(d); this->color = color; switch(type){ case LCD_STRING_LEFT: start_x = x; end_x = start_x + t_len; break; case LCD_STRING_MID: start_x = x-t_len/2; end_x = start_x + t_len; break; case LCD_STRING_RIGHT: start_x = x-t_len; end_x = x; break; } } void String_L::String_L_CHINESE_Init(u16 x,u16 y,u16 pos_1,u16 len,LCD_PLACE_TYPE type,u16 color){ isShow = false; this->y = y; string.type = _LCD_STRING_CHINESE; string.string.chinese.start = pos_1; string.string.chinese.len = len; this->color = color; switch(type){ case LCD_STRING_LEFT: start_x = x; end_x = start_x + len*2; break; case LCD_STRING_MID: start_x = x-len; end_x = start_x + len; break; case LCD_STRING_RIGHT: start_x = x-len*2; end_x = x; break; } } String_L::String_L(){ String_L_ASCII_Init(0,0,"UNKNOWN",LCD_STRING_LEFT,YELLOW); string.type = _LCD_STRING_NULL; } String_L::String_L(u16 x,u16 y,char* d){ String_L_ASCII_Init(x,y,d,LCD_STRING_LEFT,YELLOW); } String_L::String_L(u16 x,u16 y,char* d,LCD_PLACE_TYPE type){ String_L_ASCII_Init(x,y,d,type,YELLOW); } String_L::String_L(u16 x,u16 y,char* d,u16 color){ String_L_ASCII_Init(x,y,d,LCD_STRING_LEFT,color); } String_L::String_L(u16 x,u16 y,char* d,LCD_PLACE_TYPE type,u16 color){ String_L_ASCII_Init(x,y,d,type,color); } String_L::String_L(u16 x,u16 y,u16 pos_1,u16 len){ String_L_CHINESE_Init(x,y,pos_1,len,LCD_STRING_LEFT,YELLOW); } String_L::String_L(u16 x,u16 y,u16 pos_1,u16 len,u16 color){ String_L_CHINESE_Init(x,y,pos_1,len,LCD_STRING_LEFT,color); } String_L::String_L(u16 x,u16 y,u16 pos_1,u16 len,LCD_PLACE_TYPE type){ String_L_CHINESE_Init(x,y,pos_1,len,type,YELLOW); } String_L::String_L(u16 x,u16 y,u16 pos_1,u16 len,LCD_PLACE_TYPE type,u16 color){ String_L_CHINESE_Init(x,y,pos_1,len,type,color); } bool String_L::isNull(){ if(string.type == _LCD_STRING_NULL){ return true; }else{ return false; } } void String_L::show(){ isShow = true; LCD_ShowStringBig_Union(start_x,y,LCD_STRING_LEFT,string,color); } void String_L::hide(){ isShow = false; LCD_ShowStringBig_Union(start_x,y,LCD_STRING_LEFT,string,BACK_COLOR); } void String_L::setColor(u16 color){ this->color = color; if(isShow){ show(); } } void String_L::moveTo(u16 x,u16 y){ this->y = y; u16 len = end_x-start_x; this->start_x = x; this->end_x = len+x; } u16 String_L::getColor(){ return color; } u16 String_L::getLen(){ return end_x-start_x; }
true
26b9adb1149bbbf9f3b0b0e3b886077776dbd9c0
C++
peterpolidoro/SavedVariable
/examples/SavedVariableConstantString/SavedVariableConstantString.ino
UTF-8
2,038
2.9375
3
[ "BSD-3-Clause" ]
permissive
#include <Arduino.h> #include <Streaming.h> #include <EEPROM.h> #include <SavedVariable.h> #include <ConstantVariable.h> const long BAUD = 115200; union SubsetMemberType { const long l; ConstantString * const cs_ptr; }; const int EEPROM_INITIALIZED_VALUE = 98; enum{MODE_SUBSET_LENGTH=3}; CONSTANT_STRING(mode_rising,"RISING"); CONSTANT_STRING(mode_falling,"FALLING"); CONSTANT_STRING(mode_change,"CHANGE"); const SubsetMemberType mode_ptr_subset[MODE_SUBSET_LENGTH] = { {.cs_ptr=&mode_rising}, {.cs_ptr=&mode_falling}, {.cs_ptr=&mode_change}, }; const ConstantString * const mode_ptr_default = &mode_rising; void setup() { while (!Serial); Serial.begin(BAUD); Serial.flush(); SavedVariable eeprom_initialized_sv(EEPROM_INITIALIZED_VALUE); SavedVariable mode_ptr_sv(mode_ptr_default); for (int i=0; i<4; ++i) { int eeprom_initial_value; eeprom_initialized_sv.getValue(eeprom_initial_value); Serial << "eeprom_intial_value = " << eeprom_initial_value << " should be = " << EEPROM_INITIALIZED_VALUE << endl; if (eeprom_initial_value != EEPROM_INITIALIZED_VALUE) { Serial << "Default values set for the first time!" << endl; eeprom_initialized_sv.setValueToDefault(); mode_ptr_sv.setValueToDefault(); } else { Serial << "Default values already set!" << endl; } const ConstantString *read_mode_ptr; mode_ptr_sv.getValue(read_mode_ptr); Serial << "initial mode value = " << *read_mode_ptr << endl; mode_ptr_sv.getDefaultValue(read_mode_ptr); Serial << "default mode value = " << *read_mode_ptr << endl; Serial << endl; for (int j=0; j<MODE_SUBSET_LENGTH; ++j) { const ConstantString * const write_mode_ptr = mode_ptr_subset[j].cs_ptr; mode_ptr_sv.setValue(write_mode_ptr); mode_ptr_sv.getValue(read_mode_ptr); Serial << "mode value = " << *read_mode_ptr << " should be = " << *write_mode_ptr << endl; Serial << endl; delay(1000); } delay(2000); } } void loop() { }
true
57f3eb95c29228b29924a71fb354da3dd7ee56d1
C++
Aleksandra24503/OOP
/ex.8 tempelate/main.cpp
UTF-8
1,847
4.25
4
[]
no_license
#include <string> #include <iostream> using namespace std; template <class T> class stack { private: int size; T tab[200]; public: stack() { size = 0; } void push(T elem) { tab[size] = elem; size++; } void pop() { size--; } T top() { return tab[size-1]; } }; int main() { int choice; stack<int> sint; stack<string> sstr; while (true) { cout << endl; cout << "1.Push int item" << endl; cout << "2.Push string item" << endl; cout << "3.Pop int item" << endl; cout << "4.Pop string item" << endl; cout << "5.Top int item" << endl; cout << "6.Top string item" << endl; cout << "0.Exit" << endl << endl; cout << "> "; cin >> choice; if (choice == 1) { int item; cout << "Give item." << endl; cout << "> "; cin >> item; sint.push(item); } else if (choice == 2) { string item; cout << "Give item." << endl; cout << "> "; cin >> item; sstr.push(item); } else if (choice == 3) { sint.pop(); cout << "Done." << endl; } else if (choice == 4) { sstr.pop(); cout << "Done." << endl; } else if (choice == 5) { cout << "Item on top: " << sint.top() << endl; } else if (choice == 6) { cout << "Item on top: " << sstr.top() << endl; } else { return 0; } } return 0; }
true
36bcaeeb1768d0f04116fa2fd6b3aad9fcefc652
C++
Anosy/C-Primer5
/Chapter16/Section2/Exercise16_47/源.cpp
UTF-8
548
3.390625
3
[]
no_license
#include<iostream> #include<utility> #include<type_traits> using namespace std; template <typename F, typename T1, typename T2> void filp(F f, T1 &&t1, T2 &&t2) { f(std::forward<T2>(t2), std::forward<T1>(t1)); } void func1(int v1, int v2) { cout << v1 << " " << v2 << endl; } void func2(int &v1, int v2) { cout << v1 << " " << v2 << endl; } void func3(int &&v1, int &v2) { cout << v1 << " " << v2 << endl; } int main() { int a = 0; int b = 1; filp(func1, a, b); filp(func2, a, b); filp(func3, a, 42); system("pause"); return 0; }
true
d4b3e5765b456794fe9735765fdd31828a2758fc
C++
Mario173/ClosestPoints
/Divide&Conquer.cpp
UTF-8
5,584
3.625
4
[]
no_license
//Divide and Conquer algoritam --> O(nlogn) #include <iostream> #include <cmath> typedef struct{ double x, y; } tocka; //provjera udaljenosti između 2 točke u O(1) operacija double udaljenost(tocka a, tocka b) { return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)); } //potrebno za slučaj kad promatramo <=3 točke double bruteForce(tocka *sve, int start, int end) { int i, j; double min; for(i = start; i < end; i++) { for(j = i + 1; j <= end; j++) { double ud = udaljenost(sve[i], sve[j]); if(i == start && j == start + 1) min = ud; else if(ud < min) min = ud; } } return min; } double min(double x, double y) { if(x < y) return x; return y; } //merge sort --> O(nlogn) //Spaja 2 niza void merge(tocka arr[], int l, int m, int r, int koji) { int n1 = m - l + 1; int n2 = r - m; //Privremena polja tocka L[n1], R[n2]; for (int i = 0; i < n1; i++) L[i] = arr[l + i]; for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; //Spajamo polja u arr[l...r] int i = 0; int j = 0; int k = l; if(koji == 0) { //sortiramo po x koordinati while (i < n1 && j < n2) { if (L[i].x <= R[j].x) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } } else { //sortiramo po y koordinati while (i < n1 && j < n2) { if (L[i].y <= R[j].y) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } } //Ako je ostao neki element u L, ubaci ga while (i < n1) { arr[k] = L[i]; i++; k++; } //Ako je ostao neki element u R, ubaci ga while (j < n2) { arr[k] = R[j]; j++; k++; } } void mergeSort(tocka arr[],int l,int r, int koji){ if(l >= r) { return; } int m = (l + r - 1) / 2; mergeSort(arr,l,m, koji); mergeSort(arr,m + 1,r, koji); merge(arr,l,m,r, koji); } //pronalazi najmanju udaljenost točaka u pruzi širine 2d oko linije presijecanja double minPruga(tocka pruga[], int n, double d) { double min = d; for(int i = 0; i < n; i++) { //ova petlja se zavrti najviše 7 puta --> ukupno se obe petlje zavrte najvise 7n puta --> O(n) for(int j = i + 1; j < n && (pruga[j].y - pruga[i].y) < min; j++) { double dist = udaljenost(pruga[i], pruga[j]); if(dist < min) min = dist; } } return min; } //nalaženje najmanje udaljenosti između 2 od n točaka u ravnini u O(nlogn) operacija double minUdaljenost(tocka x[], tocka y[], int start, int end) { double curr_min; if(end - start <= 2) { //brute-force metoda return bruteForce(x, start, end); } int mid = (start + end) / 2, li = 0, ri = 0; tocka midPoint = x[mid]; tocka yl[mid], yr[end - mid], xl[mid], xr[end - mid]; for(int i = start; i <= end; i++) { if(y[i].x <= midPoint.x && li < mid) { yl[li].x = y[i].x; yl[li].y = y[i].y; li++; } else { yr[ri].x = y[i].x; yr[ri].y = y[i].y; ri++; } if(i <= mid) { xl[i].x = x[i].x; xl[i].y = x[i].y; } else { xr[i - mid - 1].x = x[i].x; xr[i - mid - 1].y = x[i].y; } } double dl = minUdaljenost(xl, yl, start, mid); //najmanja udaljenost lijevo od linije presijecanja double dr = minUdaljenost(xr, yr, mid + 1, end); //najmanja udaljenost desno od linije presijecanja //još je preostalo naći minimalnu udaljenost između točaka gdje je jedna lijevo, a druga desno od linije presijecanja double d = min(dl, dr); tocka pruga[end]; int j = 0; for(int i = start; i <= end; i++) { if(abs(y[i].x - midPoint.x) < d) { pruga[j].x = y[i].x; pruga[j].y = y[i].y; j++; } } return minPruga(pruga, j, d); } //unošenje točaka u O(n) operacija --> ukupno O(nlogn) int main() { int i, n; std::cout << "Koliko tocaka zelite provjeriti?\n"; std::cin >> n; if(n < 2) { std::cout << "Morate unijeti barem dvije točke." << std::endl; } else { tocka xt[n], yt[n]; for(i = 0; i < n; i++) { double x, y; std::cout << "Unesite x koordinatu " << i + 1 << ". tocke: "; std::cin >> x; xt[i].x = x; //niz tocaka koji ce biti sortiran prema x koordinati yt[i].x = x; //niz tocaka koji ce biti sortiran prema y koordinati std::cout << "Unesite y koordinatu " << i + 1 << ". tocke: "; std::cin >> y; xt[i].y = y; yt[i].y = y; } mergeSort(xt, 0, n - 1, 0); //sortiranje niza x po x koordinati --> O(nlogn) mergeSort(yt, 0, n - 1, 1); //sortiranje niza y po y koordinati --> O(nlogn) std::cout << "\nNajmanja udaljenost izmedu unesenih tocaka je: " << minUdaljenost(xt, yt, 0, n - 1) << std::endl; //O(nlogn) } return 0; }
true
a24f59bc697cf2cacaa05148e1db1cd8a58c9310
C++
HaochengLEE/PAT
/Basic/1011.cpp
UTF-8
898
2.734375
3
[]
no_license
// // Created by 李昊城 on 2019/10/27. // #include <stdio.h> int main(void){ long long a,b,c; int count,start=0; scanf("%d",&count); int at[count]; int ac=0; while (count--){ scanf("%lld%lld%lld",&a,&b,&c); if(a+b>c){ at[start]=1; } else { at[start]=0; } start++; } for(int i=1;i<=start;i++){ if(at[ac])printf("Case #%d:true\n",i); else printf("Case #%d:false\n",i); ac++; } return 0; } //#include <stdio.h> //int main(void){ // long long a,b,c; // int count,start=1; // scanf("%d",&count); // while (count--){ // scanf("%lld%lld%lld",&a,&b,&c); // if(a+b>c){ // printf("Case #%d: true\n",start); // } else { // printf("Case #%d: false\n",start); // } // start++; // } // return 0; // //}
true
bff85dc2f261dd044538d7d8178c25b8766e184a
C++
colinhp/learngit
/reference.cc
UTF-8
824
3.25
3
[]
no_license
/// /// @file reference.cc /// @author hoping(stevenfok@126.com) /// @date 2020-06-07 22:44:51 /// #include <iostream> using std::cout; using std::endl; void test0(void) { int num = 100; int &ref = num; cout<< "num = "<< num << endl; cout<< "ref = "<< ref << endl; cout<< "num = "<< &num << endl; cout<< "ref = "<< &ref << endl; ref = 200; cout<< "修改引用之后:"<< endl; cout<< "num = "<< num << endl; cout<< "ref = "<< ref << endl; // int &ref1; //error 引用不能独立存在,必须要初始化 } void swap(int &x,int &y) { int temp; temp = x; x = y; y = temp; } void test1(void) { int a = 3,b = 4; cout<<"before swap() a= "<< a << "b = "<< b << endl; swap(a,b); cout<<"after swap() a= "<< a << "b = "<< b << endl; } int main(void) { //test0(); test1(); return 0; }
true
cb24b0e7f20455c31c5f3e4c9d387ced653a285f
C++
VictorGuerrah/Estrutura-de-Dados-2
/src/hashMap.cpp
UTF-8
7,299
2.875
3
[]
no_license
#include "hashMap.h" #include "hashNode.h" hashMap::hashMap(int n){ tamMax = n+1337; tam = 0; table = new hashNode*[tamMax]; for(int i = 0; i<tamMax; i++){ //iniciando todos os valores da tabelo com NULL table[i] = NULL; } tabela=new list<int>[tamMax];//lista utilizada no encadeamento separado numComparacoes = 0; colisoes = 0; //utilizada no encadeamento coalescido } hashMap::~hashMap(){ delete [] table; } int hashMap::tamanhoMap(){ return tam; } bool hashMap::vazio(){ if(tam ==0) return true; else return false; } int hashMap::hashLinear(int chave, int i){ return(chave+i)%tamMax; } int hashMap::buscaLinear(int chave){ int i = 0; int indice = hashLinear(chave, i); while(table[indice] != NULL && table[indice]->getKey() != chave){ i++; indice = hashLinear(chave, i); } if(table[indice] == NULL) return -1; else{ return indice; } } void hashMap::insercaoLinear(registro* reg){ int i=0; int indice = hashLinear(reg->getId(), i); numComparacoes++; while(table[indice]!=NULL){ numComparacoes++; i++; indice = hashLinear(reg->getId(), i); } table[indice] = new hashNode(reg->getId(), indice, reg); tam++; } void hashMap::remocaoLinear(int chave){ int i = 0; int indice = hashLinear(chave, i); while(table[indice]->getKey() == chave){ if(table[indice]->getKey() == chave){ hashNode *aux = table[indice]; table[indice] =NULL; tam--; } i++; indice = hashLinear(chave, i); } } //Sondagem Quadratica int hashMap::hashQuadratica(int chave, int i){ return(chave+(i*i)); } int hashMap::buscaQuadratica(int chave){ int i= 0; int indice = hashQuadratica(chave, i); while(table[indice] != NULL && table[indice]->getKey() != chave){ i++; indice = hashQuadratica(chave, i); } if(table[indice] == NULL) return -1; else return indice; } void hashMap::InsercaoQuadratica(registro* chave, int valor){ int i = 0; int indice = hashQuadratica(chave->getId(),i); numComparacoes++; while(table[indice] != NULL){ numComparacoes++; i++; indice = hashQuadratica(chave->getId(), i); } table[indice] = new hashNode(chave->getId(), valor, chave); tam++; } void hashMap::remocaoQuadratica(int chave){ int i = 0; int indice = hashQuadratica(chave, i); while(table[indice] != NULL){ if(table[indice]->getKey() == chave){ hashNode *aux = table[indice]; table[indice] == NULL; tam--; } i++; indice = hashQuadratica(chave, i); } } //duplo hash void hashMap::primo(int t){ primos.clear(); int n = t; int nNew = sqrt(n); int marked[n/2 + 500] = {0}; for(int i = 1; i<=(nNew-1)/2; i++){ for(int j = (i*(i+1))<<1; j<=n/2; j = j+2*i+1) marked[j] = 1; } primos.push_back(2); for(int i = 1; i<=n/2; i++) if(marked[i] == 0) primos.push_back(2*i + 1); } int hashMap::buscaPrimo(int esq, int dir, int n){ if(esq<=dir){ int meio = (esq+dir)/2; if(meio == 0 || meio == primos.size()-1) return primos[meio]; if(primos[meio] == n) return primos[meio-1]; if(primos[meio] < n && primos[meio+1] > n){ return primos[meio]; } if(n<primos[meio]) return buscaPrimo(esq, meio-1, n); else return buscaPrimo(meio+1, dir, n); } return 0; } int hashMap::hashDuploHash2(int chave){ primo(tamMax); int p = buscaPrimo(0,primos.size()-1,tamMax); return(p-(chave%p)); } int hashMap::hashDuploHash(int chave, int i){ return(chave+i*hashDuploHash2(chave))%tamMax; } int hashMap::buscaDuploHash(int chave){ int i=0; int indice=hashDuploHash(chave,i); while(table[indice] != NULL && table[indice]->getKey() != chave) { i++; indice=hashDuploHash(chave,i); } if(table[indice] == NULL) return -1; else { return indice; } } void hashMap::insercaoDuploHash(registro* chave, int valor){ int aux = 0; int indice = hashDuploHash(chave->getId(), aux); numComparacoes++; while(table[indice] != NULL){ numComparacoes++; aux++; indice = hashDuploHash2(chave->getId()); } table[indice] = new hashNode(chave->getId(), valor, chave); tam++; } void hashMap::remocaoDuploHash(int chave, int i){ int aux = 0; int indice = hashDuploHash(chave, aux); while(table[indice] != NULL){ if(table[indice]->getKey() == chave){ hashNode *aux = table[indice]; table[indice] = NULL; tam--; } aux++; indice = hashDuploHash(chave, aux); } } //encadeamento separado int hashMap::hashEncadSeparado(int chave, int i){ return (chave+i)%tamMax; } int hashMap::buscaEncadSeparado(int chave){ int i = 0; int indice = hashEncadSeparado(chave, i); if(table[indice] == NULL){ return -1; } else{ hashNode *no = table[indice]; while(no!=NULL && no->getKey()!=chave) no = no->getProx(); if(no == NULL) return -1; else return indice; } } void hashMap::insereEncadSeparado(registro* chave, int valor){ int indice = hashEncadSeparado(chave->getId(), 0); tabela[indice].push_back(chave->getId()); } //encadeamento coalescido unsigned long int hashMap::qtdColisoes(){ return colisoes; } int hashMap::hashEncadCoalescido(int chave){ return chave%tamMax; } int hashMap::encontraProxPosicao(){ return colisoes; } void hashMap::insercaoEncadCoalescido(registro *chave){ hashNode *novo = new hashNode(chave->getId(), 0, chave); int indice = hashEncadCoalescido(chave->getId()); while(table[indice] !=NULL && table[indice]->getKey()!= -1 && ((table[indice]->getKey() != chave->getId()) || (table[indice]->getKey() == chave->getId()) || (table[indice]->getKey() != chave->getId()))){ numComparacoes++; if(table[indice]->getProxChave() == -1){ numComparacoes++; table[indice]->setProxChave(encontraProxPosicao()); } } if(table[indice] == NULL || table[indice]->getKey() == -1){ numComparacoes++; tam++; } else{ novo->setProxChave(table[indice]->getProxChave()); } table[indice] = novo; } void hashMap::buscaEncadCoalescido(registro* chave, int valor){ int indice = hashEncadCoalescido(chave->getId()); while(table[indice]!=NULL){ if(table[indice]->getKey()!=-1 && table[indice]->getKey() == chave->getId()){ //cout<<"indice: "<<indice<<" id: "<<table[indice]->getKey()<<" user: "<<table[indice]->getUser()<<" rating: "<< table[indice]->getRating()<<endl; return; } indice = table[indice]->getProxChave(); } cout<< "nao existe"<<endl; return; } void hashMap::imprimeHash() { for(int i=0; i<tamMax; i++) { if(table[i] != NULL && table[i]->getKey() != -1) { //cout<<"key: "<<table[i]->getKey()<<" value: "<<table[i]->getValue()<<endl; cout<<"i:"<<i<<" "<<table[i]->getKey()<<" | "; } } } void hashMap::imprimeHashEncad() { for (int i = 0; i < tamMax; i++) { cout << i; for (auto x : tabela[i]) cout << " --> " << x; cout << endl; } }
true
eb7bd83f557f171c991f3ca0a9926e5bd992f680
C++
subbug18/CPP
/cpp/producer_consumer.cpp
UTF-8
803
3.265625
3
[]
no_license
#include<iostream> #include <thread> #include <mutex> #include <condition_variable> #include <queue> using namespace std; bool finished = false; mutex mx; condition_variable cv; queue<int> q; void producer(int argN) { for (int i=0; i<argN; i++) { lock_guard<mutex> lk(mx); q.push(i); cout<<" pushing:"<<i<<"\n"; } cv.notify_all(); { lock_guard<mutex> lk(mx); finished = true; } cv.notify_all(); } void consumer() { while (true) { unique_lock<mutex> lk(mx); cv.wait(lk, []{return finished || !q.empty();}); while (!q.empty()) { cout<<"consuming" <<q.front()<<"\n"; q.pop(); } if (finished) break; } } int main() { int n=10; thread t1(producer, n); thread t2(consumer); t1.join(); t2.join(); cout<<"\nFinished\n"; return 0; }
true
3ae434cf14ed2b32d998eab46940ea5b105a2dbe
C++
mgroovyank/data-structures-and-algorithms1
/GraphTheory/MultiSourceBFS-Efficient Approach.cpp
UTF-8
1,594
2.8125
3
[]
no_license
#include <iostream> #include <vector> #include <set> using namespace std; #define N 100000+1 #define inf 1000000 int source[N]; int dist[N]; set<pair<int,int> > q; void multiSourceBFSUtil(vector<int> graph[],int s){ set<pair<int, int> >::iterator it; int i; for(i=0;i<graph[s].size();i++){ int v=graph[s][i]; if(dist[s]+1<dist[v]){ it=q.find(make_pair(dist[v],v)); q.erase(it); dist[v]=dist[s]+1; q.insert(make_pair(dist[v],v)); } } if(q.size()==0){ return; } it=q.begin(); int next=it->second; q.erase(it); multiSourceBFSUtil(graph,next); } void multiSourceBFS(vector<int> graph[],int n,int sources[],int s){ for(int i=1;i<=n;i++){ source[i]=0; } for(int i=0;i<s;i++){ source[sources[i]]=1; } for(int i=1;i<=n;i++){ if(source[i]){ dist[i]=0; q.insert(make_pair(0,i)); }else{ dist[i]=inf; q.insert(make_pair(inf,i)); } } set<pair<int, int> >::iterator itr; itr=q.begin(); int start=itr->second; multiSourceBFSUtil(graph,start); for(int i=1;i<= n;i++){ cout<<i<<" "<<dist[i]<<"\n"; } } void addEdge(vector<int> graph[], int u, int v){ graph[u].push_back(v); graph[v].push_back(u); } int main(){ int n=6; vector<int> graph[n + 1]; addEdge(graph, 1, 2); addEdge(graph, 1, 6); addEdge(graph, 2, 6); addEdge(graph, 2, 3); addEdge(graph, 3, 6); addEdge(graph, 5, 4); addEdge(graph, 6, 5); addEdge(graph, 3, 4); addEdge(graph, 5, 3); int sources[]={1,5}; int s=2;//size of sources multiSourceBFS(graph,n,sources,s); }
true
a4946ffb95dee96d60b244e80585c4931be0a8a4
C++
NickLuGithub/school_homework
/問題與解析/第一堂課/1315A_2.cpp
UTF-8
438
3.203125
3
[]
no_license
#include <iostream> using namespace std; int main() { int t, a, b, x, y; cin >> t; while(t--) { cin >> a >> b >> x >> y; x++; y++; int maxY, maxX; maxY = max(b-y, y - 1); maxX = max(a-x, x - 1); //cout << maxX << " " << maxY << endl; int area1 = maxX * b; int area2 = maxY * a; if(area1 > area2) cout << area1 << endl; else cout << area2 << endl; } return 0; }
true
74880c462bef822d0fb2f34b2d394726fd7bf2bd
C++
JayPolanco/CS_211
/Hanoi_Towers.cpp
UTF-8
1,483
3.40625
3
[]
no_license
/*Objective: Solve the Hanoi Towers Problem with the number of rings as user inputs*/ #include <iostream> #include <vector> using namespace std; int main(){ vector<int> t[3]; int from, move =0, n, to, candidate; cout << "Please enter the number of rings to move: "; cin >> n; for(int i = n+1; i >= 1; i--) t[0].push_back(i); t[1].push_back(n+1); t[2].push_back(n+1); from = 0; candidate =1; if(n%2!=0){ to=1; while(t[1].size() != n+1){ cout << "Move #" << ++move << ": Transfer ring " << candidate << " from tower " << char(from+'A') << " to tower " << char(to+'A') << "\n"; t[from].pop_back(); t[to].push_back(candidate); if(t[(to+1)%3].back() < t[(to + 2)%3].back()) from = (to+1)%3; else from = (to+2)%3; if(t[(from)%3].back() < t[(from+1)%3].back()) to = (from + 1)%3; else to = (from + 2)%3; candidate=t[from].back(); } } else{ to = 2; while(t[1].size() != n+1){ cout << "Move #" << ++move << ": Transfer ring " << candidate << " from tower " << char(from+'A') << " to tower " << char(to+'A') << "\n"; t[from].pop_back(); t[to].push_back(candidate); if(t[(to+1)%3].back() < t[(to + 2)%3].back()) from = (to+1)%3; else from = (to+2)%3; if(t[(from)%3].back() < t[(from+2)%3].back()) to = (from + 2)%3; else to = (from + 1)%3; candidate=t[from].back(); } } return 0; }
true
f4e4e1cf38b50208045dc6e490835c66a5b54af1
C++
presscad/LDS
/LDS/IntelliAgent/IntelliCore/MonoImage.cpp
GB18030
19,366
2.59375
3
[]
no_license
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include "MonoImage.h" #include "LogFile.h" #if defined(APP_EMBEDDED_MODULE)||defined(APP_EMBEDDED_MODULE_ENCRYPT) #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif int CMonoImage::WriteMonoBmpFile(const char* fileName, unsigned int width,unsigned effic_width, unsigned int height, unsigned char* image) { BITMAPINFOHEADER bmpInfoHeader; BITMAPFILEHEADER bmpFileHeader; FILE *filep; unsigned int row, column; unsigned int extrabytes, bytesize; unsigned char *paddedImage = NULL, *paddedImagePtr, *imagePtr; /* The .bmp format requires that the image data is aligned on a 4 byte boundary. For 24 - bit bitmaps, this means that the width of the bitmap * 3 must be a multiple of 4. This code determines the extra padding needed to meet this requirement. */ extrabytes = width%8>0?1:0;//(4 - (width * 3) % 4) % 4; long bmMonoImageRowBytes=width/8+extrabytes; long bmWidthBytes=((bmMonoImageRowBytes+3)/4)*4; // This is the size of the padded bitmap bytesize = bmWidthBytes*height;//(width * 3 + extrabytes) * height; // Fill the bitmap file header structure bmpFileHeader.bfType = 'MB'; // Bitmap header bmpFileHeader.bfSize = 0; // This can be 0 for BI_RGB bitmaps bmpFileHeader.bfReserved1 = 0; bmpFileHeader.bfReserved2 = 0; bmpFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); // Fill the bitmap info structure bmpInfoHeader.biSize = sizeof(BITMAPINFOHEADER); bmpInfoHeader.biWidth = width; bmpInfoHeader.biHeight = height; bmpInfoHeader.biPlanes = 1; bmpInfoHeader.biBitCount = 1; // 1 - bit mono bitmap bmpInfoHeader.biCompression = BI_RGB; bmpInfoHeader.biSizeImage = bytesize; // includes padding for 4 byte alignment bmpInfoHeader.biXPelsPerMeter = 2952; bmpInfoHeader.biYPelsPerMeter = 2952; bmpInfoHeader.biClrUsed = 0; bmpInfoHeader.biClrImportant = 0; // Open file if ((filep = fopen(fileName, "wb")) == NULL) { logerr.Log("Error opening file"); //AfxMessageBox("Error opening file"); return FALSE; } // Write bmp file header if (fwrite(&bmpFileHeader, 1, sizeof(BITMAPFILEHEADER), filep) < sizeof(BITMAPFILEHEADER)) { logerr.Log("Error writing bitmap file header"); //AfxMessageBox("Error writing bitmap file header"); fclose(filep); return FALSE; } // Write bmp info header if (fwrite(&bmpInfoHeader, 1, sizeof(BITMAPINFOHEADER), filep) < sizeof(BITMAPINFOHEADER)) { logerr.Log("Error writing bitmap info header"); //AfxMessageBox("Error writing bitmap info header"); fclose(filep); return FALSE; } RGBQUAD palette[2]; palette[0].rgbBlue=palette[0].rgbGreen=palette[0].rgbRed=palette[0].rgbReserved=palette[1].rgbReserved=0; //ɫ palette[1].rgbBlue=palette[1].rgbGreen=palette[1].rgbRed=255; //ɫ fwrite(palette,8,1,filep); // Allocate memory for some temporary storage paddedImage = (unsigned char *)calloc(sizeof(unsigned char), bytesize); if (paddedImage == NULL) { logerr.Log("Error allocating memory"); //AfxMessageBox("Error allocating memory"); fclose(filep); return FALSE; } /* This code does three things. First, it flips the image data upside down, as the .bmp format requires an upside down image. Second, it pads the image data with extrabytes number of bytes so that the width in bytes of the image data that is written to the file is a multiple of 4. Finally, it swaps (r, g, b) for (b, g, r). This is another quirk of the .bmp file format. */ for (row = 0; row < height; row++) { //imagePtr = image + (height - 1 - row) * width * 3; imagePtr = image + (height-row-1) * effic_width; paddedImagePtr = paddedImage + row * bmWidthBytes; for (column = 0; column < effic_width; column++) { *paddedImagePtr = *imagePtr; imagePtr += 1; paddedImagePtr += 1; } } // Write bmp data if (fwrite(paddedImage, 1, bytesize, filep) < bytesize) { logerr.Log("Error writing bitmap data"); //AfxMessageBox("Error writing bitmap data"); free(paddedImage); fclose(filep); return FALSE; } // Close file fclose(filep); free(paddedImage); return TRUE; } int CMonoImage::WriteMonoBmpFile(const char* fileName) { int nEffWidth=(this->m_nWidth+7)/8; BYTE_ARRAY imagebits(nEffWidth*m_nHeight,true); const BYTE BIT2BYTE[8]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; for(int j=0;j<m_nHeight;j++) { if(BitCount()==1) { BYTE* rowdata=m_lpBitMap+j*m_nEffWidth; BYTE* prow=&imagebits[nEffWidth*j]; for(int i=0;i<m_nEffWidth;i++) { if(!BlackBitIsTrue()) prow[i]=rowdata[i]; else prow[i]=rowdata[i]^0xff; } } else //if(BitCount()==8) { BYTE* rowdata=m_lpBitMap+j*this->m_nWidth; BYTE* prow=&imagebits[nEffWidth*j]; for(int i=0;i<m_nWidth;i++) { int ibyte=i/8,ibit=i%8; if(rowdata[i]==0) //׵ *(prow+ibyte)|=BIT2BYTE[7-ibit]; } } } return WriteMonoBmpFile(fileName,m_nWidth,nEffWidth,m_nHeight,imagebits); } const BYTE BIT2BYTE[8]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; ////////////////////////////////////////////////////////////////////////// CMonoImage::CMonoImage(BYTE* lpBitMap/*=NULL*/,int width/*=0*/,int height/*=0*/, bool black_is_true/*=true*/,BYTE ciBitCount/*=1*/) { m_lpBitMap=NULL; m_parrRelaObjs=NULL; m_bExternalData=false; m_ciBitCount=ciBitCount; InitBitImage(lpBitMap,width,height,black_is_true); } void CMonoImage::InitBitImage(BYTE* lpBitMap/*=NULL*/,int width/*=0*/,int height/*=0*/,bool black_is_true/*=true*/) { if(!m_bExternalData&&m_lpBitMap!=NULL) delete []m_lpBitMap; m_bBlackPixelIsTrue=black_is_true; m_lpBitMap=lpBitMap; m_bExternalData=m_lpBitMap!=NULL; m_nWidth=width; m_nHeight=height; long nBitWidth=m_nWidth*m_ciBitCount; m_nEffWidth=(nBitWidth+7)/8; if(m_lpBitMap==NULL&&m_nWidth>0&&m_nHeight>0) { int pixels=m_nEffWidth*m_nHeight; m_lpBitMap=new BYTE[pixels]; memset(m_lpBitMap,0,pixels); } } CMonoImage::~CMonoImage(void) { if(!m_bExternalData&&m_lpBitMap!=NULL) { delete []m_lpBitMap; m_lpBitMap=NULL; } } void CMonoImage::MirrorByAxisY() { long nBitWidth=m_nWidth*m_ciBitCount; m_nEffWidth=(nBitWidth+7)/8; BYTE mempool[2048]={0}; BYTE_ARRAY rowdata(m_nEffWidth,false,m_nEffWidth<2048?mempool:NULL,m_nEffWidth<2048?m_nEffWidth:0); BYTE* pRowData=m_lpBitMap; BYTE biBitCount=BitCount(); DYN_ARRAY<PIXEL_RELAOBJ> rowRelaObjs; PIXEL_RELAOBJ* pRowRelaObj=NULL; if(m_parrRelaObjs!=NULL) { rowRelaObjs.Resize(m_nWidth); pRowRelaObj=m_parrRelaObjs; } for(int yJ=0;yJ<m_nHeight;yJ++) { for(int xI=0;xI<m_nEffWidth;xI++) { //Y᾵ͼ if(biBitCount==1) { BYTE cbImgPixel=pRowData[m_nEffWidth-1-xI]; rowdata[xI]=0; for(int bitI=0;bitI<8;bitI++) { if((cbImgPixel&BIT2BYTE[bitI])>0) rowdata[xI]|=BIT2BYTE[7-bitI]; } } else if(biBitCount==8) rowdata[xI]=pRowData[m_nWidth-1-xI]; if(m_parrRelaObjs!=NULL) rowRelaObjs[xI]=pRowRelaObj[m_nWidth-1-xI]; } memcpy(pRowData,rowdata,m_nEffWidth); memcpy(pRowRelaObj,rowRelaObjs,m_nWidth*sizeof(PIXEL_RELAOBJ)); pRowData+=m_nEffWidth; pRowRelaObj+=m_nWidth; } } bool CMonoImage::SetPixelRelaObj(int i,int j,PIXEL_RELAOBJ& relaObj) { if(m_parrRelaObjs==NULL) return false; if( i<0||i>=m_nWidth || j<0||j>=m_nHeight) return false; int index=j*m_nWidth+i; if(m_parrRelaObjs[index].hRod==0||m_parrRelaObjs[index].zDepth<relaObj.zDepth-0.01) m_parrRelaObjs[index]=relaObj; else if(m_parrRelaObjs[index].zDepth<relaObj.zDepth+0.01&& m_parrRelaObjs[index].bTipPixel&&!relaObj.bTipPixel) m_parrRelaObjs[index]=relaObj; //Z̫£ȡֱмعϢ return true; } bool CMonoImage::SetPixelState(int i,int j,bool black/*=true*/) { if(i<0||j<0||i>=m_nWidth||j>=m_nHeight) return false; BYTE biBitCount=BitCount(); if(biBitCount==1) { bool pixelstate=BlackBitIsTrue()?black:!black; int iByte=i/8,iBit=i%8; if(pixelstate) m_lpBitMap[j*m_nEffWidth+iByte]|=BIT2BYTE[7-iBit]; else m_lpBitMap[j*m_nEffWidth+iByte]&=(0XFF-BIT2BYTE[7-iBit]); } else if(biBitCount==8) m_lpBitMap[j*m_nWidth+i]=BlackBitIsTrue()?black:!black; return black; } bool CMonoImage::IsBlackPixel(int i,int j) { if( i<0||i>=m_nWidth || j<0||j>=m_nHeight) return false; BYTE biBitCount=BitCount(); if(biBitCount==1) { int iByte=i/8,iBit=i%8; int gray=m_lpBitMap[j*m_nEffWidth+iByte]&BIT2BYTE[7-iBit]; //ȡõĻҶֵ //Ǻɫ return BlackBitIsTrue() ? (gray==BIT2BYTE[7-iBit]) : (gray!=BIT2BYTE[7-iBit]); } else { int gray=m_lpBitMap[j*m_nWidth+i]; //ȡõĻҶֵ //Ǻɫ return BlackBitIsTrue() ? (gray&0x01) : (gray&0x01)==0; } } PIXEL_RELAOBJ* CMonoImage::GetPixelRelaObj(int i,int j) { if(m_parrRelaObjs==NULL||!IsBlackPixel(i,j)) return false; return &m_parrRelaObjs[j*m_nWidth+i]; } PIXEL_RELAOBJ* CMonoImage::GetPixelRelaObjEx(int& i,int& j, BYTE ciRadiusOfSearchNearFrontObj/*=1*/,int* piExcludeXI/*=NULL*/,int* pjExcludeYJ/*=NULL*/) { PIXEL_RELAOBJ *pFrontPixelObj=NULL,*pPixelObj=NULL; pFrontPixelObj=pPixelObj=GetPixelRelaObj(i,j); if(pFrontPixelObj==NULL) return NULL; int xI=i,yJ=j; for(int x=-ciRadiusOfSearchNearFrontObj;x<=ciRadiusOfSearchNearFrontObj;x++) { for(int y=-ciRadiusOfSearchNearFrontObj;y<=ciRadiusOfSearchNearFrontObj;y++) { if(x==0&&y==0) continue; if(piExcludeXI&&pjExcludeYJ&&i+x==*piExcludeXI&&j+y==*pjExcludeYJ) continue; if((pPixelObj=GetPixelRelaObj(i+x,j+y))==NULL) continue; if(pPixelObj->hRod!=pFrontPixelObj->hRod&&pPixelObj->zDepth>pFrontPixelObj->zDepth) { pFrontPixelObj=pPixelObj; xI=x+i; yJ=y+j; } } } i=xI; j=yJ; return pFrontPixelObj; } #include <math.h> void CMonoImage::DrawPoint(const double* point,long hRelaNode/*=0*/) { int xI=point[0]>=0?(int)(point[0]+0.5):(int)(point[0]-0.5); int yJ=point[1]>=0?(int)(point[1]+0.5):(int)(point[1]-0.5); SetPixelState(xI,yJ); //ֽ֤Խ PIXEL_RELAOBJ relaObj(hRelaNode,(float)point[2],true); relaObj.ciObjType=0; SetPixelRelaObj(xI,yJ,relaObj); } void CMonoImage::DrawLine(const double* pxStart,const double* pxEnd,long hRelaRod/*=0*/) { double start[3],end[3]; bool swapping=false; if(pxStart[1]>pxEnd[1]+1) swapping=true; //» else if(fabs(pxStart[1]-pxEnd[1])<1&&pxStart[0]>pxEnd[0]) swapping=true; //ӽˮƽʱһأȴһ if(swapping) { //ֹͬһ߻ʼ->->ʼIJ memcpy(start,pxEnd,3*sizeof(double)); memcpy(end,pxStart,3*sizeof(double)); } else { memcpy(start,pxStart,3*sizeof(double)); memcpy(end,pxEnd,3*sizeof(double)); } double sx=start[0]; double sy=start[1]; double sz=start[2]; double ex=end[0]; double ey=end[1]; double ez=end[2]; double dy=end[1]-start[1]; double dx=end[0]-start[0]; if(fabs(dy)+fabs(dx)<0.01) return; //ֱڵǰͼƽֱ int xPrevI=-1,yPrevJ=-1; if(fabs(dy)>fabs(dx)) { //ֱY double coefX2Y=(end[0]-start[0])/(end[1]-start[1]); double coefZ2Y=(end[2]-start[2])/(end[1]-start[1]); //Բ꣬ᵼͶӰߵIJͬ߶λʱȫص int syi=(int)(0.5+sy); sx+=coefX2Y*(syi-sy); sz+=coefZ2Y*(syi-sy); sy=syi; int stepX=0; if(ex>sx+0.0001) stepX=1; else if(ex<sx-0.0001) stepX=-1; int stepY=ey>sy?1:-1; for(double yfJ=sy;(yfJ<=ey&&ey>sy)||(yfJ>=ey&&ey<sy);yfJ+=stepY) { int xI=(int)(0.5+sx+coefX2Y*(yfJ-sy)); int yJ=(int)(0.5+yfJ); SetPixelState(xI,yJ); double zDepth=sz+coefZ2Y*(yfJ-sy); bool tippoint=fabs(yfJ-sy)<=0.000001; //˵˼мغͬZֵʱȡмϢ if((yfJ+stepY>ey&&ey>sy)||(yfJ+stepY<ey&&ey<sy)) tippoint=true; PIXEL_RELAOBJ relaObj(hRelaRod,(float)zDepth,tippoint); relaObj.ciObjType=1; SetPixelRelaObj(xI,yJ,relaObj); if(xPrevI>=0&&yPrevJ>=0&&(abs(yJ-yPrevJ)+abs(xI-xPrevI)==2)) { SetPixelState(xI-stepX,yJ); //ֽ֤Խ SetPixelRelaObj(xI-stepX,yJ,relaObj); } xPrevI=xI; yPrevJ=yJ; } } else { //ֱX double coefY2X=(end[1]-start[1])/(end[0]-start[0]); double coefZ2X=(end[2]-start[2])/(end[0]-start[0]); //Բ꣬ᵼͶӰߵIJͬ߶λʱȫص int sxi=(int)(0.5+sx); sy+=coefY2X*(sxi-sx); sz+=coefZ2X*(sxi-sx); sx=sxi; int stepX=ex>sx?1:-1; int stepY=0; if(ey>sy+0.0001) stepY=1; else if(ey<sy-0.0001) stepY=-1; for(double xfI=sx;(xfI<=ex&&ex>sx)||(xfI>=ex&&ex<sx);xfI+=stepX) { int xI=(int)(0.5+xfI); int yJ=(int)(0.5+sy+coefY2X*(xfI-sx)); SetPixelState(xI,yJ); double zDepth=sz+coefZ2X*(xfI-sx); bool tippoint=fabs(xfI-sx)<=0.000001; //˵˼мغͬZֵʱȡмϢ if((xfI+stepX>ex&&ex>sx)||(xfI+stepX<ex&&ex<sx)) tippoint=true; PIXEL_RELAOBJ relaObj(hRelaRod,(float)zDepth,tippoint); SetPixelRelaObj(xI,yJ,relaObj); if(xPrevI>=0&&yPrevJ>=0&&(abs(yJ-yPrevJ)+abs(xI-xPrevI)==2)) { SetPixelState(xI,yJ-stepY); //ֽ֤Խ SetPixelRelaObj(xI,yJ-stepY,relaObj); } xPrevI=xI; yPrevJ=yJ; } } } ///////////////////////////////////////////////////////////////////////////////////////////// CByteMonoImage::CByteMonoImage(BYTE* lpBitMap/*=NULL*/,int width/*=0*/,int height/*=0*/,bool black_is_true/*=true*/) : CMonoImage(lpBitMap,width,height,black_is_true,8) { } CByteMonoImage::~CByteMonoImage() { if(!m_bExternalData&&m_lpBitMap!=NULL) { delete []m_lpBitMap; m_lpBitMap=NULL; } } bool CByteMonoImage::IsDetect(int i,int j) { return (0x80&m_lpBitMap[j*m_nWidth+i])>0; } bool CByteMonoImage::SetDetect(int i,int j,bool detect/*=true*/) { BYTE* pxyPixel=&m_lpBitMap[j*m_nWidth+i]; if(detect) (*pxyPixel)|=0x80; else if((*pxyPixel)>=0x80) (*pxyPixel)-=0x80; return ((*pxyPixel)&0x80)!=0; } void CByteMonoImage::ClearDetectMark() { for(int i=0;i<m_nWidth;i++) for(int j=0;j<m_nHeight;j++) m_lpBitMap[j*m_nWidth+i]&=0x0f; } bool CByteMonoImage::PIXEL::get_Black() { return pcbPixel==NULL?false:((*pcbPixel)&0x0f)>0; } bool CByteMonoImage::PIXEL::set_Black(bool black) { if(pcbPixel&&black) *pcbPixel|=0x01; return pcbPixel!=NULL&&black; } char CByteMonoImage::PIXEL::set_Connected(char connected) //ǷΪͨ { if(pcbPixel==NULL) return NONEVISIT; if(connected==NONEVISIT) { (*pcbPixel)&=0x0f; return connected; } else if(connected==CONNECTED) (*pcbPixel)|=0xc0; //0xc0=0x80|0x40 else if(connected==UNDECIDED) (*pcbPixel)|=0x80; else (*pcbPixel)&=0x0f; return connected; } char CByteMonoImage::PIXEL::get_Connected() { if(pcbPixel==NULL) return NONEVISIT; BYTE cbFlag=(*pcbPixel); if(!(cbFlag&0x80)) return NONEVISIT; if(cbFlag&0x40) return CONNECTED; else return UNDECIDED; } //ǷΪͨ int island_id=1; //TODO:ݹܵ¶ջ wjh-2018.6.20 //ʵ֤listStatPixelsԤCXhSimpleListڴЧʸ wjh-2018.4.12 bool CByteMonoImage::StatNearWhitePixels(int i,int j,ISLAND* pIsland,PRESET_ARRAY1600<PIXEL>* listStatPixels,BYTE cDetectFlag/*=0x0f*/) { BYTE* pxyPixel=&m_lpBitMap[j*m_nWidth+i]; PIXEL pixel(pxyPixel); if(i==0||j==0||i==m_nWidth-1||j==m_nHeight-1) { //һֱδ׵ΪʲôӺдͼ²Ϊʱ룬ûãע͵wjh-2018.5.22 //if(j==0) // StatNearWhitePixels(i,1,pIsland,listStatPixels,cDetectFlag); if(pixel.Black) return true; else { if(listStatPixels) listStatPixels->Append(pixel); return false; //ɫ߽ͨһ޷γɰɫµ } } if(pixel.Black) return true; //ǰΪڵֹͣͳ if(pixel.Connected==PIXEL::CONNECTED) return false; //ѼȷΪ߽ͨİ׵ if(pixel.Connected==PIXEL::UNDECIDED) return true; //ѼĽڵ pixel.Connected=PIXEL::UNDECIDED; //*pxyPixel|=0x80; Ѽ if(listStatPixels) listStatPixels->Append(pixel);//AttachObject(pixel); //if(pLogFile) // pLogFile->Log("(%2d,%2d)=%d",i,j,island_id); pIsland->x+=i; //ۻļֵ pIsland->y+=j; if(pIsland->count==0) pIsland->maxy=pIsland->miny=j; else { pIsland->maxy=max(pIsland->maxy,j); pIsland->miny=min(pIsland->miny,j); } pIsland->count+=1; bool canconinue=true; for(int movJ=-1;movJ<=1;movJ++) { int jj=movJ+j; if(jj<0||jj>=m_nHeight) continue; if(jj<j&&!(cDetectFlag&DETECT_UP)||jj>j&&!(cDetectFlag&DETECT_DOWN)||jj==j&&!(cDetectFlag&DETECT_Y0)) continue; for(int movI=-1;movI<=1;movI++) { int ii=movI+i; //Ƴabs(movJ)==abs(movI)Ϊܴڰ׵µ߽ΪڵԽǰ׵ҲԽ wjh-2018.3.28 if(ii<0||ii>=m_nWidth||(ii==i&&jj==j)||abs(movJ)==abs(movI)) continue; if(ii<i&&!(cDetectFlag&DETECT_LEFT)||ii>i&&!(cDetectFlag&DETECT_RIGHT)||ii==i&&!(cDetectFlag&DETECT_X0)) continue; if(!(canconinue=StatNearWhitePixels(ii,jj,pIsland,listStatPixels,cDetectFlag))) return false; } } return canconinue; } int CByteMonoImage::DetectIslands(CXhSimpleList<ISLAND>* listIslands) { int count=0; int rowstarti=0; //CLogFile logfile(CXhChar50("c:/%s_detect.txt",wChar.chars)); //CLogErrorLife life(&logfile); ClearDetectMark(); island_id=1; for(int j=0;j<m_nHeight;j++) { ISLAND island; bool blackpixelStarted=false,blackpixelEnded=false; bool whitepixelStarted=false; for(int i=0;i<m_nWidth;i++) { if(m_lpBitMap[rowstarti+i]==1) { blackpixelStarted=true; if(whitepixelStarted) blackpixelEnded=true; } else if(blackpixelStarted&&m_lpBitMap[rowstarti+i]==0) { whitepixelStarted=true; PRESET_ARRAY1600<PIXEL> listStatPixels; island.Clear(); //DETECT_X0|DETECT_Y0Ϊܴڰ׵µ߽ΪڵԽǰ׵ҲԽ wjh-2018.3.28 if(StatNearWhitePixels(i,j,&island,&listStatPixels,DETECT_UP|DETECT_Y0|DETECT_DOWN|DETECT_LEFT|DETECT_X0|DETECT_RIGHT))//,&logfile)) { //鵽İ׵㼯Ϊµ listIslands->AttachObject(island); //logfile.Log("%d#island finded @%2d-%2d",island_id,i,j); island_id++; count++; } else { //鵽İ׵㼯ʵ߽ͨ趨߽ for(UINT ii=0;ii<listStatPixels.Count;ii++) { PIXEL* pPixel=&listStatPixels.At(ii); pPixel->Connected=PIXEL::CONNECTED; } } } else if((m_lpBitMap[rowstarti+i]&0x7f)==0) { PRESET_ARRAY1600<PIXEL> listStatPixels; StatNearWhitePixels(i,j,&island,&listStatPixels,DETECT_UP|DETECT_Y0|DETECT_DOWN|DETECT_LEFT|DETECT_X0|DETECT_RIGHT);//,&logfile); for(UINT ii=0;ii<listStatPixels.Count;ii++) { PIXEL* pPixel=&listStatPixels.At(ii); pPixel->Connected=PIXEL::CONNECTED; } island.Clear(); } //if(blackpixelStarted&&whitepixelStarted&&blackpixelEnded) } rowstarti+=m_nWidth; } ClearDetectMark(); return count; }
true
79315e08e50509df8b268719496be0375ab6d8d5
C++
Tina-Yin-2001/Library
/studentstore.h
UTF-8
702
2.65625
3
[]
no_license
#ifndef STUDENTSTORE_H #define STUDENTSTORE_H #include <iostream> #include <cstdio> #include <cstdlib> #include <vector> #include "student.h" using namespace std; using namespace student; namespace studentstore { //构造用户 Student* creatStudent(); Student* creatStudent(string name, string stu_id, string code, string major); //添加删除(根据主键)用户 bool addStudent(Student* stu); bool deleteStudent(int ID); /*查询 因为学生只有一个,所以只能查出一条*/ Student * search(int ID); //根据ID查询学生信息 Student * search_stuid(string stu_id);//根据学号查找学生信息 vector<Student*> search_multipleReturn(string name); } #endif // STUDENTSTORE_H
true
46a6a337c323b6ac1a1f246ddeea4ef441a33fcf
C++
chloearluck/drone-freespace
/rbtree.h
UTF-8
3,770
3.03125
3
[]
no_license
#ifndef RBTREE #define RBTREE #include <vector> using namespace std; template <class V> class RBTree { public: class Node { public: Node () : v(0), p(0), l(0), r(0), red(false) {} Node (V v, Node *p, Node *l, Node *r, bool red) : v(v), p(p), l(l), r(r), red(red) {} void list (vector<V> &res) const { if (l) l->list(res); res.push_back(v); if (r) r->list(res); } int depth () const { int dl = l ? l->depth() : 0, dr = r ? r->depth() : 0, d = dl < dr ? dr : dl; return 1 + d; } int size () const { int sl = l ? l->size() : 0, sr = r ? r->size() : 0; return 1 + sl + sr; } V v; Node *p, *l, *r; bool red; }; Node *r, *nil; RBTree () : nil(new Node) { r = nil; } ~RBTree () { erase(r); delete nil; } void erase (Node *x) { if (x != nil) { erase(x->l); erase(x->r); delete x; } } Node * min (Node *x) { while (x->l != nil) x = x->l; return x; } bool find (V v) const { Node *x = r, *y = nil; int s; while (x != nil) { s = v->order(x->v); if (s == 0) { return true; } y = x; x = s == 1 ? x->l : x->r; } return false; } Node * insert (V v) { Node *x = r, *y = nil; int s; while (x != nil) { s = v->order(x->v); if (s == 0) { return x; } y = x; x = s == 1 ? x->l : x->r; } Node *z = new Node(v, y, nil, nil, true); if (y == nil) r = z; else if (s == 1) y->l = z; else y->r = z; insertFixup(z); return z; } void insertFixup (Node *z) { while (z->p->red) if (z->p == z->p->p->l) { Node *y = z->p->p->r; if (y->red) { z->p->red = false; y->red = false; z->p->p->red = true; z = z->p->p; } else { if (z == z->p->r) { z = z->p; leftRotate(z); } z->p->red = false; z->p->p->red = true; rightRotate(z->p->p); } } else { Node *y = z->p->p->l; if (y->red) { z->p->red = false; y->red = false; z->p->p->red = true; z = z->p->p; } else { if (z == z->p->l) { z = z->p; rightRotate(z); } z->p->red = false; z->p->p->red = true; leftRotate(z->p->p); } } r->red = false; } void leftRotate (Node *x) { Node *y = x->r; x->r = y->l; if (y->l != nil) y->l->p = x; y->p = x->p; if (x->p == nil) r = y; else if (x == x->p->l) x->p->l = y; else x->p->r = y; y->l = x; x->p = y; } void rightRotate (Node *x) { Node *y = x->l; x->l = y->r; if (y->r != nil) y->r->p = x; y->p = x->p; if (x->p == nil) r = y; else if (x == x->p->l) x->p->l = y; else x->p->r = y; y->r = x; x->p = y; } void remove (Node *z) { Node *y = z, *x = nil; bool yred = y->red; if (z->l == nil) { x = z->r; transplant(z, z->r); } else if (z->r == nil) { x = z->l; transplant(z, z->l); } else { y = min(z->r); yred = y->red; x = y->r; if (y->p == z) x->p = y; else { transplant(y, y->r); y->r = z->r; y->r->p = y; } transplant(z, y); y->l = z->l; y->l->p = y; y->red = z->red; } delete z; if (!yred) deleteFixup(x); } void transplant (Node *u, Node *v) { if (u->p == nil) r = v; else if (u == u->p->l) u->p->l = v; else u->p->r = v; v->p = u->p; } void deleteFixup (Node *z) {} // to do void list (vector<V> &res) { if (r) r->list(res); } int depth () const { return r ? r->depth() : 0; } int size () const { return r ? r->size() : 0; } }; #endif
true
1d8974355b75a86406a3cef066093604c7786633
C++
vietanh2222/Nguyenn-Viet-Anh
/L3B1.cpp
UTF-8
181
2.5625
3
[]
no_license
#include <stdio.h> int main(){ int x; printf("Nhap x = "); scanf("%d",&x); int n=0; while(x%10!=0){ n=n*10+x%10; x/=10; } printf(" So nghich dao la %d",n); }
true
d0cccad455cec4a7427695143f5dc2455f27155d
C++
crabyh/PAT
/PAT1014/PAT1014/main.cpp
UTF-8
3,631
2.671875
3
[]
no_license
// // main.cpp // PAT1014 // // Created by Myh on 10/14/14. // Copyright (c) 2014 Myh. All rights reserved. // #include <iostream> #include <deque> using namespace std; void print_time(int minutes){ if(minutes==-1){ cout<<"Sorry\n"; return; } int hours=8; hours+=minutes/60; minutes%=60; if(hours<10) cout<<"0"; cout<<hours<<":"; if(minutes<10) cout<<"0"; cout<<minutes<<endl; } class Customer{ public: int No; int time; }; int main(int argc, const char * argv[]) { // insert code here... int finish[1001]={}; int N, M, K, Q; deque<Customer *> customer; cin>>N>>M>>K>>Q; for(int i=0;i<K;i++){ int x; cin>>x; Customer *c=new Customer; c->No=i; c->time=x; customer.push_back(c); } int time=0; int this_time=0; deque<Customer *> window[21]; while(!customer.empty()){ //黄线前站满人 bool full=0; while(full==0){ full=1; for(int i=0;i<N;i++){ int min=0; for(int j=0;j<N;j++){ if(window[i].size()<window[min].size()) min=i; } if(window[min].size()<M&&!customer.empty()){ window[min].push_back(customer.front()); customer.pop_front(); full=0; } } } int min=-1; while(window[++min].empty()); for(int i=0;i<N;i++){ if(window[i].empty()){ continue; } if(window[i][0]->time<window[min][0]->time) min=i; } this_time=window[min][0]->time; time+=this_time; if(time>=540){ for(int j=0;j<customer.size();j++) finish[customer[j]->No]=-1; for(int j=0;j<N;j++) if(window[j].size()>1) for(int k=1;k<window[j].size();k++) finish[window[j][k]->No]=-1; } if(finish[window[min][0]->No]!=-1) finish[window[min][0]->No]=time; else finish[window[min][0]->No]=-1; for(int i=0;i<N;i++) if(!window[i].empty()) window[i][0]->time-=this_time; delete window[min].front(); window[min].pop_front(); } //完成黄线前的人 bool flag=1; while(flag){ flag=0; for(int i=0;i<N;i++){ if(!window[i].empty()){ flag=1; break; } } if(flag==0) break; int min=-1; while(window[++min].empty()); for(int i=0;i<N;i++){ if(window[i].empty()){ continue; } if(window[i][0]->time<window[min][0]->time) min=i; } this_time=window[min][0]->time; time+=this_time; if(time>=540){ for(int j=0;j<N;j++) if(window[j].size()>1) for(int k=1;k<window[j].size();k++) finish[window[j][k]->No]=-1; } if(finish[window[min][0]->No]!=-1) finish[window[min][0]->No]=time; else finish[window[min][0]->No]=-1; for(int i=0;i<N;i++) if(!window[i].empty()) window[i][0]->time-=this_time; delete window[min].front(); window[min].pop_front(); } for(int i=0;i<Q;i++){ int x; cin>>x; print_time(finish[x-1]); } return 0; }
true
9f3f6b2946405b178fe2208adb6f0b64075a6c24
C++
Phoenixcom1/SFND_2D_Feature_Tracking
/src/dataStructures.h
UTF-8
2,831
3.3125
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
#ifndef dataStructures_h #define dataStructures_h #include <vector> #include <opencv2/core.hpp> struct DataFrame { // represents the available sensor information at the same time instance cv::Mat cameraImg; // camera image std::vector<cv::KeyPoint> keypoints; // 2D keypoints within camera image cv::Mat descriptors; // keypoint descriptors std::vector<cv::DMatch> kptMatches; // keypoint matches between previous and current frame }; template <typename T, int SZ> class RingBuffer { public: RingBuffer(); void reset(); bool empty() const; bool full() const; size_t capacity() const; size_t size() const; void add(T item); T* getLatest(); T* getSecondLatest(); private: size_t read_ = 0; size_t write_ = 0; const size_t max_size_; bool full_ = 0; T buffer[SZ]; }; template <typename T,int SZ> RingBuffer<T,SZ>::RingBuffer() : max_size_(SZ) { /*empty*/ } template <typename T,int SZ> void RingBuffer<T,SZ>::reset() { read_ = write_; full_ = false; } template <typename T,int SZ> bool RingBuffer<T,SZ>::empty() const { //if head and tail are equal, we are empty return (!full_ && (read_ == write_)); } template <typename T,int SZ> bool RingBuffer<T,SZ>::full() const { //If tail is ahead the head by 1, we are full return full_; } template <typename T,int SZ> size_t RingBuffer<T,SZ>::capacity() const { return max_size_; } template <typename T,int SZ> size_t RingBuffer<T,SZ>::size() const { size_t size = max_size_; if (!full_) { if (read_ >= write_) { size = read_ - write_; } else { size = max_size_ + read_ - write_; } } return size; } template <typename T,int SZ> void RingBuffer<T,SZ>::add(T item) { buffer[write_] = item; //move add position to next slot write_ = (write_ + 1) % max_size_; //if buffer was already full, move read position to next slot since it got overwritten if (full_) { read_ = (read_ + 1) % max_size_; } //check if buffer got fully occupied with this add action full_ = write_ == read_; } template <typename T,int SZ> T* RingBuffer<T,SZ>::getLatest() { //taking care of negative wrap around if(write_ == 0) { return &buffer[max_size_-1]; } //return last written element return &buffer[write_-1]; } template <typename T,int SZ> T* RingBuffer<T,SZ>::getSecondLatest() { //taking care of negative wrap around if(write_ == 0) { return &buffer[max_size_-2]; } if(write_ == 1) { return &buffer[max_size_-1]; } //return last written element return &buffer[write_-2]; } //TODO function for getting last/oldest element, deleting elements or consuming read #endif /* dataStructures_h */
true
43abc21f9d7f3b1f0edfb8935949e6eb87ccbaa1
C++
rpuntaie/c-examples
/cpp/utility_optional_operator.cpp
UTF-8
818
3.4375
3
[ "MIT" ]
permissive
/* g++ --std=c++20 -pthread -o ../_build/cpp/utility_optional_operator.exe ./cpp/utility_optional_operator.cpp && (cd ../_build/cpp/;./utility_optional_operator.exe) https://en.cppreference.com/w/cpp/utility/optional/operator* */ #include <optional> #include <iostream> #include <string> int main() { using namespace std::string_literals; std::optional<int> opt1 = 1; std::cout<< "opt1: " << *opt1 << '\n'; *opt1 = 2; std::cout<< "opt1: " << *opt1 << '\n'; std::optional<std::string> opt2 = "abc"s; std::cout<< "opt2: " << *opt2 << " size: " << opt2->size() << '\n'; // You can "take" the contained value by calling operator* on a rvalue to optional auto taken = *std::move(opt2); std::cout << "taken: " << taken << " opt2: " << *opt2 << "size: " << opt2->size() << '\n'; }
true
f5cda787aee0935c65c42f6bbfed2f91d81b3a4a
C++
rzinkstok/starmap
/StarMap/Tikz/Tikz.cpp
UTF-8
842
2.71875
3
[]
no_license
// // Tikz.cpp // StarMap // // Created by Roel Zinkstok on 01/05/2018. // Copyright © 2018 Roel Zinkstok. All rights reserved. // #include <stdio.h> #include <iostream> #include <sstream> #include <memory> #include <stdexcept> #include <string> #include <array> #include <math.h> using namespace std; /** * @brief Executes a command in the shell * * @param cmd is the command to be executed * @return a string containing the console output of the command */ string exec(const char* cmd) { array<char, 128> buffer; string result; shared_ptr<FILE> pipe(popen(cmd, "r"), pclose); if (!pipe) { throw runtime_error("popen() failed!"); } while (!feof(pipe.get())) { if (fgets(buffer.data(), 128, pipe.get()) != nullptr) result += buffer.data(); } return result; }
true
420a31955c6de6f2e0979e0816e0cf1b5957539c
C++
arkdchst/mephi-3-lab-3
/include/sort.hpp
UTF-8
1,032
3.203125
3
[]
no_license
#pragma once #include <stack> #include <utility> #include <iostream> #include <string> #include <memory> #include "sequence.hpp" template <typename T> std::unique_ptr<Sequence<T>> sort(Sequence<T> *seq, int (*cmp)(T,T) ){ auto newSeq = std::unique_ptr<Sequence<T>>(seq->clone()); auto swap = [&newSeq](int i, int j) { T tmp = newSeq->get(i); newSeq->set(newSeq->get(j), i); newSeq->set(tmp, j); }; if(seq->getSize() == 0) return newSeq; if(seq->getSize() == 1) return newSeq; std::stack<std::pair<int,int>> edges; edges.push({0, newSeq->getSize() - 1}); while(!edges.empty()){ int start = edges.top().first; int end = edges.top().second; edges.pop(); int p = start; int i = p + 1; int j = end; while(i <= j && i <= end && j > p){ if(cmp(newSeq->get(i), newSeq->get(p)) <= 0) i++; else if(cmp(newSeq->get(j), newSeq->get(p)) > 0) j--; else swap(i, j); } swap(p, j); if(j > start + 1) edges.push({p, j - 1}); if(j < end - 1) edges.push({j + 1, end}); } return newSeq; }
true
b9d969029cdc6387aa2a71e31b38b048b7f4a765
C++
nilsoberg2/rvrmeander
/contrib/inih_r7/cpp/INIReader.h
UTF-8
2,652
2.703125
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "NCSA" ]
permissive
// Read an INI file into easy-to-access name/value pairs. // inih and INIReader are released under the New BSD license (see LICENSE.txt). // Go to the project home page for more info: // // http://code.google.com/p/inih/ #ifndef __INIREADER_H__ #define __INIREADER_H__ #if defined(_MSC_VER) #define INIH_DLL_EXPORT __declspec(dllexport) #define INIH_DLL_IMPORT __declspec(dllimport) #else #define INIH_DLL_EXPORT #define INIH_DLL_IMPORT #endif #if defined(INIH_EXPORTS) #define INIH_DLL_API INIH_DLL_EXPORT #elif !defined(INIH_STATIC_LINK) #define INIH_DLL_API INIH_DLL_IMPORT #else #define INIH_DLL_API #endif #include <map> #include <string> // Read an INI file into easy-to-access name/value pairs. (Note that I've gone // for simplicity here rather than speed, but it should be pretty decent.) class INIH_DLL_API INIReader { public: // Construct INIReader and parse given filename. See ini.h for more info // about the parsing. INIReader(const char* filename); // Return the result of ini_parse(), i.e., 0 on success, line number of // first error on parse error, or -1 on file open error. int ParseError(); // Get a string value from INI file, returning default_value if not found. std::string Get(std::string section, std::string name, std::string default_value); std::string Get(std::string key, std::string default_value); // Get an integer (long) value from INI file, returning default_value if // not found. long GetInteger(std::string section, std::string name, long default_value); long GetInteger(std::string key, long default_value); // Get a double-precision floating point value from INI file, returning // default_value if not found. double GetDouble(std::string section, std::string name, double default_value); double GetDouble(std::string key, double default_value); int GetDoubleArray(std::string key, double*& elems_out); // Get a boolean value from INI file, returning default_value if not // found. bool GetBoolean(std::string section, std::string name, bool default_value); bool GetBoolean(std::string key, bool default_value); // Determine if a key exists. bool Exists(std::string section, std::string name); bool Exists(std::string key); private: int _error; std::map<std::string, std::string> _values; static std::string MakeKey(std::string section, std::string name); static int ValueHandler(void* user, const char* section, const char* name, const char* value); static std::string ToLower(std::string input); }; #endif // __INIREADER_H__
true
814e45f8ac487f2f7aa2de1a47ac37d3153b8669
C++
YarinAVI/Leet-code-Solutions
/Backtracking + recursion_dfs_bfs/Solutions/430. Flatten a Multilevel Doubly Linked List.cpp
UTF-8
798
3.140625
3
[]
no_license
/* // Definition for a Node. class Node { public: int val; Node* prev; Node* next; Node* child; }; */ class Solution { public: Node* flatten(Node* head) { if(!head)return head; queue<Node*> q; dfs(head,q); Node* flat = q.front(); int i =0; Node * temp = nullptr; while(!q.empty()) { q.front()->prev = temp; temp = q.front(); temp->child = nullptr; q.pop(); if(!q.empty()) temp->next = q.front(); } return flat; } private: void dfs(Node* head,queue<Node*>&q) { while(head) { while(head && head->child==NULL) q.push(head),head=head->next; if(head) q.push(head),dfs(head->child,q),head=head->next; } } };
true
3d86f11d066a4b851a68a05b2710b15ea798bc36
C++
CubicPill/PDES-MAS
/include/lp/GvtCalculator.h
UTF-8
1,875
2.640625
3
[ "BSD-3-Clause" ]
permissive
#ifndef _GVT_CALCULATOR_H_ #define _GVT_CALCULATOR_H_ /** *\brief Class used for GVT calculation (uses Mattern's) * *GvtCalculator.h * *Author: Michael Lees (mhl) *Date: (08/02/05) * * *Description: This is a class which maintains gvt values on an LP. Each *Lp in the simulation has a GvtCalculator which is responsible for *keeping the Lps gvt value uptodate. The algorithm used to perform GVT *by this Calculator is matterns, for descriptions of what all the time *values mean please read the paper on matterns GVT. It should be *possible to implement another GVT calculator as long as the same *public methods are provided. * */ #include <map> #include "GvtMessage.h" #include "MatternColour.h" #include "GvtValueMessage.h" #include "GvtControlMessage.h" #include "GvtRequestMessage.h" using namespace std; namespace pdesmas { class Lp; class GvtCalculator { private: Lp* fLp; MatternColour fColour; unsigned long fRedTime; bool fIsGVTStarter; map<unsigned int, long> fWhiteTransientMessageCounter; unsigned int fNextLpInRing; bool fIsAcceptingRequests; void ProcessFirstCutGvtControl(const GvtControlMessage*); void ProcessSecondCutGvtControl(const GvtControlMessage*); void SendAndSetGvt(const GvtControlMessage*); public: GvtCalculator(); GvtCalculator(Lp*); ~GvtCalculator(); void ProcessMessage(const GvtRequestMessage*); void ProcessMessage(const GvtValueMessage*); void ProcessMessage(const GvtControlMessage*); MatternColour GetColour() const; void SetRedTime(unsigned long); unsigned long GetRedTime() const; long GetWhiteTransientMessageCounter(unsigned int) const; void DecrementWhiteTransientMessageCounter(unsigned int); void IncrementWhiteTransientMessageCounter(unsigned int); }; } #endif
true
b509482e9bd0ecaf60e185b1ec1d680a1cefc582
C++
sylvainma/UTComputer
/Interpreteur.cpp
UTF-8
10,842
3.0625
3
[]
no_license
#include "Interpreteur.h" /************************* * Interpreteur ************************/ const map<string, string> Interpreteur::regexs = { {"LitteraleEntiere", "-?[[:digit:]]+"}, {"LitteraleReelle","(-?[[:digit:]]+)(\\.|\\,)([[:digit:]]+)"}, {"LitteraleRationnelle", "-?[[:digit:]]+/-?[[:digit:]]+"}, {"LitteraleComplexe","((?:(?:[+-]?\\d+(?:(?:\\.\\d+)|(?:\\/\\d+))?)\\$[+-]?(?:\\d+(?:(?:\\.\\d+)|(?:\\/\\d+))?)))"}, {"LitteraleAtome","([[:upper:]]{1})([[:upper:]]|[[:digit:]])*"}, {"LitteraleExpression","'([^']+)'"}, {"LitteraleProgramme","\\[(.*)\\]"} }; vector<string>& Interpreteur::split(const string &s, char delim, vector<string>& elems) const { stringstream ss(s); string item; while (getline(ss, item, delim)) { if(item.find_first_not_of(' ') != std::string::npos) { elems.push_back(item); } } return elems; } /*! * \brief Fonctions qui permettent de découper en tokens une string selon un caractère délimitateur. * Source: http://stackoverflow.com/questions/409348/iteration-over-stdvector-unsigned-vs-signed-index-variable * \param La chaîne de caractère à découper, le délimitateur */ vector<string> Interpreteur::split(const string &s, char delim) const { vector<string> elems; split(s, delim, elems); return elems; } /*! * \brief Split plus flexible: split de la string avec un délimitateur regex * Source: http://stackoverflow.com/questions/16749069/c-split-string-by-regex 2ème et 3ème réponse * \param La chaîne de caractère à découper, le délimitateur sous forme de regex */ vector<string> Interpreteur::split2(const string &s, string rgx_str) const { vector<string> tokens; regex rgx(rgx_str); sregex_token_iterator iter(s.begin(), s.end(), rgx, -1); sregex_token_iterator end; while (iter != end) { tokens.push_back(*iter); ++iter; } return tokens; } /*! * \brief Split encore plus flexible: extrait les morceaux de string qui match la regex * Source: http://stackoverflow.com/questions/16749069/c-split-string-by-regex 2ème et 3ème réponse * \param La chaîne de caractère à découper, le pattern sous forme de regex */ vector<string> Interpreteur::split3(const string &s, string rgx_str) const { vector<string> tokens; string tmp(s); smatch m; regex e(rgx_str); while (std::regex_search (tmp,m,e)) { if(m[1]!=' ' && m[1]!='\r' && m[1]!='\n' && m[1]!='\t' && m[1]!='\f') { cout<<endl<<"Enregistré: "<<m[1]<<endl; tokens.push_back(m[1]); } tmp = m.suffix().str(); } return tokens; } /*! * \brief Vérifie que toutes les opérandes entrées sont correctes * \param La chaîne de caractère contenant la suite d'opérandes */ bool Interpreteur::isCommandeValide(const string& s) const { // Mettre de la forme ^((?: ... )*)\s*$ regex r("^((?:\\s*(?:(?:(?:[+-]?\\d+(?:(?:\\.\\d+)|(?:\\/\\d+))?)?\\$[+-]?(?:\\d+(?:(?:\\.\\d+)|(?:\\/\\d+))?)?)|(?:(?:\\d+(?:\\.\\d+)?)\\/(?:\\d+(?:\\.\\d+)?))|(?:[+-]?\\d+(?:\\.\\d+)?)|(?:[A-Z0-9]+)|(?:'[^']+')|(?:\\[.*\\])|(?:!=|=<|=>|[\\+\\-\\*\\/\\$=<>])))+)\\s*$"); if (regex_match(s, r)) return true; else return false; } /*! * \brief Retourne un vecteur contenant chaque opérande de la string. * Lance une exception s'il n'y a pas pas que des opérandes dans la string. * https://regex101.com/r/mV9jO4/8 * \param La chaîne de caractère contenant la suite d'opérandes */ vector<string> Interpreteur::getOperandes(const string& s) const { if(!isCommandeValide(s)) throw InterpreteurException("Suite d'opérandes invalide: "+s); string rgx="\\s*((?:(?:[+-]?\\d+(?:(?:\\.\\d+)|(?:\\/\\d+))?)?\\$[+-]?(?:\\d+(?:(?:\\.\\d+)|(?:\\/\\d+))?)?)|(?:(?:\\d+(?:\\.\\d+)?)\\/(?:\\d+(?:\\.\\d+)?))|(?:[+-]?\\d+(?:\\.\\d+)?)|(?:[A-Z0-9]+)|(?:'[^']+')|(?:\\[.*\\])|(?:!=|=<|=>|[\\+\\-\\*\\/\\$=<>]))"; vector<string> tokens = split3(s, rgx); for(std::vector<string>::iterator it = tokens.begin(); it != tokens.end(); ++it) { if(!isLitterale(*it) && !isOperateur(*it)) throw InterpreteurException("Opérande inconnue: "+*it); } return tokens; } /*! * \brief Renvoie vrai si la string correspond à une Litterale * \param La chaîne de caractère contenant la littérale */ bool Interpreteur::isLitterale(const string& s) const { regex r; // Littérales entières r=regexs.at("LitteraleEntiere"); if(regex_match(s, r)) return true; // Littérales réelles r=regexs.at("LitteraleReelle"); if(regex_match(s, r)) return true; // Littérales rationnelle r=regexs.at("LitteraleRationnelle"); if(regex_match(s, r)) return true; // Littérales Complexe r = regexs.at("LitteraleComplexe"); if (regex_match(s, r)) return true; // Littérales atomes r=regexs.at("LitteraleAtome"); if(regex_match(s, r) && !isOperateur(s)) return true; // Littérales expressions r=regexs.at("LitteraleExpression"); if(regex_match(s, r)) return true; // Littérales programmes r=regexs.at("LitteraleProgramme"); if(regex_match(s, r)) return true; return false; } /*! * \brief Transforme une string en Litterale, si c'est une litterale * \param La chaîne de caractère contenant la littérale */ Litterale* Interpreteur::toLitterale(const string& s) const { Litterale* l=nullptr; if(!isLitterale(s)) return nullptr; // Littérales entières if(regex_match(s, regex(regexs.at("LitteraleEntiere")))) { l=fl.newLitteraleEntiere(stoi(s)); } // Littérales réelles else if(regex_match(s, regex(regexs.at("LitteraleReelle")))) { vector<string> tokens = split(s, ','); if (tokens.size() == 1) { l = fl.newLitteraleReelle(stod(s)); } else { string ns; ns = tokens[0] + "." + tokens[1]; // ptite boucle pour autoriser la virgule je me faisais chier dans le train l = fl.newLitteraleReelle(stod(ns)); } } // Littérales rationnelles else if(regex_match(s, regex(regexs.at("LitteraleRationnelle")))) { // Extraction numérateur et dénominateur LitteraleEntiere* entiers[2]; vector<string> tokens=split(s, '/'); // Vérifie que ce n'est pas seulement un entier (1 au dén) if(stoi(tokens[1])==1) { l=fl.newLitteraleEntiere(stoi(tokens[0])); } else { entiers[0]=fl.newLitteraleEntiere(stoi(tokens[0])); entiers[1]=fl.newLitteraleEntiere(stoi(tokens[1])); l=fl.newLitteraleRationnelle(*entiers[0], *entiers[1]); cout<<l->toString()<<endl;; } } //Littérales Complexes if (regex_match(s, regex(regexs.at("LitteraleComplexe")))) { //branche 'a+bi' LitteraleNumerique* r; LitteraleNumerique* i; vector<string> tokens=split(s, '$'); //for(auto x:tokens) cout<<x<<endl; // Check que la partie réelle n'est pas vide, sinon on met 0 if(isLitterale(tokens[0])) r=dynamic_cast<LitteraleNumerique*>(toLitterale(tokens[0])); else r=dynamic_cast<LitteraleNumerique*>(fl.newLitteraleEntiere(0)); // Check que la partie imaginaire n'est pas vide, sinon on met 0 if(isLitterale(tokens[1])) i=dynamic_cast<LitteraleNumerique*>(toLitterale(tokens[1])); else i=dynamic_cast<LitteraleNumerique*>(fl.newLitteraleEntiere(0)); l = fl.newLitteraleComplexe(r, i); } // Littérale atome else if(regex_match(s, regex(regexs.at("LitteraleAtome"))) && !isOperateur(s)) { LitteraleAtome* var=LitteraleAtome::getVar(s); if (var) { // Si c'est une variable, on retourne l'atome l=var; } else { // Sinon c'est une littérale atome non variable, on retour une littérale expression l=fl.newLitteraleExpression(s); } } // Littérale expression else if(regex_match(s, regex(regexs.at("LitteraleExpression")))) { string exp(s); // Supression des quotes exp.erase(remove(exp.begin(), exp.end(), '\''), exp.end()); // Supression des espaces exp.erase(remove(exp.begin(), exp.end(), ' '), exp.end()); l=fl.newLitteraleExpression(exp); } // Littérale programme else if(regex_match(s, regex(regexs.at("LitteraleProgramme")))) { l=fl.newLitteraleProgramme(s); } return l; } /*! * \brief Renvoie vrai si la string correspond à un Operateur * \param La chaîne de caractère contenant l'opérateur */ bool Interpreteur::isOperateur(const string& s) const { map<string, const map<string,unsigned int>>::const_iterator outer_iter; for(outer_iter=Operateur::liste.begin(); outer_iter!=Operateur::liste.end(); ++outer_iter) { map<string, unsigned int>::const_iterator inner_iter; inner_iter=outer_iter->second.find(s); if(inner_iter!=outer_iter->second.end()) return true; } return false; } /*! * \brief Transforme une string en Operateur, si c'est un Operateur * \param La chaîne de caractère contenant l'opérateur */ Operateur* Interpreteur::toOperateur(const string& s) const { Operateur* o=nullptr; if(!isOperateur(s)) return nullptr; // Itérateur pour parcourir la map d'opérateurs map<string, unsigned int>::const_iterator it; // Opérateurs numériques it=Operateur::liste.at("numeriques").find(s); if (it!=Operateur::liste.at("numeriques").end()) o=fo.newOperateurNumerique(s); // Opérateurs de pile it=Operateur::liste.at("pile").find(s); if (it!=Operateur::liste.at("pile").end()) o=fo.newOperateurPile(s); // Opérateurs d'expression it=Operateur::liste.at("expression").find(s); if (it!=Operateur::liste.at("expression").end()) o=fo.newOperateurExpression(s); //Opérateur Logiques it = Operateur::liste.at("logiques").find(s); if (it != Operateur::liste.at("logiques").end()) o = fo.newOperateurLogique(s); return o; } /************************* * Singleton ************************/ /* * Initialisation du handler (singleton) */ Interpreteur::Handler Interpreteur::handler; /* * Retourne l'instance singleton */ Interpreteur& Interpreteur::getInstance() { if(handler.instance==nullptr) handler.instance = new Interpreteur; return *handler.instance; } /* * Supprime le singleton dans le cas où c'est souhaité avant la fin du programme */ void Interpreteur::deleteInstance() { delete handler.instance; handler.instance=nullptr; }
true
306bcbd55545a35796a3a2a16aca374bd2147055
C++
Jang355/SUZandJANG-1
/Programmers/Level 2/타겟 넘버/Solution.cpp
UTF-8
892
2.9375
3
[]
no_license
#include <string> #include <vector> #include <queue> using namespace std; vector<int> graph; int t; int bfs(int x){ int result = 0; queue<pair<int,int>> q; q.push({0,x}); q.push({0,x*(-1)}); while(!q.empty()){ int index = q.front().first; int sum = q.front().second; q.pop(); if(index == graph.size()-1 && sum == t) result++; int nindex = index + 1; if(nindex >= graph.size()) continue; int nx = graph[nindex]; int nsum = sum + nx; q.push({nindex,nsum}); nx *= (-1); nsum = sum + nx; q.push({nindex,nsum}); } return result; } int solution(vector<int> numbers, int target) { graph = numbers; t = target; int answer = 0; answer = bfs(graph[0]); return answer; }
true
d3217f1e569c05da7b65ba69fc0a5050a180f4e9
C++
IceCoffee2011/ChessGame
/ChessServer/RoSpace/RoSingleton.h
UTF-8
485
2.9375
3
[ "MIT" ]
permissive
#ifndef ROSINGLETON_H #define ROSINGLETON_H namespace RoSpace { // 单例模式的一种实现 // 注意: 这里的单例模式并不是指不能new 只能Instance()获得, // 而是一种库程序员与库用户的一种约定, 普通用户只通过 Instance() 函数获得 // 全局唯一的实例化对象 template <typename T> class CSingleton { public: static T* Instance() { static T x; return &x; } }; } #endif // ROSINGLETON_H
true
05f478cf91351313575a8337a11f403987d72e26
C++
prat31/Programming
/Competitive_Programming/GFG/nextGreaterElement.cpp
UTF-8
670
2.515625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ int testCases; cin>>testCases; while(testCases--){ int n; cin>>n; vector<int> arr; int temp; for(int i=0; i<n; i++){ cin>>temp; arr.push_back(temp); } bool found=false; for(int i=0; i<n-1; i++){ found=false; for(int j=i+1; j<n; j++){ if(arr[j]>arr[i]){ cout<<arr[j]<<" "; found=true; break; } } if(found==false) cout<<"-1 "; } cout<<endl; } return 0; }
true
28d9d2dbac63c7b60ae9e7db3844b4ad7006f79f
C++
haoyu987/multithread-downloader
/mydownload.cpp
UTF-8
2,733
2.828125
3
[]
no_license
// MyDownload.cpp: implementation of the MyDownload class. // ////////////////////////////////////////////////////////////////////// #include <afxsock.h> #include "helper.h" #include "Mydownload.h" #include <io.h> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// MyDownload::MyDownload() { onFinish = NULL; } MyDownload::~MyDownload() { } //add download task, take the URL as identifier bool MyDownload::addDownloadTask(const char* remoteUrl, const char* localFolder) { string remoteUrlString(remoteUrl); string localFolderString(localFolder); if (!existInVector(downloadListRemoteURLs, remoteUrlString)) { downloadListRemoteURLs.push_back(remoteUrlString); downloadListLocalFolders.push_back(localFolderString); return true; } else { return false; } } //check whether the task exists. bool existInVector(vector<string>& array, string& str) { for (int k = 0; k<array.size(); k++) { if (array[k].compare(str) == 0) return true; } return false; } //start download bool MyDownload::startDownload() { this->start(); return true; } //refactoring multithread downloading void * MyDownload::run(void *) { unsigned long temp = 0; unsigned long *downloaded = &temp; unsigned long totalSize = 1024; bool ret; while (downloadListRemoteURLs.size()>0) { cout << downloadListRemoteURLs[0] << endl; //default thread number is 3. The number can be changed but must be consistent. while (true) { //loop until the task is finished. ret = DownloadHelper(downloadListRemoteURLs[0].data(), downloadListLocalFolders[0].data(), downloaded, totalSize, THREAD_COUNT); if (ret) { cout << "True" << endl; } if (!exist(0)) { //file doesn't exist. cout << "Task failed,reconnecting..." << endl; Sleep(RECONNECT_INTERVAL); //reconnecting after 10 seconds. } else { //download finished. delete the first task. vector<string>::iterator startIterator = downloadListRemoteURLs.begin(); downloadListRemoteURLs.erase(startIterator); startIterator = downloadListLocalFolders.begin(); downloadListLocalFolders.erase(startIterator); break; } } } if (onFinish != NULL) { onFinish(); } return NULL; } //check if the file is already in the list. bool MyDownload::exist(int index) { string fileName = downloadListRemoteURLs[index].substr(downloadListRemoteURLs[index].find_last_of("/") + 1); string file(downloadListLocalFolders[index].data()); file.append('\\' + fileName); return (_access(file.data(), 0) == 0);; } //function pointer fired upon task finish void MyDownload::setOnFinish(void(*func)()) { onFinish = func; }
true
51e845e9258bff3a20665f9af2b70148287c8d0d
C++
fish-ball/acm.zju.edu.cn
/32XX/zoj.3279.src.1.cpp
GB18030
2,394
3.03125
3
[]
no_license
// 2056448 2009-12-13 18:19:58 Accepted 3279 C++ 400 5196 ͵ // ϣݽṹ⣬ // ߶ڵ㱣ڵͳ // ֵ֧IJijһλõֵ(ҪҶӵֵµ) // Ͳѯijһۻͳλֵ // 帴Ӷ O(nlog(n)) #include <iostream> using namespace std; struct TreeNode { int c, b, e; TreeNode *l, *r; TreeNode() : c(0), b(0), e(0), l(NULL), r(NULL) {} } *root; int n, q, v[100000]; int gen(TreeNode* node, int beg, int end) { node->b = beg; node->e = end; if(beg == end) { return node->c = v[beg-1]; } else { node->l = new TreeNode(); node->r = new TreeNode(); return node->c = gen(node->l, beg, beg+end>>1) + gen(node->r, (beg+end>>1) + 1, end); } } int chg(TreeNode* node, int pos, int val) { if(node->b == node->e) { int ans = val - node->c; node->c += ans; return ans; } else if(pos <= (node->b + node->e) / 2) { int ans = chg(node->l, pos, val); node->c += ans; return ans; } else if(pos > (node->b + node->e) / 2) { int ans = chg(node->r, pos, val); node->c += ans; return ans; } else { while(1) puts("error"); } } int qry(TreeNode* node, int rnk) { if(node->b == node->e) return node->b; else if(rnk <= node->l->c) { return qry(node->l, rnk); } else if(rnk > node->l->c) { return qry(node->r, rnk - node->l->c); } else { while(1) puts("error"); return 0; } } void destroy(TreeNode* node) { if(!node) return; destroy(node->l); destroy(node->r); delete node; } int main() { while(scanf("%d", &n) != EOF) { for(int i = 0; i < n; ++i) { scanf("%d", v + i); } root = new TreeNode(); gen(root, 1, n); scanf("%d", &q); while(q--) { char op[2]; scanf("%s", op); int x, y; if(*op == 'q') { scanf("%d", &x); printf("%d\n", qry(root, x)); } else if(*op == 'p') { scanf("%d%d", &x, &y); chg(root, x, y); } } destroy(root); } }
true
887de9fc7acab32be72fa35bc0ad4d9174249e40
C++
tommasoocari/exercises_LSN
/lib/lib.cpp
UTF-8
255
2.75
3
[]
no_license
#include <cmath> #include "lib.h" using namespace std; double length(vector<double> v1, vector<double> v2){ if(v1.size() != v2.size()) return 0; double su2=0; for(int i=0 ; i<v1.size(); i++) su2 = su2 + pow(v1[i] - v2[i],2); return sqrt(su2); }
true
658cbf7d8a385dc9b98969309e7ab20d3cdc3c9f
C++
matherno/MathernoGL
/src/maths/RaycastOperations.cpp
UTF-8
1,105
2.953125
3
[ "BSD-3-Clause" ]
permissive
#include <maths/RaycastOperations.h> namespace mathernogl { Vector3D getRaycastIntersectionOnXZPlane(const Raycast& raycast, const double planeOffset){ Vector3D intersectPoint; if(raycast.direction.y == 0){ if(raycast.position.y == planeOffset){ throw mgl_no_intersection("Raycast does not intersect at a point on the XZ plane with offset " + std::to_string(planeOffset) + ". It is parallel and on the plane. "); } throw mgl_no_intersection("Raycast does not intersect the XZ plane with offset " + std::to_string(planeOffset) + ". It is parallel the plane. "); } const double tValue = (planeOffset - raycast.position.y) / raycast.direction.y; if(tValue < raycast.minTValue || tValue > raycast.maxTValue){ throw mgl_no_intersection("Raycast does not intersect the XZ plane with offset " + std::to_string(planeOffset) + ". The raycasts bounds prevent it from intersecting "); } intersectPoint.x = raycast.position.x + raycast.direction.x * tValue; intersectPoint.y = planeOffset; intersectPoint.z = raycast.position.z + raycast.direction.z * tValue; return intersectPoint; } }
true
ead9c3e21d35963481ace38ea5542012f9d5609b
C++
Abhi-BearMunk/R-Game-Engine-DX12
/DX12Engine/Core/RGame.cpp
UTF-8
1,590
2.90625
3
[ "MIT" ]
permissive
#include <algorithm> #include <iostream> #include "RGame.h" //#include "RWindow.h" #include "REntity.h" namespace R { RGame::RGame() { } std::weak_ptr<REntity> RGame::CreateEntity() { auto entity = std::make_shared<REntity>(*this); entity->SetSelf(entity); entities.push_back(entity); return entity; } void RGame::KillEntity(std::weak_ptr<REntity> entity) { dyingEntities.push_back(entity); } void RGame::KillDyingEntities() { std::for_each(dyingEntities.begin(), dyingEntities.end(), [this](std::weak_ptr<REntity> entity) { entities.remove(entity.lock()); }); dyingEntities.clear(); } bool RGame::Init() { // Create Window /*if (!gameWindow->Init()) { return false; }*/ // Create entities etc. Setup(); // Start Entities; std::for_each(entities.begin(), entities.end(), [](const auto& entity) {entity->Start(); }); return true; } void RGame::Update() { // Rendering //gameWindow->PreUpdate(); // GamePlay ProcessGlobalInputs(); std::for_each(entities.begin(), entities.end(), [](const auto& entity) {entity->Update(); }); auto showmessage = entities.size() > 0; //gameWindow->PostProcess(); //gameWindow->FinishUpdate(); KillDyingEntities(); //isRunning = !glfwWindowShouldClose(gameWindow->window); if (showmessage) { std::cout << "Num entities = " << entities.size() << "\n"; } } void RGame::Quit() { //glfwSetWindowShouldClose(gameWindow->window, true); } const bool& RGame::GetIsRunning() const { return isRunning; } void RGame::ProcessGlobalInputs() { } }
true
cd07446a417f23e97b939263c3d3d9064150ba56
C++
HackerEva/RebornEngine
/RebornEngine/RBScene/RBScene.cpp
UTF-8
9,071
2.5625
3
[]
no_license
#include "RBScene.h" #include <sstream> namespace RebornEngine { void RBScene::Initialize() { cbPerObject.Initialize(); cbScene.Initialize(); cbBoneMatrices.Initialize(); cbLight.Initialize(); cbMaterial.Initialize(); cbGlobal.Initialize(); } void RBScene::Release() { DestroyAllObjects(); cbPerObject.Release(); cbScene.Release(); cbBoneMatrices.Release(); cbLight.Release(); cbMaterial.Release(); cbGlobal.Release(); } RBSceneMeshObject * RBScene::CreateMeshObject(const char * meshName) { RBMesh* mesh = RBResourceManager::Instance().FindMesh(meshName); assert(mesh); return CreateMeshObject(mesh); } RBSceneMeshObject * RBScene::CreateMeshObject(RBMesh * mesh) { RBSceneMeshObject* meshObject = new RBSceneMeshObject(); meshObject->SetMesh(mesh); m_SceneObjects.push_back(meshObject); return meshObject; } RBSceneObject * RBScene::CloneObject(RBSceneObject * obj) { RBSceneObject* tObj = obj->Clone(); AddObjectToScene(tObj); return obj->Clone(); } RBSceneObject * RBScene::FindObject(const char * name) const { for (UINT i = 0; i < m_SceneObjects.size(); i++) { if (m_SceneObjects[i]->GetName() == name) return m_SceneObjects[i]; } return nullptr; } bool RBScene::AddObjectToScene(RBSceneObject * obj) { std::vector<RBSceneObject*>::iterator iter = find(m_SceneObjects.begin(), m_SceneObjects.end(), obj); if (iter == m_SceneObjects.end()) { m_SceneObjects.push_back(obj); return true; } return false; } void RBScene::RemoveObjectFromScene(RBSceneObject * obj) { std::vector<RBSceneObject*>::iterator iter = find(m_SceneObjects.begin(), m_SceneObjects.end(), obj); if (iter != m_SceneObjects.end()) { m_SceneObjects.erase(iter); } } void RBScene::DestroyObject(RBSceneObject * obj) { for (UINT i = 0; i < m_SceneObjects.size(); i++) { delete m_SceneObjects[i]; } m_SceneObjects.clear(); } void RBScene::DestroyAllObjects() { for (UINT i = 0; i < m_SceneObjects.size(); i++) { delete m_SceneObjects[i]; } m_SceneObjects.clear(); } void RBScene::LoadFromFile(const char * filename) { tinyxml2::XMLDocument* doc = new tinyxml2::XMLDocument(); if (doc->LoadFile(filename) == tinyxml2::XML_SUCCESS) { tinyxml2::XMLElement* root = doc->RootElement(); tinyxml2::XMLElement* elem_obj = root->FirstChildElement("SceneObject"); while (elem_obj) { const char* name = elem_obj->Attribute("Name"); const char* script = elem_obj->Attribute("Script"); tinyxml2::XMLElement* elem_transform = elem_obj->FirstChildElement("Transform"); RBMatrix4x4 transform; int n = 0; std::stringstream ss(elem_transform->GetText()); while (ss >> ((float*)&transform)[n++] && n < 16) { if (ss.peek() == ',') ss.ignore(); } RBSceneObject* sceneObj = nullptr; string obj_type = elem_obj->Attribute("Type"); if (obj_type == "MeshObject") { const char* resPath = elem_obj->Attribute("Mesh"); RBMesh* mesh = RBResourceManager::Instance().FindMesh(resPath); if (!mesh) { mesh = RBResourceManager::Instance().LoadFbxMesh(resPath, RB_RLM_Immediate); } RBSceneMeshObject* meshObj = CreateMeshObject(resPath); meshObj->SetTransform(transform); sceneObj = meshObj; tinyxml2::XMLElement* elem_mat = elem_obj->FirstChildElement("Material"); vector<RBMaterial> xmlMaterials; if (elem_mat) { for (int i = 0; i < meshObj->GetMeshElementCount(); i++) { xmlMaterials.push_back(*meshObj->GetMaterial(i)); } } while (elem_mat) { int index = elem_mat->IntAttribute("Index"); tinyxml2::XMLElement* elem = elem_mat->FirstChildElement("MeshElement"); while (elem) { const char* shaderName = elem->Attribute("Shader"); RBMaterial material = { nullptr, 0 }; material.Shader = RBShaderManager::Instance().GetShaderResource(shaderName); tinyxml2::XMLElement* elem_tex = elem->FirstChildElement(); while (elem_tex) { const char* textureName = elem_tex->GetText(); RBTexture* texture = RBResourceManager::Instance().FindTexture(textureName); if (!texture) { texture = RBResourceManager::Instance().LoadDDSTexture(RBResourceManager::GetResourcePath(textureName).data(), RB_RLM_Immediate); } material.Textures[material.TextureNum++] = texture; elem_tex = elem_tex->NextSiblingElement(); } xmlMaterials[index] = material; elem = elem->NextSiblingElement(); } elem_mat = elem_mat->NextSiblingElement("Material"); } if (xmlMaterials.size()) { meshObj->SetMaterial(xmlMaterials.data(), (int)xmlMaterials.size()); } } if (name) sceneObj->SetName(name); if (script) sceneObj->SetScript(script); elem_obj = elem_obj->NextSiblingElement(); } } delete doc; } void RBScene::SaveToFile(const char * filename) { tinyxml2::XMLDocument* doc = new tinyxml2::XMLDocument(); tinyxml2::XMLElement* elem_scene = doc->NewElement("Scene"); for (vector<RBSceneObject*>::iterator iter = m_SceneObjects.begin(); iter != m_SceneObjects.end(); iter++) { tinyxml2::XMLElement* elem_obj = doc->NewElement("SceneObject"); if ((*iter)->GetName() != "") { elem_obj->SetAttribute("Name", (*iter)->GetName().c_str()); } if ((*iter)->GetScript() != "") { elem_obj->SetAttribute("Script", (*iter)->GetScript().c_str()); } if ((*iter)->GetType() == RB_SO_MeshObject) { elem_obj->SetAttribute("Type", "MeshObject"); RBSceneMeshObject* meshObj = (RBSceneMeshObject*)(*iter); RBMesh* mesh = meshObj->GetMesh(); elem_obj->SetAttribute("Mesh", mesh->GetPath().c_str()); // Save materials for (int i = 0; i < meshObj->GetMeshElementCount(); i++) { RBMaterial meshMaterial = mesh->GetMaterial(i); RBMaterial* objMaterial = meshObj->GetMaterial(i); bool exportMaterial = false; if (meshMaterial.Shader != objMaterial->Shader || meshMaterial.TextureNum != objMaterial->TextureNum) { exportMaterial = true; } if (!exportMaterial) { for (int j = 0; j < meshMaterial.TextureNum; j++) { if (meshMaterial.Textures[j] != objMaterial->Textures[j]) { exportMaterial = true; break; } } } if (exportMaterial) { tinyxml2::XMLElement* elem_mat = doc->NewElement("Material"); elem_mat->SetAttribute("Index", i); meshObj->SerializeMaterialsToXML(doc, elem_mat); elem_obj->InsertEndChild(elem_mat); } } } // Save transformation const RBMatrix4x4& t = (*iter)->GetNodeTransform(); tinyxml2::XMLElement* elem_trans = doc->NewElement("Transform"); char msg_buf[512]; sprintf_s(msg_buf, 512, "%f, %f, %f, %f, " "%f, %f, %f, %f, " "%f, %f, %f, %f, " "%f, %f, %f, %f", t._m11, t._m12, t._m13, t._m14, t._m21, t._m22, t._m23, t._m24, t._m31, t._m32, t._m33, t._m34, t._m41, t._m42, t._m43, t._m44); elem_trans->SetText(msg_buf); elem_obj->InsertEndChild(elem_trans); elem_scene->InsertEndChild(elem_obj); } doc->InsertEndChild(elem_scene); doc->SaveFile(filename); } RBVector3 RBScene::TestMovingAabbWithScene(const RBAABB& aabb, const RBVector3& moveVec) { RBVector3 v = moveVec; for (vector<RBSceneObject*>::iterator iter = m_SceneObjects.begin(); iter != m_SceneObjects.end(); iter++) { if ((*iter)->GetType() == RB_SO_MeshObject) { RBSceneMeshObject* meshObj = (RBSceneMeshObject*)(*iter); if (aabb.GetSweptAabb(v).TestIntersectionWithAabb(meshObj->GetAabb())) { for (int i = 0; i < meshObj->GetMeshElementCount(); i++) { RBAABB elemAabb = meshObj->GetMeshElementAabb(i).GetTransformedAabb(meshObj->GetNodeTransform()); v = aabb.TestDynamicCollisionWithAabb(v, elemAabb); } } } } return v; } void RBScene::Render(const RBFrustum * pFrustum) { for (vector<RBSceneObject*>::iterator iter = m_SceneObjects.begin(); iter != m_SceneObjects.end(); iter++) { if (pFrustum && !RBCollision::TestAABBInsideFrustum(*pFrustum, (*iter)->GetAabb())) continue; SHADER_OBJECT_BUFFER cbObject; cbObject.worldMatrix = (*iter)->GetNodeTransform(); cbPerObject.UpdateContent(&cbObject); cbPerObject.ApplyToShaders(); (*iter)->Draw(); } } void RBScene::RenderDepthPass(const RBFrustum * pFrustum) { for (vector<RBSceneObject*>::iterator iter = m_SceneObjects.begin(); iter != m_SceneObjects.end(); iter++) { if (pFrustum && !RBCollision::TestAABBInsideFrustum(*pFrustum, (*iter)->GetAabb())) continue; SHADER_OBJECT_BUFFER cbObject; cbObject.worldMatrix = (*iter)->GetNodeTransform(); cbPerObject.UpdateContent(&cbObject); cbPerObject.ApplyToShaders(); (*iter)->DrawDepthPass(); } } vector<RBSceneObject*>& RBScene::GetSceneObjects() { return m_SceneObjects; } }
true
d2a600373304ad3486da4db7d30e8ee1876a40d0
C++
vishuchhabra/cp_programs
/equivalent_string_codefroces.cpp
UTF-8
1,526
3.03125
3
[]
no_license
#include<iostream> #include<bits/stdc++.h> using namespace std; bool check_e(string first,string second) { sort(first.begin(),first.end()); sort(second.begin(),second.end()); if(first==second) return true; return false; } int main() { string first,second; cin>>first>>second; if(first.size()!=second.size()) cout<<"NO"<<endl; else if(first==second) cout<<"YES"<<endl; else { //odd cases if(first.size()%2==0) { int m1 = first.size()/2; string f1 = first.substr(0,m1); string f2 = second.substr(0,m1); string s1 = first.substr(m1,m1); string s2 =second.substr(m1,m1); bool res1 = (check_e(f1,s1)&&check_e(f2,s2))||(check_e(f1,s2)&&check_e(f2,s1)); if(res1) cout<<"YES"<<endl; else cout<<"NO"<<endl; } else { int m2 = first.size()/2; // if(first[m2]!=second[m2]) // cout<<"NO"<<endl; // else // { string s3,s4,f3,f4; f3= first.substr(0,m2); f4 = second.substr(0,m2); s3 =first.substr(m2+1,m2); s4 =second.substr(m2+1,m2); bool res1 = (check_e(f3,s3)&&check_e(f4,s4))||(check_e(f3,s4)&&check_e(f4,s3)); if(res1) cout<<"YES"<<endl; else cout<<"NO"<<endl; // } } } return 0; }
true
8f7ec8474a703481568249406df7616f3059258f
C++
Girl-Code-It/Beginner-CPP-Submissions
/Urvashi/milestone-20(bitwise manipulation)/geeks basic bits questions/check if k'th bit is set or not in a number.cpp
UTF-8
202
2.828125
3
[]
no_license
#include <iostream> using namespace std; int main() { int n, k; cin >> n >> k; //check if kth bit is set or not means it is 1 or not. (n & (1 << (k - 1))) ? cout << "SET\n" : cout << "UNSET\n"; }
true
5e0e20d13cc599fe995ee5692527662869edbc57
C++
linhanyu/ACM
/newStudent/4442.cpp
UTF-8
866
2.8125
3
[]
no_license
// // Created by Henry on 17/3/5. // #include <cstdio> #include <algorithm> typedef long long LL; using namespace std; const int MOD = 365*24*60*60; const int MAXN = 100000 + 10; struct node{ LL a,b; double cost; bool operator<(const node & n)const{ return cost > n.cost; } }s[MAXN]; void calCost(node & n,LL tot){ n.cost = n.b*1.0/n.a; } int main(){ int n; while (~scanf("%d",&n) && n){ LL tot = 0; for (int i = 0; i < n; ++i) { scanf("%d%d",&s[i].a,&s[i].b); tot += s[i].b; } for (int i = 0; i < n; ++i) { calCost(s[i],tot); } sort(s,s + n); LL ans = 0,tadd = 0; for (int i = 0; i < n; ++i) { tot -= s[i].b; ans = (ans + s[i].b*ans + s[i].a)%MOD; } printf("%lld\n",ans); } }
true
01ad9816cd89aa8bd78d1bceb8fed1b7c69365ed
C++
macias2k4/ExploreBot
/exploreBot/app/App.cpp
UTF-8
1,576
2.53125
3
[]
no_license
#include "App.hpp" #include "stm32f4xx_hal.h" using namespace std; namespace ExploreBot { // ────────────────────────────────────────────────────────────────────────────────────────────── // App::App(funct::AppModeChange::IAppModeChanger& appModeChanger, funct::InterruptHandling::InterruptsHandlerCaller& interruptsHandlerCaller, Lib::Peripherals::Logger::ILogger& logger) : _appModeChanger { appModeChanger } , _interruptsHandlerCaller { interruptsHandlerCaller } , _logger { logger } {} // ────────────────────────────────────────────────────────────────────────────────────────────── // void App::exec() noexcept { _appModeChanger.addObserver(*this); if (!_appModeChanger.changeToStartingMode()) { return; } while (true) { _currentAppMode->executeStep(); } } void App::updateAppMode(funct::AppMode::AppModePtr appMode) noexcept { _currentAppMode = appMode; _logger.info(string { "Changed AppMode to '" }.append(_currentAppMode->modeName()).append("'")); } std::optional<bool> App::callHandler(Lib::Common::GPIO::GPIOPin gpioPin) noexcept { return _interruptsHandlerCaller.callHandler(gpioPin); } } // namespace ExploreBot
true
e2d10d50db723b3a7f50c04239e6f1745fde9394
C++
tia337/ownProgbase
/progbase2/tasks/qt_windows/qt_windows/taxidriver.h
UTF-8
385
2.671875
3
[]
no_license
#ifndef TAXIDRIVER_H #define TAXIDRIVER_H #include <iostream> using namespace std; class TaxiDriver { string _name; int _age; double _salary; int _clients; public: TaxiDriver(); TaxiDriver(string name, int age, double salary, int clients); ~TaxiDriver(); string name(); int age(); double salary(); int clients(); }; #endif // TAXIDRIVER_H
true
731c3e8ae802fa4848dd1deacc88639698818c54
C++
joshpintea/ChessBoardDetection
/Util.cpp
UTF-8
1,440
2.84375
3
[]
no_license
#include "stdafx.h" #include "Util.h" #include <opencv2/shape/hist_cost.hpp> #include <opencv2/highgui.hpp> bool isInside(Mat img, int row, int col) { return (row >= 0 && row < img.rows) && (col >= 0 && col < img.cols); } float filter(Mat source, Mat mask, int row, int col) { int hs_r = (mask.rows / 2); int hs_c = (mask.cols / 2); float out = 0; for (int u = 0; u < hs_r; ++u) { for (int v = 0; v < hs_c; ++v) { int r = row + u - hs_r; int c = col + v - hs_c; if (isInside(source, r, c)) { out += (mask.at<float>(u, v) * source.at<float>(r, c)); } } } return out; } Mat convolution(Mat source, Mat mask) { Mat destination(source.rows, source.cols, CV_32FC1); int hs_r = mask.rows / 2; int hs_c = mask.cols / 2; for (int r = hs_r; r < source.rows - hs_r; ++r) { for (int c = hs_c; c < source.cols - hs_c; c++) { destination.at<float>(r, c) = filter(source, mask, r, c); } } return destination; } void harrisCorners(Mat source) { Mat gray; cvtColor(source, gray, COLOR_BGR2GRAY); imshow("Img gray", gray); imshow("Original image", source); float sobel_x[9] = { -1.0f, 0.0f, 1.0f, -2.0f, 0.0f, 2.0f, -1.0f, 0.0f, 1.0f }; float sobel_y[9] = { -1.0f, -2.0f, -1.0f, 0.0, 0.0f, 0.0f, 1.0f, 2.0f, 1.0f }; Mat mask_x(3, 3, CV_32FC1, sobel_x); Mat mask_y(3, 3, CV_32FC1, sobel_y); Mat pxFilter = convolution(gray, mask_x); Mat pyFilter = convolution(gray, mask_y); }
true
403bcca6f96efbebd171ff1c6bf83f70d45dbeac
C++
Miguel235711/CompetitiveProgrammingAndMore
/Oracle Top Tec Programmer 2020/Virtual Contest 2/F/main.cpp
UTF-8
1,057
2.5625
3
[]
no_license
#include<bits/stdc++.h> using namespace std ; int n,ai; struct es{ int hi,oc; es(){} es(int hi,int oc){ this->hi=hi; this->oc=oc; } }; int64_t checkAns(int hi,int totalOccurrences,int64_t ans){ return max(ans,(int64_t)totalOccurrences * hi); } int main(){ ios_base::sync_with_stdio(0);cin.tie(0); while(cin>>n,n){ int64_t ans = 0 ; stack<es>myStack; for(int i = 0 ; i <= n ; i ++){ if(i<n){ cin >> ai; }else{ ai=0; } int totalOccurrences = 0 ; if(!myStack.empty()&& ai<myStack.top().hi){ //poping while(!myStack.empty() && myStack.top().hi>ai){ totalOccurrences += myStack.top().oc; ans = checkAns(myStack.top().hi,totalOccurrences,ans); myStack.pop(); } } myStack.push(es(ai,totalOccurrences+1)); } cout << ans << "\n"; } return 0; }
true
16aead9994ff9cfa9e475bd4d293872bcc2d7be5
C++
chuanran/parallel-merge-sort
/ParallelMergeSort/Timer.h
UTF-8
559
3.078125
3
[]
no_license
#ifndef TIMER_H #define TIMER_H // 0 - ClockTimer, 1 - QPCTimer, 2 - CudaTimer #define TIMER_TYPE 1 #include <string> #include <sstream> using std::ostringstream; class Timer { protected: bool started; bool paused; double accumulatedTime; virtual void MeasureStartTime() = 0; virtual void MeasureStopTime() = 0; virtual double CalculateDifference() = 0; public: // Starts a timer Timer(); void Start(); // Stops the timer and returns the time in msecs double Stop(); static void Print(ostringstream* str); }; #endif
true
b1a1b24d1c4912acace96d7824c8424896d48406
C++
alanpreed/ArduinoOBD
/ArduinoOBD/ArduinoOBD.ino
UTF-8
4,361
2.6875
3
[]
no_license
#include "Block.h" #include "KW1281.h" #include "Debug.h" #include "Error.h" #include "Display.h" #include "Button.h" #include "ControlPanel.h" #define CONNECT_BUTTON 4 #define PLUS_BUTTON 2 #define MINUS_BUTTON 3 #define OBD_RX 0 #define OBD_TX 1 typedef enum { DISCONNECTED, CONNECTING, RECEIVE_HEADER, RECEIVE_DATA, DISCONNECTING, ERROR, } State; KW1281 obd(OBD_RX,OBD_TX); ControlPanel& panel = ControlPanel::get_instance(PLUS_BUTTON, MINUS_BUTTON, CONNECT_BUTTON); Display display; State current_state; Error current_error; Block rx_block; Block tx_block; void enter_error_state(Error error); void setup() { Debug.init(); Debug.println(F("Arduino OBD Interface")); display.init(); current_state = DISCONNECTED; current_error = SUCCESS; panel.enable(); } void loop() { switch(current_state) { case DISCONNECTED: if(panel.check_selector()) { display.clear(); } display.show_disconnected(panel.current_group); if(panel.check_connect()) { current_state = CONNECTING; panel.disable(); display.clear(); } break; case CONNECTING: display.show_connecting(panel.current_group); if(obd.connect(0x01, 9600)) { current_state = RECEIVE_HEADER; display.clear(); } else { Debug.println(F("ERROR: Connection failed")); enter_error_state(CONNECT_ERROR); } break; case RECEIVE_HEADER: display.show_header(panel.current_group); tx_block.len = 4; tx_block.title = GROUP_REQUEST; tx_block.data[0] = panel.current_group; if(!obd.send_block(tx_block)) { Debug.println(F("ERROR: Initial group request failed")); enter_error_state(TX_ERROR); } else if(!obd.receive_block(rx_block)) { Debug.println(F("ERROR: Didn't receive header")); enter_error_state(RX_ERROR); } else if(rx_block.title != HEADER && rx_block.title != GROUP_DATA) // Only the first group selection sends a header { Debug.print(F("ERROR: Wrong block type: ")); Debug.println(rx_block.title, HEX); enter_error_state(RX_ERROR); current_state = RECEIVE_DATA; panel.enable(); display.clear(); } else { current_state = RECEIVE_DATA; panel.enable(); display.clear(); } break; case RECEIVE_DATA: if(panel.check_connect()) { current_state = DISCONNECTING; panel.disable(); display.clear(); } else if(panel.check_selector()) { current_state = RECEIVE_HEADER; panel.disable(); display.clear(); } else { if(!obd.send_block(tx_block)) { Debug.println(F("ERROR: Group request failed")); enter_error_state(TX_ERROR); } else if(!obd.receive_block(rx_block) || rx_block.title != GROUP_DATA) { Debug.println(F("ERROR: Failed to receive data")); enter_error_state(RX_ERROR); } else { display.show_group(panel.current_group, rx_block.data[0], rx_block.data[1], rx_block.data[2], rx_block.data[3]); } } break; case DISCONNECTING: display.show_disconnecting(); tx_block.len = 3; tx_block.title = END; if(!obd.send_block(tx_block)) { Debug.println(F("ERROR: disconnect not sent")); enter_error_state(TX_ERROR); } else if(!obd.receive_block(rx_block) || rx_block.title != ACK) { Debug.println(F("ERROR: disconnect not acknowledged")); enter_error_state(RX_ERROR); } else { current_state = DISCONNECTED; obd.disconnect(); panel.enable(); display.clear(); } break; case ERROR: display.show_error(current_error); if(panel.check_connect()) { current_state = DISCONNECTED; current_error = SUCCESS; panel.enable(); display.clear(); } break; } } void enter_error_state(Error error) { current_error = error; current_state = ERROR; obd.disconnect(); panel.enable(); display.clear(); }
true
bcb521c56a0f12ae7c87425752160ccf717c2964
C++
gorbunov-dmitry/rucode-spring-2021-d
/3/c3.cpp
UTF-8
2,781
3.296875
3
[ "MIT" ]
permissive
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> long long dot ( const std::pair<long long, long long>& a, const std::pair<long long, long long>& b ) { return a.first * b.first + a.second * b.second; } long double distance ( const std::pair<long long, long long>& a, const std::pair<long long, long long>& b ) { return sqrt(pow(a.first - b.first, 2) + pow(a.second - b.second, 2)); } long double distance ( const std::pair<long long, long long>& p, const std::pair<long long, long long>& a, const std::pair<long long, long long>& b ) { std::pair<long long, long long> ab(b.first - a.first, b.second - a.second); std::pair<long long, long long> ba(a.first - b.first, a.second - b.second); std::pair<long long, long long> ap(p.first - a.first, p.second - a.second); std::pair<long long, long long> bp(p.first - b.first, p.second - b.second); long double result; if (dot(ap, ab) <= 0) { result = distance(p, a); } else if (dot(bp, ba) <= 0) { result = distance(p, b); } else { long long dx_p_b = b.first - p.first; long long dy_p_b = b.second - p.second; long long dx_p_a = a.first - p.first; long long dy_p_a = a.second - p.second; result = (abs(dy_p_b * dx_p_a - dx_p_b * dy_p_a)) / distance(a, b); } return result; } long long area ( const std::pair<long long, long long>& a, const std::pair<long long, long long>& b, const std::pair<long long, long long>& c ) { return (b.first - a.first) * (c.second - a.second) - (b.second - a.second) * (c.first - a.first); } inline bool intersects(int a, int b, int c, int d) { if (a > b) { std::swap(a, b); } if (c > d) { std::swap(c, d); } return std::max(a, c) <= std::min(b, d); } bool intersects ( const std::pair<long long, long long>& a, const std::pair<long long, long long>& b, const std::pair<long long, long long>& c, const std::pair<long long, long long>& d ) { return intersects(a.first, b.first, c.first, d.first) && intersects(a.second, b.second, c.second, d.second) && area(a, b, c) * area(a, b, d) <= 0 && area(c, d, a) * area(c, d, b) <= 0; } int main() { std::pair<long long, long long> a; std::pair<long long, long long> b; std::pair<long long, long long> c; std::pair<long long, long long> d; std::cin >> a.first >> a.second >> b.first >> b.second >> c.first >> c.second >> d.first >> d.second; long double result = 0; if (intersects(a, b, c, d)) { result = 0; } else { long double d1 = distance(a, c, d); long double d2 = distance(b, c, d); long double d3 = distance(c, a, b); long double d4 = distance(d, a, b); auto a = { d1, d2, d3, d4 }; result = *std::min_element(a.begin(), a.end()); } std::cout << std::fixed << std::setprecision(10) << result << '\n'; return 0; }
true
321b67d96ac4955623fb09decb7b54c685d54690
C++
adamgann/arduino_halloween
/arduino_halloween.ino
UTF-8
2,304
3.203125
3
[]
no_license
/* Halloween Costume 2014 Version 1.1 */ // Pin Setup int tleft = 2; int bleft = 5; int tright = 6; int bright = 3 ; int center = 9; //Timing int delayBetweenCycles = 30*1000; void setup(void) { pinMode(tleft,OUTPUT); pinMode(bleft,OUTPUT); pinMode(tright,OUTPUT); pinMode(bright,OUTPUT); pinMode(center,OUTPUT); digitalWrite(tleft, LOW); digitalWrite(bleft, LOW); digitalWrite(tright,LOW); digitalWrite(bright,LOW); digitalWrite(center,LOW); } void loop(void) { startup_sequence(); delay(delayBetweenCycles); all_off(); delay(delayBetweenCycles); fade_circle(center,15); delay(delayBetweenCycles); } void startup_sequence(void) { digitalWrite(center,HIGH); delay(1000); flash_circle(200,3); all_on(); delay(1500); all_off(); digitalWrite(center,HIGH); flash_circle(70,4); all_on(); delay(1500); all_off(); digitalWrite(tleft,HIGH); digitalWrite(center,HIGH); } void all_on(void) { digitalWrite(tleft,HIGH); digitalWrite(bleft,HIGH); digitalWrite(tright,HIGH); digitalWrite(bright,HIGH); digitalWrite(center,HIGH); } void all_off(void) { digitalWrite(tleft,LOW); digitalWrite(bleft,LOW); digitalWrite(tright,LOW); digitalWrite(bright,LOW); digitalWrite(center,LOW); } void flash_one(int pin, int delay_ms) { digitalWrite(pin,HIGH); delay(delay_ms); digitalWrite(pin,LOW); delay(delay_ms); } void flash_all(int delay_ms) { all_on(); delay(delay_ms); all_off(); delay(delay_ms); } void flash_circle(int delay_ms, int ntimes) { for (int ii=0; ii<ntimes; ii++) { flash_one(tleft,delay_ms); flash_one(tright,delay_ms); flash_one(bright,delay_ms); flash_one(bleft,delay_ms); } } void fade_up(int led) { int brightness = 0; int fadeAmount = 5; do{ analogWrite(led,brightness); brightness= brightness + fadeAmount; delay(30); } while(brightness != 255); } void fade_down(int led) { int brightness = 255; int fadeAmount = 5; do{ analogWrite(led,brightness); brightness= brightness - fadeAmount; delay(30); } while(brightness != 0); } void fade_circle(int led, int ntimes) { for (int ii=0;ii<ntimes;ii++) { digitalWrite(led,LOW); fade_up(led); fade_down(led); digitalWrite(led,LOW); } }
true
0e01c476f097c32229951e59d2ed06d9a6149d14
C++
gcorcorann/raytracing
/tests/test_triangle.cpp
UTF-8
527
2.765625
3
[]
no_license
#include <iostream> #include <cassert> #include "../triangle.h" #include "../ray.h" #include "../vector.h" int main() { Vector a = {-100, 0, -10}; Vector b = {100, 0, -10}; Vector c = {0, 100, -10}; Vector colour = {1, 0, 0}; Triangle tri = {a, b, c, colour}; Vector e = {0, 10, 0}; Vector d = {0, 0, -1}; Ray ray = {e, d}; Vector n = {0, 0, 0}; Vector p = {0, 0, 0}; float t; bool hit = tri.hit(ray, n, p, t); assert (hit == true); assert (t == 10); return 0; }
true
73991fc5a216ade2fbc9718549f2e5c6b2b6fb13
C++
sstopkin/my-car-pc
/client/Desktop/joystick.h
UTF-8
2,318
2.71875
3
[]
no_license
#ifndef JOYSTICK_H #define JOYSTICK_H #include <QObject> #include "SDL/SDL_joystick.h" #include <QThread> #include <QStringList> class JoystickAdapter : public QObject { Q_OBJECT Q_DISABLE_COPY(JoystickAdapter) public: enum HatPosition { JOYSTICK_HAT_CENTERED = SDL_HAT_DOWN, JOYSTICK_HAT_UP = SDL_HAT_UP, JOYSTICK_HAT_UP_RIGHT = SDL_HAT_RIGHT, JOYSTICK_HAT_RIGHT = SDL_HAT_RIGHT, JOYSTICK_HAT_RIGHT_DOWN = SDL_HAT_RIGHTDOWN, JOYSTICK_HAT_DOWN = SDL_HAT_DOWN, JOYSTICK_HAT_DOWN_LEFT = SDL_HAT_LEFTDOWN, JOYSTICK_HAT_LEFT = SDL_HAT_LEFT, JOYSTICK_HAT_LEFT_UP = SDL_HAT_LEFTUP }; public: explicit JoystickAdapter(QObject *parent = 0); ~JoystickAdapter(); bool open(int id); void close(); bool isConnected() const { return m_joystick ? SDL_JoystickOpened(getJoystickId()) : false; } inline int getJoystickId() const { return SDL_JoystickIndex(m_joystick); } inline QString getJoystickName() const { return QString(SDL_JoystickName(getJoystickId())); } inline int getJoystickNumAxes() const { return SDL_JoystickNumAxes(m_joystick); } inline int getJoystickNumHats() const { return SDL_JoystickNumHats(m_joystick); } inline int getJoystickNumBalls() const { return SDL_JoystickNumBalls(m_joystick); } inline int getJoystickNumButtons() const { return SDL_JoystickNumButtons(m_joystick); } static int getNumAvaliableJoystick(); static QStringList getAvaliableJoystickName(); signals: void sigButtonChanged(int id, bool state); void sigAxisChanged(int id, int state); void sigHatCanged(int id, int state); void sigBallChanged(int id, int stateX, int stateY); private: class JoystickThread; SDL_Joystick* m_joystick; JoystickThread* m_joystickThread; }; class JoystickAdapter::JoystickThread : public QThread { Q_OBJECT public: inline JoystickThread(JoystickAdapter* adapter) : m_adapter(adapter) { } protected: virtual void run(); private: JoystickAdapter *m_adapter; }; #endif // JOYSTICK_H
true
3ac205a398abd3d1ee482ebcc0582a395d360e29
C++
lainproliant/moonlight
/test/color.cpp
UTF-8
1,416
2.921875
3
[ "MIT", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "Zlib" ]
permissive
/* * color.cpp * * Author: Lain Musgrove (lain.proliant@gmail.com) * Date: Thursday March 18, 2021 * * Distributed under terms of the MIT license. */ #include "moonlight/color.h" #include "moonlight/test.h" using namespace moonlight; using namespace moonlight::color; using namespace moonlight::test; int main() { return TestSuite("moonlight color tests") .test("verify HSV/RGB conversion and back", []() { auto rgbMagenta = uRGB::of(0xFF00FF); auto frgbMagenta = static_cast<fRGB>(rgbMagenta); auto hsvMagenta = static_cast<fHSV>(rgbMagenta); std::cout << "rgbMagenta = " << rgbMagenta << std::endl; std::cout << "frgbMagenta = " << frgbMagenta << std::endl; std::cout << "hsvMagenta = " << hsvMagenta << std::endl; ASSERT_EP_EQUAL(hsvMagenta.h, 300.0f, 0.01f); ASSERT_EP_EQUAL(hsvMagenta.s, 1.0f, 0.01f); ASSERT_EP_EQUAL(hsvMagenta.v, 1.0f, 0.01f); ASSERT_EQUAL(rgbMagenta, static_cast<uRGB>(hsvMagenta)); }) .test("verify HSV color wheel rotation and conversion back to RGB", []() { auto hsvRed = static_cast<fHSV>(uRGB::of(0xAC0000)); auto rgbCyan = uRGB::of(0x00ACAC); fHSV hsvCyan = { hsvRed.h + 180.0f, hsvRed.s, hsvRed.v }; std::cout << "static_cast<uRGB>(hsvCyan) = " << static_cast<uRGB>(hsvCyan) << std::endl; ASSERT_EQUAL(rgbCyan, static_cast<uRGB>(hsvCyan)); }) .run(); }
true
3f2cd3baf2ff5468d2f0817adf567bc3a0d90763
C++
williamokano/uri-judge-answers
/1/1071.cpp
UTF-8
440
3.03125
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; /* solucao 1067 */ int main() { int A, B, limite1, limite2, counter = 0; cin >> A >> B; limite1 = A; limite2 = B; if (A > B) { limite1 = B; limite2 = A; } limite1++; for (int i = limite1; i < limite2; i++) { if (abs(i % 2) == 1) { counter += i; } } cout << counter << endl; return 0; }
true