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
a71bceb73c5c88813e0279fb77cd7bb3349149a5
C++
Embracethevoid/typecheker
/expr.h
UTF-8
1,416
2.765625
3
[]
no_license
#ifndef EXPR_H #define EXPR_H #inlcude<list> #include<string> using namespace std; typedef struct expr_val* exp; struct expr_val { char* str; int num; float num; }; extern exp mk_int(int item); extern exp mk_str(char* item); extern exp mk_float(float item); class class_signature{} class class_body{} class program { protected: list<quack_class*> classes*; list<statement *> statements*; public: program(list<quack_class*> *c,list<statement*> *s); void evaluate(); } class quack_class { protected: class_signature* sign; class_body* body; public: quack_class(class_signature* s,class_body* b); } class statement { } class expr_node { protected: public: expr(); virtual expr_val evaluate() = 0; } class operator_node : public expr_node { protected: public: virtual expr_val evaluate() = 0; } class plus_node: public operator_node { public: plus_node(expr_node *l,expr_node* r); } class minus_node: public operator_node { public: minus_node(expr_node *l,expr_node* r); } class times_node: public operator_node { public: times_node(expr_node *l,expr_node* r); } class divide_node: public operator_node { public: divide_node(expr_node *l,expr_node* r); } class int_node: public expr_node { protected: int num; public: int_node(int n); int evaluate(); } class str_node:public expr_node { protected: string val; public: str_node(char* s); string evaluate(); } #endif
true
1f2361835f561d72a499821435dbff3d330a24d9
C++
waterinet/miscellaneous_repo
/cpp_console/stree.h
UTF-8
8,938
2.96875
3
[]
no_license
#ifndef STREE_H #define STREE_H #include <map> #include <vector> #include <queue> #include <string> #include <iostream> #include <cstdarg> namespace pgr { template<typename T> std::vector<T> array_as_vector(int count, ...) { std::vector<T> vec; va_list args; va_start(args, count); for (int i = 0; i < count; i++) { T t = va_arg(args, T); vec.push_back(t); } va_end(args); return vec; } template<typename key_type, typename data_type> class stree; template<typename key_type> class stree_node_pos { public: stree_node_pos() : _parent(false, key_type()), _left(false, key_type()), _right(false, key_type()) {} stree_node_pos& parent(bool b, key_type k) { _parent.first = b; _parent.second = k; return *this; } stree_node_pos& left(bool b, key_type k) { _left.first = b; _left.second = k; return *this; } stree_node_pos& right(bool b, key_type k) { _right.first = b; _right.second = k; return *this; } bool has_parent() const { return _parent.first; } bool has_left() const { return _left.first; } bool has_right() const { return _right.first; } key_type parent() const { return _parent.second; } key_type left() const { return _left.second; } key_type right() const { return _right.second; } private: std::pair<bool, key_type> _parent; std::pair<bool, key_type> _left; std::pair<bool, key_type> _right; }; template<typename key_type, typename data_type> class stree_helper { friend class stree<key_type, data_type>; typedef stree_node_pos<key_type> stree_node_pos; typedef std::pair<key_type, data_type> node_type; public: void add_node(key_type k, data_type d) { _node_data[k] = d; } void add_nodes(const std::vector<node_type>& vec) { typename std::vector<node_type>::const_iterator it; for (it = vec.begin(); it != vec.end(); it++) { add_node(it->first, it->second); } } void add_pos_info(key_type p, const std::vector<key_type>& vec) { if (vec.empty()) return; if (_node_pos.count(p) == 0) { _node_pos[p] = stree_node_pos(); } typename std::vector<key_type>::const_iterator it; for (it = vec.begin(); it != vec.end(); it++) { stree_node_pos pos; pos.parent(true, p); if (it > vec.begin()) pos.left(true, *(it - 1)); if (it < vec.end() - 1) pos.right(true, *(it + 1)); _node_pos[*it] = pos; } } private: std::map<key_type, stree_node_pos> _node_pos; std::map<key_type, data_type> _node_data; }; template<typename key_type, typename data_type> class stree { public: struct stree_node { key_type key; data_type data; stree_node* parent; stree_node* left_child; stree_node* right_sibling; stree_node() : parent(0), left_child(0), right_sibling(0) {} stree_node(key_type k) : key(k), parent(0), left_child(0), right_sibling(0) {} stree_node(key_type k, data_type d) : key(k), data(d), parent(0), left_child(0), right_sibling(0) {} }; typedef stree_node node_type; ~stree() { typename std::map<key_type, node_type*>::iterator it = _nodes.begin(); while (it != _nodes.end()) { delete it->second; it++; } root = 0; } void add_node(stree_node_pos<key_type> pos, key_type k, data_type d) { node_type* n = set_node(k, d); node_type* p = pos.has_parent() ? get_node(pos.parent()) : 0; node_type* l = pos.has_left() ? get_node(pos.left()) : 0; node_type* r = pos.has_right() ? get_node(pos.right()) : 0; add_child(p, l, r, n); } void build(const stree_helper<key_type, data_type>& helper) { typedef typename std::map<key_type, data_type>::const_iterator data_iterator_type; typedef typename std::map<key_type, stree_node_pos<key_type> >::const_iterator pos_iterator_type; data_iterator_type it = helper._node_data.begin(); while (it != helper._node_data.end()) { pos_iterator_type pos = helper._node_pos.find(it->first); if (pos != helper._node_pos.end()) { add_node(pos->second, it->first, it->second); } it++; } } void print() { typedef std::vector< std::pair<int, node_type*> > result_type; result_type vec; std::cout << "***depth traversal***" << std::endl; if (depth_traversal(vec) > 0) { typename result_type::const_iterator it = vec.begin(); while (it != vec.end()) { std::cout << std::string(it->first * 2, ' ') << it->second->key << ": " << it->second->data << std::endl; it++; } } vec.clear(); std::cout << "***breadth traversal***" << std::endl; if (breadth_traversal(vec) > 0) { int depth = 0; typename result_type::const_iterator it = vec.begin(); while (it != vec.end()) { if (it->first > depth) { std::cout << std::endl; depth = it->first; } else if (it != vec.begin()) { std::cout << " "; } std::cout << it->second->key << ": " << it->second->data; it++; } } } private: node_type* get_node(key_type k) { if (_nodes.count(k) == 0) { _nodes[k] = new node_type(k); } return _nodes[k]; } node_type* set_node(key_type k, data_type d) { node_type* n = get_node(k); n->data = d; return n; } void add_child(node_type* p, node_type* l, node_type* r, node_type* n) { if (p) { if (l && r) { l->right_sibling = n; n->parent = p; n->right_sibling = r; } else if (l) { l->right_sibling = n; n->parent = p; } else if (r) { n->right_sibling = r; n->parent = p; p->left_child = n; } else { node_type* rc = rightmost_child(p); if (rc) { rc->right_sibling = n; n->parent = p; } else { p->left_child = n; n->parent = p; } } } else { root = n; } } node_type* rightmost_child(node_type* p) { if (p) { node_type* q = p->left_child; while (q && q->right_sibling) { q = q->right_sibling; } return q; } return 0; } int depth_traversal(std::vector< std::pair<int, node_type*> >& result) { if (!root) return 0; typedef std::pair<int, node_type*> pair_type; std::vector<pair_type> stack; std::vector<pair_type> vec; //output from left to right stack.push_back(pair_type(0, root)); while (!stack.empty()) { pair_type n = stack.back(); stack.pop_back(); result.push_back(n); node_type* child = n.second->left_child; while (child) { vec.push_back(pair_type(n.first + 1, child)); child = child->right_sibling; } while (!vec.empty()) { stack.push_back(vec.back()); vec.pop_back(); } } return result.size(); } int breadth_traversal(std::vector< std::pair<int, node_type*> >& result) { if (!root) return 0; typedef std::pair<int, node_type*> pair_type; std::queue<pair_type> que; que.push(pair_type(0, root)); while (!que.empty()) { pair_type n = que.front(); que.pop(); result.push_back(n); node_type* child = n.second->left_child; while (child) { que.push(pair_type(n.first + 1, child)); child = child->right_sibling; } } return result.size(); } node_type* root; std::map<key_type, node_type*> _nodes; }; } //namespace pgr #endif // STREE_H
true
b1c50e694872cd909bd726565a0b9bf6f5a0783b
C++
jeremiahwitt/Dragons
/All Code/routing.h
UTF-8
822
2.59375
3
[]
no_license
/** *@file routing.h *@brief Provides class used to manage routing of map */ #pragma once #include <vector> #include <iostream> #include "namespaces.h" using namespace SimplifiedMapSymbols; /*! *@class SingletonRouting *this singleton class is used for the routing part of map validation */ class SingletonRouting { private: SingletonRouting(); static SingletonRouting* _routingInstance; struct Position { public: int X_cor; int Y_cor; }; std::vector<Position> _validPositions; std::vector<std::string> _map; Position _origin; Position _exitDoor; Position _temp; const char _obstruction; const char _path; const char _exit; const char _player; void findRoute(Position node); public: bool routeValidity(std::vector<std::string> map); static SingletonRouting* getInstance(); ~SingletonRouting(); };
true
29e5eeea68048a39445e9e86d9e297638702dd71
C++
nnonnoon/AbstractDataType
/week3/chain.cpp
UTF-8
2,122
3.125
3
[]
no_license
#include<iostream> using namespace std; typedef int valueType; struct ListNode { valueType val; ListNode* next; ListNode* prev; ListNode(valueType val, ListNode* next=0,ListNode* prev=0) : val(val), next(next) ,prev(prev){} }; void print_list(ListNode* node){ while(node!=NULL){ cout<<node->val; node=node->next; } } ListNode* list[100001]; ListNode* tail[100001]; int main(){ int a,b,n,keep=0,tod=1,number; ListNode** address[100001]; int nub[100001]; char atv; cin>>a>>b; for (int i = 1 ; i<=a ; i++){ list[i] = new ListNode(0) ; tail[i]=list[i]; cin>>n; keep=keep+n; for(int j = tod ; j<=keep ; j++){ ListNode* p = new ListNode(j); address[j]=&p; if(list[i]->next == NULL){ list[i] -> next = p; p -> prev = NULL; tail[i]=p; } else{ tail[i]->next = p; p-> prev = tail[i]; tail[i]=p; } tod+=1; } } int count = 1; ListNode* p = list[1]->next; for (int k = 1 ; k<=b ;k++){ cin>>atv; if (atv == 'F'){ if(p->next == NULL){ nub[k]=p->val; count=count+1; continue; } else{ p=p->next; nub[k]=p->val; count=count+1; } } else if(atv == 'B'){ if(p->prev == list[1]){ nub[k]=p->val; count=count+1; continue; } else{ p=p->prev; nub[k]=p->val; count=count+1; } } else if (atv == 'C'){ cin>>number; if (p->next!= NULL){ p->next->prev = NULL; p->next = NULL; } else if ([number]->prev=NULL){ } } } for(int t = 1 ; t<count ;t++ ){ cout<<nub[t]; } }
true
f7a29837a07b5a1a58491d662cb0c71e1432fc25
C++
njoy/nuclearData
/implementation/PolymorphicInterpolationCrossSection/test/PolymorphicInterpolationCrossSection.test.cpp
UTF-8
3,144
2.859375
3
[ "BSD-2-Clause" ]
permissive
#define CATCH_CONFIG_RUNNER #include <cmath> #include <functional> #include "catch.hpp" #include "math/interpolate.hpp" #include "math/implementation.hpp" #include "nuclearData/implementation/PolymorphicInterpolationCrossSection.hpp" namespace { std::vector<double> X = {1.0, 2.0, 3.0, 4.0, 5.0}; auto f = [](double x){return 2.0*x + 5.0;}; std::vector<double> Y = {f(X[0]), f(X[1]), f(X[2]), f(X[3]), f(X[4])}; std::unique_ptr<math::API::InterpolationTable> storedTable = std::make_unique < math::implementation::DataReferencingInterpolationTable < std::vector<double>::iterator, math::interpolate::linLin > > ( X.begin(), X.end(), Y.begin(), Y.end() ); } math::implementation::DataReferencingInterpolationTable < std::vector<double>::iterator, math::interpolate::linLin > referenceTable( X.begin(), X.end(), Y.begin(), Y.end() ); nuclearData::implementation::PolymorphicInterpolationCrossSection XS( std::move(storedTable), false ); int testNumber = 0; int main( int argc, const char* argv[] ){ LOG(INFO) << ""; LOG(INFO) << "PolymorphicInterpolationCrossSection Tests"; LOG(INFO) << "================================="; int result = Catch::Session().run( argc, argv ); LOG(INFO) << "PolymorphicInterpolationCrossSection Tests Complete!"; return result; } SCENARIO ("Negative energies in the energy grid will cause the ctor to throw", "[nuclearData], [PolymorphicInterpolationCrossSection], [ctor]"){ GIVEN("An energy grid with a negative entry"){ std::vector<double> X = {-1.0, 2.0, 3.0, 4.0, 5.0}; WHEN("used to construct a cross section object"){ THEN("the ctor will throw"){ using crossSection = nuclearData::implementation::PolymorphicInterpolationCrossSection; using table = math::implementation::DataReferencingInterpolationTable < std::vector<double>::iterator, math::interpolate::linLin >; LOG(INFO) << "Test " << ++testNumber << ": [ctor] Errors Expected"; std::unique_ptr<math::API::InterpolationTable> referenceTable = std::make_unique<table>( X.begin(), X.end(), Y.begin(), Y.end() ); REQUIRE_THROWS( crossSection( std::move(referenceTable), false ) ); } } } } SCENARIO ("Negative values in the cross section grid will cause the ctor to throw"){ std::vector<double> Y = {f(X[0]), f(X[1]), -1, f(X[3]), f(X[4])}; GIVEN("A cross section grid with a negative entry"){ WHEN("used to construct a cross section object"){ THEN("the ctor will throw"){ LOG(INFO) << "Test " << ++testNumber << ": [ctor] Errors Expected"; using crossSection = nuclearData::implementation::PolymorphicInterpolationCrossSection; using table = math::implementation::DataReferencingInterpolationTable < std::vector<double>::iterator, math::interpolate::linLin >; std::unique_ptr<math::API::InterpolationTable> referenceTable = std::make_unique<table>( X.begin(), X.end(), Y.begin(), Y.end() ); REQUIRE_THROWS( crossSection( std::move( referenceTable ), false ) ); } } } }
true
d07f7e605b4ce7fea83a0fc83f7d0c9a7f0fb143
C++
rfsheffer/genesis-game-engine
/utilities/data/data_bits.h
UTF-8
2,235
3.21875
3
[]
no_license
// // data_bits.h // Classes for helping traversal of and setting of individual bits. // // Created by Ryan Sheffer on 11/17/2013. // Copyright (c) 2013 Ryan Sheffer. All rights reserved. // #ifndef DATA_BITS_H #define DATA_BITS_H #ifdef _WIN #pragma once #endif namespace data { //-------------------------------------------------------------------------- /** * A class designed for helping with traversal of a number of bytes * bit by bit. */ class BitGetter { public: /** The position of the current byte */ const byte *pPos; /** The number of bits left to traverse before incrementing the byte */ unsigned int bitsLeft; /** Constructor */ BitGetter(const byte *pStartingByte) { pPos = pStartingByte; bitsLeft = 8; } /** Gets the next bits state, and increments the byte pointer if needed. */ bool GetNextBitState(void) { --bitsLeft; bool bitState = ((*pPos) >> bitsLeft) & 0x01; if(bitsLeft == 0) { ++pPos; bitsLeft = 8; } return bitState; } }; //-------------------------------------------------------------------------- /** * A class designed for helping with the setting of individual bits one at * a time, from right to left. */ class BitSetter { public: /** The position of the current byte */ byte *pPos; /** The number of bits left to traverse before incrementing the byte */ unsigned int bitsLeft; /** Constructor */ BitSetter(byte *pStartingByte) { pPos = pStartingByte; bitsLeft = 8; } /** Sets the next bit in line */ void SetNextBitState(bool state) { --bitsLeft; (*pPos) = (*pPos) | (byte(state?1:0) << bitsLeft); if(bitsLeft == 0) { ++pPos; bitsLeft = 8; } } }; } #endif // DATA_BITS_H
true
cd548ca3d0f84bb34a2e4b3009dc4a79d5c1c5cc
C++
tischsoic/klasy-2-JMP-Cpp
/klasy 2 JMP 2/Punkt3D.h
UTF-8
252
2.578125
3
[]
no_license
#include <iostream> #include "Punkt.h" using namespace std; #pragma once class Punkt3D : public Punkt { double z; public: Punkt3D(); Punkt3D(double _x, double _y, double _z) : Punkt(_x, _y) { z = _z; } ~Punkt3D(); double distance(Punkt3D); };
true
3acc2086e75f7449cb2443867ceb9c2950a596da
C++
emuikernel/BDXDaq
/devel/coda/src/rc/runControl/Common/codaSlist.h
UTF-8
6,623
2.703125
3
[]
no_license
//----------------------------------------------------------------------------- // Copyright (c) 1994,1995 Southeastern Universities Research Association, // Continuous Electron Beam Accelerator Facility // // This software was developed under a United States Government license // described in the NOTICE file included as part of this distribution. // //----------------------------------------------------------------------------- // // Description: // Single Linked List for pointers void * // // Note: remove and clean operations on the list // will only remove link nodes without removal of // the content inside the nodes. It is callers' // responsiblity to clean up those contents // // This is unsafe C++ practice, use this list at you own risk // // Reason for this list: It is very difficult to instantiate // a template class in a stand alone shared library // // Author: Jie Chen // CEBAF Data Acquisition Group // // Revision History: // $Log: codaSlist.h,v $ // Revision 1.1.1.1 1996/10/11 13:39:31 chen // run control source // // Revision 1.1 1995/06/30 15:08:00 chen // single linked list for void * // // #ifndef _CODA_SLIST_H #define _CODA_SLIST_H #include <assert.h> typedef void* codaSlistItem; //====================================================================== // class codaGenSlist // Single Linked List for void* pointer //====================================================================== class codaSlistLink; class codaSlistIterator; class codaSlistCursor; class codaSlist { public: // constructors codaSlist (void); codaSlist (const codaSlist & source); virtual ~codaSlist (void); // operations // add list item to the beginning of the list virtual void add(codaSlistItem value); // remove a list item from the list // return 0: nothing to remove // return 1: remove success virtual int remove (codaSlistItem value); // clean up the list. virtual void deleteAllValues(); // return first element of the list virtual codaSlistItem firstElement() const; // return last element of the list virtual codaSlistItem lastElement() const; // duplicate ths whole list virtual codaSlist* duplicate() const; // check whether this list contains a particular item // return 1: yes. return 0: no virtual int includes(codaSlistItem value) const; // Is list empty // return 1: yes. return 0: no virtual int isEmpty() const; // remove first element of the list virtual void removeFirst(); // return number of elements inside the list virtual int count() const; protected: // data field codaSlistLink* ptrToFirstLink; // friends friend class codaSlistIterator; // cannot modify list in anyways friend class codaSlistCursor; }; //====================================================================== // class codaSlistLink // Single linked list link node //====================================================================== class codaSlistLink { public: // insert a new element following the current value codaSlistLink* insert (codaSlistItem val); private: // constructor codaSlistLink (codaSlistItem linkValue, codaSlistLink * nextPtr); // duplicate codaSlistLink* duplicate (void); // data areas codaSlistItem value; codaSlistLink* ptrToNextLink; // friends friend class codaSlist; friend class codaSlistIterator; friend class codaSlistCursor; }; //=================================================================== // class codaSlistIterator // implements iterator protocol for linked lists // also permits removal and addition of elements //=================================================================== class codaSlistIterator { public: // constructor codaSlistIterator (codaSlist& aList); // iterator protocol virtual int init (void); virtual codaSlistItem operator () (void); virtual int operator ! (void); virtual int operator ++ (void); virtual void operator = (codaSlistItem value); // new methods specific to list iterators // remove current item pointed by the iterator from the list void removeCurrent(void); // add an item to the list before the position pointed by the iterator void addBefore(codaSlistItem newValue); // add an item to the list after the position pointed by the iterator void addAfter(codaSlistItem newValue); // search an item and move the iterator to that position int searchSame(codaSlistItem &value); protected: // data areas codaSlistLink * currentLink; codaSlistLink * previousLink; codaSlist& theList; }; //=================================================================== // class codaSlistCursor // implements cursor protocol for linked lists //=================================================================== class codaSlistCursor { public: // constructor codaSlistCursor (const codaSlist& aList); // iterator protocol virtual int init (void); virtual codaSlistItem operator () (void); virtual int operator ! (void); virtual int operator ++ (void); virtual void operator = (codaSlistItem value); int searchSame (codaSlistItem &value); protected: // data areas codaSlistLink * currentLink; codaSlistLink * previousLink; const codaSlist& theList; }; //====================================================================== // class doubleEndedList // Not only keeps a pointer to first node // but also keeps a pointer to last node //====================================================================== class codaDoubleEndedSlist: public codaSlist{ public: //constructor codaDoubleEndedSlist (void); codaDoubleEndedSlist (const codaDoubleEndedSlist &v); // override the following methods from the codaSlist virtual void add (codaSlistItem value); virtual void deleteAllValues (void); virtual void removeFirst (void); // add new element to the end of the list virtual void addToEnd (codaSlistItem value); protected: codaSlistLink *ptrToLastLink; }; #endif
true
b4d137f5c831032d9ab02daa11e95919d77a2f5a
C++
Mtj-p/20FAL-CSC-17A-49285
/Homework/McDonaldJohnPaul_Gaddis_9thEd_Chap4_Prob10_DaysinaMonth/main.cpp
UTF-8
1,773
3.421875
3
[]
no_license
/* * file: McDonaldJohnPaul_Gaddis_9thEd_Chap4_Prob10_Daysinamonth * Author: John-Paul McDonald * Date: 06/29/20 * Purpose: Input a month, output the number of days */ //System Libraries #include <iostream> using namespace std; //User Libraries //Global Constants //Universal Math, Physics, Conversions, Higher Dimensions //Prototypes //Execution Begins Here int main(int argc, char** argv) { //Initialize Random Number Seed //Declare Variables int month=0; int year=0; //Initialize Variables //Process the inputs -> outputs cout<<"Enter a month (1-12): "; cin>>month; cout<<endl<<"Enter a year: "; cin>>year; //Display the results, verify inputs if(month>12||month<1){ cout<<"invalid month"<<endl; } if(year<0){ cout<<"invalid year"<<endl; } if(month==1){ cout<<"31 days"<<endl; } if(month==3){ cout<<"31 days"<<endl; }if(month==5){ cout<<"31 days"<<endl; }if(month==7){ cout<<"31 days"<<endl; }if(month==8){ cout<<"31 days"<<endl; }if(month==10){ cout<<"31 days"<<endl; } if(month==4){ cout<<"30 days"<<endl; }if(month==6){ cout<<"30 days"<<endl; }if(month==9){ cout<<"30 days"<<endl; }if(month==11){ cout<<"30 days"<<endl; } if(month==2){ if(!(year%100)&&!(year%400)){ cout<<"29 days"<<endl; } if(!(year%100)&&(year%400)){ cout<<"28 days"<<endl; } if((year%100)){ if(!(year%4)){ cout<<"29 days"<<endl; } } if((year%4)){ cout<<"28 days"<<endl; } } //Clean up and exit return 0; }
true
07949e1116f1b2c59c7de41ddc3ceac22d3c7382
C++
MaxKudravcev/KeyLogger
/KeyLogger/LogServer.cpp
UTF-8
730
2.734375
3
[]
no_license
#include <iostream> #include "TcpServer.h" std::wstring GetCurrentDirectory(std::wstring executable) { return executable.substr(0, executable.find_last_of(L'\\')); } int wmain(int argc, wchar_t* argv[]) { std::locale::global(std::locale("ru_RU.UTF-8")); int maxClients = std::stoi(argv[2]); std::wstring gLogDirectory = GetCurrentDirectory(argv[0]) + L"\\Logs\\"; TcpServer server(argv[1], maxClients, gLogDirectory); server.StartServer(); std::cout << "Type /quit to stop the server...\n"; std::string command; std::cin >> command; while (command != "/quit") { std::cout << "Unrecognized command.\n"; std::cin >> command; } std::cout << "Stopping the server...\n"; server.StopServer(); return 0; }
true
4d241521bb1dff7dceafe7e896c4eff3b136c644
C++
chiahsun/chiahsun.github.io
/_posts/src/2016-03-01-move-semantics-c++/solve1.cc
UTF-8
3,258
3.90625
4
[ "MIT" ]
permissive
#include <cstdlib> #include <cassert> #include <iostream> #include <utility> // for std::swap, std::move class Vector { int* _p_array; int _capacity, _size; public: Vector() { std::cout << "Call constructor" << std::endl; init(2); } Vector(size_t cap) { std::cout << "Call constructor 2" << std::endl; init(cap); } Vector(const Vector & rhs) { std::cout << "Call copy constuctor" << std::endl; init(rhs.capacity()); for (int i = 0; i < rhs.size(); ++i) _p_array[i] = rhs[i]; _size = rhs._size; } Vector(Vector && rhs) : Vector() { // IMPORTANT!: call default constructor to ensure that after swap, it is safe to desstruct std::cout << "Call move constuctor" << std::endl; swap(*this, rhs); } ~Vector() { std::cout << "Call destuctor" << std::endl; delete [] _p_array; _p_array = nullptr; _capacity = _size = 0; } Vector& operator = (Vector rhs) { std::cout << "Assignment operator" << std::endl; swap(*this, rhs); return *this; } friend void swap(Vector & x, Vector & y) { using std::swap; swap(x._p_array, y._p_array); swap(x._capacity, y._capacity); swap(x._size, y._size); } void init(size_t cap) { _p_array = new int [cap]; _capacity = cap; _size = 0; if (_p_array == nullptr) { printf("Out of memory"); assert(0); exit(1); } } int size() const { return _size; } int capacity() const { return _capacity; } void resize(size_t new_cap) { assert(size() <= new_cap); int* p_new_array = new int[new_cap]; _capacity = new_cap; for (int i = 0; i < size(); ++i) p_new_array[i] = _p_array[i]; delete [] _p_array; _p_array = nullptr; _p_array = p_new_array; } void push_back(int x) { if (size() == capacity()) resize(2*capacity()); _p_array[_size++] = x; } int& operator [] (int pos) { return _p_array[pos]; } int operator [] (int pos) const { return _p_array[pos]; } friend std::ostream & operator << (std::ostream & os, const Vector & v) { for (int i = 0; i < v.size(); ++i) os << ((i != 0) ? " " : "") << v[i]; return os; } }; Vector read_vector() { Vector v; int x; while (scanf("%d", &x) == 1) v.push_back(x); return v; } int main() { std::cout << "Return value optimization" << std::endl; // C++ Return value optimization // https://www.wikiwand.com/en/Return_value_optimization Vector v = read_vector(); std::cout << " v contains : " << v << std::endl; std::cout << "Copy vector" << std::endl; Vector v2(v); std::cout << " v2 contains : " << v2 << std::endl; Vector v3(std::move(v2)); std::cout << " v2 contains : " << v2 << std::endl; std::cout << " v3 contains : " << v3 << std::endl; Vector v4 = v3; std::cout << " v3 contains : " << v3 << std::endl; std::cout << " v4 contains : " << v4 << std::endl; Vector v5; v5 = v3; std::cout << " v3 contains : " << v3 << std::endl; std::cout << " v5 contains : " << v5 << std::endl; return 0; }
true
204553f463805e23c25df1ed97766bb3ed48456e
C++
rdkadiwala/BOokMyTicket
/main.cpp
UTF-8
1,646
2.71875
3
[ "MIT" ]
permissive
/* * Author : Ravi Kadiwala */ #include<iostream> #include<iomanip> #include<cstring> #include<fstream> #include<cstdlib> #include "Login.h" #include "MovieDetail.h" #include "PriceBookingDetail.h" #include "Admin.h" using namespace std; int main(){ while(1){ int choi; PriceBookingDetail bookt; MovieDetail m_list; system("cls"); cout<<"\t-----------------------------------------------------------------"<<endl; cout<<"\t\t\tWelcome to BOokMyTicket"<<endl; cout<<"\t-----------------------------------------------------------------\n"<<endl; cout<<"\t\t\t1.Login"<<endl; cout<<"\t\t\t2.Current Movies"<<endl; cout<<"\t\t\t3.Available Tickets"<<endl; cout<<"\t\t\t4.About Us"<<endl; cout<<"\t\t\tAny other for exit."<<endl; cout<<"\t-----------------------------------------------------------------\n"<<endl; cout<<"\t\tYour choice : ",cin>>choi; if(choi<1 || choi>4) break; switch(choi){ case 1 : book: bookt.login_menu(); break; case 2 : m_list.Seat_Chart(0); system("pause"); break; case 3 : if( m_list.Seat_Chart(1) ) goto book; else break; case 4 : about(); break; } } //Admin ad; //ad.addadmin(); }
true
31b6b639da67cb8f2cab0aea267466b87642aa50
C++
awerkamp/MSD_script
/env.h
UTF-8
876
2.5625
3
[]
no_license
// // Created by Awerkamp on 3/30/21. // #ifndef MSD_SCRIPT_ENV_H #define MSD_SCRIPT_ENV_H #include <cstdio> #include "pointer.h" //#include "val.cpp" #include "val.h" #include <string> #include <sstream> class Val; class Env { public: virtual PTR(Val) lookup(std::string find_name) = 0; static PTR(Env) empty; }; class EmptyEnv: public Env { public: EmptyEnv(); PTR(Val) lookup(std::string find_name) { throw std::runtime_error("free variable: " + find_name); } }; class ExtendedEnv: public Env { public: std::string name; PTR(Val) val; PTR(Env) rest; ExtendedEnv(std::string name, PTR(Val) val, PTR(Env) rest); PTR(Val) lookup(std::string find_name) { if (find_name == name) { return val; } else { return rest->lookup(find_name); } } }; #endif //MSD_SCRIPT_ENV_H
true
c2d24d0c1fb964e8c049249ea9c07ecd3f9af3aa
C++
AmadeusChan/worder
/include/WordBankImpl.h
UTF-8
1,865
3.125
3
[]
no_license
#ifndef WORD_BANK_IMPL_H #define WORD_BANK_IMPL_H #include <vector> #include "WordBank.h" #include "WordSet.h" template <typename T> class WordBankImpl : public WordBank<T> { WordSet<T>* m_word_set_; public: WordBankImpl(OperateFileStrategy* _m_operate_file_strategy_, string _path_, WordSet<T>* _m_word_set_); WordBankImpl(WordSet<T>* _m_word_set_); string convert_data_to_string(); void convert_string_to_data(string context); vector<T*> get_words(); T* find_word_by_context(string context); void add_word(T word); void remove_word(T* word); ~WordBankImpl(); }; template<typename T> WordBankImpl<T>::WordBankImpl(OperateFileStrategy* _m_operate_file_strategy_, string _path_, WordSet<T>* _m_word_set_) : WordBank<T>(_m_operate_file_strategy_, _path_), m_word_set_(_m_word_set_){} template<typename T> WordBankImpl<T>::WordBankImpl(WordSet<T>* _m_word_set_) : WordBank<T>(), m_word_set_(_m_word_set_){} template<typename T> WordBankImpl<T>::~WordBankImpl() { //delete m_word_set_; } template < typename T > string WordBankImpl < T > :: convert_data_to_string( ) { return m_word_set_ -> convert_data_to_string( ) ; } template < typename T > void WordBankImpl < T > :: convert_string_to_data( string context ) { m_word_set_ -> convert_string_to_data( context ) ; } template < typename T > vector < T* > WordBankImpl < T > :: get_words( ) { return m_word_set_ -> get_words( ) ; } template < typename T > T* WordBankImpl < T > :: find_word_by_context( string context ) { return m_word_set_ -> find_word_by_context( context ) ; } template < typename T > void WordBankImpl < T > :: add_word( T word ) { m_word_set_ -> add_word( word ) ; } template < typename T > void WordBankImpl < T > :: remove_word( T* word ) { m_word_set_ -> remove_word( word ) ; } #endif
true
395f7091d1e66c07ae4139654b6702d1fe94bb52
C++
MAYUE-92/MY-ssh
/C++/c++study/Circle/BorderCircle.h
UTF-8
272
2.53125
3
[]
no_license
#include "Circle.h"//声明基类Circle class BorderCircle:public Circle //公有继承 { public: double w; //宽度 double InnerArea();//求内圆面积 double BorderArea();//圆环面积 void Input();//输入半径和圆环宽度 };
true
d61c6058dd96a6e2e85f5a32ba5aaf0a41213808
C++
goinproduction/moto-manager
/Source/cars-manager/ORDER.cpp
UTF-8
4,356
3
3
[]
no_license
#include "ORDER.h" ORDER::ORDER() { this->totalPrice = 0; } ORDER::~ORDER() { } string ORDER::getCustomerPhone() { return this->customerPhone; } void ORDER::setCustomerPhone(string phone) { this->customerPhone = phone; } void ORDER::setTotalRevenue(__int64 revenue) { this->totalRevenue = revenue; } __int64 ORDER::getTotalRevenue() { return this->totalRevenue; } void ORDER::setTotalProfit(__int64 profit) { this->totalProfit = profit; } __int64 ORDER::getTotalProfit() { return this->totalProfit; } void ORDER::setProductLists(vector<ORDER*> pd) { this->productLists = pd; } vector<ORDER*> ORDER::getProductLists() { return this->productLists; } void ORDER::setOrderNumber(string orn) { this->orderNumber = orn; } string ORDER::getOrderNumber() { return this->orderNumber; } string ORDER::getOrderDate() { return this->orderDate; } void ORDER::setProductName(string pd) { this->productName = pd; } string ORDER::getProductName() { return this->productName; } void ORDER::setAmount(int am) { this->amount = am; } int ORDER::getAmount() { return this->amount; } void ORDER::setPrice(__int64 pr) { this->price = pr; } __int64 ORDER::getPrice() { return this->price; } void ORDER::setTotalPrice(__int64 tt) { this->totalPrice = tt; } __int64 ORDER::getTotalPrice() { return this->totalPrice; } void ORDER::Insert() { bool isValid; do { cout << "Ngay tao don (dd/mm/yyyy): "; getline(cin, this->orderDate); stringstream orderDateStr(this->orderDate); vector<string> dateTime; string segment; while (getline(orderDateStr, segment, '/')) { dateTime.push_back(segment); } string isMonthValid = dateTime[1]; string isYearValid = dateTime[2]; if ((isMonthValid == "01" || isMonthValid == "02" || isMonthValid == "03" || isMonthValid == "04" || isMonthValid == "05" || isMonthValid == "06" || isMonthValid == "07" || isMonthValid == "08" || isMonthValid == "09" || isMonthValid == "10" || isMonthValid == "11" || isMonthValid == "12") && stoi(isYearValid) >= 2021) { isValid = true; } else { isValid = false; } if (!isValid) { cout << "Dinh dang sai, vui long nhap theo dinh dang (dd/mm/yyyy)!" << endl; } } while (!isValid); cout << "Ten khach hang: "; getline(cin, this->customerName); cout << "Dia chi: "; getline(cin, this->customerAddr); } void ORDER::Display() { cout << "\t\t============>>CHI TIET DON HANG<<============" << endl; cout << "Ma don hang: " << this->orderNumber << endl; cout << "Ngay tao don: " << this->orderDate << endl; cout << "Ten khach hang: " << this->customerName << endl; cout << "Dia chi: " << this->customerAddr << endl; cout << "So dien thoai: " << this->customerPhone << endl; } void ORDER::DisplayProductList() { cout << "Ten san pham: " << this->getProductName() << endl; cout << "Gia ban: " << this->formatCurrency(this->getPrice()) << " VND" << endl; cout << "So luong: " << this->getAmount() << endl; cout << "----------------------------" << endl; } void ORDER::WriteToFile(string& orderNumbs) { string file_path = "DONHANG/CHITIETDONHANG_" + orderNumbs + ".txt"; ofstream file_out(file_path); file_out << "\t\t============>>CHI TIET DON HANG<<============" << endl; file_out << "Ma don hang: " << this->orderNumber << endl; file_out << "Ngay tao don: " << this->orderDate << endl; file_out << "Ten khach hang: " << this->customerName << endl; file_out << "Dia chi: " << this->customerAddr << endl; file_out << "So dien thoai: " << this->customerPhone << endl; file_out.close(); } void ORDER::WriteProductToFile(string& orderNumbs) { string file_path = "DONHANG/CHITIETDONHANG_" + orderNumbs + ".txt"; ofstream file_out(file_path, ios::app); file_out << "Ten san pham: " << this->getProductName() << endl; file_out << "Gia ban: " << this->formatCurrency(this->getPrice()) << " VND" << endl; file_out << "So luong: " << this->getAmount() << endl; file_out << "----------------------------" << endl; file_out.close(); } string ORDER::formatCurrency(long long val) { string ans = ""; string num = to_string(val); int count = 0; for (int i = num.size() - 1; i >= 0; i--) { count++; ans.push_back(num[i]); if (count == 3) { ans.push_back(','); count = 0; } } reverse(ans.begin(), ans.end()); if (ans.size() % 4 == 0) { ans.erase(ans.begin()); } return ans; }
true
8acdf44704ff1429746cb196b23685881a394acb
C++
lc19890306/Exercise
/leetcode/Insertion_Sort_List.cc
UTF-8
1,328
3.34375
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* insertionSortList(ListNode* head) { if (head == nullptr) return head; auto prev_i(head); auto i(head->next); ListNode *prev_head = new ListNode(INT_MIN); prev_head->next = head; auto prev_j(prev_head); auto j(prev_head->next); while (i) { // Speedup trick: if current i->val < previously inserted i->val, // we can directly search from the place where we previously inserted i (i->next actually) if (prev_j->val > i->val) { // prev_j equals the previously inserted i prev_j = prev_head; j = prev_j->next; } while (j != i && j->val <= i->val) { prev_j = j; j = j->next; } if (j != i) { prev_i->next = i->next; prev_j->next = i; i->next = j; prev_j = i; i = prev_i->next; } else { prev_i = i; i = i->next; } } return prev_head->next; } };
true
17c46cc45a9f26e50390120c13f5091b4dbc9961
C++
adelliinaa/hyped-2017
/master-slave-comms/slave/slave.cpp
UTF-8
2,205
2.8125
3
[]
no_license
#include <chrono> #include <iostream> #include <string> #include <vector> #include "drivers/i2c.hpp" #include "drivers/vl6180.hpp" #include "NetworkSlave.hpp" #define SENSOR1_PIN PIN4 #define SENSOR2_PIN PIN24 NetworkSlave master; const int SLAVE_PORT = 11999; const std::string NAME = "Slave:1"; const bool continuous_mode = true; std::vector<Vl6180*> sensors; //Create an I2C instance to represent the bus I2C i2c; // Create factory to produce sensor drivers for that bus Vl6180Factory& factory = Vl6180Factory::instance(&i2c); int proxiMap(std::string command) { if (command == "proxi-ground-front") { return 0; } } inline uint64_t timestamp() { using namespace std::chrono; return duration_cast<microseconds>( steady_clock::now().time_since_epoch()).count(); } void * loop(void * m) { pthread_detach(pthread_self()); while(1) { // Listen for commands from master std::string command = master.getMessage(); if (command.substr(0, 6) == "proxi-") { std::string readings = NAME + "\n"; // populate with readings from proxy int dist = sensors[proxiMap(command)]->get_distance(); std::string res = std::to_string(dist); std::cout << "Message:" << command << std::endl; master.Send(res); // send the readings master.clean(); } if (command == "") { // check custom commands here } } usleep(1000); master.detach(); } int main() { // Produce driver instance for the sensor with GPIO0 connected to specified pin Vl6180& sensor_ref = factory.make_sensor(SENSOR1_PIN); // Store pointer to the driver instance sensors.push_back(&sensor_ref); // Uncoment the following line and possibly add more to use more sensors //sensors.push_back( &(factory.make_sensor(SENSOR2_PIN)) ); for (unsigned int i = 0; i < sensors.size(); ++i) { //std::this_thread::sleep_for(std::chrono::seconds(3)); sensors[i]->turn_on(); sensors[i]->set_intermeasurement_period(10); sensors[i]->set_continuous_mode(continuous_mode); } pthread_t msg; master.setup(SLAVE_PORT); if( pthread_create(&msg, NULL, loop, (void *)0) == 0) { master.receive(); } return 0; }
true
9062576d80ec0e75c9df1f24daca2dcd30c94bc8
C++
calrose/Example
/datafetcher.hpp
UTF-8
2,654
2.8125
3
[]
no_license
#ifndef DATASFETCHER_H #define DATASFETCHER_H #include <sstream> #include <cstdlib> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <curlpp/Exception.hpp> #include <iostream> int simpleTest(std::ostream& output) { const char *url = "https://csi330-testingdemo.herokuapp.com/api"; try { curlpp::Cleanup myCleanup; curlpp::Easy request; request.setOpt(new curlpp::options::Url(url)); output << request; return EXIT_SUCCESS; } catch (curlpp::LogicError &e) { std::cerr << e.what() << std::endl; } catch (curlpp::RuntimeError &e) { std::cerr << e.what() << std::endl; } return EXIT_FAILURE; } int getList(std::ostream& output) { const char *url = "https://csi330-testingdemo.herokuapp.com/api/mongo"; try { curlpp::Cleanup myCleanup; curlpp::Easy request; request.setOpt(new curlpp::options::Url(url)); output << request; return EXIT_SUCCESS; } catch (curlpp::LogicError &e) { std::cerr << e.what() << std::endl; } catch (curlpp::RuntimeError &e) { std::cerr << e.what() << std::endl; } return EXIT_FAILURE; } int addItem(std::string data) { const char *url = "https://csi330-testingdemo.herokuapp.com/api/mongo"; try { curlpp::Cleanup myCleanup; curlpp::Easy request; std::list<std::string> header; header.push_back("Content-Type: application/json"); request.setOpt(new curlpp::options::Url(url)); request.setOpt(new curlpp::options::HttpHeader(header)); request.setOpt(new curlpp::options::CustomRequest{"POST"}); request.setOpt(new curlpp::options::PostFields(data)); request.setOpt(new curlpp::options::PostFieldSize(data.length())); request.perform(); return EXIT_SUCCESS; } catch (curlpp::LogicError &e) { std::cerr << e.what() << std::endl; } catch (curlpp::RuntimeError &e) { std::cerr << e.what() << std::endl; } return EXIT_FAILURE; } int removeItem(std::string data) { const std::string url = "https://csi330-testingdemo.herokuapp.com/api/mongo/" + data; try { curlpp::Cleanup myCleanup; curlpp::Easy request; request.setOpt(new curlpp::options::Url(url)); request.setOpt(new curlpp::options::CustomRequest{"DELETE"}); request.perform(); return EXIT_SUCCESS; } catch (curlpp::LogicError &e) { std::cerr << e.what() << std::endl; } catch (curlpp::RuntimeError &e) { std::cerr << e.what() << std::endl; } return EXIT_FAILURE; } #endif
true
a67456e439b413a7eae10783d9898573b6ce20e8
C++
Patrikvs94/OpenGL-Project-Tnm061
/ballin/lightsource.cpp
UTF-8
1,109
2.75
3
[]
no_license
#include "lightsource.hpp" lightsource::lightsource() { pos=new cordinate; pos->x=0.0f; pos->y=0.0f; pos->z=0.0f; tex.createTexture("textures/red.tga"); norm.createTexture("textures/red_norm.tga"); sphere.createSphere(0.5f, 2); } lightsource::~lightsource() { delete pos; } void lightsource::setX(float x) { pos->x=x; } void lightsource::setY(float y) { pos->y=y; } void lightsource::setZ(float z) { pos->z=z; } cordinate* lightsource::cordinates() { return pos; } //sends lightsource to shader void lightsource::setupLight(GLint location_l) { glUniform3fv(location_l, 1, (const GLfloat*)pos); } //renders a "spehre" at location of lightsource void lightsource::renderlight(MatrixStack& MV, GLint location_MV) { MV.push(); MV.translate(pos->x, pos->y, pos->z); glUniformMatrix4fv( location_MV, 1, GL_FALSE, MV.getCurrentMatrix() ); glBindTexture(GL_TEXTURE_2D, tex.texID); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, norm.texID); glActiveTexture(GL_TEXTURE0); sphere.render(); MV.pop(); }
true
3ea39bdea0fdf7c07ba973b04caba1e21347e278
C++
Svaard/Operating-Systems
/Lab 13/rcvmes.cpp
UTF-8
1,266
2.609375
3
[]
no_license
#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <iostream> #include <errno.h> #include <string.h> #include <unistd.h> using namespace std; int main () { int myqueue; key_t mykey; int status; int msgsz = 10; struct Mybuf { long mtype; char mtext[2]; }; struct Mybuf buf; mykey = ftok( "fifo.c" , 'a' ); myqueue = msgget(mykey, IPC_CREAT | 0600 ); if ( -1 == myqueue) { printf("error in msgget"); return 1; } for(int i = 0; i < 5; i++){ /* no special instructions, no flags */ if(i>0){ sleep(2); } status = msgrcv(myqueue, (struct msgbuf *)&buf, msgsz, 0, 0); char a = buf.mtext[0] - '0'; if ( -1 == status) { printf("error in msgrcv"); return 1; } status = msgrcv(myqueue, (struct msgbuf *)&buf, msgsz, 0, 0); char b = buf.mtext[0] - '0'; if(-1 == status){ printf("error in msgrcv"); return 1; } char c = a * b; const char* answer = &c; //printf("%c\n", answer); cout << *answer; strcpy(buf.mtext, answer); status = msgsnd(myqueue, (struct msgbuf *)&buf, msgsz, 0); if( -1 == status) { printf("error in msgsnd %s \n", strerror(errno) ); return 1; } } }
true
fc70192781d37538634f081c48022eb771288797
C++
lnicosia/Piscine-CPP
/day04/ex02/AssaultTerminator.hpp
UTF-8
584
2.5625
3
[]
no_license
#ifndef ASSAULTTERMINATOR_HPP # define ASSAULTTERMINATOR_HPP #include "ISpaceMarine.hpp" class AssaultTerminator : public ISpaceMarine { public: AssaultTerminator(void); AssaultTerminator(AssaultTerminator const &instance); AssaultTerminator &operator=(AssaultTerminator const &rhs); virtual ~AssaultTerminator(void); virtual ISpaceMarine* clone() const; virtual void battleCry() const; virtual void rangedAttack() const; virtual void meleeAttack() const; private: }; #endif
true
9603a03b601b45e5be7584d65331301b0d85b430
C++
jamesus95/Cpp
/lab4-343/lab4headers/borrow.h
UTF-8
3,673
3.03125
3
[]
no_license
//-------------------- Metadata -------------------- /** * @file borrow.h * Purpose: Header file for class Borrow * * @author James Murphree <murphs95@uw.edu> * @author Vu Dinh <vdinh143@uw.edu> * @date June 06 2014 * @copyright WTFPLv2.1 * * Note: Private helpers are typically found under the routine(s) * that uses them. *///----------------------------------------------- //--------------- Class Description ----------------- /** * @class Borrow * Purpose: Contains the logic for the Borrow routine, * as well as references to objects and data it * needs to perform the rental process. * This routine is a class instead of a function * for extensibility, following the * OOP Command Design Pattern. * * Inherit from: Transaction * Inherited by: <none> * *///------------------------------------------------- #ifndef BORROW_H #define BORROW_H #include "transaction.h" class Borrow : public Transaction { friend ostream& operator << (ostream&, const Borrow&); public: //---------- constructor/destructor --------------------------------------- /** * @brief creates a borrow transaction * @details creates a borrow with the given ID * * @param char : transaction type character * @param int : transaction ID */ Borrow(char, int); /** * @brief destructor for Borrow * @details destroys Borrow instance */ ~Borrow(); //---------- executer ----------------------------------------------------- /** * @brief processes the Borrow Transaction * @details makes the the customer contained in the Transaction borrow * the Movie contained in the Transaction * * @param Inventory* : not used in Borrow Transaction * @return bool : if transaction was successful */ bool process(Inventory*); // logic for the Borrow routine //---------- setter ------------------------------------------------------- /** * @brief sets the data for the borrow transaction * @details sets the Customer and Item in the Borrow Transaction * * @param istream& : input to get data out of * @param Inventory& : to search for Item in * @param MovieFactory& : to create reference Movie from * @param BinTree& : to search for Customer in */ void setData(istream&, Inventory&, MovieFactory&, BinTree&); /** * @brief sets the Borrow Transactions Customer * @details sets the Borrow Transactions Customer from the input * * @param istream& : input to get data from * @param BinTree& : to search for Customer in */ void setCustomer(istream&, BinTree&); /** * @brief sets the Borrow Transactions Item * @details sets the Borrow Transactions Item from the input * * @param istream& : input to get data from * @param Inventory& : to search for Item in * @param MovieFactory& : to create reference Movie to search for */ void setItem(istream&, Inventory&, MovieFactory&); //---------- initializer -------------------------------------------------- /** * @brief creates an Empty Borrow Transaction * @details creates an Empty Borrow Transaction for generic Transaction * creation * * @param int : Borrow Transaction ID * @return Transaction* : Transaction pointer containing the new Borrow */ Transaction* createEmptyInstance(int) const; //---------- getter ------------------------------------------------------- /** * @brief formats the Borrow for printing * @details formats the Borrow Transactions data and prints it to * the input ostream * * @param osteram& : stream to output to */ void formatOutput(ostream&) const; }; #endif
true
e21459f8ee6987ac14c243fca066f0c9a74f799a
C++
sphanlung/Cpp_Primer_5th_Edition
/Ex_1_4.cpp
UTF-8
1,182
3.28125
3
[]
no_license
/////////////////////////////////////////////////////////////////////////////////////// // Name: Ex_1_4.cpp // // // // Author: Sergio PL // // http://github.com/MrPotati/ // // // // Description: C++ Primer 5th exercise solutions // // // /////////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" // Comment out if not using Visual Studio #include <iostream> int main() { std::cout << "Enter two numbers:" << std::endl; // Print message int v1 = 0, v2 = 0; // Declare v1,v2 as integers std::cin >> v1 >> v2; // Insert values for v1,v2 std::cout << "The product of " << v1 << " and " << v2 << " is " << v1 * v2 << std::endl; // print product of v1,v2 std::getchar(); //Prevents Windows Debugger from closing std::getchar(); return 0; }
true
7d0c9a621566684ae85e9574e5a855320b5698f9
C++
arin6395/c-programs
/KFUNC.cpp
UTF-8
1,100
2.890625
3
[]
no_license
/* * KFUNC.cpp * * Created on: 07-Nov-2015 * Author: arindam * #include<iostream> #include<string.h> #include<stdlib.h> #include<stdio.h> #include<cmath> #include<iomanip> using namespace std; typedef unsigned long long int lli; #define FOR(i,a,b) for(int i=a;i<b;i++) lli f(lli n) { lli sum=0; while(n) { sum+=n%10; n/=10; } if(sum>9) return f(sum); else return sum; } int main() { int t; cin>>t; while(t--) { lli a,d,l,r,sum=0,start=0,val=0,num=0,total=0,i; cin>>a>>d>>l>>r; val=f(d); // d=f(d); //cout<<a<<" "<<val<<endl; if(val==0||val==9) total=(r-l+1)*f(a); else if(val==3||val==6) { sum=f(a+d)+f(a+d+d)+f(a+2*d+d); num=(r-l+1)/3; total=num*sum; i=l+num*3; start=f(a+(i-1)*f(d)); while(i<=r) { //cout<<i<<endl; total+=start; start=f(start+d); i++; } } else { sum=45; num=(r-l+1)/9; total=num*sum; i=l+num*9; start=f(a+(i-1)*f(d)); while(i<=r) { //cout<<i<<endl; total+=start; start=f(start+d); i++; } } cout<<total<<endl; } return 0; } */
true
fa8aced007d4f4f7064d0bbbfbf58f170cbff177
C++
SiddharthMishraPersonal/InterviewPreperation
/DataStructures/Docs/PriorityQueueWithLinkedList.cpp
ISO-8859-1
5,040
3.9375
4
[ "Unlicense" ]
permissive
// An example of simple priority queue using linked lists. // Priority depends on identity number. Small identity number has greater priority. // If identity numbers are equal. Then FIFO rules are used. #include <iostream> #include <cstring> #include <iomanip> using namespace std; struct DAT { int id; char fullname[50]; double salary; }; struct NODE { DAT data; Node *N; Node *P; Node(const int i , const char *f, const double s ) { data.id = i; strcpy(data.fullname,f); data.salary = s; N = NULL; P = NULL; } }; class PQueueLinkedList { private: NODE *front; NODE *back; public: PQueueLinkedList(){front = NULL;back = NULL;} ~PQueueLinkedList(){destroyList();} void enqueue(NODE *); NODE* dequeue(); void destroyList(); }; void PQueueLinkedList::enqueue(NODE *n) { if(front == NULL)//queue has one node. { front = n; back = n; } else//queue has more than one node. { NODE* temp = front; if( n->data.id > temp->data.id)//New node id's is greater than all others. { front->P = n; n->N = front; front = n; } else { //Search for the position for the new node. while( n->data.id < temp->data.id) { if(temp->N == NULL) break; temp = temp->N; } //New node id's smallest than all others if(temp->N == NULL && n->data.id < temp->data.id) { back->N = n; n->P = back; back = n; } else//New node id's is in the medium range. { temp->P->N = n; n->P = temp->P; n->N = temp; temp->P = n; } } } } NODE* PQueueLinkedList::dequeue() { NODE *temp; if( back == NULL )//no nodes return NULL; else if(back->P == NULL)//there is only one node { NODE * temp2 = back; temp = temp2; front = NULL; back = NULL; delete temp2; return temp; } else//there are more than one node { NODE * temp2 = back; temp = temp2; back = back->P; back->N = NULL; delete temp2; return temp; } } void PQueueLinkedList::destroyList() { while(front != NULL) { NODE *temp = front; front = front->N; delete temp; } } void disp(NODE *m) { if( m == NULL ) { cout << "\nQueue is Empty!!!" << endl; } else { cout << "\nId No. : " << m->data.id; cout << "\nFull Name : " << m->data.fullname; cout << "\nSalary : " << setprecision(15) << m->data.salary << endl; } } int main() { PQueueLinkedList *Queue = new PQueueLinkedList(); NODE No1( 101, "Aaaaa Nnnnnnn Mmmmm", 123456.4758 ); NODE No2( 102, "Bbbbb Ddddd Ssssss", 765432.9488 ); NODE No3( 103, "wwww nnnnn www eeee", 366667.3456 ); NODE No4( 104, "Bsrew hytre dfresw", 9876544.0432 ); Queue->enqueue(&No4); Queue->enqueue(&No3); Queue->enqueue(&No1); Queue->enqueue(&No2); disp(Queue->dequeue()); disp(Queue->dequeue()); disp(Queue->dequeue()); disp(Queue->dequeue()); disp(Queue->dequeue()); delete Queue; return 0; } /* Program's output ********************** Id No. : 101 Full Name : Aaaaa Nnnnnnn Mmmmm Salary : 123456.4758 Id No. : 102 Full Name : Bbbbb Ddddd Ssssss Salary : 765432.9488 Id No. : 103 Full Name : wwww nnnnn www eeee Salary : 366667.3456 Id No. : 104 Full Name : Bsrew hytre dfresw Salary : 9876544.0432 Queue is Empty!!! Process returned 0 (0x0) execution time : 0.015 s Press any key to continue. */
true
a2899febfc7c87fe272bd5a50e69f60832c53bb5
C++
SwReliab/gof4srm
/src/KS_arma.cpp
UTF-8
3,090
3.140625
3
[ "MIT" ]
permissive
#include <Rcpp.h> using namespace Rcpp; //' Compute P(D->d-) for the generalized KS statistic //' //' This is an experimental function instead of compute_Pdminus. //' This is not used yet. //' //' @param ctime A sequence represents time slots (bins) //' @param count A sequence indicates the number of samples falls int a bin //' @param dminus A value of d- //' @param cdf A function of CDF. It is allowd to get a closure. //' @param solve A function to solve a linear equation. //' @return A value of the probability // [[Rcpp::export]] List compute_Pdminus_arma(NumericVector ctime, IntegerVector count, double dminus, Function cdf, Function solve) { int n = sum(count); int jmax = n * (1 - dminus); // step 1 NumericVector c(jmax+1); NumericVector cp = cdf(ctime); for (int j=0; j<=jmax; j++) { double p = dminus + (double) j / n; for (int i=0; i<ctime.length(); i++) { if (cp[i] >= p) { c[j] = 1 - cp[i]; break; } } } // step 2 NumericMatrix B(jmax+1,jmax+1); NumericVector one(jmax+1); for (int j=0; j<=jmax; j++) { one(j) = 1; double x = 1; for (int i=j; i<=jmax; i++) { B(i,j) = x; x *= c(j) * (i+1) / (i-j+1); } } NumericVector b = solve(Named("a")=B, Named("b")=one); // step 3 double prob = 0.0; double binom = 1.0; for (int j=0; j<=jmax; j++) { prob += binom * std::pow(c(j), n-j) * b(j); binom *= (double) (n-j) / (j+1); } return List::create(Named("B")=B, Named("prob")=prob); } //' Compute P(D+>d+) for the generalized KS statistic //' //' This is an experimental function instead of compute_Pdplus. //' This is not used yet. //' //' @param ctime A sequence represents time slots (bins) //' @param count A sequence indicates the number of samples falls int a bin //' @param dplus A value of d+ //' @param cdf A function of CDF. It is allowd to get a closure. //' @param solve A function to solve a linear equation. //' @return A value of the probability // [[Rcpp::export]] List compute_Pdplus_arma(NumericVector ctime, IntegerVector count, double dplus, Function cdf, Function solve) { int n = sum(count); int jmax = n * (1 - dplus); // step 1 // step 1 NumericVector c(jmax+1); NumericVector cp = cdf(ctime); double cp0 = 0; for (int j=0; j<=jmax; j++) { double p = 1 - dplus - (double) j / n; for (int i=0; i<ctime.length(); i++) { if (cp[i] >= p) { c[j] = cp0; break; } cp0 = cp[i]; } } // step 2 NumericMatrix B(jmax+1,jmax+1); NumericVector one(jmax+1); for (int j=0; j<=jmax; j++) { one(j) = 1; double x = 1; for (int i=j; i<=jmax; i++) { B(i,j) = x; x *= c(j) * (i+1) / (i-j+1); } } NumericVector b = solve(Named("a")=B, Named("b")=one); // step 3 double prob = 0.0; double binom = 1.0; for (int j=0; j<=jmax; j++) { prob += binom * std::pow(c(j), n-j) * b(j); binom *= (double) (n-j) / (j+1); } return List::create(Named("B")=B, Named("b")=b, Named("prob")=prob); }
true
2ff46974ea7d59d07c4862a9be1ea964fb10404b
C++
czfshine/ComputerGraphics
/src/basic/point.cpp
UTF-8
920
3.21875
3
[ "MIT" ]
permissive
//基础:利用opengl绘制一个点 // Created by czfshine on 19-2-25. // #include <GL/glut.h> /** * 主要的绘制函数 * 因为这个程序是静态而且没有交互,所以只要这一个函数就行 * @return */ void Display(void) { glClear(GL_COLOR_BUFFER_BIT); glPointSize(5.0f); //大小 glBegin(GL_POINTS); //表明开始画点 glVertex2f(0.5f,0.8f);//屏幕分为x(-1,1)y(-1,1)的矩形 glEnd(); //表明结束绘画点,也就是可以画别的东西了 glFlush(); //注意,和写文件一样有缓冲区的,要更新才能真正的显示 } int main(int argc,char* argv[]) { //一些初始化窗口和opengl的函数 glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGB); glutInitWindowPosition(200,200); glutInitWindowSize(800,800); glutCreateWindow("The First Point"); glutDisplayFunc(&Display); glutMainLoop(); return 0; }
true
fbd3d612b2e5ead154cd08a44b11cd1f296311b0
C++
averkhaturau/Tarificator
/src/Master/Others/Всякие тесты и прочие рудименты/MashineNameControl.h
WINDOWS-1251
1,184
2.640625
3
[ "MIT" ]
permissive
#ifndef __MASHINENAMECONTROL_H__ #define __MASHINENAMECONTROL_H__ #include <string> #include "LineControl.h" class CMashineNameControl : public CLineControl { protected: std::string m_sMashineName; // . Create. LOGFONT m_LogFont; CFont m_Font; // COLORREF m_TextColor; // DWORD m_dwLeftSpace; //{{AFX_MSG(CMashineNameControl) afx_msg void OnPaint(); // Font afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: // CMashineNameControl(); // virtual ~CMashineNameControl(); // std::string* GetMashineName() {return &m_sMashineName;}; LOGFONT* GetLogFont() {return &m_LogFont;}; void SetLeftSpace(DWORD dwNew) {m_dwLeftSpace = dwNew;}; DWORD GetLeftSpace() {return m_dwLeftSpace;}; void SetTextColor(COLORREF New) {m_TextColor = New;}; COLORREF GetTextColor() {return m_TextColor;}; }; #endif // __MASHINENAMECONTROL_H__
true
2e81633b54b01ad110ce10e85f76c9f981f2f90a
C++
tuannt8/tuan-ercp
/ERCP_interac_line_point/include/Graphics/TopologyModifier.cpp
UHC
11,022
2.765625
3
[]
no_license
#include "stdafx.h" #include "TopologyModifier.h" TopologyModifier::TopologyModifier(void) { } TopologyModifier::~TopologyModifier(void) { } void TopologyModifier::addPoints(TopologyContainer* container, std::vector<Vec3f>* points) { for(int i=0;i<points->size();i++) addPoint(container, (*points)[i]); } void TopologyModifier::addPoints(TopologyContainer* container, std::vector<Vec3f>& points) { for(int i=0;i<points.size();i++) addPoint(container, points[i]); } void TopologyModifier::addPoints( TopologyContainer* container, std::vector<Vec3f>* point0, std::vector<Vec3f>* points ) { for(int i=0;i<points->size();i++) addPoint(container, point0->at(i), points->at(i)); } void TopologyModifier::addPoint( TopologyContainer* container, Vec3f _point0, Vec3f _point ) { std::vector<Vec3f>* point0=container->point0(); std::vector<Vec3f>* point=container->point(); point0->push_back(_point0); point->push_back(_point); //update topology information std::vector<std::vector<int>>* pointsAroundPoint=container->pointsAroundPoint(); std::vector<std::vector<int>>* edgesAroundPoint=container->edgesAroundPoint(); std::vector<std::vector<int>>* facesAroundPoint=container->facesAroundPoint(); pointsAroundPoint->resize(point->size()); edgesAroundPoint->resize(point->size()); facesAroundPoint->resize(point->size()); } void TopologyModifier::addPoint(TopologyContainer* container, Vec3f _point) { std::vector<Vec3f>* point0=container->point0(); std::vector<Vec3f>* point=container->point(); point0->push_back(_point); point->push_back(_point); //update topology information std::vector<std::vector<int>>* pointsAroundPoint=container->pointsAroundPoint(); std::vector<std::vector<int>>* edgesAroundPoint=container->edgesAroundPoint(); std::vector<std::vector<int>>* facesAroundPoint=container->facesAroundPoint(); pointsAroundPoint->resize(point->size()); edgesAroundPoint->resize(point->size()); facesAroundPoint->resize(point->size()); } void TopologyModifier::addEdges(TopologyContainer* container, std::vector<Vec2i>* edges) { for(int i=0;i<edges->size();i++) addEdge(container, (*edges)[i]); } void TopologyModifier::addEdges(TopologyContainer* container, std::vector<Vec2i>& edges) { std::vector<std::vector<int>>* pointAroundPoint=container->pointsAroundPoint(); for(int i=0;i<edges.size();i++) { Vec2i edge=edges[i]; addEdge(container, edges[i]); } } void TopologyModifier::addEdge(TopologyContainer* container, Vec2i _edge) { std::vector<Vec2i>* edge=container->edge(); edge->push_back(_edge); //update topology information std::vector<std::vector<int>>* pointsAroundPoint=container->pointsAroundPoint(); (*pointsAroundPoint)[_edge[0]].push_back(_edge[1]); (*pointsAroundPoint)[_edge[1]].push_back(_edge[0]); std::vector<std::vector<int>>* edgesAroundPoint=container->edgesAroundPoint(); (*edgesAroundPoint)[_edge[0]].push_back(edge->size()-1); (*edgesAroundPoint)[_edge[1]].push_back(edge->size()-1); std::vector<std::vector<int>>* facesAroundEdge=container->facesAroundEdge(); facesAroundEdge->resize(edge->size()); } void TopologyModifier::addFaces(TopologyContainer* container, std::vector<Vec3i>* faces, int preNbPoint) { for(int i=0;i<faces->size();i++) addFace(container, (*faces)[i], preNbPoint); } void TopologyModifier::addFaces(TopologyContainer* container, std::vector<Vec3i>& faces, int preNbPoint) { for(int i=0;i<faces.size();i++) addFace(container, faces[i], preNbPoint); } void TopologyModifier::addFace(TopologyContainer* container, Vec3i _face, int preNbPoint) { std::vector<Vec3i>* face=container->face(); std::vector<Vec2i>* edge=container->edge(); face->push_back(_face); //update topology information //faces around point std::vector<std::vector<int>>* facesAroundPoint=container->facesAroundPoint(); for(int i=0;i<3;i++) (*facesAroundPoint)[_face[i]].push_back(face->size()-1); //edges in face std::vector<std::vector<int>>* edgesInFace=container->edgesInFace(); std::vector<std::vector<int>>* edgesAroundPoint=container->edgesAroundPoint(); edgesInFace->resize(face->size()); for(int i=0;i<3;i++) { Vec2i edge1; if(_face[i]<_face[(i+1)%3]) edge1=Vec2i(_face[i], _face[(i+1)%3]); else edge1=Vec2i(_face[(i+1)%3], _face[i]); bool flag=false; int edgeIdx=-1; for(int j=0;j<(*edgesAroundPoint)[edge1[0]].size();j++) { edgeIdx=(*edgesAroundPoint)[edge1[0]][j]; Vec2i edge2=(*edge)[edgeIdx]; if(edge1==edge2) { flag=true; break; } } if(flag) (*edgesInFace)[face->size()-1].push_back(edgeIdx); else { addEdge(container, edge1); (*edgesInFace)[face->size()-1].push_back(edge->size()-1); } /*if(edge1[0]>=preNbPoint) { bool flag=false; int edgeIdx=-1; for(int j=0;j<(*edgesAroundPoint)[edge1[0]].size();j++) { edgeIdx=(*edgesAroundPoint)[edge1[0]][j]; Vec2i edge2=(*edge)[edgeIdx]; if(edge1==edge2) { flag=true; break; } } if(flag) (*edgesInFace)[face->size()-1].push_back(edgeIdx); else { addEdge(container, edge1); (*edgesInFace)[face->size()-1].push_back(edge->size()-1); } } else if(edge1[1]>=preNbPoint) { // edge ̹ ߰ Ǿ ˻ bool flag=false; int edgeIdx=-1; for(int j=0;j<(*edgesAroundPoint)[edge1[0]].size();j++) { edgeIdx=(*edgesAroundPoint)[edge1[0]][j]; Vec2i edge2=(*edge)[edgeIdx]; if(edge1==edge2) { flag=true; break; } } if(flag) (*edgesInFace)[face->size()-1].push_back(edgeIdx); else { addEdge(container, edge1); (*edgesInFace)[face->size()-1].push_back(edge->size()-1); } } else { // edge index ã´ int edgeIdx=-1; for(int j=0;j<(*edgesAroundPoint)[edge1[0]].size();j++) { edgeIdx=(*edgesAroundPoint)[edge1[0]][j]; Vec2i edge2=(*edge)[edgeIdx]; if(edge1==edge2) break; } (*edgesInFace)[face->size()-1].push_back(edgeIdx); }*/ } //faces around edge std::vector<std::vector<int>>* facesAroundEdge=container->facesAroundEdge(); for(int i=0;i<3;i++) { int edgeIdx=(*edgesInFace)[face->size()-1][i]; (*facesAroundEdge)[edgeIdx].push_back(face->size()-1); } } void TopologyModifier::removeEdges(TopologyContainer* container, std::vector<int>* idxs) { //for(int i=0;i<idxs->size();i++) for(int i=idxs->size()-1;i>=0;i--) removeEdge(container, (*idxs)[i]); } void TopologyModifier::removeEdges(TopologyContainer* container, std::vector<int>& idxs) { //for(int i=0;i<idxs.size();i++) for(int i=idxs.size()-1;i>=0;i--) removeEdge(container, idxs[i]); } void TopologyModifier::removeEdge(TopologyContainer* container, int idx) { std::vector<Vec2i>* edges=container->edge(); int nbEdge=edges->size(); //update topology information //1. EdgesAroundPoint std::vector<std::vector<int>>* edgesAroundPoint=container->edgesAroundPoint(); for(int i=0;i<2;i++) { int pointIdx=(*edges)[idx][i]; for(int j=0;j<(*edgesAroundPoint)[pointIdx].size();j++) { if((*edgesAroundPoint)[pointIdx][j]==idx) { removeVectorComp((*edgesAroundPoint)[pointIdx],j); break; } } pointIdx=(*edges)[nbEdge-1][i]; for(int j=0;j<(*edgesAroundPoint)[pointIdx].size();j++) { if((*edgesAroundPoint)[pointIdx][j]==(nbEdge-1)) { (*edgesAroundPoint)[pointIdx][j]=idx; break; } } } //2. PointsAroundPoint std::vector<std::vector<int>>* pointsAroundPoint=container->pointsAroundPoint(); for(int i=0;i<2;i++) { int pointIdx=(*edges)[idx][i]; for(int j=0;j<(*pointsAroundPoint)[pointIdx].size();j++) { if((*pointsAroundPoint)[pointIdx][j]==(*edges)[idx][(i+1)%2]) { removeVectorComp((*pointsAroundPoint)[(*edges)[idx][i]],j); break; } } } //3. EdgesInFace std::vector<std::vector<int>>* edgesInFace=container->edgesInFace(); std::vector<std::vector<int>>* facesAroundEdge=container->facesAroundEdge(); for(int i=0;i<(*facesAroundEdge)[nbEdge-1].size();i++) { int faceIdx=(*facesAroundEdge)[nbEdge-1][i]; for(int j=0;j<3;j++) { if((*edgesInFace)[faceIdx][j]==(nbEdge-1)) { (*edgesInFace)[faceIdx][j]=idx; break; } } } //4. FacesAroundEdge (*facesAroundEdge)[idx]=(*facesAroundEdge)[nbEdge-1]; facesAroundEdge->pop_back(); //5. Edge (*edges)[idx]=(*edges)[nbEdge-1]; edges->pop_back(); } void TopologyModifier::removeFaces(TopologyContainer* container, std::vector<int>* idxs) { for(int i=0;i<idxs->size();i++) removeFace(container, (*idxs)[i]); } void TopologyModifier::removeFaces(TopologyContainer* container, std::vector<int>& idxs) { //for(int i=0;i<idxs.size();i++) for(int i=idxs.size()-1;i>=0;i--) removeFace(container, idxs[i]); } void TopologyModifier::removeFace(TopologyContainer* container, int idx) { std::vector<Vec3i>* face=container->face(); int nbFace=face->size(); //Topology information update //1. FacesAroundPoint std::vector<std::vector<int>>* facesAroundPoint=container->facesAroundPoint(); for(int i=0;i<3;i++) { int pointIdx=(*face)[idx][i]; for(int j=0;j<(*facesAroundPoint)[pointIdx].size();j++) { if((*facesAroundPoint)[pointIdx][j]==idx) { removeVectorComp((*facesAroundPoint)[pointIdx],j); break; } } pointIdx=(*face)[nbFace-1][i]; for(int j=0;j<(*facesAroundPoint)[pointIdx].size();j++) { if((*facesAroundPoint)[pointIdx][j]==(nbFace-1)) { (*facesAroundPoint)[pointIdx][j]=idx; break; } } } //2. FacesAroundEdge std::vector<std::vector<int>>* facesAroundEdge=container->facesAroundEdge(); std::vector<std::vector<int>>* edgesInFace=container->edgesInFace(); for(int i=0;i<(*edgesInFace)[idx].size();i++) { int edgeIdx=(*edgesInFace)[idx][i]; for(int j=0;j<(*facesAroundEdge)[edgeIdx].size();j++) { if((*facesAroundEdge)[edgeIdx][j]==idx) { removeVectorComp((*facesAroundEdge)[edgeIdx], j); break; } } /*edgeIdx=(*edgesInFace)[nbFace-1][i]; for(int j=0;j<(*facesAroundEdge)[edgeIdx].size();j++) { if((*facesAroundEdge)[edgeIdx][j]==(nbFace-1)) { (*facesAroundEdge)[edgeIdx][j]=idx; break; } }*/ } for(int i=0;i<(*edgesInFace)[nbFace-1].size();i++) { int edgeIdx=(*edgesInFace)[nbFace-1][i]; for(int j=0;j<(*facesAroundEdge)[edgeIdx].size();j++) { if((*facesAroundEdge)[edgeIdx][j]==(nbFace-1)) (*facesAroundEdge)[edgeIdx][j]=idx; } } //3. EdgesInFace (*edgesInFace)[idx]=(*edgesInFace)[nbFace-1]; edgesInFace->pop_back(); //4. Face (*face)[idx]=(*face)[nbFace-1]; face->pop_back(); } void TopologyModifier::removeVectorComp(std::vector<int>& vec, int idx) { int nbComp=vec.size(); vec[idx]=vec[nbComp-1]; vec.pop_back(); }
true
42dfec180df99a9f6e5055baa847346a83e94a5d
C++
hyle-team/zano
/src/crypto/crypto-sugar.h
UTF-8
29,167
2.5625
3
[]
no_license
// Copyright (c) 2020-2021 Zano Project // Copyright (c) 2020-2021 sowle (val@zano.org, crypto.sowle@gmail.com) // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // Note: This file originates from tests/functional_tests/crypto_tests.cpp #pragma once #include <string> #include <boost/multiprecision/cpp_int.hpp> #include "crypto.h" namespace crypto { extern "C" { #include "crypto/crypto-ops.h" } // extern "C" // // Helpers // template<class pod_t> std::string pod_to_hex_reversed(const pod_t &h) { constexpr char hexmap[] = "0123456789abcdef"; const unsigned char* data = reinterpret_cast<const unsigned char*>(&h); size_t len = sizeof h; std::string s(len * 2, ' '); for (size_t i = 0; i < len; ++i) { s[2 * i] = hexmap[data[len - 1 - i] >> 4]; s[2 * i + 1] = hexmap[data[len - 1 - i] & 0x0F]; } return s; } template<class pod_t> std::string pod_to_hex(const pod_t &h) { constexpr char hexmap[] = "0123456789abcdef"; const unsigned char* data = reinterpret_cast<const unsigned char*>(&h); size_t len = sizeof h; std::string s(len * 2, ' '); for (size_t i = 0; i < len; ++i) { s[2 * i] = hexmap[data[i] >> 4]; s[2 * i + 1] = hexmap[data[i] & 0x0F]; } return s; } template<class pod_t> std::string pod_to_hex_comma_separated_bytes(const pod_t &h) { std::stringstream ss; ss << std::hex << std::setfill('0'); size_t len = sizeof h; const unsigned char* p = (const unsigned char*)&h; for (size_t i = 0; i < len; ++i) { ss << "0x" << std::setw(2) << static_cast<unsigned int>(p[i]); if (i + 1 != len) ss << ", "; } return ss.str(); } template<class pod_t> std::string pod_to_hex_comma_separated_uint64(const pod_t &h) { static_assert((sizeof h) % 8 == 0, "size of h should be a multiple of 64 bit"); size_t len = (sizeof h) / 8; std::stringstream ss; ss << std::hex << std::setfill('0'); const uint64_t* p = (const uint64_t*)&h; for (size_t i = 0; i < len; ++i) { ss << "0x" << std::setw(16) << static_cast<uint64_t>(p[i]); if (i + 1 != len) ss << ", "; } return ss.str(); } template<typename t_pod_type> bool parse_tpod_from_hex_string(const std::string& hex_str, t_pod_type& t_pod) { static const int16_t char_map[256] = { // 0-9, a-f, A-F is only allowed -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00 - 0x1F -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, // 0x20 - 0x3F -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x40 - 0x5F -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x60 - 0x7F -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x80 - 0x9F -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0xA0 - 0xBF -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0xC0 - 0xDF -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; // 0xE0 - 0xFF size_t pod_size = sizeof t_pod; uint8_t *p = reinterpret_cast<uint8_t*>(&t_pod); if (hex_str.size() != 2 * pod_size) return false; for (size_t i = 0; i < pod_size; ++i) { int16_t hi = char_map[static_cast<uint8_t>(hex_str[2 * i])]; int16_t lo = char_map[static_cast<uint8_t>(hex_str[2 * i + 1])]; if (hi < 0 || lo < 0) { // invalid characters in hex_str memset(p, 0, pod_size); return false; } p[i] = static_cast<uint8_t>(hi * 16 + lo); // write byte to pod } return true; } template<typename t_pod_type> t_pod_type parse_tpod_from_hex_string(const std::string& hex_str) { t_pod_type t_pod = AUTO_VAL_INIT(t_pod); parse_tpod_from_hex_string(hex_str, t_pod); return t_pod; } // // scalar_t - holds a 256-bit scalar, normally in [0..L-1] // struct alignas(32) scalar_t { union { uint64_t m_u64[4]; unsigned char m_s[32]; }; scalar_t() {} // won't check scalar range validity (< L) scalar_t(uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3) { m_u64[0] = a0; m_u64[1] = a1; m_u64[2] = a2; m_u64[3] = a3; } // won't check scalar range validity (< L) scalar_t(const unsigned char(&v)[32]) { memcpy(m_s, v, 32); } // won't check secret key validity (sk < L) scalar_t(const crypto::secret_key& sk) { from_secret_key(sk); } // copy data and reduce scalar_t(const crypto::hash& hash) { m_u64[0] = ((uint64_t*)&hash)[0]; m_u64[1] = ((uint64_t*)&hash)[1]; m_u64[2] = ((uint64_t*)&hash)[2]; m_u64[3] = ((uint64_t*)&hash)[3]; sc_reduce32(&m_s[0]); } scalar_t(uint64_t v) { zero(); m_u64[0] = v; // do not need to call reduce as 2^64 < L } // copy at most 256 bits (32 bytes) and reduce template<typename T> explicit scalar_t(const boost::multiprecision::number<T>& bigint) { zero(); unsigned int bytes_to_copy = bigint.backend().size() * bigint.backend().limb_bits / 8; if (bytes_to_copy > sizeof *this) bytes_to_copy = sizeof *this; memcpy(&m_s[0], bigint.backend().limbs(), bytes_to_copy); sc_reduce32(&m_s[0]); } unsigned char* data() { return &m_s[0]; } const unsigned char* data() const { return &m_s[0]; } crypto::secret_key &as_secret_key() { return *(crypto::secret_key*)&m_s[0]; } const crypto::secret_key& as_secret_key() const { return *(const crypto::secret_key*)&m_s[0]; } operator crypto::secret_key() const { crypto::secret_key result; memcpy(result.data, &m_s, sizeof result.data); return result; } void from_secret_key(const crypto::secret_key& sk) { uint64_t *p_sk64 = (uint64_t*)&sk; m_u64[0] = p_sk64[0]; m_u64[1] = p_sk64[1]; m_u64[2] = p_sk64[2]; m_u64[3] = p_sk64[3]; // assuming secret key is correct (< L), so we don't need to call reduce here } void zero() { m_u64[0] = 0; m_u64[1] = 0; m_u64[2] = 0; m_u64[3] = 0; } // genrate 0 <= x < L static scalar_t random() { scalar_t result; result.make_random(); return result; } // generate 0 <= x < L void make_random() { unsigned char tmp[64]; crypto::generate_random_bytes(64, tmp); sc_reduce(tmp); memcpy(&m_s, tmp, sizeof m_s); /* // for tests int x[8] = { rand() }; crypto::cn_fast_hash(&x, sizeof x, *(crypto::hash*)this); sc_reduce32(m_s); */ } bool is_zero() const { return sc_isnonzero(&m_s[0]) == 0; } bool is_reduced() const { return sc_check(&m_s[0]) == 0; } void reduce() { sc_reduce32(&m_s[0]); } scalar_t operator+(const scalar_t& v) const { scalar_t result; sc_add(&result.m_s[0], &m_s[0], &v.m_s[0]); return result; } scalar_t& operator+=(const scalar_t& v) { sc_add(&m_s[0], &m_s[0], &v.m_s[0]); return *this; } scalar_t operator-(const scalar_t& v) const { scalar_t result; sc_sub(&result.m_s[0], &m_s[0], &v.m_s[0]); return result; } scalar_t& operator-=(const scalar_t& v) { sc_sub(&m_s[0], &m_s[0], &v.m_s[0]); return *this; } scalar_t operator*(const scalar_t& v) const { scalar_t result; sc_mul(result.m_s, m_s, v.m_s); return result; } scalar_t& operator*=(const scalar_t& v) { sc_mul(m_s, m_s, v.m_s); return *this; } // returns this = a * b scalar_t& assign_mul(const scalar_t& a, const scalar_t& b) { sc_mul(m_s, a.m_s, b.m_s); return *this; } /* I think it has bad symantic (operator-like), consider rename/reimplement -- sowle */ // returns this * b + c scalar_t muladd(const scalar_t& b, const scalar_t& c) const { scalar_t result; sc_muladd(result.m_s, m_s, b.m_s, c.m_s); return result; } // returns this = a * b + c scalar_t& assign_muladd(const scalar_t& a, const scalar_t& b, const scalar_t& c) { sc_muladd(m_s, a.m_s, b.m_s, c.m_s); return *this; } scalar_t reciprocal() const { scalar_t result; sc_invert(result.m_s, m_s); return result; } scalar_t operator/(const scalar_t& v) const { return operator*(v.reciprocal()); } scalar_t& operator/=(const scalar_t& v) { scalar_t reciprocal; sc_invert(&reciprocal.m_s[0], &v.m_s[0]); sc_mul(&m_s[0], &m_s[0], &reciprocal.m_s[0]); return *this; } bool operator==(const scalar_t& rhs) const { return m_u64[0] == rhs.m_u64[0] && m_u64[1] == rhs.m_u64[1] && m_u64[2] == rhs.m_u64[2] && m_u64[3] == rhs.m_u64[3]; } bool operator!=(const scalar_t& rhs) const { return m_u64[0] != rhs.m_u64[0] || m_u64[1] != rhs.m_u64[1] || m_u64[2] != rhs.m_u64[2] || m_u64[3] != rhs.m_u64[3]; } bool operator<(const scalar_t& rhs) const { if (m_u64[3] < rhs.m_u64[3]) return true; if (m_u64[3] > rhs.m_u64[3]) return false; if (m_u64[2] < rhs.m_u64[2]) return true; if (m_u64[2] > rhs.m_u64[2]) return false; if (m_u64[1] < rhs.m_u64[1]) return true; if (m_u64[1] > rhs.m_u64[1]) return false; if (m_u64[0] < rhs.m_u64[0]) return true; if (m_u64[0] > rhs.m_u64[0]) return false; return false; } bool operator>(const scalar_t& rhs) const { if (m_u64[3] < rhs.m_u64[3]) return false; if (m_u64[3] > rhs.m_u64[3]) return true; if (m_u64[2] < rhs.m_u64[2]) return false; if (m_u64[2] > rhs.m_u64[2]) return true; if (m_u64[1] < rhs.m_u64[1]) return false; if (m_u64[1] > rhs.m_u64[1]) return true; if (m_u64[0] < rhs.m_u64[0]) return false; if (m_u64[0] > rhs.m_u64[0]) return true; return false; } friend std::ostream& operator<<(std::ostream& ss, const scalar_t &v) { return ss << pod_to_hex(v); } std::string to_string_as_hex_number() const { return pod_to_hex_reversed(*this); } std::string to_string_as_secret_key() const { return pod_to_hex(*this); } template<typename MP_type> MP_type as_boost_mp_type() const { MP_type result = 0; static_assert(sizeof result >= sizeof *this, "size missmatch"); // to avoid using types less than uint256_t unsigned int sz = sizeof *this / sizeof(boost::multiprecision::limb_type); result.backend().resize(sz, sz); memcpy(result.backend().limbs(), &m_s[0], sizeof *this); result.backend().normalize(); return result; } // Little-endian assumed; TODO: consider Big-endian support bool get_bit(uint8_t bit_index) const { return (m_u64[bit_index >> 6] & (1ull << (bit_index & 63))) != 0; } // Little-endian assumed; TODO: consider Big-endian support void set_bit(size_t bit_index) { m_u64[bit_index >> 6] |= (1ull << (bit_index & 63)); } // Little-endian assumed; TODO: consider Big-endian support void clear_bit(size_t bit_index) { m_u64[bit_index >> 6] &= ~(1ull << (bit_index & 63)); } static scalar_t power_of_2(uint8_t exponent) { scalar_t result = 0; result.set_bit(exponent); return result; } }; // struct scalar_t // // Global constants // extern const scalar_t c_scalar_1; extern const scalar_t c_scalar_L; extern const scalar_t c_scalar_Lm1; extern const scalar_t c_scalar_P; extern const scalar_t c_scalar_Pm1; extern const scalar_t c_scalar_256m1; extern const scalar_t c_scalar_1div8; // // // struct point_t { struct tag_zero {}; // A point(x, y) is represented in extended homogeneous coordinates (X, Y, Z, T) // with x = X / Z, y = Y / Z, x * y = T / Z. ge_p3 m_p3; point_t() { } explicit point_t(const crypto::public_key& pk) { if (!from_public_key(pk)) zero(); } point_t(const unsigned char(&v)[32]) { static_assert(sizeof(crypto::public_key) == sizeof v, "size missmatch"); if (!from_public_key(*(const crypto::public_key*)v)) zero(); } point_t(const uint64_t(&v)[4]) { static_assert(sizeof(crypto::public_key) == sizeof v, "size missmatch"); if (!from_public_key(*(const crypto::public_key*)v)) zero(); } point_t(uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3) { crypto::public_key pk; ((uint64_t*)&pk)[0] = a0; ((uint64_t*)&pk)[1] = a1; ((uint64_t*)&pk)[2] = a2; ((uint64_t*)&pk)[3] = a3; if (!from_public_key(pk)) zero(); } explicit point_t(tag_zero&&) { zero(); } // as we're using additive notation, zero means identity group element (EC point (0, 1)) here and after void zero() { ge_p3_0(&m_p3); } bool is_zero() const { // (0, 1) ~ (0, z, z, 0) if (fe_isnonzero(m_p3.X) != 0) return false; fe y_minus_z; fe_sub(y_minus_z, m_p3.Y, m_p3.Z); return fe_isnonzero(y_minus_z) == 0; } bool is_in_main_subgroup() const { return (c_scalar_L * *this).is_zero(); } bool from_public_key(const crypto::public_key& pk) { return ge_frombytes_vartime(&m_p3, reinterpret_cast<const unsigned char*>(&pk)) == 0; } bool from_key_image(const crypto::key_image& ki) { return ge_frombytes_vartime(&m_p3, reinterpret_cast<const unsigned char*>(&ki)) == 0; } bool from_string(const std::string& str) { crypto::public_key pk; if (!parse_tpod_from_hex_string(str, pk)) return false; return from_public_key(pk); } crypto::public_key to_public_key() const { crypto::public_key result; ge_p3_tobytes((unsigned char*)&result, &m_p3); return result; } void to_public_key(crypto::public_key& result) const { ge_p3_tobytes((unsigned char*)&result, &m_p3); } crypto::key_image to_key_image() const { crypto::key_image result; ge_p3_tobytes((unsigned char*)&result, &m_p3); return result; } point_t operator+(const point_t& rhs) const { point_t result; ge_cached rhs_c; ge_p1p1 t; ge_p3_to_cached(&rhs_c, &rhs.m_p3); ge_add(&t, &m_p3, &rhs_c); ge_p1p1_to_p3(&result.m_p3, &t); return result; } point_t& operator+=(const point_t& rhs) { ge_cached rhs_c; ge_p1p1 t; ge_p3_to_cached(&rhs_c, &rhs.m_p3); ge_add(&t, &m_p3, &rhs_c); ge_p1p1_to_p3(&m_p3, &t); return *this; } point_t operator-(const point_t& rhs) const { point_t result; ge_cached rhs_c; ge_p1p1 t; ge_p3_to_cached(&rhs_c, &rhs.m_p3); ge_sub(&t, &m_p3, &rhs_c); ge_p1p1_to_p3(&result.m_p3, &t); return result; } point_t& operator-=(const point_t& rhs) { ge_cached rhs_c; ge_p1p1 t; ge_p3_to_cached(&rhs_c, &rhs.m_p3); ge_sub(&t, &m_p3, &rhs_c); ge_p1p1_to_p3(&m_p3, &t); return *this; } friend point_t operator*(const scalar_t& lhs, const point_t& rhs) { point_t result; ge_scalarmult_p3(&result.m_p3, lhs.m_s, &rhs.m_p3); return result; } point_t& operator*=(const scalar_t& rhs) { // TODO: ge_scalarmult_vartime_p3 ge_scalarmult_p3(&m_p3, rhs.m_s, &m_p3); return *this; } friend point_t operator/(const point_t& lhs, const scalar_t& rhs) { point_t result; scalar_t reciprocal; sc_invert(&reciprocal.m_s[0], &rhs.m_s[0]); ge_scalarmult_p3(&result.m_p3, &reciprocal.m_s[0], &lhs.m_p3); return result; } point_t& modify_mul8() { ge_mul8_p3(&m_p3, &m_p3); return *this; } // returns a * this + G point_t mul_plus_G(const scalar_t& a) const { static const unsigned char one[32] = { 1 }; static_assert(sizeof one == sizeof(crypto::ec_scalar), "size missmatch"); point_t result; ge_double_scalarmult_base_vartime_p3(&result.m_p3, &a.m_s[0], &m_p3, &one[0]); return result; } // returns a * this + b * G point_t mul_plus_G(const scalar_t& a, const scalar_t& b) const { point_t result; ge_double_scalarmult_base_vartime_p3(&result.m_p3, &a.m_s[0], &m_p3, &b.m_s[0]); return result; } // *this = a * A + b * G void assign_mul_plus_G(const scalar_t& a, const point_t& A, const scalar_t& b) { ge_double_scalarmult_base_vartime_p3(&m_p3, &a.m_s[0], &A.m_p3, &b.m_s[0]); } friend bool operator==(const point_t& lhs, const point_t& rhs) { // convert to xy form, then compare components (because (x, y, z, t) representation is not unique) fe lrecip, lx, ly; fe rrecip, rx, ry; fe_invert(lrecip, lhs.m_p3.Z); fe_invert(rrecip, rhs.m_p3.Z); fe_mul(lx, lhs.m_p3.X, lrecip); fe_mul(rx, rhs.m_p3.X, rrecip); if (memcmp(&lx, &rx, sizeof lx) != 0) return false; fe_mul(ly, lhs.m_p3.Y, lrecip); fe_mul(ry, rhs.m_p3.Y, rrecip); if (memcmp(&ly, &ry, sizeof ly) != 0) return false; return true; }; friend bool operator!=(const point_t& lhs, const point_t& rhs) { return !(lhs == rhs); }; friend std::ostream& operator<<(std::ostream& ss, const point_t &v) { crypto::public_key pk = v.to_public_key(); return ss << pod_to_hex(pk); } operator std::string() const { crypto::public_key pk = to_public_key(); return pod_to_hex(pk); } std::string to_string() const { crypto::public_key pk = to_public_key(); return pod_to_hex(pk); } std::string to_hex_comma_separated_bytes_str() const { crypto::public_key pk = to_public_key(); return pod_to_hex_comma_separated_bytes(pk); } std::string to_hex_comma_separated_uint64_str() const { crypto::public_key pk = to_public_key(); return pod_to_hex_comma_separated_uint64(pk); } }; // struct point_t // // point_g_t -- special type for curve's base point // struct point_g_t : public point_t { point_g_t() { scalar_t one(1); ge_scalarmult_base(&m_p3, &one.m_s[0]); } friend point_t operator*(const scalar_t& lhs, const point_g_t&) { point_t result; ge_scalarmult_base(&result.m_p3, &lhs.m_s[0]); return result; } friend point_t operator/(const point_g_t&, const scalar_t& rhs) { point_t result; scalar_t reciprocal; sc_invert(&reciprocal.m_s[0], &rhs.m_s[0]); ge_scalarmult_base(&result.m_p3, &reciprocal.m_s[0]); return result; } static_assert(sizeof(crypto::public_key) == 32, "size error"); }; // struct point_g_t // // vector of scalars // struct scalar_vec_t : public std::vector<scalar_t> { typedef std::vector<scalar_t> super_t; scalar_vec_t() {} scalar_vec_t(size_t n) : super_t(n) {} scalar_vec_t(std::initializer_list<scalar_t> init_list) : super_t(init_list) {} bool is_reduced() const { for (auto& el : *this) if (!el.is_reduced()) return false; return true; } // add a scalar rhs to each element scalar_vec_t operator+(const scalar_t& rhs) const { scalar_vec_t result(size()); for (size_t i = 0, n = size(); i < n; ++i) result[i] = at(i) + rhs; return result; } // subtract a scalar rhs to each element scalar_vec_t operator-(const scalar_t& rhs) const { scalar_vec_t result(size()); for (size_t i = 0, n = size(); i < n; ++i) result[i] = at(i) - rhs; return result; } // multiply each element of the vector by a scalar scalar_vec_t operator*(const scalar_t& rhs) const { scalar_vec_t result(size()); for (size_t i = 0, n = size(); i < n; ++i) result[i] = at(i) * rhs; return result; } // component-wise multiplication (a.k.a the Hadamard product) (only if their sizes match) scalar_vec_t operator*(const scalar_vec_t& rhs) const { scalar_vec_t result; const size_t n = size(); if (n != rhs.size()) return result; result.resize(size()); for (size_t i = 0; i < n; ++i) result[i] = at(i) * rhs[i]; return result; } // add each element of two vectors, but only if their sizes match scalar_vec_t operator+(const scalar_vec_t& rhs) const { scalar_vec_t result; const size_t n = size(); if (n != rhs.size()) return result; result.resize(size()); for (size_t i = 0; i < n; ++i) result[i] = at(i) + rhs[i]; return result; } // zeroes all elements void zero() { size_t size_bytes = sizeof(scalar_t) * size(); memset(data(), 0, size_bytes); } // invert all elements in-place efficiently: 4*N muptiplications + 1 inversion void invert() { // muls muls_rev // 0: 1 2 3 .. n-1 // 1: 0 2 3 .. n-1 // 2: 0 1 3 .. n-1 // // n-1: 0 1 2 3 .. n-2 const size_t size = this->size(); if (size < 2) { if (size == 1) at(0) = at(0).reciprocal(); return; } scalar_vec_t muls(size), muls_rev(size); muls[0] = 1; for (size_t i = 0; i < size - 1; ++i) muls[i + 1] = at(i) * muls[i]; muls_rev[size - 1] = 1; for (size_t i = size - 1; i != 0; --i) muls_rev[i - 1] = at(i) * muls_rev[i]; scalar_t inv = (muls[size - 1] * at(size - 1)).reciprocal(); for (size_t i = 0; i < size; ++i) at(i) = muls[i] * inv * muls_rev[i]; } scalar_t calc_hs() const; }; // scalar_vec_t // treats vector of scalars as an M x N matrix just for convenience template<size_t N> struct scalar_mat_t : public scalar_vec_t { typedef scalar_vec_t super_t; static_assert(N > 0, "invalid N value"); scalar_mat_t() {} scalar_mat_t(size_t n) : super_t(n) {} scalar_mat_t(std::initializer_list<scalar_t> init_list) : super_t(init_list) {} // matrix accessor M rows x N cols scalar_t& operator()(size_t row, size_t col) { return at(row * N + col); } }; // scalar_mat_t // // Global constants // extern const point_g_t c_point_G; extern const point_t c_point_H; extern const point_t c_point_H2; extern const point_t c_point_0; // // hash functions' helper // struct hash_helper_t { static scalar_t hs(const scalar_t& s) { return scalar_t(crypto::cn_fast_hash(s.data(), sizeof s)); // will reduce mod L } static scalar_t hs(const void* data, size_t size) { return scalar_t(crypto::cn_fast_hash(data, size)); // will reduce mod L } static scalar_t hs(const std::string& str) { return scalar_t(crypto::cn_fast_hash(str.c_str(), str.size())); // will reduce mod L } struct hs_t { hs_t() { static_assert(sizeof(scalar_t) == sizeof(crypto::public_key), "unexpected size of data"); } void reserve(size_t elements_count) { m_elements.reserve(elements_count); } void resize(size_t elements_count) { m_elements.resize(elements_count); } void clear() { m_elements.clear(); } void add_scalar(const scalar_t& scalar) { m_elements.emplace_back(scalar); } void add_point(const point_t& point) { m_elements.emplace_back(point.to_public_key()); // faster? /* static_assert(sizeof point.m_p3 == 5 * sizeof(item_t), "size missmatch"); const item_t *p = (item_t*)&point.m_p3; m_elements.emplace_back(p[0]); m_elements.emplace_back(p[1]); m_elements.emplace_back(p[2]); m_elements.emplace_back(p[3]); m_elements.emplace_back(p[4]); */ } void add_pub_key(const crypto::public_key& pk) { m_elements.emplace_back(pk); } scalar_t& access_scalar(size_t index) { return m_elements[index].scalar; } public_key& access_public_key(size_t index) { return m_elements[index].pk; } void add_points_array(const std::vector<point_t>& points_array) { for (size_t i = 0, size = points_array.size(); i < size; ++i) add_point(points_array[i]); } void add_pub_keys_array(const std::vector<crypto::public_key>& pub_keys_array) { for (size_t i = 0, size = pub_keys_array.size(); i < size; ++i) m_elements.emplace_back(pub_keys_array[i]); } void add_key_images_array(const std::vector<crypto::key_image>& key_image_array) { for (size_t i = 0, size = key_image_array.size(); i < size; ++i) m_elements.emplace_back(key_image_array[i]); } scalar_t calc_hash(bool clear = true) { size_t data_size_bytes = m_elements.size() * sizeof(item_t); crypto::hash hash; crypto::cn_fast_hash(m_elements.data(), data_size_bytes, hash); if (clear) this->clear(); return scalar_t(hash); // this will reduce to L } void assign_calc_hash(scalar_t& result, bool clear = true) { static_assert(sizeof result == sizeof(crypto::hash), "size missmatch"); size_t data_size_bytes = m_elements.size() * sizeof(item_t); crypto::cn_fast_hash(m_elements.data(), data_size_bytes, (crypto::hash&)result); result.reduce(); if (clear) this->clear(); } union item_t { item_t() {} item_t(const scalar_t& scalar) : scalar(scalar) {} item_t(const crypto::public_key& pk) : pk(pk) {} item_t(const crypto::key_image& ki) : ki(ki) {} scalar_t scalar; crypto::public_key pk; crypto::key_image ki; }; std::vector<item_t> m_elements; }; static scalar_t hs(const scalar_t& s, const std::vector<point_t>& ps0, const std::vector<point_t>& ps1) { hs_t hs_calculator; hs_calculator.add_scalar(s); hs_calculator.add_points_array(ps0); hs_calculator.add_points_array(ps1); return hs_calculator.calc_hash(); } static scalar_t hs(const crypto::hash& s, const std::vector<crypto::public_key>& ps0, const std::vector<crypto::key_image>& ps1) { static_assert(sizeof(crypto::hash) == sizeof(scalar_t), "size missmatch"); hs_t hs_calculator; hs_calculator.add_scalar(*reinterpret_cast<const scalar_t*>(&s)); hs_calculator.add_pub_keys_array(ps0); hs_calculator.add_key_images_array(ps1); return hs_calculator.calc_hash(); } static scalar_t hs(const std::vector<point_t>& ps0, const std::vector<point_t>& ps1) { hs_t hs_calculator; hs_calculator.add_points_array(ps0); hs_calculator.add_points_array(ps1); return hs_calculator.calc_hash(); } static point_t hp(const point_t& p) { point_t result; crypto::public_key pk = p.to_public_key(); ge_bytes_hash_to_ec_32(&result.m_p3, (const unsigned char*)&pk); return result; } static point_t hp(const crypto::public_key& p) { point_t result; ge_bytes_hash_to_ec_32(&result.m_p3, (const unsigned char*)&p); return result; } static point_t hp(const scalar_t& s) { point_t result; ge_bytes_hash_to_ec_32(&result.m_p3, s.data()); return result; } static point_t hp(const void* data, size_t size) { point_t result; ge_bytes_hash_to_ec(&result.m_p3, data, size); return result; } }; // hash_helper_t struct inline scalar_t scalar_vec_t::calc_hs() const { // hs won't touch memory if size is 0, so it's safe return hash_helper_t::hs(data(), sizeof(scalar_t) * size()); } } // namespace crypto
true
28df2a81cfaa7a749a35fa06f32332004b994ff3
C++
benmhide/OpenGL-3D
/src/Brick.cpp
UTF-8
238
2.546875
3
[]
no_license
#include "Brick.h" //Constructor Brick::Brick() { //Defualt values position = { 0.0f, 0.0f, 0.0f }; scale = { 1.0f, 1.0f, 0.0f }; colour = { 1.0f, 1.0f, 1.0f }; rotation = 0.0f; brickAlive = true; brickDying = false; hits = 1; }
true
464814756443147e86c3dbe27cd2202a5403767d
C++
r-lyeh-archived/codex
/sample.cc
UTF-8
11,105
2.671875
3
[ "Zlib" ]
permissive
#include <cassert> #include <cstdint> #include <cstdio> #include <cstring> #include <iostream> #include <string> #include "codex.hpp" int main( int argc, const char **argv ) { assert( encode::html::dec(0) == "&#0;" ); assert( encode::html::dec('\'') == "&#39;" ); assert( encode::html::hex('\'') == "&#x27;" ); assert( escape::html("<hi>") == "&lt;hi&gt;" ); assert( encode::uri::hex('\'') == "%27" ); assert( encode::uri::hex('%') == "%25" ); assert( encode::uri::strings("hello", "world") == "hello=world&" ); assert( encode::string::quote("hello \"world\"") == "hello \\\"world\\\"" ); assert( encode::string::brace("hello world", "[]") == "[hello world]" ); std::cout << "All ok." << std::endl; return 0; } #define joint2(n,l) n##l #define joint(n,l) joint2(n,l) #define test(desc) void joint(fn,__LINE__)(); const int joint(var,__LINE__) = std::printf("%s ... %s\n", desc, (joint(fn,__LINE__)(), "OK") ); void joint(fn,__LINE__)() test("utf8::decode() should decode codepoint from utf8 string in the single octet range 00-7f") { const unsigned char ustr1[]={ 1 }; const unsigned char ustr2[]={ 0x32 }; const unsigned char ustr3[]={ 0x7f }; const unsigned char ustr_er[]={ 0x80 }; const char* str1 = (const char*)ustr1; const char* str2 = (const char*)ustr2; const char* str3 = (const char*)ustr3; const char* str_er = (const char*)ustr_er; unsigned int codepoint = 0; const char* res = 0; codepoint = 0; res = utf8::decode(str1, 1, &codepoint); assert( codepoint == 1u); assert( res == str1+1 ); codepoint = 0; res = utf8::decode(str2, 1, &codepoint); assert( codepoint == 0x32u); assert( res == str2+1 ); codepoint = 0; res = utf8::decode(str3, 1, &codepoint); assert( codepoint == 0x7fu); assert( res == str3+1 ); codepoint = 0; res = utf8::decode(str_er, 1, &codepoint); assert( codepoint == 0xfffdu); assert( res == str_er+1 ); } test("utf8::decode() should decode codepoint from utf8 string in the two octet range 80-7ff") { const unsigned char ustr1[]={ 0xc2u, 0x80u }; const unsigned char ustr2[]={ 0xc4u, 0x80u }; const unsigned char ustr3[]={ 0xdfu, 0xbfu }; const unsigned char ustr_er[]={ 0xdfu, 0xc0u }; const unsigned char ustr_er2[]={ 0xdfu }; const char* str1 = (const char*)ustr1; const char* str2 = (const char*)ustr2; const char* str3 = (const char*)ustr3; const char* str_er = (const char*)ustr_er; const char* str_er2 = (const char*)ustr_er2; unsigned int codepoint = 0; const char* res = 0; codepoint = 0; res = utf8::decode(str1, 2, &codepoint); assert( codepoint == 0x80u); assert( res == str1+2 ); codepoint = 0; res = utf8::decode(str2, 2, &codepoint); assert( codepoint == 0x100u); assert( res == str2+2 ); codepoint = 0; res = utf8::decode(str3, 2, &codepoint); assert( codepoint == 0x7ffu); assert( res == str3+2 ); codepoint = 0; res = utf8::decode(str_er, 2, &codepoint); assert( codepoint == 0xfffdu); assert( res == str_er+2 ); codepoint = 0; res = utf8::decode(str_er2, 1, &codepoint); assert( codepoint == 0xfffdu); assert( res == str_er2+1 ); } test("utf8::decode() should decode codepoint from utf8 string in the three octet range 800-ffff") { const unsigned char ustr1[]={ 0xe0u, 0xa0u, 0x80u }; const unsigned char ustr2[]={ 0xe1u, 0x80u, 0x80u }; const unsigned char ustr3[]={ 0xefu, 0xbfu, 0xbfu }; const unsigned char ustr_er[]={ 0xefu, 0xbfu, 0xc0u }; const unsigned char ustr_er2[]={ 0xefu, 0xbfu }; const char* str1 = (const char*)ustr1; const char* str2 = (const char*)ustr2; const char* str3 = (const char*)ustr3; const char* str_er = (const char*)ustr_er; const char* str_er2 = (const char*)ustr_er2; unsigned int codepoint = 0; const char* res = 0; codepoint = 0; res = utf8::decode(str1, 3, &codepoint); assert( codepoint == 0x800u); assert( res == str1+3 ); codepoint = 0; res = utf8::decode(str2, 3, &codepoint); assert( codepoint == 0x1000u); assert( res == str2+3 ); codepoint = 0; res = utf8::decode(str3, 3, &codepoint); assert( codepoint == 0xffffu); assert( res == str3+3 ); codepoint = 0; res = utf8::decode(str_er, 3, &codepoint); assert( codepoint == 0xfffdu); assert( res == str_er+3 ); codepoint = 0; res = utf8::decode(str_er2, 2, &codepoint); assert( codepoint == 0xfffdu); assert( res == str_er2+2 ); } test("utf8::decode() should decode codepoint from utf8 string in the four octet range 10000-1ffff") { const unsigned char ustr1[]={ 0xf0u, 0x90u, 0x80u, 0x80u }; const unsigned char ustr2[]={ 0xf0u, 0x92u, 0x80u, 0x80u }; const unsigned char ustr3[]={ 0xf0u, 0x9fu, 0xbfu, 0xbfu }; const unsigned char ustr_er[]={ 0xf0u, 0x9fu, 0xbfu, 0xc0u }; const unsigned char ustr_er2[]={ 0xf0u, 0x9fu, 0xbfu }; const char* str1 = (const char*)ustr1; const char* str2 = (const char*)ustr2; const char* str3 = (const char*)ustr3; const char* str_er = (const char*)ustr_er; const char* str_er2 = (const char*)ustr_er2; unsigned int codepoint = 0; const char* res = 0; codepoint = 0; res = utf8::decode(str1, 4, &codepoint); assert( codepoint == 0x10000u); assert( res == str1+4 ); codepoint = 0; res = utf8::decode(str2, 4, &codepoint); assert( codepoint == 0x12000u); assert( res == str2+4 ); codepoint = 0; res = utf8::decode(str3, 4, &codepoint); assert( codepoint == 0x1ffffu); assert( res == str3+4 ); codepoint = 0; res = utf8::decode(str_er, 4, &codepoint); assert( codepoint == 0xfffdu); assert( res == str_er+4 ); codepoint = 0; res = utf8::decode(str_er2, 3, &codepoint); assert( codepoint == 0xfffdu); assert( res == str_er2+3 ); } test("utf8::decode() should not allow overlong sequences") { const unsigned char ustr1[]={ 0xc0u, 0xafu }; const unsigned char ustr2[]={ 0xe0u, 0x80u, 0xafu }; const unsigned char ustr3[]={ 0xf0u, 0x80u, 0x80u, 0xafu }; const unsigned char ustr4[]={ 0xf8u, 0x80u, 0x80u, 0x80u, 0xafu }; const unsigned char ustr5[]={ 0xfcu, 0x80u, 0x80u, 0x80u, 0x80u, 0xafu }; const char* str1 = (const char*)ustr1; const char* str2 = (const char*)ustr2; const char* str3 = (const char*)ustr3; const char* str4 = (const char*)ustr4; const char* str5 = (const char*)ustr5; unsigned int codepoint; codepoint = 0; utf8::decode(str1, 2, &codepoint); assert( codepoint == 0xfffdu); codepoint = 0; utf8::decode(str2, 3, &codepoint); assert( codepoint == 0xfffdu); codepoint = 0; utf8::decode(str3, 4, &codepoint); assert( codepoint == 0xfffdu); codepoint = 0; utf8::decode(str4, 5, &codepoint); assert( codepoint == 0xfffdu); codepoint = 0; utf8::decode(str5, 6, &codepoint); assert( codepoint == 0xfffdu); } test("utf8::decode() should not allow maximum overlong sequences") { const unsigned char ustr1[]={ 0xc1u, 0xbfu }; const unsigned char ustr2[]={ 0xe0u, 0x9fu, 0xbfu }; const unsigned char ustr3[]={ 0xf0u, 0x8fu, 0xbfu, 0xbfu }; const unsigned char ustr4[]={ 0xf8u, 0x87u, 0xbfu, 0xbfu, 0xbfu }; const unsigned char ustr5[]={ 0xfcu, 0x83u, 0xbfu, 0xbfu, 0xbfu, 0xbfu }; const char* str1 = (const char*)ustr1; const char* str2 = (const char*)ustr2; const char* str3 = (const char*)ustr3; const char* str4 = (const char*)ustr4; const char* str5 = (const char*)ustr5; unsigned int codepoint; codepoint = 0; utf8::decode(str1, 2, &codepoint); assert( codepoint == 0xfffdu); codepoint = 0; utf8::decode(str2, 3, &codepoint); assert( codepoint == 0xfffdu); codepoint = 0; utf8::decode(str3, 4, &codepoint); assert( codepoint == 0xfffdu); codepoint = 0; utf8::decode(str4, 5, &codepoint); assert( codepoint == 0xfffdu); codepoint = 0; utf8::decode(str5, 6, &codepoint); assert( codepoint == 0xfffdu); } test("utf8::decode() should not allow codepoints designated as surrogates") { for(size_t i = 0xa0; i <= 0xbf; ++i) { for(size_t j = 0x80; j <= 0xbf; ++j) { const unsigned char ustr1[]={ (unsigned char)0xedu, (unsigned char)i, (unsigned char)j }; const char* str1 = (const char*)ustr1; unsigned int codepoint = 0; utf8::decode(str1, 3, &codepoint); assert( codepoint == 0xfffdu); } } } test("utf8::encode() should encode all valid codepoints to utf8") { char buf[8]; for(unsigned int i = 0; i < 0x1ffff; ++i) { // Skip surrogates, as they are not allowed in utf8 if( i >= 0xd800 && i <= 0xdfff ) continue; std::memset(buf, 0, 8); const char* ret1 = utf8::encode(i, buf); uint32_t res = 0; const char* ret2 = utf8::decode(buf,7,&res); assert( i == res ); assert( ret1 == ret2 ); } } test("utf8::strlen() should count distinct codepoints") { const char* str1 = "foobar"; const char* str2 = "foob\xc3\xa6r"; const char* str3 = "foob\xf0\x9f\x99\x88r"; assert( utf8::strlen(str1) == 6); assert( utf8::strlen(str2) == 6); assert( utf8::strlen(str3) == 6); } test("utf8::strnlen() should count distinct codepoints") { const char* str1 = "foobar"; const char* str2 = "foob\xc3\xa6r"; const char* str3 = "foob\xf0\x9f\x99\x88r"; assert( utf8::strnlen(str1,6) == 6); assert( utf8::strnlen(str2,7) == 6); assert( utf8::strnlen(str3,9) == 6); } test("utf8::is_continuation_byte() should return true if a given byte is not the initial byte of a utf8 sequence") { const char* str1 = "f"; const char* str2 = "f\xc3\xa6r"; const char* str3 = "f\xf0\x9f\x99\x88r"; assert( !utf8::is_continuation_byte( str1[0] ) ); assert( !utf8::is_continuation_byte( str2[0] ) ); assert( !utf8::is_continuation_byte( str2[1] ) ); assert( utf8::is_continuation_byte( str2[2] ) ); assert( !utf8::is_continuation_byte( str3[0] ) ); assert( !utf8::is_continuation_byte( str3[1] ) ); assert( utf8::is_continuation_byte( str3[2] ) ); assert( utf8::is_continuation_byte( str3[3] ) ); assert( utf8::is_continuation_byte( str3[4] ) ); } test("utf8::is_initial_byte() should return true if a given byte is the initial byte of a utf8 sequence") { const char* str1 = "f"; const char* str2 = "f\xc3\xa6r"; const char* str3 = "f\xf0\x9f\x99\x88r"; assert( utf8::is_initial_byte( str1[0] ) ); assert( utf8::is_initial_byte( str2[0] ) ); assert( utf8::is_initial_byte( str2[1] ) ); assert( !utf8::is_initial_byte( str2[2] ) ); assert( utf8::is_initial_byte( str3[0] ) ); assert( utf8::is_initial_byte( str3[1] ) ); assert( !utf8::is_initial_byte( str3[2] ) ); assert( !utf8::is_initial_byte( str3[3] ) ); assert( !utf8::is_initial_byte( str3[4] ) ); }
true
397ed9c676e73b8f3e987f861368efd9520a68ed
C++
lucianovr/competitive-programming
/URI/2022.cpp
UTF-8
2,666
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for (int i(a); i < (b); i++) #define all(c) c.begin(), c.end() #define UNIQUE(c) \ { sort(ALL(c); (c).resize( unique(ALL(c))-c.begin() ); \ } #define pb push_back #define D(x) \ if (1) \ cout << __LINE__ << " " << #x " = " << (x) << endl; #define DVEC(v, n) \ { \ cout << #v << "[] ={ "; \ rep(i, 0, n) cout << v[i] << " "; \ cout << "}\n"; \ } #define mp make_pair #define fst first #define snd second typedef pair<int, int> ii; typedef long long ll; typedef vector<int> vi; typedef vector<ii> vii; const int INF = 0x3f3f3f3f; const double EPS = 1e-9; struct tipo { string nome; double valor; int rank; tipo(){}; tipo(string _nome, double _valor, int _rank) : nome(_nome), valor(_valor), rank(_rank){}; }; vector<tipo> P; bool comp(tipo A, tipo B) { if (A.rank > B.rank) return true; if (A.rank < B.rank) return false; if (A.valor < B.valor) return true; if (A.valor > B.valor) return false; if (A.nome < B.nome) return true; if (A.nome > B.nome) return false; } int main() { string pessoa; int qt; double valor; int rank; string nome; while (cin >> pessoa >> qt) { P.clear(); cin.ignore(); rep(i, 0, qt) { getline(cin, nome); cin >> valor >> rank; P.pb(tipo(nome, valor, rank)); cin.ignore(); } sort(P.begin(), P.end(), comp); cout << "Lista de " << pessoa << "\n"; rep(i, 0, P.size()) { printf("%s - R$%.2lf\n", P[i].nome.c_str(), P[i].valor); } cout << "\n"; } return 0; }
true
52080fda2df86255343ea4cc2af9ae2e8d95323c
C++
sriharishekhar/Codeforces
/beautifulyear-problem271A.cpp
UTF-8
1,000
2.984375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> int main() { std::string n; std::cin >> n; int number = (n[0] - 48)*1000 + (n[1] - 48)*100 + (n[2] - 48)*10 + (n[3] - 48); ++number; std::vector<int> v; v.push_back(number/1000); v.push_back((number - (v[0]*1000))/100); v.push_back((number - (v[0]*1000) - (v[1]*100))/10); v.push_back((number - v[0]*1000 - v[1]*100 - v[2]*10)); int count; sort(v.begin(), v.end()); count = std::distance(v.begin(), std::unique(v.begin(), v.begin() + v.size())); bool check = 0; while (check == 0) { if(count == v.size()) { check = 1; } else { ++number; v[0] = (number/1000); v[1] = ((number - (v[0]*1000))/100); v[2] = ((number - (v[0]*1000) - (v[1]*100))/10); v[3] = ((number - v[0]*1000 - v[1]*100 - v[2]*10)); sort(v.begin(), v.end()); count = std::distance(v.begin(), std::unique(v.begin(), v.begin() + v.size())); } } std::cout << number; return 0; }
true
6dd7642c040ce269a383e8e9e775fa8ed70d9bf7
C++
kutsanovm/Assignment6
/main.cpp
UTF-8
1,516
3.125
3
[]
no_license
#include "sort.h" #include <iostream> #include <fstream> #include<string> #include <ctime> //http://www.codebind.com/cpp-tutorial/cpp-program-display-current-date-time/ using namespace std; int main(int argc, char const *argv[]) { if (argc > 1) { time_t t = time(NULL); tm* timePtr = localtime(&t); sort luke = sort(argv[1]); cout << "\n" << "INSERTION SORT" << endl; cout << "START TIME: " << (timePtr->tm_hour)<<":"<< (timePtr->tm_min)<<":"<< (timePtr->tm_sec) << endl; luke.insertSort(luke.arr); cout << "END TIME: " << (timePtr->tm_hour)<<":"<< (timePtr->tm_min)<<":"<< (timePtr->tm_sec)<< endl; cout << "\n" << "BUBBLE SORT" << endl; cout << "START TIME: " << (timePtr->tm_hour)<<":"<< (timePtr->tm_min)<<":"<< (timePtr->tm_sec) << endl; luke.bubbleSort(luke.arr); cout << "END TIME: " << (timePtr->tm_hour)<<":"<< (timePtr->tm_min)<<":"<< (timePtr->tm_sec)<< endl; cout << "\n" << "QUICK SORT" << endl; cout << "START TIME: " <<(timePtr->tm_hour)<<":"<< (timePtr->tm_min)<<":"<< (timePtr->tm_sec) << endl; luke.quickSort(luke.arr, luke.arr[0], luke.arr[0]); cout << "END TIME: " << (timePtr->tm_hour)<<":"<< (timePtr->tm_min)<<":"<< (timePtr->tm_sec)<<endl; cout << "\n" << "SELECTION SORT" << endl; cout << "START TIME: " << (timePtr->tm_hour)<<":"<< (timePtr->tm_min)<<":"<< (timePtr->tm_sec) << endl; luke.selectionSort(luke.arr, luke.arr[0]); cout << "END TIME: " << (timePtr->tm_hour)<<":"<< (timePtr->tm_min)<<":"<< (timePtr->tm_sec)<<endl; } return 0; }
true
754ecf00eb6dc8c3464507be6674d22c9142b446
C++
akasilov/EmbeddedLinuxProj
/drivers/gpiobutton.h
UTF-8
1,467
2.5625
3
[]
no_license
#ifndef GPIOBUTTON_H #define GPIOBUTTON_H #include <QString> #include <QObject> #include <QTimer> #include "gpiobase.h" class gpioButton : public QObject, public gpioBase { Q_OBJECT public: explicit gpioButton(QObject *parent = nullptr, quint16 PinNumber = 0); virtual ~gpioButton(); bool configureGpio(); /* must be called after exportGpio (wait >= 100ms after export call -> udev needs some time to set permissions of exported sysfs folder) */ uint8_t getValue(); /* read pin value */ bool pollForInt(); /* checks for pin pressed interrupt and generates onButtonPressed() signal (call this method periodically if onButtonPressed() is used, e.g. every 100-200ms) */ void setHoldoffTime(int TimeMs); /* set hold off time for onButtonPressed in milliseconds */ int getHoldoffTime(); /* gets hold off time for onButtonPressed in milliseconds */ void pollStart(); /* opens gpio pin value file descriptor and initialises for interrupt polling (invoke after configureGpio() and before pollForInterrupt() */ void pollStop(); signals: void onButtonPressed(); private: int poll_fd; /* file descriptor */ QTimer holdoffTimer; /* one shot timer for debouncing gpio pin */ bool isHoldoffActive; /* signals, if hold off is active (holf off time after gpio falling edge detected) */ const static quint16 defaultHoldoffTime; private slots: void holdoffTimerExpiredSlot(); }; #endif // GPIOBUTTON_H
true
f240c86f711b34e1ff1ab48d88178f87770211f6
C++
valentinvstoyanov/fmi
/dsa-cpp/game-map/game_map.h
UTF-8
797
2.703125
3
[]
no_license
#ifndef GAME_MAP_GAME_MAP_H #define GAME_MAP_GAME_MAP_H #include <vector> #include <ostream> #include "graph.h" class GameMap { using KeyMap = std::unordered_map<std::string, std::vector<std::string>>; std::string initial_zone; KeyMap keys; Graph<std::string, std::string> zones; bool canPass(const std::string&, const std::unordered_set<std::string>&) const; void collectKeysFromZone(const std::string&, std::unordered_set<std::string>&) const; void collectAllKeysFromZones(std::unordered_set<std::string>&) const; public: GameMap(const std::string&, const Graph<std::string, std::string>&, const KeyMap&); KeyMap& getKeys(); Graph<std::string, std::string>& getZones(); friend std::ostream& operator<<(std::ostream&, const GameMap&); }; #endif //GAME_MAP_GAME_MAP_H
true
6e3bbbc587e4aca99ba9ee480652286cb5cfaa37
C++
it-rangers/Red-Ranger
/równanie kwadratowe.cpp
UTF-8
906
3.40625
3
[]
no_license
#include <iostream> #include <math.h> using namespace std; int main() { cout << "Program do obliczania rownania kwadratowego, ktore ma postac :" << endl; cout << "__________________a*x^2 + b*x + c = 0_________________________" <<endl <<endl; cout << "Podaj wartosci stalych a,b,c" <<endl; float a,b,c,x1,x2,delta; cin >> a >> b >> c ; delta =(b*b)-(4*a*c) ; cout << "Delta wynosi: " << delta <<endl; if (delta>0) { x1= (-b-sqrt(delta))/(2*a) ; x2= (-b+sqrt(delta))/(2*a) ; cout << "x1 = " << x1 << endl; cout << "x2 = " << x2 << endl; } else if (delta ==0) { x1= -b/(2*a); cout << "x1 = " << x1 << endl; } else if (delta<0) cout << "To rownanie nie ma rozwiazan " <<endl; else cout << "Zostala wpisana bledna wartosc" <<endl; return 0; }
true
549f421816420198cecec65441cf7693b2c285f3
C++
RobotCasserole1736/RoboSim
/Octave/DevTest/Serial_test/arduino_serial_tx_test/arduino_serial_tx_test.ino
UTF-8
626
2.65625
3
[]
no_license
#define ROTATION_RAD_TO_TX_CHAR_CONV 254.0/2.0/PI #define POSITION_FT_TO_TX_CHAR_CONV 254.0/50.0 double robot_x_pos = 0; double robot_y_pos = 0; double robot_rotation = 0; void setup() { Serial.begin(115200); } void loop() { robot_x_pos = (int)(robot_x_pos + 1) % 40; robot_y_pos = (int)(robot_y_pos + 3 + robot_x_pos) % 40; robot_rotation = atan(robot_x_pos/robot_y_pos); Serial.write('~'); Serial.write((char)(robot_x_pos*POSITION_FT_TO_TX_CHAR_CONV)); Serial.write((char)(robot_y_pos*POSITION_FT_TO_TX_CHAR_CONV)); Serial.write((char)(robot_rotation*ROTATION_RAD_TO_TX_CHAR_CONV)); delay(10); }
true
a327954a1e05f6299b6ed2f79c1f4014c2b19586
C++
DoktorNebel/Portfolio
/Evil Supermarket Tycoon/Evil Supermarkt Tycoon/Product.cpp
UTF-8
3,022
3
3
[]
no_license
#include "Product.h" Product::Product() { } Product::Product(ProductListItem* description, unsigned short amount, GameData* gameData, TextureHandler* texHandler) { this->Name = description->Name; this->Amount = amount; this->Quality = description->Quality; this->Price = description->Price; this->ExistenceDays = 0; this->DaysToExpire = description->MinDaysToExpire; this->ExpirationDate = gameData->Date; this->Sprite = texHandler->GetSprite(description->Name)[0][0]; for (int i = 0; i < this->DaysToExpire; i++) { this->ExpirationDate.Day++; if (this->ExpirationDate.Month == 2) { if (this->ExpirationDate.Day == 29) { this->ExpirationDate.Day = 1; this->ExpirationDate.Month++; } } else if ((this->ExpirationDate.Month % 2 == 0 && this->ExpirationDate.Month < 7) || (this->ExpirationDate.Month % 2 != 0 && this->ExpirationDate.Month > 7)) { if (this->ExpirationDate.Day == 31) { this->ExpirationDate.Day = 1; this->ExpirationDate.Month++; } } else { if (this->ExpirationDate.Day == 32) { this->ExpirationDate.Day = 1; this->ExpirationDate.Month++; } } if (this->ExpirationDate.Month == 13) { this->ExpirationDate.Month = 1; this->ExpirationDate.Year++; } } this->ExpirationState = Product::State::Good; this->Description = description->Description; } Product::~Product(void) { } void Product::update(GameData* gameData, std::list<FeedMessage>* feed, Entity* entity) { if (gameData->Date.Day != this->LastDay) { this->ExistenceDays++; this->LastDay = gameData->Date.Day; } if (this->ExistenceDays > this->DaysToExpire) { if (this->ExpirationState == Product::State::Good) { FeedMessage tmp; tmp.Message = this->Name + "ist abgelaufen."; tmp.Pointer = entity; feed->push_back(tmp); } this->ExpirationState = Product::State::Expired; if (this->ExistenceDays > this->DaysToExpire + 14) { this->ExpirationState = Product::State::Rotten; } } } void Product::draw(sf::RenderTarget& target, sf::RenderStates states) const { } void Product::refresh(GameData* gameData) { this->ExistenceDays = 0; this->ExpirationDate = gameData->Date; for (int i = 0; i < this->DaysToExpire; i++) { this->ExpirationDate.Day++; if (this->ExpirationDate.Month == 2) { if (this->ExpirationDate.Day == 29) { this->ExpirationDate.Day = 1; this->ExpirationDate.Month++; } } else if ((this->ExpirationDate.Month % 2 == 0 && this->ExpirationDate.Month < 7) || (this->ExpirationDate.Month % 2 != 0 && this->ExpirationDate.Month > 7)) { if (this->ExpirationDate.Day == 31) { this->ExpirationDate.Day = 1; this->ExpirationDate.Month++; } } else { if (this->ExpirationDate.Day == 32) { this->ExpirationDate.Day = 1; this->ExpirationDate.Month++; } } if (this->ExpirationDate.Month == 13) { this->ExpirationDate.Month = 1; this->ExpirationDate.Year++; } } this->ExpirationState = Product::State::Good; }
true
b808dfc6c6c75d95ddc7b17c9890e3483ed1fc6f
C++
bamby97/haptic-bullseye-3D
/TargetShootingVr/Logger.h
UTF-8
589
2.859375
3
[ "Apache-2.0" ]
permissive
#ifndef LOGGER_H #define LOGGER_H #include <iostream> #include <fstream> #include <vector> #include <iomanip> using namespace std; struct gameInfo { bool hitTarget; float timeRemaining; float projectilePosition[3]; float projectileVelocity[3]; float targetDepth; int throwNumber; int addedScore; int targetHit; }; class Logger { public: gameInfo info; void pushInfo(); void printInfo(); void setTotalScore(int score); void setFrameCount(float count); Logger(); private: ofstream myfile; vector<gameInfo> gameData; int totalScore; int frameCount; }; #endif
true
593e086fe61cd67dadefb0006b801f1d1a2e46bc
C++
Ghadeerof/cplusplus-practices
/ExampleOfPrintingInvoiceData.cpp
UTF-8
582
3.609375
4
[]
no_license
#include <iostream> using namespace std; int main() { int n; cout<<"Enter number of products : "<<endl; cin>>n; double units,price,partialPrice , totalPrice = 0; for(int i = 0; i < n; i++){ cout<<"Enter Units #" <<(i+1)<<endl; cin>>units; cout<<"Enter Price #" <<(i+1)<<endl; cin>>price; partialPrice = units * price; cout<<"Partial Price = "<<partialPrice<<endl; totalPrice = totalPrice + partialPrice; } cout<<"Total Price : "<<totalPrice<<endl; return 0; }
true
4914519c48eeefc0d44099066d75bb0b91990756
C++
things-i-want-to-forget/dismay5
/DCommand.h
UTF-8
1,007
2.53125
3
[]
no_license
#ifndef DCOMMAND #define DCOMMAND #include "DDismay.h" class DCommand; typedef void DCommandCallback_t(const char*); extern DDismay* dismay; class DCommand { public: DCommand() { } DCommand(const char* name, int fnCallback) { m_pszName = name; m_bIsLua = true; m_fnLuaCallback = fnCallback; m_pNext = 0; } DCommand(const char* name, DCommandCallback_t* fnCallback) { m_pszName = name; m_fnCallback = fnCallback; m_bIsLua = false; m_pNext = 0; } bool Callback(char* x) { if(m_bIsLua) { if(!m_fnLuaCallback) return 0; dismay->m_pLua->GetLuaInterface(2)->ReferencePush(m_fnLuaCallback); dismay->m_pLua->GetLuaInterface(2)->PushString(x, 0); dismay->m_pLua->GetLuaInterface(2)->Call(1,0); return 1; } else { if(!m_fnCallback) return 0; m_fnCallback(x); return 1; } } int m_fnLuaCallback; const char* m_pszName; DCommandCallback_t* m_fnCallback; DCommand* m_pNext; bool m_bIsLua; }; #endif // DCOMMAND
true
d666834bb61cbf71bc27b94c9c7055e90fd9745c
C++
yahoo/tunitas-basics
/src/tunitas/number/wc/to_numeric.xcpp
UTF-8
6,802
2.59375
3
[ "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
// This is -*- c++ -*- nearly C++23 with Modules TS but in the S.C.O.L.D. stylings that are so popular these days. // Copyright Yahoo Inc. // Licensed under the terms of the Apache-2.0 license. // For terms, see the LICENSE file at https://github.com/yahoo/tunitas-basics/blob/master/LICENSE // For terms, see the LICENSE file at https://git.tunitas.technology/all/components/basics/tree/LICENSE #divert <fpp> namespace tunitas::number::wc { namespace package_to_numeric { namespace body::exported { } namespace interface = body::exported; } using namespace package_to_numeric::interface; } #import nonstd.same_as #import tunitas.number.wc.required #import tunitas.number.mp.required.Carrier namespace tunitas::number::wc::package_to_numeric { using nonstd::same_as; namespace required { using namespace tunitas::number::wc::required; using mp::required::Carrier; template<typename MP, typename... MATCHES> concept Among = Carrier<MP> && (same_as<MP, MATCHES> && ... ); } namespace body { } } #endiv #divert <hpp> #import tunitas.number.mp.required.Carrier #import std.basic_string #import std.ios_base namespace tunitas::number::wc { namespace package_to_numeric::body { namespace exported { // // Construct a CARRIER by to_numericing from a string // // Specification: // // Construct from a wide string // // Design: // // From a narrow character \0-terminated character representation. // // Access the C++ constructor which accesses the C API. // Yes, this is supposed to be difficult to access; it is an implemenetation detail. // Yes, that's a raw character pointer htat you see there. Pull yourself together! It'll work fine! // // [[FIXTHIS?]] there is no way to communicate scientific or fixed into the CARRIER parsing. // // Observe: // mpf_class::mpf_class(std::string conts &) ........................................ NO precision AND NO base // mpf_class::mpf_class(std::string conts &, mp_bitcnt_t precision, int base = 0) ... optional base // // [[WATCHOUT]] the simple conversion constructor is NOT always the same as the 2-arg constructor with base=0 // e.g. see mpf_class // // Exceptions: // // throws std::invalid_argument if the syntax is wrong; does NOT throw exception::Invalid // per the underlying constructor of CARRIER::CARRIER(string const &) // // Responsibilities: // // It is the caller's responsibility to catch std::invalid_argument and to_numeric it to an appropriate numeric::exception::Aspect descendant // e.g. numeric::exception::Invalid when called from numeric::from_string(...) or numeric::from_string_view(...) // e.g. numeric::exception::Stream when in the context of a stream operation such as operator>>(...) // // Usage: // // Hack The Spew (it's an implemenation detail). // template<required::Carrier CARRIER, required::Character CHAR, required::Character_Traits TRAITS> inline auto to_numeric(std::basic_string<CHAR, TRAITS> const &) -> CARRIER; template<required::Among<mpz_class, mpq_class> CARRIER, required::Character CHAR, required::Character_Traits TRAITS> inline auto to_numeric(std::basic_string<CHAR, TRAITS> const &, int base) -> CARRIER; template<required::Among<mpf_class> CARRIER, required::Character CHAR, required::Character_Traits TRAITS> inline auto to_numeric(std::basic_string<CHAR, TRAITS> const &, mp::Precision, int base) -> CARRIER; template<required::Carrier CARRIER, required::Character CHAR, required::Character_Traits TRAITS> inline auto to_numeric(std::basic_string<CHAR, TRAITS> const &, std::ios_base const &) -> CARRIER; } inline auto integral_base(std::ios_base const &) -> int; // because 'int base' is the type in that certain constructor CARRIER::CARRIER(...) inline auto floating_base(std::ios_base const &) -> int; // eadem ratione } } #endiv #divert <ipp> #import tunitas.number.wc.narrow namespace tunitas::number::wc::package_to_numeric { template<required::Carrier CARRIER, required::Character CHAR, required::Character_Traits TRAITS> auto interface::to_numeric(std::basic_string<CHAR, TRAITS> const &syntax) -> CARRIER { if constexpr (same_as<CHAR, char>) { return CARRIER(syntax); // [[WATCHOUT]] - see the Observe clause above } else { return CARRIER(narrow(syntax)); } } template<required::Among<mpz_class, mpq_class> CARRIER, required::Character CHAR, required::Character_Traits TRAITS> auto interface::to_numeric(std::basic_string<CHAR, TRAITS> const &syntax, int base) -> CARRIER { if constexpr (same_as<CHAR, char>) { return CARRIER(syntax, base); } else { return CARRIER(narrow(syntax), base); } } template<required::Among<mpf_class> CARRIER, required::Character CHAR, required::Character_Traits TRAITS> auto interface::to_numeric(std::basic_string<CHAR, TRAITS> const &syntax, mp::Precision precision, int base) -> CARRIER { if constexpr (same_as<CHAR, char>) { return CARRIER{syntax, precision, base}; } else { return CARRIER{narrow(syntax), precision, base}; } } template<required::Carrier CARRIER, required::Character CHAR, required::Character_Traits TRAITS> auto interface::to_numeric(std::basic_string<CHAR, TRAITS> const &syntax, std::ios_base const &ios) -> CARRIER { if constexpr (same_as<CHAR, char>) { if constexpr (same_as<CARRIER, mpf_class>) { return CARRIER{syntax, ios.precision(), floating_base(ios)}; } else { return CARRIER{syntax, integral_base(ios)}; } } else { auto narrowed = narrow(syntax); if constexpr (same_as<CARRIER, mpf_class>) { return CARRIER{narrow(syntax), ios.precision(), floating_base(ios)}; } else { return CARRIER{narrow(syntax), integral_base(ios)}; } } } auto body::integral_base(std::ios_base const &ios) -> int { auto const flags = ios.flags(); if (flags & std::ios_base::dec) { return 10; } else if (flags & std::ios_base::oct) { return 8; } else if (flags & std::ios_base::hex) { return 16; } else { return 0; // which means something slightly different than base=10 } } auto body::floating_base(std::ios_base const &ios) -> int { auto const flags = ios.flags(); auto const scientific = flags & std::ios_base::scientific; auto const fixed = flags & std::ios_base::fixed; auto const hexfloat = scientific && fixed; if (hexfloat) { return 16; } else { return 0; // which means something slightly different than base=10 } } } #endiv
true
afeb82742490d6d70d887f131b4202a649a57606
C++
MorS25/cvg_quadrotor_swarm
/lib_cvglogger/src/source/dronelogfileswritter.cpp
UTF-8
2,697
2.78125
3
[ "BSD-3-Clause", "MIT" ]
permissive
#include "dronelogfileswritter.h" DroneLogfilesWritter::DroneLogfilesWritter(std::string stackPath) : init_date(boost::gregorian::day_clock::local_day()), init_time(boost::posix_time::microsec_clock::local_time()), eventslog_out(&eventslog_buf), flight_diary_out(&flight_diary_buf) { // creating events_logfile and fligth_diary_logfile std::stringstream s0, s1, s2, s3, s4, msg; s0 << stackPath << "logs/drone_logger"; s1 << s0.str() << "/date_" << "y" << (int) init_date.year() << "m" << std::setfill('0') << std::setw(2) << (int) init_date.month() << "d" << std::setfill('0') << std::setw(2) << (int) init_date.day(); s2 << s1.str() << "/time_" << init_time.time_of_day(); s3 << s2.str() << "/frontImage"; s4 << s2.str() << "/bottomImage"; fs::path logs_path; logs_path = fs::path(s0.str()); // std::cout << "is_directory " << logs_path << ": " << fs::is_directory(logs_path) << std::endl; if ( !(fs::is_directory(logs_path)) ) { fs::create_directory(logs_path); } fs::path daylogs_path = fs::path(s1.str()); // std::cout << "is_directory " << daylogs_path << ": " << fs::is_directory(daylogs_path) << std::endl; if ( !(fs::is_directory(daylogs_path)) ) { fs::create_directory(daylogs_path); } currentlog_path = fs::path(s2.str()); // std::cout << "is_directory " << currentlog_path << ": " << fs::is_directory(currentlog_path) << std::endl; if ( !(fs::is_directory(currentlog_path)) ) { fs::create_directory(currentlog_path); } if ( !(fs::is_directory(fs::path(s3.str()))) ) { fs::create_directory(fs::path(s3.str())); } if ( !(fs::is_directory(fs::path(s4.str()))) ) { fs::create_directory(fs::path(s4.str())); } eventslog_buf.open( (currentlog_path / fs::path("events_log.txt")).string() ); flight_diary_buf.open( (currentlog_path / fs::path("flight_diary.txt")).string() ); flight_diary_out << "Start time: " << init_time.time_of_day() << " of" << " year:" << (int) init_date.year() << " month:" << std::setfill('0') << std::setw(2) << (int) init_date.month() << " day:" << std::setfill('0') << std::setw(2) << (int) init_date.day() << std::endl; return; } DroneLogfilesWritter::~DroneLogfilesWritter() { // Note: for the buffer to be emptied into the logfile, the program must be closed with control+c eventslog_buf.close(); flight_diary_buf.close(); } void DroneLogfilesWritter::writeString2Logfile(std::string string_in) { eventslog_out << string_in; }
true
b020036908fb03c02850fbf2a32fbd54a8bf1e0d
C++
PeterH2N/SOP
/src/camera.hpp
ISO-8859-15
1,848
2.921875
3
[]
no_license
#ifndef CAMERA_H #define CAMERA_H // camera klsee er implementeret p baggrund af denne video: https://www.youtube.com/watch?v=ns9eVfHCYdg #include "mesh.hpp" #define YAW -90.0f #define PITCH 0.0f #define SPEED 6.0f #define SENSITIVITY 0.1f #define ZOOM 45.0f class Camera { public: Camera(sf::RenderWindow* _window, glm::fvec3 _position = { 0,0,0 }, glm::fvec3 _up = { 0, 1, 0 }, glm::vec3 _front = { 0, 0, -1 }, float _yaw = YAW, float _pitch = PITCH, float _speed = SPEED, float _sensitivity = SENSITIVITY, float _zoom = ZOOM); enum class camMovement { forward, backward, left, right, up, down }; private: sf::RenderWindow* window; float yaw; float pitch; float speed; float sensitivity; float zoom; // positionen af kameraet i world-space glm::fvec3 position; // vektor der betegner hvad op er i verden, uafhngig af hvordan kameraet er roteret. glm::fvec3 worldUp; // vektor der altid er parallel med xz planet, men peger samme retning som front. glm::fvec3 worldFront; // op i forhold til kameraets rotation glm::fvec3 up; // vektor der peger p det der kigges p glm::fvec3 front; // krydsprodukt af up og front. glm::fvec3 right; sf::Clock deltaClock; // funktion der opdaterer alle vektorer p baggrund af ndringer i andre vrdier void updateVectors(); // tager en bevgelse (forlns hjre osv) ind, og ndrer p positionen. void processKeyboard(camMovement, float deltaTime); // tager en ndring i x og y ind, og ndrer p yaw og pitch void processMouse(float xOffset, float yOffset, bool constrainPitch = true); // zoom, bruges ikke. void processScroll(float yOffset); public: // giver view matricen, der skal bruges til at afbilde punkter glm::mat4 getView(); // opsamling af al bevgelse, skal kaldes i loop. void doMovement(); }; #endif CAMERA_H
true
8243a6dea82bb260f679b1b3ce36e9fe38395996
C++
matheuslc/car-system
/doubly_linked_list.h
UTF-8
8,561
4.09375
4
[ "Apache-2.0" ]
permissive
#ifndef STRUCTURES_DOUBLY_LIST_H #define STRUCTURES_DOUBLY_LIST_H #include <cstdint> // std::size_t #include <stdexcept> // C++ exceptions template<typename T> class DoublyLinkedList { public: DoublyLinkedList(); ~DoublyLinkedList(); void clear(); void push_back(const T& data); void push_front(const T& data); void insert(const T& data, std::size_t index); void insert_sorted(const T& data); T pop(std::size_t index); T pop_back(); T pop_front(); void remove(const T& data); bool empty() const; bool contains(const T& data) const; std::size_t find(const T& data) const; std::size_t size() const; T& at(std::size_t index); T& at(std::size_t index) const; void printAll(); private: class Node { // Elemento public: explicit Node(const T& data): data_{data}, prev_{nullptr}, next_{nullptr} {} Node(const T& data, Node* next): data_{data}, prev_{nullptr}, next_{next} {} Node(const T& data, Node* prev, Node* next): data_{data}, prev_{prev}, next_{next} {} T& data() { // getter: dado return data_; } const T& data() const { // getter const: dado return data_; } Node* prev() { // getter: anterior return prev_; } const Node* prev() const { // getter const: anterior return prev_; } void prev(Node* node) { // setter: anterior prev_ = node; } Node* next() { // getter: próximo return next_; } const Node* next() const { // getter const: próximo return next_; } void next(Node* node) { // setter: próximo next_ = node; } private: T data_; Node* prev_{nullptr}; Node* next_{nullptr}; }; Node* head{nullptr}; Node* tail{nullptr}; std::size_t size_{0u}; }; template<typename T> DoublyLinkedList<T>::DoublyLinkedList(): head{nullptr}, tail{nullptr}, size_{0u} {} template<typename T> DoublyLinkedList<T>::~DoublyLinkedList() { clear(); } template<typename T> void DoublyLinkedList<T>::push_back(const T& data) { Node* newNode{new Node(data)}; if (empty()) { head = newNode; } else { tail->next( newNode); newNode->prev(tail); } tail = newNode; size_++; } template<typename T> void DoublyLinkedList<T>::push_front(const T& data) { Node* newNode{new Node(data, nullptr, head)}; if (empty()) { tail = newNode; } else { head->prev(newNode); } head = newNode; size_++; } template<typename T> void DoublyLinkedList<T>::insert(const T& data, std::size_t index) { if (index > size()) { throw std::out_of_range("Wrong position"); } if (empty() || index == 0) { push_front(data); return; } if (index == size()) { push_back(data); return; } Node* newNode{new Node(data)}; Node* helper = head; for (auto i = 0u; i < index; ++i) { helper = helper->next(); } newNode->next(helper); newNode->prev(helper->prev()); newNode->prev()->next(newNode); helper->prev(newNode); size_++; } template<typename T> void DoublyLinkedList<T>::insert_sorted(const T& data) { if (empty()) { push_front(data); return; } Node* helper = head; auto index = 0u; while (index < size_ && *data > *helper->data()) { index++; helper = helper->next(); } insert(data, index); } template<typename T> T DoublyLinkedList<T>::pop(std::size_t index) { if (empty()) { throw std::out_of_range("Empty list"); } if (index >= size_) { throw std::out_of_range("Posição inválida"); } if (index == 0) { return pop_front(); } if (index == size()-1) { return pop_back(); } Node* helper = head; for (auto i = 0u; i < index; ++i) { helper = helper->next(); } T requested = helper->data(); helper->prev()->next(helper->next()); helper->next()->prev(helper->prev()); delete helper; size_--; return requested; } template<typename T> T DoublyLinkedList<T>::pop_back() { if (empty()) { throw std::out_of_range("Empty list"); } Node* helper = tail; if (size() == 1) { tail = nullptr; head = nullptr; } else { tail = tail->prev(); tail->next(nullptr); } T requested = helper->data(); delete helper; size_--; return requested; } template<typename T> T DoublyLinkedList<T>::pop_front() { if (empty()) { throw std::out_of_range("Empty list"); } Node* helper = head; if (size() == 1) { head = nullptr; tail = nullptr; } else { head = head->next(); head->prev(nullptr); } T requested = helper->data(); delete helper; size_--; return requested; } template<typename T> void DoublyLinkedList<T>::remove(const T& data) { if (empty()) { throw std::out_of_range("Empty list"); } if (contains(data)) pop(find(data)); } template<typename T> std::size_t DoublyLinkedList<T>::find(const T& data) const { Node* helper = head; auto index = 0u; while ( (index < size_) && (data != helper->data()) ) { index++; helper = helper->next(); } return index; } template<typename T> void DoublyLinkedList<T>::clear() { Node* helper = head; while (helper != nullptr && helper->next() != nullptr) { helper = helper->next(); delete helper->prev(); } if (helper != nullptr) { delete helper; } head = nullptr; tail = nullptr; size_ = 0u; } template<typename T> std::size_t DoublyLinkedList<T>::size() const { return size_; } template<typename T> bool DoublyLinkedList<T>::empty() const { return (size_ == 0); } template<typename T> bool DoublyLinkedList<T>::contains(const T& data) const { return (find(data) >= 0 && find(data) < size_); } template<typename T> T& DoublyLinkedList<T>::at(std::size_t index) { if (empty()) { throw std::out_of_range("Empty list"); } if (index >= size_) { throw std::out_of_range("Wrong position"); } if (index == 0) { return head->data(); } if (index == size()-1) { return tail->data(); } Node* helper = head; for (auto i = 0u; i < index; ++i) { helper = helper->next(); } return helper->data(); } template<typename T> T& DoublyLinkedList<T>::at(std::size_t index) const { if (empty()) { throw std::out_of_range("Empty"); } if (index >= size_) { throw std::out_of_range("Wrong position"); } if (index == 0) { return head->data(); } if (index == size()-1) { return tail->data(); } Node* helper = head; for (auto i = 0u; i < index; ++i) { helper = helper->next(); } return helper->data(); } template<typename T> void DoublyLinkedList<T>::printAll() { Node* helper = head; auto index = 0u; while (helper != nullptr) { printf("i: %d - data: ", index); helper->data()->print(); index++; helper = helper->next(); } } #endif
true
a1e1eb9bc90dfe977dcd8bef20b8ddc1beb7f845
C++
kohstephen/transCnt
/calculation.h
UTF-8
3,345
2.71875
3
[]
no_license
#ifndef CALCULATION_H #define CALCULATION_H #include <vector> #include <string> #include "planewall.h" #include "planewallpoint.h" #include "infcylinder.h" #include "infcylinderpoint.h" #include "rectbar.h" #include "rectbarpoint.h" #include "cylinder.h" #include "cylinderpoint.h" #include "infrectbar.h" #include "infrectbarpoint.h" #include "sphere.h" #include "spherepoint.h" #include "constant.h" #include "envmat.h" using namespace std; extern const float PI; /** * Calculate temperature at a certain point. * The temperature will be set in the point provided by the user. */ void temp_at_point(PlaneWall &w, PlaneWallPoint &p, EnvMat &envmat); void temp_at_point(Sphere &s, SpherePoint &p, EnvMat &envmat); void temp_at_point(InfCylinder &icyl, InfCylinderPoint &p, EnvMat &envmat); void temp_at_point(RectBar &rb, RectBarPoint &p, EnvMat &envmat); void temp_at_point(Cylinder &cyl, CylinderPoint &p, EnvMat &envmat); void temp_at_point(InfRectBar &irb, InfRectBarPoint &p, EnvMat &envmat); void temp_on_mesh(PlaneWall &w, Secs secs, int mesh_density, EnvMat &envmat); void temp_on_mesh(InfCylinder &icyl, Secs secs, int mesh_density, EnvMat &envmat); void temp_on_mesh(Sphere &s, Secs secs, int mesh_density, EnvMat &envmat); void temp_on_mesh(InfRectBar &irb, Secs secs, int mesh_density, EnvMat &envmat); void temp_on_mesh(Cylinder &cyl, Secs secs, int mesh_density, EnvMat &envmat); void temp_on_mesh(RectBar &rb, Secs secs, int mesh_density, EnvMat &envmat); /** * Utility functions to convert Kelvin to Fahrenheit and Celcius, * and from Fahrenheit and Celcius to Kelvin. */ float kelvin_to_fahrenheit(Kelvin k); float kelvin_to_celcius(Kelvin k); Kelvin fahrenheit_to_kelvin(float f); Kelvin celcius_to_kelvin(float c); // avg float avg_temp_at_time(Sphere &s, Secs time, EnvMat &envmat); float avg_temp_at_time(PlaneWall &s, Secs time, EnvMat &envmat); float avg_temp_at_time(InfCylinder &s, Secs time, EnvMat &envmat); float avg_temp_at_time(Cylinder &s, Secs time, EnvMat &envmat); float avg_temp_at_time(RectBar &s, Secs time, EnvMat &envmat); float avg_temp_at_time(InfRectBar &s, Secs time, EnvMat &envmat); // Plot void plot(Sphere &s, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(PlaneWall &s, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(InfCylinder &s, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(Cylinder &s, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(RectBar &s, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(InfRectBar &s, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(Sphere &s, vector<SpherePoint> &p, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(PlaneWall &s, vector<PlaneWallPoint> &p, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(InfCylinder &s, vector<InfCylinderPoint> &p, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(Cylinder &s, vector<CylinderPoint> &p, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(RectBar &s, vector<RectBarPoint> &p, Secs start, Secs end, Secs intrv, EnvMat &envmat); void plot(InfRectBar &s, vector<InfRectBarPoint> &p, Secs start, Secs end, Secs intrv, EnvMat &envmat); #endif
true
1807ddd5e8dead266b3d8aaf4ac3b61f014bc057
C++
hsy77/Data_Code
/CLionProjects/data_structure/Maze/Maze.h
UTF-8
3,241
3.109375
3
[]
no_license
// // Created by rain on 2019/9/27. // #ifndef MAZE_MAZE_H #define MAZE_MAZE_H //#include <CirQueue> enum Error_code{underflow, overflow, success}; const int maxqueue = 20; // small value for testing template<class Queue_entry> class MyQueue{ public: MyQueue(); bool empty() const; Error_code serve(); Error_code append(const Queue_entry &item); Error_code retrieve(Queue_entry &item) const; bool full() const; int size() const; void clear(); Error_code serve_and_retrieve(Queue_entry &item); private: int count; int front, rear; Queue_entry entry[maxqueue]; }; template<class Queue_entry> MyQueue<Queue_entry>::MyQueue() /* Post: The Queue is initialized to be empty. */ { count = 0; rear = -1; front = 0; } template<class Queue_entry> bool MyQueue<Queue_entry>::empty() const /* Post: Return true if the Queue is empty, otherwise return false. */ { return count == 0; } template<class Queue_entry> Error_code MyQueue<Queue_entry>::append(const Queue_entry &item) /* Post: item is added to the rear of the Queue. If the Queue is full return an Error_code of overflow and leave the Queue unchanged. */ { //队尾下标已经到达数组的末尾。则溢出 if (rear >= maxqueue-1) return overflow; count++; rear++; //队尾下标往后移 entry[rear] = item; //新的元素入队 return success; } template<class Queue_entry> Error_code MyQueue<Queue_entry>::serve() /* Post: The front of the Queue is removed. If the Queue is empty return an Error_code of underflow. */ { if (count <= 0) return underflow; count--; front++;// 队首下标直接往后移 return success; } template<class Queue_entry> Error_code MyQueue <Queue_entry>::retrieve(Queue_entry &item) const /* Post: The front of the Queue retrieved to the output parameter item. If the Queue is empty return an Error_code of underflow. */ { if (count <= 0) return underflow; item = entry[front]; //读取队首下标位置的值 return success; } template<class Queue_entry> int MyQueue<Queue_entry>::size() const /* Post: Return the number of entries in the Queue. */ { return count; } template<class Queue_entry> bool MyQueue<Queue_entry>::full() const /* Post: Return true if the Queue is full, otherwise return false. */ { return(rear==maxqueue-1); } template<class Queue_entry> void MyQueue<Queue_entry>::clear() /* Post: Return an empty Queue. */ { count = 0; rear = -1 ; front = 0; } template<class Queue_entry> Error_code MyQueue<Queue_entry>::serve_and_retrieve(Queue_entry &item) { if (count <= 0) return underflow; item = entry[front]; count--; front++; return success;; } const int maxcolrow=8; struct point{ int row; int col; }; class Maze { public: Maze(); void initMaze(int *p_maze,int n_colrow_); void PrintBfsPath(); void printMaze(); private: point cur,next; bool cango_(int row,int col); int matrix_[maxcolrow+2][maxcolrow+2]; int visitedBFS_[maxcolrow+2][maxcolrow+2]; point PathBFS_[maxcolrow+2][maxcolrow+2];//存放结构 point pstart; point pend; int n_colrow; MyQueue<point> maxqueue_; }; #endif //MAZE_MAZE_H
true
4968d86370344e07329b3d82d55f46f5882e64ae
C++
frongtb/average
/average/Source.cpp
UTF-8
243
3.046875
3
[]
no_license
#include<stdio.h> int main() { float a, b, c; scanf_s("%f", &a); scanf_s("%f", &b); scanf_s("%f", &c); printf("frist number : %f\nsecond number : %f\nthird number : %f\n", a, b, c); printf("average is %f", (a + b + c) / 3); return 0; }
true
706efe31a9df3825fde5dfc786e09967890905a8
C++
musgravehill/aquaUdoPump
/Firmware_v1/FEEDER.ino
UTF-8
495
2.53125
3
[]
no_license
void FEEDER_1DOSE_init() { if ( (millis() - FEEDER_time_start_ms) > 61000L ) { //можно запустить 1 раз в течение конкретной минуты FEEDER_isFeed = true; FEEDER_time_start_ms = millis(); } } void FEEDER_1DOSE_process() { if (FEEDER_isFeed) { if ( (millis() - FEEDER_time_start_ms) <= FEEDER_1DOSE_ms) { //feed until time not ends RELAY_1_set(true); } else { RELAY_1_set(false); FEEDER_isFeed = false; } } }
true
2adf39feaa4fca7e20fef48af029267f86476da7
C++
Brygramming/InsandOuts_Bryan
/SS6-4_LED_Pattern/SS6-4_LED_Pattern.ino
UTF-8
2,689
3.078125
3
[]
no_license
//4 LED Pattern by Bryan Santiago //Button const int Button = 13; int ButtonState = 0; //Lights const int LightOne = 2; const int LightTwo = 3; const int LightThree = 4; const int LightFour = 5; void setup() { pinMode(Button, INPUT); pinMode(LightOne, OUTPUT); pinMode(LightTwo, OUTPUT); pinMode(LightThree, OUTPUT); pinMode(LightFour, OUTPUT); } void loop() { ButtonState = digitalRead(Button); delay(10); if(ButtonState == HIGH) { OnLightTrain(); OnLightTrain(); TrainCrash(); TrainCrash(); } else { digitalWrite(LightOne, LOW); digitalWrite(LightTwo, LOW); digitalWrite(LightThree, LOW); digitalWrite(LightFour, LOW); } } //LED Pattern 1 void OnLightTrain() { //Up to on digitalWrite(LightOne, HIGH); digitalWrite(LightTwo, LOW); digitalWrite(LightThree, LOW); digitalWrite(LightFour, LOW); delay(100); digitalWrite(LightOne, HIGH); digitalWrite(LightTwo, HIGH); digitalWrite(LightThree, LOW); digitalWrite(LightFour, LOW); delay(100); digitalWrite(LightOne, HIGH); digitalWrite(LightTwo, HIGH); digitalWrite(LightThree, HIGH); digitalWrite(LightFour, LOW); delay(100); digitalWrite(LightOne, HIGH); digitalWrite(LightTwo, HIGH); digitalWrite(LightThree, HIGH); digitalWrite(LightFour, HIGH); delay(100); //Down to off digitalWrite(LightOne, LOW); digitalWrite(LightTwo, HIGH); digitalWrite(LightThree, HIGH); digitalWrite(LightFour, HIGH); delay(100); digitalWrite(LightOne, LOW); digitalWrite(LightTwo, LOW); digitalWrite(LightThree, HIGH); digitalWrite(LightFour, HIGH); delay(100); digitalWrite(LightOne, LOW); digitalWrite(LightTwo, LOW); digitalWrite(LightThree, LOW); digitalWrite(LightFour, HIGH); delay(100); digitalWrite(LightOne, LOW); digitalWrite(LightTwo, LOW); digitalWrite(LightThree, LOW); digitalWrite(LightFour, LOW); delay(100); } //LED Pattern 2 void TrainCrash() { digitalWrite(LightOne, HIGH); digitalWrite(LightTwo, LOW); digitalWrite(LightThree, LOW); digitalWrite(LightFour, HIGH); delay(200); digitalWrite(LightOne, HIGH); digitalWrite(LightTwo, HIGH); digitalWrite(LightThree, HIGH); digitalWrite(LightFour, HIGH); delay(200); digitalWrite(LightOne, HIGH); digitalWrite(LightTwo, LOW); digitalWrite(LightThree, LOW); digitalWrite(LightFour, HIGH); delay(200); digitalWrite(LightOne, LOW); digitalWrite(LightTwo, LOW); digitalWrite(LightThree, LOW); digitalWrite(LightFour, LOW); delay(200); }
true
6f19f40254c527a3b2383be949b5e2844f976aa4
C++
cfriedt/leetcode
/cut-off-trees-for-golf-event.cpp
UTF-8
2,971
3.1875
3
[ "MIT" ]
permissive
/* * Copyright (c) 2021, Christopher Friedt * * SPDX-License-Identifier: MIT */ // clang-format off // name: cut-off-trees-for-golf-event // url: https://leetcode.com/problems/cut-off-trees-for-golf-event // difficulty: 3 // clang-format on #include <algorithm> #include <deque> #include <unordered_set> #include <vector> using namespace std; class Solution { public: // convert row/col to key int make_key(int row, int col, int d = 0) { return (unsigned(d) << 16) | (unsigned(row) << 8) | unsigned(col); } // convert from key to row / col void rc(int key, int &row, int &col) { col = (key >> 0) & 0xff; row = (key >> 8) & 0xff; } int get_d(int key) { return (key >> 16) & 0xff; } int bfs(const vector<vector<int>> &forest, int a, int b) { const int rows = forest.size(); const int cols = forest[0].size(); // keep track of visited nodes unordered_set<int> visited; // queue for bfs, stack for dfs deque<int> q; q.push_back(a); visited.insert(a); while (!q.empty()) { int key = q.front(); q.pop_front(); visited.insert(key); int d = get_d(key); if ((key & 0xffff) == b) { return d; } int r, c; rc(key, r, c); for (auto &n : vector<vector<int>>{ {r - 1, c}, {r, c + 1}, {r + 1, c}, {r, c - 1}}) { int nr = n[0]; int nc = n[1]; int nkey = make_key(nr, nc); if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) { continue; } if (forest[nr][nc] == 0) { continue; } if (visited.end() != visited.find(nkey)) { continue; } // here we do not add distance to the key visited.insert(nkey); // here we do add distance to the key nkey = make_key(nr, nc, d + 1); q.push_back(nkey); } } return -1; } int cutOffTree(vector<vector<int>> &forest) { /* The minimal total distance of trees in order from shortest to tallest is the sum of the minimal distances between trees in order. */ const int rows = forest.size(); const int cols = forest[0].size(); vector<int> trees; int dist = 0; // collect all of the "trees" (i.e. cells > 1) // O(MN) for (auto row = 0; row < rows; ++row) { for (auto col = 0; col < cols; ++col) { if (forest[row][col] > 1) { trees.push_back(make_key(row, col)); } } } // sort trees from smallest to largest sort(trees.begin(), trees.end(), [&](int a, int b) -> bool { int row_a, col_a; rc(a, row_a, col_a); int row_b, col_b; rc(b, row_b, col_b); return forest[row_a][col_a] < forest[row_b][col_b]; }); auto src = make_key(0, 0); for (auto tgt : trees) { auto d = bfs(forest, src, tgt); if (d == -1) { return -1; } dist += d; src = tgt; } return dist; } };
true
4c69b6dd3ad5e78a5748619bfa031a302ade3701
C++
jpommerening/template-hell
/units/si_units.h
UTF-8
2,544
2.828125
3
[ "MIT" ]
permissive
#ifndef _SI_UNITS__H #define _SI_UNITS__H #include "unit.h" namespace SIUnits { /** * SI base units. * @{ */ class m : public Unit::unit< Unit::length > { public: static const char * const name; }; class g : public Unit::unit< Unit::mass > { public: static const char * const name; }; class s : public Unit::unit< Unit::time > { public: static const char * const name; }; class A : public Unit::unit< Unit::electric_current > { public: static const char * const name; }; class K : public Unit::unit< Unit::thermodynamic_temperature > { public: static const char * const name; }; class cd : public Unit::unit< Unit::luminous_intensity > { public: static const char * const name; }; class mol : public Unit::unit< Unit::amount_of_substance > { public: static const char * const name; }; /** @} */ /** * SI prefixes. * @{ */ namespace { template <class u, int i> class SIPrefix : public Unit::unit< typename u::quantity, Conversion::compound_conversion< typename u::conversion, Conversion::decimal_conversion<i> > > { public: static const char * const name; }; } template <class u> class yotta : public SIPrefix< u, 24 > {}; template <class u> class zetta : public SIPrefix< u, 21 > {}; template <class u> class exa : public SIPrefix< u, 18 > {}; template <class u> class peta : public SIPrefix< u, 15 > {}; template <class u> class tera : public SIPrefix< u, 12 > {}; template <class u> class giga : public SIPrefix< u, 9 > {}; template <class u> class mega : public SIPrefix< u, 6> {}; template <class u> class kilo : public SIPrefix< u, 3> {}; template <class u> class hecto : public SIPrefix< u, 2 > {}; template <class u> class deca : public SIPrefix< u, 1 > {}; template <class u> class deci : public SIPrefix< u, -1 > {}; template <class u> class centi : public SIPrefix< u, -2 > {}; template <class u> class milli : public SIPrefix< u, -3 > {}; template <class u> class micro : public SIPrefix< u, -6 > {}; template <class u> class nano : public SIPrefix< u, -9 > {}; template <class u> class pico : public SIPrefix< u, -12 > {}; template <class u> class femto : public SIPrefix< u, -15 > {}; template <class u> class atto : public SIPrefix< u, -18 > {}; template <class u> class zepto : public SIPrefix< u, -21 > {}; template <class u> class yocto : public SIPrefix< u, -24 > {}; /** @} */ } #endif
true
ced4729ea6fb7440b6ef7905560af2473d54ea10
C++
GoingMyWay/LeetCode
/1482-how-many-numbers-are-smaller-than-the-current-number/solution.cpp
UTF-8
545
2.859375
3
[]
no_license
class Solution { public: vector<int> smallerNumbersThanCurrent(vector<int>& nums) { vector<int> count(101, 0); vector<int> res(nums.size(), 0); for (int i =0; i < nums.size(); i++) { count[nums[i]]++; } for (int i = 1 ; i <= 100; i++) { count[i] += count[i-1]; } for (int i = 0; i < nums.size(); i++) { if (nums[i] == 0) res[i] = 0; else res[i] = count[nums[i] - 1]; } return res; } };
true
c0040141ff0fbf2415906c00363285627125ffb8
C++
muhammadtarek98/data-structure-c-implemenation-
/linkedlist.cpp
UTF-8
4,042
3.65625
4
[]
no_license
#include<bits/stdc++.h> using namespace std; //my code class linked_list { private: struct node { int item; node *next; }; node *first,*last; int length; public: linked_list() { first=NULL; last=NULL; length=0; } bool IsEmpty() { if(length==0) { return true; } return false; } void insertfirst(int element) { node *newnode=new node(); newnode->item=element; if(length==0) { first=last=newnode; newnode->next=NULL; } else { newnode->next=first; first=newnode; } length++; } void insertlast(int element) { node *newnode=new node(); newnode->item=element; if(length==0) { first=last=newnode; newnode->next=NULL; } else { last->next=newnode; newnode->next=NULL; last=newnode; } length++; } void insertAtPos(int pos,int element) { if(pos<0||pos>length) { cout<<"Out of range"<<endl; } else { node *newnode=new node(); newnode->item=element; if(pos==0) { insertfirst(element); } else if(pos==length) { insertlast(element); } else { node *cur=first; for(int i=1;i<pos;i++) { cur=cur->next; } newnode->next=cur->next; cur->next=newnode; } } length++; } void print() { node *cur=first; while (cur!=NULL) { cout<<cur->item; if(cur->next!=NULL) {cout<<"->";} cur=cur->next; } } int sz() { return length; } void removefront() { if(length==0||IsEmpty()) { cout<<"List empty"<<endl; return; } else if(length==1) { delete first; first=last=NULL; } else { node *temp=first; first=first->next; delete temp; } length--; } int searchelement(int element) { node *cur=first; int pos=0; while (cur!=NULL) { if(cur->item==element) { return pos; break; } cur=cur->next; pos++; } return -1; } void removeend() { node *cur=first->next; node *prev=first; if(length==0) { cout<<"List empty"<<endl; return; } else if(length==1) { delete last; first=last=NULL; } else { while (cur!=last) { prev=cur; cur=cur->next; } delete cur; last=prev; } length--; } void removepos(int element) { node *cur,*prev; if(length==0) { cout<<"List empty"<<endl; return; } if(first->item==element) { cur=first; first=first->next; delete cur; if(length==0) { last=NULL; } } else { cur=first->next; prev=first; while (cur!=NULL) { if(cur->item==element) { break; } prev=cur; cur=cur->next; } if(cur==NULL) { cout<<"element isn't found"<<endl; return; } else { prev->next=cur->next; if(cur==last) { last=prev; } delete cur; } } length--; } void reverses() { node *prev=NULL,*cur=first,*nxt; nxt=cur->next; while(nxt!=NULL) { nxt=cur->next; cur->next=prev; prev=cur; cur=nxt; } first=prev; } ~linked_list() { } }; int main() { linked_list l; l.insertfirst(21); l.insertlast(34); l.insertlast(16); l.print(); cout<<" size ="<<l.sz(); cout<<endl; l.reverses(); l.print(); cout<<endl; cout<<l.searchelement(56); return 0; }
true
af65c49c2f7c30002207c0833d033cb542dd10fc
C++
jswilder/squealing-prune
/asg4/FiloTree.cpp
UTF-8
3,937
3.1875
3
[]
no_license
// Jeremy Wilder // Asg4 #ifndef FILOTREE_CPP #define FILOTREE_CPP #include <vector> #include <iostream> #include <fstream> #include <string> #include <sstream> using namespace std; #include "FiloTree.h" FiloTree::FiloTree(string fileName){ int i, j; // Read in the file of course.. ifstream infile; infile.open( fileName.c_str() ); if( ! infile ) { cout << "could not open file" << fileName << endl; return; } // Read in size infile >> size; double array[size][size]; string word[size]; //Reads in the words for( i=0; i<size; i++){ infile >> word[i]; } //Reads in the numbers as doubles for( i=0; i<size; i++){ for(j=0; j<size; j++){ infile >> array[i][j]; } } infile.close( ); /*---------------------------------------------------------------------------*/ int x, y, z; // i & j storage for min double min; for( z=0; z<size-1; z++){ // Begin finding neighbors min = 100000000000000000; //finds two closest values - O( n^2 ) for(i=0; i< size; i++){ for( j=0; j<size; j++){ if( array[i][j] != 0 && min > array[i][j] ){ min = array[i][j]; x = i; y = j; } } } //Creates nodes out of the closest strings //Add them to the vector of nodes for the tree - constant time Node *Parent = new Node( word[x], word[y] ); nodes.push_back( *Parent ); // Replaces first word in the vector with combined word // erases the other word[x] = Parent->name; word[y] = ""; // Calculates new vals, storing them in [i][x] & [x][i] // [i][y] & [y][i] become zeros - O( n ); for(i=0; i<size; i++){ array[x][i] = ( ( array[x][i] + array[y][i] ) / 2 ); array[i][x] = array[x][i]; array[y][i] = array[i][y] = 0; if( x == i ) array[x][i] = 0; } } //Ends Neighbor-Finding loop } /*-------*/ FiloTree::~FiloTree( ){ nodes.clear( ); } /*-------*/ void FiloTree::dump( ) const{ int s = nodes.size(); cout << "\n\n\t****Dumping tree****\n"; while( s != 0 ){ cout << "\nMerge " << s-- << endl; cout << "........." << nodes[s].left->name << endl; cout << "........." << nodes[s].right->name << endl; } cout << endl << endl; } /*-------*/ void FiloTree::compare( const FiloTree &A, const FiloTree &B){ // A simple check, if the tree sizes dont match they can't be equal if( A.nodes.size() != B.nodes.size() ){ cout << "\nThe trees are NOT equal\n\n"; return; } int count, i, j, x; count = 0; for( i=0; i< A.nodes.size( ); i++){ for( j=0; j< B.nodes.size(); j++){ x = 0; // Compares all children agaisnt each other // if any node matches another, count is incremented // if count equals the size, the trees match if( A.nodes[i].left->name == B.nodes[j].left->name) x++; if( A.nodes[i].right->name == B.nodes[j].right->name) x++; if( A.nodes[i].left->name == B.nodes[j].right->name) x++; if( A.nodes[i].right->name == B.nodes[j].left->name) x++; if( x == 2 ) count++; } } if( count == A.nodes.size( ) ) cout << "\nThe trees are equal\n\n"; if( count != A.nodes.size() ) cout << "\nThe trees are NOT equal\n\n"; } void FiloTree::printNodes( FiloTree &A ){ int s = A.nodes.size(); cout << endl; while( s != 0 ){ s--; cout << A.nodes[s].left->name << " , " << A.nodes[s].right->name << endl; } } /*-------*/ //----------------------------------------------------------------------------- //-----------NODE IMPLEMENTATION----------------------------------------------- //----------------------------------------------------------------------------- //Creates a child Node::Node( string word ){ name = word; parent = NULL; left = NULL; right = NULL; } //Creates a parent node Node::Node( string a , string b ){ Node *A = new Node( a ); Node *B = new Node( b ); if( a[0] < b[0] ){ name = a + b; this->left = A; this->right = B; } else{ name = b + a; this->left = B; this->right = A; } } #endif
true
4381cc65cfa879e441e977f5f2ca015cbda1325b
C++
danbergeland/PencilDurabilitySim
/PencilSim/PaperTest.cpp
UTF-8
2,419
3.453125
3
[]
no_license
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <string> #include "Paper.h" TEST_CASE("Read and write update text","[paper]") { Paper p; p.write("abc"); REQUIRE(p.read() == "abc"); } TEST_CASE("Clear_at turns letters to spaces","[paper]") { Paper p; p.write("space"); //Intended functionality p.clear_at(0,5); REQUIRE(p.read().compare(" ")==0); //Writing resumes at end of white space p.write("after"); REQUIRE(p.read().compare(" after")==0); } TEST_CASE("clear_at only works in existing range", "[paper]") { Paper p; p.write("space"); //Clear with negative index doesn't work unsigned int i = -1; p.clear_at(i,3); REQUIRE(p.read().compare("space")==0); } TEST_CASE("clear_at can't extend text","[paper]") { Paper p; p.write("space"); //Clear beyond text length doesn't work p.clear_at(0,20); REQUIRE(p.read().compare("space")==0); } TEST_CASE("Write_at overwrites spaces","[paper]") { Paper p; p.write(" "); p.write_at(2,"St"); p.write_at(0,"Po"); REQUIRE(p.read() == "PoSt "); //write into erased space p.clear_at(0,3); p.write_at(0,"lis"); REQUIRE(p.read() == "list "); } TEST_CASE("write_at can't write to negative index","[paper]") { Paper p; p.write("list "); //Don't allow writing to negative index p.write_at(-1,"lis"); REQUIRE(p.read() == "list "); } TEST_CASE("write_at can't extend existing text","[paper]") { Paper p; p.write("list "); //Don't allow using "write_at" beyond existing text space p.write_at(0,"Listening"); REQUIRE(p.read()=="list "); } TEST_CASE("write_at can't write to index beyond text space","[paper]") { Paper p; p.write("list "); //Don't allow indexing beyond existing text p.write_at(30,"list"); REQUIRE(p.read()=="list "); } TEST_CASE("Write_at obscures letters","[paper]") { Paper p; p.write(" BC "); p.write_at(0,"Post"); REQUIRE(p.read() == "P@@t "); /* * For example, writing "artichoke" in the middle of * "An a day keeps the doctor away" would result in * "An artich@k@ay keeps the doctor away". */ Paper p2; p2.write("An a day keeps the doctor away"); p2.write_at(3,"artichoke"); REQUIRE(p2.read() == "An artich@k@ay keeps the doctor away"); }
true
e8cbfcf337df5088ac4e13b7d0766f332f1cfb63
C++
GT-TDAlab/SARMA
/include/algorithms/uniform.hpp
UTF-8
2,724
3.03125
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#pragma once /** * @brief This namespace contains required functions for * the uniform (checker-board) partitioning. Uniform partitioning * is one of the straightforward algorithms that is used to solve * mLI problem. Its dual (sarma::uniform::bal) solves the mNC problem */ #if defined(ENABLE_CPP_PARALLEL) namespace sarma::uniform { #else namespace sarma{ namespace uniform { #endif /** * @brief Implements the uniform (checker-board) partitioning * taking number of rows and number of cuts as parameters. * * @param N number of rows * @param P number of parts * @tparam Ordinal data-type of indptr and indices structures in sarma::Matrix * @return a cut vector */ template<class Ordinal> std::vector<Ordinal> partition(const Ordinal N, const Ordinal P) { std::vector<Ordinal> p; p.reserve(P + 1); for (Ordinal i = 0; i <= P; i++) p.push_back(i * 1ll * N / P); return p; } template <class Ordinal, class Value> auto bal(const Matrix<Ordinal, Value> &A, const Value Z); /** * @brief Implements the Uniform (Uni) checker-board partitioning * It basically returns equally spaced cuts. Note that if Z is * greater than zero then this function overrides P and calls * the dual of the uniform partitioning that solves MNc problem. * * @param A Matrix * @param P number of parts * @param Z Target load * @tparam Ordinal data-type of indptr and indices structures in sarma::Matrix * @return a cut vector */ template<class Ordinal, class Value> std::vector<Ordinal> partition(const Matrix<Ordinal, Value> &A, const Ordinal P, const Value Z=0) { if (Z>0) return bal (A, Z); return partition(A.N(), P); } /** * @brief Implements Bound a Load (BaL) algorithm using UNI as * the mLI algorithm. * * @param A Matrix * @param Z Target load * @tparam Ordinal data-type of indptr and indices structures in sarma::Matrix * @tparam Value data-type of data structure in sarma::Matrix * @return a cut vector */ template <class Ordinal, class Value> auto bal(const Matrix<Ordinal, Value> &A, const Value Z) { auto l = (Ordinal)1; Ordinal r = A.N() / std::sqrt(Z) + 1; while (l < r) { const auto m = l + (r - l) / 2; const auto cuts = sarma::uniform::partition(A.N(), m); const auto ld = A.compute_maxload(cuts, cuts); if (ld > Z) l = m + 1; else r = m; } return sarma::uniform::partition(A.N(), l); } } #if !defined(ENABLE_CPP_PARALLEL) } // nested namespace #endif
true
e263d76b9574d3bd2c4f8597be5658cda82da8b5
C++
niofire/Deuterium-Engine
/Deuterium/Common/d_enum.h
UTF-8
344
3.015625
3
[]
no_license
#pragma once #include <string> namespace deuterium { class dEnum { public: dEnum(int enum_id, const std::string& enum_str) { _enum_id = enum_id; _enum_str = enum_str; } ~dEnum(); const int id() {return _enum_id;} const std::string& to_string() { return _enum_str;} private: int _enum_id; std::string _enum_str; }; }
true
b6049835008828379547bc789c48aec017b9ecdd
C++
Guy-Git/ComputerGraphicsCourse
/Viewer/include/MeshModel.h
UTF-8
1,988
2.625
3
[]
no_license
#pragma once #include <glad/glad.h> #include <glm/glm.hpp> #include <string> #include <memory> #include "MeshModel.h" #include "Face.h" struct Vertex { glm::vec3 position; glm::vec3 normal; glm::vec2 textureCoords; }; class MeshModel { protected: std::vector<Face> faces_; std::vector<glm::vec3> vertices_; std::vector<glm::vec3> normals; std::vector<glm::vec3> textureCoords; std::vector<Vertex> modelVertices; glm::mat4x4 modelTransform; glm::mat4x4 worldTransform; std::string modelName; glm::vec3 color; GLuint vbo; GLuint vao; public: MeshModel(std::vector<Face> faces, std::vector<glm::vec3> vertices, std::vector<glm::vec3> normals, std::vector<glm::vec2> textureCoords, const std::string& modelName = ""); virtual ~MeshModel(); const glm::mat4x4& GetWorldTransformation() const; const glm::mat4x4& GetModelTransformation() const; void SetWorldTransformation(const glm::mat4x4& worldTransform); void SetModelTransformation(const glm::mat4x4& modelTransform); const glm::vec3& GetColor() const; void SetColor(const glm::vec3& color); const std::string& GetModelName(); const std::vector<Vertex>& GetModelVertices(); Face& GetFace(int index); int GetFacesCount() const; const glm::vec3& GetVertex(int index) const; void PlanarTexture(); void SphericalTexture(); void CylindricalTexture(); void TranslateModel(const glm::vec3& translationVector); void TranslateWorld(const glm::vec3& translationVector); void RotateXModel(double angle); void RotateYModel(double angle); void RotateZModel(double angle); void ScaleXModel(double factor); void ScaleYModel(double factor); void ScaleZModel(double factor); void ScaleModel(double factor); void RotateXWorld(double angle); void RotateYWorld(double angle); void RotateZWorld(double angle); void ScaleXWorld(double factor); void ScaleYWorld(double factor); void ScaleZWorld(double factor); void ScaleWorld(double factor); GLuint GetVAO() const; GLuint GetVBO() const; };
true
f2c28b9ba9760954ade4b4a159fe2322a7027623
C++
Galathorn/desktop-tutorial
/NPuzzleAStar/npuzzle/npuzzle/src/Astar.class.cpp
UTF-8
3,651
2.609375
3
[]
no_license
#include "../includes/Astar.class.hpp" using namespace std; Astar::Astar(void) : Algorithm() {} Astar::~Astar(void) {} std::list<std::string> Astar::findPath(nPuzzle &p) { p.setLastMove(""); std::list<std::string> path; std::list<nPuzzle> openSet = std::list<nPuzzle>(); std::list<nPuzzle> closedSet = std::list<nPuzzle>(); openSet.push_back(p); int cycle = 0; while (openSet.size() > 0) { cycle++; std::list<nPuzzle>::iterator current = openSet.begin(); std::list<nPuzzle>::iterator it = openSet.begin(); ++it; std::list<nPuzzle>::iterator end = openSet.end(); for (; it != end; ++it) if ((*it).fCost() < (*current).fCost() || ((*it).fCost() == (*current).fCost() && (*it).getHcost() < (*current).getHcost())) current = it; closedSet.splice(closedSet.end(), openSet, current); setTimeComplexity(getTimeComplexity() + 1); (*current).fillEmpty((*current).getSize()); if ((*current).getHcost() <= 0 && (*current).isGoal()) { nPuzzle *c = (*current).getParent(); if (c == nullptr) return path; path.push_back((*current).getLastMove()); while (c->getId() > 0) { path.push_back(c->getLastMove()); c = c->getParent(); } path.reverse(); return path; } std::vector<nPuzzle > neighbours = std::vector<nPuzzle>(); nPuzzle n; if ((*current).getEmpty()->getPos().getY() + 1 < (*current).getSize() && isMovementOpposite("UP", (*current).getLastMove()) == false) { n = nPuzzle((*current).getSize()); (*current).copyData(&n); n.Up(); neighbours.push_back(n); } if ((*current).getEmpty()->getPos().getY() - 1 >= 0 && isMovementOpposite("DOWN", (*current).getLastMove()) == false) { n = nPuzzle((*current).getSize()); (*current).copyData(&n); n.Down(); neighbours.push_back(n); } if ((*current).getEmpty()->getPos().getX() - 1 >= 0 && isMovementOpposite("RIGHT", (*current).getLastMove()) == false) { n = nPuzzle((*current).getSize()); (*current).copyData(&n); n.Right(); neighbours.push_back(n); } if ((*current).getEmpty()->getPos().getX() + 1 < (*current).getSize() && isMovementOpposite("LEFT", (*current).getLastMove()) == false) { n = nPuzzle((*current).getSize()); (*current).copyData(&n); n.Left(); neighbours.push_back(n); } for (short i = 0; i < neighbours.size(); ++i) { if (std::find(closedSet.begin(), closedSet.end(), neighbours[i]) != closedSet.end()) continue; neighbours[i].fillEmpty(neighbours[i].getSize()); bool contains = std::find(openSet.begin(), openSet.end(), neighbours[i]) == openSet.end() ? false : true; short newMovementCostToNeighbour = (*current).getHeuristicMod() & UNIFORM ? 0 : ((*current).getGcost() + 1); if (newMovementCostToNeighbour < neighbours[i].getGcost() || contains == false) { neighbours[i].setGcost(newMovementCostToNeighbour); neighbours[i].setParent(&(*current)); if (contains == false) { openSet.push_back(neighbours[i]); if (getSizeComplexity() < openSet.size()) setSizeComplexity(openSet.size()); } } } } return path; } bool Astar::isMovementOpposite(std::string const &currentMove, std::string const &lastMove) { if ((lastMove == "UP" && currentMove == "DOWN") || (lastMove == "DOWN" && currentMove == "UP")) return true; if ( (lastMove == "RIGHT" && currentMove == "LEFT") || (lastMove == "LEFT" && currentMove == "RIGHT")) return true; return false; }
true
6d855db16798262874136c3ec5011bfb53cadfd7
C++
37947538/Young3_7
/Classes/GameTools/GameStatePause.cpp
UTF-8
1,147
2.515625
3
[]
no_license
// // GameStatePause.cpp // hero3_2 // // Created by jl on 14-9-25. // // #include "GameStatePause.h" #include "BulletObject.h" #include "BulletBLL.h" GameStatePause* GameStatePause::instance() { static GameStatePause instance; return &instance; } void GameStatePause::enter(GameBLL* gb) { } void GameStatePause::execute(GameBLL* aHero) { } void GameStatePause::exit(GameBLL* gb) { //怪恢复 for (auto &e : gb->vectorEnemy) { e->getArmature()->resume(); e->resume(); } //子弹恢复 for (auto &b : BulletBLL::getInstance()->vectorBullets) { b->resume(); } //英雄恢复 for (auto &t : gb->vectorHero) { t->getArmature()->resume(); t->resume(); } } void GameStatePause::executeTime(GameBLL* gb,float dt) { //怪暂停 for (auto &e : gb->vectorEnemy) { e->getArmature()->pause(); e->pause(); } //子弹暂停 for (auto &b : BulletBLL::getInstance()->vectorBullets) { b->pause(); } //英雄暂停 for (auto &t : gb->vectorHero) { t->getArmature()->pause(); t->pause(); } }
true
d9690c1406aa983f2fc64ebb970967c5c9d31fe3
C++
deephealthproject/eddl
/src/serialization/onnx/net/layers/operators/sum_onnx.cpp
UTF-8
2,097
2.578125
3
[ "MIT" ]
permissive
#if defined(cPROTO) #include "eddl/serialization/onnx/layers/operators/mult_onnx.h" #include "eddl/layers/normalization/layer_normalization.h" #include "eddl/serialization/onnx/utils_onnx.h" // ONNX import Layer* build_sum_layer(onnx::NodeProto *node, map<string, vector<float>> &map_init_values, map<string, vector<int>> &map_init_dims, map<string, Layer *> &output_node_map, int dev, int mem) { string first_operator_name = node->input(0); Layer *first_operator = output_node_map[first_operator_name]; string second_operator_name = node->input(1); if(map_init_dims.count(second_operator_name)) { vector<float> scalars = map_init_values[second_operator_name]; if (scalars.size() == 1) { return new LSum(first_operator, scalars[0], node->name(), dev, mem); } else { msg("Error: The second input summand of the Sum layer " + node->name() + " is not valid", "ONNX::ImportNet"); return nullptr; } } Layer *second_operator = output_node_map[second_operator_name]; return new LSum(first_operator, second_operator, node->name(), dev, mem); } // ONNX export void build_sum_node(LSum *layer, onnx::GraphProto *graph) { // Add an empty node to the graph onnx::NodeProto *node = graph->add_node(); node->set_op_type("Sum"); node->set_name(layer->name); // Set the inputs names of the node from the parents of the layer for (Layer *parentl : layer->parent) { node->add_input(parentl->name); } // Set the name of the output of the node to link with other nodes node->add_output(layer->name); if (!layer->binary) { string value_name(layer->name + "_value"); node->add_input(value_name); // Add the value initializer as input // Create the value initializer onnx::TensorProto *sum_value = graph->add_initializer(); sum_value->set_name(value_name); sum_value->set_data_type(onnx::TensorProto::FLOAT); sum_value->add_float_data(layer->val); } } #endif // defined(cPROTO)
true
70c662a21f8e8d45b211d06845f71fd52161136f
C++
nischalbasuti/JNTUH-AA-Lab-2016
/02.heapsort/hs.cpp
UTF-8
941
4
4
[ "MIT" ]
permissive
#include<iostream> void max_heapify(int arr[],int n, int i){ int largest = i; int left = 2*i + 1; int right = 2*i + 2; //left is larger than root if(left < n && arr[left] > arr[largest]){ largest = left; } //if right is larger than largest if(right < n && arr[right] > arr[largest]){ largest = right; } //if largest is not the root if(largest != i){ std::swap(arr[i],arr[largest]); //heapify the effected subtree max_heapify(arr,n,largest); } } void heapsort(int arr[], int n){ for(int i = n/2; i >= 0; i--){ max_heapify(arr, n, i); } for(int i = n-1 ; i >= 0; i--){ std::swap(arr[0], arr[i]); max_heapify(arr, i, 0); } } void printArray(int arr[], int n){ for (int i=0; i<n; ++i) std::cout << arr[i] << " "; std::cout << std::endl; } int main(){ int arr[] = {12, 11, 13, 5, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); heapsort(arr, n); std::cout << "Sorted array is \n"; printArray(arr, n); }
true
079b185187c209e2b0584247c50f1a9bb489f880
C++
pyo7410/Study
/baek/2588_mul_parsing/2588_mul_parsing/소스.cpp
UTF-8
355
3.28125
3
[]
no_license
#include <iostream> using namespace std; int main() { int num1, num2; int n1, n2, n3; cin >> num1 >> num2; n1 = num2 / 100; n2 = (num2 - (n1 * 100)) / 10; n3 = num2 - (n1 * 100) - (n2 * 10); cout << num1 * n3 << endl; cout << num1 * n2 << endl; cout << num1 * n1 << endl; cout << (num1 * n1 * 100) + (num1 * n2 * 10) + (num1 * n3) << endl; }
true
df0301a5aa58df67ca2585e5fa1caf8a2d225989
C++
johngirvin/KoolBox
/Sources/KoolBox/Graphics/Batcher.h
UTF-8
5,244
2.703125
3
[ "MIT" ]
permissive
#ifndef KOOLBOX_GRAPHICS_BATCHER_H #define KOOLBOX_GRAPHICS_BATCHER_H #include "KoolBox.h" namespace KoolBox { class Batcher : private NonCopyable { public: // constructor // ibCount - number of indices to batch at most // vbCount - number of vertices to batch at most Batcher(u16 ibCount = UINT16_MAX-4, u16 vbCount = UINT16_MAX-4); ~Batcher(); // batcher lifecycle management // call begin() before attempting any batcher operations // call end() after the last batcher operation void begin(); void end(); // pipeline state management // the batcher will avoid redundant updates of pipeline state where possible // each update that is required will force a flush() (ie: a draw call) void set(Program *newProgram); void set(Program &newProgram); void set(TextureUnit newUnit, Texture *newTex, TextureFilter newTexFilter = Kore::Graphics4::PointFilter, TextureAddressing newTexAddressing = Kore::Graphics4::Clamp); void set(ConstantLocation location, float v0); void set(ConstantLocation location, float v0, float v1); void set(ConstantLocation location, float v0, float v1, float v2); void set(ConstantLocation location, float v0, float v1, float v2, float v3); void set(ConstantLocation location, float *values, u32 size); void set(ConstantLocation location, Mat4 &matrix); // allocate space in the batcher's buffers to store user indices and vertices // iWant - number of indices required, or 0 to not allocate any // if iWant is 0, iPtr is ignored // vWant - number of vertices required, or 0 to not allocate any // if vWant is 0, vPtr and vPos are ignored // iPtr - *iPtr will be set to the allocated index space // vPtr - *vPtr[0]...*vPtr[n] will be set to the allocated vertex spaces // (one per configured inputlayout in the current pipeline) // vPos - *vPos will be set to the initial vertex index allocated void allocate(u16 iWant, u16 vWant, int **iPtr, float **vPtr, u16 *vPos); // force a flush of the currently batched primitives void flush(); // TODO: more statistics u32 drawCalls; private: // number of indices in index buffer u16 ibCount; // number of vertices in each vertex buffer u16 vbCount; // status flags bool begun; bool locked; // pipeline state management typedef struct PrState { u32 programId = UINT32_MAX; } PrState; typedef struct TxState { u32 textureId = UINT32_MAX; TextureFilter filter = Kore::Graphics4::PointFilter; TextureAddressing addressing = Kore::Graphics4::Clamp; } TxState; typedef struct CnVnState { u32 locationId = UINT32_MAX; u32 size = 0; float v[4] = { 0 }; } CnVnState; typedef struct CnM4State { u32 locationId = UINT32_MAX; Mat4 mat4; } CnM4State; typedef struct IbState { IndexBuffer *buffer = nullptr; int *data = nullptr; void clear() { buffer = nullptr; data = nullptr; } } IbState; typedef struct VbState { VertexBuffer *buffer = nullptr; float *data = nullptr; u32 fpv = 0; void clear() { buffer = nullptr; data = nullptr; fpv = 0; } } VbState; struct BatcherState { PrState program; Map<u32,TxState> texture; Map<u32,CnVnState> cnvn; Map<u32,CnM4State> cnm4; IbState ib; VbState vb[8]; // current index/vertex positions u16 ibPos; u16 vbPos; void clear() { program.programId = UINT32_MAX; texture.clear(); cnvn.clear(); cnm4.clear(); ib.clear(); for (int i = 0; i < 8; i++) { vb[i].clear(); } ibPos = 0; vbPos = 0; } } state; // the index buffer IndexBuffer *ib = nullptr; // map indicating which VertexBuffer to use for a given VertexStructure id Map<u32,VertexBuffer*> buffersForStructures; // get or create a VertexBuffer to hold vertices in vertexStructure format // one buffer will be allocated per batcher per unique vertexStructure VertexBuffer *getVertexBuffer(const VertexStructure &vertexStructure); // prepare buffers for use void lock(); void unlock(); }; } #endif
true
ba750ef05337c193a1b464b80e3cf80f8d915d79
C++
Jeonghwan-Yoo/brain_cpp
/25_성적표ver3/student.cpp
UHC
5,644
3.65625
4
[]
no_license
//25_21 #include "BaseOutput.h" #include "student.h" #include <iostream> #include <iomanip> //25_15 #include <sstream> using namespace std; // //sNo:й Student::Student(int sNo) { //й this->sNo = sNo; // ʱȭ kor = eng = math = 0; ave = 0.0f; } // Ҹ Student::~Student() { } // Է ޴´. //ڷκ Է ޾Ƽ ϰ ձ Ѵ. //ڱ ִ ִ ڱ ϴ ߿. void Student::Input() { while (1) { //ش л ̸, , , Է ޴´. cout << "̸() , , Էϼ : \n"; cin >> name >> kor >> eng >> math; // ٸ ݺ . //good() cinü ¸ ϴ Լ. //ľ¶ false ȯ. if (cin.good()) break; // ִٸ cin ü ʱȭѴ. //ľ¶ ٽ ǵ Ѵ. //clear() ľ¸ · . cin.clear(); //ignore() cinü Է Լ. //numeric_limits<streamsize>::max() Է . <limits> cin.ignore(numeric_limits<streamsize>::max(), '\n'); //ȳ ޽ Ѵ. cout << "[Է ߸Ǿϴ.]\n"; } //ش л ̸, , , Է ޴´. //cout << "̸() , , Էϼ : \n"; //cin >> name >> kor >> eng >> math; // Ѵ. ave = float(kor + eng + math) / 3.0f; } //25_15 // ȭ鿡 Ѵ. // out : °ü void Student::Show(BaseOutput& out) const { //BaseOutput&Ÿ . // ϳ ڿ . //ڿ 迭 ϱⰡ . stringstream ss; ss.precision(2); ss << fixed; ss << sNo << " " << name << " " << kor << " "; ss << eng << " " << math << " - " << ave; //7 ڿ 迭 ʱȭѴ. //տ ڿ ɰ ڿ 迭 . string record[7]; for (int i = 0; i < 7;i++) ss >> record[i]; //л ü . //л ڿ 迭 ü ϸ ü Ÿ . out.PutRecord(record); } /* // ȭ鿡 Ѵ. // ȭ鿡 . void Student::Show() const { //26_9 cout << setw(7) << sNo << setw(7) << name; cout << setw(5) << kor << setw(5) << eng; cout << setw(5) << math << setw(9) << "-"; cout << setw(7) << ave << "\n"; cout << setw(7) << sNo << setw(7) << name; cout << setw(5) << kor << setw(5) << eng; cout << setw(5) << math << setw(7) << ave << "\n"; } */ //ڵ int Student::GetStdNumber() const { return sNo; } string Student::GetName() const { return name; } int Student::GetKor() const { return kor; } int Student::GetEng() const { return eng; } int Student::GetMath() const { return math; } float Student::GetAverage() const { return ave; } //25_9 // //θ ڸ ȣؼ StudentŬ κ ʱȭѴ. EngStudent::EngStudent(int sNo) : Student(sNo) { //EngStudent ִ ʱȭѴ. hi_eng = 0; } // Է ޴´. void EngStudent::Input() { //25_29 cin ó // Է ݺ while (1) { //ش л ̸, , , , Է ޴´. cout << "̸() , , , ޿ Էϼ : \n"; cin >> name >> kor >> eng >> math >> hi_eng; // ٸ ݺ . //good() cinü ¸ ϴ Լ. //ľ¶ false ȯ. if (cin.good()) break; // ִٸ cin ü ʱȭѴ. //ľ¶ ٽ ǵ Ѵ. //clear() ľ¸ · . cin.clear(); //ignore() cinü Է Լ. //numeric_limits<streamsize>::max() Է . <limits> cin.ignore(numeric_limits<streamsize>::max(), '\n'); //ȳ ޽ Ѵ. cout << "[Է ߸Ǿϴ.]\n"; } //ش л ̸, , , , Է ޴´. //cout << "̸() , , , ޿ Էϼ : \n"; //cin >> name >> kor >> eng >> math >> hi_eng; // Ѵ. ave = float(kor + eng + math + hi_eng) / 4.0f; } //25_15 void EngStudent::Show(BaseOutput& out) const { // ϳ ڿ . stringstream ss; ss.precision(2); ss << fixed; ss << sNo << " " << name << " " << kor << " "; ss << eng << " " << math << " " << hi_eng << " " << ave; //7 ڿ 迭 ʱȭѴ. string record[7]; for (int i = 0; i < 7;i++) ss >> record[i]; // ü . out.PutRecord(record); } /* void EngStudent::Show() const { cout << setw(7) << sNo << setw(7) << name; cout << setw(5) << kor << setw(5) << eng; cout << setw(5) << math << setw(9) << hi_eng; cout << setw(7) << ave << "\n"; } */
true
92bba7f038c273fe05ab4dcd2f227021c7cc2a6b
C++
EdsonYamamoto/URI-Online-Judge-Beginner
/1176.cpp
UTF-8
857
3.421875
3
[]
no_license
/* URI Online Judge | 1176 Fibonacci em Vetor Adaptado por Neilor Tonin, URI Brasil Timelimit: 1 Faça um programa que leia um valor e apresente o número de Fibonacci correspondente a este valor lido. Lembre que os 2 primeiros elementos da série de Fibonacci são 0 e 1 e cada próximo termo é a soma dos 2 anteriores a ele. Todos os valores de Fibonacci calculados neste problema devem caber em um inteiro de 64 bits sem sinal. Entrada A primeira linha da entrada contém um inteiro T, indicando o número de casos de teste. Cada caso de teste contém um único inteiro N (0 ≤ N ≤ 60), correspondente ao N-esimo termo da série de Fibonacci. Saída Para cada caso de teste da entrada, imprima a mensagem "Fib(N) = X", onde X é o N-ésimo termo da série de Fibonacci. Exemplo de Entrada Exemplo de Saída 3 0 4 2 Fib(0) = 0 Fib(4) = 3 Fib(2) = 1 */
true
88555686279830c2ac22800531d3a78e3ed23d39
C++
quanhuynh2007/oop
/matrix/matrixVer1/fractionOperator.h
UTF-8
833
2.609375
3
[]
no_license
#ifndef _Fraction_h #define _Fraction_h #include <iostream> #include <math.h> #include <fstream> #include <vector> #include <iomanip> #include <string> #define FLT_EPSILON (float)1.19209e-07 #define ulong unsigned long using namespace std; class Fraction { private: ulong numerator; ulong denominator; public: Fraction(); Fraction(ulong, ulong); float getF() const { return ((float)numerator/denominator); } void compact(); const Fraction operator+(const Fraction&) const; const Fraction operator*(const Fraction&) const; bool operator==(const Fraction&) const; // operator overloading << friend ostream& operator<<(ostream &out, const Fraction& src); // friend ostream& operator<<(ostream &out, const float); friend istream& operator>> (istream &is, Fraction& src); }; #endif
true
70aec619f47a825fc0702a3b3d21f042c49a20a8
C++
uchile/bh-motion_ros-pkg
/src/bh_src/Src/Representations/Modeling/ObstacleModel.cpp
UTF-8
2,219
2.890625
3
[]
no_license
/** * @file ObstacleModel.cpp * Implementation of class ObstacleModel * @author <a href="mailto:Tim.Laue@dfki.de">Tim Laue</a> */ #include "ObstacleModel.h" //#include "Tools/Debugging/DebugDrawings.h" /* void ObstacleModel::draw() { DECLARE_DEBUG_DRAWING("representation:ObstacleModel", "drawingOnField"); DECLARE_DEBUG_DRAWING("representation:ObstacleModelReduced", "drawingOnField"); COMPLEX_DRAWING("representation:ObstacleModel", { for(std::vector<Obstacle>::const_iterator it = obstacles.begin(), end = obstacles.end(); it != end; ++it) { const Obstacle& obstacle = *it; const Vector2<>& a = obstacle.leftCorner; const Vector2<>& b = obstacle.rightCorner; ColorClasses::Color color = obstacle.type == Obstacle::US ? ColorClasses::robotBlue : obstacle.type == Obstacle::ARM ? ColorClasses::yellow : ColorClasses::black; LINE("representation:ObstacleModel", 0, 0, a.x, a.y, 30, Drawings::ps_solid, color); LINE("representation:ObstacleModel", 0, 0, b.x, b.y, 30, Drawings::ps_solid, color); LINE("representation:ObstacleModel", a.x, a.y, b.x, b.y, 30, Drawings::ps_solid, color); CROSS("representation:ObstacleModel", obstacle.center.x, obstacle.center.y, 100, 20, Drawings::ps_solid, ColorClasses::blue); CROSS("representation:ObstacleModel", obstacle.closestPoint.x, obstacle.closestPoint.y, 100, 20, Drawings::ps_solid, ColorClasses::red); } }); COMPLEX_DRAWING("representation:ObstacleModelReduced", { for(std::vector<Obstacle>::const_iterator it = obstacles.begin(), end = obstacles.end(); it != end; ++it) { const Obstacle& obstacle = *it; const Vector2<>& a = obstacle.leftCorner; const Vector2<>& b = obstacle.rightCorner; ColorClasses::Color color = obstacle.type == Obstacle::US ? ColorClasses::robotBlue : obstacle.type == Obstacle::ARM ? ColorClasses::yellow : ColorClasses::black; LINE("representation:ObstacleModelReduced", 0, 0, a.x, a.y, 30, Drawings::ps_solid, color); LINE("representation:ObstacleModelReduced", 0, 0, b.x, b.y, 30, Drawings::ps_solid, color); LINE("representation:ObstacleModelReduced", a.x, a.y, b.x, b.y, 30, Drawings::ps_solid, color); } }); } */
true
d26db0e06ad4166a0dc24d856742c1c9b9d61877
C++
judefdiv/chipSmith
/include/toml/toml/value.hpp
UTF-8
41,615
2.640625
3
[ "MIT" ]
permissive
// Copyright Toru Niina 2017. // Distributed under the MIT License. #ifndef TOML11_VALUE_HPP #define TOML11_VALUE_HPP #include "traits.hpp" #include "into.hpp" #include "utility.hpp" #include "exception.hpp" #include "storage.hpp" #include "region.hpp" #include "types.hpp" #include <vector> #include <tuple> #include <unordered_map> #include <cassert> #include <cstdint> #if __cplusplus >= 201703L #include <string_view> #endif namespace toml { namespace detail { // to show error messages. not recommended for users. region_base const& get_region(const value&); template<typename Region> void change_region(value&, Region&&); }// detail template<typename T> struct value_traits { constexpr static value_t type_index = detail::check_type<T>(); constexpr static bool is_toml_type = detail::is_valid(detail::check_type<T>()); typedef typename detail::toml_default_type<type_index>::type type; }; template<typename T> constexpr value_t value_traits<T>::type_index; template<typename T> constexpr bool value_traits<T>::is_toml_type; class value { template<typename T, typename U> static void assigner(T& dst, U&& v) { const auto tmp = ::new(std::addressof(dst)) T(std::forward<U>(v)); assert(tmp == std::addressof(dst)); } using region_base = detail::region_base; public: value() noexcept : type_(value_t::Empty), region_info_(std::make_shared<region_base>(region_base{})) {} ~value() noexcept {this->cleanup();} value(const value& v): type_(v.type()), region_info_(v.region_info_) { switch(v.type()) { case value_t::Boolean : assigner(boolean_ , v.boolean_ ); break; case value_t::Integer : assigner(integer_ , v.integer_ ); break; case value_t::Float : assigner(floating_ , v.floating_ ); break; case value_t::String : assigner(string_ , v.string_ ); break; case value_t::OffsetDatetime: assigner(offset_datetime_, v.offset_datetime_); break; case value_t::LocalDatetime : assigner(local_datetime_ , v.local_datetime_ ); break; case value_t::LocalDate : assigner(local_date_ , v.local_date_ ); break; case value_t::LocalTime : assigner(local_time_ , v.local_time_ ); break; case value_t::Array : assigner(array_ , v.array_ ); break; case value_t::Table : assigner(table_ , v.table_ ); break; default: break; } } value(value&& v): type_(v.type()), region_info_(std::move(v.region_info_)) { switch(this->type_) { case value_t::Boolean : assigner(boolean_ , std::move(v.boolean_ )); break; case value_t::Integer : assigner(integer_ , std::move(v.integer_ )); break; case value_t::Float : assigner(floating_ , std::move(v.floating_ )); break; case value_t::String : assigner(string_ , std::move(v.string_ )); break; case value_t::OffsetDatetime: assigner(offset_datetime_, std::move(v.offset_datetime_)); break; case value_t::LocalDatetime : assigner(local_datetime_ , std::move(v.local_datetime_ )); break; case value_t::LocalDate : assigner(local_date_ , std::move(v.local_date_ )); break; case value_t::LocalTime : assigner(local_time_ , std::move(v.local_time_ )); break; case value_t::Array : assigner(array_ , std::move(v.array_ )); break; case value_t::Table : assigner(table_ , std::move(v.table_ )); break; default: break; } } value& operator=(const value& v) { this->cleanup(); this->region_info_ = v.region_info_; this->type_ = v.type(); switch(this->type_) { case value_t::Boolean : assigner(boolean_ , v.boolean_ ); break; case value_t::Integer : assigner(integer_ , v.integer_ ); break; case value_t::Float : assigner(floating_ , v.floating_ ); break; case value_t::String : assigner(string_ , v.string_ ); break; case value_t::OffsetDatetime: assigner(offset_datetime_, v.offset_datetime_); break; case value_t::LocalDatetime : assigner(local_datetime_ , v.local_datetime_ ); break; case value_t::LocalDate : assigner(local_date_ , v.local_date_ ); break; case value_t::LocalTime : assigner(local_time_ , v.local_time_ ); break; case value_t::Array : assigner(array_ , v.array_ ); break; case value_t::Table : assigner(table_ , v.table_ ); break; default: break; } return *this; } value& operator=(value&& v) { this->cleanup(); this->region_info_ = std::move(v.region_info_); this->type_ = v.type(); switch(this->type_) { case value_t::Boolean : assigner(boolean_ , std::move(v.boolean_ )); break; case value_t::Integer : assigner(integer_ , std::move(v.integer_ )); break; case value_t::Float : assigner(floating_ , std::move(v.floating_ )); break; case value_t::String : assigner(string_ , std::move(v.string_ )); break; case value_t::OffsetDatetime: assigner(offset_datetime_, std::move(v.offset_datetime_)); break; case value_t::LocalDatetime : assigner(local_datetime_ , std::move(v.local_datetime_ )); break; case value_t::LocalDate : assigner(local_date_ , std::move(v.local_date_ )); break; case value_t::LocalTime : assigner(local_time_ , std::move(v.local_time_ )); break; case value_t::Array : assigner(array_ , std::move(v.array_ )); break; case value_t::Table : assigner(table_ , std::move(v.table_ )); break; default: break; } return *this; } // boolean ============================================================== value(boolean b) : type_(value_t::Boolean), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->boolean_, b); } value& operator=(boolean b) { this->cleanup(); this->type_ = value_t::Boolean; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->boolean_, b); return *this; } template<typename Container> value(boolean b, detail::region<Container> reg) : type_(value_t::Boolean), region_info_(std::make_shared<detail::region<Container>>(std::move(reg))) { assigner(this->boolean_, b); } // integer ============================================================== template<typename T, typename std::enable_if<detail::conjunction< std::is_integral<T>, detail::negation<std::is_same<T, boolean>>>::value, std::nullptr_t>::type = nullptr> value(T i) : type_(value_t::Integer), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->integer_, static_cast<integer>(i)); } template<typename T, typename Container, typename std::enable_if< detail::conjunction<std::is_integral<T>, detail::negation<std::is_same<T, boolean>> >::value, std::nullptr_t>::type = nullptr> value(T i, detail::region<Container> reg) : type_(value_t::Integer), region_info_(std::make_shared<detail::region<Container>>(std::move(reg))) { assigner(this->integer_, static_cast<integer>(i)); } template<typename T, typename std::enable_if<detail::conjunction< std::is_integral<T>, detail::negation<std::is_same<T, boolean>>>::value, std::nullptr_t>::type = nullptr> value& operator=(T i) { this->cleanup(); this->type_ = value_t::Integer; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->integer_, static_cast<integer>(i)); return *this; } // floating ============================================================= template<typename T, typename std::enable_if< std::is_floating_point<T>::value, std::nullptr_t>::type = nullptr> value(T f) : type_(value_t::Float), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->floating_, f); } template<typename T, typename Container, typename std::enable_if< std::is_floating_point<T>::value, std::nullptr_t>::type = nullptr> value(T f, detail::region<Container> reg) : type_(value_t::Float), region_info_(std::make_shared<detail::region<Container>>(std::move(reg))) { assigner(this->floating_, f); } template<typename T, typename std::enable_if< std::is_floating_point<T>::value, std::nullptr_t>::type = nullptr> value& operator=(T f) { this->cleanup(); this->type_ = value_t::Float; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->floating_, f); return *this; } // string =============================================================== value(toml::string s) : type_(value_t::String), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->string_, std::move(s)); } template<typename Container> value(toml::string s, detail::region<Container> reg) : type_(value_t::String), region_info_(std::make_shared<detail::region<Container>>(std::move(reg))) { assigner(this->string_, std::move(s)); } value& operator=(toml::string s) { this->cleanup(); this->type_ = value_t::String; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->string_, s); return *this; } value(std::string s) : type_(value_t::String), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->string_, toml::string(std::move(s))); } value& operator=(std::string s) { this->cleanup(); this->type_ = value_t::String; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->string_, toml::string(std::move(s))); return *this; } value(std::string s, string_t kind) : type_(value_t::String), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->string_, toml::string(std::move(s), kind)); } value(const char* s) : type_(value_t::String), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->string_, toml::string(std::string(s))); } value& operator=(const char* s) { this->cleanup(); this->type_ = value_t::String; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->string_, toml::string(std::string(s))); return *this; } value(const char* s, string_t kind) : type_(value_t::String), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->string_, toml::string(std::string(s), kind)); } #if __cplusplus >= 201703L value(std::string_view s) : type_(value_t::String), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->string_, toml::string(s)); } value& operator=(std::string_view s) { this->cleanup(); this->type_ = value_t::String; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->string_, toml::string(s)); return *this; } value(std::string_view s, string_t kind) : type_(value_t::String), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->string_, toml::string(s, kind)); } #endif // local date =========================================================== value(const local_date& ld) : type_(value_t::LocalDate), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->local_date_, ld); } template<typename Container> value(const local_date& ld, detail::region<Container> reg) : type_(value_t::LocalDate), region_info_(std::make_shared<detail::region<Container>>(std::move(reg))) { assigner(this->local_date_, ld); } value& operator=(const local_date& ld) { this->cleanup(); this->type_ = value_t::LocalDate; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->local_date_, ld); return *this; } // local time =========================================================== value(const local_time& lt) : type_(value_t::LocalTime), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->local_time_, lt); } template<typename Container> value(const local_time& lt, detail::region<Container> reg) : type_(value_t::LocalTime), region_info_(std::make_shared<detail::region<Container>>(std::move(reg))) { assigner(this->local_time_, lt); } value& operator=(const local_time& lt) { this->cleanup(); this->type_ = value_t::LocalTime; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->local_time_, lt); return *this; } template<typename Rep, typename Period> value(const std::chrono::duration<Rep, Period>& dur) : type_(value_t::LocalTime), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->local_time_, local_time(dur)); } template<typename Rep, typename Period> value& operator=(const std::chrono::duration<Rep, Period>& dur) { this->cleanup(); this->type_ = value_t::LocalTime; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->local_time_, local_time(dur)); return *this; } // local datetime ======================================================= value(const local_datetime& ldt) : type_(value_t::LocalDatetime), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->local_datetime_, ldt); } template<typename Container> value(const local_datetime& ldt, detail::region<Container> reg) : type_(value_t::LocalDatetime), region_info_(std::make_shared<detail::region<Container>>(std::move(reg))) { assigner(this->local_datetime_, ldt); } value& operator=(const local_datetime& ldt) { this->cleanup(); this->type_ = value_t::LocalDatetime; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->local_datetime_, ldt); return *this; } // offset datetime ====================================================== value(const offset_datetime& odt) : type_(value_t::OffsetDatetime), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->offset_datetime_, odt); } template<typename Container> value(const offset_datetime& odt, detail::region<Container> reg) : type_(value_t::OffsetDatetime), region_info_(std::make_shared<detail::region<Container>>(std::move(reg))) { assigner(this->offset_datetime_, odt); } value& operator=(const offset_datetime& odt) { this->cleanup(); this->type_ = value_t::OffsetDatetime; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->offset_datetime_, odt); return *this; } value(const std::chrono::system_clock::time_point& tp) : type_(value_t::OffsetDatetime), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->offset_datetime_, offset_datetime(tp)); } value& operator=(const std::chrono::system_clock::time_point& tp) { this->cleanup(); this->type_ = value_t::OffsetDatetime; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->offset_datetime_, offset_datetime(tp)); return *this; } // array ================================================================ value(const array& ary) : type_(value_t::Array), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->array_, ary); } template<typename Container> value(const array& ary, detail::region<Container> reg) : type_(value_t::Array), region_info_(std::make_shared<detail::region<Container>>(std::move(reg))) { assigner(this->array_, ary); } value& operator=(const array& ary) { this->cleanup(); this->type_ = value_t::Array; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->array_, ary); return *this; } template<typename T, typename std::enable_if<value_traits<T>::is_toml_type, std::nullptr_t>::type = nullptr> value(std::initializer_list<T> list) : type_(value_t::Array), region_info_(std::make_shared<region_base>(region_base{})) { array ary; ary.reserve(list.size()); for(auto& elem : list) {ary.emplace_back(std::move(elem));} assigner(this->array_, std::move(ary)); } template<typename T, typename std::enable_if<value_traits<T>::is_toml_type, std::nullptr_t>::type = nullptr> value& operator=(std::initializer_list<T> list) { this->cleanup(); this->type_ = value_t::Array; this->region_info_ = std::make_shared<region_base>(region_base{}); array ary; ary.reserve(list.size()); for(auto& elem : list) {ary.emplace_back(std::move(elem));} assigner(this->array_, std::move(ary)); return *this; } template<typename T, typename std::enable_if<detail::is_container<T>::value, std::nullptr_t>::type = nullptr> value(T&& list) : type_(value_t::Array), region_info_(std::make_shared<region_base>(region_base{})) { array ary; ary.reserve(list.size()); for(const auto& elem : list) {ary.emplace_back(elem);} assigner(this->array_, std::move(ary)); } template<typename T, typename std::enable_if<detail::is_container<T>::value, std::nullptr_t>::type = nullptr> value& operator=(T&& list) { this->cleanup(); this->type_ = value_t::Array; this->region_info_ = std::make_shared<region_base>(region_base{}); array ary; ary.reserve(list.size()); for(const auto& elem : list) {ary.emplace_back(elem);} assigner(this->array_, std::move(ary)); return *this; } // table ================================================================ value(const table& tab) : type_(value_t::Table), region_info_(std::make_shared<region_base>(region_base{})) { assigner(this->table_, tab); } template<typename Container> value(const table& tab, detail::region<Container> reg) : type_(value_t::Table), region_info_(std::make_shared<detail::region<Container>>(std::move(reg))) { assigner(this->table_, tab); } value& operator=(const table& tab) { this->cleanup(); this->type_ = value_t::Table; this->region_info_ = std::make_shared<region_base>(region_base{}); assigner(this->table_, tab); return *this; } value(std::initializer_list<std::pair<key, value>> list) : type_(value_t::Table), region_info_(std::make_shared<region_base>(region_base{})) { table tab; for(const auto& elem : list) {tab[elem.first] = elem.second;} assigner(this->table_, std::move(tab)); } value& operator=(std::initializer_list<std::pair<key, value>> list) { this->cleanup(); this->type_ = value_t::Array; this->region_info_ = std::make_shared<region_base>(region_base{}); table tab; for(const auto& elem : list) {tab[elem.first] = elem.second;} assigner(this->table_, std::move(tab)); return *this; } // user-defined ========================================================= // convert using into_toml() method ------------------------------------- template<typename T, typename std::enable_if<detail::conjunction< detail::negation<detail::is_exact_toml_type<T>>, // not a toml::value detail::has_into_toml_method<T> // but has `into_toml` method >::value, std::nullptr_t>::type = nullptr> value(const T& ud): value(ud.into_toml()) {} template<typename T, typename std::enable_if<detail::conjunction< detail::negation<detail::is_exact_toml_type<T>>, // not a toml::value detail::has_into_toml_method<T> // but has `into_toml` method >::value, std::nullptr_t>::type = nullptr> value& operator=(const T& ud) { *this = ud.into_toml(); return *this; } // convert using into<T> struct ----------------------------------------- template<typename T, typename std::enable_if< detail::negation<detail::is_exact_toml_type<T>>::value, std::nullptr_t>::type = nullptr, std::size_t S = sizeof(::toml::into<T>)> value(const T& ud): value(::toml::into<T>::into_toml(ud)) {} template<typename T, typename std::enable_if< detail::negation<detail::is_exact_toml_type<T>>::value, std::nullptr_t>::type = nullptr, std::size_t S = sizeof(::toml::into<T>)> value& operator=(const T& ud) { *this = ::toml::into<T>::into_toml(ud); return *this; } // for internal use ------------------------------------------------------ template<typename T, typename Container, typename std::enable_if< detail::is_exact_toml_type<T>::value, std::nullptr_t>::type = nullptr> value(std::pair<T, detail::region<Container>> parse_result) : value(std::move(parse_result.first), std::move(parse_result.second)) {} // type checking and casting ============================================ template<typename T> bool is() const noexcept {return value_traits<T>::type_index == this->type_;} bool is(value_t t) const noexcept {return t == this->type_;} bool is_uninitialized() const noexcept {return this->is(value_t::Empty );} bool is_boolean() const noexcept {return this->is(value_t::Boolean );} bool is_integer() const noexcept {return this->is(value_t::Integer );} bool is_float() const noexcept {return this->is(value_t::Float );} bool is_string() const noexcept {return this->is(value_t::String );} bool is_offset_datetime() const noexcept {return this->is(value_t::OffsetDatetime);} bool is_local_datetime() const noexcept {return this->is(value_t::LocalDatetime );} bool is_local_date() const noexcept {return this->is(value_t::LocalDate );} bool is_local_time() const noexcept {return this->is(value_t::LocalTime );} bool is_array() const noexcept {return this->is(value_t::Array );} bool is_table() const noexcept {return this->is(value_t::Table );} value_t type() const {return type_;} template<value_t T> typename detail::toml_default_type<T>::type& cast() &; template<value_t T> typename detail::toml_default_type<T>::type const& cast() const&; template<value_t T> typename detail::toml_default_type<T>::type&& cast() &&; boolean const& as_boolean() const {return this->cast<value_t::Boolean >();} integer const& as_integer() const {return this->cast<value_t::Integer >();} floating const& as_float() const {return this->cast<value_t::Float >();} string const& as_string() const {return this->cast<value_t::String >();} offset_datetime const& as_offset_datetime() const {return this->cast<value_t::OffsetDatetime>();} local_datetime const& as_local_datetime() const {return this->cast<value_t::LocalDatetime >();} local_date const& as_local_date() const {return this->cast<value_t::LocalDate >();} local_time const& as_local_time() const {return this->cast<value_t::LocalTime >();} array const& as_array() const {return this->cast<value_t::Array >();} table const& as_table() const {return this->cast<value_t::Table >();} boolean& as_boolean() {return this->cast<value_t::Boolean >();} integer& as_integer() {return this->cast<value_t::Integer >();} floating& as_float() {return this->cast<value_t::Float >();} string& as_string() {return this->cast<value_t::String >();} offset_datetime& as_offset_datetime() {return this->cast<value_t::OffsetDatetime>();} local_datetime& as_local_datetime() {return this->cast<value_t::LocalDatetime >();} local_date& as_local_date() {return this->cast<value_t::LocalDate >();} local_time& as_local_time() {return this->cast<value_t::LocalTime >();} array& as_array() {return this->cast<value_t::Array >();} table& as_table() {return this->cast<value_t::Table >();} std::string comment() const { return this->region_info_->comment(); } std::string comment_before() const { return this->region_info_->comment_before(); } std::string comment_inline() const { return this->region_info_->comment_inline(); } private: void cleanup() noexcept { switch(this->type_) { case value_t::String : {string_.~string(); return;} case value_t::Array : {array_.~array_storage(); return;} case value_t::Table : {table_.~table_storage(); return;} default : return; } } // for error messages friend region_base const& detail::get_region(const value&); template<typename Region> friend void detail::change_region(value&, Region&&); template<value_t T> struct switch_cast; private: using array_storage = detail::storage<array>; using table_storage = detail::storage<table>; value_t type_; // for error message information. std::shared_ptr<region_base> region_info_; union { boolean boolean_; integer integer_; floating floating_; string string_; offset_datetime offset_datetime_; local_datetime local_datetime_; local_date local_date_; local_time local_time_; array_storage array_; table_storage table_; }; }; namespace detail { inline region_base const& get_region(const value& v) { return *(v.region_info_); } template<typename Region> void change_region(value& v, Region&& reg) { using region_type = typename std::remove_reference< typename std::remove_cv<Region>::type >::type; std::shared_ptr<region_base> new_reg = std::make_shared<region_type>(std::forward<region_type>(reg)); v.region_info_ = new_reg; return; } }// detail template<> struct value::switch_cast<value_t::Boolean> { static Boolean& invoke(value& v) {return v.boolean_;} static Boolean const& invoke(value const& v) {return v.boolean_;} static Boolean&& invoke(value&& v) {return std::move(v.boolean_);} }; template<> struct value::switch_cast<value_t::Integer> { static Integer& invoke(value& v) {return v.integer_;} static Integer const& invoke(value const& v) {return v.integer_;} static Integer&& invoke(value&& v) {return std::move(v.integer_);} }; template<> struct value::switch_cast<value_t::Float> { static Float& invoke(value& v) {return v.floating_;} static Float const& invoke(value const& v) {return v.floating_;} static Float&& invoke(value&& v) {return std::move(v.floating_);} }; template<> struct value::switch_cast<value_t::String> { static String& invoke(value& v) {return v.string_;} static String const& invoke(value const& v) {return v.string_;} static String&& invoke(value&& v) {return std::move(v.string_);} }; template<> struct value::switch_cast<value_t::OffsetDatetime> { static OffsetDatetime& invoke(value& v) {return v.offset_datetime_;} static OffsetDatetime const& invoke(value const& v) {return v.offset_datetime_;} static OffsetDatetime&& invoke(value&& v) {return std::move(v.offset_datetime_);} }; template<> struct value::switch_cast<value_t::LocalDatetime> { static LocalDatetime& invoke(value& v) {return v.local_datetime_;} static LocalDatetime const& invoke(value const& v) {return v.local_datetime_;} static LocalDatetime&& invoke(value&& v) {return std::move(v.local_datetime_);} }; template<> struct value::switch_cast<value_t::LocalDate> { static LocalDate& invoke(value& v) {return v.local_date_;} static LocalDate const& invoke(value const& v) {return v.local_date_;} static LocalDate&& invoke(value&& v) {return std::move(v.local_date_);} }; template<> struct value::switch_cast<value_t::LocalTime> { static LocalTime& invoke(value& v) {return v.local_time_;} static LocalTime const& invoke(value const& v) {return v.local_time_;} static LocalTime&& invoke(value&& v) {return std::move(v.local_time_);} }; template<> struct value::switch_cast<value_t::Array> { static Array& invoke(value& v) {return v.array_.value();} static Array const& invoke(value const& v) {return v.array_.value();} static Array&& invoke(value&& v) {return std::move(v.array_.value());} }; template<> struct value::switch_cast<value_t::Table> { static Table& invoke(value& v) {return v.table_.value();} static Table const& invoke(value const& v) {return v.table_.value();} static Table&& invoke(value&& v) {return std::move(v.table_.value());} }; template<value_t T> typename detail::toml_default_type<T>::type& value::cast() & { if(T != this->type_) { throw type_error(detail::format_underline(concat_to_string( "[error] toml::value bad_cast to ", T), { {this->region_info_.get(), concat_to_string("the actual type is ", this->type_)} })); } return switch_cast<T>::invoke(*this); } template<value_t T> typename detail::toml_default_type<T>::type const& value::cast() const& { if(T != this->type_) { throw type_error(detail::format_underline(concat_to_string( "[error] toml::value bad_cast to ", T), { {this->region_info_.get(), concat_to_string("the actual type is ", this->type_)} })); } return switch_cast<T>::invoke(*this); } template<value_t T> typename detail::toml_default_type<T>::type&& value::cast() && { if(T != this->type_) { throw type_error(detail::format_underline(concat_to_string( "[error] toml::value bad_cast to ", T), { {this->region_info_.get(), concat_to_string("the actual type is ", this->type_)} })); } return switch_cast<T>::invoke(std::move(*this)); } inline bool operator==(const toml::value& lhs, const toml::value& rhs) { if(lhs.type() != rhs.type()){return false;} switch(lhs.type()) { case value_t::Boolean : return lhs.cast<value_t::Boolean >() == rhs.cast<value_t::Boolean >(); case value_t::Integer : return lhs.cast<value_t::Integer >() == rhs.cast<value_t::Integer >(); case value_t::Float : return lhs.cast<value_t::Float >() == rhs.cast<value_t::Float >(); case value_t::String : return lhs.cast<value_t::String >() == rhs.cast<value_t::String >(); case value_t::OffsetDatetime: return lhs.cast<value_t::OffsetDatetime>() == rhs.cast<value_t::OffsetDatetime>(); case value_t::LocalDatetime: return lhs.cast<value_t::LocalDatetime>() == rhs.cast<value_t::LocalDatetime>(); case value_t::LocalDate: return lhs.cast<value_t::LocalDate>() == rhs.cast<value_t::LocalDate>(); case value_t::LocalTime: return lhs.cast<value_t::LocalTime>() == rhs.cast<value_t::LocalTime>(); case value_t::Array : return lhs.cast<value_t::Array >() == rhs.cast<value_t::Array >(); case value_t::Table : return lhs.cast<value_t::Table >() == rhs.cast<value_t::Table >(); case value_t::Empty : return true; case value_t::Unknown : return false; default: return false; } } inline bool operator<(const toml::value& lhs, const toml::value& rhs) { if(lhs.type() != rhs.type()){return (lhs.type() < rhs.type());} switch(lhs.type()) { case value_t::Boolean : return lhs.cast<value_t::Boolean >() < rhs.cast<value_t::Boolean >(); case value_t::Integer : return lhs.cast<value_t::Integer >() < rhs.cast<value_t::Integer >(); case value_t::Float : return lhs.cast<value_t::Float >() < rhs.cast<value_t::Float >(); case value_t::String : return lhs.cast<value_t::String >() < rhs.cast<value_t::String >(); case value_t::OffsetDatetime: return lhs.cast<value_t::OffsetDatetime>() < rhs.cast<value_t::OffsetDatetime>(); case value_t::LocalDatetime: return lhs.cast<value_t::LocalDatetime>() < rhs.cast<value_t::LocalDatetime>(); case value_t::LocalDate: return lhs.cast<value_t::LocalDate>() < rhs.cast<value_t::LocalDate>(); case value_t::LocalTime: return lhs.cast<value_t::LocalTime>() < rhs.cast<value_t::LocalTime>(); case value_t::Array : return lhs.cast<value_t::Array >() < rhs.cast<value_t::Array >(); case value_t::Table : return lhs.cast<value_t::Table >() < rhs.cast<value_t::Table >(); case value_t::Empty : return false; case value_t::Unknown : return false; default: return false; } } inline bool operator!=(const toml::value& lhs, const toml::value& rhs) { return !(lhs == rhs); } inline bool operator<=(const toml::value& lhs, const toml::value& rhs) { return (lhs < rhs) || (lhs == rhs); } inline bool operator>(const toml::value& lhs, const toml::value& rhs) { return !(lhs <= rhs); } inline bool operator>=(const toml::value& lhs, const toml::value& rhs) { return !(lhs < rhs); } inline std::string format_error(const std::string& err_msg, const toml::value& v, const std::string& comment, std::vector<std::string> hints = {}) { return detail::format_underline(err_msg, std::vector<std::pair<detail::region_base const*, std::string>>{ {std::addressof(detail::get_region(v)), comment} }, std::move(hints)); } inline std::string format_error(const std::string& err_msg, const toml::value& v1, const std::string& comment1, const toml::value& v2, const std::string& comment2, std::vector<std::string> hints = {}) { return detail::format_underline(err_msg, std::vector<std::pair<detail::region_base const*, std::string>>{ {std::addressof(detail::get_region(v1)), comment1}, {std::addressof(detail::get_region(v2)), comment2} }, std::move(hints)); } inline std::string format_error(const std::string& err_msg, const toml::value& v1, const std::string& comment1, const toml::value& v2, const std::string& comment2, const toml::value& v3, const std::string& comment3, std::vector<std::string> hints = {}) { return detail::format_underline(err_msg, std::vector<std::pair<detail::region_base const*, std::string>>{ {std::addressof(detail::get_region(v1)), comment1}, {std::addressof(detail::get_region(v2)), comment2}, {std::addressof(detail::get_region(v3)), comment3} }, std::move(hints)); } template<typename Visitor> detail::return_type_of_t<Visitor, const toml::boolean&> visit(Visitor&& visitor, const toml::value& v) { switch(v.type()) { case value_t::Boolean : {return visitor(v.cast<value_t::Boolean >());} case value_t::Integer : {return visitor(v.cast<value_t::Integer >());} case value_t::Float : {return visitor(v.cast<value_t::Float >());} case value_t::String : {return visitor(v.cast<value_t::String >());} case value_t::OffsetDatetime: {return visitor(v.cast<value_t::OffsetDatetime>());} case value_t::LocalDatetime : {return visitor(v.cast<value_t::LocalDatetime >());} case value_t::LocalDate : {return visitor(v.cast<value_t::LocalDate >());} case value_t::LocalTime : {return visitor(v.cast<value_t::LocalTime >());} case value_t::Array : {return visitor(v.cast<value_t::Array >());} case value_t::Table : {return visitor(v.cast<value_t::Table >());} case value_t::Empty : break; case value_t::Unknown : break; default: break; } throw std::runtime_error(format_error("[error] toml::visit: toml::value " "does not have any valid value.", v, "here")); } template<typename Visitor> detail::return_type_of_t<Visitor, toml::boolean&> visit(Visitor&& visitor, toml::value& v) { switch(v.type()) { case value_t::Boolean : {return visitor(v.cast<value_t::Boolean >());} case value_t::Integer : {return visitor(v.cast<value_t::Integer >());} case value_t::Float : {return visitor(v.cast<value_t::Float >());} case value_t::String : {return visitor(v.cast<value_t::String >());} case value_t::OffsetDatetime: {return visitor(v.cast<value_t::OffsetDatetime>());} case value_t::LocalDatetime : {return visitor(v.cast<value_t::LocalDatetime >());} case value_t::LocalDate : {return visitor(v.cast<value_t::LocalDate >());} case value_t::LocalTime : {return visitor(v.cast<value_t::LocalTime >());} case value_t::Array : {return visitor(v.cast<value_t::Array >());} case value_t::Table : {return visitor(v.cast<value_t::Table >());} case value_t::Empty : break; case value_t::Unknown : break; default: break; } throw std::runtime_error(format_error("[error] toml::visit: toml::value " "does not have any valid value.", v, "here")); } template<typename Visitor> detail::return_type_of_t<Visitor, toml::boolean&&> visit(Visitor&& visitor, toml::value&& v) { switch(v.type()) { case value_t::Boolean : {return visitor(std::move(v.cast<value_t::Boolean >()));} case value_t::Integer : {return visitor(std::move(v.cast<value_t::Integer >()));} case value_t::Float : {return visitor(std::move(v.cast<value_t::Float >()));} case value_t::String : {return visitor(std::move(v.cast<value_t::String >()));} case value_t::OffsetDatetime: {return visitor(std::move(v.cast<value_t::OffsetDatetime>()));} case value_t::LocalDatetime : {return visitor(std::move(v.cast<value_t::LocalDatetime >()));} case value_t::LocalDate : {return visitor(std::move(v.cast<value_t::LocalDate >()));} case value_t::LocalTime : {return visitor(std::move(v.cast<value_t::LocalTime >()));} case value_t::Array : {return visitor(std::move(v.cast<value_t::Array >()));} case value_t::Table : {return visitor(std::move(v.cast<value_t::Table >()));} case value_t::Empty : break; case value_t::Unknown : break; default: break; } throw std::runtime_error(format_error("[error] toml::visit: toml::value " "does not have any valid value.", v, "here")); } }// toml #endif// TOML11_VALUE
true
0ce5af0cf8a48bbbb2f8472e245f9fd2201f5c29
C++
BenjBarral/STABLE_FLUIDS
/main.cpp
UTF-8
11,516
2.59375
3
[]
no_license
// // main.cpp // // // Created by Benjamin Barral. // /// C++ #include <cstdio> #include <cstring> #include <iostream> #include <math.h> #include <algorithm> #include <ctime> /// OpenCv #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> /// Eigen #include <eigen3/Eigen/Dense> #include<eigen3/Eigen/IterativeLinearSolvers> using namespace cv; using namespace std; using namespace Eigen; /// IMAGE PROCESSING PARAMETERS AND VARIABLES // Image parameters : display resolution, processing resolution const int disp_width = 500, disp_height = 500, proc_width = 75, proc_height = 75; int num_particles = proc_width * proc_height; float frameRate = 60.; float dt = 1. / frameRate; int Lx = 600, Ly = 600; float dx = float(Lx) / float(proc_height), dy = float(Ly) / float(proc_height); float conv=(float) ((1440./0.3)*(1440./0.3)); float visc = 120. * pow(10,-6) * conv; double Cx = -visc * dt / (dx*dx); double Cy = -visc * dt / (dy*dy); int boundary_condition = 1; // Matrices VectorXd V_x_0(num_particles), V_x_1(num_particles), V_y_0(num_particles), V_y_1(num_particles); VectorXd F_x(num_particles), F_y(num_particles); // Image Mat fluid_grid = Mat::zeros(proc_height,proc_width,CV_8UC3), prev_grid = Mat::zeros(proc_height,proc_width,CV_8UC3); float g = 130, b = 200; void AddForce(){ V_x_0 = V_x_0 + dt * F_x; V_y_0 = V_y_0 + dt * F_y; } Vector2d Trace(int i, int j){ double x = (j + 0.5) * dx; double y = (i + 0.5) * dy; double ux = V_x_0[i * proc_height + j]; // VX[0][i*n+j]; double uy = V_y_0[i * proc_height + j]; // VY[0][i*n+j]; x = x - dt * ux; y = y - dt * uy; return Vector2d(x,y); } void LinearInterpolate(double x, double y, int i0, int j0, bool setTexture){ //int j=(int)((x-dx/2)/dx); //double t1=(x-(j+0.5)*dx)/dx; int j = (x>0) ? (int)((x -dx/2.) / dx) : (int)((x - dx/2.) / dx) - 1.; double t1 = (x- (double(j) + 0.5) * dx) / dx; if (j >= proc_height){ j = j % proc_height; if (boundary_condition == 1) return; } if (j < 0){ if (boundary_condition == 1){ if (j == -1 && t1 > 0.5) t1 = 1.; else return; } int q = j / proc_height; j = (j + (-q+1) * proc_height) % proc_height; } t1 = (j == proc_height-1 && boundary_condition==1) ? 0. : t1; //int i=(int)((y-dy/2)/dy); //double t=(y-(i+0.5)*dy)/dy; int i = (y > 0) ? (int)((y - dy/2.) / dy) : (int)((y - dy/2.) / dy) - 1.; double t = (y - (double(i) + 0.5) * dy) / dy; if (i >= proc_height){ i = i % proc_height; if (boundary_condition == 1) return; } if (i < 0){ if (boundary_condition == 1){ if (i==-1 && t>0.5) t=1.; else return; } int q = i / proc_height; i = (i + (-q + 1) * proc_height) % proc_height ; } t=(i == proc_height-1 && boundary_condition==1)? 0. : t; int i2 = (i==proc_height-1)? 0:i+1; int j2 = (j==proc_height-1)? 0:j+1; double s1a = V_x_0[i*proc_height+j], s1b = V_x_0[i*proc_height+j2]; // VX[0][i*n+j],s1b= VX[0][i*n+j2]; double s2a = V_x_0[i2*proc_height+j], s2b = V_x_0[i2*proc_height+j2]; // VX[0][i2*n+j],s2b=VX[0][i2*n+j2]; double s1 = t1*s1b+(1.-t1)*s1a; double s2 = t1*s2b+(1.-t1)*s2a; double uxBis = t*s2 + (1.-t)*s1; V_x_1[i0*proc_height+j0]= uxBis; // VX[1][i0*n+j0]= uxBis; s1a = V_y_0[i * proc_width + j]; // VY[0][i*n+j]; s1b = V_y_0[i * proc_width + j2]; // VY[0][i*n+j2]; s2a = V_y_0[i2 * proc_width + j]; // VY[0][i2*n+j]; s2b = V_y_0[i2 * proc_width + j2]; // VY[0][i2*n+j2]; s1 = t1*s1b + (1.-t1)*s1a; s2 = t1*s2b + (1.-t1)*s2a; double uyBis = t*s2 + (1.-t)*s1; V_y_1[i0*proc_height+j0]= uyBis; // VY[1][i0*n+j0]= uyBis; if (setTexture){ Vec3f s1a = prev_grid.at<Vec3b>(i,j); Vec3f s1b = prev_grid.at<Vec3b>(i,j2); Vec3f s2a = prev_grid.at<Vec3b>(i2,j); Vec3f s2b = prev_grid.at<Vec3b>(i2,j2); Vec3f s1 = t1 * s1b + (1.-t1) * s1a; Vec3f s2 = t1 * s2b + (1.-t1) * s2a; Vec3f preCol = (t*s2 + (1.-t)*s1); Vec3b color; for (int k = 0; k < 3; k++){ int col = round(preCol.val[k]); color.val[k] = col; } fluid_grid.at<Vec3b>(i0,j0) = color; } } void Transport(){ Vector2d p; fluid_grid.copyTo(prev_grid); //int[][][] textures0=displayGrid.textures.clone(); for (int i = 0; i < proc_height; i++){ for (int j = 0; j < proc_height; j++){ p=Trace(i,j); LinearInterpolate(p[0],p[1], i,j, true); } } } void Swap(){ VectorXd temp = V_x_0; V_x_0 = V_x_1; V_x_1 = temp; temp = V_y_0; V_y_0 = V_y_1; V_y_1 = temp; } VectorXd DX(VectorXd U, int n, double dx, bool tilde) { int N = n*n; VectorXd U2(num_particles); // = new double[N]; for(int i = 0; i < num_particles;i++) { int l = i%proc_width; int k = i/proc_width; if (l != 0 && (!tilde || l!=proc_width-1)) U2[i] -= U[i-1]; //AJOUTE if (l!=n-1 && (!tilde || l!=0)) U2[i] += U[i+1]; U2[i] = U2[i] / (2.*dx); } return U2; } VectorXd DY(VectorXd U, int n, double dy, bool tilde) { int N = n*n; VectorXd U2(num_particles); // = new double[N]; for(int i = 0; i < num_particles;i++) { int l = i%proc_width; int k = i/proc_width; if (k!=0 && (!tilde || k!=proc_width-1) ) U2[i]-=U[i-proc_width]; if (k!=n-1 && (!tilde || k!=0)) U2[i]+=U[i+proc_width]; U2[i] = U2[i] / (2.*dy); } return U2; } void Project(SparseMatrix<double> laplacian, const BiCGSTAB< SparseMatrix<double> >& solver_laplacian){ VectorXd q = DX(V_x_0, proc_height, dx, false) + DY(V_y_0, proc_width, dy, false); //double[] q = DX(VX[0], proc_height, dx, false) + DY(VY[0],proc,dy, false); VectorXd Q = solver_laplacian.solve(q); V_x_0 = V_x_0 - DX(Q, proc_height, dx, true); V_y_0 = V_y_0 - DY(Q, proc_height, dx, true); //VX[0]=minus(VX[0],ComputeMatricesMTJ_BC2.DX(Q,n,dx,true)); //VY[0]=minus(VY[0],ComputeMatricesMTJ_BC2.DY(Q,n,dy,true)); } void Diffuse(const BiCGSTAB< SparseMatrix<double> >& solver_diff_X, const BiCGSTAB< SparseMatrix<double> >& solver_diff_Y){ V_x_0 = solver_diff_X.solve(V_x_0);// VX[0] = solver_diff_X.solve(VX[0]); V_y_0 = solver_diff_Y.solve(V_y_0); //VY[0]=solverDiffY.solve(VY[0]); } void Routine(const BiCGSTAB< SparseMatrix<double> >& solver_diff_X, const BiCGSTAB< SparseMatrix<double> >& solver_diff_Y, SparseMatrix<double> laplacian, const BiCGSTAB< SparseMatrix<double> >& solver_laplacian){ // the routine of the solver algorith AddForce(); Transport(); Swap(); Diffuse(solver_diff_X, solver_diff_Y); Project(laplacian, solver_laplacian); } int main() { for (int i = 0; i < proc_height; i++){ int r = int(5. * double(i) * (50. / double(proc_height)))%255 ; for (int j = 0; j < proc_width; j++) { fluid_grid.at<Vec3b>(i,j) = Vec3b(r,g,b); } } for (int i = 0; i < proc_height/2; i++){ for (int j = 0; j < proc_height; j++){ int K = i*proc_width + j; F_y[K] = 0.1; } } /// VIDEO : Create windows namedWindow( "Fluid simulator", CV_WINDOW_AUTOSIZE ); int key = waitKey(3); SparseMatrix<double> diffusion_X(num_particles,num_particles), diffusion_Y(num_particles,num_particles), laplacian(num_particles,num_particles); //Compute DiffusionX for(int i = 0; i < num_particles; i++) { int k = i / proc_height; int l = i %proc_height; if(k !=0 && k != proc_height-1) diffusion_X.coeffRef(i, i) = 1. - 2. * Cx - 2. * Cy; //DX.set(i,i,1-2*Cx -2*Cy); else diffusion_X.coeffRef(i, i) = 1. - 2. * Cx - Cy; // DX.set(i,i,1-2*Cx-Cy); if(l != 0) diffusion_X.coeffRef(i, i-1) = Cx; // DX.set(i,i-1,Cx); //else diffusion_X.coeffRef(i, i+proc_width-1) = 0.; // DX.set(i,i+n-1,0.); if(l != proc_width-1) diffusion_X.coeffRef(i, i+1) = Cx; //DX.set(i,i+1,Cx); //else diffusion_X.coeffRef(i, i-n+1) = 0.; DX.set(i,i-n+1,0.); if(k != 0) diffusion_X.coeffRef(i, i-proc_height) = Cy; // DX.set(i,i-n,Cy); //else DX.set(i,N-n+l,0.); if(k != proc_height-1) diffusion_X.coeffRef(i, i+proc_height) = Cy;// DX.set(i, i + proc_height,Cy); //else DX.set(i,l,0.); } for(int i = 0; i < num_particles; i++) { int k = i / proc_height; int l = i % proc_height; if(l != 0 && l != proc_height-1) diffusion_Y.coeffRef(i, i) = 1. - 2. * Cx - 2. * Cy; // DY.set(i,i,1 -2*Cx -2*Cy); else diffusion_Y.coeffRef(i, i) = 1. - Cx - 2. * Cy; // DY.set(i,i,1 -Cx -2*Cy); if(l != 0) diffusion_Y.coeffRef(i, i-1) = Cx; // DY.set(i,i-1,Cx); //else DY.set(i,i+n-1,0.); if(l != proc_height-1) diffusion_Y.coeffRef(i,i+1) = Cx; // DY.set(i,i+1,Cx); //else DY.set(i,i-n+1,0.); if(k != 0) diffusion_Y.coeffRef(i, i-proc_height) = Cy; // DY.set(i,i-n,Cy); //else DY.set(i,N-n+l,0.); if(k != proc_height-1) diffusion_Y.coeffRef(i, i+proc_height) = Cy; // DY.set(i,i+n,Cy); //else DY.set(i,l,0.); } Cx = 1. / (dx*dx); Cy = 1. / (dy*dy); //Compute L for(int i = 0; i < num_particles;i++) { int k = i / proc_height; int l = i % proc_height; laplacian.coeffRef(i,i) = -2. * Cx - 2. * Cy; //L.set(i,i,-2*Cx -2*Cy); if(l != 0 && l != proc_height-1) { laplacian.coeffRef(i, i-1) = Cx; // L.set(i,i-1,Cx); laplacian.coeffRef(i, i+1) = Cx; // L.set(i,i+1,Cx); } else { if(l == 0) laplacian.coeffRef(i, i+1) = 2. * Cx; // L.set(i,i+1,2*Cx); //else L.set(i, i-n+1, 0.); if(l == proc_height-1) laplacian.coeffRef(i, i-1) = 2. * Cx; // L.set(i,i-1,2*Cx); //else L.set(i, i+n-1, 0.); } if(k != 0 && k != proc_height-1) { laplacian.coeffRef(i, i - proc_height) = Cy; // L.set(i,i-n,Cy); laplacian.coeffRef(i, i + proc_height) = Cy; // L.set(i,i+n,Cy); } else { if(k != proc_height-1) laplacian.coeffRef(i, i+proc_height) = Cy; // L.set(i,i+n,Cy); //else L.set(i,l,0.); if(k != 0) laplacian.coeffRef(i, i-proc_height) = Cy; // L.set(i,i-n,Cy); //else L.set(i,N-n+l,0.); } } cout << "Matrices" << endl; BiCGSTAB< SparseMatrix<double> > solver_diff_X; solver_diff_X.compute(diffusion_X); cout << "Solver Diff X created" << endl; BiCGSTAB< SparseMatrix<double> > solver_diff_Y; solver_diff_Y.compute(diffusion_Y); cout << "Solver Diff X created" << endl; BiCGSTAB< SparseMatrix<double> > solver_laplacian; solver_laplacian.compute(laplacian); cout << "Solver Laplacian created" << endl; while (key != 32) { clock_t begin = clock(); Routine(solver_diff_X, solver_diff_Y, laplacian, solver_laplacian); imshow( "Delaunay", fluid_grid); clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << "Time : " << elapsed_secs << endl; /// Exit if space bar is pressed key = waitKey(3); } }
true
4c3903e8070605fb1c892559228e0c5c4b7b5eab
C++
quhezheng/ros
/pi/src/sp1s/src/gy85/adxl345.h
UTF-8
3,279
2.875
3
[]
no_license
#pragma once #include <wiringPiI2C.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <math.h> #define ADXL345_DevAddr 0x53 //device address #define POWER_CTL 0x2d #define DATA_FORMAT 0x31 #define FIFO_CTL 0x38 #define AFS_2g 0 #define AFS_4g 1 #define AFS_8g 2 #define AFS_16g 3 class adxl345 { private: struct acc_dat { short raw_x; short raw_y; short raw_z; double scaled_x; double scaled_y; double scaled_z; } m_dat; int m_fd; short m_x_offset; short m_y_offset; short m_z_offset; public: adxl345(short x_offset = 0, short y_offset = 0, short z_offset = 0) { m_fd = wiringPiI2CSetup(ADXL345_DevAddr); if (-1 == m_fd) return; // Set FULL_RES(4mg/LSB) signed int ±16g wiringPiI2CWriteReg8(m_fd, DATA_FORMAT, 0x0b); // Wake up the device wiringPiI2CWriteReg8(m_fd, POWER_CTL, 0x08); // Disable FIFO mode wiringPiI2CWriteReg8(m_fd, FIFO_CTL, 0b00000000); m_x_offset = x_offset; m_y_offset = y_offset; m_z_offset = z_offset; read_raw_data(); } void read_raw_data() { char x0, y0, z0, x1, y1, z1; x0 = wiringPiI2CReadReg8(m_fd, 0x32); x1 = wiringPiI2CReadReg8(m_fd, 0x33); y0 = wiringPiI2CReadReg8(m_fd, 0x34); y1 = wiringPiI2CReadReg8(m_fd, 0x35); z0 = wiringPiI2CReadReg8(m_fd, 0x36); z1 = wiringPiI2CReadReg8(m_fd, 0x37); m_dat.raw_x = (short)(x1 << 8) + (int)x0 + m_x_offset; m_dat.raw_y = (short)(y1 << 8) + (int)y0 + m_y_offset; m_dat.raw_z = (short)(z1 << 8) + (int)z0 + m_z_offset; m_dat.scaled_x = m_dat.raw_x * 0.004; m_dat.scaled_y = m_dat.raw_y * 0.004; m_dat.scaled_z = m_dat.raw_z * 0.004; } double distance(double x, double y) { //Returns the distance between two point in 2d space// return sqrt((x * x) + (y * y)); } double read_x_rotation(double x, double y, double z) { //Returns the rotation around the X axis in radians// if(z>=0) return (atan2(y, distance(x, z))); else return (atan2(y, -distance(x, z))); } double read_y_rotation(double x, double y, double z) { //Returns the rotation around the Y axis in radians// if(z>=0) return (-atan2(x, distance(y, z))); else return (-atan2(x, -distance(y, z))); } short read_raw_accel_x() { //Return the RAW X accelerometer value// return m_dat.raw_x; } short read_raw_accel_y() { //Return the RAW Y accelerometer value// return m_dat.raw_y; } short read_raw_accel_z() { //Return the RAW Z accelerometer value// return m_dat.raw_z; } double read_scaled_accel_x() { //Return the SCALED X accelerometer value// return m_dat.scaled_x; } double read_scaled_accel_y() { //Return the SCALED Y accelerometer value// return m_dat.scaled_y; } double read_scaled_accel_z() { //Return the SCALED Z accelerometer value// return m_dat.scaled_z; } double read_pitch() { //Calculate the current pitch value in radians// double x = read_scaled_accel_x(); double y = read_scaled_accel_y(); double z = read_scaled_accel_z(); return read_y_rotation(x, y, z); } double read_roll() { //Calculate the current roll value in radians// double x = read_scaled_accel_x(); double y = read_scaled_accel_y(); double z = read_scaled_accel_z(); return read_x_rotation(x, y, z); } };
true
aaa694f4d6e7f6ba4bfecbbf63502a60fe0dbf28
C++
Xin-Jiaqi/C-exercises
/文件.cpp
GB18030
1,465
3.0625
3
[]
no_license
/*ļ ıļĸֽڣASCֵ ļָ룺FILE *fp */ ļ if((fp = fopen("f1.txt","w")) == NULL){ printf("File open error!\n"); exit(0); } رļ if(fclose(fp)){ ʧܷEOF-1 printf("Can not close the file!\n"); exit(0); } fgetc int fgetc(FILE *fp) while((c = fgetc(fp)) != EOF){ printf("%c",C); } fputc int fputc(char ch,FILE *fp) while(ch[i] != '\0'){ fputc(ch[i++],fp); } fread int fread(char *buffer, int size, int count, FILE *fp) bufferŶ/дݵʼַ if( fread(myarr, sizeof(int), 100, fp) !=100 ){ exit(0); } Ӽж100,Ƿŵmyarr fwrite int fwrite (char *buffer, int size,int count,FILE *fp) fgets char * fgets(char *buff,int n,FILE*fp ) fputs int fputs(char *str,FILE *fp ) scanf("%s",st); fputs(st,fp); fscanf fscanf(fp,%d,%f,&i,&f); fprintf fprintf(fp,%3d,%6.1f,i,f); for(i=0;i<NO;i++){ fprintf(fp,%s %d %d %d %5.1f\n, stud[i].name,stud[i].score[0], stud[i].score[1],stud[i].score[2], stud[i].ave); } printf(\n); /*ļ rewind( ) void rewind(FILE *fp) λָƵļס fseek( ) int fseek(FILE *fp,long offset,int base) 㿪ʼλָƶƶλ */
true
498eda26c4837a2a8cfaca5f8b7dfce5d3228c41
C++
k0167/Exercicios
/listaEncadeada/main.cpp
UTF-8
1,057
3.03125
3
[]
no_license
#include "elemento.h" #include <QString> class Lista{ private: Elemento* inicio; Elemento* fim; public: Lista(){ this->inicio=this->fim=nullptr; } ~Lista(){ if(this->inicio!=nullptr) delete this->inicio; } void inserir(Elemento* novo){ if(this->inicio==nullptr) this->inicio=this->fim=novo; else{ novo->setProximo(this->inicio); this->inicio=novo; } } Elemento* retirar(){ if(this->inicio==nullptr) return nullptr; else{ Elemento* aux=this->inicio; this->inicio=inicio->getProximo(); aux->setProximo(nullptr); return aux; } } bool estaVazio(){ if(this->inicio==nullptr) return true; else return false; } void inserirNoFim(Elemento* novo) { fim->setProximo(novo); fim=novo; } QString listar(){ } }; int main(){ }
true
02223c2cadf89fed3cbc2afa76906930bb26b119
C++
Arquanite/ProjektPO
/src/addumpiredialog.cpp
UTF-8
1,251
2.515625
3
[]
no_license
#include "addumpiredialog.h" #include "ui_addumpiredialog.h" AddUmpireDialog::AddUmpireDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AddUmpireDialog){ ui->setupUi(this); connect(ui->OK, SIGNAL(clicked(bool)), this, SLOT(Sprawdz())); connect(ui->Anuluj, SIGNAL(clicked(bool)), this, SLOT(reject())); } AddUmpireDialog::~AddUmpireDialog(){ delete ui; } void AddUmpireDialog::Sprawdz(){ if(ui->Imie->text().isEmpty()){ QMessageBox::warning(this, "Błąd", "Sędzia musi mieć imię!"); return; } if(ui->Nazwisko->text().isEmpty()){ QMessageBox::warning(this, "Błąd", "Sędzia musi mieć nazwisko!"); return; } if(ui->Konkurencja->currentIndex() != 0 && ui->Pomocniczy->isChecked()){ QMessageBox::warning(this, "Błąd", "Tylko w siatkówce plażowej występują sędziowie pomocniczy!"); return; } Sedzia Andrzej(ui->Imie->text(), ui->Nazwisko->text()); emit DodajSedziego(Andrzej, ui->Konkurencja->currentIndex(), ui->Pomocniczy->isChecked()); } void AddUmpireDialog::UdaoSiem(bool Odpowiedz){ if(Odpowiedz) accept(); else { QMessageBox::warning(this, "Błąd", "Osoba o tym samym imieniu i nazwisku już istnieje!"); } }
true
e906db188ec1c0d10ca3650e332a3bab116d09a8
C++
guzhaolun/LeetCode
/LeetCode/MyCode/76 minimum_window_substring.h
GB18030
2,814
3.140625
3
[]
no_license
#include <string> #include <map> #include <set> #include <vector> #include <algorithm> using namespace std; class Solution76 { public: //1.ظĸֿӰ㲻ˡ //2.˹ˣò״ظģʱˡ //ҵ뷨Ǽ¼ÿӽȥλãȻظȥǸظ //Ȼ漰ܶɾֻǶ˸hash_map¼Щظģ //Ȼǰ߾ͺˣţơ string minWindow(string s, string t) { if (s.size() < t.size()) return ""; map<char, int> map_t; for (int i = 0; i < t.size(); i++) map_t[t[i]]++; vector<int> pos; int start = 0; int currlen = 0; int count = 0; int minLen = INT_MAX; char last; for (int i = 0; i < s.size(); i++) { if (map_t.find(s[i]) != map_t.end()) { if (map_t[s[i]] != 0) map_t[s[i]]--; else if (last == s[i]) { pos.back() = i; continue; } else { last = s[i]; { for (vector<int>::iterator it = pos.begin(); it != pos.end();) if (s[*it] == s[i]) { pos.erase(it); break; } else it++; } pos.push_back(i); continue; } pos.push_back(i); last = s[i]; count++; if (count == t.size()) { map_t[s[*pos.begin()]]++; count--; currlen = pos.back() - *pos.begin() + 1; if (currlen < minLen) { minLen = currlen; start = *pos.begin(); } pos.erase(pos.begin()); } } } string res; if (minLen == INT_MAX) return ""; res += s.substr(start, minLen); return res; } private: int count1[256]; int count2[256]; public: string minWindow2(string S, string T) { // Start typing your C/C++ solution below // DO NOT write int main() function if (T.size() == 0 || S.size() == 0) return ""; memset(count1, 0, sizeof(count1)); memset(count2, 0, sizeof(count2)); for (int i = 0; i < T.size(); i++) { count1[T[i]]++; count2[T[i]]++; } int count = T.size(); int start = 0; int minSize = INT_MAX; int minStart; for (int end = 0; end < S.size(); end++) { if (count2[S[end]] > 0) { count1[S[end]]--; if (count1[S[end]] >= 0)//ظֵIJȥ count--; } if (count == 0) { while (true) { if (count2[S[start]] > 0) { if (count1[S[start]] < 0)//޳ͷظ count1[S[start]]++; else break; } start++; } if (minSize > end - start + 1) { minSize = end - start + 1; minStart = start; } } } if (minSize == INT_MAX) return ""; string ret(S, minStart, minSize); return ret; } };
true
003e9f448281944cf5067d07d53c624b47dcec38
C++
Jackie890621/Arithmetic
/stack.cpp
UTF-8
1,072
3
3
[ "MIT" ]
permissive
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include <vector> using namespace std; int main() { int n; long long num1, num2; vector<long long> stack; string str; string temp; cin >> n; for (int i = 0; i < n; i++) { scanf("\n"); getline(cin, str); for (int j = 0; j < str.length(); j++) { if (str[j] >= 48 && str[j] <= 57) { temp += str[j]; continue; } if (str[j] == ' ') { if (temp.empty()) { continue; } stack.push_back(stoll(temp)); temp.clear(); } if (str[j] == '+' || str[j] == '*') { if (!temp.empty()) { stack.push_back(stoll(temp)); temp.clear(); } num2 = stack.back(); stack.pop_back(); num1 = stack.back(); stack.pop_back(); if (str[j] == '+') { num1 = num1 + num2; stack.push_back(num1); } else { num1 = num1 * num2; stack.push_back(num1); } } } for (int j = 0; j < stack.size(); j++) { cout << stack[j] << endl; } str.clear(); stack.clear(); } return 0; }
true
f338cb623f634c44fd283bb65eb04686fa290cb5
C++
igusher/euler
/20. FactorialDigitSum/main.cpp
UTF-8
657
2.703125
3
[]
no_license
#include <iostream> #include "MyBigInt.h" using namespace std; void main () { unsigned long long sum =0; char * buff = new char[1000]; int buffSize = 0; MyBigInt * bigInt = new MyBigInt(); bigInt->add(1); unsigned int rem; for(int i = 2 ; i <= 100; i++) { bigInt->mul(i); } //bigInt->mul(21); while((bigInt->val[0] != 0) || (bigInt->size > 1)) { bigInt->div(10, rem); sum+=rem; buff[buffSize++] = '0' + rem; } buff[buffSize] = 0; strrev(buff); cout<<sum << endl; cout<<buff; cout<<endl; for(int i = 0 ; i< bigInt->size; i++) { cout << bigInt->val[i] << endl; } delete bigInt; }
true
15571797846a56a536889f650656a00a204a58ac
C++
leungyukshing/DataStructure
/Queen/Queens.cpp
UTF-8
1,411
3.328125
3
[]
no_license
#include <iostream> #include "Queens.hpp" using namespace std; void Queens::insert(int col) { queen_square[count++][col] = true; } void Queens::remove(int col) { queen_square[--count][col] = false; } Queens::Queens(int size) { board_size = size; count = 0; for (int row = 0; row < board_size; row++) { for (int col = 0; col < board_size; col++) { queen_square[row][col] = false; } } } bool Queens::unguarded(int col) const { int i; bool ok = true; // turns false if we find a queen in column or diagonal for (i = 0; ok && i < count; i++) { ok = !queen_square[i][col]; // Check upper part of column } for (i = 1; ok && count - i >= 0 && col - i >= 0; i++) { ok = !queen_square[count - i][col - i]; // ck upper-left diagonal } for (i = 1; ok && count- i >= 0 && col + i < board_size; i++) { ok = !queen_square[count - i][col + i]; // Check upper-right diagonal } return ok; } bool Queens::is_solved() const{ return (count == board_size); } void Queens::print() const { int row, col; for (col = 0; col < board_size; col++) { cout << "--"; } cout << "--\n"; for (row = 0; row < board_size; row++) { for (col = 0; col < board_size;col++) { if (queen_square[row][col]) { cout << "Q"; } else { cout << "."; } } cout << endl; } }
true
c14437ff2dc1c83339523afbb598ddb7b561b107
C++
lwxGitHub123/micro-manager
/mmCoreAndDevices/MMDevice/ModuleInterface.cpp
UTF-8
4,237
2.640625
3
[ "BSD-3-Clause" ]
permissive
/////////////////////////////////////////////////////////////////////////////// // FILE: ModuleInterface.cpp // PROJECT: Micro-Manager // SUBSYSTEM: MMDevice - Device adapter kit //----------------------------------------------------------------------------- // DESCRIPTION: The implementation for the common plugin functions // AUTHOR: Nenad Amodaj, nenad@amodaj.com, 08/08/2005 // NOTE: Change the implementation of module interface methods in // this file with caution, since the Micro-Manager plugin // mechanism relies on specific functionality as implemented // here. // COPYRIGHT: University of California, San Francisco, 2006 // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. #include "ModuleInterface.h" #include <algorithm> #include <string> #include <vector> namespace { struct DeviceInfo { std::string name_; MM::DeviceType type_; std::string description_; DeviceInfo(const char* name, MM::DeviceType type, const char* description) : name_(name), type_(type), description_(description) {} }; // Predicate for searching by name class DeviceNameMatches { std::string name_; public: explicit DeviceNameMatches(const std::string& deviceName) : name_(deviceName) {} bool operator()(const DeviceInfo& info) { return info.name_ == name_; } }; } // anonymous namespace // Registered devices in this module (device adapter library) static std::vector<DeviceInfo> g_registeredDevices; MODULE_API long GetModuleVersion() { return MODULE_INTERFACE_VERSION; } MODULE_API long GetDeviceInterfaceVersion() { return DEVICE_INTERFACE_VERSION; } MODULE_API unsigned GetNumberOfDevices() { return static_cast<unsigned>(g_registeredDevices.size()); } MODULE_API bool GetDeviceName(unsigned deviceIndex, char* name, unsigned bufLen) { if (deviceIndex >= g_registeredDevices.size()) return false; const std::string& deviceName = g_registeredDevices[deviceIndex].name_; if (deviceName.size() >= bufLen) return false; // buffer too small, can't truncate the name strcpy(name, deviceName.c_str()); return true; } MODULE_API bool GetDeviceType(const char* deviceName, int* type) { std::vector<DeviceInfo>::const_iterator it = std::find_if(g_registeredDevices.begin(), g_registeredDevices.end(), DeviceNameMatches(deviceName)); if (it == g_registeredDevices.end()) { *type = MM::UnknownType; return false; } // Prefer int over enum across DLL boundary so that the module ABI does not // change (somewhat pedantic, but let's be safe). *type = static_cast<int>(it->type_); return true; } MODULE_API bool GetDeviceDescription(const char* deviceName, char* description, unsigned bufLen) { std::vector<DeviceInfo>::const_iterator it = std::find_if(g_registeredDevices.begin(), g_registeredDevices.end(), DeviceNameMatches(deviceName)); if (it == g_registeredDevices.end()) return false; strncpy(description, it->description_.c_str(), bufLen - 1); return true; } void RegisterDevice(const char* deviceName, MM::DeviceType deviceType, const char* deviceDescription) { if (!deviceName) return; if (!deviceDescription) // This is a bug; let the programmer know by displaying an ugly string deviceDescription = "(Null description)"; if (std::find_if(g_registeredDevices.begin(), g_registeredDevices.end(), DeviceNameMatches(deviceName)) != g_registeredDevices.end()) // Device with this name already registered return; g_registeredDevices.push_back(DeviceInfo(deviceName, deviceType, deviceDescription)); }
true
e70d40a9881291f8e627bb85ae6d35f365d0be87
C++
devyetii/OOP_PaintForKids_Ph2
/GUI/Output.cpp
UTF-8
11,631
2.71875
3
[]
no_license
#include "Output.h" Output::Output() { //Initialize user interface parameters UI.InterfaceMode = MODE_DRAW; UI.width = 1250; UI.height = 650; UI.wx = 5; UI.wy = 5; UI.StatusBarHeight = 50; UI.ToolBarHeight = 60; UI.MenuItemWidth = 70; UI.DrawColor = BLUE; //Drawing color UI.FillColor = GREEN; //Filling color UI.MsgColor = RED; //Messages color UI.BkGrndColor = LIGHTGOLDENRODYELLOW; //Background color UI.HighlightColor = MAGENTA; //This color should NOT be used to draw figures. use if for highlight only UI.StatusBarColor = TURQUOISE; UI.PenWidth = 5; //width of the figures frames //Create the output window pWind = CreateWind(UI.width, UI.height, UI.wx, UI.wy); //Change the title pWind->ChangeTitle("Paint for Kids - Programming Techniques Project"); CreateDrawToolBar(); CreateStatusBar(); } Input* Output::CreateInput() const { Input* pIn = new Input(pWind); return pIn; } //======================================================================================// // Interface Functions // //======================================================================================// window* Output::CreateWind(int w, int h, int x, int y) const { window* pW = new window(w, h, x, y); pW->SetBrush(UI.BkGrndColor); pW->SetPen(UI.BkGrndColor, 1); pW->DrawRectangle(0, UI.ToolBarHeight, w, h); return pW; } ////////////////////////////////////////////////////////////////////////////////////////// void Output::CreateStatusBar() const { pWind->SetPen(UI.StatusBarColor, 1); pWind->SetBrush(UI.StatusBarColor); pWind->DrawRectangle(0, UI.height - UI.StatusBarHeight, UI.width, UI.height); } ////////////////////////////////////////////////////////////////////////////////////////// void Output::ClearStatusBar() const { //Clear Status bar by drawing a filled white rectangle pWind->SetPen(UI.StatusBarColor, 1); pWind->SetBrush(UI.StatusBarColor); pWind->DrawRectangle(0, UI.height - UI.StatusBarHeight, UI.width, UI.height); } ////////////////////////////////////////////////////////////////////////////////////////// /*void Output::CreateFillClrToolBar()const { UI.InterfaceMode = MODE_FILL_COLOR; pWind->SetBrush(UI.BkGrndColor); pWind->DrawRectangle(0, 0, UI.width, UI.ToolBarHeight); pWind->SetPen(RED, 3); string MenuItemImages[COLOR_ITM_COUNT]; MenuItemImages[ITM_RED] = "images\\MenuItems\\RED.jpg"; MenuItemImages[ITM_Blue] = "images\\MenuItems\\Blue.jpg"; MenuItemImages[ITM_Green] = "images\\MenuItems\\Green.jpg"; MenuItemImages[ITM_Black] = "images\\MenuItems\\Black.jpg"; MenuItemImages[ITM_White] = "images\\MenuItems\\White.jpg"; MenuItemImages[ITM_Paint] = "images\\MenuItems\\Paint.jpg"; for (int i = 0; i < COLOR_ITM_COUNT; i++) pWind->DrawImage(MenuItemImages[i], i*UI.MenuItemWidth, 0, UI.MenuItemWidth, UI.ToolBarHeight); pWind->SetPen(RED, 3); pWind->DrawLine(0, UI.ToolBarHeight, UI.width, UI.ToolBarHeight); }*/ void Output::CreateDrawToolBar() const { UI.InterfaceMode = MODE_DRAW; //You can draw the tool bar icons in any way you want. //Below is one possible way //First prepare List of images for each menu item //To control the order of these images in the menu, //reoder them in UI_Info.h ==> enum DrawMenuItem string MenuItemImages[DRAW_ITM_COUNT]; ///////////////////////////////////////////////////////// MenuItemImages[ITM_SELECT] = "images\\MenuItems\\Menu_Select.jpg"; MenuItemImages[ITM_LINE] = "images\\MenuItems\\Menu_line1.jpg"; MenuItemImages[ITM_RECT] = "images\\MenuItems\\Menu_Rect.jpg"; MenuItemImages[ITM_TRI] = "images\\MenuItems\\Menu_Triangle.jpg"; MenuItemImages[ITM_RHOM] = "images\\MenuItems\\Menu_Rohmbus.jpg"; MenuItemImages[ITM_ELLIPSE] = "images\\MenuItems\\Menu_Circ.jpg"; MenuItemImages[ITM_CHNG_DRW_CLR] = "images\\MenuItems\\Menu_Draw_Color.jpg"; MenuItemImages[ITM_CHNG_FILL_CLR] = "images\\MenuItems\\Menu_Fill_Color.jpg"; MenuItemImages[ITM_COPY] = "images\\MenuItems\\Menu_Copy.jpg"; MenuItemImages[ITM_CUT] = "images\\MenuItems\\Menu_CUT.jpg"; MenuItemImages[ITM_PASTE] = "images\\MenuItems\\Menu_Paste.jpg"; MenuItemImages[ITM_DELETE] = "images\\MenuItems\\Menu_Delete.jpg"; MenuItemImages[ITM_SAVE] = "images\\MenuItems\\Menu_save.jpg"; MenuItemImages[ITM_SAVETYPE] = "images\\MenuItems\\Menu_savetype.jpg"; MenuItemImages[ITM_LOAD] = "images\\MenuItems\\Menu_Load.jpg"; MenuItemImages[ITM_SWTOPLAY] = "images\\MenuItems\\Menu_Play.jpg"; MenuItemImages[ITM_EXIT] = "images\\MenuItems\\Menu_Exit.jpg"; //Draw menu item one image at a time for (int i = 0; i < DRAW_ITM_COUNT; i++) pWind->DrawImage(MenuItemImages[i], i*UI.MenuItemWidth, 0, UI.MenuItemWidth, UI.ToolBarHeight); //Draw a line under the toolbar pWind->SetPen(RED, 3); pWind->DrawLine(0, UI.ToolBarHeight, UI.width, UI.ToolBarHeight); } ////////////////////////////////////////////////////////////////////////////////////////// void Output::CreatePlayToolBar() const { UI.InterfaceMode = MODE_PLAY; ///TODO: write code to create Play mode menu string MenuItemImages[PLAY_ITM_COUNT]; /////////////////////////////////////////////////////////// ////TODO ::: ADD PLAY MODE MENU IMAGES ////////////////////// ///////////////////////////////////////////////////////////// MenuItemImages[ITM_PICKCOLOR] = "images\\MenuItems\\Pick_By_Color.jpg"; MenuItemImages[ITM_PICKTYPE] = "images\\MenuItems\\Pick_By_Type.jpg"; MenuItemImages[ITM_SWTODRAW] = "images\\MenuItems\\To_Draw_2.jpg"; // MenuItemImages[ITM_circ1] = "images\\MenuItems\\Menu_circ.jpg"; for (int i = 0; i < PLAY_ITM_COUNT; i++) pWind->DrawImage(MenuItemImages[i], i*UI.MenuItemWidth, 0, UI.MenuItemWidth, UI.ToolBarHeight); //////////////////////////////////////////////////////////// //Draw a line under the toolbar pWind->SetPen(RED, 3); pWind->DrawLine(0, UI.ToolBarHeight, UI.width, UI.ToolBarHeight); } ////////////////////////////////////////////////////////////////////////////////////////// void Output::CreateColorToolBar(ActionType A, string& ActStr) const { UI.InterfaceMode = MODE_COLOR; //Determining what action to do with the color, whether draw or fill pWind->SetBrush(UI.BkGrndColor); pWind->DrawRectangle(0, 0, UI.width, UI.ToolBarHeight); pWind->SetPen(RED, 3); string MenuItemImages[COLOR_ITM_COUNT]; MenuItemImages[ITM_RED] = "images\\MenuItems\\RED.jpg"; MenuItemImages[ITM_BLUE] = "images\\MenuItems\\Blue.jpg"; MenuItemImages[ITM_GREEN] = "images\\MenuItems\\Green.jpg"; MenuItemImages[ITM_BLACK] = "images\\MenuItems\\Black.jpg"; MenuItemImages[ITM_WHITE] = "images\\MenuItems\\White.jpg"; //The icon of applying the chosen color depends on if it's fill or draw color if (A == CHNG_DRAW_CLR) { MenuItemImages[ITM_PAINT] = "images\\MenuItems\\Menu_Draw_Color.jpg"; ActStr = "Draw"; } else if (A == CHNG_FILL_CLR) { MenuItemImages[ITM_PAINT] = "images\\MenuItems\\Menu_Fill_Color.jpg"; ActStr = "Fill"; } else { MenuItemImages[ITM_PAINT] = "images\\MenuItems\\Menu_Draw_Color.jpg"; ActStr = ""; } for (int i = 0; i < COLOR_ITM_COUNT; i++) pWind->DrawImage(MenuItemImages[i], i*UI.MenuItemWidth, 0, UI.MenuItemWidth, UI.ToolBarHeight); pWind->SetPen(RED, 3); pWind->DrawLine(0, UI.ToolBarHeight, UI.width, UI.ToolBarHeight); } ////////////////////////////////////////////////////////////////////////////////////////// void Output::ClearToolbar() const { pWind->SetPen(WHITE, 1); pWind->SetBrush(WHITE); pWind->DrawRectangle(0, 0, UI.width, UI.ToolBarHeight); } ////////////////////////////////////////////////////////////////////////////////////////// void Output::ClearDrawArea() const { pWind->SetPen(UI.BkGrndColor, 1); pWind->SetBrush(UI.BkGrndColor); pWind->DrawRectangle(0, UI.ToolBarHeight, UI.width, UI.height - UI.StatusBarHeight); } ////////////////////////////////////////////////////////////////////////////////////////// void Output::PrintMessage(string msg) const //Prints a message on status bar { ClearStatusBar(); //First clear the status bar pWind->SetPen(UI.MsgColor, 50); pWind->SetFont(20, BOLD, BY_NAME, "Arial"); pWind->DrawString(10, UI.height - (int)(UI.StatusBarHeight / 1.5), msg); } ////////////////////////////////////////////////////////////////////////////////////////// color Output::getCrntDrawColor() const //get current drawing color { return UI.DrawColor; } ////////////////////////////////////////////////////////////////////////////////////////// color Output::getCrntFillColor() const //get current filling color { return UI.FillColor; } ////////////////////////////////////////////////////////////////////////////////////////// int Output::getCrntPenWidth() const //get current pen width { return UI.PenWidth; } //======================================================================================// // Figures Drawing Functions // //======================================================================================// void Output::DrawRect(Point P1, Point P2, GfxInfo RectGfxInfo, bool selected) const { color DrawingClr; if (selected) DrawingClr = UI.HighlightColor; //Figure should be drawn highlighted else DrawingClr = RectGfxInfo.DrawClr; pWind->SetPen(DrawingClr, 1); drawstyle style; if (RectGfxInfo.isFilled) { style = FILLED; pWind->SetBrush(RectGfxInfo.FillClr); } else style = FRAME; pWind->DrawRectangle(P1.x, P1.y, P2.x, P2.y, style); } void Output::DrawLine(Point P1, Point P2, GfxInfo LINEGfxInfo, bool selected) const { color DrawingClr; if (selected) DrawingClr = UI.HighlightColor; //Figure should be drawn highlighted else DrawingClr = LINEGfxInfo.DrawClr; pWind->SetPen(DrawingClr, 1); drawstyle style; style = FRAME; pWind->DrawLine(P1.x, P1.y, P2.x, P2.y, style); } void Output::DrawTriangle(Point P1, Point P2, Point P3, GfxInfo TRIGfxInfo, bool selected) const { color DrawingClr; if (selected) DrawingClr = UI.HighlightColor; //Figure should be drawn highlighted else DrawingClr = TRIGfxInfo.DrawClr; pWind->SetPen(DrawingClr, 1); drawstyle style; if (TRIGfxInfo.isFilled) { style = FILLED; pWind->SetBrush(TRIGfxInfo.FillClr); } else style = FRAME; pWind->DrawTriangle(P1.x, P1.y, P2.x, P2.y, P3.x, P3.y, style); } void Output::DrawRhombus(Point P, GfxInfo RhombusGfxInfo, bool selected) const { if (P.y < 160) { P.y = 135; } else if (P.y > 500) { P.y = 524; } if (P.x < 100) { P.x = 50; } else if (P.x > 1150) { P.x = 1185; } color DrawingClr; if (selected) DrawingClr = UI.HighlightColor; //Figure should be drawn highlighted else DrawingClr = RhombusGfxInfo.DrawClr; pWind->SetPen(DrawingClr, 1); drawstyle style; if (RhombusGfxInfo.isFilled) { style = FILLED; pWind->SetBrush(RhombusGfxInfo.FillClr); } else style = FRAME; Point p1, p2, p3, p4; p1.x = P.x + 50; p1.y = P.y; p2.x = P.x - 50; p2.y = P.y; p3.x = P.x; p3.y = P.y + 75; p4.x = P.x; p4.y = P.y - 75; const int A[4] = { p1.x , p3.x , p2.x , p4.x }; const int B[4] = { p1.y , p3.y , p2.y , p4.y }; pWind->DrawPolygon(A, B, 4, style); } void Output::DrawEllipse(Point P1, GfxInfo EllipseGfxInfo, bool selected) const { color DrawingClr; if (selected) DrawingClr = UI.HighlightColor; //Figure should be drawn highlighted else DrawingClr = EllipseGfxInfo.DrawClr; pWind->SetPen(DrawingClr, 1); drawstyle style; if (EllipseGfxInfo.isFilled) { style = FILLED; pWind->SetBrush(EllipseGfxInfo.FillClr); } else style = FRAME; pWind->DrawEllipse(P1.x - 100, P1.y - 50, P1.x + 100, P1.y + 50, style); } ////////////////////////////////////////////////////////////////////////////////////////// Output::~Output() { delete pWind; }
true
86705898bc582b4a559448ab396012c4b88dfd47
C++
jacobswisher/ChessV3
/Headers/Move.h
UTF-8
738
3
3
[]
no_license
#include <cstdint> class Move { public: uint8_t origin; uint8_t destin; bool isCapture; bool isDoublePush; bool isKingCastle; bool isQueenCastle; bool isEP; bool isKnightPromo; bool isBishopPromo; bool isRookPromo; bool isQueenPromo; Move(uint8_t o, uint8_t d) { origin = o; destin = d; } Move(uint8_t o, uint8_t d, bool capture, bool doublePawn, bool kc, bool qc, bool ep, bool knightp, bool bishopp, bool rookp, bool queenp){ origin = o; destin = d; isCapture = capture; isDoublePush = doublePawn; isKingCastle = kc; isQueenCastle = qc; isEP = ep; isKnightPromo = knightp; isBishopPromo = bishopp; isRookPromo = rookp; isQueenPromo = queenp; } };
true
413af8ae4723bdc01dcf47890d1b2d9412fd0240
C++
veldrinlab/veldrinlabProjects
/AlleMario/AlleMario/Allegro/Viewport.cpp
WINDOWS-1250
1,858
2.984375
3
[]
no_license
/** * Viewport.cpp * File contains definition of Viewport class. * * Created on: 2010-07-09 * Author: Szymon "Veldrin" Jaboski */ #include <iostream> #include "Viewport.h" using namespace std; Viewport::Viewport() { setViewportWidth(640.0f); setViewportHeight(480.0f); setWorldX(0.0f); setWorldY(0.0f); setScreenX(0.0f); setScreenY(0.0f); viewportBlocked = false; } Viewport::~Viewport() { } void Viewport::updateViewport(float dt,ALLEGRO_KEYBOARD_STATE key_state) { velocity.setX(0.0f); //w naszym przypadku niepotrzebne velocity.setY(0.0f); if(al_key_down(&key_state,ALLEGRO_KEY_RIGHT) && !viewportBlocked) velocity.setX(96.0f); else if(al_key_down(&key_state,ALLEGRO_KEY_LEFT) && !viewportBlocked) velocity.setX(-96.0f); float deltaX = velocity.getX() * dt; float deltaY = velocity.getY() * dt; //w naszym przypadku nie potrzebne this->worldX = this->worldX + deltaX; this->worldY = this->worldY + deltaY; } void Viewport::setViewportWidth(float viewportWidth) { this->viewportWidth = viewportWidth; } void Viewport::setViewportHeight(float viewportHeight) { this->viewportHeight = viewportHeight; } void Viewport::setWorldX(float worldX) { this->worldX = worldX; } void Viewport::setWorldY(float worldY) { this->worldY = worldY; } void Viewport::setScreenX(float screenX) { this->screenX = screenX; } void Viewport::setScreenY(float screenY) { this->screenY = screenY; } float Viewport::getViewportWidth() { return viewportWidth; } float Viewport::getViewportHeight() { return viewportHeight; } float Viewport::getWorldX() { return worldX; } float Viewport::getWorldY() { return worldY; } float Viewport::getScreenX() { return screenX; } float Viewport::getScreenY() { return screenY; } void Viewport::setViewportVelocity(Vector2D newVelocity) { this->velocity = newVelocity; }
true
2c52e2517ed0c837e5d717636ea9265558cc9f03
C++
adillon3/CPSC-350-Assignment-5
/StudentBST.cpp
UTF-8
584
2.625
3
[]
no_license
/******************************* * Andrew Dillon * 2382400 * CPSC 350 * Assignment 05 *******************************/ #include "StudentBST.h" void StudentBST :: SerializeStudentBST(ostream& oFile) { SerializeStudentBSTHelper(oFile, root); } void StudentBST :: SerializeStudentBSTHelper(ostream& oFile, TreeNode<Student>* parentNode) { if(parentNode == nullptr) { return; } parentNode -> key.SerializeStudent(oFile); SerializeStudentBSTHelper(oFile, parentNode -> left); SerializeStudentBSTHelper(oFile, parentNode -> right); }
true
f464bc103cc52d6b60b316e9004a57473a7f61c1
C++
jwvg0425/boj
/solutions/3050/3050.cpp14.cpp
UTF-8
1,159
2.96875
3
[]
no_license
#include <stdio.h> #include <algorithm> #include <queue> #include <iostream> #include <bitset> #include <memory.h> int maxHeight[401][401]; int main() { int r, c; scanf("%d %d", &r, &c); std::vector<std::string> map; for (int i = 0; i < r; i++) { std::string str; std::cin >> str; map.push_back(str); } for (int x = 0; x < r; x++) { for (int y = 0; y < c; y++) { if (map[x][y] != '.') continue; //각 지점에서 시작해서 밑으로 뻗을 수 있는 최대 높이 저장해 둠 int count = 0; for (int h = y; h < c; h++) { if (map[x][h] != '.') break; count++; } maxHeight[x][y] = count; } } int maxNum = 0; for (int x = 0; x < r; x++) { for (int y = 0; y < c; y++) { if (map[x][y] != '.') continue; //모든 지점에서, 최대한 크게 만들 수 있는 모든 직사각형을 검사 int height = c; for (int w = 0; w < r - x && map[x+w][y] == '.'; w++) { height = std::min(height, maxHeight[x + w][y]); int num = (w + height + 1) * 2; maxNum = std::max(maxNum, num); } } } printf("%d", std::max(0, maxNum - 1)); return 0; }
true
26dabd1d457effade3123b233c473369f4b9cbdf
C++
cycasmi/proyectos-VS
/Segundo semestre orientada a objetos/ProyectoFinal v.5/YogurGriego.h
UTF-8
547
2.515625
3
[]
no_license
#pragma once #include "Yogur.h" class YogurGriego : public Yogur { private: string fruta; public: YogurGriego(string nombre, int costo, int precio, int calorias, int diaC, int mesC, int anioC) : Yogur(nombre, costo, precio, calorias, diaC, mesC, anioC) {} void imprimir() { cout << "\nSoy un Yogur Griego\n"; cout << nombre << endl << *costo << endl << *precio << endl << *calorias << endl; compraDate.imprimir(); } string getNombre() {}; int& getCosto() {}; int& getPrecio() {}; int& getCalorias() {}; string caducidad(){}; };
true
ee2453a5ecb6930328402fcb3c30b1c15548e756
C++
satomshr/toy_car
/test_motor_sensor_01/test_motor_sensor_01.ino
UTF-8
1,789
2.5625
3
[]
no_license
// test_motor_sensor_01.ico ; test program of mortor (DRV8835) and // ultrasonic sensor (HC-SR04) // author ; sato.mshr@gmail.com // connection of DRV8835 // Vcc = 5V // MODE = GND (using IN/IN mode) // AIN1 = D5 (arduino) // AIN2 = D6 (arduino) // BIN1 = GND // BIN2 = GND // VM = 3V // AOUT1 = Motor // AOUT2 = Motor // BOUT1 = open // BOUT2 = open // GND = GND // connection of HCSR04 // Vcc = 5V // Trig = D2 (arduino) // Echo = D3 (arduino) // GND = GND // Arduino Pin assign #define PIN_LED 13 #define PIN_MT_A 6 #define PIN_MT_B 5 #define PIN_TRIG 2 #define PIN_ECHO 3 #define DELAY_MSEC 100 #define HIGH_SPEED 153 // 255 / 5V * 3V #define LOW_SPEED 76 // 255 / 5V * 1.5V #define STOP_SPEED 0 #define STOP_DISTANCE 15 // cm #define BACK_DISTANCE 5 // cm float cm; void setup() { // put your setup code here, to run once: analogWrite(PIN_MT_A, STOP_SPEED); analogWrite(PIN_MT_B, STOP_SPEED); pinMode(PIN_LED, OUTPUT); pinMode(PIN_TRIG, OUTPUT); pinMode(PIN_ECHO, INPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(PIN_TRIG, LOW); delayMicroseconds(2); digitalWrite(PIN_TRIG, HIGH); delayMicroseconds(10); digitalWrite(PIN_TRIG, LOW); cm = pulseIn(PIN_ECHO, HIGH) / 58.0; //The echo time is converted into cm if(cm > STOP_DISTANCE){ // CW, High speed analogWrite(PIN_MT_A, HIGH_SPEED); analogWrite(PIN_MT_B, STOP_SPEED); } else if(cm > BACK_DISTANCE){ // Brake analogWrite(PIN_MT_A, HIGH_SPEED); analogWrite(PIN_MT_B, HIGH_SPEED); /* delay(100); analogWrite(PIN_MT_A, STOP_SPEED); analogWrite(PIN_MT_B, STOP_SPEED); */ } else{ // CCW, High speed analogWrite(PIN_MT_A, STOP_SPEED); analogWrite(PIN_MT_B, HIGH_SPEED); } delay(DELAY_MSEC); }
true
e564f72d13e7788f51185b1e3c304cf5c3214fcc
C++
legendsovermyths/DSA
/C++/PopulateInorderSuc.cpp
UTF-8
2,772
3.5625
4
[]
no_license
// { Driver Code Starts #include <stdio.h> #include <stdlib.h> #include <bits/stdc++.h> using namespace std; typedef long long int ll; struct node { int data; struct node *left; struct node *right; struct node *next; node(int x) { data = x; left = NULL; right = NULL; next = NULL; } }; struct node *Inorder(struct node *root) { if (root->left == NULL) return root; Inorder(root->left); } void populateNext(struct node *root); void insert(struct node *root, int n1, int n2, char lr) { if (root == NULL) return; if (root->data == n1) { switch (lr) { case 'L': root->left = new node(n2); break; case 'R': root->right = new node(n2); break; } } else { insert(root->left, n1, n2, lr); insert(root->right, n1, n2, lr); } } int main() { int t; cin >> t; while (t--) { int n; cin >> n; struct node *root = NULL; while (n--) { char lr; int n1, n2; cin >> n1 >> n2; cin >> lr; if (root == NULL) { root = new node(n1); switch (lr) { case 'L': root->left = new node(n2); break; case 'R': root->right = new node(n2); break; } } else { insert(root, n1, n2, lr); } } populateNext(root); struct node *ptr = Inorder(root); while (ptr) { printf("%d->%d ", ptr->data, ptr->next ? ptr->next->data : -1); ptr = ptr->next; } cout << endl; } return 0; } // } Driver Code Ends /* Set next of p and all descendents of p by traversing them in reverse Inorder */ /* Node Structure struct node { int data; struct node *left; struct node *right; struct node *next; node(int x){ data = x; left = NULL; right = NULL; next = NULL; } }; */ void inOrderP(node *root, vector<node *> &m) { if (root == NULL) return; inOrderP(root->left, m); m.push_back(root); inOrderP(root->right, m); } struct node *search(struct node *root, int key) { if (root == NULL || root->data == key) return root; if (root->data < key) return search(root->right, key); return search(root->left, key); } void populateNext(struct node *p) { vector<node *> m; inOrderP(p, m); for (int i = 0; i < m.size() - 1; i++) { m[i]->next = m[i + 1]; } }
true
268422c64518b601fe8a3c9e6c9fe633009956fa
C++
Sarvesh2k/FreeRTOS_Arduino
/Accurate_Delay/Accurate_Delay.ino
UTF-8
1,056
3.359375
3
[]
no_license
#include <Arduino_FreeRTOS.h> //Program to perform more accurate delays using getTick //Define two tasks void Task_Print1(void *param); void Task_Print2(void *param); TaskHandle_t TaskHandle_1; TaskHandle_t TaskHandle_2; void setup() { // Inititalize serial communication at 9600 bits per second Serial.begin(9600); //Create tasks xTaskCreate(Task_Print1, "Task1", 100, NULL, 1, &TaskHandle_1); xTaskCreate(Task_Print2, "Task2", 100, NULL, 1, &TaskHandle_2); } void loop() { // Empty. Things are done in Tasks } void Task_Print1(void *param) { (void) param; TickType_t getTick; getTick = xTaskGetTickCount(); // the getTick will get time from systick of OS vTaskDelayUntil(&getTick,1000 / portTICK_PERIOD_MS); while(1) { Serial.println("TASK 1"); vTaskDelayUntil(&getTick,1000 / portTICK_PERIOD_MS); // wait for one second. More accurate Delay } } void Task_Print2(void *param) { (void) param; while(1) { Serial.println("TASK 2"); vTaskDelay(1000 / portTICK_PERIOD_MS); // wait for one second } }
true
72a6b88c43cf7129815549c0e6a0077bfb0f13e5
C++
algorithm005-class01/algorithm005-class01
/Week_08/G20190343020042/LeetCode_8_0042.cpp
UTF-8
712
2.984375
3
[]
no_license
class Solution { public: int myAtoi(string str) { int index = 0, sign = 1, total = 0; if(str.length() == 0) return 0; while(str[index] == ' '&& index < str.length()) index++; if(str[index] == '+'||str[index] == '-'){ sign = str[index] == '+' ? 1 : -1; index++; } while(index < str.length()){ int digit = str[index] - '0'; if(digit < 0 || digit > 9) break; if(INT_MAX/10 < total || (INT_MAX/10 == total && INT_MAX%10 < digit)) return sign == 1 ? INT_MAX : INT_MIN; total = 10 * total + digit; index++; } return total * sign; } };
true
1b5f91339f29183b5fea31bc94cea012f594b4f7
C++
JustZyx/StackCalculator
/Input.h
UTF-8
359
2.875
3
[]
no_license
#if !defined (INPUT_H) #define INPUT_H const int maxBuf = 100; // Tokens are tokNumber, tokError, +, -, *, /. const int tokNumber = 1; const int tokError = 2; // Gets input from stdin, converts to token. class Input { public: Input (); int Token () const { return _token; } int Number () const; private: int _token; char _buf [maxBuf]; }; #endif
true
ee3915455c270c63ded2d8aa94abe2eae86deef0
C++
kiborroq/CPP_piscine
/CPP00/ex01/main.cpp
UTF-8
3,775
3.25
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kiborroq <kiborroq@kiborroq.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/07 15:20:54 by kiborroq #+# #+# */ /* Updated: 2021/03/12 11:56:02 by kiborroq ### ########.fr */ /* */ /* ************************************************************************** */ #include <string> #include <iostream> #include <iomanip> #include <sstream> #include "Contact.class.hpp" #include "PhoneBook.class.hpp" #include "Colors.class.hpp" void printWelcome(void) { std::cout << Colors::darkBlue("Hello! This is simple phonebook.") << std::endl << Colors::darkBlue("Phonebook knows only three command: ADD, SEARCH and EXIT.") << std::endl << Colors::blue("ADD: new contanct add") << std::endl << Colors::blue("SEARCH: display a list of the available contacts") << std::endl << Colors::blue("EXIT: the program quits") << std::endl << Colors::darkBlue("Let's start!") << std::endl << std::endl; } int translateInput(std::string input) { if (!input.compare("ADD")) return (1); if (!input.compare("SEARCH")) return (2); if (!input.compare("EXIT")) return (3); return (0); } std::string inputField(std::string nameField) { std::string field(""); while (!field.length()) { std::cout << Colors::blue(nameField + ": "); std::getline(std::cin, field); } return (field); } int isNum(std::string str) { for (std::string::iterator i = str.begin(); i < str.end(); i++) { if (*i < '0' || *i > '9') return (0); } return (1); } int inputIndex(void) { std::string indexField; std::stringstream converter; int index; indexField = inputField("contact index"); if (isNum(indexField)) { converter << indexField; converter >> index; } else index = -1; return (index); } void addContact(PhoneBook *phones) { std::cout << Colors::darkBlue("Enter contact’s information:") << std::endl; Contact newContact ( inputField("first name"), inputField("last name"), inputField("login"), inputField("postal adress"), inputField("phone number"), inputField("birth date"), inputField("favorite meal"), inputField("underwear color"), inputField("darkest secret") ); phones->add(newContact); std::cout << Colors::green("Contact has been successfully created!") << std::endl; } void searchPhoneBook(PhoneBook *phones) { int index; std::string num; phones->search(); if (phones->getCurrSize() == 0) { std::cout << Colors::darkBlue("Now phonebook is empty. You should create a new contact!") << std::endl; return ; } std::cout << Colors::darkBlue("Enter any contact index for detail information: ") << std::endl; index = inputIndex(); if (phones->isValidIndex(index)) phones->search(index); else std::cout << Colors::red("Index isn't valid!") << std::endl; } int main(void) { PhoneBook phones; std::string input; int command; printWelcome(); while (true) { std::cout << Colors::pink("PHONEBOOK >> "); std::getline(std::cin, input); command = translateInput(input); switch (command) { case 1: addContact(&phones); break; case 2: searchPhoneBook(&phones); break; case 3: return (0); break; default: break; } } return (0); }
true
87e0d723bdde3132233eca92eb9e185fbdd6b696
C++
Compiler/Far-Game-Engine
/FarEngine/src/EntityComponentSystem/EntityManager.h
UTF-8
5,809
2.765625
3
[]
no_license
#pragma once #include <stdint.h> #include <vector> #include <unordered_map> #include <memory> #include <EntityComponentSystem/Components/Component.h> #include <iostream> #include <Tools/Logging/TmpLog.h> namespace far{ typedef uint64_t Entity; class EntityManager{ private: std::unordered_map<uint64_t, const char*> __dbg_compIDToName; private: static uint64_t _ENTITY_COUNT; std::vector<Entity> _entities; std::unordered_map<ComponentID, std::vector<std::shared_ptr<Component>>> _components; std::vector<ComponentID> _componentIDs; std::unordered_map<Entity, std::unordered_map<ComponentID, std::shared_ptr<Component>>> _ecsMap; public: EntityManager() = default; Entity createEntity(){ Entity entity = _ENTITY_COUNT++; FAR_DEBUG("Entity #" << entity << " created!"); _ecsMap[entity] = std::unordered_map<ComponentID, std::shared_ptr<Component>>(); _entities.push_back(entity); return entity; } std::unordered_map<Entity, std::unordered_map<ComponentID, std::shared_ptr<Component>>> getECSMap(){return _ecsMap;}; template <typename CompType> void addComponent(Entity ent, std::shared_ptr<CompType> comp){ auto id = comp->getID(); auto name = CompType().name; FAR_LOG("'addComponent<type>'\n\tCompType id: \t" << CompType().name << " added to entity #" << ent); _ecsMap[ent][id] = comp; _components[id].push_back(comp); } template <typename CompType> void addComponent(Entity ent, CompType comp){ auto id = comp.getID(); auto compPtr = std::make_shared<CompType>(comp); auto name = CompType().name; FAR_LOG("'addComponent<type>'\n\tCompType id: \t" << CompType().name << " added to entity #" << ent); _ecsMap[ent][id] = compPtr; if(_components.find(id) == _components.end() ){ _components[id].push_back(compPtr); }//else _components[id] = st/d::vector<std::shared_ptr<Component>>(); } template <typename CompType, typename... Types> void addComponent(Entity ent, std::shared_ptr<CompType> comp, std::shared_ptr<Types> ... types){ auto id = comp->getID(); FAR_LOG("'addComponent<type>'\n\tCompType id: \t" << CompType().name << " added to entity #" << ent); _ecsMap[ent][id] = comp; if(_components.find(id) == _components.end() ){ _components[id].push_back(comp); }//else _components[id] = std::vector<std::shared_ptr<Component>>(); addComponent(ent, types...); } template <typename CompType> std::shared_ptr<CompType> getComponent(Entity ent){ return std::dynamic_pointer_cast<CompType>(_ecsMap[ent][CompType().getID()]); } template <typename CompType> std::vector<std::shared_ptr<CompType>> getComponentsList(){ std::vector<std::shared_ptr<CompType>> finalList; FAR_LOG("'getComponentsList'\n\tCompType id: \t" << CompType().name); auto baseList = _components[CompType().getID()]; std::cout << "\tBase list size: " << baseList.size() << "\n"; for(auto i : baseList){ finalList.push_back(std::dynamic_pointer_cast<CompType>(i)); } return finalList; } template<typename T> std::vector<Entity> getAssociatedEntities(){ std::vector<Entity> ids; Entity current; // _entities.size() crashes the program. Memory corruption. for(int i = 0; i < _entities.size(); i++){ current = _entities[i]; if(_ecsMap[current][T().getID()]) ids.push_back(current); } return ids; } template<typename T, typename M> std::vector<Entity> getAssociatedEntities(){ std::vector<Entity> ids; Entity current; for(int i = 0; i <_entities.size(); i++){ current = _entities[i]; if(_ecsMap[current][T().getID()] && _ecsMap[current][M().getID()]) ids.push_back(current); } return ids; } template<typename T, typename M, typename N> std::vector<Entity> getAssociatedEntities(){ std::vector<Entity> ids; Entity current; for(int i = 0; i <_entities.size(); i++){ current = _entities[i]; if(_ecsMap[current][T().getID()] && _ecsMap[current][M().getID()] && _ecsMap[current][N().getID()]) ids.push_back(current); } return ids; } // template <typename CompType> // std::vector<std::shared_ptr<CompType>> getComponents2DList(){ // auto list = getComponentsList<CompType>(); // } // template <typename CompType1, typename CompType2> // void getComponents2DList(std::vector<std::vector<std::shared_ptr<Component>>>& list, int placement = 0){ // //list[placement++].push_back(getComponentsList<CompType1>()); // //list[placement++].push_back(getComponentsList<CompType2>()); // } }; }
true
8d01464f10adbf410f2adc360c96f2d93e6321ca
C++
revilo196/ofVisualGenerator
/src/PreviewApp.cpp
UTF-8
1,069
2.8125
3
[]
no_license
/** * @file PreviewApp.cpp * @author PreviewApp code * @brief * @version 0.1 * @date 2020-06-26 * * @copyright Copyright (c) 2020 * */ #include "PreviewApp.h" /** * @brief setup the PreviewApp * allocate the FBO's */ void PreviewApp::setup() { settings.loadFile("settings.xml"); const int width = settings.getValue("settings:render:width", 1920); const int height = settings.getValue("settings:render:height", 1080); } /** * @brief upadte the window * */ void PreviewApp::update() { //Unsued } /** * @brief draw the diffrent preview FBO's * */ void PreviewApp::draw() { ofClear(0, 0, 0, 0); for (size_t i = 0; i < layers.size(); i++) { layers[i].draw(configs[i].offsetX, configs[i].offsetY, configs[i].width, configs[i].height); } } void PreviewApp::exit() { } /** * @brief add a Preview FBO to the preview window * * @param lay ofFbo to add to the preview * @param conf preview size an position in the window */ void PreviewApp::addLayer(ofFbo lay, PreviewConfig conf) { layers.push_back(lay); configs.push_back(conf); }
true
dd80099a5ea608621aaf694d4b054ba1d0740516
C++
YishaiSeela/ex3
/Map/BfsSearch.h
UTF-8
616
2.84375
3
[]
no_license
#ifndef EXERCISE1_BFSSEARCH_H #define EXERCISE1_BFSSEARCH_H #include "Grid.h" #include <queue> class BfsSearch // Class that performs the bfs algorithm search // and prints the shortest path { public: queue<Node *> ptQueue; // The stack for the bfs algorithm Grid gameGrid; // The grid of the map //BfsSearch(Grid &grid); // Ctor BfsSearch(Grid *grid); // Ctor void runBfs(); // Run the algorithm void visitNode(Node* parent, Node *vistingNode); void printPath(); // Prints the shortest path ~BfsSearch(); // Dtor std::vector<Point> path; }; #endif //EXERCISE1_BFSSEARCH_H
true
d18586db1a29fa3053482b4a75247575adf95d14
C++
Bingyy/LeetCode
/C++/lib.h
UTF-8
226
2.546875
3
[]
no_license
#include <vector> #include <algorithm> #include <string> #include <stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL){} };
true
0d4046c6d2bcd00d30eb46217d0e2f86d6e3960f
C++
dcampora/netfpga-polling
/poller/udp_headers.cpp
UTF-8
2,050
2.734375
3
[]
no_license
#include "udp_headers.h" UDPPacket::UDPPacket(GenericPacket* packet){ // Assuming the packet is an UDPPacket processPacket(packet->_header, packet->_packet); } bool UDPPacket::processPacket(const struct pcap_pkthdr* header, const u_char* packet){ cloneHeaderAndPacket(header, packet); // Generic type for all packets packet_type = "udp"; // Get the timestamp timestamp = _header->ts; /* define ethernet header */ ethernet = (struct sniff_ethernet*)(packet); /* define/compute ip header offset */ ip = (struct sniff_ip*)(packet + SIZE_ETHERNET); size_ip = ip->ip_header * 4; if (size_ip < 20) { // cerr << "Invalid IP header length: " << size_ip << endl; return 0; } /* determine protocol */ string protocol = "unknown"; if (size_ip < 20) protocol += " (not-IP)"; else { switch(this->ip->ip_p) { case IPPROTO_TCP: protocol = "TCP"; break; case IPPROTO_UDP: protocol = "UDP"; break; case IPPROTO_ICMP: protocol = "ICMP"; break; case IPPROTO_IP: protocol = "IP"; break; } } if(protocol == "UDP"){ /* define/compute tcp header offset */ udp = (struct sniff_udp*)(packet + SIZE_ETHERNET + size_ip); size_udp = ntohs(udp->ud_length); if (size_udp < 8) { // cerr << "Invalid UDP header length: " << size_udp << " bytes" << endl; return 0; } /* define/compute udp payload (segment) offset */ payload = packet + SIZE_ETHERNET + size_ip + 8; /* compute udp payload (segment) size */ size_payload = ntohs(ip->ip_len) - (size_ip + 8); /* size of udp headers is 8 */ } else { // cerr << "Protocol specified is " << protocol << " (not UDP)" << endl; return 0; } return 1; }
true