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
3967b0978c4ced52caa7499da39aa8b09ab85986
C++
SaraElbesomy4/Castle-game---Data-structure
/Castle/Enemyheap.h
UTF-8
4,505
4
4
[]
no_license
#ifndef ENEMYHEAP_H #define ENEMYHEAP_H #include "..\Enemies\Enemy.h" #include <iostream> using namespace std; template <int const MAX_HEAP_SIZE=100> class Enemyheap { private: Enemy* Elements[MAX_HEAP_SIZE]; // Array of pointers int size; // Number of elements in the heap public: Enemyheap(); // Parameterized constructor ~Enemyheap(); // Destructor void ReheapDown(int root); // Reheap after removing item void ReheapUp(int child_index); // Reheap after inserting item bool Enqueue(Enemy *item); // Add an item to the heap Enemy *Dequeue(); // Get item at the root int GetSize(); // Return number of elements in the heap void printPriotity(); // Print all the elements in the heap }; template <int const MAX_HEAP_SIZE> Enemyheap<MAX_HEAP_SIZE>::Enemyheap() { size = 0; } //--------------------------------------- // Destructor //--------------------------------------- template <int const MAX_HEAP_SIZE> Enemyheap<MAX_HEAP_SIZE>::~Enemyheap() { } //--------------------------------------- // Reheap after removing item //--------------------------------------- template <int const MAX_HEAP_SIZE> void Enemyheap<MAX_HEAP_SIZE>::ReheapDown(int root) { int maxChild_index; int leftChild_index; int rightChild_index; Enemy *temp; leftChild_index = root * 2 + 1; // Get index of root's left child rightChild_index = root * 2 + 2; // Get index of root's right child // Check base case in recursive calls. If leftChild's index is less // than or equal to the bottom index we have not finished recursively // reheaping. if (leftChild_index <= (size-1)) { if (leftChild_index == (size-1)) // If this root has no right child then { maxChild_index = leftChild_index; // leftChild must hold max key } else { // Get the one lowest in the tree (highest index in the array) if (Elements[leftChild_index]->GetPriority() <= Elements[rightChild_index]->GetPriority()) maxChild_index = rightChild_index; else maxChild_index = leftChild_index; } if (Elements[root]->GetPriority() < Elements[maxChild_index]->GetPriority()) { // Swap these two elements temp = Elements[root]; Elements[root] = Elements[maxChild_index]; Elements[maxChild_index] = temp; // Make recursive call till reheaping completed ReheapDown(maxChild_index); } } } //--------------------------------------- // Reheap after inserting item //--------------------------------------- template <int const MAX_HEAP_SIZE> void Enemyheap<MAX_HEAP_SIZE>::ReheapUp(int child_index) { int parent_index; Enemy *temp; // Check base case in recursive calls. If bottom's index is greater // than the root index we have not finished recursively reheaping. if (child_index > 0) { parent_index = (child_index - 1) / 2; if (Elements[parent_index]->GetPriority() < Elements[child_index]->GetPriority()) { // Swap these two elements temp = Elements[parent_index]; Elements[parent_index] = Elements[child_index]; Elements[child_index] = temp; // Make recursive call till reheaping completed ReheapUp(parent_index); } } } //--------------------------------------- // Add an item to the heap //--------------------------------------- template <int const MAX_HEAP_SIZE> bool Enemyheap<MAX_HEAP_SIZE>::Enqueue(Enemy *item) { if (size < MAX_HEAP_SIZE && item != nullptr) { Elements[size] = item; // Copy item into array ReheapUp(size); size++; return true; } return false; } //--------------------------------------- // Get item at the root //--------------------------------------- template <int const MAX_HEAP_SIZE> Enemy *Enemyheap<MAX_HEAP_SIZE>::Dequeue() { if (size <= 0) return nullptr; Enemy *temp = Elements[0]; size--; // Copy last item into root Elements[0] = Elements[size]; // Reheap the tree ReheapDown(0); return temp; } //--------------------------------------- // Return number of elements in the heap //--------------------------------------- template <int const MAX_HEAP_SIZE> int Enemyheap<MAX_HEAP_SIZE>::GetSize() { return size; } //--------------------------------------- // Print all the elements in the heap //--------------------------------------- template <int const MAX_HEAP_SIZE> void Enemyheap<MAX_HEAP_SIZE>::printPriotity() { for (int i = 0; i<size; i++) { cout << "Heap element " << i << ". key=" << Elements[i]->GetPriority() << endl; } } #endif
true
9a158ce6eec414cea35a03175fbeea7b411fcc49
C++
skrphv/ITVDN-Advanced
/lesson10_main.cpp
UTF-8
1,018
3.71875
4
[]
no_license
#include <iostream> #include <string> #include <cassert> #include <deque> #include <stack> #include <sstream> #include <algorithm> #include <iterator> void reverse_text (std::string& text) { //1) split to words std::istringstream test_stream {text}; std::deque<std::string> text_in_words {}; std::string word {}; while ( test_stream >> word ) { text_in_words.push_front(std::move(word)); } //2) reversing std::ostringstream result_stream{}; std::copy(std::make_move_iterator(text_in_words.begin()), std::make_move_iterator(text_in_words.end()), std::ostream_iterator<std::string>(result_stream, " ")); text = result_stream.str(); std::cout << *text_in_words.begin() << std::endl; } int main() { std::string test_str1 { "Test1 Test2 Test3" }; std::string reverse_test_str1 { "Test3 Test2 Test1 "}; reverse_text (test_str1); assert(test_str1 == reverse_test_str1); std::cout << "Ok!!" << std::endl; return 0; }
true
a514d0da4b7ddd8f815aba9afe229a638b3860d6
C++
marromlam/lhcb-software
/Online/Online/OMAlib/algorithms/OMACompareToReference.cpp
UTF-8
1,549
2.640625
3
[]
no_license
#include <TH1F.h> #include <TF1.h> #include "OMAlib/OMAAlgorithms.h" #include "OMAlib/OMAlib.h" #include <sstream> OMACompareToReference::OMACompareToReference(OMAlib* Env) : OMACheckAlg("CompareToReference", Env) { m_ninput = 1; m_inputNames.push_back("Test"); m_inputDefValues.push_back(1.f); m_npars = 1; m_parnames.push_back("Min_p-value"); m_parDefValues.push_back(.01f); m_doc = "Compares histogram to reference performing a Kolmogorov (Test=1, default) or chi2 (Test=2) test."; m_needRef = true; } void OMACompareToReference::exec(TH1 &Histo, std::vector<float> & warn_thresholds, std::vector<float> & alarm_thresholds, std::vector<float> & input_pars, unsigned int anaID, TH1* Ref) { if( warn_thresholds.size() <m_npars || alarm_thresholds.size() <m_npars) return; int test =1; double pvalue=1.; if(input_pars.size() > 0) test = (int) (input_pars[0]+0.1); if(Ref){ if (test ==1 ) { pvalue = Histo.Chi2Test(Ref); } else if (test == 2 ) { pvalue = Histo.KolmogorovTest(Ref); } } else { return; } std::stringstream message; std::string hname(Histo.GetName()); message << "Comparison Test p-value= "<< pvalue; raiseMessage( anaID, ( pvalue < warn_thresholds[0] ), ( pvalue < alarm_thresholds[0] ), message.str(), hname); }
true
487a087f33873802be064ca5cff8bbc3e5b2bd99
C++
Balnian/Technique_Nouvelle_Image
/Image/Source.cpp
WINDOWS-1250
1,553
3.578125
4
[]
no_license
#include <iostream> #include <memory> using namespace std; class Image { bool original = true; protected: Image(const Image&) = default; public: Image() = default; void modifier() { original = false; } bool est_modifier() const { return !original; } virtual Image* cloner() const = 0; virtual void Dessiner() const = 0; virtual ~Image() = default; }; class Jpeg :public Image { protected: Jpeg(const Jpeg&) = default; public: Jpeg() = default; Jpeg *cloner() const override { return new Jpeg{*this}; } void Dessiner() const override { cout << "JPeg" << endl; } }; class Png : public Image { protected: Png(const Png&) = default; public: Png() = default; Png *cloner() const override { return new Png{ *this }; } void Dessiner() const override { cout << "Png" << endl; } }; unique_ptr<Image> ModifMaybe(unique_ptr<Image> p) { unique_ptr<Image> bak{ p->cloner() }; // modifier *p ... omis pour fin de simplicit cout << "Voulez-vous conserver les modifs? "; char c; while (cin >> c && c != 'O' && c != 'N') cout << "Voulez-vous conserver les modifs? "; // si l'usager veut garder les modifs, on scrappe le backup //sinon on scrappe p if (c == 'N') swap(p, bak); return p; } int main() { unique_ptr<Image> p{ new Png }; p = ModifMaybe(move(p)); p->Dessiner(); if (p->est_modifier()) { cout << "(Version modifier)" << endl; } else { cout << "(Version original)" << endl; } }
true
7e45435ed850741b261d273de96f4895187e183a
C++
EduardoVaz06/n2
/Pessoa.hpp
UTF-8
476
2.75
3
[]
no_license
#include <iostream> using namespace std; #ifndef PESSOA_hpp #define PESSOA_hpp class Pessoa { public: Pessoa(){}; Pessoa(string n, string en, int tel); void setNome(string n); string getNome(); void setEndereco(string en); string getEndereco(); void setTelefone(int tel); int getTelefone(); virtual void imprimeInfo(); protected: string nome; string endereco; int telefone; }; #endif
true
9325335da4af38167d579d8e20ffec8a170f3a50
C++
knavite/LeetCode
/Happy Number/solution.cpp
UTF-8
469
2.828125
3
[]
no_license
class Solution { public: bool isHappy(int n) { map<int,int> m; int flag=0; while(m[n]==false) { m[n]=true; int newN=0; while(n!=0) { int d=n%10; newN+=d*d; n=n/10; } n=newN; if(n==1) { flag=1; break; } } if(flag) return true; else return false; } };
true
c8a2611b380dfdbd4700cfe4698316808e5c7c60
C++
YiBasuo/BackTest
/Utility.cpp
UTF-8
2,634
3
3
[]
no_license
#include <iostream> #include <sstream> #include <ctime> #include <cstring> #include "Constants.h" #include "Utility.h" using namespace std; string Error::GetMsg() { return msg; } ostream& operator<<(ostream& os, const DataLineT& dataline) { stringstream iss; iss << GetDateTimeStr(dataline.dateTime); if (dataline.updateMillisec == 0) { iss << ".0"; } if (dataline.updateMillisec == 500) { iss << ".5"; } iss << "\t" << dataline.instrumentID; iss << "\t" << dataline.lastPrice; iss << "\t" << dataline.preSettle; iss << "\t" << dataline.preClose; iss << "\t" << dataline.preOpenInterest; iss << "\t" << dataline.openPrice; iss << "\t" << dataline.highestPrice; iss << "\t" << dataline.lowestPrice; iss << "\t" << dataline.volume; iss << "\t" << dataline.turnover; iss << "\t" << dataline.openInterest; iss << "\t" << dataline.upperLimitPrice; iss << "\t" << dataline.lowerLimitPrice; iss << "\t" << dataline.bidPrice; iss << "\t" << dataline.bidVolume; iss << "\t" << dataline.askPrice; iss << "\t" << dataline.askVolume; iss << "\t" << dataline.averagePrice; os << iss.str(); return os; } std::ostream& operator<<(std::ostream& os, const PositionT& posi) { stringstream iss; iss << "Position " << (posi.direction == LONG_POSI ? "Long(+)" : "Short(-)"); iss << " | Lots: " << posi.lots; iss << " | Price " << posi.price; iss << " | opened at time " << ctime(&posi.openTime); os << iss.str(); return os; } double operator-(const DataLineT& left, const DataLineT& right) { return difftime(left.dateTime, right.dateTime) + (left.updateMillisec - right.updateMillisec) / 1000.0; } double operator-(const DataLineT& left, time_t rightTime) { return difftime(left.dateTime, rightTime) + left.updateMillisec / 1000.0; } double operator-(time_t leftTime, const DataLineT& right) { return difftime(leftTime, right.dateTime) + right.updateMillisec / 1000.0; } string GetDateTimeStr(time_t dateTime) { tm* ptm = localtime(&dateTime); //"2011-07-18 23:03:01 "; string strFormat = "%Y-%m-%d %H:%M:%S"; char buffer[30]; strftime(buffer, 30, strFormat.c_str(), ptm); string dateTimeStr(buffer); return dateTimeStr; } time_t ConvertStringToTime(const string & timeString) { if (timeString.size() >= max_time_string_size_c) { string msg = "DataGenerator: ConvertStringToTime\ntimeString -" + timeString + "- is too long"; throw Error(msg); } tm rawtm; time_t time; char buf[max_time_string_size_c]; strcpy(buf, timeString.c_str()); strptime(buf, "%Y-%m-%d %H:%M:%S", &rawtm); rawtm.tm_isdst = -1; time = mktime(&rawtm); return time; }
true
45d642538be748b7b81e1a930c50f2862a8fd962
C++
zhufeizhu/Process
/src/PriorityQueue.cpp
UTF-8
1,706
3.59375
4
[]
no_license
#include "PriorityQueue.h" #include "ListItem.h" #include "Node.h" PriorityQueue::PriorityQueue():front(nullptr),back(nullptr),size(0){}; bool PriorityQueue::isEmpty(){ return size == 0; } void PriorityQueue::enqueue(ListItem *item){ // special case: adding to empty queue if(front == nullptr){ front = new Node(item, nullptr); back = front; } else { if (item->compareTo(front->getItem()) > 0){ //表明待插入的节点应该为首节点 Node *node = new Node(item,front); front = node; } else{ Node *pre = front; Node *next = front->getNext(); while(next && item->compareTo(next->getItem()) < 0){ //next节点存在且优先级低于next节点时 向后遍历 pre = next; next = next->getNext(); } //当跳出循环时表明当前节点一定比pre节点优先级低 且next节点不存在或者比其优先级高 Node *node = new Node(item,next); pre->setNext(node); if (!next){ //表明需要更新back指针 back = node; } } } size++; }// enqueue ListItem *PriorityQueue::dequeue(){ ListItem *theItem = nullptr; Node *theNode = front; if(front != nullptr){ theItem = front->getItem(); // special case: removing last item if(front == back){ front = back = nullptr; } else { front = front->getNext(); } size--; delete(theNode); } return theItem; }// dequeue ListItem *PriorityQueue::getFront(){ ListItem *theItem = nullptr; if(front != nullptr){ theItem = front->getItem(); } return theItem; }// getFront
true
65d73e9c280b84f7c75831d10a154e77bfd4d287
C++
walterfreeman/phy211
/_site/slides/lec12/gas3d.cpp
UTF-8
21,730
3.109375
3
[]
no_license
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> #include "vector.h" #include <omp.h> int ilist_size=1000000; // how much memory to allocate for the list of possible interactions int N=2000; // default number of particles (probably changed later) double L=1; // box width double r0=0.015; // interaction radius int NG; // number of zones in each direction. Set later double pad=2; // At what multiple of r0 do we assume the force is small and neglect the interactions? double timer[10]; // Array shared by starttimer() and stoptimer() for timing things double steprate; double forcerate; // the following is a new thing y'all haven't learned yet. Ask me about in person; this is used to make // "linked lists", which are a way of keeping track of which particles are where. struct list_el { int val; struct list_el *next; }; typedef struct list_el item; double myclock(void) { return omp_get_wtime(); } bool istime3(int msec) { static double lasttime=0; if (myclock() - lasttime > msec / 1000.0) { lasttime=myclock(); return true; } else return false; } // Just a dopey timing function that tells you if n milliseconds have passed since the last time you called it // "bool" = "boolean", true or false (1 or 0, basically) bool istime2(int msec) { static double lasttime=0; if (myclock() - lasttime > msec / 1000.0) { lasttime=myclock(); return true; } else return false; } bool istime(int msec) { static double lasttime=0; if (msec == 0) { lasttime=myclock(); return false; } if (myclock() - lasttime > msec / 1000.0) { return true; } else return false; } // given a particle's position, which zone is it in? ivec getzone (vector v) { ivec result; result.x=(int)((v.x+L/2)*NG/L); result.y=(int)((v.y+L/2)*NG/L); result.z=(int)((v.z+L/2)*NG/L); if (result.x>=NG) result.x=NG-1; if (result.x<0) result.x=0; if (result.y>=NG) result.y=NG-1; if (result.y<0) result.y=0; if (result.z>=NG) result.z=NG-1; if (result.z<0) result.z=0; // printf("!Particle in zone (%d, %d, %d)\n",result.x, result.y, result.z); return result; } // add/remove an item from linked lists -- will explain this in person void add(item **list, int v) { // printf("!Adding item %d\n",v); item *curr; curr=(item *)malloc(sizeof(item)); curr->val = v; curr->next = *list; *list=curr; } void del (item **list, int v) { item *curr; curr=*list; item *temp; if (curr == NULL) {return;} // printf("!Deleting item %d... list starts with %d (%d)\n",v,*list,(*list)->val); if (curr->val == v) {*list=curr->next; free(curr);} else while (curr -> next != NULL) { if (curr->next->val == v) { temp=curr->next; curr->next=curr->next->next; free(temp); break; } curr=curr->next; } } // cycle through all the particles and put them in the right zones void check_zonelist(item **zonelist,ivec zone[], vector pos[]) { ivec cz; // the correct zone for the particle to be in for (int i=0;i<N;i++) { // printf("zonelist check: particle %d of %d\n",i,N); cz = getzone(pos[i]); if (cz.x != zone[i].x || cz.y != zone[i].y || cz.z != zone[i].z) // if we're not in the right zone, fix it { if (zone[i].x >= 0 && zone[i].x < NG && zone[i].y >= 0 && zone[i].y < NG && zone[i].z >= 0 && zone[i].x < NG) del(&zonelist[zone[i].x*NG*NG + zone[i].y * NG + zone[i].z],i); add(&zonelist[cz.x*NG*NG + cz.y*NG + cz.z],i); } zone[i]=cz; // printf("Done checking zone of particle %d of %d (it's in (%d, %d, %d)\n",i,N,cz.x,cz.y,cz.z); } } // a function for V(r), used only to compute total energy double V(double r) { if (r > r0*pad) return V(r0*pad); r/=r0; static double r6; r6=r*r*r*r*r*r; return (4*r0*(1/(r6*r6)-1/r6)); } double V2(double r) { if (r*r > r0*r0*pad*pad) return V2(r0*r0*pad*pad); r/=(r0*r0); static double r6; r6=r*r*r; return (4*r0*(1/(r6*r6)-1/r6)); } // derpy timing functions: this one starts a timer with index t... void starttimer(int t) { timer[t]=myclock(); } // and this one stops it, returning how long it's been in microseconds since starttimer was called double stoptimer(int t) { return myclock()-timer[t]; } // NOTE: Actually returns F/r to avoid having to do a square root in velocity_update // when dealing with the unit vectors. This is why it's r^14-r^8. // Square roots are 'spensive. double force(double r2) { static double r8,r14,r6; r6=r2*r2*r2; // doing this is substantially faster than using pow() r8=r6*r2; r14=r6*r8; return -24.*(2./r14 - 1./r8) / r0; // the factor of 24 is in some canonical form of this. gods know why. } double drnd48(void) // just a way to get a centered random number { return drand48()-0.5; } void draw_box(double L) { // baaaaarf. printf("l3 -%e -%e -%e -%e -%e %e\n",L,L,L,L,L,L); printf("l3 -%e -%e %e -%e %e %e\n",L,L,L,L,L,L); printf("l3 -%e %e %e -%e %e -%e\n",L,L,L,L,L,L); printf("l3 -%e %e -%e -%e -%e -%e\n",L,L,L,L,L,L); printf("l3 %e -%e -%e %e -%e %e\n",L,L,L,L,L,L); printf("l3 %e -%e %e %e %e %e\n",L,L,L,L,L,L); printf("l3 %e %e %e %e %e -%e\n",L,L,L,L,L,L); printf("l3 %e %e -%e %e -%e -%e\n",L,L,L,L,L,L); printf("l3 %e -%e -%e -%e -%e -%e\n",L,L,L,L,L,L); printf("l3 %e %e -%e -%e %e -%e\n",L,L,L,L,L,L); printf("l3 %e -%e %e -%e -%e %e\n",L,L,L,L,L,L); printf("l3 %e %e %e -%e %e %e\n",L,L,L,L,L,L); } // This is the function I said I'd give you a copy of. What this does: // * assumes that zonelist is an array of linked lists, one for each zone, that holds the particles in each zone // * ... and that zone is an array of size N that holds which zone each particle is in // * For each particle i in the simulation: // * For its own zone and all adjacent zones: // * For each particle j in those zones (iterated over with the while loop -- I'll explain this in person) // * If the distance from i to j is more than r0*pad, do nothing // * ... otherwise, add that pair of particles to ilist1 and ilist2, and their squared distance to r2list // When we're done, ilist1 and ilist2 contain paired lists of all the interactions worth thinking about // ... and r2list contains how far away those particles are, so you don't have to work it out again // This returns the number of interactions that we found, so we know how far to take the for loops later int build_interaction_list(const vector pos[],item *zonelist[],const ivec zone[],int ilist1[],int ilist2[], double r2list[], vector seplist[]) { // need to make some internally-used interaction list arrays for the threads static int * ilist1p=(int *)malloc(sizeof(int) * ilist_size); static int * ilist2p=(int *)malloc(sizeof(int) * ilist_size); static double * r2p=(double *)malloc(sizeof(double) * ilist_size); static vector * seplistp=(vector *)malloc(sizeof(vector) * ilist_size); const int iliststride=ilist_size / omp_get_max_threads(); int num_found[omp_get_max_threads()]={0}; // keep track of how many interactions we've found already -- // separate per thread! #pragma omp barrier #pragma omp parallel { int num_found_local=0; ivec myzone; //ivec = vector of integers (only used here) item *curr; int i, j, k, l, m; int tid=omp_get_thread_num(); int nth=omp_get_num_threads(); int stride=N/nth+1; // printf("!I am thread %d, scanning from %d to %d\n",tid,stride*tid, stride*(tid+1)-1); for (i=stride*tid; i<stride*(tid+1); i++) { double r2; if (i >= N) break; myzone=getzone(pos[i]); int index; for (k=myzone.x-1; k<=myzone.x+1; k++) for (l=myzone.y-1; l<=myzone.y+1; l++) for (m=myzone.z-1; m<=myzone.z+1; m++) { // if we've driven off the edge of the simulation region, ignore and move to // the next zone if (k<0 || k>=NG || l<0 || l>=NG || m<0 || m>=NG) continue; curr=zonelist[k*NG*NG + l*NG + m]; // this awkwardness avoids the issues with passing multidimensional arrays // while there are particles left in this zone... while (curr) { j=curr->val; // skip if pair misordered, same particle, or further apart than permitted // this last condition may seem silly, but it allows us to consistently truncate // the force so that the physics don't depend on the exact layout of the zone boundaries. // (it also makes things faster.) //r2=(pos[i]-pos[j])*(pos[i]-pos[j])/(r0*r0); // squared distance between, in units of r0 if (i<=j) {curr=curr->next; continue;} r2 = ((pos[i].x - pos[j].x) * (pos[i].x - pos[j].x) + (pos[i].y - pos[j].y) * (pos[i].y - pos[j].y) + (pos[i].z - pos[j].z) * (pos[i].z - pos[j].z))/(r0*r0); if (r2 > pad*pad) {curr=curr->next; continue;} index = num_found_local+iliststride*tid; // if (i<=j || r2 > pad*pad) {curr=curr->next; continue;} r2p[index] = r2; // it is very marginally faster to store a third array, containing the squared seplistp[index] = (pos[i] - pos[j]); // distances between particles, so we don't have to compute it again. ilist1p[index] = i; ilist2p[index] = j; num_found_local++; curr=curr->next; } } } num_found[tid]=num_found_local; } #pragma omp barrier // merge lists int numtotal=0; for (int i=0; i<omp_get_max_threads(); i++) { // printf("!Found %d interactions in list %d\n",num_found[i],i); for (int j=0; j<num_found[i]; j++) { ilist1[numtotal]=ilist1p[j + iliststride*i]; ilist2[numtotal]=ilist2p[j + iliststride*i]; r2list[numtotal]=r2p[j + iliststride*i]; seplist[numtotal]=seplistp[j + iliststride*i]; numtotal++; } } // printf("!Found %d total.\n",numtotal); // printf("!Entire interaction list cost: %f us\n",stoptimer(9)*1e3); for (int i=0; i<numtotal; i++) { // printf("!Merged: Interaction %d between %d and %d, distance %e\n",i,ilist1[i],ilist2[i], r2list[i]); } return numtotal; } void position_step(vector *pos, vector *vel, double dt) { for (int i=0; i<N; i++) pos[i] += vel[i] * dt; } void velocity_step(vector *pos, vector *vel, double *m, int *ilist1, int *ilist2, double *r2list, int nint, double dt, int *nints) { double PE=0; vector sep; double r2; for (int i=0; i<N; i++) nints[i]=0; for (int i=0; i<nint; i++) // traverse the interaction list in ilist1 and ilist2 { vector F; int j,k; j=ilist1[i]; k=ilist2[i]; nints[j]++; nints[k]++; sep=pos[j]-pos[k]; // r2 = sep*sep/r0*r0; // if (r2 > pad*pad) continue; // F=(force((sep*sep)/(r0*r0))*dt)*sep; // parentheses not absolutely necessary but may save a few flops F=(force((r2list[i]))*dt)*sep; // is it faster to look up the radius in the list, or compute it? // maybe for bigger problems that don't fit into cache the above is better vel[j] -= F/m[j]; vel[k] += F/m[k]; } } double kinetic(vector v[], double m[]) { double T=0; for (int i=0;i<N;i++) T+=0.5*m[i]*v[i]*v[i]; // note that v*v does a dot product return T; } double potential(vector pos[]) { double U=0; for (int i=0;i<N;i++) for (int j=i+1;j<N;j++) { U+=V(norm(pos[i]-pos[j])); } return U; } // dummy space int main(int argc, char **argv) { printf("font large\n"); double time_intlist=0; double time_velstep=0; double lastframetime=0; double time_posstep=0; double time_check=0; double time_checklist=0; double time_anim=0; double lastchecksteps=0; double time_energy=0; // some variables for timing double dt=1e-3, vinit=0; double P=0, T=0, U, J=0; // J is impulse -- haven't finished that bit yet int i=0,j=0,k=0,l=0; int ninttotal=0; int nint=0; int drawn=0; int *ilist1=NULL,*ilist2=NULL; double *r2list=NULL; vector *seplist=NULL; double KE=0, PE=0,Tnow=0; ilist1=(int *)malloc(sizeof(int) * ilist_size); ilist2=(int *)malloc(sizeof(int) * ilist_size); r2list=(double *)malloc(sizeof(double) * ilist_size); seplist=(vector *)malloc(sizeof(vector) * ilist_size); printf("!Allocated...\n"); double thermo_interval=1; double next_thermo=thermo_interval; double Taccum=0; printf("!!%d parameters\n",argc); if (argc < 11) // if they didn't give us command line parameters, die and print out the order { printf("!!Usage: <this> <N> <dt> <vinit> <pad> <L> <draw_msec> <neighbor threshold> <threads> <t_max> <temp target> <temp change rate>\n"); exit(1); } // read command line parameters N=atoi(argv[1]); dt=atof(argv[2]); vinit=atof(argv[3]); pad=atof(argv[4]); L=atof(argv[5]); double drawms=atof(argv[6]); int drawthreshold=atoi(argv[7]); int threads=atoi(argv[8]); double tmax=atof(argv[9]); omp_set_num_threads(threads); double Ttarget=atof(argv[10]); double smult=atof(argv[11]); double rate=1; NG=L/(r0*pad); printf("!!Read parameters. Drawing every %f ms\n",drawms); ivec zone[N]; int lastframe=0; vector pos[N],v[N]; double drawbuf[N*7]; double m[N]; int interactioncount[N]; double smooth_interaction_count[N]={0}; char logfilename[100]; snprintf(logfilename,100,"thermodynamics_N%d_dt%s_pad%s_L%s_vinit%s.dat",N,argv[2],argv[4],argv[5],argv[3]); printf("!!Opening file %s for thermodynamics data\n",logfilename); FILE *logfile=fopen(logfilename,"w"); fprintf(logfile,"# Starting up: N=%d dt=%e pad=%e L=%e\n",N,dt,pad,L); fprintf(logfile,"time\tPV\tNkT\tPV/NkT\tEnergy\n"); FILE *energyfile=fopen("energy.txt","w"); printf("!!NG = %d, NG^3 = %d\n",NG,NG*NG*NG); // item *zonelist[NG*NG*NG]; item **zonelist; zonelist=(item **)malloc(NG*NG*NG*sizeof(item *)); for (i=0;i<NG*NG*NG;i++) { zonelist[i]=NULL; } printf("!!Allocated zone list array\n"); // set up initial conditions double interval = r0 * pow(2,1./6.); // how far away to put the particles at the start for (i=0;i<N;i++) { j++; if (j>pow(N,1./3.)) {j=0;k++;} if (k>pow(N,1./3.)) {k=0;l++;} zone[i].x=-1; zone[i].y=-1; zone[i].z=-1; // set these to -1, we'll fix later pos[i].x=k*interval-interval * pow(N,1./3.)/2; pos[i].y=l*interval-interval * pow(N,1./3.)/2; pos[i].z=j*interval-interval * pow(N,1./3.)/2; v[i].x=drnd48()*vinit; v[i].y=drnd48()*vinit; v[i].z=drnd48()*vinit; m[i]=1; } printf("!!Initialization done: N = %d\n",N); check_zonelist(zonelist,zone,pos); // put particles in the right zones to start printf("!!start main loop\n"); int steps=0; for (double t=0; t<tmax; t+=dt) { #pragma omp barrier starttimer(9); if (istime2(4000) && 0) { KE=kinetic(v,m); PE=potential(pos); fprintf(energyfile,"%e %e\n",t,KE+PE); fflush(energyfile); } time_energy+=stoptimer(9); #pragma omp barrier if (istime(drawms)) // anim time // if (steps % 100 == 0) { int drawct=0; starttimer(4); // it's actually super expensive to compute the total energy since we do it // pairwise to ensure absolute sanity, so do it only every 100 anim updates printf("C 0.5 1 0.5\n"); // draw particles for (i=0;i<N;i++) { drawbuf[i*7+0] = pos[i].x; drawbuf[i*7+1] = pos[i].y; drawbuf[i*7+2] = pos[i].z; drawbuf[i*7+3] = r0/4; if (smooth_interaction_count[i] < drawthreshold) { drawbuf[i*7+4] = 0.5; drawbuf[i*7+5] = 1; drawbuf[i*7+6] = 0.5; } else { drawbuf[i*7+4] = 1; drawbuf[i*7+5] = 0.2; drawbuf[i*7+6] = 0.2; } // if (i==0) printf("C 1 1 1\n"); // if (i==1) printf("C 0.5 1 0.5\n"); // if (i<1) printf("ct3 %d %.3e %.3e %.3e %.3e\n",i,pos[i].x,pos[i].y,pos[i].z,r0/4); } printf("manycoloredballs %d\n",N); fwrite(drawbuf, N*7, sizeof(double), stdout); printf("C 0.7 0.2 0.2\n"); draw_box(L/2); printf("C 0.5 0.5 1\n"); // printf("T -0.9 0.85\nt=%.3f/%.2f, E=%.5e = %.5e + %.5e\n",t,next_thermo,KE+PE,KE,PE); //POS // printf("T -0.9 0.68\nCurrent temp = %.3e\tTarget = %.3e\trate = %.4e\n",Tnow,Ttarget,rate); printf("T -0.9 0.75\nPV = %.4e \t NkT = %.4e \t ratio = %f\n",P*L*L*L,N*T,P*L*L*L/(N*T)); if (rate > 0 ) printf("T -0.9 0.68\nCurrent temp = %.3e\tTarget = %.3e\trate = %.4e\n",Tnow,Ttarget,rate); printf("T -0.9 0.85\nSimulation rate: %.1f steps per second, %.2f million forces/sec, %d particles\n",steprate,forcerate/1e6,N); lastframe=steps; printf("F\n"); // printf("!!%d interactions\n",nint); if (istime3(drawms*2) && 0) { for (j=0; j<nint; j++) { if (fabs(seplist[j].x)<r0*10) { printf("!c3 %.4e %.4e %.4e %.4e\n",-seplist[j].x,-seplist[j].y,-seplist[j].z,r0/100); printf("!c3 %.4e %.4e %.4e %.4e\n",seplist[j].x,seplist[j].y,seplist[j].z,r0/100); } } printf("!F\n"); } lastframetime=stoptimer(4); fflush(stdout); time_anim += stoptimer(4); istime(0); } // start force calculations // check zonelist // build list of interactions. pass in pointers // to interaction lists so it can realloc them // if need be position_step(pos,v,dt/2); starttimer(1); starttimer(2); check_zonelist(zonelist,zone,pos); time_checklist += stoptimer(2); nint=build_interaction_list(pos,zonelist,zone,ilist1,ilist2,r2list,seplist); time_intlist += stoptimer(1); // printf("!%d interactions\n",nint); starttimer(3); velocity_step(pos,v,m,ilist1,ilist2,r2list,nint,dt,interactioncount); position_step(pos,v,dt/2); double eps = 0.1786178958448; double lam = -0.2123418310626; double chi = -0.06626458266982; /* Commented out -- fourth-order Omelyan algorithm doesn't seem to have stability advantages position_step(pos,v,dt*eps); velocity_step(pos,v,m,ilist1,ilist2,r2list,nint,dt*(1-2*lam)/2); position_step(pos,v,dt*chi); velocity_step(pos,v,m,ilist1,ilist2,r2list,nint,dt*lam); position_step(pos,v,dt*(1-2*(chi+eps))); velocity_step(pos,v,m,ilist1,ilist2,r2list,nint,dt*lam); position_step(pos,v,dt*chi); velocity_step(pos,v,m,ilist1,ilist2,r2list,nint,dt*(1-2*lam)/2); position_step(pos,v,dt*eps); */ time_velstep += stoptimer(3); steps++; ninttotal+=nint; for (int i=0; i<N; i++) { if (smooth_interaction_count[i]==0) smooth_interaction_count[i]=interactioncount[i]; else smooth_interaction_count[i] = smooth_interaction_count[i]*0.99+interactioncount[i]*0.01; } // all this code is just here to determine how much time different parts of the calculation are taking if (myclock() - 1.0 > time_check) { double curtime=myclock(); steprate = (float)(steps-lastchecksteps)/(curtime-time_check); forcerate = (float)ninttotal/(curtime-time_check); printf("!!%.2f force (%.2f ns/int), %.2f anim, %.2f ilist, %.2f checklist, %.2f energy (us/step): %.1f ints/atom, %.1f SPS, %.1f MIPS (%d threads)\n", 1e3*(float)time_velstep / (steps-lastchecksteps), 1e6*(float)time_velstep/ (ninttotal), 1e3*(float)time_anim / (steps-lastchecksteps), 1e3*(float)time_intlist / (steps-lastchecksteps), 1e3*(float)time_checklist / (steps-lastchecksteps), 1e3*(float)time_energy / (steps-lastchecksteps), (float)ninttotal/N/(steps-lastchecksteps), (float)(steps-lastchecksteps)/(curtime-time_check), (float)ninttotal/(curtime-time_check)/1e6, omp_get_max_threads()); printf("!!test: time_anim = %e, time_intlist = %e, time_velstep = %e, drawms = %e\n",time_anim,time_intlist,time_velstep, drawms); if (time_anim < 0.1*(time_intlist + time_velstep + time_energy) && drawms < 1000) { //drawms *= 0.98; printf("!!now drawing every %.3f ms\n",drawms); } if (time_anim > 0.2*(time_intlist + time_velstep + time_energy)) { //drawms /= 0.98; //printf("!!now drawing every %.3f ms\n",drawms); } time_velstep=time_intlist=time_posstep=time_anim=time_energy=time_checklist=0; lastchecksteps=steps; time_check=myclock(); ninttotal=0; } // do wall collisions and accumulate impulse for (i=0; i<N; i++) { if ( (pos[i].y > L/2 && v[i].y > 0) || ((pos[i].y < -L/2 && v[i].y < 0) ) ) { v[i].y=-v[i].y; J=J+2*fabs(v[i].y)*m[i]; } if ( (pos[i].z > L/2 && v[i].z > 0) || ((pos[i].z < -L/2 && v[i].z < 0) ) ) { v[i].z=-v[i].z; J=J+2*fabs(v[i].z)*m[i]; } if ( (pos[i].x > L/2 && v[i].x > 0) || ((pos[i].x < -L/2 && v[i].x < 0) ) ) { v[i].x=-v[i].x; J=J+2*fabs(v[i].x)*m[i]; } } Tnow=0; for (i=0; i<N; i++) { Tnow += 0.5 * m[i] * v[i]*v[i] * dt; } Taccum+=Tnow; Tnow/=N; // determine cooling/heating rate rate = (Tnow-Ttarget)*smult; if (Tnow > Ttarget) { for (i=0; i<N; i++) { v[i] = v[i] * (1 - rate*dt); } } if (t > next_thermo) { P=J/(thermo_interval)/(6*L*L); T=Taccum * 2.0 / 3.0 / N / thermo_interval; fprintf(logfile,"%e %e %e %e %e\n",t,P*L*L*L,N*T,P*L*L*L/(N*T),KE+PE); J=Taccum=0; next_thermo = t + thermo_interval; } } fprintf(logfile,"# Shutting down\n"); printf("Q\n"); }
true
1420a37be4bc17af55e5d72ac5674df77da1964b
C++
robertcal/cpp_competitive_programming
/AtCoder/ABC/114/D_after1.cpp
UTF-8
949
2.890625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 1e9; const int MOD = 1e9 + 7; const ll LINF = 1e18; int cnt[110] = {}; // n - 1以上の数がある個数 int num(int n) { int res = 0; for (int i = 0; i < 110; ++i) { if (cnt[i] >= n - 1) res++; } return res; } void prime_factor(int n) { for (int i = 2; i * i <= n; ++i) { if (n % i != 0) continue; int num = 0; while (n % i == 0) { ++num; n /= i; } cnt[i] += num; } if (n != 1) cnt[n]++; } int main() { int n; cin >> n; for (int i = 1; i <= n; ++i) { prime_factor(i); } int ans = num(75) + num(25) * (num(3) - 1) + num(15) * (num(5) - 1) + num(5) * (num(5) - 1) * (num(3) - 2) / 2; //なぜ2で割るのか? → 5の選び方で2重で数えいているから cout << ans << endl; }
true
00b18f22f2c97763a9ef595e57c32be9bc0477e4
C++
Brukols/Epitech-Arcade
/lib/sfml/src/ListScores/ListScoresEvent.cpp
UTF-8
1,831
2.59375
3
[ "MIT" ]
permissive
/* ** EPITECH PROJECT, 2020 ** OOP_arcade_2019 ** File description: ** ListScoresEvent */ #include "sfml/ListScores.hpp" void arc::ListScores::event(const sf::Event &event, sf::RenderWindow &window) { if (event.type != sf::Event::MouseWheelScrolled) return; sf::Vector2i pos = sf::Mouse::getPosition(window); if (pos.x > _rects[0].getPosition().x && pos.x < _rects[0].getPosition().x + _rects[0].getLocalBounds().width && pos.y > _rects[0].getPosition().y && pos.y < _rects[0].getPosition().y + _rects[0].getLocalBounds().height) { if (event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel) { if (event.mouseWheelScroll.delta < 0) scrollUp(); else scrollDown(); } } } void arc::ListScores::scrollUp() { if (_begin == 0) return; _begin--; std::for_each(_textScores.begin(), _textScores.end(), [this](std::pair<Text, Text> &pair) { pair.first.setPosition(sf::Vector2f(450 + 250 - pair.first.getText().getLocalBounds().width / 2, pair.first.getPosition().y + 50)); pair.second.setPosition(sf::Vector2f(950 + 250 - pair.second.getText().getLocalBounds().width / 2, pair.second.getPosition().y + 50)); }); } void arc::ListScores::scrollDown() { if (_textScores.size() <= 10) return; if (static_cast<long unsigned int>(_begin + 1) == _textScores.size() - 9) return; _begin++; std::for_each(_textScores.begin(), _textScores.end(), [this](std::pair<Text, Text> &pair) { pair.first.setPosition(sf::Vector2f(450 + 250 - pair.first.getText().getLocalBounds().width / 2, pair.first.getPosition().y - 50)); pair.second.setPosition(sf::Vector2f(950 + 250 - pair.second.getText().getLocalBounds().width / 2, pair.second.getPosition().y - 50)); }); }
true
9fa157c1667cebadc187283abae2b0a8ef077c47
C++
RootVirtual/Ard-Mux-Dimmer
/Ard_Mux_Dimmer/Ard_Mux_Dimmer.ino
UTF-8
2,027
2.703125
3
[]
no_license
// Testing sketch for 50Hz !!! #include <TimerOne.h> #include <Mux.h> Mux mux(2,3,4,5,4); // initialise on construct... int counter=0; unsigned char CH1, CH2, CH3, CH4; unsigned char i=0; unsigned int delay_time=2500; // delay ms or SPEED unsigned char clock_tick; // variable for Timer1 void setup() { Serial.begin(9600); mux.setup(8,9,10,11,4); // initialise Mux attachInterrupt(1, zero_crosss_int, RISING); Timer1.initialize(100); // set a timer of length 100 microseconds for 50Hz or 83 microseconds for 60Hz; Timer1.attachInterrupt( timerIsr ); // attach the service routine here } void timerIsr(){ clock_tick++; if (CH1==clock_tick){ mux.write(0, HIGH); // triac firing delayMicroseconds(10); // triac On propogation delay (for 60Hz use 8.33) mux.write(0, LOW); // triac Off } if (CH2==clock_tick){ mux.write(1, HIGH); // triac firing delayMicroseconds(10); // triac On propogation delay (for 60Hz use 8.33) mux.write(1, LOW); // triac Off } if (CH3==clock_tick){ mux.write(2, HIGH); // triac firing delayMicroseconds(10); // triac On propogation delay (for 60Hz use 8.33) mux.write(2, LOW); // triac Off } if (CH4==clock_tick){ mux.write(3, HIGH); // triac firing delayMicroseconds(10); // triac On propogation delay (for 60Hz use 8.33) mux.write(3, LOW); // triac Off } } void zero_crosss_int(){ // function to be fired at the zero crossing to dim the light // Every zerocrossing interrupt: For 50Hz (1/2 Cycle) => 10ms ; For 60Hz (1/2 Cycle) => 8.33ms // 10ms=10000us , 8.33ms=8330us clock_tick=0; } void loop() { CH1=5; CH2=45; CH3=65; CH4=80; delay(delay_time); CH1=80; CH2=65; CH3=45; CH4=5; delay(delay_time); CH1=65; CH2=5; CH3=65; CH4=5; delay(delay_time); CH1=5; CH2=65; CH3=5; CH4=65; delay(delay_time); CH1=5; CH2=65; CH3=65; CH4=5; delay(delay_time); CH1=65; CH2=5; CH3=5; CH4=65; delay(delay_time); CH1=5; CH2=5; CH3=5; CH4=5; delay(delay_time); CH1=95; CH2=95; CH3=95; CH4=95; delay(delay_time); }
true
7f4b977e84e749f97c4a4c583e23ffc9b999dc28
C++
barte525/tep1
/TEP1mod.cpp
UTF-8
3,968
3.0625
3
[]
no_license
using namespace std; #include <iostream> #include "CTable.h" static const int ADDITION_NUMBER = 5; static const int MAX_TAB_LENGTH = 100000; bool vAllocTableAdd5(int iSize) { if (iSize > 0 && iSize <= MAX_TAB_LENGTH) { int* table; table = new int[iSize]; for (int i = 0; i < iSize; i++) table[i] = i + ADDITION_NUMBER; for (int i = 0; i < iSize; i++) cout << "table[" << i << "] = " << table[i] << endl; delete table; return true; } else return false; } bool bAllocTable2Dim(int*** piTable, int iSizeX, int iSizeY) { if (iSizeX >= 1 && iSizeY >= 1 && iSizeX <= MAX_TAB_LENGTH && iSizeY <= MAX_TAB_LENGTH) { *piTable = new int* [iSizeX]; for (int i = 0; i < iSizeX; i++) (*piTable)[i] = new int[iSizeY]; return true; } else return false; } bool bDeallocTable2Dim(int** piTable, int iSizeX) { //zakładam, że zapamiętałem długość tablicy i wpisuje ją do procedury (tak zrozumiałem na labolatoriach) if (iSizeX > 0) { for (int i = 0; i < iSizeX; i++) delete piTable[i]; delete piTable; return true; } else return false; } bool vModTab(CTable* pcTab, int iNewSize) { return pcTab->bSetNewSize(iNewSize); } bool vModTab(CTable pcTab, int iNewSize) { return pcTab.bSetNewSize(iNewSize); } int main() { //testy zadan 1-3 cout << "zadania 1-3:" << endl << "vAllocTableAdd5(10):" << endl; vAllocTableAdd5(10); int** piTable; cout << "czy udalo sie zaalokowac tablice: " << bAllocTable2Dim(&piTable, 4, 1) << endl; piTable[3][0] = 3; cout << "piTable[3][0] = " << piTable[3][0] << endl; bDeallocTable2Dim(piTable, 4); //cout << piTable[3][0] << endl; //linijka wywołująca błąd w celu sprawdzenia czy tablica została zdealokowana cout << "\n\n\n"; //zadanie 4 cout << "zadanie 4: " << endl; CTable tabToCopy("tabToCopy", 1); CTable* copy; copy = new CTable(tabToCopy); copy->bSetNewSize(2); copy->vSetName("newName"); cout << "Wielkosc tablicy copy po ustawieniu na 2: " << copy->getTabLength() << "\nNazwa tablicy copy po ustawieniu na 'newName': " << copy->getSName() << endl; cout << "test metody pcClone: " << endl; CTable c_tab; CTable* pc_new_tab; pc_new_tab = c_tab.pcClone(); delete pc_new_tab; cout << "\n\n\n"; //testy procedur cout << "test procedur" << endl; vModTab(copy, 3); cout << "przekazanie przez wskaznik, dlugosc tablicy bo wywolaniu procedury vModTab(copy, 3): " << copy->getTabLength() << endl; CTable tabToMod("tabToMod", 1); vModTab(tabToMod, 2); cout << "przekazanie przez wartosc, dlugosc tablicy bo wywolaniu procedury vModTab(tab1, 2): " << tabToMod.getTabLength() << endl; cout << "\n\n\n"; cout << "test alokacji statycznej i dynamicznej obiekow CTable" << endl; CTable tabStatic("tabStatic", 3); CTable* tabDynamic; tabDynamic = new CTable("tabDynamic", 3); CTable tabOfTabsStatic[5]; CTable* tabOfTabsDynamic; tabOfTabsDynamic = new CTable[5]; cout << "\n\n\n"; cout << "test modyfikacji" << endl; CTable modTest("mod", 1); modTest.vPush(2); cout << "przekazanie przez wartosc, dlugosc tablicy bo wywolaniu metody vPush(2): " << modTest.getTabLength() << endl; cout << "\n\n\n"; cout << "usuniecie obiektow zaalokowanych dynamicznie" << endl; //usuniecie dynamicznie zaalokowanych obiektow delete copy; delete tabDynamic; //aby usunac elementy tablicy zaalokowanej dynamicznie musze wykonac taka operacje cout << "delete[] tabOfTabsDynamic" << endl; delete[] tabOfTabsDynamic; cout << "koniec maina" << endl; }
true
ae22bf454387add18cad67ef365327d4b0296708
C++
Pavlete/ModularSynth
/src/UI/common/juceaudionode.h
UTF-8
1,027
2.53125
3
[]
no_license
#pragma once #include "socket.h" class JuceAudioNode: public Component , public ButtonListener { public: JuceAudioNode(const SharedNode& model,int inputNumber, int outputNumber); virtual ~JuceAudioNode() = default; virtual void setContent(Rectangle<int> &r) = 0; virtual std::string getConnectorName(int ); int getNodeID() const; void mouseDown(const MouseEvent &event) override; void mouseDrag(const MouseEvent &event) override; void setConnection(std::shared_ptr<JuceConnection> con, Socket::Direction dir); private: void paint(Graphics &g) override; void resized() override; void moved() override; void parentHierarchyChanged() override; std::vector<std::unique_ptr<Socket>> m_inConnectors; std::vector<std::unique_ptr<Socket>> m_outConnectors; SharedNode m_model; ComponentDragger m_dragger; OngoingConnection m_ongoing; ShapeButton m_removeButton; Path m_buttonPath; void buttonClicked(Button *) override; };
true
4525565e9937f3e5026a801cb281cd54f12cb1be
C++
knightfox75/ngine
/Tools/NGN_CollisionMap/source/convert_to_map.cpp
UTF-8
15,023
2.59375
3
[ "MIT" ]
permissive
/****************************************************************************** Conversor de PNG a Mapa de Colisiones (.map) para N'gine - Convierte un archivo PNG en tiles - Proyecto iniciado el 11 de Febrero del 2016 (c) 2016 - 2023 by Cesar Rincon "NightFox" https://nightfoxandco.com contact@nightfoxandco.com Requiere LodePNG (20220717) (c) 2005 - 2022 by Lode Vandevenne http://lodev.org/lodepng/ Conversor de PNG a Mapa de Colisiones is under MIT License Copyright (c) 2016-2023 by Cesar Rincon "NightFox" Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ /*** Includes ***/ // C++ #include <cstdio> #include <iostream> #include <fstream> #include <string> #include <vector> #include <cmath> // LodePNG #include "lodepng/lodepng.h" // Includes del proyecto #include "convert_to_map.h" #include "defines.h" /*** Constructor ***/ ConvertToMap::ConvertToMap() { map_width = 0; // Ancho del mapa map_height = 0; // Altura del mapa size_of_tile = 0; // tamaño del tile pal_length = 0; // tamaño de la paleta tileset_length = 0; // tamaño del tileset map_length = 0; // tamaño del mapa palette.clear(); tiles.clear(); tmap.clear(); bitmap.clear(); } /*** Destructor ***/ ConvertToMap::~ConvertToMap() { bitmap.clear(); palette.clear(); tiles.clear(); tmap.clear(); } /*** Convierte un archivo PNG en tiles ***/ bool ConvertToMap::Convert( std::string in_file, // Archivo PNG a convertir std::string out_file, // Nombre base de los archivos de salida uint32_t tile_size // tamaño del tile ) { // Guarda los parametros size_of_tile = tile_size; // Prepara el buffer para los pixeles de la imagen std::vector<uint8_t> png_pixels; png_pixels.clear(); // Intenta abrir y decodificar el archivo PNG if (!ReadPng(in_file, png_pixels)) return false; // Convierte el PNG a BITMAP + PALETA if (!GenerateBitmap(png_pixels)) return false; png_pixels.clear(); // Genera un tilemap con los datos del bitmap GenerateTileMap(); // Guarda en el archivo empaquetado los datos generados bool r = WriteFile(out_file); // Elimina los buffers bitmap.clear(); palette.clear(); tiles.clear(); tmap.clear(); // Conversion correcta return r; } /*** Convierte la imagen en bitmap + paleta ***/ bool ConvertToMap::GenerateBitmap(std::vector<uint8_t> &data) { // Prepara los bufferes de destino bitmap.clear(); bitmap.resize((map_width * map_height), 0); // Prepara los buffers temporales std::vector<uint32_t> t_palette; t_palette.clear(); t_palette.resize(256, 0); // Variables de uso temporal uint32_t pixel; // Alamacena el valor del pixel int32_t id = 0; // Contenedor de ID de la paleta uint32_t pal_id = 0; // Posicion actual en la paleta uint32_t offset = 0; // Posicion actual en el mapa // Marcador de progreso uint64_t max_pixels = (map_width * map_height); uint64_t current_pixel = 0; uint64_t percent = 0, old_percent = 0; char s[16]; std::cout << std::endl; std::cout << "Generating bitmap & palette..." << std::endl; // Identifica el color de cada pixel e identificalo en la paleta, de no existir, a�adelo for (uint32_t y = 0; y < map_height; y ++) { for (uint32_t x = 0; x < map_width; x ++) { // Color del pixel actual offset = ((y * map_width) + x); pixel = GetPixel(data, (offset << 2)); // Reset de ID id = -1; // Si el color coincide con alguno de la paleta... for (uint32_t c = 0; c < t_palette.size(); c ++) { if (pixel == t_palette[c]) { id = c; break; } } // Si es un nuevo color, indicalo if (id < 0) { if (pal_id > 255) { std::cout << "Image format not compatible. The image must be indexed at 256 colors." << std::endl; bitmap.clear(); t_palette.clear(); return false; } // Guarda el nuevo color t_palette[pal_id] = pixel; // Guarda el pixel bitmap[offset] = (0xff & ((uint8_t)(pal_id))); // Siguente PAL ID pal_id ++; } else { // Guarda el Pixel bitmap[offset] = (0xff & ((uint8_t)(id))); } // Informacion del progreso current_pixel ++; percent = ((current_pixel * 1000) / max_pixels); if (percent != old_percent) { sprintf(s, "%05.1f%%", ((float)percent / 10.0f)); std::cout << "\x0d" << s << " "; old_percent = percent; } //std::cout << "OFFSET:" << offset << " COLOR:" << pixel << " ID:" << (int32_t)_id << " BITMAP:" << (int32_t)bitmap[offset] << std::endl; } } // Mensage del finde del progreso std::cout << "done!" << std::endl; std::cout << "Bitmap generation completed." << std::endl; std::cout << "Palette generation completed. The palette contains " << pal_id << " colors." << std::endl; // Guarda el tamaño del buffer de la paleta pal_length = pal_id; // Copia la paleta temporal a la final palette.clear(); palette.resize(pal_length, 0); for (uint32_t n = 0; n < pal_length; n ++) palette[n] = t_palette[n]; t_palette.clear(); // Todo Ok return true; } /*** Genera una mapa de tiles a partir del bitmap ***/ void ConvertToMap::GenerateTileMap() { // Aviso de ajuste del tamaño de tiles std::cout << std::endl; if (((map_width % size_of_tile) != 0) || (map_height % size_of_tile) != 0) { std::cout << "WARNING: Image size doesn't fits the tile size." << std::endl; std::cout << "The size of the Tilemap will be adjusted to the closest right size." << std::endl; } // Prepara el buffer para almacenar el mapa de tiles uint32_t width = (map_width / size_of_tile); if ((map_width % size_of_tile) != 0) width ++; uint32_t height = (map_height / size_of_tile); if ((map_height % size_of_tile) != 0) height ++; // Crea el buffer para el mapa map_length = (width * height); tmap.clear(); tmap.resize(map_length, 0); // Crea el buffer temporal para el tileset uint32_t tile_length = (size_of_tile * size_of_tile); uint32_t l = (width * height * tile_length); std::vector<uint8_t> t_tiles; // Buffer para almacenar los pixeles de los tiles t_tiles.clear(); t_tiles.resize(l, 0); // Crea el buffer temporal para el tile actual a analizar std::vector<uint8_t> t_tl; t_tl.clear(); // Control de tile nuevo bool new_tile = false, miss_match = false; uint32_t last_tile = 0; uint32_t offset = 0; uint32_t t_num = 0; // Datos para el indicador de progreso uint64_t max_tiles = (height * width); uint64_t current_tile = 0; uint64_t percent = 0, old_percent = 0; char s[16]; std::cout << "Generating a tilemap of " << width << "x" << height <<" tiles." << std::endl; // Recorre todo el mapa analizando los tiles for (uint32_t ty = 0; ty < height; ty ++) { for (uint32_t tx = 0; tx < width; tx ++) { // Reset del flag new_tile = true; // Copia un tile del bitmap GetTile(t_tl, tx, ty); // Comparalo con todos los tiles previamente guardados for (uint32_t i = 0; i < last_tile; i ++) { offset = (i * tile_length); miss_match = false; for (uint32_t n = 0; n < tile_length; n ++) { if (t_tl[n] != t_tiles[(offset + n)]) { miss_match = true; break; } } // Si no hay discrepancia, a�ade el tile actual al mapa if (!miss_match) { t_num = ((ty * width) + tx); tmap[t_num] = i; new_tile = false; break; } } // Si no se encuentra coincidencia, a�ade el tile if (new_tile) { t_num = ((ty * width) + tx); tmap[t_num] = last_tile; offset = (last_tile * tile_length); for (uint32_t n = 0; n < tile_length; n ++) t_tiles[(offset + n)] = t_tl[n]; last_tile ++; } // Informacion del progreso current_tile ++; percent = ((current_tile * 1000) / max_tiles); if (percent != old_percent) { sprintf(s, "%05.1f%%", ((float)percent / 10.0f)); std::cout << "\x0d" << s << " "; old_percent = percent; } } } // Copia el tileset final al buffer de destino tileset_length = (last_tile * tile_length); tiles.clear(); tiles.resize(tileset_length, 0); for (uint32_t n = 0; n < tileset_length; n ++) tiles[n] = t_tiles[n]; // Borra los buffers temporales t_tl.clear(); t_tiles.clear(); // Resultado std::cout << "done!" << std::endl; std::cout << "Tilemap with " << last_tile << " tiles created successfully." << std::endl << std::endl; } /*** Graba el archivo empaquetado ***/ bool ConvertToMap::WriteFile(std::string filename) { // Guarda la informacion para la cabecera del archivo FileHeader header; memset((void*)&header, 0, sizeof(header)); header.version = VERSION; strncpy(header.magic, MAGIC_STRING.c_str(), MAGIC_STRING.length()); header.width = map_width; // tamaño del mapa en pixeles header.height = map_height; header.tile_size = size_of_tile; // tamaño del tile header.pal_length = pal_length; // n� de elementos de la paleta (*4) header.tileset_length = tileset_length; // n� de elementos del tileset header.map_length = map_length; // n� de elementos del mapa (*4) // Genera el nombres de archivo std::string fname = filename + MAP_EXTENSION; const char* map_filename = fname.c_str(); // Graba el archivo principal std::ofstream file; file.open(map_filename, std::ofstream::out | std::ofstream::binary); if (file.is_open()) { file.write((char*)&header, sizeof(header)); // Cabecera file.write((char*)&palette[0], (palette.capacity() * sizeof(int32_t))); // Paleta file.write((char*)&tiles[0], tiles.capacity()); // Tiles file.write((char*)&tmap[0], (tmap.capacity() * sizeof(int32_t))); // Mapa de tiles file.close(); std::cout << "File " << fname << " successfully saved." << std::endl; } else { std::cout << "Error saving " << fname << "." << std::endl; return false; } // Todo correcto return true; } /*** Lee un archivo .PNG y coloca los pixeles en un buffer ***/ bool ConvertToMap::ReadPng(std::string filename, std::vector<uint8_t> &data) { // Variables uint32_t width = 0, height = 0; // tamaño del archivo cargado // Prepara el buffer temporal std::vector<uint8_t> png_data; png_data.clear(); // Prepara el buffer para los datos decodificados data.clear(); // Carga el archivo PNG if (lodepng::load_file(png_data, filename) != 0) { std::cout << "Error loading " << filename << "." << std::endl; png_data.clear(); return false; } // Si se ha cargado correctamente, decodifica la imagen if (lodepng::decode(data, width, height, png_data) != 0) { std::cout << "Error decoding " << filename << "." << std::endl; png_data.clear(); data.clear(); return false; } // Guarda el tamaño del mapa map_width = width; map_height = height; // Borra el buffer temporal png_data.clear(); // Fin de la funcion de carga return true; } /*** Lee un pixel del buffer especificado ***/ uint32_t ConvertToMap::GetPixel(std::vector<uint8_t> &data, uint32_t offset) { // Variables uint32_t pixel = 0; // Lee los bits del pixel /*if ((offset + 3) < data.capacity()) {*/ pixel = data[(offset + 3)] | (data[(offset + 2)] << 8) | (data[(offset + 1)] << 16) | (data[offset] << 24); /*} else { pixel.r = pixel.g = pixel.b = pixel.a = 0; std::cout << "Pixel read out of range." << std::endl; }*/ return pixel; } /*** Obten un tile del bitmap ***/ void ConvertToMap::GetTile(std::vector<uint8_t> &data, uint32_t pos_x, uint32_t pos_y) { // Prepara el buffer de salida data.clear(); data.resize(size_of_tile * size_of_tile); // Calcula los puntos de corte uint32_t start_x = (pos_x * size_of_tile); uint32_t end_x = (start_x + size_of_tile); uint32_t start_y = (pos_y * size_of_tile); uint32_t end_y = (start_y + size_of_tile); // Copia los datos del buffer al tile uint32_t px = 0; uint32_t offset = 0; for (uint32_t y = start_y; y < end_y; y ++) { for (uint32_t x = start_x; x < end_x; x ++) { if ((y < map_height) && (x < map_width)) { offset = ((map_width * y) + x); data[px] = bitmap[offset]; } else { data[px] = 0; } px ++; } } }
true
760e925860f72db92ec81be97d7b0bc5a16fe60d
C++
Path000/Hector
/controleur/StateMove.cpp
UTF-8
1,444
2.75
3
[]
no_license
#include "StateMove.h" void StateMove::setData(String strafeDirection, String rotationDirection) { _robot->computeMove(strafeDirection.toInt(), rotationDirection.toInt()); _robot->_ecran.clear(); _robot->_ecran.set(0, String("St:")+strafeDirection); _robot->_ecran.set(1, String("Ro:")+rotationDirection); _robot->_ecran.refresh(); } void StateMove::onStart() { _robot->_compteur1.readyToRead(); _robot->_compteur2.readyToRead(); _lastRefresh = millis(); } State* StateMove::run() { unsigned long now = millis(); if((now - _lastRefresh) > UPDATE_PID_PERIOD) { _lastRefresh = now; _robot->_compteur1.readyToRead(); _robot->_compteur2.readyToRead(); } SpeedSampleType* compteur1 = _robot->_compteur1.readIfAvailable(); if (compteur1->newSampleAvailable) { _robot->_ecran.set(2, String("A:")+String(compteur1->speed2)+String(" B:")+String(compteur1->speed1)); _robot->_ecran.refresh(); _robot->_moteurA.update(compteur1->speed2, duration()); _robot->_moteurB.update(compteur1->speed1, duration()); } SpeedSampleType* compteur2 = _robot->_compteur2.readIfAvailable(); if (compteur2->newSampleAvailable) { _robot->_ecran.set(3, String("D:")+String(compteur2->speed2)+String(" C:")+String(compteur2->speed1)); _robot->_ecran.refresh(); _robot->_moteurC.update(compteur2->speed1, duration()); _robot->_moteurD.update(compteur2->speed2, duration()); } return NULL; }
true
682b708932cbef297d6a696b1dfdc7607f93f960
C++
tpetrina/rp1
/2012/4/kvadrat/main.5.cpp
UTF-8
3,417
3.21875
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> #include "kvadrat.h" using namespace std; class MainKvadrat : public Kvadrat { int __brojPoziva; int __M[ 16 ]; void __rot( int perm[], int duljina ) { int temp = __M[ perm[ duljina-1 ] ]; for( int i = duljina-1; i > 0; --i ) __M[ perm[ i ] ] = __M[ perm[ i-1 ] ]; __M[ perm[ 0 ] ] = temp; } public: MainKvadrat() { __brojPoziva = 0; } int __getBrojPoziva() { return __brojPoziva; } MainKvadrat &operator>( const pair<int, int> &x ) { ++__brojPoziva; int perm[ 4 ]; for( int i = 0; i < 4; ++i ) perm[ i ] = (x.first-1)*4 + i; for( int i = 0; i < x.second; ++i ) __rot( perm, 4 ); Kvadrat::operator>( x ); return *this; } MainKvadrat &operator^( const pair<int, int> &x ) { ++__brojPoziva; int perm[ 4 ]; for( int i = 0; i < 4; ++i ) perm[ i ] = 4*(3-i) + x.first-1; for( int i = 0; i < x.second; ++i ) __rot( perm, 4 ); Kvadrat::operator^( x ); return *this; } void __set( int r, int s, int value ) { __M[ 4*(r-1) + s-1 ] = value; (*this)( r, s ) = value; } void __printout() { for( int r = 1; r <= 4; ++r, cout << endl ) for( int s = 1; s <= 4; ++s ) cout << setw(2) << __M[ 4*(r-1) + s-1 ] << " "; } }; int main( void ) { { MainKvadrat K; // K > make_pair( 3, 2 ); // K ^ make_pair( 1, 3 ); // 13 2 3 4 // 1 6 7 8 // 5 12 9 10 // 11 14 15 16 K.__set( 1, 1, 13 ); K.__set( 1, 2, 2 ); K.__set( 1, 3, 3 ); K.__set( 1, 4, 4 ); K.__set( 2, 1, 1 ); K.__set( 2, 2, 6 ); K.__set( 2, 3, 7 ); K.__set( 2, 4, 8 ); K.__set( 3, 1, 5 ); K.__set( 3, 2, 12 ); K.__set( 3, 3, 9 ); K.__set( 3, 4, 10 ); K.__set( 4, 1, 11 ); K.__set( 4, 2, 14 ); K.__set( 4, 3, 15 ); K.__set( 4, 4, 16 ); cout << "prije:" << endl; K.__printout(); !K; cout << "poslije:" << endl; K.__printout(); cout << ( ( K.__getBrojPoziva() < 1000 ) ? "OK" : "previse poziva" ) << endl << endl; } { MainKvadrat K; // K > make_pair( 4, 2 ); // K ^ make_pair( 2, 1 ); // K > make_pair( 1, 3 ); // 6 3 4 1 // 5 10 7 8 // 9 16 11 12 // 15 2 13 14 K.__set( 1, 1, 6 ); K.__set( 1, 2, 3 ); K.__set( 1, 3, 4 ); K.__set( 1, 4, 1 ); K.__set( 2, 1, 5 ); K.__set( 2, 2, 10 ); K.__set( 2, 3, 7 ); K.__set( 2, 4, 8 ); K.__set( 3, 1, 9 ); K.__set( 3, 2, 16 ); K.__set( 3, 3, 11 ); K.__set( 3, 4, 12 ); K.__set( 4, 1, 15 ); K.__set( 4, 2, 2 ); K.__set( 4, 3, 13 ); K.__set( 4, 4, 14 ); cout << "prije:" << endl; K.__printout(); !K; cout << "poslije:" << endl; K.__printout(); cout << ( ( K.__getBrojPoziva() < 1000 ) ? "OK" : "previse poziva" ) << endl << endl; } { MainKvadrat K; // K ^ make_pair( 2, 3 ); // K > make_pair( 1, 1 ); // K > make_pair( 4, 2 ); // K ^ make_pair( 3, 2 ); // 4 1 11 3 // 5 2 13 8 // 9 6 14 12 // 15 16 7 10 K.__set( 1, 1, 4 ); K.__set( 1, 2, 1 ); K.__set( 1, 3, 11 ); K.__set( 1, 4, 3 ); K.__set( 2, 1, 5 ); K.__set( 2, 2, 2 ); K.__set( 2, 3, 13 ); K.__set( 2, 4, 8 ); K.__set( 3, 1, 9 ); K.__set( 3, 2, 6 ); K.__set( 3, 3, 14 ); K.__set( 3, 4, 12 ); K.__set( 4, 1, 15 ); K.__set( 4, 2, 16 ); K.__set( 4, 3, 7 ); K.__set( 4, 4, 10 ); cout << "prije:" << endl; K.__printout(); !K; cout << "poslije:" << endl; K.__printout(); cout << ( ( K.__getBrojPoziva() < 1000 ) ? "OK" : "previse poziva" ) << endl << endl; } return 0; }
true
557ad3c2fc5d2f0854bc8c8265773db6d227f91f
C++
rskelly/geotools
/src/pcnorm.cpp
UTF-8
8,295
2.59375
3
[]
no_license
/* * pcnorm2.cpp * * Created on: May 5, 2019 * Author: rob */ #include <limits> #include <fstream> #include <liblas/liblas.hpp> #include "geo.hpp" #include "util.hpp" using namespace geo::util; void getBounds(liblas::Reader& rdr, double* bounds) { double x, y, z; rdr.Reset(); while(rdr.ReadNextPoint()) { const liblas::Point& pt = rdr.GetPoint(); x = pt.GetX(); y = pt.GetY(); z = pt.GetZ(); if(x < bounds[0]) bounds[0] = x; if(x > bounds[1]) bounds[1] = x; if(y < bounds[2]) bounds[2] = y; if(y > bounds[3]) bounds[3] = y; if(z < bounds[4]) bounds[4] = z; if(z > bounds[5]) bounds[5] = z; } } bool buildGrid(const std::vector<std::string>& infiles, double* bounds, double res, int& cols, int& rows, std::vector<float>& grid) { // Increase bounds enough to add 2 cells all around. bounds[0] -= res; bounds[1] += res; bounds[2] -= res; bounds[3] += res; // Get grid size. cols = (int) std::ceil((bounds[1] - bounds[0]) / res); rows = (int) std::ceil((bounds[3] - bounds[2]) / res); std::vector<float> weights(cols * rows); size_t count = 0; { // To compute weighted mean, need weights and values arrays. grid.resize(cols * rows); std::fill(grid.begin(), grid.end(), 0); std::fill(weights.begin(), weights.end(), 0); double px, py, pz; double x, y, d, w; int col, row; double rad = std::pow(res, 2); size_t num = 0; for(const std::string& infile : infiles) { std::cout << ++num << " of " << infiles.size() << "\n"; std::ifstream input(infile, std::ios::binary); liblas::ReaderFactory rf; liblas::Reader rdr = rf.CreateWithStream(input); while(rdr.ReadNextPoint()) { const liblas::Point& pt = rdr.GetPoint(); if(pt.GetClassification().GetClass() != 2) continue; px = pt.GetX(); py = pt.GetY(); pz = pt.GetZ(); col = (int) (px - bounds[0]) / res; row = (int) (py - bounds[2]) / res; for(int r = row - 1; r < row + 2; ++r) { for(int c = col - 1; c < col + 2; ++c) { if(c >= 0 && r >= 0 && c < cols && r < rows) { x = bounds[0] + (c * res) + res * 0.5; y = bounds[2] + (r * res) + res * 0.5; d = std::pow(x - px, 2.0) + std::pow(y - py, 2.0); if(d > rad) continue; w = 1.0 - d / rad; // Accumulate the weighted heights and weights. grid[r * cols + c] += pz * w; weights[r * cols + c] += w; ++count; } } } } } } if(!count) { std::cout << "There are no ground points. Quitting.\n"; return false; } // Normalize by weights. for(size_t i = 0; i < grid.size(); ++i) { if(weights[i] > 0) grid[i] /= weights[i]; } // Fill in zeroes. std::cout << "Filling gaps\n"; for(size_t i = 0; i < grid.size(); ++i) { if(i % cols == 0) std::cout << "Row " << (i / cols) << " of " << rows << "\n"; if(weights[i] == 0) { double x, y, d, w0, rad, w = 0, s = 0; int o = 2; int col = i % cols; int row = i / cols; double cx = bounds[0] + col * res + res * 0.5; double cy = bounds[2] + row * res + res * 0.5; do { rad = std::pow(o * res, 2); for(int r = row - o; r < row + o + 1; ++r) { for(int c = col - o; c < col + o + 1; ++c) { if(c >= 0 && r >= 0 && c < cols && r < rows) { if(weights[r * cols + c] == 0) continue; x = bounds[0] + (c * res) + res * 0.5; y = bounds[2] + (r * res) + res * 0.5; d = std::pow(x - cx, 2.0) + std::pow(y - cy, 2.0); if(d > rad) continue; w0 = 1.0 - d / rad; // Accumulate the weighted heights and weights. s += grid[r * cols + c] * w0; w += w0; } } } ++o; } while(w == 0); grid[i] = s / w; } } return true; } double bary(double x, double y, double x0, double y0, double z0, double x1, double y1, double z1, double x2, double y2, double z2) { double w0 = ((y1 - y2) * (x - x2) + (x2 - x1) * (y - y2)) / ((y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2)); double w1 = ((y2 - y0) * (x - x2) + (x0 - x2) * (y - y2)) / ((y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2)); double w2 = 1 - w0 - w1; return (w0 * z0) + (w1 * z1) + (w2 * z2); } void normalize(const std::vector<std::string>& infiles, liblas::Writer& wtr, double* bounds, double res, int cols, int /*rows*/, std::vector<float>& grid) { bounds[4] = std::numeric_limits<double>::max(); bounds[5] = std::numeric_limits<double>::lowest(); double z, px, py, pz, cx0, cy0, cz0, cx1, cy1, cz1, cx2, cy2, cz2, nz; int col, row, col0, row0; size_t num = 0; for(const std::string& infile : infiles) { std::cout << ++num << " of " << infiles.size() << "\n"; std::ifstream input(infile, std::ios::binary); liblas::ReaderFactory rf; liblas::Reader rdr = rf.CreateWithStream(input); while(rdr.ReadNextPoint()) { const liblas::Point& pt = rdr.GetPoint(); px = pt.GetX(); py = pt.GetY(); pz = pt.GetZ(); // Point's home cell. col = (int) (px - bounds[0]) / res; row = (int) (py - bounds[2]) / res; // Center of home cell. cx0 = bounds[0] + (col * res) + res * 0.5; cy0 = bounds[2] + (row * res) + res * 0.5; cz0 = grid[row * cols + col]; // Cell offsets. col0 = px < cx0 ? col - 1 : col + 1; row0 = py < cy0 ? row - 1 : row + 1; // Centers of offset cells. cx1 = bounds[0] + (col0 * res) + res * 0.5; cy1 = bounds[2] + (row * res) + res * 0.5; cz1 = grid[row * cols + col0]; cx2 = bounds[0] + (col * res) + res * 0.5; cy2 = bounds[2] + (row0 * res) + res * 0.5; cz2 = grid[row0 * cols + col]; if(cz0 == -9999.0 || cz1 == -9999.0 || cz2 == -9999.0) continue; // Get the barycentric z nz = bary(px, py, cx0, cy0, cz0, cx1, cy1, cz1, cx2, cy2, cz2); // Make point and write it. liblas::Point pt0(pt); pt0.SetZ((z = pz - nz)); wtr.WritePoint(pt0); // Adjust bounds. if(z < bounds[4]) bounds[4] = z; if(z > bounds[5]) bounds[5] = z; } } } void usage() { std::cerr << "Usage: pcnorm [options] <outfile (.las)> <resolution> <infile(s) (.las)>\n" << " -f Force overwrite of existing files.\n"; } int main(int argc, char** argv) { if(argc < 4) { usage(); return 1; } std::string outfile; std::vector<std::string> infiles; double resolution = 0; bool force = false; int mode = 0; for(int i = 1; i < argc; ++i) { std::string arg = argv[i]; if(arg == "-f") { force = true; } else if(mode == 0) { ++mode; outfile = arg; } else if(mode == 1) { ++mode; resolution = atof(arg.c_str()); } else { infiles.push_back(arg); } } if(!checkValidInputFiles(infiles)) { g_error("At least one of the input files is invalid."); usage(); return 1; } if(resolution <= 0 || std::isnan(resolution)) { g_error("The resolution " << resolution << " is invalid."); usage(); return 1; } if(outfile.empty()) { g_error("Output file not given."); usage(); return 1; } if(!geo::util::safeToWrite(outfile, force)) { g_error("The file " << outfile << " is not safe to write to. " << "If it is a file, use the -f flag. If it is a directory, " << "choose a different path."); usage(); return 1; } double bounds[6]; bounds[0] = bounds[2] = bounds[4] = std::numeric_limits<double>::max(); bounds[1] = bounds[3] = bounds[5] = std::numeric_limits<double>::lowest(); std::unique_ptr<liblas::Header> whdr; std::cout << "Computing bounds\n"; for(const std::string& infile : infiles) { std::ifstream input(infile, std::ios::binary); liblas::ReaderFactory rf; liblas::Reader rdr = rf.CreateWithStream(input); const liblas::Header& rhdr = rdr.GetHeader(); getBounds(rdr, bounds); if(infile == infiles.front()) whdr.reset(new liblas::Header(rhdr)); } double gbounds[6]; for(int i = 0; i < 6; ++i) gbounds[i] = bounds[i]; int cols, rows; std::vector<float> grid; std::cout << "Building grid\n"; if(!buildGrid(infiles, gbounds, resolution, cols, rows, grid)) return 1; std::ofstream output; liblas::WriterFactory wf; liblas::Create(output, outfile); liblas::Writer wtr(output, *whdr); std::cout << "Normalizing\n"; normalize(infiles, wtr, gbounds, resolution, cols, rows, grid); whdr->SetMin(bounds[0], bounds[2], gbounds[4]); whdr->SetMax(bounds[1], bounds[3], gbounds[5]); wtr.SetHeader(*whdr); return 0; }
true
d4511d9939ccbaa77eed62578821bec3612c51a8
C++
Thornhill-GYL/mycompiler
/lexdll/sematic.cpp
GB18030
15,656
2.53125
3
[]
no_license
#include<iostream> #include<fstream> #include<cstring> #include "stdafx.h" #include "lex.h" #include <iostream> #include<iostream> #include<fstream> #include<string> using namespace std; class lexword { public: int num; char word[10]; int type; } ; class Temp { public: char newtemp; int newtemp_num; Temp() { newtemp='t'; newtemp_num=1; }; }; void newtemp(); void Next(); void Before(); void A(); void B(); void C(); void D(); bool F(); void H(); void I(); void J(); void K(); void N(); void O(); void P(); void Q(); void R(); void S(); void T(); void U(); void X(); void Y(); void Z(); void putstart(int pop); void putEqual(int pop); void putAdd(int pop); int lookup(int num); int sym_num=0,countword=0,flag=0; int operator_flag = 0; int operator_confirm = 0; int sort=0; lexword lw[400]; Temp ntemp; ofstream fouterr("F:\\grammarerror.txt ",ios::out);//Լ趨·ļ ofstream four("F:\\fourout.txt ",ios::out);//Լ趨·ļ typedef struct { int stack[10]; int first; int end; }Four; Four start; Four Equal; Four Judge; Four Add; typedef struct { int name[100]; int name_count; int key[100]; int key_count; int num[100]; int num_count; }symbol; symbol symbollist; void newtemp() { ntemp.newtemp_num++; } void Next()//õһʶַ { if (sym_num < countword) { sym_num++; } } void Before() { if (sym_num > 0) { sym_num--; } } void putstart(int pop) { start.end=0; four<<"("<<sort<<")"; four<<"<"; while(start.end!=pop-1) { if(start.stack[start.end]==100) { four<<"_"; } else { four<<lw[start.stack[start.end]].word; } start.end++; four<<","; } if(start.stack[start.end]==100) { four<<"_"; } four<<">"<<endl; sort++; } void putEqual(int pop) { Equal.end=1; four<<"("<<sort<<")"; four<<"<"; while(Equal.end!=pop) { if(Equal.stack[Equal.end]==100) { four<<"_"; } else if (Equal.stack[Equal.end] == 120) { four << ntemp.newtemp<<ntemp.newtemp_num; newtemp(); } else { four<<lw[Equal.stack[Equal.end]].word; } Equal.end++; four<<","; } four<<lw[Equal.stack[0]].word; four<<">"<<endl; sort++; } void putAdd(int pop) { Add.end = 0; four << "(" << sort << ")"; four << "<"; while (Add.end != pop-1) { if (Add.stack[Add.end] == 120) { four << ntemp.newtemp<<ntemp.newtemp_num; } else { four << lw[Add.stack[Add.end]].word; } Add.end++; four << ","; } if (Add.stack[Add.end] == 120) { four << ntemp.newtemp<<ntemp.newtemp_num; } four << ">" << endl; sort++; operator_flag = 0; operator_confirm = 0; } //򡵡startAB# void A() { start.first=0; if (lw[sym_num].num == 1)//start { start.stack[start.first++]=sym_num; Next(); if(lw[sym_num].num==26) { start.stack[start.first++]=sym_num; } else { flag=1; fouterr<<"óstartȱð"<<endl; } Next(); if (lw[sym_num].num == 37)//DZʶ { //ִг start.stack[start.first++]=sym_num; start.stack[start.first++]=100; putstart(start.first); Next(); B(); } else { flag=1; fouterr<<"óstartȱٷ"<<endl; } } else { flag=1; fouterr<<"óȱٹؼ֣start"<<endl; } } // BCD void B()// { if (lw[sym_num].num == 4)//жvar { Next(); C(); } else if (lw[sym_num].num == 8)//жbegin { Next(); D(); } else { flag=1; fouterr<<"ȱvarbegin"<<endl; } } //C var E| //EFGFGE void C()// { if (F()) { Next(); if (lw[sym_num].num == 26)// { Next(); if (lw[sym_num].num == 5 || lw[sym_num].num == 6 || lw[sym_num].num == 7)//integer,bool,real { int j = sym_num; j = j - 2; lw[j].type = lw[sym_num].num; symbollist.key[symbollist.key_count++]=lw[j].type; j--; while (lw[sym_num].num == 27) { j--; lw[j].type = lw[sym_num].num; symbollist.key[symbollist.key_count++]=lw[j].type; } Next(); if (lw[sym_num].num == 28) { Next(); if (lw[sym_num].num == 8) { Next(); D(); } else if(lw[sym_num].num == 4) { Next(); C(); } else { flag=1; fouterr<< "ȱvarbegin"<<endl; } } else { flag=1; fouterr<< "ȱ٣"<<endl; } } else { flag=1; fouterr<< "ȱͻͶ"<<endl; return; } } else { flag=1; fouterr<<"ʶȱð"<<endl; } } else { flag=1; fouterr<<"ʶ"<<endl; } } //D begin H end void D()// { H(); if (flag == 0) { if (lw[sym_num].num == 9) { return; } else { flag=1; fouterr<<"Ͼĩβȱend"<<endl; } } } //HIHI void H()// { I(); if (flag==0) { Next(); if (lw[sym_num].num == 28) { Next(); H(); } } } int lookup(int num) { int i = 0; int flag = 0; for (int i = 0; i < symbollist.name_count; i++) { if (strcmp(lw[symbollist.name[i]].word, lw[num].word) == 0) { flag = 1; break; } else flag = 0; } return flag; } // IJK void I()// { int flag_work=0; Equal.first=0; if (lw[sym_num].num == 37) { flag_work = lookup(sym_num); if(flag_work==1) { Equal.stack[Equal.first++]=sym_num; Next(); J(); } else { flag=1; fouterr<<"δ"<<endl; } } else if (lw[sym_num].num == 8 || lw[sym_num].num == 14 || lw[sym_num].num == 10) { K(); } else { Before(); } } // JAN void J()// { if (lw[sym_num].num == 32)//:= { Equal.stack[Equal.first++]=sym_num; Next(); N(); } else { flag=1; fouterr<<"ֵȱ٣="<<endl; } } //NRQ void N()// { if (lw[sym_num].num == 12 || lw[sym_num].num == 13 || (lw[sym_num].num == 37&&lw[sym_num].type == 7)) { Q(); } else { Next(); if (lw[sym_num].num == 19 || lw[sym_num].num == 20||lw[sym_num].num==21||lw[sym_num].num==22) { operator_flag = 1; } Before(); R(); } } //QX or QX void Q()// { X(); if (flag == 0) { Next(); if (lw[sym_num].num == 17) { Next(); Q(); } else { Before(); } } else { return; } } //XY and XY void X()// { Y(); if (flag == 0) { Next(); if (lw[sym_num].num == 36) { Next(); X(); } else { Before(); } } } //Y not YZ void Y()// { if (lw[sym_num].num == 18) { Next(); Y(); } else { Z(); } } //ZB'AQM //MA L A //L<|< | | >| > //B' truefalse void Z()// { Judge.first = 0; if (lw[sym_num].num == 12 || lw[sym_num].num == 13) { return; } else if (lw[sym_num].num == 37) { Judge.stack[Judge.first++] = sym_num; Next(); if (lw[sym_num].num == 34 || lw[sym_num].num == 33 || lw[sym_num].num == 30 || lw[sym_num].num == 31 || lw[sym_num].num == 29 || lw[sym_num].num == 35) { Next(); if (lw[sym_num].num == 37) { } else { flag=1; fouterr<<"ϵȱٱʶ"<<endl; } } else { Before(); } } else if (lw[sym_num].num == 23) { Q(); if (lw[sym_num].num == 24) { return; } else { flag=1; fouterr<<"еIJʽȱһ"<<endl; } } else { flag=1; fouterr<<""<<endl; } } //FAFA bool F()//жǷDZʶ { if (lw[sym_num].num == 37) { symbollist.name[symbollist.name_count++]=sym_num; Next(); if (lw[sym_num].num == 27)//, { Next(); return F(); } else { Before(); return true; } } else { return false; } } //RS+RS-RS void R()// { S(); if (flag == 0) { Next(); if (lw[sym_num].num == 19 || lw[sym_num].num == 20) { operator_confirm = 1; Add.first = 0; Add.stack[Add.first++] = sym_num; Next(); R(); } else { Before(); return; } } else { return; } } //ST*ST/ST void S() { T(); if (flag == 0) { Next(); if (lw[sym_num].num == 21|| lw[sym_num].num == 22) { operator_confirm = 1; Add.first = 0; Add.stack[Add.first++] = sym_num; Next(); S(); } else { Before(); return; } } else { return; } } //TUR void T()// { if (lw[sym_num].num == 23) { Next(); R(); Next(); if (lw[sym_num].num == 24) { return; } else { flag=1; fouterr<<"ʽȱ٣"<<endl; } } else { U(); } } //UACONSTANTFLOAT void U()// { int flag_work = 0; int tag = 0; int num_temp = 0; if (lw[sym_num].num == 2 || lw[sym_num].num == 3 || lw[sym_num].num == 37) { if(lw[sym_num].num==2||lw[sym_num].num==3) { if (operator_flag==1) { int a = Equal.first - 1; int temp = Equal.stack[a]; flag_work = lookup(temp); if (flag_work == 1) { Equal.first--; Add.stack[Add.first++] = temp; } else { flag = 1; fouterr << "ֵδ" << endl; } if (operator_confirm == 1) { Add.stack[Add.first++] = sym_num; Add.stack[Add.first++] = 120; putAdd(Add.first); Equal.stack[Equal.first++] = 120; Equal.stack[Equal.first++] = 100; putEqual(Equal.first); } } else { symbollist.num[symbollist.num_count++] = sym_num; Equal.stack[Equal.first++] = sym_num; Equal.stack[Equal.first++] = 100; putEqual(Equal.first); } } else if (lw[sym_num].num == 37) { if (operator_flag == 1) { if (operator_confirm==1) { int a = Equal.first - 1; int temp = Equal.stack[a]; flag_work = lookup(temp); if (flag_work == 1) { Equal.first--; Add.stack[Add.first++] = temp; } else { flag = 1; fouterr << "ֵδ" << endl; } flag_work = lookup(sym_num); if (flag_work == 1) { Add.stack[Add.first++] = sym_num; Add.stack[Add.first++] = 120; putAdd(Add.first); Equal.stack[Equal.first++] = 120; Equal.stack[Equal.first++] = 100; putEqual(Equal.first); } else { flag = 1; fouterr << "ֵδ" << endl; } } else { flag_work = lookup(sym_num); if (flag_work == 1) { Equal.stack[Equal.first++] = sym_num; } else { flag = 1; fouterr << "ֵδ" << endl; } } } else { for (int i = 0; i < symbollist.name_count; i++) { if (strcmp(lw[symbollist.name[i]].word, lw[sym_num].word) == 0) { Equal.stack[Equal.first++] = sym_num; Equal.stack[Equal.first++] = 100; putEqual(Equal.first); flag_work = 1; tag = i; break; } else flag_work = 0; } if (flag_work == 1) { symbollist.num[symbollist.num_count++] = symbollist.num[tag]; } else { flag = 1; fouterr << "ֵδ" << endl; } } } return; } else { flag=1; fouterr<<"ȱ"<<endl; } } // KDOP void K() { if (lw[sym_num].num == 8) { Next(); D(); } else if (lw[sym_num].num == 14) { Next(); O(); } else if (lw[sym_num].num == 10) { Next(); P(); } } // O if Q then I| if Q then I else I void O()// { Q(); if (flag == 0) { Next(); if (lw[sym_num].num == 15) { Next(); I(); Next(); if (lw[sym_num].num == 16) { Next(); I(); } else { Before(); return; } } else { flag=1; fouterr<<"if...thenȱthen"<<endl; } } else { flag=1; fouterr<<"if䲼ʽ"<<endl; } } // P while Q do I void P() { Q(); if (flag == 0) { Next(); if (lw[sym_num].num == 11) { Next(); if(lw[sym_num].num == 8) { Next(); D(); } else I(); } else { flag=1; fouterr<<"whileȱdo"<<endl; } } } int senmatic() { char gettxt[1000]; int i,j=0,k=0; symbollist.key_count=0; symbollist.name_count=0; symbollist.num_count=0; ifstream fin("F:\\shuchu.txt ",ios::in);//Լ趨·ļ for(i=0;i<1000;i++) gettxt[i] =fin.get();//ļȡa[] fin.close(); i=0; while(gettxt[i]=='<') { i++;k=0; if(gettxt[i+1]!=',') { lw[j].num=(gettxt[i]-'0')*10+(gettxt[i+1]-'0'); i=i+3; } else { lw[j].num=gettxt[i]-'0'; i++;i++; } if(lw[j].num==30) { lw[j].word[k++]=gettxt[i]; i++; } while(gettxt[i]!='>') { lw[j].word[k++]=gettxt[i]; i++; } lw[j].word[k]='\0'; i++;i++; j++; } countword=j; for(int x=0;x<j;j++) { lw[x].type=0; } A(); /*if(flag==0) cout<<"ɹ"<<endl; else cout<<""<<endl;*/ four << "(" << sort++ << ")"; four<<"<sys,_,_,_>"<<endl; fouterr.close(); four.close(); system("pause"); return flag; }
true
ea24b635272e3083135bb61fc04adad6a8cb608a
C++
Pechenkya/GameProject
/ConsoleApplication1/Pathfinding.h
UTF-8
2,732
2.734375
3
[]
no_license
#pragma once #include <list> #include <queue> #include <memory> #include <functional> #define OUT class Vector2D; class Object; class Node { private: int HCost = 0; int GCost = 0; int SCost = 0; float PriorityScore = 0; // // For Querying int GridX; int GridY; Node * PathRoot = nullptr; bool Walkable = true; bool Reachable = false; // For Querying void SetSCost(); public: void SetWalkable(bool av); void SetReachable(bool av); static int GetTwoNodesHueristic(Node * n1, Node * n2); void SetHCost(Node * Target); void SetPathRoot(Node * ParentNode); void SetGCost(float G_Cost); void SetX(int X); void SetY(int Y); void AddPriorityScore(float score); int GetPosX() const; int GetPosY() const; int GetPriorityScore() const; int GetSCost() const; int GetHCost() const; int GetGCost() const; Node * GetPathRootNode() const; bool IsWalkable() const; bool IsReachable() const; }; struct NodeSCostCompare { bool operator()(const Node * n1, const Node * n2); }; struct NodePriorityCompare { bool operator()(const Node * n1, const Node * n2); }; class NodeGridComponent { private: Vector2D * GridBottomLeft = nullptr; Vector2D * GridTopRight = nullptr; int GridSizeX; int GridSizeY; std::vector<std::vector<Node>> NodeGrid; public: std::vector<Node> &operator[](int index); Node * VectorToNode(Vector2D vec); Vector2D NodeToVector(Node * node); int GetSizeX() const; int GetSizeY() const; std::vector<std::vector<Node>> * GetGrid(); NodeGridComponent(); NodeGridComponent(Vector2D & GBottomLeft, Vector2D & GTopRight, std::list<Object*> ObjList); }; class PathfindingComponent { private: NodeGridComponent NavGrid; std::list<Node*> ProcessedNodes; std::priority_queue<Node*, std::vector<Node*>, NodeSCostCompare> OpenNodes; bool IsNodeInProccesed(Node * NodeToCheck); bool IsNodeInOpen(Node * NodeToCheck); void Clear(); public: PathfindingComponent(); std::queue<Vector2D> GetPath(Vector2D GBottomLeft, Vector2D GTopRight, Vector2D StartLocation, Vector2D TargetLocation, std::list<Object*> ObjList, OUT float & PathLength); }; class GridQueryComponent { private: NodeGridComponent QueryGrid; PathfindingComponent Pathfinder; std::priority_queue<Node*, std::vector<Node*>, NodePriorityCompare> Nodes; void SetReachable(Vector2D FromVector, Vector2D GBottomLeft, Vector2D GTopRight, std::list<Object*> Obstacles); void ScoreByDistance(Vector2D FromVector, float BestDistance); // basically * 0.1 void ScoreByStraightVisibility(Vector2D VisibleFromVector); public: std::queue<Vector2D> GetBestPositions(Vector2D SelfPosition, Vector2D EnemyPosition, float EnemyBestRange, std::list<Object*> Obstacles, Vector2D GBottomLeft, Vector2D GTopRight); };
true
4e7decaf2324c5378d1946db4866de82980c74c2
C++
iUmarov/acm-tuit-uz
/0046. Inversiyalar soni.cpp
UTF-8
1,377
2.890625
3
[]
no_license
#include <iostream> using namespace std; __int64 inv = 0, helper[1000001]; void Merge(__int64 a[], __int64 left, __int64 middle, __int64 right) { __int64 i, j, size; i = left; j = middle; size = middle - left; for (__int64 k=left;k<right;k++) { if (i==middle) {helper[k]=a[j++]; continue;} if (j==right) {helper[k]=a[i++]; continue;} if(a[i] <= a[j]) { helper[k] = a[i++]; size--; } else { helper[k] = a[j++]; inv += size; } } for(__int64 k = left; k < right; k++) a[k] = helper[k]; } void MergeSort(__int64 a[], __int64 left, __int64 right) { if(right == 1 + left) return; int middle=(left+right) / 2; MergeSort(a,left,middle); MergeSort(a,middle,right); Merge(a,left,middle,right); } int main() { __int64 n, i; __int64 a[50000]; cin >> n; for(i = 0; i < n; i++) cin >> a[i]; MergeSort(a,0,n); cout << inv << endl; //system("pause"); return 0; }
true
4bfbd75c0756d915cffa9eee4a9cb1bddb525da7
C++
Szelethus/cpp_courses
/2022-23-1/monday12-14/12gy/minh_interface.cpp
UTF-8
551
3.390625
3
[]
no_license
#include <iostream> struct Printable { virtual void print() const = 0; virtual int getId() { return -1; } }; struct Drawable { virtual void draw() const { } virtual int getId() { return -1; } }; void print(Printable *p) { p->print(); } class Shape : public Printable, public Drawable { protected: int x, y; public: Shape(int x, int y) : x(x), y(y) {} virtual void print() const { std::cout << "(x: " << x << ", y: " << y << ")"; } virtual int getId() { return -1; } }; int main() { Shape s(0,0); s.getId(); }
true
cc4f4b9b14db7eebf4665f17d67bd74ecc93c769
C++
steppobeck/rgbd-recon
/framework/DataTypes.cpp
UTF-8
3,923
2.8125
3
[ "MIT" ]
permissive
#include "DataTypes.h" namespace kinect{ uv interpolate(const uv& a, const uv& b, float t){ uv r; r.u = (1.0f - t)*a.u + t*b.u; r.v = (1.0f - t)*a.v + t*b.v; return r; } xyz interpolate(const xyz& a, const xyz& b, float t){ xyz r; r.x = (1.0f - t)*a.x + t*b.x; r.y = (1.0f - t)*a.y + t*b.y; r.z = (1.0f - t)*a.z + t*b.z; return r; } /*extern*/ xyz operator* (const float v, const xyz& b){ xyz res; res.x = v * b.x; res.y = v * b.y; res.z = v * b.z; return res; } /*extern*/ uv operator* (const float v, const uv& b){ uv res; res.u = v * b.u; res.v = v * b.v; return res; } /*extern*/ xyz operator+ (const xyz& a, const xyz& b){ xyz res; res.x = a.x + b.x; res.y = a.y + b.y; res.z = a.z + b.z; return res; } std::ostream& operator << (std::ostream& o, const xyz& v){ o << "(" << v.x << "," << v.y << "," << v.z << ")"; return o; } /*extern*/ uv operator+ (const uv& a, const uv& b){ uv res; res.u = a.u + b.u; res.v = a.v + b.v; return res; } /*extern*/ uv operator- (const uv& a, const uv& b){ uv res; res.u = a.u - b.u; res.v = a.v - b.v; return res; } std::ostream& operator << (std::ostream& o, const uv& v){ o << "(" << v.u << "," << v.v << ")"; return o; } /*extern*/ xyz_d operator* (const float v, const xyz_d& b){ xyz_d res; res.x = v * b.x; res.y = v * b.y; res.z = v * b.z; return res; } /*extern*/ uv_d operator* (const float v, const uv_d& b){ uv_d res; res.u = v * b.u; res.v = v * b.v; return res; } /*extern*/ xyz_d operator+ (const xyz_d& a, const xyz& b){ xyz_d res; res.x = a.x + b.x; res.y = a.y + b.y; res.z = a.z + b.z; return res; } /*extern*/ uv_d operator+ (const uv_d& a, const uv& b){ uv_d res; res.u = a.u + b.u; res.v = a.v + b.v; return res; } xyz getTrilinear(xyz* data, unsigned width, unsigned height, unsigned depth, float x, float y, float z){ // calculate weights and boundaries along x direction unsigned xa = std::floor(x); unsigned xb = std::ceil(x); float w_xb = x - xa; float w_xa = 1.0 - w_xb; // calculate weights and boundaries along y direction unsigned ya = std::floor(y); unsigned yb = std::ceil(y); float w_yb = y - ya; float w_ya = 1.0 - w_yb; // calculate weights and boundaries along z direction unsigned za = std::floor(z); unsigned zb = std::ceil(z); float w_zb = z - za; float w_za = 1.0 - w_zb; // calculate indices to access data const unsigned idmax = width * height * depth; unsigned id000 = std::min( za * width * height + ya * width + xa , idmax); unsigned id100 = std::min( za * width * height + ya * width + xb , idmax); unsigned id110 = std::min( za * width * height + yb * width + xb , idmax); unsigned id010 = std::min( za * width * height + yb * width + xa , idmax); unsigned id001 = std::min( zb * width * height + ya * width + xa , idmax); unsigned id101 = std::min( zb * width * height + ya * width + xb , idmax); unsigned id111 = std::min( zb * width * height + yb * width + xb , idmax); unsigned id011 = std::min( zb * width * height + yb * width + xa , idmax); // 1. interpolate between x direction: 4 times; xyz tmp_000_100 = w_xa * data[id000] + w_xb * data[id100]; xyz tmp_010_110 = w_xa * data[id010] + w_xb * data[id110]; xyz tmp_001_101 = w_xa * data[id001] + w_xb * data[id101]; xyz tmp_011_111 = w_xa * data[id011] + w_xb * data[id111]; // 2. interpolate between y direction: 2 times; xyz tmp_A = w_ya * tmp_000_100 + w_yb * tmp_010_110; xyz tmp_B = w_ya * tmp_001_101 + w_yb * tmp_011_111; xyz result = w_za * tmp_A + w_zb * tmp_B; return result; } }
true
caaad2ba4bd7c02a0aa48abf5303b2095c2673f7
C++
kljoshi/C_plus_plus
/Exercise/Chapter7/implicitArray.cpp
UTF-8
238
2.75
3
[]
no_license
#include <iostream> #include <cstdlib> #include <stdlib.h> #include <time.h> #include <fstream> using namespace std; int main() { int num[] = {1,2,3,4,5,6,7,8,9}; for(int value: num){ cout << value << endl; } return 0; }
true
0f4cfafde81acfb9b23dc50b7da36144c68ba0c9
C++
bizzehdee/neuro
/neuro/ActivationNeuron.h
UTF-8
572
2.71875
3
[]
no_license
#pragma once #include "Neuron.h" #include "IActivationFunction.h" namespace neuro { class ActivationNeuron : public Neuron { public: ActivationNeuron(int inputCount, IActivationFunction *activationFunction); double Threshold() const { return this->threshold; } void Threshold(const double x) { this->threshold = x; } IActivationFunction *ActivationFunction() { return this->activationFunction; } virtual void Randomize(); virtual double Compute(double *input); protected: double threshold = 0; IActivationFunction *activationFunction = 0; }; }
true
dfd0a489d88253bea3e2984aa734df95a6ccb53d
C++
SamRuckley/Temp
/Players.h
UTF-8
2,668
3.375
3
[]
no_license
#ifndef PLAYERS_H #define PLAYERS_H // // @summary Contains the information for the Players // class Players { ///////////////////////////////////////////////////////////////////////// // Public ///////////////////////////////////////////////////////////////////////// public: ///////////////////////////////////////////////////////////////////////// // Variables ///////////////////////////////////////////////////////////////////////// // // @summary The maximum amount of players allowed. // static const int MaximumPlayerCount = 2; ///////////////////////////////////////////////////////////////////////// // Methods ///////////////////////////////////////////////////////////////////////// // // @summary Constructor // explicit Players(); // // @summary Initialises the player class. // @return true if initialised; otherwise false. // bool Initialise(); // // @summary Gets if the player class has been initialised. // @return true if initialised; otherwise false. // bool IsInitialised(); // // @summary Creates an instance of the player class. // @return true if successful; otherwise false. // static bool CreateInstance(); // // @summary Gets an instance of the player class. // @return An instance of the player class; otherwise null. // static Players* GetInstance(); // // @summary Sets the player name. // @param amountOfPlayers The amount of players. // void SetPlayerNames(int amountOfPlayers); // // @summary Gets the player name at the specified index. // @param i The index of the player name. // @return The player name as a string. // std::string GetPlayerName(int i); ///////////////////////////////////////////////////////////////////////// // Private ///////////////////////////////////////////////////////////////////////// private: ///////////////////////////////////////////////////////////////////////// // Variables ///////////////////////////////////////////////////////////////////////// // // @summary If the class has been initialised. // bool initialised; // // @summary The instance of the player class. // static Players* instance; // // @summary Contains the player names. // std::string PlayerName[MaximumPlayerCount]; ///////////////////////////////////////////////////////////////////////// // Methods ///////////////////////////////////////////////////////////////////////// // // @summary Destructor // virtual ~Players(); }; #endif // PLAYERS_H
true
45285ca126347f726351629afd4edd66328d5ee7
C++
hp-peti/ofApps
/HexTile/src/ViewCoords.h
UTF-8
1,681
2.953125
3
[]
no_license
/* * ViewCoords.h * * Created on: 11 Feb 2018 * Author: hpp */ #ifndef SRC_VIEWCOORDS_H_ #define SRC_VIEWCOORDS_H_ #include <ofVec2f.h> #include <ofRectangle.h> #include <ofGraphics.h> struct ViewCoords { float zoom = 1.0; ofVec2f offset { 0, 0 }; ViewCoords() = default; ViewCoords(float zoom, const ofVec2f &offset) noexcept : zoom(zoom) , offset(offset) { } bool operator ==(const ViewCoords &other) { return zoom == other.zoom && offset == other.offset; } void setZoomWithOffset(float zoom, ofVec2f center) { offset += center / this->zoom; this->zoom = zoom; offset -= center / zoom; } void roundOffsetTo(float roundX, float roundY) { static const auto roundTo = [](float &value, float to) { if (to != 0) { value = to * std::round(value / to); } }; roundTo(offset.x, roundX); roundTo(offset.y, roundY); } ofRectangle getViewRect(const ofVec2f &size) const { ofRectangle result(0, 0, size.x, size.y); result.scale(1 / zoom, 1 / zoom); result.x += offset.x; result.y += offset.y; return result; } static ViewCoords blend(const ViewCoords &prevView, const ViewCoords &nextView, float alpha) { const auto beta = 1 - alpha;; return ViewCoords(prevView.zoom * beta + nextView.zoom * alpha, prevView.offset * beta + nextView.offset * alpha); } void applyToCurrentMatrix() const { ofScale(zoom, zoom); ofTranslate(-offset.x, -offset.y); } }; #endif /* SRC_VIEWCOORDS_H_ */
true
26cd0f2b2f6400442d0c623ce719fb4fca616025
C++
UniqueZHY/ZHY
/LeetCode/111_二叉树的最小深度.cpp
UTF-8
599
3.140625
3
[]
no_license
/************************************************************************* > File Name: 111_二叉树的最小深度.cpp > Author: > Mail: > Created Time: 2020年02月28日 星期五 15时21分31秒 ************************************************************************/ int minDepth(struct TreeNode* root) { if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 1; if (root->left == NULL || root->right == NULL) return minDepth(root->right ? root->right : root->left) + 1; return fmin(minDepth(root->left), minDepth(root->right)) + 1; }
true
039ad502cb256db98b0f65b61e98bccebec76b77
C++
githubcai/hiho
/1/1040.cpp
UTF-8
1,221
3.21875
3
[]
no_license
#include <cstdio> struct Node{ int x, y; bool operator==(const Node &a) const{ return x == a.x && y == a.y; } }; Node nodes[8]; bool check(){ int cnt = 8; for(int i = 0; i < 8; ++i){ for(int j = i + 1; j < 8; ++j){ if(nodes[i] == nodes[j]) --cnt; } } if(cnt == 4) return true; return false; } bool checkRect(){ int cnt1 = 0, cnt2 = 0; for(int i = 1; i < 4; ++i){ if((nodes[0].x - nodes[1].x) * (nodes[2 * i].x - nodes[2 * i + 1].x) == -(nodes[2 * i].y - nodes[2 * i + 1].y) * (nodes[0].y - nodes[1].y)){ cnt1 += 1; continue; } if((nodes[0].x - nodes[1].x) * (nodes[2 * i].y - nodes[2 * i + 1].y) == (nodes[2 * i].x - nodes[2 * i + 1].x) * (nodes[0].y - nodes[1].y)){ cnt2 += 1; continue; } } if(cnt1 == 2 && cnt2 == 1) return true; return false; } int main(){ int T; scanf("%d", &T); while(T-- > 0){ for(int i = 0; i < 8; ++i){ scanf("%d%d", &nodes[i].x, &nodes[i].y); } if(check() && checkRect()){ printf("YES\n"); }else{ printf("NO\n"); } } return 0; }
true
3fbc4c22a7948d51d30679c4b21c32fb8862dd2d
C++
anderra57/1maila
/2. KUATRI/KE/ARDUINO/KE/SADFSD/Arduino_Lana_erm/Arduino_Lana_erm.ino
UTF-8
3,204
2.625
3
[]
no_license
// include the library code: #include <LiquidCrystal.h> // initialize the library with the numbers of the interface pins LiquidCrystal lcd(7, 6, 5, 4, 3, 2); const int inputPin = A0; // buttons array analog input uint16_t inputValue = 0; // value read from buttons array int hrs=23; int mins=58; int sec=55; int cont=0; int cont2=0; float graduak; const int sensorPin= A5; byte gradua[]={ B11100, B10100, B11100, B00000, B00000, B00000, B00000, B00000 }; // Initialization void setup(){ lcd.begin(16,2); lcd.clear(); lcd.createChar(0,gradua); } // main loop void loop(){ inputValue = analogRead(inputPin); if(inputValue < 100 && inputValue >= 0) inputValue = 1; else if(inputValue < 250 && inputValue > 150) inputValue = 2; else if(inputValue < 470 && inputValue > 370) inputValue = 3; else if(inputValue < 670 && inputValue > 570) inputValue = 4; else if(inputValue < 870 && inputValue > 770) inputValue = 5; else if(inputValue <= 1023 && inputValue > 950) inputValue = 0; if(cont >= 4 ){ cont = 0; } if(inputValue == 5 ){ cont ++; } if(cont == 0){ if(sec>58){ sec=0; mins ++; } else { sec ++; if(mins>=60){ mins=0; hrs ++; } if(hrs>23){ hrs=0; }} lcd.clear(); lcd.setCursor(0,0); lcd.print("Menu: Ordua"); lcd.setCursor(0,2); if (hrs<10){ lcd.print("0"); } lcd.print(hrs); lcd.print(":"); if (mins<10){ lcd.print("0"); } lcd.print(mins); lcd.print(":"); if (sec<10){ lcd.print("0"); } lcd.print(sec); delay(1000); } if(cont==1){ lcd.clear(); lcd.setCursor(0,0); lcd.print("Menu: Aldatu Ordua"); lcd.setCursor(0,2); if (hrs<10){ lcd.print("0"); } lcd.print(hrs); lcd.print(":"); if (mins<10){ lcd.print("0"); } lcd.print(mins); lcd.print(":"); if (sec<10){ lcd.print("0"); } lcd.print(sec); delay(1000); if(inputValue == 1 ){ hrs ++; } if(inputValue == 2 ){ mins ++; } if(inputValue == 3 ){ sec ++; }} if(cont==3 ){ if(sec>59){ sec=0; mins ++; } else { sec ++; if(mins>59){ mins=0; hrs ++; } if(hrs>23){ hrs=0; }} lcd.clear(); lcd.setCursor(0,0); lcd.print("Menu: Ordua"); lcd.setCursor(0,2); if (hrs<10){ lcd.print("0"); } lcd.print(hrs); lcd.print(":"); if (mins<10){ lcd.print("0"); } lcd.print(mins); lcd.print(":"); if (sec<10){ lcd.print("0"); } lcd.print(sec); delay(1000); } if (cont==2 ){ graduak=analogRead(sensorPin); graduak=(5.0*graduak*100.0)/1024.0; lcd.setCursor(0,0); lcd.print("Menu:Tenperatura"); lcd.setCursor(0,2); lcd.print(graduak); lcd.write(byte(0)); lcd.print("C "); if(sec>59){ sec=0; mins ++; } else { sec ++; if(mins>59){ mins=0; hrs ++; } if(hrs>23){ hrs=0; }} delay(1000); } }
true
a9f9946dbb3737d3001a646622843e4e629655fb
C++
am009/PAT
/A1086-Tree-Traversals-Again/main.cpp
UTF-8
2,068
3.25
3
[]
no_license
#include <cstdio> #include <iostream> #include <stack> #include <cstring> struct node { int data; struct node* lchild; struct node* rchild; }; typedef struct node node; node* head; int N; char buf[11]; int * preO; int *inO; // 先序和中序构建树,包含端点 node* construct(int inOl, int inOr, int preOl, int preOr) { if (inOl > inOr || preOl > preOr) { return nullptr; } // 初始化 node* head = new node; head->data = preO[preOl]; // 计算位置 int ind = -1; for(int i=inOl;i<=inOr;i++) { if (inO[i] == head->data) { ind = i; break; } } if (ind == -1) { // printf("#err1#"); return nullptr; } int lLen = ind - inOl; // 递归构建 head->lchild = construct(inOl, ind-1, preOl+1, preOl+lLen); head->rchild = construct(ind+1, inOr, preOl+1+lLen, preOr); return head; } void postVisit(node* head) {\ static bool first = true; if (head == nullptr) { return; } postVisit(head->lchild); postVisit(head -> rchild); if(first) { printf("%d", head->data); first = false; } else { printf(" %d", head->data); } } int main () { std::cin >> N; preO = new int[N]; inO = new int[N]; std::stack<int> que_tmp; int tmp; int push_ind = 0; int pop_ind = 0; for (int i=0;i<2*N;i++) { scanf("%10s", buf); if (!strcmp(buf, "Push")) { std::cin >> tmp; que_tmp.push(tmp); preO[push_ind] = tmp; push_ind ++; // printf("push %d\n", tmp); } else if(!strcmp(buf, "Pop")) { inO[pop_ind] = que_tmp.top(); pop_ind ++; // printf("pop %d\n", que_tmp.top()); que_tmp.pop(); } else { // printf("#err#"); } } if(push_ind != N && pop_ind != N) { printf("!%d %d\n", push_ind, pop_ind); } head = construct(0, N-1, 0, N-1); postVisit(head); return 0; }
true
d26ebceb1a62a4d92c2b421f7a67efbcc9de02ce
C++
heshamOuda1/FHNW-Java-Projekte
/prcpp/Vector/VectorTest/unittest1.cpp
UTF-8
2,855
3.15625
3
[]
no_license
#include "stdafx.h" #include "CppUnitTest.h" #include "Expression.hpp" #include "Array.hpp" #include "Scalar.hpp" #include "Operations.hpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace VectorTest { TEST_CLASS(Vector) { public: TEST_METHOD(Construction) { double a_data[] = { 2, 3, 5, 9 }; Array<double> A(a_data, 4); Assert::IsTrue(A.getLength() == 4); Scalar<double> S(2); Assert::IsTrue(S.m_value == 2); } TEST_METHOD(Addition) { double a_data[] = { 2, 3, 5, 9 }; double b_data[] = { 1, 0, 0, 0 }; double c_data[] = { 3, 0, 2, 5 }; double d_data[4]; double e_data[] = { 6, 3, 7, 14 }; Array<double> A(a_data, 4); Array<double> B(b_data, 4); Array<double> C(c_data, 4); Array<double> D(d_data, 4); Array<double> E(e_data, 4); D = A + B + C; Assert::IsTrue(D == E); } TEST_METHOD(Subtraction) { double a_data[] = { 2, 3, 5, 9 }; double b_data[] = { 1, 0, 0, 0 }; double c_data[] = { 3, 0, 2, 5 }; double d_data[4]; double f_data[] = { -2, 3, 3, 4 }; Array<double> A(a_data, 4); Array<double> B(b_data, 4); Array<double> C(c_data, 4); Array<double> D(d_data, 4); Array<double> F(f_data, 4); D = A - B - C; Assert::IsTrue(D == F); } TEST_METHOD(MultiplicationVectorVector) { double a_data[] = { 2, 3, 5, 9 }; double b_data[] = { 1, 0, 0, 0 }; double d = 2+0+0+0; Array<double> A(a_data, 4); Array<double> B(b_data, 4); Scalar<double> D; D = A * B; Assert::IsTrue(D.m_value == d); } TEST_METHOD(MultiplicationVectorScalar) { double a = 2; double b_data[] = { 2, 3, 5, 9 }; double c_data[] = { 4, 6, 10, 18 }; double d_data[4]; Scalar<double> A(a); Array<double> B(b_data, 4); Array<double> C(c_data, 4); Array<double> D(d_data, 4); D = B * A; Assert::IsTrue(D == C); } TEST_METHOD(MultiplicationScalarVector) { double a = 2; double b_data[] = { 2, 3, 5, 9 }; double c_data[] = { 4, 6, 10, 18 }; double d_data[4]; Scalar<double> A(a); Array<double> B(b_data, 4); Array<double> C(c_data, 4); Array<double> D(d_data, 4); D = A * B; Assert::IsTrue(D == C); } TEST_METHOD(MultiplicationScalarScalar) { double a = 2; double b = 3; Scalar<double> A(a); Scalar<double> B(b); Assert::IsTrue((A * B)[1] == 6); } TEST_METHOD(StammTest) { double k = 5; double l = 3.14; double a_data[] = { 2, 3, 5, 9 }; double b_data[] = { 1, 0, 0, 1 }; double c_data[] = { 3, 0, 2, 5 }; double d_data[4]; double e_data[] = {20.42,15,31.28,61.7}; Array<double> A(a_data, 4); Array<double> B(b_data, 4); Array<double> C(c_data, 4); Array<double> D(d_data, 4); Array<double> E(d_data, 4); D = k*A + B + l*C; Assert::IsTrue(D == E); } }; }
true
11fcac7c464c30fc9707aab5454b290c679d3801
C++
yuhaim/PTA
/basic/1047.cpp
UTF-8
487
3.09375
3
[]
no_license
#include <iostream> #include <cstdio> #include <map> using namespace std; int main() { int N; cin >> N; map<int, int> data; while(N--){ int team, id, score; scanf("%d-%d %d", &team, &id, &score); data[team] += score; } int max_team, max_score = 0; for(auto x=data.begin(); x!=data.end(); x++){ if(x->second > max_score){ max_score = x->second; max_team = x->first; } } cout << max_team << ' ' << max_score << endl; return 0; }
true
4fa5c4034b252f705d4a0c722c10985f0d29924f
C++
akotadi/Competitive-Programming
/Interview/LeetCode/TopInterviewQuestions/Array/Remove Duplicates from Sorted Array.cpp
UTF-8
2,451
3.453125
3
[]
no_license
/* * Copyright (c) 2019 ManuelCH. * * This file is part of Interview-solutions * (see https://github.com/akotadi). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example 1: Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length. Clarification: Confused why the returned value is an integer but your answer is an array? Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. Internally you can think of this: // nums is passed in by reference. (i.e., without making a copy) int len = removeDuplicates(nums); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); } */ class Solution { public: int removeDuplicates(vector<int>& nums) { int n = nums.size(); if(n < 2) return n; int i = 0, j = 1; while(j < n){ if(nums[j] > nums[i]){ if(j > i + 1) swap(nums[++i], nums[j++]); else i++, j++; } else j++; } return i + 1; } };
true
59f0a1b8ee8404252b37164340a9b21478feeb96
C++
theAnton-forks/Competitive-Programming-Portfolio
/Ability To Convert/src/Ability To Convert.cpp
UTF-8
1,901
2.609375
3
[]
no_license
#include <bits/stdc++.h> typedef long long ll; using namespace std; const int max_digs = 105; const int maxn = 65; ll dp[max_digs][maxn]; ll n; ll biggest = 1000000000000000000; string s_biggest = "1000000000000000000"; string k; ll smaller(string s, ll num){ if(s.size() > s_biggest.size() or (s.size() == s_biggest.size() and s > s_biggest)){ return -1; } ll gen = 0; for(int i = 0; i < s.size(); i++){ gen *= 10; gen += s[i] - '0'; } if(gen < num){ return gen; } else { return -1; } } ll fucking_peasant_multiplication(ll a, ll b){ ll orig = a; a = 0; while(b != 0){ if(b % 2 == 1){ a += orig; } if(a > biggest){ return -2; } b /= 2; orig *= 2; if(b != 0 and orig > biggest){ return -2; } } return a; } ll dfs(int digs_left, int pos){ if(dp[digs_left][pos] == -1){ ll &ans = dp[digs_left][pos]; if(pos == k.size()){ ans = 0; } else if(digs_left == 0){ ans = biggest + 1; } else { ans = biggest + 1; if(k[pos] == '0'){ ans = dfs(digs_left - 1, pos + 1); } else { for(int i = k.size() - 1; i >= pos; i--){ string gen = ""; for(int j = pos; j <= i; j++){ gen += k[j]; } if(smaller(gen, n) != -1){ ll tryy = smaller(gen, n); for(int j = 0; j < digs_left - 1; j++){ tryy = fucking_peasant_multiplication(tryy, n); if(tryy == -2LL){ tryy = ans; break; } } tryy += dfs(digs_left - 1, i + 1); if(tryy <= biggest and tryy < ans){ ans = tryy; } } } } } } return dp[digs_left][pos]; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; cin >> k; for(int i = 0; i < max_digs; i++){ for(int j = 0; j < maxn; j++){ dp[i][j] = -1; } } for(ll digs = 1; digs <= 100; digs++){ if(dfs(digs, 0) <= biggest){ cout << dfs(digs, 0) << endl; break; } } }
true
baa3bfdb08be99fe5ee665819467bbe5cb82e810
C++
brainexcerpts/MDD_file_exporter
/point_cache_export.hpp
UTF-8
2,150
2.625
3
[ "MIT" ]
permissive
#ifndef ASSET_POINT_CACHE_EXPORT_HPP #define ASSET_POINT_CACHE_EXPORT_HPP #include <vector> #include <string> // ============================================================================= namespace asset { // ============================================================================= // ============================================================================= namespace loader { // ============================================================================= /** * @brief (.mdd loader) Handling export of mesh point frame by frame * Point cache frame files enables to save at each frame the position of every * vertices of a mesh. It's an easy way to export a whole animation as the * format is largely supported by other animation software. The file is * rapidely too large to fit in memory though... * Don't record hours of sequences! */ class Point_cache_file{ public: Point_cache_file(int nb_points, int nb_frame_hint = 0); /// Add a new frame given the list of points coordinates points. /// @param points array of points with x y z coordinates contigus /// @param offset The number of elements to ignore and begin to read the /// array 'points' /// @param stride number of elements to ignore between each points void add_frame(float* points, int offset=0, int stride=0); /// Write out a mdd file void export_mdd(const std::string& path_name); // TODO: //void export_pc2(const std::string& path_name); //void import_pc2(const std::string& path_name, // const std::vector< std::vector<float> >& frames); private: /// list of frame. Each frame stores the object vertex coordinates. /// X Y Z coordinates are contigus. /// _frames[num_frame][list_points] std::vector< std::vector<float> > _frames; /// Number of points the cached object is. int _nb_points; }; }// END loader ================================================================= }// END asset NAMESPACE ======================================================== #endif // ASSET_POINT_CACHE_EXPORT_HPP
true
4fe45a023d78f57a1112aec99f5050d5ceaf3bd3
C++
vijayapradap/Arduino_Programs
/Arduino_Programs/button/button.ino
UTF-8
267
2.703125
3
[]
no_license
void setup() { // put your setup code here, to run once: pinMode(0, INPUT); pinMode(1, OUTPUT); } void loop() { // put your main code here, to run repeatedly: if(digitalRead(0) == 1) { digitalWrite(1, HIGH); } else { digitalWrite(1, LOW); } }
true
439bf221f77974e3a13b7059dcbf0d9f24b821bd
C++
Dzzirt/Game
/CBook/CBook/1.15.cpp
WINDOWS-1251
751
3.53125
4
[]
no_license
#include <stdio.h> /* , . */ int fromFahrToCels(float fahr); int main() { float fahr, celsius; int lower, upper, step; lower = 0; /* */ upper = 300; /* */ step = 20; /* */ fahr = lower; printf("%3s %9s\n", "Fahren", "Cels"); while (fahr <= upper) { celsius = fromFahrToCels(fahr); printf("%5.0f %9.1f\n", fahr, celsius); fahr = fahr + step; } return 0; } int fromFahrToCels(float fahr) { return (5.0 / 9.0) * (fahr - 32.0); }
true
82924919462ae8b34b88414697c42c9059a06326
C++
wcc17/untitled-game
/src/npc/NpcManager.cpp
UTF-8
5,226
2.71875
3
[]
no_license
#include "../../includes/npc/NpcManager.h" static const std::string NPC_TYPE_HUMAN = "human"; static const std::string NPC_TYPE_CAT = "cat"; static const std::string NPC_TYPE_MONSTER = "monster"; void NpcManager::initialize(const std::shared_ptr<EventBus> eventBus, const std::vector<Collidable>& collidables, const std::map<std::string, sf::IntRect>& npcMoveBoundaries, const std::map<std::string, std::vector<tmx::Property>>& npcNameToPropertiesMap, const sf::Vector2u& mapTileSize, TextureManager& textureManager) { this->eventBus = eventBus; this->mapTileSize = mapTileSize; for(Collidable collidable : collidables) { initializeNpc(textureManager, collidable, npcMoveBoundaries, npcNameToPropertiesMap); } eventBus->subscribe(this, &NpcManager::onOpenDialogueEvent, "NpcManager"); eventBus->subscribe(this, &NpcManager::onCloseDialogueEvent, "NpcManager"); eventBus->subscribe(this, &NpcManager::onNpcCollisionEvent, "NpcManager"); } void NpcManager::update(sf::Time deltaTime) { for(std::shared_ptr<NpcEntity> npc : npcs) { npc->update(deltaTime, mapTileSize); } } void NpcManager::drawToRenderTexture(sf::RenderTexture& renderTexture) const { for(std::shared_ptr<NpcEntity> npc : npcs) { renderTexture.draw(*npc); } } //TODO: stop writing out this for loop for every single function that needs to look at all of the npcs. Or put the NPCs in a map? void NpcManager::onOpenDialogueEvent(OpenDialogueEvent* event) { if(event->interactedWith.getType() == ObjectType::NPC) { for(std::shared_ptr<NpcEntity> npc : npcs) { if(event->interactedWith.getName() == npc->getEntityCollidable().getName()) { npc->onPlayerInteractionStart(event->playerFacingDirection); break; } } } } void NpcManager::onCloseDialogueEvent(CloseDialogueEvent* event) { for(std::shared_ptr<NpcEntity> npc : npcs) { if(npc->isPlayerInteractingWithEntity()) { npc->onPlayerInteractionFinish(); break; } } } void NpcManager::onNpcCollisionEvent(NpcCollisionEvent* event) { for(std::shared_ptr<NpcEntity> npc : npcs) { if(event->npc.getEntityCollidable().getName() == npc->getEntityCollidable().getName()) { npc->onCollisionEvent(event->newNpcPosition); break; } } } void NpcManager::initializeNpc( TextureManager& textureManager, const Collidable& collidable, const std::map<std::string, sf::IntRect>& npcMoveBoundaries, const std::map<std::string, std::vector<tmx::Property>>& npcNameToPropertiesMap) { std::vector<tmx::Property> npcProperties = npcNameToPropertiesMap.at(collidable.getName()); sf::IntRect moveBoundaries = npcMoveBoundaries.at(collidable.getName()); NpcType npcType = getNpcTypeFromString(Map::getObjectPropertyStringValue(Map::PROPERTY_NAME_NPC_TYPE, npcProperties)); std::string assetName = Map::getObjectPropertyStringValue(Map::PROPERTY_NAME_ASSET_NAME, npcProperties); bool isAggressive = Map::getObjectPropertyBoolValue(Map::PROPERTY_NAME_IS_AGGRESSIVE, npcProperties); sf::Texture* texture = loadAndRetrieveNpcTexture(assetName, textureManager); std::shared_ptr<NpcEntity> npcEntity = getNewNpcEntityFromType(npcType); npcEntity->initialize(texture, collidable, moveBoundaries, assetName, isAggressive, npcType); npcs.push_back(npcEntity); } sf::Texture* NpcManager::loadAndRetrieveNpcTexture(std::string assetName, TextureManager& textureManager) { std::string assetFilePath = AssetPath::getNpcAssetPath(assetName); textureManager.loadTexture(assetFilePath); return textureManager.getTexture(assetFilePath); } NpcType NpcManager::getNpcTypeFromString(std::string npcTypeString) { if(NPC_TYPE_HUMAN == npcTypeString) { return NpcType::HUMAN; } else if(NPC_TYPE_CAT == npcTypeString) { return NpcType::CAT; } else if(NPC_TYPE_MONSTER == npcTypeString) { return NpcType::MONSTER; } else { return NpcType::NO_NPC_TYPE; } } std::shared_ptr<NpcEntity> NpcManager::getNewNpcEntityFromType(NpcType npcType) { switch(npcType) { case NpcType::HUMAN: return std::make_shared<HumanNpcEntity>(); case NpcType::CAT: return std::make_shared<CatNpcEntity>(); case NpcType::MONSTER: return std::make_shared<MonsterNpcEntity>(); case NpcType::NO_NPC_TYPE: return std::make_shared<HumanNpcEntity>(); } } void NpcManager::releaseNpcTextures(std::string assetName, TextureManager& textureManager) { textureManager.releaseTexture(AssetPath::getNpcAssetPath(assetName)); } std::vector<std::shared_ptr<NpcEntity>>& NpcManager::getNpcEntities() { return this->npcs; } void NpcManager::release(TextureManager& textureManager) { eventBus->unsubscribeInstanceFromAllEventTypes(this); for(std::shared_ptr<NpcEntity> npc : npcs) { releaseNpcTextures(npc->getAssetName(), textureManager); } npcs.clear(); }
true
dc8911025b8f93a9b94c3a15951dd09d55929911
C++
HSaddiq/IDP
/Physical Programs/tests/angle_turned_test/angle_turned_test.ino
UTF-8
1,402
3.09375
3
[]
no_license
#include <Ultrasonic.h> #include <Wire.h> #include <Adafruit_MotorShield.h> #include <motor.h> using namespace std; String bearing_string = ""; int bearing_value = 0; int current_bearing = 0; int direction = 0; void setup() { Movement mov; //mov.get_threshold(); } void rotate(int direction, int bearing){ Movement mov; mov.turn(direction, 200, bearing); } void loop(){ Serial.println("arduino ready"); delay(500); if(Serial.readStringUntil('\n').equals("python ready")) { Serial.println("requesting bearing"); delay(3000); //read bearing as a string and convert to integer bearing_string = Serial.readStringUntil('\n'); bearing_value = bearing_string.toInt(); //check if the bearing sent is valid and different to the previous one (to make sure it has been updated) if(bearing_value > 0 && bearing_value <= 360 && bearing_value != current_bearing) { Serial.println("received"); current_bearing = bearing_value; //determines the direction of the turn based on the angle given if (bearing_value < 180) { direction = 1; //LEFT } else { direction = 0; // RIGHT bearing_value = 360 - bearing_value; } //calls the rotate function with the given variables rotate(direction, bearing_value); } } }
true
2083f6ea5b4d521a301c674e52f717e89d92c50e
C++
eglrp/myds
/Stack/ArrayStack/ArrayStack.h
GB18030
3,400
3.71875
4
[ "MIT" ]
permissive
#include <iostream> #include <string> #include "Stack.h" using namespace std; /** * ArrayStack: ջ */ template<typename T> class ArrayStack: public Stack<T> { public: // 1. public constructor static ArrayStack<T> *arrayStackFactory(int max_size); // 2. copy/move_controller ArrayStack(const ArrayStack<T> &other); ArrayStack<T> &operator= (const ArrayStack<T> &other); ArrayStack(ArrayStack<T> &&other); ArrayStack<T> &operator= (ArrayStack<T> &&other); // 3. methods bool push(T val); bool pop(T &val); bool top(T &val) const; int length() const; // 4. destructor ~ArrayStack(); int size; // ǰջԪظ int max_size; // ǰջԪظ T *data; // ջ洢 int pos; // ջָλ // 5. private constructor ArrayStack(int _max_size); }; template<typename T> ArrayStack<T> *ArrayStack<T>::arrayStackFactory(int max_size) { if(max_size<0) return NULL; else return new ArrayStack<T>(max_size); } template<typename T> ArrayStack<T>::ArrayStack(int _max_size) { size=0; max_size=_max_size; data=new T [max_size]; pos=-1; } template<typename T> ArrayStack<T>::ArrayStack(const ArrayStack<T> &other) { size=other.size; max_size=other.max_size; data=new T [max_size]; pos=other.pos; for(int i=0;i<pos;i++) { data[i]=other.data[i]; } } template<typename T> ArrayStack<T> & ArrayStack<T>::operator= (const ArrayStack<T> &other) { if(this==&other) return (*this); if(max_size!=other.max_size) { delete [] data; data=new T [other.max_size]; } size=other.size; max_size=other.max_size; pos=other.pos; for(int i=0;i<=pos;i++) { data[i]=other.data[i]; } return (*this); } template<typename T> ArrayStack<T>::ArrayStack(ArrayStack &&other) { size=other.size; max_size=other.max_size; data=other.data; pos=other.pos; other.size=0; other.data=new T [other.max_size]; other.pos=-1; } template<typename T> ArrayStack<T> &ArrayStack<T>::operator= (ArrayStack<T> &&other) { if(&other==this) return (*this); delete [] data; size=other.size; max_size=other.max_size; data=other.data; pos=other.pos; other.size=0; other.data=new T [other.max_size]; other.pos=-1; return (*this); } template<typename T> bool ArrayStack<T>::push(T val) { if(size>=max_size) return false; else { pos+=1; data[pos]=val; size+=1; return true; } } template<typename T> bool ArrayStack<T>::pop(T &val) { if(pos==-1) // ʹsize==0 return false; else { val=data[pos]; pos-=1; size-=1; return true; } } template<typename T> bool ArrayStack<T>::top(T &val) const { if(pos==-1) // ʹsize==0 return false; else { val=data[pos]; return true; } } template<typename T> int ArrayStack<T>::length() const { return size; } template<typename T> ArrayStack<T>::~ArrayStack() { delete data; }
true
5b67d35334b95ed1d4b1ce58b563639de3687f2a
C++
WladWD/AndroidGame
/AGame/GlobalMove.cpp
UTF-8
860
2.6875
3
[]
no_license
#include "GlobalMove.h" GameEngine::GlobalMove::GlobalMove(float fMoveStep, float fMoveSpeed) : fMoveStep(fMoveStep), fMoveSpeed(fMoveSpeed), fDiv(1.0f / 1000.0f) { fMoveValue = 0.0f; flag = 0; fDMove = 0.0f; } GameEngine::GlobalMove::~GlobalMove() { } void GameEngine::GlobalMove::Move(float fDeltaTimeMs, float fGlobalTimeMs) { fDMove = fMoveSpeed * fDeltaTimeMs * fDiv; fMoveValue += fDMove; if (fMoveValue >= fMoveStep) { fMoveValue -= fMoveStep; flag ^= 1; } fH[flag] = fMoveValue; fH[flag ^ 1] = fMoveValue - fMoveStep; mMoveMatrix[0] = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, fH[0], 0.0f)); mMoveMatrix[1] = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, fH[1], 0.0f)); } float GameEngine::GlobalMove::GetMove(void) { return fDMove; } const glm::mat4 *GameEngine::GlobalMove::GetMoveMatrix() { return mMoveMatrix; }
true
1e4b64059878d6e06509b6ba4f2a4d8e2d63e600
C++
arapson/PortalGame
/Code/Portal.cpp
UTF-8
8,212
3.203125
3
[ "MIT" ]
permissive
// Nov, 17 2015 // Portal.cpp // Jacob London Avery Rapson // This Class handles 95% of the portal logic. It needs to be initialized in main, and requires 10 portals to be passs in. // #include "Portal.h" using namespace std; class Portal{ private: /** Storage of all portals**/ array<float,7> Portal1; array<float,7> Portal2; array<float,7> Portal3; array<float,7> Portal4; array<float,7> Portal5; array<float,7> Portal6; array<float,7> Portal7; array<float,7> Portal8; array<float,7> Portal9; array<float,7> Portal10; array<float,7> Portal11; array<float,7> Portal12; int position; //current portal marker /** Last Portal markers (to prevent falling back into the portal) */ bool portal1; bool portal2; bool portal3; bool portal4; bool portal5; bool portal6; bool portal7; bool portal8; bool portal9; bool portal10; bool portal11; public: /*Constructor -Creates Portal object *Pre: Requires 10 portals (array<float,7>) *Post: All portal information is saved in private globals, all variables initialized. */ Portal(array<float,7> p1, array<float,7> p2, array<float,7> p3, array<float,7> p4, array<float,7> p5, array<float,7> p6, array<float,7> p7, array<float,7> p8, array<float,7> p9, array<float,7> p10){ Portal1 = p1; Portal2 = p2; Portal3 = p3; Portal4 = p4; Portal5 = p5, Portal6 = p6; Portal7 = p7; Portal8 = p8; Portal9 = p9; Portal10= p10; for(int k = 0; k < 4; k++){ std::cout<< Portal1[k]+1 << ","; } std::cout<<"\n"; for(int k = 0; k < 4; k++){ std::cout<< Portal2[k]+1 << ","; } portal1 =portal2 =portal3 =portal4=portal5 =portal6 =portal7 =portal8 =portal9 =portal10 =portal11= false; position = 0; } /*checkPortal- Determins if camera is in portal area. * Pre: X and Z position of camera passed in, portals are valid and in-scene * Post: Returns true if the camera is in a portal area, Position is changed to current portal, portal markers are set to prevent falling back into poratl*/ bool checkPortal(float x, float z){ bool trans =false; /**Each of these control structures checks a portal location*/ if (z >= Portal2[1]-6 && z<= Portal2[1]+6) { if (x >= Portal2[0]-6 && x<= Portal2[0]+6) { position =2; if (!portal2) { trans = true; makeFalse(); portal8 = true; } } } if(z >= Portal3[1]-6 && z<= Portal3[1]+6) { if (x >= Portal3[0]-6 && x<= Portal3[0]+6) { position = 3; if (!portal3) { trans = true; makeFalse(); portal6 = true; } } } if (z >= Portal4[1]-6 && z<= Portal4[1]+6) { if (x >= Portal4[0]-6 && x<= Portal4[0]+6) { position = 4; if (!portal4) { trans = true; makeFalse(); portal4 = true; } } } if (z >= Portal7[1]-6 && z<= Portal7[1]+6) { if (x >= Portal7[0]-6 && x<= Portal7[0]+6) { position = 7; if (!portal7) { trans = true; makeFalse(); portal3 = true; } } } if (z >= Portal8[1]-6 && z<= Portal8[1]+6) { if (x >= Portal8[0]-6 && x<= Portal8[0]+6) { position = 8; if (!portal8) { trans = true; makeFalse(); portal2 = true; } } } if (z >= Portal6[1]-6 && z<= Portal6[1]+6) { if (x >= Portal6[0]-6 && x<= Portal6[0]+6) { position = 6; if (!portal6) { trans = true; makeFalse(); portal4 = true; } } } if (z >= Portal5[1]-6 && z<= Portal5[1]+6) { if (x >= Portal5[0]-6 && x<= Portal5[0]+6) { position = 5; if (!portal5) { trans = true; makeFalse(); portal7 = true; } } } if (z >= Portal1[1]-6 && z<= Portal1[1]+6) { if (x >= Portal1[0]-6 && x<= Portal1[0]+6) { position = 1; if (!portal1) { trans = true; makeFalse(); portal11= true; } } } if (z >= Portal9[1] -20 && z<= Portal9[1]) { if (x >= Portal9[0] && x<= Portal9[0]+6) { position = 9; trans = true; makeFalse(); } } if (z >= Portal10[1] -20 && z<= Portal10[1]) { if (x >= Portal10[0] && x<= Portal10[0]+6) { position = 10; trans = true; makeFalse(); } } return trans; } /* Changes all the portal markers to false, allowing the preveious portals to be set again * Pre: none * Post: are made false */ void makeFalse(){ portal1 =portal2 =portal3 =portal4=portal5 =portal6 =portal7 =portal8 =portal9 =portal10 =portal11= false; portal7 = false; } /* Switches the position of the camera with the target posistion of the current portal */ array<float, 5> switchPos(int num){ array<float, 5> r ={0,0,0,0,0}; if (num == 3){ r[0] = Portal3[2]; r[1] = Portal3[3]; r[2] = Portal3[4]; r[3] = Portal3[5]; r[4] = Portal3[6]; } else if (num == 4){ r[0] = Portal4[2]; r[1] = Portal4[3]; r[2] = Portal4[4]; r[3] = Portal4[5]; r[4] = Portal4[6]; } else if (num == 6){ r[0] = Portal6[2]; r[1] = Portal6[3]; r[2] = Portal6[4]; r[3] = Portal6[5]; r[4] = Portal6[6]; } else if (num == 2){ r[0] = Portal2[2]; r[1] = Portal2[3]; r[2] = Portal2[4]; r[3] = Portal2[5]; r[4] = Portal2[6]; } else if (num == 7){ r[0] = Portal7[2]; r[1] = Portal7[3]; r[2] = Portal7[4]; r[3] = Portal7[5]; r[4] = Portal7[6]; } else if (num == 5){ r[0] = Portal5[2]; r[1] = Portal5[3]; r[2] = Portal5[4]; r[3] = Portal5[5]; r[4] = Portal5[6]; } else if (num == 8){ r[0] = Portal8[2]; r[1] = Portal8[3]; r[2] = Portal8[4]; r[3] = Portal8[5]; r[4] = Portal8[6]; } else if (num == 1){ r[0] = Portal1[2]; r[1] = Portal1[3]; r[2] = Portal1[4]; r[3] = Portal1[5]; r[4] = Portal1[6]; } else if (num == 9){ r[0] = Portal9[2]; r[1] = Portal9[3]; r[2] = Portal9[4]; r[3] = Portal9[5]; r[4] = Portal9[6]; } else if (num == 10){ r[0] = Portal10[2]; r[1] = Portal10[3]; r[2] = Portal10[4]; r[3] = Portal10[5]; r[4] = Portal10[6]; } return r; } /*Returns the position data memeber. The position data memeber is the current portal.*/ int getPosition(){ return position; } };
true
494114f142f47ed110f48203150786dd9200ab6a
C++
SzymonPietraszek00/OOP
/Labs/Lab9/src/FlatPoint.cpp
UTF-8
691
3.390625
3
[]
no_license
#include "FlatPoint.h" bool FlatPoint::operator<(const FlatPoint &f2)const{ return _d < f2._d; } void FlatPoint::FunctionPrintY(const FlatPoint& point){ std::cout << "Function print y=" << point.getY() << std::endl; } void FlatPoint::PrintPoint(const FlatPoint& point){ point.Print(); } void FlatPoint::Print()const{ std::cout << "Point coordinates (" << _x << ", " << _y << ") distance from origin: " << _d << std::endl; } void FunctionPrintX(const FlatPoint& point){ std::cout << "Function print x=" << point.getX() << std::endl; } bool MaxDistanceAsc(const FlatPoint &f1, const FlatPoint &f2){ return std::max(f1.getX(), f1.getY()) < std::max(f2.getX(), f2.getY()); }
true
d2b1000cb0bef8e5fb1719ae9bde095b496e0c8a
C++
WSU-CS1410-AA/in-class_examples
/src/chp11-Streams_and_files/ex02-hello_append.cpp
UTF-8
195
2.96875
3
[]
no_license
// FILE: ex02-hello_append.cpp #include <fstream> using namespace std; int main () { ofstream out("hello.txt", ios::app); out << "Hello World!" << endl; out.close(); return 0; }
true
97c926aae93a595aa48b300aae22609769c440de
C++
The-Final-Cookie/ece2031-proj
/simulation/Vector.hpp
UTF-8
22,680
3.1875
3
[]
no_license
#ifndef VECTOR_HPP #define VECTOR_HPP #include <array> #include <cmath> #include "Util.hpp" namespace TFC { template<typename T, size_t N> class Vector : public std::array<T, N> { public: typedef std::array<T, N> Base; template<size_t P, typename T2=void> using Enable2D = typename std::enable_if<P == 2 && N == P, T2>::type; template<size_t P, typename T2=void> using Enable3D = typename std::enable_if<P == 3 && N == P, T2>::type; template<size_t P, typename T2=void> using Enable4D = typename std::enable_if<P == 4 && N == P, T2>::type; template<size_t P, typename T2=void> using Enable2DOrHigher = typename std::enable_if<P >= 2 && N == P, T2>::type; template<size_t P, typename T2=void> using Enable3DOrHigher = typename std::enable_if<P >= 3 && N == P, T2>::type; template<size_t P, typename T2=void> using Enable4DOrHigher = typename std::enable_if<P >= 4 && N == P, T2>::type; constexpr static Vector filled(T const& t); template<typename T2> constexpr static Vector floor(Vector<T2, N> const& v); template<typename T2> constexpr static Vector ceil(Vector<T2, N> const& v); template<typename T2> constexpr static Vector round(Vector<T2, N> const& v); template<typename Iterator> constexpr static Vector copyFrom(Iterator p); // Is zero-initialized (from Array) constexpr Vector(); constexpr explicit Vector(T const& e1); template<typename... TN> constexpr Vector(T const& e1, TN const&... rest); template<typename T2> constexpr explicit Vector(std::array<T2, N> const& v); template<typename T2, typename T3> constexpr Vector(std::array<T2, N-1> const& u, T3 const& v); template<size_t N2> Vector<T, N2> toSize() const; Vector<T, 2> vec2() const; Vector<T, 3> vec3() const; Vector<T, 4> vec4() const; Vector piecewiseMultiply(Vector const& v2) const; Vector piecewiseDivide(Vector const& v2) const; Vector piecewiseMin(Vector const& v2) const; Vector piecewiseMax(Vector const& v2) const; Vector piecewiseClamp(Vector const& min, Vector const& max) const; T min() const; T max() const; T sum() const; T product() const; template<typename Function> Vector combine(Vector const& v, Function f) const; // Outputs angles in the range [0, pi] T angleBetween(Vector const& v) const; // Angle between two normalized vectors. T angleBetweenNormalized(Vector const& v) const; T magnitudeSquared() const; T magnitude() const; void normalize(); Vector normalized() const; Vector projectOnto(Vector const& v) const; Vector projectOntoNormalized(Vector const& v) const; void negate(); // Reverses order of components of vector void reverse(); Vector abs() const; Vector floor() const; Vector ceil() const; Vector round() const; void fill(T const& v); void clamp(T const& min, T const& max); template<typename Function> void transform(Function&& function); Vector operator-() const; Vector operator+(Vector const& v) const; Vector operator-(Vector const& v) const; T operator*(Vector const& v) const; Vector operator*(T s) const; Vector operator/(T s) const; Vector& operator+=(Vector const& v); Vector& operator-=(Vector const& v); Vector& operator*=(T s); Vector& operator/=(T s); // Vector2 // Return vector rotated to given angle template<size_t P=N> constexpr static Enable2D<P, Vector> withAngle(T angle, T magnitude = 1); template<size_t P=N> constexpr static Enable2D<P, T> angleBetween2(Vector const& u, Vector const& v); template<size_t P=N> constexpr static Enable2D<P, T> angleFormedBy2(Vector const& a, Vector const& b, Vector const& c); template<size_t P=N> constexpr static Enable2D<P, T> angleFormedBy2(Vector const& a, Vector const& b, Vector const& c, std::function<Vector(Vector, Vector)> const& diff); template<size_t P=N> Enable2D<P, Vector> rotate(T angle) const; // Faster than rotate(M_PI/2). template<size_t P=N> Enable2D<P, Vector> rot90() const; // Angle of vector on 2d plane, in the range [-pi, pi] template<size_t P=N> Enable2D<P, T> angle() const; // Returns polar coordinates of this cartesian vector template<size_t P=N> Enable2D<P, Vector> toPolar() const; // Returns cartesian coordinates of this polar vector template<size_t P=N> Enable2D<P, Vector> toCartesian() const; template<size_t P=N> Enable2DOrHigher<P, T> const& x() const; template<size_t P=N> Enable2DOrHigher<P, T> const& y() const; template<size_t P=N> Enable2DOrHigher<P> setX(T const& t); template<size_t P=N> Enable2DOrHigher<P> setY(T const& t); // Vector3 template<size_t P=N> constexpr static Enable3D<P, Vector> fromAngles(T psi, T theta); template<size_t P=N> constexpr static Enable3D<P, Vector> fromAnglesEnu(T psi, T theta); template<size_t P=N> constexpr static Enable3D<P, T> tripleScalarProduct(Vector const& u, Vector const& v, Vector const& w); template<size_t P=N> constexpr static Enable3D<P, T> angle(Vector const& v1, Vector const& v2); template<size_t P=N> Enable3D<P, T> psi() const; template<size_t P=N> Enable3D<P, T> theta() const; template<size_t P=N> Enable3D<P, Vector<T, 2>> eulers() const; template<size_t P=N> Enable3D<P, T> psiEnu() const; template<size_t P=N> Enable3D<P, T> thetaEnu() const; template<size_t P=N> Enable3D<P, Vector> nedToEnu() const; template<size_t P=N> Enable3D<P, Vector> enuToNed() const; template<size_t P=N> Enable3DOrHigher<P, T> const& z() const; template<size_t P=N> Enable3DOrHigher<P> setZ(T const& t); // Vector4 template<size_t P=N> Enable4DOrHigher<P, T> const& w() const; template<size_t P=N> Enable4DOrHigher<P> setW(T const& t); private: using Base::size; using Base::empty; }; typedef Vector<int, 2> Vec2I; typedef Vector<unsigned, 2> Vec2U; typedef Vector<float, 2> Vec2F; typedef Vector<double, 2> Vec2D; typedef Vector<uint8_t, 2> Vec2B; typedef Vector<size_t, 2> Vec2S; typedef Vector<int, 3> Vec3I; typedef Vector<unsigned, 3> Vec3U; typedef Vector<float, 3> Vec3F; typedef Vector<double, 3> Vec3D; typedef Vector<uint8_t, 3> Vec3B; typedef Vector<size_t, 3> Vec3S; typedef Vector<int, 4> Vec4I; typedef Vector<unsigned, 4> Vec4U; typedef Vector<float, 4> Vec4F; typedef Vector<double, 4> Vec4D; typedef Vector<uint8_t, 4> Vec4B; typedef Vector<size_t, 4> Vec4S; template<typename T, size_t N> std::ostream& operator<<(std::ostream& os, Vector<T, N> const& v); template<typename T, size_t N> Vector<T, N> operator*(T s, Vector<T, N> v); template<typename T, size_t N> Vector<T, N> vnorm(Vector<T, N> v); template<typename T, size_t N> T vmag(Vector<T, N> const& v); template<typename T, size_t N> T vmagSquared(Vector<T, N> const& v); template<typename T, size_t N> Vector<T, N> vmin(Vector<T, N> const& a, Vector<T, N> const& b); template<typename T, size_t N> Vector<T, N> vmax(Vector<T, N> const& a, Vector<T, N> const& b); template<typename T, size_t N> Vector<T, N> vclamp(Vector<T, N> const& a, Vector<T, N> const& min, Vector<T, N> const& max); template<typename VectorType> VectorType vmult(VectorType const& a, VectorType const& b); template<typename VectorType> VectorType vdiv(VectorType const& a, VectorType const& b); // Returns the cross product template<typename T> Vector<T, 3> operator^(Vector<T, 3> v1, Vector<T, 3> v2); // Returns the cross product / determinant template<typename T> T operator^(Vector<T, 2> const& v1, Vector<T, 2> const& v2); template<typename T, size_t N> constexpr Vector<T, N> Vector<T, N>::filled(T const& t) { Vector v; for (size_t i = 0; i < N; ++i) v[i] = t; return v; } template<typename T, size_t N> template<typename T2> constexpr Vector<T, N> Vector<T, N>::floor(Vector<T2, N> const& v) { Vector vec; for (size_t i = 0; i < N; ++i) vec[i] = floor(v[i]); return vec; } template<typename T, size_t N> template<typename T2> constexpr Vector<T, N> Vector<T, N>::ceil(Vector<T2, N> const& v) { Vector vec; for (size_t i = 0; i < N; ++i) vec[i] = ceil(v[i]); return vec; } template<typename T, size_t N> template<typename T2> constexpr Vector<T, N> Vector<T, N>::round(Vector<T2, N> const& v) { Vector vec; for (size_t i = 0; i < N; ++i) vec[i] = round(v[i]); return vec; } template<typename T, size_t N> template<typename Iterator> constexpr Vector<T, N> Vector<T, N>::copyFrom(Iterator p) { Vector v; for (size_t i = 0; i < N; ++i) v[i] = *(p++); return v; } template<typename T, size_t N> constexpr Vector<T, N>::Vector() {} template<typename T, size_t N> constexpr Vector<T, N>::Vector(T const& e1) : Base(e1) {} template<typename T, size_t N> template<typename... TN> constexpr Vector<T, N>::Vector(T const& e1, TN const&... rest) : Base({{e1, rest...}}) {} template<typename T, size_t N> template<typename T2> constexpr Vector<T, N>::Vector(std::array<T2, N> const& v) : Base(v) {} template<typename T, size_t N> template<typename T2, typename T3> constexpr Vector<T, N>::Vector(std::array<T2, N-1> const& u, T3 const& v) { for (size_t i = 0; i < N-1; ++i) { Base::operator[](i) = u[i]; } Base::operator[](N-1) = v; } template<typename T, size_t N> template<size_t N2> Vector<T, N2> Vector<T, N>::toSize() const { Vector<T, N2> r; size_t ns = std::min(N2, N); for (size_t i = 0; i < ns; ++i) r[i] = (*this)[i]; return r; } template<typename T, size_t N> Vector<T, 2> Vector<T, N>::vec2() const { return toSize<2>(); } template<typename T, size_t N> Vector<T, 3> Vector<T, N>::vec3() const { return toSize<3>(); } template<typename T, size_t N> Vector<T, 4> Vector<T, N>::vec4() const { return toSize<4>(); } template<typename T, size_t N> Vector<T, N> Vector<T, N>::piecewiseMultiply(Vector const& v2) const { return combine(v2, std::multiplies<T>()); } template<typename T, size_t N> Vector<T, N> Vector<T, N>::piecewiseDivide(Vector const& v2) const { return combine(v2, std::divides<T>()); } template<typename T, size_t N> Vector<T, N> Vector<T, N>::piecewiseMin(Vector const& v2) const { Vector r; for (size_t i = 0; i < N; ++i) r[i] = std::min((*this)[i], v2[i]); return r; } template<typename T, size_t N> Vector<T, N> Vector<T, N>::piecewiseMax(Vector const& v2) const { Vector r; for (size_t i = 0; i < N; ++i) r[i] = std::max((*this)[i], v2[i]); return r; } template<typename T, size_t N> Vector<T, N> Vector<T, N>::piecewiseClamp(Vector const& min, Vector const& max) const { Vector r; for (size_t i = 0; i < N; ++i) r[i] = std::max(std::min((*this)[i], max[i]), min[i]); return r; } template<typename T, size_t N> T Vector<T, N>::min() const { T s = (*this)[0]; for (size_t i = 1; i < N; ++i) s = std::min(s, (*this)[i]); return s; } template<typename T, size_t N> T Vector<T, N>::max() const { T s = (*this)[0]; for (size_t i = 1; i < N; ++i) s = std::max(s, (*this)[i]); return s; } template<typename T, size_t N> T Vector<T, N>::sum() const { T s = (*this)[0]; for (size_t i = 1; i < N; ++i) s += (*this)[i]; return s; } template<typename T, size_t N> T Vector<T, N>::product() const { T p = (*this)[0]; for (size_t i = 1; i < N; ++i) p *= (*this)[i]; return p; } template<typename T, size_t N> template<typename Function> Vector<T, N> Vector<T, N>::combine(Vector const& v, Function f) const { Vector r; for (size_t i = 0; i < N; ++i) r[i] = f((*this)[i], v[i]); return r; } template<typename T, size_t N> T Vector<T, N>::angleBetween(Vector const& v) const { return acos(this->normalized() * v.normalized()); } template<typename T, size_t N> T Vector<T, N>::angleBetweenNormalized(Vector const& v) const { return acos(*this * v); } template<typename T, size_t N> T Vector<T, N>::magnitudeSquared() const { T m = 0; for (size_t i = 0; i < N; ++i) m += square((*this)[i]); return m; } template<typename T, size_t N> T Vector<T, N>::magnitude() const { return sqrt(magnitudeSquared()); } template<typename T, size_t N> void Vector<T, N>::normalize() { T m = magnitude(); if (m != 0) *this = (*this)/m; } template<typename T, size_t N> Vector<T, N> Vector<T, N>::normalized() const { T m = magnitude(); if (m != 0) return (*this)/m; else return *this; } template<typename T, size_t N> Vector<T, N> Vector<T, N>::projectOnto(Vector const& v) const { T m = v.magnitudeSquared(); if (m != 0) return projectOntoNormalized(v) / m; else return Vector(); } template<typename T, size_t N> Vector<T, N> Vector<T, N>::projectOntoNormalized(Vector const& v) const { return ((*this) * v) * v; } template<typename T, size_t N> Vector<T, N> Vector<T, N>::operator-() const { auto v = *this; v.negate(); return v; } template<typename T, size_t N> void Vector<T, N>::negate() { for (size_t i = 0; i < N; ++i) (*this)[i] = -(*this)[i]; } template<typename T, size_t N> Vector<T, N> Vector<T, N>::abs() const { Vector v; for (size_t i = 0; i < N; ++i) v[i] = fabs((*this)[i]); return v; } template<typename T, size_t N> Vector<T, N> Vector<T, N>::floor() const { return floor(*this); } template<typename T, size_t N> Vector<T, N> Vector<T, N>::ceil() const { return ceil(*this); } template<typename T, size_t N> Vector<T, N> Vector<T, N>::round() const { return round(*this); } template<typename T, size_t N> void Vector<T, N>::reverse() { std::reverse(Base::begin(), Base::end()); } template<typename T, size_t N> void Vector<T, N>::fill(T const& v) { Base::fill(v); } template<typename T, size_t N> void Vector<T, N>::clamp(T const& min, T const& max) { for (size_t i = 0; i < N; ++i) (*this)[i] = max(min, min(max, (*this)[i])); } template<typename T, size_t N> template<typename Function> void Vector<T, N>::transform(Function&& function) { for (auto& e : *this) e = function(e); } template<typename T, size_t N> Vector<T, N> Vector<T, N>::operator+(Vector const& v) const { Vector r; for (size_t i = 0; i < N; ++i) r[i] = (*this)[i] + v[i]; return r; } template<typename T, size_t N> Vector<T, N> Vector<T, N>::operator-(Vector const& v) const { Vector r; for (size_t i = 0; i < N; ++i) r[i] = (*this)[i] - v[i]; return r; } template<typename T, size_t N> T Vector<T, N>::operator*(Vector const& v) const { T sum = 0; for (size_t i = 0; i < N; ++i) sum += (*this)[i] * v[i]; return sum; } template<typename T, size_t N> Vector<T, N> Vector<T, N>::operator*(T s) const { Vector r; for (size_t i = 0; i < N; ++i) r[i] = (*this)[i] * s; return r; } template<typename T, size_t N> Vector<T, N> Vector<T, N>::operator/(T s) const { Vector r; for (size_t i = 0; i < N; ++i) r[i] = (*this)[i] / s; return r; } template<typename T, size_t N> Vector<T, N>& Vector<T, N>::operator+=(Vector const& v) { return (*this = *this + v); } template<typename T, size_t N> Vector<T, N>& Vector<T, N>::operator-=(Vector const& v) { return (*this = *this - v); } template<typename T, size_t N> Vector<T, N>& Vector<T, N>::operator*=(T s) { return (*this = *this * s); } template<typename T, size_t N> Vector<T, N>& Vector<T, N>::operator/=(T s) { return (*this = *this / s); } //Vector2 template<typename T, size_t N> template<size_t P> constexpr auto Vector<T, N>::withAngle(T angle, T magnitude) -> Enable2D<P, Vector<T, N>> { return Vector(std::cos(angle) * magnitude, std::sin(angle) * magnitude); } template<typename T, size_t N> template<size_t P> constexpr auto Vector<T, N>::angleBetween2(Vector const& v1, Vector const& v2) -> Enable2D<P, T> { // TODO: Inefficient return v2.angle() - v1.angle(); } template<typename T, size_t N> template<size_t P> constexpr auto Vector<T, N>::angleFormedBy2(Vector const& a, Vector const& b, Vector const& c) -> Enable2D<P, T> { return angleBetween2(b - a, b - c); } template<typename T, size_t N> template<size_t P> constexpr auto Vector<T, N>::angleFormedBy2(Vector const& a, Vector const& b, Vector const& c, std::function<Vector(Vector, Vector)> const& diff) -> Enable2D<P, T> { return angleBetween2(diff(b, a), diff(b, c)); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::angle() const -> Enable2D<P, T> { return atan2(Base::operator[](1), Base::operator[](0)); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::rotate(T a) const -> Enable2D<P, Vector<T, N>> { // TODO: Need a Matrix2 T cosa = std::cos(a); T sina = std::sin(a); return Vector( Base::operator[](0) * cosa - Base::operator[](1) * sina, Base::operator[](0) * sina + Base::operator[](1) * cosa); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::rot90() const -> Enable2D<P, Vector<T, N>> { return Vector(-y(), x()); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::toPolar() const -> Enable2D<P, Vector<T, N>> { return Vector(angle(), Base::magnitude()); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::toCartesian() const -> Enable2D<P, Vector<T, N>> { return vec2d(sin((*this)[0]) * (*this)[1], cos((*this)[0]) * (*this)[1]); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::x() const -> Enable2DOrHigher<P, T> const& { return Base::operator[](0); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::y() const -> Enable2DOrHigher<P, T> const& { return Base::operator[](1); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::setX(T const& t) -> Enable2DOrHigher<P> { Base::operator[](0) = t; } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::setY(T const& t) -> Enable2DOrHigher<P> { Base::operator[](1) = t; } // Vector3 template<typename T, size_t N> template<size_t P> constexpr auto Vector<T, N>::tripleScalarProduct(Vector const& a, Vector const& b, Vector const& c) -> Enable3D<P, T> { return a * (b ^ c); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::theta() const -> Enable3D<P, T> { Vector<T, N> vn = norm(*this); T tmp = fabs(vn.z()); if(almost_equal(tmp, 1)) { return tmp > 0.0 ? T(-M_PI/2) : T(M_PI/2); } else { return asin(-vn.z()); } } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::psi() const -> Enable3D<P, T> { Vector<T, N> vn = norm(*this); T tmp = T(fabs(vn.z())); if(almost_equal(tmp, 1)) { return 0.0; } else { return T(atan2(vn.y(), vn.x())); } } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::thetaEnu() const -> Enable3D<P, T> { Vector<T, N> vn = norm(*this); T tmp = fabs(vn.z()); if(almost_equal(tmp, 1)) { return tmp > 0.0 ? -M_PI/2 : M_PI/2; } else { return asin(vn.z()); } } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::psiEnu() const -> Enable3D<P, T> { Vector<T, N> vn = norm(*this); T tmp = fabs(vn.z()); if (almost_equal(tmp, 1)) { return 0.0; } else { return atan2(vn.x(), vn.y()); } } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::eulers() const -> Enable3D<P, Vector<T, 2>> { T psi, theta; Vector<T, N> vn = norm(*this); T tmp = fabs(vn.z()); if (almost_equal(tmp, 1)) { psi = 0.0; theta = tmp > 0.0 ? -M_PI/2 : M_PI/2; } else { psi = atan2(vn.y(), vn.x()); theta = asin(-vn.z()); } return Vector<T, 2>(psi, theta); } template<typename T, size_t N> template<size_t P> constexpr auto Vector<T, N>::fromAngles(T psi, T theta) -> Enable3D<P, Vector<T, N>> { Vec3F nv; T cosTheta = T(cos(theta)); nv.x() = T(cos(psi)); nv.y() = T(sin(psi)); nv.x() *= cosTheta; nv.y() *= cosTheta; nv.z() = T(-sin(theta)); return nv; } template<typename T, size_t N> template<size_t P> constexpr auto Vector<T, N>::fromAnglesEnu(T psi, T theta) -> Enable3D<P, Vector<T, N>> { Vector nv = fromAngles(psi, theta); return Vector(nv.y(), nv.x(), -nv.z()); } template<typename T, size_t N> template<size_t P> constexpr auto Vector<T, N>::angle(Vector const& v1, Vector const& v2) -> Enable3D<P, T> { return acos(std::min(norm(v1)*norm(v2), 1.0)); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::nedToEnu() const -> Enable3D<P, Vector<T, N>> { return Vector(y(), x(), -z()); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::enuToNed() const -> Enable3D<P, Vector<T, N>> { return Vector(y(), x(), -z()); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::z() const -> Enable3DOrHigher<P, T> const& { return Base::operator[](2); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::setZ(T const& t) -> Enable3DOrHigher<P> { Base::operator[](2) = t; } // Vector4 template<typename T, size_t N> template<size_t P> auto Vector<T, N>::w() const -> Enable4DOrHigher<P, T> const& { return Base::operator[](3); } template<typename T, size_t N> template<size_t P> auto Vector<T, N>::setW(T const& t) -> Enable4DOrHigher<P> { Base::operator[](3) = t; } // Free Functions template<typename T, size_t N> std::ostream& operator<<(std::ostream& os, Vector<T, N> const& v) { os << '('; for (size_t i = 0; i < N; ++i) { os << v[i]; if (i != N - 1) os << ", "; } os << ')'; return os; } template<typename T, size_t N> Vector<T, N> operator*(T s, Vector<T, N> v) { return v*s; } template<typename T, size_t N> Vector<T, N> vnorm(Vector<T, N> v) { return v.normalized(); } template<typename T, size_t N> T vmag(Vector<T, N> const& v) { return v.magnitude(); } template<typename T, size_t N> T vmagSquared(Vector<T, N> const& v) { return v.magnitudeSquared(); } template<typename T, size_t N> Vector<T, N> vmin(Vector<T, N> const& a, Vector<T, N> const& b) { return a.piecewiseMin(b); } template<typename T, size_t N> Vector<T, N> vmax(Vector<T, N> const& a, Vector<T, N> const& b) { return a.piecewiseMax(b); } template<typename T, size_t N> Vector<T, N> vclamp(Vector<T, N> const& a, Vector<T, N> const& min, Vector<T, N> const& max) { return a.piecewiseClamp(min, max); } template<typename VectorType> VectorType vmult(VectorType const& a, VectorType const& b) { return a.piecewiseMultiply(b); } template<typename VectorType> VectorType vdiv(VectorType const& a, VectorType const& b) { return a.piecewiseDivide(b); } template<typename T> Vector<T, 3> operator^(Vector<T, 3> v1, Vector<T, 3> v2) { return Vector<T, 3>( v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0] ); } template<typename T> T operator^(Vector<T, 2> const& v1, Vector<T, 2> const& v2) { return v1[0] * v2[1] - v1[1] * v2[0]; } } #endif
true
10e0368ca3dffd4519694307ca2ecdd759add879
C++
Tudor67/Competitive-Programming
/LeetCode/Problems/Algorithms/#112_PathSum_sol3_bfs_O(N)_time_O(W)_extra_space_17ms_21.7MB.cpp
UTF-8
1,213
3.390625
3
[ "MIT" ]
permissive
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool hasPathSum(TreeNode* root, int targetSum) { queue<pair<TreeNode*, int>> q; if(root != nullptr){ q.emplace(root, root->val); } bool found = false; while(!q.empty() && !found){ TreeNode* node = q.front().first; int sum = q.front().second; q.pop(); if(node->left == nullptr && node->right == nullptr){ found = found || (sum == targetSum); } if(node->left != nullptr){ q.emplace(node->left, sum + node->left->val); } if(node->right != nullptr){ q.emplace(node->right, sum + node->right->val); } } return found; } };
true
fbb16b665fc1d751197aa42dacf2471571a50e99
C++
hypoactiv/pdp
/multipart.h
UTF-8
3,803
2.75
3
[]
no_license
#ifndef MULTIPART_H #define MULTIPART_H #include "consts.h" #include "stdint.h" namespace PDP { typedef struct { uint8_t sequenceNum; uint16_t messageId; uint8_t protocolVersion; uint32_t messageLength; } MultipartHeader; // MultipartSplitter creates multipart messages from a buffer, to be // recombined using a MultipartCombiner on the receiving side. template <uint16_t PartSize> class MultipartSplitter { public: MultipartSplitter(void *src, uint16_t len, uint8_t seq, uint16_t mid); // Returns true if there are more parts to be emitted bool More(); // Gets the next size PartSize part of the multipart message into dst // // Returns true if there are more parts to be emitted bool Get(uint8_t *dst); private: uint8_t *src; uint16_t len; uint8_t seq; uint16_t mid, cursor; }; template <uint16_t PartSize> MultipartSplitter<PartSize>::MultipartSplitter(void *src, uint16_t len, uint8_t seq, uint16_t mid) : src((uint8_t *)src), len(len), seq(seq), mid(mid), cursor(0) {} template <uint16_t PartSize> bool MultipartSplitter<PartSize>::More() { return (this->cursor < this->len); } template <uint16_t PartSize> bool MultipartSplitter<PartSize>::Get(uint8_t *dst) { MultipartHeader *mpHeader = (MultipartHeader *)dst; mpHeader->sequenceNum = this->seq; mpHeader->messageId = this->mid; memcpy(dst + 3, this->src + this->cursor, (this->cursor + PartSize - 3 < this->len) ? PartSize - 3 : this->len - this->cursor); this->seq++; this->cursor += PartSize - 3; return this->More(); } // MultipartCombiner reassembles the parts emitted by a MultipartSplitter template <uint16_t PartSize> class MultipartCombiner { public: MultipartCombiner(void *dst, uint16_t len, uint8_t seq); // Returns true if there are more parts to be combined bool More(); // Puts the size PartSize part of the multipart message stored in src // // Returns true if there are more parts to be combined bool Put(uint8_t *src); // Returns true if there was a sequence number error uint16_t Remaining(); Error_t Error; private: uint8_t *dst; uint16_t len; uint8_t seq; uint16_t cursor, mid; bool knowMid; }; template <uint16_t PartSize> MultipartCombiner<PartSize>::MultipartCombiner(void *dst, uint16_t len, uint8_t seq) : Error(ERROR_NONE), dst((uint8_t *)dst), len(len), seq(seq), cursor(0), knowMid(false) {} template <uint16_t PartSize> bool MultipartCombiner<PartSize>::More() { if (this->Error) { // previous error, stop combining return false; } return (this->cursor < this->len); } template <uint16_t PartSize> bool MultipartCombiner<PartSize>::Put(uint8_t *src) { MultipartHeader *mpHeader = (MultipartHeader *)src; if (this->Error || !this->More()) { return false; } // compare src's sequence number to expected value if (mpHeader->sequenceNum == this->seq - 1) { // duplicate part, ignore return true; } if (mpHeader->sequenceNum != this->seq) { // invalid sequence number, error this->Error = ERROR_MULTIPART_BAD_SEQUENCE; return false; } if (!this->knowMid) { this->knowMid = true; this->mid = mpHeader->messageId; } else { if (mpHeader->messageId != this->mid) { // part of some other message, ignore return true; } } memcpy(this->dst + this->cursor, src + 3, (this->Remaining() > PartSize - 3) ? PartSize - 3 : this->Remaining()); this->seq++; this->cursor += PartSize - 3; return this->More(); } template <uint16_t PartSize> uint16_t MultipartCombiner<PartSize>::Remaining() { return this->len - this->cursor; } } // namespace PDP #endif // MULTIPART_H
true
eceb6f0d3b9384726439821ee4066c417ee810c5
C++
grigp/a-analyser
/metodics/dynamic_tests/triangle/triangletemplate.h
UTF-8
1,749
2.703125
3
[]
no_license
#ifndef TRIANGLETEMPLATE_H #define TRIANGLETEMPLATE_H #include <QObject> #include "metodictemplate.h" /*! * \brief Класс шаблона теста "Треугольник" TriangleTemplate class */ class TriangleTemplate : public MetodicTemplate { Q_OBJECT public: explicit TriangleTemplate(QObject *parent = nullptr); /*! * \brief Возвращает уникальный идентификатор методики */ QString uid() override; /*! * \brief Возвращает название методики */ QString name() override; /*! * \brief Создает и возвращает виджет выполнения теста по методике * \param params - параметры методики */ QWidget *execute(QWidget *parent, const QJsonObject &params) override; /*! * \brief Создает и возвращает виджет визуализации результатов тестирования по методике * \param testUid - параметры методики */ QWidget *visualize(QWidget *parent, const QString &testUid) override; /*! * \brief Печать результатов теста * \param printer - принтер * \param testUid - uid теста */ void print(QPrinter *printer, const QString &testUid) override; /*! * \brief Редактирование параметров методики * \param params - параметры методики * \return true, если нужно сохранить параметры */ bool editParams(QWidget *parent, QJsonObject &params) override; }; #endif // TRIANGLETEMPLATE_H
true
4f4ae36e6b589b8cc6d7dc04536c9306e5759dd6
C++
kryzthov/gooz
/store/values_test.cc
UTF-8
2,433
2.875
3
[]
no_license
#include "store/values.h" #include <gtest/gtest.h> #include "base/stl-util.h" #include "combinators/oznode_eval_visitor.h" using combinators::oz::ParseEval; namespace store { const uint64 kStoreSize = 1024 * 1024; // ----------------------------------------------------------------------------- // Value graph exploring class ExploreTest : public testing::Test { protected: ExploreTest() : store_(kStoreSize) { } StaticStore store_; }; TEST_F(ExploreTest, PrimitiveValue) { { Atom* atom = Atom::Get("atom"); ReferenceMap rmap; Value(atom).Explore(&rmap); EXPECT_EQ(1UL, rmap.size()); EXPECT_TRUE(ContainsKey(rmap, atom)); EXPECT_FALSE(GetExisting(rmap, atom)); Value(atom).Explore(&rmap); EXPECT_EQ(1, rmap.size()); EXPECT_TRUE(ContainsKey(rmap, atom)); EXPECT_TRUE(GetExisting(rmap, atom)); } { Value integer = Value::Integer(1); ReferenceMap rmap; integer.Explore(&rmap); EXPECT_EQ(1, rmap.size()); EXPECT_TRUE(ContainsKey(rmap, integer)); EXPECT_FALSE(GetExisting(rmap, integer)); integer.Explore(&rmap); EXPECT_EQ(1, rmap.size()); EXPECT_TRUE(ContainsKey(rmap, integer)); EXPECT_TRUE(GetExisting(rmap, integer)); } } // ----------------------------------------------------------------------------- // String representation class ToStringTest : public testing::Test { protected: ToStringTest() : store_(kStoreSize) { } StaticStore store_; }; TEST_F(ToStringTest, Primitives) { EXPECT_EQ("1", Value::Integer(1).ToString()); EXPECT_EQ("1000", Value::Integer(1000).ToString()); EXPECT_EQ("0", Value::Integer(0).ToString()); EXPECT_EQ("~500", Value::Integer(-500).ToString()); EXPECT_EQ("''", Atom::Get("")->ToString()); EXPECT_EQ("atom1", Atom::Get("atom1")->ToString()); EXPECT_EQ("'atom with \\'quote\\''", Atom::Get("atom with 'quote'")->ToString()); EXPECT_EQ("{NewName}", Name::New(&store_)->ToString()); EXPECT_EQ("{NewName}", ParseEval("{NewName}", &store_).ToString()); } TEST_F(ToStringTest, Lists) { EXPECT_EQ("1|2|3|4", ParseEval("1 | 2 | 3 |4", &store_).ToString()); EXPECT_EQ("[1 2 3]", ParseEval("[1 2 3]", &store_).ToString()); EXPECT_EQ("1|2|3|_", ParseEval("1 | 2|3|_", &store_).ToString()); EXPECT_EQ("[1 {NewName} 3]", ParseEval("[1 {NewName} 3]", &store_).ToString()); } } // namespace store
true
75243714c4d0a7b870fbcdec152a9da868414a6e
C++
PalliativeX/Chess
/Chess/src/Board.h
UTF-8
2,300
3.25
3
[]
no_license
#pragma once #include "ChessPiece.h" #include <vector> #include <algorithm> const int BOARD_LENGTH = 8; class Board { private: Point prevMove; // separate move methods for each chess piece, bool moveKnight(Point& from, Point& to); void displayPawnTransformWindow(const Point& to); void attemptToTransformPawn(const Point& newPos); bool movePawn(Point& from, Point& to); bool moveRook(Point& from, Point& to); bool moveKing(Point& from, Point& to); bool moveQueen(Point& from, Point& to); bool moveBishop(Point& from, Point& to); // we move our piece to a chosen square void swapAndDeleteSecond(ChessPiece*& to, ChessPiece*& from); // needed for checking whether a square is protected // or a king can go there bool canEnemyPiecesReachSquare(const Point& to, const Color currentColor) const; bool canMoveInLine(const Point& from, const Point& to) const; bool canMoveDiagonally(const Point& from, const Point& to) const; bool canMoveKing1Square(const Point& from, const Point& to) const; // if it's an enemy piece, we must check whether it is protected bool attemptKingCastle(const Point& from, const Point& to, const bool hasKingMoved); bool canMoveKnight(const Point& from, const Point& to) const; bool canPawnTake(const Point& from, const Point& to) const; // check if a pawn can take either left or right diagonal enemy piece bool canBlockDiagonalAttack(const Point& attackerPos, const Color currentColor) const; // by bishop or queen bool canBlockLinearAttack(const Point& attackerPos, const Color currentColor) const; // by rook or queen public: ChessPiece* board[BOARD_LENGTH][BOARD_LENGTH]; Board(); bool move(Point& from, Point& to, Turn turn); void display() const; bool isWhiteKingAttacked = false; bool isBlackKingAttacked = false; // a king can't be checkmated if it's not even attacked bool isWhiteKingCheckmated = false; bool isBlackKingCheckmated = false; bool isKingCheckmated(Color kingColor); const Point getWhiteKingPosition() const; const Point getBlackKingPosition() const; // we return a previous move, necessary for checking // where a piece attacking our king stays const Point& getPrevMove() const { return prevMove; } void setPrevMove(Point move) { prevMove = move; } int mainWindowXpos, mainWindowYpos; };
true
249c27ab0c6a7b1d5eb464417b81c53b95dd6f96
C++
Mark-Mamdouh/Complier
/Phase 2/include/ParsingTable.h
UTF-8
1,066
2.71875
3
[]
no_license
#ifndef PARSINGTABLE_H #define PARSINGTABLE_H #include "phase2.h" using namespace std; class ParsingTable { public: ParsingTable(vector<struct PR_ELEM> all_elem,map<int, vector<vector<int>>> prod_rules ); virtual ~ParsingTable(); vector<struct PR_ELEM> elements; /*list for the structs of terminals and non terminals*/ map<pair< int, string>, vector<int> > parsing_table; /* parsing table */ /* function for constructing the parsing table */ void construct_parsing_table(); protected: private: map<int, vector<vector<int>>> prod_rules; /* production rules*/ /* functions for computing the first */ void construct_first(); void get_first(int); /* functions for computing the follow */ void fill_owners(); void construct_follow(); void get_follow(int NT_index); void insert_to_map(int NT_index,int ter_index); /* functions for printing the steps of constructing the parsing table */ void print_first_or_follow(string); void print_table(); }; #endif // PARSINGTABLE_H
true
817a0118397ebc1f8eb2dc7a5c1a5e370c0c3ef6
C++
asdlei99/TweedeFrameworkRedux
/Source/Framework/Core/Physics/TeConeTwistJoint.h
UTF-8
973
2.734375
3
[ "Zlib", "MIT", "RSA-MD" ]
permissive
#pragma once #include "TeCorePrerequisites.h" #include "Physics/TeJoint.h" namespace te { struct CONE_TWIST_JOINT_DESC; /** * To create ragdolls, the conve twist constraint is very useful for limbs like the upper arm. It is a special * point to point constraint that adds cone and twist axis limits. The x-axis serves as twist axis. */ class TE_CORE_EXPORT ConeTwistJoint : public Joint { public: ConeTwistJoint(const CONE_TWIST_JOINT_DESC& desc) { } virtual ~ConeTwistJoint() = default; /** * Creates a new cone twist joint. * * @param[in] scene Scene to which to add the joint. * @param[in] desc Settings describing the joint. */ static SPtr<ConeTwistJoint> Create(PhysicsScene& scene, const CONE_TWIST_JOINT_DESC& desc); }; /** Structure used for initializing a new ConeTwistJoint. */ struct CONE_TWIST_JOINT_DESC : JOINT_DESC { }; }
true
555f62f10db98c75311995fbe996f5ebceec0975
C++
Tiger1994/LeetCode
/Q19.cpp
UTF-8
1,731
3.4375
3
[]
no_license
#include<iostream> #include<vector> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* removeNthFromEnd_1(ListNode* head, int n) { int idx = 0; vector<ListNode*> nodes; ListNode* temp = head; while (temp){ nodes.push_back(temp); temp = temp->next; } int list_len = nodes.size(); if (list_len == 1) return NULL; else if (list_len == 2){ if (n == 1){ delete head->next; head->next = NULL; return head; } else{ ListNode* temp = head; head = head->next; delete temp; return head; } } if (list_len == n){ ListNode* temp = head; head = head->next; delete temp; return head; } ListNode* q = nodes[list_len-n-1]; ListNode* p = q->next; q->next = p->next; delete p; return head; } ListNode* removeNthFromEnd(ListNode* head, int n){ ListNode *feakhead; feakhead = new ListNode(-1); feakhead->next = head; head = feakhead; ListNode *p1, *p2; p1 = p2 = head; for (int i = 0; i < n; i++){ p1 = p1->next; } while (p1->next){ p1 = p1->next; p2 = p2->next; } ListNode* temp; temp = p2->next; p2->next = p2->next->next; delete temp; return head->next; } }; int main(void){ ListNode *head, *curr; int n = 1; head = new ListNode(1); //curr = head; //for (int i = 1; i < 3; i++){ // ListNode* temp; // temp = new ListNode(i+1); // curr->next = temp; // curr = curr->next; //} Solution model; ListNode* result = model.removeNthFromEnd(head, n); return 0; }
true
47436ee82e34a5367909cc9c7048580243fd428e
C++
aaron-ng/CS4500_Project
/src/ea2/kvstore/kvstore.cpp
UTF-8
4,257
2.8125
3
[]
no_license
// Language C++ #include "kvstore.h" #include "../../dataframe/dataframe.h" #include "../dataframe_description.h" KVStore::KVStore(in_addr_t ip, uint16_t port, in_addr_t serverIP, uint16_t serverPort): _byteStore(ip, port, serverIP, serverPort) {} /** * Retrieves the dataframe with the given key from the key value store. If the * value does not exist, nullptr is returned * @param key The key of the dataframe to return */ DataFrame* KVStore::get(Key& key) { return _dataframeFrom(_byteStore.get(key)); } /** * Retrieves the dataframe with the given key from the key value store. If the * value does not exist, this call will wait until it is available * @param key The key of the dataframe to return */ DataFrame* KVStore::waitAndGet(Key& key) { return _dataframeFrom(_byteStore.waitAndGet(key)); } /** * Puts the dataframe in the store. If the key references a node that is not * this machine, it is sent across the network. * @param dataframe The data to store * @param key The key of the dataframe in the store */ void KVStore::put(DataFrame* dataframe, Key& key) { size_t stores = _byteStore.nodes(); DataframeDescription* description = _descFrom(dataframe, key, stores); for (uint64_t i = 0; i < dataframe->getColumn(0)->numChunks(); i++) { putDataframeChunk(key, dataframe, i, stores); } putDataframeDesc(key, description); delete description; } /** * Provides the node identifier of the running application. This is determined * by the rendezvous server */ size_t KVStore::this_node() const { return _byteStore.this_node(); } /** Generates a description of a dataframe that can be serialized */ DataframeDescription* KVStore::_descFrom(DataFrame* dataframe, Key& key, size_t stores) { // Generate column descriptions size_t columns = dataframe->ncols(); ColumnDescription** descriptions = new ColumnDescription*[columns]; for (size_t i = 0; i < columns; i++) { Column* column = dataframe->getColumn(i); size_t numChunks = column->numChunks(); Key** chunkKeys = new Key*[numChunks]; for (size_t chunk = 0; chunk < numChunks; chunk++) { chunkKeys[chunk] = _keyFor(key, i, chunk, stores); } descriptions[i] = new ColumnDescription(chunkKeys, numChunks, column->size(), (ColumnType)dataframe->get_schema().col_type(i)); } return new DataframeDescription(new String(dataframe->get_schema().types()), columns, descriptions); } Key* KVStore::_keyFor(const Key& key, size_t column, size_t chunk, size_t nodes) { sprintf(_keyBuffer, "%s-%zu-%zu", key.getName(), column, chunk); return new Key(_keyBuffer, chunk % nodes); } DataFrame *KVStore::_dataframeFrom(ByteArray* bytes) { if (!bytes) { return nullptr; } Deserializer deserializer(bytes->length, bytes->contents); DataframeDescription desc; desc.deserialize(deserializer); Schema schema(""); DataFrame* dataframe = new DataFrame(schema); for (size_t i = 0; i < desc.numColumns; i++) { ColumnDescription* colDesc = desc.columns[i]; Key** keyCopies = new Key*[colDesc->chunks]; for (size_t chunk = 0; chunk < colDesc->chunks; chunk++) { keyCopies[chunk] = (Key*)colDesc->keys[chunk]->clone(); } Column* newColumn = allocateChunkedColumnOfType(colDesc->type, keyCopies, colDesc->chunks, _byteStore, colDesc->totalLength); dataframe->add_column(newColumn, nullptr); } delete bytes; return dataframe; } void KVStore::putDataframeChunk(const Key& key, DataFrame* dataframe, size_t chunk, size_t nodes, long int serializedChunk) { for (size_t col = 0; col < dataframe->ncols(); col++) { Column* column = dataframe->getColumn(col); Key* chunkKey = _keyFor(key, col, chunk, nodes); Serializer serializer; column->serializeChunk(serializer, serializedChunk == -1 ? chunk : serializedChunk); _byteStore.put(serializer.getBuffer(), serializer.getSize(), *chunkKey); delete chunkKey; } } void KVStore::putDataframeDesc(Key &key, DataframeDescription *desc) { Serializer serializer; desc->serialize(serializer); _byteStore.put(serializer.getBuffer(), serializer.getSize(), key); }
true
53aab81a32fc4380e896e8694c5a200f5ec01944
C++
browe/hspace-old
/HSFileDatabase.cpp
UTF-8
7,115
2.578125
3
[]
no_license
// ----------------------------------------------------------------------- // $Id: HSFileDatabase.cpp,v 1.4 2006/04/04 12:37:11 mark Exp $ // ----------------------------------------------------------------------- #include "pch.h" #include <cstdio> #include "HSFileDatabase.h" CHSFileDatabase::CHSFileDatabase(): m_pFilePtr(NULL), m_eCurrentMode(OPENMODE_READ) { } CHSFileDatabase::~CHSFileDatabase() { if (m_pFilePtr) { fclose(m_pFilePtr); m_pFilePtr = NULL; } } CHSFileDatabase::EHSReturnVal CHSFileDatabase::OpenFile(const HS_INT8 * pcFilePath, EHSFileOpenMode eMode) { if (eMode == OPENMODE_READ) { fopen_s(&m_pFilePtr, pcFilePath, "r"); if (NULL == m_pFilePtr) { return DB_FILE_NOT_FOUND; } } else { fopen_s(&m_pFilePtr, pcFilePath, "w"); if (NULL == m_pFilePtr) { // Couldn't create it. return DB_CREATE_FILE_FAILED; } } m_eCurrentMode = eMode; return DB_OK; } void CHSFileDatabase::CloseFile() { if (m_pFilePtr) { fclose(m_pFilePtr); m_pFilePtr = NULL; } } CHSFileDatabase::EHSReturnVal CHSFileDatabase::StartSection() { if (!m_pFilePtr) { return DB_FILE_NOT_OPEN; } // We should be open in write mode. if (m_eCurrentMode != OPENMODE_WRITE) { return DB_INVALID_OPERATION; } // Write a section token. fwrite(&FILE_DATABASE_SECTION_TOKEN, 1, 1, m_pFilePtr); fwrite("\n", 1, 1, m_pFilePtr); return DB_OK; } CHSFileDatabase::EHSReturnVal CHSFileDatabase::EndSection() { if (!m_pFilePtr) { return DB_FILE_NOT_OPEN; } // We should be open in write mode. if (m_eCurrentMode != OPENMODE_WRITE) { return DB_INVALID_OPERATION; } // Do we have any attributes to write? while (!m_listSectionAttributes.empty()) { THSDBEntry & rtEntry = m_listSectionAttributes.front(); // Write the attribute name. fwrite(rtEntry.strAttributeName.c_str(), 1, rtEntry.strAttributeName.length(), m_pFilePtr); // Is there an attribute value to write? if (rtEntry.strValue.length() > 0) { fwrite("=", 1, 1, m_pFilePtr); fwrite(rtEntry.strValue.c_str(), 1, rtEntry.strValue.length(), m_pFilePtr); } // Next line please. fwrite("\n", 1, 1, m_pFilePtr); m_listSectionAttributes.pop_front(); } return DB_OK; } CHSFileDatabase::EHSReturnVal CHSFileDatabase::LoadNextSection() { if (!m_pFilePtr) { return DB_FILE_NOT_OPEN; } // We should be open in write mode. if (m_eCurrentMode != OPENMODE_READ) { return DB_INVALID_OPERATION; } m_listSectionAttributes.clear(); // Load lines from the database until we hit the section token. HS_INT8 cDBCharacter; HS_UINT32 uiLineOffset = 0; while (fread(&cDBCharacter, 1, 1, m_pFilePtr) == 1) { if (cDBCharacter == EOF) { return DB_END_OF_FILE; } if (cDBCharacter == '\r' || cDBCharacter == '\n') { // We hit a new line character. uiLineOffset = 0; continue; } else if (cDBCharacter == FILE_DATABASE_SECTION_TOKEN) { // Are we at the beginning of a newline? if (uiLineOffset == 0) { // This is the next section. Skip to the next line. while (fread(&cDBCharacter, 1, 1, m_pFilePtr) == 1) { if (cDBCharacter == EOF) { // This is technically a corrupt database. return DB_END_OF_FILE; } if (cDBCharacter == '\r' || cDBCharacter == '\n') { // Peek the next character to see if it's a printable. while (fread(&cDBCharacter, 1, 1, m_pFilePtr) == 1) { if (cDBCharacter != '\r' && cDBCharacter != '\n') { // Rewind one character. fseek(m_pFilePtr, -1, SEEK_CUR); break; } } break; } } if (feof(m_pFilePtr)) { // This is technically a corrupt database. return DB_END_OF_FILE; } break; } } uiLineOffset++; } if (feof(m_pFilePtr)) { return DB_END_OF_FILE; } // We are now at the first attribute in the section. // Read all attributes until the next section token. HS_BOOL8 bLoadAttrName = true; // Load attribute name first. THSDBEntry tCurrentEntry; uiLineOffset = 0; while (fread(&cDBCharacter, 1, 1, m_pFilePtr) == 1) { if (cDBCharacter == EOF) { break; } if ((cDBCharacter == FILE_DATABASE_SECTION_TOKEN) && (uiLineOffset == 0)) { // This is the next section. // Rewind one character. fseek(m_pFilePtr, -1, SEEK_CUR); break; } if (cDBCharacter == '\n' || cDBCharacter == '\r') { // Add the current database entry to the list. m_listSectionAttributes.push_back(tCurrentEntry); // Clear the entry. tCurrentEntry.strAttributeName = ""; tCurrentEntry.strValue = ""; uiLineOffset = 0; bLoadAttrName = true; continue; } if (cDBCharacter == '=') { // Are we loading the attribute name? if (bLoadAttrName) { bLoadAttrName = false; continue; } else { // Corruption. return DB_SECTION_READ_ERROR; } } // Are we loading the attribute name or value? if (bLoadAttrName) { tCurrentEntry.strAttributeName.append(&cDBCharacter, 1); } else { tCurrentEntry.strValue.append(&cDBCharacter, 1); } uiLineOffset++; } return DB_OK; } HS_BOOL8 CHSFileDatabase::GetFirstAttribute(THSDBEntry & rtEntry) { m_iterCurAttribute = m_listSectionAttributes.begin(); return GetNextAttribute(rtEntry); } HS_BOOL8 CHSFileDatabase::GetNextAttribute(THSDBEntry & rtEntry) { if (m_iterCurAttribute == m_listSectionAttributes.end()) { return false; } THSDBEntry & rtListEntry = *m_iterCurAttribute; rtEntry.strAttributeName = rtListEntry.strAttributeName; rtEntry.strValue = rtListEntry.strValue; m_iterCurAttribute++; return true; }
true
d145613e81d5f5e6b21f96a47a3148e003d6ae72
C++
sischkg/nxnsattack
/tests/test-readbuffer.cpp
UTF-8
3,861
2.671875
3
[ "MIT" ]
permissive
#include "readbuffer.hpp" #include "gtest/gtest.h" #include <cstring> #include <iostream> #include <boost/log/trivial.hpp> class ReadBufferTest : public ::testing::Test { public: virtual void SetUp() { } virtual void TearDown() { } }; TEST_F( ReadBufferTest, readUInt8 ) { uint8_t buf[] = { 0x00, 0x01, 0x02, 0x03, }; ReadBuffer msg( buf, sizeof( buf ) ); EXPECT_EQ( 0x00, msg.readUInt8() ); EXPECT_EQ( 0x01, msg.readUInt8() ); EXPECT_EQ( 0x02, msg.readUInt8() ); EXPECT_EQ( 0x03, msg.readUInt8() ); } TEST_F( ReadBufferTest, readUInt16 ) { uint8_t buf[] = { 0x00, 0x01, 0x02, 0x03, }; ReadBuffer msg( buf, sizeof( buf ) ); EXPECT_EQ( 0x0100, msg.readUInt16() ); EXPECT_EQ( 0x0302, msg.readUInt16() ); } TEST_F( ReadBufferTest, readUInt32 ) { uint8_t buf[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; ReadBuffer msg( buf, sizeof( buf ) ); EXPECT_EQ( 0x03020100, msg.readUInt32() ); EXPECT_EQ( 0x07060504, msg.readUInt32() ); } TEST_F( ReadBufferTest, readUInt64 ) { uint8_t buf[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; ReadBuffer msg( buf, sizeof( buf ) ); EXPECT_EQ( 0x0706050403020100, msg.readUInt64() ); } TEST_F( ReadBufferTest, readUInt16NtoH ) { uint8_t buf[] = { 0x00, 0x01, 0x02, 0x03, }; ReadBuffer msg( buf, sizeof( buf ) ); EXPECT_EQ( 0x0001, msg.readUInt16NtoH() ); EXPECT_EQ( 0x0203, msg.readUInt16NtoH() ); } TEST_F( ReadBufferTest, readUInt32NtoH ) { uint8_t buf[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; ReadBuffer msg( buf, sizeof( buf ) ); EXPECT_EQ( 0x00010203, msg.readUInt32NtoH() ); EXPECT_EQ( 0x04050607, msg.readUInt32NtoH() ); } TEST_F( ReadBufferTest, readUInt64NtoH ) { uint8_t buf[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; ReadBuffer msg( buf, sizeof( buf ) ); EXPECT_EQ( 0x0001020304050607, msg.readUInt64NtoH() ); } TEST_F( ReadBufferTest, readBuffer ) { uint8_t buf[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; ReadBuffer msg( buf, sizeof( buf ) ); std::vector<uint8_t> dst; msg.readBuffer( dst, 3 ); EXPECT_EQ( 3, dst.size() ); EXPECT_EQ( 0x00, dst[0] ); EXPECT_EQ( 0x01, dst[1] ); EXPECT_EQ( 0x02, dst[2] ); msg.readBuffer( dst, 4 ); EXPECT_EQ( 4, dst.size() ); EXPECT_EQ( 0x03, dst[0] ); EXPECT_EQ( 0x04, dst[1] ); EXPECT_EQ( 0x05, dst[2] ); EXPECT_EQ( 0x06, dst[3] ); } TEST_F( ReadBufferTest, readBuffer_from_short_buffer ) { uint8_t buf[] = { 0x00, 0x01, 0x02, }; ReadBuffer msg( buf, sizeof( buf ) ); std::vector<uint8_t> dst; msg.readBuffer( dst, 5 ); EXPECT_EQ( 3, dst.size() ); EXPECT_EQ( 0x00, dst[0] ); EXPECT_EQ( 0x01, dst[1] ); EXPECT_EQ( 0x02, dst[2] ); EXPECT_THROW( { msg.readBuffer( dst, 5 ); }, std::runtime_error ); } TEST_F( ReadBufferTest, checkOutOfBonund_uint8 ) { uint8_t buf[] = { 0x00, 0x01 }; ReadBuffer msg( buf, sizeof( buf ) ); EXPECT_NO_THROW( { msg.readUInt8(); } ); EXPECT_NO_THROW( { msg.readUInt8(); } ); EXPECT_THROW( { msg.readUInt8(); }, std::runtime_error ); } TEST_F( ReadBufferTest, checkOutOfBonund_uint16 ) { uint8_t buf[] = { 0x00, 0x01, 0x02 }; ReadBuffer msg( buf, sizeof( buf ) ); EXPECT_NO_THROW( { msg.readUInt16(); } ); EXPECT_THROW( { msg.readUInt16(); }, std::runtime_error ); } TEST_F( ReadBufferTest, getRemainedSize ) { uint8_t buf[] = { 0x00, 0x01, 0x02 }; ReadBuffer msg( buf, sizeof( buf ) ); EXPECT_EQ( 3, msg.getRemainedSize() ); msg.readUInt16(); EXPECT_EQ( 1, msg.getRemainedSize() ); msg.readUInt8(); EXPECT_EQ( 0, msg.getRemainedSize() ); } int main( int argc, char **argv ) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); }
true
c1ccb2d3f87110312b377306fb1f54e26c1de564
C++
fferegrino/ukranio
/clase1/ejercicio3.cpp
UTF-8
253
2.984375
3
[]
no_license
#include <iostream> using namespace std; int main () { double c ; c= 20; double f; cout <<"Programa para convertir grados centigrados a Farenheit \n"; f = (9/5 *c )+ 32; cout <<"El resultado es : " << f << "\n" ; }
true
e4be3ec05767fd44c7d67ecf0feb3c2d040b7cd5
C++
fuzzwaz/Fuzzy2D-Game-Engine
/Fuzzy2D/Polygon.cpp
UTF-8
3,924
3.421875
3
[ "Apache-2.0" ]
permissive
#include "Common.h" #include "Polygon.h" #include "Vector2.h" Polygon::Polygon() { _vertices.reset(new std::vector<Vector2>()); _perpendiculars.reset(new std::vector<Vector2>()); } void Polygon::operator=(const Polygon& source) { if (this == &source) return; _vertices->clear(); _perpendiculars->clear(); _vertices->insert(_vertices->end(), source._vertices->cbegin(), source._vertices->cend()); _perpendiculars->insert(_perpendiculars->end(), source._perpendiculars->cbegin(), source._perpendiculars->cend()); } void Polygon::AddVertexPoint(float x, float y) { AddVertexPoint(Vector2(x, y)); } void Polygon::AddVertexPoint(const Vector2& vertex) { _vertices->push_back(vertex); _numOfVertices++; _dirtyPerpendiculars = true; //New vertex means a new edge has been added. Perpendiculars need to be recalculated RecalculateCenterPoint(); } void Polygon::AddVertexPoint(const std::vector<Vector2>& vertices) { for (auto it = vertices.begin(); it != vertices.end(); it++) { AddVertexPoint(*it); } } /* Description: A getter which can trigger a Perpendicular recalculation if marked as dirty Returns: shared_ptr<vector<Vector2>> - Pointer to the cached perpendiculars for this Collider */ const std::shared_ptr<const std::vector<Vector2>> Polygon::GetPerpendiculars() const { if (_dirtyPerpendiculars) { RecalculatePerpendicularVectors(); } return _perpendiculars; } /* Description: Rotates each vertex point by "degrees" degrees clockwise. Sets the dirty flag for perpendiculars. Arguments: degrees - Clockwise rotatation */ void Polygon::Rotate(float degrees) { const float radians = CommonHelpers::DegToRad(degrees); for (int i = 0; i < _vertices->size(); i++) { float newX = (_vertices->at(i).x * cos(radians)) + (_vertices->at(i).y * sin(radians) * -1); float newY = (_vertices->at(i).x * sin(radians)) + (_vertices->at(i).y * cos(radians)); _vertices->at(i).x = newX; _vertices->at(i).y = newY; } if (degrees != 0) _dirtyPerpendiculars = true; } /* Description: Resets the current Perpendicular list. Goes through each edge in the polygon and calculates a clockwise perpendicular vector. Adds that vector to _perpendiculars. Clears the dirty flag */ void Polygon::RecalculatePerpendicularVectors() const { _perpendiculars->clear(); if (_vertices->size() >= 2) { for (int i = 0; i < _vertices->size() - 1; i++) { _perpendiculars->push_back(ClockwisePerpendicularVector(_vertices->at(i), _vertices->at(i + 1))); } //Wrap the last vertex to the first for the final polygon perpendicular _perpendiculars->push_back(ClockwisePerpendicularVector(_vertices->at(_vertices->size() - 1), _vertices->at(0))); } _dirtyPerpendiculars = false; } void Polygon::RecalculateCenterPoint() { float minX = INT_MAX, minY = INT_MAX; float maxX = INT_MIN, maxY = INT_MIN; for (int i = 0; i < _vertices->size(); i++) { Vector2 vertex(_vertices->at(i)); if (vertex.x < minX) minX = vertex.x; if (vertex.x > maxX) maxX = vertex.x; if (vertex.y < minY) minY = vertex.y; if (vertex.y > maxY) maxY = vertex.y; } Vector2 sizeVector(maxX - minX, maxY - minY); _center.x = (sizeVector.x / 2) + minX; _center.y = (sizeVector.y / 2) + minY; } Vector2 ClockwisePerpendicularVector(const Vector2& pointA, const Vector2& pointB) { const Vector2 clockwiseVector(pointB.x - pointA.x, pointB.y - pointA.y); return ClockwisePerpendicularVector(clockwiseVector); } Vector2 ClockwisePerpendicularVector(const Vector2& vector) { return Vector2(vector.y, -1 * vector.x); } Vector2 CounterClockwisePerpendicularVector(const Vector2& pointA, const Vector2& pointB) { const Vector2 counterClockwiseVector(pointB.x - pointA.x, pointB.y - pointA.y); return CounterClockwisePerpendicularVector(counterClockwiseVector); } Vector2 CounterClockwisePerpendicularVector(const Vector2& vector) { return Vector2(-1 * vector.y, vector.x); }
true
ebfb034fa06f7f69d004c18d97dc933b26317732
C++
clearoff/DataStruct
/BinaryTest.cpp
GB18030
4,807
3.453125
3
[]
no_license
#include "BinaryTree.hpp" #include "BinarySearchTree.hpp" #include <cassert> //Test1:һŶԶڵ֮ľ //typedef BinaryTreeNode<int> Node; //size_t DepthOfNode(BinaryTreeNode<int>* node) //{ // if (node == NULL) // { // return 0; // } // // //ֱ // size_t Left = DepthOfNode(node->_Left) + 1; // size_t Right = DepthOfNode(node->_Right) + 1; // // /*cout << "Left:"<<Left << endl; // cout << "Right:" << Right << endl;*/ // return Left > Right ? Left : Right; //} // //void _DisTanceOfNode(Node* root, size_t& LeftHigh, size_t RightHigh, size_t& Max); //size_t DisTanceOfNode(BinaryTree<int>& tree) //{ // size_t LeftHight = 0; // size_t RightHight = 0; // size_t Max = 0; // // _DisTanceOfNode(tree.ReturnRoot(), LeftHight, RightHight,Max); // // return Max; //} //ʱ临ӶΪO(N*N)㷨 //void _DisTanceOfNode(Node* root, size_t& LeftHigh, size_t RightHigh,size_t& Max) //{ // if (root == NULL) // return; // // if (root->_Left == NULL) // LeftHigh = 0; // // if (root->_Right == NULL) // RightHigh = 0; // // if (root->_Left != NULL) // _DisTanceOfNode(root->_Left, LeftHigh, RightHigh, Max); // // if (root->_Right != NULL) // _DisTanceOfNode(root->_Right, LeftHigh, RightHigh, Max); // // LeftHigh = DepthOfNode(root->_Left); // RightHigh = DepthOfNode(root->_Right); // // //µǰڵԶڵ֮ľ // if (LeftHigh + RightHigh + 1 > Max) // Max = LeftHigh + RightHigh + 1; // //} // //void _DisTanceOfNode(Node* root, size_t& LeftHigh, size_t RightHigh, size_t& Max) //{ // if (root == NULL) // { // return; // } // _DisTanceOfNode(root->_Left, LeftHigh, RightHigh, Max); //ݹԶڵ֮ľ // // _DisTanceOfNode(root->_Right, LeftHigh,RightHigh, Max); // // // LeftHigh = DepthOfNode(root->_Left); // RightHigh = DepthOfNode(root->_Right); // // if (LeftHigh + RightHigh + 1 > Max) // Max = LeftHigh + RightHigh + 1; //} //void Test1() //{ // int b[] = { 1, 2, 3, 5, '#', '#', '#', 4, '#', 6, '#', '#', '#' }; // int a[15] = { 1, 2, '#', 3, '#', '#', 4, 5, '#', 6, '#', 7, '#', '#', 8 }; // BinaryTree<int> t1(b, sizeof(b) / sizeof(b[0]), '#'); // t1.InOrder(); // t1.LevelOrder(); // cout << "Զڵ֮ľǣ" << DisTanceOfNode(t1) << endl; //} ////Test2 ڵ //typedef BinaryTreeNode<int> Node; //Node* _GetAncestor(Node* root, Node* node1, Node* node2) //{ // if (root == NULL) // return NULL; // // Node* Left = _GetAncestor(root->_Left, node1, node2); // Node* Right = _GetAncestor(root->_Right, node1, node2); // // if (Left&&Right) //LeftRightΪNULL rootڵΪǵ // return root; // // if (root == node2) // return node2; // if (root == node1) // return node1; // // if ((Right == NULL) && Left) // return Left; // if ((Left == NULL) && Right) // return Right; // // return NULL; //} //Node* GetAncestor(BinaryTree<int>& tree, Node* node1, Node* node2) //{ // //assert(node1); // //assert(node2); // Node* ancestor = _GetAncestor(tree.ReturnRoot(), node1, node2); // return ancestor; //} //void Test2() //{ // int b[] = { 1, 2, 3, 5, '#', '#', '#', 4, '#', 6, '#', '#', '#' }; // int a[15] = { 1, 2, '#', 3, '#', '#', 4, 5, '#', 6, '#', 7, '#', '#', 8 }; // BinaryTree<int> t1(b, sizeof(b) / sizeof(b[0]), '#'); // t1.InOrder(); // t1.LevelOrder(); // cout << "ǣ" << GetAncestor(t1,t1.Find(5),t1.Find(7))->_Data<< endl; //} //һŶתΪ //typedef BinarySearchTreeNode<int> Node; // //void _TreeToList(Node* cur, Node*& prev) //{ // if (cur == NULL) // return; // // _TreeToList(cur->_left, prev); // // cur->_left = prev; // if (prev != NULL) // prev->_right = cur; // // prev = cur; // _TreeToList(cur->_right, prev); //} // //Node* TreeToList(BinarySearchTree<int>& tree) //{ // Node* Head = tree.ReturnRoot(); // while (Head->_left) // { // Head = Head->_left; //ڵǵĵһڵ // } // Node* Prev = NULL; // Node* cur = tree.ReturnRoot(); // _TreeToList(cur, Prev); // return Head; //} // //void OrDerList(Node* root) //{ // assert(root); // while (root) // { // cout << root->_key << " "; // root = root->_right; // } // cout << endl; //} // //void Test5() //{ // BinarySearchTree<int> t; // t.Insert(5); // t.Insert(4); // t.Insert(7); // t.Insert(3); // t.Insert(6); // t.Insert(9); // t.Insert(2); // t.Insert(0); // t.Insert(1); // t.Insert(8); // t.InorderR(); // Node* head=TreeToList(t); // OrDerList(head); //} enum A { a1, a2, a3 = 10, a4, }a; void Test() { cout << a << endl; } int main() { Test(); return 0; }
true
39c1d4d80b758667af643b0712c8e0c2d508b166
C++
simple-user/cpp
/tempik011 vector/tempik011 vector/Source.cpp
UTF-8
588
3.046875
3
[]
no_license
#include <iostream> #include <Windows.h> #include <conio.h> #include <vector> using namespace std; class A { int a; public: A(int _a) : a(_a) {} virtual void f() { cout << "In A. a = " << a << endl; } }; class B : public A { int b; public: B(int _a, int _b) : A(_a), b(_b) {} final void f() { cout << "In B."; A::f(); cout << "b = " << b << endl; } void f1() { cout << "asdasd" << endl; } }; int main() { SetConsoleCP(1251); SetConsoleOutputCP(1251); /*A a(1); a.f(); */ B b(1,2); //b.f(); cout << "*a1" << endl; A *a1 = &b; a1->f(); return 0; }
true
1780a44b93ef125bb14edb07ede95aa0eff7ddc5
C++
Breush/evilly-evil-villains
/inc/dungeon/command/trapinterpreter.hpp
UTF-8
1,171
2.65625
3
[]
no_license
#pragma once #include "context/command.hpp" #include "dungeon/structs/room.hpp" #include "dungeon/command/facilityinterpreter.hpp" #include <functional> namespace dungeon { // Forward declarations class Inter; //! Interprets a room-wide command. class TrapInterpreter { public: //! Constructor. TrapInterpreter(Inter& inter); //! Default destructor. ~TrapInterpreter() = default; //-------------// //! @name Data //! @{ //! Set the room from its coords. void roomSet(const RoomCoords& coords); //! @} //--------------------// //! @name Interpreter //! @{ //! Interpret a command line. void interpret(std::vector<context::Command>& commands, std::vector<std::wstring>& tokens); //! Tries to auto-complete the lastToken. void autoComplete(std::vector<std::wstring>& tokens, const std::function<void(const std::wstring&)>& checkAdd) const; //! @} private: Inter& m_inter; //!< Reference to the inter. RoomCoords m_roomCoords; //!< The room coords. }; }
true
7d5b326a2aefc3e9443ed511c10b1859cac94f31
C++
daffa-d/Smart_IoT
/lib/Firebase/Firebase.cpp
UTF-8
3,051
2.796875
3
[]
no_license
#include "Firebase.h" /** * @file Firebase.cpp * * @mainpage Library For Get data, Send data, and activate relay from firebase * */ FirebaseData fbdo; void FB::begin(const String Host, const String Auth) { Firebase.begin(Host, Auth); } void FB::sendDataInt(int time, const String &path_db, int value) { //Serial.print(F("Data Yang Dikirim Adalah (Interger) = ")); //Serial.println(value); Firebase.setInt(fbdo, path_db, value); delay(time); } void FB::sendDataFloat(int time, const String &path_db, float value) { //Serial.print(F("Data Yang Dikirim Adalah (Float) = ")); //Serial.println(value); Firebase.setFloat(fbdo, path_db, value); delay(time); } /*! * @param pin * pin For relay. input with connected relay * @param buzzer * buzzer flagging. true for active buzzer. false for deactive buzzer * @param serial * for active serial print relay */ getDataRelay::getDataRelay(uint8_t pin) { getDataRelay::_pin = pin; } getDataRelay::getDataRelay(uint8_t pin, uint8_t pinBuzzer) { _pin = pin; _pinBuzzer = pinBuzzer; } void getDataRelay::begin() { pinMode(_pin, OUTPUT); pinMode(_pinBuzzer, OUTPUT); } /*! * @brief Get Data From Firebase Database * @param pathDB * path Realtime Database from Firebase * @param dataRelay * add value from database to global variabel / arguments */ int getDataRelay::run(const char *pathDB, int &dataRelay) { if (Firebase.getInt(fbdo, pathDB)) { dataRelay = fbdo.intData(); if (dataRelay == 1) { digitalWrite(_pin, HIGH); } else if (dataRelay == 0) { digitalWrite(_pin, LOW); } else { Serial.println(F("Tidak Menerima Data")); } } else if (Firebase.getString(fbdo, pathDB)) { getDataRelay::_get = fbdo.stringData(); String res = getDataRelay::_get; res.replace('\"', ' '); dataRelay = res.toInt(); if (dataRelay == 1) { digitalWrite(_pin, HIGH); } if (dataRelay == 0) { digitalWrite(_pin, LOW); } } else { Serial.println(fbdo.errorReason()); } return dataRelay; } int getDataRelay::run(const char *pathDB, int &dataRelay, bool StateBuzzer) { if (Firebase.getInt(fbdo, pathDB)) { dataRelay = fbdo.intData(); if (dataRelay == 1) { digitalWrite(_pin, HIGH); } else if (dataRelay == 0) { digitalWrite(_pin, LOW); } else { Serial.println(F("Tidak Menerima Data")); } } else if (Firebase.getString(fbdo, pathDB)) { getDataRelay::_get = fbdo.stringData(); String res = getDataRelay::_get; res.replace('\"', ' '); dataRelay = res.toInt(); if (dataRelay = !dataRelay) { if (dataRelay == 1) { digitalWrite(_pin, HIGH); } if (dataRelay == 0) { digitalWrite(_pin, LOW); } } else if( dataRelay == dataRelay) { Serial.println("Data Sama"); } } else { Serial.println(fbdo.errorReason()); } return dataRelay; }
true
909377bb52e5876b6055b106a0ab0dc3742b2397
C++
proxenek/supremacy-csgo
/element.h
UTF-8
2,101
2.609375
3
[]
no_license
#pragma once // pre-declares. class Element; class Tab; class Form; enum ElementFlags : size_t { NONE = 0 << 0, DRAW = 1 << 0, CLICK = 1 << 1, ACTIVE = 1 << 2, SAVE = 1 << 3, DEACIVATE = 1 << 4, }; enum ElementTypes : size_t { CHECKBOX = 1, SLIDER, KEYBIND, DROPDOWN, COLORPICKER, MULTI_DROPDOWN, EDIT, BUTTON, CUSTOM }; using ToggleCallback_t = void( *)( ); #define LABEL_OFFSET 20 class Element { friend class GUI; friend class Tab; friend class Form; friend class Config; protected: using ShowCallback_t = bool( *)( ); using Callback_t = void( *)( ); protected: Point m_pos; int m_w; int m_h; int m_base_h; size_t m_col; Form* m_parent; std::string m_label; std::string m_file_id; size_t m_flags; size_t m_type; std::vector< ShowCallback_t > m_show_callbacks; Callback_t m_callback; bool m_show; bool m_use_label; public: __forceinline Element( ) : m_pos{}, m_w{}, m_h{}, m_base_h{}, m_parent{ nullptr }, m_label{}, m_file_id{}, m_flags{}, m_type{}, m_use_label{}, m_show_callbacks{}, m_callback{}, m_show{} {} __forceinline void setup( const std::string &label, const std::string &file_id ) { m_label = label; m_file_id = file_id; } __forceinline void AddFlags( size_t flags ) { m_flags |= flags; } __forceinline void RemoveFlags( size_t flags ) { m_flags &= ~flags; } __forceinline void AddShowCallback( ShowCallback_t scb ) { m_show_callbacks.push_back( scb ); } __forceinline void SetCallback( Callback_t cb ) { m_callback = cb; } __forceinline void SetPosition( int x, int y ) { m_pos.x = x; m_pos.y = y; } protected: virtual void draw( ) {}; virtual void think( ) {}; virtual void click( ) {}; };
true
1c18127c2451b66459ce31e3f66ec1a1e8695a9a
C++
avinashvrm/Data-Structure-And-algorithm
/Dynamic Programming/Minimum Cost For Tickets.cpp
UTF-8
908
2.859375
3
[]
no_license
class Solution { public: vector<int> dp; int sub(vector<int> &day, vector<int> &cost, int si) // si denotes starting index { //cout<<"| "; int n = day.size(); if(si>=n) return 0; if(dp[si]) return dp[si]; int cost_day = cost[0] + sub(day , cost , si+1); int i; for(i = si ; i<n; i++) if(day[i] >=day[si] + 7) break; int cost_week = cost[1] + sub(day, cost, i); for(i = si ; i<n; i++) if(day[i] >=day[si] + 30) break; int cost_month = cost[2] + sub(day, cost, i); return dp[si] = min({cost_day, cost_week , cost_month }); } int mincostTickets(vector<int>& days, vector<int>& costs) { dp.resize(367); return sub(days,costs,0); } };
true
ea0b73b8e21a8beddca373a69047453ad79139de
C++
MatthewRodriguez/GridGraph
/GridGraph.h
UTF-8
1,241
2.8125
3
[]
no_license
// // GridGraph.h // GridGraph // // Created by Matt Rodriguez on 4/6/20. // Copyright © 2020 Matthew Rodriguez. All rights reserved. // #ifndef GridGraph_h #define GridGraph_h #include <iostream> #include <vector> #include <cstdlib> #include <ctime> #include <random> #include <unordered_set> #include <unordered_map> #include <climits> using namespace std; struct Node{ int x; int y; int info; bool visit; int heuristic; Node *parent = nullptr; vector<Node*> list; Node (int x_val, int y_val, int i, bool v = false) : x(x_val), y(y_val), info(i), visit(v) {} }; class GridGraph{ vector<Node*> nodes; public: GridGraph(); void addGridNode(int x, int y, int val); void addUndirectedEdge(Node *first, Node *second); void removeUndirectedGraph(Node *first, Node *second); unordered_set<Node*> getAllNodes(); void createRandomGridGraph(int n); Node* findMinDistance(unordered_map<Node*, int> umap); void updateDistance(Node *first, Node *second, unordered_map<Node*, int> &umap); void setHeuristic(Node *first, Node *second); vector<Node*> astar(Node *sourceNode, Node *destNode); vector<Node*> a(); void printNodes(); void printU(); }; #endif /* GridGraph_h */
true
c3c4f6f25a406a076757cca55fc0f5cb354a3155
C++
jmcabornero/TrabajoInformatica2
/Cofres.cpp
UTF-8
923
2.90625
3
[]
no_license
#include "Cofres.h" Cofres::Cofres(float x, float y, int t) { i = x; j = y; tipo = t; } void Cofres::Dibuja() { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); if (tipo==1) glBindTexture(GL_TEXTURE_2D, ETSIDI::getTexture("imagenes/Cofres/Cerrado.png").id); if (tipo==2||tipo==3) glBindTexture(GL_TEXTURE_2D, ETSIDI::getTexture("imagenes/Cofres/Abierto.png").id); glDisable(GL_LIGHTING); glBegin(GL_POLYGON); glColor3f(1, 1, 1); glTexCoord2d(0, 1);glVertex3d(i, j, 0.025); glTexCoord2d(1, 1);glVertex3d(i + 1, j, 0.025); glTexCoord2d(1, 0);glVertex3d(i + 1, j + 1, 0.025); glTexCoord2d(0, 0);glVertex3d(i, j + 1, 0.025); glEnd(); glEnable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); } Vector2D Cofres::GetEsquina() { Vector2D vec; vec.x = i; vec.y = j; return vec; } void Cofres::SetTipo(int a) { tipo=a; } int Cofres::GetTipo() { return tipo; }
true
0c0479d8f17c023d29976c83f5c71b31cf3005c7
C++
tusharkashyap2768/Data-Structures
/linked_list-main/insert at sorted in sorted pos.cpp
UTF-8
1,101
3.265625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; struct Node { int data; struct Node * next; }*first=NULL; void create (int a[],int n) { int i; struct Node *t,*last; first=new Node; first->data=a[0]; first->next=NULL; last=first; for(i= 1; i <n; i++) { t=new Node; t->data=a[i]; t->next=NULL; last->next=t; last=t; } } void display(struct Node *p) { while(p!=NULL) { cout<<p->data<<" "; p=p->next; } } void SortedInsert(struct Node *p,int x) { struct Node *t,*q=NULL; t=new Node; t->data=x; t->next=NULL; if(first==NULL) first=t; else { while(p && p->data<x) { q=p; p=p->next; } if(p==first) { t->next=first; first=t; } else { t->next=q->next; q->next=t; } } } int main() { struct Node * temp; int n; int key,index,x; cout<<"enter the no of nodes in linked list :-"<<endl; cin>>n; int a[n]; cout<<"enter data of linked list :-"<<endl; for(int i=0;i<n;i++) { cin>>a[i]; } create(a,n); display(first); cout<<SortedInsert(first,15); display(first);
true
5e5e25e9ccedaae486a4dbe69a06bf9ac3668e77
C++
gregoryfikator/RTS_Foundation
/RTS_Foundation.Core/Framework/TextureManagerClass.cpp
UTF-8
1,756
2.890625
3
[]
no_license
#include "TextureManagerClass.h" TextureManagerClass::TextureManagerClass() { m_TextureArray = nullptr; } TextureManagerClass::TextureManagerClass(const TextureManagerClass& other) { } TextureManagerClass::~TextureManagerClass() { } bool TextureManagerClass::Initialize(int count) { m_textureCount = count; // Create the color texture object. m_TextureArray = new TextureClass[m_textureCount]; if (!m_TextureArray) { return false; } return true; } bool TextureManagerClass::InitializeTerrainTextures(int count, int* textureIndexArray) { // Create the color texture object. m_TerrainTextureArray = new TerrainTextureArrayClass(count); if (!m_TerrainTextureArray) { return false; } for (int i = 0; i < count; i++) { m_TerrainTextureArray->SetTexture(i, m_TextureArray[textureIndexArray[i]].GetTexture()); } return true; } void TextureManagerClass::Shutdown() { int i; if (m_TerrainTextureArray) { delete m_TerrainTextureArray; m_TerrainTextureArray = nullptr; } // Release the texture objects. if (m_TextureArray) { for (i = 0; i < m_textureCount; i++) { m_TextureArray[i].Shutdown(); } delete[] m_TextureArray; m_TextureArray = nullptr; } return; } bool TextureManagerClass::LoadTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, const WCHAR* filename, int location) { bool result; // Initialize the color texture object. result = m_TextureArray[location].Initialize(device, filename); if (!result) { return false; } return true; } ID3D11ShaderResourceView* TextureManagerClass::GetTexture(int id) { return m_TextureArray[id].GetTexture(); } ID3D11ShaderResourceView** TextureManagerClass::GetTerrainTextures() { return m_TerrainTextureArray->GetTextureArray(); }
true
146303f5d1f8becbdb1cbdd55f53bba53ecfe766
C++
ysyesilyurt/Metu-CENG
/242/hw3/Miner.cpp
UTF-8
5,958
3.09375
3
[ "MIT" ]
permissive
#include <iomanip> #include "Miner.h" #include "Utilizer.h" /* YOU MUST WRITE THE IMPLEMENTATIONS OF THE REQUESTED FUNCTIONS IN THIS FILE. START YOUR IMPLEMENTATIONS BELOW THIS LINE */ int Miner::getNextAvailableBlockchainID() const { return last_blockchainID + 1; } Miner::Miner(std::string name) { minerChain.emplace_back(std::pair <Blockchain *,bool> (nullptr, false)); last_blockchainID = -1; Miner::name = std::move(name); // moves the string, to get rid of reduntant copies } Miner::~Miner() { unsigned long size = minerChain.size(), index = 0; while(index < size) { delete minerChain[index].first; index++; } } void Miner::createNewBlockchain() { if(!minerChain[0].first) // no head { minerChain[0].first = new Blockchain(getNextAvailableBlockchainID()); last_blockchainID += 1; } else { minerChain.emplace_back(std::pair <Blockchain *,bool> (new Blockchain(getNextAvailableBlockchainID()), false)); last_blockchainID += 1; } } void Miner::mineUntil(int cycleCount) { unsigned long size = minerChain.size(), index; for (int i = 0; i < cycleCount; ++i) { index = 0; while(index < size) { ++(*minerChain[index].first); index++; } } } void Miner::demineUntil(int cycleCount) { unsigned long size = minerChain.size(), index; int flag; for (int i = 0; i < cycleCount; ++i) { index = 0; while(index < size) { if(!minerChain[index].first->getHead()) // blockchain has no value left return; flag = 0; if(minerChain[index].second) // softforked blockchain { if(!minerChain[index].first->getHead()->getNext()) // if just head remains in the softforked blockchain index++; else { --(*minerChain[index].first); index++; } } else { Koin * tempKoin = minerChain[index].first->getHead(); // last Koin to be demined while(tempKoin->getNext()) tempKoin = tempKoin->getNext(); for (int j = 0; j < softforkedChains.size(); ++j) { if(tempKoin->getValue() == softforkedChains[j].second) // if the value to be demined is the head of any softforked { flag++; break; } } if(!flag) { --(*minerChain[index].first); index++; } else index++; } } } } double Miner::getTotalValue() const // Soft-forks DO NOT constitute for the total value of the miner. { unsigned long size = minerChain.size(), index = 0; double result = .0; while(index < size) { if(minerChain[index].second) // softforked index++; else { result += minerChain[index].first->getTotalValue(); index++; } } return result; } long Miner::getBlockchainCount() const { return last_blockchainID + 1; } Blockchain* Miner::operator[](int id) const { unsigned long size = minerChain.size(), index = 0; while(index < size) { if(id == minerChain[index].first->getID()) return minerChain[index].first; else index++; } return nullptr; } bool Miner::softFork(int blockchainID) { Blockchain * blkchn_toCopy = (*this)[blockchainID]; if(!blkchn_toCopy) // fork blockchain dne return false; else { Koin * lastKoin = blkchn_toCopy->getHead(); if(lastKoin) { while (lastKoin->getNext()) lastKoin = lastKoin->getNext(); int nextID = getNextAvailableBlockchainID(); last_blockchainID += 1; Blockchain * newBlockchain= new Blockchain(nextID,lastKoin); newBlockchain->isSoft = true; minerChain.emplace_back(std::pair <Blockchain *,bool> (newBlockchain, true)); softforkedChains.emplace_back(std::pair <int,double> (newBlockchain->getID(),newBlockchain->getHead()->getValue())); } else this->createNewBlockchain(); } return true; } bool Miner::hardFork(int blockchainID) { Blockchain * blkchn_toCopy = (*this)[blockchainID]; if(!blkchn_toCopy) // fork blockchain dne return false; else { Koin * lastKoin = blkchn_toCopy->getHead(); if(lastKoin) { while (lastKoin->getNext()) lastKoin = lastKoin->getNext(); int nextID = getNextAvailableBlockchainID(); last_blockchainID += 1; Koin * newLastKoin = new Koin(lastKoin->getValue()); Blockchain * newBlockchain = new Blockchain(nextID,newLastKoin); minerChain.emplace_back(std::pair <Blockchain *,bool> (newBlockchain, false)); } else this->createNewBlockchain(); } return true; } std::ostream & operator<<(std::ostream& os,const Miner& miner) { int precision = Utilizer::koinPrintPrecision(); unsigned long size = miner.getChain().size(), index = 0; os << std::fixed << std::setprecision(precision); os << "-- BEGIN MINER --\n" << "Miner name: " << miner.name << "\nBlockchain count: "; os << miner.getBlockchainCount() << "\n"; os << "Total value: " << miner.getTotalValue() << "\n\n"; while (index < size) { os << *miner.getChain()[index].first; os << '\n'; index++; } os << "\n-- END MINER --\n"; return os; } std::vector< std::pair<Blockchain *,bool> > Miner::getChain() const { return minerChain; }
true
7c516f847090aec19b3044ace91df841cd5d4630
C++
JacobJBublitz/Orion
/Core/Private/Win32/Platform.cc
UTF-8
1,720
2.640625
3
[]
no_license
#include "Orion/Platform.hh" #include <system_error> extern "C" { #include <Windows.h> } namespace Orion { namespace { constexpr std::size_t kEnvBufferSize = 64; } // namespace std::optional<Stl::String> EnvironmentVariable(Stl::StringView variable) { wchar_t name_stack_buffer[kEnvBufferSize]; wchar_t value_stack_buffer[kEnvBufferSize]; std::vector<wchar_t> name_heap_buffer; std::vector<wchar_t> value_heap_buffer; const wchar_t *name_ptr; if (Stl::EncodeWide(variable, name_stack_buffer, true) <= kEnvBufferSize) { // Name fit into stack-allocated buffer name_ptr = name_stack_buffer; } else { // Store the encoded name in the heap name_heap_buffer = Stl::EncodeWide(variable, true); name_ptr = name_heap_buffer.data(); } DWORD result = GetEnvironmentVariableW(name_ptr, value_stack_buffer, kEnvBufferSize); if (result == 0) { DWORD err = GetLastError(); if (err == ERROR_ENVVAR_NOT_FOUND) return {}; throw std::system_error(err, std::system_category(), "Failed to get environment variable"); } if (result <= kEnvBufferSize) { // Value fit into stack-allocated buffer return Stl::DecodeWide({value_stack_buffer, result}); } // Value didn't fit into stack-allocated buffer value_heap_buffer.resize(result); result = GetEnvironmentVariableW(name_ptr, value_heap_buffer.data(), result); if (result == 0) { DWORD err = GetLastError(); if (err == ERROR_ENVVAR_NOT_FOUND) return {}; throw std::system_error(err, std::system_category(), "Failed to get environment variable"); } return Stl::DecodeWide(value_heap_buffer); } } // namespace Orion
true
8bb5c9a715d2566b4d897ba1b8c154b8432478cb
C++
RebelOfDeath/CP
/DSA/recursion/rope_cutting_problem.cpp
UTF-8
417
2.625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int solve(int n, int a, int b, int c){ if(n==0) return 0; if(n < 0) return -1; int res = max({solve(n-a, a, b, c), solve(n-b, a, b, c), solve(n-c, a, b, c)}); if(res == -1) return -1; return res+1; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n, a, b, c; cin >> n >> a >> b >> c; cout << solve(n, a, b, c) << '\n'; return 0; }
true
3b0db7a6c5e697807fff624e8698991a517618b5
C++
diaoshaoyou/Computer-Network-Project
/Lab7/Client/Client/Client_main.cpp
UTF-8
5,031
2.6875
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #define _WINSOCK_DEPRECATED_NO_WARNINGS #include "client.h" /* *Only support sending data once!! When sending data the second time, please input "6" again. */ int main(void) { //Initialize socket InitSocket(); //Create main thread HANDLE MainThread = NULL; DWORD ThreadId = 0; //Call the function mainThrFun MainThread = CreateThread(NULL, 0, mainThrFun, NULL, 0, &ThreadId); if (MainThread == NULL || ThreadId == 0) { printf(MainThrErr); } //Loop for the main thread while (1) { if (WaitForSingleObject(InputEvent, 10) == WAIT_OBJECT_0) { ResetEvent(InputEvent); Sleep(1); } } return 0; } //Initialize socket void InitSocket(void) { WSADATA wsaData; WORD wVersionRequested = MAKEWORD(2, 2); if (WSAStartup(wVersionRequested, &wsaData) != 0) { printf(WSASErr); return; } //Check the version if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); printf(VersionErr); return; } } //The function to be called by mai thread DWORD WINAPI mainThrFun(LPVOID lp) { //Display the start menu int Op = -1; printf(CreateMain, GetCurrentThreadId()); printf(C_preface); int index = 1; while (1) { if (recvJustNow) { printf(C_InputTip); recvJustNow = false; } //Input the instruction scanf("%d", &Op); switch (Op) { case CONN: _connect(); break; case EXIT: exit(); break; case DISCONN: disconnect(); break; case TIME: //send_time_request(); memset(RequestBuf, 0, sizeof(RequestBuf)); RequestBuf[0] = TIME; //for (int i = 0; i < 4; i++)//debug sendRequest(); break; case NAME: memset(RequestBuf, 0, sizeof(RequestBuf)); RequestBuf[0] = NAME; sendRequest(); break; case LIST: memset(RequestBuf, 0, sizeof(RequestBuf)); RequestBuf[0] = LIST; sendRequest(); break; case SENDMSG: memset(RequestBuf, 0, sizeof(RequestBuf)); printf(InputIndex);//Input the client's index you want to send scanf("%d", &index); printf(InputMsg);//Input the client's message you want to send scanf("%s", RequestBuf + HEADERLENGTH); strcat(RequestBuf + HEADERLENGTH, "\0"); RequestBuf[0] = SENDMSG; RequestBuf[1] = index; sendRequest(); break; default: break; } //If the connectton is established,creating the child thread to receive message from the server if (ConnectStatus) { if (WaitForSingleObject(ReceiveEvent, 10) == WAIT_OBJECT_0) { ResetEvent(ReceiveEvent); Sleep(1); } } } } //The opertion to connect the client and the server void _connect(void) { //If the connection is established,return if (ConnectStatus) { printf(AlreadyConn); recvJustNow = true; return; } //Input the server's IP address printf(InputIP); scanf("%s", ServerIP); //Initialize the server SOCKADDR_IN Server; Server.sin_family = AF_INET; Server.sin_port = htons(ServerPort); Server.sin_addr.s_addr = inet_addr(ServerIP); //Get the socket ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ClientSocket == INVALID_SOCKET) { WSACleanup(); printf(CreateSockErr); return; } printf("$Socket: %lu, Port: %d, IP: %s\n", ClientSocket, ServerPort, ServerIP); //Create InputEvent's event InputEvent = CreateEvent(NULL, TRUE, FALSE, NULL); int ret = connect(ClientSocket, (PSOCKADDR)&Server, sizeof(Server)); if (ret == SOCKET_ERROR) { printf(ConnErr); closesocket(ClientSocket); WSACleanup(); return; } //Set the status to be true ConnectStatus = true; //Create child thread ReceiveEvent = CreateEvent(NULL, TRUE, FALSE, NULL); //Create child thread create_child_thread(); } //Create child thread void create_child_thread() { HANDLE ChildThread = NULL; DWORD ThreadId = 0; //Call the function ChildThread = CreateThread(NULL, 0, childThrFun, NULL, 0, &ThreadId); if (ChildThread == NULL || ThreadId == 0) { printf(ChildThrErr); } } //The function to be called by child thread DWORD WINAPI childThrFun(LPVOID lp) { printf(CreateChild, GetCurrentThreadId()); int ret = 0; //Receive the response from the server while (true) { memset(ReceiveBuf, 0, sizeof(ReceiveBuf)); if (recv(ClientSocket, ReceiveBuf, sizeof(ReceiveBuf), 0) <= 0) { printf(RecvErr); break; } printf("$Received-->%s", ReceiveBuf + HEADERLENGTH); printf("\n"); recvJustNow = true;//print input tips after reciving SetEvent(ReceiveEvent); if (ConnectStatus == false) { break; } } closesocket(ClientSocket); return 1; } //Exit the program void exit(void) { if (ConnectStatus) { disconnect(); } exit(0); } void disconnect() { memset(RequestBuf, 0, sizeof(RequestBuf)); RequestBuf[0] = DISCONN; sendRequest(); } void sendRequest() { if (ConnectStatus == false) printf(ConnFirstErr); else { if(RequestBuf[0]==DISCONN) ConnectStatus = false; if (RequestBuf[0] != SENDMSG) { RequestBuf[1] = 1; RequestBuf[2] = 0; } if (send(ClientSocket, RequestBuf, strlen(RequestBuf), 0) < 0) { printf(SendErr); } } }
true
d9a9a89c648eef83e973d355d6232f5fe0927114
C++
xchmwang/algorithm
/uva/uva12657/uva12657/main.cpp
UTF-8
1,402
3.109375
3
[]
no_license
#include <iostream> #include <list> using namespace std; int main() { int n, m; while (cin >> n >> m) { list<int> l; for (int i = 1; i <= n; i++) l.push_back(i); int op, x, y; for (int i = 0; i < m; i++) { cin >> op; if (op <= 3) cin >> x >> y; list<int>::iterator iter = l.begin(); if (op == 1) { while (iter != l.end()) { if (*iter == x) iter = l.erase(iter); else if (*iter == y) l.insert(iter++, x); else iter++; } } else if (op == 2) { while (iter != l.end()) { if (*iter == x) iter = l.erase(iter); else if (*iter == y) { iter++; l.insert(iter, x); continue; } else iter++; } } else if (op == 3) { list<int>::iterator it; int tmp, find = 0; for ( ;iter != l.end(); iter++) { if (*iter == x || *iter == y) { find++; if (find == 1) it = iter; else if (find == 2) { tmp = *iter; *iter = *it; *it = tmp; } } } } else if (op == 4) { l.reverse(); } } list<int>::iterator iter = l.begin(); __int64 sum = 0; for (int i = 0; iter != l.end(); i++, iter++) { if (i%2 == 0) sum += *iter; } cout << sum << endl; } /*list<int> l; for (int i = 0; i < 10; i++) l.push_back(i); list<int>::iterator iter = l.begin(); for ( ; iter != l.end(); ) { if (*iter == 4) iter = l.erase(iter); else ++iter; } l.reverse();*/ return 0; }
true
1ad009d0b788a980c0353d7e75341bcfbb149e24
C++
epiccoleman/aoc-2018
/day-19/Elfcode.cpp
UTF-8
1,710
2.859375
3
[]
no_license
#include "Elfcode.h" #include <iostream> #include <sstream> #include <iterator> Elfcode::ElfcodeInterpreter::ElfcodeInterpreter(std::map<std::string, Operation> code_map, int ip_reg) : ip_value(0), ip_register(ip_reg), // gets set when evaluating a program opcodes(code_map), registers { 0, 0, 0, 0, 0, 0 } {} void Elfcode::ElfcodeInterpreter::execute_instruction(const std::string& input) { registers[ip_register] = ip_value; // std::cerr << "Instruction: " << input << std::endl; auto op = instruction_name(input); auto args = instruction_args(input); registers = opcodes[op](registers, args); ip_value = registers[ip_register]; ip_value++; // std::cerr << "Registers: { "; // fprintf(stderr, "%4d, %10d, %10d, %4d, %4d, %4d", registers[0], registers[1],registers[2],registers[3],registers[4],registers[5]); // std::cerr << " }" << std::endl; } void Elfcode::ElfcodeInterpreter::execute_program(std::vector<std::string> program) { int max = 10000000; int i = 0; while(ip_value < program.size() && i < max){ execute_instruction(program[ip_value]); i++; if (i % 100000 == 0) std::cerr << "Cycle " << i << std::endl; } } const std::string Elfcode::ElfcodeInterpreter::instruction_name(const std::string& input) { return input.substr(0, input.find(' ')); } const std::vector<int> Elfcode::ElfcodeInterpreter::instruction_args(std::string input) { std::vector<int> args; std::istringstream iss(input); std::vector<std::string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>()); for (int i = 1; i < 4; i++){ args.push_back(stoi(results[i])); } return args; }
true
99dba68719b6b0bcb932b319ee081da6fe78c803
C++
Stormcross/AISP_vjezba
/krug/krug/krug.cpp
UTF-8
764
2.859375
3
[]
no_license
#include "krug.h" //definicija klase double krug::getPovrsina() const { return radius * radius*PI; //r^2 x PI } void krug::setPovrsina(double _povrsina) { radius = sqrt(_povrsina / PI); } double krug::getOpseg() const { return 2 * radius*PI; } void krug::setOpseg(double _opseg) { radius = _opseg / (2 * PI); } double krug::getRadius() const { return radius; } void krug::setRadius(double _radius) { radius = _radius; } string krug::Opis() const { stringstream ss; ss << "Krug - Radius=" << getRadius() << ", Opseg=" << getOpseg() << ", Povrsina=" << getPovrsina(); return ss.str(); } krug::krug() { radius = 0; } krug::krug(double _radius) { radius = _radius; } krug::~krug() { }
true
50a88208c6351b5901e59583f21234edc6a46d61
C++
cyhan1004/Algorithm
/cpp/1212.cpp
UTF-8
878
3.09375
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int main(void) { string octal; int temp; string temp_str; string ans = ""; int r; cin >> octal; int size = octal.size(); bool b = false; for (int i = 0 ; i < size; i++) { temp = (octal[i] - '0'); temp_str = ""; for (int j = 0; j < 3; j++) { r = temp % 2; temp_str += (char)(r + '0'); temp /= 2; } reverse(temp_str.begin(), temp_str.end()); ans += temp_str; } for (int i = 0; i< ans.size(); i++) { if(ans == "000") { cout<<ans[0] << endl; break; } if(b == false && ans[i] == '0') continue; if(ans[i] == '1') b = true; cout<<ans[i]; } cout<<endl; return 0; }
true
5b123be43870abfa2d9ed80a9c1700f6ed98a94e
C++
cmt218/Compiler
/lexer.h
UTF-8
428
2.671875
3
[]
no_license
/* CSE109 Cole Tomlinson cmt218 Lexer Program Program #4 */ #ifndef LEXER_H #define LEXER_H #include <iostream> #include "token.h" using namespace std; class Lexer { public: //Member variables istream &input; int lineNum; int linePos; //Constructor Lexer(istream&); //Member functions Token nextToken(); int peep(); char peek(); private: //Private member function char nextChar(); }; #endif
true
de6023841c6ed51d4a0a377a205c84c6dc0e2f20
C++
Abhijeet1990/NS3_CUNB
/cunb/helper/cunb-interference-helper.h
UTF-8
4,697
2.6875
3
[]
no_license
#ifndef CUNB_INTERFERENCE_HELPER_H #define CUNB_INTERFERENCE_HELPER_H #include "ns3/nstime.h" #include "ns3/simulator.h" #include "ns3/object.h" #include "ns3/traced-callback.h" #include "ns3/callback.h" #include "ns3/packet.h" #include "ns3/logical-cunb-channel.h" #include <list> namespace ns3 { /** * Helper for CunbPhy that manages interference calculations * This class keeps a list of signals that are impinging on the antenna of the * device, in order to compute which ones can be correctly received and which * ones are lost due to interference. */ class CunbInterferenceHelper { public: /** * A class representing a signal in time. * * Used in CunbInterferenceHelper to keep track of which signals overlap and * cause destructive interference. */ class Event : public SimpleRefCount<CunbInterferenceHelper::Event> { public: Event (Time duration, double rxPowerdBm, Ptr<Packet> packet, double frequencyMHz); ~Event (); /** * Get the duration of the event. */ Time GetDuration (void) const; /** * Get the starting time of the event. */ Time GetStartTime (void) const; /** * Get the ending time of the event. */ Time GetEndTime (void) const; /** * Get the power of the event. */ double GetRxPowerdBm (void) const; /** * Get the packet this event was generated for. */ Ptr<Packet> GetPacket (void) const; /** * Get the frequency this event was on. */ double GetFrequency (void) const; /** * Print the current event in a human readable form. */ void Print (std::ostream &stream) const; private: /** * The time this signal begins (at the device). */ Time m_startTime; /** * The time this signal ends (at the device). */ Time m_endTime; /** * The power of this event in dBm (at the device). */ double m_rxPowerdBm; /** * The packet this event was generated for. */ Ptr<Packet> m_packet; /** * The frequency this event was on. */ double m_frequencyMHz; }; static TypeId GetTypeId (void); CunbInterferenceHelper(); virtual ~CunbInterferenceHelper(); /** * Add an event to the InterferenceHelper * * \param duration the duration of the packet. * \param rxPower the received power in dBm. * \param packet The packet carried by this transmission. * \param frequencyMHz The frequency this event was sent at. * * \return the newly created event */ Ptr<CunbInterferenceHelper::Event> Add (Time duration, double rxPower, Ptr<Packet> packet, double frequencyMHz); /** * Get a list of the interferers currently registered at this * InterferenceHelper. */ std::list< Ptr< CunbInterferenceHelper::Event > > GetInterferers (); /** * Print the events that are saved in this helper in a human readable format. */ void PrintEvents (std::ostream &stream); /** * Determine whether the event was destroyed by interference or not. This is * the method where the SNIR tables come into play and the computations * regarding power are performed. * \param event The event for which to check the outcome. * \return 1 if the packets caused the loss, or 0 if there was no * loss. */ bool IsDestroyedByInterference (Ptr<CunbInterferenceHelper::Event> event); /** * Compute the time duration in which two given events are overlapping. * * \param event1 The first event * \param event2 The second event * * \return The overlap time */ Time GetOverlapTime (Ptr< CunbInterferenceHelper:: Event> event1, Ptr<CunbInterferenceHelper:: Event> event2); /** * Delete all events in the CunbInterferenceHelper. */ void ClearAllEvents (void); /** * Delete old events in this CunbInterferenceHelper. */ void CleanOldEvents (void); private: /** * A list of the events this CunbInterferenceHelper is keeping track of. */ std::list< Ptr< CunbInterferenceHelper::Event > > m_events; /** * The information about how packets survive interference. */ static const double collisionSnir; /** * The threshold after which an event is considered old and removed from the * list. */ static Time oldEventThreshold; }; /** * Allow easy logging of CunbInterferenceHelper Events */ std::ostream &operator << (std::ostream &os, const CunbInterferenceHelper::Event &event); } #endif /* CUNB_INTERFERENCE_HELPER_H */
true
7575e058e09653b33cc0c91f48cb9384ca8aaea9
C++
Houssk/Synthese-d-images-avec-OpenGL
/Basics/03-2D-reshape/C++/Triangle.cpp
UTF-8
2,989
3.0625
3
[]
no_license
// Définition de la classe Triangle #include <iostream> #include <GL/glew.h> #include <GL/gl.h> #include <math.h> #include <utils.h> #include <Triangle.h> /** constructeur */ Triangle::Triangle() throw (std::string) { /** Shader */ const char* srcVertexShader = "#version 300 es\n" "in vec2 glVertex;\n" "in vec3 glColor;\n" "out vec3 frgColor;\n" "void main()\n" "{\n" " vec2 position = glVertex;\n" " position.x = position.x * 0.5;\n" " position.y = -position.y;\n" " gl_Position = vec4(position, 0.0, 1.0);\n" " frgColor = glColor;\n" "}"; const char* srcFragmentShader = "#version 300 es\n" "precision mediump float;\n" "in vec3 frgColor;\n" "out vec4 glFragColor;\n" "void main()\n" "{\n" " vec3 color = frgColor;\n" " color.gb = 1.0 - color.gb;\n" " glFragColor = vec4(color, 1.0);\n" "}"; // compiler le shader de dessin m_ShaderId = Utils::makeShaderProgram(srcVertexShader, srcFragmentShader, "Triangle"); // déterminer où sont les variables attribute m_VertexLoc = glGetAttribLocation(m_ShaderId, "glVertex"); m_ColorLoc = glGetAttribLocation(m_ShaderId, "glColor"); /** VBOs */ // créer et remplir le buffer des coordonnées std::vector<GLfloat> vertices { -0.88, +0.52, // P0 +0.63, -0.79, // P1 +0.14, +0.95, // P2 }; m_VertexBufferId = Utils::makeFloatVBO(vertices, GL_ARRAY_BUFFER, GL_STATIC_DRAW); // créer et remplir le buffer des couleurs std::vector<GLfloat> colors { 1.0, 0.0, 0.5, // P0 0.0, 0.0, 1.0, // P1 1.0, 1.0, 0.0, // P2 }; m_ColorBufferId = Utils::makeFloatVBO(colors, GL_ARRAY_BUFFER, GL_STATIC_DRAW); } /** dessiner l'objet */ void Triangle::onDraw() { // activer le shader glUseProgram(m_ShaderId); // activer et lier le buffer contenant les coordonnées glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferId); glEnableVertexAttribArray(m_VertexLoc); glVertexAttribPointer(m_VertexLoc, Utils::VEC2, GL_FLOAT, GL_FALSE, 0, 0); // activer et lier le buffer contenant les couleurs glBindBuffer(GL_ARRAY_BUFFER, m_ColorBufferId); glEnableVertexAttribArray(m_ColorLoc); glVertexAttribPointer(m_ColorLoc, Utils::VEC3, GL_FLOAT, GL_FALSE, 0, 0); // dessiner un triangle avec les trois vertices glDrawArrays(GL_TRIANGLES, 0, 3); // désactiver les buffers glDisableVertexAttribArray(m_VertexLoc); glDisableVertexAttribArray(m_ColorLoc); glBindBuffer(GL_ARRAY_BUFFER, 0); // désactiver le shader glUseProgram(0); } /** destructeur */ Triangle::~Triangle() { // supprimer le shader et les VBOs Utils::deleteShaderProgram(m_ShaderId); Utils::deleteVBO(m_VertexBufferId); Utils::deleteVBO(m_ColorBufferId); }
true
d09eca939ddb644cb409c340ee888965e8a2686b
C++
Xoliper/SpaceRivals
/Sources/Engine/Common/Objects/Object.hpp
WINDOWS-1250
1,643
2.59375
3
[]
no_license
#ifndef ENGINE_COMMON_OBJECTS_OBJECT_HPP_ #define ENGINE_COMMON_OBJECTS_OBJECT_HPP_ #include "ObjTemplate.hpp" #include "../Drawable.hpp" #include "../Shaderloader.hpp" #include "../Graphics/Texture.hpp" #include "../World.hpp" #include "../Exceptions.hpp" #include <math.h> #include <algorithm> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> using namespace glm; class PhantomPointObject : public Drawable { public: PhantomPointObject(); PhantomPointObject(float x, float y, float z, float s); virtual ~PhantomPointObject(); void Render(); float x, y, z; float diameter; }; class VisualObject : public Drawable { public: VisualObject(World * wrd, ObjTemplate * obj); virtual ~VisualObject(); void SetLightViewMatrix(glm::mat4 newLv); void SetPosition(float x, float y, float z); void SetScale(float x, float y, float z); void SetRotation(bool x, bool y, bool z, float angle); void ChangeRotation(bool x, bool y, bool z, float angle); void SetupAnimation(bool ifStart, bool repeat, bool ifReturn, bool recalculateBoxDimm); bool Animate(float deltaTime); void SetShader(std::string shaderName); void Render(); protected: void AnimationProc(int curFrame, float ratio); //Display mode std::string shaderName; //Obj Data ObjTemplate * objTemplate; //Lightning view-matrix glm::mat4 lv; bool otherLv; //Animation vars bool animRepeat; bool animPlayback; bool animReturn; float curAnimTimeStamp; //(2 sekundy, ale jestemy np w 1.45s) bool recalculateBoxDimm; //Additional matrixes mat4 mvp; }; #endif /* ENGINE_COMMON_OBJECTS_OBJECT_HPP_ */
true
1152f01190dda5c8fe86542730eb184e8b6cad74
C++
Teabeans/CrackingTheCodingInterview
/S09_Ch01_ArraysAndStrings/01_07_RotateMatrix.cpp
UTF-8
8,071
3.421875
3
[]
no_license
//-----------------------------------------------------------------------------| // Authorship //-----------------------------------------------------------------------------| // // Tim Lum // twhlum@gmail.com // Created: 2018.07.15 // Modified: 2018.08.22 // /* 1.7 - RotateMatrix() - P.91 Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? //-----------------------------------------------------------------------------| // PROBLEM SETUP AND ASSUMPTIONS //-----------------------------------------------------------------------------| A left rotation may be performed by calling a right rotation 3 times. Only the right (clockwise) rotation shall be handled The nature of the pixel is immaterial; we may handle the pixel as a 32-bit int Since the problem specifies an N x N matrix, we address a square aspect ratio To move a pixel 0 1 X 0 1 X +---+---+ +---+---+ ([0][0] becomes [1][0]) 0 | 1 | 2 | 0 | 4 | 1 | ([1][0] becomes [1][1]) +---+---+ +---+---+ 1 | 4 | 3 | 1 | 3 | 2 | +---+---+ +---+---+ Y Y Output format is ambiguous, though it is implied that the data itself should be rotated. However, displaying the "image" and its rotated result may also be acceptable. //-----------------------------------------------------------------------------| // NAIVE APPROACH //-----------------------------------------------------------------------------| Iterate across every pixel within a quadrant and for (4) times Identify the 4 sister-pixels And swap them in turn 0 1 2 X [X][Y] is sister to +---+---+---+ [XMax - X][Y] which is sister to 0 | 1 | 2 | 3 | [XMax - X][YMax - Y] which is sister to +---+---+---+ [X][YMax-Y] 1 | 8 | 9 | 4 | +---+---+---+ 2 | 7 | 6 | 5 | +---+---+---+ The global behavioral rule may be defined as: The 90 degree rotational position of any pixel in a square matrix with coordinates: X, Y Is (XMax - Y), X 0 1 2 X +---+---+---+ 0 | X | O | X | 0, 0 rotates 90 degrees to +---+---+---+ 2, 0 which rotates 90 degrees to 1 | O | O | O | 2, 2 which rotates 90 degrees to +---+---+---+ 0, 2 2 | X | O | X | +---+---+---+ //-----------------------------------------------------------------------------| // OPTIMIZATIONS //-----------------------------------------------------------------------------| 1) The orientation of the image may be stored as a separate value from 0 to 3. This may then be used to interpret the N, E, S, W orientation of the image without modifying the image itself. Effectively, we may interject an orientation filter which appropriately redirects array access based upon the rotational state of the image. This has the added benefit of functioning on non-square arrays, and also facilitates easy addition of -90 and 180 degree rotations. From an image editing standpoint, interpretation rather than alteration of the base data will also better preserve image information. //-----------------------------------------------------------------------------| // TIME COMPLEXITY //-----------------------------------------------------------------------------| Any solution which modifies the original body of data may not complete faster than in a time complexity of: O( n^2 ) A filter solution, however, only adds a constant time alteration to the random access lookup of the parent data. As a "rotation" is merely the toggling of a rotation byte, the filter may complete in a time complexity of: O( 1 ) //-----------------------------------------------------------------------------| // PSEUDOLOGIC //-----------------------------------------------------------------------------| For every call to rotate, add 1 to the rotation state. For a call to display the image, read across the rows and columns in an appropriate fashion. //-----------------------------------------------------------------------------| // CODE (C++) //-----------------------------------------------------------------------------| */ // Compile with: // $ g++ --std=c++11 01_07_RotateMatrix.cpp -o RotateMatrix // Run with: // $ ./RotateMatrix #include <string> #include <iostream> #include <iomanip> #define WIDTH 3 #define HEIGHT 7 // Rotation control: // 0 == Base image // 1 == 90 degree clockwise rotation // 2 == 180 degree rotation // 3 == 270 degree rotation int ROTATION = 0; int IMAGE[ WIDTH ][ HEIGHT ]; // (+) --------------------------------| // #printMatrix( ) // ------------------------------------| // Desc: Print a matrix // Params: None // PreCons: None // PosCons: None // RetVal: None void printMatrix( ) { int xDim = WIDTH; int yDim = HEIGHT; if( ROTATION == 0 ) { // For rows 0 to MAX... for( int row = 0 ; row < yDim ; row++ ) { // Print column 0 to MAX for( int col = 0 ; col < xDim; col++ ) { std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " "; } std::cout << std::endl << std::endl; } } else if( ROTATION == 1 ) { for( int col = 0 ; col < xDim ; col++ ) { for( int row = ( yDim - 1 ) ; row >= 0; row-- ) { std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " "; } std::cout << std::endl << std::endl; } } else if ( ROTATION == 2 ) { for( int row = yDim-1 ; row >= 0 ; row-- ) { for( int col = ( xDim - 1 ) ; col >= 0 ; col-- ) { std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " "; } std::cout << std::endl << std::endl; } } else if ( ROTATION == 3 ) { for( int col = ( xDim - 1 ) ; col >= 0 ; col-- ) { for( int row = 0 ; row < yDim ; row++ ) { std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " "; } std::cout << std::endl << std::endl; } } } // (+) --------------------------------| // #rotateMatrix( ) // ------------------------------------| // Desc: Rotates a matrix // Params: None // PreCons: None // PosCons: The rotation has been incremented // RetVal: None void rotateMatrix( ) { ROTATION = ( ROTATION + 1 ) % 4; } //-----------------------------------------------------------------------------| // DRIVER //-----------------------------------------------------------------------------| // (+) --------------------------------| // #main( int, char* ) // ------------------------------------| // Desc: Code driver // Params: int arg1 - The number of command line arguments passed in // char* arg2 - The content of the command line arguments // PreCons: None // PosCons: None // RetVal: int - The exit code (0 for normal, -1 for error) int main( int argc, char* argv[ ] ) { std::cout << "Test of rotateMatrix( )" << std::endl; int xDim = WIDTH; int yDim = HEIGHT; // For row 0 to MAX for( int row = 0 ; row < yDim ; row++ ) { for( int col = 0 ; col < xDim ; col++ ) { IMAGE[ col ][ row ] = ( xDim * row ) + col; } } printMatrix( ); std::cout << std::endl; std::cout << "Rotating..." << std::endl << std::endl; rotateMatrix( ); printMatrix( ); std::cout << std::endl; std::cout << "Rotating..." << std::endl << std::endl; rotateMatrix( ); printMatrix( ); std::cout << std::endl; std::cout << "Rotating..." << std::endl << std::endl; rotateMatrix( ); printMatrix( ); std::cout << std::endl; std::cout << "Rotating..." << std::endl << std::endl; rotateMatrix( ); printMatrix( ); return( 0 ); } // Closing main( int, char* ) // End of file 01_07_RotateMatrix.cpp
true
9b3c649aaeb8bea3f4521858d9aaac1f59b53870
C++
uditabose/Collectibles
/MSCS/Compiler/include/Token.h
UTF-8
666
3.203125
3
[]
no_license
/** * Class to represent a token class */ #ifndef TOKEN_H #define TOKEN_H #include <string> class Token { public: Token(std::string tokType, std::string tokRegEx); virtual ~Token(); /** * returns the token type */ std::string getTokenType(); /** * returns the regular expression * associated with the token type */ std::string getTokenRegEx(); protected: private: // the type of token - tokword, toknum std::string tokenType; // the regular expression associated with the token class std::string tokenRegEx; }; #endif // TOKEN_H
true
60611029ac3748b4577b4caee5f1aad6e643ae44
C++
Croer01/GameEngine
/editor/GameComponentsProvider.cpp
UTF-8
6,336
2.609375
3
[]
no_license
// // Created by adria on 23/11/2019. // #include <game-engine/geEnvironment.hpp> #include "GameComponentsProvider.hpp" #include "ViewModels.hpp" using namespace GameEngine; void GameComponentsProvider::updateNames() { namesCached_ = env_->getRegisteredPropertiesIds(); } std::vector<std::string> GameComponentsProvider::getRegisteredPropertiesIds() { if(namesCached_.empty()) updateNames(); return namesCached_; } std::vector<PropertyDataRef> GameComponentsProvider::getPropertiesMetadata(const std::string &name) const { std::shared_ptr<GameEngine::PropertySetBase> gameProperties = env_->getProperties(name); std::vector<PropertyDataRef> properties; properties.reserve(gameProperties->size()); for(int i = 0; i < gameProperties->size(); i++) { properties.emplace_back(buildPropertyByType(gameProperties->get(i))); } return properties; } std::vector<std::shared_ptr<PropertyData>> GameComponentsProvider::getPropertiesMetadataByComponent(const std::string &componentName) const { std::shared_ptr<GameEngine::PropertySetBase> gameProperties = env_->getProperties(componentName); std::vector<PropertyDataRef> properties; properties.reserve(gameProperties->size()); for(int i = 0; i < gameProperties->size(); i++) { properties.emplace_back(buildPropertyByType(gameProperties->get(i))); } return properties; } PropertyDataRef GameComponentsProvider::buildPropertyByType(const GameEngine::PropertyBase &property) const { PropertyDataType result = PropertyDataType::STRING; PropertyDataRef propertyData; switch (property.type()) { case GameEngine::PropertyTypes::INT: { PropertyIntData *propertyInt = new PropertyIntData(property.name()); propertyData = PropertyDataRef(propertyInt); property.getDefault(&propertyInt->value_); } break; case GameEngine::PropertyTypes::FLOAT: { PropertyFloatData *propertyFloat = new PropertyFloatData(property.name()); propertyData = PropertyDataRef(propertyFloat); property.getDefault(&propertyFloat->value_); } break; case GameEngine::PropertyTypes::STRING: { PropertyStringData *propertyString = new PropertyStringData(property.name()); propertyData = PropertyDataRef(propertyString); property.getDefault(&propertyString->value_); } break; case GameEngine::PropertyTypes::BOOL: { PropertyBoolData *propertyBool = new PropertyBoolData(property.name()); propertyData = PropertyDataRef(propertyBool); property.getDefault(&propertyBool->value_); } break; case GameEngine::PropertyTypes::VEC2D: { PropertyVec2DData *propertyVec2D = new PropertyVec2DData(property.name()); propertyData = PropertyDataRef(propertyVec2D); GameEngine::Vec2D defaultValue; property.getDefault(&defaultValue); propertyVec2D->value_.xy = {defaultValue.x, defaultValue.y}; } break; case GameEngine::PropertyTypes::ARRAY_STRING: { PropertyStringArrayData *propertyStringArray = new PropertyStringArrayData(property.name()); propertyData = PropertyDataRef(propertyStringArray); property.getDefault(&propertyStringArray->value_); } break; case GameEngine::PropertyTypes::ARRAY_VEC2D: { PropertyVec2DArrayData *propertyVec2DArray = new PropertyVec2DArrayData(property.name()); propertyData = PropertyDataRef(propertyVec2DArray); std::vector<GameEngine::Vec2D> defaultValue; property.getDefault(&defaultValue); for(const auto &value : defaultValue) { Vector2DData data; data.xy = {value.x, value.y}; propertyVec2DArray->value_.push_back(data); } } break; case GameEngine::PropertyTypes::COLOR: { PropertyColorData *propertyColor = new PropertyColorData(property.name()); propertyData = PropertyDataRef(propertyColor); GameEngine::geColor defaultValue; property.getDefault(&defaultValue); propertyColor->value_.rgb = {defaultValue.r, defaultValue.g, defaultValue.b}; } break; case GameEngine::PropertyTypes::FILEPATH: { PropertyFilePathData *propertyFilepath = new PropertyFilePathData(property.name()); propertyData = PropertyDataRef(propertyFilepath); std::string defaultValue; property.getDefault(&defaultValue); DataFileType filetype = DataFileType::Other; const auto &gamePropertyFilePath = dynamic_cast<const GameEngine::PropertyFilePathBase &>(property); if(gamePropertyFilePath.getFileType() == GameEngine::FileType::IMAGE) filetype = DataFileType::Image; propertyFilepath->value_ = DataFile(defaultValue); propertyFilepath->fileTypeSupported_ = filetype; } break; case GameEngine::PropertyTypes::ENUM: { PropertyEnumData *propertyEnum = new PropertyEnumData(property.name()); propertyData = PropertyDataRef(propertyEnum); const auto &gamePropertyEnum = dynamic_cast<const GameEngine::PropertyEnumBase &>(property); property.getDefault(&propertyEnum->value_); propertyEnum->allowedValues_ = gamePropertyEnum.getAllowedValues(); } break; default: if(property.type() == GameEngine::PropertyTypes::UNKNOWN) throw std::invalid_argument("property " + property.name() + " is an unknown type"); else throw std::invalid_argument("property " + property.name() + " doesn't have valid deserializer"); break; } propertyData->requrired_ = property.required(); return propertyData; } GameComponentsProvider::GameComponentsProvider() { //Register components created from the game //TODO: improve the way to do this (maybe a macro or "if define"?) env_ = GameEngine::geEnvironment::createInstance(); //RegisterComponents(env_); }
true
a93e5f3264e71124f702922e62c758b6bec531eb
C++
andrejlevkovitch/KaliLaska
/src/events/sdl/MousePressEventSdl.hpp
UTF-8
754
2.71875
3
[]
no_license
// MousePressEventSdl.hpp #pragma once #include "events/imp/MousePressEventImp.hpp" #include <SDL2/SDL.h> namespace KaliLaska { class MousePressEventSdl final : public MousePressEventImp { public: MousePressEventSdl(Mouse::Button button, Mouse::Click click, Point clickPos); /**\param buttons mask of currently pressed mouse buttons. This needed because * sdl event not store this information */ MousePressEventSdl(SDL_MouseButtonEvent sdlEvent, uint32_t buttons); Mouse::Button button() const override; Mouse::Buttons buttons() const override; Mouse::Click click() const override; Point clickPos() const override; private: SDL_MouseButtonEvent event_; uint32_t buttons_; }; } // namespace KaliLaska
true
55fa0c4448c0298719174f4de40cb65a1a4dcda2
C++
wadejong/Summer-School-Materials
/MPI/exercises/recursive_master_worker.cc
UTF-8
4,715
2.75
3
[ "BSD-3-Clause" ]
permissive
/*** This implements a master-worker model to parallelize the recursive quadrature example. In this 1-D example, it is unlikely master-worker decomposition will give a a performance benefit since there is so little computation per task compared to the amount of communication. However, it is instructive to adopt this approach. We start by diving the range [a,b] into 128 sub intervals. These are dynamically allocated by the master to a pool of workers. ***/ #include <mpi.h> #include <cstdio> #include <cmath> #include <algorithm> #include <iostream> double g(double x) { return exp(-x*x)*cos(3*x); } // 3-point Gauss-Legendre quadrature on [a,b] double I(const double a, const double b, double (*f)(double)) { // Points/weights for GL on [0,1] const int N = 3; const double x[3] = {8.87298334620741702e-01, 5.00000000000000000e-01, 1.12701665379258312e-01}; const double w[3] = {2.77777777777777790e-01, 4.44444444444444420e-01, 2.77777777777777790e-01}; double L = (b-a); double sum = 0.0; for (int i=0; i<N; i++) { sum += w[i]*f(a+L*x[i]); } return sum*L; } double Irecur(const double a, const double b, double (*f)(double), const double eps, int level=0) { const double middle = (a+b)*0.5; double total=I(a,b,f); double left = I(a,middle,f); double right= I(middle,b,f); double test=left+right; double err=std::abs(total-test); //for (int i=0; i<level; i++) printf(" "); //printf("[%6.3f,%6.3f] total=%.6e test=%.6e err=%.2e\n", a, b, total, test, err); if (level >= 20) return test; // 2^20 = 1M boxes if (err<eps) return test; else { double neweps = std::max(eps*0.5,1e-15*std::abs(total)); return Irecur(a,middle,f,neweps,level+1) + Irecur(middle,b,f,neweps,level+1); } } // Information that defines a task struct Info { double a; double b; int flag; // 0=work 1=die Info(double a, double b, int flag) : a(a), b(b), flag(flag) {} Info() : a(0), b(0), flag(-1) {} }; // Made this global out of laziness const double eps=1e-10; // Only the master (rank=0) executes this void master() { int nproc, rank, nworker; MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &rank); nworker = nproc-1; const double gexact = std::sqrt(4.0*std::atan(1.0))*std::exp(-9.0/4.0); const double a=-6.0, b=6.0; const int NBOX = 128; double result = 0.0; int nbusy=0; for (int box=0; box<NBOX; box++) { double abox = a+box*(b-a)/NBOX; double bbox = a+(box+1)*(b-a)/NBOX; int nextworker; if (nbusy < nworker) { // In startup keep assigning tasks to the next worker until everyone is busy nextworker = nbusy+1; nbusy += 1; } else { // Once everyone is working receive a result and assign more work double value; MPI_Status status; MPI_Recv(&value, 1, MPI_DOUBLE, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD, &status); result += value; nextworker = status.MPI_SOURCE; } Info info(abox, bbox, 0); MPI_Send(&info, sizeof(info), MPI_BYTE, nextworker, 0, MPI_COMM_WORLD); } // Once all work has been issued, receive any outstanding results for (int i=0; i<nbusy; i++) { double value; MPI_Status status; MPI_Recv(&value, 1, MPI_DOUBLE, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD, &status); result += value; } // Tell the workers to finish for (int i=0; i<nworker; i++) { Info info(0, 0, 1); MPI_Send(&info, sizeof(info), MPI_BYTE, i+1, 0, MPI_COMM_WORLD); } // Print results double oldresult = Irecur(a,b,g,eps); double err_exact = std::abs(result-gexact); printf("result=%.10e old_result=%.10e err-exact=%.2e\n", result, oldresult, err_exact); } // All workers (rank>0) execute this void worker() { Info info; int nproc, rank; MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &rank); while (1) { // Wait for a message from the master MPI_Status status; MPI_Recv(&info, sizeof(info), MPI_BYTE, 0, 0, MPI_COMM_WORLD, &status); //std::cout << "Worker: " << rank << " " << info.a << " " << info.b << " " << info.flag << std::endl; if (info.flag == 0) { // Work! double value = Irecur(info.a, info.b, g, eps); MPI_Send(&value, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD); } else if (info.flag == 1) { // Die! return; } else { // Confusion std::cout << "Uh?"; MPI_Abort(MPI_COMM_WORLD, 1); } } } int main(int argc, char** argv) { MPI_Init(&argc,&argv); int nproc, rank; MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { master(); } else { worker(); } MPI_Finalize(); return 0; }
true
c72ac6be805f23d1cfbce6cba8fb033cc4a7493a
C++
Saumya1507/DSA-SHEET
/kthmaxandmin.cpp
UTF-8
359
2.859375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ int n,k; //the number of elements you want cout<<"enter the number of elements" cin>>n; cout<<"enter the kth number"; cin>>k; int arr[n]; // enter the array elements for(int i=0;i<n;i++){ cin>>arr[i]; } sort(arr,arr+n); //kth min cout<<arr[k-1]<<endl; //kth max cout<<arr[n-k]<<endl; }
true
ea6992a74c1bc43ccff5f3e25586be8c3aba3979
C++
jvtaufner/stable-matching
/lib/person.hpp
UTF-8
348
2.5625
3
[]
no_license
#ifndef PERSON_H #define PERSON_H #include <cmath> #include <vector> #include <algorithm> #include <iostream> using namespace std; class Person{ public: int age; int index; pair<int, int> coordinates; Person(int age, int x, int y, int index); static bool comparePeople(Person p1, Person p2); }; #endif
true
b773be51d793f2317dd56446d47d14d01d6ec474
C++
Lukas19/Tarea4
/funciones.cpp
UTF-8
1,848
3.671875
4
[]
no_license
/* list: Lista todos los tags contenidos en el tag actual change x: donde x es un numero mayor o igual a 1, indicando el tag al cual queremos navegar back: ir al tag anterior en la jerarquia position: indica el tag en el cual estamos situados actualmente exit: salir del programa */ #include <iostream> #include <string> #include <fstream> #include "arbol.h" using namespace std; //Prototipo void back(ptrNodo &n); void cargar_archivo(string filename, ptrNodo &n){ //recibe puntero al nodo raiz fstream myfile; myfile.open(filename.c_str()); string line; int nivel = 0; int fin = 0; cout << "Cargando archivo." << endl; ptrNodo r = n; // r es un puntero fijo a raiz while(getline(myfile, line)){ for (unsigned int i = 0; i < line.size(); i++){ if(line[nivel] == '/'){ nivel-=2; fin++; if(fin==3) //fin del documento break; back(n); if(fin == 2){ // si hay 2 cierres seguidos vuelve solo 1 nivel nivel++; break; } back(n); break; } if (line[i]==' '){ //cuenta los espacios si los hay if(i>nivel){ insertar_nodo(n); //n cambia al nodo creado nivel++; } } else{ if (nivel) //borra los espacios si los hay line.erase(line.begin(),line.begin()+i-1); n->dato = line; break; } fin = 0; } } cout << "Archivo cargado." << endl; n = r; } void list(ptrNodo &n){ for (auto it = n->hijos.begin(); it != n->hijos.end(); ++it) cout << *it->dato <<endl; } void change(int x, ptrNodo &n){ n = n->hijos[x-1]; } void back(ptrNodo &n){ n = n->padre; } /* otra forma es tener un puntero fijo a la raiz y recorrer el arbol hasta que un puntero del vector sea igual al nodo en el que estamos */ void position(ptrNodo &n){ cout << n->dato << endl; } //void exit() hacer esta funcion en el main y ponerle un break al while(true)
true
1514de134cca202abae8beac9843fee8d24369c6
C++
FrankBATMAN/Soft-Shadows-Rendering-with-Split-screen
/SourceCode/SSRS/LBBML/LBBML/LBBML/DataSimulator/Distances/ManhattanDistance.cpp
UTF-8
522
3.125
3
[]
no_license
#include "ManhattanDistance.h" //************************************************************* //Function: float CManhattanDistance::distanceV(const std::vector<float>& vVec1, const std::vector<float>& vVec2) { _ASSERT(!vVec1.empty() && !vVec2.empty(), "empty vector"); _ASSERT(vVec1.size() == vVec2.size(), "vectors size not match"); float ManhattanDistance = 0.0; for (unsigned int index = 0; index < vVec1.size(); ++index) ManhattanDistance += std::abs(vVec1[index] - vVec2[index]); return ManhattanDistance; }
true
9de1b49cf1e2a38e9e453a470d0d9091e920c3af
C++
puma3/IA-tictactoe
/util.cpp
UTF-8
11,206
2.875
3
[]
no_license
#include "util.h" Position::Position(size_t _x, size_t _y) : x(_x), y(_y) {} Position::Position(const Position &_other) : x(_other.x), y(_other.y) {} Position Position::operator =(const Position &_other) { x = _other.x; y = _other.y; return *this; } void Position::print() { cout << "x: " << x << ", y: " << y; } Table::Table(bool _turn, size_t n) : m_turn(_turn), m_size(n) { m_table.resize(n*n, unplayed); } Table::Table(Table &other) : m_turn(other.m_turn), m_size(other.m_size) { m_table = other.m_table; } bool Table::marcar(Position _pt) { size_t pos = m_size*_pt.y + _pt.x; if(m_table[pos] != unplayed) return false; m_table[pos] = (m_turn) ? played_op : played_me; m_turn = !m_turn; return true; } void Table::check(float &_w1, float &_w2) { _w1 = _w2 = 0.0; float _step = 1.0 / m_size, _w1_aux, _w1_aux2, _w2_aux, _w2_aux2; int _n_w1 = 0, _n_w2 = 0; //Verificar columnas completas _w1_aux = _w2_aux = 0.0; for(size_t i = 0; i < m_size; ++i) { if(m_table[i] != unplayed) { _w1_aux2 = _w2_aux2 = 0.0; for(size_t j = 0; j < m_size; ++j) { if(m_table[j*m_size + i] != m_table[i]) break; if(m_table[i] == played_me) { if(j == m_size-1) { _w1_aux2 = 1.0; _n_w1++; } else _w1_aux2 += _step; } else { if(j == m_size-1) { _w2_aux2 = 1.0; _n_w2++; } else _w2_aux2 += _step; } } if(_w1_aux2 > _w1_aux) _w1_aux = _w1_aux2; if(_w2_aux2 > _w2_aux) _w2_aux = _w2_aux2; } } if(_w1_aux > _w1) _w1 = _w1_aux; if(_w2_aux > _w2) _w2 = _w2_aux; //Verificar filas completas _w1_aux = _w2_aux = 0.0; for(size_t j = 0; j < m_size; ++j) { if(m_table[j*m_size] != unplayed) { _w1_aux2 = _w2_aux2 = 0.0; for(size_t i = 0; i < m_size; ++i) { if(m_table[j*m_size + i] != m_table[j*m_size]) break; if(m_table[j*m_size] == played_me) { if(i == m_size-1) { _w1_aux2 = 1.0; _n_w1++; } else _w1_aux2 += _step; } else { if(i == m_size-1) { _w2_aux2 = 1.0; _n_w2++; } else _w2_aux2 += _step; } } if(_w1_aux2 > _w1_aux) _w1_aux = _w1_aux2; if(_w2_aux2 > _w2_aux) _w2_aux = _w2_aux2; } } if(_w1_aux > _w1) _w1 = _w1_aux; if(_w2_aux > _w2) _w2 = _w2_aux; //Verificar primera diagonal _w1_aux = _w2_aux = 0.0; if(m_table[0] != unplayed) { _w1_aux2 = _w2_aux2 = 0.0; for(size_t i = 1; i < m_size; ++i){ if(m_table[i*m_size+i] != m_table[0]) break; if(m_table[0] == played_me) { if(i == m_size-1) { _w1_aux2 = 1.0; _n_w1++; } else _w1_aux2 += _step; } else { if(i == m_size-1) { _w2_aux2 = 1.0; _n_w2++; } else _w2_aux2 += _step; } } if(_w1_aux2 > _w1_aux) _w1_aux = _w1_aux2; if(_w2_aux2 > _w2_aux) _w2_aux = _w2_aux2; } if(_w1_aux > _w1) _w1 = _w1_aux; if(_w2_aux > _w2) _w2 = _w2_aux; //Verificar segunda diagonal _w1_aux = _w2_aux = 0.0; size_t _edge = m_size-1; if(m_table[_edge] != unplayed) { _w1_aux2 = _w2_aux2 = 0.0; for(size_t i = 1; i < m_size; ++i) { if(m_table[i*m_size + _edge-i] != m_table[_edge]) break; if(m_table[_edge] == played_me) { if(i == _edge) { _w1_aux2 = 1.0; _n_w1++; } else _w1_aux2 += _step; } else { if(i == _edge) { _w2_aux2 = 1.0; _n_w2++; } else _w2_aux2 += _step; } } if(_w1_aux2 > _w1_aux) _w1_aux = _w1_aux2; if(_w2_aux2 > _w2_aux) _w2_aux = _w2_aux2; } if(_w1_aux > _w1) _w1 = _w1_aux; if(_w2_aux > _w2) _w2 = _w2_aux; if(_w1 == 1.0) _w1 *= _n_w1; if(_w2 == 1.0) _w2 *= _n_w2; } void Table::availablePositions(vector<Position> &_pos) { _pos.clear(); Position tmp; for(size_t i = 0; i < m_size; ++i) { for(size_t j = 0; j < m_size; ++j) { if(m_table[i * m_size + j] == unplayed) { tmp.y = i; tmp.x = j; _pos.push_back(tmp); } } } } float Table::weight() { float w1, w2; check(w1, w2); return (w1-w2)*w1*w1-w2*w2-w2; } GameTreeNode::GameTreeNode(Table &_table, bool _minMax) : m_table(0), m_positions(new vector<Position>), m_weight(0), m_minmax_bool(_minMax) { m_table = new Table(_table); } GameTreeNode::~GameTreeNode() { if(m_positions) { delete m_positions; m_positions = NULL; } for(vector<GameTreeNode*>::iterator it = m_children.begin(); it != m_children.end(); ++it) { delete (*it); } if(m_table) { delete m_table; m_table = NULL; } } void GameTreeNode::buildTree(size_t _level, bool _notRoot) { m_table->availablePositions(*m_positions); if(_level == 0 || m_positions->empty()) { //Alcanzó la profundidad deseada o ya no hay movimientos posibles // if(m_positions.empty()) // cout << "No más movimientos disponibles" << endl; ////*********DEBUG*********//// m_weight = m_table->weight(); cout << "Peso: " << m_weight << endl; ////*********DEBUG*********//// return; } if(_level > 0) { ////*********DEBUG*********//// // cout << "Entro por nivel: " << _level << endl; // cout << "Posiciones (" << m_positions.size() << ") {"; // for(size_t i = 0; i < m_positions.size(); ++i) { // m_positions[i].print(); cout << " | "; // } // cout << "}" << endl; // ////*********DEBUG*********//// GameTreeNode *tmp; for(size_t i = 0; i < m_positions->size(); ++i) { tmp = new GameTreeNode(*m_table, !m_minmax_bool); tmp->playPosition((*m_positions)[i]); tmp->buildTree(_level-1); // cout << "Árbol construido" << endl; ////*********DEBUG*********//// m_children.push_back(tmp); // cout << "Árbol añadido: " << _level << endl; ////*********DEBUG*********//// } // cout << "Sale del nivel: " << _level << endl; ////*********DEBUG*********//// } // cout << "Antes del delete en nivel: " << _level << endl; ////*********DEBUG*********//// delete m_table; if(_notRoot && m_positions) { delete m_positions; m_positions = NULL; } // cout << "Después del delete" << endl; ////*********DEBUG*********//// } void GameTreeNode::playPosition(Position &_pos) { m_table->marcar(_pos); } Position &GameTreeNode::getPositionAt(size_t _pos) { if(_pos < m_positions->size()) return (*m_positions)[_pos]; cout << "No finalizó" << endl; ////*********DEBUG*********//// return (*m_positions)[0]; //MEJOR LANZAR EXCEPCIÓN } size_t GameTreeNode::getMaxMin() { if(m_children.empty()) //Retorna su peso si es que el nodo ya no tiene hijos return 0; //******PUEDE CAUSAR PROBLEMAS SI EL NIVEL DEL ÁRBOL ES 0******// m_children[0]->getMaxMin(); int tmp0 = m_children[0]->m_weight, //Almacena el mayor/menor valor tmp1; size_t pos = 0; for(size_t i = 1; i < m_children.size(); ++i) { m_children[i]->getMaxMin(); tmp1 = m_children[i]->m_weight; if(m_minmax_bool) { if(tmp1 > tmp0) { tmp0 = tmp1; pos = i; } } else { if(tmp1 < tmp0) { tmp0 = tmp1; pos = i; } } } m_weight = tmp0; return pos; } GameTree::GameTree(Table &_root) : m_root(new GameTreeNode(_root)) {} GameTree::~GameTree() { if(m_root) delete m_root; } void GameTree::build(size_t _level) { // cout << "Build Tree" << _level << endl; ////*********DEBUG*********//// m_root->buildTree(_level, false); // cout << "End build tree" << _level << endl; ////*********DEBUG*********//// } Position &GameTree::minMax() { return m_root->getPositionAt(m_root->getMaxMin()); } Game::Game(bool _start_me, size_t _n) : m_gameTable(_start_me,_n) {} void Game::play(Position &_pos) { if(_pos.x < m_gameTable.m_size && _pos.y < m_gameTable.m_size) m_gameTable.marcar(_pos); else return; //RETORNAR UNA EXCEPCIÓN PODRÍA SER MEJOR OPCIÓN //****FUNCIONES ALTERNATIVAS, BORRARLAS CUANDO SE PUEDA****// draw(); status winner = checkWinner(); switch (winner) { case played_me: cout << "I won!" << endl; break; case played_op: cout << "You won!" << endl; break; default: break; } cout << endl; //*********************************************************// } void Game::bestPlay(size_t _sizeOfTree) { GameTree __gameTree(m_gameTable); __gameTree.build(_sizeOfTree); play(__gameTree.minMax()); ////Posición al azar // vector<Position> pos; // m_gameTable.availablePositions(pos); // return pos[rand() % pos.size()]; } status Game::checkWinner() { float w1, w2; m_gameTable.check(w1, w2); if(w1 >= 1.0) return played_me; if(w2 >= 1.0) return played_op; return unplayed; } void Game::draw() { for(size_t i = 0; i < m_gameTable.m_size; ++i) { for(size_t j = 0; j < m_gameTable.m_size; ++j) { status val = m_gameTable.m_table[i*m_gameTable.m_size + j]; switch (val) { case unplayed: cout << "- "; break; case played_me: cout << "x "; break; case played_op: cout << "/ "; break; default: break; } } cout << endl; } }
true
37827c935d9c41dc3747dcda4812c96048fce064
C++
harshitmuhal/InterviewBit
/Backtracking/Permutations.cpp
UTF-8
1,022
3.546875
4
[]
no_license
/* Given a collection of numbers, return all possible permutations. Example: [1,2,3] will have the following permutations: [1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1] NOTE No two entries in the permutation sequence should be the same. For the purpose of this problem, assume that all the numbers in the collection are unique. LINK: https://www.interviewbit.com/problems/permutations/ */ vector<vector<int> > res; void getPerm(vector<int> &A, vector<bool> &used, vector<int> &temp, int n) { if(n==0) { res.push_back(temp); return; } for(int i=0;i<A.size();i++) { if(!used[i]) { used[i]=true; temp.push_back(A[i]); getPerm(A,used,temp,n-1); temp.pop_back(); used[i]=false; } } } vector<vector<int> > Solution::permute(vector<int> &A) { res.clear(); int n = A.size(); vector<bool> used(n,false); vector<int> temp; getPerm(A, used, temp, n); return res; }
true
019d08f441cb8934dd8356a5dd4169f94becca07
C++
finalitylabs/snark-challenge-prover-reference
/ocl_kernels/kernel.hpp
UTF-8
4,784
2.5625
3
[ "MIT" ]
permissive
// #define __CL_ENABLE_EXCEPTIONS #include <CL/cl.h> #define DATA_SIZE (131072) #define limbs_per_elem (12) #include <chrono> #include <typeinfo> #include <unistd.h> #include <string.h> #include <errno.h> class Kernel { public: char* program_source_code; size_t program_source_code_size; int err; // error code returned from api calls char name[128]; size_t global; // global domain size for our calculation size_t local; // local domain size for our calculation cl_device_id device_id; // compute device id cl_context context; // compute context cl_command_queue commands; // compute command queue cl_program program; // compute program cl_device_id *devices; void init(int n) { // OPENCL START char *getcwd(char *buf, size_t size); printf("initializing GPU prover..."); char cwd[1024]; if (getcwd(cwd, sizeof(cwd)) != NULL) { // printf("Current working dir: %s\n", cwd); } else { perror("getcwd() error"); exit(1); } FILE *fp; char *source_str; size_t source_size, program_size; fp = fopen("ocl_kernels/main.cl", "r"); if (!fp) { fprintf(stderr, "could not open program file\n"); exit(1); } program_source_code = (char*)malloc(400000); program_source_code_size = fread(program_source_code, 1, 400000, fp); fclose(fp); // Connect to a compute device // /* get platform number of OpenCL */ cl_uint num_platforms = 0; clGetPlatformIDs (0, NULL, &num_platforms); printf("num_platforms: %d\n", (int)num_platforms); /* allocate a segment of mem space, so as to store supported platform info */ cl_platform_id *platforms = (cl_platform_id *) malloc (num_platforms * sizeof (cl_platform_id)); /* get platform info */ clGetPlatformIDs (num_platforms, platforms, NULL); /* get device number on platform */ cl_uint num_devices = 0; clGetDeviceIDs (platforms[0], CL_DEVICE_TYPE_GPU, 0, NULL, &num_devices); printf("num_devices: %d\n", (int)num_devices); /* allocate a segment of mem space, to store device info, supported by platform */ devices = (cl_device_id *) malloc (num_devices * sizeof (cl_device_id)); /* get device info */ clGetDeviceIDs (platforms[0], CL_DEVICE_TYPE_GPU, num_devices, devices, NULL); // int gpu = 1; // err = clGetDeviceIDs(NULL, gpu ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU, 1, &device_id, NULL); // if (err != CL_SUCCESS) // { // printf("Error: Failed to create a device group!\n"); // return EXIT_FAILURE; // } printf("Device id: %u\n", devices[0]); clGetDeviceInfo(devices[0], CL_DEVICE_NAME, 128, name, NULL); fprintf(stdout, "Created a dispatch queue using the %s\n", name); // Create a compute context // printf("creating context\n"); context = clCreateContext(0, num_devices, devices, NULL, NULL, &err); if (!context) { printf("Error: Failed to create a compute context!\n"); //return EXIT_FAILURE; exit(1); } // Create a command commands // commands = clCreateCommandQueue(context, devices[0], CL_QUEUE_PROFILING_ENABLE, &err); if (!commands) { printf("Error: Failed to create a command commands!\n"); //return EXIT_FAILURE; exit(1); } // Create the compute program from the source buffer // program = clCreateProgramWithSource(context, 1, (const char **) &program_source_code, &program_source_code_size, &err); if (!program) { printf("Error: Failed to create compute program!\n"); //return EXIT_FAILURE; exit(1); } // Build the program executable // printf("building program\n"); char options[] = "-cl-opt-disable"; err = clBuildProgram(program, num_devices, devices, NULL, NULL, NULL); if (err != CL_SUCCESS) { size_t len; char buffer[2048]; //std::cerr << getErrorString(err) << std::endl; printf("Error: Failed to build program executable!\n"); printf ("Message: %s\n",strerror(err)); clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len); exit(1); } // END OCL INIT }; };
true
6c7981b53127c275653be0f1c6f766fbb1d755e4
C++
fjh658/MachOExplorer
/libmoex/node/MachSection.h
UTF-8
5,071
2.828125
3
[ "MIT" ]
permissive
// // Created by everettjf on 2017/4/2. // #ifndef MACHOEXPLORER_MACHSECTION_H #define MACHOEXPLORER_MACHSECTION_H #include "Node.h" MOEX_NAMESPACE_BEGIN class MachHeader; // Section wrapper : unifiy section and section_64 into one struct class moex_section{ private: section *s=nullptr; section_64 *s64=nullptr; bool is64=false; public: moex_section(){} // Init as section struct void Init(section *sect){s=sect;is64=false;} // Init as section_64 struct void Init(section_64 *sect){s64=sect;is64=true;} // Getter for is64 bool Is64()const{return is64;} // Shared for 32bit and 64bit struct char (&sectname())[16]{return is64?s64->sectname:s->sectname;} char (&segname())[16]{return is64?s64->segname:s->segname;} uint32_t &offset(){return is64?s64->offset:s->offset;} uint32_t &align(){return is64?s64->align:s->align;} uint32_t &reloff(){return is64?s64->reloff:s->reloff;} uint32_t &nreloc(){return is64?s64->nreloc:s->nreloc;} uint32_t &flags(){return is64?s64->flags:s->flags;} uint32_t &reserved1(){return is64?s64->reserved1:s->reserved1;} uint32_t &reserved2(){return is64?s64->reserved2:s->reserved2;} // 32bit uint32_t &addr(){return s->addr;} uint32_t &size(){return s->size;} // 64bit uint64_t &addr64(){return s64->addr;} uint64_t &size64(){return s64->size;} uint32_t &reserved3(){return s64->reserved3;} // Get segname as string std::string segment_name() {return std::string(segname(),16).c_str();} // Get sectname as string std::string section_name() {return std::string(sectname(),16).c_str();} // Return either 32bit or 64bit as bigger type uint64_t addr_both(){return is64?s64->addr:(uint64_t)s->addr;} uint64_t size_both(){return is64?s64->size:(uint64_t)s->size;} }; // Internal class for section class MachSectionInternal : public NodeOffset<section>{ public: }; using MachSectionInternalPtr = std::shared_ptr<MachSectionInternal>; // Internal class for section_64 class MachSection64Internal : public NodeOffset<section_64>{ public: }; using MachSection64InternalPtr = std::shared_ptr<MachSection64Internal>; // Section wrapper class MachSection : public Node{ private: MachSectionInternalPtr section_; MachSection64InternalPtr section64_; moex_section sect_; protected: // Corresponding MachO header MachHeader* header_; public: // Getter and setter for header void set_header(MachHeader* header){header_ = header;} MachHeader * header(){return header_;} bool Is64()const{return sect_.Is64();} // Init as section (32bit) section void Init(section *offset,NodeContextPtr & ctx); // Init as section (64bit) section void Init(section_64 *offset,NodeContextPtr & ctx); // Data size for current section type std::size_t DATA_SIZE(){return Is64()?section64_->DATA_SIZE():section_->DATA_SIZE();} // Context for current section NodeContextPtr ctx(){return Is64()?section64_->ctx():section_->ctx();} // Offset for current section void *offset(){return Is64()?(void*)(section64_->offset()):(void*)(section_->offset());} // Get wrapper struct for section moex_section & sect(){return sect_;} // Get addr offset from file beginning uint64_t GetRAW(const void * addr); // Get RVA offset of current section char *GetOffset(); // Get size of current section uint32_t GetSize(); // str : c style string void ForEachAs_S_CSTRING_LITERALS(std::function<void(char* str)> callback); // ptr : can be cast into 4byte,8byte,16byte void ForEachAs_N_BYTE_LITERALS(std::function<void(void* ptr)> callback, size_t unitsize); void ForEachAs_S_4BYTE_LITERALS(std::function<void(void* ptr)> callback); void ForEachAs_S_8BYTE_LITERALS(std::function<void(void* ptr)> callback); void ForEachAs_S_16BYTE_LITERALS(std::function<void(void* ptr)> callback); // ptr : uint64_t when 64bit, uint32_t when 32bit void ForEachAs_POINTERS(std::function<void(void* ptr)> callback); void ForEachAs_S_LITERAL_POINTERS(std::function<void(void* ptr)> callback); void ForEachAs_S_MOD_INIT_FUNC_POINTERS(std::function<void(void* ptr)> callback); void ForEachAs_S_MOD_TERM_FUNC_POINTERS(std::function<void(void* ptr)> callback); void ForEachAs_S_LAZY_SYMBOL_POINTERS(std::function<void(void* ptr)> callback); void ForEachAs_S_NON_LAZY_SYMBOL_POINTERS(std::function<void(void* ptr)> callback); void ForEachAs_S_LAZY_DYLIB_SYMBOL_POINTERS(std::function<void(void* ptr)> callback); void ForEachAs_S_SYMBOL_STUBS(std::function<void(void* str,size_t unitsize)> callback); // ptr : uint64_t when 64bit, uint32_t when 32bit void ForEachAs_ObjC2Pointer(std::function<void(void* ptr)> callback); void ParseAsObjCImageInfo(std::function<void(objc_image_info* ptr)> callback); }; using MachSectionPtr = std::shared_ptr<MachSection>; using MachSectionWeakPtr = std::weak_ptr<MachSection>; MOEX_NAMESPACE_END #endif //MACHOEXPLORER_MACHSECTION_H
true
7e7e668a90f8a2a3862112847543bf8dfd33df36
C++
Heongilee/Inflearn_Cpp_Proj
/TBCppStudy/Chapter4-5/main.cpp
UHC
1,127
3.78125
4
[]
no_license
#include <iostream> #include <iomanip> #include <limits> #include <typeinfo> int main() { using namespace std; /* //Pra1. int a = 123; // 4.0̶ Literal  ڷ ִ ش. cout << typeid(4.0).name() << endl; cout << typeid(a).name() << endl; //Numeric Promotion ( ū ) float a = 1.0f; double d = a; //Numeric Conversion(ū ų ٲ ) double c = 3; short s = 2; */ /* //Pra2. int i = 25; char c = i; cout << static_cast<int>(c) << endl; */ /* //Pra3. double d = 0.123456789; float f = d; cout <<setprecision(12)<< d << endl; */ /* //Pra4. cout << 5u-10u << endl; // 4Ʈ ϴ ڵ int ٲ // 켱 . // int, unsigned int, // long, unsigned long, long long, unsigned long long // float, double, long double */ // int i = int(4.0); //C++ Style Casting int j = (int)4.0; //C Style Casting int k = static_cast<int>(4.0); //ɼ ̴ ... return 0; }
true
00ee1390b9fabe6b4e0ac5a65cc064cffdef536b
C++
ssyuva/Algorithms-And-Data-Structures
/Stacks/08_Evaluate_Postfix_Stack.cpp
UTF-8
2,967
3.90625
4
[]
no_license
//Evaluation of postfix expression using stack //Author: Yuvaraja Subramaniam ( www.linkedin.com/in/yuvaraja ) #include <iostream> #include <stack> #include <vector> #include <string> #include <ctype.h> #include <cmath> using namespace std; int evaluate_postfix_exp_stack(string pexp); int main () { cout << " EVALUATION OF POSTFIX EXPRESSION USING STACK " << endl; cout << "---------------------------------------------------------------------" << endl; vector<string> postfixexprs = { "32^6/43*2+-", "322**232+^+" }; for(string & pexp : postfixexprs) { cout << "Evaluating expression : " << pexp << endl; int result = evaluate_postfix_exp_stack(pexp); cout << "Result : " << result << endl; cout << "---------------------------------------------------------------------" << endl; cout << endl; } } //evaluate postfix expression /* 1. The postfix expression needs to be scanned from the front (left to right) 2. If the incoming char is an operand, push on stack 3. If the incoming char is an operator, the corresponding operands will the top two elements of the stack. Pop the top two operands from the stack, evaluate the expression and push the result back into the stack. 4. Keep scanning the expression in end is reached. When the expression evaluation is complete, there should be only one operand (result) in the stack. Pop the result and print. */ int evaluate_postfix_exp_stack(string pexp) { stack<int> stk; //scan the expression left to right and start evaluating for (int i = 0; i <pexp.length(); i++) { char inchar = pexp[i]; if ( isspace(inchar) ) { continue; } if ( inchar == '+' or inchar == '-' or inchar == '*' or inchar == '/' or inchar == '^' ) { //incoming operator char operatr = inchar; int operand_2 = stk.top(); stk.pop(); int operand_1 = stk.top(); stk.pop(); int result; switch(operatr) { case '+': result = operand_1 + operand_2; break; case '-': result = operand_1 - operand_2; break; case '*': result = operand_1 * operand_2; break; case '/': result = operand_1 / operand_2; break; case '^': result = pow(operand_1, operand_2); break; default: cout << "do not know what to do with operator : " << operatr << endl; } cout << "sub-exp operator : " << operatr << ", operand_1 = " << operand_1 << ", operand_2 = " << operand_2; cout << ", result back to stk = " << result << endl; stk.push(result); //push the result back to the stack } else { //incoming number stk.push( inchar - '0' ); } } //check for only one element in the top of the stack and return result if (stk.size() == 1) { int result = stk.top(); stk.pop(); return result; } else { cout << "error evaluating expression : << " << pexp << endl; return -1; } }
true
f213653c47aebd325e1a9e8efb76c36cd75feb4b
C++
hmeyer/facetype
/typewriter.h
UTF-8
1,340
2.96875
3
[]
no_license
#include <string> enum Boldness { kNormal, kBold }; class BaseTypewriter { public: BaseTypewriter() {} virtual ~BaseTypewriter() {}; virtual void print_char(char, Boldness =kNormal) {} virtual void print_string(const std::string&, Boldness =kNormal) {} virtual void print_align_right(const std::string&, Boldness =kNormal) {} virtual void wait_for_space() {} virtual bool should_stop() const { return false; } }; class Typewriter : public BaseTypewriter { public: Typewriter(); ~Typewriter() override { set_bold(kNormal); enable_mod(false); enable_shift(false); enable_code(false); }; static const int kWidth = 70; static const int kHeight = 55; void print_char(char c, Boldness b=kNormal) override; void print_string(const std::string& s, Boldness b=kNormal) override; void print_align_right(const std::string& s, Boldness b=kNormal) override; void wait_for_space() override; bool should_stop() const override; private: void press_key(int key); void enable_shift(bool enable); void enable_mod(bool enable); void enable_code(bool enable); void reset_lf(); void print_char_base(char c, bool undead=false); void set_bold(Boldness b); Boldness bold_ = kNormal; bool code_enabled_ = false; bool mod_enabled_ = false; bool shift_enabled_ = false; };
true
254af3fa17c129b5d0037713040368f5fe10c7b4
C++
alexandraback/datacollection
/solutions_2705486_1/C++/Lutyj/h.cpp
UTF-8
2,051
2.53125
3
[]
no_license
#include <algorithm> #include <iostream> #include <cstring> #include <cstdio> #include <string> #include <vector> #include <map> #include <set> using namespace std; const int MAXS = 6000; struct tree_node { bool end; tree_node* link[26]; }; char S[MAXS+1]; int N, res[MAXS+1][5]; void go(tree_node* T, int pos, int e0, int ne, int pe) { if (T->end) { int tpe = (pe > 4) ? 4 : pe; if (res[pos][tpe] == -1 || res[pos][tpe] > e0+ne) res[pos][tpe] = e0+ne; } if (pos == N) return; if (T->link[S[pos]] != 0) { go(T->link[S[pos]], pos+1, e0, ne, pe+1); } if (pe >= 4) { for (int c = 0; c < 26; ++c) if (T->link[c] != 0) go(T->link[c], pos+1, e0, ne+1, 0); } } tree_node* root; void solve() { memset(res, -1, sizeof(res)); res[0][4] = 0; for (int start = 1; start <= N; ++start) { for (int pe = 0; pe <= 4; ++pe) { if (res[start-1][pe] == -1) continue; go(root, start-1, res[start-1][pe], 0, pe); } } int mn = 1000000000; for (int pe = 0; pe <= 4; ++pe) if (res[N][pe] != -1 && res[N][pe] < mn) mn = res[N][pe]; printf("%d", mn); } void add_word(tree_node* T, char *s) { if (*s == 0) { T->end = true; return; } if (T->link[*s-'a'] == 0) { tree_node* tmp = new tree_node; tmp->end = false; memset(tmp->link, 0, sizeof(tmp->link)); T->link[*s-'a'] = tmp; } add_word(T->link[*s-'a'], s+1); } int main() { FILE* dict = fopen("garbled_email_dictionary.txt", "r"); char tmp[100]; root = new tree_node; root->end = false; memset(root->link, 0, sizeof(root->link)); while (true) { if (fscanf(dict, "%s", tmp) < 1) break; add_word(root, tmp); } int T; scanf("%d", &T); for (int t = 0; t < T; ++t) { scanf("%s", S); N = strlen(S); for (int i = 0; i < N; ++i) S[i] -= 'a'; printf("Case #%d: ", t+1); solve(); printf("\n"); } return 0; }
true
bb843e1501983cb9aaa7cd741e705355744b1ee0
C++
renedekluis/HBO-ICT_jaar_2_Blok_B_C_plus_plus
/week2-opgave/windowHandler.hpp
UTF-8
594
2.515625
3
[]
no_license
#pragma once #include <iostream> #include <SFML\Graphics.hpp> #include "ball.hpp" #include "player.hpp" const struct { sf::Keyboard::Key Key; float x; float y; }actions[] = { { sf::Keyboard::Left, -1, 0 }, { sf::Keyboard::Right, +1, 0 }, { sf::Keyboard::Up, 0, -1 }, { sf::Keyboard::Down, 0, +1 } }; class windowHandler { private: sf::RenderWindow & window; sf::FloatRect player_bounds; sf::FloatRect ball_bounds; player my_player; ball my_ball; public: windowHandler(sf::RenderWindow & window); void update(); void draw(); void check_collision(); void move(); };
true
bc714e1fddc4a21d42ee2a2b40c1211257fd317f
C++
Markweese/CreativeCoding
/Song Map/src/ofApp.h
UTF-8
1,781
2.75
3
[]
no_license
#pragma once #include "ofMain.h" struct State; class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); // this get's called when a state was clicked void stateClicked(string name); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); void playRandomTrack(string dirPath); void updateImageRect(); void generateStates(); //scaling variables and images ofImage key; ofImage soundImage; float imageScaleX; float imageScaleY; ofRectangle imageRect; //player, polyline, color identifier, and directory declarators. ofSoundPlayer NewNoise; ofPolyline line; ofColor colorAtXY; ofDirectory dir; //stores file path string name for soundtracks string path; //stores name data to be displayed on screen ofTrueTypeFont stampFont; //stores song name from getName() function and displays it on screen string songName; vector<State> states; }; struct State { void clear() { name = ""; line.clear(); } void draw() { line.draw(); } void mousePressed(int x, int y) { if(line.inside(x, y)) { ofApp *app = (ofApp *)ofGetAppPtr(); app->stateClicked(name); } } string name; ofPolyline line; };
true