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
f980ae2b0bf2452f2c02605b1e25ec62bacf5b21
C++
warelab/snapdragon
/src/bvec/bvec.cpp
UTF-8
5,646
3.203125
3
[ "MIT" ]
permissive
#include "bvec.h" // constructor - given a sorted vector of distinct 32bit integers BitVector::BitVector(vector<word_t>& vals) { count = vals.size(); // if the density is too low, run length encoding will take MORE space if (lowDensity(vals)) { if (DEBUG) printf("constructed non rle\n"); words = vals; rle = false; size = words.back(); } else { if (DEBUG) printf("constructRLE\n"); constructRLE(vals); } } vector<word_t>& BitVector::getWords() { return words; } word_t BitVector::getSize() { return size; } word_t BitVector::bytes() { return 4 * words.size(); } void BitVector::compress() { if (rle) { /* Throw exception? */ return; } vector<word_t> tmp; tmp.swap(words); constructRLE(tmp); } // in place version of the bitwise OR operator. void BitVector::operator|=(BitVector& bv) { // decide which version we'll be using if (rle) if (bv.rle) rleORrle(bv); else rleORnon(bv); else if (bv.rle) nonORrle(bv); else nonORnon(bv); } // in place version of the bitwise AND operator. void BitVector::operator&=(BitVector& bv) { // decide which version we'll be using if (rle) if (bv.rle) rleANDrle(bv); else rleANDnon(bv); else if (bv.rle) nonANDrle(bv); else nonANDnon(bv); } BitVector* BitVector::operator|(BitVector& rhs) { BitVector *res = new BitVector(); if (words.size() > rhs.words.size()) { res->copy(rhs); *res |= *this; return res; } res->copy(*this); *res |= rhs; return res; } BitVector* BitVector::operator&(BitVector& rhs) { BitVector *res = new BitVector(); if (words.size() > rhs.words.size()) { res->copy(rhs); *res &= *this; return res; } res->copy(*this); *res &= rhs; return res; } bool BitVector::operator==(BitVector& other) const { return (words == other.words) && (count == other.count) && (size == other.size) && (rle == other.rle); } bool BitVector::equals(const BitVector& other) const { return (words == other.words) && (count == other.count) && (size == other.size) && (rle == other.rle); } BitVector* BitVector::copyflip() { BitVector *res = new BitVector(); res->copy(*this); res->flip(); return res; } void BitVector::nonORnon(BitVector& bv) { vector<word_t> res; vector<word_t>::iterator a = words.begin(); vector<word_t>::iterator b = bv.words.begin(); res.push_back(*a < *b ? *a : *b); while(a != words.end() && b != bv.words.end()) { if (*a < *b) { if (*a != res.back()) res.push_back(*a); ++a; } else if (*b < *a) { if (*b != res.back()) res.push_back(*b); ++b; } else { if (*a != res.back()) res.push_back(*a); ++a; ++b; } } if (a != words.end()) res.insert(res.end(),a,words.end()); else if (b != bv.words.end()) res.insert(res.end(),b,bv.words.end()); count = res.size(); // TODO: check if it's worth compressing words.swap(res); } void BitVector::nonANDnon(BitVector& bv) { vector<word_t> res; vector<word_t>::iterator a = words.begin(); vector<word_t>::iterator b = bv.words.begin(); res.push_back(*a < *b ? *a : *b); while(a != words.end() && b != bv.words.end()) { if (*a < *b) ++a; else if (*b < *a) ++b; else { res.push_back(*a); ++a; ++b; } } count = res.size(); words.swap(res); } void BitVector::nonANDrle(BitVector& bv) { // decompress // run nonANDnon BitVector *tmp = new BitVector(); tmp->copy(bv); tmp->decompress(); nonANDnon(*tmp); delete tmp; } void BitVector::rleANDnon(BitVector& bv) { // decompress // run nonANDnon decompress(); nonANDnon(bv); } void BitVector::nonORrle(BitVector& bv) { // compress // run rleORrle compress(); rleORrle(bv); } void BitVector::rleORnon(BitVector& bv) { // compress // run rleORrle BitVector *tmp = new BitVector(); tmp->copy(bv); tmp->compress(); rleORrle(*tmp); delete tmp; } void BitVector::setBit(word_t x) { if (rle) { // this should really be done in an rle specific way. decompress(); setBit(x); compress(); } else { if (words.size() == 0 || x > words.back()) { words.push_back(x); } else { vector<word_t>::iterator lb = lower_bound(words.begin(),words.end(),x); if (*lb == x) return; words.insert(lb,x); } size++; count++; } } BitVector& BitVector::copy(const BitVector& bv) { words = bv.words; count = bv.count; size = bv.size; rle = bv.rle; return *this; } ostream& operator<<(ostream &os, const vector<word_t> vec) { return os << vec; } ostream& operator<<(ostream &os, const BitVector &vec) { return os << vec; } void BitVector::save(const BitVector &bv, const char *filename) { std::ofstream ofs(filename); boost::archive::text_oarchive oa(ofs); oa << bv; } void BitVector::restore(BitVector &bv, const char *filename) { std::ifstream ifs(filename); boost::archive::text_iarchive ia(ifs); ia >> bv; }
true
2e8071237bffeb00d194d82631d6dd134909fb7c
C++
tonyplotnikov/Labs_PSTU
/9/9.cpp
UTF-8
1,970
3.359375
3
[]
no_license
// Лабораторная работа №9. Плотников Антон. ИВТ-19-1Б. #include <iostream> #include <string.h> #include <string> #include <ctime> using namespace std; void umalch(string name = "Антон", string soname = "Плотников", string otchestvo = "Андреевич") { cout << "Фамилия: " << soname << endl << "Имя: " << name << endl << "Отчество: " << otchestvo << endl; } int perem(...) { int s, f, g; s = rand() % 50; f = rand() % 50; g = rand() % 50; if (s > f && s > g) cout << "Максимальный параметр = s = " << s << endl; if (f > s && f > g) cout << "Максимальный параметр = f = " << f << endl; if (g > f && g > s) cout << "Максимальный параметр = g = " << g << endl; return 0; } template<class T, class D> T max(T n, D d) { D* a = new D[n]; for (int i = 0; i < n; i++) { a[i] = d; cout << a[i] << ' '; } cout << endl; D k; T r; cout << "Введите новый элемент массива: "; cin >> k; cout << "Введите номер элемента массива: "; cin >> r; for (int i = n - 1; i >= r - 1; i--) { a[i + 1] = a[i]; } a[r - 1] = k; n++; for (int i = 0; i < n; i++) { cout << a[i] << ' '; } cout << endl; return 0; } int main() { int p, k = 0, a = 5, b = 3; setlocale(LC_ALL, "Russian"); srand(time(NULL)); do { cout << "1. Функция с умалчиваемыми параметрами\n"; cout << "2. Функция с переменным числом параметров\n"; cout << "3. Перегруженные функции и шаблон функции\n"; cout << "4. Выход\n"; cin >> p; switch (p) { case 1: { umalch(); break; } case 2: { perem(k, 1, 2, 3); break; } case 3: { max(15, 5.234); break; } } } while (p != 4); }
true
1ee43f1ce8636b089c89508ea32747100bd4ea6d
C++
TushGoel/Fundamentals_of_ComputerEngineering
/Task-1/Problem_3.cpp
UTF-8
1,753
3.890625
4
[]
no_license
/* Name: Tushar Goel Student_id: 001356901 */ #include <stdio.h> #include <iostream> #include <string> using namespace std; // Function for inputting the data of the student from the teacher void input_data (int s, string n[], int g[]) { for (int i=0; i<s; i++) { cout << "Enter the name of the student --> "; cin >> n [i]; cout << "Enter the grade of the " << n[i] << " --> "; cin >> g [i]; } } // Function for the sorting of student's data in the descending order void insertion_sorting (string n[], int g[], int s) { int temp1,j=0; string temp2; for (int i=1; i<s; i++) { temp1=g[i]; temp2=n[i]; j=i-1; while(j>=0 && g[j] < temp1) { g[j+1]=g[j]; n[j+1]=n[j]; j=j-1; } g[j+1]=temp1; n[j+1]=temp2; } } // Function for displaying the result void display (string n[], int g[], int s) { for (int j=0; j<s; j++) { cout << "Name --> " << n[j] << " Marks --> " << g[j]; cout <<"\n"; } } // Main function for calling other functions int main () { int *grades; string *name; int size; cout << "Enter the size of the class --> "; cin >> size; // dynamic creation of the arrays grades = new int [size]; name = new string [size]; // function call for inputting data of the student input_data(size,name,grades); cout << "The data entered is as follows: \n "; // Function for calling display function for displaying the entered data display(name,grades,size); // Function call for the sorting of data in the descending order insertion_sorting(name,grades,size); cout << "The data after sorting in descending order as follows: \n "; // Function for calling display function for displaying the sorted data display(name,grades,size); delete[] grades; delete[] name; return 0; }
true
c6160bf29575cfa55b0f333a457f92df8f5b1756
C++
liurnd/ronald-leetcode
/length-of-last-word.cpp
UTF-8
830
3.203125
3
[]
no_license
// // Created by Ronald Liu on 29/5/15. // #include <string> using namespace std; class Solution { public: int lengthOfLastWord(string s) { int l=-1, r=-1; int state = 0; for (int i = 0 ; i < s.size(); i++) { if (state == 0) { if (s[i] == ' ') state = 1; else {l = i; r = i; state = 2;} }else if (state == 1) { if (s[i] == ' ') ; else {l = i; r = i; state = 2;} } if (state == 2) { if (s[i] == ' ') state = 1; else r = i; } } if (l==-1) return 0; return r-l+1; } }; #include <iostream> int main() { Solution s; cout << s.lengthOfLastWord(" e e"); return 0; }
true
7a2493e642caf1a4acbfe8d2debfd1c934cbb161
C++
jewela29/codeforces
/339A_Helpful Maths.cpp
UTF-8
370
2.9375
3
[]
no_license
#include<iostream> #include<algorithm> #include<string> using namespace std; int main() { int i; string s; string s1; cin >> s; sort(s.begin(), s.end()); for (i = 0; i < s.length(); i++) { if (s[i] != '+') { s1.push_back(s[i]); } } cout << s1[0]; for (i = 1; i < s1.length(); i++) { cout << "+" << s1[i]; } return 0; }
true
d01ddd9358d2b6067eda7e148c37a9804a8b155e
C++
1998factorial/Codeforces
/practice/DP/CF1129C.cpp
UTF-8
1,835
2.671875
3
[]
no_license
/* let DP[l][r] = the number of decoding way for s[l .. r] LCS[i][j] = longest common suffix for s[...i] and s[...j] ans for s[..i] is the ans for s[1...i-1] + some DP[x][i] where s[x..i] has not been counted before, so x < i - max(LCS[j][i]) where j < i */ #include <bits/stdc++.h> #define MOD 1000000007 using namespace std; int a[3005]; int DP[3005][3005]; int LCS[3005][3005]; int N; bool mask[16]; int add(int x , int y){ x += y; if(x >= MOD)x -= MOD; return x; } int main(){ mask[3] = mask[5] = mask[14] = mask[15] = 1; int i , j , k; scanf("%d" , &N); for(i = 1; i <= N; ++i){ scanf("%d" , &a[i]); } for(i = 1; i <= N; ++i){ for(j = i; j >= 1; --j){ if(a[i] == a[j])LCS[i][j] = LCS[i - 1][j - 1] + 1; } } for(i = 1; i <= N; ++i)DP[i][i - 1] = 1; for(i = 1; i <= N; ++i){ for(j = i; j <= N; ++j){ if(j - i + 1 <= 3)DP[i][j] = (1 << (j - i)); else{ int val = 0; for(k = 1; k <= 3; ++k){ val = add(val , DP[i][j - k]); // right point use length k word } int vmask = 0; for(k = 3; k >= 0; --k){ vmask = (vmask << 1) | a[j - k]; // see if right most length 4 word is bad } if(!mask[vmask]){ val = add(val , DP[i][j - 4]); // if not bad, we can use it } DP[i][j] = val; } } } int ret = 0; for(i = 1; i <= N; ++i){ int max_lcs = 0; for(j = i - 1; j >= 0; --j){ max_lcs = max(max_lcs , LCS[i][j]); } for(j = max_lcs; j <= i; ++j){ ret = add(ret , DP[i - j][i]); } printf("%d\n" , ret); } }
true
905b46e03acd02fcc27cee5fd867fa3504bbe3f6
C++
graphisoft-python/DGLib
/Support/Modules/GSRoot/EventSender.hpp
UTF-8
7,896
2.578125
3
[ "Apache-2.0" ]
permissive
// ***************************************************************************** // // Class EventSender // // Module: GSRoot // Namespace: GS // Contact person: MB // // SG compatible // // ***************************************************************************** #if !defined EVENTSENDER_HPP #define EVENTSENDER_HPP #pragma once // --------------------------------- Includes ---------------------------------- #include "GSRootExport.hpp" #include "Array.hpp" #include "EventReceiver.hpp" #include <functional> // ============================= Class EventSender ============================= namespace GS { class GSROOT_DLL_EXPORT EventSenderBase { protected: friend class EventReceiver; // to access ReceiverDeleted virtual ~EventSenderBase (); virtual void ReceiverDeleted (EventReceiver& receiver) = 0; }; template <class CallbackFunctionType, class SendCaller = void> class EventSender: public EventSenderBase { public: typedef std::function<CallbackFunctionType> CallbackFunction; protected: struct Receiver { EventReceiver* receiver; CallbackFunction callbackFunction; Receiver (): receiver (nullptr) {} Receiver (EventReceiver* receiver, const CallbackFunction& callbackFunction): receiver (receiver), callbackFunction (callbackFunction) {} }; Array<Receiver> receivers; // receivers of the sender bool sending; // true during sending bool reverseSendOrder; // true if receivers are notified in the reverse order during sending, it is alternated after each send virtual void ReceiverDeleted (EventReceiver& receiver) override; friend SendCaller; void Send (); template <class Type1> void Send (const Type1& parameter1); template <class Type1, class Type2> void Send (const Type1& parameter1, const Type2& parameter2); template <class Type1, class Type2, class Type3> void Send (const Type1& parameter1, const Type2& parameter2, const Type3& parameter3); void Send (const std::function<void (const CallbackFunction&)>& invoker); public: EventSender (); EventSender (const EventSender& source); EventSender& operator= (const EventSender& source); ~EventSender (); void Attach (EventReceiver& receiver, const CallbackFunction& callbackFunction); void Detach (EventReceiver& receiver); }; class PublicSendCaller {}; template <class CallbackFunctionType> class EventSender<CallbackFunctionType, void>: public EventSender<CallbackFunctionType, PublicSendCaller> { public: void Send () { EventSender<CallbackFunctionType, PublicSendCaller>::Send (); } template <class Type1> void Send (const Type1& parameter1) { EventSender<CallbackFunctionType, PublicSendCaller>::Send (parameter1); } template <class Type1, class Type2> void Send (const Type1& parameter1, const Type2& parameter2) { EventSender<CallbackFunctionType, PublicSendCaller>::Send (parameter1, parameter2); } template <class Type1, class Type2, class Type3> void Send (const Type1& parameter1, const Type2& parameter2, const Type3& parameter3) { EventSender<CallbackFunctionType, PublicSendCaller>::Send (parameter1, parameter2, parameter3); } void Send (const std::function<void (const typename EventSender::CallbackFunction&)>& invoker) { EventSender<CallbackFunctionType, PublicSendCaller>::Send (invoker); } }; } // namespace GS template <class CallbackFunctionType, class SendCaller> GS::EventSender<CallbackFunctionType, SendCaller>::EventSender (): sending (false), reverseSendOrder (false) { } template <class CallbackFunctionType, class SendCaller> GS::EventSender<CallbackFunctionType, SendCaller>::EventSender (const EventSender& /*source*/): sending (false), reverseSendOrder (false) { // receivers are not copied } template <class CallbackFunctionType, class SendCaller> GS::EventSender<CallbackFunctionType, SendCaller>& GS::EventSender<CallbackFunctionType, SendCaller>::operator= (const EventSender& /*source*/) { // receivers are not copied return *this; } template <class CallbackFunctionType, class SendCaller> GS::EventSender<CallbackFunctionType, SendCaller>::~EventSender () { for (UInt32 i = 0; i < receivers.GetSize (); i++) receivers[i].receiver->eventSenders.DeleteFirst (this); } template <class CallbackFunctionType, class SendCaller> void GS::EventSender<CallbackFunctionType, SendCaller>::Attach (EventReceiver& receiver, const CallbackFunction& callbackFunction) { DBASSERT (&receiver != nullptr); DBASSERT (&callbackFunction != nullptr); //lint !e914 [Implicit adjustment of function return value] LINT felrefutas DBASSERT (!receivers.Contains ([&] (const Receiver& r) { return r.receiver == &receiver; })); DBASSERT (!sending); // it needs further development to enable Attach during event sending (new receivers should be added only after event sending has been finished) receivers.Push (Receiver (&receiver, callbackFunction)); receiver.eventSenders.Push (this); } template <class CallbackFunctionType, class SendCaller> void GS::EventSender<CallbackFunctionType, SendCaller>::Detach (EventReceiver& receiver) { DBASSERT (&receiver != nullptr); DBASSERT (!sending); // it needs further development to enable Detach during event sending (existing receivers should be deleted only after event sending has been finished) //lint !e914 [Implicit adjustment of function return value] LINT felrefutas UInt32 receiverIndex = receivers.FindFirst ([&] (const Receiver& r) { return r.receiver == &receiver; }); if (receiverIndex != MaxUIndex) { receivers.Delete (receiverIndex); receiver.eventSenders.DeleteFirst (this); } } template <class CallbackFunctionType, class SendCaller> void GS::EventSender<CallbackFunctionType, SendCaller>::ReceiverDeleted (EventReceiver& receiver) { DBASSERT (!sending); // it is not allowed to delete receiver during event sending UInt32 receiverIndex = receivers.FindFirst ([&] (const Receiver& r) { return r.receiver == &receiver; }); receivers.Delete (receiverIndex); } template <class CallbackFunctionType, class SendCaller> void GS::EventSender<CallbackFunctionType, SendCaller>::Send () { std::function<void (const CallbackFunction&)> invoker = [&] (const CallbackFunction& function) { function (); }; Send (invoker); } template <class CallbackFunctionType, class SendCaller> template <class Type1> void GS::EventSender<CallbackFunctionType, SendCaller>::Send (const Type1& parameter1) { std::function<void (const CallbackFunction&)> invoker = [&] (const CallbackFunction& function) { function (parameter1); }; Send (invoker); } template <class CallbackFunctionType, class SendCaller> template <class Type1, class Type2> void GS::EventSender<CallbackFunctionType, SendCaller>::Send (const Type1& parameter1, const Type2& parameter2) { std::function<void (const CallbackFunction&)> invoker = [&] (const CallbackFunction& function) { function (parameter1, parameter2); }; Send (invoker); } template <class CallbackFunctionType, class SendCaller> template <class Type1, class Type2, class Type3> void GS::EventSender<CallbackFunctionType, SendCaller>::Send (const Type1& parameter1, const Type2& parameter2, const Type3& parameter3) { std::function<void (const CallbackFunction&)> invoker = [&] (const CallbackFunction& function) { function (parameter1, parameter2, parameter3); }; Send (invoker); } template <class CallbackFunctionType, class SendCaller> void GS::EventSender<CallbackFunctionType, SendCaller>::Send (const std::function<void (const CallbackFunction&)>& invoker) { DBASSERT (&invoker != nullptr); sending = true; if (reverseSendOrder) { for (UInt32 i = receivers.GetSize (); i > 0; i--) invoker (receivers[i - 1].callbackFunction); } else { for (UInt32 i = 0; i < receivers.GetSize (); i++) invoker (receivers[i].callbackFunction); } reverseSendOrder = !reverseSendOrder; sending = false; } #endif
true
e59361490b228e5a550f6e9fa02d74a824183021
C++
xpbluesmile/How-Not-to-Program-in-Cpp
/program061_faulty.cpp
UTF-8
5,260
3.828125
4
[]
no_license
/************************************************ * find_word -- find a word in the dictionary. * * * * Usage: * * find_word <word-start> [<word-start>...] * ************************************************/ #include <iostream> #include <fstream> #include <iomanip> #include <cctype> #include <cstring> #include <cstdlib> /************************************************ * tree -- A simple binary tree class * * * * Member functions: * * enter -- Add an entry to the tree * * find -- See if an entry is in the tree. * ************************************************/ class tree { private: // The basic node of a tree class node { private: // tree to the right node *right; // tree to the left node *left; public: // data for this tree char *data; public: node() : right(NULL), left(NULL), data(NULL) {} // Destructor defaults private: // No copy constructor node(const node &); // No assignment operator node & operator = (const node &); // Let tree manipulate our data friend class tree; }; // the top of the tree node *root; // Enter a new node into a tree or // sub-tree void enter_one( // Node of sub-tree to look at node *&node, // Word to add const char *const data ); // Find an item in the tree void find_one( // Prefix to search for const char start[], // Node to start search const node *const node, // Keep looking flag const bool look ); public: tree(void) { root = NULL;} // Destructor defaults private: // No copy constructor tree(const tree &); // No assignment operator tree & operator = (const tree &); public: // Add a new data to our tree void enter( // Data to add const char *const data ) { enter_one(root, data); } // Find all words that start // with the given prefix void find( const char start[] // Starting string ) { find_one(start, root, true); } }; /************************************************ * tree::enter_one -- enter a data into * * the tree * ************************************************/ void tree::enter_one( node *&new_node, // Sub-tree to look at const char *const data // Word to add ) { int result; // result of strcmp // see if we have reached the end if (new_node == NULL) { new_node = new node; new_node->left = NULL; new_node->right = NULL; new_node->data = strdup(data); } result = strcmp(new_node->data, data); if (result == 0) { return; } if (result < 0) enter_one(new_node->right, data); else enter_one(new_node->left, data); } /************************************************ * tree::find_one -- find words that match this * * one in the tree. * ************************************************/ void tree::find_one( const char start[], // Start of the work const node *const top,// Top node const bool look // Keep looking ) { if (top == NULL) return; // short tree // Result of checking our prefix // against the word int cmp = strncmp(start, top->data, strlen(start)); if ((cmp < 0) && (look)) find_one(start, top->left, true); else if ((cmp > 0) && (look)) find_one(start, top->right, true); if (cmp != 0) return; /* * We found a string that starts this one. * Keep searching and print things. */ find_one(start, top->left, false); std::cout << top->data << '\n'; find_one(start, top->right, false); } int main(int argc, char *argv[]) { // A tree to hold a set of words tree dict_tree; // The dictionary to search std::ifstream dict_file("/usr/share/dict/words"); if (dict_file.bad()) { std::cerr << "Error: Unable to open " "dictionary file\n"; exit (8); } /* * Read the dictionary and construct the tree */ while (1) { char line[100]; // Line from the file dict_file.getline(line, sizeof(line)); if (dict_file.eof()) break; dict_tree.enter(strdup(line)); } /* * Search for each word */ while (argc > 1) { std::cout << "------ " << argv[1] << '\n'; dict_tree.find(argv[1]); ++argv; --argc; } return (0); }
true
46e93bc79a2b99641aeed1242079bdfbcf40fd77
C++
bertolinocastro/cimatec_senai
/desenvolvimento_sistemas/cpp/heranca/conta.cpp
UTF-8
1,651
3.703125
4
[]
no_license
#include "conta.hpp" #include <iostream> using namespace std; Conta::Conta(int numConta, float saldo){ this->NumConta(numConta); this->Saldo(saldo); } Conta::~Conta(void){ cout<<"Oi! Eu:"<<this->NumConta()<<" com "<<this->Saldo()<<" Morri!"<<endl; } // getters e setters void Conta::NumConta(int numConta){ this->numConta = numConta; } int Conta::NumConta(void){ return this->numConta; } void Conta::Saldo(float saldo){ this->saldo = saldo; } float Conta::Saldo(void){ return this->saldo; } // methods void Conta::Depositar(float money){ this->Saldo(this->Saldo() + money); } void Conta::Sacar(float money){ if(this->Saldo() >= money) this->Saldo(this->Saldo() - money); } /* ContaPoupanca */ void ContaPoupanca::Depositar(float money){ this->Saldo( this->Saldo() + money + 0.02 ); } /* ContaCorrente */ void ContaCorrente::Sacar(float money){ if(this->Saldo() >= money) this->Saldo( this->Saldo() - money - 0.1 ); } // programa int main(int argc, char **argv){ ContaCorrente pessoa1(123, 1000); ContaPoupanca pessoa2(321, 1000); cout << "Sou a pessoa1:" <<pessoa1.NumConta() << " " << pessoa1.Saldo() << endl; cout<<"Sou a pessoa2:"<<pessoa2.NumConta()<<""<<pessoa2.Saldo()<<endl; pessoa1.Depositar(500); pessoa2.Depositar(500); cout<<"Sou a pessoa1:"<<pessoa1.NumConta()<<""<<pessoa1.Saldo()<<endl; cout<<"Sou a pessoa2:"<<pessoa2.NumConta()<<""<<pessoa2.Saldo()<<endl; pessoa1.Sacar(600); pessoa2.Sacar(600); cout<<"Sou a pessoa1:"<<pessoa1.NumConta()<<""<<pessoa1.Saldo()<<endl; cout<<"Sou a pessoa2:"<<pessoa2.NumConta()<<""<<pessoa2.Saldo()<<endl; return 0; }
true
ccfce7c54fd443e612a68233f9766e79423f1f22
C++
guarrod/statuslight-rgb-device
/src/main.cpp
UTF-8
5,805
2.859375
3
[ "MIT" ]
permissive
#include <Arduino.h> #include <Adafruit_NeoPixel.h> #include <Homie.h> #define PIN D4 #define LED_NUM 7 // When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals. // Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest // example for more information on possible values. Adafruit_NeoPixel leds = Adafruit_NeoPixel(LED_NUM, PIN, NEO_GRB + NEO_KHZ800); const int UPDATE_INTERVAL = 1; unsigned long lastUpdated = 0; unsigned long lastStatusUpdated = 0; String myStatus = ""; String myStatusDetail = ""; String myColor = "grey"; String newStatus = ""; String newStatusDetail = ""; //id, name, type HomieNode statuslightNode("statuslight", "Statuslight", "statuslight"); void setColor(uint8 R, uint8 G, uint8 B) { for (int i = 0; i < LED_NUM; i++) { leds.setPixelColor(i, leds.Color(R, G, B)); } leds.show(); } void updateDevice(const String& status, const String& statusDetail) { if ((status != myStatus) || (statusDetail != myStatusDetail)) { myStatus = status; myStatusDetail = statusDetail; String color = "grey"; if (myStatus == "busy") { color = "red"; setColor(255, 0, 0); } if (myStatus == "free") { color = "green"; setColor(0, 255, 0); } if (myStatus == "away") { color = "yellow"; setColor(200, 155, 0); } if (myStatus == "error") { color = "grey"; setColor(100, 100, 100); } if (color != myColor) { myColor = color; statuslightNode.setProperty("color").send(myColor); } Homie.getLogger() << "Status: " << myStatus << " - " << myStatusDetail << endl; Homie.getLogger() << "Color: " << myColor << endl; } } void onHomieEvent(const HomieEvent& event) { switch (event.type) { case HomieEventType::STANDALONE_MODE: Serial << "Standalone mode started" << endl; break; case HomieEventType::CONFIGURATION_MODE: Serial << "Configuration mode started" << endl; updateDevice(myStatus, "Configuration mode"); break; case HomieEventType::NORMAL_MODE: Serial << "Normal mode started" << endl; break; case HomieEventType::OTA_STARTED: Serial << "OTA started" << endl; break; case HomieEventType::OTA_PROGRESS: Serial << "OTA progress, " << event.sizeDone << "/" << event.sizeTotal << endl; break; case HomieEventType::OTA_FAILED: Serial << "OTA failed" << endl; break; case HomieEventType::OTA_SUCCESSFUL: Serial << "OTA successful" << endl; break; case HomieEventType::ABOUT_TO_RESET: Serial << "About to reset" << endl; break; case HomieEventType::WIFI_CONNECTED: Serial << "Wi-Fi connected, IP: " << event.ip << ", gateway: " << event.gateway << ", mask: " << event.mask << endl; updateDevice(myStatus, "WiFi ok, MQTT..."); break; case HomieEventType::WIFI_DISCONNECTED: Serial << "Wi-Fi disconnected, reason: " << (int8_t)event.wifiReason << endl; myStatus = "error"; updateDevice(myStatus, "Wifi disconnected"); break; case HomieEventType::MQTT_READY: Serial << "MQTT connected" << endl; updateDevice(myStatus, "MQTT connected"); break; case HomieEventType::MQTT_DISCONNECTED: Serial << "MQTT disconnected, reason: " << (int8_t)event.mqttReason << endl; updateDevice("error", "MQTT disconnected"); break; case HomieEventType::READY_TO_SLEEP: Serial << "Ready to sleep" << endl; break; case HomieEventType::SENDING_STATISTICS: Serial << "Sending statistics" << endl; break; case HomieEventType::MQTT_PACKET_ACKNOWLEDGED: break; } } bool globalInputHandler(const HomieNode& node, const HomieRange& range, const String& property, const String& value) { Homie.getLogger() << "Received on node " << node.getId() << ": " << property << " = " << value << endl; if (property == "status") { lastStatusUpdated = millis(); statuslightNode.setProperty("status").send(value); newStatus = value; } if (property == "statusdetail") { statuslightNode.setProperty("statusdetail").send(value); newStatusDetail = value; } return true; } void loopHandler() { if (millis() - lastUpdated >= UPDATE_INTERVAL * 1000UL || lastUpdated == 0) { // Homie.getLogger() << "Status has been upated " << millis() - lastStatusUpdated << " millisec ago" << endl; updateDevice(newStatus, newStatusDetail); lastUpdated = millis(); if (millis() - lastStatusUpdated >= UPDATE_INTERVAL * 100 * 1000UL && lastStatusUpdated != 0) { newStatus = "error"; newStatusDetail = "timeout"; updateDevice(newStatus, newStatusDetail); lastStatusUpdated = millis(); } } } void setup() { Homie_setBrand("SL"); Homie.setResetTrigger(0, LOW, 2000); Serial.begin(115200); Serial << endl << endl; Homie_setFirmware("SLON-RGB-LED", "0.0.3"); Homie.setLoopFunction(loopHandler); statuslightNode.advertise("status").setName("Status").setDatatype("string").settable(); statuslightNode.advertise("statusdetail").setName("StatusDetail").setDatatype("string").settable(); statuslightNode.advertise("color").setName("Color").setDatatype("string"); Homie.onEvent(onHomieEvent); Homie.setGlobalInputHandler(globalInputHandler); leds.begin(); // This initializes the NeoPixel library. leds.setBrightness(255); leds.setPixelColor(6, leds.Color(0, 0, 10)); leds.show(); updateDevice(myStatus, "Starting..."); Homie.setup(); } void led_set(uint8 R, uint8 G, uint8 B) { for (int i = 0; i < LED_NUM; i++) { leds.setPixelColor(i, leds.Color(R, G, B)); leds.show(); delay(50); } } void loop() { Homie.loop(); }
true
85d8be9b35039956790ae7a8da732661c0f3ce06
C++
RaunakJalan/CP-Practice
/STL/multiset_stl.cpp
UTF-8
2,041
4.125
4
[]
no_license
#include <iostream> #include <set> using namespace std; typedef multiset<int>::iterator It; // Multi Set is a set like container that can store multiple elements with same value. // All elements are stored in a specific order -> sorted according to internal comparing object, can give custom object too. // MultiSet also cannot be updated. Like we want to set 3 as 13 in {1,2,3,5}, then we would have to remove 3 and then add 13. // Associative container - elements are reffered by their value and not by the index. // UNderlying implementation is BST int main(){ int arr[] = {10, 20, 30, 11, 9, 8, 11, 10, 30, 30, 30, 70, 70, 70}; int n = sizeof(arr)/sizeof(int); multiset<int> m(arr, arr+n); // Uses values from arr from 0 to 6 index // Iterator for(multiset<int>::iterator it = m.begin(); it!=m.end(); it++){ cout<<(*it)<<" "; } cout<<endl; // Inserting 80 in set cout<<"Inseting 80 to set"<<endl; m.insert(80); for(auto x:m){ cout<<x<<", "; } cout<<endl; //Count frequency of an element cout<<"Frequency of 10: "<<m.count(10)<<endl; // Erase cout<<"Deleting 10 and 11 from set"<<endl; m.erase(10); // -> 1st way -> deletes all occurings of the value // Find auto it = m.find(11); // Gives iterator to a element m.erase(it); // -> 2nd way -> deletes the value at given address. for(set<int>::iterator it = m.begin(); it!=m.end(); it++){ cout<<(*it)<<" "; } cout<<endl; cout<<"After deletion Frequency of 10: "<<m.count(10)<<endl; // Get all iterators of 30 cout<<"Getting range of elements with 30: "<<endl; pair<It, It> p = m.equal_range(30); for(auto it = p.first; it!=p.second; it++){ cout<<(*it)<<" - "; } cout<<endl; // Lower bound and Upper Bound: // Getting all elements with value between 11 and 77 included. for(It it = m.lower_bound(11); it!=m.upper_bound(77); it++){ cout<<(*it)<<"-"; } cout<<endl; return 0; }
true
9a4afcf21ce9c0855f4f6faa05521b6df90ca5ee
C++
wolvestotem/LeetCode
/面试题/tencent/笔试/solve/solve.cpp
UTF-8
2,867
2.84375
3
[]
no_license
#include<iostream> #include<vector> #include<unordered_map> #include<algorithm> #include<queue> using namespace std; struct Listnode { int val; Listnode* next; Listnode(int x):val(x),next(nullptr){} }; //void solve(Listnode* fir, Listnode* sec) { // if (!fir || !sec) // return; // Listnode* pre = new Listnode(0); // Listnode* curr(pre); // while (fir && sec) { // if (fir->val == sec->val) { // curr->next = new Listnode(fir->val); // fir = fir->next; // sec = sec->next; // curr = curr->next; // } // else if (fir->val < sec->val) { // sec = sec->next; // } // else { // fir = fir->next; // } // } // while (pre->next) // { // cout << pre->next->val << ' '; // pre = pre->next; // } //} //int main() { // int n, m; // Listnode* fir = new Listnode(0); // Listnode* sec = new Listnode(0); // Listnode* cfir(fir), * csec(sec); // // cin >> n; // int infir, insec; // while (n--) { // cin >> infir; // cfir->next = new Listnode(infir); // cfir = cfir->next; // } // cin >> m; // while (m--) { // cin >> insec; // csec->next = new Listnode(insec); // csec = csec->next; // } // // solve(fir->next, sec->next); //} void solve(vector<pair<int,int>>& group, vector<vector<int>>& people, vector<vector<int>>& yingshe, int m, int n, bool havezero) { int number = 0; if (!havezero) { cout << 1 << endl; return; } queue < int> q; for (auto i : people[0]) { q.push(i); group[i].second = 1; number = number + group[i].first; } while (!q.empty()) { int g = q.front(); for (int j : yingshe[g]) { for (int k : people[j]) { if (group[k].second == 0) { q.push(k); number = number + group[k].first; group[k].second = 1; } } } } cout << number << endl; } int main() { int n, m; cin >> n >> m; int ori(m); vector<pair<int, int>> group; vector<vector<int>> people(n, vector<int>(0)); vector<vector<int>> yingshe(m, vector<int>(0)); bool havezero = false; int t, a; m++; while (m--) { cin >> t; group.emplace_back(t, 0); while (t--) { cin >> a; if (a == 0) havezero = true; people[a].push_back(ori-m-1); //yingshe[ori - m - 1].push_back(a); } } solve(group, people, yingshe, m, n, havezero); } //int main() { // int n, k; // cin >> n >> k; // unordered_map<string, int> m; // string input; // while (n--) { // cin >> input; // if (m.count(input)) // m[input]++; // else // m[input] = 1; // } //} //void solve(vector<int>& input,int n) { // vector<int> b(input.begin(), input.end()); // sort(b.begin(), b.end()); // int r = n >> 1; // int l = r - 1; // for (int i : input) { // if (i <= b[l]) // cout << b[r] << endl; // else // cout << b[l] << endl; // } //} // //int main() { // int n,t; // int originn; // cin >> n; // originn = n; // vector<int> input; // while (n--) { // cin >> t; // input.push_back(t); // } // solve(input,originn); //}
true
f9a1eec64fdaf3e57d652be90adebcf1666da698
C++
GabeOchieng/ggnn.tensorflow
/program_data/PKU_raw/45/2467.c
UTF-8
331
2.703125
3
[]
no_license
int locate(char s[], char w[]) {int m, k,len1,len2; len1=strlen(s); len2=strlen(w); m=0; while(m+len1<=len2) { k=0; while((k<len1)&&(s[k]==w[m+k])) ++k; if(k==len1) return m; m++; } return -1; // ??? } int main() { char s[50],w[50]; scanf("%s %s",s,w); int a; a=locate(s,w); printf("%d",a); return 0; }
true
9dabfa84494fa84f03e61e4bfeeed32e692ded6f
C++
danys/streamscraper
/Flv2m4a.cpp
UTF-8
9,893
2.921875
3
[]
no_license
#include <iostream> #include <fstream> #include "Flv2m4a.h" #include "AudioFile.h" #include "AudioExtractor.h" using namespace std; //declarations related to file I/O ifstream::pos_type fsize; ifstream::pos_type fosize; //output file size ifstream inputFile; ofstream outputFile; int Flv2m4a::power10(int x) { int result = 1; for (int i = 1;i<=x;i++) result = result*10; return result; } int Flv2m4a::digits(int x) { int counter = 0; if (x==0) return 1; while (x!=0) { x = x/10; counter ++; } return counter; } //output single char of number, least significant first char Flv2m4a::extractchar(int number) { int res = number % 10; char result = res + 48; return result; } // selects a new filename // for example shakira.m4a is transformed into shakira(1).m4a // shakira(1).m4a is transformed into shakira(2).m4a ... void Flv2m4a::newaudiofile(char* in,char* out) { int i = 0; while (*(in+i) != '\0') i++; // at this point i-1 is known to be the length: in[0..i] //check if there is a ')' at the last position, ==> ).m4a\0 if (*(in+i-5) != ')') { for (int k=0;k<=i-5;k++) //used to be i-1 { *(out+k) = *(in+k); //copy in to out } // append (1) to out *(out+i-4) = '('; *(out+i-3) = '1'; *(out+i-2) = ')'; *(out+i-1) = '.'; *(out+i) = 'm'; *(out+i+1) = '4'; *(out+i+2) = 'a'; *(out+i+3) = '\0'; return; } else { int j = i; while (j>=0) { if (*(in+j) == '(') break; j--; } if (j==-1) //no '(' detected { for (int k=0;k<=i-5;k++) //used to be i-1 { *(out+k) = *(in+k); //copy in to out } // append (1) to out *(out+i-4) = '('; *(out+i-3) = '1'; *(out+i-2) = ')'; *(out+i-1) = '.'; *(out+i) = 'm'; *(out+i+1) = '4'; *(out+i+2) = 'a'; *(out+i+3) = '\0'; return; } // j tells where '(' is //check if there are only numbers between '(' and ')' if (j+1==i) // '(' besides ')' { for (int k=0;k<=i-5;k++) //used to be i-1 { *(out+k) = *(in+k); //copy in to out } // append (1) to out *(out+i-4) = '('; *(out+i-3) = '1'; *(out+i-2) = ')'; *(out+i-1) = '.'; *(out+i) = 'm'; *(out+i+1) = '4'; *(out+i+2) = 'a'; *(out+i+3) = '\0'; return; } int counter = 0; for (int l=j+1;l<i-4;l++) { if ((*(in+l) >=48) && (*(in+l) <= 57))//ASCII table 0-9 { counter++; } else break; } if (counter == i-j-2-4) //every char is a digit 0-9 { int number = 0; for (int a=1;a<=i-j-2-4;a++) { number = number + (*(in+j+a)-48)*power10(i-j-2-4-a); } number++; // increment int width = digits(number); //extract number & write out for (int k=0;k<=j;k++) { *(out+k) = *(in+k); //copy in to out until and including'(' } int n = extractchar(number); for (int k=width;k>=1;k--) { *(out+j+k) = n; number = number / 10; n = extractchar(number); } *(out+j+width+1) = ')'; *(out+j+width+2) = '.'; *(out+j+width+3) = 'm'; *(out+j+width+4) = '4'; *(out+j+width+5) = 'a'; *(out+j+width+6) = '\0'; return; } else { for (int k=0;k<=i-5;k++) //used to be i-1 { *(out+k) = *(in+k); //copy in to out } // append (1) to out *(out+i-4) = '('; *(out+i-3) = '1'; *(out+i-2) = ')'; *(out+i-1) = '.'; *(out+i) = 'm'; *(out+i+1) = '4'; *(out+i+2) = 'a'; *(out+i+3) = '\0'; return; } } } Flv2m4a::Flv2m4a() { nchunks = 0; message = 0; } Flv2m4a::~Flv2m4a() { //delete [] mediaheader; //to check if size is big enough //mediaheader = 0; delete [] temp; temp = 0; delete [] memblock; memblock = 0; } void Flv2m4a::convert(char* flvfile, char* audiofile,int starttime, int endtime, bool cut, unsigned char *title,unsigned char *artist) { inputFile.open(flvfile, ios::in|ios::binary|ios::ate); //set file read pointer to the end of the file = ios:ate //outputFile.open(audiofile,ios::out | ios::app | ios::binary); if (inputFile.is_open()) { //cout << "File successfully opened !" << endl; fsize = inputFile.tellg(); //get the current read pointer ==> tells size //cout << "File size in bytes = " << fsize << endl; memblock = new unsigned char [fsize]; //dynamically allocate memory for the FLV file temp = new unsigned char [fsize]; //dynamically allocate memory for the extracted audio data inputFile.seekg (0, ios::beg); //set the read pointer to the beginning of the file inputFile.read ((char*)memblock, fsize); //memblock stores whole FLV file inputFile.close(); //close FLV file int i; char * out; //loop tries to avoid overwriting files //if std file exists try appending (1), then (2),... while(true) { ifstream inputFile(audiofile); // returns true if file exists else false if (!inputFile.good()) { inputFile.close(); break; //file doesn't exist break, we have a name } else { inputFile.close(); i = 0; while (*(audiofile+i) != '\0') i++; // i+1 is the length of audio //we now know i+4 is the maximum length of out out = new char[i+4]; newaudiofile(audiofile,out); delete audiofile; audiofile = new char[i+4]; for (int k=0;k<=i+3;k++) { *(audiofile+k) = *(out+k); } delete out; out = 0; } } // end try loop // check if audio.flv file is open outputFile.open(audiofile,ios::out | ios::app | ios::binary); if (outputFile.is_open()) { // extract audio data ---------------------------------------------------------------------------- //AudioExtractor Audio; audiospecificconfig1 = new unsigned char(18); audiospecificconfig2 = new unsigned char(16); Audio = new AudioExtractor(); Audio->extract(memblock, temp,chunksize,fsize,starttime,endtime,cut,audiospecificconfig1,audiospecificconfig2); if (Audio->getmessage() == 3) //wrong music format { message = 4; outputFile.close(); remove(audiofile); //delete [] audiofile; //audiofile = 0; return; } if (Audio->getmessage() == 1) //corrupted or no FLV file { message = 5; //delete [] audiofile; //audiofile = 0; return; } audiodatasize = Audio->getAudioSize(); nchunks = Audio->getnchunks(); delete Audio; Audio = 0; // write music file ------------------------------------------------------------------------------ //AudioFile Header (nchunks,chunksize,audiodatasize); Header = new AudioFile(nchunks,chunksize,audiodatasize); Header->createHeader(mediaheader,audiospecificconfig1,audiospecificconfig2,title,artist); delete audiospecificconfig1; audiospecificconfig1 = 0; delete audiospecificconfig2; audiospecificconfig2 = 0; int index = Header->getIndex(); outputFile.write((char*)mediaheader, index); // just writing audio data to file, not header outputFile.write((char*)temp, audiodatasize); delete [] temp; temp = 0; Header->createTrailer(mediaheader); index = Header->getIndex(); delete Header; Header = 0; delete [] memblock; memblock = 0; outputFile.write((char*)mediaheader, index); // close file outputFile.close(); // delete line under //emit convertdone(); //end write music file ---------------------------------------------------------------------------- //cout << "Done !" << endl; message = 1; //this means operation done //delete [] audiofile; //audiofile = 0; return; } //end if output file is open else { message = 2;//cout << "Unable to open output file !" << endl; //delete [] audiofile; //audiofile = 0; return; } } //end check if file could be opened else { message = 3;//cout << "Unable to read FLV file !" << endl; return; } } void Flv2m4a::extractformat(char* flvfile) { inputFile.open(flvfile, ios::in|ios::binary|ios::ate); //set file read pointer to the end of the file = ios:ate if (inputFile.is_open()) { fsize = inputFile.tellg(); //get the current read pointer ==> tells size memblock = new unsigned char [fsize]; //dynamically allocate memory for the FLV file inputFile.seekg (0, ios::beg); //set the read pointer to the beginning of the file inputFile.read ((char*)memblock, fsize); //memblock stores whole FLV file inputFile.close(); // extract audio data ---------------------------------------------------------------------------- //AudioExtractor Audio; Audio = new AudioExtractor(); Audio->extractformat(memblock, fsize); if (Audio->getmessage() == 1) //corrupted or no FLV file { message = 5; return; } delete [] memblock; memblock = 0; message = 1; //this means operation done musicformat = Audio->getsoundformat(); stereo = Audio->getstereo(); samplesize = Audio->getsamplesize(); samplerate = Audio->getsoundrate(); delete Audio; Audio = 0; } else message = 3; //cout << "Unable to read FLV file !" << endl; return; } int Flv2m4a::getmessage() { return message; } bool Flv2m4a::getstereo() { return stereo; } int Flv2m4a::getmusicformat() { return musicformat; } int Flv2m4a::getsamplesize() { return samplesize; } int Flv2m4a::getsamplerate() { return samplerate; }
true
4ace9046000165dc62884d4baf205040a88c6340
C++
Bharath-k06/Compi_practise
/wave.cpp
UTF-8
575
3.296875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void wave(int *arr,int n) { //arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... (considering the increasing lexicographical order). for(int i=0;i<n-1;i+=2) { if(arr[i]<arr[i+1]) { arr[i] = arr[i]+arr[i+1]; arr[i+1] = arr[i]-arr[i+1]; arr[i] =arr[i] -arr[i+1]; } } } int main() { int n; cin>>n; int a[n]; //Give an sorted array of distinct element for(int i=0;i<n;i++) { cin>>a[i]; } wave(a,n); for(int i=0;i<n;i++) { cout<<a[i]<<" "; } cout<<endl; return 0; }
true
929efabafccec3db341d3b4ceadf9354fea0a017
C++
Straygear/ServerSocket
/ServerSocket/SERVER.cpp
UTF-8
6,624
2.625
3
[]
no_license
#include "SERVER.h" #include "ACCOUNTS.h" SERVER::SERVER(): result(0), ptr(0), iResult(0) { ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; ListenSocket = INVALID_SOCKET; ClientSocket = INVALID_SOCKET; recvbuf[DEFAULT_BUFLEN]; recvbuflen = DEFAULT_BUFLEN; clientSize = sizeof(client); } SERVER::~SERVER(){} int SERVER::initialiseSocket() { iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { std::cout << "WSAStartup failed: " << iResult << std::endl; return 1; } std::cout << "Socket Initialised!" << std::endl; return iResult; } int SERVER::createSocket() { iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result); if (iResult != 0) { std::cout << "getaddrinfo failed: " << iResult << std::endl; WSACleanup(); return 1; } //create a SOCKET for the server to listen for client connections ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (ListenSocket == INVALID_SOCKET) { std::cout << "Error at socket(): " << WSAGetLastError() << std::endl; freeaddrinfo(result); WSACleanup(); return 1; } std::cout << "address is: " << result->ai_addr << std::endl; std::cout << "Socket created!" << std::endl; return iResult; } int SERVER::bindSocket() { //bind socket to localhost iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen); if (iResult == SOCKET_ERROR) { std::cout << "bind failed with error " << WSAGetLastError() << std::endl; freeaddrinfo(result); closesocket(ListenSocket); WSACleanup(); return 1; } std::cout << "Socket binded!" << std::endl; return iResult; } int SERVER::listenSocket() { if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) { std::cout << "Listen failed with error: " << WSAGetLastError() << std::endl; closesocket(ListenSocket); WSACleanup(); return 1; } //wait for a connection std::cout << "Listning...." << std::endl; return iResult; } int SERVER::connectMultipleClients() { char host[NI_MAXHOST]; char service[NI_MAXHOST]; std::map<SOCKET, std::string> socketname; std::map<SOCKET, bool> sockMap; std::pair<SOCKET, bool> sockets; std::string name; fd_set master; FD_ZERO(&master); FD_SET(ListenSocket, &master); while (true) { fd_set copy = master; int socketCount = select(0, &copy, nullptr, nullptr, nullptr); //here is where the magic happens for (int i = 0; i < socketCount; i++) { SOCKET sock = copy.fd_array[i]; if (sock == ListenSocket) { //accept new connection ClientSocket = accept(ListenSocket, (sockaddr*)&client, &clientSize); if (ClientSocket == INVALID_SOCKET) { std::cout << "accept failed: " << WSAGetLastError() << std::endl; closesocket(ListenSocket); WSACleanup(); return 1; } std::cout << "connection accepted!" << std::endl; //add the new connection to the list of connected clients FD_SET(ClientSocket, &master); sockets.first = sock; sockets.second = false; sockMap.insert(sockets); //send a welcome message to the connected client std::ostringstream st; st << "Welcome SOCKET #" << ClientSocket << " to the chat server!\r\n" << "please enter your name: " << "\r\n"; std::string msg = st.str(); //TODO: broadcast we have a new connection for(int i = 0; i < master.fd_count; i++) { SOCKET broadSock = master.fd_array[i]; if (broadSock != ListenSocket && broadSock != ClientSocket) { std::ostringstream br; br << "\r\n" << "SOCKET #" << ClientSocket << " has connected to the server!\r\n"; std::string msgtwo = br.str(); sendMsg(msgtwo, broadSock); } } ZeroMemory(host, NI_MAXHOST); ZeroMemory(service, NI_MAXHOST); if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) { std::cout << host << " connected on port " << service << std::endl; sendMsg(msg, ClientSocket); } else { inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST); std::cout << host << " connected on host " << ntohs(client.sin_port) << std::endl; sendMsg(msg, ClientSocket); } } else { ZeroMemory(recvbuf, recvbuflen); //recieve message int bytesIn = recv(sock, recvbuf, recvbuflen, 0); if (bytesIn <= 0) { //drop the client closesocket(sock); FD_CLR(sock, &master); } if (!sockMap[sock]) { std::ostringstream sg; sg << recvbuf; //name = std::string(recvbuf, 0, bytesIn); name = sg.str(); sockMap[sock] = true; socketname[sock] = name; } else { for (int i = 0; i < master.fd_count; i++) { SOCKET outSock = master.fd_array[i]; //send message to other clients, and definitly NOT the listening socket if (outSock != ListenSocket && outSock != sock) { std::ostringstream ss; ss << socketname[sock] << ": " << recvbuf << "\n\r"; std::string strOut = ss.str(); sendMsg(strOut, outSock); } } } } } } } void SERVER::sendMsg(std::string msg, SOCKET socket) { int isendresult = send(socket, msg.c_str(), msg.size() + 1, 0); if (isendresult == SOCKET_ERROR) { std::cout << "send failed: " << WSAGetLastError() << std::endl; WSACleanup(); } } //int SERVER::recieveSendData() { // do { // ZeroMemory(recvbuf, recvbuflen); // // iResult = recv(ClientSocket, recvbuf, recvbuflen, 0); // if (iResult > 0) { // std::cout << "Bytes recieved: " << iResult << std::endl; // std::cout << "CLIENT> " << std::string(recvbuf, 0, iResult) << std::endl; // // //Echo the buffer back to the sender // int isendresult = send(ClientSocket, recvbuf, iResult + 1, 0); // if (isendresult == SOCKET_ERROR) { // std::cout << "send failed: " << WSAGetLastError() << std::endl; // closesocket(ClientSocket); // WSACleanup(); // return 1; // } // std::cout << "Bytes sent " << isendresult << std::endl; // } // else if (iResult == 0) { // std::cout << "Connection closing...\n" << std::endl; // return iResult; // } // else { // std::cout << "recv failed: " << WSAGetLastError() << std::endl; // closesocket(ClientSocket); // WSACleanup(); // return 1; // } // } while (true); //} int SERVER::disconnectServer() { iResult = shutdown(ClientSocket, SD_SEND); if (iResult == SOCKET_ERROR) { std::cout << "shutdown failed: " << WSAGetLastError << std::endl; closesocket(ClientSocket); WSAGetLastError(); return 1; } std::cout << "shuting down" << std::endl; return iResult; }
true
8d45e226645e0da36ab10a19d7909770e1050763
C++
scottwang54/cs22001
/warm-up-project/src/person.cpp
UTF-8
4,904
3.46875
3
[]
no_license
#include "person.h" #include <regex> #include <iostream> #include <fstream> // bool str_isalpha(const string str){ // for(int i = 0; i < str.size(); i++) // if((isalpha(str[i]) == 0) || (str[i] == ' ')) // return false; // return true; //} bool str_isalnum(const string s) { std::string::const_iterator it = s.begin(); while (it != s.end() && std::isdigit(*it)) ++it; return !s.empty() && it == s.end(); } /* bool atleastone_alnum(const string str) // helper function to check for at least >1 digit and alphabet { int num = 0; int alpha = 0; for(int i = 0; i < str.size(); i++) { if (isdigit(str[i]) == 1) { num = 1; } if (isalpha(str[i]) == 1) { alpha = 1; } } if (num == 1 && alpha == 1) { return true; } else { return false; } } */ Person::Person() : username(""), firstname(""), lastname(""), gender(0), age(0), tagline("") { } // why do we need this one in addition to the line below Person::Person(string _username, string _firstname, string _lastname, int _gender, int _age, string _tagline) : username(_username), firstname(_firstname), lastname(_lastname), gender(_gender), age(_age), tagline(_tagline) { if (set_info(_username, _firstname, _lastname, _age, _tagline, _gender) == false) { username = ""; firstname = ""; lastname = ""; gender = 0; age = 0; tagline = ""; // if set info fails, return a Person with empty fields } } string Person::get_username() { return username; } string Person::get_firstname() { return firstname; } string Person::get_lastname() { return lastname; } int Person::get_gender(){ return gender; } int Person::get_age() { return age; } string Person::get_tagline() { return tagline; } string Person::get_info() { std::stringstream buffer; buffer << "Username: " << username << ", Firstname: " << firstname << ", Lastname: " << lastname << ", Age: " << age << ", Tagline: " << tagline << ", Gender: " << gender; string ret = buffer.str(); return ret; } bool Person::set_username(string _username) { regex r("^[[:alpha:]]+[[:digit:]]+[[:alnum:]]*$"); if (_username.length() <= 64 && regex_match(_username, r)) { username = _username; return true; } else { return false; } } bool Person::set_firstname(string _firstname) { regex r("^[[:alpha:]]+$"); if (_firstname.length()<= 64 && regex_match(_firstname, r)) { firstname = _firstname; return true; } else { return false; } } //--------------DONE--------------// bool Person::set_lastname(string _lastname) { regex r("^[[:alpha:]]+$"); if (_lastname.length()<= 64 && regex_match(_lastname, r)) { lastname = _lastname; return true; } else { return false; } } //--------DONE----------// bool Person::set_gender(int _gender){ if (_gender == 1 || _gender == 2) { gender = _gender; return true; } else { return false; } } // --------DONE---------- // bool Person::set_age(int _age) { if (_age>=18 && _age<=100) { age = _age; return true; } else { return false; } } // ----------DONE-----------// bool Person::set_tagline(string _tagline) { if (_tagline.length() <= 128) { tagline = _tagline; return true; } else { return false; } } bool Person::set_info(string _username, string _firstname, string _lastname, int _age, string _tagline, int _gender) { string old_username = username; string old_firstname = firstname; string old_lastname = lastname; int old_age = age; string old_tagline = tagline; int old_gender = gender; if (set_username(_username) && set_firstname(_firstname) && set_lastname(_lastname) && set_gender(_gender) && set_age(_age) && set_tagline(_tagline)) { return true; } username = old_username; firstname = old_firstname; lastname = old_lastname; age = old_age; tagline = old_tagline; gender = old_gender; return false; } bool Person::send_msg(Person &recipient, string msg) { if (recipient.get_msgstat(*this) > 10) { return false; } else { recipient.get_msg(msg); recipient.get_msg_with_info(msg, this); return true; } } void Person::get_msg(string msg) { inbox.push(msg); } int Person::get_msgstat(Person recipient){ queue<pair<string,Person*> > inbox_stat_copy = inbox_stat; int result = 0; pair<string,Person*> entry; while (!inbox_stat_copy.empty()) { if (inbox_stat_copy.front().first == recipient.username) { result++; } inbox_stat_copy.pop(); } return result; } void Person::get_msg_with_info (string msg, Person* sender){ inbox_stat.push(make_pair(msg,sender)); } bool Person::read_msg() { if (inbox.empty() || inbox_stat.empty()) { return false; } else { inbox.pop(); inbox_stat.pop(); return true; } }
true
6792feb37db326e189863f587800a3f70fb3805b
C++
vadixidav/gpi-cpp
/meprogram.h
UTF-8
1,310
2.75
3
[ "BSD-2-Clause" ]
permissive
#ifndef MEPROGRAM_H #define MEPROGRAM_H #include "chromosome.h" namespace gpi { struct Scratchpad { double result; Scratchpad(); bool isSolved(); }; struct MEProgram { unsigned tInputs; //Total inputs to network unsigned tOutputs; //Total outputs from network unsigned tInternalChromosomes; //Extra internal chromosomes unsigned tChromosomeSize; //Instructions in a chromosome std::vector<Chromosome> internalChromosomes; std::vector<Chromosome> outputChromosomes; std::vector<Scratchpad> scratchValues; //Construct a new program and randomize it MEProgram(unsigned totalInputs, unsigned totalOutputs, unsigned totalInternalChromosomes, unsigned totalChromosomeSize, std::mt19937 &rand); //Construct a new program as a copy of another MEProgram(const MEProgram &parent); void crossover(const MEProgram &parent, std::mt19937 &rand); void randomize(std::mt19937 &rand); void mutate(std::mt19937 &rand); void startSolve(); //Run this every time the program or the inputs change before solving again double solveOutput(unsigned output, double *inputs); }; } #endif // MEPROGRAM_H
true
3202fca8529fc22f747eae29aa4314b7192cf470
C++
geckods/CodeForces
/206/c.cpp
UTF-8
6,534
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll altcost(ll arr[], ll cum[], ll n, ll i, ll j, bool isleft, ll l, ll r){ if((j-i+1)%2 == 0){ ll left = cum[(i+j)/2]*l; if(i>0)left-=cum[i-1]*l; ll right = cum[j]*r; if((i+j)/2>0)right = cum[(i+j)/2 -1]*r; return left+right; } else{ ll left=0; if((i+j)/2>0){ left = cum[(i+j)/2-1]*l; } if(i>0)left-=cum[i-1]*l; ll right = cum[j]*r; right -= cum[(i+j)/2]*r; ll mid=0; if(isleft){ mid=arr[(i+j)/2]*l; } else{ mid=arr[(i+j)/2]*r; } // cerr<<"LRM"<<" "<<left<<" "<<right<<" "<<mid<<endl; // cerr<<"L:"<<" "<<l<<endl; return left+right+mid; } } ll leftcost(ll arr[], ll cum[], ll i, ll j, ll l, ll r, ll ql, ll qr){ ll cost=cum[j]; if(i>0){ cost-=cum[i-1]; } cost*=l; cost+=(j-i)*ql; return cost; } ll rightcost(ll arr[], ll cum[], ll i, ll j, ll l, ll r, ll ql, ll qr){ ll cost=cum[j]; if(i>0){ cost-=cum[i-1]; } cost*=r; cost+=(j-i)*qr; return cost; } int main(){ #ifndef ONLINE_JUDGE freopen("input", "r", stdin); freopen("output", "w", stdout); freopen("error", "w", stderr); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); ll n,l,r,ql,qr; cin>>n>>l>>r>>ql>>qr; ll arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } // cerr<<"HI"<<endl; //alternate till a point //start left ll ans=LLONG_MAX; int currmin=0; int currmax=(n-1); ll cum[n]; cum[0]=arr[0]; for(int i=1;i<n;i++){ cum[i]=arr[i]+cum[i-1]; } ll minians=0; ll minterm=0; // ll newans=0; // bool lastleft; // if(arr[currmin]*l<=arr[currmax]*r){ // newans+=arr[currmin]*l; // currmin++; // lastleft=true; // } // else{ // newans+=arr[currmax]*r; // currmax--; // lastleft=false; // } // while(currmin<=currmax){ // ll leftcost = arr[currmin]*l; // ll rightcost = arr[currmax]*r; // if(lastleft)leftcost+=ql; // else rightcost+=qr; // // cerr<<currmin<<" "<<currmax<<" "<<leftcost<<" "<<rightcost<<" "<<newans<<endl; // if(leftcost<=rightcost){ // lastleft=true; // newans+=leftcost; // currmin++; // } // else{ // lastleft=false; // newans+=rightcost; // currmax--; // } // } // cout<<newans<<endl; // return 0; // while(currmin<=currmax){ // if(currmin==0) // minterm=min(leftcost(arr, cum,currmin,currmax,l,r,ql,qr),rightcost(arr, cum,currmin,currmax,l,r,ql,qr)); // else // minterm=min(leftcost(arr, cum,currmin,currmax,l,r,ql,qr),rightcost(arr, cum,currmin,currmax,l,r,ql,qr)+qr); // cerr<<currmin<<" "<<currmax<<" "<<minians<<" "<<minterm<<endl; // if(altcost(arr, cum, n, currmin, currmax,true,l,r)<minterm){ // minians+=arr[currmin]*l; // currmin++; // } // else{ // minians+=minterm; // break; // } // minterm=min(leftcost(arr, cum,currmin,currmax,l,r,ql,qr)+ql,rightcost(arr, cum,currmin,currmax,l,r,ql,qr)); // cerr<<currmin<<" "<<currmax<<" "<<minians<<" "<<minterm<<endl; // if(altcost(arr, cum, n, currmin, currmax,false,l,r) < minterm){ // minians+=arr[currmax]*r; // currmax--; // } // else{ // minians+=minterm; // break; // } // } // cerr<<minians<<endl; // ans=min(ans,minians); // minians=0; // currmin=0; // currmax=(n-1); // while(currmin<=currmax){ // if(currmax==(n-1)) // minterm=min(leftcost(arr, cum,currmin,currmax,l,r,ql,qr),rightcost(arr, cum,currmin,currmax,l,r,ql,qr)); // else // minterm=min(leftcost(arr, cum,currmin,currmax,l,r,ql,qr)+ql,rightcost(arr, cum,currmin,currmax,l,r,ql,qr)); // cerr<<currmin<<" "<<currmax<<" "<<minians<<" "<<minterm<<endl; // if(altcost(arr, cum, n, currmin, currmax,false,l,r) < minterm){ // minians+=arr[currmax]*r; // currmax--; // } // else{ // minians+=minterm; // break; // } // minterm=min(leftcost(arr, cum,currmin,currmax,l,r,ql,qr),rightcost(arr, cum,currmin,currmax,l,r,ql,qr)+qr); // cerr<<currmin<<" "<<currmax<<" "<<minians<<" "<<minterm<<endl; // // cerr<<altcost(arr, cum, n, currmin, currmax,true,l,r)<<endl; // if(altcost(arr, cum, n, currmin, currmax,true,l,r) < minterm){ // // cerr<<"HI"<<endl; // minians+=arr[currmin]*l; // currmin++; // } // else{ // minians+=minterm; // break; // } // } // cerr<<minians<<endl; // ans=min(ans,minians); // cout<<ans<<endl; if(n==1){ cout<<arr[0]*min(l,r)<<endl; return 0; } if(n%2==0){ ll dp[n][2]; //dp[i] represents the range from ((n-1)/2 - i) to ((n-1)/2 + i +1) //dp[i][0] represents leftstart dp[0][0]=min(arr[((n-1)/2)]*l + arr[((n-1)/2)+1]*r,arr[((n-1)/2)]*l + arr[((n-1)/2)+1]*l+ql); dp[0][1]=min(arr[((n-1)/2)]*l + arr[((n-1)/2)+1]*r,arr[((n-1)/2)]*r + arr[((n-1)/2)+1]*r+qr); // cout<<dp[0][0]<<" "<<dp[0][1]<<endl; for(int i=1;i<n/2;i++){ dp[i][0]=min(arr[((n-1)/2)-i]*l+arr[((n-1)/2)+i+1]*r+dp[i-1][0],arr[((n-1)/2)-i]*l+arr[((n-1)/2)+i+1]*r+dp[i-1][1]+qr); dp[i][0]=min(dp[i][0],leftcost(arr, cum, ((n-1)/2)-i, ((n-1)/2)+i+1, l, r, ql, qr)); dp[i][1]=min(arr[((n-1)/2)-i]*l+arr[((n-1)/2)+i+1]*r+dp[i-1][1],arr[((n-1)/2)-i]*l+arr[((n-1)/2)+i+1]*r+dp[i-1][0]+ql); // cout<<dp[i][1]<<endl; dp[i][1]=min(dp[i][1],rightcost(arr, cum, ((n-1)/2)-i, ((n-1)/2)+i+1, l, r, ql, qr)); } cout<<min(dp[((n-1))/2][0],dp[((n-1))/2][1])<<endl; } else{ ll dp[n][2]; //dp[i] represents the range from (n/2-i-1) to (n/2+i+1) //dp[i][0] represents leftstart dp[0][0]=min(arr[(n/2)-1]*l+arr[(n/2)+1]*r+arr[(n/2)]*l,arr[(n/2)-1]*l+arr[n/2]*l+ql+arr[(n/2)+1]*l+ql); dp[0][1]=min(arr[(n/2)-1]*l+arr[(n/2)+1]*r+arr[(n/2)]*r,arr[(n/2)-1]*r+arr[n/2]*r+qr+arr[(n/2)+1]*r+qr); // cout<<dp[0][0]<<" "<<dp[0][1]<<endl; for(int i=1;i<n/2;i++){ dp[i][0]=min(arr[(n/2)-i-1]*l+arr[(n/2)+i+1]*r+dp[i-1][0],arr[(n/2)-i-1]*l+arr[(n/2)+i+1]*r+dp[i-1][1]+qr); dp[i][0]=min(dp[i][0],leftcost(arr, cum, (n/2)-i-1, (n/2)+i+1, l, r, ql, qr)); dp[i][1]=min(arr[(n/2)-i-1]*l+arr[(n/2)+i+1]*r+dp[i-1][1],arr[(n/2)-i-1]*l+arr[(n/2)+i+1]*r+dp[i-1][0]+ql); dp[i][1]=min(dp[i][1],rightcost(arr, cum, (n/2)-i-1, (n/2)+i+1, l, r, ql, qr)); } cout<<min(dp[n/2-1][0],dp[n/2-1][1])<<endl; } }
true
e388d6ab946638de08acc01b6d3958eac04c422b
C++
tanvirtareq/programming
/uva/UVA 11308.cpp
UTF-8
1,812
2.734375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; string binder, ingredient, reciep, requrment; map<string, int>ing, req; map< int, string>out; void printmap() { map<string, int>::iterator i; for(i=ing.begin();i!=ing.end();i++) { cout<<i->first<<" "<<i->second<<endl; } } void print_binder() { for(int i=0;i<binder.size();i++) { binder[i]=toupper(binder[i]); cout<<binder[i]; } cout<<endl; return; } void output() { map<int, string>::iterator i; for(i=out.begin();i!=out.end();i++) { cout<<i->second<<endl; } return; } int main() { int t; cin>>t; cin.ignore(); while(t--) { ing.clear(); out.clear(); getline(cin, binder); print_binder(); int m, n, b; cin>>m>>n>>b; while(m--) { int c; cin>>ingredient>>c; ing[ingredient]=c; } cin.ignore(); int flag=0; while(n--) { getline(cin, reciep); int k; cin>>k; int cost=0; while(k--) { int money; cin>>requrment>>money; req[requrment]=money; cost+=req[requrment]*ing[requrment]; } cin.ignore(); if(cost<=b) { flag=1; out[cost]=reciep; } } if(flag==0) { cout<<"Too expensive!"<<endl; } else if(flag==1) { output(); } cout<<endl; } return 0; }
true
8553ebe431d32ef91f8ad79c759fc91bea62b455
C++
habib302/leetcode-1
/951. Flip Equivalent Binary Trees.cpp
UTF-8
1,167
3.3125
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ void dfs(TreeNode* node, vector < vector < int > > &graph) { if( node == NULL ) return; graph[node->val].push_back(0); if(node->left) { graph[node->val].push_back(node->left->val); dfs(node->left, graph); } if( node->right ) { graph[node->val].push_back(node->right->val); dfs(node->right, graph); } } class Solution { public: bool flipEquiv(TreeNode* root1, TreeNode* root2) { vector < vector < int > > a( 105 ); vector < vector < int > > b(105 ); dfs(root1, a); dfs(root2, b); for( int i = 0 ; i < 100 ; i++ ) { if(a[i].size() != b[i].size()) return false; sort(a[i].begin(), a[i].end()); sort(b[i].begin(), b[i].end()); for( int j = 0 ; j < a[i].size() ; j++ ) { if(a[i][j] != b[i][j] ) return false; } } return true; } };
true
6b08a60575011b3dde6daa2f8e7acd0a22aad7b8
C++
Oskari-Tuormaa/E4PRJ-2021
/ControlUnit/WebSocket, UserData, Controller/WebSocketServer_IF/WebSocketServer_IF.h
UTF-8
13,366
2.515625
3
[]
no_license
#pragma once /*#define ASIO_STANDALONE*/ #include <websocketpp/config/asio_no_tls.hpp> #include <websocketpp/server.hpp> #include <iostream> #include <fstream> #include <ctime> #include <functional> #include <chrono> #include <thread> #include "json.hpp" #include "WebSocket_Message.hpp" using json = nlohmann::json; typedef websocketpp::server<websocketpp::config::asio> server; class WebSocketServer_IF { public: WebSocketServer_IF() { // Find config file readConfigfile(); // Set logging settings for websocketpp m_endpoint.set_error_channels(websocketpp::log::elevel::none); m_endpoint.set_access_channels(websocketpp::log::alevel::none); // Initialize Asio m_endpoint.init_asio(); // Set message handler m_endpoint.set_message_handler(websocketpp::lib::bind(&WebSocketServer_IF::on_message, this, websocketpp::lib::placeholders::_1, websocketpp::lib::placeholders::_2)); // Set open handler m_endpoint.set_open_handler(bind(&WebSocketServer_IF::on_open, this, websocketpp::lib::placeholders::_1)); // Set close handler m_endpoint.set_close_handler(bind(&WebSocketServer_IF::on_close, this, websocketpp::lib::placeholders::_1)); //Set HTTP handler m_endpoint.set_http_handler(bind(&WebSocketServer_IF::on_http, this, websocketpp::lib::placeholders::_1)); } ~WebSocketServer_IF() { std::cout << "[WebSocketServer_IF][INFO] Stopping server." << std::endl; m_endpoint.stop(); endpointThread.join(); std::cout << "[WebSocketServer_IF][INFO] Server stopped." << std::endl; } /* Register a function to be called when a message is recieved. Callback function should be of type void(Message*). */ void add_onMessage_Handler(std::function<void(WebSocket_Message *)> cb) { onMessage = cb; } /* Register a function to be called when a client connects. Callback function should be of type void(Client*). */ void add_onConnected_Handler(std::function<void(Client *)> cb) { onConnected = cb; } /* Register a function to be called when a client disconnects. Callback function should be of type void(Client*). */ void add_onDisconnected_Handler(std::function<void(Client *)> cb) { onDisconnected = cb; } // Starts the server. Async. void run() { endpointThread = std::thread(&WebSocketServer_IF::_run, this); } // Returns a pointer to a vector of all connected clients. std::vector<Client> *getClients() { return &connections; } /* Returns a vector of Client pointes for all clients of a certan type. Returns an empty vector if no clients of the given type is connected. */ std::vector<Client *> getConnectionsOfType(Client::connectionType type) { std::vector<Client *> res; for (auto &con : connections) { if (con.getType() == type) { res.push_back(&con); } } return res; } // Changes the connectiontype of a connection and transmits a message if needed void redefineConnection(Client *con, Client::connectionType newType, bool broadcastUpdate = true) { if (con->getType() != newType) { con->setType(newType); json informMessage; json meta; switch (newType) { case Client::connectionType::dormantBrowser: informMessage["type"] = "SetToDormantBrowser"; break; case Client::connectionType::primaryBrowser: informMessage["type"] = "UpgradeToPrimaryBrowser"; break; case Client::connectionType::pistol: informMessage["type"] = "UpgradeToPistol"; meta["battery"] = 0; meta["charging"] = false; con->mergeMetadata(meta); break; case Client::connectionType::unknown: informMessage["type"] = "DowngradeToUnknown"; meta["battery"] = nullptr; meta["charging"] = nullptr; con->mergeMetadata(meta); break; default: std::cout << "[WebSocketServer_IF][WARN] Tried to upgade to an unknown connectiontype." << std::endl; break; } if (!informMessage["type"].is_null()) { con->send(informMessage); } if (broadcastUpdate && (newType == Client::connectionType::pistol || newType == Client::connectionType::primaryBrowser)) { broadcastConnections(); } } } // Sends a list of the connected pistols to the primary browser void broadcastConnections() { auto res = getConnectionsOfType(Client::connectionType::primaryBrowser); if (res.size() > 0) { json message; message["type"] = "Pistollist"; message["pistols"] = json::array(); for (auto &con : getConnectionsOfType(Client::connectionType::pistol)) { message["pistols"].push_back(con->getMetadata()); } res[0]->send(message); } else { std::cout << "[WebSocketServer_IF][WARN] Canceled broadcast of information. No primary browser was found." << std::endl; } } private: // On message callback funton. std::function<void(WebSocket_Message *)> onMessage = nullptr; // On new connection callback function. std::function<void(Client *)> onConnected = nullptr; // On connection ended callback function. std::function<void(Client *)> onDisconnected = nullptr; // The actual server server m_endpoint; // Thead running the endpoint std::thread endpointThread; // Port int port = 80; // Document root of HTTP requests std::string httpfilelocation = "httpcontent/"; // Vector containing pointers to all connections std::vector<Client> connections; // Server start. Runs in thread void _run() { // Retrying to allocate the port if it fails bool portSucess = false; while (portSucess == false) { try { // Listen on port 3000 m_endpoint.listen(boost::asio::ip::tcp::v4(), port); portSucess = true; } catch (const std::exception &ex) { std::cout << "[WebSocketServer_IF][ERROR] Failed to allocate port " << port << ". Retry will commence in 10 seconds" << std::endl; std::cout << "[WebSocketServer_IF][ERROR] " << ex.what() << std::endl; std::this_thread::sleep_for((std::chrono::milliseconds)10000); } } // Queues a connection accept operation m_endpoint.start_accept(); std::cout << "[WebSocketServer_IF][INFO] Starting server on port " << port << "." << std::endl << std::endl; // Start the Asio io_service run loop m_endpoint.run(); } // Message handler void on_message(websocketpp::connection_hdl hdl, server::message_ptr msg) { try { // Connection pointer std::shared_ptr<websocketpp::connection<websocketpp::config::asio>> connectionPointer = m_endpoint.get_con_from_hdl(hdl); std::cout << "[WebSocketServer_IF][INFO] Message recieved from: " << connectionPointer->get_remote_endpoint() << " | saying: " << msg->get_payload() << std::endl; // Find connection from connectionlist Client *con = nullptr; for (auto &_con : connections) { if (_con.is(connectionPointer)) { con = &_con; } } if (con == nullptr) { std::cout << "[WebSocketServer_IF][ERROR] Connection was not found in connectionlist. Terminating handle." << std::endl; std::cout << std::endl; return; } // Input as JSON json input; try { input = json::parse(msg->get_payload()); } catch (const std::exception &ex) { std::cout << "[WebSocketServer_IF][ERROR] Could not pass incomming message as JSON. Terminating handle. Errordetails: " << ex.what() << std::endl; std::cout << std::endl; return; } WebSocket_Message message(input, con); if (onMessage != nullptr) { try { onMessage(&message); } catch (const std::exception &ex) { std::cout << "[WebSocketServer_IF][ERROR] Fatal error in message handle callback. Terminating handle. Errordetails: " << ex.what() << std::endl; std::cout << std::endl; return; } } else { std::cout << "[WebSocketServer_IF][WARN] No handler for event 'onMessage' found." << std::endl; message.addToResponse("{\"status\": 501}"_json); } if (message.is_requestingReply()) { if (!message.is_replyUpdated()) { message.addToResponse("{\"status\": 204}"_json); } message.getClient()->send(message.getResponseContent()); } } catch (const std::exception &ex) { std::cout << "[WebSocketServer_IF][ERROR] Fatal error on incomming message. Terminating handle. Errordetails: " << ex.what() << std::endl; std::cout << std::endl; return; } std::cout << std::endl; } // Open handler void on_open(websocketpp::connection_hdl hdl) { // Translating connection-handle to connection-pointer which is much more functional std::shared_ptr<websocketpp::connection<websocketpp::config::asio>> connectionPointer = m_endpoint.get_con_from_hdl(hdl); // Console message std::cout << "[WebSocketServer_IF][INFO] Connection established with: " << (connectionPointer)->get_remote_endpoint() << std::endl; // Adds the pointer to a vector for later use json metadata; metadata["ID"] = connectionPointer->get_remote_endpoint().substr(connectionPointer->get_remote_endpoint().find_last_of(":") + 1); connections.push_back({connectionPointer, time(0), metadata}); if (onConnected != nullptr) { onConnected(&connections[connections.size() - 1]); } else { std::cout << "[WebSocketServer_IF][WARN] No handler for event 'onConnected' found." << std::endl; } std::cout << std::endl; } // Close handler void on_close(websocketpp::connection_hdl hdl) { // Connectionpointer for disconnected connection std::shared_ptr<websocketpp::connection<websocketpp::config::asio>> pointer = m_endpoint.get_con_from_hdl(hdl); // Removes pointer from vector for (std::vector<Client>::iterator it = connections.begin(); it < connections.end(); it++) { if ((*it).is(pointer)) { std::cout << "[WebSocketServer_IF][INFO] Client of type: " << it->getType() << " disconnected." << std::endl; if (onDisconnected != nullptr) { onDisconnected(&(*it)); } else { std::cout << "[WebSocketServer_IF][WARN] No handler for event 'onDisconnected' found." << std::endl; } if ((*it).getType() == Client::connectionType::primaryBrowser) { std::cout << "[WebSocketServer_IF][INFO] Primary browser disconnected" << std::endl; auto res = getConnectionsOfType(Client::connectionType::dormantBrowser); if (res.size() > 0) { redefineConnection(res[0], Client::connectionType::primaryBrowser); } else { std::cout << "[WebSocketServer_IF][WARN] No new primary browser was found" << std::endl; } } connections.erase(it); break; } } broadcastConnections(); std::cout << std::endl; } // Handler for HTTP requests void on_http(websocketpp::connection_hdl hdl) { // Upgrade our connection handle to a full connection_ptr server::connection_ptr con = m_endpoint.get_con_from_hdl(hdl); std::ifstream file; std::string filename = con->get_uri()->get_resource(); std::string response; std::string filePath = filename; if (filename == "/") { filePath = httpfilelocation + "index.html"; } else { filePath = httpfilelocation + filename.substr(1); } std::cout << "[WebSocketServer_IF][INFO] HTTP request on content: '" << filename << "'." << std::endl; file.open(filePath.c_str(), std::ios::in); if (!file) { filePath = httpfilelocation + "index.html"; file.open(filePath.c_str(), std::ios::in); if (!file) { return; } } file.seekg(0, std::ios::end); response.reserve(file.tellg()); file.seekg(0, std::ios::beg); response.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); con->set_body(response); con->set_status(websocketpp::http::status_code::ok); std::cout << std::endl; } void readConfigfile() { try { std::ifstream configStream("config.json"); json config; if (configStream.is_open()) { std::cout << "[WebSocketServer_IF][INFO] Configurationfile found." << std::endl; configStream >> config; configStream.close(); if (config.is_object()) { // Get port if (config["WebSocketServer_IF"]["port"].is_number()) { port = config["WebSocketServer_IF"]["port"]; std::cout << "[WebSocketServer_IF][INFO] Serverport changed to '" << port << "'." << std::endl; } else { std::cout << "[WebSocketServer_IF][WARN] Syntaxerror in configurationfile." << std::endl; } // Get httpfile location if (config["WebSocketServer_IF"]["httpfilelocation"].is_string()) { httpfilelocation = config["WebSocketServer_IF"]["httpfilelocation"]; std::cout << "[WebSocketServer_IF][INFO] Httpfile location changed to '" << httpfilelocation << "'." << std::endl; } else { std::cout << "[WebSocketServer_IF][WARN] Syntaxerror in configurationfile" << std::endl; } // Add more config here. std::cout << "[WebSocketServer_IF][INFO] End of configurationfile." << std::endl; } else { std::cout << "[WebSocketServer_IF][INFO] Configurationfile is empty." << std::endl; } } else { std::cout << "[WebSocketServer_IF][INFO] Configurationfile was not found." << std::endl; } } catch (const std::exception &ex) { std::cout << "[WebSocketServer_IF][WARN] An error occurred while reading configurationfile." << std::endl; std::cout << "[WebSocketServer_IF][WARN] " << ex.what() << std::endl; } std::cout << std::endl; } };
true
5084854934e1f9e7380914eb9f771df709cf69ac
C++
patrickbergel/huji-rich
/source/3D/GeometryCommon/Tessellation3D.hpp
UTF-8
5,167
3.203125
3
[]
no_license
/*! \file Tessellation3D.hpp \brief Abstract class for the tessellation in 3D \author Elad Steinberg */ #ifndef TESSELLATION3D_HPP #define TESSELLATION3D_HPP 1 #include <vector> #include "HilbertOrder3D.hpp" #include "Face.hpp" #include "OuterBoundary3D.hpp" using std::vector; /*! \brief Abstract class for tessellation in 3D \author Elad Steinberg */ class Tessellation3D { public: /*! \brief Initialises the tessellation \param points Initial position of mesh generating points \param bc Boundary conditions of the computational domain */ virtual void Initialise(vector<Vector3D> const& points, OuterBoundary3D const* bc) = 0; /*! \brief Update the tessellation \param points The new positions of the mesh generating points */ virtual void Update(vector<Vector3D> const& points) = 0; /*! \brief Get Total number of mesh generating points \return Number of mesh generating points */ virtual size_t GetPointNo(void) const = 0; /*! \brief Returns Position of mesh generating point \param index Mesh generating point index \return Position of mesh generating point */ virtual Vector3D GetMeshPoint(size_t index) const = 0; /*! \brief Returns Position of Cell's Center of Mass \param index Mesh generating point index (the cell's index) \return Position of CM */ virtual Vector3D const& GetCellCM(size_t index) const = 0; /*! \brief Returns the total number of faces \return Total number of faces */ virtual size_t GetTotalFacesNumber(void) const = 0; /*! \brief Returns Face (interface between cells) \param index Face index \return Interface between cells */ virtual Face const& GetFace(size_t index) const = 0; /*! \brief Returns the effective width of a cell \param index Cell index \return Effective cell width */ virtual double GetWidth(size_t index) const = 0; /*! \brief Returns the volume of a cell \param index Cell index \return Cell volume */ virtual double GetVolume(size_t index) const = 0; /*! \brief Returns the indeces of a cell's Faces \param index Cell index \return Cell edges */ virtual vector<size_t>const& GetCellFaces(size_t index) const = 0; /*! \brief Returns a reference to the point vector \returns The reference */ virtual vector<Vector3D>& GetMeshPoints(void) = 0; /*! \brief Returns a list of the neighbors of a cell \param index The cell to check \return The neighbors */ virtual vector<size_t> GetNeighbors(size_t index)const = 0; /*! \brief Cloning function \return Pointer to clone */ virtual Tessellation3D* clone(void) const = 0; //! \brief Virtual destructor virtual ~Tessellation3D(void); /*! \brief Returns if the cell is adjacent to a boundary \param index The cell to check \return If near boundary */ virtual bool NearBoundary(size_t index) const = 0; /*! \brief Returns if the face is a boundary one \param index The face to check \return True if boundary false otherwise */ virtual bool BoundaryFace(size_t index) const = 0; /*! \brief Returns the indeces of the points that where sent to other processors as ghost points (or to same cpu for single thread) ad boundary points \return The sent points, outer vector is the index of the outer Face and inner vector are the points sent through the face */ virtual vector<vector<size_t> >& GetDuplicatedPoints(void) = 0; /*! \brief Returns the indeces of the points that where sent to other processors as ghost points (or to same cpu for single thread) ad boundary points \return The sent points, outer vector is the index of the outer Face and inner vector are the points sent through the face */ virtual vector<vector<size_t> >const& GetDuplicatedPoints(void)const = 0; /*! \brief Returns the total number of points (including ghost) \return The total number of points */ virtual size_t GetTotalPointNumber(void)const = 0; /*! \brief Returns the center of masses of the cells \return The CM's */ virtual vector<Vector3D>& GetAllCM(void) = 0; /*! \brief Returns the neighbors and neighbors of the neighbors of a cell \param point The index of the cell to calculate for \param result The neighbors and their neighbors indeces */ virtual void GetNeighborNeighbors(vector<size_t> &result,size_t point)const = 0; /*! \brief Returns a vector normal to the face whose magnitude is the seperation between the neighboring points \param faceindex The index of the face \return The vector normal to the face whose magnitude is the seperation between the neighboring points pointing from the first neighbor to the second */ virtual Vector3D Normal(size_t faceindex)const=0; /*! \brief Checks if a point is a ghost point or not \param index Point index \return True if is a ghost point, false otherwise */ virtual bool IsGhostPoint(size_t index)const=0; /*! \brief Calculates the velocity of a face \param p0 The index of the first neighbor \param p1 The index of the second neighbor \param v0 The velocity of the first neighbor \param v1 The velocity of the second neighbor \return The velocity of the face */ virtual Vector3D CalcFaceVelocity(size_t p0,size_t p1,Vector3D const& v0, Vector3D const& v1)const=0; }; #endif // TESSELLATION3D_HPP
true
efbb8ab7cb43067373ce0cd13472df1d762c3f8e
C++
jfantell/ReactiveProjectionMapping
/shadows/include/mesh.h
UTF-8
1,852
2.890625
3
[]
no_license
#ifndef SHADOWS_SHADOWS_INCLUDE_MESH_H_ #define SHADOWS_SHADOWS_INCLUDE_MESH_H_ #include <string.h> #include <iostream> #include <vector> #include "glm/vec2.hpp" #include "glm/vec3.hpp" // Needed later for interlacing everything - see interlaceAll() struct vertex_struct { glm::vec3 vertex; glm::vec3 normal; glm::vec2 uv; }; // Needed later for interlacing everything - see interlaceAll() struct indices { unsigned int vertex; unsigned int uv; unsigned int normal; // This operator required to use an unordered_map - see interlaceAll() bool const operator==(const indices &o) const { return vertex == o.vertex && uv == o.uv && normal == o.normal; } }; // This std::hash specialization also required for unordered_map - see interlaceAll() template<> struct std::hash<indices> { std::size_t operator()(const indices& i) const { return std::hash<unsigned int>()(i.vertex) + 7 ^ std::hash<unsigned int>()(i.uv) + 2 ^ std::hash<unsigned int>()(i.normal) + 3; } }; class Mesh { public: Mesh(); void loadOBJ(std::string pathtofile); unsigned int vertexCount(); float * getVertexArrayPTR(); float * getNormalArrayPTR(); unsigned int indexCount(); unsigned int * getIndexArrayPTR(); void interlaceVertexAndNormal(); void interlaceAll(); void printAttributes(); bool isInterlaced() { return _interlaced; } void setInterlaced(bool interlaced) { _interlaced = interlaced; } std::vector<glm::vec3> normals; std::vector<glm::vec3> vertices; std::vector<glm::vec2> uvs; std::vector<unsigned int> indices_vertex; std::vector<unsigned int> indices_normal; std::vector<unsigned int> indices_uv; std::vector<vertex_struct> interlacedVertices; std::vector<unsigned int> interlacedIndices; private: bool _interlaced = false; }; #endif //SHADOWS_SHADOWS_INCLUDE_MESH_H_
true
473a18f963dd54ceb5cff91af90330ba59334840
C++
echo-team/Snoke
/app/Widgets/logo.cpp
UTF-8
2,109
3.234375
3
[]
no_license
#include "logo.h" /** * Sets coordinates of logo * @param {int} left - x coordinate of left logo side * @param {int} top - y coordinate of top logo side */ void Logo::setPosition(int left, int top) { x = left; y = top; } /** * Returns size of the logo * @return {Point} - width and height of the logo */ Point Logo::getSize() { Point size; size.x = strlen(inscription[language][0]); size.y = 5; return size; } /** * Draws Logo in console window */ void Logo::draw() { init_color(COLOR_WHITE, 1000, 1000, 1000); init_pair(1, style.fg, style.bg); init_pair(2, shadowStyle.fg, shadowStyle.bg); for (int rowCounter = 0; rowCounter < 5; rowCounter++) { for (int colCounter = 0; colCounter < (int)strlen(inscription[language][0]); colCounter++) { if (inscription[language][rowCounter][colCounter] != ' ') { move(y + rowCounter, x + colCounter); attron(COLOR_PAIR(1)); addch(style.letter); attroff(COLOR_PAIR(1)); attron(COLOR_PAIR(2)); move(y + rowCounter + 1, x + colCounter + 1); addch(shadowStyle.letter); attroff(COLOR_PAIR(2)); } } } } /** * @constructor * @param {PointStyle} style - style of the cells with logo * @param {PointStyle} shadowStyle - style of the cells with shadow of the logo */ Logo::Logo(int x, int y, PointStyle style, PointStyle shadowStyle, int language) : x(x), y(y), style(style), shadowStyle(shadowStyle), language(language) { inscription.push_back( { " **** * * *** * * ****", "* ** * * * * * * ", " *** * * * * * **** ****", " * * ** * * * * * ", "**** * * *** * * ****" }); inscription.push_back( { "**** * * * * *** ", " * ** ** * ** * *", " ** * * * * * * * *", " * * * ** * ****", "**** * * * * * *" }); }
true
8ab906734f6bb8397d94220ee4cf97cad48508f9
C++
lineCode/ABx
/abserv/abserv/OctreeQuery.h
UTF-8
3,584
3.03125
3
[]
no_license
#pragma once #include "BoundingBox.h" #include "Vector3.h" #include "Sphere.h" #include "Ray.h" namespace Game { class GameObject; } namespace Math { class OctreeQuery { public: OctreeQuery(std::vector<Game::GameObject*>& result) : result_(result) { } virtual ~OctreeQuery() = default; OctreeQuery(const OctreeQuery& rhs) = delete; OctreeQuery& operator =(const OctreeQuery& rhs) = delete; /// Intersection test for an octant. virtual Intersection TestOctant(const BoundingBox& box, bool inside) = 0; /// Intersection test for objects. virtual void TestObjects(Game::GameObject** start, Game::GameObject** end, bool inside) = 0; std::vector<Game::GameObject*>& result_; }; class PointOctreeQuery : public OctreeQuery { public: PointOctreeQuery(std::vector<Game::GameObject*>& result, const Vector3 point) : OctreeQuery(result), point_(point) { } /// Intersection test for an octant. Intersection TestOctant(const BoundingBox& box, bool inside) override; /// Intersection test for objects. void TestObjects(Game::GameObject** start, Game::GameObject** end, bool inside) override; Vector3 point_; }; class SphereOctreeQuery : public OctreeQuery { public: /// Construct with sphere and query parameters. SphereOctreeQuery(std::vector<Game::GameObject*>& result, const Sphere& sphere) : OctreeQuery(result), sphere_(sphere) {} /// Intersection test for an octant. Intersection TestOctant(const BoundingBox& box, bool inside) override; /// Intersection test for objects. void TestObjects(Game::GameObject** start, Game::GameObject** end, bool inside) override; /// Sphere. Sphere sphere_; }; class BoxOctreeQuery : public OctreeQuery { public: /// Construct with bounding box and query parameters. BoxOctreeQuery(std::vector<Game::GameObject*>& result, const BoundingBox& box) : OctreeQuery(result), box_(box) {} /// Intersection test for an octant. Intersection TestOctant(const BoundingBox& box, bool inside) override; /// Intersection test for objects. void TestObjects(Game::GameObject** start, Game::GameObject** end, bool inside) override; /// Bounding box. BoundingBox box_; }; struct RayQueryResult { /// Construct with defaults. RayQueryResult() : distance_(0.0f), object_(nullptr) {} /// Test for inequality, added to prevent GCC from complaining. bool operator !=(const RayQueryResult& rhs) const { return position_ != rhs.position_ || normal_ != rhs.normal_ || !Equals(distance_, rhs.distance_) || object_ != rhs.object_; } /// Hit position in world space. Vector3 position_; /// Hit normal in world space. Negation of ray direction if per-triangle data not available. Vector3 normal_; /// Distance from ray origin. float distance_; /// Drawable. Game::GameObject* object_; }; class RayOctreeQuery { public: /// Construct with ray and query parameters. RayOctreeQuery(std::vector<RayQueryResult>& result, const Ray& ray, float maxDistance = INFINITY) : result_(result), ray_(ray), maxDistance_(maxDistance) {} RayOctreeQuery(const RayOctreeQuery& rhs) = delete; RayOctreeQuery& operator =(const RayOctreeQuery& rhs) = delete; /// Result vector reference. std::vector<RayQueryResult>& result_; /// Ray. Ray ray_; /// Maximum ray distance. float maxDistance_; }; }
true
cab794be792db567a619b19cd640138024b1cc08
C++
scaevola96/online-courses
/Hackerrank C++/STL/vectorerase.cpp
UTF-8
437
2.875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> int main() { int n; std::cin >> n; std::vector<int> vec(n); for(auto& i:vec){ std::cin>>i; } int x; int a,b; std::cin >> x; std::cin >> a >> b; vec.erase(vec.begin()+x-1); vec.erase(vec.begin()+a-1,vec.begin()+b-1); std:: cout <<vec.size() <<'\n'; for(auto& i:vec){ std::cout<<i<<" "; } return 0; }
true
35194dd794abbd7db2b12d32cc5bec8abf24c94c
C++
taowenyi/zhangziyu
/GetLeastNumbers/GetLeastNumbers/GetLeastNumbers.cpp
GB18030
955
3.171875
3
[]
no_license
// GetLeastNumbers.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include<set> #include<vector> #include<functional> using namespace std; vector<int> GetLeastNumbers(vector<int> input, int k) { multiset<int,greater<int>> LeastSet;//һݼset LeastSet.clear(); int length = input.size(); if (length <= 0 || k <= 0) return vector<int>(); vector<int>::const_iterator iter = input.begin(); for (;iter!=input.end();iter++) { if (LeastSet.size() < k) LeastSet.insert(*iter); else { multiset<int, greater<int>>::const_iterator iterGreatest = LeastSet.begin(); if (*iter < *(LeastSet.begin())) { LeastSet.erase(iterGreatest); LeastSet.insert(*iter); } } } return vector<int>(LeastSet.begin(), LeastSet.end()); } int _tmain(int argc, _TCHAR* argv[]) { vector<int> input = { 4, 5, 1, 6, 2, 7, 3, 8 }; int k = 4; vector<int> output = GetLeastNumbers(input, k); return 0; }
true
1c32f6a34ea3ce2854649af98331469c6af93243
C++
lordzizzy/leet_code
/04_daily_challenge/2021/06-june/week1/max_perf_of_team.cpp
UTF-8
3,966
3.265625
3
[]
no_license
// https://leetcode.com/problems/maximum-performance-of-a-team/ // Maximum Performance of a Team // You are given two integers n and k and two integer arrays speed and // efficiency both of length n. There are n engineers numbered from 1 to n. // speed[i] and efficiency[i] represent the speed and efficiency of the ith // engineer respectively. // Choose at most k different engineers out of the n engineers to form a team // with the maximum performance. // The performance of a team is the sum of their engineers' speeds multiplied // by the minimum efficiency among their engineers. // Return the maximum performance of this team. Since the answer can be a huge // number, return it modulo 109 + 7. // Example 1: // Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2 // Output: 60 // Explanation: // We have the maximum performance of the team by selecting engineer 2 (with // speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). // That is, performance = (10 + 5) * min(4, 7) = 60. // Example 2: // Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3 // Output: 68 // Explanation: // This is the same example as the first but k = 3. We can select engineer 1, // engineer 2 and engineer 5 to get the maximum performance of the team. That // is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68. // Example 3: // Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4 // Output: 72 // Constraints: // 1 <= <= k <= n <= 10⁵ // speed.length == n // efficiency.length == n // 1 <= speed[i] <= 10⁵ // 1 <= efficiency[i] <= 10⁸ #include "stdafx.h" #include <queue> #include <vector> using namespace std; using namespace leetcode::format; int maxPerformance_greedy_priorityQ(int const n, vector<int> const &speeds, vector<int> const &efficiencies, int const k) { vector<pair<int, int>> candidates(n); for (int i = 0; i < n; i++) { candidates[i] = {efficiencies[i], speeds[i]}; } sort(candidates.rbegin(), candidates.rend()); auto speed_sum = 0, perf = 0; priority_queue<int, vector<int>, greater<int>> min_heap; for (auto const &[eff, spd] : candidates) { min_heap.emplace(spd); speed_sum += spd; if (min_heap.size() > k) { speed_sum -= min_heap.top(); min_heap.pop(); } perf = max(perf, speed_sum * eff); } return perf % int(1e9 + 7); } void test_solution(int n, vector<int> const &speeds, vector<int> const &efficiencies, int k, int expected) { using SolutionFunc = std::function<int(int, vector<int> const &, vector<int> const &, int)>; auto test_impl = [](SolutionFunc func, string_view func_name, int n, vector<int> const &speeds, vector<int> const &efficiencies, int k, int expected) { auto const r = func(n, speeds, efficiencies, k); if (r == expected) { fmt::print(pass_color, "PASSED {} => Max performance of chosen {} of team with size {}, speeds: " "{} and efficiencies: {} is {}.\n", func_name, k, n, to_str(speeds), to_str(efficiencies), r); } else { fmt::print(fail_color, "FAILED {} => Max performance of chosen {} of team with size {}, speeds: " "{} and efficiencies: {} is {} but expected {}.\n", func_name, k, n, to_str(speeds), to_str(efficiencies), r, expected); } }; test_impl(maxPerformance_greedy_priorityQ, "maxPerformance_greedy_priorityQ", n, speeds, efficiencies, k, expected); } int main() { test_solution(6, {2, 10, 3, 1, 5, 8}, {5, 4, 3, 9, 7, 2}, 2, 60); test_solution(6, {2, 10, 3, 1, 5, 8}, {5, 4, 3, 9, 7, 2}, 3, 68); test_solution(6, {2, 10, 3, 1, 5, 8}, {5, 4, 3, 9, 7, 2}, 4, 72); return 0; }
true
0ebe0aac6506ed3533f949f10d974e91fa70081f
C++
AravindVasudev/datastructures-and-algorithms
/datastructures/linked-list/modular_node.cc
UTF-8
1,104
3.96875
4
[ "MIT" ]
permissive
#include <iostream> #include <vector> struct Node { int data; Node *next; }; Node* array_to_list(std::vector<int> arr) { Node *head = new Node; Node *ptr = head; int size = arr.size(); for (int i = 0; i < size; i++) { ptr->data = arr[i]; ptr->next = (i == size - 1 ? NULL : new Node); ptr = ptr->next; } return head; } std::string visualize(Node *head) { std::string visualized_list = ""; if (head == NULL) return ""; if (!head->next) return std::to_string(head->data); while (head) { visualized_list += std::to_string(head->data) + " -> "; head = head->next; } return visualized_list + "NULL"; } int modular_node(Node *head, int k) { Node *ptr; int i = 1; if (!head) return -1; while (head) { if (i++ % k == 0) ptr = head; head = head->next; } return ptr->data; } int main() { std::vector<int> arr = {2, 5, 6, 1, 9, 10, 45}; Node *list = array_to_list(arr); std::cout << visualize(list) << "\n" << modular_node(list, 4) << "\n"; return 0; }
true
1a98470b8f17206b29bf6db3620554091a024a7e
C++
Kotevode/Purple
/src/purple/include/purple/efdist.h
UTF-8
3,003
2.9375
3
[]
no_license
// // Created by Mark on 08.03.17. // #ifndef PURPLE_EFDIST_H #define PURPLE_EFDIST_H #include "hdist.h" #include <set> using namespace std; namespace Purple { template<class _info_iterator> bool strong_rule(_info_iterator begin, _info_iterator end, int min_node_index, int max_node_index, int &delta) { if (delta == 0) return false; for (_info_iterator min = begin; min < end; min++) { if (min->get_node_number() == max_node_index && min->get_weight() < delta) { min->set_node_number(min_node_index); delta = min->get_weight(); return true; } } return false; } template<class _info_iterator> bool weak_rule(_info_iterator begin, _info_iterator end, int min_node_index, int max_node_index, int &delta) { if (delta == 0) return false; for (_info_iterator min = begin; min < end; min++) for (_info_iterator max = begin; max < end; max++) { if (min->get_node_number() == min_node_index && max->get_node_number() == max_node_index && max->get_weight() - min->get_weight() < delta && max->get_weight() - min->get_weight() > 0) { min->set_node_number(max_node_index); max->set_node_number(min_node_index); delta = max->get_weight() - min->get_weight(); return true; } } return false; } template<class _info_iterator, class _info = typename iterator_traits<_info_iterator>::value_type> void ef_distribution(_info_iterator begin, _info_iterator end, size_t node_cnt) { h_distribution(begin, end, node_cnt); int node_load[node_cnt]; memset(node_load, 0, sizeof(int) * node_cnt); for_each(begin, end, [&](_info &t) { node_load[t.get_node_number()] += t.get_weight(); }); set<int> not_min; for (int i = 0; i < node_cnt; i++) not_min.insert(i); while (true) { if (not_min.size() == 1) return; auto min_and_max = minmax_element(not_min.begin(), not_min.end(), [&](int a, int b) -> bool { return node_load[a] < node_load[b]; }); int min_loaded_index = *(min_and_max.first); int max_loaded_index = *(min_and_max.second); int delta = node_load[max_loaded_index] - node_load[min_loaded_index]; if (strong_rule(begin, end, min_loaded_index, max_loaded_index, delta) || weak_rule(begin, end, min_loaded_index, max_loaded_index, delta)) { for (int i = 0; i < node_cnt; i++) not_min.insert(i); node_load[min_loaded_index] += delta; node_load[max_loaded_index] -= delta; } else { not_min.erase(min_loaded_index); } } } } #endif //PURPLE_EFDIST_H
true
4f9adac4f67d79d2181ebc3408bdeecbf07f50a5
C++
Bhaikko/data-structures
/Graphs/Prim.cpp
UTF-8
2,114
3.484375
3
[]
no_license
#include <iostream> #include <climits> int minVertex(int* weights, bool* isVisited, int vertices) { int minIndex = -1; for (int currentVertex = 0; currentVertex < vertices; currentVertex++) { if (!isVisited[currentVertex] && (minIndex == -1 || weights[currentVertex] < weights[minIndex])) { minIndex = currentVertex; } } return minIndex; } void prim(int** graph, int vertices) { bool* isVisited = new bool[vertices]; int* parents = new int[vertices]; int* weights = new int[vertices]; for(int i = 0; i < vertices; i++) { weights[i] = INT_MAX; isVisited[i] = false; } parents[0] = -1; weights[0] = 0; for (int currentVertex = 0; currentVertex < vertices - 1; currentVertex++) { int vertex = minVertex(weights, isVisited, vertices); isVisited[vertex] = true; for (int i = 0; i < vertices; i++) { if (graph[vertex][i] && !isVisited[i]) { if (graph[vertex][i] < weights[i]) { weights[i] = graph[vertex][i]; parents[i] = vertex; } } } } // Printing MST for (int i = 1; i < vertices; i++) { if (parents[i] < i) { std::cout << parents[i] << " " << i << " " << weights[i] << std::endl; } else { std::cout << i << " " << parents[i] << " " << weights[i] << std::endl; } } } int main() { int vertices, edges; std::cin >> vertices >> edges; int** graph = new int*[vertices]; for (int i = 0; i < vertices; i++) { graph[i] = new int[vertices]; for (int j = 0; j < vertices; j++) { graph[i][j] = 0; } } for (int i = 1; i <= edges; i++) { int e1, e2, weight; std::cin >> e1 >> e2 >> weight; graph[e1][e2] = weight; graph[e2][e1] = weight; } prim(graph, vertices); /* SAMPLE INPUT 6 8 0 1 2 0 2 4 1 2 1 1 3 7 2 4 3 3 4 2 3 5 1 4 5 5 */ }
true
24b87f774bedba27b517f2263aee63aa6a6363f1
C++
sric0880/web_extractor
/src/HtmlProcessor.cpp
UTF-8
1,062
2.578125
3
[]
no_license
/* * HtmlProcessor.cpp *html文档处理核心模块 *实现多线程 线程安全列队 * Created on: 2013-5-20 * Author: qiong */ #include "HtmlProcessor.h" HtmlProcessor::HtmlProcessor(Output* output, Template * temt): info_ext(output,temt),queue_html(), text_ext(280, 6),flag(false) { if (!NLPIR_Init(".", UTF8_CODE))//Data文件夹所在的路径,默认为GBK编码的分词 { printf("ICTCLAS INIT FAILED!\n"); } // NLPIR_ImportUserDict("position.txt"); // NLPIR_SaveTheUsrDic(); } HtmlProcessor::~HtmlProcessor() { //释放分词组件资源 NLPIR_Exit(); } void HtmlProcessor::addHtml(string html){ queue_html.push(html); } void HtmlProcessor::run(){ int i = 0; while(1){ if(flag&&queue_html.isEmpty()){ printf("html process over!\n"); break; } //从列队中取html string input; input = queue_html.front_pop(); //正文提取 input = text_ext.extract(input); info_ext.infoExtract(i,input);//提取结构化信息 并输出 ++i; } pthread_exit( NULL); } void HtmlProcessor::over(){ flag = true; }
true
f9bab6d1f922793472c9eb8297707f448c23c8c6
C++
muhammet-mucahit/My-CPlusPlus-Studies
/School KTU/Sinav Cozumleri/2010 - Final/3/Source.cpp
UTF-8
305
2.78125
3
[]
no_license
#include <iostream> #include "base.h" #include "derived.h" using namespace std; int main(){ Derived X, Y, *p = new Derived; X.Dizi_Al(); Y.Dizi_Al(); if (Y.Min() > X.Max()){ X.Ekle(Y.Min()); *p = X; } else{ Y.Ekle(X); *p = Y; } p->print(); cout << endl; Y.print(); cout << endl; }
true
ed318094df52e445e7c16ec84a1ff9065c169712
C++
YangZhongLou/LearningVulkan
/Src/Utils.cpp
UTF-8
4,967
2.671875
3
[]
no_license
#include "Utils.h" #include <iostream> namespace yzl { bool LoadVulkanLib(LIBRARY_TYPE & vulkanLibrary) { #if defined _WIN32 vulkanLibrary = LoadLibrary("vulkan-1.dll"); #elif defined __linux vulkanLibrary = dlopen("libvulkan.so.1", RTLD_NOW); #endif if (vulkanLibrary == nullptr) { std::cout << "Error, LoadVulkanLib" << std::endl; return false; } return true; } void UnloadVulkanLib(LIBRARY_TYPE & vulkanLibrary) { if (nullptr != vulkanLibrary) { #if defined _WIN32 FreeLibrary(vulkanLibrary); #elif defined __linux dlclose(vulkanLibrary); #endif vulkanLibrary = nullptr; } } bool LoadVulkanFunctions(LIBRARY_TYPE& vulkanLibrary) { #if defined _WIN32 #define LoadFunction GetProcAddress #elif defined __linux #define LoadFunction dlsym #endif #define EXPORTED_VULKAN_FUNCTION( name ) \ name = (PFN_##name)LoadFunction( vulkanLibrary, #name ); \ if( name == nullptr ) { \ std::cout << "Could not load exported Vulkan function named: " \ #name << std::endl; \ return false; \ } #include "Vulkan/ListOfVulkanFunctions.inl" return true; } bool LoadGlobalLevelFunctions() { #define GLOBAL_LEVEL_VULKAN_FUNCTION( name ) \ name = (PFN_##name)vkGetInstanceProcAddr( nullptr, #name ); \ if( name == nullptr ) { \ std::cout << "Could not load global level Vulkan function named: " \ #name << std::endl; \ return false; \ } #include "Vulkan/ListOfVulkanFunctions.inl" return true; } bool LoadInstanceLevelFunctions(VkInstance instance, std::vector<char const *> const & enabledExtensions) { #define INSTANCE_LEVEL_VULKAN_FUNCTION( name ) \ name = (PFN_##name)vkGetInstanceProcAddr( instance, #name ); \ if( name == nullptr ) { \ std::cout << "Could not load instance-level Vulkan function named: " \ #name << std::endl; \ return false; \ } // Load instance-level functions from enabled extensions #define INSTANCE_LEVEL_VULKAN_FUNCTION_FROM_EXTENSION( name, extension ) \ for( auto & enabledExtension : enabledExtensions ) { \ if( std::string( enabledExtension ) == std::string( extension ) ) { \ name = (PFN_##name)vkGetInstanceProcAddr( instance, #name ); \ if( name == nullptr ) { \ std::cout << "Could not load instance-level Vulkan function named: " \ #name << std::endl; \ return false; \ } \ } \ } #include "Vulkan/ListOfVulkanFunctions.inl" return true; } bool LoadDeviceLevelFunctions(VkDevice logicalDevice, std::vector<char const *> const & enabledExtensions) { #define DEVICE_LEVEL_VULKAN_FUNCTION( name ) \ name = (PFN_##name)vkGetDeviceProcAddr( logicalDevice, #name ); \ if( name == nullptr ) { \ std::cout << "Could not load device-level Vulkan function named: " \ #name << std::endl; \ return false; \ } // Load device-level functions from enabled extensions #define DEVICE_LEVEL_VULKAN_FUNCTION_FROM_EXTENSION( name, extension ) \ for( auto & enabled_extension : enabledExtensions ) { \ if( std::string( enabled_extension ) == std::string( extension ) ) { \ name = (PFN_##name)vkGetDeviceProcAddr( logicalDevice, #name ); \ if( name == nullptr ) { \ std::cout << "Could not load device-level Vulkan function named: " \ #name << std::endl; \ return false; \ } \ } \ } #include "Vulkan/ListOfVulkanFunctions.inl" return true; } }
true
1e8f21f731d4c9dd8432005902fd8583454e12de
C++
j3lew/BME-261-Chemotherapy-Drug-Box
/combine/combine.ino
UTF-8
5,002
3.40625
3
[]
no_license
// include the library for LCD #include <math.h> #include <LiquidCrystal.h> // Variables String data = ""; String morning, after, evening, bed, patient, age, treatment = ""; String infoForDay[7]; unsigned int time; // Time variables unsigned long timeNow = 0; unsigned long timeLast = 0; int seconds = 0; int day = 1; // initial day that is incremented by 1 for every 30 seconds ("day") const int rs = 8, en = 9, d4 = 4, d5 = 5, d6 = 6, d7 = 7; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); void setup() { Serial.begin(9600); //initialize serial COM at 9600 baudrate // update current time currentTime(); //find drugs in day getData(day); // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Display sentence on lcd // String test = "test"; // int str_len = test.length() + 1; // char test1[str_len]; // test.toCharArray(test1, str_len); // lcd.print(test1); lcd.print("My name is Bill!"); lcd.setCursor(0, 1); lcd.print("I will help you take your pills!"); lcd.display(); delay(1000); // scroll to the right for (int positionCounter = 0; positionCounter < 16; positionCounter++) { // scroll one position left: lcd.scrollDisplayLeft(); // wait a bit: delay(500); } delay(1000); // call instructionLCD instructionLCD(); } void loop() { } void currentTime(){ //TIMING/ALARM SYSTEM IN LOOP timeNow = millis()/1000; seconds = timeNow - timeLast; } //TIMING/ALARM SYSTEM void updateDay() { timeLast = timeNow; //switch to reset the times, as it is the next day if(day < 28){ day = day + 1; } else{ day = 1; setup(); } getData(day); instructionLCD(); } void getData(int day) { //get drugs and personal info of the day String dayString = String(day); Serial.println(day); for ( int i = 0; i < 7; i++) { infoForDay[i] = Serial.readStringUntil(';'); } // Test // for( int c = 0; c < 7; c++){ // Serial.println(patient[c]); // } patient = infoForDay[0]; age = infoForDay[1]; treatment = infoForDay[2]; morning = infoForDay[3]; after = infoForDay[4]; evening = infoForDay[5]; bed = infoForDay[6]; } void instructionLCD() { lcd.clear(); // converting string to char array int str_len = patient.length() + 1; char patientLCD[str_len]; patient.toCharArray(patientLCD, str_len); lcd.setCursor(0, 0); lcd.print("Day" + String(day) + ":Hi " + String(patientLCD) + "!"); lcd.setCursor(0, 1); lcd.print("Press R-M,U-A,L-E,D-B,S-I"); lcd.display(); // scroll right left right scroll(str_len); } void morningLCD() { lcd.clear(); // converting string to char array int str_len = morning.length() + 1; char morningDisplay[str_len]; morning.toCharArray(morningDisplay, str_len); lcd.setCursor(0, 0); lcd.print(String(morningDisplay)); lcd.setCursor(0, 1); lcd.print("Press R-M,U-A,L-E,D-B,S-I"); lcd.display(); // scroll right left right scroll(str_len); } void afterLCD() { lcd.clear(); // converting string to char array int str_len = after.length() + 1; char afterDisplay[str_len]; after.toCharArray(afterDisplay, str_len); lcd.setCursor(0, 0); lcd.print(after); lcd.setCursor(0, 1); lcd.print("Press R-M,U-A,L-E,D-B,S-I"); lcd.display(); // scroll right left right scroll(str_len); } void eveLCD() { lcd.clear(); // converting string to char array int str_len = evening.length() + 1; char eveningDisplay[str_len]; evening.toCharArray(eveningDisplay, str_len); lcd.setCursor(0, 0); lcd.print(evening); lcd.setCursor(0, 1); lcd.print("Press R-M,U-A,L-E,D-B,S-I"); lcd.display(); // scroll right left right scroll(str_len); } void bedLCD() { lcd.clear(); // converting string to char array int str_len = bed.length() + 1; char bedDisplay[str_len]; bed.toCharArray(bedDisplay, str_len); lcd.setCursor(0, 0); lcd.print(bed); lcd.setCursor(0, 1); lcd.print("Press R-M,U-A,L-E,D-B,S-I"); lcd.display(); // scroll right left right scroll(str_len); } void scroll(int str_len){ delay(1000); int minLength = min(str_len, 24); boolean infiniteLoop = true; while(infiniteLoop){ // loop to scroll to the right // scroll to the right for (int positionCounter = 0; positionCounter < minLength; positionCounter++) { delay(200); // scroll one position left: lcd.scrollDisplayLeft(); // updating current time and update day currentTime(); if(seconds == 140){ updateDay(); } // check for button button(); // wait a bit: } lcd.setCursor(0, 0); } } void button(){ // reading the button int button = analogRead(0); if (button < 50) { // right button morningLCD(); } else if(button < 195){ // up button afterLCD(); } else if(button < 380){ // down button bedLCD(); } else if(button < 555){ // left button eveLCD(); } else if(button < 790) { // select button instructionLCD(); } }
true
ea9479e8c008f4c4a32a4f43a94b0c604020301c
C++
math132d/APshot
/Arduino/SerialTest/SerialTest.ino
UTF-8
1,462
3.078125
3
[]
no_license
char input; int num = 0, cng = 0; int minimum = 0, maximum = 100, increment = 20; void setup() { // put your setup code here, to run once: // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); // open serial port Serial.begin(9600); // //loop to wait for confirmation from the computer // while (true) // { // digitalWrite(LED_BUILTIN, HIGH); // delay(100); // if (Serial.available()) // { // input = Serial.read(); // break; // } // digitalWrite(LED_BUILTIN, LOW); // delay(100); // } // digitalWrite(LED_BUILTIN, HIGH); } void loop() { // put your main code here, to run repeatedly: if (Serial.available()) { String message = ""; while (Serial.available()) { input = Serial.read(); message += input; } if (message == "R" || message == "r") { reset(); } else { Serial.print(message); Serial.print(" "); Serial.println(""); } } numGen(); Serial.print("N: "); Serial.print(num); Serial.print(" "); Serial.print("C: "); Serial.print(cng); Serial.print(" "); Serial.println(""); delay(100); } //this is just a number generator for testing purposes void numGen() { int newNum = random(num - (increment / 2), num + (increment / 2)); newNum = constrain(newNum, minimum, maximum); cng = newNum - num; num = newNum; } void reset() { num = 0; cng = 0; }
true
dbf25a03d5d46ffce079ad99f1a4ab9dd5bc0bb7
C++
phg1024/UVa
/10961-Factstone-Benchmark/main.cpp
UTF-8
736
2.90625
3
[]
no_license
#include <cstdlib> #include <iostream> #include <vector> #include <string> #include <cmath> using namespace std; // compare 2^(2^x) with n! // boils down to compare 2^x with sum_{i=1}^n log_2(i) int main() { double logsum = 0; // all the benchmark scores vector<int> pos(23); int i=1, w=2, cutoff_w = 4; while( true ) { logsum += log2(double(i)); if( logsum >= cutoff_w ){ pos[w] = i+1; ++w; cutoff_w *= 2; } if( w>22 ) break; ++i; }; int year; while( true ) { scanf("%d", &year); if( year == 0 ) break; year -= 1960; year /= 10; // the power int p = year + 2; printf("%d\n", pos[p]-2); } return 0; }
true
3fb0ac42780ccb614cb9472b8adac662a9e096ed
C++
fbocharov/au-grafon
/src/glpp/texture.h
UTF-8
644
2.78125
3
[]
no_license
#ifndef GLPP_TEXTURE_H #define GLPP_TEXTURE_H #include <string> #include <vector> #include <memory> #include <GL/glew.h> namespace glpp { class Texture; using TexturePtr = std::shared_ptr<Texture>; class Texture { public: explicit Texture(GLuint texture); ~Texture(); Texture(Texture const &) = delete; Texture & operator=(Texture const &) = delete; static TexturePtr load1D(std::string const & path); static TexturePtr load2D(std::string const & path); static TexturePtr loadCubemap(std::vector<std::string> const & faces); operator GLuint() const; private: GLuint m_handle; }; } // namespace glpp #endif // GLPP_TEXTURE_H
true
76015cc8926ab97f17c202e8ed85305e445016e8
C++
JUSTYNTOWLER/PERSONAL-PROJECT
/2020-9-27/三角函数.cpp
GB18030
6,789
2.984375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cmath> #include "Ǻ.h" #include "ȫָ.h" using namespace std; Calc_SC::Calc_SC() {}; void Calc_SC::checkSC() { if (s) { in[0] = '\0'; int d = 0; strcpy(in, INPUT.c_str()); for (int i = 0; i < INPUT.size()-2; i++) { if (INPUT.substr(i, 3) == "sin") { d = 0; if (i == INPUT.size() - 3) { cout << "ʽϹ淶" << endl; s = 0; return; //sinΪַĽβ } for (int x = i + 3; x < INPUT.size(); x++) { if ((int)in[x] <= 57 && (int)in[x] >= 48) //0-9 { continue; } else if ((in[x] <= 'z' && in[x] >= 'a') || (in[x] >= 'A' && in[x] <= 'Z')) { cout << "ʽϹ淶" << endl; s = 0; return; } else { if (x == i + 3) { cout << "ʽϹ淶" << endl; s = 0; return; //sinûֱֵ'+''('ȷǷַ } else if (in[x] == '.') { d++; if (x == INPUT.size() - 1) { cout << "ʽϹ淶" << endl; s = 0; return; //С㲻Ϊһλ } else if (d == 1) { continue; } else { cout << "ʽϹ淶" << endl; s = 0; return; //ܺжС } } else { break; } } } } } in[0] = '\0'; // sinĺϷ for (int i = 0; i < INPUT.size() - 2; i++) { if (INPUT.substr(i, 3) == "cos") { d = 0; if (i == INPUT.size() - 3) { cout << "ʽϹ淶" << endl; s = 0; return; //cosΪַĽβ } for (int x = i + 3; x < INPUT.size(); x++) { if ((int)in[x] <= 57 && (int)in[x] >= 48) //0-9 { continue; } else if ((in[x] <= 'z' && in[x] >= 'a') || (in[x] >= 'A' && in[x] <= 'Z')) { cout << "ʽϹ淶" << endl; s = 0; return; } else { if (x == i + 3) { cout << "ʽϹ淶" << endl; s = 0; return; //cosûֱֵ'+''('ȷǷַ } else if (in[x] == '.') { d++; if (x == INPUT.size() - 1) { cout << "ʽϹ淶" << endl; s = 0; return; //С㲻Ϊһλ } else if (d == 1) { continue; } else { cout << "ʽϹ淶" << endl; s = 0; return; //ܺжС } } else { break; } } } } } in[0] = '\0'; // cosĺϷ for (int i = 0; i < INPUT.size() - 2; i++) { if (INPUT.substr(i, 3) == "tan") { d = 0; if (i == INPUT.size() - 3) { cout << "ʽϹ淶" << endl; s = 0; return; //tanΪַĽβ } for (int x = i + 3; x < INPUT.size(); x++) { if ((int)in[x] <= 57 && (int)in[x] >= 48) //0-9 { continue; } else if ((in[x] <= 'z' && in[x] >= 'a') || (in[x] >= 'A' && in[x] <= 'Z')) { cout << "ʽϹ淶" << endl; s = 0; return; } else { if (x == i + 3) { cout << "ʽϹ淶" << endl; s = 0; return; //tanûֱֵ'+''('ȷǷַ } else if (in[x] == '.') { d++; if (x == INPUT.size() - 1) { cout << "ʽϹ淶" << endl; s = 0; return; //С㲻Ϊһλ } else if (d == 1) { continue; } else { cout << "ʽϹ淶" << endl; s = 0; return; //ܺжС } } else { break; } } } } } in[0] = '\0'; // tanĺϷ } else return; } void Calc_SC::calcSC() { if (s) { const string SIN = "sin"; const string COS = "cos"; const string TAN = "tan"; int pos; int q =0; double v = 0 , result ; string SC; char input[100]; pos = INPUT.find(SIN); //sin int p = pos + 3; while (pos != -1) { for (int x = pos + 3; x < INPUT.size(); x++) { if (((int)in[x] <= 57 && (int)in[x] >= 48) || in[x] == '.') //0-9С { if (x == INPUT.size() - 1) { q = x - p + 1; break; } else continue; } else { q = x - p; break; } } v = 0; input[0] = '\0'; SC = INPUT.substr(p,q); convertFromString(v, SC); result = sin(v); sprintf(input, "%.20lf", result); INPUT.replace(pos, q+3, input); pos = INPUT.find(SIN); } pos = INPUT.find(COS); //cos while (pos != -1) { for (int x = pos + 3; x < INPUT.size(); x++) { if (((int)in[x] <= 57 && (int)in[x] >= 48) || in[x] == '.') //0-9С { if (x == INPUT.size() - 1) { q = x - p + 1; break; } else continue; } else { q = x - p; break; } } v = 0; input[0] = '\0'; SC = INPUT.substr(p, q); convertFromString(v, SC); result = cos(v); sprintf(input, "%.20lf", result); INPUT.replace(pos, q + 3, input); pos = INPUT.find(SIN); } pos = INPUT.find(TAN); //tan while (pos != -1) { for (int x = pos + 3; x < INPUT.size(); x++) { if (((int)in[x] <= 57 && (int)in[x] >= 48) || in[x] == '.') //0-9С { if (x == INPUT.size() - 1) { q = x - p + 1; break; } else continue; } else { q = x - p; break; } } v = 0; input[0] = '\0'; SC = INPUT.substr(p, q); convertFromString(v, SC); if (cos(v) == 0) { cout << "ʽϹ淶" << endl; s = 0; return; } else result = tan(v); sprintf(input, "%.20lf", result); INPUT.replace(pos, q + 3, input); pos = INPUT.find(SIN); } } }
true
dca673a298f24b594a04e390a90c4167921bf1be
C++
esdream/AIEngineer
/julyDSA/Graph/leetcode_207_Course_Schedule.cpp
UTF-8
1,840
3.734375
4
[]
no_license
/* 使用邻接表结构实现 */ #include <iostream> #include <vector> #include <map> #include <queue> using namespace std; class Solution { public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { if (prerequisites.empty()) return true; v_ = numCourses; int edgesNum = prerequisites.size(); // 初始化邻接表 adjTable_ = vector<vector<int>>(numCourses); for (int i = 0; i < numCourses; i++) { vertexInDeg_[i] = 0; } for (int j = 0; j < edgesNum; j++) { addEdge(prerequisites[j]); } for(int i = 0; i < numCourses; i++) if (vertexInDeg_[i] == 0) zeroDeg_.push(i); int count = 0; while(!zeroDeg_.empty()) { int zeroVertex = zeroDeg_.front(); zeroDeg_.pop(); ++count; for (int w = 0; w < adjTable_[zeroVertex].size(); w++) { if ((--(vertexInDeg_[adjTable_[zeroVertex][w]])) == 0) { zeroDeg_.push(adjTable_[zeroVertex][w]); } } } if(count < numCourses) return false; else return true; } void addEdge(pair<int, int>& prerequisty) { adjTable_[prerequisty.second].push_back(prerequisty.first); vertexInDeg_[prerequisty.first] += 1; } private: vector<vector<int>> adjTable_; map<int, int> vertexInDeg_; queue<int> zeroDeg_; int v_; }; int main() { Solution s; vector<pair<int, int>> edges; edges.push_back(std::make_pair(1, 0)); edges.push_back(std::make_pair(2, 1)); bool isFinish = s.canFinish(3, edges); cout << isFinish << endl; return 0; }
true
5fd3a415364eee0e17986c11bb97046a81367976
C++
IvanBacic/LV1rgrv
/RG_LV1/RVL3DTools.h
UTF-8
23,413
2.921875
3
[]
no_license
//V = [x y z]' #define RVLSET3VECTOR(V, x, y, z) {V[0] = x; V[1] = y; V[2] = z;} // Tgt = Src(3x1) #define RVLCOPY3VECTOR(Src, Tgt) Tgt[0] = Src[0]; Tgt[1] = Src[1]; Tgt[2] = Src[2]; // Tgt = Src(3x3) #define RVLCOPYMX3X3(Src, Tgt) Tgt[0] = Src[0]; Tgt[1] = Src[1]; Tgt[2] = Src[2]; Tgt[3] = Src[3]; Tgt[4] = Src[4]; Tgt[5] = Src[5]; Tgt[6] = Src[6]; Tgt[7] = Src[7]; Tgt[8] = Src[8]; // Tgt = Src(3x3)' #define RVLCOPYMX3X3T(Src, Tgt) Tgt[0] = Src[0]; Tgt[1] = Src[3]; Tgt[2] = Src[6]; Tgt[3] = Src[1]; Tgt[4] = Src[4]; Tgt[5] = Src[7]; Tgt[6] = Src[2]; Tgt[7] = Src[5]; Tgt[8] = Src[8]; // Tgt = -Src(3x1) #define RVLNEGVECT3(Src, Tgt) Tgt[0] = -Src[0]; Tgt[1] = -Src[1]; Tgt[2] = -Src[2]; // y = i-th column of X(3x3) #define RVLCOPYCOLMX3X3(X, i, y) y[0] = X[i]; y[1] = X[3+i]; y[2] = X[6+i]; // i-th column of Y(3x3) = x #define RVLCOPYTOCOL3(x, i, Y) Y[i] = x[0]; Y[3+i] = x[1]; Y[6+i] = x[2]; // Z = X(3x3) + Y(3x3) #define RVLSUMMX3X3(X, Y, Z) Z[0] = X[0] + Y[0]; Z[1] = X[1] + Y[1]; Z[2] = X[2] + Y[2]; Z[3] = X[3] + Y[3]; Z[4] = X[4] + Y[4]; Z[5] = X[5] + Y[5]; Z[6] = X[6] + Y[6]; Z[7] = X[7] + Y[7]; Z[8] = X[8] + Y[8]; // Z = X(3x3) - Y(3x3) #define RVLDIFMX3X3(X, Y, Z) Z[0] = X[0] - Y[0]; Z[1] = X[1] - Y[1]; Z[2] = X[2] - Y[2]; Z[3] = X[3] - Y[3]; Z[4] = X[4] - Y[4]; Z[5] = X[5] - Y[5]; Z[6] = X[6] - Y[6]; Z[7] = X[7] - Y[7]; Z[8] = X[8] - Y[8]; // Z = X(3x3) + Y(3x3)' (only diagonal + upper triangle are computed) #define RVLSUMMX3X3T2UT(X, Y, Z) Z[0] = X[0] + Y[0]; Z[1] = X[1] + Y[3]; Z[2] = X[2] + Y[6]; Z[4] = X[4] + Y[4]; Z[5] = X[5] + Y[7]; Z[8] = X[8] + Y[8]; // Z = X(3x3) + Y(3x3) (only diagonal + upper triangle are computed) #define RVLSUMMX3X3UT(X, Y, Z) Z[0] = X[0] + Y[0]; Z[1] = X[1] + Y[1]; Z[2] = X[2] + Y[2]; Z[4] = X[4] + Y[4]; Z[5] = X[5] + Y[5]; Z[8] = X[8] + Y[8]; // X = 0(3x1) #define RVLNULL3VECTOR(X) X[0] = X[1] = X[2] = 0.0; // X = 0(3x3) #define RVLNULLMX3X3(X) X[0] = X[1] = X[2] = X[3] = X[4] = X[5] = X[6] = X[7] = X[8] = 0.0; // X = I(3x3) #define RVLUNITMX3(X) X[0] = X[4] = X[8] = 1.0; X[1] = X[2] = X[3] = X[5] = X[6] = X[7] = 0.0; // X = diag(x) #define RVL3VECTORTODIAGMX(x,X) X[0] = x[0]; X[4] = x[1]; X[8] = x[2]; X[1] = X[2] = X[3] = X[5] = X[6] = X[7] = 0.0; // X = diag([d1 d2 d3]') #define RVLDIAGMX3(d1, d2, d3, X) X[0] = d1; X[4] = d2; X[8] = d3; X[1] = X[2] = X[3] = X[5] = X[6] = X[7] = 0.0; // element in i-th row and j-th column of matrix Mx with nCol columns #define RVLMXEL(Mx, nCols, i, j) Mx[nCols * i + j] // Tgt = Src1(3x1) + Src2(3x1) #define RVLSUM3VECTORS(Src1, Src2, Tgt) Tgt[0] = Src1[0] + Src2[0]; Tgt[1] = Src1[1] + Src2[1]; Tgt[2] = Src1[2] + Src2[2]; // Tgt = Src1(3x1) - Src2(3x1) #define RVLDIF3VECTORS(Src1, Src2, Tgt) Tgt[0] = Src1[0] - Src2[0]; Tgt[1] = Src1[1] - Src2[1]; Tgt[2] = Src1[2] - Src2[2]; // Tgt = a * Src(3x1) #define RVLSCALE3VECTOR(Src, a, Tgt) Tgt[0] = a * Src[0]; Tgt[1] = a * Src[1]; Tgt[2] = a * Src[2]; // Tgt = Src(3x1) / a #define RVLSCALE3VECTOR2(Src, a, Tgt) Tgt[0] = Src[0] / a; Tgt[1] = Src[1] / a; Tgt[2] = Src[2] / a; // Tgt = Src(3x3) * a #define RVLSCALEMX3X3(Src, a, Tgt)\ {\ Tgt[0] = a * Src[0]; Tgt[1] = a * Src[1]; Tgt[2] = a * Src[2]; \ Tgt[3] = a * Src[3]; Tgt[4] = a * Src[4]; Tgt[5] = a * Src[5]; \ Tgt[6] = a * Src[6]; Tgt[7] = a * Src[7]; Tgt[8] = a * Src[8]; \ } // Tgt = Src(3x3) / a #define RVLSCALEMX3X32(Src, a, Tgt)\ {\ Tgt[0] = Src[0] / a; Tgt[1] = Src[1] / a; Tgt[2] = Src[2] / a; \ Tgt[3] = Src[3] / a; Tgt[4] = Src[4] / a; Tgt[5] = Src[5] / a; \ Tgt[6] = Src[6] / a; Tgt[7] = Src[7] / a; Tgt[8] = Src[8] / a; \ } // TgtCol = a * SrcCol, where SrcCol and TgtCol are the i-th column of 3x3 matrices Src and Tgt respectively #define RVLSCALECOL3(Src, i, a, Tgt) Tgt[i] = a * Src[i]; Tgt[i+3] = a * Src[i+3]; Tgt[i+6] = a * Src[i+6]; // dot product of i-th row of A(3x3) and j-th column of B(3x3) #define RVLMULROWCOL3(A,B,i,j) (A[3*i+0]*B[3*0+j] + A[3*i+1]*B[3*1+j] + A[3*i+2]*B[3*2+j]) // dot product of i-th row of A(3x3) and j-th row of B(3x3) #define RVLMULROWROW3(A,B,i,j) (A[3*i+0]*B[3*j+0] + A[3*i+1]*B[3*j+1] + A[3*i+2]*B[3*j+2]) // dot product of i-th column of A(3x3) and j-th column of B(3x3) #define RVLMULCOLCOL3(A,B,i,j) (A[3*0+i]*B[3*0+j] + A[3*1+i]*B[3*1+j] + A[3*2+i]*B[3*2+j]) // y = A(3x3) * x(3x1) #define RVLMULMX3X3VECT(A, x, y) y[0] = A[0]*x[0] + A[1]*x[1] + A[2]*x[2]; y[1] = A[3]*x[0] + A[4]*x[1] + A[5]*x[2]; y[2] = A[6]*x[0] + A[7]*x[1] + A[8]*x[2]; // y = A(3x3)' * x(3x1) #define RVLMULMX3X3TVECT(A, x, y) y[0] = A[0]*x[0] + A[3]*x[1] + A[6]*x[2]; y[1] = A[1]*x[0] + A[4]*x[1] + A[7]*x[2]; y[2] = A[2]*x[0] + A[5]*x[1] + A[8]*x[2]; // invt = -R(3x3)' * t(3x1) #define RVLINVTRANSL(R, t, invt) invt[0] = -R[0]*t[0] - R[3]*t[1] - R[6]*t[2]; invt[1] = -R[1]*t[0] - R[4]*t[1] - R[7]*t[2]; invt[2] = -R[2]*t[0] - R[5]*t[1] - R[8]*t[2]; // y = A(3x3) * x(3x1), where A is a simetric matrix with only diagonal + upper triangle defined #define RVLMULCOV3VECT(A, x, y) y[0] = A[0]*x[0] + A[1]*x[1] + A[2]*x[2]; y[1] = A[1]*x[0] + A[4]*x[1] + A[5]*x[2]; y[2] = A[2]*x[0] + A[5]*x[1] + A[8]*x[2]; // y = min(x(3x1)) #define RVL3DVECTORMIN(x, y) {if(x[0] <= x[1]) {if(x[0] <= x[2]) y = x[0]; else y = x[2];} else {if(x[1] <= x[2]) y = x[1]; else y = x[2];}} // y = A(3x3) * j-th column of B(3x3) #define RVLMULMXCOL3(A,B,j,y) y[0] = A[0] * B[j] + A[1] * B[3+j] + A[2] * B[6+j]; y[1] = A[3] * B[j] + A[4] * B[3+j] + A[5] * B[6+j]; y[2] = A[6] * B[j] + A[7] * B[3+j] + A[8] * B[6+j]; // C = A(3x3)*B(3x3) #define RVLMXMUL3X3(A,B,C)\ {\ RVLMXEL(C, 3, 0, 0) = RVLMULROWCOL3(A,B,0,0);\ RVLMXEL(C, 3, 0, 1) = RVLMULROWCOL3(A,B,0,1);\ RVLMXEL(C, 3, 0, 2) = RVLMULROWCOL3(A,B,0,2);\ RVLMXEL(C, 3, 1, 0) = RVLMULROWCOL3(A,B,1,0);\ RVLMXEL(C, 3, 1, 1) = RVLMULROWCOL3(A,B,1,1);\ RVLMXEL(C, 3, 1, 2) = RVLMULROWCOL3(A,B,1,2);\ RVLMXEL(C, 3, 2, 0) = RVLMULROWCOL3(A,B,2,0);\ RVLMXEL(C, 3, 2, 1) = RVLMULROWCOL3(A,B,2,1);\ RVLMXEL(C, 3, 2, 2) = RVLMULROWCOL3(A,B,2,2);\ } // C = A(3x3)*B'(3x3) #define RVLMXMUL3X3T2(A,B,C)\ {\ RVLMXEL(C, 3, 0, 0) = RVLMULROWROW3(A,B,0,0);\ RVLMXEL(C, 3, 0, 1) = RVLMULROWROW3(A,B,0,1);\ RVLMXEL(C, 3, 0, 2) = RVLMULROWROW3(A,B,0,2);\ RVLMXEL(C, 3, 1, 0) = RVLMULROWROW3(A,B,1,0);\ RVLMXEL(C, 3, 1, 1) = RVLMULROWROW3(A,B,1,1);\ RVLMXEL(C, 3, 1, 2) = RVLMULROWROW3(A,B,1,2);\ RVLMXEL(C, 3, 2, 0) = RVLMULROWROW3(A,B,2,0);\ RVLMXEL(C, 3, 2, 1) = RVLMULROWROW3(A,B,2,1);\ RVLMXEL(C, 3, 2, 2) = RVLMULROWROW3(A,B,2,2);\ } // C = A'(3x3)*B(3x3) #define RVLMXMUL3X3T1(A,B,C)\ {\ RVLMXEL(C, 3, 0, 0) = RVLMULCOLCOL3(A,B,0,0);\ RVLMXEL(C, 3, 0, 1) = RVLMULCOLCOL3(A,B,0,1);\ RVLMXEL(C, 3, 0, 2) = RVLMULCOLCOL3(A,B,0,2);\ RVLMXEL(C, 3, 1, 0) = RVLMULCOLCOL3(A,B,1,0);\ RVLMXEL(C, 3, 1, 1) = RVLMULCOLCOL3(A,B,1,1);\ RVLMXEL(C, 3, 1, 2) = RVLMULCOLCOL3(A,B,1,2);\ RVLMXEL(C, 3, 2, 0) = RVLMULCOLCOL3(A,B,2,0);\ RVLMXEL(C, 3, 2, 1) = RVLMULCOLCOL3(A,B,2,1);\ RVLMXEL(C, 3, 2, 2) = RVLMULCOLCOL3(A,B,2,2);\ } // Y = C(3x3)*J(3x3)' (C is simmetric) #define RVLMULCOV3MX3X3T(C, J, Y)\ {\ RVLMXEL(Y, 3, 0, 0) = C[0]*J[0] + C[1]*J[1] + C[2]*J[2];\ RVLMXEL(Y, 3, 0, 1) = C[0]*J[3] + C[1]*J[4] + C[2]*J[5];\ RVLMXEL(Y, 3, 0, 2) = C[0]*J[6] + C[1]*J[7] + C[2]*J[8];\ RVLMXEL(Y, 3, 1, 0) = C[1]*J[0] + C[4]*J[1] + C[5]*J[2];\ RVLMXEL(Y, 3, 1, 1) = C[1]*J[3] + C[4]*J[4] + C[5]*J[5];\ RVLMXEL(Y, 3, 1, 2) = C[1]*J[6] + C[4]*J[7] + C[5]*J[8];\ RVLMXEL(Y, 3, 2, 0) = C[2]*J[0] + C[5]*J[1] + C[8]*J[2];\ RVLMXEL(Y, 3, 2, 1) = C[2]*J[3] + C[5]*J[4] + C[8]*J[5];\ RVLMXEL(Y, 3, 2, 2) = C[2]*J[6] + C[5]*J[7] + C[8]*J[8];\ } #define RVLCOMPLETESIMMX3(A)\ {\ A[3*1+0] = A[3*0+1];\ A[3*2+0] = A[3*0+2];\ A[3*2+1] = A[3*1+2];\ } // Y = A(3x3)*B(3x3) (only diagonal + upper triangle are computed) #define RVLMULMX3X3UT(A, B, Y)\ {\ Y[3*0+0] = A[3*0+0] * B[3*0+0] + A[3*0+1] * B[3*1+0] + A[3*0+2] * B[3*2+0];\ Y[3*0+1] = A[3*1+0] * B[3*0+0] + A[3*1+1] * B[3*1+0] + A[3*1+2] * B[3*2+0];\ Y[3*0+2] = A[3*2+0] * B[3*0+0] + A[3*2+1] * B[3*1+0] + A[3*2+2] * B[3*2+0];\ Y[3*1+1] = A[3*1+0] * B[3*0+1] + A[3*1+1] * B[3*1+1] + A[3*1+2] * B[3*2+1];\ Y[3*1+2] = A[3*2+0] * B[3*0+1] + A[3*2+1] * B[3*1+1] + A[3*2+2] * B[3*2+1];\ Y[3*2+2] = A[3*2+0] * B[3*0+2] + A[3*2+1] * B[3*1+2] + A[3*2+2] * B[3*2+2];\ } // COut = J(3x3)*C(3x3)*J(3x3)' (C is simmetric; only diagonal + upper triangle are computed) #define RVLCOV3DTRANSF(CIn, J, COut, Tmp)\ {\ RVLMULCOV3MX3X3T(CIn, J, Tmp)\ RVLMULMX3X3UT(J, Tmp, COut)\ } // x(3x1)'*y(3x1) #define RVLDOTPRODUCT3(x, y) (x[0]*y[0]+x[1]*y[1]+x[2]*y[2]) #define RVLDOTPRODUCT3_64(x, y) ((int64)(x[0])*(int64)(y[0])+(int64)(x[1])*(int64)(y[1])+(int64)(x[2])*(int64)(y[2])) // z = x(3x1) x y(3x1) #define RVLCROSSPRODUCT3(x, y, z) z[0] = x[1] * y[2] - x[2] * y[1];z[1] = x[2] * y[0] - x[0] * y[2];z[2] = x[0] * y[1] - x[1] * y[0]; // normalize vector x(3x1) #define RVLNORM3(x, len) {len = sqrt(RVLDOTPRODUCT3(x, x)); RVLSCALE3VECTOR2(x, len, x);} #define RVLSKEW(x, A)\ {\ A[0 * 3 + 0] = 0.0;\ A[0 * 3 + 1] = -x[2];\ A[0 * 3 + 2] = x[1];\ A[1 * 3 + 0] = x[2];\ A[1 * 3 + 1] = 0.0;\ A[1 * 3 + 2] = -x[0];\ A[2 * 3 + 0] = -x[1];\ A[2 * 3 + 1] = x[0];\ A[2 * 3 + 2] = 0.0;\ } // A = x(3x1) * y(3x1)' #define RVLMULVECT3VECT3T(x, y, A)\ {\ A[3*0+0] = x[0] * y[0]; A[3*0+1] = x[0] * y[1]; A[3*0+2] = x[0] * y[2];\ A[3*1+0] = x[1] * y[0]; A[3*1+1] = x[1] * y[1]; A[3*1+2] = x[1] * y[2];\ A[3*2+0] = x[2] * y[0]; A[3*2+1] = x[2] * y[1]; A[3*2+2] = x[2] * y[2];\ } // x(3x1) * j-th column of A(3x3) #define RVLMULVECTORCOL3(x, A, j) (x[0]*A[3*0+j]+x[1]*A[3*1+j]+x[2]*A[3*2+j]) #define RVLCOVMX3BBVOLUME(C) (C[3*0+1]*(2.0*C[3*0+2]*C[3*1+2] - C[3*2+2]*C[3*0+1]) - C[3*1+1]*C[3*0+2]*C[3*0+2] + C[3*0+0]*(C[3*1+1]*C[3*2+2] - C[3*1+2]*C[3*1+2])) // invC = inv(C) (C is simmetric; only diagonal + upper triangle are computed) #define RVLINVCOV3(C, invC, detC)\ {\ detC = 2.0*C[5]*C[1]*C[2] - C[8]*C[1]*C[1] - C[4]*C[2]*C[2] - C[0]*(C[5]*C[5] - C[4]*C[8]);\ invC[0] = (C[4]*C[8] - C[5]*C[5]) / detC;\ invC[1] = (C[2]*C[5] - C[1]*C[8]) / detC;\ invC[2] = (C[1]*C[5] - C[2]*C[4]) / detC;\ invC[4] = (C[0]*C[8] - C[2]*C[2]) / detC;\ invC[5] = (C[1]*C[2] - C[0]*C[5]) / detC;\ invC[8] = (C[0]*C[4] - C[1]*C[1]) / detC;\ } // return J(1x3)*C(3x3)*J(1x3)' #define RVLCOV3DTRANSFTO1D(C, J) (C[0]*J[0]*J[0] + 2*C[1]*J[0]*J[1] + 2*C[2]*J[0]*J[2] + C[4]*J[1]*J[1] + 2*C[5]*J[1]*J[2] + C[8]*J[2]*J[2]) #define RVLMIN(x, y) (x <= y ? (x) : (y)) #define RVLMAX(x, y) (x >= y ? (x) : (y)) #define RVLABS(x) (x >= 0.0 ? (x) : -(x)) // R = [1, 0, 0; // 0, cs, -sn; // 0, sn, cs] #define RVLROTX(cs, sn, R)\ {\ RVLMXEL(R, 3, 0, 0) = 1.0;\ RVLMXEL(R, 3, 0, 1) = 0.0;\ RVLMXEL(R, 3, 0, 2) = 0.0;\ RVLMXEL(R, 3, 1, 0) = 0.0;\ RVLMXEL(R, 3, 1, 1) = cs;\ RVLMXEL(R, 3, 1, 2) = -sn;\ RVLMXEL(R, 3, 2, 0) = 0.0;\ RVLMXEL(R, 3, 2, 1) = sn;\ RVLMXEL(R, 3, 2, 2) = cs;\ } // R = [ cs, 0, sn; // 0, 1, 0; // -sn, 0, cs] #define RVLROTY(cs, sn, R)\ {\ RVLMXEL(R, 3, 0, 0) = cs;\ RVLMXEL(R, 3, 0, 1) = 0.0;\ RVLMXEL(R, 3, 0, 2) = sn;\ RVLMXEL(R, 3, 1, 0) = 0.0;\ RVLMXEL(R, 3, 1, 1) = 1.0;\ RVLMXEL(R, 3, 1, 2) = 0.0;\ RVLMXEL(R, 3, 2, 0) = -sn;\ RVLMXEL(R, 3, 2, 1) = 0.0;\ RVLMXEL(R, 3, 2, 2) = cs;\ } // R = [cs, -sn, 0; // sn, cs, 0; // 0, 0, 1] #define RVLROTZ(cs, sn, R)\ {\ RVLMXEL(R, 3, 0, 0) = cs;\ RVLMXEL(R, 3, 0, 1) = -sn;\ RVLMXEL(R, 3, 0, 2) = 0.0;\ RVLMXEL(R, 3, 1, 0) = sn;\ RVLMXEL(R, 3, 1, 1) = cs;\ RVLMXEL(R, 3, 1, 2) = 0.0;\ RVLMXEL(R, 3, 2, 0) = 0.0;\ RVLMXEL(R, 3, 2, 1) = 0.0;\ RVLMXEL(R, 3, 2, 2) = 1.0;\ } // V(3x1) = R(3x3) OX X ie[1 0 0] #define RVLOX_X(R,V)\ {\ V[0] = R[8] * R[4] - R[5] * R[7];\ V[1] = R[6] * R[5] - R[3] * R[8];\ V[2] = R[7] * R[3] - R[4] * R[6];\ } // V(3x1) = R(3x3) OX Z ie[0 0 1] #define RVLOX_Z(R,V)\ {\ V[0] = R[5] * R[1] - R[2] * R[4];\ V[1] = R[3] * R[2] - R[0] * R[5];\ V[2] = R[4] * R[0] - R[1] * R[3];\ } // C(3x3) = A(3x1) * B'(3x1) #define RVLVECMUL3X1T2(A,B,C)\ {\ RVLMXEL(C, 3, 0, 0) = A[0] * B[0];\ RVLMXEL(C, 3, 0, 1) = A[0] * B[1];\ RVLMXEL(C, 3, 0, 2) = A[0] * B[2];\ RVLMXEL(C, 3, 1, 0) = A[1] * B[0];\ RVLMXEL(C, 3, 1, 1) = A[1] * B[1];\ RVLMXEL(C, 3, 1, 2) = A[1] * B[2];\ RVLMXEL(C, 3, 2, 0) = A[2] * B[0];\ RVLMXEL(C, 3, 2, 1) = A[2] * B[1];\ RVLMXEL(C, 3, 2, 2) = A[2] * B[2];\ } // C(3x3) = x(3x1)*x(3x1)' (only diagonal + upper triangle are computed) #define RVLVECTCOV3(x, C)\ {\ C[0] = (x[0] * x[0]);\ C[1] = (x[0] * x[1]);\ C[2] = (x[0] * x[2]);\ C[4] = (x[1] * x[1]);\ C[5] = (x[1] * x[2]);\ C[8] = (x[2] * x[2]);\ } // C(3x3) = C(3x3) + x(3x1)*x(3x1)' (only diagonal + upper triangle are computed) // M(3x1) = M(3x1) + x(3x1) #define RVLMOMENTS3UPDATE(x, M, C, n)\ {\ n++;\ M[0] += x[0];\ M[1] += x[1];\ M[2] += x[2];\ C[0] += (x[0] * x[0]);\ C[1] += (x[0] * x[1]);\ C[2] += (x[0] * x[2]);\ C[4] += (x[1] * x[1]);\ C[5] += (x[1] * x[2]);\ C[8] += (x[2] * x[2]);\ } // pTgt = R * pSrc + t #define RVLTRANSF3(pSrc, R, t, pTgt)\ {\ RVLMULMX3X3VECT(R, pSrc, pTgt)\ RVLSUM3VECTORS(pTgt, t, pTgt)\ } // pTgt = R' * (pSrc - t) #define RVLINVTRANSF3(pSrc, R, t, pTgt, tmp3x1)\ {\ RVLDIF3VECTORS(pSrc, t, tmp3x1);\ RVLMULMX3X3TVECT(R, tmp3x1, pTgt);\ } // T(R, t) = T(R1, t1) * T(R2, t2) #define RVLCOMPTRANSF3D(R1, t1, R2, t2, R, t)\ {\ RVLMXMUL3X3(R1, R2, R)\ RVLMULMX3X3VECT(R1, t2, t)\ RVLSUM3VECTORS(t, t1, t)\ } // R = R1 * R2 (rotations around z-axis) #define RVLCOMPROT3D3DOF(R1, R2, R)\ {\ R[0] = R1[0]*R2[0]+R1[1]*R2[3];\ R[1] = R1[0]*R2[1]+R1[1]*R2[4];\ R[2] = 0.0;\ R[3] = R1[3]*R2[0]+R1[4]*R2[3];\ R[4] = R1[3]*R2[1]+R1[4]*R2[4];\ R[5] = 0.0;\ R[6] = 0.0;\ R[7] = 0.0;\ R[8] = 1.0;\ } // T(R, t) = T(R1, t1) * T(R2, t2) (3DOF transformations) #define RVLCOMPTRANSF3D3DOF(R1, t1, R2, t2, R, t)\ {\ RVLCOMPROT3D3DOF(R1, R2, R)\ t[0] = R1[0]*t2[0]+R1[1]*t2[1]+t1[0];\ t[1] = R1[3]*t2[0]+R1[4]*t2[1]+t1[1];\ t[2] = 0.0;\ } // T(R, t) = inv(T(R1, T1)) * T(R2, T2) #define RVLCOMPTRANSF3DWITHINV(R1, t1, R2, t2, R, t, tmp3x1)\ {\ RVLMXMUL3X3T1(R1, R2, R)\ RVLDIF3VECTORS(t2, t1, tmp3x1)\ RVLMULMX3X3TVECT(R1, tmp3x1, t)\ } // T(RTgt, tTgt) = inv(T(RSrc, tSrc)) #define RVLINVTRANSF3D(RSrc, tSrc, RTgt, tTgt)\ {\ RVLCOPYMX3X3T(RSrc, RTgt)\ RVLINVTRANSL(RSrc, tSrc, tTgt)\ } // T(RTgt, tTgt) = inv(T(RSrc, tSrc)) (3DOF transformations) #define RVLINVTRANSF3D3DOF(RSrc, tSrc, RTgt, tTgt)\ {\ RTgt[0] = RSrc[0];\ RTgt[1] = RSrc[3];\ RTgt[2] = 0.0;\ RTgt[3] = RSrc[1];\ RTgt[4] = RSrc[4];\ RTgt[5] = 0.0;\ RTgt[6] = 0.0;\ RTgt[7] = 0.0;\ RTgt[8] = 1.0;\ tTgt[0] = - RSrc[0]*tSrc[0] - RSrc[3]*tSrc[1];\ tTgt[1] = RSrc[3]*tSrc[0] - RSrc[0]*tSrc[1];\ tTgt[2] = 0.0;\ } #define RVLHTRANSFMX(R, t, T)\ {\ T[0] = R[0];\ T[1] = R[1];\ T[2] = R[2];\ T[4] = R[3];\ T[5] = R[4];\ T[6] = R[5];\ T[8] = R[6];\ T[9] = R[7];\ T[10] = R[8];\ T[3] = t[0];\ T[7] = t[1];\ T[11] = t[2];\ T[12] = T[13] = T[14] = 0.0;\ T[15] = 1.0;\ } #define RVLHTRANSFMXDECOMP(T, R, t)\ {\ R[0] = T[0];\ R[1] = T[1];\ R[2] = T[2];\ R[3] = T[4];\ R[4] = T[5];\ R[5] = T[6];\ R[6] = T[8];\ R[7] = T[9];\ R[8] = T[10];\ t[0] = T[3];\ t[1] = T[7];\ t[2] = T[11];\ } #define RVLHTRANSFMXDECOMP_COLMAY(T, R, t)\ {\ R[0] = T[0];\ R[1] = T[4];\ R[2] = T[8];\ R[3] = T[1];\ R[4] = T[5];\ R[5] = T[9];\ R[6] = T[2];\ R[7] = T[6];\ R[8] = T[10];\ t[0] = T[12];\ t[1] = T[13];\ t[2] = T[14];\ } // Compute s and RTgt such that RSrc = s * RTgt. #define RVLEXTRACTSCALEFROMROT(RSrc, s, RTgt) {s = sqrt(RVLDOTPRODUCT3(RSrc, RSrc)); RVLSCALEMX3X32(RSrc, s, RTgt)} //// Compute vector Y orthogonal to X //#define RVLORTHOGONAL3(X, Y, i, j, k, tmp3x1, fTmp)\ //{\ // tmp3x1[0] = RVLABS(X[0]);\ // tmp3x1[1] = RVLABS(X[1]);\ // tmp3x1[2] = RVLABS(X[2]);\ // i = (tmp3x1[0] > tmp3x1[1] ? 0 : 1);\ // if(tmp3x1[2] > tmp3x1[i])\ // i = 2;\ // j = (i + 1) % 3;\ // k = (i + 2) % 3;\ // Y[i] = -X[j];\ // Y[j] = X[i];\ // Y[k] = 0.0;\ // fTmp = sqrt(Y[j] * Y[j] + Y[i] * Y[i]);\ // RVLSCALE3VECTOR2(Y, fTmp, Y)\ //} // Compute vector Y orthogonal to X #define RVLORTHOGONAL3(X, Y, i, j, k, fTmp)\ {\ i = (RVLABS(X[0]) < RVLABS(X[1]) ? 0 : 1);\ j = (i + 1) % 3;\ k = (i + 2) % 3;\ Y[j] = -X[k];\ Y[k] = X[j];\ Y[i] = 0.0;\ fTmp = sqrt(Y[j] * Y[j] + Y[k] * Y[k]);\ RVLSCALE3VECTOR2(Y, fTmp, Y)\ } // Tgt = Src(2x2) #define RVLCOPYMX2X2(Src, Tgt) Tgt[0] = Src[0]; Tgt[1] = Src[1]; Tgt[2] = Src[2]; Tgt[3] = Src[3]; // C = A(2x2)*B(2x2) #define RVLMXMUL2X2(A,B,C)\ {\ RVLMXEL(C, 2, 0, 0) = RVLMXEL(A, 2, 0, 0)*RVLMXEL(B, 2, 0, 0)+RVLMXEL(A, 2, 0, 1)*RVLMXEL(B, 2, 1, 0);\ RVLMXEL(C, 2, 0, 1) = RVLMXEL(A, 2, 0, 0)*RVLMXEL(B, 2, 0, 1)+RVLMXEL(A, 2, 0, 1)*RVLMXEL(B, 2, 1, 1);\ RVLMXEL(C, 2, 1, 0) = RVLMXEL(A, 2, 1, 0)*RVLMXEL(B, 2, 0, 0)+RVLMXEL(A, 2, 1, 1)*RVLMXEL(B, 2, 1, 0);\ RVLMXEL(C, 2, 1, 1) = RVLMXEL(A, 2, 1, 0)*RVLMXEL(B, 2, 0, 1)+RVLMXEL(A, 2, 1, 1)*RVLMXEL(B, 2, 1, 1);\ } // y = det(C(2x2)) (C is simmetric) #define RVLDET2(C) (C[0]*C[3] - C[1]*C[1]) // y = x(2x1)' * inv(C(2x2)) * x (C is simmetric) #define RVLMAHDIST2(x, C, detC) ((C[3]*x[0]*x[0] - 2.0*C[1]*x[0]*x[1] + C[0]*x[1]*x[1]) / detC) // COut = J(2x2)*C(2x2)*J(2x2)' (C is simmetric; only diagonal + upper triangle are computed) #define RVLCOV2DTRANSF(C, J, COut)\ {\ COut[0] = C[0]*J[0]*J[0] + 2*C[1]*J[0]*J[1] + C[3]*J[1]*J[1];\ COut[1] = J[2]*(C[0]*J[0] + C[1]*J[1]) + J[3]*(C[1]*J[0] + C[3]*J[1]);\ COut[3] = C[0]*J[2]*J[2] + 2*C[1]*J[2]*J[3] + C[3]*J[3]*J[3];\ } // y = A(2x2) * x(2x1), where A is a simetric matrix with only diagonal + upper triangle defined #define RVLMULCOV2VECT(A, x, y) y[0] = A[0]*x[0] + A[1]*x[1]; y[1] = A[1]*x[0] + A[3]*x[1]; // invC(2x2) = inv(C(2x2)) (C is simmetric; only diagonal + upper triangle are computed) #define RVLINVCOV2(C, invC, detC)\ {\ invC[0] = C[3] / detC;\ invC[1] = -C[1] / detC;\ invC[3] = C[0] / detC;\ } #define RVLCONVTOINT3(Src, Tgt) Tgt[0] = (int)Src[0]; Tgt[1] = (int)Src[1]; Tgt[2] = (int)Src[2]; #define RVLCONVTOUCHAR3(Src, Tgt) Tgt[0] = (unsigned char)Src[0]; Tgt[1] = (unsigned char)Src[1]; Tgt[2] = (unsigned char)Src[2]; #define RVLSORT3ASCEND(Vect3, idx, tmp)\ {\ if(Vect3[0] <= Vect3[1])\ {\ idx[0] = 0;\ idx[1] = 1;\ }\ else{\ idx[0] = 1; \ idx[1] = 0; \ }\ if(Vect3[idx[0]] > Vect3[2])\ {\ idx[2] = idx[0];\ idx[0] = 2;\ }\ else\ idx[2] = 2;\ if (Vect3[idx[1]] > Vect3[idx[2]])\ {\ tmp = idx[1];\ idx[1] = idx[2];\ idx[2] = tmp;\ }\ } //AT(3x3) = A(3x3)' - Vidovic #define RVLTRASPOSE3X3(A, AT)\ {\ AT[0] = A[0]; \ AT[1] = A[3]; \ AT[2] = A[6]; \ AT[3] = A[1]; \ AT[4] = A[4]; \ AT[5] = A[7]; \ AT[6] = A[2]; \ AT[7] = A[5]; \ AT[8] = A[8]; \ } template <typename Type> struct Moments { int n; Type S[3], S2[9]; }; template <typename Type> inline void InitMoments(Moments<Type> &moments) { moments.n = 0; RVLNULL3VECTOR(moments.S); RVLNULLMX3X3(moments.S2); } template <typename Type> inline void UpdateMoments(Moments<Type> &moments, Type *P) { RVLMOMENTS3UPDATE(P, moments.S, moments.S2, moments.n); } template <class Type> void GetCovMatrix3( Moments<Type> *pMoments, Type *C, Type *M) { Type fn = (Type)(pMoments->n); M[0] = pMoments->S[0] / fn; M[1] = pMoments->S[1] / fn; M[2] = pMoments->S[2] / fn; C[0] = pMoments->S2[0] / fn - M[0] * M[0]; C[1] = pMoments->S2[1] / fn - M[0] * M[1]; C[2] = pMoments->S2[2] / fn - M[0] * M[2]; C[3] = C[1]; C[4] = pMoments->S2[4] / fn - M[1] * M[1]; C[5] = pMoments->S2[5] / fn - M[1] * M[2]; C[6] = C[2]; C[7] = C[5]; C[8] = pMoments->S2[8] / fn - M[2] * M[2]; } template <typename Type> inline void LinePlaneIntersection( Type *P1, Type *P2, Type *N, Type d, Type *PIS) { Type dP[3]; RVLDIF3VECTORS(P2, P1, dP); Type s = (d - RVLDOTPRODUCT3(N, P1)) / (RVLDOTPRODUCT3(N, dP)); RVLSCALE3VECTOR(dP, s, PIS); RVLSUM3VECTORS(PIS, P1, PIS); } namespace RVL { template <typename Type> struct Box { Type minx; Type maxx; Type miny; Type maxy; Type minz; Type maxz; }; template <typename T> void ExpandBox(Box<T> *pBox, T extension) { pBox->minx -= extension; pBox->maxx += extension; pBox->miny -= extension; pBox->maxy += extension; pBox->minz -= extension; pBox->maxz += extension; } template <typename Type> void PrintMatrix(FILE *fp, Type *A, int n, int m) { Type *pA = A; int i, j; for (i = 0; i < n; i++) { for (j = 0; j < m; j++, pA++) fprintf(fp, "%f\t", *pA); fprintf(fp, "\n"); } } template <typename Type> void AngleAxisToRot(Type *k, Type q, Type *R) { Type cq = cos(q); Type sq = sin(q); Type cqcomp = 1.0 - cq; Type kxy = k[0] * k[1] * cqcomp; Type kyz = k[1] * k[2] * cqcomp; Type kzx = k[2] * k[0] * cqcomp; R[0] = k[0] * k[0] * cqcomp + cq; R[1] = kxy - k[2] * sq; R[2] = kzx + k[1] * sq; R[3] = kxy + k[2] * sq; R[4] = k[1] * k[1] * cqcomp + cq; R[5] = kyz - k[0] * sq; R[6] = kzx - k[1] * sq; R[7] = kyz + k[0] * sq; R[8] = k[2] * k[2] * cqcomp + cq; } #define RVLCREATE3DTRANSF(R, t, T)\ {\ T[0] = R[0];\ T[1] = R[1];\ T[2] = R[2];\ T[4] = R[3];\ T[5] = R[4];\ T[6] = R[5];\ T[8] = R[6];\ T[9] = R[7];\ T[10] = R[8];\ T[3] = t[0];\ T[7] = t[1];\ T[11] = t[2];\ T[12] = T[13] = T[14] = 0.0;\ T[15] = 1.0;\ } template <typename T> struct Vector3 { T Element[3]; }; template <typename T> struct Matrix3 { T Element[9]; }; template < typename T1, typename T2 > struct Correspondence { T1 item1; T2 item2; }; template <typename T> void InitBoundingBox(Box<T> *pBox, T *P) { pBox->minx = pBox->maxx = P[0]; pBox->miny = pBox->maxy = P[1]; pBox->minz = pBox->maxz = P[2]; } template <typename T> void UpdateBoundingBox(Box<T> *pBox, T *P) { if (P[0] < pBox->minx) pBox->minx = P[0]; else if (P[0] > pBox->maxx) pBox->maxx = P[0]; if (P[1] < pBox->miny) pBox->miny = P[1]; else if (P[1] > pBox->maxy) pBox->maxy = P[1]; if (P[2] < pBox->minz) pBox->minz = P[2]; else if (P[2] > pBox->maxz) pBox->maxz = P[2]; } template <typename T> bool InBoundingBox(Box<T> *pBox, T *P) { return (P[0] >= pBox->minx && P[0] <= pBox->maxx && P[1] >= pBox->miny && P[1] <= pBox->maxy && P[2] >= pBox->minz && P[2] <= pBox->maxz); } template <typename T> bool BoxIntersection( Box<T> *pBoxSrc1, Box<T> *pBoxSrc2, Box<T> *pBoxTgt) { pBoxTgt->minx = RVLMAX(pBoxSrc1->minx, pBoxSrc2->minx); pBoxTgt->maxx = RVLMIN(pBoxSrc1->maxx, pBoxSrc2->maxx); if (pBoxTgt->minx >= pBoxTgt->maxx) return false; pBoxTgt->miny = RVLMAX(pBoxSrc1->miny, pBoxSrc2->miny); pBoxTgt->maxy = RVLMIN(pBoxSrc1->maxy, pBoxSrc2->maxy); if (pBoxTgt->miny >= pBoxTgt->maxy) return false; pBoxTgt->minz = RVLMAX(pBoxSrc1->minz, pBoxSrc2->minz); pBoxTgt->maxz = RVLMIN(pBoxSrc1->maxz, pBoxSrc2->maxz); if (pBoxTgt->minz >= pBoxTgt->maxz) return false; return true; } template <typename T> void BoxSize( Box<T> *pBox, T &a, T &b, T &c) { a = pBox->maxx - pBox->minx; b = pBox->maxy - pBox->miny; c = pBox->maxz - pBox->minz; } template <typename T> T BoxSize(Box<T> *pBox) { T a, b, c; BoxSize(pBox, a, b, c); T tmp = RVLMAX(a, b); return RVLMAX(tmp, c); } template <typename T> T BoxVolume(Box<T> *pBox) { return (pBox->maxx - pBox->minx) * (pBox->maxy - pBox->miny) * (pBox->maxz - pBox->minz); } template <typename T> void BoxCenter( Box<T> *pBox, T *P) { P[0] = 0.5f * (pBox->minx + pBox->maxx); P[1] = 0.5f * (pBox->miny + pBox->maxy); P[2] = 0.5f * (pBox->minz + pBox->maxz); } }
true
efa4dd654a0516049010367762f466c147bf004c
C++
IAmDylanDennison/CS1B
/Lab6_powerball/Lab6_powerball/powerball.cpp
UTF-8
1,635
3.578125
4
[]
no_license
// Dylan Dennison // Lab6_powerball // Array size of 20 with random numbers 1-100 // 10/1/19 #include <iostream> #include <cmath> #include <cstdlib> #include <ctime> #include <random> using std::cin; using std::cout; using std::endl; void assign(int[], int); int entry(); bool check(int guess, int wins[], int arraySize); void draw(int[], int arraySize); void printOut(int wins[], int arraySize); void assign(int wins[], int arraySize) { for (int i = 0; i < arraySize; i++) { wins[i] = 0; } } int entry() { int guess; cout << " input your number guess!"; cin >> guess; return guess; } bool check(int guess, int wins[], int arraySize) { for (int i = 0; i < arraySize; ++i) { if (wins[i] == guess) { return true; } } return false; } void draw(int wins[], int arraySize) { int i = 0; srand(time(nullptr)); while (i < arraySize) { int random = rand() % 100 + 1; if (!check(random, wins, arraySize)) { wins[i] = random; ++i; } } } void printOut(int wins[], int arraySize) { for (int i = 0; i < arraySize; i++) { cout << wins[i] << " "; } } int main() { const int arraySize = 20; int wins[arraySize]; int guess; int count; count = 1; cout << "Welcome to my lottery game!"; assign(wins, arraySize); draw(wins, arraySize); while (count <= 3) { guess = entry(); count++; } if (check(guess, wins, arraySize)) { cout << "You are a winner!"; } else { cout << "You Lost! no money for you!"; } cout << "The lottery numbers are.."; printOut(wins, arraySize); }
true
15e6c107b7b20f31e6e8feb1a8c2931a7c626762
C++
iscsi/algorithms
/rili/test/BaseFixture.cpp
UTF-8
2,449
2.953125
3
[]
no_license
#include <algorithm> #include <iterator> #include <rili/test/BaseFixture.h> #include <rili/test/TestStorage.h> #include <string> #include <utility> #include <vector> namespace rili { namespace test { void TestBaseFixture::before() {} void TestBaseFixture::after() {} const std::string& TestCreatorBase::fixtureName() const { return m_fixtureName; } const std::string& TestCreatorBase::scenarioName() const { return m_scenarioName; } const std::string& TestCreatorBase::typeName() const { return m_typeName; } bool TestCreatorBase::operator<(const TestCreatorBase& other) const noexcept { return m_fixtureName + "@" + m_scenarioName + "@" + m_typeName < other.m_fixtureName + "@" + other.m_scenarioName + "@" + other.m_typeName; } TestCreatorBase::TestCreatorBase(const std::string& fixtureName, const std::string& scenarioName, std::string const& typeName) : m_fixtureName(fixtureName), m_scenarioName(scenarioName), m_typeName(typeName) { TestStorage::getInstance().registerTestCreator(*this); } namespace detail { std::vector<std::string> getTypeNamesImpl(std::string const& typeNames) noexcept { std::vector<std::string> types; int bracketsCounter = 0; std::string currentType; for (auto it = typeNames.begin(); it != typeNames.end(); it++) { char back = 0; if (!currentType.empty()) { back = currentType.back(); } switch (*it) { case '<': { bracketsCounter++; if (back == ' ') { currentType.back() = '<'; } else { currentType += "<"; } break; } case '>': { bracketsCounter--; if (back == ' ') { currentType.back() = '>'; } else { currentType += ">"; } break; } case ':': { if (back == ' ') { currentType.back() = ':'; } else { currentType += ":"; } break; } case ',': { if (bracketsCounter == 0) { types.push_back(currentType); currentType.clear(); } else { if (back == ' ') { currentType.back() = ','; } else { currentType += ", "; } } break; } case '\t': case '\r': case '\n': case ' ': { if (back != 0 && back != '>' && back != '<' && back != ':' && back != ' ') { currentType += " "; } break; } default: { currentType += *it; break; } } } if (!currentType.empty()) { types.push_back(currentType); } return types; } } // namespace detail } // namespace test } // namespace rili
true
a0e8d15ea8c440806f3e22f3c624c832f8908f61
C++
Bigstorm20008/CrazyTank3
/src/RandomEngine.cpp
UTF-8
698
2.921875
3
[]
no_license
#include "RandomEngine.h" namespace helpers { std::shared_ptr<RandomEngine> RandomEngine::m_instance = nullptr; RandomEngine::RandomEngine() : m_defaultRandomEngine{ std::default_random_engine{ static_cast<unsigned int>(time(0)) } } { } RandomEngine::~RandomEngine() { } std::shared_ptr<RandomEngine> RandomEngine::getInstance() { if (m_instance == nullptr) { m_instance.reset(new RandomEngine); } return m_instance; } const int RandomEngine::getRandomInteger(const int& startDistance, const int& endDistance) { std::uniform_int_distribution<int> widthDistance(startDistance, endDistance); return widthDistance(m_defaultRandomEngine); } }//namespace helpers
true
4194c32407cc39ee9e74d8602ed8b651c354f2cb
C++
sh4062/Leetcode
/301.cpp
UTF-8
1,217
2.984375
3
[]
no_license
class Solution { public: bool isvalid(string S){ stack<char>st; for(int i = 0;i<S.size();i++){ if(S[i]=='('){ st.push(S[i]); } if(S[i]==')'){ if(st.empty()){ return false; } st.pop(); }} return st.size()==0; } vector<string> removeInvalidParentheses(string s) { queue<string>q; q.push(s); set<string>res; vector<string>ret; int flag = 1; int sz = -1; while(!q.empty()){ auto tmp = q.front(); q.pop(); if(isvalid(tmp)){ ret.push_back(tmp); flag = 0; } if(flag) for(int i = 0;i<tmp.size();i++){ if(tmp[i]=='('||tmp[i]==')'){ string ss = tmp.substr(0,i)+tmp.substr(i+1); //cout<<ss<<endl; if(!res.count(ss)){ res.insert(ss); q.push(ss); } } } } return ret; } };
true
d8f96e623c699226dfe290f6e2d23fa078247591
C++
niltonvasques/gl-data-structure
/TestShape.cpp
UTF-8
1,397
2.890625
3
[]
no_license
#include "TestShape.h" TestShape::TestShape() :Shape(Color()){ } TestShape::~TestShape(){ } void TestShape::Draw(){ // Altera a cor do desenho para azul glColor3f(0.0f, 0.0f, 1.0f); // Desenha a casa glBegin(GL_QUADS); glVertex2f(-15.0f,-15.0f); glVertex2f(-15.0f, 5.0f); glVertex2f( 15.0f, 5.0f); glVertex2f( 15.0f,-15.0f); glEnd(); // Altera a cor do desenho para branco glColor3f(1.0f, 1.0f, 1.0f); // Desenha a porta e a janela glBegin(GL_QUADS); glVertex2f(-4.0f,-14.5f); glVertex2f(-4.0f, 0.0f); glVertex2f( 4.0f, 0.0f); glVertex2f( 4.0f,-14.5f); glVertex2f( 7.0f,-5.0f); glVertex2f( 7.0f,-1.0f); glVertex2f(13.0f,-1.0f); glVertex2f(13.0f,-5.0f); glEnd(); // Altera a cor do desenho para azul glColor3f(0.0f, 0.0f, 1.0f); // Desenha as "linhas" da janela glBegin(GL_LINES); glVertex2f( 7.0f,-3.0f); glVertex2f(13.0f,-3.0f); glVertex2f(10.0f,-1.0f); glVertex2f(10.0f,-5.0f); glEnd(); // Altera a cor do desenho para vermelho glColor3f(1.0f, 0.0f, 0.0f); // Desenha o telhado glBegin(GL_TRIANGLES); glVertex2f(-15.0f, 5.0f); glVertex2f( 0.0f,17.0f); glVertex2f( 15.0f, 5.0f); glEnd(); // Executa os comandos OpenGL glFlush(); }
true
7da98082978e0b652ad651b9415141557b9d9c5b
C++
KrzaQ/secret-dangerzone
/kq/menu.hpp
UTF-8
2,058
3.3125
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
#ifndef IOUTILS_H #define IOUTILS_H #include <functional> #include <iosfwd> #include <iostream> #include <map> #include <memory> #include <limits> #include <string> #include <utility> namespace kq{ namespace detail{ template<typename Func> class ExceptionWrapper { public: template<typename T, typename U = typename std::enable_if< !std::is_same< typename std::decay<T>::type, ExceptionWrapper >::value, void>::type > ExceptionWrapper(T&& t): f(std::forward<T>(t)){} ExceptionWrapper(ExceptionWrapper const&) = default; ExceptionWrapper(ExceptionWrapper &&) = default; void operator()() const { try{ f(); }catch(std::exception const& e){ std::cout << "Exception: " << e.what() << std::endl; } } private: Func f; }; } template<typename T> auto makeExceptionWrapper(T&& t){ return detail::ExceptionWrapper<typename std::decay<T>::type>(std::forward<T>(t)); } class Menu { public: Menu(): options_{{0,{"exit",[this]{exit();}}}}{} enum class LoopStrategy{ Infinite, NoLoop }; template<typename T> void addOption(int no, std::string const& name, T&& o){ options_[no] = std::make_pair(name, std::forward<T>(o)); } template<typename T> void addOption(std::string const& name, T&& o){ int no = options_.size() ? options_.rbegin()->first + 1 : 1; options_[no] = std::make_pair(name, std::forward<T>(o)); } template<typename T> static T get(std::string const& name = {}){ T ret; if(name.size()) std::cout << "Please enter the value of " << name << ":" << std::endl; while(!(std::cin >> ret)){ std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); std::cout << "Please enter a valid value:" << std::endl; } return ret; } void operator()() const; void setLoopStrategy(LoopStrategy ls) { loopStrategy_ = ls; } void exit(){ setLoopStrategy(LoopStrategy::NoLoop); } private: LoopStrategy loopStrategy_ = LoopStrategy::NoLoop; std::map<int, std::pair<std::string,std::function<void()>>> options_; }; } #endif // IOUTILS_H
true
711d87be30f5ed8a907f690765d60927e4a09d66
C++
dsamt/Data-Strcutures-and-Algorithms-Projects
/Project5.1/P5.1/P5.1/treap_bst.hpp
UTF-8
3,117
3.484375
3
[]
no_license
#ifndef TREAP_BST_HPP #define TREAP_BST_HPP #include <random> #include <iostream> #include "abstract_bst.hpp" template <typename KeyType, typename ValueType> class TreapBST : public AbstractBST<KeyType, ValueType> { public: /** Default contructor. */ TreapBST(); /** Copy constructor. */ TreapBST(const TreapBST &x); /** Copy-assignment. */ TreapBST &operator=(TreapBST x); /** Destructor. */ ~TreapBST(); bool empty(); /** Search for key. If found is true, returns the value associated with that key. If found is false, returns a default constructed ValueType. */ ValueType search(const KeyType &key, bool &found); /* Insert value into the BST with unique key. thows std::logic_error if key is already in the tree. */ void insert(const KeyType &key, const ValueType &value); /* Remove value from the BST with key. Do nothing if there is no such key in the BST. throws std::logic_error if empty. */ void remove(const KeyType &key); /** Get the height of the treap. */ std::size_t height(); //used for debugging //void print(); private: /* Random number generator. */ std::mt19937 rndgen; /* Node struct with key, data, random priority, and parent, left child, and right child pointers. */ template <typename K, typename V> struct Node { K key; V data; std::mt19937::result_type priority; Node* parent; Node* childl; Node* childr; Node(const K& k, const V& d, Node* p = nullptr) : key(k) , data(d) , parent(p) , childl(nullptr) , childr(nullptr) { priority = rand() % 100; } }; // You may add private member variables/methods as needed. //defining the variable root node for use htroughout the program Node<KeyType, ValueType>* root; //method that rotates a treap right in order to hold max-heap properties TreapBST<KeyType, ValueType>::Node<KeyType, ValueType>* rotateRight(Node<KeyType, ValueType>* subtree); //method that rotates a treap left in order to hold max-heap properties TreapBST<KeyType, ValueType>::Node<KeyType, ValueType>* rotateLeft(Node<KeyType, ValueType>* subtree); //used for debugging //void inOrder(Node<KeyType, ValueType>* subTree); //helper method for the insert method TreapBST<KeyType, ValueType>::Node<KeyType, ValueType>* insert(Node <KeyType, ValueType>* subtree, const KeyType &key, const ValueType &value); //helper method for the remove method TreapBST<KeyType, ValueType>::Node<KeyType, ValueType>* deleteNode(Node<KeyType, ValueType>* subtree, const KeyType &key); //helper method for the copy constructor TreapBST<KeyType, ValueType>::Node<KeyType, ValueType>* copyTreap(const Node<KeyType, ValueType>* subtree); //helper method for the destructor void destroyTreap(Node<KeyType, ValueType>* subtree); //helper method for the height() method std::size_t heightHelper(Node<KeyType, ValueType>* subtree); //helper method for the copy assignment operator void swap(TreapBST<KeyType, ValueType>& x, TreapBST<KeyType, ValueType>& y); //used for debugging //void inorderPrint(Node<KeyType, ValueType>* subtree); }; #include "treap_bst.txx" #endif // TREAP_BST_HPP
true
9cd071a5dea7d9b4c35046ae7a56bb7ae351516c
C++
Sean-Huang65/leetcode
/code/561.cpp
UTF-8
391
3.140625
3
[]
no_license
#include <vector> #include <iostream> #include <algorithm> using namespace std; class Solution { public: //先排序,后取奇数 //sort(),给出首尾指针 int arrayPairSum(vector<int>& nums) { int result = 0; sort(nums.begin(),nums.end()); for(int i =0;i<nums.size();i+=2) result+=nums[i]; return result; } };
true
7dab04658b54ea9e5b91617c589344942b097b01
C++
hacker-taso/algorithm_judges
/facebook/hacker-cup/2021/Qual/A1.cpp
UTF-8
1,003
2.921875
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> #include<limits> using namespace std; string s; vector<char> vowels = {'A', 'E', 'I', 'O', 'U'}; #define showthis(s) cout << s << endl; int solve() { vector<int> cnts(256, 0); for (char c: s) { cnts[c]++; } int vcnt = 0; char vmax = 'A'; char cmax = 'B'; for (char c='A'; c<='Z'; c++) { bool isv = find(vowels.begin(), vowels.end(), c) != vowels.end(); vcnt += isv ? cnts[c] : 0; if (isv && cnts[vmax] < cnts[c]) { vmax = c; } else if (!isv && cnts[cmax] < cnts[c]) { cmax = c; } } // change vs into c int twice = s.size() - cnts[cmax] - vcnt; int once = vcnt; int ret = twice*2 + once; showthis(ret) // change cs into v twice = vcnt - cnts[vmax]; once = s.size() - vcnt; ret = min(ret, twice*2 + once); showthis(ret) return ret; } int main() { int T; cin >> T; for (int i=0; i<T; i++) { cin >> s; cout << "Case #" << i+1 << ": " << solve() << endl; } }
true
ec98ce78d2b57432387f3bc5d8e626e2ea5853ad
C++
i-am-arvinder-singh/CP
/OOPS/mutable_lambda_capture_dynamic_allocation_class_destructor_using_delete_message_const_keyword.cpp
UTF-8
1,045
3.609375
4
[]
no_license
#include<bits/stdc++.h> class Base { private: int a, b ; mutable int cc=0 ; const int w = 5; public: Base(int a, int b) { Base * const c = this; c->a = a; c->b = b; } void Show() { std::cout<<"The value of 'a' and 'b' are "<<a<<" "<<b<<std::endl; } void Show_w() const { cc++; std::cout<<"The value of 'w' is "<<w<<std::endl; } void Show_c() const { std::cout<<"The value of 'cc' is "<<cc<<std::endl; } }; int main() { Base * b = new Base(2,3); b->Show(); int w = 0; auto p = [=] () mutable { w++; for(int i = 0; i<4;i++){ std::cout<<"***** "<<std::endl; b->Show_w(); b->Show_c(); } std::cout<< " From inside the function p() ---->> " << w <<std::endl; }; std::cout<<"Times executed p() is : "<< w <<std::endl; p(); std::cout<<"Times executed p() is : "<< w <<std::endl; }
true
c99400d0c17bfd90baffc2517ce3e1e48605a7b4
C++
betallcoffee/leetcode
/old/Merge Sorted Array/Merge Sorted Array/main.cpp
UTF-8
2,934
3.5625
4
[ "Apache-2.0" ]
permissive
// // main.cpp // Merge Sorted Array // // Created by liang on 1/11/17. // Copyright © 2017年 liang. All rights reserved. // https://leetcode.com/problems/merge-sorted-array/description/ /** Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. */ #include <vector> using namespace std; class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { nums1.erase(nums1.begin()+m, nums1.end()); nums2.erase(nums2.begin()+n, nums2.end()); int left = 0; int right = (int)nums1.size(); for (int i = 0; i < nums2.size(); i++) { int k = nums2[i]; if (k < nums1.back()) { right = (int)nums1.size(); int j = find(nums1, left, right, k); if (nums1[j] < k) { nums1.insert(nums1.begin()+j+1, k); } else { nums1.insert(nums1.begin()+j, k); } left = j; } else { nums1.push_back(k); } } } int find(vector<int>& nums, int left, int right, int value) { while (left < right) { int min = (left + right) / 2; if (nums[min] == value) { return min; } else if (nums[min] < value) { left = min + 1; } else if (nums[min] > value) { right = min - 1; } } return left; } }; void test1() { vector<int> nums1 = {}; vector<int> nums2 = {}; Solution s; s.merge(nums1, (int)nums1.size(), nums2, (int)nums2.size()); for_each(nums1.begin(), nums1.end(), [&](int n) { printf("%d ", n); }); printf("\n"); } void test2() { vector<int> nums1 = {1, 5, 6, 9, 10, 11}; vector<int> nums2 = {2, 3, 7, 8, 12}; Solution s; s.merge(nums1, (int)nums1.size(), nums2, (int)nums2.size()); for_each(nums1.begin(), nums1.end(), [&](int n) { printf("%d ", n); }); printf("\n"); } void test3() { vector<int> nums1 = {0}; vector<int> nums2 = {1}; Solution s; s.merge(nums1, 0, nums2, (int)nums2.size()); for_each(nums1.begin(), nums1.end(), [&](int n) { printf("%d ", n); }); printf("\n"); } void test4() { vector<int> nums1 = {1, 0}; vector<int> nums2 = {2}; Solution s; s.merge(nums1, 1, nums2, 1); for_each(nums1.begin(), nums1.end(), [&](int n) { printf("%d ", n); }); printf("\n"); } int main(int argc, const char * argv[]) { // insert code here... test1(); test2(); test3(); test4(); return 0; }
true
70f81622cd6c18287ca9c9f282eef75cb4c56081
C++
emculber/AndroidOpenCL
/sendCode/main.cpp
UTF-8
4,534
3
3
[]
no_license
#include <iostream> #include <vector> #include <fstream> #include <cstring> #include <netdb.h> #include <unistd.h> #include <fcntl.h> #include <strings.h> using namespace std; int main(int argc, char * argv[]) { //Test to ensure the user has provided one argument as required. If not, default the server hostname. If so, take //the server hostname from the user. char defaultHostname[] = "home.luwsnet.com"; char hostname[]= ""; if(argc != 2) { cout << "Usage: sendCode [hostname]" << endl; cout << "Example: sendCode localhost" << endl; cout << endl << "The hostname is optional and if none is picked will default to Matt's home box" << endl; strcpy(hostname, defaultHostname); } else { strcpy(hostname, argv[1]); } /*This part is mandatory to setup connections * */ //Setup variables to establish a connection and send a JPG to the server int socketDescriptor1; struct sockaddr_in server; struct hostent *hp; int cnct; //Initiate a socket on the server socketDescriptor1 = socket(AF_INET, SOCK_STREAM, 0); if (socketDescriptor1 < 0) { //If the socket cannot be established throw an error and exit cout << "Socket cannot be established. Exiting." << endl; exit(1); } cout << "Socket established successfully!" << endl; //Set connection parameters for an IPv4 connection on port 5050 and connect using any available interface server.sin_family = AF_INET; server.sin_port = htons(5050); server.sin_addr.s_addr = INADDR_ANY; //Resolve the hostname or IP address provided by the user and assign it to the destination address hp = gethostbyname(hostname); bcopy((char *) hp->h_addr,(char *)&server.sin_addr.s_addr,hp->h_length); //Try to connect on the established socket cnct = connect(socketDescriptor1, (struct sockaddr*) &server, sizeof(server)); //If a negative value was returned, connection failed. Need to quit. if (cnct < 0) { cout << "Unable to connect on the created socket. Exiting." << endl; exit(1); } cout << "\tConnection established!" << endl; char buf[3000] = { ' ' }; /* This is where you would implement your jpg capture from camera. Currently using a file example as a placeholder * Refer to the server side for a vector<char> example where jpg data was held in memory. Can you do something * similar on Android? */ int from; from = open("input.jpg", O_RDONLY); if (from < 0) { cout << "\tUnable to open the specified file" << endl; return 0; } //Get size of the file to be sent by seeking to the end and the reset the descriptor back int outgoingFilesize = lseek(from, 0, SEEK_END); lseek(from, 0, 0); int outgoingFilesizeConverted = htonl(outgoingFilesize); /* Need all the rest of the lines to keep network handshakes rolling. At the end of this block * there is a vector of jpg data that's come back in. You will need to manipulate that into a proper format to * display on Android I'm sure */ int n, s; s = write(socketDescriptor1, &outgoingFilesizeConverted, sizeof(outgoingFilesizeConverted)); //Send data from the file while (true) { n = read(from, buf, sizeof(buf)); s = write(socketDescriptor1, buf, n); if (s < 0) { cout<<"\tError sending data to the outgoing connection" << endl; exit(1); } if(n==0) { break; } } //Get data back after conversion int incomingFilesize, incomingFileSizeConverted; n = recv(socketDescriptor1, &incomingFilesize, sizeof(incomingFilesize),0); incomingFileSizeConverted = ntohl(incomingFilesize); cout << "\t" << incomingFileSizeConverted << " bytes incoming." << endl; int bytesRead = 0; vector<unsigned char>incomingData; while(bytesRead < incomingFileSizeConverted) { n = recv(socketDescriptor1,buf,sizeof(buf),0); if(n < 0) { cout<<"\tError receiving data from the incoming connection" << endl; exit(1); } //Append this loops data to the buffer incomingData.insert(incomingData.end(), &buf[0], &buf[n]); bytesRead += sizeof(buf); } /* Just above... incomingData is a char vector which contains the full jpg response from the server * */ cout << "\t" << incomingData.size() << " bytes in data element!" << endl;; //Uncomment this to output a test file to the file system along the way...verification of good data cout << "\tWriting the file to the filesystem as test.jpg" << endl; ofstream outie("test.jpg"); outie.write((const char*)&incomingData[0], incomingData.size()); close(socketDescriptor1); shutdown(socketDescriptor1, 0); return 0; }
true
81483e03b211c45d9c998732eddb0c2b4a4de210
C++
vsokh/DataStructures-Algorithms
/algorithms/sorting/non-comparison/string-sort.cpp
UTF-8
990
3.234375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; template<typename T> using KeyGetter = function<int(vector<T> const& A, int i)>; template<typename T> void printV(vector<T> const& v) { for (auto i : v) cout << i << " "; cout << endl; } template<typename T> vector<T> countingSort( vector<T> const& A, int k, KeyGetter<T> key) { vector<vector<T>> L(k + 1); for (int i = 0; i < A.size(); ++i) { L[key(A, i)].push_back(A[i]); vector<T> B; for (auto v : L) for (auto s : v) B.push_back(s); return B; } KeyGetter<string> stringKey(int k) { return [k] (vector<string> const& A, int i) { return A[i][k] - 'A'; }; } void stringSort(vector<string>& A) { int k = A[0].length(); for (int i = k-1; i >= 0; --i) { A = countingSort<string>(A, 'Z' - 'A', stringKey(i)); } } int main() { vector<string> s{"COW","DOG","SEA","RUG","ROW","MOB","BOX","TAB","BAR","EAR","TAR","DIG", "BIG", "TEA", "NOW", "FOX"}; stringSort(s); printV(s); return 0; }
true
a29dcbac258cae3fcefeb014b8a307d7d0310e82
C++
onyazuka/Simple-system-monitor
/widgets/memorywidget.cpp
UTF-8
2,764
2.90625
3
[ "MIT" ]
permissive
#include "memorywidget.hpp" MemoryWidget::MemoryWidget(InfoManager::pointer _infoManager, QWidget* parent) : EmulateableWidget{parent}, dataPrecision{2}, infoManager{_infoManager} { setUpdateInterval(500); createWidgets(); createLayout(); createUpdaterFunctions(); } void MemoryWidget::createWidgets() { freeMemoryInfoLabel = new QLabel; freeSwapInfoLabel = new QLabel; memoryUsageChart = new MemoryChart(1); memoryUsageChart->setDrawUnderLine(true); swapUsageChart = new MemoryChart(1); swapUsageChart->setDrawUnderLine(true); // setting object names for stylesheeting freeMemoryInfoLabel->setObjectName(chartDescriptionName); freeSwapInfoLabel->setObjectName(chartDescriptionName); } void MemoryWidget::createLayout() { QVBoxLayout* vbl = new QVBoxLayout; QHBoxLayout* memhbl = new QHBoxLayout; memhbl->addWidget(freeMemoryInfoLabel); vbl->addLayout(memhbl); vbl->setAlignment(memhbl, Qt::AlignCenter); vbl->addWidget(memoryUsageChart, 2); QHBoxLayout* swaphbl = new QHBoxLayout; swaphbl->addWidget(freeSwapInfoLabel); vbl->addLayout(swaphbl); vbl->setAlignment(swaphbl, Qt::AlignCenter); vbl->addWidget(swapUsageChart, 2); setLayout(vbl); } void MemoryWidget::createUpdaterFunctions() { MemoryUsageUpdater muu(infoManager); SwapUsageUpdater suu(infoManager); memoryUsageChart->setUpdaterFunction(muu); swapUsageChart->setUpdaterFunction(suu); } // settings setters void MemoryWidget::setDataPrecision(int prec) { dataPrecision = prec; update(); } void MemoryWidget::setChartGridEnabled(bool on) { getMemoryUsageChart().setEnableGrid(on); getSwapUsageChart().setEnableGrid(on); update(); } void MemoryWidget::setChartMode(Modes mode) { getMemoryUsageChart().setMode(mode); getSwapUsageChart().setMode(mode); update(); } void MemoryWidget::stopCharts() { memoryUsageChart->stop(); swapUsageChart->stop(); } void MemoryWidget::restartCharts() { memoryUsageChart->start(); swapUsageChart->start(); } /* Tries to continue or start work. If it can not, does nothing. */ void MemoryWidget::start() { try { updater(); EmulateableWidget::start(); } catch (...) { qWarning() << "Memory widget is not working"; } } void MemoryWidget::updater() { // multiplying by 1024 because /proc/memstat provides data in kilobytes QString label = tr("Memory free: ") + Translator::fitBytes(infoManager->getMemoryAvailable() * 1024, dataPrecision); freeMemoryInfoLabel->setText(label); label = tr("Swap free: ") + Translator::fitBytes(infoManager->getSwapAvailable() * 1024, dataPrecision); freeSwapInfoLabel->setText(label); }
true
e9c12c6ac77bff844a03d9d7aefd53db52f59043
C++
yohe/CLI-DevTool
/parser/tokenize_argument.cc
UTF-8
1,793
2.953125
3
[ "MIT" ]
permissive
#include "parser/tokenize_argument.h" #include <iostream> namespace clidevt { std::vector<std::string>* divideArgumentList(std::string& src) { std::vector<std::string>* result = new std::vector<std::string>(); if(src.empty()){ return result; } std::string::iterator begin = src.begin(); std::string::iterator end = src.end(); std::string tmp; while(begin != end) { if(*begin == '"') { begin++; while(true) { if(*begin == '"') { begin++; break; } if(begin == end) { delete result; throw std::runtime_error("Double quote error"); } if(*begin == '\\') { tmp.append(1,*begin); begin++; if(begin == end) { delete result; throw std::runtime_error("Escape sequence error"); } } tmp.append(1,*begin); begin++; } } if(*begin == ' ') { result->push_back(tmp); tmp.clear(); while(*begin == ' ') { begin++; } begin--; } else { tmp.append(1,*begin); } begin++; } if(tmp.length() != 0) { result->push_back(tmp); } #ifdef DEBUG { std::cout << src << std::endl; std::vector<std::string>::iterator begin = result->begin(); std::vector<std::string>::iterator end = result->end(); for(; begin != end; begin++) { std::cout << *begin << std::endl; } } #endif return result; } }
true
fd913b82c5cfc64cc50039d5b9809d24a060710d
C++
songchengjiang/Lutra
/runtime/Lutra/Resources/Mesh.cpp
UTF-8
2,570
2.640625
3
[]
no_license
// // Mesh.cpp // Lutra // // Created by JasonCheng on 2021/1/4. // #include "Mesh.h" #include "Stream.h" namespace Lutra { void Mesh::Serialize(WriteStream& stream) { Resource::Serialize(stream); stream.WriteValue("Vertices", Vertices); if (!Normals.empty()) stream.WriteValue("Normals", Normals); if (!Tangents.empty()) stream.WriteValue("Tangents", Tangents); if (!Colors.empty()) stream.WriteValue("Colors", Colors); if (!Texcoord0.empty()) stream.WriteValue("Texcoord0", Texcoord0); if (!Texcoord1.empty()) stream.WriteValue("Texcoord1", Texcoord1); stream.BeginArray("SubMeshes"); for (auto &subMesh : SubMeshList) { stream.BeginMap(""); stream.WriteValue("PrimitiveType", (int)subMesh.Type); stream.WriteValue("MaterialID", subMesh.MaterialIndex); stream.WriteValue("Indices", subMesh.Indices); stream.BeginMap("BoundingBox"); stream.WriteValue("Min", subMesh.BBox.Min()); stream.WriteValue("Max", subMesh.BBox.Min()); stream.EndMap(); stream.EndMap(); } stream.EndArray(); } void Mesh::Deserialize(ReadStream& stream) { Resource::Deserialize(stream); stream.ReadValue("Vertices", Vertices); if (stream.HasValue("Normals")) stream.ReadValue("Normals", Normals); if (stream.HasValue("Tangents")) stream.ReadValue("Tangents", Tangents); if (stream.HasValue("Colors")) stream.ReadValue("Colors", Colors); if (stream.HasValue("Texcoord0")) stream.ReadValue("Texcoord0", Texcoord0); if (stream.HasValue("Texcoord1")) stream.ReadValue("Texcoord1", Texcoord1); size_t size = stream.BeginArray("SubMeshes"); SubMeshList.resize(size); for (size_t i = 0; i < size; ++i) { stream.EnterArray(i); int type; stream.ReadValue("PrimitiveType", type); SubMeshList[i].Type = (PrimitiveType)type; stream.ReadValue("MaterialID", SubMeshList[i].MaterialIndex); stream.ReadValue("Indices", SubMeshList[i].Indices); stream.BeginMap("BoundingBox"); stream.ReadValue("Min", SubMeshList[i].BBox.Min()); stream.ReadValue("Max", SubMeshList[i].BBox.Max()); stream.EndMap(); stream.LeaveArray(); } stream.EndArray(); } }
true
3c144ae39cbe62ee6d91802fb3f62809fca47da5
C++
kioco/Benchmark
/Network/client.cpp
UTF-8
6,109
2.625
3
[]
no_license
#include <string.h> #include <cstring> #include <unistd.h> #include <stdio.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <pthread.h> #include <strings.h> #include <stdlib.h> #include <string> #include <ctime> #include <time.h> #include <vector> #define SERVER "192.x.x.x" using namespace std; void * threadit(void * ); int portNo,proto,port2,i2; int main (int argc, char* argv[]) { bool loop = false; pthread_t threads[4]; int n,s[4] = {0,1,2,3}; if(argc < 3) { cerr<<"Syntax : ./client <port> <buffer_size>"<<endl; return 0; } port2 = atoi(argv[1]); cout<<"ENTER THE COMMUNICATION PROTOCOL TO CHOOSE FROM : "<<endl<<"1.TCP"<<endl<<"2.UDP"<<endl; cin>>proto; portNo = atoi(argv[2]); cout<<"ENTER THE NUMER OF THREADS TO EXECUTE"<<endl; cin>>n; for( i2=0;i2<n;i2++) pthread_create(&(threads[i2]), NULL, threadit,&s[i2] ); for( i2=0;i2<n;i2++) pthread_join(threads[i2],NULL); } void * threadit(void * dums) { double time_spent; double begin,end; struct sockaddr_in svrAdd; int checker; int listenFd; int* num1 = (int *)dums; int num2 = *num1; cout<<num2<<endl; int i,mem; //create client skt if(proto == 1) { listenFd = socket(AF_INET, SOCK_STREAM, 0); if(listenFd < 0) { cerr << "Cannot open socket" << endl; return 0; } bzero((char *) &svrAdd, sizeof(svrAdd)); svrAdd.sin_family = AF_INET; svrAdd.sin_addr.s_addr= INADDR_ANY; svrAdd.sin_port = htons(port2+num2); checker = connect(listenFd,(struct sockaddr *) &svrAdd, sizeof(svrAdd)); if (checker < 0) { cerr << "Cannot connect!" << endl; return 0; } else { if(portNo == 1) { char s[8]; for( i=0;i<8;i++) s[i] = i; cout<<"SELECTED MEMORY RANGE FOR DUPLEX TRANSMISSIONS"<<endl<<"1 byte"<<endl; begin =(double) clock(); for(int j=0;j<5000;j++) for(int i=0;i<1024;i++) { write(listenFd, s, 8); read(listenFd, s, 8); //cout<<i; } end = (double) clock(); time_spent = (end -begin)/CLOCKS_PER_SEC; cout<<"Total Time consumed for duplex transmission: "<<time_spent<<endl; cout<<"SPEED = "<< (1024/(time_spent+0.000000))<<"MB/SEC"<<endl; } else if(portNo == 2) { char s1[1024]; for( i=0;i<1024;i++) s1[i] = i; cout<<"SELECTED MEMORY RANGE FOR DUPLEX TRANSMISSIONS"<<endl<<"1 kilo byte"<<endl; //write(listenFd,(void *)&k,1); begin = (double) clock(); for(int j =0 ;j<512;j++) for(i=0;i<1024;i++) { write(listenFd, s1, 1024); read(listenFd, s1, 1024); //cout<<i; } end = (double) clock(); time_spent = (double) (end-begin)/CLOCKS_PER_SEC; cout<<"Total Time consumed for duplex transmission:"<<time_spent<<endl; cout<<"SPEED = "<<((1024/(time_spent)))<<"MB/SEC"<<endl; } else if(portNo == 3) { char s2[6144]; for( i=0;i<6144;i++) s2[i] = i; cout<<"SELECTED MEMORY RANGE FOR DUPLEX TRANSMISSIONS 1 mega byte"<<endl; begin = (double) clock(); for(i=0;i<7;i++) for(int j=0;j<1020;j++) { write(listenFd, s2, 6144); read(listenFd,s2,6144); //cout<<i; } end = (double) clock(); cout<<portNo<<endl; time_spent = (double) (end-begin)/CLOCKS_PER_SEC; cout<<"Total Time consumed for duplex transmission:"<<time_spent<<endl; cout<<"SPEED = "<< (1024/(time_spent+0.00000))<<"MB/SEC"<<endl; } else { cout<<"INVALID OPTION"<<endl; }close(listenFd); } } else if(proto == 2) { //struct sockaddr_in udp_other; size_t len = sizeof(svrAdd); listenFd = socket(AF_INET, SOCK_DGRAM, 0); bzero((char *) &svrAdd, sizeof(svrAdd)); svrAdd.sin_family = AF_INET; svrAdd.sin_addr.s_addr= htonl(INADDR_ANY); svrAdd.sin_port = htons(port2+num2); //if (inet_aton(SERVER , &svrAdd.sin_addr) == 0) // Create datagram with server IP and port. //{ // cerr<<"inet_aton() failed"<<endl; // exit(1); //} if(portNo == 1) { char s[8]; for( i=0;i<8;i++) s[i] = i; cout<<"SELECTED MEMORY RANGE FOR DUPLEX TRANSMISSIONS"<<endl<<"1 byte"<<endl; begin = (double) clock(); for(int j=0;j<50000;j++) for(int i=0;i<1024;i++) { sendto(listenFd,s,8,0,(struct sockaddr *)&svrAdd,len); recvfrom(listenFd,s,8,0,(struct sockaddr *)&svrAdd,&len); //cout<<i; } end = (double) clock(); time_spent = (end -begin)/CLOCKS_PER_SEC; cout<<"Total Time consumed for duplex transmission: 0sec"<<endl; cout<<"SPEED = "<< (1024/(time_spent+0.000000)) <<"MB/SEC"<<endl; } else if(portNo == 2) { char s1[1024]; for( i=0;i<1024;i++) s1[i] = i; cout<<"SELECTED MEMORY RANGE FOR DUPLEX TRANSMISSIONS"<<endl<<"1 kilo byte"<<endl; //write(listenFd,(void *)&k,1); begin = (double) clock(); for(int j =0 ;j<512;j++) for(i=0;i<1024;i++) { sendto(listenFd,s1,1024,0,(struct sockaddr *)&svrAdd,len); recvfrom(listenFd,s1,1024,0,(struct sockaddr *)&svrAdd,&len); } end = (double) clock(); time_spent = (double) (end-begin)/CLOCKS_PER_SEC; cout<<"Total Time consumed for duplex transmission:"<<time_spent<<endl; cout<<"SPEED = "<<((1024/(time_spent)))<<"MB/SEC"<<endl; } else if(portNo == 3) { char s2[6144]; for( i=0;i<6144;i++) s2[i] = i; cout<<"SELECTED MEMORY RANGE FOR DUPLEX TRANSMISSIONS 1 mega byte"<<endl; begin = (double) clock(); for(i=0;i<7;i++) for(int j=0;j<1020;j++) { sendto(listenFd,s2,6144,0,(struct sockaddr *)&svrAdd,len); recvfrom(listenFd,s2,6144,0,(struct sockaddr *)&svrAdd,&len); //cout<<i; } end = (double) clock(); time_spent = (double) (end-begin)/CLOCKS_PER_SEC; cout<<"Total Time consumed for duplex transmission:"<<time_spent<<endl; cout<<"SPEED = "<< (1024/(time_spent+0.00000))<<"MB/SEC"<<endl; } else { cout<<"INVALID OPTION"<<endl; }close(listenFd); } else cout<<"INVALID OPTION"<<endl; }
true
77e16d50d6010bc47bec2932a5e30050bfc8505b
C++
lucasfranklin/Programacao-Orientada-a-Objetos
/C++/TP4/2.2/include/Matriz.h
UTF-8
16,538
3.0625
3
[]
no_license
#ifndef MATRIZ_H #define MATRIZ_H #include <string> #include <vector> #include <fstream> #include <algorithm> #include <iostream> #include "CVetor.h" #include "ETamMatrix.h" #include "ECompMatrix.h" #include "EPosMatrix.h" using namespace DataStructures; namespace Matematica { template <class T> class Matriz { private: T **matrix = NULL; //Matriz int numRows; //Numero de linhas int numColumns; //Numero de colunas public: Matriz(const int rows = 0,const int columns = 0):numRows(rows), numColumns(columns) { initializeMatrix(); }; //Construtor convencional Matriz(const std::string fileName); //Construtor a partir de um arquivo Matriz(const Matriz& copyObject); //Construtor de copia bool printMatrix() const; //Imprime matriz void printMatrix(const Matriz copyObject) const; //Sobrecarga do printMatrix, somente para teste void grava(const std::string& fileName) const; ~Matriz(); //Sobrecarga de Operadores const Matriz operator+ (const Matriz& sumMatrix) const; const Matriz operator- (const Matriz& subMatrix) const; const Matriz operator* (const Matriz& multiMatrix) const; const Matriz operator* (const std::vector<T>& elements) const; const Matriz operator* (const DataStructures::CVetor& elements) const; const Matriz operator= (const Matriz& attMatrix); const Matriz operator+= (const Matriz& sumMatrix) const; const Matriz operator-= (const Matriz& subMatrix) const; const Matriz operator*= (const Matriz& multiMatrix); const Matriz operator*= (const std::vector<T>& elements); const Matriz operator*= (const DataStructures::CVetor& elements); T& operator()(const int i, const int j) const; template <class U> const friend std::ostream& operator<< (std::ostream& output, Matriz& flowOut); template <class U> const friend std::istream& operator>> (std::istream& input, Matriz& flowIn); const std::ostream& outstream(std::ostream& output); //----- class myIterator; myIterator begin(); myIterator end(); //Metodo para o iterator friend class myIterator; class myIterator { private: Matriz& mat; int Rows; //Numero de linhas int Columns; //Numero de colunas public: //Begin myIterator(Matriz& newMat) : mat(newMat), Rows(0), Columns(0) {} //End myIterator(Matriz& newMat, bool) : mat(newMat), Rows(mat.numRows), Columns(mat.numColumns) {} T& operator++(int); // i++ T& operator*() const; T& operator++(); // ++i myIterator& operator+=(int amount); bool operator==(const myIterator& comp) const; myIterator& operator= (myIterator& comp); bool operator!=(const myIterator& comp); friend std::ostream& operator<<(std::ostream& os, const myIterator& it) { return os << *it; } }; private: void initializeMatrix(); bool allocMatrix(); void freeMatrix(); }; //--------------------ITERATOR-------------------- template <class T> T& Matriz<T>::myIterator::operator++(int) // i++ { T aux = mat.matrix[Rows][Columns++]; if(Columns==mat.numColumns) { Columns = 0; Rows++; } return aux; } template <class T> T& Matriz<T>::myIterator::operator*() const { return mat.matrix[Rows][Columns]; } template <class T> T& Matriz<T>::myIterator::operator++() // ++i { T aux = mat.matrix[Rows][Columns++]; if(Columns==mat.numColumns) { Columns = 0; Rows++; } return aux; } template <class T> typename Matriz<T>::myIterator& Matriz<T>::myIterator::operator+=(int amount) { if(Columns + amount >= mat.numColumns*mat.numRows) { return *this; } Columns += amount; if(Columns >= mat.numColumns) { int position = Columns; while(position >= mat.numColumns) { position = position - mat.numColumns; Rows++; } Columns = position; } else { Rows = 0; } return *this; } template <class T> bool Matriz<T>::myIterator::operator==(const myIterator& comp) const { return (Rows==comp.Rows && Columns==comp.Columns); } template <class T> typename Matriz<T>::myIterator& Matriz<T>::myIterator::operator= (myIterator& comp) { mat = comp.mat; Columns = comp.Columns; Rows = comp.Rows; return *this; } template <class T> bool Matriz<T>::myIterator::operator!=(const myIterator& comp) { return ((Rows!=comp.Rows) && (Columns!=comp.Columns)); } //--------------------FIM ITERATOR-------------------- //Constroi a matriz a partir de um arquivo template <class T> Matriz<T>::Matriz(const std::string fileName) { int rows, columns; std::ifstream inFile(fileName.c_str()); if(inFile) //Se o arquivo existir, prossegue com a criacao { inFile >> rows >> columns; numRows = rows; numColumns = columns; if(rows !=0 && columns != 0) //Se o numero de linhas e colunas for diferente de 0, prossegue com a criacao { if(allocMatrix()) //Se a alocacao ocorreu corretamente { for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { inFile >> matrix[i][j]; //Atribui a matriz os valores do arquivo } } } } inFile.close(); //Fecha o arquivo } else std::cout << "Arquivo nao encontrado"; //Se o arquivo nao existir exibe a frase } //Construtor de copia template <class T> Matriz<T>::Matriz(const Matriz& copyObject) { numRows = copyObject.numRows; numColumns = copyObject.numColumns; allocMatrix(); for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { matrix[i][j] = copyObject.matrix[i][j]; } } } //Aloca a matriz template <class T> void Matriz<T>::initializeMatrix() { if(numRows !=0 && numColumns != 0) //Procede com a construcao apenas se o numero de linhas e colunas for diferente de 0 { if(allocMatrix()) //Se a alocacao ocorrer { for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { matrix[i][j] = 0; //Inicializa a matriz com 0's } } } } } template <class T> bool Matriz<T>::allocMatrix() { matrix = new T*[numRows]; for(int i = 0; i<numRows; i++) { matrix[i] = new T[numColumns]; } //Se alocado retorna TRUE, senao retorna FALSE if(matrix == NULL) return false; else return true; } //Desaloca a matriz template <class T> void Matriz<T>::freeMatrix() { if(matrix) { for(int i = 0; i<numRows; i++) { if(matrix[i]) delete[] matrix[i]; } delete matrix; } } //Grava dados da matriz em um arquivo template <class T> void Matriz<T>::grava(const std::string& fileName) const { if(matrix) { std::ofstream outFile(fileName.c_str()); outFile << numRows << " " << numColumns << std::endl << std::endl; for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { outFile << matrix[i][j] << " "; } outFile << std::endl; } outFile.close(); } } //Imprime a matriz template <class T> bool Matriz<T>::printMatrix() const { if(matrix) { for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { std::cout << matrix[i][j] << " "; } std::cout << std::endl; } } else return false; return true; } //Sobrecarrega o operador de atribuicao template <class T> const Matriz<T> Matriz<T>::operator= (const Matriz& attMatrix) { if(this == &attMatrix) return *this; numColumns = attMatrix.numColumns; numRows = attMatrix.numRows; allocMatrix(); for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { matrix[i][j] = attMatrix.matrix[i][j]; } } return *this; } //Sobrecarga de operador para acesso direto aos elementos da matriz template <class T> T& Matriz<T>::operator()(const int i, const int j) const { if(i>=numRows || j>=numColumns) throw(EPosMatrix(__LINE__)); return matrix[i][j]; } //Sobrecarga do operador de adicao, soma duas matrizes de mesmo tamanho template <class T> const Matriz<T> Matriz<T>::operator+ (const Matriz<T>& sumMatrix) const { if((numRows != sumMatrix.numRows) || (numColumns != sumMatrix.numColumns)) throw (ETamMatrix(__LINE__)); Matriz resultMatrix(numRows, numColumns); for(int i = 0; i<numRows; i++) for(int j = 0; j<numColumns; j++) resultMatrix.matrix[i][j] = matrix[i][j]+sumMatrix(i,j); return resultMatrix; return NULL; } //Sobrecarga do operador de atribuicao com adicao direta, soma a matriz atual com outra, se forem do mesmo tamanho template <class T> const Matriz<T> Matriz<T>::operator+= (const Matriz<T>& sumMatrix) const { if((numRows != sumMatrix.numRows) || (numColumns != sumMatrix.numColumns)) throw (ETamMatrix(__LINE__)); for(int i = 0; i<numRows; i++) for(int j = 0; j<numColumns; j++) matrix[i][j] += sumMatrix(i,j); return *this; } //Sobrecarga do operador de subtracao, subtrai duas matrizes de mesmo tamanho template <class T> const Matriz<T> Matriz<T>::operator- (const Matriz& subMatrix) const { if((numRows != subMatrix.numRows) || (numColumns != subMatrix.numColumns)) throw (ETamMatrix(__LINE__)); Matriz resultMatrix(numRows, numColumns); for(int i = 0; i<numRows; i++) for(int j = 0; j<numColumns; j++) resultMatrix.matrix[i][j] = matrix[i][j]-subMatrix(i,j); return resultMatrix; } //Sobrecarga do operador de atribuicao com subtracao direta, subtrai a matriz atual com outra, se forem do mesmo tamanho template <class T> const Matriz<T> Matriz<T>::operator-= (const Matriz& subMatrix) const { if((numRows != subMatrix.numRows) || (numColumns != subMatrix.numColumns)) throw (ETamMatrix(__LINE__)); for(int i = 0; i<numRows; i++) for(int j = 0; j<numColumns; j++) matrix[i][j] -= subMatrix(i,j); return *this; } //Sobrecarga do operador de multiplicacao, multiplica duas matrizes, se compativel template <class T> const Matriz<T> Matriz<T>::operator* (const Matriz& multiMatrix) const { if(numColumns != multiMatrix.numRows) throw (ECompMatrix(__LINE__)); Matriz resultMatrix(numRows, multiMatrix.numColumns); T sum = 0; for(int i=0; i<numRows; i++) { for(int j=0; j<multiMatrix.numColumns; j++) { for(int k=0; k<multiMatrix.numRows; k++) { sum += matrix[i][k] * multiMatrix(k,j); } resultMatrix.matrix[i][j] = sum; sum = 0; } } return resultMatrix; } //Sobrecarga do operador de atribuicao com multiplicacao direta, multiplica a matriz atual com outra, se forem compativel template <class T> const Matriz<T> Matriz<T>::operator*= (const Matriz& multiMatrix) { if(numColumns != multiMatrix.numRows) throw (ECompMatrix(__LINE__)); T sum = 0; Matriz auxMatrix(numRows, multiMatrix.numColumns); for(int i=0; i<numRows; i++) { for(int j=0; j<multiMatrix.numColumns; j++) { for(int k=0; k<multiMatrix.numRows; k++) { sum += matrix[i][k] * multiMatrix(k,j); } auxMatrix.matrix[i][j] = sum; sum = 0; } } freeMatrix(); numRows = auxMatrix.numRows; numColumns = multiMatrix.numColumns; allocMatrix(); matrix = auxMatrix.matrix; return *this; } //Sobrecarga do operador de multiplicacao, multiplica uma matriz por um vetor, se compativel template <class T> const Matriz<T> Matriz<T>::operator* (const std::vector<T>& elements) const { if(numColumns!=elements.size()) throw (ECompMatrix(__LINE__)); T elementsSum = 0; Matriz resultMatrix(numRows,1); for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { elementsSum += matrix[i][j]*elements[j]; } resultMatrix.matrix[i][0] = elementsSum; elementsSum = 0; } return resultMatrix; } //Sobrecarga do operador de multiplicacao, multiplica uma matriz por um CVetor, se compativel template <class T> const Matriz<T> Matriz<T>::operator* (const CVetor& elements) const { int elementSize = elements.getSize(); if(numColumns==elementSize) throw (ECompMatrix(__LINE__)); T elementsSum = 0; Matriz resultMatrix(numRows,1); for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { elementsSum += matrix[i][j]*elements[j]; } resultMatrix.matrix[i][0] = elementsSum; elementsSum = 0; } return resultMatrix; } //Sobrecarga do operador de atribuicao com multiplicacao direta, multiplica a matriz atual com um vetor, se forem compativel template <class T> const Matriz<T> Matriz<T>::operator*= (const std::vector<T>& elements) { if(numColumns==elements.size()) throw (ECompMatrix(__LINE__)); T elementsSum = 0; Matriz auxMatrix(numRows, 1); for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { elementsSum += matrix[i][j]*elements[j]; } auxMatrix.matrix[i][0] = elementsSum; elementsSum = 0; } freeMatrix(); numRows = auxMatrix.numRows; numColumns = 1; allocMatrix(); matrix = auxMatrix.matrix; return *this; } //Sobrecarga do operador de atribuicao com multiplicacao direta, multiplica a matriz atual com um CVetor, se forem compativel template <class T> const Matriz<T> Matriz<T>::operator*= (const CVetor& elements) { int elementSize = elements.getSize(); if(numColumns==elementSize) throw (ECompMatrix(__LINE__)); T elementsSum = 0; Matriz auxMatrix(numRows, 1); for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { elementsSum += matrix[i][j]*elements[j]; } auxMatrix.matrix[i][0] = elementsSum; elementsSum = 0; } freeMatrix(); numRows = auxMatrix.numRows; numColumns = 1; allocMatrix(); matrix = auxMatrix.matrix; return *this; } //Sobrecarga do operator de fluxo de saida template <class T> const std::ostream& operator<<(std::ostream& output, Matriz<T>& flowOut) { return flowOut.outstream(output); } template <class T> const std::ostream& Matriz<T>::outstream(std::ostream& output) { for(int i = 0; i<numRows; i++) { for(int j = 0; j<numColumns; j++) { output << matrix[i][j] << " "; } output << std::endl; } output << std::endl; return output; } //Sobrecarga do operador de fluxo de entrada template <class T> const std::istream& operator>>(std::istream& input, Matriz<T>& flowIn) { input >> flowIn.numRows >> flowIn.numColumns; if(flowIn.numRows !=0 && flowIn.numColumns != 0) //Se o numero de linhas e colunas for diferente de 0, prossegue com a criacao { if(flowIn.allocMatrix()) //Se a alocacao ocorreu corretamente { for(int i = 0; i<flowIn.numRows; i++) { for(int j = 0; j<flowIn.numColumns; j++) { input >> flowIn.matrix[i][j]; //Atribui a matriz os valores do arquivo } } } } } template <class T> typename Matriz<T>::myIterator Matriz<T>::begin() { return myIterator(*this); } template <class T> typename Matriz<T>::myIterator Matriz<T>::end() { return myIterator(*this, true); } //Destrutor template <class T> Matriz<T>::~Matriz() { freeMatrix(); } } template <typename Iterator> Iterator maxValue(Iterator begin, Iterator end) { Iterator be = begin; Iterator maximo = begin; while(be != end) { if((be++) > *maximo) { maximo = be; } } return maximo; } #endif // MATRIZ_H
true
d54d6261f8c86edfbe04715ecaac2dff324143d0
C++
EagleCarlton/linked_list
/Node.cpp
UTF-8
679
3.296875
3
[]
no_license
#include "stdafx.h" #include "Node.h" Node *Get_node(Type item, Node *prev0, Node *next0) {//生成一个节点,返回此节点指针 Node *p; p = (Node*)malloc(sizeof(Node)); if (p == NULL) { printf("Memory allocation failure!"); exit(1); } p->data = item; p->prev = prev0; p->next = next0; return p; } Type Get_data(Node *current) {//取节点中data成员的值 return current->data; } Node *Get_prev(Node *current) {//取节点中prev成员的值 return current->prev; } Node *Get_next(Node *current) {//取节点中next成员的值 return current->next; } void Set_data(Node *current, Type item) {//给节点中的data成员赋值 current->data = item; }
true
5d0a2e8ceed7cb0991e09e45a8338495240f6321
C++
mendsley/sched
/src/sema.cpp
UTF-8
3,648
2.546875
3
[ "BSD-2-Clause" ]
permissive
/** * Copyright 2015-2017 Matthew Endsley * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted providing that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <atomic> #include <cstdint> #include <mutex> #include "private.h" #include "sched/scheduler.h" #include "sched/sema.h" using namespace sched; namespace { struct Waiter { Waiter* next; Task* owner; Sema* sema; }; struct Root { std::mutex lock; Waiter* head = nullptr; std::atomic<uint32_t> waiters = ATOMIC_VAR_INIT(0); }; } // namesapce `anonymous' static constexpr uintptr_t c_rootTableSize = 251; static Root g_roots[c_rootTableSize]; static Root* rootFromAddr(const void* addr) { const uintptr_t index = (reinterpret_cast<uintptr_t>(addr) / 8) % c_rootTableSize; return &g_roots[index]; } static bool tryAcquire(std::atomic<uint32_t>* sem) { uint32_t value = sem->load(); for (;;) { if (0 == value) { return false; } else if (sem->compare_exchange_weak(value, value - 1)) { return true; } } } void sched::Sema::acquire() { // handle the easy, non-contended case if (tryAcquire(&s)) { return; } Task* task = currentTask(); Root* root = rootFromAddr(this); for (;;) { root->lock.lock(); // add ourselves to the tasks waiting on this root root->waiters.fetch_add(1); // acquired inbetween lock states if (tryAcquire(&s)) { root->waiters.fetch_sub(1); root->lock.unlock(); break; } // wait to be notified Waiter w; w.next = root->head; w.owner = task; w.sema = this; root->head = &w; suspendWithUnlock(task, [](void* context) { Root* root = static_cast<Root*>(context); root->lock.unlock(); }, root); if (tryAcquire(&s)) { // wait count decremented by Sema::release break; } } } bool sched::Sema::try_acquire() { return tryAcquire(&s); } void sched::Sema::release() { Root* root = rootFromAddr(this); s.fetch_add(1); // easy, no waiters path for this root if (0 == root->waiters.load()) { return; } Waiter* toAwake = nullptr; { std::unique_lock<std::mutex> lock(root->lock); if (0 == root->waiters.load()) { // another semaphore cleared all the waiters return; } // find a task waiting on this semaphore Waiter** prev = &root->head; for (Waiter* w = root->head; w; prev = &w->next, w = w->next) { if (w->sema == this) { root->waiters.fetch_sub(1); toAwake = w; // unlink w *prev = w->next; break; } } } if (toAwake) { wake(toAwake->owner); } }
true
32a2e15da7ff6aacece6fe2284cca0aa071e4eb1
C++
Karun842002/Algos-for-Amigos
/Computer_Science/2_Competitive_Programming/Leetcode/p08_pascal_Triangle.cpp
UTF-8
1,036
3.765625
4
[ "MIT" ]
permissive
/* Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it Example: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] */ #include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> pascal = {{1}}; for(int i = 1; i < numRows; i++) { vector<int> row = {1}; int prevRowLen = pascal[i-1].size(); for(int j = 1; j < prevRowLen; j++) { row.push_back(pascal[i-1][j-1] + pascal[i-1][j]); } row.push_back(1); pascal.push_back(row); } return pascal; } }; int main() { int n; cin >> n; Solution sol; vector<vector<int>> res; res = sol.generate(n); for(auto i : res) { for(auto j : i) { cout << j << " "; } cout << "\n"; } return 0; }
true
83eb68ef11292a17d5b3e79d99220b145e9cff94
C++
21901040/nowic
/labs/lab7/quick.cpp
UTF-8
3,427
3.421875
3
[]
no_license
// quicksort algorithm // // A quicksort algorithm - its time complexity is O(n^2). // 2019/02/02: Created by idebtor@gmail.com // 2021/01/02: Testing added, updated c++11 and documented // 2021/01/20: partition_lo() partition_hi() added // now, the pivot can be either the first or the last element. // 2021/01/20: comparator default argument added // // To build and run, // Set #if 1 to activate main() function at the bottom of the file first. // > g++ -std=c++11 quick.cpp -o quick // > ./quick // // To use DEBUG or test it, compile with -D option and turn #if 1 on. // Then build it with -D option run it as shown below: // > g++ -std=c++11 -DDEBUG quick.cpp -o quick // > ./quick // // To add this function to a static library libsort.a, // 1. set #if 0 to deactivate main() function at the bottom of the file first. // 2. compile first to produce ~.o file. // 3. add it to libsort.a as shown below. // > g++ -std=c++11 -c quick.cpp # produce quick.o // > ar r libsort.a quick.o # insert or update quick.o in libsort.a // > ar t libsort.a # show objects in libsort.a #include <iostream> using namespace std; #ifdef DEBUG #define DPRINT(func) func; #else #define DPRINT(func) ; #endif // This function takes last element as pivot, places the pivot element at its // correct position in sorted array, and places all smaller (smaller than pivot) // to left of pivot and all greater elements to right of pivot */ int partition(int list[], int lo, int hi) { DPRINT(cout << "partition pivot:" << list[hi] << " ";); int pivot = list[hi]; // pivot value int i = (lo - 1); // Index of smaller element for (int j = lo; j <= hi - 1; j++) { if (list[j] <= pivot) { // if current element is <= pivot i++; // increment index of smaller element swap(list[j], list[i]); // swap current element with index } } swap(list[hi], list[i + 1]); DPRINT(cout << ".... is now in place at list[" << i + 1 << "]\n";); return (i + 1); // returns the new pivot index which it is now in place or sorted. } // quicksort helper function for recursive operation // list[]: array to be sorted, lo: Starting index, h: Ending index // N is added only for debugging or DPRINT void quicksort(int *list, int lo, int hi, int n) { if (lo < hi) { int pi = partition(list, lo, hi); // pi: pivot index DPRINT(cout << "\npivot(" << pi << ")=" << list[pi] << " LEFT\n";); quicksort(list, lo, pi - 1, n); DPRINT(cout << "\npivot(" << pi << ")=" << list[pi] << " RIGHT\n";); quicksort(list, pi + 1, hi, n); } } void quicksort(int *a, int n, bool (*comp)(int, int)) { DPRINT(cout << "QUICK SORTING...\n"); quicksort(a, 0, n - 1, n); // the last argument n is added only for DPRINT() } #if 1 #include "sort.h" int main() { int list[] = { 54, 26, 93, 17, 77, 31, 44, 55, 20 }; int N = sizeof(list) / sizeof(list[0]); cout << "UNSORTED: " << endl; for (auto x: list) cout << x << " "; cout << endl << endl; quicksort(list, N); cout << "QUICK SORTED: " << endl; for (auto x: list) cout << x << " "; cout << endl << endl; // Uncomment the next line and modify the code above to make it work. quicksort(list, N, more); cout << "QUICK SORTED using more fp: " << endl; // Using printlist() printlist(list, N); // for (auto x: list) cout << x << " "; // cout << endl << endl; cout << "Happy Coding~~"; return 0; } #endif
true
70410d1aab3db3d5395fa048c22710854d4ddc2a
C++
xiaochuanle/lesv
/src/ncbi_blast/str_util/str_cmp.hpp
UTF-8
22,060
2.765625
3
[]
no_license
#ifndef __STR_CMP_HPP #define __STR_CMP_HPP #include "../ncbi_blast_aux.hpp" #include "tempstr.hpp" BEGIN_HBNSTR_SCOPE using namespace ncbi; int strcmp(const char* s1, const size_t n1, const char* s2, const size_t n2, ECase use_case = ECase::eCase); // NOTE. On some platforms, "strn[case]cmp()" can work faster than their // "Compare***()" counterparts. /// String compare. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - 0, if s1 == s2. /// - Negative integer, if s1 < s2. /// - Positive integer, if s1 > s2. /// @sa /// strncmp(), strcasecmp(), strncasecmp() int strcmp(const char* s1, const char* s2); /// String compare up to specified number of characters. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @param n /// Number of characters in string /// @return /// - 0, if s1 == s2. /// - Negative integer, if s1 < s2. /// - Positive integer, if s1 > s2. /// @sa /// strcmp(), strcasecmp(), strncasecmp() int strncmp(const char* s1, const char* s2, size_t n); /// Case-insensitive comparison of two zero-terminated strings. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - 0, if s1 == s2. /// - Negative integer, if s1 < s2. /// - Positive integer, if s1 > s2. /// @sa /// strcmp(), strncmp(), strncasecmp() int strcasecmp(const char* s1, const char* s2); /// Case-insensitive comparison of two zero-terminated strings, /// narrowed to the specified number of characters. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - 0, if s1 == s2. /// - Negative integer, if s1 < s2. /// - Positive integer, if s1 > s2. /// @sa /// strcmp(), strcasecmp(), strcasecmp() int strncasecmp(const char* s1, const char* s2, size_t n); /// Check if a string is blank (has no text). /// /// @param str /// String to check. /// @param pos /// starting position (default 0) bool IsBlank(const CTempString str, SIZE_TYPE pos = 0); /// Checks if all letters in the given string have a lower case. /// /// @param str /// String to be checked. /// @return /// TRUE if all letter characters in the string are lowercase /// according to the current C locale (std::islower()). /// All non-letter characters will be ignored. /// TRUE if empty or no letters. bool IsLower(const CTempString str); /// Checks if all letters in the given string have a upper case. /// /// @param str /// String to be checked. /// @return /// TRUE if all letter characters in the string are uppercase /// according to the current C locale (std::isupper()). /// All non-letter characters will be skipped. /// TRUE if empty or no letters. bool IsUpper(const CTempString str); // The following 4 methods change the passed string, then return it /// Convert string to lower case -- string& version. /// /// @param str /// String to be converted. /// @return /// Lower cased string. string& ToLower(string& str); /// Convert string to lower case -- char* version. /// /// @param str /// String to be converted. /// @return /// Lower cased string. char* ToLower(char* str); /// Convert string to upper case -- string& version. /// /// @param str /// String to be converted. /// @return /// Upper cased string. string& ToUpper(string& str); /// Convert string to upper case -- char* version. /// /// @param str /// String to be converted. /// @return /// Upper cased string. char* ToUpper(char* str); /// Case-sensitive compare of two strings -- char* version. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - 0, if s1 == s2. /// - Negative integer, if s1 < s2. /// - Positive integer, if s1 > s2. /// @sa /// CompareNocase(), Compare() versions with same argument types. int CompareCase(const char* s1, const char* s2); /// Case-sensitive compare of two strings -- CTempStringEx version. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - 0, if s1 == s2. /// - Negative integer, if s1 < s2. /// - Positive integer, if s1 > s2. /// @sa /// CompareNocase(), Compare() versions with same argument types. int CompareCase(const CTempStringEx s1, const CTempStringEx s2); /// Case-insensitive compare of two strings -- char* version. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - 0, if s1 == s2 (case-insensitive compare). /// - Negative integer, if s1 < s2 (case-insensitive compare). /// - Positive integer, if s1 > s2 (case-insensitive compare). /// @sa /// CompareCase(), Compare() versions with same argument types. int CompareNocase(const char* s1, const char* s2); /// Case-insensitive compare of two strings -- CTempStringEx version. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - 0, if s1 == s2 (case-insensitive compare). /// - Negative integer, if s1 < s2 (case-insensitive compare). /// - Positive integer, if s1 > s2 (case-insensitive compare). /// @sa /// CompareCase(), Compare() versions with same argument types. int CompareNocase(const CTempStringEx s1, const CTempStringEx s2); /// Compare two strings -- char* version. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @param use_case /// Whether to do a case sensitive compare(default is eCase), or a /// case-insensitive compare (eNocase). /// @return /// - 0, if s1 == s2. /// - Negative integer, if s1 < s2. /// - Positive integer, if s1 > s2. /// @sa /// Other forms of overloaded Compare() with differences in argument /// types: char* vs. CTempString[Ex] int Compare(const char* s1, const char* s2, ECase use_case = ECase::eCase); /// Compare two strings -- CTempStringEx version. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @param use_case /// Whether to do a case sensitive compare(default is eCase), or a /// case-insensitive compare (eNocase). /// @return /// - 0, if s1 == s2. /// - Negative integer, if s1 < s2. /// - Positive integer, if s1 > s2. /// @sa /// Other forms of overloaded Compare() with differences in argument /// types: char* vs. CTempString[Ex] int Compare(const CTempStringEx s1, const CTempStringEx s2, ECase use_case = ECase::eCase); /// Case-sensitive equality of two strings -- char* version. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - true, if s1 equals s2 /// - false, otherwise /// @sa /// EqualCase(), Equal() versions with same argument types. bool EqualCase(const char* s1, const char* s2); /// Case-sensitive equality of two strings. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - true, if s1 equals s2 /// - false, otherwise /// @sa /// EqualCase(), Equal() versions with same argument types. bool EqualCase(const CTempStringEx s1, const CTempStringEx s2); /// Case-insensitive equality of two strings -- char* version. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - true, if s1 equals s2 (case-insensitive compare). /// - false, otherwise. /// @sa /// EqualCase(), Equal() versions with same argument types. bool EqualNocase(const char* s1, const char* s2); /// Case-insensitive equality of two strings. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @return /// - true, if s1 equals s2 (case-insensitive compare). /// - false, otherwise. /// @sa /// EqualCase(), Equal() versions with same argument types. bool EqualNocase(const CTempStringEx s1, const CTempStringEx s2); /// Test for equality of two strings -- char* version. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @param use_case /// Whether to do a case sensitive compare(default is eCase), or a /// case-insensitive compare (eNocase). /// @return /// - 0, if s1 == s2. /// - Negative integer, if s1 < s2. /// - Positive integer, if s1 > s2. /// @sa /// EqualNocase(), Equal() versions with similar argument types. bool Equal(const char* s1, const char* s2, ECase use_case = ECase::eCase); /// Test for equality of two strings. /// /// @param s1 /// String to be compared -- operand 1. /// @param s2 /// String to be compared -- operand 2. /// @param use_case /// Whether to do a case sensitive compare(default is eCase), or a /// case-insensitive compare (eNocase). /// @return /// - true, if s1 equals s2. /// - false, otherwise. /// @sa /// EqualNocase(), Equal() versions with similar argument types. bool Equal(const CTempStringEx s1, const CTempStringEx s2, ECase use_case = ECase::eCase); /// Check if a string starts with a specified prefix value. /// /// @param str /// String to check. /// @param start /// Prefix value to check for. /// @param use_case /// Whether to do a case sensitive compare(default is eCase), or a /// case-insensitive compare (eNocase) while checking. bool StartsWith(const CTempString str, const CTempString start, ECase use_case = ECase::eCase); /// Check if a string starts with a specified character value. /// /// @param str /// String to check. /// @param start /// Character value to check for. /// @param use_case /// Whether to do a case sensitive compare(default is eCase), or a /// case-insensitive compare (eNocase) while checking. bool StartsWith(const CTempString str, char start, ECase use_case = ECase::eCase); /// Check if a string ends with a specified suffix value. /// /// @param str /// String to check. /// @param end /// Suffix value to check for. /// @param use_case /// Whether to do a case sensitive compare(default is eCase), or a /// case-insensitive compare (eNocase) while checking. bool EndsWith(const CTempString str, const CTempString end, ECase use_case = ECase::eCase); /// Check if a string ends with a specified character value. /// /// @param str /// String to check. /// @param end /// Character value to check for. /// @param use_case /// Whether to do a case sensitive compare(default is eCase), or a /// case-insensitive compare (eNocase) while checking. bool EndsWith(const CTempString str, char end, ECase use_case = ECase::eCase); ///////////////////////////////////////////////////////////////////////////// // Predicates // ///////////////////////////////////////////////////////////////////////////// /// /// Define Case-sensitive string comparison methods. /// /// Used as arguments to template functions for specifying the type of /// comparison. template <typename T> struct PCase_Generic { /// Return difference between "s1" and "s2". int Compare(const T& s1, const T& s2) const; /// Return TRUE if s1 < s2. bool Less(const T& s1, const T& s2) const; /// Return TRUE if s1 == s2. bool Equals(const T& s1, const T& s2) const; /// Return TRUE if s1 < s2. bool operator()(const T& s1, const T& s2) const; }; typedef PCase_Generic<std::string> PCase; typedef PCase_Generic<const char *> PCase_CStr; ///////////////////////////////////////////////////////////////////////////// /// /// Define Case-insensitive string comparison methods. /// /// Used as arguments to template functions for specifying the type of /// comparison. /// /// @sa PNocase_Conditional_Generic template <typename T> struct PNocase_Generic { /// Return difference between "s1" and "s2". int Compare(const T& s1, const T& s2) const; /// Return TRUE if s1 < s2. bool Less(const T& s1, const T& s2) const; /// Return TRUE if s1 == s2. bool Equals(const T& s1, const T& s2) const; /// Return TRUE if s1 < s2 ignoring case. bool operator()(const T& s1, const T& s2) const; }; typedef PNocase_Generic<std::string> PNocase; typedef PNocase_Generic<const char *> PNocase_CStr; ///////////////////////////////////////////////////////////////////////////// /// /// Define Case-insensitive string comparison methods. /// Case sensitivity can be turned on and off at runtime. /// /// Used as arguments to template functions for specifying the type of /// comparison. /// /// @sa PNocase_Generic template <typename T> class PNocase_Conditional_Generic { public: /// Construction PNocase_Conditional_Generic(NStr::ECase case_sens = NStr::ECase::eCase); /// Get comparison type NStr::ECase GetCase() const { return m_CaseSensitive; } /// Set comparison type void SetCase(NStr::ECase case_sens) { m_CaseSensitive = case_sens; } /// Return difference between "s1" and "s2". int Compare(const T& s1, const T& s2) const; /// Return TRUE if s1 < s2. bool Less(const T& s1, const T& s2) const; /// Return TRUE if s1 == s2. bool Equals(const T& s1, const T& s2) const; /// Return TRUE if s1 < s2 ignoring case. bool operator()(const T& s1, const T& s2) const; private: NStr::ECase m_CaseSensitive; ///< case sensitive when TRUE }; typedef PNocase_Conditional_Generic<std::string> PNocase_Conditional; typedef PNocase_Conditional_Generic<const char *> PNocase_Conditional_CStr; ///////////////////////////////////////////////////////////////////////////// // PCase_Generic:: // template <typename T> inline int PCase_Generic<T>::Compare(const T& s1, const T& s2) const { return NStr::Compare(s1, s2, NStr::ECase::eCase); } template <typename T> inline bool PCase_Generic<T>::Less(const T& s1, const T& s2) const { return Compare(s1, s2) < 0; } template <typename T> inline bool PCase_Generic<T>::Equals(const T& s1, const T& s2) const { return Compare(s1, s2) == 0; } template <typename T> inline bool PCase_Generic<T>::operator()(const T& s1, const T& s2) const { return Less(s1, s2); } //////////////////////////////////////////////////////////////////////////// // PNocase_Generic<T>:: // template <typename T> inline int PNocase_Generic<T>::Compare(const T& s1, const T& s2) const { return NStr::Compare(s1, s2, NStr::ECase::eNocase); } template <typename T> inline bool PNocase_Generic<T>::Less(const T& s1, const T& s2) const { return Compare(s1, s2) < 0; } template <typename T> inline bool PNocase_Generic<T>::Equals(const T& s1, const T& s2) const { return Compare(s1, s2) == 0; } template <typename T> inline bool PNocase_Generic<T>::operator()(const T& s1, const T& s2) const { return Less(s1, s2); } //////////////////////////////////////////////////////////////////////////// // PNocase_Conditional_Generic<T>:: // template <typename T> inline PNocase_Conditional_Generic<T>::PNocase_Conditional_Generic(NStr::ECase cs) : m_CaseSensitive(cs) {} template <typename T> inline int PNocase_Conditional_Generic<T>::Compare(const T& s1, const T& s2) const { return NStr::Compare(s1, s2, m_CaseSensitive); } template <typename T> inline bool PNocase_Conditional_Generic<T>::Less(const T& s1, const T& s2) const { return Compare(s1, s2) < 0; } template <typename T> inline bool PNocase_Conditional_Generic<T>::Equals(const T& s1, const T& s2) const { return Compare(s1, s2) == 0; } template <typename T> inline bool PNocase_Conditional_Generic<T>::operator()(const T& s1, const T& s2) const { return Less(s1, s2); } END_HBNSTR_SCOPE inline int NStr::strcmp(const char* s1, const char* s2) { return ::strcmp(s1, s2); } inline int NStr::strncmp(const char* s1, const char* s2, size_t n) { return ::strncmp(s1, s2, n); } inline int NStr::strcasecmp(const char* s1, const char* s2) { #if defined(HAVE_STRICMP) #if NCBI_COMPILER_MSVC && (_MSC_VER >= 1400) return ::_stricmp(s1, s2); #else return ::stricmp(s1, s2); #endif #elif defined(HAVE_STRCASECMP_LC) return ::strcasecmp(s1, s2); #else int diff = 0; for ( ;; ++s1, ++s2) { char c1 = *s1; // calculate difference diff = tolower((unsigned char) c1) - tolower((unsigned char)(*s2)); // if end of string or different if (!c1 || diff) break; // return difference } return diff; #endif } inline int NStr::strncasecmp(const char* s1, const char* s2, size_t n) { #if defined(HAVE_STRICMP) #if NCBI_COMPILER_MSVC && (_MSC_VER >= 1400) return ::_strnicmp(s1, s2, n); #else return ::strnicmp(s1, s2, n); #endif #elif defined(HAVE_STRCASECMP_LC) return ::strncasecmp(s1, s2, n); #else int diff = 0; for ( ; ; ++s1, ++s2, --n) { if (n == 0) return 0; char c1 = *s1; // calculate difference diff = tolower((unsigned char) c1) - tolower((unsigned char)(*s2)); // if end of string or different if (!c1 || diff) break; // return difference } return diff; #endif } inline int NStr::CompareCase(const char* s1, const char* s2) { return NStr::strcmp(s1, s2); } inline int NStr::CompareNocase(const char* s1, const char* s2) { return NStr::strcasecmp(s1, s2); } inline int NStr::Compare(const char* s1, const char* s2, ECase use_case) { return use_case == NStr::ECase::eCase ? CompareCase(s1, s2) : CompareNocase(s1, s2); } inline int NStr::Compare(const CTempStringEx s1, const CTempStringEx s2, ECase use_case) { return use_case == NStr::ECase::eCase ? CompareCase(s1, s2) : CompareNocase(s1, s2); } inline bool NStr::EqualCase(const char* s1, const char* s2) { size_t n = strlen(s1); if (n != strlen(s2)) { return false; } return NStr::strncmp(s1, s2, n) == 0; } inline bool NStr::EqualCase(const CTempStringEx s1, const CTempStringEx s2) { return s1 == s2; } inline bool NStr::EqualNocase(const char* s1, const char* s2) { size_t n = strlen(s1); if (n != strlen(s2)) { return false; } return NStr::strncasecmp(s1, s2, n) == 0; } inline bool NStr::EqualNocase(const CTempStringEx s1, const CTempStringEx s2) { if (s1.length() != s2.length()) { return false; } return CompareNocase(s1, s2) == 0; } inline bool NStr::Equal(const char* s1, const char* s2, ECase use_case) { return use_case == ECase::eCase ? EqualCase(s1, s2) : EqualNocase(s1, s2); } inline bool NStr::Equal(const CTempStringEx s1, const CTempStringEx s2, ECase use_case) { return use_case == ECase::eCase ? EqualCase(s1, s2) : EqualNocase(s1, s2); } inline bool NStr::StartsWith(const CTempString str, const CTempString start, ECase use_case) { return str.size() >= start.size() && Equal(str.substr(0, start.size()), start, use_case); } inline bool NStr::StartsWith(const CTempString str, char start, ECase use_case) { return !str.empty() && (use_case == ECase::eCase ? (str[0] == start) : (str[0] == start || toupper((unsigned char) str[0]) == start || tolower((unsigned char) str[0])) ); } inline bool NStr::EndsWith(const CTempString str, const CTempString end, ECase use_case) { return str.size() >= end.size() && Equal(str.substr(str.size() - end.size(), end.size()), end, use_case); } inline bool NStr::EndsWith(const CTempString str, char end, ECase use_case) { if (!str.empty()) { char last = str[str.length() - 1]; return use_case == ECase::eCase ? (last == end) : (last == end || toupper((unsigned char) last) == end || tolower((unsigned char) last) == end); } return false; } /// Check equivalence of arguments using predicate. template<class Arg1, class Arg2, class Pred> inline bool AStrEquiv(const Arg1& x, const Arg2& y, Pred pr) { return pr.Equals(x, y); } #endif // __STR_CMP_HPP
true
81fa5e298f1c3ed16681086b2289965355fed534
C++
rrwick/genome_painter
/src/painter/paint.cpp
UTF-8
1,624
2.78125
3
[]
no_license
#include "paint.h" namespace paint { std::vector<PaintBucket> paint_sequence(genome::FastaRecord &fasta, db::Database &database) { std::vector<PaintBucket> paint(fasta.sequence.size(), PaintBucket(database.header.species_num)); for (size_t i = 0; i < fasta.sequence.size()-KMER_SIZE; i++) { std::vector<float> probabilities; if(get_probabilities(fasta.sequence, i, probabilities, database)) { // Add current kmer_probabilities if they're higher than what is currently present PaintBucket kmer_probabilities(probabilities); compare_paint(paint, kmer_probabilities, i); } } return paint; } bool get_probabilities(std::string &sequence, size_t i, std::vector<float> &probabilities, db::Database &database) { // Encode common::ullong bincode; if (! kmer::encode_kmer(sequence, i, bincode)) { return false; } // Get probabilities if (database.probabilities.find(bincode) != database.probabilities.end()) { probabilities = database.probabilities[bincode]; return true; } else { return false; } } void compare_paint(std::vector<PaintBucket> &paint, PaintBucket &bucket, size_t i) { size_t end_idx; if (i+KMER_SIZE > paint.size()) { end_idx = paint.size(); } else { end_idx = i + KMER_SIZE; } // TODO: to save memory we could use a reference and one of each bucket on the stack for ( ; i < end_idx; i++) { if (paint[i].max_probability < bucket.max_probability) { paint[i] = bucket; } } } } // namespace paint
true
b49a6ddddde8e28a785eb48b6bb6c00e56394145
C++
AveryFerrante/FinalProject
/interactivemode.cpp
UTF-8
18,555
2.90625
3
[]
no_license
#include "interactivemode.h" using namespace std; InteractiveMode::InteractiveMode(int consoleArgs, char **consolePaths) { argc = consoleArgs; argv = consolePaths; setToNull(); // Sets the member variable pointers to null } InteractiveMode::~InteractiveMode() { /*deleteObjects();*/ } // AWFUL PROGRAMMING PRACTICE, BUT SINCE THE PROGRAM EXITS STRAIGHT FROM THIS, I WON'T EVER BE CONTINUING TO RUN THE // PROGRAM WITHOUT DELETEING THE DATA STRUCTURE. I ONLY DO THIS BECAUSE AVL TREE DELETION SEG FAULTS AND I CAN'T HAVE THAT DURING THE DEMO //"Runs" the program, loops until the exit command is entered void InteractiveMode::run() { int decision = -1; while(decision != 0) { clearScreen(); display(); decision = getInput(EXIT_VALUE, MAX_INTERACTIVE_MODE_NUMBER); if(decision == LOAD_FROM_INDEX) loadFromIndex(); // else if(decision == DELETE_CURRENT_INDEX) // Would like to add this feature at some point // deleteCurrentIndex(); else if(decision == BOOLEAN_QUERY) search(); } } //***************************UTILITY FUNCTIONS************************************************** //Handles searches for fords void InteractiveMode::search() { clearScreen(); //Try-catch to handle attempts to search a //non-existant index vector<char *> userQuery; try { if(dataStructure == NULL || documentIndexObject == NULL) throw UNINITIALIZED_OBJECT_ERROR; string tempUserInput; cout << "Enter boolean querey:" << endl; cin.clear(); cin.ignore(1000, '\n'); // These clear cin so the following loop will work while(cin.peek() != '\n') { cin >> tempUserInput; char *temp = new char[tempUserInput.length() + 1]; strcpy(temp, tempUserInput.c_str()); userQuery.push_back(temp); } if(strcmp(userQuery[0], "AND") == 0) andQuery(userQuery); else if(strcmp(userQuery[0], "OR") == 0) orQuery(userQuery); else singleQuery(userQuery); for(size_t i = 0; i < userQuery.size(); ++i) delete [] userQuery[i]; } catch(int e) { for(size_t i = 0; i < userQuery.size(); ++i) delete [] userQuery[i]; errorHandle(e); } } void InteractiveMode::andQuery(vector<char *> &userQuery) { if(userQuery.size() < 3) // Impossible to process throw USER_INPUT_UNDERFLOW; vector<DocumentAndFrequency *> *finalList = andProcessor(userQuery); finalList = notProcessor(userQuery, finalList); if(finalList->size() > 0) { string title = createTitle(userQuery); titlesAndBodies(finalList, title); } else throw NO_RESULTS; delete finalList; } void InteractiveMode::orQuery(vector<char *> &userQuery) { if(userQuery.size() < 3) throw USER_INPUT_UNDERFLOW; vector<DocumentAndFrequency *> *finalList = new vector<DocumentAndFrequency *>(); for(size_t index = 1; index < userQuery.size() && strcmp(userQuery[index], "NOT") != 0; ++index) { char *tempWord = stemAndPreserve(userQuery[index]); vector<DocumentAndFrequency *> *temp = dataStructure->getDocumentsForWord(tempWord); delete [] tempWord; finalList->insert(finalList->end(), temp->begin(), temp->end()); } finalList = notProcessor(userQuery, finalList); if(finalList->size() > 0) { string title = createTitle(userQuery); titlesAndBodies(finalList, title); delete finalList; } else { delete finalList; throw NO_RESULTS; } } void InteractiveMode::singleQuery(vector<char *> &userQuery) { if(userQuery.size() < 1) throw USER_INPUT_UNDERFLOW; char *tempWord = stemAndPreserve(userQuery[0]); // Word should ALWAYS be at index 0 vector<DocumentAndFrequency *> *documentList = dataStructure->getDocumentsForWord(tempWord); delete [] tempWord; if(documentList == NULL) throw NO_RESULTS; else if(userQuery.size() > 1) // NOT words { if(strcmp(userQuery[1], "NOT") != 0) throw INCORRECT_FORMAT; documentList = notProcessor(userQuery, documentList); if(documentList->size() > 0) { string title = createTitle(userQuery); titlesAndBodies(documentList, title); delete documentList; } else { delete documentList; throw NO_RESULTS; } } else { string title = createTitle(userQuery); titlesAndBodies(documentList, title); } } vector<DocumentAndFrequency *>* InteractiveMode::andProcessor(vector<char *> &userQuery) { char *tempWord = stemAndPreserve(userQuery[1]); // no case where index 1 won't contain a search word vector<DocumentAndFrequency *> *list1 = dataStructure->getDocumentsForWord(tempWord); delete [] tempWord; tempWord = stemAndPreserve(userQuery[2]); // no case where index 2 won't contain a search word vector<DocumentAndFrequency *> *list2 = dataStructure->getDocumentsForWord(tempWord); delete [] tempWord; if(list1 == NULL || list2 == NULL) throw AND_WORD_DOES_NOT_EXIST; // MUST BE SORTED ASCEDINGLY BY DOCUMENT ID VALUE // This vector should never be as big as I declare it here, but it is resized later, so I am being safe here. vector<DocumentAndFrequency *> *returnVector = new vector<DocumentAndFrequency *>(list1->size() + list2->size()); vector<DocumentAndFrequency *>::iterator it; it = set_intersection(list1->begin(), list1->end(), list2->begin(), list2->end(), returnVector->begin(), DocumentAndFrequency::andCompare); returnVector->resize(it - returnVector->begin()); // Start at 3 because we have already processed the first two AND words. Now we see if we should process more. for(size_t index = 3; index < userQuery.size() && strcmp(userQuery[index], "NOT") != 0; ++index) { list1 = returnVector; // This is now one of our "good word lists." char *temp = stemAndPreserve(userQuery[index]); list2 = dataStructure->getDocumentsForWord(temp); delete [] temp; if(list2 == NULL) { delete list1; throw AND_WORD_DOES_NOT_EXIST; } returnVector = new vector<DocumentAndFrequency *>(list1->size() + list2->size()); it = set_intersection(list1->begin(), list1->end(), list2->begin(), list2->end(), returnVector->begin(), DocumentAndFrequency::andCompare); returnVector->resize(it - returnVector->begin()); // This is now our list that is meeting all the AND requirements delete list1; // No longer need the old good word list, returnVector is our new good word list. } return returnVector; } std::vector<DocumentAndFrequency *> *InteractiveMode::notProcessor(vector<char *> &userQuery, std::vector<DocumentAndFrequency *> *goodWordList) { if(userQuery.size() < 3) throw INCORRECT_FORMAT; size_t index = 0; // This gets the starting index where the NOT list of words begins for(; index < userQuery.size() && strcmp(userQuery[index], "NOT") != 0; ++index); if(index == userQuery.size()) { return goodWordList; // Does not have any NOT words to process } ++index; // Now pointing at the next not word. // MUST BE SORTED ASCENDINGLY BY DOCUMENT ID NUMBER! vector<DocumentAndFrequency *> *returnVector = new vector<DocumentAndFrequency *>(goodWordList->size()); vector<DocumentAndFrequency *>::iterator it; char *temp = stemAndPreserve(userQuery[index++]); vector<DocumentAndFrequency *> *badWordList = dataStructure->getDocumentsForWord(temp); delete [] temp; if(badWordList == NULL) { delete returnVector; throw NOT_WORD_DOES_NOT_EXIST; } it = set_difference(goodWordList->begin(), goodWordList->end(), badWordList->begin(), badWordList->end(), returnVector->begin(), DocumentAndFrequency::notCompare); returnVector->resize(it - returnVector->begin()); // Initialization complete. Continue Processing for(; index < userQuery.size(); ++index) { vector<DocumentAndFrequency *> *tempGoodWordList = returnVector; // This is now the "good word list". Must use it in the set algorithm temp = stemAndPreserve(userQuery[index]); badWordList = dataStructure->getDocumentsForWord(temp); delete [] temp; if(badWordList == NULL) { delete tempGoodWordList; throw NOT_WORD_DOES_NOT_EXIST; } returnVector = new vector<DocumentAndFrequency *>(tempGoodWordList->size()); it = set_difference(tempGoodWordList->begin(), tempGoodWordList->end(), badWordList->begin(), badWordList->end(), returnVector->begin(), DocumentAndFrequency::notCompare); returnVector->resize(it - returnVector->begin()); delete tempGoodWordList; // No longer need the old good word list, we now have new updated one } return returnVector; } void InteractiveMode::titlesAndBodies(std::vector<DocumentAndFrequency *> *documentList, string &title) { assert( documentList != NULL ); // Really this will never happen, but defensive programming int decision = -1; sortByFreq(documentList); while(decision != 0) { clearScreen(); cout << title << ": " << endl; cout << "Enter 0 to return" << endl; for(size_t i = 0; i < documentList->size(); ++i) { cout << i + 1 << ": "; documentIndexObject->getTitle(((*documentList)[i])->getDocNumb()); cout << " - " << ((*documentList)[i])->getFinalFreq() << " occurances of a keyword." << endl; if(i == MAX_RESULTS) break; } cout << "Enter the number of the document you would like to view: "; if(documentList->size() > MAX_RESULTS) decision = getInput(EXIT_VALUE, MAX_RESULTS + 1); else decision = getInput(EXIT_VALUE, documentList->size()); if((decision - 1) > -1) { clearScreen(); documentIndexObject->getDocument(((*documentList)[decision - 1])->getDocNumb()); pause(); } } for(size_t i = 0; i < documentList->size(); ++i) (*documentList)[i]->resetFreq(); // Set the final frequencies back to original value so they are not permanently altered for future searches } string InteractiveMode::createTitle(std::vector<char *> &userQuery) { // Some redundant looking practices. What I came up with that worked in under 10 minutes string returnVal("Results for "); size_t index = 0; if(strcmp(userQuery[index], "AND") == 0) { for(index = 1; index < userQuery.size() && strcmp(userQuery[index], "NOT") != 0; ++index) { returnVal += userQuery[index]; returnVal += " "; if((index + 1) < userQuery.size() && strcmp(userQuery[index + 1], "NOT") != 0) returnVal += "AND "; // Don't want to add this if no word is coming after it, thats why the above check happens } } else if(strcmp(userQuery[index], "OR") == 0) { for(index = 1; index < userQuery.size() && strcmp(userQuery[index], "NOT") != 0; ++index) { returnVal += userQuery[index]; returnVal += " "; if((index + 1) < userQuery.size() && strcmp(userQuery[index + 1], "NOT") != 0) returnVal += "OR "; } } else // Single word query { returnVal += userQuery[index++]; returnVal += " "; } // NOT words if(index < userQuery.size() && strcmp(userQuery[(index)++], "NOT") == 0) { returnVal += "NOT "; for(; index < userQuery.size(); ++index) { returnVal += userQuery[index]; returnVal += " "; } } return returnVal; } void InteractiveMode::sortByFreq(std::vector<DocumentAndFrequency *> *documentList) { std::sort(documentList->begin(), documentList->end(), DocumentAndFrequency::descendingByFreq); } //void InteractiveMode::deleteCurrentIndex() Eventually would like this functionality. The only thing stopping this is the avl tree not destroying properly //{ // if(dataStructure == NULL || documentIndexObject == NULL) // throw UNINITIALIZED_OBJECT_ERROR; // clearScreen(); // deleteObjects(); // setToNull(); // pause(); //} void InteractiveMode::loadFromIndex(int structure /* = 0*/) // Structure is passed from stress test mode { try { if(dataStructure != NULL || documentIndexObject != NULL) throw INITIALIZED_OBJECT_ERROR; bool avlTree; if(structure == 0) // Building from interactive mode avlTree = getDataStruct(); else // Building from stress test mode { if(structure == AVL_TREE) avlTree = true; else avlTree = false; } clearScreen(); if(avlTree) { cout << "Loading the AVL-Tree." << endl; dataStructure = new avltree; documentIndexObject = new DocumentIndex; dataStructure->buildFromIndex(); documentIndexObject->buildFromIndex(); cout << "Loaded Successfully" << endl; pause(); } else { cout << "Loading the Hash Table." << endl; dataStructure = new HashTable; documentIndexObject = new DocumentIndex; dataStructure->buildFromIndex(); documentIndexObject->buildFromIndex(); cout << "Loaded Successfully" << endl; pause(); } } catch(int e) { deleteObjects(); setToNull(); errorHandle(e); } } bool InteractiveMode::getDataStruct() { clearScreen(); cout << "Please select which data structure to load into:" << endl; cout << AVL_TREE << ". AVL-Tree" << endl; cout << HASH_TABLE << ". Hash Table" << endl; int decision = getInput(AVL_TREE, HASH_TABLE); if(decision == AVL_TREE) return true; else return false; } void InteractiveMode::display() { cout << "Interactive Mode:" << endl; cout << EXIT_VALUE << ". Exit" << endl; cout << LOAD_FROM_INDEX << ". Load from Index" << endl; cout << BOOLEAN_QUERY << ". Boolean Query Search" << endl; //cout << DELETE_CURRENT_INDEX << ". Delete the Current Data Structure." << endl; } int InteractiveMode::getInput(int lowerBound, int upperBound) { assert ( lowerBound < upperBound ); string returnValue; cin >> returnValue; bool validInput = false; while(true) { for(size_t i = 0; i < returnValue.length(); ++i) { if(!isdigit(returnValue.at(i))) { validInput = false; break; } validInput = true; } if(validInput && atoi(returnValue.c_str()) >= lowerBound && atoi(returnValue.c_str()) <= upperBound) break; // Loop over, good input cout << "Invalid input, please re-enter: "; cin.ignore(100, '\n'); cin >> returnValue; } return atoi(returnValue.c_str()); } char * InteractiveMode::stemAndPreserve(const char *word) { char *temp = new char[strlen(word) + 1]; strcpy(temp, word); temp[strlen(word)] = '\0'; temp[stemObj.stem(temp, 0, strlen(temp) - 1)] = '\0'; return temp; } //Error handler, prints relevant error message using definitions //The errorHandler is used in the "catch" portion of try-catches void InteractiveMode::errorHandle(int e) { clearScreen(); cout << "ERROR ENCOUNTERED" << endl; if(e == XML_FILE_OPEN_ERROR) cout << "Error opening the file entered.\nMake sure the file name is spelled correctly and" << " is in the proper working directory (See manual)." << endl; if(e == STOP_WORDS_FILE_OPEN_ERROR) cout << "Unable to open the file containing the stop words.\nMake sure this is provided as the" << " last command line argument (see manual)." << endl; if(e == ERROR_BUILDING_INDEX) cout << "Unable to build the structure. Please make sure an index file exists in the working directory.\n" << "If none exists, you may use maintenance mode to build the default index and try again (see manual)." << endl; if( e == ERROR_BUILDING_DOCUMENT_INDEX) cout << "Unable to build document index. Please make sure an index file exists in the working directory.\n" << "If none exists, you may use maintenance mode to build the default index and try again (see manual)." << endl; if(e == USER_INPUT_UNDERFLOW) cout << "Query didn't contain minimum amount of words.\nMake sure query is properly formatted (see manual)." << endl; if(e == UNINITIALIZED_OBJECT_ERROR) cout << "Cannot perform task because the current data structure is not initialized (see manual)" << endl; if(e == AND_WORD_DOES_NOT_EXIST) cout << "A word in your AND query does not exist in the current index." << endl; if(e == INCORRECT_FORMAT) cout << "Your query entry is not formatted properly.\nSee manual for details on formatting." << endl; if(e == NO_RESULTS) cout << "There are no documents in the index that meet all of the search criteria." << endl; if(e == INITIALIZED_OBJECT_ERROR) cout << "There is already a data strucutre loaded in memory." << endl; if(e == INPUT_FILE_OPEN_ERROR) cout << "Could not open the file entered by the user (see manual)" << endl; if(e == UNFORMATTED_ERROR) cout << "Unknown command encountered. Improper file formatting (see manual)." << endl; pause(); // "Press any key to continue" } //Helper function that deletes the dataStructure that contains the index and the Index void InteractiveMode::deleteObjects() { delete documentIndexObject; delete dataStructure; } //After deleting the index (or during initialization of interactive mode), //This function sets member variables to a default value of NULL void InteractiveMode::setToNull() { documentIndexObject = NULL; dataStructure = NULL; } //Helpers for cleaning the user interface void InteractiveMode::clearScreen() { system("cls"); } void InteractiveMode::pause() { system("pause"); }
true
cf250824ae2164b69ac1231a014de67404193385
C++
kamilgajewski11/SparseArray
/SparseArray.h
UTF-8
8,963
3.109375
3
[]
no_license
#ifndef SPARSE_ARRAY_SPARSEARRAY_H #define SPARSE_ARRAY_SPARSEARRAY_H #include <iostream> #include <map> #include <cstdlib> #include <stdexcept> using namespace std; template <class V, unsigned D> class SparseArray { public: class Index{ private: unsigned *indexArray; unsigned counter; public: Index(){ counter = 0; indexArray = new unsigned[D]; for (unsigned i = 0; i < D; i++) { indexArray[i] *= 0; } } Index(const Index& ind){ counter = ind.counter; unsigned *new_array = new unsigned[D]; for(unsigned i = 0; i<D; i++){ new_array[i] = ind.indexArray[i]; } indexArray = new_array; } ~Index(){ delete[] indexArray; } unsigned& operator[](unsigned id){ if(id < 0 || id>D-1){ throw runtime_error("Invalid index"); } return indexArray[id]; } unsigned operator[](unsigned id) const{ if(id < 0 || id>D-1){ throw runtime_error("Invalid index"); } return indexArray[id]; } Index& operator,(unsigned a){ counter++; if(counter >= D){ throw runtime_error("Index overflow"); } indexArray[counter] = a; return *this; } Index& operator=(unsigned a){ counter = 0; for(unsigned i = 0; i<D; i++){ indexArray[i] = 0; } indexArray[0] = a; return *this; } friend bool operator==(const Index& ind1, const Index& ind2){ for(unsigned i = 0; i<D; i++){ if(ind1[i] != ind2[i]){ return false; } } return true; } Index& operator=(const Index& ind){ if(this == &ind) { return *this; } unsigned *new_array = new unsigned[D]; for(int i = 0; i<D; i++){ new_array[i] = indexArray[i]; } indexArray = new_array; return *this; } friend bool operator<(const Index& ind1, const Index& ind2){ for(unsigned i = 0; i<D; i++){ if(ind1[i] < ind2.indexArray[i]){ return true; } if(ind1[i]> ind2.indexArray[i]){ return false; } } return false; } friend ostream& operator<<(ostream& o, const Index& ind) { o<<"{"; for(int i = 0; i<D-1; i++){ o<<ind.indexArray[i]<<","; } o<<ind.indexArray[D-1]; o<<"}"; return o; } }; class reference { public: Index ind; map<const Index, V>* refMap; reference()= default; reference(const Index& ind,map<const Index, V>& refMap): ind(ind), refMap(&refMap){} reference(const reference& ref){ ind = ref.ind; refMap = ref.refMap; } reference& operator =(const reference& ref) { if(this == &ref){ return *this; } ind = ref.ind; refMap = ref.refMap; } reference& operator =(const V& v){ if(v != V()) { (*refMap)[ind] = v; } if(v == V() && (*refMap).count(ind)){ (*refMap).erase(ind); } return *this; } operator V() { if(!(*refMap).count(ind)){ return V(); } return (*refMap)[ind]; } }; reference operator[](const Index& ind){ return reference(ind, mapa); } class const_reference{ public: Index ind; const map<const Index, V>* refMap; const_reference()= default; const_reference(const Index& ind,const map<const Index, V>& refMap): ind(ind), refMap(&refMap){} const_reference(const const_reference& ref){ ind = ref.ind; refMap = ref.refMap; } const_reference(const reference& ref){ ind = ref.ind; refMap = ref.refMap; } const_reference& operator =(const reference& ref) { ind = ref.ind; refMap = ref.refMap; } const_reference& operator =(const const_reference& ref) { if(this == &ref){ return *this; } ind = ref.ind; refMap = ref.refMap; } operator V() const{ if(!(*refMap).count(ind)){ return V(); } return (*refMap).at(ind); } }; const_reference operator[](const Index& ind) const{ return const_reference(ind, mapa); } class iterator{ public: typename map<Index,V>::iterator it; map<const Index, V>* itMap; iterator()= default; iterator(const typename map<Index,V>::iterator& it, map<const Index, V>& itMap): it(it), itMap(&itMap){} Index key(){ return it->first; } V value(){ return it->second; } reference operator*(){ return reference(it->first, *itMap); } bool operator ==(const iterator& iter){ if(it == iter.it){ return true; } return false; } bool operator !=(const iterator& iter){ if(it == iter.it){ return false; } return true; } void operator++(){ if(it != (*itMap).end()){ ++it; } else{ throw runtime_error("Iterator overflow"); } } void operator++(int){ if(it != (*itMap).end()){ ++it; } else{ throw runtime_error("Iterator overflow"); } } }; iterator begin(){ return iterator(mapa.begin(), mapa); } iterator end(){ return iterator(mapa.end(), mapa); } class const_iterator{ public: typename map<Index,V>::const_iterator it; const map<const Index, V>* itMap; const_iterator()= default; const_iterator(const typename map<Index,V>::const_iterator& it,const map<const Index, V>& itMap): it(it), itMap(&itMap){} const_iterator(const const_iterator& iter): it(iter.it), itMap(iter.itMap){} const_iterator& operator =(const const_iterator& iter){ if(this == &iter){ return *this; } it = iter.it; itMap = iter.itMap; } bool operator ==(const const_iterator& iter){ if(it == iter.it){ return true; } return false; } bool operator !=(const const_iterator& iter){ if(it == iter.it){ return false; } return true; } Index key(){ return it->first; } V value(){ return it->second; } const_reference operator*(){ return const_reference(it->first, *itMap); } void operator++(){ if(it != (*itMap).end()){ ++it; } else{ throw runtime_error("Iterator overflow"); } } void operator++(int){ if(it != (*itMap).end()){ ++it; } else{ throw runtime_error("Iterator overflow"); } } }; const_iterator begin() const{ return const_iterator(mapa.begin(), mapa); } const_iterator end() const{ return const_iterator(mapa.end(), mapa); } SparseArray()= default; SparseArray(const SparseArray<V,D>& arr){ mapa = arr.mapa; } SparseArray<V,D>& operator =(const SparseArray<V,D>& arr){ mapa = arr.mapa; return *this; } map<const Index, V> mapa; void show() const{ typename std::map<Index, V>::const_iterator it = mapa.cbegin(); while (it!=mapa.end()) { cout << it->first << " = " << it->second << endl; ++it; } if(mapa.begin() == mapa.end()){ cout<<"Pusta tablica"<<endl; } cout<<endl; }; unsigned size() const{ unsigned counter = 0; typename std::map<Index, V>::const_iterator it = mapa.begin(); while (it!=mapa.end()) { it++; counter++; } return counter; } }; #endif //SPARSE_ARRAY_SPARSEARRAY_H
true
a9d94e177b061f0c7780aa251c431b092882374d
C++
tardate/LittleArduinoProjects
/playground/PrecisionTimer/MicroTimer2.cpp
UTF-8
1,539
2.5625
3
[ "MIT" ]
permissive
#include "MicroTimer2.h" MicroTimer2 microTimer2; // Handle Timer2 overflow. this will occur every 128us ISR(TIMER2_OVF_vect) { microTimer2.increment_overflow_count(); } MicroTimer2::MicroTimer2() { _overflow_count = 0; _total_count = 0; _started = false; } void MicroTimer2::enable() { if (_started) return; _initial_tccr2a = TCCR2A; _initial_tccr2b = TCCR2B; // set normal Waveform Generation Mode, OC0A and OC0B disconnected TCCR2A = 0; TCCR2B = _BV(CS21); enable_overflow_interrupt(); reset(); _started = true; } void MicroTimer2::disable(){ if (!_started) return; disable_overflow_interrupt(); TCCR2A = _initial_tccr2a; TCCR2B = _initial_tccr2b; _started = false; } unsigned long MicroTimer2::get_count() { enable(); pause(); _total_count = _overflow_count * 0x100 + TCNT2; resume(); return _total_count; } float MicroTimer2::micros() { return get_count()/2.0; } void MicroTimer2::reset() { pause(); _overflow_count = 0; _total_count = 0; TCNT2 = 0; reset_overflow_flag(); resume(); } inline void MicroTimer2::pause() { _paused_SREG = SREG; noInterrupts(); } inline void MicroTimer2::resume() { SREG = _paused_SREG; } inline void MicroTimer2::increment_overflow_count() { ++_overflow_count; } inline void MicroTimer2::reset_overflow_flag() { TIFR2 |= _BV(TOV2); } inline void MicroTimer2::enable_overflow_interrupt() { TIMSK2 |= _BV(TOIE2); } inline void MicroTimer2::disable_overflow_interrupt() { TIMSK2 &= ~(_BV(TOIE2)); }
true
cc16cddf57487e3cb697e42610d8299d737e3874
C++
a1368017681/study
/src/define.h
UTF-8
659
2.578125
3
[]
no_license
#pragma once #include <iostream> #define PR(...) printf(__VA_ARGS__) #define LOG(...) {\ fprintf(stderr, "%s:Line %d:\t", __FILE__, __LINE__);\ fprintf(stderr, __VA_ARGS__);\ fprintf(stderr, "\n");\ } void test_LOG(){ int x = 6; LOG("x = %d", x); } struct TestStructFun { TestStructFun():name(__func__) {} const char* name; }; void test_Fun() { TestStructFun ts; std::cout << ts.name << std::endl; } void get_std_define() { std::cout << "Standard Clib: " << __STDC_HOSTED__ << std::endl; std::cout << "Standard C: " << __STDC__ << std::endl; // std::cout << "ISO/IEC " << __STDC_ISO_10646__ << std::endl; }
true
c6b3d5272e50b89fdd11608de19872221b1b2982
C++
HolySmoke86/blank
/src/world/EntityState.hpp
UTF-8
1,127
2.734375
3
[]
no_license
#ifndef BLANK_WORLD_ENTITYSTATE_HPP_ #define BLANK_WORLD_ENTITYSTATE_HPP_ #include "../geometry/Location.hpp" #include "../graphics/glm.hpp" #include <glm/gtc/quaternion.hpp> namespace blank { struct EntityState { ExactLocation pos; glm::vec3 velocity; glm::quat orient; float pitch; float yaw; EntityState(); /// make sure pos.block is within chunk bounds void AdjustPosition() noexcept; /// make sure pitch and yaw are normalized void AdjustHeading() noexcept; /// get a position vector relative to the (0,0,0) chunk glm::vec3 AbsolutePosition() const noexcept { return pos.Absolute(); } /// get a position vector relative to given reference chunk glm::vec3 RelativePosition(const glm::ivec3 &reference) const noexcept { return pos.Relative(reference).Absolute(); } /// get the difference between this and the given position glm::vec3 Diff(const EntityState &other) const noexcept { return pos.Difference(other.pos).Absolute(); } /// get entity state as a matrix tranform relative to given reference chunk glm::mat4 Transform(const glm::ivec3 &reference) const noexcept; }; } #endif
true
b56ea62c13c2855043e136f625bdd43bde48ab78
C++
erwanbou/LatMRG
/include/latmrg/Weights.h
UTF-8
2,008
2.6875
3
[]
no_license
// This file is part of LatMRG. // // LatMRG // Copyright (C) 2012-2016 Pierre L'Ecuyer and Universite de Montreal // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef LATMRG__WEIGHTS_H #define LATMRG__WEIGHTS_H #include <string> #include "latmrg/CoordinateSets.h" namespace LatMRG { /** * Scalar weight type. * * \note We could have used \c Weight, but it might be wise to leave this \c * typedef in case we decide to use <tt>long Weight</tt> at some point. */ typedef double Weight; /** * Abstract weights class. * * This abstract class is the basis for different kinds of weights used to * accentuate the importance given to some projections when computing * figures of merit for lattices or point sets. */ class Weights { public: /** * Destructor. */ virtual ~Weights() { } /** * Returns the weight of the projection specified by `projection`. */ virtual Weight getWeight (const Coordinates & projection) const = 0; protected: /** * Identifies the type of weights, formats them and outputs them on \c os. * * \remark Deriving classes should identify themselves in the output. */ virtual void format(std::ostream& os) const = 0; friend std::ostream & operator<< (std::ostream & out, const Weights & o); }; /** * \relates Weights * Identifies the type of weights, formats them and outputs them on \c os. */ inline std::ostream & operator<< (std::ostream & os, const Weights & o) { o.format(os); return os; } } #endif
true
d36df381beb9f8df210261cf8a2cdaff059a481d
C++
sfinae/watcher
/src/ClientTcpSocket/global.h
UTF-8
4,488
2.546875
3
[]
no_license
#ifndef GLOBAL_H #define GLOBAL_H #include <QPixmap> #include <QDateTime> namespace global { namespace types { /* operation type if equal zero then previous operation compleated and wait a new command */ typedef qint8 operation_t; /* operation data size which read/write from/to socket */ typedef qint32 operation_size_t; } ////////////////////////////////////////////////////////////////////////////////////////// namespace params { enum Operation { NOOPERATION, // autorization AUTORIZATION, // pictures operations GETPICTURE, GETALLPICTURES, GETCURRENTDATEPICTURES, GETPERIODPICTURES, PICTURETIMER, GETPICTURETIMER, MAILPROPERTIES, GETMAILPROPERTIES, // execution process EXECUTIONREPORT, // settings GETSETTINGS, SETSETTINGS, // clipboard GETCLIPBOARD, SETCLIPBOARD, GETLASTCLIPBOARD }; /* the end in transmittion */ /* in size field */ const qint32 END = 0; } ////////////////////////////////////////////////////////////////////////////////////////////// namespace functions { /* calculate size of data(without operation field) and set after operation field */ // with 1 parameter template <typename T> void writeDataToByteArray(QByteArray& outputArray, params::Operation operation, const T& t) { QDataStream out(&outputArray, QIODevice::WriteOnly); // write data with zero size out << (types::operation_t)operation << (types::operation_size_t)0 << t; // counting size types::operation_size_t size = outputArray.size() - sizeof(types::operation_t) - sizeof(types::operation_size_t); // write size out.device()->seek(sizeof(types::operation_t)); out << size; } // with 2 parameters template <typename T1, typename T2> void writeDataToByteArray(QByteArray& outputArray, params::Operation operation, const T1& t1, const T2& t2) { QDataStream out(&outputArray, QIODevice::WriteOnly); // write data with zero size out << (types::operation_t)operation << (types::operation_size_t)0 << t1 << t2; // counting size types::operation_size_t size = outputArray.size() - sizeof(types::operation_t) - sizeof(types::operation_size_t); // write size out.device()->seek(sizeof(types::operation_t)); out << size; } // with 3 parameters template <typename T1, typename T2, typename T3> void writeDataToByteArray(QByteArray& outputArray, params::Operation operation, const T1& t1, const T2& t2, const T3& t3) { QDataStream out(&outputArray, QIODevice::WriteOnly); // write data with zero size out << (types::operation_t)operation << (types::operation_size_t)0 << t1 << t2 << t3; // counting size types::operation_size_t size = outputArray.size() - sizeof(types::operation_t) - sizeof(types::operation_size_t); // write size out.device()->seek(sizeof(types::operation_t)); out << size; } // with 7 parameters template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> void writeDataToByteArray(QByteArray& outputArray, params::Operation operation, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7) { QDataStream out(&outputArray, QIODevice::WriteOnly); // write data with zero size out << (types::operation_t)operation << (types::operation_size_t)0 << t1 << t2 << t3 << t4 << t5 << t6 << t7; // counting size types::operation_size_t size = outputArray.size() - sizeof(types::operation_t) - sizeof(types::operation_size_t); // write size out.device()->seek(sizeof(types::operation_t)); out << size; } } } // global #endif // GLOBAL_H
true
a46b03db5db517a32b16c8b1147ff8a271d05987
C++
codiy1992/fzu_031102406
/大一大二/C,C++,数构/算法与数据结构/8. 银行(完成)/银行.cpp
GB18030
2,302
3.234375
3
[]
no_license
#include<iostream> using namespace std; typedef struct people *link; link p1=NULL,head; typedef struct people { long ID; long P; link next; link last; }peo; struct people *creat(long IDs,long Ps) { link q1; q1=(struct people *)malloc(sizeof(struct people)); q1->ID=IDs; q1->P=Ps; q1->next=NULL; q1->last=NULL; if(p1==NULL) head=q1; if(p1!=NULL) { p1->next=q1; q1->last=p1; } return q1; } /////////////ɾȼpIDĺ/////////////// long delete1 (link h) { long max; link q2,q3; q2=h; max=q2->P; q3=q2; q2=q2->next; if(q2==NULL) { head=NULL; return q3->ID; } while(q2!=NULL) { if(max<q2->P) {max=q2->P; q3=q2;} q2=q2->next; } if(q3->next!=NULL&&q3->last!=NULL){q3->last->next=q3->next;q3->next->last=q3->last;}//**********// if(q3->next==NULL&&q3->last!=NULL){q3->last->next=NULL;} if(q3->next!=NULL&&q3->last==NULL){head=q3->next;q3->next->last=NULL;} return q3->ID;//return滹䣬ִУΪreturnζźǰif䲻ܷŵreturnĺ } ///////////ȼ͵IDɾýĺ////////// long delete2 (link h) { long min; link h2,h3; h2=h; min=h2->P; h3=h2; h2=h2->next; if(h2==NULL) { head=NULL; return h3->ID; } while(h2!=NULL) { if(min>h2->P) {min=h2->P; h3=h2;} h2=h2->next; } if(h3->next!=NULL&&h3->last!=NULL){h3->last->next=h3->next;h3->next->last=h3->last;} if(h3->next==NULL&&h3->last!=NULL){h3->last->next=NULL;} if(h3->next!=NULL&&h3->last==NULL){head=h3->next;h3->next->last=NULL;} return h3->ID; } /////////////////////////////////////////////////// void main() { link p2,p3; int x,i; long IDs,Ps; cin>>x; for(i=0;;i++) { if(head==NULL){p1=NULL;} if(x==1) { cin>>IDs>>Ps; p1=creat(IDs,Ps); } if(x==2) { if(head==NULL){cout<<"0"<<endl;} else { cout<<delete1(head)<<endl; } } if(x==3) { if(head==NULL){cout<<"0"<<endl;} else { cout<<delete2(head)<<endl; } } if(x==0)break; cin>>x; } /* p2=head; while(p2!=NULL) { cout<<p2->ID<<" "<<p2->P<<endl; p2=p2->next; } p2=head; while(p2!=NULL) { if(p2->next==NULL){p3=p2;} p2=p2->next; } while(p3!=NULL) { cout<<p3->ID<<" "<<p3->P<<endl; p3=p3->last; }*/ }
true
762b1b220158849e045d85c879e30d553f33548d
C++
tcarrel/Brain
/Brain/src/Brain/Events/app_event.h
UTF-8
1,646
2.546875
3
[ "Apache-2.0" ]
permissive
#pragma once #include "Brain/Events/event.h" namespace Brain { class Window_Resize_Event : public Event { unsigned width_; unsigned height_; public: Window_Resize_Event( unsigned width, unsigned height ) : width_( width ), height_( height ) {} const unsigned& w{ width_ }; const unsigned& h{ height_ }; std::string to_string( void ) const override { std::stringstream ss; ss << "Window_Resize_Event: ( " << w << 'x' << h << " )"; return ss.str(); } EVENT_CLASS_TYPE( WIN_RESIZE ); EVENT_CLASS_CATEGORY( static_cast<int>( Event_Category::APPLICATION ) ); }; class Window_Close_Event : public Event { public: Window_Close_Event() = default; EVENT_CLASS_TYPE( WIN_CLOSE ); EVENT_CLASS_CATEGORY( static_cast<int>( Event_Category::APPLICATION ) ); }; class App_Tick_Event : public Event { public: App_Tick_Event() = default; EVENT_CLASS_TYPE( APP_TICK ); EVENT_CLASS_CATEGORY( static_cast<int>( Event_Category::APPLICATION ) ); }; class App_Update_Event : public Event { public: App_Update_Event() = default; EVENT_CLASS_TYPE( APP_UPDATE ); EVENT_CLASS_CATEGORY( static_cast<int>( Event_Category::APPLICATION ) ); }; class App_Render_Event : public Event { public: App_Render_Event() = default; EVENT_CLASS_TYPE( APP_RENDER ); EVENT_CLASS_CATEGORY( static_cast<int>( Event_Category::APPLICATION ) ); }; }
true
996ca01b4a5a313cb5bb2513e68e132c4dbb95b9
C++
JonathanZip/COP3503-Fall2016
/Exam1-Review/const-with-classes.cpp
UTF-8
339
3.78125
4
[ "MIT" ]
permissive
#include <iostream> class Person { int age; std::string name; public: Person(int age, std::string name) { this->age = age; this->name = name; } int getAge() const { return age; } void setAge(int age) { this->age = age; } }; int main() { const Person max(22, "Max"); max.getAge(); max.setAge(21); }
true
e547531525b0c76a3906678619a7a30935a6a429
C++
Needrom/TCP_Data_Send
/src/clientTest.cpp
UTF-8
1,773
2.515625
3
[]
no_license
#include"tcp.h" #include<stdlib.h> #include<stdio.h> #include<pthread.h> #include"myqueue.h" #include"dataStruct.h" #include"file.h" #include<fstream> #include <csignal> #include<sys/time.h> using namespace std; MyQueue queue = MyQueue(2058); OptFile myfile = OptFile(sizeof(DataFrame)); void* HeadCheck_thread(void* args){ struct timeval start; struct timeval curr; unsigned long time; gettimeofday(&start, NULL); while(1){ gettimeofday(&curr, NULL); time = 1000000 * (curr.tv_sec-start.tv_sec)+ curr.tv_usec-start.tv_usec; printf("\rsecond:[%ld]", time); fflush(stdout); } } void sig_handler( int sig ) { if ( sig == SIGINT) { printf("app end"); myfile.close(); exit(-1); } } void OnRecvData(char* buf, int size){ DataFrame *Data = (DataFrame *)buf; // printf("PreCounter is %d \r\n", Data->PreCounter); myfile<<buf; }; int main(int argc, char* argv[]){ char dataRecv_buf[sizeof(DataFrame)] = {0}; pthread_t threadID = 0; myfile.open("./data/test.dat", "w+"); if(argc < 3){ printf("usage: %s [ip address] [port] \r\n", argv[0]); exit(-1); } signal( SIGINT, sig_handler ); TCPmy tcp = TCPmy(argv[1], (int)atoi(argv[2])); if(pthread_create(&threadID, NULL, HeadCheck_thread, NULL) != 0){ perror("thread create error"); } tcp.SocketCreate(); if(tcp.Connect() < 0){ perror("fialed to connected"); exit(-1); } while(1){ memset(dataRecv_buf, '0', sizeof(dataRecv_buf)); int ReadLength = tcp.Recv(dataRecv_buf, sizeof(dataRecv_buf)); OnRecvData(dataRecv_buf, ReadLength); } myfile.close(); }
true
13bc1701716582abdab4bc4e21009f74865b6c72
C++
geekbitcreations/illinoistech
/ITM_312/ITM312/Project1A/ConsoleApplication6/ConsoleApplication6/Source.cpp
UTF-8
1,543
4.8125
5
[]
no_license
// This program asks for the number of hours worked by six employees. It stores // the values in an array. #include <iostream> using namespace std; int main() { /*const int NUM_EMPLOYEES = 6; int hours[NUM_EMPLOYEES]; // Get the hours worked by each employee. cout << "Enter the hours worked by " << NUM_EMPLOYEES << " employees: "; cin >> hours[0]; cin >> hours[1]; cin >> hours[2]; cin >> hours[3]; cin >> hours[4]; cin >> hours[5]; // Display the values in the array. cout << "The hours you entered are:"; cout << " " << hours[0]; cout << " " << hours[1]; cout << " " << hours[2]; cout << " " << hours[3]; cout << " " << hours[4]; cout << " " << hours[5] << endl; return 0; const int SIZE = 3; // Constant for the array size int values[SIZE]; // An array of 3 integers int count; // Loop counter variable // Attempt to store five numbers in the three-element array. cout << "I will store 5 numbers in a 3 element array!\n"; for (count = 0; count < 5; count++) values[count] = 100; // This program demonstrates the range-based for loop. // Define an array of integers. int numbers[] = { 10, 20, 30, 40, 50 }; // Display the values in the array. for (int val : numbers) cout << val << endl; return 0;*/ const int SIZE = 5; int numbers[5]; // Get values for the array. for (int &val : numbers) { cout << "Enter an integer value: "; cin >> val; } // Display the values in the array. cout << "Here are the values you entered:\n"; for (int val : numbers) cout << val << endl; }
true
3a5b20f8f228b72deff19e22ec70c33b947a2c14
C++
mohamedAAhassan/airhockey
/AHokey/AHokey/NeuronLayer.cpp
UTF-8
851
2.90625
3
[]
no_license
#include "StdAfx.h" #include "NeuronLayer.h" NeuronLayer::NeuronLayer(int inputsPerNeuron, int numberOfNeurons) : m_inputsPerNeuron(inputsPerNeuron), m_numberOfNeurons(numberOfNeurons) { for(int i=0; i<m_numberOfNeurons; i++) { m_neurons.push_back(new Neuron(m_inputsPerNeuron)); } } vector<double> NeuronLayer::calculate(vector<double> inputs) { vector<double> result; for(int i=0; i<m_numberOfNeurons; i++) { result.push_back(m_neurons[i]->calculate(inputs)); } return result; } Neuron* NeuronLayer::neuronAt(int index) { return m_neurons[index]; } vector<Neuron*> NeuronLayer::neurons() { return m_neurons; } /*int NeuronLayer::numNeurons() const { return this->m_numberOfNeurons; } void NeuronLayer::setNumNeurons(int num) { this->m_numberOfNeurons = num; }*/
true
4d926478e8607abbe992dcac0c5bc9af425bdfe5
C++
depp/dreamless
/src/game/physics.hpp
UTF-8
2,254
2.921875
3
[ "BSD-2-Clause" ]
permissive
/* Copyright 2014 Dietrich Epp. This file is part of Dreamless. Dreamless is licensed under the terms of the 2-clause BSD license. For more information, see LICENSE.txt. */ #ifndef LD_GAME_PHYSICS_HPP #define LD_GAME_PHYSICS_HPP #include "defs.hpp" namespace Game { class Level; /// Utility class for objects that move. class Mover { FVec m_pos0, m_pos1; public: Mover(IVec pos) : m_pos0(pos), m_pos1(pos) { } /// Update the mover, setting the new location. void update(FVec new_pos) { m_pos0 = m_pos1; m_pos1 = new_pos; } /// Get the current location. FVec pos() const { return m_pos1; } /// Get the previous location. FVec lastpos() const { return m_pos0; } /// Get the draw location. IVec drawpos(int delta) const { return Defs::interp(m_pos0, m_pos1, delta); } }; /// Utility class for objects that can walk and jump. class Walker { private: enum class State { WALK, AIR, DOUBLE }; /// The state of the jump, or lack thereof. State m_state; /// Time remaining with jump control, or -1 if jump was released. int m_jumptime; /// The distance traveled since the last footstep. float m_stepdistance; public: struct Stats { // Horizontal movement float accel_ground; float speed_ground; float accel_air; float speed_air; // Jumping int jump_time; float jump_accel; float jump_speed; float jump_gravity; bool jump_double; // Time interval between footsteps float step_time; }; public: /// Horizontal movement blocked by obstacle. static const unsigned FLAG_BLOCKED = 1u << 0; /// Did jump. static const unsigned FLAG_JUMPED = 1u << 1; /// The jump is a double jump. static const unsigned FLAG_DOUBLE = 1u << 2; /// Is currently airborne. static const unsigned FLAG_AIRBORNE = 1u << 3; /// Should play a footstep sound. static const unsigned FLAG_FOOTSTEP = 1u << 4; Walker(); /// This will also update the mover. Returns flags. unsigned update(const struct Stats &stats, const Level &level, Mover &mover, FVec drive); }; } #endif
true
3398c53c4afe6485433413841e56aefa096d6e7f
C++
jacobtruman/college
/CS/135/prog4/prog4.cpp
UTF-8
1,419
3.578125
4
[]
no_license
// Truman, Jacob // CSC 135 - Program Assignment 4 // Inputs: Reads times from file. // Outputs: Either adds of subtracts the numbers read in outputs the results. #include <iostream> #include <fstream> using namespace std; long rtime(ifstream&); void wtime(long); int main(){ cout << endl; char op, coln, ch; long time1, time2, res; int i = 0, num; ifstream timeFile; timeFile.open("times.txt"); timeFile >> num; while (i < num){ time1 = rtime (timeFile); timeFile >> op; cout << " " << op << " "; time2 = rtime (timeFile); if (op == '+') res = time1 + time2; else if (op == '-') res = time1 - time2; cout << " = "; wtime(res); cout << endl; i++; } cout << endl; return 0; } long rtime(ifstream& files){ int d, h, m, s; long thrs, tmin, tsec; char ch; files >> d >> ch >> h >> ch >> m >> ch >> s; thrs = d * 24 + h; tmin = thrs * 60 + m; tsec = tmin * 60 + s; wtime(tsec); return tsec; } void wtime(long tsec){ int days, hrs, mins, secs; days = tsec / (24 * 60 * 60); tsec = tsec % (24 * 60 * 60); hrs = tsec / (60 * 60); tsec = tsec % (60 * 60); mins = tsec / 60; secs = tsec % 60; if (days < 10) cout << "0" << days << ":"; else cout << days << ":"; if (hrs < 10) cout << "0" << hrs << ":"; else cout << hrs << ":"; if (mins < 10) cout << "0" << mins << ":"; else cout << mins << ":"; if (secs < 10) cout << "0" << secs; else cout << secs; }
true
d84d3526cf261dd1070c822e554e610c6208f516
C++
suyinlong/leetcode
/010-Regular.Expression.Matching.cpp
UTF-8
744
2.65625
3
[]
no_license
class Solution { public: bool isMatch(string s, string p) { int m = p.size(), n = s.size(); vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false)); dp[0][0] = true; // match p = 'x*x*x*' for (int i = 1; i <= m; i++) dp[i][0] = i > 1 && p[i-1] == '*' && dp[i-2][0]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (p[i-1] != '*') { dp[i][j] = dp[i-1][j-1] && (p[i-1] == s[j-1] || p[i-1] == '.'); } else { dp[i][j] = dp[i-2][j] || ((p[i-2] == s[j-1] || p[i-2] == '.') && dp[i][j-1]); } } } return dp[m][n]; } };
true
a9ed0c6e5bee7264e744e46152e32b9e65617dcf
C++
samcsanttos/MTP
/aula20171123/matriz.cpp
UTF-8
2,861
3.046875
3
[]
no_license
#ifndef MATRIZ_H #define MATRIZ_H #include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct aMatriz { double ** m; int lin, col; } Matriz; Matriz criarMatriz(int M, int N) { Matriz A; int i; A.m = calloc(M, sizeof(double *)); for(i = 0; i < M; i++) A.m[i] = calloc(N, sizeof(double)); A.lin = M; A.col = N; return A; } void destruirMatriz(Matriz A) { int i; for(i = 0; i < A.lin; i++) free(A.m[i]); free(A.m); } void preencherMatriz(Matriz A) { int i, j; for(i = 0; i < A.lin; i++) for(j = 0; j < A.col; j++) { printf("Entre com o elemento [%d][%d]: ", i, j); scanf("%lf", A.m[i]+j); } } void imprimirMatriz(Matriz A) { int i, j; for(i = 0; i < A.lin; i++) { for(j = 0; j < A.col; j++) printf("%lg\t", A.m[i][j]); printf("\n"); } printf("> %dx%d\n\n", A.lin, A.col); } void multiplicaMatriz(Matriz A; Matriz B; Matriz transposta(Matriz A) { Matriz At = criarMatriz(A.col, A.lin); int i, j; for(i = 0; i < A.col; i++) for(j = 0; j < A.lin; j++) At.m[i][j] = A.m[j][i]; return At; } double determinante(Matriz A); double menor(Matriz A, int l, int c) { Matriz M = criarMatriz(A.lin-1,A.col-1); double menorA; int i, j, p, q; p = 0; for(i = 0; i < A.lin; i++) { if(i != l) { q = 0; for(j = 0; j < A.col; j++) if(j != c) { M.m[p][q] = A.m[i][j]; q++; } p++; } } menorA = determinante(M); destruirMatriz(M); return menorA; } double cofator(Matriz A, int i, int j) { return ((i+j)%2) ? -1*menor(A,i,j) : menor(A,i,j); } double determinante(Matriz A) { double det = NAN; int i; if(A.lin != A.col) fprintf(stderr,"Matriz retangular, sem determinante!\n"); if(A.lin == 1) det = A.m[0][0]; if(A.lin == 2) det = A.m[0][0]*A.m[1][1]-A.m[0][1]*A.m[1][0]; if(A.lin == 3) det = (A.m[0][0]*A.m[1][1]*A.m[2][2]+ A.m[0][1]*A.m[1][2]*A.m[2][0]+A.m[0][2]*A.m[1][0]*A.m[2][1])- (A.m[0][0]*A.m[1][2]*A.m[2][1]+A.m[0][1]*A.m[1][0]*A.m[2][2]+ A.m[0][2]*A.m[1][1]*A.m[2][0]); if(A.lin > 3) { det = 0; for(i = 0; i < A.col; i++) det += A.m[0][i]*cofator(A,0,i); } return det; } Matriz comatriz(Matriz A){ Matriz C= criarMatriz(A.lin,A.col); int i,j; for(i = 0; i < A.col; i++) for(j = 0; j < A.lin; j++) C.m[i][j] = cofator(A,i,j); return C; } Matriz adjunta(Matriz A){ Matriz C = comatriz(A); Matriz ct = transposta(C); destruirMatriz(C); return ct; } Matriz inversa(Matriz A){ Matriz invA= criarMatriz(A.lin,A.col); Matriz adjA = adjunta(A); int i, j; if(determinante(A) == 0) fprintf(stderr,"determinante = 0!\n"); if(determinante(A) != 0){ double idet= 1/determinante(A); for(i = 0; i < A.col; i++) for(j = 0; j < A.lin; j++) invA.m[i][j] = (idet*adjA.m[i][j]); } destruirMatriz(adjA); return invA; } #endif
true
cfc3f67cb346247a773b971b93c49bdeffb6fd4c
C++
dmzhuang/cpp-reference
/std/algorithm_usage.cpp
UTF-8
2,462
3.53125
4
[]
no_license
// Standard Tempate Library: Algorithms // The header <algorithm> defines a collection of functions especially designed // to be used on ranges of elements. #include <algorithm> #include <array> #include <iostream> template <class InputIterator1, class InputIterator2> bool my_equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2) { while(first1 != last1) { if(*first1 != *first2) return false; ++first1; ++first2; } return true; } int main(int argc, char const *argv[]) { // non-modifying sequence operations std::array<int,8> foo = {1,2,3,4,5,6}; if(std::all_of(std::begin(foo), std::end(foo), [](int& i) {return i%2;})) std::cout << "all are odd" << std::endl; if(std::any_of(std::begin(foo), std::end(foo), [](int& i) {return i%2;})) std::cout << "any are odd" << std::endl; if(std::none_of(std::begin(foo), std::end(foo), [](int& i) {return i%2;})) std::cout << "none are odd" << std::endl; std::for_each(std::begin(foo), std::end(foo), [](int& i) {std::cout << i << std::endl;}); // find find_if find_if_not find_end find_first_of adjacent_find auto iter = std::find(std::begin(foo), std::end(foo), 3); iter = std::find_if(std::begin(foo), std::end(foo), [](int& i) {return i>3;}); if(iter != std::end(foo)) std::cout << "find " << *iter << std::endl; // count count_if // mismatch // equal // is_permutation // search // modifying sequence operations std::vector<int> vec(8); std::copy(std::begin(foo), std::end(foo), std::begin(vec)); for_each(std::begin(vec), std::end(vec), [](int& i) {std::cout << i << std::endl;}); // OutputIterator copy_n(InputIterator first, Size n, OutputIterator result); // OutputIterator copy_if(InputIterator first1, InputIterator last1, OutputItertor result, UnaryPredicate pred); // OutputIterator copy_backward(InputIterator first, InputIterator last, OutputIterator result) { // while(last != first) // *(--result) = *(--last); // return result; // } // move move_backward // swap swap_ranges std::transform(std::begin(foo), std::end(foo), std::begin(foo), [](int i) {return i*2;}); // generate // partitions // sorting // binary search // merge // heap // min/max // other return 0; }
true
40065ffa1757d069973c480f33bace156475d524
C++
autious/kravall
/src/gfx/Renderer/Console/ConsolePainter.hpp
UTF-8
1,585
2.59375
3
[]
no_license
#ifndef SRC_GFX_RENDERER_CONSOLE_PAINTER_HPP #define SRC_GFX_RENDERER_CONSOLE_PAINTER_HPP #include "../BasePainter.hpp" #include <Shaders/ShaderManager.hpp> #include "../DebugRenderer/DebugManager.hpp" #include "../DeferredRenderer/FBOTexture.hpp" #include "../../Buffers/UniformBufferManager.hpp" #include <GL/glew.h> namespace GFX { class ConsolePainter : public BasePainter { public: /*! Set ShaderManager and BufferManager pointers of the painter to point to the managers within the rendering core \param shaderManager Pointer to ShaderManager present in RenderCore \param uniformBufferManager Pointer to uniformBufferManager present in RenderCore */ ConsolePainter(ShaderManager* shaderManager, UniformBufferManager* uniformBufferManager); ~ConsolePainter(); /*! Initialization function which sets the dummyVAO and FBO for later use in the painter. Loads all shaders associated with debug rendering. \param FBO ID of FBO used for rendertargets \param dummyVAO ID of an empty VAO used for screenspace rendering */ void Initialize(GLuint FBO, GLuint dummyVAO); /*! Main console rendering loop */ void Render(); void SetConsoleVisible(bool visible); bool GetConsoleVisible(); DebugRect GetConsoleRect(); void SetConsoleHeight(int height); private: // Uniforms GLuint m_rectPosUniform; GLuint m_rectDimUniform; GLuint m_rectColorUniform; GLuint m_screenSizeUniform; bool m_showConsole; DebugRect m_consoleRect; DebugRect m_consoleInputRect; int m_consoleHeight; glm::vec4 m_consoleColor; }; } #endif
true
479099ecea5302ee345837fb8facc2c4eb1d17e8
C++
PatrykWasowski/EAPoL
/app/GUI/TextFieldManager.cpp
UTF-8
2,706
2.703125
3
[]
no_license
#include "TextFieldManager.h" TextFieldManager::TextFieldManager () { font.loadFromFile ("./Resources/data_control/data-latin.ttf"); } TextFieldManager::~TextFieldManager () { } void TextFieldManager::associateWindow (sf::RenderWindow& wind) { window = &wind; } void TextFieldManager::createFields () { fieldsList.push_back (new TextField (sf::Vector2f (35.f, 30.f), sf::Vector2f (160.f, 30.f), font, TextType::type::LOGIN)); fieldsList.push_back (new TextField (sf::Vector2f (35.f, 80.f), sf::Vector2f (160.f, 30.f), font, TextType::type::PASSWORD)); fieldsList.push_back (new TextField (sf::Vector2f (35.f, 130.f), sf::Vector2f (160.f, 30.f), font, TextType::type::MACADDR)); } void TextFieldManager::draw () { for (auto &i : fieldsList) { i->draw (window); } } Gui::GuiEvent TextFieldManager::checkActivation (const sf::Event& ev) { if (ev.type == sf::Event::MouseButtonPressed) { sf::Vector2f click ((float) ev.mouseButton.x, (float) ev.mouseButton.y); bool clicked = false; for (auto &i : fieldsList) { if (i->checkActivation (click) == Gui::GuiEvent::ACTIVATED) { i->setIsActive (true); activeField = i; clicked = true; } else i->setIsActive (false); } if (!clicked) { activeField = nullptr; return Gui::GuiEvent::MISSED; } } return Gui::GuiEvent::ACTIVATED; } bool TextFieldManager::checkIfAnyActive () { if (activeField == nullptr) return false; return true; } Gui::GuiEvent TextFieldManager::manageTextInput (const sf::Event& ev) { if ((activeField != nullptr) && ev.type == sf::Event::TextEntered) { sf::Uint32 code = ev.text.unicode; if (code >= 32 && code <= 126) { char c = static_cast<char>(code); activeField->addCharToText (c); return Gui::GuiEvent::CHAR_TYPED; } if (code == 8) { activeField->eraseChar (); return Gui::GuiEvent::MISSED; } //tabulation if (code == 9){ for (std::list<TextField*>::const_iterator iter = fieldsList.begin (); iter != fieldsList.end (); ++iter) { if ((*iter)->getIsActive ()) { (*iter)->setIsActive (false); ++iter; if (iter == fieldsList.end ()) iter = fieldsList.begin (); (*iter)->setIsActive (true); activeField = (*iter); break; } } return Gui::GuiEvent::MISSED; } } return Gui::GuiEvent::MISSED; } std::vector<std::string> TextFieldManager::getData () { std::vector<std::string> data; for (auto i : fieldsList) data.push_back (i->getText ()); return data; } void TextFieldManager::setMacAddress (std::string& mac) { for (auto &i : fieldsList) { i->resetMac (); i->setMac (mac); } } void TextFieldManager::addCharToMac (char& c) { for (auto &i : fieldsList) { i->addMacChar(c); } }
true
3b5cd509d9d4d5bf4d50fba9bb484a66b775b496
C++
TyeBryant/MaxKB
/dev/sdk/include/qgf2d/gameobject.h
UTF-8
1,753
2.53125
3
[]
no_license
#ifndef QGF2D_GAMEOBJECT_HEADER #define QGF2D_GAMEOBJECT_HEADER #include "kf/kf_vector2.h" #include <SFML/Graphics.hpp> #include "box2d/Box2D.h" namespace qgf { class GameObject { public: enum PhysicsStyle { e_psNone=0, e_psNewtonian, e_psBox2D }; kf::Vector2 m_position; kf::Vector2 m_velocity; kf::Vector2 m_force; float m_rotation; float m_life; bool m_dead; long long m_id; PhysicsStyle m_physicsStyle; bool m_overlap; int m_type; bool m_collide; bool m_gravity; sf::Sprite *m_sprite; b2Body *m_body; GameObject(); ~GameObject(); void update(float dt); void render(sf::RenderWindow *rw); GameObject &position(const kf::Vector2 &pos); GameObject &velocity(const kf::Vector2 &vel); kf::Vector2 position(); kf::Vector2 velocity(); GameObject &addForce(const kf::Vector2 &force); static GameObject *build(); }; typedef void (*CollisionCallback_t)(GameObject *obj1, GameObject *obj2); namespace GameWorld { kf::Vector2 gravity(); void gravity(const kf::Vector2 &grav); long long newID(); void update(float dt); void render(sf::RenderWindow *rw); } class ObjectTemplate { public: ObjectTemplate(); std::string m_imageName; kf::Vector2T<int> m_corner1,m_corner2; kf::Vector2 m_centre; int m_type; float m_life; bool m_gravity; GameObject *(*m_buildFunc)(); }; class ObjectFactory { public: ObjectFactory(); virtual ~ObjectFactory(); std::map<std::string, ObjectTemplate> m_objectTemplates; std::map<std::string, sf::Texture *> m_images; GameObject *addObject(const std::string name); sf::Texture *getImage(const std::string &filename); }; extern CollisionCallback_t CollisionCallback; extern ObjectFactory g_objectFactory; } #endif
true
368b47f2964d69498e4fd0aa95b2aa7aa3e41bf9
C++
Ajay35/spoj
/big_mod.cpp
UTF-8
319
2.65625
3
[]
no_license
#include <bits/stdc++.h> #define ll long long using namespace std; ll pow(ll a,ll b,ll c){ ll res=1; while(b){ if(b&1) res=(res*a)%c; a=(a*a)%c; b=b>>1; } return res; } int main(int argc, char const *argv[]) { ll a,b,c; while(cin>>a>>b>>c){ printf("%lld\n",pow(a,b,c)); } return 0; }
true
e01f918cbbf88bd40095db170d230d48b8c88379
C++
fagan2888/dtccClient
/dtccCommon/src/application/web/queries/eod.hpp
UTF-8
749
2.53125
3
[]
no_license
#ifndef QUERY_EOD_HPP_ #define QUERY_EOD_HPP_ #include <string> #include <locale> #include <boost/date_time.hpp> #include "application/web/query.hpp" #include "application/asset/description.hpp" namespace dtcc { namespace web { class eod : public query { public: eod(const boost::gregorian::date & date, const asset::description & asset) : query() , asset_(asset) , date_(date) , format_(std::locale::classic(), new boost::gregorian::date_facet("%Y_%m_%d")) {} virtual std::string path() const; boost::gregorian::date date() const; asset::description asset() const; private: asset::description asset_; boost::gregorian::date date_; std::locale format_; }; } } #endif /* QUERY_EOD_HPP_ */
true
11f76f798bcd92fe6ed4c4ebc51904346c95bce3
C++
nikkaramessinis/Qbert
/BitmapLoader.cpp
UTF-8
709
2.6875
3
[]
no_license
#include "BitmapLoader.h" ALLEGRO_BITMAP* BitmapLoader::GetBitmap(const std::string path) const { BitmapMap::const_iterator i = bitmaps.find(path); return i != bitmaps.end() ? i->second : (ALLEGRO_BITMAP*)0; } ALLEGRO_BITMAP * BitmapLoader::Load(const std::string& path) { ALLEGRO_BITMAP* b = GetBitmap(path); if (!b) { bitmaps[path] = (b = al_load_bitmap(path.c_str())); assert(b); } return b; } void BitmapLoader::CleanUp(void) { for (BitmapMap::iterator i = bitmaps.begin(); i != bitmaps.end(); i++) { //DestroyBitmap(i->second); } bitmaps.clear(); } BitmapLoader::BitmapLoader(void) { } BitmapLoader::~BitmapLoader(void) { CleanUp(); }
true
1db07684f7ded4dc346f55d67c88bb62830dc214
C++
MaquedaPaul/Ejercicios-C-
/Ejercicios-Nahuel/Bloque2/While.cpp
UTF-8
372
3.171875
3
[]
no_license
#include <iostream> #include <math.h> using namespace std; int main(){ float a, resultado; cout<<"Digite el valor del numero"; cin>>a; int cantidadVeces; cout<<"Digite la cantidad de veces a dividir"<<endl; cin>>cantidadVeces; int i=0; while (i < cantidadVeces) { a = a / 2; i++; } resultado = a; cout<<"El resultado es: "<<resultado<<endl; return 0; }
true
1ab0a4781a11d58e14e0691953a05ebc7c6cb703
C++
bargle/SympEngine
/API/message.h
UTF-8
785
3.1875
3
[ "MIT" ]
permissive
#ifndef _MESSAGE_H_ #define _MESSAGE_H_ #include <vector> #define CREATE_MESSAGE(x) CMessage *x = new CMessage; #define CREATE_MESSAGE_RESERVE(x, n) CMessage *x = new CMessage(n); #define RELEASE_MESSAGE(x) delete x; class CMessage { public: CMessage():m_nPointer(0){} CMessage(int nReserve):m_nPointer(0){ m_Data.reserve(nReserve); } ~CMessage(){ m_Data.clear(); } void SeekTo(int nSeek) { m_nPointer = nSeek; } void PushByte(uint8 nByte) { m_Data.push_back(nByte); } uint8 PopByte() { uint8 nByte = m_Data[m_nPointer]; ++m_nPointer; return nByte; } uint8 PeekByte() { return m_Data[m_nPointer]; } protected: typedef std::vector<uint8> MessageData; MessageData m_Data; uint32 m_nPointer; }; #endif
true
fa4a20c1b90de6adc744af0340c22b912aad5505
C++
zjucsxxd/ImageResizer
/src/include/matrix.hh
UTF-8
2,215
3.140625
3
[]
no_license
// File: matrix.hh // Date: Sun Dec 29 02:34:52 2013 +0800 // Author: Yuxin Wu <ppwwyyxxc@gmail.com> #pragma once #include <cstring> #include <memory> #include "debugutils.hh" #include "utils.hh" // basic 2-d array class Matrix { public: typedef real_t vtype; real_t **val; int w = 0, h = 0; Matrix(){} Matrix(int m_w, int m_h): // initialize with value 0 w(m_w), h(m_h) { val = new real_t* [h]; REP(i, h) val[i] = new real_t[w](); } ~Matrix() { free_2d<real_t>(val, h); } // something bad Matrix(const Matrix& m) { w = m.w, h = m.h; val = new real_t* [h]; REP(i, h) { val[i] = new real_t[w](); memcpy(val[i], m.val[i], w * sizeof(real_t)); } } Matrix & operator = (const Matrix & m) { if (this != &m) { free_2d<real_t>(val, h); w = m.w, h = m.h; val = new real_t* [h]; REP(i, h) { val[i] = new real_t[w](); memcpy(val[i], m.val[i], w * sizeof(real_t)); } } return *this; } Matrix & operator = (Matrix && r) { m_assert(this != &r); free_2d<real_t>(val, h); val = r.val; w = r.w, h = r.h; r.val = nullptr; return *this; } Matrix(Matrix&& r) { val = r.val; w = r.w, h = r.h; r.val = nullptr; } // something ugly real_t & get(int i, int j) { return val[i][j]; } const real_t & get(int i, int j) const { return val[i][j]; } Matrix transpose() const; Matrix prod(const Matrix & r) const; friend std::ostream& operator << (std::ostream& os, const Matrix & m); void normrot(); real_t sqrsum() const; Matrix col(int i) const; static Matrix I(int); }; template <typename T> class MatrixBase { public: T **val; int w, h; MatrixBase(int m_w, int m_h): w(m_w), h(m_h) { val = new T* [h]; for (int i = 0; i < h; i ++) val[i] = new T[w](); } MatrixBase(int m_w, int m_h, T** v) :w(m_w), h(m_h) { val = new T* [h]; int rowlen = w * sizeof(T); for (int i = 0; i < h; i++) { val[i] = new T [w](); if (v) memcpy(val[i], v[i], rowlen); } } ~MatrixBase() { for (int i = 0; i < h; i++) delete [] val[i]; delete [] val; } // get the ith row T*& operator [] (int i) { return val[i]; } };
true
7fc6bf40862778b33c0c59e160224781c1811e72
C++
AnPelec/Incremental-TopSort
/simple.h
UTF-8
460
2.703125
3
[]
no_license
#include <bits/stdc++.h> #include <iostream> typedef std::vector < size_t > vs; class SimpleAlgorithm { private: size_t n; size_t m; std::vector < size_t > L; // partial ordering of each node std::vector < vs > adj; // adjacency list bool update_label(size_t, size_t); public: SimpleAlgorithm(size_t, size_t); bool insert_edge(size_t, size_t); bool precedes(size_t, size_t); std::vector < size_t > topsort(void); };
true
e52311023548aa1e52e1414cdaa3d5ec274f8486
C++
Gtrakas1/OOP345
/LAB5_OOP345/LAB5_OOP345/Grades.h
UTF-8
475
3.109375
3
[]
no_license
#include <iostream> #include <string> #include <fstream> namespace sict { class Grades { std::string* studentnum; double* grade; size_t size; public: Grades() : studentnum(nullptr), grade(0), size(0) {} ~Grades(); Grades(std::string File); template<typename T> void displayGrades(std::ostream& os, T F) { for (int i = 0; i < size; i++) { os << studentnum[i] <<" "<< grade[i]<<" " << F(grade[i]) << "\n"; } } }; }
true
79e404cc5f75ad5ce9a29fd38c6fe80901b3dd7f
C++
RohitRajoria28/pep_practice
/LECTURE 4/b1.cpp
UTF-8
646
3.515625
4
[]
no_license
#include <iostream> using namespace std; int binary(int arr[], int size, int data) { int start =0; int end = size-1; while (start<=end) { int mid =start+end/2; if ( arr[mid]==data) { return mid ; } else if(arr[mid]< data) { start=mid+1; } else { end=mid -1; } } return -1; } int main() { int arr[]={10,20,30,40,50,60,70,80,80,90}; int size =sizeof(arr)/sizeof(int); int data; cout<<" enter the data to be found " <<data; cin>> data; cout<< binary(arr,data,size); }
true
9f43932dc9d8974ac9d36e122490167f011a303f
C++
AlConta/ITP_Study
/ITP/ITP_1_8_C/ITP_1_8_C.cpp
UTF-8
1,856
2.859375
3
[]
no_license
// ITP_1_8_C.cpp : このファイルには 'main' 関数が含まれています。プログラム実行の開始と終了がそこで行われます。 // #include<iostream> #include<string> #include<vector> using namespace std; #define rep(i, a, b) for(int i = a; i < b; i++) #define Rep(i, a, b) for(int i = a; i <= b; i++) #define sz(s) (int)s.size() int main() { string str; vector<int> vAlpha(26); while (getline(cin, str)) { rep(i, 0, sz(str)) { char c = str[i]; if (c >= 'A' && c <= 'Z') vAlpha[c - 'A']++; else if (c >= 'a' && c <= 'z') vAlpha[c - 'a']++; } } rep(i, 0, 26) { cout << char('a' + i) << " : " << vAlpha[i] << "\n"; } return 0; } // プログラムの実行: Ctrl + F5 または [デバッグ] > [デバッグなしで開始] メニュー // プログラムのデバッグ: F5 または [デバッグ] > [デバッグの開始] メニュー // 作業を開始するためのヒント: // 1. ソリューション エクスプローラー ウィンドウを使用してファイルを追加/管理します // 2. チーム エクスプローラー ウィンドウを使用してソース管理に接続します // 3. 出力ウィンドウを使用して、ビルド出力とその他のメッセージを表示します // 4. エラー一覧ウィンドウを使用してエラーを表示します // 5. [プロジェクト] > [新しい項目の追加] と移動して新しいコード ファイルを作成するか、[プロジェクト] > [既存の項目の追加] と移動して既存のコード ファイルをプロジェクトに追加します // 6. 後ほどこのプロジェクトを再び開く場合、[ファイル] > [開く] > [プロジェクト] と移動して .sln ファイルを選択します
true
9826b76d6b1f7da64412ca4dd63f523d27a8b7c0
C++
yumdeer/daily_practice
/vs_project/Template_/依赖/依赖.cpp
UTF-8
624
3.453125
3
[]
no_license
#include <iostream> #include <list> template <typename T> class CCustomerList { public: void push(T item) { m_customer.push_back(item); } void show_item() { CCIterator it = m_customer.begin(); while (it != m_customer.end()) { std::cout << (*it) << std::endl; ++it; } } private: typedef std::list<T> CustomerContainer; //typedef typename CustomerContainer::iterator CCIterator; typedef typename CustomerContainer::iterator CCIterator; CustomerContainer m_customer; }; int main(int argc, char *argv[]) { CCustomerList<int> c; for (int i = 0; i < 10; ++i) c.push(i); c.show_item(); return 0; }
true
a646a3c6a30c96f1c2c4d77fe64ab81502818447
C++
sychov/seabattle
/screen.h
UTF-8
771
2.828125
3
[]
no_license
// // Header: some functions for text-mode output with color and positioning // /////////////////////////////////////////////////////////////////////////////// #pragma once namespace seabattle_screen { // -----ENUMS----- enum class Colors { Black, Blue, Green, Cyan, Red, Magenta, Yellow, LightGrey, Grey, LightBlue, LightGreen, LightCyan, LightRed, LightMagenta, LightYellow, White }; // -----FUNCTIONS----- void PrintChar(int x, int y, char character, Colors fg, Colors bg); void PrintString(int x, int y, const char *str, Colors fg, Colors bg); void GotoXY(int x, int y); void SetColor(Colors fg, Colors bg); // -----CONST----- const int k_messagesStartRow = 27; const int k_messagesMaxRows = 8; }
true
5b6e5c106cf123171b5b1d67e953d49df0f8d59e
C++
HC-Chang/Learn-CPlusPlus
/10-Pointer/3.cpp
UTF-8
1,003
3.625
4
[]
no_license
# include <iostream> using namespace std; // pointer - 3 void method1(); void method2(); void method3(); int main() { method1(); cout << "\n"; method2(); cout << "\n"; method3(); return 0; } void method1() { double x = 3.14; double y = 2.71; double *p1 = &x; double *p2 = &y; cout << "This is p for x = " << *p1 << endl; cout << "This is p for y = " << *p2 << endl; p1 = p2; cout << "This is p for x = " << *p1 << endl; } void method2() { int x = 7; double y = 6.21; int *p1 = &x; double *p2 = &y; *p1 = *p2; cout << *p1 << endl; } void method3() { int *p; int x = 7; p = &x; cout << "This is p = " << p << endl; cout << "This is *p = " << *p << endl; cout << "This is x = " << x << endl; *p = 100; cout << "This is p = " << p << endl; cout << "This is *p = " << *p << endl; cout << "This is x = " << x << endl; x = 10; cout << "This is p = " << p << endl; cout << "This is *p = " << *p << endl; cout << "This is x = " << x << endl; }
true