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
de998bb64512ca0bcc1c6da332e4eb711c874ea9
C++
irfansofyana/cp-codes
/03 - Online Judges/codeforces/B.code_parsing,cpp.cpp
UTF-8
785
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; string s; int n,i,j; int idx1,idx2; bool cek1,cek2; bool simpulan; int main(){ cin.tie(0) ios_base::sync_with_stdio(0); cin>>s; idx1=s.find("yx",0); simpulan=true; while (simpulan){ cek1=true; cek2=true; idx1=s.find("yx",0); while (idx1>=0 && idx1<s.length()){ s.erase(idx1,2); s.insert(idx1,"xy"); idx1=s.find("yx",idx1+1); } idx2=s.find("xy",0); while (idx2>=0 && idx2<s.length()){ s.erase(idx2,2); idx2=s.find("xy",idx2+1); } if (s.length()==1) simpulan=false; else{ if (!(s.find("yx")>=0 && s.find("yx")<s.length())) cek1=false; if (!(s.find("xy")>=0 && s.find("xy")<s.length())) cek2=false; simpulan=cek1||cek2; } } cout<<s<<endl; return 0; }
true
9a2326cd50c39c6701fee836ba5313979e38ce4d
C++
IIT-Lab/HetSNets
/Computing.cpp
UTF-8
1,016
2.875
3
[]
no_license
// // Created by lee on 17-9-27. // #include <math.h> #include "Computing.h" sinrComputing* sinrComputing::_Instance = nullptr; sinrComputing::sinrComputing() { this->interferencePow = 0; this->noisePow = 0; this->signalPow = 0; this->sinr = 0; } sinrComputing& sinrComputing::GetInstance() { if (_Instance == nullptr) { _Instance = new sinrComputing(); } return *_Instance; } void sinrComputing::addSignalPow(double _signalPow) { signalPow += _signalPow; } void sinrComputing::addNoisePow(double _noisePow) { noisePow += _noisePow; } void sinrComputing::addInterferencePow(double _interferencePow) { interferencePow += _interferencePow; } double sinrComputing::getSinr() { return sinr; } void sinrComputing::updateSinr() { sinr = signalPow / (noisePow + interferencePow); sinr = 10 * log10(sinr);//dB值 } void sinrComputing::clearSinr() { this->interferencePow = 0; this->noisePow = 0; this->signalPow = 0; this->sinr = 0; }
true
65173c281068aa17dd96d2c3d56ce31946a48c5c
C++
siyuanchai1999/CProgrammingLangPractice
/Chapter 1-2/2.10.cpp
UTF-8
207
3.03125
3
[]
no_license
#include <stdio.h> int bitcount(unsigned x); int main(){ printf("%d", bitcount(127)); } int bitcount(unsigned x){ int count = 0; while(x!=0){ count++; x &= (x-1); } return count; }
true
8f8ab1496b2644ec69063b3445c01e96068e4e44
C++
andreasfertig/cppinsights
/tests/ExceptionTest.cpp
UTF-8
283
2.765625
3
[ "MIT" ]
permissive
#include <stdexcept> int main() { try { int x = 2; throw std::logic_error("Error"); } catch (std::runtime_error& e){ return -1; } catch (std::logic_error& e){ return -1; } catch(...) { return -3; } return 0; }
true
c3e9f1edbd130e02c917e01b3736cebb1dc0f929
C++
SoshinK/Akinator
/Tree.h
UTF-8
10,389
2.90625
3
[]
no_license
#ifndef TREE_H #define TREE_H #include <cstdio> #include <cstring> #include <cassert> #include <cstdlib> //!~~~~NODE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class Node { public: Node(); explicit Node(const char* data); ~Node(); char* data(); //! returns data Node* right(); //! returns right leaf Node* left(); //! .... Node* parent(); //! returns parent void setright(Node* right); //! change/set leaves void setparent(Node* parent); void setleft(Node* left); void setdata(const char* data); //! change/set data void kill(FILE*); //! calls delete for leaves(used by visitor in //! Tree::~Tree()) void dotprint(FILE* out); //! put in *.gv file node descrition //! (used by visitor in Tree::dotdump()) void nodeprint(FILE* out); //! writes in file current node void dump(FILE*); //! dumping current node(used by visitor in //! Tree::dump()) void fnodescan(FILE*); //! reads from file current node private: Node* Parent_; Node* Left_; Node* Right_; char* Data_; }; //!macro to verify data #define IS_CORRECT \ if(!Data_) \ { \ printf("Node:ERROR:Lost data\n"); \ dump(NULL); \ assert(0); \ } Node::Node(): Parent_(NULL), Left_(NULL), Right_(NULL), Data_(NULL) {} Node::Node(const char* data): Parent_(NULL), Left_(NULL), Right_(NULL) { Data_ = new char[strlen(data)]; Data_ = strcpy(Data_, data); IS_CORRECT; } Node::~Node() { Parent_ = NULL; Left_ = NULL; Right_ = NULL; if(!Data_)delete [] Data_; } void Node::kill(FILE*) { if(left())delete left(); if(right())delete right(); } #define NODEPRINT(leaf) \ if(leaf)leaf->nodeprint(out); \ else fprintf(out, "N"); void Node::nodeprint(FILE* out) { fprintf(out, "("); fprintf(out, "%c%s%c", '\'', Data_, '\''); NODEPRINT(Left_); NODEPRINT(Right_); fprintf(out, ")"); } #undef NODEPRINT char* Node::data(){return Data_; IS_CORRECT;} Node* Node::right(){return Right_; IS_CORRECT;} Node* Node::left(){return Left_; IS_CORRECT;} Node* Node::parent(){return Parent_; IS_CORRECT;} void Node::setright(Node* right) { Right_ = right; right->setparent(this); IS_CORRECT; } void Node::setparent(Node* parent) { Parent_ = parent; IS_CORRECT; } void Node::setleft(Node* left) { Left_ = left; left->setparent(this); IS_CORRECT; } void Node::setdata(const char* newdata) { delete [] Data_; Data_ = new char [strlen(newdata)]; Data_ = strcpy(Data_, newdata); IS_CORRECT; } void Node::dump(FILE* f) { printf("~~~~\n"); printf("Node:Dump has been called\n"); printf("That node = %p\n", this); if(Data_)printf("Data_ = %s\n", Data_); printf("Parent_ = %p\n", Parent_); printf("Left_ leaf = %p\n", Left_); printf("Right_ leaf = %p\n", Right_); printf("~~~~\n"); //..... } void Node::dotprint(FILE* in) { fprintf(in, "TreeNode_%p [label = ", this); fprintf(in, "%c", '"'); fprintf(in, "TreeNode_%p\\l parent = %p\\l data = '%s'\\l left = %p\\l right = %p", this, parent(), data(), left(), right()); fprintf(in, "%c]\n", '"'); if(left())fprintf(in, "TreeNode_%p->TreeNode_%p\n", this, left()); if(right())fprintf(in, "TreeNode_%p->TreeNode_%p\n", this, right()); } #define IFEOF \ if(c == EOF) \ { \ printf("Node:fnodescan:getstr:ERROR:bad inputfile(EOF reached)\n"); \ assert(0); \ } char* getstr(FILE* in) //! local function to read data { int size = 20; int index = 0; char c = 1; char* str = (char*)malloc(sizeof(char) * size); while(c != '\'') { c = fgetc(in); IFEOF; } c = fgetc(in); IFEOF; while(c != '\'') { str[index++] = c; if(index == size) { size *= 2; str = (char*)realloc(str, sizeof(char) * size); } c = fgetc(in); IFEOF; } str[index] = '\0'; return str; } #define LEAF(side) \ c = fgetc(file); \ if(c == '(') \ { \ fseek(file, -1, SEEK_CUR); \ Node* side = new Node; \ side->fnodescan(file); \ set##side(side); \ } \ else if(c != 'N') \ { \ printf("Node:fnodscan:ERROR:bad input(wrong symbol)\n"); \ assert(0); \ } void Node::fnodescan(FILE* file) { char c = fgetc(file); if(c != '(') { printf("Node:fnodscan:ERROR:bad input(brace is lost)\n"); assert(0); } char* str = getstr(file); Data_ = str; LEAF(left); LEAF(right); c = fgetc(file); if(c != ')') { printf("Node:fnodscan:ERROR:bad input(brace is lost)\n"); assert(0); } } #undef LEAF #undef IS_CORRECT //!~~~~/NODE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //!~~~~TREE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ enum TRAVERSAL //! taversal modes { PRE_ORDER, //! data - left leaf - right leaf IN_ORDER, //! leaft leaf - data - right leaf POST_ORDER, //! leaft leaf - right leaf - data }; class Tree { public: Tree(); Tree(Node* root); explicit Tree(const char* filename); ~Tree(); Node* Root(); //! return root Node* getcursor(); //! returns current cursor position bool mcleft(); //! moves cursor to the left leaf bool mcright(); bool mcabove(); //! moves to parent bool mcroot(); bool mcnode(Node* dest); void dump(); bool dotdump(const char* filename); //! put commands in *.gv file for Dotter void addl(Node* newnode); //! add new left leaf(old one //! wont be deleted) void addr(Node* newnode); bool fscan(const char* filename); //! reads tree from the file bool fprint(const char* filename); //! writes tree to the file void visitor/*your mum*/(TRAVERSAL mode, //! visits every node according to Node* curnode, void (Node::*func)(FILE*),//! traversal mode FILE* file); Node* search(const char* data); //! seatch node with specified data, //! put cursor on it and returns its address private: Node* Root_; //! Root Node* Cursor_; //! Cursor (thx, Cap) }; Tree::Tree(): Root_(new Node), Cursor_(Root_) {} Tree::Tree(Node* root): Root_(root), Cursor_(Root_) {} Tree::Tree(const char* filename): Root_(new Node), Cursor_(new Node) { if(!fscan(filename)) { printf("Tree:ERROR:cant open/read input file"); dump(); assert(0); } Root_ = Cursor_; } Tree::~Tree() { visitor(POST_ORDER, Root_, &Node::kill, NULL); Root_->~Node(); Cursor_->~Node(); // } void Tree::dump() { printf("========\n"); printf("Root_ = %p\n", Root_); printf("Cursor_ = %p\n", Cursor_); visitor(PRE_ORDER, Root_, &Node::dump, NULL); printf("========\n"); } bool Tree::dotdump(const char*filename) { FILE* file = fopen(filename, "wt"); if(!file) { printf("Tree:dotdump:ERROR:cant open file\n"); return 0; } fprintf(file, "digraph G{\ngraph [ dpi = 300]\n"); visitor(POST_ORDER, Cursor_, &Node::dotprint, file); fprintf(file, "}"); fclose(file); return true; } Node* Tree::Root() { return Root_; } bool Tree::fprint(const char* filename) { FILE* file = fopen(filename, "wt"); if(!file) { printf("Tree:fprint:ERROR:cant open file\n"); return false; } Cursor_->nodeprint(file); fclose(file); return true; } bool Tree::fscan(const char* filename) { FILE* file = fopen(filename, "rt"); if(!file) { printf("Tree:fscan:ERROR:cant open/read input file\n"); return false; } Cursor_->fnodescan(file); fclose(file); return true; } void Tree::addr(Node* newnode) { Cursor_->setright(newnode); } void Tree::addl(Node* newnode) { Cursor_->setleft(newnode); } Node* Tree::getcursor(){return Cursor_;} bool Tree::mcleft() { if(Cursor_->left()) { Cursor_ = Cursor_->left(); return true; } return false; } bool Tree::mcright() { if(Cursor_->right()) { Cursor_ = Cursor_->right(); return true; } return false; } bool Tree::mcabove() { if(Cursor_->parent()) { Cursor_ = Cursor_->parent(); return true; } return false; } bool Tree::mcroot() { if(!Root_)return false; Cursor_ = Root_; } bool Tree::mcnode(Node* dest) { Cursor_ = dest; } #define LEFT \ if(curnode->left())visitor(mode, curnode->left(), func, file); #define RIGHT \ if(curnode->right())visitor(mode, curnode->right(), func, file); void Tree::visitor(TRAVERSAL mode, Node* curnode, void (Node::*func)(FILE* f), FILE* file) { switch(mode) { case PRE_ORDER: (curnode->*func)(file); LEFT; RIGHT; break; case IN_ORDER: LEFT; (curnode->*func)(file); RIGHT; break; case POST_ORDER: LEFT; RIGHT; (curnode->*func)(file); break; default: break; } } #undef LEFT #undef RIGHT Node* Tree::search(const char* data) { if(!data)return NULL; if(!strcmp(data, Cursor_->data()))return Cursor_; Node* wanted = NULL; if(Cursor_->left()) { mcleft(); wanted = search(data); if(wanted)return wanted; } if(Cursor_->right()) { mcright(); wanted = search(data); if(wanted)return wanted; } mcabove(); return NULL; } //!~~~~/TREE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #endif
true
cdda42ac9ee9ffb4892d6cbb066cb2cb519e97c4
C++
guilhermealbm/CC-UFMG
/pds2/tp - Full Dress Chess/tests/test_rainha.cpp
UTF-8
1,840
3.203125
3
[]
no_license
#include "../third_party/doctest.h" #include "../include/queen.h" TEST_CASE("Teste 1: Testando o Construtor"){ CHECK_NOTHROW(Queen(1, 1, "Branca")); } TEST_CASE("Teste 2: Testando Movimento na Vertical"){ Queen q(1, 1, "Branca"); CHECK(q.movimentValidator(2, 1)); //movimento válido CHECK(q.movimentValidator(8, 1)); //movimento válido CHECK(q.movimentValidator(5, 1)); //movimento válido } TEST_CASE("Teste 3: Testando Movimento na Horizontal"){ Queen q(1, 1, "Branca"); CHECK(q.movimentValidator(1, 2)); //movimento válido CHECK(q.movimentValidator(1, 5)); //movimento válido CHECK(q.movimentValidator(1, 8)); //movimento válido } TEST_CASE("Teste 4: Testando Movimento na Diagonal"){ Queen q(4, 2, "Branca"); CHECK(q.movimentValidator(3, 1)); //movimento válido CHECK(q.movimentValidator(5, 1)); //movimento válido CHECK(q.movimentValidator(8, 6)); //movimento válido CHECK(q.movimentValidator(2, 4)); //movimento válido CHECK(q.movimentValidator(5, 3)); //movimento válido } TEST_CASE("Teste 5: Testando Movimentos Inválidos"){ Queen q(4, 2, "Branca"); CHECK(!q.movimentValidator(1, 1)); //movimento inválido - fora de reta ou diagonal CHECK(!q.movimentValidator(8, 8)); //movimento inválido - fora de reta ou diagonal CHECK(!q.movimentValidator(6, 5)); //movimento inválido - fora de reta ou diagonal CHECK(!q.movimentValidator(2, 3)); //movimento inválido - fora de reta ou diagonal CHECK(!q.movimentValidator(4, 2)); //movimento inválido - parado } TEST_CASE("Teste 6: Testando Nome e Cor"){ Queen q(4, 5, "Preta"); CHECK(q.getName() == "queen"); CHECK(q.getColor() == "Preta"); Queen q2(5, 4, "Branca"); CHECK(q2.getName() == "queen"); CHECK(q2.getColor() == "Branca"); }
true
fe57b539fc15dcec0c176adb5a3a28be092bd54f
C++
JackCode/Early_Objects_Practice
/ch_8_arrays/13_drink_machine_simulator/drink_machine.cpp
UTF-8
2,641
3.4375
3
[]
no_license
#include "drink_machine.h" #include <iomanip> #include <iostream> #include <string> using namespace std; DrinkMachine::DrinkMachine() { inventory[0].name = "Cola"; inventory[0].price = 0.75; inventory[0].qty = 20; inventory[1].name = "Root Beer"; inventory[1].price = 0.75; inventory[1].qty = 20; inventory[2].name = "Orange Soda"; inventory[2].price = 0.75; inventory[2].qty = 20; inventory[3].name = "Grape Soda"; inventory[3].price = 0.75; inventory[3].qty = 20; inventory[4].name = "Bottled water"; inventory[4].price = 1.00; inventory[4].qty = 20; } void DrinkMachine::display_choices() { cout << " Drink Name" << setw(25) << "Cost" << setw(25) << "Number in Machine" << endl; cout << "****************************************************************" << endl; for (int i = 0; i < 5; i++) { cout << (i+1) << ". " << left << setw(22) << inventory[i].name << right << setw(12) << setprecision(2) << fixed << inventory[i].price << setprecision(0) << setw(18) << inventory[i].qty << endl; } cout << "****************************************************************" << endl; } void DrinkMachine::buy_drink(const int& choice, const double& inserted) { double change; change = input_money(choice, inserted); cout << setprecision(2) << fixed << "-- CHANGE: $" << change << " --\n"; } double DrinkMachine::input_money(const int& choice, const double& inserted) { char confirm; // Return money if sold out if(inventory[choice-1].qty == 0) { cout << "-- SOLD OUT --\n"; return inserted; } // Confirm Purchase cout << "You want to purchase a " << inventory[choice-1].name << "(Y/n)? "; cin >> confirm; if(confirm == 'Y' || confirm == 'y') { if (inserted < inventory[choice-1].price) { cout << "-- NOT ENOUGH FUNDS --\n"; return inserted; } inventory[choice-1].qty--; cout << "-- SODA DELIVERED --\n"; return (inserted - inventory[choice-1].price); } else { // Return money if not confirmed return inserted; } } void DrinkMachine::daily_report() { system("clear"); double total = 0; for (int i = 0; i < 5; i++) { cout << inventory[i].name << ": " << inventory[i].qty << " remaining\n"; total += (20 - inventory[i].qty) * inventory[i].price; } cout << "Money collected: $" << total << endl << endl; }
true
e25f8e9eb030b52878bc2a0e5989bf48a1524894
C++
leyarotheconquerer/UrhoEditor
/EditorLib/Controls/DataGridWidget.h
UTF-8
3,928
2.765625
3
[ "MIT" ]
permissive
#pragma once #include <EditorLib/Selectron.h> #include <QWidget> #include <QStackedLayout> #include <QTableWidget> #include <vector> #include <set> #include <string> #include <memory> class DocumentBase; /// Control that displays the values of selected objects in a datagrid format. /// Enables relatively easy comparisons of values and editing to match/differ. class DataGridWidget : public QWidget, public SelectronLinked { Q_OBJECT public: /// Construct. DataGridWidget(); /// Destruct. virtual ~DataGridWidget(); /// Setup signals/slots for selection changes. virtual void Link(Selectron* sel) override; /// DataSource based strategy handling for the datagrid's population and cell management. struct DataSourceHandler { /// Implementation should return true for DataSources that it can handle. Should perform any required conversions (ie. Euler -> Quat). virtual bool CanHandleDataSource(std::shared_ptr<DataSource> dataSource) const = 0; /// Returns true if the given column can be shown, or false if not ... such as for properties that have no viable way to edit as plain-text. virtual bool CanShow(std::shared_ptr<DataSource> dataSource, const std::string& column) const { return true; } /// Returns a list of all columns in the datasource. virtual std::vector<std::string> GetColumns(std::shared_ptr<DataSource> dataSource) const = 0; /// Returns true if the given datafield is editable in text form. virtual bool CanSetText(std::shared_ptr<DataSource> dataSource, const std::string& column) const { return true; } /// Implementation sets a value from text for a column/property. Should perform any required conversions (ie. Quat -> Euler). virtual void FromText(std::shared_ptr<DataSource> dataSoruce, const std::string& column, const std::string& textValue) = 0; /// Creates a widget to use instead of plain-text in the cell. virtual QWidget* CreateWidget(std::shared_ptr<DataSource> dataSource, const std::string& column) const { return 0x0; } /// Implementation gets the text value of a column. virtual QString ToText(std::shared_ptr<DataSource> dataSource, const std::string& column) const = 0; }; void AddHandler(DataSourceHandler* handler) { handlers_.push_back(handler); } private slots: /// Flush. void ActiveDocumentChanged(DocumentBase* newDoc, DocumentBase* oldDoc); /// Redertimine the grid layout. void SelectionChanged(void* source, Selectron* sel); /// Update changes to the data of selected objects. void SelectionDataChanged(void* source, Selectron* sel, unsigned hash); /// Update properties from text cell changes. void DataChanged(QTableWidgetItem* item); protected: virtual void showEvent(QShowEvent*) Q_DECL_OVERRIDE; virtual void hideEvent(QHideEvent*) Q_DECL_OVERRIDE; DataSourceHandler* GetHandlerFor(std::shared_ptr<DataSource> dataSource); private: /// Sets the layout stack to display the "Incompatible selections" page. void SetToIncompatible(); /// Sets the layout stack to display the "Nothing selected" page. void SetToNoSelection(); /// Only contains 3 pages, "nothing selected," "Incompatible objects selected", and the datatable itself QStackedLayout* stack_; /// Table-grid used for cell display. QTableWidget* table_; /// List of the columns in left-to-right order, based on the order in which their names were first encountered. std::vector<std::string> appearanceOrder_; /// List of the columns to be displayed that have passed filtering. std::set<std::string> filtered_; /// List of the datasources used for each row of the datagrid. std::vector< std::shared_ptr<DataSource> > dataSources_; /// List of datasource handlers. std::vector<DataSourceHandler*> handlers_; bool hidden_ = true; };
true
52ec83e8cd9e75a219e45f17c9fdb3ada479023a
C++
kelaicai/ADT_CPP
/张彪/20180415/Stack.cpp
GB18030
1,840
3.359375
3
[]
no_license
#include "Stack.h" #include<iostream> using namespace std; /* member vars int *mpstack; int mtop; int msize; */ //ĬϴĹ캯 SqStack::SqStack(int size=10) { msize =size; mtop = -1; mpstack = new int[msize]; } // SqStack::~SqStack() { delete[] mpstack; mtop = -1; msize = 0; } //캯 SqStack::SqStack(const SqStack &src) { msize = src.msize; delete[] mpstack; int* tmp = new int[msize]; mpstack = tmp; for (int i = 0; i < msize; i++) { mpstack[i] = src.mpstack[i]; } } SqStack SqStack::operator=(const SqStack &src) { if (this == &src) //Ըֵ { return *this; } //srcmsizeܱthismsizeҲС msize = src.msize; delete[] mpstack; int *ptr = new int[msize]; mpstack = ptr; ptr = NULL; for (int i = 0; i < msize; i++) { mpstack[i] = src.mpstack[i]; } return *this; } //ջ void SqStack::push(int val) { if (full()) { cout << "stack is full" << endl; //resizeStack(): return; } mpstack[++mtop] = val; } //ջ void SqStack::pop() { if (empty()) { cout << "ջѾ" << endl; return; } mtop--; } //ȡջԪ int SqStack::top() { if (empty()) { throw "stack is empty"; } return mpstack[mtop]; } //жջ bool SqStack::empty() { return mtop == -1; } //жջ bool SqStack::full() { return mtop == msize - 1; } void SqStack::showStack() { cout << "ǰ˳ջе ջ---ջ" << endl; if (empty()) { cout << "ǰջΪ" << endl; return; } for (int i = 0; i <= mtop; i++) { cout << mpstack[i] << " "; } cout << endl; } /**/ void SqStack::resizeStack() { int size =msize*2; int *tmp = new int[size]; for (int i = 0; i < size/2; i++) { tmp[i] = mpstack[i]; } delete[] mpstack; mpstack = tmp; msize = size; }
true
82a084a18fdf36123b7598ff7120ce0177a46301
C++
afnanetman/cipher4
/Baconian(20170054).cpp
WINDOWS-1252
2,410
3.125
3
[]
no_license
#include <iostream> #include<bits/stdc++.h> // FCI Programming 1 2018 - Assignment 2 // Program Name: Baconian(20170054).cpp // Last Modification Date: 04/03/2018 // Author and ID and Group: 20170054 G6 // Teaching Assistant: Eng Khadega and Eng Mohamed Atta // Purpose:Cipher problem using namespace std; int main() { string arr1[27]= {"aaaaa","aaaab","aaaba","aaabb","aabaa","aabab","aabba","aabbb","abaaa","abaab","ababa","ababb","abbaa","abbab","abbba","abbbb","baaaa","baaab","baaba","baabb","babaa","babab","babba","babbb","bbaaa","bbaab"," "}; char arr2[27]= {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' '}; char arr3[27]= {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' '}; string sentence; while (true) { char typ; cout << "Enter E for Encryption or D for Decryption :" ; cin >> typ; if (typ=='E'||typ=='e') { cout <<"Enter the sentence :"; cin.ignore(); getline(cin,sentence); for (int i=0; i<sentence.size(); i++) { for (int j=0; j<27; j++) { if (sentence[i]==arr2[j]||sentence[i]==arr3[j]) { cout<<arr1[j]; } } } } else if (typ=='D'||typ=='d') { cout <<"Enter the sentence :"; cin.ignore(); getline(cin,sentence); for (int i=0; i<=sentence.size(); i=i+5) { string y; if (sentence[i]==' ') { cout <<" "; i++; } y+=sentence[i]; y+=sentence[i+1]; y+=sentence[i+2]; y+=sentence[i+3]; y+=sentence[i+4]; for (int j=0; j<27; j++) { if (y==arr1[j]) { cout<<arr2[j]; break; } } } } else { cout <<"Try Again"<<endl; continue; } break; } }
true
315157c9e60b0506cf81776028289a295c0b1056
C++
alpox/CPP-Exercises
/7.4/driver.cpp
UTF-8
472
2.84375
3
[ "MIT" ]
permissive
// // Created by Rafael Kallis on 29.12.16. // #include "locker.h" #include <iostream> #include <unistd.h> int main() { try { Locker lock("my_file"); // Locker not_existing_file_lock("not_existing_file"); // Locker locked_file_lock("my_file"); } catch (const FileNotFoundException &e) { std::cout << e.what() << std::endl; } catch (const FileLockedException &e) { std::cout << e.what() << std::endl; } return 0; }
true
b99c41d60baa95047eee68b8aa976e76e60b6757
C++
mporcheron/bethyw
/autograder/testus3.cpp
UTF-8
1,887
2.703125
3
[]
no_license
/* +---------------------------------------+ | BETH YW? WELSH GOVERNMENT DATA PARSER | +---------------------------------------+ AUTHOR: Dr Martin Porcheron Catch2 test script — https://github.com/catchorg/Catch2 Catch2 is licensed under the BOOST license. */ #include "lib_catch.hpp" #include <fstream> #include "datasets.h" #include "areas.h" #include "area.h" SCENARIO( "an Areas instance can contain Area instances [extended]", "[Areas][contain][extended]" ) { GIVEN( "a newly constructed Areas" ) { Areas areas; AND_GIVEN( "two newly constructed Area instances with the same local authority codes ('W06000011') but overlapping Measures" ) { std::string localAuthorityCode = "W06000011"; Area area1(localAuthorityCode); Area area2(localAuthorityCode); Area areaCombined(localAuthorityCode); const std::string codename1 = "pop"; const std::string label1 = "Population"; Measure measure1(codename1, label1); const std::string codename2 = "dens"; const std::string label2 = "Population density"; Measure measure2(codename2, label2); area1.setMeasure(codename1, measure1); area2.setMeasure(codename2, measure2); areaCombined.setMeasure(codename1, measure1); areaCombined.setMeasure(codename2, measure2); THEN( "the Area instances can be emplaced in the Areas instance without exception" ) { REQUIRE_NOTHROW( areas.setArea(localAuthorityCode, area1) ); REQUIRE_NOTHROW( areas.setArea(localAuthorityCode, area2) ); AND_THEN( "the names of the second Area instances will overwrite the first" ) { Area &newArea = areas.getArea(localAuthorityCode); REQUIRE( newArea == areaCombined ); } // AND_THEN } // THEN } // AND_GIVEN } // THEN } // SCENARIO
true
f63036e655249aed967a2de1037d36f8db84f35b
C++
cdwood/Programming-Foundations-I
/lab12c.cpp
UTF-8
3,002
3.609375
4
[]
no_license
#include <string> #include <fstream> #include <iostream> using namespace std; class Student { public: Student(); Student(const Student & original); ~Student(); void set(const int uaid, const string name, const double gpa); void get(int & uaid, string & name, double & gpa) const; void print() const; void read(); private: int mUaid; string mName; double mGpa; }; Student::Student() { mUaid = 0; mName = "none"; mGpa = 0.0; } Student::Student(const Student & original) { mUaid = original.mUaid; mName = original.mName; mGpa = original.mGpa; } Student::~Student() { } void Student::set(const int uaid, const string name, const double gpa) { mUaid = uaid; mName = name; mGpa = gpa; if (mGpa < 0.0) mGpa = 0.0; else if (mGpa > 4.0) mGpa = 4.0; } void Student::get(int &uaid, string & name, double &gpa) const { uaid = mUaid; name = mName; gpa = mGpa; } void Student::print() const { cout << mUaid << " " << mName << " " << mGpa << endl; } void Student::read() { cin >> mUaid >> mName >> mGpa; if (mGpa < 0.0) mGpa = 0.0; else if (mGpa > 4.0) mGpa = 4.0; } class Course { public: Course(const int count=0); Course(const Course & original); ~Course(); void print() const; void read(); void topStudents(double gpa); private: static const int MAX_STUDENTS = 100; Student mStudents[MAX_STUDENTS]; int mNumStudents; }; Course::Course(const int count) { cout << "Constructor" << endl; mNumStudents = count; } Course::Course(const Course & original) { cout << "Copy constructor" << endl; mNumStudents = original.mNumStudents; for (int i = 0; i < mNumStudents; i++) { mStudents[i] = original.mStudents[i]; } } Course::~Course() { cout << "Destructor" << endl; } void Course::print() const { cout << "Print" << endl; for(int i = 0; i < mNumStudents; i++) { mStudents[i].print(); } } void Course::read() { cout << "Read" << endl; for(int i = 0; i< mNumStudents; i++) { mStudents[i].read(); } } void Course::topStudents(double gpa) { cout << "topStudents" << endl; int id; string name; double mGpa; for(int i = 0; i < mNumStudents; i++) { mStudents[i].get(id, name, mGpa); if(mGpa >= gpa) { mStudents[i].print(); } } } int main() { cout << "Testing Student class\n"; Student student1; student1.set(1234, "John", 2.5); student1.print(); cout << "Testing Course class\n"; Course course(5); course.print(); course.read(); course.print(); course.topStudents(3.5); return 0; } /* Output: cdwood@turing:~/CSCE2004/labs/lab12$ ./lab12c < Students.txt Testing Student class 1234 John 2.5 Testing Course class Constructor Print 0 none 0 0 none 0 0 none 0 0 none 0 0 none 0 Read Print 1234 Susan 3.9 2345 John 3.2 3456 Laura 3.8 4567 Brian 3.5 5678 David 3.1 topStudents 1234 Susan 3.9 3456 Laura 3.8 4567 Brian 3.5 Destructor */
true
8d164cfe2b7311da22eacac2d46b05e9708ef17d
C++
fermi-lat/irfs
/irfInterface/irfInterface/IrfsFactory.h
UTF-8
1,168
2.578125
3
[ "BSD-3-Clause" ]
permissive
/** * @file IrfsFactory.h * @brief Generate Irf objects using Prototypes. * @author J. Chiang * * $Header$ */ #ifndef irfInterface_IrfsFactory_h #define irfInterface_IrfsFactory_h #include <string> #include <map> #include <vector> #include <string> #include "st_facilities/libStApiExports.h" #include "irfInterface/Irfs.h" namespace irfInterface { /** * @class IrfsFactory * * @brief Factory to supply Irf prototype objects. * * @author J. Chiang * */ #ifndef SWIG class SCIENCETOOLS_API IrfsFactory { #else class IrfsFactory { #endif public: Irfs * create(const std::string & name) const; void addIrfs(const std::string & name, Irfs * irfs, bool verbose=false); void getIrfsNames(std::vector<std::string> & names) const; const std::vector<std::string> & irfNames() const { return m_irfNames; } static IrfsFactory * instance(); static void delete_instance(); protected: IrfsFactory() {} ~IrfsFactory(); private: std::map<std::string, Irfs *> m_prototypes; std::vector<std::string> m_irfNames; static IrfsFactory * s_instance; }; } // namespace irfInterface #endif // irfInterface_IrfsFactory_h
true
889bc222f115d041fd608dfc56df32720f05ebee
C++
frinkr/FontViewer
/FontX/FXFTPrivate.cpp
UTF-8
5,759
2.515625
3
[ "MIT" ]
permissive
#include "FXFTPrivate.h" #include "FXFS.h" #if FX_WIN #include <stdio.h> #include <locale> #include <codecvt> #endif namespace { #if FX_WIN // adapted from freetype/ftsystem.c unsigned long streamRead( FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count ) { FILE* file; if ( !count && offset > stream->size ) return 1; file = (FILE*)stream->descriptor.pointer; if ( stream->pos != offset ) fseek( file, (long)offset, SEEK_SET ); return (unsigned long)fread( buffer, 1, count, file ); } // adapted from freetype/ftsystem.c void streamClose( FT_Stream stream ) { FILE * file = (FILE*)stream->descriptor.pointer; if (file) fclose(file); free(stream->pathname.pointer); stream->descriptor.pointer = NULL; stream->pathname.pointer = NULL; stream->size = 0; stream->base = NULL; // free the stream created by calloc (file_path_to_open_args) free(stream); } FT_Error streamFromUTF8FilePath(const char * filePath, FT_Stream stream) { static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> convert; std::wstring wFilePath = convert.from_bytes(filePath); FILE * file = _wfopen(wFilePath.c_str(), L"rb"); if (!file) return FT_Err_Cannot_Open_Resource; fseek(file, 0, SEEK_END); stream->size = ftell(file); if (!stream->size) { fclose(file); return FT_Err_Cannot_Open_Resource; } fseek(file, 0, SEEK_SET); stream->descriptor.pointer = file; stream->pathname.pointer = (void*)strdup(filePath); stream->read = streamRead; stream->close = streamClose; return FT_Err_Ok; } #endif } FT_Error FXFilePathToOpenArgs(const FXString & filePath, FT_Open_Args * args) { memset(args, 0, sizeof(FT_Open_Args)); #if FX_WIN FT_Stream stream = (FT_Stream)calloc(1, sizeof(FT_StreamRec)); FT_Error error = streamFromUTF8FilePath(filePath.c_str(), stream); if (error) { streamClose(stream); return error; } args->flags = FT_OPEN_STREAM; args->pathname = NULL; args->stream = stream; #else args->flags = FT_OPEN_PATHNAME; args->pathname = (char*)filePath.c_str(); args->stream = NULL; #endif return FT_Err_Ok; }; namespace { unsigned long FXStreamRead(FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count ) { FXPtr<FXStream> * s = (FXPtr<FXStream>*)stream->descriptor.pointer; (*s)->seek(offset); return (unsigned long)(*s)->read(buffer, count); } void FXStreamClose( FT_Stream stream ) { FXPtr<FXStream> * s = (FXPtr<FXStream>*)stream->descriptor.pointer; if (s) { (*s)->close(); delete s; } stream->descriptor.pointer = NULL; stream->pathname.pointer = NULL; stream->size = 0; stream->base = NULL; // free the stream created by calloc (FXStreamToOpenArgs) free(stream); } } FT_Error FXStreamToOpenArgs(FXPtr<FXStream> stream, FT_Open_Args * args) { memset(args, 0, sizeof(FT_Open_Args)); FT_Stream ftStream = (FT_Stream)calloc(1, sizeof(FT_StreamRec)); ftStream->descriptor.pointer = new FXPtr<FXStream>(stream); ftStream->size = stream->size(); ftStream->read = FXStreamRead; ftStream->close = FXStreamClose; args->flags = FT_OPEN_STREAM; args->pathname = NULL; args->stream = ftStream; return FT_Err_Ok; }; FT_Error FXFTCountFaces(FXFTLibrary lib, const FXString & filePath, size_t & count) { FT_Error error = FT_Err_Ok; FT_Face face; FT_Open_Args args; error = FXFilePathToOpenArgs(filePath, &args); if (error) return error; error = FT_Open_Face(lib, &args, -1, &face); if (error) return error; count = face->num_faces; FT_Done_Face(face); return error; } FT_Error FXFTEnumurateFaces(FXFTLibrary lib, const FXString & filePath, std::function<bool(FXFTFace face, size_t index)> callback) { FT_Error error = FT_Err_Ok; size_t numFaces; error = FXFTCountFaces(lib, filePath, numFaces); if (error) return error; // new ft face for (size_t i = 0; i < numFaces; i++ ) { FT_Face face; FT_Open_Args args; error = FXFilePathToOpenArgs(filePath, &args); if (error) return error; error = FT_Open_Face(lib, &args, FT_Long(i), &face); if (error) return error; bool continueLoop = callback(face, i); FT_Done_Face(face); if (!continueLoop) break; } return FT_Err_Ok; } FT_Error FXFTOpenFace(FXFTLibrary lib, const FXString & filePath, size_t index, FXFTFace * face) { FT_Error error = FT_Err_Ok; FT_Open_Args args; error = FXFilePathToOpenArgs(filePath, &args); if (error) return error; return FT_Open_Face(lib, &args, FT_Long(index), face); } FT_Error FXFTOpenFace(FXFTLibrary lib, FXPtr<FXStream> stream, size_t index, FXFTFace * face) { FT_Error error = FT_Err_Ok; FT_Open_Args args; error = FXStreamToOpenArgs(stream, &args); if (error) return error; return FT_Open_Face(lib, &args, FT_Long(index), face); }
true
10dd85850d9c94ff91b8f71a37f4cb09f01e9a8e
C++
romilpunetha/Online-Judges
/Resources/share/bit.cpp
UTF-8
880
3.234375
3
[]
no_license
#include <stdio.h> #include <string.h> #include <iostream> #define ll long long using namespace std; void update(ll int *tree, ll int n, ll int index, ll int val) { while (index <= n) { tree[index] += val; index += (index & (-index)); } } ll int query(ll int *tree, ll int n, ll int index) { ll int sum = 0; while (index > 0) { sum += tree[index]; index -= (index & (-index)); } return sum; } void construct(ll int *tree, ll int *arr, ll int n) { ll int i; for (i = 1; i <= n; i++) update(tree, n, i, arr[i]); } int main() { ll int n = 13; ll int arr[13] = { 0, 2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9 }; ll int tree[n + 1]; memset(tree, 0, sizeof(tree)); construct(tree, arr, n - 1); cout << query(tree, 1, 6) << endl; update(tree, n, 4, 6); cout << query(tree, 1, 6) << endl; }
true
6b7fce6299a39e8ef6cc65f5db7d32ccf468264a
C++
nadirizr/technioncstests
/OperSystems/tests/ex2/tester/test_special.cpp
UTF-8
3,766
3.28125
3
[]
no_license
#include <string> #include <sched.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <errno.h> #include <sys/wait.h> #include "test.h" #include "hw2_syscalls.h" std::string location; /* * This test checks that the parent runs before it's two children, and that the * second child runs before the first. * It does this by setting itself as a short process, then creating two * children, and setting their requested time to be higher. Since the * differences are less than 10 jiffies at first, the parent should be able to * run and eventually the second child should be able to run before the first. */ bool testTwoChildren_SecondChildBeforeFirstChild() { int child_pid1, child_pid2; int a = 0, b = 1, c; struct sched_param param = { 100 }; ASSERT_TRUE(sched_setscheduler(getpid(), SCHED_SHORT, &param) == 0); sleep(1); child_pid1 = fork(); if (child_pid1 == 0) { // This is the first child. param.sched_priority = 10000; ASSERT_TRUE(sched_setscheduler(getpid(), SCHED_SHORT, &param) == 0); while (short_query_remaining_time(getpid()) > 7000) { c = a + b; a = b; b = c; } exit(0); } else { // This is the parent. child_pid2 = fork(); if (child_pid2 == 0) { // This is the second child. param.sched_priority = 9900; ASSERT_TRUE(sched_setscheduler(getpid(), SCHED_SHORT, &param) == 0); while (short_query_remaining_time(getpid()) > 7000) { c = a + b; a = b; b = c; } exit(0); } else { // This is the parent. ASSERT_TRUE((int)wait(NULL) == child_pid2); ASSERT_TRUE((int)wait(NULL) == child_pid1); } } return true; } /* * This test checks that the parent runs before it's child, if the difference * in remaining time is smaller than 10 jiffies. * It does this by setting itself as a short process with enough time, then * creating a child, which should get less time to run. */ bool testOneChild_FatherBeforeChildLessThan10Jiffies() { int child_pid; int a = 0, b = 1, c; struct sched_param param = { 200 }; ASSERT_TRUE(sched_setscheduler(getpid(), SCHED_SHORT, &param) == 0); sleep(1); child_pid = fork(); if (child_pid == 0) { // This is the child. while (short_query_remaining_time(getpid()) > 0) { c = a + b; a = b; b = c; } exit(0); } else { // This is the parent. while (short_query_remaining_time(getpid()) > 10) { c = a + b; a = b; b = c; } ASSERT_TRUE(waitpid(child_pid, NULL, WNOHANG) == 0); ASSERT_TRUE(wait(NULL) == child_pid); } return true; } /* * This test checks that the child runs before it's parent, if the difference * in remaining time is larger than 10 jiffies. * It does this by setting itself as a short process with enough time, then * creating a child, which should get more time to run. */ bool testOneChild_ChildBeforeFatherMoreThan10Jiffies() { int child_pid; int a = 0, b = 1, c; struct sched_param param = { 10000 }; ASSERT_TRUE(sched_setscheduler(getpid(), SCHED_SHORT, &param) == 0); sleep(1); child_pid = fork(); if (child_pid == 0) { // This is the child. while (short_query_remaining_time(getpid()) > 3000) { c = a + b; a = b; b = c; } exit(0); } else { // This is the parent. ASSERT_TRUE(waitpid(child_pid, NULL, WNOHANG) == child_pid); } return true; } int main() { // initialize random number generator srand( time(NULL) ); RUN_TEST(testTwoChildren_SecondChildBeforeFirstChild); RUN_TEST(testOneChild_FatherBeforeChildLessThan10Jiffies); RUN_TEST(testOneChild_ChildBeforeFatherMoreThan10Jiffies); return 0; }
true
f443a48fb67b45d7c118190c5a22c33f61caef0d
C++
idooi/Student-Projects
/1 Data Structures/WET 2/tree.h
UTF-8
10,698
3.140625
3
[]
no_license
// // Created by IdoSarel on 01/01/20. // #ifndef WET2_RANKTREE_H #define WET2_RANKTREE_H #define LEFT 0 #define RIGHT 1 #include <iostream> using namespace std; enum epart{ KEY,DATA }; template <class T, class K> class Tree{ private : K* _key ; T* _data; int _height ; Tree* _father ; Tree* _left ; Tree* _right ; int _rank ; T* _dataSum; template <class T2, class K2> friend class Root; public: Tree(K* key, T* data, Tree* father): _key(key), _data(data), _height(0), _father(father), _left(nullptr), _right(nullptr), _rank(1), _dataSum(new T()) { *_dataSum = *_data; } Tree(Tree* father): _key(nullptr), _data(nullptr), _height(0), _father(father), _left(nullptr), _right(nullptr), _rank(1), _dataSum(nullptr){} ~Tree(){ delete _key; delete _data; delete _dataSum; }; T* getData() const { return _data; } K* getKey() const{ return _key; } void setData(T* newData){ _data = newData; } void setKey(K* newKey){ _key = newKey; } T* getDataSum() const { return _dataSum; } void insertElement(Tree* element){ if (*_key > *(element->_key)){//the root is greater -> go left if (!_left) {//add as left return addChild(element, LEFT); } return _left ->insertElement(element); } else { // assuming never equals -> go right if (!_right) {//add as right return addChild(element, RIGHT); } return _right->insertElement(element); } } int getHeight(){ int left = (_left ? _left ->_height : -1); int right = (_right ? _right ->_height : -1); return max(left ,right) + 1; } int getRank(){ int left = (_left ? _left ->_rank : 0); int right = (_right ? _right ->_rank : 0); return left + right + 1; } T getSum(){ if (!_data){ return 0; } T sum = *_data; if (_left){ sum += *_left->_dataSum; } if (_right){ sum += *_right->_dataSum; } return sum; } void maintainMembers(){ _height = getHeight(); _rank = getRank() ; if (_dataSum) { *_dataSum = getSum() ; } } void addChild (Tree* element, int dir){ if (dir == LEFT){ _left = element; } else {//There's so many directions I can't choose... _right = element; } element->_father = this; element->maintainMembers(); fixTree(); } int getBF(){ if (!this) return 0; int left = (_left ? _left ->_height : 0 ); int right = (_right ? _right->_height : 0 ); return left - right; } void fixTree(){ if (!this) return; maintainMembers(); int BF = getBF(); if (abs(BF) <= 1){//skip!! go upper if(_father){ _father->fixTree(); } return; } //now abs(BF) = 2 int lBF = _left ->getBF(); int rBF = _right->getBF(); //start fixing if ( BF == 2){ if (lBF >= 0){//LL LL(); } else {//assuming lBF = -1 -> LR _left->RR(); LL(); } } else {// assuming BF = -2 if (rBF <= 0) {//RR RR(); } else {//assuming rBF = 1 -> RL _right->LL(); RR(); } } maintainMembers(); fixTree(); } void LL(){ Tree * b = this;// Tree * a = b->_left; Tree * aR = a->_right; //start moving b ->_left = aR; if (aR) { aR->_father = b ; } //// a->_right = b; b->rotateRootAndHeightHandling(a); } void RR(){ Tree * b = this;// Tree * a = b->_right; Tree * aL = a->_left; //start moving b ->_right = aL; if (aL){ aL->_father = b ; } //// a->_left = b; b->rotateRootAndHeightHandling(a); } void rotateRootAndHeightHandling(Tree *a){ Tree * b = this; Tree * root = b->_father; if (root){// handle the upper root if not null - a is the new child of root if (root->_right == b){ root->_right = a; }else {//root->_left == b root->_left = a; } } b->_father = a; a->_father = root; b->maintainMembers(); a->maintainMembers(); } T* findElement(K* key) const{ if (*_key > *key){ return (_left ? _left ->findElement(key) : nullptr); } if (*_key < *key) { return (_right ? _right->findElement(key) : nullptr); }//must be equal return _data; } Tree * detachPrep(K* key) { if (*_key > *key) { return (_left ? _left ->detachPrep(key) : nullptr); } if (*key > *_key) { return (_right ? _right->detachPrep(key) : nullptr); } // assuming *_key == *key if (!_left && !_right) {// a leaf return this; } if (_left && _right) { //find the element with the closet next key value and swap //that means go right once and go left as much as possible Tree<T, K> *tr = _right; while (tr->_left) { tr = tr->_left; } //now tr is either a leaf or has one child K* tempKey = this->_key ; T* tempData = this->_data; this->_key = tr->_key; tr->_key = tempKey; this->_data = tr->_data; tr-> _data = tempData; if (!tr->_left && !tr->_right){//tr is a leaf -> detach return tr; } //tr has one child Tree *trChild = (tr->_left ? tr->_left : tr->_right); //tr has a father tr->_father->_left = (tr->_father-> _left == tr ? trChild : tr->_father->_left ); tr->_father->_right = (tr->_father->_right == tr ? trChild : tr->_father->_right); trChild->_father = tr->_father; // now tr can be detached return tr; } //now there's only one child //just lift the child Tree<T, K> * child = (_left ? _left : _right); if (_father) {//the detached wasn't the root _father->_left = (_father-> _left == this ? child : _father-> _left); _father->_right = (_father->_right == this ? child : _father->_right); child->_father = _father; } else{//no father -> child is the new root child->_father = nullptr; } return this; } void almostFull(int size){//size is number of trees to add if (!this) return; if (size == 0) return;//nothing to build Tree * left = new Tree(this); _left = left; if (size == 1){ left = nullptr; return;//I just wanted the left one } Tree * right = new Tree(this); _right = right; if (size == 2) { left = nullptr; right = nullptr; return;//just wanted two children } size = size - 2;//already built to new children if (size != 0) { int leftSize = 0, rightSize = 0; leftSize = (size % 2 == 0 ? size / 2 : size / 2 + 1);//I'm left wing (just kidding) rightSize = size - leftSize; left = nullptr; right = nullptr; _left->almostFull(leftSize); _right->almostFull(rightSize); } left = nullptr; right = nullptr; return; } void emptyTree(){//use with caution! memory leak warning if (!this) return; _key = nullptr; _data = nullptr; _left->emptyTree(); _right->emptyTree(); } void fillTree(K** keys, T** datas, int * i){ if (!this) return; _left ->fillTree(keys, datas, i); _key = keys[*i]; _data = datas[*i]; *i = *i + 1; _right->fillTree(keys, datas, i); _height = getHeight(); _rank = getRank() ; _dataSum = new T(getSum()); } void detachAllData(){ if (!this) return; _left-> detachAllData(); _right->detachAllData(); _data = nullptr; } void detachAllKeys(){ if (!this) return; _left-> detachAllKeys(); _right->detachAllKeys(); _key = nullptr; } int getLength(){ if (!this) return 0; return _left->getLength() + _right ->getLength() + 1 ; } Tree* getMax() const{ if (!this) return nullptr; if (_right) return _right->getMax(); return this; } Tree* getMin() const{ if (_left) return _left->getMin(); return this; } template<class A> void getInorder(A** dataArr, int* i, epart e){ if (_left ) _left ->getInorder(dataArr, i, e); dataArr[*i] = (e == DATA ? (A*)_data : (A*)_key); *i = *i + 1; if (_right) _right->getInorder(dataArr, i, e); } int getRealRank(){ if(!this) return 0; return (_left->getRealRank()+_right->getRealRank()+1); } T checkSum(){ T sum = *_data; if (_left){ sum += _left->checkSum(); } if (_right){ sum += _right->checkSum(); } return sum; } void indexSum(int i, T* sum){ if (i == 0){ return; } int leftRank = (_left ? _left->_rank : 0); if (leftRank == i - 1){// our journey is done *sum = *sum + *_data; *sum = (_left ? *_left->_dataSum + *sum : *sum); return; } else {//keep going down if (leftRank > i - 1 && _left){ _left->indexSum(i, sum); return; } else if (_right) {// going right *sum = *sum + *_data; *sum = (_left ? *sum + *(_left->_dataSum) : *sum); _right->indexSum(i - leftRank - 1, sum); return; } } } }; #endif //WET2_RANKTREE_H
true
a02efb619ffacffc59c5cf5b02b8b196aa6dd15a
C++
alejandratub/ProgramacionOrientadaObjetos
/SegundoParcial/vehiculo/deportivo.cpp
UTF-8
550
2.640625
3
[]
no_license
#include <iostream> #include <string> #include "vehiculo.h" #include "deportivos.h" using namespace std; Deportivo::Deportivo(){} Deportivo::Deportivo(string nMa,string nMo,int a,string c,int nPa,int nPu,float p, float k,string t,string e, int tur, double pot):Vehiculo(nMa,nMo,a,c,nPa,nPu,p,k,t,e) { turbo = tur; potencia = pot; } //Deportivo::~Deportivo(){} void Deportivo::imprimir() { Vehiculo::imprimir(); cout << "\n\tEl turbo está: " << turbo << endl; cout << "\n\tTiene una potencia: " << potencia << endl; }
true
8fa345fd5eeb1ed4807e0c93844efede98273d91
C++
trantrunghieu0409/Caro
/Model.cpp
UTF-8
2,476
2.875
3
[]
no_license
#include"Control.h" #include"View.h" #include"Model.h" #include"DoAnCaro.h" #include <stdlib.h> extern struct _POINT { int x, y, c; };// x : diaphragm degree , y : bounce degree , c : flag extern _POINT _A[BOARD_SIZE][BOARD_SIZE]; extern bool _TURN; // player 1 = true ; player 2 = false extern int _COMMAND;//Value input from user extern int _X, _Y;//Current position of cursor void ResetData() { for (int i = 0; i < BOARD_SIZE; i++) for (int j = 0; j < BOARD_SIZE; j++) { _A[i][j].x = 4 * j + LEFT + 2; _A[i][j].y = 2 * i + TOP + 1; _A[i][j].c = 0; // 0 if not marked . -1 if taken by player 1. 1 if taken by player 2 } _TURN = true; _COMMAND = -1; // Set Default Player and Default Key _X = _A[0][0].x; _Y = _A[0][0].y; // Set Default Coordinate } void GarbageCollect() { //Clean resource if declared cursor variables } int CheckFullBoard() { for (int i = 0; i < BOARD_SIZE; i++) for (int j = 0; j < BOARD_SIZE; j++) { if (_A[i][j].c != 0) return 0; } return 1; } int CheckStateWin() { int flag = (_TURN == true) ? (-1) : 1; for (int i = 0; i < BOARD_SIZE; i++) for (int j = 0; j < BOARD_SIZE; j++) if (_A[i][j].c == flag) { //Ngang int count = 0; for (int k = j; k < BOARD_SIZE && (k - j) < LINE; k++) { if (_A[i][k].c == flag) count++; } if (count == LINE) return 1; //Doc count = 0; for (int k = i; k < BOARD_SIZE && (k - i) < LINE; k++) { if (_A[k][j].c == flag) count++; } if (count == LINE) return 1; //Cheo phai count = 0; for (int k = 0; ((i + k) < BOARD_SIZE) && (j + k) < BOARD_SIZE && k < LINE; k++) { if (_A[i + k][j + k].c == flag) count++; } if (count == LINE) return 1; //Cheo trai count = 0; for (int k = 0; (i + k) < BOARD_SIZE && (j - k)>= 0 && k < LINE; k++) { if (_A[i + k][j - k].c == flag) count++; } if (count == LINE) return 1; } return 0; } int TestBoard() { if (CheckFullBoard() == 1) return 0; else if (CheckStateWin() == 1) return ((_TURN == true) ? -1 : 1); else return 2; } int CheckBoard(int pX, int pY) { for (int i = 0; i < BOARD_SIZE; i++) for (int j = 0; j < BOARD_SIZE; j++) if (_A[i][j].x == pX && _A[i][j].y == pY && _A[i][j].c == 0) { if (_TURN == true) _A[i][j].c = -1; else _A[i][j].c = 1; return _A[i][j].c; } return 0; }
true
900b07b7d610cb1f1d0210115a23ef8641761600
C++
MorgesHAB/ERT2020GS
/UI/Gui_message.h
UTF-8
436
2.625
3
[]
no_license
#ifndef Gui_Message_H #define Gui_Message_H #include "../Logger/Logger.h" #include "../Logger/utilities.h" /** * @brief The Gui_Message class Inheriting the Loggable, this is a basic data which will be used by the GUI. */ class Gui_Message : public Loggable { public: Gui_Message(const std::string & message); virtual std::string log_description() const; private: const std::string message_; }; #endif // Gui_Message_H
true
95cd90e542733d4a0b4c301770f66efc541f2096
C++
nixz-leon/schoolwork
/project2/countCategoryDriver.cpp
UTF-8
1,123
3.875
4
[]
no_license
#include "Product.h" bool checker_category(string first, string second){ string temp_1 = ""; string temp_2 = ""; for(int i = 0; i< first.size(); i ++){ if(first[i] != ' '){ if(isdigit(first[i])){ temp_1 += first[i]; }else{ temp_1 += tolower(first[i]); } } } for(int i = 0; i< second.size(); i ++){ if(second[i] != ' '){ temp_2 += tolower(second[i]); }else if(isdigit(second[i])){ temp_1 += second[i]; } } // the above loops convert all the chars to lower case, and removing spaces if(temp_1 == temp_2){ return true; }else{ return false; } } int countCategory(string Cat, Product products[], int Num_Stored){ int count = 0; for(int i = 0; i < Num_Stored; i++){ string curr_cat = products[i].getCategory(); if(checker_category(curr_cat, Cat)){ // checks if the cat matches if so adds one to the count count++; } } return count; }
true
f15e826e3e7b9ae5a0621660361573078079c106
C++
jshelton/axelrodnorms
/norms.cpp
UTF-8
24,206
3.03125
3
[]
no_license
#include <iostream> #include <list> #include <vector> #include <sstream> #include <math.h> #include <time.h> using namespace std; // For double math to work well const double doubleError = 0.00000001; // Populationcontrols const int defaultPopulationSize = 40; const int initialScore = 0; const double bitsPerPlayerByte = 3; const double probAboveStdDev = 0.1587; const int numberOfDefectionOpportunities = 4; const bool metaNormsDefault = true; const double bitFlipProbability = 0.01; const int numberOfGenerations = 1000; const int numberOfGames = 50; const bool printTrace = true; const bool printGame = false; // AxelRod's Algorithm bool metaNormsEnabled = true; int boldnessScale = 8; int vengenceScale = 8; const int T = 3; const int H = -3; const int P = -8; const int E = -2; const int Pp = -8; const int Ep = -2; double rand1() { return (rand() % RAND_MAX) / (1.0 * RAND_MAX); } int seed = -1; int seedTime() { seed = time(NULL); srand(seed); return seed; } int setSeed(int seedIn) { seed = seedIn; srand(seed); return seed; } struct AvgSet { double averageBoldness; double averageVengence; double averageScore; int count; AvgSet() { averageBoldness = -1; averageVengence = -1; averageScore = 0; } AvgSet(double a, double b, double c) { averageBoldness = a; averageVengence = b; averageScore = c; } }; ostream &operator<<(ostream &os, const AvgSet &p) { return os << "[" << p.averageBoldness << "," << p.averageVengence << "," << p.averageVengence << "],"; } class Player { int V, B; int S; /** * randomBitFlip(number,probability) * This function will flip assumes bitsPerPlayer number of bits (usually 3) * It will randomly flip one of the first bitsPerPlayer bits if the random * generated double is below the input probability. */ int randomBitFlip(int &number, double probability) { for (int i = 0; i < bitsPerPlayerByte; i++) { if (rand1() < probability) { // lucky bit number = number ^ (1 << i); } } return number; } public: int vengance() const { return V; } int &vengance() { return V; } int score() const { return S; } int &score() { return S; } int boldness() const { return B; } int &boldness() { return B; } int resetScore() { return S = initialScore; } Player(Player const &p) { this->V = p.V; this->B = p.B; this->S = p.S; } Player(int newV, int newB, int newS) { this->V = newV; this->B = newB; this->S = newS; } Player(int newV, int newB) { this->V = newV; this->B = newB; this->S = initialScore; } void BitFlip(double probability) { this->V = randomBitFlip(this->V, probability); this->B = randomBitFlip(this->B, probability); } }; bool scoreCompare(const Player &p1, const Player &p2) { return p1.score() > p2.score(); } ostream &operator<<(ostream &os, const Player &p) { os << "(" << p.vengance() << "," << p.boldness() << "," << p.score() << ")"; return os; } class PlaySet { list<Player> playerList; int length; int populationSize; int seed; public: void setSeed(int seedIn = -1) { if (seedIn == -1) seed = time(NULL); else seed = seedIn; srand(seed); } void setPopulationSize(int size = defaultPopulationSize) { populationSize = size; } /** * Return the list size for printing to ostream */ int size() const { return playerList.size(); } /* * This generates a list of random players */ void generateList() { for (int i = 0; i < populationSize; i++) { playerList.push_back(Player(rand() % boldnessScale, rand() % vengenceScale)); } } void calculateScores() { bool debug = false; for (list<Player>::iterator it = playerList.begin(); it != playerList.end(); it++) { if (debug) { cerr << endl << "-Now Player: " << (*it) << " "; } for (int defectionOpportunity = 0; defectionOpportunity < numberOfDefectionOpportunities; defectionOpportunity++) { // probability of being seen double S = rand1(); if (debug) { cerr << "Defection opportunity: " << defectionOpportunity << ", S = " << S << ". Brave enough (" << S * boldnessScale << "/" << it->boldness() << ")? " << endl; } // If he is brave enough if (S * boldnessScale < it->boldness()) { if (debug) { cerr << "Yes Brave enough. "; } // Increase the player's payoff it->score() += T; // Now to see if anyone caught this person for (list<Player>::iterator jt = playerList.begin(); jt != playerList.end(); jt++) { // skip over the subject if (it == jt) continue; // Every other agent was hurt because of this defection jt->score() += H; double probabilityWasSeen = rand1(); if (debug) cerr << endl << "Did " << (*jt) << " see him (" << probabilityWasSeen << "/" << S << ")? "; // if this defection falls in the probability of being seen if (probabilityWasSeen < S) { if (debug) cerr << "Yes, he was seen by " << (*jt) << ". "; // Agent j saw agent i // Now let's see what he does about it // is he going to be vengeful double probabilityWasVengeful = rand1() * vengenceScale; if (debug) cerr << "Did " << (*jt) << " punish him (" << probabilityWasVengeful << "/" << jt->vengance() << ")?"; if (probabilityWasVengeful < jt->vengance()) { jt->score() += E; it->score() += P; if (debug) cerr << "Yes " << (*jt) << " punished " << (*it) << "."; } else { if (debug) cerr << " He was not vengeful."; // Someone has seen the culprit but not punished if (metaNormsEnabled) { // kt is the punisher of jt when he does not punish it for (list<Player>::iterator kt = playerList.begin(); kt != playerList.end(); kt++) { // skip over the subject and the observer who did nothing if (kt == jt || kt == it) continue; // No other agent was hurt by this // jt->score() += H; double probabilityWasSeen = rand1(); if (debug) cerr << endl << " Did " << (*kt) << " see " << (*jt) << " walk away (" << probabilityWasSeen << "/" << S << ")? "; // if this defection falls in the probability of being seen if (probabilityWasSeen < S) { if (debug) cerr << " Yes, he was seen."; // Agent j saw agent i // Now let's see what he does about it // is he going to be vengeful double probabilityWasVengeful = rand1() * vengenceScale; if (debug) cerr << "Did " << (*kt) << " punish him for walking away (" << probabilityWasVengeful << "/" << kt->vengance() << ")?"; if (probabilityWasVengeful < kt->vengance()) { kt->score() += Ep; jt->score() += Pp; if (debug) cerr << " Yes " << (*kt) << " punished " << (*jt) << "."; } // if was vengeful else if (debug) cerr << " No not vengeful."; } // if was seen else if (debug) cerr << " No not seen not punishing."; } // for all other metapunishers } // if Metanorms working else if (debug) cerr << " No metanorms."; } // not punished first time } // Seen defecting else if (debug) cerr << " No not seen defecting."; } // For each other agent possibly observing } // If Boldness is high enough else if (debug) cerr << " No too brave."; } // For each defecting opportunity } // For each player } // Calculate Scores Player & playerAt(int indexFrom) { list<Player>::iterator it = playerList.begin(); for (int i = 0; i < indexFrom; i++) it++; return *it; } const Player &playerAt(int indexFrom) const { list<Player>::const_iterator it = playerList.cbegin(); for (int i = 0; i < indexFrom; i++) it++; return *it; } static inline double squared(double num) { return num * num; } /* * Procreate * This function will go through all the items and will generate 2 clones of individuals with scores * One standard deviation higher, as well as clones for all except the lowest generation. */ void procreate() { bool debug = false; // In theory Here we procreate by: // Add two of the ones higher than one standard deviation // Add one for those who are above one standard deviation // Ignore less than one standard deviation // Until we reach the size of our max Population and then we stop // In practice it is easier to remove a low one and add two high ones // until we get to a standard deviation. Essentially the top 15.87% // replaces the bottom 15.87%. // Just make sure our assumptions are correct if (populationSize != playerList.size()) cerr << "ERROR: Population sizes do not match up" << endl; int numberOfTopEschelon = populationSize * probAboveStdDev; int countProgeny = 0; list<Player> newList; playerList.sort(scoreCompare); if (debug) { cerr << "-playerList "; for (list<Player>::iterator it = playerList.begin(); it != playerList.end(); it++) { cerr << "," << *it; } cerr << endl; } // First Start with top eschelon for (int i = 0; i < numberOfTopEschelon; i++) { // Just checking Assumptions if (playerList.begin() == playerList.end()) { cerr << "ERROR: top eschelon miscalculated" << endl; break; } // Top Eschelon gets kids newList.push_back(Player(*playerList.begin())); newList.push_back(Player(*playerList.begin())); // This will replace the spot of one lower eschelon and one upper eschelon playerList.pop_front(); playerList.pop_back(); } // Checking Assumptions if (playerList.size() != populationSize - 2 * numberOfTopEschelon) cerr << "ERROR: The math behind normal population size is mistaken" << endl; // Now the remaining Should be newList.insert(newList.end(), playerList.begin(), playerList.end()); if (debug) { cerr << "-newList "; for (list<Player>::iterator it = newList.begin(); it != newList.end(); it++) { cerr << "," << *it; } cerr << endl; } playerList.clear(); playerList.assign(newList.begin(), newList.end()); for (list<Player>::iterator it = playerList.begin(); it != playerList.end() && countProgeny < populationSize; it++) { it->resetScore(); it->BitFlip(bitFlipProbability); } } //TODO: Check if length or size is used much ostream &printAvgs(ostream &os) { double sumBoldness = 0; double sumVengance = 0; double sumScores = 0; for (list<Player>::iterator it = playerList.begin(); it != playerList.end(); it++) { sumBoldness += it->boldness(); sumVengance += it->vengance(); sumScores += it->score(); } os << (1.0 * sumBoldness / playerList.size()) << "\t" << (1.0 * sumVengance / playerList.size()) << "\t" << (1.0 * sumScores / playerList.size()) << endl; return os; } AvgSet &getAvgSet() { double sumBoldness = 0; double sumVengance = 0; double sumScores = 0; for (list<Player>::iterator it = playerList.begin(); it != playerList.end(); it++) { sumBoldness += it->boldness(); sumVengance += it->vengance(); sumScores += it->score(); } return *(new AvgSet((1.0 * sumBoldness / playerList.size()), (1.0 * sumVengance / playerList.size()), (1.0 * sumScores / playerList.size()))); } ostream &print(ostream &os) const { for (list<Player>::const_iterator it = playerList.begin(); it != playerList.end(); it++) { os << (*it); } return os; } void run(int numberOfTimes) { bool debug = false; for (int i = 0; i < numberOfTimes; i++) { cout << "[" << getAvgSet(); calculateScores(); if (debug) printAvgs(cerr); procreate(); cout << getAvgSet() << "]," << endl; } } PlaySet() { length = 0; populationSize = defaultPopulationSize; } }; ostream &operator<<(ostream &os, const PlaySet &ps) { return ps.print(os); } struct UnitTests { template <typename Function> static void runTest(vector<bool> &pass, Function f, bool debug) { if (debug) { cerr << "Test Number: " << pass.size() << endl; } pass.push_back(f(debug)); if (debug) { cerr << "Test " << (pass.back() ? "passed" : "failed") << endl << endl; } } static bool test0(bool debug) { string testName = "Test of the Testing system"; stringstream ss; string expected("This is a Test"); { ss << "This is a Test"; } // See if the expectation value is accurate bool success = (expected.compare(ss.str()) == 0); if (debug) { cerr << "Test Title: " << testName << "" << endl; cerr << "Expected: " << endl << expected << endl; cerr << "Actual: " << endl << ss.str() << endl; } return success; } static bool test1(bool debug) { string testName = "Test five players with seed two"; stringstream ss; string expected("(0,0,0)(3,5,0)(4,5,0)(4,1,0)(1,1,0)"); { PlaySet pl; pl.setSeed(2); pl.setPopulationSize(5); pl.generateList(); ss << pl; } // See if the expectation value is accurate bool success = (expected.compare(ss.str()) == 0); if (debug) { cerr << "Test Title: " << testName << "" << endl; cerr << "Expected: " << endl << expected << endl; cerr << "Actual: " << endl << ss.str() << endl; } return success; } static bool test2(bool debug) { string testName = "Test twenty new players"; stringstream ss; string expected("(0,0,0)(4,3,0)(3,4,0)(6,1,0)(1,1,0)(3,5,0)(5,4,0)(0,0,0)(4,5,0)(4,2,0)(4,6,0)(2,5,0)(1,1,0)(4,5,0)(6,4,0)(3,0,0)(0,4,0)(1,1,0)(6,1,0)(5,4,0)"); { PlaySet pl; pl.setSeed(3); pl.setPopulationSize(20); pl.generateList(); ss << pl; } // See if the expectation value is accurate bool success = (expected.compare(ss.str()) == 0); if (debug) { cerr << "Test Title: " << testName << "" << endl; cerr << "Expected: " << endl << expected << endl; cerr << "Actual: " << endl << ss.str() << endl; } return success; } static bool test3(bool debug) { string testName = "Test reproduction"; stringstream ss; string expected("(0,3,-40)(2,1,-33)(1,4,-15)(4,5,-23)(1,5,-10)\n(1,5,0)(1,4,0)(4,5,0)(2,1,0)(0,3,0)"); { PlaySet pl; pl.setSeed(9823); pl.setPopulationSize(5); pl.generateList(); pl.playerAt(0).score() = -40; pl.playerAt(1).score() = -33; pl.playerAt(2).score() = -15; pl.playerAt(3).score() = -23; pl.playerAt(4).score() = -10; ss << pl << endl; pl.procreate(); ss << pl; } // See if the expectation value is accurate bool success = (expected.compare(ss.str()) == 0); if (debug) { cerr << "Test Title: " << testName << "" << endl; cerr << "Expected: " << endl << expected << endl; cerr << "Actual: " << endl << ss.str() << endl; } return success; } static bool test4(bool debug) { string testName = "Test RandomBitSwitch"; stringstream ss; string expected("(6,4,-12)(0,2,-32)(3,3,-25)(1,1,-79)(6,4,-77)(3,5,-92)(3,0,-81)(5,4,-76)(6,3,-53)(6,6,-87)(1,4,-58)(3,1,-71)(4,1,-60)(1,5,-73)(4,6,-75)(4,6,-6)(4,0,-7)(1,0,-47)(4,3,-81)(6,6,-22)\n(4,6,0)(4,6,0)(4,0,0)(4,1,0)(6,4,0)(6,4,0)(6,6,0)(3,3,0)(0,2,0)(1,0,0)(6,3,0)(1,4,0)(4,1,0)(3,1,0)(1,5,0)(4,6,0)(5,4,0)(6,4,0)(1,1,0)(3,0,0)"); { PlaySet pl; pl.setSeed(232321); int popSize = 20; pl.setPopulationSize(popSize); pl.generateList(); for (int i = 0; i < popSize; i++) pl.playerAt(i).score() = (rand() % 100) - 95; ss << pl << endl; pl.procreate(); ss << pl; } // See if the expectation value is accurate bool success = (expected.compare(ss.str()) == 0); if (debug) { cerr << "Test Title: " << testName << "" << endl; cerr << "Expected: " << endl << expected << endl; cerr << "Actual: " << endl << ss.str() << endl; } return success; } static bool test5(bool debug) { string testName = "Test Score Calculation"; stringstream ss; string expected("(6,6,0)(0,3,0)(4,0,0)(1,6,0)(5,2,0)(6,1,0)(2,2,0)(0,6,0)(0,1,0)(0,3,0)(3,0,0)(1,6,0)(5,6,0)(5,2,0)(2,5,0)(0,3,0)(0,0,0)(0,1,0)(1,3,0)(5,6,0)\n(6,6,-62)(0,3,-10)(4,0,-16)(1,6,-10)(5,2,-16)(6,1,-12)(2,2,-26)(0,6,-6)(0,1,-6)(0,3,-10)(3,0,-14)(1,6,-26)(5,6,-19)(5,2,-14)(2,5,-44)(0,3,-10)(0,0,-10)(0,1,-10)(1,3,-24)(5,6,-24)"); { PlaySet pl; pl.setSeed(195105); int popSize = 20; pl.setPopulationSize(popSize); pl.generateList(); ss << pl << endl; metaNormsEnabled = false; pl.calculateScores(); metaNormsEnabled = metaNormsDefault; ss << pl; } // See if the expectation value is accurate bool success = (expected.compare(ss.str()) == 0); if (debug) { cerr << "Test Title: " << testName << "" << endl; cerr << "Expected: " << endl << expected << endl; cerr << "Actual: " << endl << ss.str() << endl; } return success; } static bool test6(bool debug) { string testName = "Test Score Calculation with Metanorms"; stringstream ss; string expected("(6,6,0)(0,3,0)(4,0,0)(1,6,0)(5,2,0)(6,1,0)(2,2,0)(0,6,0)(0,1,0)(0,3,0)(3,0,0)(1,6,0)(5,6,0)(5,2,0)(2,5,0)(0,3,0)(0,0,0)(0,1,0)(1,3,0)(5,6,0)\n(6,6,-57)(0,3,-112)(4,0,-57)(1,6,-54)(5,2,-22)(6,1,-45)(2,2,-93)(0,6,-58)(0,1,-49)(0,3,-17)(3,0,-42)(1,6,-71)(5,6,-70)(5,2,-135)(2,5,-84)(0,3,-76)(0,0,-26)(0,1,-35)(1,3,-102)(5,6,-34)"); { PlaySet pl; pl.setSeed(195105); int popSize = 20; pl.setPopulationSize(popSize); pl.generateList(); metaNormsEnabled = true; ss << pl << endl; pl.calculateScores(); ss << pl; } metaNormsEnabled = metaNormsDefault; // See if the expectation value is accurate bool success = (expected.compare(ss.str()) == 0); if (debug) { cerr << "Test Title: " << testName << "" << endl; cerr << "Expected: " << endl << expected << endl; cerr << "Actual: " << endl << ss.str() << endl; } return success; } static bool test7(bool debug) { string testName = "Test Multigeneration"; stringstream ss; string expected("(0,4,0)(5,0,0)(6,0,0)(5,5,0)(6,0,0)(0,3,0)(3,4,0)(6,4,0)(6,0,0)(1,2,0)(4,1,0)(5,6,0)(4,4,0)(2,3,0)(2,5,0)\n(6,1,0)(6,1,0)(6,1,0)(6,1,0)(6,0,0)(4,0,0)(6,1,0)(6,1,0)(6,2,0)(4,0,0)(6,1,0)(6,1,0)(6,1,0)(6,1,0)(6,1,0)"); { PlaySet pl; pl.setSeed(12852); int popSize = 15; pl.setPopulationSize(popSize); pl.generateList(); metaNormsEnabled = true; ss << pl << endl; pl.run(numberOfGenerations); ss << pl; } metaNormsEnabled = metaNormsDefault; // See if the expectation value is accurate bool success = (expected.compare(ss.str()) == 0); if (debug) { cerr << "Test Title: " << testName << "" << endl; cerr << "Expected: " << endl << expected << endl; cerr << "Actual: " << endl << ss.str() << endl; } return success; } static bool test8(bool debug) { string testName = "Test Multigeneration"; stringstream ss; string expected("(0,4,0)(5,0,0)(6,0,0)(5,5,0)(6,0,0)(0,3,0)(3,4,0)(6,4,0)(6,0,0)(1,2,0)(4,1,0)(5,6,0)(4,4,0)(2,3,0)(2,5,0)\n(6,1,0)(6,1,0)(6,1,0)(6,1,0)(6,0,0)(4,0,0)(6,1,0)(6,1,0)(6,2,0)(4,0,0)(6,1,0)(6,1,0)(6,1,0)(6,1,0)(6,1,0)"); { PlaySet pl; pl.setSeed(23231); int popSize = numberOfGenerations; pl.setPopulationSize(popSize); pl.generateList(); metaNormsEnabled = true; ss << pl << endl; pl.run(numberOfGenerations); ss << pl; } metaNormsEnabled = metaNormsDefault; // See if the expectation value is accurate bool success = (expected.compare(ss.str()) == 0); if (debug) { cerr << "Test Title: " << testName << "" << endl; cerr << "Expected: " << endl << expected << endl; cerr << "Actual: " << endl << ss.str() << endl; } return success; } static bool runAll() { bool debug = true; vector<bool> pass; runTest(pass, test0, debug); //0 runTest(pass, test1, debug); //1 runTest(pass, test2, debug); //2 runTest(pass, test3, debug); //3 runTest(pass, test4, debug); //4 runTest(pass, test5, debug); //5 runTest(pass, test6, debug); //6 runTest(pass, test7, debug); //7 runTest(pass, test8, debug); //7 bool passall = true; for (int i = 0; i < pass.size(); i++) { passall = passall && pass[i]; } if (debug) { cout << "The results are " << (passall ? "all passing" : "failing") << "." << endl; for (int i = 0; i < pass.size(); i++) if (!pass[i]) cerr << "Test number " << i << " failed." << endl; } return passall; } } test; ostream &operator<<(ostream &os, const list<AvgSet> &myList) { os << "[["; for (list<AvgSet>::const_iterator it = myList.begin(); it != myList.end(); it++) { os << it->averageBoldness << ","; } os << "],["; for (list<AvgSet>::const_iterator it = myList.begin(); it != myList.end(); it++) { os << it->averageVengence << ","; } os << "],["; for (list<AvgSet>::const_iterator it = myList.begin(); it != myList.end(); it++) { os << it->averageScore << ","; } os << "]]"; return os; } list<AvgSet> &runSets(int numberOfTimes = numberOfGames, int seed = -1) { // srand(23231); list<AvgSet> *initialSet = new list<AvgSet>(); list<AvgSet> *results = new list<AvgSet>(); if (printGame || printTrace) cout << "var a = [" << endl; for (int i = 0; i < numberOfTimes; i++) { PlaySet pl; int popSize = defaultPopulationSize; pl.setPopulationSize(popSize); pl.generateList(); initialSet->push_back(pl.getAvgSet()); pl.run(numberOfGenerations); results->push_back(pl.getAvgSet()); if (printGame) cout << "[" << initialSet->back() << results->back() << "]," << endl; } if (printGame || printTrace) cout << "]" << endl; metaNormsEnabled = metaNormsDefault; cerr << "Results:" << endl; cerr << (*initialSet) << endl; cerr << (*results) << endl; return (*results); } int main() { // test.runAll(); cerr << "Seed:" << setSeed(1554923370) << endl; // cerr << "Seed:" << seedTime() << endl; runSets(); }
true
57d36ba35279fd1e2d95032acb49c50b0bba89d4
C++
aben20807/oj_code
/google_code_jam/2018/Qualification_Round/p2_Trouble_Sort.cpp
UTF-8
1,033
2.890625
3
[ "MIT" ]
permissive
// TLE in hidden test case #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> using namespace std; int v[100001]; int n; void troublesort() { bool done = false; while (!done) { done = true; for (int i = 0; i < n - 2; i++) { if (v[i] > v[i + 2]) { done = false; swap(v[i], v[i + 2]); } } } } int main() { int t; int casecnt = 1; scanf("%d", &t); while (t--) { memset(v, -1, sizeof(v)); scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &v[i]); } troublesort(); bool ok = true; int i; for (i = 0; i < n - 1; i++) { if (v[i] > v[i + 1]) { ok = false; break; } } printf("Case #%d: ", casecnt++); if (ok) { printf("OK\n"); } else { printf("%d\n", i); } } return 0; }
true
de44bb178eb1ad451266509437e43983fd14e548
C++
blockspacer/test-cpp
/template-metaprog/has_sort.cpp
UTF-8
1,337
3.40625
3
[]
no_license
#include <iostream> #define HAS_MEMBER(NAME)\ template<typename T>\ struct has_##NAME {\ using yes = char;\ using no = char[2];\ \ template<typename U = T>\ static auto test(void*) -> decltype(&U::NAME, yes());\ \ template<typename U = T>\ static no& test(...);\ \ static constexpr bool value = sizeof(has_##NAME::test<T>(nullptr)) == \ sizeof(has_##NAME::yes);\ } /* template<typename T> struct has_sort { using yes = char; using no = char[2]; template<typename U = T> static auto test(void*) -> decltype(&U::sort, yes()); template<typename U = T> static no& test(...); static constexpr bool value = sizeof(has_sort::test<T>(nullptr)) == sizeof(has_sort::yes); };*/ HAS_MEMBER(sort); HAS_MEMBER(empty); struct my_storage { void sort() {} void empty() {} }; struct null_t {}; void test0() { auto r1 = has_sort<my_storage>::value; auto r2 = has_sort<int>::value; auto e1 = has_empty<my_storage>::value; auto e2 = has_empty<null_t>::value; std::cout << "r1 = " << r1 << std::endl; std::cout << "r2 = " << r2 << std::endl; std::cout << "e1 = " << e1 << std::endl; std::cout << "e2 = " << e2 << std::endl; } int main() { test0(); return 0; }
true
358e3bbb5abc77553722a3e2b5a3b9718cf16832
C++
vanyakandlakunta/PrimerExercises
/Chap10/Ex07_files/Ex07.cpp
UTF-8
935
2.625
3
[]
no_license
// ===================================================================================== // // Filename: Ex07.cpp // // Description: Exercise 7 of Chapter 10 CPP Primer // // Version: 0.01 // Created: Wednesday 08 July 2015 02:18:14 IST // Revision: none // Compiler: clang 3.5 // // Author: kchary@andrew.cmu.edu // Company: Carnegie Mellon University // ===================================================================================== /* Function definitions file for the prototypes in header */ #include"Ex07.h" #include<iostream> #include<string.h> Plorg::Plorg(char defaultName[] = "Plorga") { strcpy(name,defaultName); CI = 50; } Plorg::~Plorg() { } void Plorg::Report() const { std::cout<<std::endl; std::cout<<"Name : "<<name<<std::endl; std::cout<<"Contentment Index : "<<CI<<std::endl; } void Plorg::ChangeCI(int newCI) { CI = newCI; }
true
226d935234107487ccf540aae676f7ccbdb57d9c
C++
LucasAMiranda/Estrutura-Dados
/funcões-heterogeneas.cpp
UTF-8
656
3.25
3
[]
no_license
#include <iostream> using namespace std; #include<string.h> struct DADOS_ALUNO{ int CodAluno; char Nome[100]; int Turma; }; void imprimirDados(DADOS_ALUNO Aluno); int main() { struct DADOS_ALUNO AlunoA; cout << "Digite o código do Aluno: "; cin >> AlunoA.CodAluno; cout << "Digite o nome do Aluno: "; cin >> AlunoA.Nome; cout << "Digite a turma: "; cin >> AlunoA.Turma; Imprimir(AlunoA); system("pause > null "); } void Imprimir(DADOS_ALUNO Aluno){ cout<< "Código do Aluno(a): " << Aluno.CodAluno<<endl; cout<< "Nome: " << Aluno.Nome <<endl; cout<< "Turma: " << Aluno.Turma <<endl; }
true
db7e803dd380d3539f6b6b666a55789936a97750
C++
mashharuki/C-Sample
/sample7.cpp
UTF-8
3,872
4.125
4
[]
no_license
#include <iostream> #include <vector> /** * リンゴクラス */ class Ringo { public: // 列挙型変数を用意する。 enum color_index{ color_red, color_green, color_yellow }; /** 色 */ color_index color; /** 重さ */ double weight; /** 品種 */ std::string kind; /** * コンストラクター */ Ringo () { color = color_red; weight = 320.0; kind = "ふじ"; } Ringo (const enum color_index &c, const double w, const char *k) { color = c; weight = w; kind = k; } /** * 色の名前を取得する関数 */ const char *GetColorName() { static const char *color_name[] = {"赤", "青", "緑"}; return color_name[color]; } /** * データを出力する関数 */ void PrintData() { printf("色 =%s 重さ =%5.1fg 品種 =%s¥n", GetColorName(), weight, kind.c_str()); } }; /** * リンゴクラス */ class RingoBox { public: // コンストラクター RingoBox() { Empty(); } /** * 追加関数 */ bool Add(Ringo &r); /** * 削除関数 */ bool Del(int index); /** * 空白にする関数 */ void Empty(){ ringo.clear(); } /** * 合計個数を算出する関数 */ int GetTotalNum() { return (int) ringo.size(); } /** * 合計重量を算出する関数 */ double GetTotalWeight(); /** * データを全て表示する関数 */ void PrintData(); private: /** Ringo型の変数 */ std::vector<Ringo> ringo; }; /** * Add関数のオーバーロード */ bool RingoBox::Add (Ringo &r) { if (ringo.size() > 40) return false; ringo.push_back(r); return true; } /** * Del関数のオーバーロード */ bool RingoBox::Del (int index) { if (index < 1 || index > (int)ringo.size()) return false; ringo.erase(ringo.begin() + index - 1); return true; } /** * GetTotalWeight関数のオーバーロード */ double RingoBox::GetTotalWeight () { double w = 0; for (std::vector<Ringo>::iterator i = ringo.begin(); i != ringo.end(); i++) { w += (*i).weight; } return w; } /** * PrintData関数のオーバーロード */ void RingoBox::PrintData () { int n = GetTotalNum(); for (int i=0; i < n; i++) { ringo[i].PrintData(); } printf("%d個のりんごがあります。¥n", n); printf("総重量 %5.1fg¥n", GetTotalWeight()); } /** * メイン関数 */ int main () { // 総数を宣言する。 static const char init_num= 4; // Ringo型のコンストラクターを生成する。 Ringo myRingo[] = { Ringo(Ringo::color_red, 316.2, "ふじ"), Ringo(Ringo::color_green, 352.1, "王林"), Ringo(Ringo::color_red, 341.8, "つがる"), Ringo(Ringo::color_yellow, 320.7, "ゴールデンデリシャス") }; // RingoBos型のインスタンスを生成 RingoBox myRingoBox; // 箱に全て入れる for (int i=0; i < init_num; i++) { bool ret = myRingoBox.Add(myRingo[i]); if (ret) { std::cout << "1個追加" << std::endl; } } // 2番目のものを箱から取り出す。 bool ret = myRingoBox.Del(2); if (ret) { std::cout << "1個削除" << std::endl; } // データを全て表示する。 myRingoBox.PrintData(); return 0; }
true
40beac246515f7fef2551051505088767bb2c5bd
C++
m1kron/SimpleTaskSystem
/sts/include/sts/tasking/TaskHandle.h
UTF-8
2,194
2.875
3
[]
no_license
#pragma once #include <sts\private_headers\common\NamespaceMacros.h> NAMESPACE_STS_BEGIN ///////////////////////////////////////////////////////////// // Handle, that holds entry in pool and allows to release slot. class TaskHandle { friend class TaskAllocator; friend class TaskManager; friend class Task; friend class TaskContext; public: TaskHandle(); // Move ctor: TaskHandle( TaskHandle&& other_task ); TaskHandle& operator=( TaskHandle&& other ); // Cannot copy: TaskHandle( TaskHandle& ) = delete; TaskHandle& operator=( TaskHandle& other ) = delete; // Comparsion operators: bool operator==( const TaskHandle& other ) const; bool operator!=( const TaskHandle& other ) const; // Class member access operator. Task* operator->( ) const;//rethink this. // Makes this handle invalid. void Invalidate(); private: TaskHandle( Task* task ); Task* m_task; }; #define INVALID_TASK_HANDLE TaskHandle() //////////////////////////////////////////////////////// // // INLINES: // //////////////////////////////////////////////////////// inline TaskHandle::TaskHandle( Task* task ) : m_task( task ) { } //////////////////////////////////////////////////////// inline TaskHandle::TaskHandle() : m_task( nullptr ) { } //////////////////////////////////////////////////////// inline TaskHandle::TaskHandle( TaskHandle&& other_task ) : m_task( other_task.m_task ) { other_task.Invalidate(); } //////////////////////////////////////////////////////// inline Task* TaskHandle::operator->( ) const { return m_task; } ////////////////////////////////////////////////////////s inline TaskHandle& TaskHandle::operator=( TaskHandle&& other ) { m_task = other.m_task; other.Invalidate(); return *this; } ////////////////////////////////////////////////////////s inline bool TaskHandle::operator==( const TaskHandle& other ) const { return m_task == other.m_task; } ////////////////////////////////////////////////////////s inline bool TaskHandle::operator!=( const TaskHandle& other ) const { return m_task != other.m_task; } //////////////////////////////////////////////////////// inline void TaskHandle::Invalidate() { m_task = nullptr; } NAMESPACE_STS_END
true
3974ca6eeef54d020bfbb5ab8ddb72b6717ac210
C++
NeelayRaj/CPPNotes
/Array/BubbleSort.cpp
UTF-8
629
3.421875
3
[]
no_license
#include <iostream> using namespace std; int main() { int n; cout << "Enter Size of array "; cin >> n; int arr[n]; cout << "Enter element of array "; for(int i = 0; i < n; i++) cin >> arr[i]; for(int i = 0; i < n; i++) { for(int j = 0; j < n-1; j++) { if(arr[i]<arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } cout << "Array after sorting "; for(int i = 0; i < n; i++) cout << arr[i]<<" "; return 0; }
true
da643c0c0a3c120b10d435b9950a0b217138f65e
C++
Wantod/GameMulti
/src/ini/socket/UDPSocket.cpp
ISO-8859-1
3,082
2.6875
3
[]
no_license
#include "UDPSocket.hpp" UDPSocket::UDPSocket() { } UDPSocket::~UDPSocket() { Sockets::CloseSocket(sock); Sockets::Release(); } bool UDPSocket::init(bool blocking) { if (!Sockets::Start()) { std::cout << "Erreur initialisation WinSock : " << Sockets::GetError() << std::endl; return false; } // init socket sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // ipv4, UDP if (sock == INVALID_SOCKET) { std::cout << "Erreur initialisation socket : " << Sockets::GetError() << std::endl; return false; } if (blocking && !Sockets::SetNonBlocking(sock)) { std::cout << "Erreur settings non bloquant : " << Sockets::GetError() << std::endl; return false; } return true; } Sockets::Address UDPSocket::getSocket() { Sockets::Address addr; addr.set(server); return addr; } bool UDPSocket::bind(unsigned short port) { server.sin_addr.s_addr = INADDR_ANY; // indique que toutes les sources seront acceptes // UTILE: si le port est 0 il est assign automatiquement server.sin_port = htons(port); // toujours penser traduire le port en rseau server.sin_family = AF_INET; // notre socket est UDP socklen_t size = sizeof(server); getsockname(sock, (struct sockaddr *) &server, &size); if (::bind(sock, reinterpret_cast<SOCKADDR *>(&server), sizeof(server)) == SOCKET_ERROR) { std::cout << "Erreur bind : " << Sockets::GetError() << std::endl; return false; } return true; } bool UDPSocket::wait() { fd_set readset; timeval timeout = { 0 }; int selectRedy; FD_ZERO(&readset); FD_SET(sock, &readset); selectRedy = select(sock + 1, &readset, nullptr, nullptr, &timeout); if (selectRedy == -1) { std::cout << "Erreur select : " << Sockets::GetError() << std::endl; return false; } else if (selectRedy > 0) { if (FD_ISSET(sock, &readset)) { return true; } } return false; } int UDPSocket::recv(void *data, std::size_t size, Sockets::Address &addr) { //if (!wait()) // return -1; /* a client is talking */ int sinsize = sizeof (addr.sin); int n = recvfrom(sock, static_cast<char*>(data), static_cast<int>(size), 0, reinterpret_cast<sockaddr*>(&addr.sin), &sinsize); if (n < 0) return -1; return n; } bool UDPSocket::send(const void *data, std::size_t size, Sockets::Address &addr) { if (sendto(sock, static_cast<const char*>(data), static_cast<int>(size), 0, reinterpret_cast<sockaddr*>(&addr.sin), sizeof (addr.sin)) < 0) { std::cout << "Erreur send()" << std::endl; return false; } return true; } int UDPSocket::recv(Packet &packet, Sockets::Address & addr) { int sinsize = sizeof(addr.sin); int n = recvfrom(sock, packet.data(), static_cast<int>(packet.fullSize()), 0, reinterpret_cast<sockaddr*>(&addr.sin), &sinsize); if (n < 0) return -1; packet.appendSize(n); return n; } bool UDPSocket::send(const Packet &packet, Sockets::Address & addr) { if (sendto(sock, packet.data(), static_cast<int>(packet.size()), 0, reinterpret_cast<sockaddr*>(&addr.sin), sizeof(addr.sin)) < 0) { std::cout << "Erreur send()" << std::endl; return false; } return true; }
true
c792aab16e51f62e9b6bca2b03d49d7546768846
C++
lolzballs/Blocket
/src/util/aabb.h
UTF-8
1,850
3
3
[]
no_license
#ifndef AABB_H #define AABB_H #include "geom.h" #include "vertex.h" #include <array> #include <vector> class AABB { public: AABB(glm::vec3 position, glm::vec3 min, glm::vec3 max); ~AABB(); inline void SetPosition(glm::vec3 position) { m_position = position; } inline glm::vec3 GetPosition() { return m_position; } inline void SetMin(glm::vec3 min) { m_min = min; } inline glm::vec3 GetMin() { return m_min; } inline glm::vec3 GetAbsMin() { return m_min + m_position; } inline void SetMax(glm::vec3 max) { m_max = max; } inline glm::vec3 GetMax() { return m_max; } inline glm::vec3 GetAbsMax() { return m_max + m_position; } inline glm::vec3 GetSize() { return m_max - m_min; } inline glm::vec3 GetCenter() { return (GetAbsMin() + GetAbsMax()) / 2.0f; } AABB Expand(glm::vec3 amount); bool Intersects(AABB other); std::array<Vertex, 32> GetBoundingBoxVertices(glm::vec4 color = glm::vec4(1, 1, 1, 1)); static std::vector<AABB> GetAllAABBs(AABB area); static bool Contains(glm::vec2 point, glm::vec2 points[4]); static bool Intersects(Geom::Quad2 quad, Geom::Line2 line); static bool IntersectX(Geom::Quad3 quad, Geom::Quad3 qSta, glm::vec3 velocity); static bool IntersectX(Geom::Quad3 quad, Geom::Line3 line); static bool IntersectY(Geom::Quad3 quad, Geom::Quad3 qSta, glm::vec3 velocity); static bool IntersectY(Geom::Quad3 quad, Geom::Line3 line); static bool IntersectZ(Geom::Quad3 quad, Geom::Quad3 qSta, glm::vec3 velocity); static bool IntersectZ(Geom::Quad3 quad, Geom::Line3 line); private: glm::vec3 m_position; glm::vec3 m_min; glm::vec3 m_max; }; #endif
true
d3c4523d33b28b0cf410cbefb67456c0ce1ff161
C++
andriatv/Uzduotis_1
/Skaiciai.cpp
UTF-8
1,273
2.78125
3
[]
no_license
// // Created by Lenovo on 2021-04-07. // #include "Skaiciai.h" int TiesinePaieska(const vector<int>&sarasas,int raktinisZodis){ for (int i = 0; i < sarasas.size(); ++i) { if(raktinisZodis == sarasas[i]){ return i; } } return -1; } vector<int> TiesinePaieskaVisi(const vector<int>&sarasas,int raktinisZodis){ vector<int>laikinasSarsas; for (int i = 0; i <sarasas.size() ; ++i) { if(raktinisZodis == sarasas[i]){ laikinasSarsas.emplace_back(i); } } return laikinasSarsas; } int DvejetainePaieska(vector<int>&sarasas, int kaire, int desine, int raktinisZodis){ std::sort(sarasas.begin(), sarasas.end()); cout << " " << endl; cout <<"Skaiciu sarasas (surusiuotas): "<<endl; cout << "_________________________________________________" << endl; for (auto it:sarasas){ cout << it<<" "; } while(kaire<=desine){ int vidurioElementas = kaire +(desine -kaire)/2; if (sarasas[vidurioElementas] == raktinisZodis){ return vidurioElementas; } if(sarasas[vidurioElementas]< raktinisZodis){ kaire= vidurioElementas +1; }else{ desine = vidurioElementas -1; } } return -1; }
true
b3a4cfedd5e6d38034e88bea0900f6bdaeabdadf
C++
bmoretz/Daily-Coding-Problem
/cpp/hackerrank/sample.h
UTF-8
7,445
3.34375
3
[ "MIT" ]
permissive
#pragma once #include <sstream> #include <stack> #include <memory> #include <cassert> #include "problem.h" namespace hackerrank::sample { /// <summary> /// some simple problems that I use to test the problem /// solving framework. /// </summary> /// /// struct tutorial_string_stream final : problem { using problem::problem; explicit tutorial_string_stream(std::string&& name) : problem(std::move(name)) { entry_point = []() { return main(); }; } static std::vector<int> parse_integers(const std::string& str) { std::istringstream iss(str); std::vector<int> results; std::string integer; while (std::getline(iss, integer, ',')) results.emplace_back(std::stoi(integer)); return results; } static int main() { std::string str; std::cin >> str; auto integers = parse_integers(str); for (auto integer : integers) { std::cout << integer << "\n"; } return 0; } }; struct tutorial_string final : problem { explicit tutorial_string(std::string&& name) : problem(std::move(name)) { entry_point = [this]() { return main(); }; } int main() { std::string a, b; std::getline(std::cin, a); std::getline(std::cin, b); std::cout << a.size() << " " << b.size() << std::endl; std::cout << a + b << std::endl; std::swap(a[0], b[0]); std::cout << a << " " << b << std::endl; return 0; } }; struct tutorial_struct final : problem { explicit tutorial_struct(std::string&& name) : problem(std::move(name)) { entry_point = [this]() { return main(); }; } struct student { int age; std::string first_name, last_name; int standard; }; int main() { student st; std::cin >> st.age >> st.first_name >> st.last_name >> st.standard; std::cout << st.age << " " << st.first_name << " " << st.last_name << " " << st.standard; return 0; } }; struct box_it final : problem { explicit box_it( std::string&& name ) : problem( std::move( name ) ) { entry_point = [this]() { return main(); }; } // The class should have the following functions : using box_size = unsigned long long; //Implement the class Box //l,b,h are integers representing the dimensions of the box class box { box_size l_{}, b_{}, h_{}; public: box() { } box( const box_size l, const box_size b, const box_size h ) : l_{ l }, b_{ b }, h_{ h } { } // Constructors: // Box(); // Box(int,int,int); // Box(Box); box( const box& other ) = default; // int getLength(); // Return box's length box_size getLength() const { return l_; } // int getBreadth (); // Return box's breadth box_size getBreath() const { return b_; } // int getHeight (); //Return box's height box_size getHeight() const { return h_; } // long long CalculateVolume(); // Return the volume of the box box_size CalculateVolume() const { return l_ * b_ * h_; } //Overload operator < as specified //bool operator<(Box& b) bool operator<( const box& b ) { return ( l_ < b.l_ ) || ( b_ < b.b_&& l_ == b.l_ ) || ( h_ < b.h_&& b_ == b.b_ && l_ == b.l_ ); } //Overload operator << as specified //ostream& operator<<(ostream& out, Box& B) friend std::ostream& operator<<( std::ostream& out, const box& other ); }; void check2() { int n; std::cin >> n; box temp; for( auto i = 0; i < n; i++ ) { int type; std::cin >> type; if( type == 1 ) { std::cout << temp << std::endl; } if( type == 2 ) { int l, b, h; std::cin >> l >> b >> h; const box NewBox( l, b, h ); temp = NewBox; std::cout << temp << std::endl; } if( type == 3 ) { int l, b, h; std::cin >> l >> b >> h; box new_box( l, b, h ); if( new_box < temp ) { std::cout << "Lesser\n"; } else { std::cout << "Greater\n"; } } if( type == 4 ) { std::cout << temp.CalculateVolume() << std::endl; } if( type == 5 ) { const auto& new_box( temp ); std::cout << new_box << std::endl; } } } int main() { check2(); return 0; } }; inline std::ostream& operator<<(std::ostream& out, const box_it::box& other) { out << other.getLength() << " " << other.getBreath() << " " << other.getHeight(); return out; } struct fizz_buzz final : problem { explicit fizz_buzz( std::string&& name ) : problem( std::move( name ) ) { entry_point = [this]() { return main(); }; } void fizzBuzz( const int n ) { for( auto index = 1; index < n + 1; ++index ) { if( index % 3 == 0 ) std::cout << "Fizz"; if( index % 5 == 0 ) std::cout << "Buzz"; if( index % 3 != 0 && index % 5 != 0 ) std::cout << index; std::cout << std::endl; } } int main() { std::string n_temp; std::getline( std::cin, n_temp ); const auto n = std::stoi( ltrim( rtrim( n_temp ) ) ); fizzBuzz( n ); return 0; } std::string ltrim( const std::string& str ) { auto s( str ); return s.erase( 0, s.find_first_not_of( ' ' ) );; } std::string rtrim( const std::string& str ) { auto s( str ); return s.substr( s.find_first_not_of( ' ' ) );; } }; struct inheritance final : problem { explicit inheritance( std::string&& name ) : problem( std::move( name ) ) { entry_point = []() { return main(); }; } class Triangle { public: void triangle() { std::cout << "I am a triangle\n"; } virtual void description() = 0; }; class Isosceles : public Triangle { public: void isosceles() { std::cout << "I am an isosceles triangle\n"; } void description() override { std::cout << "In an isosceles triangle two sides are equal" << std::endl; } }; static int main() { Isosceles isc; isc.isosceles(); isc.description(); isc.triangle(); return 0; } }; struct ra_inheritance final : problem { explicit ra_inheritance( std::string&& name ) : problem( std::move( name ) ) { entry_point = [this]() { return main(); }; } class rectangle { protected: int width_ = 0, height_ = 0; public: virtual ~rectangle() = default; virtual void read_input() = 0; virtual void display() { std::cout << width_ << " " << height_ << std::endl; } }; class rectangle_area : public rectangle { public: void read_input() override { std::cin >> width_ >> height_; } void display() override { std::cout << width_ * height_ << std::endl; } }; static int main() { rectangle_area r_area; r_area.read_input(); r_area.rectangle::display(); r_area.display(); return 0; } }; struct mult_inheritance final : problem { explicit mult_inheritance( std::string&& name ) : problem( std::move( name ) ) { entry_point = []() { return main(); }; } class tri { public: void triangle() { std::cout << "I am a triangle\n"; } }; class iso : public tri { public: void isosceles() { std::cout << "I am an isosceles triangle" << std::endl; } }; class equ : public iso { public: void equilateral() { std::cout << "I am an equilateral triangle" << std::endl; } }; static int main() { equ eqr; eqr.equilateral(); eqr.isosceles(); eqr.triangle(); return 0; } }; }
true
9b14e3103adea0008e6d87d69f9ee88a2b85956d
C++
Balog/Synchonization
/копия/Сервер/tReadWriteMutex.h
UTF-8
978
2.78125
3
[]
no_license
#ifndef TREADWRITEMUTEX_H #define TREADWRITEMUTEX_H #include <QSemaphore> #include <QMutex> #include <vector> #include<QDebug> using namespace std; class tReadWriteMutex { public: tReadWriteMutex(const int _max); ~tReadWriteMutex(); void lockRead(const QString &_login); void unlockRead(const QString &_login); void lockWrite(const QString &_login); void unlockWrite(); bool IsFree(); bool isWriteBlock(); void unlockReadWrite(const QString &_login); int maxReaders() const; bool isWriteBlock(const QString &_login) const; private: int max; QSemaphore semaphore; QMutex mutex; QString write_user_login; typedef vector<QString>user_semaphore; //список логинов клиентов занявших семафор. Для возвращения при неожиданном завершении клиента user_semaphore us; }; #endif // TREADWRITEMUTEX_H
true
52b05ee2ab412686b0abc9e738c4eadad36bd4bd
C++
Edacth/AIE-Assignments
/CodeDesign/DynamicArrays/tStack.h
UTF-8
1,223
3.5625
4
[]
no_license
// tStack.h #pragma once #include "tVector.h" template <typename T> class tStack { tVector<T> vec; // contains the data for a stack public: tStack(); // initializes the stack's default values ~tStack(); void push(const T& value); // adds an element to the top of the Stack void pop(); // drops the top-most element of the Stack T& top(); // returns the top-most element at the given element const T& top() const; size_t size(); bool empty() const; size_t size() const; // returns current number of elements }; template <typename T> tStack<T>::tStack() { } template <typename T> tStack<T>::~tStack() { } template <typename T> void tStack<T>::push(const T& value) { vec.push_back(value); } template <typename T> void tStack<T>::pop() { vec.pop_back(); } template <typename T> T& tStack<T>::top() { return vec[vec.used() - 1]; } template <typename T> const T& tStack<T>::top() const { return vec[vec.used() - 1]; } template <typename T> size_t tStack<T>::size() { return vec.used(); } template <typename T> inline bool tStack<T>::empty() const { return (vec.used() == 0); }
true
fd2869bd9396e2589475c61cbc211edb95bb9342
C++
AntoineDrouhin/cpp-samples
/functions/factorial.cpp
UTF-8
242
2.828125
3
[]
no_license
#include <cstdio> #include "factorial.h" using namespace std; int main(int argc, char ** argv){ printf("%lu\n", factorial(5)); } unsigned long factorial( unsigned long n) { if (n < 2) return 1; return factorial (n - 1) * n; }
true
2b3d1115e47b3845e98024c9270a8c80d21ef5b0
C++
aemylt/High-Performance-Computing
/opencl_example/opencl-exercises-2013/Solutions/Solution05/matmul_par.cpp
UTF-8
4,003
2.71875
3
[]
no_license
//------------------------------------------------------------------------------ // // PROGRAM: Matrix Multipliplication // // PURPOSE: This is a simple matrix multiplication program // // C = A * B // // A and B are set to constant matrices so we // can make a quick test of the multiplication. // // We run a distinct dot-product for each element of the // product matrix, C. // // USAGE: The matrices are constant matrices, square and the order is // set as a constant, ORDER (see mult.h). // // HISTORY: Written by Tim Mattson, November 2013 //------------------------------------------------------------------------------ #include "matmul.hpp" #include "matrix_lib.hpp" // pick up device type from compiler command line or from the default type #ifndef DEVICE #define DEVICE CL_DEVICE_TYPE_DEFAULT #endif int main(void) { int N; // A[N][N], B[N][N], C[N][N] int sz; // number of elements in each matrix float tmp; N = ORDER; sz = N * N; std::vector<float> h_A(sz); // Matrix A on the host std::vector<float> h_B(sz); // Matrix B on the host std::vector<float> h_C(sz); // Matrix C on the host cl::Buffer d_A; // matrix A on the device cl::Buffer d_B; // matrix B on the device cl::Buffer d_C; // matrix C on the device initmat(N, N, N, h_A, h_B, h_C); printf("\n===== Sequential, matrix mult (dot prod), order %d on CPU ======\n",ORDER); zero_mat(N, N, h_C); util::Timer timer; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { tmp = 0.0f; for (int k = 0; k < N; k++) { tmp += h_A[i*N+k] * h_B[k*N+j]; } h_C[i*N+j] = tmp; } } double rtime = static_cast<double>(timer.getTimeMilliseconds()) / 1000.0; results(N, N, N, h_C, rtime); printf("\n===== Parallel matrix mult (dot prod), order %d on CPU ======\n",ORDER); zero_mat(N, N, h_C); try { cl::Context context(DEVICE); // Load in kernel source, creating a program object for the context. // Build program explicitly so I can catch the error and display // compiler error messages (should any be generated) cl::Program program(context, util::loadProgram("matmul1.cl")); try { program.build(); } catch (cl::Error error) { // If it was a build error then show the error if (error.err() == CL_BUILD_PROGRAM_FAILURE) { std::vector<cl::Device> devices; devices = context.getInfo<CL_CONTEXT_DEVICES>(); std::string built = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]); std::cerr << built << "\n"; } throw error; } // Get the command queue cl::CommandQueue queue(context); // Create the kernel functor auto mmul = cl::make_kernel<int, cl::Buffer, cl::Buffer, cl::Buffer>(program, "mmul"); util::Timer timer; d_A = cl::Buffer(context, begin(h_A), end(h_A), true); d_B = cl::Buffer(context, begin(h_B), end(h_B), true); d_C = cl::Buffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * sz); mmul( cl::EnqueueArgs( queue, cl::NDRange(N,N)), N, d_A, d_B, d_C); cl::copy(queue, d_C, begin(h_C), end(h_C)); double rtime = static_cast<double>(timer.getTimeMilliseconds()) / 1000.0; results(N, N, N, h_C, rtime); } catch (cl::Error err) { std::cout << "Exception\n"; std::cerr << "ERROR: " << err.what() << std::endl; } }
true
00d05271c56b6f8cc77e5bf2cfb0d934137107e0
C++
abhinavp13/Opengl-Ubuntu
/Final Game Project/source/myfile.cpp
UTF-8
4,825
2.640625
3
[]
no_license
#include "SDL/SDL_mixer.h" #include <iostream> #include<sstream> using namespace std; //840x680 bool start=false; bool stop=false; int arrow_x=350; int arrow_y=295; int choice=1; int score=0; int lives=10; string sscore; string slives; ostringstream temp1,temp2; char *temp; //The music that will be played Mix_Music *music = NULL; //The sound effects that will be used Mix_Chunk *fire = NULL; Mix_Chunk *blast = NULL; Mix_Chunk *shell = NULL; //The event structure SDL_Event event; void music_start(); void music_stop(); void draw_startpage(); void check_arrow(); void output(int x, int y, char *string); void output_h(int x, int y, char *string); void check_arrow(); void music_fire(); void music_blast(); void sound_effect(); void draw_score(); void draw_gameover(); void init_startpage() { //Initialize SDL_mixer if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 ) cout<<"ERROR initializing sound"<<endl; music_start(); } void deinit_startpage() { //Free the music Mix_FreeMusic( music ); //Free the sound effects Mix_FreeChunk( fire ); Mix_FreeChunk( blast ); //Quit SDL_mixer Mix_CloseAudio(); } void music_start() { //Load the music music = Mix_LoadMUS( "music.wav" ); //If there was a problem loading the music if( music == NULL ) { cout<<"ERROR loading music"<<endl; } //Play the music if( Mix_PlayMusic( music, -1 ) == -1 ) { cout<<"ERROR playing music"<<endl; } fire = Mix_LoadWAV( "fire.wav" ); blast = Mix_LoadWAV( "blast.wav" ); shell = Mix_LoadWAV ("shell.wav"); //If there was a problem loading the sound effects if( ( fire == NULL ) || ( blast == NULL ) || shell == NULL ) { cout<<"ERROR loading sound effects"<<endl; } } void music_stop() { Mix_HaltMusic(); } void draw_startpage() { output_h(250,100,"B A L L O O N B L A S T E R"); output(400,300, "PLAY"); output(400,350, "EXIT"); arrow_y=295+(choice-1)*50; glBegin(GL_TRIANGLES); glVertex3f(arrow_x, arrow_y, 0); glVertex3f(arrow_x-20, arrow_y-10, 0); glVertex3f(arrow_x-20, arrow_y+10, 0); glEnd(); glFlush(); check_arrow(); } void output_h(int x, int y, char *string) { int len, i; //glColor3f(1.0, 0.0, 0.0); glRasterPos2f(x, y); len = (int) strlen(string); for (i = 0; i < len; i++) { glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, string[i]); } } void output(int x, int y, char *string) { int len, i; //glColor3f(1.0, 0.0, 0.0); glRasterPos2f(x, y); len = (int) strlen(string); for (i = 0; i < len; i++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, string[i]); } } void draw_score() { output(600,600,"Score\t"); temp1<<score; sscore=temp1.str(); temp = new char [sscore.length()+1]; strcpy (temp, sscore.c_str()); output(700, 600, temp); delete temp; temp1.str(""); output(600,650,"Lives\t"); temp2<<lives; slives=temp2.str(); temp = new char [slives.length()+1]; strcpy (temp, slives.c_str()); output(700, 650, temp); delete temp; temp2.str(""); } void check_arrow() { while( SDL_PollEvent( &event ) ) { //If a key was pressed if( event.type == SDL_KEYDOWN ) { switch( event.key.keysym.sym ) { case SDLK_UP: if (choice >1 ) choice--; break; case SDLK_DOWN: if (choice<2) choice++; break; case SDLK_RETURN: switch (choice) { case 1: music_stop(); start=true; break; case 2: exit(0); break; default: ; } default : ; } } } } void music_fire() { Mix_PlayChannel( -1, fire, 0 ); Mix_PlayChannel (-1, shell, 0); } void music_blast() { Mix_PlayChannel( -1, blast, 0 ); } void sound_effect() { while( SDL_PollEvent( &event ) ) { //If a key was pressed if( event.type == SDL_KEYDOWN ) { switch( event.key.keysym.sym ) { case SDLK_UP: music_fire(); break; case SDLK_DOWN: score++; //music_blast(); break; default : ; } } } } void draw_gameover() { output_h(350,100,"G A M E O V E R"); output(400,200, "Your Score "); temp1<<score; sscore=temp1.str(); temp = new char [sscore.length()+1]; strcpy (temp, sscore.c_str()); output(440, 250, temp); delete temp; temp1.str(""); }
true
215c6c16c9a9ad4ccb5be4ad60a5cc257fd82b1c
C++
kanaev-ch/tetris
/Cube.h
UTF-8
1,057
2.53125
3
[]
no_license
#pragma once #include <iostream> #include <SFML/Graphics.hpp> #include "Shape.h" #include "Data.h" class Cube //cube - component of future figures // :public Shape//inherit from virtual Class shape, in future will create Polymorph claster from Shape { private: float x, y;//coords of cube on screen // sf::RectangleShape rect_cube;//rectangle of cube, rect_cube needs if no sprites bool same;//flag if elements is same with other 10 elements in line sf::Sprite sprite;//sprite of Cube int type_figure;//var needs for memory what kind of figure owns this Cube, in future will load sprite in FloorArray.DRAW, without it will bug of draw bottom array public: Cube(); Cube(float, float); Cube(float, float, sf::Texture&, int, int, int); ~Cube(); float X()const; void X(float); float Y()const; void Y(float); void SAME(bool); bool SAME()const; void SPRITE(sf::Sprite &); void TYPE_FIGURE(int); int TYPE_FIGURE()const; void DRAW(sf::RenderWindow&)const;//draw cube void MOVE(float, float, float); void SETPOSITION(float, float); };
true
be87ef305b8c32986ac98929236304ca61f61448
C++
Amanuttam1192/The-CP-Companion
/RECURSION/QUESTION 3/Solution_3.cpp
UTF-8
318
3.078125
3
[]
no_license
/* Solution of Recursion question 3 in C++ By: Shourya Gupta */ #include <iostream> using namespace std; void multiply(int n,int temp){ cout<<n<<" x "<<temp<<" = "<<n*temp<<endl; temp++; if (temp<=10){ multiply(n, temp); } } int main() { int num,temp=1; cin>>num; multiply(num,temp); }
true
9c2dab0533ec0e40566cc57a102ee2882d142fce
C++
Jean-xavierr/42Piscine_CPP
/cpp04/ex03/Ice.cpp
UTF-8
1,367
2.75
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Ice.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jereligi <jereligi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/10/15 17:17:20 by jereligi #+# #+# */ /* Updated: 2020/10/15 18:19:12 by jereligi ### ########.fr */ /* */ /* ************************************************************************** */ #include "Ice.hpp" Ice::Ice(void) : AMateria("ice") { return ; } Ice::Ice(Ice const &src) : AMateria("ice") { *this = src; } Ice::~Ice(void) { return ; } Ice &Ice::operator=(Ice const &src) { this->type = src.type; this->xp = src.xp; return (*this); } AMateria *Ice::clone() const { Ice *clone = new Ice(*this); return clone; } void Ice::use(ICharacter& target) { AMateria::use(target); std::cout << "* shoots an ice bolt at " << target.getName() << " *" << std::endl; }
true
974e4b35747f5efa9d4d5ac617714db5dfc04e2f
C++
m0r1k/IPNoise
/packages/ipnoise-ui/ui-rc/src/prop/time.cpp
UTF-8
1,215
2.84375
3
[]
no_license
#include "prop/time.hpp" PropTime::PropTime() : Prop(Prop::PROP_TYPE_TIME) { m_val = 0.0f; } PropTime::PropTime( const double &a_val) : Prop(Prop::PROP_TYPE_TIME) { m_val = a_val; setDirty(1); } PropTime::~PropTime() { } string PropTime::toString() const { char buffer[512] = { 0x00 }; snprintf(buffer, sizeof(buffer), "%f", m_val ); return buffer; } string PropTime::serialize( const string &) const { return toString(); } PropTimeSptr PropTime::now() { PropTimeSptr ret(new PropTime); ret->reset(); return ret; } void PropTime::reset() { struct timeval tv; gettimeofday(&tv, NULL); m_val = tv.tv_sec + tv.tv_usec / 1e6; setDirty(1); } double PropTime::getVal() const { return m_val; } PropTime::operator PropSptr() const { return PropSptr(new PropTime(*this)); } PropTime::operator double() const { return m_val; } PropTime::operator int32_t() const { return (int32_t)m_val; } PropTime::operator int64_t() const { return (int64_t)m_val; } bool PropTime::operator != ( const PropTime &a_right ) const { bool ret = false; ret = (m_val != a_right.m_val); return ret; }
true
58a2445200be64fc1c9f4ed76ec8b52565ab818b
C++
henrievjen/CS-1575
/2020-sp-a-hw2-hoe4ng/bag_simple.hpp
UTF-8
1,190
3.296875
3
[]
no_license
/* Templated implementations of a simple bag * Note the lack of including the h file! * The h file includes the hpp at the bottom! */ // Define your name function here: void get_identity(string &my_id) { my_id = "hoe4ng"; } // Fix this function to throw a MyException when full template <typename T> bool SimpleBag<T>::insert(const T &myItem) { try { if (size() >= CAPACITY) { throw MyException(); } data[used] = myItem; used++; return true; } catch (const MyException &err) { std::cerr << err.what(); return false; } } template <typename T> bool SimpleBag<T>::remove(const T &myItem) { if (used == 0) // empty SimpleBag. return false; int index = 0; while (index < used && data[index] != myItem) index++; //if myItem is not present, index would be == used. if (index == used) return false; // myItem is now removed. // we overwrite data[index] with data[used - 1] and decrement used by 1. data[index] = data[used - 1]; used--; return true; }
true
609687c82b5140a81e75af54ce0babccf4f8df2e
C++
Renaultivo/RNI
/src/Core/Core.cpp
UTF-8
2,478
2.75
3
[]
no_license
#include <iostream> #include <time.h> #include "Core.hpp" #include "../Graphics/TextureManager.cpp" #include "../Events/EventHandler.cpp" #include "../UI/UIManager/UIManager.cpp" Core *Core::instance = nullptr; Core::Core() { } Core *Core::getInstance() { if (instance == nullptr) { instance = new Core(); } return instance; } void Core::init( std::string name, unsigned short int width, unsigned short int height ) { this->name = name; this->width = width; this->height = height; // SDL_Init returns 0 on success if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { printf("Failed to initialize SDL: %s", SDL_GetError()); exit(EXIT_FAILURE); } // IMG_Init returns 0 on failure if (IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG) == 0) { printf("Failed to initialize IMG: %s", SDL_GetError()); exit(EXIT_FAILURE); } window = SDL_CreateWindow( this->name.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, this->width, this->height, SDL_WINDOW_RESIZABLE ); if (window == nullptr) { printf("Failed to create window: %s", SDL_GetError()); exit(EXIT_FAILURE); } renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); if (renderer == nullptr) { printf("Failed to create window: %s", SDL_GetError()); exit(EXIT_FAILURE); } state.isRunning = true; TextureManager::getInstance()->load("tree", "../assets/tree.png"); /*std::string id, std::string name, float x, float y, float width, float height,*/ SDL_SetRenderDrawColor(renderer, 34, 34, 34, 255); SDL_RenderClear(renderer); } void Core::events() { EventHandler::getInstance()->listen(); } void Core::quit() { SDL_Quit(); IMG_Quit(); exit(EXIT_SUCCESS); } bool Core::isRunning() { return state.isRunning; } void Core::onResize(SDL_Event *event) { } unsigned short int Core::getScreenWidth() { return this->width; } unsigned short int Core::getScreenHeight() { return this->height; } // S 000000 // 1000000 // 4.166.163 // 60 void Core::render() { /*TextureManager::getInstance()->draw( "tree", 0, 0, 1100, 823 );*/ SDL_RenderPresent(renderer); SDL_SetRenderDrawColor(renderer, 22, 22, 22, 255); SDL_RenderClear(renderer); UIManager::getInstance()->render(); //uiComponent->render(); } SDL_Window *Core::getWindow() { return window; } SDL_Renderer *Core::getRenderer() { return renderer; }
true
3db66e30e498ecf3b250ab8cc891585952bb08bb
C++
TaylorClark/PrimeTime
/GamePlay/GameFieldPrimeTime.h
UTF-8
3,040
2.890625
3
[ "MIT" ]
permissive
//================================================================================================= /*! \file GameFieldPrimeTime.h Game Play Library Game Field Multiplication Header \author Taylor Clark \date May 12, 2006 This header contains the definition for the Prime Time mode game field object. */ //================================================================================================= #pragma once #ifndef __GameFieldPrimeTime_h #define __GameFieldPrimeTime_h #include "GameFieldMultBase.h" class GameFieldBlockProduct; //------------------------------------------------------------------------------------------------- /*! \class GameFieldPrimeTime \brief Represents a game field used for the normal mode of gameplay. This class defines the game field class that is used to encapsulate data related to the block layout of a game field. */ //------------------------------------------------------------------------------------------------- class GameFieldPrimeTime : public GameFieldMultBase { private: enum EBlockDir { BD_Right = 0, BD_Up, BD_Left, BD_Down }; struct SurroundingBlocks { SurroundingBlocks() { for( int32 blockIndex = 0; blockIndex < NumSurrounding; ++blockIndex ) blocks[blockIndex] = 0; } static const int32 NumSurrounding = 8; GameFieldBlock* blocks[NumSurrounding]; }; /// The combo block bounding box Box2i m_ComboBlockBoundBox; /// The combo block bounding box in field coordinates Box2i m_ComboBlockFieldBoundBox; /// The combo block, NULL if there is none GameFieldBlockProduct* m_pComboBlock; MultBlockList m_ComboableProducts; AnimSprite m_ComboSelection; AnimSprite m_WideComboSelection; /// Get the blocks that surrounding a block BlockList GetSurroundingBlocks( GameFieldBlockProduct* pBlock ); /// Remove blocks virtual void RemoveBlock( GameFieldBlockProduct* pBlock ); /// Update the game field virtual void SubclassUpdate( float frameTime ); public: /// The default constructor GameFieldPrimeTime() : m_pComboBlock( 0 ) {} /// The destructor virtual ~GameFieldPrimeTime() { ClearField(); } /// Initialize the field virtual bool Init(); /// Draw the game virtual void Draw() const; /// Get the block at a position on the field virtual GameFieldBlock* GetBlockAtPos( const Point2i& fieldPos ); /// Determine if a block is comboable bool IsBlockComboable( GameFieldBlockProduct* pBlock, MultBlockList::const_iterator* pIterBlock = NULL ) const; bool IsBlockComboable( GameFieldBlockProduct* pBlock, MultBlockList::iterator* pIterBlock = NULL ); /// Set the combo block void SetComboBlock( int32 blockValue ); /// Get the combo block GameFieldBlockProduct* GetComboBlock() { return reinterpret_cast<GameFieldBlockProduct*>(m_pComboBlock); } /// Add comboable blocks to the list void AddToComboBlocksFromSelection(); /// Clear the comboable blocks void ClearComboable() { m_ComboableProducts.clear(); } /// Clear the field virtual void ClearField(); }; #endif // __GameFieldPrimeTime_h
true
fb1dfc79e39e88e3c36111e92d9067b9a9d386ad
C++
alexarenasf/IA-ForwardChecking
/main.cpp
UTF-8
5,359
2.546875
3
[ "MIT" ]
permissive
using namespace std; #include "forwardchecking.h" int main(int argc, char **argv){ cout << "Algoritmo Forward Checking + Conflict-directed Back Jumping para el OPHS" << endl; cout << "Alex Arenas F." << endl << endl; if(argc<3){ cout << "Faltan parámetros." << endl << endl; cout << "Para ejecutar escribir" << endl; cout << "> make INSTANCE={instancia}" << endl << endl; cout << "Debe existir el archivo ./instances/SET0/{instancia}.ophs" << endl << endl; cout << "Para más información, lea el archivo Readme.md" << endl << endl; return 0; } bool rehacer_u = false; stringstream p; string path = ""; Helper helper; string instancia = ""; stringstream rutas_path; p << "./instances/SET0/"; for(int i = 1; i < argc; i++){ if(strcmp(argv[i],"-instance")==0){ if(argc>=3){ instancia = argv[i+1]; p << argv[i+1]; p << ".ophs"; path = p.str(); } i++; }else if(strcmp(argv[i],"-make-routes")==0){ rehacer_u = true; } } if(instancia.empty()){ cout << "No se ha especificado una instancia." << endl << endl; return 0; } if(!helper.ArchivoExiste(path)){ cout << "No Existe la instancia " << path << endl << endl; return 0; } int H; int N; int D; vector<int> S; vector<vector<double> > t; vector<double> T; helper.LeerInstancia(path, H, N, D, S, t, T); ForwardChecking forwardchecking(H, N, D, S, t, T); int i,j,k; bool puedoInstanciar; rutas_path << "./tmp/"; rutas_path << instancia; rutas_path << ".routes"; helper.TiempoIniciar(); // Protección contra sobreescritura de rutas if(rehacer_u){ string respuesta; if(helper.ArchivoExiste(rutas_path.str())){ do{ cout << "Ya existe un archivo de rutas generado, desea sobreescribirlo? [S/n] "; getline(cin, respuesta); }while(respuesta.compare("S")!=0 && respuesta.compare("n")!=0); if(respuesta.compare("n")==0) rehacer_u = false; } }else{ // Si no existe el archivo de rutas, hay que hacerlo if(!helper.ArchivoExiste(rutas_path.str())){ rehacer_u = true; } } // Variable u[i] if(rehacer_u){ helper.ReiniciarArchivos(); puedoInstanciar = true; int primeraVariable = H + 1; int ultimaVariable = H + N; i = primeraVariable; helper.TiempoGuardar("Iniciando creación de rutas","u"); while(true){ puedoInstanciar = forwardchecking.Instanciar(i); if(i == ultimaVariable && puedoInstanciar){ //Solución helper.EscribirRuta(forwardchecking.Ruta_u()); helper.TiempoGuardar("Ruta creada","u"); }else if(puedoInstanciar){ // Revisar dominios de variables futuras y avanzar a la variable i i = forwardchecking.CheckForward(i); helper.TiempoGuardar("Checkeando Dominios futuros","u_FC"); }else{ //volver a variable i i = forwardchecking.CBJ(i); helper.TiempoGuardar("Retorno Inteligente","u_CBJ"); } if(i == primeraVariable && forwardchecking.DominioVacio(i)) break; } } helper.TiempoGuardar("Creación de rutas terminada","u"); vector<vector<int> > rutas; helper.LeerRutas(rutas,N); forwardchecking.SetRutas(rutas); helper.TiempoGuardar("Iniciando la busqueda de Tours factibles","X"); // Variable X[i][j][k] while(!forwardchecking.NoHayMasRutas()){ helper.TiempoGuardar("Usando nueva ruta","X"); forwardchecking.DominioReiniciar_ijk(); forwardchecking.IteradorCrear(); //Condiciones iniciales forwardchecking.DominioFiltrar_X(); bool checkearDominio = false; puedoInstanciar = true; string sn; while(true){ forwardchecking.IteradorSet_ijk(i,j,k); puedoInstanciar = forwardchecking.Instanciar(i,j,k); if(forwardchecking.IteradorUltimo() && puedoInstanciar){ // Solución if(forwardchecking.Instancia_X(helper)){ helper.TiempoGuardar("Tour Solución encontrado","X"); } }else if(puedoInstanciar){ // Revisar dominios de variables futuras y avanzar a la variable ijk forwardchecking.CheckForward(i,j,k); helper.TiempoGuardar("Checkeando Dominios futuros","X_FC"); if(checkearDominio){ cout << "FC" << endl; forwardchecking.Dominio_ijk(); getline(cin, sn); } }else{ //volver a variable i forwardchecking.CBJ(i,j,k); helper.TiempoGuardar("Retorno Inteligente","X_CBJ"); if(checkearDominio){ cout << "CBJ" << endl; forwardchecking.Dominio_ijk(); getline(cin, sn); } } if(forwardchecking.IteradorPrimero() && forwardchecking.DominioVacio(i,j,k)){ // Fin del recorrido, se retornó a la raiz y no quedan más valores que instanciar break; } } helper.TiempoGuardar("Terminando la ruta","X"); forwardchecking.SiguienteRuta(); } helper.TiempoGuardar("Terminada la busqueda","X"); return 0; }
true
f4c60709a0f31ef37c4a4a8d0d48b4c260e6491d
C++
ntbrewer/matching_2
/source/include/TraceAnalyzer.h
UTF-8
3,287
2.90625
3
[ "MIT" ]
permissive
/** \file TraceAnalyzer.h * \brief Header file for the TraceAnalyzer class * * SNL - 7-2-07 */ #ifndef __TRACEANALYZER_H_ #define __TRACEANALYZER_H_ #include <string> #include <vector> #include <sys/times.h> using std::string; using std::vector; /** \brief quick online trace analysis * * Trace class implements a quick online trapezoidal fiter for the * identification of double pulses with relatively little computation. */ class TraceAnalyzer { private: // things associated with timing double userTime; ///< user time used by this class double systemTime; ///< system time used by this class double clocksPerSecond; ///< frequency of system clock vector<double> average; ///< trace average vector<int> fastFilter; ///< fast filter of trace vector<int> energyFilter; ///< energy filter of trace vector<int> thirdFilter; /*< third filter of trace, used as a second * threshold check */ vector<int> flt; ///< vector used in filter function int t1; ///< time of E1 pulse int t2; ///< time of E2 pulse double e1; ///< energy of E1 pulse double e2; ///< energy of E2 pulse int rownum850; ///< rownumber of DAMM spectrum 850 int rownum870; ///< rownumber of DAMM spectrum 870 int fastRise; ///< rise time of fast filter (in samples) int slowRise1; ///< rise time of energy filter (in samples) int slowRise2; ///< rise time of slow threshold filter (in samples) int fastGap; ///< gap time of fast filter (in samples) int slowGap1; ///< gap time of energy filter (in samples) int slowGap2; ///< gap time of slow threshold filter (in samples) int fastThresh; ///< threshold of fast filter int slowThresh; ///< threshold of slow filter double avgBaseline; ///< Avg. Baseline of the trace for PSA double stdDevBaseline; ///< Variance of Baseline of the trace for PSA int traceMax; ///< Maximum Value of the trace int region; ///< Region of Trace analysis FOM /** default filename containing filter parameters */ static const std::string defaultFilterFile; public: int Init(const std::string &filterFile=defaultFilterFile); void DeclarePlots(void) const; int Analyze(const vector<int> &, const string &, const string &); vector<int> Filter(vector<int> &, int , int , int , int ); void FilterFill(const vector<int> &, vector<int> &, int, int, int, int); void CalculateTraceMaxAndAvgBaseline(const vector<int> &, vector<int> &, int, int, int, int); void TracePlot(const vector<int> &); int GetTime(void) const {return t1;} int GetSecondTime(void) const {return t2;} double GetEnergy(void) const {return e1;} double GetAvgBaseline(void) const {return avgBaseline;} double GetStdDevBaseline(void) const {return stdDevBaseline;} int GetTraceMax(void) const {return traceMax;} int GetRegion(void) const {return region;} double GetSecondEnergy(void) const {return e2;} TraceAnalyzer(); ~TraceAnalyzer(); }; #endif // __TRACEANALYZER_H_
true
ca5257fff167215a68d59e689a92d43619607b76
C++
rostun/teenyWeeny
/linkedList/deleteDuplicateValues.cpp
UTF-8
1,563
3.578125
4
[]
no_license
/* Cracking the Code Interview 2.1 Write code to remove duplicated from an unsorted linked list */ #include "stdafx.h" #include <string> #include <iostream> #include <map> using namespace std; struct node{ int value; node* next; node(int value){ this->value = value; next = NULL; } }; int _tmain(int argc, _TCHAR* argv[]) { //make nodes node one(1); node two(2); node three(3); node four(4); node two1(2); //1 2 3 4 2 one.next = &two; two.next = &three; three.next = &four; four.next = &two1; //set counter, make hash table node* currentNode; currentNode = &one; map<int, int> valueChart; //one while loop puts things into map while(currentNode != NULL){ valueChart[currentNode->value] = 0; //set them all equal to 0 currentNode = currentNode->next; } //check linked list currentNode = &one; while(currentNode != NULL){ cout <<currentNode->value << endl; currentNode = currentNode->next; } //check map for(auto it = valueChart.begin(); it !=valueChart.end(); it++){ cout << it->first << " " << it->second << endl; } //delete duplicate nodes node* prevNode = NULL; currentNode = &one; while(currentNode != NULL){ if(valueChart[currentNode->value] == 1){ prevNode->next = currentNode->next; //delete currentNode } else{ //visited valueChart[currentNode->value] = 1; } prevNode = currentNode; currentNode = currentNode->next; } //check linked list currentNode = &one; while(currentNode != NULL){ cout <<currentNode->value << endl; currentNode = currentNode->next; } return 0; }
true
9de6d46db999bc3a92a72553c214f9871a741c5f
C++
WhiZTiM/coliru
/Archive2/d6/976cd205e5543e/main.cpp
UTF-8
1,297
2.546875
3
[]
no_license
#include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/cpp_bin_float.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/number.hpp> int main() { namespace mp = boost::multiprecision; //v += 6 * ceil((sqrt(uMax * uMax - candidate) - v) / 6); { using BF = mp::cpp_bin_float_100; using BI = mp::cpp_int; BI v = 1, uMax = 9, candidate = 1; #ifdef DEBUG BF tmp1(uMax * uMax - candidate); BF tmp2(sqrt(BF(uMax * uMax - candidate)) - BF(v)); BF tmp3(ceil(tmp2 / 6)); BI tmp4(tmp3.convert_to<BI>()); std::cout << tmp1 << " " << tmp2 << " " << tmp3 << " " << tmp4 << "\n"; #endif v += 6*ceil((sqrt(BF(uMax * uMax - candidate)) - BF(v)) / 6).convert_to<BI>(); } { using BF = mp::number<mp::cpp_bin_float_100::backend_type, mp::et_off>; using BI = mp::number<mp::cpp_int::backend_type, mp::et_off>; BI v = 1, uMax = 9, candidate = 1; v += 6 * ceil((sqrt(BF(uMax * uMax - candidate)) - BF(v)) / 6).convert_to<BI>(); } { using BF = mp::number<mp::cpp_dec_float_100::backend_type, mp::et_off>; BF v = 1, uMax = 9, candidate = 1; v += 6 * ceil((sqrt(uMax * uMax - candidate) - v) / 6); } }
true
a7ff125dec6d43832e774ed656801a2d4d9ef1f1
C++
astraekr/Development
/superimpose/superimpose.cpp
UTF-8
2,279
2.890625
3
[]
no_license
#include <stdio.h> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; /* * *./SuperImpose ../test_webcam_r.jpg ../test_webcam_centre.jpg ../test_infrared_flip.jpg * * */ const string name = "superimposed.jpeg"; int main (int argc, char ** argv ) { /* * Handle arguments * */ if (argc != 4) { printf("usage: displayimage.out <image_right_path> <image_centre_path> <image_left_path> \n"); return -1; } /* * Get images * */ Mat leftImageTemp, leftImage, rightImage, centreImage, dst, leftImageThresh; double input = 0.0; double beta; double alpha = 0.5; double maxValue = 0.0; //Right webcam image, 352x288 pixels rightImage = imread( argv[1], 0); //Centre webcam image, 352x288 pixels centreImage = imread( argv[2], 0); //IR camera, 80x60 pixels leftImageTemp = imread( argv[3], 0); //cout << leftImageTemp << "\n"; if (!leftImageTemp.data | !rightImage.data | !centreImage.data) { printf("No image data in at least one image\n"); return -1; } //scale the IR image to be of equal resolution to the other two resize(leftImageTemp, leftImage, Size(), 4.4, 4.8, INTER_LINEAR); namedWindow("Display Image Left", WINDOW_AUTOSIZE); namedWindow("Display Image Centre", WINDOW_AUTOSIZE); namedWindow("Display Image Right", WINDOW_AUTOSIZE); imshow("Display Image Left", leftImage); imshow("Display Image Centre", centreImage); imshow("Display Image Right", rightImage); std::cout<<"* Enter Threshold [0-255]: "; std::cin>>input; threshold(leftImage, leftImageThresh, input, maxValue, THRESH_TOZERO); namedWindow("Display Image Left Thresh", WINDOW_AUTOSIZE); imshow("Display Image Left Thresh", leftImageThresh); std::cout<<"* Enter alpha [0-1]: "; std::cin>>input; /// We use the alpha provided by the user if it is between 0 and 1 if( input >= 0.0 && input <= 1.0 ) { alpha = input; } namedWindow("Linear Blend", 1); beta = (1.0 - alpha); addWeighted( centreImage, alpha, leftImageThresh, beta, 0.0, dst); imshow("Linear Blend", dst); imwrite(name, dst); waitKey(0); return 0; }
true
8a3a4529021bf7ae243c7311a55a0847a2ad6593
C++
jainamandelhi/Geeks-For-Geeks-Solutions
/Stack/Sort a stack.cpp
UTF-8
428
3.078125
3
[]
no_license
void dfs1(stack<int>&s,int a) { if(s.size()==0) return; int b=s.top(); s.pop(); if(s.size() && a<s.top()) dfs1(s,a); else s.push(a); s.push(b); } void dfs(stack<int>&s) { if(s.size()==1) return; int a=s.top(); s.pop(); dfs(s); if(a<s.top()) dfs1(s,a); else s.push(a); } void SortedStack :: sort() { dfs(s); //Your code here }
true
7f3e9320bec2f339e64913e005644dafcfbbc5b8
C++
spuder/Foosball
/sandbox/Foosball.ino
UTF-8
658
2.71875
3
[ "LicenseRef-scancode-public-domain" ]
permissive
/** *Program to detect if someone is playing foosball *Uses an Arduino and a Piezo element to detect vibrations * * Revision 0.1 2013-3-15 initial commit Spencer Owen **/ int ledPin = 13; int sensorPin = 2; byte sensorValue = 0; float lastMovement = 0; void setup() { pinMode(ledPin, OUTPUT); Serial.begin(115200); } void loop() { sensorValue = analogRead(sensorPin); Serial.print(sensorValue); if (sensorValue >=10) { lastMovement = millis(); digitalWrite(ledPin, HIGH); } if ( (millis() - lastMovement) > 500) { digitalWrite(ledPin, LOW); } Serial.print("\t :"); Serial.println(lastMovement); delay(50); }
true
0103b76847c8ae112523e58ca7e393dcbfafeb31
C++
trueneu/Karabiner-Elements
/appendix/control_led/main.cpp
UTF-8
1,784
2.765625
3
[ "Unlicense" ]
permissive
#include "hid_manager.hpp" namespace { class control_led final { public: control_led(const control_led&) = delete; control_led(void) : hid_manager_({ std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_keyboard), }) { hid_manager_.device_detected.connect([](auto&& human_interface_device) { auto r = human_interface_device->open(); if (r != kIOReturnSuccess) { krbn::logger::get_logger().error("failed to open"); return; } if (auto caps_lock_led_state = human_interface_device->get_caps_lock_led_state()) { switch (*caps_lock_led_state) { case krbn::led_state::on: krbn::logger::get_logger().info("caps_lock_led_state is on."); break; case krbn::led_state::off: krbn::logger::get_logger().info("caps_lock_led_state is off."); break; } if (caps_lock_led_state == krbn::led_state::on) { human_interface_device->set_caps_lock_led_state(krbn::led_state::off); } else { human_interface_device->set_caps_lock_led_state(krbn::led_state::on); } krbn::logger::get_logger().info("set_caps_lock_led_state is called."); } else { krbn::logger::get_logger().info("failed to get caps_lock_led_state."); } }); hid_manager_.start(); } ~control_led(void) { hid_manager_.stop(); } private: krbn::hid_manager hid_manager_; }; } // namespace int main(int argc, const char* argv[]) { krbn::thread_utility::register_main_thread(); if (getuid() != 0) { krbn::logger::get_logger().error("control_led requires root privilege."); return 1; } control_led d; CFRunLoopRun(); return 0; }
true
738035be8e126adfc6e38314c133e5bdffe08efd
C++
AkshitIITG/Competitive_Coding
/My Templates/Amortized/sliding_window_minimum.cpp
UTF-8
598
3.078125
3
[]
no_license
void sliding_window_min(ll n,ll k,ll arr[]){ deque<ll> q; q.push_back(arr[0]); REP(i,1,k){ while(q.size() > 0 && q.back() >= arr[i]){ q.pop_back(); } q.push_back(arr[i]); } vector<ll> v; v.push_back(q.front()); REP(i,k,n){ if(q.size() > 0 && q.front() == arr[i - k]){ q.pop_front(); } while(q.size() > 0 && q.back() >= arr[i]){ q.pop_back(); } q.push_back(arr[i]); v.push_back(q.front()); } for(auto it:v) cout<<it<<" "; cout<<endl; } int main() { ll n,k; cin>>n>>k; ll arr[n]; REP(i,0,n){ cin>>arr[i]; } sliding_window_min(n,k,arr); return 0; }
true
962cd3a091623f3bbcea54d527a51caeed70b950
C++
martamaira/Projeto-Escultor-3D
/Parte 2/putsphere.cpp
UTF-8
743
3.109375
3
[]
no_license
#include "putsphere.h" #include <cmath> putSphere::putSphere(int xcenter, int ycenter, int zcenter, int radius, float r, float g, float b, float a) { this->xcenter=xcenter; this->ycenter=ycenter; this->zcenter=zcenter; this->radius=radius; this->r=r; this->g=g; this->b=b; this->a=a; } void putSphere::draw(Sculptor &s){ s.setColor(r,g,b,a); int i, j, k; for(i=xcenter-radius; i<=xcenter+radius; i++){ for(j=ycenter-radius; j<=ycenter+radius; j++){ for(k=zcenter-radius; k<=zcenter+radius; k++){ if(((pow(i-xcenter, 2)) + (pow(j-ycenter, 2)) + (pow(k-zcenter, 2))) <= pow(radius, 2)){ s.putVoxel(i, j, k); } } } } }
true
97ee4cdf105a7a579028f09de7797f26cba01123
C++
Vesion/Misirlou
/leetcode/688-KnightProbabilityInChessboard.cpp
UTF-8
1,052
2.8125
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; // DP, O(k*n*n) class Solution { public: double knightProbability(int n, int k, int row, int col) { constexpr int go[8][2] = { {-2,-1}, {-2,1}, {-1,2}, {1, 2}, {2,1}, {2,-1}, {1,-2}, {-1,-2} }; vector<vector<double>> dp(n, vector<double>(n, 0)); dp[row][col] = 1; for (int t = 0; t < k; ++t) { vector<vector<double>> ndp(n, vector<double>(n, 0)); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { for (int d = 0; d < 8; ++d) { int oi = i+go[d][0], oj = j+go[d][1]; if (oi < 0 || oi >= n || oj < 0 || oj >= n) continue; ndp[i][j] += dp[oi][oj] * (1.0 / 8); } } swap(dp, ndp); } double res = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) res += dp[i][j]; return res; } }; int main() { return 0; }
true
2b7a52678630d2954339311a1ff7593526a8d428
C++
zilongwhu/cutility
/include/fast_timer.h
UTF-8
1,298
2.984375
3
[]
no_license
#ifndef __CUTILITY_FAST_TIMER_H__ #define __CUTILITY_FAST_TIMER_H__ #include <cstddef> #include <stdint.h> #include <sys/time.h> class FastTimer { public: FastTimer() { _st.tv_sec = _et.tv_sec = 0; _st.tv_usec = _et.tv_usec = 0; } void start() { ::gettimeofday(&_st, NULL); } void stop() { ::gettimeofday(&_et, NULL); } int64_t stopAndStart() { this->stop(); int64_t us = this->timeInUs(); this->_st = this->_et; return us; } int64_t timeInMs() const { return this->timeInUs()/1000; } int64_t timeInUs() const { return (_et.tv_sec - _st.tv_sec)*1000000l + ((int)_et.tv_usec - (int)_st.tv_usec); } struct timeval startTime() const { return _st; } void startTime(struct timeval tm) { this->_st = tm; } struct timeval stopTime() const { return _et; } void stopTime(struct timeval tm) { this->_et = tm; } private: struct timeval _st; struct timeval _et; }; #endif
true
bf8b2ee60560a0069b010d86f894f8f4b5411f35
C++
Nyakaru/calculator
/calculator.cc
UTF-8
420
3.84375
4
[]
no_license
#include <iostream> using namespace std; // function declaration int Add(int num1, int num2); int Multiply(int num1, int num2); int main() { // your code goes here int sum = Add(10, 15); int product = Multiply(10, 15); std::cout << sum << std::endl; std::cout << product << std::endl; return 0; } int Add(int num1, int num2) { return num1+num2; } int Multiply(int num1, int num2) { return num1*num2; }
true
085ca867b1e1c19822fa3d0cd2954f0a79c76e5c
C++
kimdahyeee/algorithm
/20161218_10451번 순열사이클.cpp
UTF-8
604
3.03125
3
[]
no_license
#include <iostream> using namespace std; int order[1001]; bool check[1001]; int cycle_check(int num) { int start, end; int result = 0; for (int i = 0; i < num; i++) { if (check[i + 1] != true) { result++; start = i + 1; end = order[start]; check[start] = true; } while (start != end) { check[end] = true; end = order[end]; } } return result; } int main() { int t, n; int vertex; cin >> t; while (t--) { cin >> n; for(int i=1; i<=n; i++){ cin >> order[i]; check[i] = false; } cout << cycle_check(n) << endl; } }
true
ad3261f79406982f82bb2045b8125030f5f90465
C++
themarioga/CCLHBot
/CCLHBotCommons/include/Services/CardService.h
UTF-8
7,469
3.1875
3
[]
no_license
#pragma once #include "../Models/Card.h" #include "../Models/Player.h" #include "../Exceptions/Card/CardAlreadyUsedException.h" #include "../Exceptions/Card/CardExcededLength.h" #include "../Exceptions/Dictionary/DictionaryNotExistsException.h" #include "../Exceptions/Game/GameNotExistsException.h" #include "../Exceptions/Player/PlayerNotExistsException.h" struct RoundBlackCard { Card card; int64_t game_id; int64_t message_id; RoundBlackCard(int64_t id, uint8_t type, std::string text, int64_t dictionary_id, int64_t game_id, int64_t message_id) { this->card = Card(id, type, text, dictionary_id); this->game_id = game_id; this->message_id = message_id; } }; struct RoundWhiteCard { Card card; int64_t game_id; int64_t player_id; int64_t message_id; RoundWhiteCard(int64_t id, uint8_t type, std::string text, int64_t dictionary_id, int64_t game_id, int64_t player_id, int64_t message_id) { this->card = Card(id, type, text, dictionary_id); this->game_id = game_id; this->player_id = player_id; this->message_id = message_id; } }; class CardService { public: ////////////////////////////////////////////////////////////DECK WHITE CARDS///////////////////////////////////////////////////////////////// /** * @brief Add all the white cards to a player's deck * * @param int64_t dictionary id * @param std::vector<Player>& players * @param int32_t quantity of cards we want to add to each player */ static void AddWhiteCardsToPlayerDeck(int64_t, std::vector<Player>&, int32_t); /** * @brief Get the White Cards from the player's deck * * @param int64_t player id * @param int32_t number of cards in hand * @return std::vector<Card> */ static std::vector<Card> GetWhiteCardsFromPlayerDeck(int64_t, int32_t); /** * @brief Delete all the white cards from all the player's decks * * @param int64_t game id */ static void DeleteAllWhiteCardsFromAllPlayerDecks(int64_t); /** * @brief Delete all the white cards from the player's deck * * @param int64_t player id */ static void DeleteAllWhiteCardsFromPlayerDeck(int64_t); /** * @brief Delete a white card from the player's deck * * @param int64_t player id * @param int64_t card id */ static void DeleteWhiteCardFromPlayerDeck(int64_t, int64_t); ////////////////////////////////////////////////////////////ROUND WHITE CARDS///////////////////////////////////////////////////////////////// /** * @brief Add a white card to current round of the game * * @param int64_t player id * @param int64_t game id * @param int64_t card id * @param int64_t message id */ static void AddWhiteCardToCurrentRound(int64_t, int64_t, int64_t, int64_t); /** * @brief Get the White Cards from the current round of the game * * @param int64_t game id * @return std::vector<Card> */ static std::vector<RoundWhiteCard> GetWhiteCardsFromCurrentRound(int64_t); /** * @brief Delete all the white cards from the current round of the game * * @param int64_t game id */ static void DeleteAllWhiteCardsFromCurrentRound(int64_t); ////////////////////////////////////////////////////////////ROUND VOTES///////////////////////////////////////////////////////////////// /** * @brief Add a new vote * * @param int64_t game id * @param int64_t player id * @param int64_t card id * @param int64_t message id */ static void AddVoteToCurrentRound(int64_t, int64_t, int64_t, int64_t); /** * @brief Get the most voted card in the current round of the game * * @param int64_t game id * @return Card */ static Card GetMostVotedCardAtCurrentRound(int64_t); /** * @brief Get the Message ID From Current Round * * @param int64_t player id * @return int64_t message id */ static int64_t GetVoteMessageIDFromCurrentRound(int64_t); /** * @brief Get the cards voted in the current round of the game * * @param int64_t game id * @return std::vector<Card> */ static std::vector<RoundWhiteCard> GetVotesFromCurrentRound(int64_t); /** * @brief Delete all the votes from the current round of the game * * @param int64_t game id */ static void DeleteAllVotesFromCurrentRound(int64_t); ////////////////////////////////////////////////////////////DECK BLACK CARDS///////////////////////////////////////////////////////////////// /** * @brief Add all the black cards to a game * * @param int64_t dictionary id * @param int64_t game id * @param int32_t quantity of cards we want to add */ static void AddBlackCardsToGameDeck(int64_t, int64_t, int32_t); /** * @brief Get the First Black Card from a game * * @param int64_t game id * @return Card */ static Card GetFirstBlackCardFromGameDeck(int64_t); /** * @brief Delete all the black cards from a game * * @param int64_t game id */ static void DeleteBlackCardsFromGameDeck(int64_t); /** * @brief Delete the first black card from a game * * @param int64_t card id * @param int64_t game id */ static void DeleteBlackCardFromGameDeck(int64_t, int64_t); ////////////////////////////////////////////////////////////ROUND BLACK CARDS///////////////////////////////////////////////////////////////// /** * @brief Add a black card to current round of the game * * @param int64_t game id * @param int64_t card id * @param int64_t message id */ static void AddBlackCardToCurrentRound(int64_t, int64_t, int64_t); /** * @brief Get the Black Card from the current round of the game * * @param int64_t game id * @return Card */ static RoundBlackCard GetBlackCardFromCurrentRound(int64_t); /** * @brief Delete a black card from current round * * @param int64_t game id */ static void DeleteBlackCardFromCurrentRound(int64_t); ////////////////////////////////////////////////////////////PLAYERS///////////////////////////////////////////////////////////////// /** * @brief Get the Players that sent white cards in the current round * * @param int64_t game id * @return std::vector<Card> */ static std::vector<Player> GetPlayersThatSentWhiteCards(int64_t); /** * @brief Get the Players that voted white cards in the current round * * @param int64_t game id * @return std::vector<Card> */ static std::vector<Player> GetPlayersThatVotedWhiteCards(int64_t); /** * @brief Get the Player From Round White Card ID * * @param int64_t game id * @param int64_t card id * @return Player */ static Player GetPlayerFromRoundWhiteCardID(int64_t, int64_t); ////////////////////////////////////////////////////////////UTILS///////////////////////////////////////////////////////////////// /** * @brief Delete All Cards * * @param uint64_t dictionary_id * @return uint64_t number of cards */ static void DeleteAllCards(int64_t = -1); /** * @brief Get All Cards * * @param int8_t card type * @param uint64_t dictionary_id * @return uint64_t number of cards */ static uint64_t CountCards(int8_t = -1, int64_t = -1); /** * @brief Get All Cards * * @param int8_t card type * @param uint64_t dictionary_id * @return std::vector<Card> vector of cards */ static std::vector<Card> GetAllCards(int8_t = -1, int64_t = -1); private: };
true
6dc2085a3551f36dd97741e1932687ff4a3122fa
C++
rubenvereecken/challenges
/Glassdoor/cpp/solveEquation.cpp
UTF-8
3,100
3.34375
3
[]
no_license
/*! * \file * \brief solveEquation.cpp * * \date Sep 16, 2013 * \author Ruben Vereecken */ #include "GlassDoor.h" #include <stdlib.h> using namespace std; map<char, int> precedence ({{'+', 0}, {'-', 0}, {'*', 1}, {'/', 1}}); bool isNum(char num) { return num == '0' || num == '1' || num == '2' || num == '3' || num == '4' || num == '5' || num == '6' || num == '7' || num == '8' || num == '9' || num == 'x'; }; bool isOp(char op) { return op == '+' || op == '-' || op == '*' || op == '/'; }; int strtol (string a) { return std::strtol(a.c_str(), nullptr, 10); } bool lowerPrec(char opA, char opB) { return precedence[opA] <= precedence[opB]; } string inToPost(string infix) { string post; stack<char> S; string::iterator s = infix.begin(); while (s != infix.end()) { // cout << post << endl; string numSoFar; while (isNum(*s)) { numSoFar += *s; s++; } if (!numSoFar.empty()) { post += " " + numSoFar; } else if (*s == '(') { S.push(*s); s++; } else if (isOp(*s)) { if (S.empty()) { S.push(*s); s++; } else { // if (!S.empty()) // cout << "S.top: " << S.top() << endl; while (!S.empty() && S.top() != '(' && lowerPrec(*s, S.top())) { post += S.top(); S.pop(); } S.push(*s); s++; } } else if (*s == '(') { S.push(*s); s++; } else if (*s == ')') { while (!S.empty()) { char top = S.top(); S.pop(); if (top == '(') break; post += top; } s++; } else s++; } while (!S.empty()) { post += S.top(); S.pop(); } return post; } int eval(int operand1, int operand2, char op) { switch (op) { case '+': return operand1 + operand2; case '-': return operand1 - operand2; case '*': return operand1 * operand2; case '/': return operand1 / operand2; } } int evaluatePost(string post, int replaceX) { stack<int> S; string::iterator s = post.begin(); while (s != post.end()) { string numSoFar; while (isNum(*s)) { numSoFar += *s; s++; } if (!numSoFar.empty()) { S.push(strtol(numSoFar)); } else if (*s == 'x') { S.push(replaceX); s++; } else if (isOp(*s)) { int operand2 = S.top(); S.pop(); int operand1 = S.top(); S.pop(); S.push(eval(operand1, operand2, *s)); s++; } else s++; } return S.top(); } int findX(string equation) { int equationIndex = equation.find("="); string left(equation.begin(), equation.begin() + equationIndex); string right(equation.begin() + equationIndex + 1, equation.end()); // cout << "left infix: " << left << endl; // cout << "right infix: " << right << endl; string leftPost = inToPost(left); // cout << "left postfix: " << leftPost << endl; string rightPost = inToPost(right); // cout << "right postfix: " << rightPost << endl; string total = leftPost + " " + rightPost + "-"; // cout << total << endl; int f0 = evaluatePost(total, 0); int f1 = evaluatePost(total, 1); // cout << "f0 = " << f0 << endl; // cout << "f1 = " << f1 << endl; if (f0 == f1) { // cout << "noooope " << endl; return -1; } else return f0 / (f0 - f1); }
true
8d32a03ae7d6c6722f73fdf4bc4b88bc864733dd
C++
shivam-2002/cpp
/function (callby/3.cpp
UTF-8
233
3.171875
3
[]
no_license
#include<iostream> using namespace std;//function without parameter without return type power() { int x,y; cin>>x; for(int a=0;a<=x;a++) cout<<a<<"*"<<a<<"="<<a*a<<endl; } main() { for(int p=0;p<5;p++) power(); }
true
78600259c0cbfc762f621ff30244494039ed6ef5
C++
diptu/Teaching
/CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab8 Stack ( Linked List)/StackType(18).cpp
UTF-8
1,548
3.671875
4
[ "MIT" ]
permissive
#include <iostream> #include "stacktype.h" using namespace std; template <class ItemType> StackType<ItemType>::StackType() { topPtr = NULL; } template <class ItemType> bool StackType<ItemType>::IsEmpty() { return (topPtr == NULL); } template <class ItemType> ItemType StackType<ItemType>::Top() { if (IsEmpty()) throw EmptyStack(); else return topPtr->info; } template <class ItemType> bool StackType<ItemType>::IsFull() { NodeType* location; try { location = new NodeType; delete location; return false; } catch(bad_alloc& exception) { return true; } } template <class ItemType> void StackType<ItemType>::Push(ItemType newItem) { try{ if (IsFull()) throw FullStack(); else { NodeType* location; location = new NodeType; location->info = newItem; location->next = topPtr; topPtr = location; } } catch(...) { cout<<"Stack is full"<<endl; } } template <class ItemType> void StackType<ItemType>::Pop() { try{ if (IsEmpty()) throw EmptyStack(); else { NodeType* tempPtr; tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr; } } catch(...) { cout<<"Stack is empty"<<endl; } } template <class ItemType> StackType<ItemType>::~StackType() { NodeType* tempPtr; while (topPtr != NULL) { tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr; } }
true
b666ca2a6398f5ce443bb04e65e0c66b14545e3c
C++
smokhov/comp477-samples
/src/Demos/particle-221/src/DMcTools/Image/ImageLoadSave.cpp
UTF-8
43,164
2.53125
3
[ "Apache-2.0" ]
permissive
////////////////////////////////////////////////////////////////////// // ImageLoadSave.cpp - Load and save images of many file formats. // // Copyright David K. McAllister, Aug. 1997 - 2007. // How loading works: // tImage<>.Load() calls tLoad<>(). // tLoad<>() creates an ImageLoadSave and calls into it to do the loading. // ImageLoadSave.Load() creates a tImage of the data type and num channels of the image file. // Its baseImage is returned by ImageLoadSave.Load(). // tImage.Load() of the dest image converts the returned image to this one's type. // // For working with a baseImage rather than a known image type, call LoadtImage(). // This creates an ImageLoadSave and calls into it to do the loading. // ImageLoadSave.Load() creates a tImage of the data type and num channels of the image file. // Its baseImage is returned by ImageLoadSave.Load(). // LoadtImage() returns the created baseImage. // How saving works: // tImage<>.Save() calls tSave<>(). // tSave<>() looks at the source image and the chosen file format. // If the chosen format cannot support the image type, it creates another image of a supported type. // It calls ImageLoadSave.Save(), which saves the image. // If a converted image was created, it is deleted. #include "Image/ImageLoadSave.h" #include "Image/tImage.h" #include "Image/RGBEio.h" #include "Util/Utils.h" #include "tiffio.h" extern "C" { #include "jpeglib.h" #ifdef DMC_MACHINE_win #include "png.h" #else #include "/usr/include/png.h" #endif #ifdef DMC_USE_MAT #include "mat.h" #endif } #include <fstream> #include <string> using namespace std; #define RAS_MAGIC 0x59a66a95 #define GIF_MAGIC 0x47494638 #define JPEG_MAGIC 0xffd8ffe0 #define RGB_MAGIC 0x01da0101 namespace { #ifdef DMC_DEBUG bool Verbose = true; #else bool Verbose = false; #endif }; // A back-door way to set this. bool dmcTGA_R5G6B5 = false; // Return an int whose bytes equal the characters of the extension string // Used by tSave() and ImageLoadSave::Load(). int GetExtensionVal(const char *fname) { char *ext = GetFileExtension(fname); ToLower(ext); return (ext[0]<<0)|(ext[1]<<8)|(ext[2]<<16); } // Fills wid, hgt, chan, Pix, and baseImg. // Pix points to the same data as does baseImg.Pix. // The data must be deleted by baseImg. // baseImg must also be deleted by the caller (tLoad or LoadtImage). // Pix and baseImg will be NULL on error. void ImageLoadSave::Load(const char *fname) { ASSERT_R(fname); ASSERT_R(Pix == NULL && wid == 0 && hgt == 0 && chan == 0); int exts = GetExtensionVal(fname); ifstream InFile(fname, ios::in | ios::binary); if(!InFile.is_open()) throw DMcError("Failed to open file '" + string(fname) + "'"); unsigned int Magic; char *Mag = (char *)&Magic; InFile.read(Mag, 4); InFile.close(); unsigned int eMagic = Magic; ConvertLong(&eMagic, 1); if(Magic==RAS_MAGIC || eMagic==RAS_MAGIC || exts==RAS_) { LoadRas(fname); } else if(Magic==GIF_MAGIC || eMagic==GIF_MAGIC || exts==GIF_) { LoadGIF(fname); } else if(Magic==JPEG_MAGIC || eMagic==JPEG_MAGIC || exts==JPG_) { LoadJPEG(fname); } else if(Magic==RGB_MAGIC || eMagic==RGB_MAGIC || exts==RGB_) { LoadRGB(fname); } else if((Mag[0]=='P' && (Mag[1]=='5' || Mag[1]=='6' || Mag[1]=='7' || Mag[1]=='8' || Mag[1]=='Z')) || (Mag[3]=='P' && (Mag[2]=='5' || Mag[2]=='6' || Mag[2]=='7' || Mag[2]=='8' || Mag[2]=='Z')) || exts==PPM_ || exts==PGM_ || exts==PAM_ || exts==PFM_ || exts==PSM_ || exts==PZM_) { LoadPPM(fname); } else if((Mag[1]=='P' && Mag[2]=='N' && Mag[3]=='G') || (Mag[2]=='P' && Mag[1]=='N' && Mag[0]=='G') || exts==PNG_) { LoadPNG(fname); } else if((Mag[0]=='B' && Mag[1]=='M') || (Mag[3]=='B' && Mag[2]=='M') || exts==BMP_) { LoadBMP(fname); } else if((Mag[0]==0 || Mag[3]==0) && (exts==TGA_)) { LoadTGA(fname, dmcTGA_R5G6B5); } else if(exts==TIF_) { LoadTIFF(fname); } else if(exts==HDR_) { LoadRGBE(fname); } else { stringstream er; er << "Could not determine file type of `" << fname << "'.\n"; er << "Magic was " << Magic << " or "<<eMagic<< " or `" << Mag[0] << Mag[1] << Mag[2] << Mag[3] << "'.\n"; er << "Extension was " << exts << endl; throw DMcError(er.str()); } Pix = NULL; // When loading, Pix is only used by Load*(). baseImg carries the data when we return from here. } // Allocate a tImage of the appropriate type for the file being loaded. // Called by Load*(). It creates a tImage that matches the is_* and chan args. Stores the pointer to the tImage in baseImg. unsigned char *ImageLoadSave::ImageAlloc() { switch(chan) { case 1: if(is_uint) { baseImg = new ui1Image(wid,hgt); } else if(is_float) { baseImg = new f1Image(wid,hgt); } else if(is_ushort) { baseImg = new us1Image(wid,hgt); } else { baseImg = new uc1Image(wid,hgt); } break; case 2: if(is_ushort) { baseImg = new us2Image(wid,hgt); } else { baseImg = new uc2Image(wid,hgt); } break; case 3: if(is_float) { baseImg = new f3Image(wid,hgt); } else if(is_ushort) { baseImg = new us3Image(wid,hgt); } else { baseImg = new uc3Image(wid,hgt); } break; case 4: if(is_ushort) { baseImg = new us4Image(wid,hgt); } else { baseImg = new uc4Image(wid,hgt); } break; } Pix = (unsigned char *)baseImg->pv_virtual(); return Pix; } // Choose a saver based strictly on extension. // The individual savers may look at chan, is_uint, etc. to decide a format. void ImageLoadSave::Save(const char *fname_) const { ASSERT_R(fname_); char *fname = strdup(fname_); int exts = GetExtensionVal(fname); char *outfname3 = strchr(fname, '\n'); if(outfname3) *outfname3 = '\0'; outfname3 = strchr(fname, '\r'); if(outfname3) *outfname3 = '\0'; switch(exts) { case BMP_: SaveBMP(fname); // 1 3 break; case GIF_: SaveGIF(fname); // 1 3 break; case HDR_: SaveRGBE(fname); // 3f break; case JPG_: SaveJPEG(fname); // 1 3 break; case TGA_: SaveTGA(fname); // 1 3 4 break; case TIF_: SaveTIFF(fname); // 1 2 3 4 uc, us, ui, f break; case MAT_: SaveMAT(fname); // 1 2 3 4 break; case PNG_: SavePNG(fname); // 1 2 3 4 break; case PPM_: case PGM_: case PAM_: case PSM_: case PFM_: case PZM_: SavePPM(fname); // 1s 2s 3s 4s 1f 3f 1uc 3uc 4uc break; default: throw DMcError("Saving file with unknown filename extension in filename '" + string(fname_) + "'"); break; } if(fname) delete [] fname; } ////////////////////////////////////////////////////// // Sun Raster File Format // RAS Header struct rasterfile { int ras_magic; /* magic number */ int ras_width; /* width (pixels) of image */ int ras_height; /* height (pixels) of image */ int ras_depth; /* depth (1, 8, or 24 bits) of pixel */ int ras_length; /* length (bytes) of image */ int ras_type; /* type of file; see RT_* below */ int ras_maptype; /* type of colormap; see RMT_* below */ int ras_maplength; /* length (bytes) of following map */ /* color map follows for ras_maplength bytes, followed by image */ }; /* Sun supported ras_type's */ #define RT_OLD 0 /* Raw pixrect image in 68000 byte order */ #define RT_STANDARD 1 /* Raw pixrect image in 68000 byte order */ #define RT_BYTE_ENCODED 2 /* Run-length compression of bytes */ #define RT_FORMAT_RGB 3 /* XRGB or RGB instead of XBGR or BGR */ #define RT_FORMAT_TIFF 4 /* tiff <-> standard rasterfile */ #define RT_FORMAT_IFF 5 /* iff (TAAC format) <-> standard rasterfile */ #define RT_EXPERIMENTAL 0xffff /* Reserved for testing */ /* Sun registered ras_maptype's */ #define RMT_RAW 2 /* Sun supported ras_maptype's */ #define RMT_NONE 0 /* ras_maplength is expected to be 0 */ #define RMT_EQUAL_RGB 1 /* red[ras_maplength/3],green[],blue[] */ /* * NOTES: * Each line of the image is rounded out to a multiple of 16 bits. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^!!!!!!!!!!!!!! * This corresponds to the rounding convention used by the memory pixrect * package (/usr/include/pixrect/memvar.h) of the SunWindows system. * The ras_encoding field (always set to 0 by Sun's supported software) * was renamed to ras_length in release 2.0. As a result, rasterfiles * of type 0 generated by the old software claim to have 0 length; for * compatibility, code reading rasterfiles must be prepared to compute the * true length from the width, height, and depth fields. */ void ImageLoadSave::LoadRas(const char *fname) { // Read a Sun Raster File image. ifstream InFile(fname, ios::in | ios::binary); if(!InFile.is_open()) throw DMcError("Could not open file for LoadRas: " + string(fname)); rasterfile Hedr; InFile.read((char *) &Hedr, sizeof(rasterfile)); #ifdef DMC_LITTLE_ENDIAN ConvertLong((unsigned int *)&Hedr, sizeof(rasterfile) / sizeof(int)); #endif wid = Hedr.ras_width; hgt = Hedr.ras_height; chan = 3; if(Hedr.ras_depth != 24) { stringstream er; er << "Take your " << Hedr.ras_depth << " bit image and go away!"; throw DMcError(er.str()); } if(size_bytes() != Hedr.ras_length) { stringstream er; er << "Size was " << size_bytes() << ", but ras_length was " << Hedr.ras_length << ".\n"; throw DMcError(er.str()); } if(wid > 4096) { stringstream er; er << "Too big! " << wid << endl; throw DMcError(er.str()); } is_uint = false; is_float = false; Pix = ImageAlloc(); if(Hedr.ras_type==RT_FORMAT_RGB) { if(Hedr.ras_maptype==RMT_NONE) { // Now read the color values. for (int y = 0; y < hgt; y++) { InFile.read((char *)&Pix[y*wid*3], wid*3); } } else if(Hedr.ras_maptype==RMT_EQUAL_RGB) { if(Verbose) cerr << "Reading color mapped image. Maplength = " << Hedr.ras_maplength << endl; unsigned char ColorMap[256][3]; unsigned char Colors[4096]; InFile.read((char *)ColorMap, Hedr.ras_maplength*3); for (int y = 0; y < hgt; y++) { InFile.read((char *)Colors, wid); for(int x=0; x<wid; ) { Pix[y*wid+x] = ColorMap[Colors[x]][0]; x++; Pix[y*wid+x] = ColorMap[Colors[x]][1]; x++; Pix[y*wid+x] = ColorMap[Colors[x]][2]; x++; } } } else { throw DMcError("Strange color map scheme."); } } else if(Hedr.ras_type==RT_STANDARD) { if(Verbose) cerr << "BGR ImageLoadSave (RT_STANDARD)\n"; if(Hedr.ras_maptype==RMT_NONE) { // Now read the color values. unsigned char Colors[4096][3]; int ii=0; for (int y = 0; y < hgt; y++) { InFile.read((char *)Colors, wid*3); for(int x=0; x<wid; x++) { Pix[ii++] = Colors[x][2]; Pix[ii++] = Colors[x][1]; Pix[ii++] = Colors[x][0]; } } } else { throw DMcError("Strange color map scheme."); } } else { throw DMcError("Strange format."); } InFile.close(); } ////////////////////////////////////////////////////// // PPM File Format // PAM is four-channel PPM. PFM is one- or three-channel float. PGM is one-channel uchar. void ImageLoadSave::LoadPPM(const char *fname) { ifstream InFile(fname, ios::in | ios::binary); if(!InFile.is_open()) throw DMcError("Could not open file for LoadPPM: " + string(fname)); char Magic1, Magic2; InFile >> Magic1 >> Magic2; if(Magic1!='P' || (Magic2!='5' && Magic2!='6' && Magic2!='7' && Magic2!='8' && Magic2!='Z' && Magic2!='S' && Magic2!='T' && Magic2!='U' && Magic2!='V')) { InFile.close(); throw DMcError("Not a known PPM file: " + string(fname)); } InFile.get(); char c = InFile.peek(); while(c=='#') { char line[999]; InFile.getline(line, 1000); if(Verbose) cerr << line << endl; c = InFile.peek(); } int dyn_range; InFile >> wid >> hgt >> dyn_range; InFile.get(); if(dyn_range != 255) throw DMcError("PPM Must be 255."); // XXX Need to distinguish one-channel float images. is_uint = false; is_float = false; switch(Magic2) { case '5': chan = 1; break; case '6': chan = 3; break; case '8': chan = 4; break; case '7': chan = 3; is_float = true; break; case 'Z': chan = 1; is_float = true; break; case 'S': case 'T': case 'U': case 'V': // Unsigned short 1,2,3,4 channels chan = 1 + Magic2 - 'S'; is_ushort = true; break; } Pix = ImageAlloc(); InFile.read((char *)Pix, size_bytes()); InFile.close(); #ifdef DMC_LITTLE_ENDIAN // Intel is little-endian. // Always assume they are stored as big-endian. if(is_uint || is_float) ConvertLong((unsigned int *)Pix, size()*chan); if(is_ushort) ConvertShort((unsigned short *)Pix, size()*chan); #endif if(Verbose) cerr << "Loaded a PPM image.\n"; } void ImageLoadSave::SavePPM(const char *fname) const { ASSERT_RM(fname, "NULL fname"); if(Pix==NULL || chan < 1 || wid < 1 || hgt < 1) { throw DMcError("PPM image is not defined. Not saving."); } ASSERT_RM(!(chan < 1 || chan > 4), "Can't save a X channel image as a PPM."); ofstream OutFile(fname, ios::out | ios::binary); if(!OutFile.is_open()) throw DMcError("Could not open file for SavePPM: " + string(fname)); OutFile << 'P'; if(is_ushort) OutFile << char('S' + chan - 1) << endl; else OutFile << ((chan==1 ? (is_float?'Z':'5') : (chan==3 ? (is_float?'7':'6') : '8'))) << endl; OutFile << wid << " " << hgt << endl << 255 << endl; #ifdef DMC_LITTLE_ENDIAN if(is_uint || is_float || is_ushort) { // Need to convert multibyte words to big-endian before saving. unsigned char *Tmp = new unsigned char[size_bytes()]; ASSERT_RM(Tmp, "memory alloc failed"); memcpy(Tmp, Pix, size_bytes()); if(is_ushort) ConvertShort((unsigned short *)Tmp, size()*chan); else ConvertLong((unsigned int *)Tmp, size()*chan); OutFile.write((char *)Tmp, size_bytes()); delete [] Tmp; } else OutFile.write((char *)Pix, size_bytes()); #else OutFile.write((char *)Pix, size_bytes()); #endif OutFile.close(); if(Verbose) cerr << "Wrote PPM file " << fname << endl; } ////////////////////////////////////////////////////// // SGI Iris RGB Images /* private typedefs */ struct rawImageRec { unsigned short imagic; unsigned short type; unsigned short dim; unsigned short sizeX, sizeY, sizeZ; unsigned long min, max; unsigned long wasteBytes; char name[80]; unsigned long colorMap; // Not part of image header. FILE *file; unsigned char *tmp; unsigned long rleEnd; unsigned int *rowStart; int *rowSize; }; namespace { void RawImageGetRow(rawImageRec *raw, unsigned char *buf, int y, int z) { unsigned char *iPtr, *oPtr, pixel; int count; if((raw->type & 0xFF00)==0x0100) { fseek(raw->file, raw->rowStart[y+z*raw->sizeY], SEEK_SET); fread(raw->tmp, 1, (unsigned int)raw->rowSize[y+z*raw->sizeY], raw->file); iPtr = raw->tmp; oPtr = buf; while (1) { pixel = *iPtr++; count = (int)(pixel & 0x7F); if(!count) { return; } if(pixel & 0x80) { while (count--) { *oPtr++ = *iPtr++; } } else { pixel = *iPtr++; while (count--) { *oPtr++ = pixel; } } } } else { fseek(raw->file, 512+(y*raw->sizeX)+(z*raw->sizeX*raw->sizeY), SEEK_SET); fread(buf, 1, raw->sizeX, raw->file); } } }; void ImageLoadSave::LoadRGB(const char *fname) { rawImageRec raw; unsigned char *tmpR, *tmpG, *tmpB; bool swapFlag = AmLittleEndian(); // Open the file if((raw.file = fopen(fname, "rb"))==NULL) throw DMcError("LoadRGB() failed: can't open image file " + string(fname)); fread(&raw, 1, 104, raw.file); if(Verbose) cerr << "ImageLoadSave name is: `" << raw.name << "'\n"; if(swapFlag) { ConvertShort(&raw.imagic, 6); } raw.tmp = new unsigned char[raw.sizeX*256]; tmpR = new unsigned char[raw.sizeX*256]; tmpG = new unsigned char[raw.sizeX*256]; tmpB = new unsigned char[raw.sizeX*256]; ASSERT_RM(raw.tmp && tmpR && tmpG && tmpB, "memory alloc failed"); if((raw.type & 0xFF00)==0x0100) { int x = raw.sizeY * raw.sizeZ; int y = x * sizeof(unsigned int); raw.rowStart = new unsigned int[x]; raw.rowSize = new int[x]; ASSERT_RM(raw.rowStart && raw.rowSize, "memory alloc failed"); raw.rleEnd = 512 + (2 * y); fseek(raw.file, 512, SEEK_SET); fread(raw.rowStart, 1, y, raw.file); fread(raw.rowSize, 1, y, raw.file); if(swapFlag) { ConvertLong(raw.rowStart, x); ConvertLong((unsigned int *)raw.rowSize, x); } } wid = raw.sizeX; hgt = raw.sizeY; chan = raw.sizeZ; is_uint = false; is_float = false; Pix = ImageAlloc(); if((raw.type & 0xFF00)==0x0100) { if(Verbose) cerr << "Loading an rle compressed RGB image.\n"; } else { if(Verbose) cerr << "Loading a raw RGB image.\n"; } unsigned char *ptr = Pix; for (int i = raw.sizeY - 1; i >= 0; i--) { if(chan==1) { RawImageGetRow(&raw, ptr, i, 0); ptr += wid; } else { RawImageGetRow(&raw, tmpR, i, 0); RawImageGetRow(&raw, tmpG, i, 1); RawImageGetRow(&raw, tmpB, i, 2); // Copy into standard RGB image. for (int j = 0; j < raw.sizeX; j++) { *ptr++ = tmpR[j]; *ptr++ = tmpG[j]; *ptr++ = tmpB[j]; } } } fclose(raw.file); delete [] raw.tmp; delete [] tmpR; delete [] tmpG; delete [] tmpB; delete [] raw.rowStart; delete [] raw.rowSize; } ////////////////////////////////////////////////////// // JPEG File Format #ifdef DMC_USE_JPEG void JPEGError(j_common_ptr cinfo) { const char *msgtext = ""; if (cinfo->err->msg_code > 0 && cinfo->err->msg_code <= cinfo->err->last_jpeg_message) { msgtext = cinfo->err->jpeg_message_table[cinfo->err->msg_code]; } stringstream st; st << "JPEG error or warning: " << msgtext; throw DMcError(st.str()); } void ImageLoadSave::LoadJPEG(const char *fname) { #define NUM_ROWS 16 struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; FILE *infile; unsigned int y; JSAMPROW row_ptr[NUM_ROWS]; if((infile = fopen(fname, "rb"))==NULL) throw DMcError("Can't open JPEG file " + string(fname)); cinfo.err = jpeg_std_error(&jerr); cinfo.err->output_message = JPEGError; jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, infile); jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); wid = cinfo.output_width; hgt = cinfo.output_height; chan = cinfo.output_components; is_uint = false; is_float = false; Pix = ImageAlloc(); while(cinfo.output_scanline < cinfo.output_height) { for(y=0; y<NUM_ROWS; y++) row_ptr[y] = &Pix[(cinfo.output_scanline + y) * wid * chan]; jpeg_read_scanlines(&cinfo, row_ptr, NUM_ROWS); } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); fclose(infile); } void ImageLoadSave::SaveJPEG(const char *fname) const { if(Pix==NULL || chan < 1 || wid < 1 || hgt < 1) throw DMcError("Image is not defined. Not saving."); if(chan != 1 && chan != 3) throw DMcError("Can only save 1 and 3 channel image as a JPEG."); struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; FILE *outfile; int y; JSAMPROW row_ptr[1]; if((outfile = fopen(fname, "wb"))==NULL) throw DMcError("SaveJPEG() failed: can't write to " + string(fname)); cinfo.err = jpeg_std_error(&jerr); cinfo.err->output_message = JPEGError; jpeg_create_compress(&cinfo); jpeg_stdio_dest(&cinfo, outfile); cinfo.image_width = wid; cinfo.image_height = hgt; cinfo.input_components = chan; cinfo.in_color_space = (chan==1) ? JCS_GRAYSCALE : JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality (&cinfo, 80, true); jpeg_start_compress(&cinfo, TRUE); for(y=0; y<hgt; y++) { row_ptr[0] = &Pix[y*wid*chan]; jpeg_write_scanlines(&cinfo, row_ptr, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); fclose(outfile); } #else /* DMC_USE_JPEG */ void ImageLoadSave::LoadJPEG(const char *fname) { throw DMcError("JPEG Support not compiled in."); } void ImageLoadSave::SaveJPEG(const char *fname) const { throw DMcError("JPEG Support not compiled in."); } #endif /* DMC_USE_JPEG */ ////////////////////////////////////////////////////// // TIFF File Format #ifdef DMC_USE_TIFF // Compression mode constants #define NONE 1 #define LEMPELZIV 5 void TiffErrHand(const char *module, const char *fmt, va_list ap) { char Err[1024]; sprintf(Err, fmt, ap); throw DMcError(string(module) + string(Err)); } void ImageLoadSave::LoadTIFF(const char *fname) { TIFF* tif; // tif file handler TIFFSetErrorHandler(TiffErrHand); if(Verbose) cerr << "Attempting to open " << fname << " as TIFF.\n"; if(Verbose) cerr << "TIFF version is " << TIFFGetVersion() << endl; tif = TIFFOpen(fname, "r"); if(!tif) throw DMcError("Could not open TIFF file '" + string(fname) + "'."); TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &wid); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &hgt); TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &chan); #ifdef DMC_MACHINE_sgi chan = chan >> 16; #endif int bitspersample = -1; TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitspersample); bitspersample = bitspersample & 0xffff; if(Verbose) { cerr << "size=" << wid <<"x"<< hgt << endl; cerr << "TIFFTAG_SAMPLESPERPIXEL=" << chan << endl; int tmp = 0, tmp2 = 0; TIFFGetField(tif, TIFFTAG_EXTRASAMPLES, &tmp, &tmp2); cerr << "TIFFTAG_EXTRASAMPLES " << tmp << ": " << tmp2 << endl; cerr << "TIFFTAG_BITSPERSAMPLE " << bitspersample << endl; TIFFGetField(tif, TIFFTAG_COMPRESSION, &tmp); cerr << "TIFFTAG_COMPRESSION " << tmp << endl; TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &tmp); cerr << "TIFFTAG_PHOTOMETRIC " << tmp << endl; TIFFPrintDirectory(tif, stderr, 0); } is_uint = false; is_ushort = false; is_float = false; if(bitspersample == 32) is_float = true; if(bitspersample == 16) is_ushort = true; // XXX How do we distinguish a uint from a float image? if(bitspersample > 16) throw DMcError("The TIFF library can save float TIFF, but not load them."); // Loads the data into a 32-bit word for each pixel, regardless of chan. chan = 4; Pix = ImageAlloc(); if(!TIFFReadRGBAImage(tif, wid, hgt, (uint32 *) Pix, 0)) { throw DMcError("TIFFReadRGBAImage failed."); } if(Verbose) { int dircount = 0; do { dircount++; } while (TIFFReadDirectory(tif)); if(dircount > 1) cerr << fname << "contains " << dircount << " directories!!!\n"; } TIFFClose(tif); } // Handles 1 through 4 channels, uchar, ushort, uint, or float. void ImageLoadSave::SaveTIFF(const char *fname) const { if(Pix==NULL || chan < 1 || wid < 1 || hgt < 1) throw DMcError("Image is not defined. Not saving."); TIFFSetErrorHandler(TiffErrHand); TIFF *tif = TIFFOpen(fname, "w"); if(tif==NULL) throw DMcError("TIFFOpen failed: " + string(fname)); int bitsperchan = 8; if(is_float || is_uint) bitsperchan = 32; else if(is_ushort) bitsperchan = 16; int bytesperchan = bitsperchan / 8; // WARNING: It seems to have a problem with two-channel images. Am I setting things wrong, or what? TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, wid); TIFFSetField(tif, TIFFTAG_IMAGELENGTH, hgt); TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bitsperchan); TIFFSetField(tif, TIFFTAG_COMPRESSION, LEMPELZIV); TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, (chan > 2) ? PHOTOMETRIC_RGB : PHOTOMETRIC_MINISBLACK); TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, chan); TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT); TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(tif, TIFFTAG_XRESOLUTION, 96.0); TIFFSetField(tif, TIFFTAG_YRESOLUTION, 96.0); TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, 2); TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1); // Actually isn't associated, but the library breaks. uint16 extyp = EXTRASAMPLE_ASSOCALPHA; if(chan==2 || chan==4) TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, 1, &extyp); // Write one row of the image at a time unsigned char *c = Pix; for (int l = 0; l < hgt; l++) { if(TIFFWriteScanline(tif, c, l, 0) < 0) { TIFFClose(tif); throw DMcError("TIFFWriteScanline failed: " + string(fname)); } c += wid*chan*bytesperchan; } // Close the file and return OK TIFFClose(tif); } #else /* DMC_USE_TIFF */ void ImageLoadSave::LoadTIFF(const char *fname) { throw DMcError("TIFF Support not compiled in."); } void ImageLoadSave::SaveTIFF(const char *fname) const { throw DMcError("TIFF Support not compiled in."); } #endif /* DMC_USE_TIFF */ ////////////////////////////////////////////////////// // PNG File Format #ifdef DMC_USE_PNG namespace { double guess_display_gamma() { /* Try to guess a good value for the display exponent */ /* Taken from rpng program by Greg Roelofs. * Copyright (c) 1998-2000 Greg Roelofs. All rights reserved. * This product includes software developed by Greg Roelofs * and contributors for the book, "PNG: The Definitive Guide," * published by O'Reilly and Associates. */ double LUT_exponent; /* just the lookup table */ double CRT_exponent = 2.2; /* just the monitor */ double default_display_exponent; /* whole display system */ double display_exponent; /* First set the default value for our display-system exponent, i.e., * the product of the CRT exponent and the exponent corresponding to * the frame-buffer's lookup table (LUT), if any. This is not an * exhaustive list of LUT values (e.g., OpenStep has a lot of weird * ones), but it should cover 99% of the current possibilities. And * yes, these ifdefs are completely wasted in a Windows program... */ #if defined(NeXT) LUT_exponent = 1.0 / 2.2; /* if(some_next_function_that_returns_gamma(&next_gamma)) LUT_exponent = 1.0 / next_gamma; */ #elif defined(sgi) LUT_exponent = 1.0 / 1.7; /* there doesn't seem to be any documented function to get the * "gamma" value, so we do it the hard way */ FILE *infile = fopen("/etc/config/system.glGammaVal", "r"); if(infile) { double sgi_gamma; char tmpline[90]; fgets(tmpline, 80, infile); fclose(infile); sgi_gamma = atof(tmpline); if(sgi_gamma > 0.0) LUT_exponent = 1.0 / sgi_gamma; } #elif defined(Macintosh) LUT_exponent = 1.8 / 2.61; /* if(some_mac_function_that_returns_gamma(&mac_gamma)) LUT_exponent = mac_gamma / 2.61; */ #else LUT_exponent = 1.0; /* assume no LUT: most PCs */ #endif /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */ default_display_exponent = LUT_exponent * CRT_exponent; /* If the user has set the SCREEN_GAMMA environment variable as suggested * (somewhat imprecisely) in the libpng documentation, use that; otherwise * use the default value we just calculated. Either way, the user may * override this via a command-line option. */ char *gamma_str; if((gamma_str = getenv("SCREEN_GAMMA")) != NULL) display_exponent = atof(gamma_str); else display_exponent = default_display_exponent; return display_exponent; } }; // Read a PNG file. void ImageLoadSave::LoadPNG(const char *fname) { FILE *fp; if((fp = fopen(fname, "rb"))==NULL) throw DMcError(string(fname) + " can't open PNG file"); // Check magic number unsigned char buf[4]; fread(buf, 1, 4, fp); if(png_sig_cmp(buf, 0, 4)) throw DMcError(string(fname) + " is not a PNG file."); /* Create and initialize the png_struct with the desired error handler * functions. If you want to use the default stderr and longjump method, * you can supply NULL for the last three parameters. We also supply the * the compiler header file version, so that we know if the application * was compiled with a compatible version of the library. REQUIRED */ png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, NULL, NULL); if(!png_ptr) { fclose(fp); throw DMcError(string(fname) + " png_ptr failed."); } /* Allocate/initialize the memory for image information. REQUIRED. */ png_infop info_ptr = png_create_info_struct(png_ptr); if(!info_ptr) { fclose(fp); png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); throw DMcError(string(fname) + " PNG info_ptr failed."); } /* Set error handling if you are using the setjmp/longjmp method (this is * the normal method of doing things with libpng). REQUIRED unless you * set up your own error handlers in the png_create_read_struct() earlier. */ if(setjmp(png_jmpbuf(png_ptr))) { /* Free all of the memory associated with the png_ptr and info_ptr */ png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); fclose(fp); throw DMcError(string(fname) + " PNG file read failed."); } /* Set up the input control using standard C streams */ png_init_io(png_ptr, fp); /* Let pnglib know that we already read some of the signature */ png_set_sig_bytes(png_ptr, 4); /* Read file info */ png_read_info(png_ptr, info_ptr); /* Parse info_ptr */ wid = png_get_image_width(png_ptr, info_ptr); hgt = png_get_image_height(png_ptr, info_ptr); chan = png_get_channels(png_ptr, info_ptr); int color_type = png_get_color_type(png_ptr, info_ptr); /* Expand paletted colors into true RGB triplets */ if(color_type==PNG_COLOR_TYPE_PALETTE) { png_set_expand(png_ptr); chan = 3; } /* Expand paletted or RGB images with transparency to full alpha channels * so the data will be available as RGBA quartets. */ if(png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { png_set_expand(png_ptr); chan = 4; } /* Allocate image buffer */ is_uint = false; is_float = false; Pix = ImageAlloc(); /* Tell lib we can't handle 16 bit channels */ png_set_strip_16(png_ptr); /* Extract multiple pixels with bit depths of 1, 2, and 4 from a single * byte into separate bytes (useful for paletted and grayscale images). */ png_set_packing(png_ptr); double gamma; // gamma of image // If this png doesn't set gamma, we shouldn't play with gamma either if(png_get_gAMA(png_ptr, info_ptr, &gamma)) { double display_gamma = guess_display_gamma(); // exponent of screen png_set_gamma(png_ptr, display_gamma, gamma); } /* Set up row pointers to hand to libpng */ png_bytep* row_pointers = new png_bytep[hgt]; unsigned int row_stride = wid*chan; unsigned char *rowptr = Pix; for (int row = 0; row < hgt; row++) { row_pointers[row] = rowptr; rowptr += row_stride; } /* Read the whole thing */ png_read_image(png_ptr, row_pointers); /* clean up after the read, and free any memory allocated - REQUIRED */ delete [] row_pointers; png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); /* close the file */ fclose(fp); } // Write a PNG file void ImageLoadSave::SavePNG(const char *fname) const { if(Pix==NULL || chan < 1 || wid < 1 || hgt < 1) throw DMcError("SavePNG: Image is not defined. Not saving."); if(!fname || !fname[0]) throw DMcError("SavePNG: Filename not specified. Not saving."); FILE *fp; if((fp = fopen(fname, "wb"))==NULL) throw DMcError("SavePNG failed: can't write to " + string(fname)); /* Allocate write structures */ png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if(!png_ptr) { fclose(fp); throw DMcError("SavePNG: png_ptr failure"); } png_infop info_ptr = png_create_info_struct(png_ptr); if(!info_ptr) { png_destroy_write_struct(&png_ptr, (png_infopp)NULL); fclose(fp); throw DMcError("SavePNG: info_ptr failure"); } /* Setup error handling */ if(setjmp(png_jmpbuf(png_ptr))) { /* If we get here, we had a problem reading the file */ png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); throw DMcError("SavePNG: setjmp failure"); } /* Setup file IO */ png_init_io(png_ptr, fp); /* Set file options */ int chan2color_type[] = { 0, PNG_COLOR_TYPE_GRAY, PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_RGB, PNG_COLOR_TYPE_RGB_ALPHA }; int bit_depth = 8; png_set_IHDR(png_ptr, info_ptr, wid, hgt, bit_depth, chan2color_type[chan], PNG_INTERLACE_NONE, // PNG_INTERLACE_ADAM7, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); // Optional gamma chunk is strongly suggested if you have any guess // as to the correct gamma of the image. (we don't have a guess) // // png_set_gAMA(png_ptr, info_ptr, image_gamma); // Write the file header information. REQUIRED png_write_info(png_ptr, info_ptr); /* The easiest way to write the image (you may have a different memory * layout, however, so choose what fits your needs best). You need to * use the first method if you aren't handling interlacing yourself. */ png_bytep* row_pointers = new png_bytep[hgt]; unsigned int row_stride = wid*chan; unsigned char *rowptr = Pix; for (int row = 0; row < hgt; row++) { row_pointers[row] = rowptr; rowptr += row_stride; } /* write out the entire image data in one call */ png_write_image(png_ptr, row_pointers); /* It is REQUIRED to call this to finish writing the rest of the file */ png_write_end(png_ptr, info_ptr); /* clean up after the write, and free any memory allocated */ png_destroy_write_struct(&png_ptr, &info_ptr); /* close the file */ fclose(fp); } #else /* DMC_USE_PNG */ void ImageLoadSave::LoadPNG(const char *fname) { throw DMcError("PNG Support not compiled in."); } void ImageLoadSave::SavePNG(const char *fname) const { throw DMcError("PNG Support not compiled in."); } #endif /* DMC_USE_PNG */ ////////////////////////////////////////////////////// // Matlab MAT File Format #ifdef DMC_USE_MAT // Read a MAT file. void ImageLoadSave::LoadMAT(const char *fname) { MATFile *pmat; mxArray *pa; // open file and verify its contents with matGetArray pmat = matOpen(fname, "r"); if(pmat == NULL) throw DMcError("Error opening fname " + string(fname)); // Read in array pa = matGetNextArray(pmat); if(pa == NULL) throw DMcError("Error reading matrix.)"; if(mxGetNumberOfDimensions(pa) != 2) throw DMcError("MAT Error: matrix does not have two dimensions."); // Copy the data out. // Not implemented. ASSERT_R(0); mxDestroyArray(pa); if(matClose(pmat)) throw DMcError("Error closing MAT file."); } // Write a MAT file void ImageLoadSave::SaveMAT(const char *fname) const { if(Pix==NULL || chan < 1 || wid < 1 || hgt < 1) throw DMcError("MAT Image is not defined. Not saving.)"; if(!fname || !fname[0]) throw DMcError("MAT Filename not specified. Not saving."); MATFile *pmat; mxArray *pa; int status; if(Verbose) cerr << "Saving " << fname << endl; pmat = matOpen(fname, "w"); if(pmat == NULL) throw DMcError("Error creating fname " +string(fname)); mxClassID TheClass = mxUNKNOWN_CLASS; if(is_ushort) { TheClass = mxUINT16_CLASS; } else { ASSERT_R(0); } int dims[3]; dims[0] = hgt; dims[1] = wid; dims[2] = chan; pa = mxCreateNumericArray(chan > 1 ? 3:2, dims, TheClass, mxREAL); ASSERT_RM(pa, "memory alloc failed"); mxSetName(pa, "Img"); if(is_ushort) { // Transpose the data. I hate this. unsigned short *ImTr = (unsigned short *)mxGetPr(pa); unsigned short *usPix = (unsigned short *)Pix; int k = 0; for(int y=0; y<hgt; y++) { for(int x=0; x<wid; x++) { for(int c=0; c<chan; c++) { ImTr[(x * hgt + y) * chan + c] = usPix[k++]; } } } } else { ASSERT_R(0); } status = matPutArray(pmat, pa); if(status) throw DMcError("Error using matPutArray."); mxDestroyArray(pa); if(matClose(pmat) != 0) throw DMcError("Error closing MAT file."); } #else /* DMC_USE_MAT */ void ImageLoadSave::LoadMAT(const char *fname) { throw DMcError("MAT Support not compiled in."); } void ImageLoadSave::SaveMAT(const char *fname) const { throw DMcError("MAT Support not compiled in."); } #endif /* DMC_USE_MAT */ ////////////////////////////////////////////////////// // HDR (RGBE) File Format // Currently this loads and saves f3Images, not rgbeImages. // I will add this later. void ImageLoadSave::LoadRGBE(const char* fname) { FILE *filep = fopen(fname, "rb"); if(filep == NULL) throw DMcError("LoadRGBE: Unable to load HDR: " + string(fname)); int i, j, row; float exposure; /*a very basic RADIANCE pic file header */ char line[1000]; fgets(line, 1000, filep); if(!strcmp(line, "#?RADIANCE")) throw DMcError("LoadRGBE: Not a HDR file: " + string(fname)); fgets(line, 1000, filep); fgets(line, 1000, filep); fscanf(filep, "EXPOSURE=%f\n", &exposure); if(Verbose) cerr << "Reading HDR file with exposure " << exposure << endl; //fgets(line, 1000, filep); fscanf(filep, "-Y %d +X %d\n", &hgt, &wid); if(Verbose) cerr << wid << "x" << hgt << endl; is_uint = false; is_float = true; chan = 3; Pix = ImageAlloc(); RGBE *helpit = new RGBE[wid]; /*Allocate enough space for one row of COLOR at a time */ COLOR* oneRow = (COLOR*)malloc(sizeof(COLOR)*wid); float invexp = 1.0f / exposure; /* Convert RGBE representation to float,float,float representation */ int k=0; float *P = (float *)Pix; for (row=0;row<hgt;row++) { freadscan(oneRow, helpit, wid, filep); for(i=0;i<wid;i++) { for(j=0;j<3;j++) { P[k] = oneRow[i][j] * invexp; k++; } } } fclose(filep); free(oneRow); delete [] helpit; } // int freadscan(register COLOR *scanline, int len, FILE *fp) /* read in a scanline */ // XXX Here's a global variable. It's totally evil. Use it to set the outgoing exposure. float DMcExposureGlobal = 1.0f; void ImageLoadSave::SaveRGBE(const char* fname) const { ASSERT_R(is_float && chan==3); ASSERT_R(Pix); FILE *filep = fopen(fname, "wb"); if(filep == NULL) throw DMcError("SaveRGBE: Unable to save HDR: " + string(fname)); const char * comments = "no comment"; /*Allocate enough space for one row of COLOR at a time */ COLOR* oneRow; oneRow = (COLOR*)malloc(sizeof(COLOR)*wid); float exposure; // exposure = 0.52/getApproxMedian(); // exposure = 1.0f; // Give a constant default exposure (and save time). exposure = DMcExposureGlobal; // Use the evil global exposure value. /*a very basic RADIANCE pic file header */ fprintf(filep,"#?RADIANCE\n"); fprintf(filep,"# %s\n",comments); fprintf(filep,"FORMAT=32-bit_rle_rgbe\n"); fprintf(filep,"EXPOSURE=%25.13f\n",exposure); fprintf(filep,"\n"); fprintf(filep,"-Y %d +X %d\n",hgt, wid); RGBE *helpit = new RGBE[wid]; /* Convert separated channel representation to per pixel representation */ // int k=0; float *P = (float *)Pix; for (int row=0;row<hgt;row++) { #if 0 int i, j, row; for(i=0;i<wid;i++) { for(j=0;j<3;j++) { oneRow[i][j] = P[k]; // *exposure; k++; } } // fwritescan(oneRow, helpit, wid, filep); #endif fwritescan((COLOR*)&P[row*wid*3], helpit, wid, filep); } fclose(filep); free(oneRow); delete [] helpit; if(Verbose) cerr << "Wrote out HDR file with exposure " << exposure << endl; }
true
7fe28b2427e6d516140672adb54bf9b7ba8b6ebe
C++
preetisahani16/CPP-Practice
/arr.cpp
UTF-8
1,275
3.609375
4
[]
no_license
#include<iostream> using namespace std; class member{ string name; int age; int phn_no; int address; int salary; public: void print_salary() { cout<<"salary of members"<<endl; cin>>salary; } void input() { cout<<" Enter the name"<<endl; cin>>name; cout<<" Enter the age"<<endl; cin>>age; cout<<"Enter the phn_no"<<endl; cin>>phn_no; cout<<"Enter the address"<<endl; cin>>address; } void output(){ cout<<"name="<<name<<endl; cout<<"age="<<age<<endl; cout<<"phn_no="<<phn_no<<endl; cout<<"address="<<address<<endl; } }; class manager: public member { string specialisation; string department; public: manager(string specializsation,string department) { this->department =department; this->specialisation =specialisation; } void show(){ cout<<"Department="<<department<<endl; cout<<"specialisation="<<specialisation<<endl; } }; int main(){ member obj; manager obj1("Human Resource","Accounting"); obj.input(); obj.output(); obj.print_salary(); obj1.show(); return 0; }
true
2c6f310f94e34f8b58bbb2981d6911542e6309e7
C++
colorstheforce/MapleEngine
/Code/Maple/src/Scripts/Mono/MapleMonoMethod.h
UTF-8
2,687
2.765625
3
[]
no_license
////////////////////////////////////////////////////////////////////////////// // This file is part of the Maple Engine // // Copyright ?2020-2022 Tian Zeng // ////////////////////////////////////////////////////////////////////////////// #pragma once #include "Mono.h" #include <string> #include <vector> #include <tuple> #include <utility> namespace Maple { class MAPLE_EXPORT MapleMonoMethod { public: ~MapleMonoMethod(); MapleMonoMethod(MonoMethod* method); auto invoke(MonoObject* instance, void** params = nullptr) ->MonoObject*; auto invokeVirtual(MonoObject* instance, void** params = nullptr)->MonoObject*; template<typename ...Args> inline auto invokeVirtual(MonoObject* instance, Args ...args) { void* params[sizeof...(Args)] = {}; auto a = std::forward_as_tuple(args...); packParams(params, a); return invokeVirtual(instance, params); } template<typename ...Args> inline auto invoke(MonoObject* instance, Args ...args) { void* params[sizeof...(Args)] = {}; auto a = std::forward_as_tuple(args...); packParams(params, a); return invoke(instance, params); } /** * Gets a thunk for this method. A thunk is a C++ like function pointer that you can use for calling the method. * @note This is the fastest way of calling managed code. */ auto getThunk() const -> void*; auto getName() const ->std::string; auto getReturnType() const->std::shared_ptr<MapleMonoClass>; auto getNumParameters() const -> uint32_t; auto getParameterType(uint32_t paramIdx) const->std::shared_ptr<MapleMonoClass>; auto isStatic() const -> bool; auto hasAttribute(std::shared_ptr<MapleMonoClass> monoClass) const -> bool; auto getAttribute(std::shared_ptr<MapleMonoClass> monoClass) const ->MonoObject*; auto getVisibility() ->MonoMemberVisibility; private: friend class MapleMonoClass; friend class MapleMonoProperty; auto cacheSignature() const -> void; MonoMethod* method = nullptr; mutable std::shared_ptr<MapleMonoClass> cachedReturnType = nullptr; mutable std::vector< std::shared_ptr<MapleMonoClass>> cachedParameters; mutable uint32_t cachedNumParameters = 0; mutable bool _static = false; mutable bool hasCachedSignature = false; private: template<size_t I = 0, typename ...Tp> inline typename std::enable_if_t<I == sizeof ...(Tp)> packParams(void**, std::tuple<Tp ...>& t) { } template<size_t I = 0, typename ...Tp> inline typename std::enable_if_t < I < sizeof ...(Tp)> packParams(void** param, std::tuple<Tp ...>& t) { param[I] = (void*)(&std::get<I>(t)); packParams<I + 1, Tp...>(param, t); } }; };
true
6b5121965f4522416a31c30f5aa2625c9cc4130f
C++
msempere/aisoyTutor
/src/led.cpp
UTF-8
905
3.25
3
[]
no_license
#include "led.h" Led::Led() { Set(-1,-1,-1); } Led::Led(int xx,int yy,int v) { SetX(xx); SetY(yy); value=v; } Led::~Led() { value=0; } void Led::Set(int xx, int yy, int v) { SetX(xx); SetY(yy); value=v; } void Led::SetValue(int v) { value=v; } int Led::Value() { return value; } int Led::GetX() { return x; } int Led::GetY() { return y; } void Led::SetX(int xx) { if(xx<=KmaxX-1) x=xx; } void Led::SetY(int yy) { if(yy<=KmaxY-1) y=yy; } void Led::SetRandom() { SetX(GetRandom(0,KmaxX-1)); SetY(GetRandom(0,KmaxY-1)); SetValue(1); } bool Led::operator==(Led &derecha) { if(GetX()==derecha.GetX() && GetY()==derecha.GetY() && Value()==derecha.Value()) return true; return false; } Led& Led::operator=(Led& derecha) { if (this == &derecha) return *this; else{ Set(derecha.GetX(),derecha.GetY(),derecha.Value()); } }
true
bf310ca3a0bae26f1d2dd759fc46b35347fbb7a4
C++
EmplaceBackCS/Cpp-2D-game-using-SDL-OpenGL
/SlimeGame/Bullets.cpp
UTF-8
3,255
3.109375
3
[]
no_license
#include "Bullets.h" #include "Zombie.h" #include <algorithm> Bullets::Bullets() : _position(0.0f), _speed(0.0f), _direction(0.0f), _lifeTime(1), _damage(1.0f), _size(20) { } Bullets::~Bullets() { } Bullets::Bullets(glm::vec2 pos, glm::vec2 direction, float speed, float lifeTime, int size): _position(pos), _direction(direction), _speed(speed), _lifeTime(lifeTime), _size(size) { } //----------------------------------------- Draw function ---------------------------------------- void Bullets::draw(CSGengine::SpriteBatch& spriteBatch) { CSGengine::ColorRGBA8; const static glm::vec4 uv(0.0f, 0.0f, 1.0f, 1.0f); //This was copied and pasted from main game. This is just to test out our class, bad practice to do this! static CSGengine::GLTexture texture = CSGengine::ResourceManager::getTexture("Textures/Bullet_000_Left.png"); CSGengine::ColorRGBA8 color; color.a = 255; color.b = 255; color.g = 255; color.r = 255; glm::vec4 posAndSize = glm::vec4( _position.x + 21, _position.y + 20, _size, _size); spriteBatch.draw(posAndSize, uv, texture.id, 0.0f, color); } //Check if we need to update. If it returns true, it will update the position. //False will cause it to die out bool Bullets::update() { _position += (_direction * _speed); //Make sure every frame we update, we shorten the lifetime //of our bullet _lifeTime--; if (_lifeTime == 0) { return true; } ////Returns false if life time isn't 0 return false; } bool Bullets::checkBulletCollision(std::vector<Zombie*> zombie, int& index) { static const float MIN_DISTANCE = 30 + 30; static const int BULLET_RADIUS = 30; for (unsigned int i = 0; i < zombie.size(); i++) { //Going to use circular collision glm::vec2 centerPosA = _position + glm::vec2(BULLET_RADIUS); glm::vec2 centerPosB = zombie[i]->getPos() + glm::vec2(BULLET_RADIUS); //Dist vect for distance vector glm::vec2 distVect = centerPosA - centerPosB; //This will give us the length of both center agents when they collide float distance = glm::length(distVect); float collisionDepths = MIN_DISTANCE - distance; //If our math was right, then when we collide with a bullet //Collision depths should be greater then 0! if (collisionDepths > 0) { return index = i; } } return false; } //------------------------------ Check bullet collision here ------------------- //Collision needs a bit of help //Needs update when we can figure out a better formula bool Bullets::checkBulletCollisionWithWorld(const std::vector<std::string>& levelData) { static const float TILE_WIDTH = 64.0f; glm::ivec2 gridPosition; gridPosition.x = floor(_position.x / (float)TILE_WIDTH); gridPosition.y = floor(_position.y / (float)TILE_WIDTH); //Check if any one is outside the world if (gridPosition.x < 0 || gridPosition.x >= levelData[0].length() || gridPosition.y < 0 || gridPosition.y >= levelData.size()) { //Return true, meaning delete the bullet return true; } //This is just a bool expression. Will be true whenever it's not a dot return (levelData[gridPosition.y][gridPosition.x] != '.'); } //-----------------------------------------Set functions----------------------- void Bullets::setPosition(glm::vec2 position) { _position += position; }
true
b8678569385f870aaf503351685e8cd8c8617bbf
C++
iburgoa13/Algoritmias
/Cucurucho/Cucurucho/Source.cpp
UTF-8
834
3.578125
4
[]
no_license
#include <iostream> #include <string> using namespace std; const int MAX = 15; void resuelve(); void cucuruchoC(int c, int v, string pal, bool &primero); int main() { int casos; int i = 0; cin >> casos; while (i < casos) { resuelve(); cout << endl; i++; } return 0; } void resuelve() { int choco, vainilla; string palabra = ""; cin >> choco >> vainilla; bool primero = true; cucuruchoC(choco, vainilla, palabra,primero); } void cucuruchoC(int c, int v, string pal,bool &primero) { if (c == 0 && v == 0 && primero) { cout << pal; primero = false; return; } if (c == 0 && v == 0 && !primero) { cout << " " + pal; return; } if (c > 0) { cucuruchoC(c - 1, v, pal + 'C',primero); } if (v > 0) { cucuruchoC(c, v - 1, pal + 'V',primero); } }
true
6df9934adae1e957e4760ae3a61c970d746add43
C++
Auliyaa/choux-pro
/src/choux_window.cpp
UTF-8
2,934
2.515625
3
[ "Apache-2.0" ]
permissive
#include "choux_window.h" #include <QtCore/QDir> #include <QtCore/QDebug> #include <QtCore/QTime> #include "ui_choux_window.h" choux_window::choux_window() : QMainWindow(), _ui(new Ui::choux_window) { _ui->setupUi(this); // Add some background magic QDir bg_dir(":/bg"); qsrand(QTime::currentTime().msec()); QString bg = bg_dir.entryList()[qrand()%bg_dir.entryInfoList().size()]; _ui->centralwidget->setStyleSheet("#centralwidget { border-image: url(:/bg/" + bg + ") 0 0 0 0 stretch stretch; }"); } choux_window::~choux_window() { delete _ui; } void choux_window::input_changed() { _ui->results->setText(""); int base = _ui->base->value(); int total = _ui->total->value(); int last = _ui->last->value(); _ui->total->setEnabled(!(base != 0 && last != 0)); _ui->base->setEnabled( !(last != 0 && total != 0)); _ui->last->setEnabled( !(base != 0 && total != 0)); if (last != 0 && total != 0) { // Compute number of steps and base size int current_count = last; int current_total = total-current_count; int steps=1; while (current_total >= current_count) { ++current_count; ++steps; current_total -= current_count; } setResults(current_count, last, steps, total-current_total, current_total); } else if (base != 0 && total != 0) { // Compute number of steps and top size int current_count = base; int current_total = total-current_count; int steps=1; while (current_count-1 >= 3 && current_total >= current_count-1) { ++steps; --current_count; current_total -= current_count; } setResults(base, current_count, steps, total-current_total, current_total); } else if (base != 0 && last != 0) { // Compute number of steps and total int current_count = last; int steps=1; int total=current_count; while (current_count < base) { ++steps; ++current_count; total+=current_count; } setResults(base, last, steps, total, 0); } } void choux_window::reset() { _ui->base->setValue(0); _ui->total->setValue(0); _ui->last->setValue(0); } void choux_window::setResults(int base, int top, int steps, int count, int leftover) { QString result = "Cette <b>splendide</b> pièce montée comprend les éléments suivants:<br/><br/>"; result += "<ul>"; result += "<li><b>Etage du haut :</b> " + QString::number(top) + "</li>"; result += "<li><b>Etage du bas :</b> " + QString::number(base) + "</li>"; result += "<li><b>Nombre d'étages:</b> " + QString::number(steps) + "</li>"; result += "<li><b>Nombre de choux:</b> " + QString::number(count) + "</li>"; result += "<li><b>Reste en choux :</b> " + QString::number(leftover) + "</li>"; result += "</ul>"; _ui->results->setText(result); }
true
04f5d62d41e61b69c3d75e42fff794e44bf4672e
C++
angrysea/AMGServer
/parser/XMLAttr.h
UTF-8
481
2.71875
3
[]
no_license
#pragma once #include <string> #include <memory> #include "export.h" #include "XMLNode.h" class PARSER_API XMLAttr { public: XMLAttr(const std::string & name) : name{ name } { } const std::string & getNodeName() const { return name; } const std::string & getNodeValue() const { return value->getNodeValue(); } void appendChild(std::shared_ptr<XMLNode> & newValue) { value = newValue; } private: std::string name; std::shared_ptr<XMLNode> value; };
true
cc32d2d9e9621cae5821e58f7d6320db9e7aaaeb
C++
mucsirobert/Clever_String
/main.cpp
UTF-8
4,092
3.375
3
[]
no_license
#include <iostream> #include "mystring.h" int main() { {//Constructors std::cout << "Constructor test:" << std::endl; MyString emp{}; std::cout << emp << " " << emp.getCount() << std::endl; MyString str{"cica"}; std::cout << str << " " << str.getCount() << std::endl; MyString my = "kutya"; std::cout << my << " " << my.getCount() << std::endl; } {//Copy std::cout << "Copy constructor test:" << std::endl; MyString to_copy{"to_copy"}; MyString copied{to_copy}; std::cout << to_copy << " " << to_copy.getCount() << std::endl; std::cout << copied << " " << copied.getCount() << std::endl; } {//operator= std::cout << "Operator= test:" << std::endl; MyString to_copy{"to="}; MyString copied = to_copy; std::cout << to_copy << " " << to_copy.getCount() << std::endl; std::cout << copied << " " << copied.getCount() << std::endl; } {//move std::cout << "Move constructor test:" << std::endl; MyString str{"str"}; MyString moved{std::move(str)}; // std::cout << str << " " << str.getCount() << std::endl; std::cout << moved << " " << moved.getCount() << std::endl; str = std::move(moved); std::cout << str << " " << str.getCount() << std::endl; } {//MyString append std::cout << "MyString append test:" << std::endl; // MyString cica{"cica"}; // MyString kutya{"kutya"}; // MyString cica2{cica}; // MyString allatok = cica+kutya; // cica += cica; // std::cout << cica << " " << cica.getCount() << std::endl; // std::cout << cica2 << " " << cica2.getCount() << std::endl; // std::cout << kutya << " " << kutya.getCount() << std::endl; // std::cout << allatok << " " << allatok.getCount() << std::endl; // std::cout << cica << " " << cica.getCount() << std::endl; // cica += MyString{}; // std::cout << cica << " " << cica.getCount() << std::endl; // std::cout << "----------------"<< std::endl; MyString str1{"alma"}; MyString str2{"fa"}; MyString str3 = str2; MyString osszeg = str1 + str2; std::cout << osszeg << " " << osszeg.getCount() << std::endl; str1 += str2; std::cout << str1 << " " << str1.getCount() << std::endl; str2 += MyString{}; std::cout << str2 << " " << str2.getCount() << std::endl; str2 += MyString{"haz"}; std::cout << str2 << " " << str2.getCount() << std::endl; std::cout << str3 << " " << str3.getCount() << std::endl; } {//char append std::cout << "Char append test:" << std::endl; MyString dob{"dob"}; MyString dobok{dob}; dob += 'i'; std::cout << dob << " " << dob.getCount() << std::endl; std::cout << dobok << " " << dobok.getCount() << std::endl; MyString str = dobok + '5'; std::cout << dobok << " " << dobok.getCount() << std::endl; std::cout << str << " " << str.getCount() << std::endl; } {//index std::cout << "Index test:" << std::endl; MyString dobberman{"kutya"}; MyString husky = dobberman; dobberman[4] = 'u'; std::cout << dobberman << " " << dobberman.getCount() << std::endl; std::cout << husky << " " << husky.getCount() << std::endl; MyString const constant{"Konstans"}; char o = constant[1]; std::cout << "constant[1]: " << o << std::endl; try{ std::cout<<dobberman[5]<<std::endl; } catch (std::out_of_range& e){ std::cout << e.what() << " kivetel elkapva" << std::endl; } } {//input and length std::cout << "Input and legth test:\n (write smthng)" << std::endl; MyString str; std::cin >> str; std::cout << str << " " << str.getLength() << std::endl; } return 0; }
true
1c1e506b0d86d7cff8de517ac31c33b7951407d0
C++
Przemotar/MarsColony
/main.cpp
UTF-8
1,528
2.703125
3
[]
no_license
#include <iostream> #include <SFML/Graphics.hpp> #include "Enemy.h" #include "EnemyManager.h" #include "GameManager.h" #include "MapManager.h" #include "BuildingManager.h" int main() { sf::RenderWindow window(sf::VideoMode(800, 600), "SFML works!"); EnemyManager enemyManager; GameManager gameManager; MapManager mapManager; enemyManager.Init(); gameManager.Init(); mapManager.Init(); BuildingManager buildingManager(window); buildingManager.Init(); int playerHp = 100; sf::Texture texture; texture.loadFromFile("MarsWarm.png"); sf::Clock clock; sf::Time timer; bool moveRight; while (window.isOpen()) { timer = clock.getElapsedTime(); if (timer.asSeconds() >= 1) { clock.restart(); gameManager.Gold += buildingManager.getIncome(); } sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } enemyManager.Update(); gameManager.Update(); buildingManager.Update(); if (enemyManager.isEnemyAtBase()) { gameManager.DealDamage(enemyManager.GetEnemyAtBase().DealDamageAmount()); enemyManager.ClearEnemiesAtBase(); } window.clear(); mapManager.DrawMap(window); enemyManager.DrawEnemies(window); buildingManager.DrawBuildings(window); window.display(); } return 0; }
true
737c78ad64fcdf272ad843b8aab9093d5cdb1815
C++
lunakoly/EyeBang
/editing/layer.cpp
UTF-8
3,158
3.078125
3
[]
no_license
#include "layer.h" Layer::Layer(const QString &name, QObject *parent) : QObject(parent) , name(name) { } QString Layer::getName() { return name; } void Layer::setName(const QString &name) { auto oldName = this->name; this->name = name; emit nameChanged(oldName, name); } const QVector<Segment> Layer::getSegments() const { return segments; } void Layer::addSegment(const Segment &segment) { // detect if segments is contained // inside some other segment for (auto &it : segments) { if (it.begin <= segment.begin && segment.end <= it.end) { return; } } // detect segments that the new // one contains itself int it = 0; while (it < segments.size()) { if (segment.begin <= segments[it].begin && segments[it].end <= segment.end) { segments.remove(it); } else { it += 1; } } // detect touching and one-side // overlapping segments // (by invariant we believe that there're // no overlapping segments now). int touchLeft = -1; int touchRight = -1; for (int it = 0; it < segments.size(); it++) { if (segments[it].begin <= segment.begin && segment.begin <= segments[it].end) { touchLeft = it; } else if (segments[it].begin <= segment.end && segment.end <= segments[it].end) { touchRight = it; } } if (touchLeft != -1 && touchRight != -1) { segments[touchLeft].end = segments[touchRight].end; segments.remove(touchRight); emit segmentAdded(segments[touchLeft]); } else if (touchLeft != -1) { segments[touchLeft].end = segment.end; emit segmentAdded(segments[touchLeft]); } else if (touchRight != -1) { segments[touchRight].begin = segment.begin; emit segmentAdded(segments[touchRight]); } else { segments.append(segment); emit segmentAdded(segment); } } void Layer::removeSegment(int index) { auto it = segments[index]; segments.remove(index); emit segmentRemoved(it); } void Layer::clearSegments() { while (!segments.isEmpty()) { auto it = segments[0]; segments.removeFirst(); emit segmentRemoved(it); } } void Layer::setNewLeftBound(int position) { if (!segments.isEmpty()) { int closest = -1; for (int it = 0; it < segments.size(); it++) { if (position < segments[it].end) { if (closest == -1) { closest = it; } else if (segments[it].end < segments[closest].end) { closest = it; } } } if (closest != -1) { if (position < segments[closest].begin) { addSegment({position, segments[closest].end}); } else { segments[closest].begin = position; emit segmentsModified(); } } } } void Layer::setNewRightBound(int position) { if (!segments.isEmpty()) { int closest = -1; for (int it = 0; it < segments.size(); it++) { if (segments[it].begin < position) { if (closest == -1) { closest = it; } else if (segments[it].begin > segments[closest].begin) { closest = it; } } } if (closest != -1) { if (segments[closest].end < position) { addSegment({segments[closest].begin, position}); } else { segments[closest].end = position; emit segmentsModified(); } } } }
true
8be00007ceefe88e8c379c02bed8110674653dca
C++
ShinSeungChul/BOJ
/10773/10773/소스.cpp
UTF-8
497
2.6875
3
[]
no_license
#include<iostream> #include<cstdio> #include<vector> #include<string> #include<set> #include<utility> #include<algorithm> #include<map> #pragma warning(disable:4996) using namespace std; int main() { int n; cin >> n; vector<int> v; int num; for (int i = 0; i < n; i++) { scanf("%d", &num); if (num) v.push_back(num); else v.pop_back(); } vector<int>::iterator iter; int sum = 0; for (iter = v.begin(); iter != v.end(); iter++) { sum += (*iter); } cout << sum << endl; }
true
700a85e63277d024b039fe3fe3923266c549cf95
C++
upple/BOJ
/src/9000/9251.cpp
UTF-8
400
2.53125
3
[ "MIT" ]
permissive
#include <cstdio> #include <cstring> #define max(x, y) (x>y?x:y) int main() { char s1[1001], s2[1001]; int dp[1001][1001] = {}; scanf("%s %s", s1, s2); for (int i = 0; s2[i]; i++) { for (int j = 0; s1[j]; j++) { if (s1[j] == s2[i]) dp[j + 1][i + 1] = dp[j][i] + 1; else dp[j + 1][i + 1] = max(dp[j][i + 1], dp[j + 1][i]); } } printf("%d", dp[strlen(s1)][strlen(s2)]); }
true
5e175a36706035a6870059b7aee85cb8210af0bd
C++
Gyudev/JUNGOL
/함수1/형성평가4.cpp
UTF-8
280
3.40625
3
[]
no_license
#include <iostream> using namespace std; int Print(int a, int b) { int max = 0; int min = 0; if (a > b) { max = a * a; min = b * b; } else { max = b * b; min = a * a; } return max - min; } int main() { int a, b; cin >> a >> b; cout << Print(a, b) << endl; }
true
229dc9d9221ec074a53afd2b04156113faa9db70
C++
anujjain5699/cpp
/reverse_stack_without_using_another_stack.cpp
UTF-8
795
3.640625
4
[]
no_license
#include<iostream> #include<stack> using namespace std; void insertAtButtom(stack<int>&st,int buttom_element){ if(st.empty()){ st.push(buttom_element); return; } int top_element=st.top(); st.pop(); insertAtButtom(st,buttom_element); st.push(top_element); } void reverse(stack<int>& st){ if(st.empty()) return; int top_element = st.top(); st.pop(); reverse(st); insertAtButtom(st, top_element); } void printstack(stack<int> st){ while(!st.empty()){ cout << st.top()<<" "; st.pop(); } return; } int main() { stack<int> st; st.push(1); st.push(2); st.push(3); st.push(4); st.push(5); printstack(st); reverse(st); cout<<"\nStack :\n"; printstack(st); return 0; }
true
ba5bebf2cec4013c194d104c2626000c24e3a414
C++
FServais/SushiPP
/compiler/ast/visitor/TypeInferenceVisitor.cpp
UTF-8
69,462
2.65625
3
[]
no_license
#include "TypeInferenceVisitor.hpp" #include "../../inference/Types.hpp" #include "../../inference/InferenceExceptions.hpp" #include <algorithm> #include <stdexcept> using namespace std; using namespace visitor; using namespace inference; using namespace symb; using namespace errors; using namespace settings; #include <iostream> TypeInferenceVisitor::TypeInferenceVisitor(ErrorHandler& handler, SymbolTable<FunctionInfo>& function_table_, SymbolTable<VariableInfo>& variable_table_, TypeSymbolTable& type_table_, BuiltInFunctions& built_in) : error_handler(handler), type_table(type_table_), function_table(function_table_), variable_table(variable_table_), current_scope(0) { // insert the built in functions in the table for(auto& function : built_in) { string func_name = type_table.unique_id_name(0, function.first); // get unique variable names for parameters vector<string> param_variables; generate_n(back_inserter(param_variables), get<2>(function.second).size(), [this](){ return type_table.unique_varname(); }); pair<string,string> func_data = type_table.new_function(param_variables, func_name, get<2>(function.second)); // set return type type_table.unify(func_data.second, get<3>(function.second)); if(get<4>(function.second) == NO_TYPE) continue; for(size_t i = 0; i < get<2>(function.second).size(); ++i) { ShallowType type = get<2>(function.second)[i]; if(type & (ARRAY | LIST)) // if the type of the parameter is either array or list { // create a new array or list variable pair<string, string> structure = (type == ARRAY) ? type_table.new_array() : type_table.new_list(); // unify this new variable with the ith parameter variable type_table.unify(structure.first, param_variables[i]); // unify the structure type with the actual type type_table.unify(structure.second, get<4>(function.second)); } } } } void TypeInferenceVisitor::visit( ast::ASTNode& node ) { //cout << "ASTNode" << endl << type_table << endl << endl; // hopefully, never called because of virtual for(auto child : node.get_children()) { params.call(); child->accept(*this); } params.ret(); } void TypeInferenceVisitor::visit( ast::Identifier& id ) { //cout << "Identifier (" << id.id() << ")" << endl << type_table << endl << endl; string alpha = params.get_param(1); // unify alpha with the type of the identifier size_t identifier_scope; if(variable_table.symbol_exists(id.id())) identifier_scope = variable_table.get_symbol_scope_id(id.id()); else if(function_table.symbol_exists(id.id())) identifier_scope = function_table.get_symbol_scope_id(id.id()); else throw std::logic_error("The symbol is still undefined after scope checking"); string id_type_name = type_table.unique_id_name(identifier_scope, id.id()); //cout << alpha << " - > " << id_type_name << endl; /** * A function identifier could not be in the table yet, the its variable has to be added * It happens in case of cross-recursive function */ if(!type_table.contains(id_type_name)) type_table.new_variable(id_type_name); type_table.unify(alpha, id_type_name); params.ret(); } void TypeInferenceVisitor::visit( ast::K_Continue& cont ) { // bypassed by the decl func node //throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::K_Break& brk ) { // bypassed by the decl func node //throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Type_Int& type ) { // bypassed by the decl func node throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Type_Float& type ) { // bypassed by the decl func node throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Type_Char& type ) { // bypassed by the decl func node throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Type_String& type ) { // bypassed by the decl func node throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Type_Array& type ) { // bypassed by the decl func node throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Type_List& type ) { // bypassed by the decl func node throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Type_Bool& type ) { // bypassed by the decl func node throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Type_Function& type ) { // bypassed by the decl func node throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Op_Plus& op ) { //cout << "Op_Plus" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator // operands can only be integers or float type_table.update_hints(alpha, TypesHint(INT | FLOAT)); // record the operator type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '+' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '+' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_Minus& op ) { //cout << "Op_Minus" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(INT | FLOAT)); // operands can only be integers or float // record the operator type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '-' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '-' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_Mult& op ) { //cout << "Op_Mult" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(INT | FLOAT)); // operands can only be integers or float // record the operator type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '*' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '*' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_Div& op ) { //cout << "Op_Div" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(INT | FLOAT));// operands can only be integers or float // record the operator type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '/' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '/' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_Modulo& op ) { //cout << "Op_Modulo" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // module can only have integer operands // record the operator type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '%' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '%' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_Exponentiation& op ) { //cout << "Op_Exponentiation" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(INT | FLOAT)); // base can only be an integer or a float // record the exponent base type id op.set_type_id(alpha); string beta = type_table.new_variable(); // add a type variable for the exponent type_table.unify_int(beta); // exponent must be an integer params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '**' operator's left operand : " + string(e.what())); } params.add_param(beta); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '**' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_UnaryMinus& op ) { //cout << "Op_UnaryMinus" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(INT | FLOAT)); // base can only be an integer or a float // record the operator type id op.set_type_id(alpha); params.add_param(alpha); // alpha is transmitted to the expression params.call(); try { op.get_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '-' unary operator's operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_BitwiseOr& op ) { //cout << "Op_BitwiseOr" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // bitwise operators applies on int and return int // record the operator type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '|' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '|' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_BitwiseAnd& op ) { //cout << "Op_BitwiseAnd" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // bitwise operators applies on int and return int // record the operator type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '&' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '&' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_BitwiseXor& op ) { //cout << "Op_BitwiseXor" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // bitwise operators applies on int and return int // record the operator type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '^' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '^' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_BitwiseNot& op ) { //cout << "Op_BitwiseNot" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // bitwise operators applies on int and return int // record the operator type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '~' unary operator's operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_LogicalOr& op ) { //cout << "Op_LogicalOr" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_bool(alpha); // boolean operator expect boolean operands and return a boolean // record the operator type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '||' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '||' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_LogicalAnd& op ) { //cout << "Op_LogicalAnd" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_bool(alpha); // boolean operator expect boolean operands and return a boolean // record the operator type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '&&' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '&&' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_LogicalNot& op ) { //cout << "Op_LogicalNot" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_bool(alpha); // boolean operator expect boolean operands and return a boolean // record the operator type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '!' unary operator's left operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_CompLessThan& op ) { //cout << "Op_CompLessThan" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_bool(alpha); // comparison operators return a boolean // operands can have a different types (but must be both either float or int) string beta = type_table.new_variable(TypesHint(FLOAT | INT)); // record the operands type id op.set_type_id(beta); params.add_param(beta); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '<' operator's left operand : " + string(e.what())); } params.add_param(beta); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '<' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_CompGreaterThan& op ) { //cout << "Op_CompGreaterThan" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_bool(alpha); // comparison operators return a boolean // operands can have a different types (but must be both either float or int) string beta = type_table.new_variable(TypesHint(FLOAT | INT)); // record the operands type id op.set_type_id(beta); params.add_param(beta); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '>' operator's left operand : " + string(e.what())); } params.add_param(beta); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '>' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_CompLessEqual& op ) { //cout << "Op_CompLessEqual" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_bool(alpha); // comparison operators return a boolean // operands can have a different types (but must be both either float or int) string beta = type_table.new_variable(TypesHint(FLOAT | INT)); // record the operands type id op.set_type_id(beta); params.add_param(beta); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '<=' operator's left operand : " + string(e.what())); } params.add_param(beta); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '<=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_CompGreaterEqual& op ) { //cout << "Op_CompGreaterEqual" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_bool(alpha); // comparison operators return a boolean // operands can have a different types (but must be both either float or int) string beta = type_table.new_variable(TypesHint(FLOAT | INT)); // record the operands type id op.set_type_id(beta); params.add_param(beta); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '>=' operator's left operand : " + string(e.what())); } params.add_param(beta); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '>=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_CompEqual& op ) { //cout << "Op_CompEqual" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_bool(alpha); // comparison operators return a boolean // operands can have a different types (but must be both either float, bool or int) string beta = type_table.new_variable(TypesHint(INT | FLOAT | BOOL)); // record the operands type id op.set_type_id(beta); params.add_param(beta); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '==' operator's left operand : " + string(e.what())); } params.add_param(beta); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '==' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_CompNotEqual& op ) { //cout << "Op_CompNotEqual" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_bool(alpha); // comparison operators return a boolean // operands can have a different types (but must be both either float, bool or int) string beta = type_table.new_variable(TypesHint(INT | FLOAT | BOOL)); // record the operands type id op.set_type_id(beta); params.add_param(beta); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '!=' operator's left operand : " + string(e.what())); } params.add_param(beta); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '!=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_LeftShift& op) { //cout << "Op_LeftShift" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // bitwise operators applies on int and return int // record the operands type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '<<' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '<<' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_RightShift& op) { //cout << "Op_RightShift" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // bitwise operators applies on int and return int // record the operands type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '>>' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '>>' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_StringConcat& op ) { //cout << "Op_StringConcat" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_string(alpha); // string concatenation takes strings as operand and return string // record the operands type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '.' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '.' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_PrefixIncrement& op ) { //cout << "Op_PrefixIncrement" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(INT | FLOAT)); // operand can only be an integer or a float // record the operands type id op.set_type_id(alpha); params.add_param(alpha); // alpha is transmitted to the expression params.call(); try { op.get_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '++' unary operator's operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_PrefixDecrement& op ) { //cout << "Op_PrefixDecrement" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(INT | FLOAT)); // operand can only be an integer or a float // record the operands type id op.set_type_id(alpha); params.add_param(alpha); // alpha is transmitted to the expression params.call(); try { op.get_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '--' unary operator's operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_PostfixIncrement& op ) { //cout << "Op_PostfixIncrement" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(INT | FLOAT)); // operand can only be an integer or a float // record the operands type id op.set_type_id(alpha); params.add_param(alpha); // alpha is transmitted to the expression params.call(); try { op.get_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '++' unary operator's operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_PostfixDecrement& op ) { //cout << "Op_PostfixDecrement" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(INT | FLOAT)); // operand can only be an integer or a float // record the operands type id op.set_type_id(alpha); params.add_param(alpha); // alpha is transmitted to the expression params.call(); try { op.get_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '--' unary operator's operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_Assignment& op ) { //cout << "Op_Assignment" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator // record the operands type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '=' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_AssignPlus& op ) { //cout << "Op_AssignPlus" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(FLOAT | INT)); // operands must be either Float or Int // record the operands type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '+=' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '+=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_AssignMinus& op ) { //cout << "Op_AssignMinus" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(FLOAT | INT)); // operands must be either Float or Int // record the operands type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '-=' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '-=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_AssignMult& op ) { //cout << "Op_AssignMult" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(FLOAT | INT)); // operands must be either Float or Int // record the operands type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '*=' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '*=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_AssignDiv& op ) { //cout << "Op_AssignDiv" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(FLOAT | INT)); // operands must be either Float or Int // record the operands type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '/=' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '/=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_AssignExpo& op ) { //cout << "Op_AssignExpo" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.update_hints(alpha, TypesHint(FLOAT | INT)); // left operand can be either an float or an int // record the exponent base type id op.set_type_id(alpha); // exponent must be an integer string beta = type_table.new_variable(); type_table.unify_int(beta); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '**=' operator's left operand : " + string(e.what())); } params.add_param(beta); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '**=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_AssignMod& op ) { //cout << "Op_AssignMod" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // modulo op expects integer operands and return an integer // record the exponent base type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '%=' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '%=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_AssignAnd& op ) { //cout << "Op_AssignAnd" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // bitwise op expects integer operands and return an integer // record the exponent base type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '&=' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '&=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_AssignOr& op ) { //cout << "Op_AssignOr" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // bitwise op expects integer operands and return an integer // record the exponent base type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '|=' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '|=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_AssignXor& op ) { //cout << "Op_AssignXor" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_int(alpha); // bitwise op expects integer operands and return an integer // record the exponent base type id op.set_type_id(alpha); // alpha goes to both operand params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '^=' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '^=' operator's right operand : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Op_AssignConcat& op ) { //cout << "Op_AssignConcat" << endl << type_table << endl << endl; string alpha = params.get_param(1); // type returned by the operator type_table.unify_string(alpha); // string concatenation takes strings as operand and return string // record the exponent base type id op.set_type_id(alpha); params.add_param(alpha); params.call(); try { op.get_left_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '.=' operator's left operand : " + string(e.what())); } params.add_param(alpha); params.call(); try { op.get_right_operand().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", op.get_location().first_line(), op.get_location().first_column(), "invalid type for the '.=' operator's right operand : " + string(e.what())); } params.ret(); } /** * Constants */ void TypeInferenceVisitor::visit( ast::String& cste ) { //cout << "String" << endl << type_table << endl << endl; string alpha = params.get_param(1); // string constant -> alpha is a string type_table.unify_string(alpha); params.ret(); } void TypeInferenceVisitor::visit( ast::Character& cste ) { //cout << "Character" << endl << type_table << endl << endl; string alpha = params.get_param(1); // char constant -> alpha is a char type_table.unify_char(alpha); params.ret(); } void TypeInferenceVisitor::visit( ast::Integer& cste ) { //cout << "Integer" << endl << type_table << endl << endl; string alpha = params.get_param(1); // int constant -> alpha is a int type_table.unify_int(alpha); params.ret(); } void TypeInferenceVisitor::visit( ast::Float& cste ) { //cout << "Float" << endl << type_table << endl << endl; string alpha = params.get_param(1); // float constant -> alpha is a float type_table.unify_float(alpha); params.ret(); } void TypeInferenceVisitor::visit( ast::Bool& cste ) { //cout << "Bool" << endl << type_table << endl << endl; string alpha = params.get_param(1); // bool constant -> alpha is a bool type_table.unify_bool(alpha); params.ret(); } void TypeInferenceVisitor::visit( ast::Array& array ) { //cout << "Array" << endl << type_table << endl << endl; string alpha = params.get_param(1); // array constant : alpha is an array of type beta pair<string, string> array_type_vars = type_table.new_array(); string beta = array_type_vars.second; array.set_type_id(beta); // alpha is of type array(beta) type_table.unify(alpha, array_type_vars.first); // each element of the array must have the type beta if(!array.empty_items()) { params.add_param(beta); params.call(); array.get_items().accept(*this); } params.ret(); } void TypeInferenceVisitor::visit( ast::List& list ) { //cout << "List" << endl << type_table << endl << endl; string alpha = params.get_param(1); // list constant : alpha is an list of type beta pair<string, string> list_type_vars = type_table.new_list(); string beta = list_type_vars.second; list.set_type_id(beta); // alpha is of type list(beta) type_table.unify(alpha, list_type_vars.first); // each element of the list must have the type beta if(!list.empty_items()) { params.add_param(beta); params.call(); list.get_items().accept(*this); } params.ret(); } void TypeInferenceVisitor::visit( ast::MakeSequenceList& seq_list ) { //cout << "MakeSequenceList" << endl << type_table << endl << endl; string alpha = params.get_param(1); // list constant : alpha is an list of type beta pair<string, string> list_type_vars = type_table.new_list(); string beta = list_type_vars.second; // alpha is of type list(beta) and beta has type int type_table.unify(alpha, list_type_vars.first); type_table.unify_int(beta); // begin and end must be of type int params.add_param(beta); params.call(); try { seq_list.get_begin().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", seq_list.get_location().first_line(), seq_list.get_location().first_column(), "invalid type for the begin expression of the sequence maker : " + string(e.what())); } params.add_param(beta); params.call(); try { seq_list.get_end().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", seq_list.get_location().first_line(), seq_list.get_location().first_column(), "invalid type for the end expression of the sequence maker : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::MakeSequenceArray& seq_array ) { //cout << "MakeSequenceArray" << endl << type_table << endl << endl; string alpha = params.get_param(1); // array constant : alpha is an array of type beta pair<string, string> array_type_vars = type_table.new_array(); string beta = array_type_vars.second; // alpha is of type array(beta) and beta has type int type_table.unify(alpha, array_type_vars.first); type_table.unify_int(beta); // begin and end must be of type int params.add_param(beta); params.call(); try { seq_array.get_begin().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", seq_array.get_location().first_line(), seq_array.get_location().first_column(), "invalid type for the begin expression of the sequence maker : " + string(e.what())); } params.add_param(beta); params.call(); try { seq_array.get_end().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", seq_array.get_location().first_line(), seq_array.get_location().first_column(), "invalid type for the end expression of the sequence maker : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::DeclFunc& declfunc ) { //cout << "DeclFunc" << endl << type_table << endl << endl; // update the symbol table with function data pair<string, string> func_type_names; if(declfunc.contains_params()) func_type_names = add_function_declaration_rule(declfunc.get_param_list(), declfunc.get_id().id(), declfunc.get_scope().get_scope_id()); else func_type_names = add_function_declaration_rule(declfunc.get_id().id(), declfunc.get_scope().get_scope_id()); // propagate return value to scope params.add_param(func_type_names.second); params.call(); declfunc.get_scope().accept(*this); // if the unification succeeds, either their was empty nory or no nori at all try { type_table.unify_void(func_type_names.second); } catch ( except::UnificationException& e ) { } params.ret(); } void TypeInferenceVisitor::visit( ast::DeclVars& declvars ) { //cout << "DeclVars" << endl << type_table << endl << endl; // no argument expecte for(size_t i = 0; i < declvars.nb_variables(); ++i) { params.call(); declvars.get_variable(i).accept(*this); } params.ret(); } void TypeInferenceVisitor::visit( ast::DeclVar& declaration ) { //cout << "DeclVar" << endl << type_table << endl << endl; // no argument expected // create a new type variable string varname = type_table.new_variable(type_table.unique_id_name(current_scope, declaration.get_identifier().id())); if(declaration.contains_expr()) { params.add_param(varname); // the expression has the same type of the identifier params.call(); declaration.get_expression().accept(*this); } params.ret(); } void TypeInferenceVisitor::visit( ast::ParamList& param_list ) { // bypassed by DelcFunc and SoyExpression throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Param& param ) { // bypassed by DelcFunc and SoyExpression throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Expression& expression ) { //cout << "Expression" << endl << type_table << endl << endl; /** * can either take one or zero parameter. If the number of * parameters is 0, then a new type variable is created for the * subexpression. Otherwise the one given as parameter is taken */ string alpha = (params.nb_params() == 0) ? type_table.new_variable(TypesHint()) : params.get_param(1); params.add_param(alpha); params.call(); try { expression.get_child().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", expression.get_location().first_line(), expression.get_location().first_column(), "invalid type in expression : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::ExpressionList& expr_list ) { string alpha = params.get_param(1); // type of the elements of the list for(size_t i = 0; i < expr_list.nb_expressions(); ++i) { params.add_param(alpha); params.call(); try { expr_list.get_nth_expression(i).accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", expr_list.get_location().first_line(), expr_list.get_location().first_column(), "invalid type for expression " + to_string(i + 1) + " of the expression list : " + string(e.what())); } } params.ret(); } void TypeInferenceVisitor::visit( ast::ModifyingExpression& expression ) { //cout << "ModifyingExpression" << endl << type_table << endl << endl; /** * can either take one or zero parameter. If the number of * parameters is 0, then a new type variable is created for the * subexpression. Otherwise the one given as parameter is taken */ string alpha = (params.nb_params() == 0) ? type_table.new_variable(TypesHint()) : params.get_param(1); params.add_param(alpha); params.call(); try { expression.get_child().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", expression.get_location().first_line(), expression.get_location().first_column(), "invalid type in expression : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::DatastructureAccess& ds_access ) { //cout << "DatastructureAccess" << endl << type_table << endl << endl; // only array can be access with [ ] string alpha = params.get_param(1); // type of the array pair<string,string> array_type = type_table.new_array(); // alpha is the type of the array type_table.unify(alpha, array_type.second); // the idenfier should 'contain' an array params.add_param(array_type.first); params.call(); try { ds_access.get_id().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", ds_access.get_location().first_line(), ds_access.get_location().first_column(), "attempt to access array field on an element which is not an array : " + string(e.what())); } // the index expression should be an integer string beta = type_table.new_variable(); type_table.unify_int(beta); params.add_param(beta); params.call(); try { ds_access.get_index().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", ds_access.get_index().get_location().first_line(), ds_access.get_index().get_location().first_column(), "invalid type for array index : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::FuncCall& func_call ) { //cout << "FuncCall" << endl << type_table << endl << endl; string gamma = params.get_param(1); // type that should be returned by the function // add function matching the structure of the call size_t number_args = 0; if(func_call.contains_arglist()) number_args = func_call.get_arg_list().nb_args(); // build the vector of parameter names vector<string> type_param_name; generate_n(back_inserter(type_param_name), number_args, [this](){ return type_table.unique_varname(); }); // create the function type pair<string,string> func_type = type_table.new_function(type_param_name); // gamma should be the same type as the one returned by the function type_table.unify(gamma, func_type.second); // the function id or soy should have the same structure as the one defined here params.add_param(func_type.first); params.call(); try { func_call.get_function().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", func_call.get_function().get_location().first_line(), func_call.get_function().get_location().first_column(), "invalid function type : " + string(e.what())); } // each argument should have the correct type for(size_t i = 0; i < number_args; ++i) { params.add_param(type_param_name[i]); params.call(); try { func_call.get_arg_list().get_arg(i).accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", func_call.get_arg_list().get_arg(i).get_location().first_line(), func_call.get_arg_list().get_arg(i).get_location().first_column(), "invalid type for argument " + to_string(i + 1) + " : " + string(e.what())); } } params.ret(); } void TypeInferenceVisitor::visit( ast::ArgList& arg_list ) { // bypassed by FuncCall throw std::logic_error("This node should be bypassed"); } void TypeInferenceVisitor::visit( ast::Argument& arg ) { //cout << "Argument" << endl << type_table << endl << endl; string alpha = params.get_param(1); params.add_param(alpha); params.call(); arg.get_child().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::SoyFunc& soy ) { //cout << "SoyFunc" << endl << type_table << endl << endl; string delta = params.get_param(1); // function type // update the symbol table with soy function data pair<string, string> func_type_names = add_function_declaration_rule(soy.get_params(), soy.get_name(), soy.get_scope().get_scope_id()); // unify the function type with the inherited type type_table.unify(delta, func_type_names.first); // propagate return value to scope params.add_param(func_type_names.second); params.call(); soy.get_scope().accept(*this); // if the unification succeeds, either their was empty nory or no nori at all try { type_table.unify_void(func_type_names.second); } catch ( except::UnificationException& e ) { } params.ret(); } void TypeInferenceVisitor::visit( ast::Program& program ) { //cout << "Program" << endl << type_table << endl << endl; string alpha(""); params.add_param(alpha); // empty string means that nothing is expected as return type params.call(); program.get_scope().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::Scope& scope ) { //cout << "Scope" << endl << type_table << endl << endl; string alpha = params.get_param(1), beta; // type to pass to the children nodes size_t prev_scope = current_scope; current_scope = scope.get_scope_id(); // move to the new scope in the symbol tables variable_table.move_to_scope(current_scope); function_table.move_to_scope(current_scope); if(alpha.empty()) // empty string means that nothing is expected as return type { // the scope is not expected to return something beta = type_table.new_variable(TypesHint(VOID)); type_table.unify_void(beta); } else beta = alpha; // pass beta recursively for(auto child : scope.get_children()) { if(propagate_type_from_scope(*child)) params.add_param(beta); params.call(); child->accept(*this); } // go back to the previous scope variable_table.move_to_scope(prev_scope); function_table.move_to_scope(prev_scope); current_scope = prev_scope; //cout << "Go back to " << current_scope << endl; params.ret(); } void TypeInferenceVisitor::visit( ast::Statement& statement ) { //cout << "Statement" << endl << type_table << endl << endl; statement.get_statement().accept(*this); // forward the type to the actual statement } void TypeInferenceVisitor::visit( ast::Return& nori ) { //cout << "Return" << endl << type_table << endl << endl; string alpha = params.get_param(1); try { if(nori.empty_nori()) type_table.unify_void(alpha); else { // the nori is not empty, it cannot return void type_table.update_hints(alpha, TypesHint(INT | STRING | CHAR | BOOL | FUNCTION | FLOAT | ARRAY | LIST)); params.add_param(alpha); params.call(); nori.get_returned_expression().accept(*this); } } catch(except::UnificationException& e) { error_handler.add_sem_error("", nori.get_location().first_line(), nori.get_location().first_column(), "invalid return type : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Menu& menu ) { //cout << "Menu" << endl << type_table << endl << endl; string alpha = params.get_param(1), // type that should be returned by the element of the body beta = type_table.new_variable(TypesHint(CHAR | INT)); // type of the menu expression params.add_param(beta); params.call(); try { menu.get_expression().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", menu.get_location().first_line(), menu.get_location().first_column(), "invalid type for the menu expression : " + string(e.what())); } params.add_param(alpha); params.add_param(beta); params.call(); menu.get_body().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::MenuBody& body ) { //cout << "MenuBody" << endl << type_table << endl << endl; string alpha = params.get_param(1), // case body return type beta = params.get_param(2); // matcher type for(size_t i = 0; i < body.nb_cases(); i++) { params.add_param(alpha); params.add_param(beta); params.call(); body.get_nth_case(i).accept(*this); } params.add_param(alpha); params.call(); if(body.contains_default()) body.get_default_case().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::MenuDef& menudef ) { //cout << "MenuDef" << endl << type_table << endl << endl; string alpha = params.get_param(1); // the parameter that should be returned by case scope params.add_param(alpha); params.call(); menudef.get_scope().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::MenuCase& menucase ) { //cout << "MenuCase" << endl << type_table << endl << endl; string alpha = params.get_param(1), // the parameter that should be returned by case scope beta = params.get_param(2); // function of the case expression params.add_param(alpha); params.call(); menucase.get_scope().accept(*this); params.add_param(beta); params.call(); try { menucase.get_expression().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", menucase.get_location().first_line(), menucase.get_location().first_column(), "invalid type for the case matching expression : " + string(e.what())); } params.ret(); } void TypeInferenceVisitor::visit( ast::Roll& roll ) { //cout << "Roll" << endl << type_table << endl << endl; string alpha = params.get_param(1), // the parameter to pass to the roll body scope beta = type_table.new_variable(); // type of the roll expression // the expression must return stg of type bool type_table.unify_bool(beta); params.add_param(beta); params.call(); try { roll.get_expression().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", roll.get_location().first_line(), roll.get_location().first_column(), "invalid type for the roll guardian : " + string(e.what())); } params.add_param(alpha); params.call(); roll.get_scope().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::Foreach& foreach ) { //cout << "Foreach" << endl << type_table << endl << endl; string alpha = params.get_param(1); // the parameter to pass to the roll body scope string iter_var_type = type_table.unique_id_name(foreach.get_scope().get_scope_id(), foreach.get_identifier().id()); type_table.new_variable(iter_var_type); // the type of the iteration variable pair<string,string> list_type = type_table.new_list(); // the list expression // the variable must have the same type as the list elements type type_table.unify(list_type.second, iter_var_type); // the expression must be a list params.add_param(list_type.first); params.call(); try { foreach.get_expression().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", foreach.get_expression().get_location().first_line(), foreach.get_expression().get_location().first_column(), "invalid type for the iteratable : " + string(e.what())); } params.add_param(alpha); params.call(); foreach.get_scope().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::For& for_loop ) { //cout << "For" << endl << type_table << endl << endl; string alpha = params.get_param(1), // the parameter to pass to the for body scope beta = type_table.new_variable(); // the type of the expression // the guardian must be a boolean type_table.unify_bool(beta); params.add_param(beta); params.call(); try { for_loop.get_expression().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", for_loop.get_expression().get_location().first_line(), for_loop.get_expression().get_location().first_column(), "invalid type int the for loop guardian : " + string(e.what())); } params.add_param(alpha); params.call(); for_loop.get_scope().accept(*this); if(!for_loop.empty_initializer()) { params.call(); for_loop.get_initializer().accept(*this); } if(!for_loop.empty_update()) { params.call(); for_loop.get_update().accept(*this); } params.ret(); } void TypeInferenceVisitor::visit( ast::ForInitializer& initializer ) { //cout << "ForInitializer" << endl << type_table << endl << endl; params.call(); initializer.get_expression().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::ForUpdate& update ) { //cout << "ForUpdate" << endl << type_table << endl << endl; params.call(); update.get_expression().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::Conditional& conditional ) { //cout << "Conditional" << endl << type_table << endl << endl; string alpha = params.get_param(1); // to pass to the scopes // transmit to if params.add_param(alpha); params.call(); conditional.get_if().accept(*this); for(size_t i = 0; i < conditional.count_elseif(); ++i) { params.add_param(alpha); params.call(); conditional.get_nth_elseif(i).accept(*this); } // transmit to else if(conditional.contains_else()) { params.add_param(alpha); params.call(); conditional.get_else().accept(*this); } params.ret(); } void TypeInferenceVisitor::visit( ast::If& if_node ) { //cout << "If" << endl << type_table << endl << endl; string alpha = params.get_param(1), beta = type_table.new_variable(); // the expression must be a boolean type_table.unify_bool(beta); params.add_param(beta); params.call(); try { if_node.get_expression().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", if_node.get_expression().get_location().first_line(), if_node.get_expression().get_location().first_column(), "invalid type for condition : " + string(e.what())); } params.add_param(alpha); params.call(); if_node.get_scope().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::Elseif& elseif ) { //cout << "Elseif" << endl << type_table << endl << endl; string alpha = params.get_param(1), beta = type_table.new_variable(); // the expression must be a boolean type_table.unify_bool(beta); params.add_param(beta); params.call(); try { elseif.get_expression().accept(*this); } catch(except::UnificationException& e) { error_handler.add_sem_error("", elseif.get_expression().get_location().first_line(), elseif.get_expression().get_location().first_column(), "invalid type for condition : " + string(e.what())); } params.add_param(alpha); params.call(); elseif.get_scope().accept(*this); params.ret(); } void TypeInferenceVisitor::visit( ast::Else& else_node ) { //cout << "Else" << endl << type_table << endl << endl; string alpha = params.get_param(1); params.add_param(alpha); params.call(); else_node.get_scope().accept(*this); params.ret(); } pair<string, string> TypeInferenceVisitor::add_function_declaration_rule(const ast::ParamList& param_list, const string& func_name, size_t scope_id) { vector<string> param_names, // param names without scope ids param_type_names; // params names with scope ids param_list.get_parameters_name(param_names); // get name with scope ids auto mk_unique_id_name = [this, scope_id](const std::string& name) { return type_table.unique_id_name(scope_id, name); }; transform(param_names.begin(), param_names.end(), back_inserter(param_type_names), mk_unique_id_name); // unify possible hints with param type variables vector<ShallowType> param_type_hints; param_list.get_parameters_type(param_type_hints); // create function string func_type_name = type_table.unique_id_name(current_scope, func_name); /** * A function identifier could already be in the table * It happens in case of cross-recursive function * In this case, a variable is created mapping the function type, then this variable is * unified with the already loaded function variable */ if(type_table.contains(func_type_name)) { pair<string, string> func_data = type_table.new_function(param_type_names, type_table.unique_varname(), param_type_hints); type_table.unify(func_data.first, func_type_name); func_data.first = func_type_name; return func_data; } else return type_table.new_function(param_type_names, func_type_name, param_type_hints); } pair<string, string> TypeInferenceVisitor::add_function_declaration_rule(const string& func_name, size_t scope_id) { vector<string> param_type_names; // params names with scope ids // create function string func_type_name = type_table.unique_id_name(current_scope, func_name); return type_table.new_function(param_type_names, func_type_name); } bool TypeInferenceVisitor::propagate_type_from_scope(const ast::ASTNode& node) const { const ast::Statement* statement = dynamic_cast<const ast::Statement*>(&node); return statement; }
true
62c6fe359ae1952a0da1136369b5ac76bb30a696
C++
randeng/GameEngineFromScratch
/Framework/GeomMath/geommath.h
UTF-8
12,132
3.125
3
[ "MIT" ]
permissive
#pragma once #include <math.h> #include "include/CrossProduct.h" #ifndef PI #define PI 3.14159265358979323846f #endif #ifndef TWO_PI #define TWO_PI 3.14159265358979323846f * 2.0f #endif namespace My { template< typename T, int ... Indexes> class swizzle { float v[sizeof...(Indexes)]; public: T& operator=(const T& rhs) { int indexes[] = { Indexes... }; for (int i = 0; i < sizeof...(Indexes); i++) { v[indexes[i]] = rhs[i]; } return *(T*)this; } operator T () const { return T( v[Indexes]... ); } }; typedef struct Vector2Type { union { float data[2]; struct { float x, y; }; struct { float r, g; }; struct { float u, v; }; swizzle<Vector2Type, 0, 1> xy; swizzle<Vector2Type, 1, 0> yx; }; Vector2Type() {}; Vector2Type(float _v) : x(_v), y(_v) {}; Vector2Type(float _x, float _y) : x(_x), y(_y) {}; } Vector2Type; typedef struct Vector3Type { union { float data[3]; struct { float x, y, z; }; struct { float r, g, b; }; swizzle<Vector2Type, 0, 1> xy; swizzle<Vector2Type, 1, 0> yx; swizzle<Vector2Type, 0, 2> xz; swizzle<Vector2Type, 2, 0> zx; swizzle<Vector2Type, 1, 2> yz; swizzle<Vector2Type, 2, 1> zy; swizzle<Vector3Type, 0, 1, 2> xyz; swizzle<Vector3Type, 1, 0, 2> yxz; swizzle<Vector3Type, 0, 2, 1> xzy; swizzle<Vector3Type, 2, 0, 1> zxy; swizzle<Vector3Type, 1, 2, 0> yzx; swizzle<Vector3Type, 2, 1, 0> zyx; }; Vector3Type() {}; Vector3Type(float _v) : x(_v), y(_v), z(_v) {}; Vector3Type(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {}; } Vector3Type; typedef struct Vector4Type { union { float data[4]; struct { float x, y, z, w; }; struct { float r, g, b, a; }; Vector3Type xyz; swizzle<Vector3Type, 0, 2, 1> xzy; swizzle<Vector3Type, 1, 0, 2> yxz; swizzle<Vector3Type, 1, 2, 0> yzx; swizzle<Vector3Type, 2, 0, 1> zxy; swizzle<Vector3Type, 2, 1, 0> zyx; }; Vector4Type() {}; Vector4Type(float _v) : x(_v), y(_v), z(_v), w(_v) {}; Vector4Type(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) {}; operator Vector3Type() { return Vector3Type(x, y, z); }; } Vector4Type; typedef struct Matrix3X3 { union { float data[9]; struct { Vector3Type row[3]; }; }; float& operator[](int index) { return data[index]; } float operator[](int index) const { return data[index]; } } Matrix3X3; typedef struct Matrix4X4 { union { float data[16]; struct { Vector4Type row[4]; }; }; float& operator[](int index) { return data[index]; } float operator[](int index) const { return data[index]; } } Matrix4X4; void MatrixRotationYawPitchRoll(Matrix4X4& matrix, const float yaw, const float pitch, const float roll) { float cYaw, cPitch, cRoll, sYaw, sPitch, sRoll; // Get the cosine and sin of the yaw, pitch, and roll. cYaw = cosf(yaw); cPitch = cosf(pitch); cRoll = cosf(roll); sYaw = sinf(yaw); sPitch = sinf(pitch); sRoll = sinf(roll); // Calculate the yaw, pitch, roll rotation matrix. matrix[0] = (cRoll * cYaw) + (sRoll * sPitch * sYaw); matrix[1] = (sRoll * cPitch); matrix[2] = (cRoll * -sYaw) + (sRoll * sPitch * cYaw); matrix[3] = (-sRoll * cYaw) + (cRoll * sPitch * sYaw); matrix[4] = (cRoll * cPitch); matrix[5] = (sRoll * sYaw) + (cRoll * sPitch * cYaw); matrix[6] = (cPitch * sYaw); matrix[7] = -sPitch; matrix[8] = (cPitch * cYaw); return; } void TransformCoord(Vector3Type& vector, const Matrix4X4& matrix) { float x, y, z; // Transform the vector by the 3x3 matrix. x = (vector.x * matrix[0]) + (vector.y * matrix[3]) + (vector.z * matrix[6]); y = (vector.x * matrix[1]) + (vector.y * matrix[4]) + (vector.z * matrix[7]); z = (vector.x * matrix[2]) + (vector.y * matrix[5]) + (vector.z * matrix[8]); // Store the result in the reference. vector.x = x; vector.y = y; vector.z = z; return; } void BuildViewMatrix(const Vector3Type position, const Vector3Type lookAt, const Vector3Type up, Matrix4X4& result) { Vector3Type zAxis, xAxis, yAxis; float length, result1, result2, result3; // zAxis = normal(lookAt - position) zAxis.x = lookAt.x - position.x; zAxis.y = lookAt.y - position.y; zAxis.z = lookAt.z - position.z; length = sqrt((zAxis.x * zAxis.x) + (zAxis.y * zAxis.y) + (zAxis.z * zAxis.z)); zAxis.x = zAxis.x / length; zAxis.y = zAxis.y / length; zAxis.z = zAxis.z / length; // xAxis = normal(cross(up, zAxis)) xAxis.x = (up.y * zAxis.z) - (up.z * zAxis.y); xAxis.y = (up.z * zAxis.x) - (up.x * zAxis.z); xAxis.z = (up.x * zAxis.y) - (up.y * zAxis.x); length = sqrt((xAxis.x * xAxis.x) + (xAxis.y * xAxis.y) + (xAxis.z * xAxis.z)); xAxis.x = xAxis.x / length; xAxis.y = xAxis.y / length; xAxis.z = xAxis.z / length; // yAxis = cross(zAxis, xAxis) yAxis.x = (zAxis.y * xAxis.z) - (zAxis.z * xAxis.y); yAxis.y = (zAxis.z * xAxis.x) - (zAxis.x * xAxis.z); yAxis.z = (zAxis.x * xAxis.y) - (zAxis.y * xAxis.x); // -dot(xAxis, position) result1 = ((xAxis.x * position.x) + (xAxis.y * position.y) + (xAxis.z * position.z)) * -1.0f; // -dot(yaxis, eye) result2 = ((yAxis.x * position.x) + (yAxis.y * position.y) + (yAxis.z * position.z)) * -1.0f; // -dot(zaxis, eye) result3 = ((zAxis.x * position.x) + (zAxis.y * position.y) + (zAxis.z * position.z)) * -1.0f; // Set the computed values in the view matrix. result[0] = xAxis.x; result[1] = yAxis.x; result[2] = zAxis.x; result[3] = 0.0f; result[4] = xAxis.y; result[5] = yAxis.y; result[6] = zAxis.y; result[7] = 0.0f; result[8] = xAxis.z; result[9] = yAxis.z; result[10] = zAxis.z; result[11] = 0.0f; result[12] = result1; result[13] = result2; result[14] = result3; result[15] = 1.0f; } void BuildIdentityMatrix(Matrix4X4& matrix) { matrix[0] = 1.0f; matrix[1] = 0.0f; matrix[2] = 0.0f; matrix[3] = 0.0f; matrix[4] = 0.0f; matrix[5] = 1.0f; matrix[6] = 0.0f; matrix[7] = 0.0f; matrix[8] = 0.0f; matrix[9] = 0.0f; matrix[10] = 1.0f; matrix[11] = 0.0f; matrix[12] = 0.0f; matrix[13] = 0.0f; matrix[14] = 0.0f; matrix[15] = 1.0f; return; } void BuildPerspectiveFovLHMatrix(Matrix4X4& matrix, const float fieldOfView, const float screenAspect, const float screenNear, const float screenDepth) { matrix[0] = 1.0f / (screenAspect * tan(fieldOfView * 0.5f)); matrix[1] = 0.0f; matrix[2] = 0.0f; matrix[3] = 0.0f; matrix[4] = 0.0f; matrix[5] = 1.0f / tan(fieldOfView * 0.5f); matrix[6] = 0.0f; matrix[7] = 0.0f; matrix[8] = 0.0f; matrix[9] = 0.0f; matrix[10] = screenDepth / (screenDepth - screenNear); matrix[11] = 1.0f; matrix[12] = 0.0f; matrix[13] = 0.0f; matrix[14] = (-screenNear * screenDepth) / (screenDepth - screenNear); matrix[15] = 0.0f; return; } void MatrixRotationY(Matrix4X4& matrix, const float angle) { matrix[0] = cosf(angle); matrix[1] = 0.0f; matrix[2] = -sinf(angle); matrix[3] = 0.0f; matrix[4] = 0.0f; matrix[5] = 1.0f; matrix[6] = 0.0f; matrix[7] = 0.0f; matrix[8] = sinf(angle); matrix[9] = 0.0f; matrix[10] = cosf(angle); matrix[11] = 0.0f; matrix[12] = 0.0f; matrix[13] = 0.0f; matrix[14] = 0.0f; matrix[15] = 1.0f; return; } void MatrixTranslation(Matrix4X4& matrix, const float x, const float y, const float z) { matrix[0] = 1.0f; matrix[1] = 0.0f; matrix[2] = 0.0f; matrix[3] = 0.0f; matrix[4] = 0.0f; matrix[5] = 1.0f; matrix[6] = 0.0f; matrix[7] = 0.0f; matrix[8] = 0.0f; matrix[9] = 0.0f; matrix[10] = 1.0f; matrix[11] = 0.0f; matrix[12] = x; matrix[13] = y; matrix[14] = z; matrix[15] = 1.0f; return; } void MatrixRotationZ(Matrix4X4& matrix, const float angle) { matrix[0] = cosf(angle); matrix[1] = -sinf(angle); matrix[2] = 0.0f; matrix[3] = 0.0f; matrix[4] = sinf(angle); matrix[5] = cosf(angle); matrix[6] = 0.0f; matrix[7] = 0.0f; matrix[8] = 0.0f; matrix[9] = 0.0f; matrix[10] = 1.0f; matrix[11] = 0.0f; matrix[12] = 0.0f; matrix[13] = 0.0f; matrix[14] = 0.0f; matrix[15] = 1.0f; return; } void MatrixMultiply(Matrix4X4& result, const Matrix4X4& matrix1, const Matrix4X4& matrix2) { result[0] = (matrix1[0] * matrix2[0]) + (matrix1[1] * matrix2[4]) + (matrix1[2] * matrix2[8]) + (matrix1[3] * matrix2[12]); result[1] = (matrix1[0] * matrix2[1]) + (matrix1[1] * matrix2[5]) + (matrix1[2] * matrix2[9]) + (matrix1[3] * matrix2[13]); result[2] = (matrix1[0] * matrix2[2]) + (matrix1[1] * matrix2[6]) + (matrix1[2] * matrix2[10]) + (matrix1[3] * matrix2[14]); result[3] = (matrix1[0] * matrix2[3]) + (matrix1[1] * matrix2[7]) + (matrix1[2] * matrix2[11]) + (matrix1[3] * matrix2[15]); result[4] = (matrix1[4] * matrix2[0]) + (matrix1[5] * matrix2[4]) + (matrix1[6] * matrix2[8]) + (matrix1[7] * matrix2[12]); result[5] = (matrix1[4] * matrix2[1]) + (matrix1[5] * matrix2[5]) + (matrix1[6] * matrix2[9]) + (matrix1[7] * matrix2[13]); result[6] = (matrix1[4] * matrix2[2]) + (matrix1[5] * matrix2[6]) + (matrix1[6] * matrix2[10]) + (matrix1[7] * matrix2[14]); result[7] = (matrix1[4] * matrix2[3]) + (matrix1[5] * matrix2[7]) + (matrix1[6] * matrix2[11]) + (matrix1[7] * matrix2[15]); result[8] = (matrix1[8] * matrix2[0]) + (matrix1[9] * matrix2[4]) + (matrix1[10] * matrix2[8]) + (matrix1[11] * matrix2[12]); result[9] = (matrix1[8] * matrix2[1]) + (matrix1[9] * matrix2[5]) + (matrix1[10] * matrix2[9]) + (matrix1[11] * matrix2[13]); result[10] = (matrix1[8] * matrix2[2]) + (matrix1[9] * matrix2[6]) + (matrix1[10] * matrix2[10]) + (matrix1[11] * matrix2[14]); result[11] = (matrix1[8] * matrix2[3]) + (matrix1[9] * matrix2[7]) + (matrix1[10] * matrix2[11]) + (matrix1[11] * matrix2[15]); result[12] = (matrix1[12] * matrix2[0]) + (matrix1[13] * matrix2[4]) + (matrix1[14] * matrix2[8]) + (matrix1[15] * matrix2[12]); result[13] = (matrix1[12] * matrix2[1]) + (matrix1[13] * matrix2[5]) + (matrix1[14] * matrix2[9]) + (matrix1[15] * matrix2[13]); result[14] = (matrix1[12] * matrix2[2]) + (matrix1[13] * matrix2[6]) + (matrix1[14] * matrix2[10]) + (matrix1[15] * matrix2[14]); result[15] = (matrix1[12] * matrix2[3]) + (matrix1[13] * matrix2[7]) + (matrix1[14] * matrix2[11]) + (matrix1[15] * matrix2[15]); return; } void CrossProduct(Matrix3X3& result, const Matrix3X3 matrix1, const Matrix3X3 matrix2) { ispc::CrossProduct(matrix1.data, matrix2.data, result.data); } }
true
69b0c5ecbed8531dc57f3dd76f453fba09578621
C++
tal8374/Graphs_Project
/Edge.h
UTF-8
730
2.703125
3
[]
no_license
#pragma once #include "Vertex.h" #include "AutoVertex.h" #include <string> #include <map> #include "Exception.h" #include "InvalidInputException.h" #include "OutOfMemoryException.h" #include "UndefinedVerticeException.h" #include <cstdlib> using namespace std; class Edge { protected: string m_Name; Vertex *m_From, *m_To; void setVertexFromMap(string vertexFrom, string vertexTo, map<string, Vertex*>& allVertexs); int m_Memory_Size; public: Edge(); Edge(string name, Vertex& from, Vertex& to); virtual ~Edge(); string getName()const; Vertex& getFromVertex()const; Vertex& getToVertex()const; virtual string get_Edge_Data() { return ""; }; virtual int get_Memory_Size() ; virtual double getWieght()const=0; };
true
0f644a555dab3203a89ea7e9252a867546bb09f9
C++
jmmrrsn/silent-phone-android
/silentphone2/support/silentphone/os/CTSockNN.h
UTF-8
2,169
2.53125
3
[]
no_license
//VoipPhone //Created by Janis Narbuts //Copyright (c) 2004-2012 Tivi LTD, www.tiviphone.com. All rights reserved. #ifndef _C_TIVI_SOCK #define _C_TIVI_SOCK class ADDR{ public: ADDR(unsigned int ip=0,unsigned int port=0):ip(ip) { setPort(port); } ADDR(char *p) { clear(); *this=(p); } inline void clear() { ip=0;port=0;portNF=0; } inline void setPort(unsigned int uiPort); inline void setPortNF(unsigned int uiPortNF); void operator =(char *p); char *toStr(char *ipStr, int iShowPort=1); inline unsigned int getPortNF() { if(portNF) return portNF; if(port) { setPort(port); return portNF; } return 0; } inline unsigned int getPort() { if(port) return port; if(portNF) { setPort(portNF); return port; } return 0; } inline int operator ==(ADDR &addr) { if(ip!=addr.ip)return 0; if(port) return (port==addr.port); return portNF==addr.portNF; } inline int operator !=(ADDR &addr) { if(ip!=addr.ip)return 1; if(port) return port!=addr.port; return portNF!=addr.portNF; } inline void operator =(ADDR &addr) { ip=addr.ip ; port=addr.port; if(portNF) portNF=addr.portNF; else { portNF=port; SWAP_SHORT(portNF); } } unsigned int ip; private: unsigned int port; unsigned int portNF; }; class CTSock{ public: #define MAX_SOCK_COUNT 4 typedef struct{ SOCKET sock; int iThId; }SOCK; CTSock(); ~CTSock(); int createSock(ADDR *addrToBind,int toAny) { if(createSock()) return Bind(addrToBind,toAny); return -1; } int createSock(); int reconect(); int closeSocket(); int sendTo(char *buf, int iLen, ADDR *address); int recvFrom(char *buf, int iLen, ADDR *addr); int Bind(ADDR *addrToBind, int toAny); int sock; ADDR addr; int iIsBinded; private: int sockHeelperInUse; int iNeedClose; SOCK sockHeelper[MAX_SOCK_COUNT]; int getSocket(int iThId); }; #endif //_C_TIVI_SOCK
true
5f8e79d5da300c2f068db37c6667a791a9fef5e5
C++
kuljotbiring/C-Early-Objects-9th-Edition
/chapter5/5_04.cpp
UTF-8
750
3.796875
4
[ "MIT" ]
permissive
/********************************************************************* ** Author: Kuljot Biring ** ** Date: July 06, 2018 ** ** Write a program that uses a loop to display a table of ** the Celsius temperatures from 0 to 30 and their Fahrenheit ** equivalents. *********************************************************************/ #include <iostream> using std::cout; using std::cin; using std::endl; int main() { double fahrenheit; cout << "\nCelsius Fahrenheit" << endl; cout << "-----------------------" << endl; for(double celsius = 0.0; celsius <= 30.0; celsius++) { fahrenheit = (static_cast<double>(9) / 5) * celsius + 32; cout << celsius << " " << fahrenheit << endl; } return 0; }
true
d1a23514dff153062262c6c3adbdbfdfa76ffea1
C++
aditya1k2/CPP-SEM-2-KIIT
/lab/1706291/swappoint.cpp
UTF-8
211
2.671875
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; int main() { int a,b,c,*p=&a,*q=&b,*r=&c; cout<<"Enter a,b\n"; cin>>*p; cin>>*q; *r=*p; *p=*q; *q=*r; cout<<"After Swapping\n"<<"a="<<*p<<"b="<<*q; return 0; }
true
09dac87cf3b35965857da715e88f8d226f323ad7
C++
haoyuanliu/LeetCode
/13.RomanToInteger.cpp
UTF-8
736
3.328125
3
[]
no_license
#include <iostream> #include <string> #include <map> using namespace std; class Solution { public: int romanToInt(string s) { map<char, int> m; char ch[] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; int num[] = {1, 5, 10, 50, 100, 500, 1000}; for(int i = 0; i < 7; ++i) { m.insert(make_pair(ch[i], num[i])); } int res = 0; for(int i = 0; i < s.length(); ++i) { if(m[s[i]] < m[s[i+1]]) res -= m[s[i]]; else res += m[s[i]]; } return res; } }; int main() { Solution res; string str; while(cin >> str) cout << res.romanToInt(str) << endl; return 0; }
true
1d16b2d1a13a5b552cfd05fe7526bb61c7d906f9
C++
shubhamraja7d/WebDevelopmentKit
/WebDevelopmentKit/ClassUser.h
UTF-8
574
2.796875
3
[]
no_license
#include<iostream> #include<string> using namespace std; class UserDet { // static int Counter; // int ctr; public: string name; string u_id; string password; string role; UserDet() { } UserDet(string name,string u_id,string password,string role) { // this->ctr=ctr; this->name=name; this->u_id=u_id; this->password=password; this->role=role; } /* static int getcounter() { Counter++; return Counter; } */ string getUserId() { return this->u_id; } string getPassword() { return this->password; } }; //int UserDet :: Counter = 0;
true
1e546a3c49151fe1631812b025613fd3169ba2b3
C++
Ronnie-Git/Starting-point
/6.relearn_algorithm/图论/代码/最短路/P2910_floyd.cpp
UTF-8
761
2.8125
3
[]
no_license
#include<iostream> using namespace std; #define maxn 1000 #define INF 0x3f3f3f3f int g[maxn][maxn]; int arr[10005]; void floyd(int n) { for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { g[i][j] = min(g[i][j], g[i][k] + g[k][j]); } } } return ; } int main() { int n, m; cin >> n >> m; for (int i = 0; i < m; i++) cin >> arr[i]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> g[i][j]; } } floyd(n); int sum = 0; for (int i = 1; i < m; i++) { sum += g[arr[i - 1]][arr[i]]; } cout << sum << endl; return 0; }
true
d0f7210f4a6905abe0013491b211900cc99613ff
C++
ishankhanna28/Data-Structures-and-Algorithms
/Vectors/vector_class_CAB.cpp
UTF-8
781
3.59375
4
[]
no_license
#include<iostream> #include<utility> #include<vector> #include<algorithm> #include<string> using namespace std; class CAB { public: string name; int x,y; CAB(string name, int x, int y) { this->name = name; this->x = x; this->y= y; } int dist() { return x*x + y*y; } }; bool compare(CAB a, CAB b) { if(a.dist() == b.dist()) return b.name > a.name; else return b.dist() > a.dist(); } int main() { int n, i, x, y; vector<CAB> v; cin>>n; v.reserve(n); string name; for(i=0; i<n; i++) { cin>>name>>x>>y; CAB C(name,x,y); v.push_back(C); } sort(v.begin(), v.end(), compare); for(auto c:v) cout<<c.name<<" at location coordinates ("<<c.x<<","<<c.y<<")"<<endl; return 0; }
true
c4137d3594e257971fc495d49eda730553f361ed
C++
catbro666/prac1b
/Cipher.cpp
UTF-8
8,598
2.640625
3
[]
no_license
#include "Cipher.h" int CCipher::Encrypt(const char* inFile, const char* outFile, const unsigned char* aKey, const unsigned char* iVec, const char* format, ENGINE *impl) { int n = 0; unsigned char* transData = NULL; unsigned char inbuf[BufferSize]; unsigned char outbuf[BufferSize + MaxBlockSize + 2]; unsigned char offsetData[2]; int offset = 0; int readlen = 0; int writelen = 0; int cryptlen = 0; int formatedlen = 0; MODE mode = Binary; if(!strcmp(format, "binary")) mode = Binary; else if(!strcmp(format, "hex")) mode = Hex; else if(!strcmp(format, "base64")) mode = Base64; else { sprintf(m_szErr, "CCipher::Encrypt: Unknown format (%s)!\n", format); Cleanup(); throw m_szErr; } unsigned char* keybin = NULL; unsigned char* ivbin = NULL; if(aKey) { int keylen = strlen((const char*)aKey); keybin = Hex2Byte(aKey, &keylen, 0); } if(iVec) { int ivlen = strlen((const char*)iVec); ivbin = Hex2Byte(iVec, &ivlen, 0); } /* * 初始化算法:设置算法密钥,IV,以及加解密标志位dir * 如果使用Engine,此时会调用其实现的EVP_CIPHER->init回调函数 */ if (!EVP_CipherInit_ex(m_ctx, m_cipher, impl, keybin, ivbin, 1)) //最后一个参数,1表示加密,0表示解密 { n = ERR_get_error(); char errmsg[1024]; ERR_error_string(n, errmsg); sprintf(m_szErr, "CCipher::Encrypt: EVP_CipherInit_ex failed: \nopenssl return %d, %s\n", n, errmsg); Cleanup(); throw m_szErr; } if (!(m_fpin = fopen(inFile, "rb"))) { char errmsg[1024]; char* msg = strerror_r(errno, errmsg, 1024); sprintf(m_szErr, "CCipher::Encrypt: file(%s) open failed!\nerrno=%d, ErrMess:%s\n", inFile, errno, msg); Cleanup(); throw m_szErr; } if (!(m_fpout = fopen(outFile, "wt"))) { char errmsg[1024]; char* msg = strerror_r(errno, errmsg, 1024); sprintf(m_szErr, "CCipher::Encrypt: file(%s) open failed!\nerrno=%d, ErrMess:%s\n", outFile, errno, msg); Cleanup(); throw m_szErr; } while(readlen = fread(inbuf, 1, BufferSize, m_fpin)) { /* * 对数据进行加/解密(如果使用Engine,此时会调用其实现的EVP_CIPHER->do_cipher回调函数) * 对于连续数据流,CipherUpdate一般会被调用多次 */ if (!EVP_CipherUpdate(m_ctx, outbuf + offset, &cryptlen, inbuf, readlen)) { n = ERR_get_error(); char errmsg[1024]; ERR_error_string(n, errmsg); sprintf(m_szErr, "CCipher::Encrypt: EVP_CipherUpdate failed!\nopenssl return %d, %s\n", n, errmsg); Cleanup(); throw m_szErr; } if(mode) { transData = TransCode(outbuf, &cryptlen, mode,1, offsetData, &offset); formatedlen = strlen((const char*)transData); } else { transData = outbuf; formatedlen = cryptlen; } if (!(writelen = fwrite(transData, 1, formatedlen, m_fpout))) { char errmsg[1024]; char* msg = strerror_r(errno, errmsg, 1024); sprintf(m_szErr, "CCipher::Encrypt: file(%s) write failed!\nerrno=%d, ErrMess:%s\n", outFile, errno, msg); if(mode) free(transData); transData = NULL; Cleanup(); throw m_szErr; } if(mode) free(transData); transData = NULL; } if ( feof(m_fpin) ) { /** *输出最后一块数据(块加密时,数据将被padding到block长度的整数倍,因此会产生额外的最后一段数据) *注意:如果使用Engine,此时会触发其实现的EVP_CIPHER->do_cipher,而不是EVP_CIPHER->cleanup *这点上与EVP_DigestFinal/EVP_SignFinal/EVP_VerifyFinal是完全不同的 */ if (!EVP_CipherFinal(m_ctx, outbuf + offset, &cryptlen)) { n = ERR_get_error(); char errmsg[1024]; ERR_error_string( n, errmsg ); sprintf( m_szErr, "CCipher::Encrypt EVP_CipherFinalfailed: \nopenssl return %d, %s\n", n, errmsg ); Cleanup(); throw m_szErr; } if(mode) { transData = TransCode(outbuf, &cryptlen, mode,1, NULL, &offset); formatedlen = strlen((const char*)transData); } else { transData = outbuf; formatedlen = cryptlen; } if(formatedlen != 0) { if (!(writelen = fwrite(transData, 1, formatedlen, m_fpout))) { char errmsg[1024]; char* msg = strerror_r(errno, errmsg, 1024); sprintf(m_szErr, "CCipher::Encrypt: file(%s) write failed!\nerrno=%d, ErrMess:%s\n", outFile, errno, msg); if(mode) free(transData); transData = NULL; Cleanup(); throw m_szErr; } if(mode) free(transData); transData = NULL; } } else { char errmsg[1024]; char* msg = strerror_r(errno, errmsg, 1024); sprintf(m_szErr, "CCipher::Encrypt: file(%s) read failed!\nerrno=%d, ErrMess:%s\n", outFile, errno, msg); Cleanup(); throw m_szErr; } return 0; } int CCipher::Decrypt(const char* inFile, const char* outFile, const unsigned char* aKey, const unsigned char* iVec, const char* format, ENGINE *impl) { return 0; } CCipher::CCipher(const char* ciphername): m_fpin(NULL), m_fpout(NULL) { OpenSSL_add_all_algorithms(); m_ctx = EVP_CIPHER_CTX_new(); if(!m_ctx) { sprintf(m_szErr, "CCipher construct fail: EVP_CIPHER_CTX_new failed\n",ciphername); Cleanup(); throw m_szErr; } m_cipher = EVP_get_cipherbyname(ciphername); if (NULL == m_cipher) { sprintf(m_szErr, "CCipher construct fail: Cipher for %s is NULL\n",ciphername); Cleanup(); throw m_szErr; } } CCipher::~CCipher() { Cleanup(); } void CCipher::Reset(const char* ciphername) { CCipher tmp(ciphername); Swap(tmp); } void CCipher::Swap(CCipher& other) { using std::swap; swap(m_cipher, other.m_cipher); swap(m_ctx, other.m_ctx);//passing temporary object, try bind to a non-const lval } void CCipher::Cleanup() { if(m_fpin) { fclose(m_fpin); m_fpin = NULL; } if(m_fpout) { fclose(m_fpout); m_fpout = NULL; } EVP_CIPHER_CTX_cleanup(m_ctx); EVP_CIPHER_CTX_free(m_ctx); EVP_cleanup(); } //if (offsetData == NULL), then it's the last round unsigned char* CCipher::TransCode(unsigned char* input, int* plen, MODE mode, bool isEncode, unsigned char* offsetData, int* offset) { unsigned char* transData = NULL; if(!input) { sprintf(m_szErr, "CCipher::TransCode: input null pointer!"); Cleanup(); throw m_szErr; } if(isEncode) { if(Hex == mode) { if (!(transData = Byte2Hex(input, *plen, 0))) { sprintf(m_szErr, "CCipher::TransCode: unsigned char2Hex transform failed!"); Cleanup(); throw m_szErr; } } else if(Base64 == mode) { *plen += *offset; if(offsetData) { *offset = *plen % 3; if(*offset != 0) { memcpy(offsetData, input + *plen - *offset, *offset); *plen -= *offset; } } if (!(transData = Base64Encode(input,*plen , 0))) { sprintf(m_szErr, "CCipher::TransCode: Base64Encode transform failed!"); Cleanup(); throw m_szErr; } if(offsetData && *offset != 0) { memcpy(input, offsetData, *offset); } } else { sprintf(m_szErr, "CCipher::TransCode: Only Hex and Base64 are supported so far, sorry!"); Cleanup(); throw m_szErr; } } //Decode else { if(Hex == mode) { if (!(transData = Hex2Byte(input, plen, 0))) { sprintf(m_szErr, "CCipher::TransCode: Hex2unsigned char transform failed!"); Cleanup(); throw m_szErr; } } else if(Base64 == mode) { *plen += *offset; if(offsetData) { *offset = *plen % 4; if(*offset != 0) { memcpy(offsetData, input + *plen - *offset, *offset); *plen -= *offset; } } if (!(transData = Base64Decode(input, plen , 0))) { sprintf(m_szErr, "CCipher::TransCode: Base64Decode transform failed!"); Cleanup(); throw m_szErr; } if(offsetData && *offset != 0) { memcpy(input, offsetData, *offset); } } else { sprintf(m_szErr, "CCipher::TransCode: Only Hex and Base64 are supported so far, sorry!"); Cleanup(); throw m_szErr; } } return transData; } namespace std { template<> void swap<CCipher> (CCipher& a, CCipher& b) { a.Swap(b); } }
true
2adad271b2d92e35944b4de335362350ef2f1a1e
C++
samar1tan/project-map
/test/test_map.cpp
UTF-8
1,594
3.609375
4
[ "MIT" ]
permissive
#include "../lib/simple_map.h" #include <iostream> using namespace std; // typedef for SimpleMap testing typedef SimpleMap<int, char> Map; typedef Entry<int, char> Elem; int main() { Map* test = new Map; test->insert(Elem(1, 'a')); test->insert(Elem(2, 'b')); test->insert(Elem(3, 'c')); test->insert(Elem(4, 'd')); test->insert(Elem(5, 'e')); test->insert(Elem(6, 'f')); test->insert(Elem(7, 'g')); test->insert(Elem(8, 'h')); test->insert(Elem(9, 'i')); test->insert(Elem(10, 'j')); for (Map::iterator i = test->begin(); i != test->end(); i++) { cout << "(" << i->key() << ", " << i->value() << ") "; } cout << endl << endl; cout << "Size: " << test->size() << endl; cout << "Is empty? " << test->empty() << endl; cout << "Max Size: " << test->max_size() << endl << endl; cout << "The value with key 6 is '" << (*test)[6] << "'" << endl; cout << "The value with min key is '" << test->min()->value() << "'" << endl << endl; test->erase(6); test->erase(test->min()); cout << "key-6 and key-min deleted" << endl << endl; if (!(test->find(6).data())) { cout << "Cannot find non-existed key-6" << endl << endl; } cout << "The amount of key-7: " << test->count(7) << endl; cout << "The value with max key is '" << test->max()->value() << "'" << endl << endl; for (Map::iterator i = test->begin(); i != test->end(); i++) { cout << "(" << i->key() << ", " << i->value() << ") "; } cout << endl; test->clear(); delete test; return 0; }
true
ba6bc58e41f0e14dca21569cf9adf7acdf6b2999
C++
s3ponia/fractional
/include/overflowchecker.hpp
UTF-8
10,631
3.203125
3
[]
no_license
// // Created by Linux Oid on 07.05.2020. // #ifndef FRACTIONNUMBER_OVERFLOWCHECKER_HPP #define FRACTIONNUMBER_OVERFLOWCHECKER_HPP #include <functional> #include <exception> #include <string> #define DECLARATION_TEMPLATE_PARAMS \ class _EqualOperator,\ class _NoEqualOperator,\ class _GreaterOperator,\ class _GreaterEqualOperator,\ class _LessOperator,\ class _LessEqualOperator,\ class _PlusOperator,\ class _MinusOperator,\ class _MultiplyOperator,\ class _DivideOperator,\ class _NegateOperator,\ class _ModulusOperator #define DECLARATION_DEFAULT_TEMPLATE_PARAMS \ class _EqualOperator = std::equal_to<_NaturalType>,\ class _NoEqualOperator = std::not_equal_to<_NaturalType>,\ class _GreaterOperator = std::greater<_NaturalType>,\ class _GreaterEqualOperator = std::greater_equal<_NaturalType>,\ class _LessOperator = std::less<_NaturalType>,\ class _LessEqualOperator = std::less_equal<_NaturalType>,\ class _PlusOperator = std::plus<_NaturalType>,\ class _MinusOperator = std::minus<_NaturalType>,\ class _MultiplyOperator = std::multiplies<_NaturalType>,\ class _DivideOperator = std::divides<_NaturalType>,\ class _NegateOperator = std::negate<_NaturalType>,\ class _ModulusOperator = std::modulus<_NaturalType> #define TEMPLATE_PARAMS \ _EqualOperator,\ _NoEqualOperator,\ _GreaterOperator,\ _GreaterEqualOperator,\ _LessOperator,\ _LessEqualOperator,\ _PlusOperator,\ _MinusOperator,\ _MultiplyOperator,\ _DivideOperator,\ _NegateOperator,\ _ModulusOperator namespace fractional::overflow { using namespace std::string_literals; template<class _LhsType, class _RhsType> struct OverflowBinaryError final : std::exception { using LhsType = _LhsType; using RhsType = _RhsType; OverflowBinaryError(const LhsType &lhs, const RhsType &rhs) : lhs_(lhs), rhs_(rhs) {} const LhsType &lhs() const noexcept { return lhs_; } const RhsType &rhs() const noexcept { return rhs_; } [[nodiscard]] const char *what() const noexcept override { return "Binary Overflow error."; } private: LhsType lhs_; RhsType rhs_; }; template<class _NaturalType> struct OverflowUnaryError final : std::exception { using NaturalType = _NaturalType; explicit OverflowUnaryError(const NaturalType &op) : operand_(op) {} const NaturalType &operand() const noexcept { return operand_; } [[nodiscard]] const char *what() const noexcept override { return "Unary Overflow error."; } private: NaturalType operand_; }; template<class _NaturalType, DECLARATION_DEFAULT_TEMPLATE_PARAMS > struct CheckNoOverflow { using NaturalType = _NaturalType; using PlusOperator = _PlusOperator; using MinusOperator = _MinusOperator; using MultiplyOperator = _MultiplyOperator; using DivideOperator = _DivideOperator; using NegateOperator = _NegateOperator; using ModulusOperator = _ModulusOperator; using EqualOperator = _EqualOperator; using NoEqualOperator = _NoEqualOperator; using GreaterOperator = _GreaterOperator; using GreaterEqualOperator = _GreaterEqualOperator; using LessOperator = _LessOperator; using LessEqualOperator = _LessEqualOperator; static constexpr bool CheckMultiply(const NaturalType &lhs, const NaturalType &rhs) noexcept { return true; } static constexpr bool CheckPlus(const NaturalType &lhs, const NaturalType &rhs) noexcept { return true; } static constexpr bool CheckDivide(const NaturalType &lhs, const NaturalType &rhs) noexcept { return true; } static constexpr bool CheckMinus(const NaturalType &lhs, const NaturalType &rhs) noexcept { return true; } static constexpr bool CheckNegate(const NaturalType &lhs) noexcept { return true; } static constexpr bool CheckModulus(const NaturalType &lhs, const NaturalType &rhs) noexcept { return true; } static constexpr bool CheckIncrement(const NaturalType &lhs) noexcept { return true; } static constexpr bool CheckDecrement(const NaturalType &lhs) noexcept { return true; } static constexpr bool CheckBitwiseLeftShift(const NaturalType &lhs, std::size_t rhs) noexcept { return true; } }; /** * Class for checking overflowing * Contains static methods to check overflow, return true if it is not overflows, false otherwise */ template<class _NaturalType, DECLARATION_DEFAULT_TEMPLATE_PARAMS > struct IntegralCheckOverflow { static_assert(_EqualOperator{}(_NaturalType{}, _NegateOperator{}(_NaturalType{})), "Default constructed NaturalType must be zero."); static_assert(std::numeric_limits<_NaturalType>::is_specialized, "std::numeric_limits<_NaturalType> must be specialized"); static_assert(std::numeric_limits<_NaturalType>::is_integer, "_NaturalType must be integer"); using NaturalType = _NaturalType; using PlusOperator = _PlusOperator; using MinusOperator = _MinusOperator; using MultiplyOperator = _MultiplyOperator; using DivideOperator = _DivideOperator; using NegateOperator = _NegateOperator; using ModulusOperator = _ModulusOperator; using EqualOperator = _EqualOperator; using NoEqualOperator = _NoEqualOperator; using GreaterOperator = _GreaterOperator; using GreaterEqualOperator = _GreaterEqualOperator; using LessOperator = _LessOperator; using LessEqualOperator = _LessEqualOperator; static constexpr bool CheckMaxNegate(); static constexpr bool CheckMinNegate(); static constexpr bool CheckMultiply(const NaturalType &lhs, const NaturalType &rhs); static constexpr bool CheckPlus(const NaturalType &lhs, const NaturalType &rhs); static constexpr bool CheckMinus(const NaturalType &lhs, const NaturalType &rhs); static constexpr bool CheckDivide(const NaturalType &lhs, const NaturalType &rhs); static constexpr bool CheckNegate(const NaturalType &lhs); static constexpr bool CheckModulus(const NaturalType &lhs, const NaturalType &rhs); static constexpr bool CheckIncrement(const NaturalType &lhs); static constexpr bool CheckDecrement(const NaturalType &lhs); static constexpr bool CheckBitwiseLeftShift(const NaturalType &lhs, std::size_t rhs); }; template<class _NaturalType, template<class...> class _Checker = IntegralCheckOverflow, DECLARATION_DEFAULT_TEMPLATE_PARAMS > struct ThrowOnCheck { using NaturalType = _NaturalType; using Checker = _Checker<NaturalType, TEMPLATE_PARAMS>; using BinaryError = OverflowBinaryError<NaturalType, NaturalType>; using BitwiseError = OverflowBinaryError<NaturalType, std::size_t>; using UnaryError = OverflowUnaryError<NaturalType>; using PlusOperator = _PlusOperator; using MinusOperator = _MinusOperator; using MultiplyOperator = _MultiplyOperator; using DivideOperator = _DivideOperator; using NegateOperator = _NegateOperator; using ModulusOperator = _ModulusOperator; using EqualOperator = _EqualOperator; using NoEqualOperator = _NoEqualOperator; using GreaterOperator = _GreaterOperator; using GreaterEqualOperator = _GreaterEqualOperator; using LessOperator = _LessOperator; using LessEqualOperator = _LessEqualOperator; static void CheckMultiply(const NaturalType &lhs, const NaturalType &rhs); static void CheckPlus(const NaturalType &lhs, const NaturalType &rhs); static void CheckDivide(const NaturalType &lhs, const NaturalType &rhs); static void CheckMinus(const NaturalType &lhs, const NaturalType &rhs); static void CheckNegate(const NaturalType &lhs); static void CheckModulus(const NaturalType &lhs, const NaturalType &rhs); static void CheckIncrement(const NaturalType &lhs); static void CheckDecrement(const NaturalType &lhs); static void CheckBitwiseLeftShift(const NaturalType &lhs, std::size_t rhs); }; template<class _NaturalType, template<class...> class _Checker = CheckNoOverflow, DECLARATION_DEFAULT_TEMPLATE_PARAMS > struct NoCheck { using NaturalType = _NaturalType; using Checker = _Checker<NaturalType, TEMPLATE_PARAMS>; using BinaryError = OverflowBinaryError<NaturalType, NaturalType>; using BitwiseError = OverflowBinaryError<NaturalType, std::size_t>; using UnaryError = OverflowUnaryError<NaturalType>; using PlusOperator = _PlusOperator; using MinusOperator = _MinusOperator; using MultiplyOperator = _MultiplyOperator; using DivideOperator = _DivideOperator; using NegateOperator = _NegateOperator; using ModulusOperator = _ModulusOperator; using EqualOperator = _EqualOperator; using NoEqualOperator = _NoEqualOperator; using GreaterOperator = _GreaterOperator; using GreaterEqualOperator = _GreaterEqualOperator; using LessOperator = _LessOperator; using LessEqualOperator = _LessEqualOperator; static constexpr void CheckMultiply(const NaturalType &lhs, const NaturalType &rhs) noexcept {}; static constexpr void CheckPlus(const NaturalType &lhs, const NaturalType &rhs) noexcept {}; static constexpr void CheckDivide(const NaturalType &lhs, const NaturalType &rhs) noexcept {}; static constexpr void CheckMinus(const NaturalType &lhs, const NaturalType &rhs) noexcept {}; static constexpr void CheckNegate(const NaturalType &lhs) noexcept {}; static constexpr void CheckModulus(const NaturalType &lhs, const NaturalType &rhs) noexcept {}; static constexpr void CheckIncrement(const NaturalType &lhs) noexcept {}; static constexpr void CheckDecrement(const NaturalType &lhs) noexcept {}; static constexpr void CheckBitwiseLeftShift(const NaturalType &lhs, std::size_t rhs) noexcept {}; }; template<class _NaturalType> struct OverflowChecker : ThrowOnCheck<_NaturalType> { }; } #include "overflowchecker.hxx" #endif //FRACTIONNUMBER_OVERFLOWCHECKER_HPP
true
573ce61857efab2a9218654a0c23464d5b2f4943
C++
yaomthu/leetcode
/flatten_2d_vector.cpp
UTF-8
790
4.09375
4
[]
no_license
/** * Flatten 2d vector * Implement an iterator to flatten a 2d vector. For example, Given 2d vector = [ [1,2], [3], [4,5,6] ] By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6]. space complexity: O(1) */ #include <iostream> #include <vector> using namespace std; namespace flatten_2d_vector { class Vector2D { public: Vector2D(vector<vector<int> >& vec2d) { i = vec2d.begin(); iEnd = vec2d.end(); j = 0; } int next() { return (*i)[j++]; } bool hasNext() { while (i != iEnd && j == (*i).size()) { i++; j = 0; } return i != iEnd; } private: vector<vector<int> >::iterator i, iEnd; int j; }; }
true
e6d21283dc666e3110bfa8b858567d82082d6107
C++
Deepanshu088/C-Competetive
/a20jLevel_11/30_EffectiveApproach.cpp
UTF-8
692
2.796875
3
[]
no_license
//https://codeforces.com/problemset/problem/227/B //Effective Approach #include<iostream> #include<conio.h> using namespace std; void func(){ unsigned int n,m,ltr=0,rtl=0; cin>>n; unsigned int *A = new unsigned int[n]; for(int i=0;i<n;i++) cin>>A[i]; cin>>m; unsigned int *B = new unsigned int[m]; for(int i=0;i<m;i++) cin>>B[i]; for(int i=0;i<m;i++){ int j=0; for(j=0;j<n;j++) if(B[i] == A[j]) break; ltr +=j+1; for(j=n-1;j>=0;j--) if(B[i] == A[j]) break; rtl += n-j; } cout<<ltr<<" "<<rtl; return; } int main(){ func(); return 0; }
true
8f80a7a297495e4adfa1b23d5ea2de6d134abf07
C++
abcdvemm/MPM_Novice
/include/MPM_SHPQ4.hpp
UTF-8
19,412
3.0625
3
[]
no_license
// Class to provide and handle Ansatz/Shape functions for a Q4 // Q4 -> four noded polygon in 2d #include <iostream> #include <iomanip> class MPMSHPQ4 { public: MPMSHPQ4(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); MPMSHPQ4(); ~MPMSHPQ4(); double N1; // Shape Function at Node 1 double N2; // Shape Function at Node 2 double N3; // Shape Function at Node 3 double N4; // Shape Function at Node 4 double dN1dX; // Shape Function at Node 1 differentiated w.r.t X double dN2dX; // Shape Function at Node 2 differentiated w.r.t X double dN3dX; // Shape Function at Node 3 differentiated w.r.t X double dN4dX; // Shape Function at Node 4 differentiated w.r.t X double dN1dY; // Shape Function at Node 1 differentiated w.r.t Y double dN2dY; // Shape Function at Node 2 differentiated w.r.t Y double dN3dY; // Shape Function at Node 3 differentiated w.r.t Y double dN4dY; // Shape Function at Node 4 differentiated w.r.t Y double *N[4] = {&N1, &N2, &N3, &N4}; // Introduce vector structure to loop over ansatz functions ! use *() to get value double *dNdX[4] = {&dN1dX, &dN2dX, &dN3dX, &dN4dX}; // Introduce vector structure to loop over ansatz functions ! use *() to get value double *dNdY[4] = {&dN1dY, &dN2dY, &dN3dY, &dN4dY}; // Introduce vector structure to loop over ansatz functions ! use *() to get value // SHP_i double SHP(int i){ if (i==0) return N1; if (i==1) return N2; if (i==2) return N3; if (i==3) return N4; return 0; }; // dSHP_i dX_j double SHP(int i, int j){ if (i==0) { if(j==0) { return dN1dX; } if(j==1) { return dN1dY; } return 0; } if (i==1) { if(j==0) { return dN2dX; } if(j==1) { return dN2dY; } return 0; } if (i==2) { if(j==0) { return dN3dX; } if(j==1) { return dN3dY; } return 0; } if (i==3) { if(j==0) { return dN4dX; } if(j==1) { return dN4dY; } return 0; } return 0; }; void evaluate(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); //double getMass(void); // A Member Function that returns the Current Mass of the Particle MemberFunction: hass access to all data of the object //void Report(void); // A Member Function to print out a report of this object //std::cout << MyShape.N1 << std::endl; //std::cout << *MyShape.SHP[0] << std::endl; private: double SHPN1(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double SHPN2(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double SHPN3(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double SHPN4(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double dSHPN1dX(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double dSHPN2dX(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double dSHPN3dX(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double dSHPN4dX(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double dSHPN1dY(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double dSHPN2dY(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double dSHPN3dY(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); double dSHPN4dY(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); void SHPTest(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]); }; MPMSHPQ4::~MPMSHPQ4(){} MPMSHPQ4::MPMSHPQ4(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ bool DetailedOutput = true; N1 = SHPN1(X1, X2, X3, X4, XP); N2 = SHPN2(X1, X2, X3, X4, XP); N3 = SHPN3(X1, X2, X3, X4, XP); N4 = SHPN4(X1, X2, X3, X4, XP); dN1dX = dSHPN1dX(X1, X2, X3, X4, XP); dN2dX = dSHPN2dX(X1, X2, X3, X4, XP); dN3dX = dSHPN3dX(X1, X2, X3, X4, XP); dN4dX = dSHPN4dX(X1, X2, X3, X4, XP); dN1dY = dSHPN1dY(X1, X2, X3, X4, XP); dN2dY = dSHPN2dY(X1, X2, X3, X4, XP); dN3dY = dSHPN3dY(X1, X2, X3, X4, XP); dN4dY = dSHPN4dY(X1, X2, X3, X4, XP); if (DetailedOutput) SHPTest(X1, X2, X3, X4, XP); } MPMSHPQ4::MPMSHPQ4(){ } // Method to evaluate the shape functions void MPMSHPQ4::evaluate(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ N1 = SHPN1(X1, X2, X3, X4, XP); N2 = SHPN2(X1, X2, X3, X4, XP); N3 = SHPN3(X1, X2, X3, X4, XP); N4 = SHPN4(X1, X2, X3, X4, XP); dN1dX = dSHPN1dX(X1, X2, X3, X4, XP); dN2dX = dSHPN2dX(X1, X2, X3, X4, XP); dN3dX = dSHPN3dX(X1, X2, X3, X4, XP); dN4dX = dSHPN4dX(X1, X2, X3, X4, XP); dN1dY = dSHPN1dY(X1, X2, X3, X4, XP); dN2dY = dSHPN2dY(X1, X2, X3, X4, XP); dN3dY = dSHPN3dY(X1, X2, X3, X4, XP); dN4dY = dSHPN4dY(X1, X2, X3, X4, XP); } // Shape Function For Node 1 Evaluated at XP inline double MPMSHPQ4::SHPN1(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (X2[0]*(-(XP[0]*(X3[1] - X4[1])*(X2[1] - XP[1])) + X4[0]*(X2[1] - X4[1])*(X3[1] - XP[1]) - X3[0]*(X2[1] - X3[1])*(X4[1] - XP[1])) - X3[0]*X4[0]*(X3[1] - X4[1])*(X2[1] - XP[1]) + X3[0]*XP[0]*(X2[1] - X4[1])*(X3[1] - XP[1]) - X4[0]*XP[0]*(X2[1] - X3[1])*(X4[1] - XP[1]))/ (X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } // Shape Function For Node 1 Evaluated at XP inline double MPMSHPQ4::SHPN2(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (X1[0]*(XP[0]*(X3[1] - X4[1])*(X1[1] - XP[1]) - X4[0]*(X1[1] - X4[1])*(X3[1] - XP[1]) + X3[0]*(X1[1] - X3[1])*(X4[1] - XP[1])) + X3[0]*X4[0]*(X3[1] - X4[1])*(X1[1] - XP[1]) - X3[0]*XP[0]*(X1[1] - X4[1])*(X3[1] - XP[1]) + X4[0]*XP[0]*(X1[1] - X3[1])*(X4[1] - XP[1]))/ (X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } // Shape Function For Node 1 Evaluated at XP inline double MPMSHPQ4::SHPN3(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (X1[0]*(-(XP[0]*(X2[1] - X4[1])*(X1[1] - XP[1])) + X4[0]*(X1[1] - X4[1])*(X2[1] - XP[1]) - X2[0]*(X1[1] - X2[1])*(X4[1] - XP[1])) - X2[0]*X4[0]*(X2[1] - X4[1])*(X1[1] - XP[1]) + X2[0]*XP[0]*(X1[1] - X4[1])*(X2[1] - XP[1]) - X4[0]*XP[0]*(X1[1] - X2[1])*(X4[1] - XP[1]))/ (X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } // Shape Function For Node 1 Evaluated at XP inline double MPMSHPQ4::SHPN4(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (X1[0]*(XP[0]*(X2[1] - X3[1])*(X1[1] - XP[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - XP[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - XP[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - XP[1]) - X2[0]*XP[0]*(X1[1] - X3[1])*(X2[1] - XP[1]) + X3[0]*XP[0]*(X1[1] - X2[1])*(X3[1] - XP[1]))/ (X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } // Derived Shape Functions inline double MPMSHPQ4::dSHPN1dX(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (-(X2[0]*(X3[1] - X4[1])*(X2[1] - XP[1])) + X3[0]*(X2[1] - X4[1])*(X3[1] - XP[1]) - X4[0]*(X2[1] - X3[1])*(X4[1] - XP[1]))/(X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } inline double MPMSHPQ4::dSHPN2dX(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (X1[0]*(X3[1] - X4[1])*(X1[1] - XP[1]) - X3[0]*(X1[1] - X4[1])*(X3[1] - XP[1]) + X4[0]*(X1[1] - X3[1])*(X4[1] - XP[1]))/(X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } inline double MPMSHPQ4::dSHPN3dX(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (-(X1[0]*(X2[1] - X4[1])*(X1[1] - XP[1])) + X2[0]*(X1[1] - X4[1])*(X2[1] - XP[1]) - X4[0]*(X1[1] - X2[1])*(X4[1] - XP[1]))/(X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } inline double MPMSHPQ4::dSHPN4dX(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (X1[0]*(X2[1] - X3[1])*(X1[1] - XP[1]) - X2[0]*(X1[1] - X3[1])*(X2[1] - XP[1]) + X3[0]*(X1[1] - X2[1])*(X3[1] - XP[1]))/(X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } inline double MPMSHPQ4::dSHPN1dY(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (X4[0]*XP[0]*(X2[1] - X3[1]) + X2[0]*(X3[0]*(X2[1] - X3[1]) - X4[0]*(X2[1] - X4[1]) + XP[0]*(X3[1] - X4[1])) - X3[0]*XP[0]*(X2[1] - X4[1]) + X3[0]*X4[0]*(X3[1] - X4[1]))/(X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } inline double MPMSHPQ4::dSHPN2dY(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (-(X4[0]*XP[0]*(X1[1] - X3[1])) + X1[0]*(-(X3[0]*(X1[1] - X3[1])) + X4[0]*(X1[1] - X4[1]) - XP[0]*(X3[1] - X4[1])) + X3[0]*XP[0]*(X1[1] - X4[1]) - X3[0]*X4[0]*(X3[1] - X4[1]))/(X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } inline double MPMSHPQ4::dSHPN3dY(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (X4[0]*XP[0]*(X1[1] - X2[1]) + X1[0]*(X2[0]*(X1[1] - X2[1]) - X4[0]*(X1[1] - X4[1]) + XP[0]*(X2[1] - X4[1])) - X2[0]*XP[0]*(X1[1] - X4[1]) + X2[0]*X4[0]*(X2[1] - X4[1]))/(X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } inline double MPMSHPQ4::dSHPN4dY(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ return (-(X3[0]*XP[0]*(X1[1] - X2[1])) + X1[0]*(-(X2[0]*(X1[1] - X2[1])) + X3[0]*(X1[1] - X3[1]) - XP[0]*(X2[1] - X3[1])) + X2[0]*XP[0]*(X1[1] - X3[1]) - X2[0]*X3[0]*(X2[1] - X3[1]))/(X1[0]*(X4[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X3[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X2[0]*(X1[1] - X2[1])*(X3[1] - X4[1])) + X2[0]*X3[0]*(X2[1] - X3[1])*(X1[1] - X4[1]) - X2[0]*X4[0]*(X1[1] - X3[1])*(X2[1] - X4[1]) + X3[0]*X4[0]*(X1[1] - X2[1])*(X3[1] - X4[1])); } // Shape Function Test void MPMSHPQ4::SHPTest(double X1[3], double X2[3], double X3[3], double X4[3], double XP[3]){ std::cout << "Shape Function Created! Test: :" << std::endl; std::cout << "X1 :" << X1[0] << ", " << X1[1] << ", " << X1[2] << std::endl; std::cout << "X2 :" << X2[0] << ", " << X2[1] << ", " << X2[2] << std::endl; std::cout << "X3 :" << X3[0] << ", " << X3[1] << ", " << X3[2] << std::endl; std::cout << "X4 :" << X4[0] << ", " << X4[1] << ", " << X4[2] << std::endl; std::cout << "XP :" << XP[0] << ", " << XP[1] << ", " << XP[2] << std::endl; //Test for Partition OF Unity std::cout << "N(X1) :" << SHPN1(X1, X2, X3, X4, X1) << ", " << SHPN2(X1, X2, X3, X4, X1) << ", " << SHPN3(X1, X2, X3, X4, X1) << ", " << SHPN4(X1, X2, X3, X4, X1) << std::endl; std::cout << "N(X2) :" << SHPN1(X1, X2, X3, X4, X2) << ", " << SHPN2(X1, X2, X3, X4, X2) << ", " << SHPN3(X1, X2, X3, X4, X2) << ", " << SHPN4(X1, X2, X3, X4, X2) << std::endl; std::cout << "N(X3) :" << SHPN1(X1, X2, X3, X4, X3) << ", " << SHPN2(X1, X2, X3, X4, X3) << ", " << SHPN3(X1, X2, X3, X4, X3) << ", " << SHPN4(X1, X2, X3, X4, X3) << std::endl; std::cout << "N(X4) :" << SHPN1(X1, X2, X3, X4, X4) << ", " << SHPN2(X1, X2, X3, X4, X4) << ", " << SHPN3(X1, X2, X3, X4, X4) << ", " << SHPN4(X1, X2, X3, X4, X4) << std::endl; //Test Call of dx std::cout << "dNdx(X1) :" << dSHPN1dX(X1, X2, X3, X4, X1) << ", " << dSHPN2dX(X1, X2, X3, X4, X1) << ", " << dSHPN3dX(X1, X2, X3, X4, X1) << ", " << dSHPN4dX(X1, X2, X3, X4, X1) << std::endl; std::cout << "dNdx(X2) :" << dSHPN1dX(X1, X2, X3, X4, X2) << ", " << dSHPN2dX(X1, X2, X3, X4, X2) << ", " << dSHPN3dX(X1, X2, X3, X4, X2) << ", " << dSHPN4dX(X1, X2, X3, X4, X2) << std::endl; std::cout << "dNdx(X3) :" << dSHPN1dX(X1, X2, X3, X4, X3) << ", " << dSHPN2dX(X1, X2, X3, X4, X3) << ", " << dSHPN3dX(X1, X2, X3, X4, X3) << ", " << dSHPN4dX(X1, X2, X3, X4, X3) << std::endl; std::cout << "dNdx(X4) :" << dSHPN1dX(X1, X2, X3, X4, X4) << ", " << dSHPN2dX(X1, X2, X3, X4, X4) << ", " << dSHPN3dX(X1, X2, X3, X4, X4) << ", " << dSHPN4dX(X1, X2, X3, X4, X4) << std::endl; //Test Call of dx std::cout << "dNdy(X1) :" << dSHPN1dY(X1, X2, X3, X4, X1) << ", " << dSHPN2dY(X1, X2, X3, X4, X1) << ", " << dSHPN3dY(X1, X2, X3, X4, X1) << ", " << dSHPN4dY(X1, X2, X3, X4, X1) << std::endl; std::cout << "dNdy(X2) :" << dSHPN1dY(X1, X2, X3, X4, X2) << ", " << dSHPN2dY(X1, X2, X3, X4, X2) << ", " << dSHPN3dY(X1, X2, X3, X4, X2) << ", " << dSHPN4dY(X1, X2, X3, X4, X2) << std::endl; std::cout << "dNdy(X3) :" << dSHPN1dY(X1, X2, X3, X4, X3) << ", " << dSHPN2dY(X1, X2, X3, X4, X3) << ", " << dSHPN3dY(X1, X2, X3, X4, X3) << ", " << dSHPN4dY(X1, X2, X3, X4, X3) << std::endl; std::cout << "dNdy(X4) :" << dSHPN1dY(X1, X2, X3, X4, X4) << ", " << dSHPN2dY(X1, X2, X3, X4, X4) << ", " << dSHPN3dY(X1, X2, X3, X4, X4) << ", " << dSHPN4dY(X1, X2, X3, X4, X4) << std::endl; //Test For Interpolation of a constant field // interpolate nodal values TI over element defined with TestXI and evalueate the interpolation as well as its gradient at points TestXP double TI[4] = {2.0,2.0,2.0,2.0}; double TestXI[4][2] = {{0.0 ,0.0},{1.0,0.0},{1.0,1.0},{0.0,1.0}}; double TestXP[4][2] = {{0.2 ,0.2},{0.8,0.2},{0.8,0.8},{0.2,0.8}}; double TXP[4]; double Grad_TXP[4][2]; for(int TestPoint=0;TestPoint<4;TestPoint++){ evaluate(TestXI[0], TestXI[1], TestXI[2], TestXI[3], TestXP[TestPoint]); // interpolate TI TXP[TestPoint] = 0; Grad_TXP[TestPoint][0] = 0.0; Grad_TXP[TestPoint][1] = 0.0; for(int i=0;i<4;i++) TXP[TestPoint] += (*N[i]) * TI[i]; for(int i=0;i<4;i++) Grad_TXP[TestPoint][0] += (*dNdX[i]) * TI[i]; for(int i=0;i<4;i++) Grad_TXP[TestPoint][1] += (*dNdY[i]) * TI[i]; } std::cout << "Constant Field TI = 2 at Test Points: " << std::endl; std::cout << " P1 P2 P3 P4 " << std::endl; std::cout << " TI " << std::setw(5) << TXP[0] << " ," << std::setw(5) << TXP[1] << " ," << std::setw(5) << TXP[2] << " ," << std::setw(5) << TXP[3] << std::endl; std::cout << " dTidX " << std::setw(5) << Grad_TXP[0][0] << " ," << std::setw(5) << Grad_TXP[1][0] << " ," << std::setw(5) << Grad_TXP[2][0] << " ," << std::setw(5) << Grad_TXP[3][0] << std::endl; std::cout << " dTidX " << std::setw(5) << Grad_TXP[0][1] << " ," << std::setw(5) << Grad_TXP[1][1] << " ," << std::setw(5) << Grad_TXP[2][1] << " ," << std::setw(5) << Grad_TXP[3][1] << std::endl; //Test For Interpolation of a bilinear field // interpolate nodal values TI over element defined with TestXI and evalueate the interpolation as well as its gradient at points TestXP double TIBiLin[4] = {-2.0,3.0,5.0,7.239}; double TestXIBiLin[4][2] = {{0.0 ,0.0},{1.0,0.0},{1.0,1.0},{0.0,1.0}}; double TestXPBiLin[4][2] = {{0.2 ,0.2},{0.8,0.2},{0.8,0.8},{0.2,0.8}}; double TXPBiLin[4]; double Grad_TXPBiLin[4][2]; for(int TestPoint=0;TestPoint<4;TestPoint++){ evaluate(TestXIBiLin[0], TestXIBiLin[1], TestXIBiLin[2], TestXIBiLin[3], TestXPBiLin[TestPoint]); // interpolate TI TXPBiLin[TestPoint] = 0; Grad_TXPBiLin[TestPoint][0] = 0.0; Grad_TXPBiLin[TestPoint][1] = 0.0; for(int i=0;i<4;i++) TXPBiLin[TestPoint] += (*N[i]) * TIBiLin[i]; for(int i=0;i<4;i++) Grad_TXPBiLin[TestPoint][0] += (*dNdX[i]) * TIBiLin[i]; for(int i=0;i<4;i++) Grad_TXPBiLin[TestPoint][1] += (*dNdY[i]) * TIBiLin[i]; } std::cout << "Constant Field T(x,y) = -2+x(5-7.239y)+ 9.239y at Test Points: " << std::endl; std::cout << " P1 P2 P3 P4 " << std::endl; std::cout << " TI " << std::setw(5) << TXPBiLin[0] << " ," << std::setw(5) << TXPBiLin[1] << " ," << std::setw(5) << TXPBiLin[2] << " ," << std::setw(5) << TXPBiLin[3] << std::endl; std::cout << " dTidX " << std::setw(5) << Grad_TXPBiLin[0][0] << " ," << std::setw(5) << Grad_TXPBiLin[1][0] << " ," << std::setw(5) << Grad_TXPBiLin[2][0] << " ," << std::setw(5) << Grad_TXPBiLin[3][0] << std::endl; std::cout << " dTidX " << std::setw(5) << Grad_TXPBiLin[0][1] << " ," << std::setw(5) << Grad_TXPBiLin[1][1] << " ," << std::setw(5) << Grad_TXPBiLin[2][1] << " ," << std::setw(5) << Grad_TXPBiLin[3][1] << std::endl; }
true
76731167bf316a333865cfc42b8ab461861da1e2
C++
intfreedom/C
/C++/20190906/20190906/ClassArray.cpp
UTF-8
1,045
3.15625
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<string.h> class CGirl { public: char m_name[50]; int m_age; int m_height; char m_sc[30]; char m_yz[30]; int Show(); }; void func(CGirl Girltest); int CGirl::Show() { printf("name: %s, age: %d, height: %d, body: %s, face: %s\n", m_name, m_age, m_height, m_sc, m_yz); return 0; } void func(CGirl Girltest) { strcpy(Girltest.m_name, "Angle"); Girltest.m_age = 28; Girltest.m_height = 179; strcpy(Girltest.m_sc, "gogogo"); strcpy(Girltest.m_yz, "tototo"); Girltest.Show(); } int main() { //CGirl Girl[10]; CGirl Girltest; func(Girltest); /* strcpy(Girl[0].m_name, "meimei"); Girl[0].m_age = 18; Girl[0].m_height = 178; strcpy(Girl[0].m_sc, "very"); strcpy(Girl[0].m_yz, "years"); Girl[0].Show(); strcpy(Girl[1].m_name, "hanhan"); Girl[1].m_age = 23; Girl[1].m_height = 163; strcpy(Girl[1].m_sc, "much"); strcpy(Girl[1].m_yz, "haokan"); Girl[1].Show();*/ getchar();/*the same project is not,even two different file can't be the same function*/ }
true
6cec40baccd5f3dec0c0a7e64a888388b97a299e
C++
AdrianTP/covalence-arduboy
/headers/board.h
UTF-8
351
2.578125
3
[]
no_license
#ifndef BOARD_H #define BOARD_H class Board { private: int board[BOARD_WIDTH][BOARD_HEIGHT]; // TODO: multidimensional array BOARD_WIDTH by BOARD_HEIGHT public: Board(); virtual ~Board(); int readCellAtCoords(int x, int y); void emptyCellAtCoords(int x, int y); int writeCellAtCoords(int x, int y, int atomIndexInManifest); }; #endif
true
46593c5da0d67edf4964a461e2b93f8fe9c42307
C++
magiccjae/cs235
/Lab6 - bst/BST.h
UTF-8
1,126
3.15625
3
[]
no_license
#pragma once #include "NodeInterface.h" #include "Node.h" #include "BSTInterface.h" using namespace std; class BST : public BSTInterface { public: Node* root; BST() { root = NULL; } virtual ~BST() { while(root != NULL) { remove(root->data); } } /* * Returns the root node for this tree * * @return the root node for this tree. */ virtual NodeInterface * getRootNode(); /* * Attempts to add the given int to the BST tree * * @return true if added * @return false if unsuccessful (i.e. the int is already in tree) */ virtual bool add(int data); /* * Attempts to remove the given int from the BST tree * * @return true if successfully removed * @return false if remove is unsuccessful(i.e. the int is not in the tree) */ virtual bool remove(int data); Node* addRecursively(int data, Node* current); bool removeRecursively(int data, Node*& current); void replace_parent(Node*& old_root, Node*& current); void print(); void printRecursively(Node* current, int depth); bool is_duplicate(int data, Node* current); };
true
795ed4d37728aea5173655c3f4b51b1a001d4987
C++
mariogeiger/billiard
/system.cc
UTF-8
3,888
2.796875
3
[]
no_license
#include "system.hh" #include <QDebug> #include <iostream> using namespace std; System::System() { } void System::step(double dt) { for (uint i = 0; i < balls.size(); ++i) { Ball* a = &balls[i]; Vec3 g = Vec3(0, 0, -10); for (uint j = 0; j < walls.size(); ++j) { Wall* w = &walls[j]; Vec3 d = a->q - w->p; if (Vec3::dot(d, w->n) - R < 1e-5) { Vec3 d = a->q - w->p; d -= Vec3::dot(d, w->n) * w->n; a->q = w->p + d + w->n * R; Vec3 v = a->p / m + Vec3::cross(a->L / I, -w->n * R); //std::cout << a->p/m << std::endl; //std::cout << v << std::endl; if (Vec3::length(v) < 5e-3) { // static force } else { //qDebug() << "cinetic force"; Vec3 f = 1.2 * Vec3::dot(m * g, -w->n) * (-v / Vec3::length(v)); a->force += f; a->torque += Vec3::cross(-w->n * R, f); } // slowing if (Vec3::length(a->L) > 0) { //qDebug() << "slowing force"; //Vec3 f = 0.05 * Vec3::dot(m * g, -w->n) * (-a->p / Vec3::length(a->p)); //a->force += f; //a->torque += Vec3::cross(w->n * R, f); // to maintain v a->torque += -0.2 * Vec3::dot(m * g, -w->n) * a->L / Vec3::length(a->L); } } } a->force += m * g; a->p += dt * a->force; a->L += dt * a->torque; a->q += a->p / m * dt; double angle = Vec3::length(a->L) / I * dt * 180./M_PI; a->Qrot = QQuaternion::fromAxisAndAngle(a->L[0], a->L[1], a->L[2], angle) * a->Qrot; a->force.setNull(); a->torque.setNull(); } } void System::simulate(double dt) { double ddt = 1e-5 * dt; for (uint i = 0; i < balls.size(); ++i) { Ball* a = &balls[i]; for (uint j = i+1; j < balls.size(); ++j) { Ball* b = &balls[j]; while (is_collision_ball(a, b)) { collision_ball(a, b); step(ddt); dt -= ddt; } } for (uint j = 0; j < walls.size(); ++j) { Wall* w = &walls[j]; if (is_collision_wall(a, w)) { collision_wall(a, w); } } } step(dt); } bool System::is_collision_ball(Ball* a, Ball* b) { Vec3 n = a->q - b->q; return Vec3::length(a->q - b->q) < 2.*R && Vec3::dot(n, a->p * m - b->p * m) < 0.0; } bool System::is_collision_wall(Ball* a, Wall* w) { Vec3 d = a->q - w->p; return Vec3::dot(d, w->n) < R && Vec3::dot(a->p, w->n) < 0.; } void System::collision_ball(Ball* a, Ball* b) { static int count = 0; count++; //if (count >= 2) return; //qDebug() << "collision" << count; Vec3 vg = (a->p + b->p) / (2.0 * m); Vec3 p = a->p - m * vg; Vec3 r = (b->q - a->q) / 2.0; // hypothèses // - choc instantané // - force appliquée au point de l'impact uniquement // - q. de mvt / moment cinétique conservés // - choc élastique // - force colinéaire au vecteur suivant : Vec3 v = 2.*p/m + 1./I * Vec3::cross(a->L + b->L, r); v /= Vec3::length(v); v = r / Vec3::length(r) + 0.2 * v; // dp = \int Force dt = alpha v, avec alpha tel que les hypothèses soient vérifiées double alpha = (2.*I/m * Vec3::dot(p, v) + Vec3::dot(a->L+b->L, Vec3::cross(r, v))) / (I/m * Vec3::norm(v) + Vec3::norm(Vec3::cross(r, v))); Vec3 dp = alpha * v; Vec3 p_prim = p - dp; a->p = m * vg + p_prim; b->p = m * vg - p_prim; Vec3 dL = Vec3::cross(r, dp); a->L = a->L - dL; b->L = b->L - dL; } void System::collision_wall(Ball* a, Wall* w) { static int count = 0; count++; //if (count >= 2) return; //qDebug() << "collision wall" << count; double p_perp = -Vec3::dot(a->p, w->n); //cout << p_perp << endl; double cor = 0.5; if (p_perp < 0.15) { a->p = a->p + p_perp * w->n; Vec3 d = a->q - w->p; d -= Vec3::dot(d, w->n) * w->n; a->q = w->p + d + w->n * R; } else { a->p = a->p + (1. + cor) * p_perp * w->n; } }
true
fcbc7c44919e13ea7a9b2d4e2c62732921e084f6
C++
curguest/COMPUTER-PROGRAMMING
/esp3_01.cpp
UTF-8
431
3.25
3
[]
no_license
#include<iostream.h> void main() { int x,b; b=0; cout<<"请输入一个整数"<<endl; cin>>x; while(x!=0) { if(b<4) { b++; x=x/10; } else cout<<"输入有误!!!"; } switch(b) { case 0:cout<<"x等于0";break; case 1:cout<<"x小于10";break; case 2:cout<<"x大于9小于100";break; case 3:cout<<"x大于99小于1000";break; case 4:cout<<"x大于999";break; } }
true