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
64408a3e240f514b810cf69c54783c0dcd004f83
C++
Asmilex/CppUniversityProjects
/First_year/Triannual1/Classwork/Parte 4/410.cpp
UTF-8
422
3.109375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main(){ vector<int> v(1); cout <<"Introduce una serie de valores: \n"; for (int i=0; i<v.size(); i++){ v.push_back(1); cin >>v[i]; if (v[i]==0){ v.pop_back(); v.pop_back(); } } for (int i=0; i<v.size(); i++) cout <<v[i]<<" "; }
true
b3b7b189f9033ce3b3f62d008a269e92f6d9d46d
C++
marcellosautto/Red-Black-Tree
/RBT.h
UTF-8
1,004
2.78125
3
[]
no_license
#pragma once #include <iostream> #include <fstream> #include <conio.h> #include <string> #include <Windows.h> using namespace std; class rbt { public: struct Node { Node* left; Node* right; Node* parent; Node* pnc; int num; bool black, isLC; Node() { left = nullptr; right = nullptr; parent = nullptr; num = 0; isLC = false; black = false; pnc = nullptr; }; Node(Node* p, int number, bool lc) { left = nullptr; right = nullptr; parent = p; num = number; isLC = lc; black = false; pnc = nullptr; }; }*root; //member variables int number; HANDLE color; //constructor rbt(); //member functions void run(), menu(), displayTree(Node* r, int x, int y, int width); struct Node* buildTree(Node* r, Node* p, bool isLC, int n), * rightRightRotate(Node* r), * leftLeftRotate(Node* r), * leftRightRotate(Node* r), * rightLeftRotate(Node* r), * balanceTree(Node* r); int Difference(Node* r); int height(Node* r) const; };
true
858015648967eb4ac7316da437d36e60acb99952
C++
paquiro/Exams-2-Ing-Inform.
/Primer Cuatrimestre/POO/ExamenesResueltos/POOFebrero/ong.hpp
UTF-8
869
2.671875
3
[]
no_license
#ifndef __ONG_H_ #define __ONG_H_ #include <string> #include <vector> #include "socio.hpp" #include "persona.hpp" using namespace std; class Ong { public: Ong(); ~Ong(); string getNombreOng() {return nombreOng_;} void setNombreOng(string nombreOng) {nombreOng_ = nombreOng;} void setVectorSocios(vector<Socio> vectorSocios) {vectorSocios_ = vectorSocios;} vector<Socio> getVectorSocios() {return vectorSocios_;} unsigned int getNumeroSocios() {return vectorSocios_.size();} Socio* getSocio(unsigned int indice) {return &(vectorSocios_[indice]);} Socio* operator [] (unsigned int indice) {return &(vectorSocios_[indice]);} void operator = (Ong ong); void leerOng(); void escribirOng(); bool grabarOngEnFichero(string nombreFichero); private: string nombreOng_; vector<Socio> vectorSocios_; }; #endif
true
78990b4f66c88165c39e98ad7f780966594bc21c
C++
aigerard/cplusplus-coursera
/examples/9 - template_functions/ExampleClass.h
UTF-8
850
3.375
3
[]
no_license
#include <iostream> #ifndef EXAMPLE_CLASS_H #define EXAMPLE_CLASS_H using namespace std; namespace ExampleNamespace { // only one declared template<typename T> class ExampleClass { public: int num; T flexibleVar; // best to define these in the same class with template<typename T> declaration void exampleMethodOne() { cout << "exampleMethodOne() " << flexibleVar << " " << typeid(flexibleVar).name() << endl; } T flexibleMethodOne(T a) { cout << "flexibleMethodOne() " << a << " " << typeid(a).name() << endl; return a; } T flexibleMethodTwo(T a, T b) { T result = a + b; cout << "flexibleMethodTwo() " << result << " " << typeid(result).name() << endl; return a + b; } }; } #endif
true
477ce36c4537e85d522a71f574dcfbef7d1df147
C++
alvls/mp1-2020-1
/troegubova_aa/task2/VectorClass.cpp
UTF-8
2,723
3
3
[]
no_license
#include <iostream> #include "Vector.h" Vector::Vector() { count = 0; memo = nullptr; } Vector::Vector(int _count) : count(_count) { memo = new int[count]; } Vector::Vector(int _count, int d) : count(_count) { memo = new int[count]; for (int i = 0; i < count; ++i) memo[i] = d; } Vector::Vector(int _count, int* ar) : count(_count) { memo = new int[count]; for (int i = 0; i < count; ++i) memo[i] = ar[i]; } Vector::Vector(const Vector &vec) { count = vec.count; memo = new int[count]; for (int i = 0; i < count; ++i) memo[i] = vec.memo[i]; } Vector::~Vector() { delete[] memo; memo = NULL; count = 0; } void Vector::outPut(const char* name) { std::cout << name << ":\t "; for (int i = 0; i < count; ++i) std::cout << memo[i] << "\t"; std::cout << std::endl; } void Vector::outPut(const char* name) const { std::cout << name << ":\t "; for (int i = 0; i < count; ++i) std::cout << memo[i] << "\t"; std::cout << std::endl; } void Vector::setSize(int _count) { delete[] memo; count = _count; memo = new int(count); } void Vector::setComp(int _numd, int _valute) { memo[_numd] = _valute; } int Vector::getSize() { return count; } int Vector::getComp(int numb) { return memo[numb]; } double Vector::getLen() { double len = 0; for (int i = 0; i < count; i++) len += memo[i] * memo[i]; len = sqrt(len); return len; } int& Vector::operator[](int index) { if (index < 0 || index >= count) abort(); return memo[index]; } Vector& Vector::operator=(const Vector &vec) { if (this != &vec) { if (count != vec.count) { delete[] memo; count = vec.count; memo = new int[count]; } for (int i = 0; i < count; ++i) memo[i] = vec.memo[i]; } return *this; } Vector Vector::operator+(const Vector &vec) { if (count != vec.count) abort(); Vector res(count); for (int i = 0; i < count; ++i) res.memo[i] = memo[i] + vec.memo[i]; return res; } int Vector::operator*(const Vector &vec) { if (count != vec.count) abort(); int res = 0; for (int i = 0; i < count; ++i) res += memo[i] * vec.memo[i]; return res; } Vector operator*(int d, const Vector &vec) { Vector res(vec.count); for (int i = 0; i < vec.count; ++i) res.memo[i] = d * vec.memo[i]; return res; } std::ostream& operator<<(std::ostream& stream, const Vector &vec) { for (int i = 0; i < vec.count; ++i) stream << vec.memo[i] << " "; stream << std::endl; return stream; } std::istream& operator>>(std::istream& stream, Vector &vec) { int strCount; stream >> strCount; if (vec.count != strCount) { if (vec.memo != NULL) delete[] vec.memo; vec.count = strCount; vec.memo = new int[strCount]; } for (int i = 0; i < vec.count; ++i) stream >> vec.memo[i]; return stream; }
true
87bcc2e524598c5cce5c3deed40049b580ff6a89
C++
sooreect/Harry-Potter-and-the-3-Socks
/space.hpp
UTF-8
785
2.90625
3
[]
no_license
//Tida Sooreechine //Final Project, 12/5/15 //space.hpp is the Space class specification file #ifndef SPACE_HPP #define SPACE_HPP #include <iostream> #include <string> #include "die.hpp" using std::cin; using std::cout; using std::endl; using std::string; //Space class declaration class Space { protected: int id; int type; string name; string enemy; string task; string reward; int numSides; bool taskCompleted; public: Space *north; Space *east; Space *west; Space *south; int getID(); int getType(); string getName(); string getEnemy(); string getReward(); void setMap(Space *north, Space *east, Space *west, Space *south); virtual void getTask() = 0; virtual bool special(int number) = 0; bool getTaskCompleted(); void setTaskCompleted(bool status); }; #endif
true
0d3aa669d42f8916fe575204ff884461fbbc0ce9
C++
ivanmmurciaua/P2
/P1/PRACTICA1/autocorrectorP2p1/uncleOwen.cc
UTF-8
9,533
2.828125
3
[]
no_license
//DNI 48729799K MAÑUS MURCIA,IVÁN #include <iostream> #include <climits> #include <vector> #include <string> using namespace std; // ---------------- android ------------------------- const int NUMDROIDMODELS=5; const string droidModels[NUMDROIDMODELS] = { "x-75", "fx-7", "JK9", "XAR-25", "HC-2" }; enum Status {ST_WORKING, ST_IDLE}; typedef struct { string model; int speed; int serialNumber; Status status; } Android; // ---------------- field ------------------------- int const WORK_HOURS=5; typedef struct { string name; int products; vector<Android> androids; } Field; // ---------------- farm -------------------------- typedef struct { string name; vector<Field> fields; vector<Android> androids; } Farm; // ---------------- error ------------------------- enum Error {ERR_NO_FIELDS, ERR_UNKNOWN_OPTION, ERR_WRONG_MODEL, ERR_WRONG_FIELD, ERR_WRONG_SPEED, ERR_WRONG_PRODUCTS, ERR_NAME}; void error(Error n){ switch (n) { case ERR_NO_FIELDS: cout << "Error, there are no fields in the farm" << endl; break; case ERR_UNKNOWN_OPTION: cout << "Error, unknown option" << endl; break; case ERR_WRONG_MODEL: cout << "Error, wrong android model name" << endl; break; case ERR_WRONG_FIELD: cout << "Error, wrong field name" << endl; break; case ERR_WRONG_SPEED: cout << "Error, wrong speed" << endl; break; case ERR_WRONG_PRODUCTS: cout << "Error, wrong number of products" << endl; break; case ERR_NAME: cout << "Error, field name repeated" << endl; break; } } //--------------------------------------------------------------- const string HEADER1="---- start ----"; const string HEADER2="---- distribution ----"; const string HEADER3="---- end ----"; //--------------------------------------------------------------- //clear buffer void clearBf(){ while (cin.get() != '\n'); } // validate model of Android bool validModel(string model){ bool result=false; for(int i=0;i<NUMDROIDMODELS;i++){ if(model==droidModels[i]) result=true; } return(result); } // validate that number > 0 bool validHigherThan0(int quantity){ bool result=true; if(quantity<=0) result=false; return(result); } // validate the repetition of field name bool equalityFarmName(string fname, const Farm &farm){ bool result=true; for(size_t i=0;i<farm.fields.size();i++){ if(fname==farm.fields[i].name) result=false; } return(result); } // at least one field in the farm bool atLeastOne(const Farm &farm){ bool result=true; if(farm.fields.size()==0) result=false; return(result); } // comprobate that there are more than 0 products to recollect bool dif0(const Farm &farm){ bool result=false; for(size_t i=0;i<farm.fields.size();i++){ if(farm.fields[i].products!=0) result=true; } return(result); } // position of the elected field to add products int positionOfField(string farmname, const Farm &farm){ int result=0; for(size_t i=0;i<farm.fields.size();i++){ if(farmname==farm.fields[i].name){ result=i; } } return(result); } // prints android info void printAndroid(const Android &android){ cout << "[" << android.model << " sn=" << android.serialNumber << " s=" << android.speed << " st=" << android.status << "]" << endl; } // prints field info void printField(const Field &field){ cout << "{Field: " << field.name << "(" << field.products << ")" << endl; for(size_t i=0;i<field.androids.size();i++){ cout << " "; printAndroid(field.androids[i]); } cout << "}" << endl; } // prints farm info void printFarm(const Farm &farm){ cout << "Farm: " << farm.name << endl; for(size_t i=0;i<farm.fields.size();i++) printField(farm.fields[i]); for(size_t i=0;i<farm.androids.size();i++) printAndroid(farm.androids[i]); } // Creates a new android asking the data to the user given nextSerialNumber, and // adds the android to the farm void createAndroid(Farm &farm, int &nextSerialNumber){ Android a; string model=""; int velocity; cout << "Enter android speed: "; cin>>velocity; if(validHigherThan0(velocity)){ clearBf(); cout << "Enter android model: "; getline(cin,model); //cin>>model; if(validModel(model)){ a.model=model; a.speed=velocity; a.serialNumber=nextSerialNumber; a.status=ST_IDLE; farm.androids.push_back(a); nextSerialNumber++; } else error(ERR_WRONG_MODEL); } else error(ERR_WRONG_SPEED); } // creates a new field in the farm with the name provided by the user void createField(Farm &farm){ Field f; string fname=""; cout << "Enter field name: "; getline(cin,fname); if(equalityFarmName(fname,farm)){ f.name=fname; f.products=0; farm.fields.push_back(f); } else error(ERR_NAME); } //distribute the androids void distribution(Farm &farm, int position){ int maxsp=0; Android android; int pos; for(size_t i=0;i<farm.androids.size();i++){ if(farm.androids[i].speed>maxsp){ maxsp=farm.androids[i].speed; pos=i; } } android.model=farm.androids[pos].model; android.speed=farm.androids[pos].speed; android.serialNumber=farm.androids[pos].serialNumber; android.status=ST_WORKING; farm.fields[position].androids.push_back(android); farm.androids.erase(farm.androids.begin()+pos); } // fields not equal 0 void fieldsW0P(vector<int> &v,const Farm &farm){ for(size_t i=0;i<farm.fields.size();i++){ if(farm.fields[i].products!=0) v.push_back(i); } } // distributes the farm's androids among its fields void distributeAndroids(Farm &farm){ vector<int> v; //VECTOR FIELDS > 0 PRODUCTS vector<int> iguales; int min=INT_MAX; fieldsW0P(v,farm); if(dif0(farm)){ while(farm.androids.size()>0){ int max=0; int pos,tamanyo; for(size_t i=0;i<v.size();i++){ tamanyo=farm.fields[v[i]].androids.size(); if(tamanyo<min) min=tamanyo; if(tamanyo==min) iguales.push_back(v[i]); } if(iguales.size()>0){ for(size_t i=0;i<iguales.size();i++){ if(farm.fields[iguales[i]].products>max){ max=farm.fields[iguales[i]].products; pos=iguales[i]; } } iguales.clear(); distribution(farm,pos); } else min++; } } } // return one android to recollect Android recollectAndroids(Field &field,int pos){ Android android; android.model=field.androids[pos].model; android.speed=field.androids[pos].speed; android.serialNumber=field.androids[pos].serialNumber; android.status=ST_IDLE; return(android); } // simulates the collection of products in a field by its androids void collectField(Field &field){ int vel=0; for(size_t i=0;i<field.androids.size();i++) vel=vel+field.androids[i].speed; field.products=field.products-(vel*WORK_HOURS); if(field.products<0) field.products=0; } // collects the products in the farm's fields void collectFarm(Farm &farm){ cout << HEADER1 << endl; printFarm(farm); cout << HEADER2 << endl; distributeAndroids(farm); printFarm(farm); cout << HEADER3 << endl; for(size_t i=0;i<farm.fields.size();i++){ collectField(farm.fields[i]); for(size_t j=0;j<farm.fields[i].androids.size();j++) farm.androids.push_back(recollectAndroids(farm.fields[i],j)); farm.fields[i].androids.clear(); } printFarm(farm); } // asks for products data in the farm's fields, then collects them void startWorkingDay(Farm &farm){ if(atLeastOne(farm)){ string option=""; int products=0; do{ cout << "Enter field name: "; getline(cin,option); cin.clear(); if(option!="q"){ if(!equalityFarmName(option,farm)){ cout << "Products: "; cin >> products; clearBf(); if(validHigherThan0(products)){ farm.fields[positionOfField(option,farm)].products=farm.fields[positionOfField(option,farm)].products+products; } else error(ERR_WRONG_PRODUCTS); } else error(ERR_WRONG_FIELD); } }while(option!="q"); collectFarm(farm); } else error(ERR_NO_FIELDS); } void menu(){ cout << "-----========== Farm manager ==========-----" << endl << "1- List farm info" << endl << "2- Add field" << endl << "3- Add android" << endl << "4- Start working day" << endl << "q- Quit" << endl << "Option: " ; } int main(){ Farm farm; farm.name = "west farm"; char option; int nextSerialNumber = 100; do { menu(); cin >> option; cin.get(); switch (option) { case '1': {printFarm(farm); break; } case '2': {createField(farm); break; } case '3': {createAndroid(farm,nextSerialNumber); break; } case '4': {startWorkingDay(farm); break; } case 'q': { break; } default: { error(ERR_UNKNOWN_OPTION); break; } } } while (option != 'q'); return 0; }
true
a93a1bad081393420cf45bde0800c2eaf8b3d62f
C++
btcup/sb-admin
/exams/2558/02204111/1/final/4_1_715_5820502302.cpp
UTF-8
773
2.90625
3
[ "MIT" ]
permissive
#include<iostream> #include<cmath> using namespace std; /*int GetInVal(int z,int x,int y) { cout<<x<<"b10 is "<<z<<"b"<<y<<endl; return 0; }*/ int main() { int x,y; float i,j; float k,z=0; do { cout<<"Enter decimal number: "; cin>>x; cout<<"Enter base(2-9)"; cin>>y; if(x>0||x==0) { continue; } /*{ for(i=0;i<10;i++) { k = x%y; j = x/y; x = j; if(j>y) { k = pow(y,i); z = z + k; } else if(j<y) { GetInVal(z,x,y); } } }*/ else if(x<0) { break; } } while(1); return 0; }
true
6f55c5f6575f592ad334ad46549f7ee06b10090b
C++
nexusstar/SoftUni
/Cplusplus/week_four/extra/DailyTask_Paint/paint.cpp
UTF-8
1,358
3.34375
3
[ "MIT" ]
permissive
#include <iostream> class Size { public: float x; float y; }; class PaintObject { public: char color[4]; Size size; Size sheetSize; }; class Whale { public: Size size; char sckinColor[4]; unsigned short mass; }; class PaintWhale : public Whale, public PaintObject, public Size { public: void whaleSizeOnSheet(); double scaleFactor(); }; void PaintWhale::whaleSizeOnSheet() { double scaleFactorOnX = this -> Whale::size.x / this -> PaintObject::sheetSize.x; double scaleFactorOnY = this -> Whale::size.y / this -> PaintObject::sheetSize.y; double desiredScaleFactor; if (scaleFactorOnX > scaleFactorOnY) { desiredScaleFactor = scaleFactorOnX; } else { desiredScaleFactor = scaleFactorOnY; } this -> PaintObject::size.x = this->Whale::size.x / desiredScaleFactor; this -> PaintObject::size.y = this->Whale::size.x / desiredScaleFactor; } double PaintWhale::scaleFactor() { return this -> PaintObject::size.x / this -> Whale::size.x; } int main() { using std::cout; using std::endl; PaintWhale aPaintWhale; aPaintWhale.Whale::size.x = 12; aPaintWhale.Whale::size.y = 4; aPaintWhale.PaintObject::sheetSize.x = 0.3; aPaintWhale.PaintObject::sheetSize.y = 0.2; aPaintWhale.whaleSizeOnSheet(); cout << aPaintWhale.scaleFactor() << endl; return 0; }
true
587dd5438cee69ebef4321ef0f5e19c8a8d5fea8
C++
CM4all/libcommon
/test/net/TestAnonymize.cxx
UTF-8
2,208
2.6875
3
[]
no_license
// SPDX-License-Identifier: BSD-2-Clause // Copyright CM4all GmbH // author: Max Kellermann <mk@cm4all.com> #include "net/Anonymize.hxx" #include <gtest/gtest.h> #include <string> using std::string_view_literals::operator""sv; void PrintTo(std::string_view s, std::ostream* os) { *os << '"' << s << '"'; } void PrintTo(std::pair<std::string_view, std::string_view> p, std::ostream* os) { *os << '"' << p.first << p.second << '"'; } namespace std { bool operator==(pair<string_view, string_view> a, const string_view b) noexcept { string c(a.first); c.append(a.second); return c == b; } } // namespace std TEST(Anonymize, Other) { EXPECT_EQ(AnonymizeAddress("foo"sv), "foo"sv); EXPECT_EQ(AnonymizeAddress("foo.example.com"sv), "foo.example.com"sv); } TEST(Anonymize, IPv4) { EXPECT_EQ(AnonymizeAddress("1.2.3.4"), "1.2.3.0"); EXPECT_EQ(AnonymizeAddress("123.123.123.123"), "123.123.123.0"); } TEST(Anonymize, IPv6) { EXPECT_EQ(AnonymizeAddress("1:2:3:4:5:6:7:8"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1:2:3:4:5:6:7:8"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1:2:3:4:5:6:7::"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1:2:3:4:5::"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1:2:3:4::"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1:2:3::"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1:2:ab:4:5:6:7:8"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1:2:abc:4:5:6:7:8"), "1:2:a00::"); EXPECT_EQ(AnonymizeAddress("1:2:abcd:4:5:6:7:8"), "1:2:ab00::"); EXPECT_EQ(AnonymizeAddress("1:2:abcd:4:5:6:7::"), "1:2:ab00::"); EXPECT_EQ(AnonymizeAddress("1:2:abcd:4:5::"), "1:2:ab00::"); EXPECT_EQ(AnonymizeAddress("1:2:abcd:4::"), "1:2:ab00::"); EXPECT_EQ(AnonymizeAddress("1:2:abcd::"), "1:2:ab00::"); EXPECT_EQ(AnonymizeAddress("1:2::"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1::"), "1::"); EXPECT_EQ(AnonymizeAddress("::1"), "::"); EXPECT_EQ(AnonymizeAddress("1:2:abcd::6:7:8"), "1:2:ab00::"); EXPECT_EQ(AnonymizeAddress("1:2:3:4:5::7:8"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1:2:3:4:5::8"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1:2::8"), "1:2::"); EXPECT_EQ(AnonymizeAddress("1:2::7:8"), "1:2::"); }
true
5a458daf20a15213a07b114f9e617b76fa80c85b
C++
teamhimeh/simutrans
/script/api/api_simple.h
UTF-8
992
2.703125
3
[ "Artistic-1.0" ]
permissive
/* * This file is part of the Simutrans project under the Artistic License. * (see LICENSE.txt) */ #ifndef SCRIPT_API_API_SIMPLE_H #define SCRIPT_API_API_SIMPLE_H #include "../../squirrel/squirrel.h" #include "../../dataobj/ribi.h" /** @file api_simple.h Helper functions to export simple datatypes: ribi & friends */ /** * Use own type for ribis and slopes */ struct my_ribi_t { uint8 data; my_ribi_t(ribi_t::ribi r) : data(r) { } operator ribi_t::ribi() const { return data; } }; struct my_slope_t { uint8 data; my_slope_t(slope_t::type r) : data(r) { } operator slope_t::type() const { return data; } }; namespace script_api { struct mytime_t { uint32 raw; mytime_t(uint32 r_) : raw(r_) {} }; struct mytime_ticks_t : public mytime_t { uint32 ticks; uint32 ticks_per_month; uint32 next_month_ticks; mytime_ticks_t(uint32 r, uint32 t, uint32 tpm, uint32 nmt) : mytime_t(r), ticks(t), ticks_per_month(tpm), next_month_ticks(nmt) {} }; }; #endif
true
9f0bc4e2ac511cfbba32ed2a54907327bf3b2460
C++
lex-96/ip_filter
/ip_filter_test.cpp
UTF-8
1,136
2.546875
3
[]
no_license
#define BOOST_TEST_MODULE test_main #include <boost/test/included/unit_test.hpp> #include "ip_filter.h" BOOST_AUTO_TEST_SUITE(test_suite_main) BOOST_AUTO_TEST_CASE(test_split) { BOOST_CHECK( split( "aaaa\taaa\taa\ta", '\t') == std::vector<std::string>({ "aaaa", "aaa", "aa", "a"}) ); BOOST_CHECK( split(".." , '.') == std::vector<std::string>({"", "", "" }) ); BOOST_CHECK( split("aa.aa." , '.') == std::vector<std::string>({"aa", "aa", "" }) ); BOOST_CHECK( split(".aa.aa" , '.') == std::vector<std::string>({"", "aa", "aa" }) ); BOOST_CHECK( split("aa..aa" , '.') == std::vector<std::string>({"aa", "", "aa" }) ); BOOST_CHECK( split("aa" , '.') == std::vector<std::string>({"aa" }) ); BOOST_CHECK( split("" , '.') == std::vector<std::string>({"" }) ); } BOOST_AUTO_TEST_CASE(test_getIP) { BOOST_CHECK( getIP("221.22.45.31") == ip_adress({ 221, 22, 45, 31}) ); BOOST_CHECK_THROW(getIP("121.322.45.71"), std::invalid_argument); BOOST_CHECK_THROW(getIP("240.234.121.22.56.78"), std::length_error); BOOST_CHECK_THROW(getIP("240.234"), std::length_error); } BOOST_AUTO_TEST_SUITE_END()
true
c51d1b05e9d78958877c80ac78a6d73f93060cf7
C++
markpudd/gate_opener
/arduino/GateOpener/GateOpener.ino
UTF-8
6,630
2.734375
3
[ "MIT" ]
permissive
/* Non replay request This code is a simple 2 request secure request for Arduino It works by having a shatred seceret between the client and the arduino (hmacKey). The first request generated a random token which is passed back to the client. The client then appends a command ("open") to the token and creates the hmac digest which it sends back to the server. The server can then verify the request using the hmac key. The above method should be able to avoid replay attacks. There are a few limitations:- - There is only one token which changes on every token request. This means that it only supports one client at a time. There is also no checking arround this so if multiple client use the server it won't work properly - The random() function is somewhat predicatble. An improvement would be to seed the random geneator with some "noise" from an analogue pin. */ #include <SPI.h> #include <Ethernet.h> #include "sha1.h" // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192,168,1,177); int openPin = 4; // LED connected to digital pin 13 int inPin =2; // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); //Servo myservo; // create servo object to control a servo char token[16]; const int requestBufferSize=512; char requestBuffer[requestBufferSize]; // Randon key for HMAC - Should change char * hmacKey = "TESTHMACKEY"; void setup() { pinMode(openPin, OUTPUT); pinMode(inPin, INPUT); digitalWrite(openPin, LOW); // Open serial communications and wait for port to open: Serial.begin(9600); // myservo.attach(9); // attaches the servo on pin 9 to the servo object while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // start the Ethernet connection and the server: Ethernet.begin(mac, ip); server.begin(); Serial.print("server is at "); Serial.println(Ethernet.localIP()); } void generateToken(EthernetClient client) { for(int i=0;i<15;i++) { token[i]= (char)random(26)+65; } token[15]=0; // Just return the token (no markup) Serial.println("Token "); Serial.println(token); client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/plain"); client.println("Connection: close"); client.println(); client.println(token); Serial.println("Sent "); // client.println("Content-Type: text/plain"); //client.println("Connection: close"); // the connection will be closed after completion of the response } void openGate() { Serial.println("bbOpen Suceess "); // digitalWrite(openPin, HIGH); // delay(500); // waits for a second // digitalWrite(openPin, LOW); } void hashToString(uint8_t* hash, char* buffer) { int i; for (i=0; i<20; i++) { buffer[i*2] = "0123456789abcdef"[hash[i]>>4]; buffer[i*2+1] = "0123456789abcdef"[hash[i]&0xf]; } buffer[40]=0; } void generateOpen(EthernetClient client, char * digest) { char hmBuffer[41]; char checkString[100]; Sha1.initHmac((uint8_t*)hmacKey,strlen(hmacKey)); strcpy(checkString, token); strcat(checkString, "open"); Sha1.print(checkString); Serial.println(checkString); client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/plain"); client.println("Connection: close"); client.println(); hashToString(Sha1.resultHmac(),hmBuffer); Serial.println(digest); Serial.println("***"); Serial.println(hmBuffer); Serial.println("***"); if(strcmp(digest,hmBuffer) == 0) { client.println("OK"); openGate(); } else client.println("FAIL"); } void checkButton() { // read the state of the pushbutton value: int buttonState = digitalRead(inPin); // check if the pushbutton is pressed. // if it is, the buttonState is HIGH: if (buttonState == HIGH) { openGate(); } } void loop() { checkButton(); // listen for incoming clients EthernetClient client = server.available(); if (client) { Serial.println("new client"); // an http request ends with a blank line boolean currentLineIsBlank = true; boolean isTokenRequest =false; boolean isOpenRequest =false; boolean digestSet =false; char digest[41]; int bufPos =0; while (client.connected()) { if (client.available()) { char c = client.read(); if(bufPos < (requestBufferSize-1)) { requestBuffer[bufPos]=c; bufPos++; } Serial.write(c); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if ((c == '\n' || c==0) && currentLineIsBlank) { if(isTokenRequest) { generateToken(client); break; } else if (isOpenRequest) { // Read next line bufPos =0; c = client.read(); while(client.available()) { requestBuffer[bufPos++]=c; c=client.read(); } requestBuffer[bufPos++]=c; requestBuffer[bufPos++]=0; if(strncmp(requestBuffer,"d=",2) == 0 && bufPos >41) { strncpy(digest, requestBuffer+2, 40); digest[40]=0; Serial.println("Digest Rec"); Serial.println(requestBuffer); digestSet = true; generateOpen(client,digest); } break; } // } if (c == '\n'){ if(strncmp(requestBuffer,"GET /token",10) == 0) isTokenRequest = true; if(strncmp(requestBuffer,"POST /open",10) == 0) isOpenRequest = true; requestBuffer[bufPos]=0; bufPos =0; currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disonnected"); } }
true
ce9374660b7e5bbd314960a775a4ca290c947212
C++
brokenhalo420/Store-System
/Store.cpp
UTF-8
4,059
3.265625
3
[]
no_license
#include "Store.h" #include <iostream> using namespace std; Store::Store() { this->myProfile = Profile(); this->myData = Database(); this->myAccounts = AccountManager(); this->isLogged = false; } Store::Store(const Database& database, const AccountManager& myAccounts) { this->myProfile = Profile(); this->myData = database; this->myAccounts = myAccounts; this->isLogged = false; } const Profile& Store::getProfile() const { return this->myProfile; } const Database& Store::getData() const { return this->myData; } void Store::setProfile(const Profile& other) { for (Profile it : this->myAccounts.getList()) { if (it == other) { this->myProfile = other; return; } } cout << "This profile is not registered in the system" << endl; return; } void Store::setData(const Database& other) { this->myData = other; } void Store::login(string username, string password) { if (this->isLogged) { cout << "You are already logged in..." << endl; return; } for (Profile it : this->myAccounts.getList()) { if (it.getUsername()._Equal(username) && it.getPassword()._Equal(password)) { this->myProfile = it; this->isLogged = true; cout << "Welcome, " << this->myProfile.getFirstName() << endl; return; } } cout << "No user with this username and password found" << endl; return; } void Store::logout() { if (this->isLogged) { this->updateManager(); this->isLogged = false; this->myProfile = Profile(); cout << "You've succesfully logged out" << endl; return; } cout << "You're not logged in..." << endl; return; } void Store::registration(const Profile& other) { this->myAccounts.addUser(other); } void Store::addProduct(const Product& other, int quantity) { this->myData.addProduct(other, quantity); } void Store::removeProduct(string serialId) { this->myData.removeProduct(serialId); } void Store::removeProductQuantity(string serialId, int quantity) { this->myData.removeProductQuantity(serialId, quantity); } void Store::removeUser(const Profile& other) { this->myAccounts.removeUser(other); } void Store::addToShoppingCart(const Product& newProduct, int quantity) { if (this->isLogged) { pair<Product, int> temp(newProduct, quantity); for (pair<Product, int> product : this->myData.getList()) { if (temp.first == product.first) { if (temp.second <= product.second) { this->myProfile.addToCart(newProduct, quantity); this->updateManager(); return; } else { cout << "Not enough quantity in storage to add" << endl; return; } } } cout << "No such product identified in the database" << endl; return; } else { cout << "You are not logged in" << endl; return; } } void Store::removeFromShoppingCart(const Product& removal) { this->myProfile.removeFromCart(removal); this->updateManager(); } void Store::addToFavorites(const Product& newProduct) { this->myProfile.addToFavorites(newProduct); this->updateManager(); } void Store::removeProductFromFavorites(const Product& removal) { this->myProfile.removeFromFavorites(removal); this->updateManager(); } ostream& operator<<(ostream& cout, const Store& other) { //if (other.myAccounts.getUserCount() == 0 && other.myData.getProductCount() == 0) //{ // cout << "Empty Store" << endl; // return cout; //} cout << "----------------------------------------------------- " << endl; cout << "Current Profile:\n" << other.myProfile << endl; cout << "----------------------------------------------------- " << endl; cout << "The DataBase:\n" << other.myData<<endl; cout << "----------------------------------------------------- " << endl; cout << "The Account Manager:\n" << other.myAccounts << endl; cout << "----------------------------------------------------- " << endl; cout << "Is a user logged in: " << other.isLogged << endl; cout << "----------------------------------------------------- " << endl; return cout; } void Store::updateManager() { if (!isLogged) { return; } this->myAccounts.update(this->myProfile); }
true
b752b79c80414a8708efe6e38e74d0bfe068495b
C++
kumbralyov/pservice
/add_forms/add_tickets_form.cpp
UTF-8
3,462
2.625
3
[]
no_license
#include "add_tickets_form.h" #include <QRegExpValidator> add_tickets_form::add_tickets_form(QWidget *parent) : QMainWindow(parent) { form_show(); } add_tickets_form::~add_tickets_form() { db.close(); } int add_tickets_form::form_show() { QGridLayout *gl = new QGridLayout; lb_series = new QLabel("Серия"); gl->addWidget(lb_series, 0, 0, 1, 1); le_series = new QLineEdit; le_series->setValidator(new QRegExpValidator(QRegExp("[А-Я,а-я,A-Z,a-z]{1,5}"))); gl->addWidget(le_series, 0, 1, 1, 1); le_series->setFocus(); lb_numbers = new QLabel("Номера"); gl->addWidget(lb_numbers, 1, 0, 1, 1); gl->addWidget(new QLabel("с"), 2, 0, 1, 1); le_from = new QLineEdit; le_from->setValidator(new QRegExpValidator(QRegExp("[0-9]{1,6}"))); gl->addWidget(le_from, 2, 1, 1, 1); gl->addWidget(new QLabel("по"), 3, 0, 1, 1); le_to = new QLineEdit; le_to->setValidator(new QRegExpValidator(QRegExp("[0-9]{1,6}"))); gl->addWidget(le_to, 3, 1, 1, 1); QPushButton *pb_add = new QPushButton("Добавить"); gl->addWidget(pb_add, 4, 1, 1, 1); pb_add->setShortcut(QKeySequence(Qt::Key_Return)); pb_add->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed, QSizePolicy::ToolButton)); connect(pb_add, SIGNAL(clicked()), this, SLOT(add_tickets())); QLabel *lb_space = new QLabel; gl->addWidget(lb_space, 5, 0, 1, 1); QWidget *wgt = new QWidget (); wgt->setLayout(gl); this->setCentralWidget(wgt); this->minimumHeight(); this->setWindowTitle("Добавление билетов"); return 0; } int add_tickets_form::add_tickets() { // проверка полей QString errors; errors = ""; if (le_series->text() == "") errors = errors + "Не введена серия\n"; if (le_from->text() == "") errors = errors + "Не введены номера билетов (поле \"с\"\n"; if (le_to->text() == "") errors = errors + "Не введены номера билетов (поле \"по\"\n"; if (le_to->text().toInt() < le_from->text().toInt()) errors = errors + "Неверный диапозон номеров билетов\n"; if (errors != "") { QMessageBox::critical(this, "Ошибка!", errors, QMessageBox::Ok); return 1; } QString strsql; QSqlQuery *quer = new QSqlQuery(db); // запись информации о выданных билетах strsql.clear(); QString series = ""; series = le_series->text().toUpper(); int from = 0; int to = 0; from = le_from->text().toInt(); to = le_to->text().toInt(); strsql = "insert into tickets(tickets_series, tickets_number, status, id_branch) " "values('%1', '%2', '0', '0')"; strsql = strsql.arg(series) .arg(le_from->text()); for (int i = 0; i < to-from; i++) { strsql = strsql + ",('" + series + "', '" + QString::number(from+1+i) + "', '0', '0')"; } qDebug() << __FILE__ << __LINE__ << strsql; quer->exec(strsql); if (quer->isActive()) { statusBar()->showMessage("Запись успешно добавлена"); } else { statusBar()->showMessage("Ошибка при добавлении записи"); qDebug() << __FILE__ << __LINE__ << quer->lastError().text(); } return 0; }
true
e40477527f168f4478fa16df696efa673af72d9b
C++
triicst/Reinforcement-Learning
/Node.h
UTF-8
969
2.671875
3
[]
no_license
// // Node.h // CS440-HW4 // // Created by Wenzhao Xu on 12/9/12. // Copyright (c) 2012 Xu Wenzhao. All rights reserved. // #ifndef __CS440_HW4__Node__ #define __CS440_HW4__Node__ #include <iostream> #include <vector> using namespace std; class node { public: node * child[6]; //children node pointer: 0=1,2,3,4=5 float expect_U; //the expected utility of current state float R; float expect_U_next; //the expect utility of next stage; int xi,yj; node(int i0, int j0); float Q[4]; //the Q function 0: up 1: right, 2: down; 3: left float Qfinal; int NAction[4]; //the Ne function 0 int visittime; int optimalpolicy_Q; //the optimal policy based on Q value int optimalpolicy_U; //the optimal policy based on U value vector<float> HistoryU; //the U value convergence history }; #endif /* defined(__CS440_HW4__Node__) */
true
9a1400809258f281198c7e92d10a45d89114c8d0
C++
ShihabShafkat/c-
/prims.cpp
UTF-8
1,388
3.21875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; struct nodes{ int number; int weight = INT_MAX; int parent = -1; bool operator < (const nodes &a)const{ return weight > a.weight; } }; int connection[100][100]; int main(){ int vertex, edge, cost = 0, x, y, z; cout<<"Vertex: "; cin>>vertex; cout<<"Edge: "; cin>>edge; priority_queue <nodes> pq; nodes prims[100]; for(int i = 0; i < edge; i++){ cout<<"Enter source, destination & cost: "; cin>>x>>y>>z; connection[x][y] = z; } prims[1].number = 0; prims[1].weight = 0; prims[1].parent = 0; for(int i =1; i < vertex; i++){ prims[i].number = i; pq.push(prims[i]); } while(!pq.empty()){ nodes u = pq.top(); pq.pop(); for(int v =1; v < vertex; v++){ if(connection[u.number][v] != 0){ if(connection[u.number][v] < prims[v].weight){ prims[v].parent = u.number; prims[v].weight = connection[u.number][v]; } } } } cout<<endl; for(int i = 2; i < vertex; i++){ cout<<prims[i].number<<" "<<prims[i].parent<<" "<<prims[i].weight<<endl; cost += prims[i].weight; } cout<<"Total cost: "<<cost; return 0; }
true
0aa60f466614a43760ba72d4a30918fab279c97f
C++
ruitaocc/RcEngine
/RcEngine/RcEngine/Graphics/RenderQueue.h
UTF-8
3,047
2.859375
3
[]
no_license
#ifndef RenderQueue_h__ #define RenderQueue_h__ #include <Core/Prerequisites.h> namespace RcEngine { struct _ApiExport RenderQueueItem { Renderable* Renderable; float SortKey; RenderQueueItem() {} RenderQueueItem(class Renderable* rd, float key) : Renderable(rd), SortKey(key) { } }; typedef std::vector<RenderQueueItem> RenderBucket; class _ApiExport RenderQueue { public: enum Bucket { /** * A special mode used for rendering really far away, flat objects - * e.g. skies. In this mode, the depth is set to infinity so * spatials in this bucket will appear behind everything, the downside * to this bucket is that 3D objects will not be rendered correctly * due to lack of depth testing. */ BucketBackground = 1UL << 0, /** * The renderer will try to find the optimal order for rendering all * objects using this mode. * You should use this mode for most normal objects, except transparent * ones, as it could give a nice performance boost to your application. */ BucketOpaque = 1UL << 1, /** * This is the mode you should use for object with * transparency in them. It will ensure the objects furthest away are * rendered first. That ensures when another transparent object is drawn on * top of previously drawn objects, you can see those (and the object drawn * using Opaque) through the transparent parts of the newly drawn * object. */ BucketTransparent = 1UL << 2, /** * A special mode used for rendering transparent objects that * should not be effected by {@link SceneProcessor}. * Generally this would contain translucent objects, and * also objects that do not write to the depth buffer such as * particle emitters. */ BucketTranslucent = 1UL << 3, /** * This is a special mode, for drawing 2D object * without perspective (such as GUI or HUD parts). * The spatial's world coordinate system has the range * of [0, 0, -1] to [Width, Height, 1] where Width/Height is * the resolution of the screen rendered to. Any spatials * outside of that range are culled. */ BucketOverlay = 1UL << 4, /** * All bucket */ BucketAll = BucketBackground | BucketOpaque | BucketTransparent | BucketTranslucent | BucketOverlay }; public: RenderQueue(); ~RenderQueue(); void AddRenderBucket(Bucket bucket); const RenderBucket& GetRenderBucket(Bucket bucket, bool sort = true); const std::map<Bucket, RenderBucket*>& GetAllRenderBuckets(bool sort = true); void AddToQueue(RenderQueueItem item, Bucket bucket); void ClearAllQueue(); void ClearQueues(uint32_t bucketFlags); void SwapRenderBucket(RenderBucket& bucket, Bucket type); public: std::map<Bucket, RenderBucket*> mRenderBuckets; }; } #endif // RenderQueue_h__
true
ba453e81791a14ab628332c16a8e012421944079
C++
wakeup5/Learning-Lesson
/04-10 Lesson - 1 게임 종합/NumberPuzzle.h
UTF-8
567
2.703125
3
[]
no_license
#pragma once #include "Gamble.h" enum NP_GAME_INPUT_ARROW { NP_GAME_INPUT_ARROW_NONE, NP_GAME_INPUT_ARROW_UP, NP_GAME_INPUT_ARROW_DOWN, NP_GAME_INPUT_ARROW_LEFT, NP_GAME_INPUT_ARROW_RIGHT }; class NumberPuzzle : public Gamble { private: int _board[5][5]; int _x, _y; NP_GAME_INPUT_ARROW getArrow(); void createBoardAndSuffle(); void print(); void findZero(); void positionChange(int, int); void moveUp(); void moveDown(); void moveLeft(); void moveRight(); public: NumberPuzzle(); ~NumberPuzzle(); void startGame(); };
true
645a8b30df849d87b0a9f5eca2aad7cf50761741
C++
wrapdavid/Dungeon_Crawler
/engine/core/inc/timer.h
UTF-8
605
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*! @file timer.h @brief Functionality for timers in the game engine. @detail */ #pragma once //-------------------------------------------- // Includes //-------------------------------------------- #include "gumshoe_typedefs.h" namespace Gumshoe { //-------------------------------------------- // Timer class definition //-------------------------------------------- class Timer { public: Timer(); ~Timer(); bool Init(); void Update(); float GetTime(); private: INT64 m_frequency; float m_ticksPerMs; INT64 m_startTime; float m_frameTime; }; } // end of namespace Gumshoe
true
d2995b4f5a976126271b9a57c3d2bae50617e0e7
C++
aro-ai-robots/FullyHeadlessNick
/MouthControll/MouthControll.ino
UTF-8
5,051
2.59375
3
[]
no_license
//Summer 2017 intern ship by Sierra Dacey and Molly Nehring //Orangutans are powered separate from the pi with a battery //Use the power/ground wires with silver tape //Orangutans must be powered to be programmed //**THE MOUTH OPEN IS NOT CURRENTLY WORKING (MOTOR IS STUCK)** #include <Wire.h> #include <OrangutanLEDs.h> //#include <OrangutanAnalog.h> #include <OrangutanMotors.h> #include <Servo.h> //OrangutanAnalog analog; OrangutanLEDs leds; OrangutanMotors motors; //Turning Servo Servo myservo; //Variables used in controlling motor speeds //30 lowest speed from dead stop int mouthOpen;// motor M2 int expressionMotor;// motor M1 int motorSmooth = 5;//milliseconds delay between succesive //motor speeds on the way to final speed //Standard Motor Speeds int forwardCruz = 80; int backCruz = -80; //Variables used to manage I2C communication; int lspd = 0, ldir = 0, rspd = 0, rdir = 0; byte I2Cbuffer[8]; //Used to hold received information volatile boolean recFlag = false; //True is new command int openChange = 225; int closeChange = -225; int happyChange = 225; int sadChange = -225; float openInterval; float expressionInterval; int openTop; int openBottom; int expressionTop; int expressionBottom; int openInput = 5; int expressionInput = 5; void setup() { // put your setup code here, to run once: //myservo.attach(9); pinMode(7, INPUT); Wire.begin(9); // join i2c bus with address #9 Wire.onReceive(receiveEvent); // register event // Wire.onRequest(requestEvent); // register event calibrateMouth(); } int encodeOpen; int encodeExpression; int negativeChange = 225; int positiveChange = -225; double openSetAs; double expressionSetAs; void loop() { if(recFlag){ recFlag=false; int openInput = I2Cbuffer[2]; int expressionInput = I2Cbuffer[4]; //lspd = I2Cbuffer[2]; ldir = I2Cbuffer[3]; //rspd = I2Cbuffer[4]; rdir = I2Cbuffer[5]; delay(500); // int openTop = 600; // int openBottom = 465; openInterval = (openTop - openBottom)/10.0; //different intervals the mouth can open at openSetAs = (openInput * openInterval) + openBottom; // int expressionTop = 780; // int expressionBottom = 220; expressionInterval = (expressionTop - expressionBottom)/10.0; //different intervals the mouth can smile/frown at expressionSetAs = (expressionInput * expressionInterval) + expressionBottom; } encodeOpen = analogRead(1); if ( abs(encodeOpen - openSetAs)< 7){ chgOpenSpeed(0); // leds.red(HIGH); // delay(50); // leds.red(LOW); // delay(50); } else if (encodeOpen > openSetAs) { //make mouth open more chgOpenSpeed(positiveChange); } else if (encodeOpen < openSetAs){ //make mouth close more chgOpenSpeed(negativeChange); } encodeExpression = analogRead(2); if ( abs(encodeExpression - expressionSetAs)<7){ chgExpressionSpeed(0); leds.red(HIGH); delay(50); leds.red(LOW); delay(50); // if ( abs(encodeOpen - openSetAs)<25){ // // chgOpenSpeed(0); // leds.red(HIGH); // delay(50); // leds.red(LOW); // delay(50); // } } else if (encodeExpression > expressionSetAs) { //make mouth smile more chgExpressionSpeed(positiveChange); } else if (encodeExpression < expressionSetAs){ //make mouth frown more chgExpressionSpeed(negativeChange); } //Check Sensors//*/ } void chgOpenSpeed(int newSp){ if(newSp == mouthOpen)return; double diff = newSp - mouthOpen; double delta = diff/11; for(double s = mouthOpen; abs(s-newSp)<=abs(delta); s+=delta){ motors.setM2Speed(s); delay(motorSmooth); } mouthOpen = newSp; motors.setM2Speed(newSp); } void calibrateMouth(){ //set values for open closed chgOpenSpeed(closeChange); delay(500); openBottom = (analogRead(1) + 5); chgOpenSpeed(openChange); delay(500); openTop = (analogRead(1) - 5); openInterval = (openTop - openBottom)/10.0; openSetAs = (openInput * openInterval) + openBottom; chgExpressionSpeed(happyChange); delay(1000); expressionTop = (analogRead(5) - 5); chgExpressionSpeed(sadChange); delay(1000); expressionBottom = (analogRead(2) + 5); expressionInterval = (expressionTop - expressionBottom)/10.0; expressionSetAs = (expressionInput * expressionInterval) + expressionBottom; } void chgExpressionSpeed(int newSp){ if(newSp == expressionMotor)return; double diff = newSp - expressionMotor; double delta = diff/11; for(double s=expressionMotor; abs(s-newSp)<=abs(delta); s+=delta){ motors.setM1Speed(s); delay(motorSmooth); } expressionMotor = newSp; motors.setM1Speed(newSp); }//*/ // function that executes whenever data is received from master // this function is registered as an event, see setup() void receiveEvent(int howMany) { Wire.readBytes(I2Cbuffer,howMany); recFlag = true; } void requestEvent() { Wire.write("hello "); // respond with message of 6 bytes // as expected by master }
true
f00fa3d518fa1885fb2499072e53f7f8605aced8
C++
VitaliyOschepkov/Labs_PSTU2
/8. Программаб управляемая событиями/Lab_08/Student.cpp
WINDOWS-1251
894
3.734375
4
[]
no_license
#include "Student.h" Student::Student() :Person() { rating = 0; } Student::Student(string n, int a, float r) : Person(n, a) { rating = r; } Student::Student(const Student& s) { name = s.name; age = s.age; rating = s.rating; } Student::~Student() { } float Student::getRating() { return rating; } void Student::setRating(float r) { rating = r; } Student& Student::operator=(const Student& s) { if (&s == this) return *this; name = s.name; age = s.age; rating = s.rating; return *this; } void Student::Show() { cout << "\n: " << name; cout << "\n: " << age; cout << "\n: " << rating << "\n"; } void Student::Input() { cout << "\n : "; cin >> name; cout << "\n : "; cin >> age; cout << "\n : "; cin >> rating; }
true
5270bfbe122fcb1569eb8fa444b44f4f78bcd527
C++
AparnaChinya/100DaysOfCode
/42. Trapping Rain Water.cpp
UTF-8
989
3.625
4
[]
no_license
/* Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. From <https://leetcode.com/problems/trapping-rain-water/> */ class Solution { public: int trap(vector<int>& height) { int number = height.size(); if(!number) return 0; int *Left = new int[number]; int *Right = new int[number]; Left[0] = height[0]; Right[number-1] = height[number-1]; for (int i = 1; i<number; i++) { Left[i] = max(Left[i - 1], height[i]); } for (int j = number - 2; j >= 0; j--) { Right[j] = max(Right[j + 1], height[j]); } int sum = 0; for (int k = 1; k<number; k++) { sum += min(Left[k], Right[k]) - height[k]; } return (sum); } };
true
ab51397530f850f78be823ae60b2aea46fe6a422
C++
fauzanbakri/Arduino_Folder
/sdtest/sdtest.ino
UTF-8
7,314
3.046875
3
[]
no_license
#include <SPI.h> #include <SD.h> const int chipSelect = D8; // use D0 for Wemos D1 Mini File root; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); Serial.print("\r\nWaiting for SD card to initialise..."); if (!SD.begin(chipSelect)) { // CS is D8 in this example Serial.println("Initialising failed!"); return; } Serial.println("Initialisation completed"); } void loop() { // SD.open(filename,OPEN_READ|OPEN_WRITE) SD.open(filename) defaults to OPEN_READ root = SD.open("/"); root.rewindDirectory(); printDirectory(root, 0); //Display the card contents root.close(); Serial.println("\r\nOPEN FILE example completed"); Serial.flush(); Serial.begin(9600); while(!Serial.available()); //------------------------------------------------------------------------------- // SD.exists(filename) returns TRUE is found the name of the file to test for existence, which can include directories (delimited by forward-slashes, /) Serial.println("Look for a file called 'testfile.txt', if found remove it"); if (SD.exists("testdata.txt")) { Serial.println("File testfile.txt found"); if (SD.remove("testdata.txt")) Serial.println("File successfully deleted"); else Serial.println("Error - file not deleted"); } if (!SD.exists("testdata.txt")); { Serial.println("Following confirmation checks, 'testfile.txt' now deleted\r\n"); } root = SD.open("/"); root.rewindDirectory(); printDirectory(root, 0); //Display the card contents root.close(); Serial.flush(); Serial.begin(9600); while(!Serial.available()); //------------------------------------------------------------------------------- // SD.open(filename,OPEN_READ|OPEN_WRITE) SD.open(filename) defaults to OPEN_READ Serial.println("Open a new file called 'testfile.txt' and write 1 to 5 to it"); File testfile = SD.open("testdata.txt", FILE_WRITE); // FILE_WRITE opens file for writing and moves to the end of the file, returns 0 if not available if (testfile) { for (int entry = 0; entry <= 5; entry = entry + 1) { testfile.print(entry); Serial.print(entry); } } Serial.println("\r\nCompleted writing data 1 to 5\r\n"); testfile.close(); Serial.flush(); Serial.begin(9600); while(!Serial.available()); //------------------------------------------------------------------------------- Serial.println("Open a file called 'testfile.txt' and read the data from it"); testfile = SD.open("testdata.txt", FILE_READ); // FILE_WRITE opens file for writing and moves to the end of the file while (testfile.available()) { Serial.write(testfile.read()); } Serial.println("\r\nCompleted reading data from file\r\n"); // close the file: testfile.close(); Serial.flush(); Serial.begin(9600); while(!Serial.available()); //------------------------------------------------------------------------------- Serial.println("Open a file called 'testfile.txt' and append 5 downto 1 to it"); testfile = SD.open("testdata.txt", FILE_WRITE); // FILE_WRITE opens file for writing and moves to the end of the file for (int entry = 5; entry >= 0; entry = entry - 1) { testfile.print(entry); Serial.print(entry); } Serial.println("\r\nCompleted writing data 5 to 1\r\n"); testfile.close(); Serial.flush(); Serial.begin(9600); while(!Serial.available()); //------------------------------------------------------------------------------- Serial.println("Open a file called 'testfile.txt' and read it"); testfile = SD.open("testdata.txt", FILE_READ); // FILE_WRITE opens file for writing and moves to the end of the file while (testfile.available()) { Serial.write(testfile.read()); } Serial.println("\r\nCompleted reading from the file\r\n"); // close the file: testfile.close(); Serial.flush(); Serial.begin(9600); while(!Serial.available()); //012345543210 //------------------------------------------------------------------------------- Serial.println("\r\nOpen a file called 'testfile.txt' and move to position 8 in the file then print the data (should be 3)"); testfile = SD.open("testdata.txt", FILE_READ); // FILE_WRITE opens file for writing and moves to the end of the file Serial.print("Data at file location (8): "); testfile.seek(8); Serial.write(testfile.read()); //------------------------------------------------------------------------------- Serial.flush(); Serial.begin(9600); while(!Serial.available()); Serial.println("\r\nOpen a file called 'testfile.txt' and move to position 6 in the file then print the data (should be 5)"); Serial.print("Data at file location (6): "); testfile.seek(6); Serial.write(testfile.read()); //------------------------------------------------------------------------------- Serial.print("\r\nFile pointer is at file location: "); Serial.println(testfile.position()); Serial.print("\r\nData at current file location (should be 4): "); Serial.println(char(testfile.peek())); //------------------------------------------------------------------------------- // close the file: testfile.close(); //------------------------------------------------------------------------------- Serial.flush(); Serial.begin(9600); while(!Serial.available()); //------------------------------------------------------------------------------- Serial.println("\r\nOpen a file called 'testfile.txt' and write some data records"); testfile = SD.open("testdata.txt", FILE_WRITE); // FILE_WRITE opens file for writing and moves to the end of the file int hours = 10; int mins = 00; String names = "Mr Another"; testfile.print("\r\n"+String(hours)); testfile.print(":"); testfile.print(String(mins,2)); testfile.println(" "+names); Serial.print(hours); Serial.print(":"); Serial.print(mins); Serial.println(names); names = "Mr And Another"; testfile.print(String(hours+1)); testfile.print(":"); testfile.print(String(mins+1)); testfile.println(" "+names+"\r\n"); Serial.print(hours); Serial.print(":"); Serial.print(mins,2); Serial.print(names); Serial.println("\r\nCompleted writing data records to the file\r\n"); testfile.close(); Serial.flush(); Serial.begin(9600); while(!Serial.available()); // Now read file contents Serial.println("\r\nOpen a file called 'testfile.txt' and move to position 8 in the file then print the data (should be 4)"); testfile = SD.open("testdata.txt", FILE_READ); // FILE_WRITE opens file for writing and moves to the end of the file while (testfile.available()) { Serial.write(testfile.read()); } Serial.println("\r\nCompleted reading records from the file\r\n"); Serial.flush(); Serial.begin(9600); while(!Serial.available()); Serial.println("\r\nStarting again"); } void printDirectory(File dir, int numTabs) { int colcnt =0; while(true) { File entry = dir.openNextFile(); if (! entry) { // no more files break; } if (numTabs > 0) { for (uint8_t i=0; i<=numTabs; i++) { Serial.print('\t'); } } Serial.print(entry.name()); if (entry.isDirectory()) { Serial.println("/"); printDirectory(entry, numTabs+1); } else { // files have sizes, directories do not Serial.print("\t"); Serial.println(entry.size(), DEC); } entry.close(); } }
true
135374299f8b63d11a885ee91678e3f0081e2d94
C++
kwon-young/Millenium-Neural-Net
/src/Neural_Net.cpp
UTF-8
4,056
2.96875
3
[ "MIT" ]
permissive
#include "Neural_Net.hpp" #include <cmath> #include <iostream> using namespace Eigen; double Neural_Net_Functions::logistic(const double input) const { return 1.0 / (1.0 + exp(-input)); } double Neural_Net_Functions::logisticPrime(const double input) const { return logistic(input)*(1-logistic(input)); } void Neural_Net_Functions::vec_logistic( const Eigen::VectorXd &input, Eigen::VectorXd &output) const { for (unsigned int i=0; i < output.rows(); i++) { output[i] = logistic(input[i]); } } void Neural_Net_Functions::vec_logisticPrime( const Eigen::VectorXd &input, Eigen::VectorXd &output) const { for (unsigned int i=0; i < output.rows(); i++) { output[i] = logisticPrime(input[i]); } } double Neural_Net_Functions::cost( const Eigen::VectorXd &output, const Eigen::VectorXd &desired_output) const { VectorXd temp = desired_output.array() - output.array(); return 0.5*temp.squaredNorm(); } Eigen::VectorXd Neural_Net_Functions::costPrime( const Eigen::VectorXd &output, const Eigen::VectorXd &desired_output) const { return desired_output.array() - output.array(); } Neural_Net::Neural_Net( VectorXd &weight_sizes, Neural_Net_Functions *functions) : _layer_size(weight_sizes.size()), _weights(), _bias(), _activations(), _zs(), _errors(), _gradientSum(0.0), _functions(functions) { _activations.push_back(VectorXd::Constant(weight_sizes[0], 1.0)); for(unsigned int i = 1; i < _layer_size; i++) { _weights.push_back(MatrixXd::Random(weight_sizes[i], weight_sizes[i-1])); _bias.push_back(VectorXd::Random(weight_sizes[i])); _activations.push_back(VectorXd::Constant(weight_sizes[i], 0.0)); _zs.push_back(VectorXd::Constant(weight_sizes[i], 0.0)); _errors.push_back(VectorXd::Constant(weight_sizes[i], 0.0)); } } Neural_Net::~Neural_Net() { } void Neural_Net::feedForward() { for (unsigned int layer = 1; layer < _layer_size; layer++) { _zs[layer-1] = _weights[layer-1] * _activations[layer-1] + _bias[layer-1]; _functions->vec_logistic(_zs[layer-1], _activations[layer]); } } double Neural_Net::getCost(Eigen::VectorXd desired_output) const { return _functions->cost(_activations[_layer_size-1], desired_output); } void Neural_Net::computeError(Eigen::VectorXd desired_output) { VectorXd temp = _functions->costPrime( _activations[_layer_size-1], desired_output); _functions->vec_logisticPrime(_zs[_layer_size-2], _zs[_layer_size-2]); _errors[_layer_size-2] = temp.cwiseProduct(_zs[_layer_size-2]); for (unsigned int layer = _layer_size-2; layer > 0; layer--) { VectorXd temp = _weights[layer].transpose() * _errors[layer]; _functions->vec_logisticPrime(_zs[layer-1], _zs[layer-1]); _errors[layer-1] = temp.cwiseProduct(_zs[layer-1]); } } void Neural_Net::gradientSum() { //_gradientSum += _activations[ } void Neural_Net::backPropagation( Eigen::MatrixXd input, Eigen::MatrixXd desired_output) { for (unsigned int i=0; i < input.cols(); i++) { setInput(input.col(i)); feedForward(); computeError(desired_output.col(i)); } } void Neural_Net::print_layer(unsigned int layer) const { std::cout << "layer number " << layer << std::endl; if (layer == 0) { std::cout << "input layer" << std::endl; } else { if (layer == _layer_size-1) { std::cout << "output layer" << std::endl; } std::cout << "weights" << std::endl; std::cout << _weights[layer-1] << std::endl; std::cout << "bias" << std::endl; std::cout << _bias[layer-1] << std::endl; std::cout << "zs" << std::endl; std::cout << _zs[layer-1] << std::endl; std::cout << "errors" << std::endl; std::cout << _errors[layer-1] << std::endl; } std::cout << "activation" << std::endl; std::cout << _activations[layer] << std::endl; std::cout << std::endl; } void Neural_Net::print_neural_net() const { for (unsigned int layer=0; layer<_layer_size; layer++) { print_layer(layer); } }
true
8996f5d9b112e610d83bf8808e26b27e1ab82a49
C++
mlowerysimpson/AMOS
/gps_odometer.cpp
UTF-8
3,246
2.9375
3
[]
permissive
//gps_odometer.cpp -- program for parsing gps data from ship logs to determine total distance that boat has travelled //program takes as input a folder name and parses all of the "shiplog_*.txt" files in that folder to determine the total distance that the boat has travelled. //The total distance is tracked in a file called total_distance.bin that resides in the folder where this program is located and run from. //The total_distance.bin file also keeps track of which files have been parsed already, so that if the same file is parsed again, it won't count the same travel twice. #include <stdio.h> #include <dirent.h> #include <string.h> #include <fcntl.h> #include <stdlib.h> #include <io.h> #include <vector> #include <windows.h> using namespace std; vector <time_t> g_shipLogTimes; void ShowUsage() {//show format for using this program printf("gps_odometer <folder where ship's logs are stored>\); printf("or\n"); printf("gps_odometer <-h | -help>\n"); } FILE * GetTotalDistanceFile(char *rootFolder) { char szFilename[_MAX_PATH]; sprintf(szFilename,"%s\\total_distance.bin",rootFolder); FILE *totalDistFile = fopen(szFilename,"r+"); return totalDistFile; } bool FindTotalDistTraveled(FILE *totalDistFile, char *szShipLogFolder) {//find the total distance traveled //based on the contents of totalDistFile (if it exists) and any shiplog_*.txt files in the szShipLogFolder double dTotalDistance=0.0; if (totalDistFile) { if (fread(&dTotalDistance,1,sizeof(double),totalDistFile)!=sizeof(double)) { printf("Error reading total distance from total_distance.bin file.\n"); return false; } //read in times of files already parsed and included in the total_distance.bin file time_t shipLogTime; while (fread(&shipLogTime, 1, sizeof(time_t),totalDistFile)==sizeof(time_t)) { g_shipLogTimes.push_back(shipLogTime); } } DIR *dir; struct dirent *ent; if ((dir = opendir(szShipLogFolder)) != NULL) { /* look for shiplog_*.txt files within directory */ while ((ent = readdir (dir)) != NULL) { int nYr=0,nMonth=0,nDay=0,nHr=0,nMin=0,nSec=0; if (sscanf(ent->d_name,"shiplog_%d_%d_%d_%d_%d_%d.txt",&nYr,&nMonth,&nDay, &nHr,&nMin,&nSec)==6) { struct tm fileTime; fileTime.tm_year = nYr - 1900; fileTime.tm_mon = nMonth - 1; fileTime.tm_mday = nDay; fileTime.tm_hour = nHr; fileTime.tm_min = nMin; fileTime.tm_sec = nSec; time_t tt = mktime(&fileTime); if (!timeExists(//left off here... g_shipLogTimes.push_back(tt); double dDistTraveled = GetDistTraveled(ent->d_name); } } closedir (dir); } } } int main(int argc, const char * argv[]) { char currentFolder[_MAX_PATH]; ::GetCurrentDirectory(_MAX_PATH,currentFolder); int (argc!=2) { ShowUsage(); return -1; } else if (isHelpText(argv[1])) { ShowUsage(); return -2; } else { FILE *totalDistFile = GetTotalDistanceFile(currentFolder); char *shipLogFolder = argv[1]; if (!FindTotalDistTraveled(totalDistFile, shipLogFolder)) { if (totalDistFile) { fclose(totalDistFile); } return -3; } if (totalDistFile) { fclose(totalDistFile); } } return 0; }
true
bf57129e447d5fe5e273dd8f771847fa1ddd2633
C++
mark-smits/CSD2
/csd2c/Aansturing/encoder.cpp
UTF-8
955
2.984375
3
[]
no_license
#include "encoder.h" #include <stdio.h> #include <wiringPi.h> #include <iostream> Encoder::Encoder(int lPin, int rPin) : lPin(lPin), rPin(rPin) { this->minVal = 0; this->maxVal = 10; this->val = 0; this->lPinLastState = 0; wiringPiSetup(); pinMode(lPin, INPUT); pinMode(rPin, INPUT); } Encoder::~Encoder() { } int Encoder::readPin(int pin) { return digitalRead(pin); } void Encoder::setMinVal(int minInput) { if (minInput > maxVal) { minInput = maxVal; } minVal = minInput; } void Encoder::setMaxVal(int maxInput) { if (maxInput < minVal) { maxInput = minVal; } maxVal = maxInput; } void Encoder::clip() { if (val > maxVal) { val = maxVal; } else if (val < minVal) { val = minVal; } } void Encoder::tick() { if (readPin(lPin) == 1 && readPin(lPin) != lPinLastState) { if (readPin(rPin) == 1) { val++; } else { val--; } } clip(); lPinLastState = readPin(lPin); } int Encoder::getVal() { return val; }
true
eeb975a0dd8b45d09868df66709c333b951d1e64
C++
Veinard29/D31
/VKSubject.cpp
UTF-8
552
2.796875
3
[]
no_license
#include "VKSubject.h" VKSubject::VKSubject() { SubjectName = ""; } VKSubject::VKSubject(const string& _SubjectName) { SubjectName = _SubjectName; } string VKSubject::GetClassName() { return "VKSubject"; } string VKSubject::Print() { return GetSubjectName(); } bool VKSubject::operator==(const VKSubject& object) { VKSubject s = object; return s.GetSubjectName() == GetSubjectName(); } string VKSubject::GetSubjectName() { return SubjectName; } void VKSubject::SetSubjectName(const string& _SubjectName) { SubjectName = _SubjectName; }
true
06d632c116f37af105f4bc3e946c55ec60aef634
C++
Graphics-Physics-Libraries/SimpleRenderEngine-1
/src/Core/HardwareBuffer/VertexElement.cpp
UTF-8
1,825
2.671875
3
[]
no_license
#include "VertexElement.h" namespace SRE { VertexElement::VertexElement(unsigned short source, size_t offset, Vertex_Element_Type type, Vertex_Element_Semantic semantic, unsigned short index) : _source(source), _offset(offset), _type(type), _semantic(semantic), _index(index) { } size_t VertexElement::getSize(void) const { switch (_type) { case VET_FLOAT1: return sizeof(float); case VET_FLOAT2: return sizeof(float) * 2; case VET_FLOAT3: return sizeof(float) * 3; case VET_FLOAT4: return sizeof(float) * 4; case VET_SHORT1: return sizeof(short); case VET_SHORT2: return sizeof(short) * 2; case VET_SHORT3: return sizeof(short) * 3; case VET_SHORT4: return sizeof(short) * 4; case VET_UBYTE4: return sizeof(unsigned char) * 4; } return 0; } size_t VertexElement::getTypeSize(Vertex_Element_Type type) const { switch (type) { case VET_FLOAT1: return sizeof(float); case VET_FLOAT2: return sizeof(float) * 2; case VET_FLOAT3: return sizeof(float) * 3; case VET_FLOAT4: return sizeof(float) * 4; case VET_SHORT1: return sizeof(short); case VET_SHORT2: return sizeof(short) * 2; case VET_SHORT3: return sizeof(short) * 3; case VET_SHORT4: return sizeof(short) * 4; case VET_UBYTE4: return sizeof(unsigned char) * 4; } return 0; } unsigned short VertexElement::getTypeCount(Vertex_Element_Type type) { switch (type) { case VET_COLOUR: //case VET_COLOUR_ABGR: //case VET_COLOUR_ARGB: return 1; case VET_FLOAT1: return 1; case VET_FLOAT2: return 2; case VET_FLOAT3: return 3; case VET_FLOAT4: return 4; case VET_SHORT1: return 1; case VET_SHORT2: return 2; case VET_SHORT3: return 3; case VET_SHORT4: return 4; case VET_UBYTE4: return 4; } } }
true
0b80a6703fe23edf31e89480a3dec751a2c81fdd
C++
GuilhermePontoAut/PCC103
/PCC103_Intervalos_de_Confiança_3.cpp
ISO-8859-1
5,110
3.46875
3
[]
no_license
// PCC103 - METODOLOGIA // Nome do exerccio: Intervalos de Confiana - exerccio 3 # include <iostream> # include <vector> # include <ctime> # include <math.h> using namespace std; void VetorAleatorio (vector <double> &x, int tam); void MostraVetor (vector <double> vetor); double Particao (vector<double> &data, int ini, int fim); double QuickSort(vector<double> &data, int ini, int fim); double mean(const std::vector<double> &data); double Busca (vector <double> vetor, int k); double hipergeometrica( double a, double b, double c, double x); double t_distribution_cdf(double x, int v); double t_distribution_confidence_interval(const std::vector<double>& data, double alpha); int main () { setlocale(LC_ALL, "Portuguese"); // Recurso utilizado para conseguir imprimir acentuao e caracteres especiais srand(time(NULL)); // Utiliza o relgio interno do computador para escolher uma semente para gerar os nmeros aleatrios. vector <double> vetor; int n =25; // Tamanho do vector int p; double Intervalo; double Media; VetorAleatorio(vetor, n); // Chama funo para gera vetor aleatrio cout << "Digite o valor da probabilidade(%): "; cin >> p; cout << endl; cout << "Vetor com nmeros escolhidos aleatoriamente: "<< endl; MostraVetor(vetor); cout << endl; cout << "Vetor ordenado utilizando QuickSort: "<< endl; QuickSort(vetor, 0, vetor.size()-1); MostraVetor(vetor); cout << endl; Media = mean(vetor); Intervalo = t_distribution_confidence_interval(vetor, p); if (Intervalo == -1) { cout << "No existe intervalo de confiana em torno da mdia "<< Media << " para a probabilidade " << p << "%." << endl; } else { cout << "O intervalo de confiana em torno da mdia " << Media << " para a probabilidade " << p << "% : " << "(" << (Media - Intervalo) << ", " << (Media + Intervalo) << ")" << endl; } } double t_distribution_confidence_interval(const std::vector<double>& data, double alpha){ double Media = mean(data); int n = data.size(); vector<double> VetorAux(n, 0); int Pos = Busca(VetorAux, alpha); for (int i = 0; i < n; i++) { VetorAux[i] = round(100 * t_distribution_cdf(data[i], n - 1)); } if (Pos == -1) { return -1; } else { return data[Pos]; } } void VetorAleatorio (vector <double> &x, int tam) { for (int i=0; i<tam; i++){ x.push_back(rand() %30); } } void MostraVetor (vector <double> vetor) { cout << "{ "; for (int i=0; i<vetor.size(); i++){ cout << vetor[i]; if (i < vetor.size()-1){ cout << ", "; } } cout << " }" << endl; } double Particao (vector<double> &data, int ini, int fim){ int pivot = data[fim]; // Define pivot como sendo o ltimo elemento do vetor int i = ini-1; for (int j = ini; j <= fim - 1; j++){ if (data[j] <= pivot){ // Compara cada elemento do vetor com o pivot i++; swap(data[i], data[j]); } } swap(data[i + 1], data[fim]); return (i + 1); } double QuickSort(vector<double> &data, int ini, int fim){ if (ini < fim){ int posicao = Particao(data, ini, fim); QuickSort(data, ini, posicao - 1); QuickSort(data, posicao + 1, fim); } } double mean(const std::vector<double> &data){ double media = 0; for (int i =0; i<data.size(); i++){ media = media + data[i]; } return media/data.size(); } double Busca (vector <double> vetor, int k){ int x; int l = 0; // Left: Incio da busca do vetor int r = vetor.size()-1; // Right: Fim da busca do vetor while (r > l) { x = (l+r)/2; if (k==vetor[x]){ return x; } else if (k>vetor[x]){ l = x+1; } else if (k<vetor[x]) { r=x-1; } if (r<=l && l!= 25){ return -1; } } } double hipergeometrica( double a, double b, double c, double x ){ const double TOLERANCE = 1.0e-10; double term = a * b * x / c; double value = 1.0 + term; int n = 1; while ( abs( term ) > TOLERANCE ){ a++, b++, c++, n++; term *= a * b * x / c / n; value += term; } return value; } double t_distribution_cdf(double x, int v){ double aux1, aux2, aux3, aux4, aux5, aux6; aux1 = hipergeometrica(1/2, (v+1)/2, 3/2, -(pow(x,2)/v)); aux2 = (sqrt(v*M_PI))*(tgamma(v/2)); aux3 = aux1/aux2; aux4 = x*tgamma((v+1)/2); aux5 = aux3*aux4; aux6 = 1/2 + aux5; return aux6; }
true
c1a07b2e83f4038d2353c1df4e1dfbb346c41ce9
C++
JerryTheUser/Leetcode
/Maximum_Binary_Tree.cpp
UTF-8
1,340
3.78125
4
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using std::vector; using std::cout; using std::max_element; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { return solve(nums,0,nums.size()-1); } TreeNode* solve(vector<int>& nums,int begin,int end){ if(begin > end)return nullptr; else{ int index = begin; int max = nums[index]; int i; for(i=begin ; i<=end ; ++i){ if(nums[i] > max){ index = i; max = nums[index]; } } TreeNode *head = new TreeNode(max); head -> left = solve(nums,begin,index-1); head -> right = solve(nums,index+1,end); return head; } } }; void print_tree(TreeNode *head){ if(head == nullptr)return; else{ cout << head->val << '\n'; print_tree(head->left); print_tree(head->right); } } int main(){ vector<int> input = { 5,6,7,3,2,4,9,11,23,16,13,28,1,2}; Solution sol; TreeNode *Ta = sol.constructMaximumBinaryTree(input); print_tree(Ta); return 0; }
true
9f504fed2582a627ee2e14f22e7d186a99689d88
C++
chriniko13/simple_cpp_exercise
/behaviour_test.cpp
UTF-8
8,852
3.0625
3
[]
no_license
// // Created by nchristidis on 20/1/21. // #include "behaviour_test.h" #include <iostream> #include <thread> #include <unordered_map> #include <random> //#include <climits> // Note: std::uniform_int_distribution<long> distribution(LONG_MIN,LONG_MAX); #include "queue.cpp" #include "publisher.cpp" #include "subscriber.cpp" #include "flowable.cpp" // ######################################### test 1 #################################################################### /* * The purpose of this test is to just test the behaviour of the queue (single threaded) */ template<typename t> void addToQueue(queue<t *> *q, t *rec) { q->offer(rec); } void test1() { std::cout << "\n\nTEST 1" << std::endl; queue<int> *q = new queue<int>; int i = 1; int i2 = 2; std::cout << "(q1) size: " << q->size() << std::endl; q->offer(std::ref(i)); std::cout << "(q1) size: " << q->size() << std::endl; q->offer(i2); std::cout << "(q1) size: " << q->size() << std::endl; while (q->size() != 0) { int &r = q->poll(); std::cout << "r: " << r << std::endl; } delete q; std::cout << "\n\n"; queue<int *> *q2 = new queue<int *>; int *i3 = new int(3); q2->offer(i3); int *i4 = new int(4); addToQueue(q2, i4); std::cout << "(q2)size: " << q2->size() << std::endl; std::cout << "(q2)poll: " << *(q2->poll()) << std::endl; std::cout << "(q2)poll: " << *(q2->poll()) << std::endl; delete i3; delete i4; delete q2; std::cout << "\n\n" << std::endl; } // #################################### test 2 ######################################################################### /* * The purpose of this test, is to test the behaviour of the queue under multiple threads (multi-threaded). */ struct sensor_temp { int sensorId; double temp; }; long random_long(long &&min, long &&max) { std::default_random_engine generator; std::uniform_int_distribution<long> distribution(min, max); long result = distribution(generator); return result; } std::mutex counter_mutex; int thread_operations = 0; void addTemp(queue<sensor_temp *> *q, int batch) { using namespace std; std::thread::id this_id = std::this_thread::get_id(); // # START counter_mutex.lock(); thread_operations += 1; cout << "current thread id under work: " << this_id << endl; counter_mutex.unlock(); // # END for (int i = 0; i < batch; i++) { //if (i % 100 == 0) cout << "thread with id: " << this_id << " working..." << endl; sensor_temp *st = new sensor_temp; st->sensorId = i + 1; st->temp = 2.0 + i; q->offer(st); long time_to_sleep = random_long(75, 200); std::this_thread::sleep_for(std::chrono::milliseconds(time_to_sleep)); } } void test2() { std::cout << "\n\nTEST 2" << std::endl; int no_of_workers = 400; //int no_of_workers = 40; int records_to_save = 20000; int worker_batch = records_to_save / no_of_workers; if (worker_batch % 2 != 0) exit(-1); queue<sensor_temp *> *q = new queue<sensor_temp *>; std::vector<std::thread> threads; for (int i = 0; i < no_of_workers; i++) { threads.push_back( std::thread(addTemp, q, worker_batch) ); } for (auto &th : threads) { th.join(); } std::cout << "q size: " << q->size() << std::endl; std::cout << "total thread operations: " << thread_operations << std::endl; std::cout << "worker batch size: " << worker_batch << std::endl; std::cout << "\n\n" << std::endl; } // ######################################### test 3 #################################################################### /* * The purpose of this test, is to test the behaviour of the publisher class. */ void print_just_an_int(int *input) { std::cout << "(version) just an int: " << *input << std::endl; } void print_just_an_int2(int *input) { std::cout << "(version) just an int2: " << *input << std::endl; } void test3() { std::cout << "\n\nTEST 3" << std::endl; void (*my_func)(int *); publisher<int> *p = new publisher<int>(1); std::cout << "success operations: " << p->get_successful_operations() << std::endl; std::cout << "failure operations: " << p->get_failed_operations() << std::endl; // Note: add subscribers first. my_func = print_just_an_int; p->add_subscriber(my_func); my_func = print_just_an_int2; p->add_subscriber(my_func); // Note: populate queue. p->offer(3); p->offer(4); p->offer(5); p->offer(6); // Note: do notification. p->do_action(); std::cout << "success operations: " << p->get_successful_operations() << std::endl; delete p; std::cout << "\n\n" << std::endl; } // ######################################### test 4 #################################################################### /* * The purpose of this test, is to test the behaviour of the subscriber class. */ struct foo_bar { int x; explicit foo_bar(int x) { this->x = x; } }; void print_foo_bar(foo_bar *f) { std::cout << "[subscribe notify via seek] f.x == " << f->x << std::endl; } void test4() { std::cout << "\n\nTEST 4" << std::endl; void (*my_func)(foo_bar *); my_func = print_foo_bar; subscriber<foo_bar> *s = new subscriber<foo_bar>(my_func, 1); // Note: populate queue. s->offer(foo_bar(1)); s->offer(foo_bar(2)); s->offer(foo_bar(3)); // Note: do notification. s->do_action(); s->do_action(); s->do_action(); delete s; std::cout << "\n\n" << std::endl; } // ######################################### test 5 #################################################################### struct unprocessed_record { int x; }; struct processed_record { int x; }; std::vector<unprocessed_record *> unprocessed_records; std::vector<unprocessed_record *>::iterator source_iterator; void init_source() { // init vector for (int i = 0; i < 100; i++) { unprocessed_record *r = new unprocessed_record; r->x = i + 500; unprocessed_records.push_back(r); } // init iterator source_iterator = unprocessed_records.begin(); } // ---source--- unprocessed_record *get_next() { if (source_iterator == unprocessed_records.end()) return nullptr; unprocessed_record *result = *source_iterator; source_iterator++; return result; } // ---map--- processed_record *process(unprocessed_record *ur) { processed_record *pr = new processed_record; pr->x = ur->x; return pr; } // ---sink--- std::unordered_map<int, processed_record *> processed_records_by_id; void save_processed_record(processed_record *pr) { processed_records_by_id[pr->x] = pr; } void print_processed_record(processed_record *pr) { std::cout << "processed record: " << pr->x << std::endl; } void print_unprocessed_record(unprocessed_record *upr) { std::cout << "[add_subscriber => notification] unprocessed record: " << upr->x << std::endl; } void test5() { std::cout << "\n\nTEST 5" << std::endl; // Note: create source. init_source(); unprocessed_record *(*source)(); source = get_next; // Note: create map. processed_record *(*map)(unprocessed_record *); map = process; // Note: create sink. void (*sink)(processed_record *); sink = save_processed_record; flowable<unprocessed_record, processed_record> *f = new flowable<unprocessed_record, processed_record>( source, map, sink, print_processed_record, 1); f->add_subscriber(print_unprocessed_record); std::cout << "processed_records_by_id.size(): " << processed_records_by_id.size() << std::endl; f->do_action(); f->do_action(); std::cout << "processed_records_by_id.size(): " << processed_records_by_id.size() << std::endl; int i = 0; while (i++ < 3 /*106*/ ) { f->do_action(); } std::cout << "processed_records_by_id.size(): " << processed_records_by_id.size() << std::endl; //=============================================================================================== // Note: time to do the cleaning of memory - housekeeping stuff. std::vector<unprocessed_record *>::iterator it = unprocessed_records.begin(); while (it != unprocessed_records.begin()) { delete *it; } std::unordered_map<int, processed_record *>::iterator it2 = processed_records_by_id.begin(); while (it2 != processed_records_by_id.end()) { processed_record *to_delete = (*it2).second; delete to_delete; it2++; } delete f; std::cout << "\n\n" << std::endl; }
true
a99b4a4288dd3d0f5cee1aa386fe3e81d25bae13
C++
Fentom/cpp-Cars
/Lib/Voiture.cxx
UTF-8
5,515
3.46875
3
[]
no_license
#include "Voiture.h" #include <stdlib.h> #include <iostream> #include <cstring> #include <sstream> #include <fstream> using namespace std; int Voiture::Comparaison(const Voiture & V) { if(getPrix() < V.getPrix() ) return -1; if(getPrix() > V.getPrix() ) return 1; if(getPrix() == V.getPrix() ) return 0; } Voiture::Voiture() { // cout << endl << "Appel du constructeur par defaut de voiture" << endl; _name = NULL; setNom("DEFAULT"); setModele(Modele()); for (int i = 0 ; i < 10 ; i++) options[i] = NULL; } Voiture::Voiture(const char * name, const Modele & obj) { // cout << endl << "Appel du constructeur complet de voiture" << endl; _name = NULL; setNom(name); setModele(obj); for (int i = 0 ; i < 10 ; i++) options[i] = NULL; } Voiture::Voiture(const Voiture & obj) { // cout << endl << "Appel du constructeur de copie de voiture" << endl; _name = NULL; setNom(obj.getNom()); setModele(obj.getModele()); for (int i = 0 ; i < 10 ; i++) options[i] = NULL; for (int i = 0 ; i < 10 ; i++) { if(obj.options[i] != NULL) { AjouteOption(obj.getOption(i)); } } } Voiture::~Voiture() { // cout << endl << "Appel du desructeur de voiture" << endl; if (_name != NULL) delete []_name; for(int i = 0 ; i < 10 ; i++) { if (options[i] != NULL) delete options[i]; } } void Voiture::setNom(const char * name) { if(_name != NULL) delete [] _name; _name = new char[strlen(name)+1]; strcpy(_name, name); } void Voiture::setModele(const Modele & obj) { _modele.setNom(obj.getNom()); _modele.setPuissance(obj.getPuissance()); _modele.setDiesel(obj.getPuissance()); _modele.setPrixDeBase(obj.getPrixDeBase()); } const char * Voiture::getNom() const { return _name; } const Modele & Voiture::getModele() const { return _modele; } Option & Voiture::getOption(int ind) const { return *options[ind]; } const float Voiture::getPrix() const { float prix = 0; prix = prix + getModele().getPrixDeBase(); for (int i = 0 ; i < 10 ; i++) { if(options[i] != NULL) prix = prix + options[i]->getPrix(); } return prix; } void Voiture::Affiche() const { int i = 0; cout << endl << "Nom : " << getNom() << endl << endl; cout << " Modele : "; getModele().Affiche(); cout << endl; cout << " Options : " << endl; int trouve = 0; for (i = 0 ; i < 10 ; i++) { if (options[i] != NULL) { trouve = 1; options[i]->Affiche(); cout << endl; } } if (trouve == 0) cout << "Il n'y a pas d'options" << endl; } const char * Voiture::toString() const { ostringstream s; s << "VOITURE:" << getNom() << "#" << getModele().getNom(); return s.str().c_str(); } void Voiture::AjouteOption(const Option & opt) { for(int i = 0 ; i < 10 ; i++) { if(options[i] == NULL) { options[i] = new Option(opt); i = 10; } } } void Voiture::RetireOption(const char * code) { int found = 0; for (int i = 0 ; i < 10 && found == 0 ; i++) { if(strcmp(options[i]->getCode(), code) == 0) { delete options[i]; options[i] = NULL; found = 1; } } if (found == 1) cout << "Option retiree avec succes." << endl; else cout << "Option inconnue." << endl; } Voiture & Voiture::operator=(const Voiture & V) { _name = NULL; setNom(V.getNom()); setModele(V.getModele()); for (int i = 0 ; i < 10 ; i++) options[i] = NULL; for (int i = 0 ; i < 10 ; i++) { if(V.options[i] != NULL) { AjouteOption(V.getOption(i)); } } } int Voiture::operator<(const Voiture & V) { return Comparaison(V) == -1; } int Voiture::operator>(const Voiture & V) { return Comparaison(V) == 1; } int Voiture::operator==(const Voiture & V) { return Comparaison(V) == 0; } void Voiture::Save() { char NomFichier[100]; char Buff[100]; int n; strcpy(NomFichier, _name); strcat(NomFichier, ".car"); ofstream fichier(NomFichier,ios::out); n = strlen(_name); fichier.write((char*) &n, sizeof(int)); fichier.write(_name, n); _modele.Save(fichier); n = 0; for (int i = 0; i < 10; i++) { if (options[i] != NULL) { n++; } } fichier.write((char*) &n, sizeof(int)); // Pour connaitre le nbr d'option for (int i = 0; i < 10; i++) { if (options[i] != NULL) { options[i]->Save(fichier); } } } void Voiture::Load(const char* nomFichier) { char buff[100]; int n; Option opt; ifstream f(nomFichier,ios::in); if(f.is_open()) { f.read((char*)&n, sizeof(int)); f.read(buff, n); buff[n] = '\0'; setNom(buff); _modele.Load(f); f.read((char*)&n, sizeof(int)); for (int i = 0; i < 10; ++i) { delete options[i]; options[i] = NULL; } for (int i = 0; i < n; ++i) { opt.Load(f); AjouteOption(opt); } } else cout << "Il n'y a pas de fichier avec ce nom. (NOM: " << nomFichier << ")" << endl; } // FONCTION LIBRE (donc amie) -- HORS de la classe Voiture operator+(const Voiture & V, const Option & O) { Voiture result = V; result.AjouteOption(O); return result; } Voiture operator-(const Voiture & V, const Option & O) { Voiture result = V; result.RetireOption(O.getCode()); return result; } Voiture operator-(const Voiture & V, const char * code) { Voiture result = V; result.RetireOption(code); return result; } ostream & operator<< (ostream & flux, const Voiture & V) { flux << V.toString(); return flux; } istream & operator>> (istream & flux, Voiture & V) { cout << "Nom : "; flux >> V._name; cout << "Modele : " << endl; flux >> V._modele; flux.clear(); flux.ignore(); return flux; } //
true
91f7be1867bc65bacc565a305fd403a66c4f548f
C++
kapz28/All-the-projects
/big_int/a1_doubly_linked_list.cpp
UTF-8
6,626
3.359375
3
[]
no_license
//kapilan satkunanathan and yuanpei gao #include <iostream> #include "a1_doubly_linked_list.hpp" using namespace std; DoublyLinkedList::Node::Node(DataType data) { prev= NULL; next= NULL; value = data; } DoublyLinkedList::DoublyLinkedList() { head_ = NULL; tail_ = NULL; size_=0; } DoublyLinkedList::~DoublyLinkedList() { } unsigned int DoublyLinkedList::size() const { return size_; } unsigned int DoublyLinkedList::capacity() const { return CAPACITY; } bool DoublyLinkedList::empty() const { // if(head_==NULL){ if(size_==0){ return true; } return false; } bool DoublyLinkedList::full() const { if(size_== CAPACITY){ return true; } return false; } DoublyLinkedList::DataType DoublyLinkedList::select(unsigned int index) const { if (index >= size_-1){ DataType num = tail_->value; return num; }else{ Node *a1 = new Node(0); a1=head_; for(int i=0;i<index;i++){ a1 = a1->next; } DataType num = a1->value; return num; } } unsigned int DoublyLinkedList::search(DataType value) const { Node *a1; a1=head_; if(head_->value == value){ return 0; } for(int i=1 ;i<size_;i++){ a1 = a1->next; if(a1->value == value){ return i; } } return size_; } void DoublyLinkedList::print() const { Node *a = head_; //current is the beginning value of the list while (a != NULL) //Continue while current is not at the end of the list { cout << a->value << " "; //Print out the data of current a = a->next; //Move one value along in the list } } DoublyLinkedList::Node* DoublyLinkedList::getNode(unsigned int index) const { Node *n = head_; while(index > 0){ n = n->next; index--; } return n; } bool DoublyLinkedList::insert(DataType value, unsigned int index) { if (index > size_|| index<0){ return false; } if(index == 0 && size_==0){ Node *newnode = new Node(value); head_ =newnode; tail_ = newnode; size_ ++; return true; } if (index == size_){ insert_back(value); return true; } if(size_==1 && index == 0){ Node *newnode = new Node(value); head_ =newnode; newnode->next= tail_; tail_->prev = newnode; size_ ++; return true; } Node *newnode = new Node(value); Node *a1 = getNode(index); Node *a2 = getNode(index - 1); newnode -> next = a1; a1 ->prev= newnode; a2 -> next = newnode; newnode -> prev = a2; size_ ++; return true; } bool DoublyLinkedList::insert_front(DataType value) { Node *a1= new Node(value); if(head_==NULL){ head_=a1; tail_=a1; size_++; return true; } else{ a1->next =head_; head_->prev= a1; head_= a1; size_++; return true; } } bool DoublyLinkedList::insert_back(DataType value) { if(size_==CAPACITY){ return false; } Node *a1= new Node(value); if(head_==NULL){ head_=a1; tail_=a1; size_++; return true; } else{ a1->prev = tail_; tail_->next= a1; tail_= a1; size_++; return true; } } bool DoublyLinkedList::remove(unsigned int index) { if(size_==0){ return false; } if(index>=size_){ return false; } if(index<0){ return false; } Node* track = getNode(index); if(track->prev == NULL){ return remove_front(); } if(track->next == NULL){ return remove_back(); } track->next->prev = track->prev; track->prev->next = track->next; size_--; delete track; track = NULL; return true; } bool DoublyLinkedList::remove_front() { if(size_ ==0){ return false; } if(size_ ==1){ head_ = NULL; tail_ = NULL; size_--; return true; } head_ = head_->next; size_--; return true; } bool DoublyLinkedList::remove_back() { if(size_ ==0 ){ return false; } if(size_ ==1 ){ head_ = NULL; tail_ = NULL; size_--; return true; } Node *kap= tail_; tail_ = tail_->prev; tail_->next=NULL; size_--; return true; } bool DoublyLinkedList::replace(unsigned int index, DataType value) { if (index > size_-1){ return false; } else if(index==0){ head_->value= value; return true; } else{ Node *a1; a1=head_; //Node* temp; for(int i=0;i<index;i++){ //temp = a1; a1 = a1->next; } a1->value = value; return true; } } bool DoublyLinkedList::is_sorted_asc() const { if(size_ == 0 || size_ ==1){ return true; } Node *a1; a1=head_; Node* a2 = a1->next; for(int i=0 ;i<(size_-1);i++){ if(a1->value > a2->value){ return false; } a1 = a1->next; a2 = a1->next; } return true; } bool DoublyLinkedList::is_sorted_desc() const { if(size_ == 0 || size_ ==1){ return true; } Node *a1; a1=head_; Node* a2 = a1->next; for(int i=0 ;i<(size_-1);i++){ if(a1->value < a2->value){ return false; } a1 = a1->next; a2 = a1->next; } return true; } bool DoublyLinkedList::insert_sorted_asc(DataType val) { if(!is_sorted_asc()){ return false; } if(size_==0){ insert_front(val); return true; } if(tail_->value <= val){ insert_back(val); return true; } if(head_->value > val){ insert_front(val); return true; } if(size_==1){ DataType temp= head_->value; head_->value = val; insert_back(temp); return true; } Node *a1; a1=head_; Node* a2 = a1->next; for(int i=0 ;i<(size_-1);i++){ if((a1->value<val)&&(a2->value > val)){ if(a1->value == a2->value){ } else{ DataType index=search(a2->value); insert(val,index); return true; } } a1 = a1->next; a2 = a1->next; } } bool DoublyLinkedList::insert_sorted_desc(DataType val) { if(!is_sorted_desc()){ return false; } if(size_==0){ insert_front(val); return true; } if(tail_->value >= val){ insert_back(val); return true; } if(head_->value < val){ insert_front(val); return true; } Node *a1; a1=head_; Node* a2 = a1->next; for(int i=0 ;i<(size_-1);i++){ if((a1->value>val)&&(a2->value < val)){ if(a1->value == a2->value){ } else{ DataType index=search(a2->value); insert(val,index); return true; } } a1 = a1->next; a2 = a1->next; } } void DoublyLinkedList::sort_asc() { if(size_==0||size_==1){ } else{ Node *a1; a1=head_; Node* a2 = a1->next; for(int j=0 ;j<(size_-1);j++){ a1= head_; a2 = a1->next; for(int i=0 ;i<(size_-1);i++){ if(a1->value>a2->value){ DataType temp = a2->value; a2->value=a1->value; a1->value=temp; } a1 = a1->next; a2 = a1->next; } } } } void DoublyLinkedList::sort_desc() { if(size_==0||size_==1){ } else{ Node *a1; a1=head_; Node* a2 = a1->next; for(int j=0 ;j<(size_-1);j++){ a1= head_; a2 = a1->next; for(int i=0 ;i<(size_-1);i++){ if(a1->value<a2->value){ DataType temp = a2->value; a2->value=a1->value; a1->value=temp; } a1 = a1->next; a2 = a1->next; } } } }
true
3989c8ed4bb53753b135a846bb89b6983fd00c70
C++
junseublim/Algorithm-study
/baekjoon/2630.cpp
UTF-8
895
2.9375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int paper[128][128]; int white = 0; int blue = 0; void divide(int ys, int ye, int xs, int xe) { int num = paper[ys][xs]; int able = 1; for (int i = ys; i<ye; i++) { for (int j = xs; j<xe; j++) { if (paper[i][j] != num) { able = 0; } } } if (able) { if (num == 0) { white += 1; } else { blue += 1; } } else { int ym = (ys+ye)/2; int xm = (xs+xe)/2; divide(ys,ym,xs,xm); divide(ym,ye,xs,xm); divide(ys,ym, xm,xe); divide(ym,ye, xm,xe); } } int main() { int n; cin>>n; for (int i =0; i<n; i++) { for (int j =0; j<n; j++) { cin>>paper[i][j]; } } divide(0,n,0,n); cout<<white<<endl; cout<<blue<<endl; }
true
aa1a74dd3deb05e075d8e00fc13b3029245ca8e8
C++
Oswal-Fuentes/Proyecto_Programacion3
/Cuenta_normal.cpp
UTF-8
2,877
2.78125
3
[]
no_license
#include "Cuenta_normal.h" #include <cstdlib> Cuenta_normal::Cuenta_normal(string nombre,string username,string password,vector<Cuenta*>* perteneceA){ this->nombre=nombre; this->username=username; this->password=password; this->perteneceA=perteneceA; } Cuenta_normal::Cuenta_normal(){ } void Cuenta_normal::agregar_a_Favoritos(Cancion* cancion){ for (int i = 0; i < 10; ++i){ mvprintw(5+i,5,"Pásate a premium para hacer esto"); } mvprintw(15,5,"Presiona una tecla para continuar."); getch(); clear(); } void Cuenta_normal::verHistorial(){ clear(); for (int i = 0; i < 10; ++i){ mvprintw(5+i,5,"Pásate a premium para hacer esto"); } mvprintw(15,5,"Presiona una tecla para continuar."); getch(); clear(); } void Cuenta_normal::agregar_a_Playlist(Cancion* cancion){ for (int i = 0; i < 10; ++i){ mvprintw(5+i,5,"Pásate a premium para hacer esto"); } mvprintw(15,5,"Presiona una tecla para continuar."); getch(); clear(); } void Cuenta_normal::cambiarTipo(){ clear(); mvprintw(5,5,"Está bloqueado en su region"); clear(); } void Cuenta_normal::cancelarSuscripcion(){ for (int i = 0; i < 10; ++i){ mvprintw(5+i,5,"Pásate a premium para hacer esto"); } mvprintw(15,5,"Presiona una tecla para continuar."); getch(); clear(); } void Cuenta_normal::borrarCuenta(){ clear(); for (int i = 0; i < 10; ++i){ mvprintw(5+i,5,"Se eliminó la cuenta"); } getch(); delete this; clear(); } void Cuenta_normal::reproducir(vector<Cancion*> cancionesActuales){ clear(); char respuesta[1000]; //Se listan las canciones mvprintw(4,5,"Lista de canciones."); for (int i = 0; i < cancionesActuales.size(); ++i){ mvprintw(5+i,5,to_string(i).c_str()); mvprintw(5+i,7,cancionesActuales[i]->getNombre().c_str()); } //Menú reproducir mvprintw(5+cancionesActuales.size(),5,"Menú"); mvprintw(5+cancionesActuales.size()+1,5, "1. Reproducir aleatoriamente"); mvprintw(5+cancionesActuales.size()+2,5, "2. Agregar a favoritos"); mvprintw(5+cancionesActuales.size()+3,5, "3. Ver historial"); mvprintw(5+cancionesActuales.size()+4,5, "4. Agregar a playlist"); mvprintw(5+cancionesActuales.size()+5,5, "Ingrese opción: "); //Se lee la respuesta getstr(respuesta); string resp(respuesta); //Cuando se escoge una opción if (resp.compare("1")==0){ int pos=rand()%cancionesActuales.size(); Cancion* cancion; cancion=cancionesActuales[pos]; cancion++; historial.push_back(cancion); clear(); mvprintw(5,5,"La cancion se está reproduciendo actualmente,"); mvprintw(6,5,"presione una tecla para continuar."); getch(); } if (resp.compare("2")==0){ clear(); agregar_a_Favoritos(cancionesActuales[0]); } if (resp.compare("3")==0){ clear(); verHistorial(); } if (resp.compare("4")==0){ clear(); agregar_a_Playlist(cancionesActuales[0]); } } string Cuenta_normal::getTipo(){ return "Cuenta_normal"; }
true
e25904acbec772a4c844792a1adcb95f895d730a
C++
NikitaNikson/xray-2_0
/engine/xray/maya/sources/xray_shader_node_calculate.cpp
UTF-8
4,510
2.59375
3
[]
no_license
//////////////////////////////////////////////////////////////////////////// // Created : 18.05.2010 // Author : Andrew Kolomiets // Copyright (C) GSC Game World - 2010 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "xray_shader_node.h" // The compute() method does the actual work of the node using the inputs // of the node to generate its output. // // Compute takes two parameters: plug and data. // - Plug is the the data value that needs to be recomputed // - Data provides handles to all of the nodes attributes, only these // handles should be used when performing computations. // MStatus xray_shader_node::compute( const MPlug& plug, MDataBlock& block ) { // The plug parameter will allow us to determine which output attribute // needs to be calculated. if( plug == aOutColor || plug == aOutColorR || plug == aOutColorG || plug == aOutColorB || plug == aOutTransparency || plug == aOutTransR || plug == aOutTransG || plug == aOutTransB ) { MStatus status; MFloatVector resultColor( 0.0, 0.0, 0.0 ); // Get surface shading parameters from input block // MFloatVector& surfaceNormal = block.inputValue( aNormalCamera, &status ).asFloatVector(); CHK_STAT ( status ); MFloatVector& surfaceColor = block.inputValue( aColor, &status ).asFloatVector(); CHK_STAT ( status ); //MFloatVector& incandescence = block.inputValue( aIncandescence, &status ).asFloatVector(); //CHK_STAT ( status ); //float diffuseReflectivity = block.inputValue(aDiffuseReflectivity, &status ).asFloat(); //CHK_STAT ( status ); // float translucenceCoeff = block.inputValue( aTranslucenceCoeff, &status ).asFloat(); // CHK_STAT ( status ); // Get light list // MArrayDataHandle lightData = block.inputArrayValue( aLightData, &status ); CHK_STAT ( status ); int numLights = lightData.elementCount( &status ); CHK_STAT ( status ); // Calculate the effect of the lights in the scene on the color // Iterate through light list and get ambient/diffuse values for( int count=1; count <= numLights; count++ ) { // Get the current light out of the array // MDataHandle currentLight = lightData.inputValue( &status ); CHK_STAT ( status ); // Get the intensity of that light MFloatVector& lightIntensity = currentLight.child( aLightIntensity ).asFloatVector(); // Find ambient component if ( currentLight.child( aLightAmbient ).asBool() ) resultColor += lightIntensity; // Find diffuse component // if ( currentLight.child( aLightDiffuse ).asBool() ) { MFloatVector& lightDirection = currentLight.child( aLightDirection ).asFloatVector(); float cosln = lightDirection * surfaceNormal; if ( cosln > 0.0f ) resultColor += lightIntensity * ( cosln*0.8f /* *diffuseReflectivity*/ ); } // Advance to the next light. // if ( count < numLights ) { status = lightData.next(); CHK_STAT ( status ); } } // Factor incident light with surface color and add incandescence // resultColor[0] = resultColor[0] * surfaceColor[0];// + incandescence[0]; resultColor[1] = resultColor[1] * surfaceColor[1];// + incandescence[1]; resultColor[2] = resultColor[2] * surfaceColor[2];// + incandescence[2]; // Set ouput color attribute if ( plug == aOutColor || plug == aOutColorR || plug == aOutColorG || plug == aOutColorB) { // Get the handle to the attribute MDataHandle outColorHandle = block.outputValue( aOutColor, &status ); CHK_STAT ( status ); MFloatVector& outColor = outColorHandle.asFloatVector(); outColor = resultColor;// Set the output value outColorHandle.setClean ( ); // Mark the output value as clean } // Set ouput transparency if ( plug == aOutTransparency || plug == aOutTransR || plug == aOutTransG || plug == aOutTransB ) { MFloatVector& transparency = block.inputValue( aInTransparency, &status ).asFloatVector(); CHK_STAT ( status ); // Get the handle to the attribute MDataHandle outTransHandle = block.outputValue( aOutTransparency, &status ); CHK_STAT ( status ); MFloatVector& outTrans = outTransHandle.asFloatVector(); outTrans = transparency; // Set the output value outTransHandle.setClean ( ); // Mark the output value as clean } } else { return( MS::kUnknownParameter ); // We got an unexpected plug } return( MS::kSuccess ); }
true
9f99165f285f2a910f629317e11852abb08e18ed
C++
hgeorge21/Physical_Animation
/A4/src/dphi_cloth_triangle_dX.cpp
UTF-8
637
2.671875
3
[]
no_license
#include <dphi_cloth_triangle_dX.h> #include <iostream> //compute 3x3 deformation gradient void dphi_cloth_triangle_dX(Eigen::Matrix3d &dphi, Eigen::Ref<const Eigen::MatrixXd> V, Eigen::Ref<const Eigen::RowVectorXi> element, Eigen::Ref<const Eigen::Vector3d> X) { Eigen::MatrixXd T(3, 2); T.block<3, 1>(0, 0) = V.row(element(1)) - V.row(element(0)); T.block<3, 1>(0, 1) = V.row(element(2)) - V.row(element(0)); Eigen::MatrixXd temp = (T.transpose() * T).inverse() * T.transpose(); Eigen::Matrix32d tmp; tmp << -1. * Eigen::RowVector2d::Ones(), Eigen::Matrix2d::Identity(); dphi = tmp * temp; }
true
a6d687fcf1344ecdb287723d5b3ba919a56b6bc7
C++
raquelmolinare/IG-UGR
/Codigo/src/camara.cc
UTF-8
10,125
3.03125
3
[]
no_license
#include "auxiliar.h" #include "camara.h" #define PI 3.141592 //Definimos PI Camara::Camara (Tupla3f eyeCam,Tupla3f atCam,Tupla3f upCam, int tipoCam,float leftCam, float rightCam, float bottomCam, float topCam,float nearCam ,float farCam) { if( tipoCam > 2 || tipoCam < 1){ tipo = 1; } else tipo = tipoCam; //parámetros gluLookAt eye = eyeCam; at = atCam; up = upCam; //Parametros de la camara left = leftCam; right = rightCam; bottom = bottomCam; top = topCam; near = nearCam; far = farCam; //Parametros para el control del movimiento cteGiro = 0.2; anguloX = 0.0; anguloY = 0.0; yaw = 0.0; pitch = 0.0; modo = FIRSTPERSON; seleccionaObjeto = false; indiceObjeto = 0; //0 si ninguno } Camara::Camara (Tupla3f eyeCam,Tupla3f atCam, int tipoCam) { if( tipoCam > 2 || tipoCam < 1){ tipo = 1; } else tipo = tipoCam; //parámetros gluLookAt eye = eyeCam; at = atCam; up = {0.0,1.0,0.0}; //Sentido hacia arriba //El volumen de visualización depende del tipo de camara switch (tipo) { case 1: //ORTOGONAL (1) left = -200.0; right = 200.0; bottom = -200.0; top = 200.0; near = -200.0; far = 2000.0; break; case 2: //Perspectiva (2) bottom = left = -70.0; top = right = 70.0; near =50.0; far = 2000.0; break; } cteGiro = 0.2; anguloX = 0.0; anguloY = 0.0; yaw = 0.0; pitch = 0.0; seleccionaObjeto = false; indiceObjeto = false; //0 si ninguno } //Rotar x en torno a un punto void Camara::rotarXExaminar ( float angle ){ //glRotatef( angle, 1, 0, 0 ); //Rotar eye respecto a at sobre el eje x Tupla3f direccion = eye - at; //Obtenemos el vector director float modulo = sqrt(pow(direccion[0],2) + pow(direccion[1],2) + pow(direccion[2],2)); //Rotacion en X //direccion[0] = direccion[0]; direccion[1] = (direccion[1] * cos((angle*PI)/180.0)) - (direccion[2] * sin((angle*PI)/180.0)); direccion[2] = (direccion[1] * sin((angle*PI)/180.0)) + (direccion[2] * cos((angle*PI)/180.0)); direccion = direccion.normalized() * modulo; //Aignamos eye = direccion + at; } //Rotar y en torno a un punto void Camara::rotarYExaminar ( float angle ){ //glRotatef( angle, 0 ,1, 0 ); //Rotar eye respecto a at sobre el eje y Tupla3f direccion = eye - at; //Obtenemos el vector director float modulo = sqrt(pow(direccion[0],2) + pow(direccion[1],2) + pow(direccion[2],2)); //Rotacion en Y direccion[0] = (direccion[0] * cos((angle*PI)/180.0)) + (direccion[2] * sin((angle*PI)/180.0)); //direccion[1] = direccion[1]; direccion[2] = (direccion[0] * -sin((angle*PI)/180.0)) + (direccion[2] * cos((angle*PI)/180.0)); direccion = direccion.normalized() * modulo; //Aignamos eye = direccion + at; } //Rotar z en torno a un punto void Camara::rotarZExaminar ( float angle ){ //glRotatef( angle, 0 ,0, 1 ); //Rotar eye respecto a at sobre el eje z Tupla3f direccion = eye - at; //Obtenemos el vector director float modulo = sqrt(pow(direccion[0],2) + pow(direccion[1],2) + pow(direccion[2],2)); //Rotacion en Z direccion[0] = (direccion[0] * cos((angle*PI)/180.0)) - (direccion[1] * sin((angle*PI)/180.0)); direccion[1] = (direccion[0] * sin((angle*PI)/180.0)) + (direccion[1] * cos((angle*PI)/180.0)); //direccion[2] = direccion[2]; direccion = direccion.normalized() * modulo; //Aignamos eye = direccion + at; } void Camara::rotarXFirstPerson ( float angle ){ //Rotar at respecto a eye sobre el eje x Tupla3f direccion = at - eye; float modulo = sqrt(pow(direccion[0],2) + pow(direccion[1],2) + pow(direccion[2],2)); //Rotacion en X //direccion[0] = direccion[0]; direccion[1] = (direccion[1] * cos((angle*PI)/180.0)) - (direccion[2] * sin((angle*PI)/180.0)); direccion[2] = (direccion[1] * sin((angle*PI)/180.0)) + (direccion[2]* cos((angle*PI)/180.0)); direccion = direccion.normalized() * modulo; at = direccion + eye; } void Camara::rotarYFirstPerson ( float angle ){ //Rotar at respecto a eye sobre el eje Y Tupla3f direccion = at - eye; float modulo = sqrt(pow(direccion[0],2) + pow(direccion[1],2) + pow(direccion[2],2)); //Rotacion en Y direccion[0] = (direccion[0] * cos((angle*PI)/180.0)) + (direccion[2] * sin((angle*PI)/180.0)); //direccion[1] = direccion[1]; direccion[2] = (direccion[0]* -sin((angle*PI)/180.0)) + (direccion[2] * cos((angle*PI)/180.0)); direccion = direccion.normalized() * modulo; at = direccion + eye; } void Camara::rotarZFirstPerson ( float angle ){ //Rotar at respecto a eye sobre el eje Z Tupla3f direccion = at - eye; float modulo = sqrt(pow(direccion[0],2) + pow(direccion[1],2) + pow(direccion[2],2)); //Rotacion en Z direccion[0] = (direccion[0] * cos((angle*PI)/180.0)) - (direccion[2] * sin((angle*PI)/180.0)); direccion[1] = (direccion[0] * sin((angle*PI)/180.0)) + (direccion[2] * cos((angle*PI)/180.0)); //direccion[2] = direccion[2]; direccion = direccion.normalized() * modulo; at = direccion + eye; } void Camara::mover ( float x, float y, float z ){ eye[0] = x; eye[1] = y; eye[2] = z; } //Pone la camara en posicion examinar un objeto que esta en el x,y,z void Camara::posicionarExaminar( float x, float y, float z ){ at[0] = x; at[1] = y; at[2] = z; //eye[0] = x; eye[1] = y + 100.0; //eye[2] = z + 100.0; /*switch (tipo) { case 1: //ORTOGONAL (1) if( eye[2] < 0 ) eye[2] = z - 50.0; else eye[2] = z + 50.0; break; case 2: //Perspectiva (2) if( eye[2] < 0 ) eye[2] = z - 100.0; else eye[2] = z + 100.0; break; }*/ } /** * @brief recalcula el valor de sus parámetros de giro en X y en Y (angleX y angleY). * * @param x : Diferencia de xactual - xanterior * @param y : Diferencia de yactual - yanterior */ void Camara::girarExaminar( float x, float y){ //Calculamos el angulo de giro //modo = EXAMINAR; anguloX = (float)(-cteGiro*y); anguloY = (float)(-cteGiro*x); //Realizamos el giro rotarYExaminar(anguloY); rotarXExaminar(anguloX); } void Camara::girarFirstPerson( float x, float y){ //Calculamos el angulo de giro //modo = FIRSTPERSON; pitch = (-cteGiro*y); yaw = (-cteGiro*x); //Realizamos el giro rotarYFirstPerson(yaw); rotarXFirstPerson(pitch); } void Camara::zoom ( float factor ){ left = (left * factor); right = (right *factor); top = (top * factor); bottom = (bottom * factor); //Para que se aplique el zoom setProyeccion(); } void Camara::rotarX( float angle ){ if(modo == EXAMINAR){ anguloX = angle; rotarXExaminar(anguloX); } else{ pitch = -angle; rotarXFirstPerson(pitch); } } void Camara::rotarY( float angle ){ if(modo == EXAMINAR){ anguloY = angle; rotarYExaminar(anguloY); } else{ yaw = -angle; rotarYFirstPerson(yaw); } } /** * @brief Esta función posiciona al observador de forma que el ojo está en la posición eye, mirando hacia el punto at y con el sentido “hacia arriba” definido por el vector up * */ void Camara::setObserver () { gluLookAt( eye[0], eye[1], eye[2], at[0], at[1], at[2], up[0], up[1], up[2]); /* if(modo == EXAMINAR){ glTranslatef(at[0],at[1],at[2]); rotarXExaminar(anguloX); rotarYExaminar(anguloY); }*/ } void Camara::setProyeccion(){ //indicar a OpenGL que todas las operacionessobre matrices que se apliquen desde //ese instante hasta que se cambie el glMatrixMode, se aplicarán sobre la matriz de proyección glMatrixMode(GL_PROJECTION); glLoadIdentity(); //La proyeccion depende del tipo de camara switch (tipo) { case 1: //ORTOGONAL (1) --> glOrtho glOrtho( left, right, bottom, top, near, far); case 2: //Perspectiva (2) --> glFrustrum glFrustum( left, right, bottom, top, near, far); } } //--------------------------------------------------------- //------SETTERS //--------------------------------------------------------- void Camara::setAt(Tupla3f atNew){ at = atNew; } void Camara::setLeft(float nleft){ left = nleft; } void Camara::setRight(float nright){ right = nright; } void Camara::setNear(float nnear){ near = nnear; } void Camara::setFar(float nfar){ far = nfar; } void Camara::setBottom(float nbottom){ bottom = nbottom; } void Camara::setTop(float ntop){ top = ntop; } void Camara::setSeleccionaObjeto( bool selecciona){ if(selecciona){ seleccionaObjeto = true; modo = EXAMINAR; } else{ seleccionaObjeto = false; modo = FIRSTPERSON; } } void Camara::setIndiceObjeto(int indice){ indiceObjeto = indice; } //--------------------------------------------------------- //-----GETTERS //--------------------------------------------------------- float Camara::getLeft(){ return left; } float Camara::getRight(){ return right; } float Camara::getNear(){ return near; } float Camara::getFar(){ return far; } float Camara::getBottom(){ return bottom; } float Camara::getTop(){ return top; } /** * @brief Devuelve el modo de movimiento actual de la camara * * @return int 0: si esta en modo EXAMINAR o 1 si está en modo FIRSTPERSON */ int Camara::getModo(){ return modo; } int Camara::getIndiceObjeto(){ return indiceObjeto; } bool Camara::getSeleccionaObjeto(){ return seleccionaObjeto; }
true
29c2b488a74373141041aabda1cecb1144527118
C++
Happyxianyueveryday/wdpl
/第二章:线性表/2.3节习题/problem_17.cpp
GB18030
3,695
3.890625
4
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ // רµľϰ⣬leetcodeӼ: https://leetcode-cn.com/problems/palindrome-linked-list/ // A. ȸһʱ临ӶO(n)ռ临ӶO(n)дʹջʵ֣ٶ // 㷨: һջʹڲм˫ָ뷨: // (1) ָfastָslow // (2) ѭ²ֱָfastָNULL: ָslowָĽֵջȻָfastǰƶָslowǰһѭͬʱͳ Ľ // (3) Ϊʼµָtest=slow->nextΪżʼָtest=slow // (4) ѭ²ֱָtestΪ: ָtestֵջԪرȽϣѭȣֱӷfalseʾǻ // (5) вִϺջΪ򷵻trueջǿ򷵻false class Solution { public: bool isPalindrome(ListNode* head) { // 0. ͵Ԫ if(!head||!head->next) return true; // 1. ȣм㣬м֮ǰĽֵмջͬʱеĽż ListNode *fast=head; ListNode *slow=head; stack<int> sta; while(fast&&fast->next) { sta.push(slow->val); // ע⣬дslowм㲢δջ slow=slow->next; fast=fast->next->next; } bool isodd; if(!fast) // fast==NULL˳ѭΪż isodd=false; else // fast->next==NULL˳ѭΪ isodd=true; // 2. ʼµαָtest ListNode *test=(isodd)?slow->next:slow; while(test&&sta.size()) { if(sta.top()!=test->val) return false; else { sta.pop(); test=test->next; } } if(sta.size()) return false; else return true; } }; // B. 2: ת벿Ȼͷм㿪ʼȽ class Solution { public: bool isPalindrome(ListNode* head) { // 0. if(!head||!head->next) return true; // 1. ָ뷨м ListNode *fast=head, *slow=head, *slowprev=NULL; while(fast&&fast->next) { slowprev=slow; slow=slow->next; fast=fast->next->next; } // 2. תslowʼĺ if(slow&&slow->next) // дslowʼϲҪзת { ListNode *now=slow->next, *nowprev=slow; while(now) { nowprev->next=now->next; now->next=slowprev->next; slowprev->next=now; now=nowprev->next; } } // 3. ͷм㿪ʼбȽ ListNode *pos1=head, *pos2=slowprev->next; //ָslowѾı䣬Ҫע while(pos2&&pos1!=slowprev->next) { if(pos1->val!=pos2->val) return false; else { pos1=pos1->next; pos2=pos2->next; } } return true; } };
true
bb52c73d077a3bf310481813978c3277ca6e285f
C++
ydlme/LeetCodeOj
/src/Sort_List.cpp
UTF-8
1,753
3.390625
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 *sortList(ListNode *head) { /* if (head == NULL || head->next == NULL) return head; ListNode *fast = head; ListNode *slow = head; while (fast->next != NULL && fast->next->next != NULL) { fast = fast->next->next; slow = slow->next; } fast = slow->next; slow->next = NULL; ListNode *left = sortList(head); ListNode *right = sortList(fast); return merge(left, right); */ if (head == NULL) return NULL; int len = 1; ListNode *cur = head; while ( (cur = cur->next) ) { len++; } ListNode* *nodeAdrr = new ListNode*[len]; cur = head; for (int i = 0; i < len; i++) { nodeAdrr[i] = cur; cur = cur->next; } cur = partition(nodeAdrr, 0, len-1); delete []nodeAdrr; return cur; } ListNode *partition(ListNode* *nodeAdrr, int begin, int end) { if (begin >= end) return nodeAdrr[end]; int mid = begin + (end - begin) / 2; nodeAdrr[mid]->next = NULL; ListNode *left = partition(nodeAdrr, begin, mid); ListNode *right = partition(nodeAdrr, mid+1, end); return merge(left, right); } ListNode* merge(ListNode *a, ListNode*b) { ListNode head(0); ListNode *tail = &head; while ( a&&b ) { /* importance for stability */ if (a->val <= b->val) { tail->next = a; a = a->next; } else { tail->next = b; b = b->next; } tail = tail->next; } tail->next = a ? a : b; return head.next; } };
true
84cab1966f9f76c77f728216ab960a05849e84f4
C++
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-scott-gleason
/src/homework/04_iteration/main.cpp
UTF-8
1,174
3.78125
4
[ "MIT" ]
permissive
//write include statements #include "dna.h" //write using statements using std::cin; using std::cout; /* Write code that prompts user to enter 1 for Get GC Content, or 2 for Get DNA Complement. The program will prompt user for a DNA string and call either get gc content or get dna complement function and display the result. Program runs as long as user enters a y or Y. */ int main() { char choice; double gc_content; string dna, new_dna; bool quit_program; do { cout << "Please enter 1 for Get GC Content, 2 for Get DNA Complement, Y to quit: "; cin >> choice; if (choice == '1') { cout << "\nPlease enter DNA string: "; cin >> dna; gc_content = get_gc_content(dna); cout <<"The GC Content for DNA string " << dna << " is " << gc_content << "\n"; } else if (choice == '2') { cout << "\nPlease enter DNA string: "; cin >> dna; new_dna = get_dna_complement(dna); cout << "The DNA Complement for DNA string " << dna << " is " << new_dna << "\n"; } else if (choice == 'Y' || choice == 'y') { quit_program = true; } else { cout << "Invalid Entry!"; } } while (quit_program == false); return 0; }
true
26c45ff1f45a4442d6e920d95244b59215048b9c
C++
drkzrg/SynthControl
/usb.cpp
UTF-8
9,349
2.765625
3
[]
no_license
#include <QPushButton> #include "usb.h" BOOL GetDeviceHandle(GUID guidDeviceInterface, PHANDLE hDeviceHandle) { BOOL bResult = TRUE; HDEVINFO hDeviceInfo; SP_DEVINFO_DATA DeviceInfoData; SP_DEVICE_INTERFACE_DATA deviceInterfaceData; PSP_DEVICE_INTERFACE_DETAIL_DATA pInterfaceDetailData = NULL; ULONG requiredLength = 0; LPTSTR lpDevicePath = NULL; DWORD index = 0; if(hDeviceHandle == INVALID_HANDLE_VALUE) return FALSE; // Get information about all the installed devices for the specified // device interface class. hDeviceInfo = SetupDiGetClassDevs(&guidDeviceInterface, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if(hDeviceInfo == INVALID_HANDLE_VALUE) { // ERROR printf("Error SetupDiGetClassDevs: %d.\n", GetLastError()); LocalFree(lpDevicePath); LocalFree(pInterfaceDetailData); bResult = SetupDiDestroyDeviceInfoList(hDeviceInfo); return bResult; } //Enumerate all the device interfaces in the device information set. DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); for(index = 0; SetupDiEnumDeviceInfo(hDeviceInfo, index, &DeviceInfoData); index++) { //Reset for this iteration if(lpDevicePath) LocalFree(lpDevicePath); if(pInterfaceDetailData) LocalFree(pInterfaceDetailData); deviceInterfaceData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA); //Get information about the device interface. bResult = SetupDiEnumDeviceInterfaces(hDeviceInfo, &DeviceInfoData, &guidDeviceInterface, 0, &deviceInterfaceData); // Check if last item if(GetLastError() == ERROR_NO_MORE_ITEMS) break; //Check for some other error if(!bResult) { printf("Error SetupDiEnumDeviceInterfaces: %d.\n", GetLastError()); LocalFree(lpDevicePath); LocalFree(pInterfaceDetailData); bResult = SetupDiDestroyDeviceInfoList(hDeviceInfo); return bResult; } //Interface data is returned in SP_DEVICE_INTERFACE_DETAIL_DATA //which we need to allocate, so we have to call this function twice. //First to get the size so that we know how much to allocate //Second, the actual call with the allocated buffer bResult = SetupDiGetDeviceInterfaceDetail(hDeviceInfo, &deviceInterfaceData, NULL, 0, &requiredLength, NULL ); //Check for some other error if(!bResult) { if((ERROR_INSUFFICIENT_BUFFER == GetLastError()) && (requiredLength > 0)) { //we got the size, allocate buffer pInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, requiredLength); if(!pInterfaceDetailData) { //ERROR printf("Error allocating memory for the device detail buffer.\n"); LocalFree(lpDevicePath); LocalFree(pInterfaceDetailData); bResult = SetupDiDestroyDeviceInfoList(hDeviceInfo); return bResult; } } else { printf("Error SetupDiEnumDeviceInterfaces: %d.\n", GetLastError()); LocalFree(lpDevicePath); LocalFree(pInterfaceDetailData); bResult = SetupDiDestroyDeviceInfoList(hDeviceInfo); return bResult; } } //get the interface detailed data pInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); //Now call it with the correct size and allocated buffer bResult = SetupDiGetDeviceInterfaceDetail(hDeviceInfo, &deviceInterfaceData, pInterfaceDetailData, requiredLength, NULL, &DeviceInfoData); //Check for some other error if(!bResult) { printf("Error SetupDiGetDeviceInterfaceDetail: %d.\n", GetLastError()); LocalFree(lpDevicePath); LocalFree(pInterfaceDetailData); bResult = SetupDiDestroyDeviceInfoList(hDeviceInfo); return bResult; } //copy device path size_t nLength = wcslen(pInterfaceDetailData->DevicePath) + 1; lpDevicePath = (TCHAR *)LocalAlloc(LPTR, nLength * sizeof(TCHAR)); StringCchCopy(lpDevicePath, nLength, pInterfaceDetailData->DevicePath); lpDevicePath[nLength - 1] = 0; printf("Device path: %s\n", lpDevicePath); } if(!lpDevicePath) { //Error. printf("Error %d.", GetLastError()); LocalFree(lpDevicePath); LocalFree(pInterfaceDetailData); bResult = SetupDiDestroyDeviceInfoList(hDeviceInfo); return bResult; } //Open the device *hDeviceHandle = CreateFile(lpDevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if(*hDeviceHandle == INVALID_HANDLE_VALUE) { //Error. printf("Error %d.", GetLastError()); LocalFree(lpDevicePath); LocalFree(pInterfaceDetailData); bResult = SetupDiDestroyDeviceInfoList(hDeviceInfo); return bResult; } LocalFree(lpDevicePath); LocalFree(pInterfaceDetailData); bResult = SetupDiDestroyDeviceInfoList(hDeviceInfo); return bResult; } BOOL GetWinUSBHandle(HANDLE hDeviceHandle, PWINUSB_INTERFACE_HANDLE phWinUSBHandle) { if(hDeviceHandle == INVALID_HANDLE_VALUE) return FALSE; BOOL bResult = WinUsb_Initialize(hDeviceHandle, phWinUSBHandle); if(!bResult) { printf("WinUsb_Initialize Error %d.", GetLastError()); return FALSE; } return bResult; } BOOL GetUSBDeviceSpeed(WINUSB_INTERFACE_HANDLE hDeviceHandle, UCHAR* pDeviceSpeed) { if(!pDeviceSpeed || hDeviceHandle == INVALID_HANDLE_VALUE) return FALSE; BOOL bResult = TRUE; ULONG length = sizeof(UCHAR); bResult = WinUsb_QueryDeviceInformation(hDeviceHandle, DEVICE_SPEED, &length, pDeviceSpeed); if(!bResult) { printf("Error getting device speed: %d.\n", GetLastError()); return bResult; } if(*pDeviceSpeed == LowSpeed) { printf("Device speed: %d (Low speed).\n", *pDeviceSpeed); return bResult; } if(*pDeviceSpeed == FullSpeed) { printf("Device speed: %d (Full speed).\n", *pDeviceSpeed); return bResult; } if(*pDeviceSpeed == HighSpeed) { printf("Device speed: %d (High speed).\n", *pDeviceSpeed); return bResult; } return bResult; } BOOL QueryDeviceEndpoints(WINUSB_INTERFACE_HANDLE hDeviceHandle, PIPE_ID* pipeid) { if(hDeviceHandle == INVALID_HANDLE_VALUE) return FALSE; BOOL bResult = TRUE; USB_INTERFACE_DESCRIPTOR InterfaceDescriptor; ZeroMemory(&InterfaceDescriptor, sizeof(USB_INTERFACE_DESCRIPTOR)); WINUSB_PIPE_INFORMATION Pipe; ZeroMemory(&Pipe, sizeof(WINUSB_PIPE_INFORMATION)); bResult = WinUsb_QueryInterfaceSettings(hDeviceHandle, 0, &InterfaceDescriptor); if(bResult) { for(int index = 0; index < InterfaceDescriptor.bNumEndpoints; index++) { bResult = WinUsb_QueryPipe(hDeviceHandle, 0, index, &Pipe); if(bResult) { if(Pipe.PipeType == UsbdPipeTypeControl) { printf("Endpoint index: %d Pipe type: Control Pipe ID: %d.\n", index, Pipe.PipeType, Pipe.PipeId); } if(Pipe.PipeType == UsbdPipeTypeIsochronous) { printf("Endpoint index: %d Pipe type: Isochronous Pipe ID: %d.\n", index, Pipe.PipeType, Pipe.PipeId); } if(Pipe.PipeType == UsbdPipeTypeBulk) { if(USB_ENDPOINT_DIRECTION_IN(Pipe.PipeId)) { printf("Endpoint index: %d Pipe type: Bulk Pipe ID: %c.\n", index, Pipe.PipeType, Pipe.PipeId); pipeid->PipeInId = Pipe.PipeId; } if(USB_ENDPOINT_DIRECTION_OUT(Pipe.PipeId)) { printf("Endpoint index: %d Pipe type: Bulk Pipe ID: %c.\n", index, Pipe.PipeType, Pipe.PipeId); pipeid->PipeOutId = Pipe.PipeId; } } if(Pipe.PipeType == UsbdPipeTypeInterrupt) { printf("Endpoint index: %d Pipe type: Interrupt Pipe ID: %d.\n", index, Pipe.PipeType, Pipe.PipeId); } } else { continue; } } } return bResult; } ULONG send_config(WINUSB_INTERFACE_HANDLE h, PIPE_ID p, PUCHAR bf) { ULONG bytes; WinUsb_WritePipe(h, p.PipeOutId, bf, 64, &bytes, NULL); WinUsb_ReadPipe(h, p.PipeInId, bf, 64, &bytes, NULL); if(bf[0] != USBCONTROL_RESPONSE) { return -1; // char chbuf[32]; // sprintf_s(chbuf, 32, "Error: 0x%02X", bf[0]); // QPushButton button(chbuf); // button.resize(250, 100); // button.show(); // while(!button.isChecked()); // exit(-1); } return bytes; }
true
65bbf45780dddc2fa1a7750924ad9cfd46d425bb
C++
xiweihuang/Primer
/chapter10/r_iter.cpp
UTF-8
1,517
3.375
3
[]
no_license
// 反向迭代器 #include <stdio.h> #include <vector> #include <list> #include <string> using namespace std; void r_iter() { vector<int> vec = {0, 1, 2, 3, 4, 5}; for (auto iter = vec.crbegin(); iter != vec.crend(); ++iter) { printf("%d\n", *iter); } } void exercise_10_34(); void exercise_10_35(); void exercise_10_36(); void exercise_10_37(); void exercise_10_42(); int main() { // r_iter(); // exercise_10_34(); // exercise_10_35(); // exercise_10_36(); // exercise_10_37(); exercise_10_42(); return 0; } void exercise_10_34() { vector<int> vec = {1, 2, 3, 4, 5}; for (auto iter = vec.crbegin(); iter != vec.crend(); ++iter) { printf("%d\n", *iter); } } void exercise_10_35() { vector<int> vec = {1, 2, 3, 4, 5}; for (auto iter = --(vec.cend()); iter != --(vec.begin()); --iter) { printf("%d\n", *iter); } } void exercise_10_36() { list<int> lst = {0, 1, 2, 3, 4, 5, 0, 6, 7}; auto iter = find(lst.rbegin(), lst.rend(), 0); printf("%d\n", *iter); printf("%d\n", *(++iter)); } void exercise_10_37() { vector<int> vec = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; list<int> lst; copy(vec.rbegin()+3, vec.rbegin()+8, back_inserter(lst)); for (auto &val : lst) { printf("%d\n", val); // 6 5 4 3 2 } } void exercise_10_42() { // sort() list<string> lst = {"Kobe", "Jordan", "Kobe", "James", "Durcant"}; lst.sort([](const string &s1, const string &s2){ return s1.size() < s2.size(); }); lst.unique(); lst.sort(); for (auto &val : lst) { printf("%s\n", val.c_str()); } }
true
6af2b69e4656e58bbf365d4a7997a7689980eec3
C++
leag37/RayTracer
/SuperTrace/SuperTrace/include/Ray.h
UTF-8
2,463
3.328125
3
[]
no_license
//************************************************************************************************* // Title: Ray.h // Author: Gael Huber // Description: This class defines a ray used for projecting light and intersection tests //************************************************************************************************* #ifndef __STRAY_H__ #define __STRAY_H__ #include "Vector3.h" #include <limits> namespace SuperTrace { /** \addtogroup Math * @{ */ // Enum for different ray types enum RayType { RAY_TYPE_UNKNOWN = 0, RAY_TYPE_CAMERA, RAY_TYPE_SHADOW }; class Ray { public: /** Contructor */ Ray(const Vector3& origin, const Vector3& direction, RayType type = RAY_TYPE_UNKNOWN, float tMin = 0.0f, float tMax = FLT_MAX); /** Parametric operator * @param * t Find the endpoint at the corresponding time * @return * Vector3 The vector to the end point */ Vector3 operator() (float t) const; /** Get the origin of the ray * @return * Vector3 Origin of the ray */ const Vector3& getOrigin() const; /** Get the direction of the ray * @return * Vector3 The direction of the ray */ const Vector3& getDirection() const; /** Return the type * @return * RayType The ray type */ RayType getType() const; /** Return the current tMin value * @return * float tMin */ float getTMin() const; /** Set tMin * @param * tMin The new tMin value */ void setTMin(float tMin) const; /** Return the current tMax value * @return * float tMax */ float getTMax() const; /** Set tMax * @param * tMax The new tMax value */ void setTMax(float tMax) const; /** Get the inverse direction * @return * Vector3 The inverse direction */ const Vector3& getInvDirection() const; /** Get the array of signs * @return * const int* The pointer to the signs */ const int* getSign() const; private: /** Origin point */ Vector3 _origin; /** Ray direction */ Vector3 _direction; /** The ray type */ RayType _type; /** Ray minimum distance */ mutable float _tMin; /** Ray maximum distance */ mutable float _tMax; /** Inverted direction */ Vector3 _invDirection; /** Signs for inverted direction */ int _sign[3]; }; /** @} */ } // Namespace #endif // __STRAY_H__
true
6b612015391a16b295d7224d675c33cf87a6fe7d
C++
stillwater-sc/hpr-blas
/applications/apf/cpp_apfloat.cpp
UTF-8
3,769
2.71875
3
[ "MIT" ]
permissive
#include <boost/multiprecision/cpp_bin_float.hpp> #include <boost/math/special_functions/gamma.hpp> #include <iostream> #include <universal/native/ieee754.hpp> #include <universal/number/cfloat/cfloat.hpp> const char* pistr = "3.141592653589793238462643383279"; constexpr float pi = 3.141592653589793238462643383279; // 3.14159265358979311599796346854 // B 8 4 | = 15 digits of accuracy int main() { using namespace sw::universal; using namespace boost::multiprecision; /* cfloat print behavior you need to emulate: native single precision : 0b0.11111110.00000000000000000000000 : 170141183460469231731687303715884105728.0000000000 <-- fixed format takes precision as the number of bits after the fixed point cfloat single precision : 0b0.11111110.00000000000000000000000 : 170141183460469231731687303715884105728.00000000000000000000000 <-- you are taking the precision of the mantissa boost single precision : : 170141183460469231731687303715884105728.0000000000 native single precision : 0b0.11111110.00000000000000000000000 : 1.7014118346e+38 <-- scientific format takes precision as the number of bits after the decimal point cfloat single precision : 0b0.11111110.00000000000000000000000 : 1.70141e+38 <-- you are not honoring precision boost single precision : : 1.7014118346e+38 */ auto oldPrecision = std::cout.precision(); constexpr std::streamsize newPrecision = 10; { float v = 1.0f * pow(2.0f, 127.0f); float spnat = v; cfloat<32, 8, uint32_t, true> spcf = v; cpp_bin_float_single spmp = v; std::cout << std::setprecision(newPrecision); std::cout << std::fixed; std::cout << "native single precision : " << to_binary(spnat) << " : " << spnat << '\n'; std::cout << "cfloat single precision : " << to_binary(spcf) << " : " << spcf << '\n'; std::cout << "boost single precision : " << " " << " : " << spmp << '\n'; std::cout << std::scientific; std::cout << "native single precision : " << to_binary(spnat) << " : " << spnat << '\n'; std::cout << "cfloat single precision : " << to_binary(spcf) << " : " << spcf << '\n'; std::cout << "boost single precision : " << " " << " : " << spmp << '\n'; std::cout << spmp << '\n'; std::cout << std::setw(newPrecision) << std::string(pistr) << '\n'; } return 0; { cpp_bin_float_quad qp(pistr); std::cout << "quad precision : " << qp << '\n'; std::cout << std::setprecision(newPrecision); std::cout << std::setw(30) << qp << '\n'; std::cout << std::setw(30) << std::string(pistr) << '\n'; } std::cout << std::setprecision(oldPrecision); return 0; { // Operations at fixed precision and full numeric_limits support: cpp_bin_float_100 b = 2; std::cout << std::numeric_limits<cpp_bin_float_100>::digits << std::endl; std::cout << std::numeric_limits<cpp_bin_float_100>::digits10 << std::endl; // We can use any C++ std lib function, lets print all the digits as well: std::cout << std::setprecision(std::numeric_limits<cpp_bin_float_100>::max_digits10) << log(b) << std::endl; // print log(2) // We can also use any function from Boost.Math: std::cout << boost::math::tgamma(b) << std::endl; // These even work when the argument is an expression template: std::cout << boost::math::tgamma(b * b) << std::endl; // And since we have an extended exponent range we can generate some really large // numbers here (4.0238726007709377354370243e+2564): std::cout << boost::math::tgamma(cpp_bin_float_100(1000)) << std::endl; } return 0; }
true
0f01e621f1e89eea82950c84585d063eadfd3e5b
C++
brujackie-zhang/Experiences
/data structure/countSort.cpp
UTF-8
451
3.328125
3
[]
no_license
#include<stdio.h> int countSort(int a[], int n) { int maxLen = n + 1; int b[maxLen]; int index = 0; for (int i = 0; i < n; i ++) { if (!b[a[i]]) { b[a[i]] = 0; } b[a[i]] ++; } for (int j = 0; j < maxLen; j ++) { while (b[j] > 0) { a[index ++] = j; b[j] --; } } return *a; } int main() { int a[10] = {15,7,45,96,1,52,6,3,0,78}; countSort(a, 10); for (int i = 0; i < 10; i ++) { printf("%d ", a[i]); } printf("\n"); }
true
0a33b7bb9ea1bb06ebcfecf7c930907706ae93b2
C++
michlord/AngryJets
/Game/Ground.h
UTF-8
980
2.734375
3
[]
no_license
#ifndef GROUND_H #define GROUND_H #include <SFML/Graphics.hpp> #include "Collidable.h" #include <vector> namespace game{ class Ground : public sf::Drawable, public Collidable { public: Ground(const sf::Texture& background_,const sf::Texture& foreground_, const sf::Image& mask_); void makeCircleHole(sf::Vector2f position, float radius=1.0f); void makeSquareHole(sf::Vector2f position, int size=1); std::vector<sf::Vector2f> makeSquareHoleGetPixels(sf::Vector2f position, int size=1); void makeSpriteHole(sf::Sprite sprite); sf::Sprite getCollisionSprite(); sf::Color getAlphaColor(); const sf::Image* getCollisionMask(); void setScale(float scale=1.0f); sf::Vector2f getSize(); private: sf::Sprite sprite; sf::Texture background; sf::Texture foreground; sf::Image mask; private: virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; }; } #endif /* GROUND_H */
true
12e94e37464b54d13d7c696a7527c88bcee0a64b
C++
nastaranrezai/tamrin-2
/سوال 4.cpp
UTF-8
459
2.671875
3
[]
no_license
#include <iostream> #include <conio.h> #include <string.h> using namespace std; int main() { int n, i, j, min= 21, max= 0, sum = 0; cout <<"tedad daneshjo:"; cin >> n; for(i = 0; i < a; i++) { cin >> j; sum += j; if(j <= min ) min = j; if(j >= max) max = j; } float avg = (float)sum / n; cout <<"avg :"<< avg << "\n"; cout <<"min :"<< min << "\n"; cout <<"max :"<< max << "\n"; return 0; }
true
2e55ff07b79863c021350a9d5a102c14984657ba
C++
Dwillnio/ConBox
/base/function_data.h
UTF-8
457
2.546875
3
[]
no_license
#ifndef FUNCTION_DATA_H #define FUNCTION_DATA_H #include <vector> #include "function.h" class function_data : public function { public: function_data(std::vector<vec>* data_points_, rnum dt_) : function(1, (*data_points_)[0].dimension()), dt(dt_) {} virtual vec value(const vec &x); virtual vec value(nnum k) {return (*data_points)[k];} protected: const std::vector<vec>* data_points; rnum dt; }; #endif // FUNCTION_DATA_H
true
d332efd82f6bfb502f1baf78b3d00b50ddc50f25
C++
gitliuyuhan/Algorithm
/min_edit_distance.cpp
UTF-8
1,548
3.640625
4
[]
no_license
/*====================================================== > File Name: min_edit_distance.cpp > Author: lyh > E-mail: > Other : 字符串的最短编辑距离 > Created Time: 2016年05月06日 星期五 08时55分36秒 =======================================================*/ #include<iostream> #include<string.h> int min(int a,int b,int c) { int min = a < b ? a : b; return (min < c ? min : c); } //str1经过插入或删除或替换变为str2的最小操作次数 int minEditDistance(char* str1,char* str2) { const int len1 = strlen(str1+1); const int len2 = strlen(str2+1); int dp[len1+1][len2+1] = {0}; //dp[i][j] str1的前i个字符与str2的前j个字符的最小编辑距离 for(int i = 0;i<=len1;i++) { for(int j = 0;j<=len2;j++) { if(i==0 && j==0) //dp[0][0]设置为0 dp[i][j] = 0; if(i==0 && j>0) dp[i][j] = j; if(j==0 && i>0) dp[i][j] = i; if(i>0 && j>0) { if(str1[i] == str2[j]) dp[i][j] = dp[i-1][j-1] + 0; else //删除,插入,替换三种操作比较 dp[i][j] = min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+1); } } } return dp[len1][len2]; } int main() { char str1[1000]; char str2[1000]; std::cin>>str1+1>>str2+1; //字符串下标从1开始 std::cout<<minEditDistance(str1,str2)<<std::endl; return 0; }
true
e23f64f3b16c7270a5a571c969942bfad38e6095
C++
nowaits/base
/third/circularbuffer.cpp
UTF-8
3,271
2.796875
3
[]
no_license
#include "circularbuffer.h" #include <windows.h> namespace vncjingle { CircularBuffer::CircularBuffer(int size) { capacity_ = size; store_ = new char[capacity_]; read_pos_ = 0; write_pos_ = 0; cached_length_ = 0; done_ = false; } //----------------------------------------------------------------------------- CircularBuffer::~CircularBuffer() { delete store_; store_ = 0; } //----------------------------------------------------------------------------- int CircularBuffer::Length() { //talk_base::CritScope lock(&lock_); if (write_pos_ >= read_pos_) { return write_pos_ - read_pos_; } else { return (capacity_ - read_pos_) + write_pos_; } } //----------------------------------------------------------------------------- int CircularBuffer::AvailableCapacity() { return capacity_ - Length(); } //----------------------------------------------------------------------------- bool CircularBuffer::Read(const char *buffer, int length, bool blocking, bool peek) { /* * Wait until enough data has arrived. */ while (cached_length_ < length && (cached_length_ = Length()) < length) { if (!blocking || done_) { return false; } ::Sleep(10); } cached_length_ -= length; /* * Read data. */ int read_end_ = read_pos_; if (capacity_ - read_pos_ >= length) { // Enough data without wrapping. memcpy((void*)buffer, store_ + read_pos_, length); read_end_ = read_pos_ + length; } else { // Handle wrap around. int available = capacity_ - read_pos_; memcpy((void*)buffer, store_ + read_pos_, available); length -= available; buffer += available; memcpy((void*)buffer, store_, length); read_end_ = length; } /* * Update the read pointer. */ if (!peek) { //talk_base::CritScope lock(&lock_); read_pos_ = read_end_; if (read_pos_ == capacity_) { read_pos_ = 0; } } return true; } //----------------------------------------------------------------------------- void CircularBuffer::ReadSkip(int length) { //>talk_base::CritScope lock(&lock_); if (read_pos_ + length > capacity_) { length -= capacity_ - read_pos_; read_pos_ = length; } else { read_pos_ += length; } if (read_pos_ == capacity_) { read_pos_ = 0; } } //----------------------------------------------------------------------------- void CircularBuffer::Write(const char *buffer, int length) { /* * Wait until there is space for new data. */ while (AvailableCapacity() < length) { if (done_) { return; } ::Sleep(10); } /* * Write the data. */ if (capacity_ - write_pos_ >= length) { // Enough data without wrapping. memcpy(store_ + write_pos_, buffer, length); write_pos_ = write_pos_ + length; if (write_pos_ == capacity_) { write_pos_ = 0; } } else { // Handle wrap around. int available = capacity_ - write_pos_; memcpy(store_ + write_pos_, buffer, available); length -= available; buffer += available; memcpy(store_, buffer, length); write_pos_ = length; if (write_pos_ == capacity_) { write_pos_ = 0; } } } //----------------------------------------------------------------------------- } // Namespace vncjingle
true
cb4cbc4ea5f1ace9f05404580078747ba25917bb
C++
LataSinha/Coding-Ninjas-Data-Structures-In-CPP
/OOPS-1/Student_class.cpp
UTF-8
345
3.453125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; class Student{ public: int age; int rollnumber; }; int main(){ Student s1; s1.age = 20; s1.rollnumber = 101; cout << s1.age << " " << s1.rollnumber << endl; Student* s2 = new Student; s2->age = 25; s2->rollnumber = 102; cout << s2->age << " " << s2->rollnumber << endl; return 0; }
true
7dad041a0516b189c7b788238f17c4c923149c51
C++
yuanjinsongquyi/ndktest
/app/src/main/cpp/VideoDecode.cpp
UTF-8
5,890
2.53125
3
[]
no_license
// // Created by 袁劲松 on 18/9/12. // extern "C" { #include <libavutil/imgutils.h> #include <libavutil/time.h> } #include "VedioDecode.h" #include "macro.h" void releaseAvPacket(AVPacket** packet) { if (packet) { av_packet_free(packet); //为什么用指针的指针? // 指针的指针能够修改传递进来的指针的指向 *packet = 0; } } void releaseAvFrame(AVFrame** frame) { if (frame) { av_frame_free(frame); //为什么用指针的指针? // 指针的指针能够修改传递进来的指针的指向 *frame = 0; } } /** * 丢包 直到下一个关键帧 * BIP帧 * @param q */ void dropAvPacket(queue<AVPacket *> &q) { while (!q.empty()) { AVPacket *packet = q.front(); //如果不属于 I 帧 if (packet->flags != AV_PKT_FLAG_KEY) { releaseAvPacket(&packet); q.pop(); } else { break; } } } /** * 丢已经解码的图片 * @param q */ void dropAvFrame(queue<AVFrame *> &q) { if (!q.empty()) { AVFrame *frame = q.front(); releaseAvFrame(&frame); q.pop(); } } void* palyTask(void* arg){ VedioDecode *vedioDecode = static_cast<VedioDecode*> (arg); vedioDecode->doPlay(); return 0; } void* decodeTask(void* arg){ VedioDecode *vedioDecode = static_cast<VedioDecode*> (arg); vedioDecode->doDecode(); return 0; } VedioDecode::VedioDecode(int type,AVCodecContext *context,int fps,AVRational timebase) { this->type = type; this->context = context; queue_frame.setReleaseCallback(releaseAvFrame); this->fps = fps; this->timebase = timebase; } VedioDecode::~VedioDecode() { queue_frame.clear(); } void VedioDecode::play() { isplaying=1; //创建两个线程一个用于播放,一个用于解码 queue_frame.setWork(1); queue.setWork(1); pthread_create(&thread_decode,0,decodeTask,this); pthread_create(&thread_play,0,palyTask,this); } void VedioDecode::doDecode() { AVPacket* avPacket = 0; int ret = 0; while (isplaying) { ret = queue.pop(avPacket); if (!isplaying) { break; } if (!ret){ continue; } //将队列里待解码的包传给解码器 ret=avcodec_send_packet(context,avPacket); //释放packet releaseAvPacket(&avPacket); if(ret!=0){ break; } //获得一个包的具体图像 AVFrame* frame = av_frame_alloc(); ret=avcodec_receive_frame(context,frame); if (ret==AVERROR(EAGAIN)){ //需要更多的packet才能够完整的展现一个frame画面 continue; }else if (ret!=0){ break; } //开一个线程去播放frame queue_frame.push(frame); } releaseAvPacket(&avPacket); } void VedioDecode::doPlay() { //将frame的yua格式的数据转换为RGBf格式画到surfaceview上 swsContext = sws_getContext( context->width, context->height,context->pix_fmt, context->width, context->height,AV_PIX_FMT_RGBA, SWS_BILINEAR,0,0,0); AVFrame* frame = 0; //指针数组 uint8_t *dst_data[4]; int dst_linesize[4]; av_image_alloc(dst_data, dst_linesize, context->width, context->height,AV_PIX_FMT_RGBA, 1); double frame_delays = 1.0 / fps; while (isplaying){ int ret = queue_frame.pop(frame); if (!isplaying){ break; } //src_linesize: 表示每一行存放的 字节长度 sws_scale(swsContext, reinterpret_cast<const uint8_t *const *>(frame->data), frame->linesize, 0, context->height, dst_data, dst_linesize); #if 1 //获得 当前这一个画面 播放的相对的时间 double clock = frame->best_effort_timestamp * av_q2d(timebase); //额外的间隔时间 double extra_delay = frame->repeat_pict / (2 * fps); // 真实需要的间隔时间 double delays = extra_delay + frame_delays; if (!audioChannel) { //休眠 // //视频快了 // av_usleep(frame_delays*1000000+x); // //视频慢了 // av_usleep(frame_delays*1000000-x); av_usleep(delays * 1000000); } else { if (clock == 0) { av_usleep(delays * 1000000); } else { //比较音频与视频 double audioClock = audioChannel->clock; //间隔 音视频相差的间隔 double diff = clock - audioClock; if (diff > 0) { //大于0 表示视频比较快 LOGE("视频快了:%lf",diff); av_usleep((delays + diff) * 1000000); } else if (diff < 0) { //小于0 表示音频比较快 LOGE("音频快了:%lf",diff); // 视频包积压的太多了 (丢包) if (fabs(diff) >= 0.05) { releaseAvFrame(&frame); //丢包 queue_frame.sync(); continue; }else{ //不睡了 快点赶上 音频 } } } } #endif //回调出去进行播放 callplay(dst_data[0],dst_linesize[0],context->width, context->height); releaseAvFrame(&frame); } av_freep(&dst_data[0]); releaseAvFrame(&frame); } void VedioDecode::setCallPlay(callPlay callplay) { this->callplay = callplay; } void VedioDecode::setAudioChannel(AudioChannel *audioChannel) { this->audioChannel = audioChannel; }
true
ddd0d7156d5d9e31b9ea04fe716355a7d8fc8d2f
C++
xamex/lab02
/include/questao2/util.h
UTF-8
2,324
3.453125
3
[]
no_license
/** * @file util.h * @brief Arquivo de cabeçalho contendo as definições de funções que realizam * operações utilizadas em várias partes do programa. * @author Gabriel Barbosa (gbsbarbosa.gb@gmail.com) * @since 23/06/2017 * @date 25/06/2017 */ #ifndef UTIL_H #define UTIL_H #include <iostream> using std::cin; using std::cout; using std::endl; using std::cerr; #include <string> #include <limits> //numeric_limits #include <new> using std::bad_alloc; namespace util{ /** * @brief Função que limpa o terminal do linux usando ANSI escape codes * @details para mais detalher, acesse o link deixado como comentário ao lado do comando. */ void limpa_tela(); /** * @brief Função que realiza o tratamento de algumas entradas do usuário * verificando se são válidas ou não. * @details parte da função retirada do link: http://stackoverflow.com/questions/4798936/numeric-limits-was-not-declared-in-this-scope-no-matching-function-for-call-t * @param num int a ser testado */ void invalida(float &num); /** * @brief Função que realiza o tratamento de algumas entradas do usuário * verificando se são válidas ou não. * @details parte da função retirada do link: http://stackoverflow.com/questions/4798936/numeric-limits-was-not-declared-in-this-scope-no-matching-function-for-call-t * @param num float a ser testado */ void invalida(int &num); /** * @brief Função que limpa todo o buffer. */ void limpa_buffer(); /** * @brief Função template que imprime os elementors do vetor passado * @param v vetor onde ocorrerá a busca * @param tam tamanho do vetor */ template<typename T> void print_array(T *v, int tam){ cout << endl << endl; for (int i = 0; i < tam; ++i) { cout << v[i] << ' '; } cout << endl << endl; } /** * @brief Função template que faz a verificação do elemento pasasdo pelo usuário * antes de inserir ele no vetor informado. * @param v vetor onde ocorrerá a alteração * @param tam tamanho do vetor */ template<typename T> void entra_elementos(T *(&v), int tam) { T aux; for (int i = 0; i < tam; ++i) { invalida(aux); // resolvi usar a função invalida() em vez da erro_tamanho() por ela aceitar numeros negativos. v[i] = aux; } } } #endif
true
24d6b5db2a375ffed211211eb7fa874d2bb6b78f
C++
CynicalHeart/clion_CV
/Demo_ch7/sources/Demo_ch7_3.cpp
GB18030
4,424
2.625
3
[]
no_license
#include "../header/Demo_ch7_3.h" Mat g_srcImage,g_dstImage; Mat g_map_x,g_map_y; void CVMap_Demo() { ShowHelpText(); g_srcImage = imread("F:\\Ѷ\\ͼ\\chouyou.jpg"); if(!g_srcImage.data){ cout<<"ȡͼƬ"<<endl; } imshow("ԭʼͼ", g_srcImage); g_dstImage.create(g_srcImage.size(),g_srcImage.type()); g_map_x.create(g_srcImage.size(),CV_32FC1); g_map_y.create(g_srcImage.size(),CV_32FC1); namedWindow(WINDOW_NAME, WINDOW_AUTOSIZE); imshow(WINDOW_NAME, g_srcImage); while(1){ int key = waitKey(0); if((key&255) == 27){ cout<<"˳"<<endl; break; } update_map(key); remap(g_srcImage, g_dstImage, g_map_x, g_map_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0)); imshow(WINDOW_NAME, g_dstImage); } } void ShowHelpText() { cout<<"ӳʾ"<<endl; cout<<"ǰopenCV汾Ϊ"<<CV_VERSION<<endl; cout<<endl; cout<<"˵:"<<endl; cout<<"\t̰ESC - ˳"<<endl; cout<<"\t̰1 - һӳ䷽ʽ"<<endl; cout<<"\t̰2 - ڶӳ䷽ʽ"<<endl; cout<<"\t̰3 - ӳ䷽ʽ"<<endl; cout<<"\t̰4 - ӳ䷽ʽ"<<endl; } int update_map(int key) { for (int i = 0; i <g_srcImage.rows ; ++i) { for (int j = 0; j <g_srcImage.cols ; ++j) { switch(key){ case '1': if(j>g_srcImage.cols*0.25&&j<g_srcImage.cols*0.75&&i>g_srcImage.rows*0.25&&i<g_srcImage.rows*0.75) { g_map_x.at<float>(i,j) = static_cast<float>(2*(j-g_srcImage.cols*0.25)+0.5); g_map_y.at<float>(i,j) = static_cast<float>(2*(i-g_srcImage.rows*0.25)+0.5); } else{ g_map_x.at<float>(i,j) = 0; g_map_y.at<float>(i, j) = 0; } break; case '2': g_map_x.at<float>(i,j) = static_cast<float>(j); g_map_y.at<float>(i, j) = static_cast<float>(g_srcImage.rows-i); break; case '3': g_map_x.at<float>(i, j) = static_cast<float>(g_srcImage.cols - j); g_map_y.at<float>(i,j) = static_cast<float>(i); break; case '4': g_map_x.at<float>(i, j) = static_cast<float>(g_srcImage.cols - j); g_map_y.at<float>(i, j) = static_cast<float>(g_srcImage.rows - i); break; } } } return 1; } void Affine_Demo() { ShowHelpText_2(); Point2f srcTriangle[3]; Point2f dstTriangle[3]; Mat rotMat(2, 3, CV_32FC1); Mat warpMat(2, 3, CV_32FC1); Mat srcImage, dstImage_warp, dstImage_warp_rotate; srcImage = imread("F:\\Ѷ\\ͼ\\67814952_p0_master1200.jpg"); dstImage_warp = Mat::zeros(srcImage.rows, srcImage.cols, srcImage.type()); //ԭͼӦĿͼ srcTriangle[0] = Point2f(0, 0); srcTriangle[1] = Point2f(static_cast<float>(srcImage.cols - 1), 0); srcTriangle[2] = Point2f(0, static_cast<float>(srcImage.rows-1)); dstTriangle[0] = Point2f(static_cast<float>(srcImage.cols*0.0), static_cast<float>(srcImage.rows*0.33)); dstTriangle[1] = Point2f(static_cast<float>(srcImage.cols*0.65), static_cast<float>(srcImage.rows*0.35)); dstTriangle[2] = Point2f(static_cast<float>(srcImage.cols*0.15), static_cast<float>(srcImage.rows*0.6)); //ķ任 warpMat = getAffineTransform(srcTriangle, dstTriangle); //Ӧ÷任 warpAffine(srcImage, dstImage_warp, warpMat, dstImage_warp.size()); //ͼźת Point center = Point(dstImage_warp.cols/2,dstImage_warp.rows/2); double angle = -30; double scale = 0.8; //ת rotMat = getRotationMatrix2D(center, angle, scale); //תѾźͼ warpAffine(dstImage_warp,dstImage_warp_rotate,rotMat,dstImage_warp.size()); imshow(WINDOW_NAME1, srcImage); imshow(WINDOW_NAME2, dstImage_warp); imshow(WINDOW_NAME3, dstImage_warp_rotate); waitKey(0); } void ShowHelpText_2() { cout<<"ӭ任ʾ"<<endl; cout<<"\tǰʹõOpenCV汾Ϊ"<<CV_VERSION<<endl; }
true
141aa58bbc429fab418d73f1b4ef5e9c181d18fa
C++
ahans/hoerbert-clone
/wavreader/wavreader.h
UTF-8
1,489
2.578125
3
[]
no_license
#include <fstream> namespace de { namespace ahans { class WavReader { public: #pragma pack(push, 1) struct WavHeader { unsigned char riff[4]; // RIFF string unsigned int overall_size; // overall size of file in bytes unsigned char wave[4]; // WAVE string unsigned char fmt_chunk_marker[4]; // fmt string with trailing null char unsigned int length_of_fmt; // length of the format data unsigned char format_type[2]; // format type. 1-PCM, 3- IEEE float, 6 - 8bit A law, 7 - 8bit mu law unsigned char channels[2]; // no.of channels unsigned int sample_rate; // sampling rate (blocks per second) unsigned int byterate; // SampleRate * NumChannels * BitsPerSample/8 unsigned char block_align[2]; // NumChannels * BitsPerSample/8 unsigned short bits_per_sample; // bits per sample, 8- 8bits, 16- 16 bits etc unsigned char data_chunk_header[4]; // DATA string or FLLR string unsigned int data_size; // NumSamples * NumChannels * BitsPerSample/8 - size of the next chunk that will be read }; #pragma pack(pop) public: WavReader(); ~WavReader(); bool open(const char* filename); void close(); size_t read(char* buf, size_t max_size); const WavHeader& getHeader() const; private: std::ifstream file_; WavHeader header_; }; } } // namespace
true
7bb8125af01d165dad7a726ffad836f8b42eb63f
C++
triffon/oop-2014-15
/player/superhero.cpp
UTF-8
1,547
2.96875
3
[ "MIT" ]
permissive
/* * superhero.cpp * * Created on: 7.05.2015 г. * Author: trifon */ #include <cstring> #include "superhero.h" SuperHero::SuperHero(const char* _name, int _pts, int _level, const char* _sp, int _linc) : Hero(_name, _pts, _level), Player(_name, _pts), levelIncrease(_linc), usingSP(false) { setSuperPower(_sp); } SuperHero::SuperHero(const SuperHero& sh) : Hero(sh), levelIncrease(sh.levelIncrease), usingSP(sh.usingSP) { setSuperPower(sh.superPower); } SuperHero& SuperHero::operator=(const SuperHero& sh) { if (this != &sh) { levelIncrease = sh.levelIncrease; usingSP = sh.usingSP; delete[] superPower; setSuperPower(sh.superPower); } return *this; } SuperHero::~SuperHero() { delete[] superPower; } void SuperHero::print() const { Hero::print(); cout << *this; } void SuperHero::setSuperPower(const char* _sp) { // TODO: да се сложи ограничение на дължината на superPower superPower = new char[strlen(_sp) + 1]; strcpy(superPower, _sp); } int SuperHero::getLevel() const { if (usingSP) { // !!! return ((Hero*)this)->getLevel() + levelIncrease; return Hero::getLevel() + levelIncrease; } // !!! return ((Hero*)this)->getLevel(); return Hero::getLevel(); } ostream& operator<<(ostream& os, SuperHero const& sh) { return os << ", но може да стане супергерой със суперсила " << sh.superPower << ", която дава увеличение на нивото " << sh.levelIncrease; }
true
83b31c95776abf89c14f5dd2af36bdb8c475548d
C++
neutronest/goodgoodstudy
/gcj/2013/round_qulification_a.cc
UTF-8
2,872
3.265625
3
[ "MIT" ]
permissive
#include <iostream> #include <cstdio> #include <vector> #include <string> using namespace std; class Solution { public: void solve(vector<string> board, int t) { int res = 0; int flag = 0; // check each row std::string s = ""; for (int r=0; r<4; r++) { s = board[r]; flag = isOver(s); if (flag != 0) { res = flag; } } // check each column for(int c=0; c<4; c++) { s = ""; for (int r=0; r<4; r++) { s += board[r][c]; } flag = isOver(s); if (flag != 0) { res = flag; } } // check diagonal s = ""; for(int i=0; i<4; i++) { s += board[i][i]; } flag = isOver(s); if (flag != 0) { res = flag; } s = ""; for(int i=3; i>=0; i--) { s += board[i][3-i]; } flag = isOver(s); if (flag != 0) { res = flag; } if (res == 1) { cout<<"Case #"<<t+1<<": "<<"X won"<<endl; return; } else if (res == -1) { cout<<"Case #"<<t+1<<": "<<"O won"<<endl; return; } else { // check if draw or uncompleted for(int r=0; r<4; r++) { for(int c=0; c<4; c++) { if (board[r][c] == '.') { cout<<"Case #"<<t+1<<": Game has not completed"<<endl; return; } } } cout<<"Case #"<<t+1<<": Draw"<<endl; return; } } int isOver(string str) { if (str.length() != 4) { //cout<<"What?"<<endl; return 0; } int playFlag = 0; for (int i=0; i<str.length(); i++) { char c = str[i]; if (c == '.') { return false; } else if (c == 'X') { if (playFlag == -1) { // exist 'O', conflict return 0; } playFlag = 1; } else if (c == 'O') { if (playFlag == 1) { // exist 'X', conflict return 0; } playFlag = -1; } else { // c == 'T' } } return playFlag; } }; int main() { int T; cin>>T; Solution solution = Solution(); vector<string> board = {}; for (int t=0; t<T; t++) { board.clear(); for(int i=0; i<4; i++) { string str; cin>>str; board.push_back(str); } solution.solve(board, t); } return 0; }
true
3c5256cd30a66c78292ca3ebb406bd425890ae07
C++
katyhuff/cycamore
/src/Models/Market/StubMarket/StubMarketTests.cpp
UTF-8
2,494
2.53125
3
[]
no_license
// StubMarketTests.cpp #include <gtest/gtest.h> #include "StubMarket.h" #include "CycException.h" #include "Message.h" #include "MarketModelTests.h" #include "ModelTests.h" #include <string> #include <queue> using namespace std; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class FakeStubMarket : public StubMarket { public: FakeStubMarket() : StubMarket() { } virtual ~FakeStubMarket() { } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class StubMarketTest : public ::testing::Test { protected: FakeStubMarket* src_market; FakeStubMarket* new_market; virtual void SetUp(){ src_market = new FakeStubMarket(); new_market = new FakeStubMarket(); }; virtual void TearDown() { delete src_market; delete new_market; } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Model* StubMarketModelConstructor(){ return dynamic_cast<Model*>(new FakeStubMarket()); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MarketModel* StubMarketConstructor(){ return dynamic_cast<MarketModel*>(new FakeStubMarket()); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(StubMarketTest, InitialState) { EXPECT_TRUE(true); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(StubMarketTest, CopyMarket) { new_market->copy(src_market); EXPECT_TRUE(true); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(StubMarketTest, CopyFreshModel) { new_market->copyFreshModel(dynamic_cast<Model*>(src_market)); // deep copy EXPECT_NO_THROW(dynamic_cast<StubMarket*>(new_market)); // still a source market EXPECT_NO_THROW(dynamic_cast<FakeStubMarket*>(new_market)); // still a fake source market } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(StubMarketTest, Print) { EXPECT_NO_THROW(std::string s = src_market->str()); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(StubMarketTest, ReceiveMessage) { msg_ptr msg; EXPECT_NO_THROW(src_market->receiveMessage(msg)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INSTANTIATE_TEST_CASE_P(StubMarket, MarketModelTests, Values(&StubMarketConstructor)); INSTANTIATE_TEST_CASE_P(StubMarket, ModelTests, Values(&StubMarketModelConstructor));
true
075412f5b80e254d4bf5de195f79f0fdcf2b0375
C++
serek8/JSONDeserializer
/JSONDeserializer/Parser.hpp
UTF-8
5,643
2.609375
3
[]
no_license
// // Parser.hpp // test // // Created by Jan Seredynski on 02/12/15. // Copyright © 2015 Jan Seredynski. All rights reserved. // #ifndef Parser_hpp #define Parser_hpp #include <string> #include <stdio.h> #include <string> #include <iostream> #include <vector> #include "ParserStringProxy.hpp" #define WHITE_SPACES_AMOUNT 3 #define NUMBER_OF_CHARS_TO_DISPLAY_IN_ERROR_FIRST_CHARS 15 enum class ParsingFlag { OK=0, INVALID_INPUT, END_OF_FILE }; class Parser { template<bool> struct _TPrimaryAdapter {}; template<bool> struct _TVectorAdapter {}; template<bool> struct _TStringProxyAdapter {}; template<bool> struct _TParsableAdapter {}; public: ~Parser(){} Parser(const char* source) :source_(source) ,overall_parsed_charts(0) ,flag_(ParsingFlag::OK) ,isFirstIteration_(true) { skip_white_spaces(); skip_start_new_scope(); //std::cout<<source_; } template <typename T> T parse(const char *key_name) { go_to_key(key_name); return fun<T>(_TPrimaryAdapter<std::is_pod<T>::value || std::is_same<std::string, T>::value>()); } template <typename T> T parse() { return fun<T>(_TPrimaryAdapter<std::is_pod<T>::value || std::is_same<std::string, T>::value>()); } template<typename T> T fun(_TPrimaryAdapter<true>) { return parse_primary<T>(); } template<typename T> T fun(_TPrimaryAdapter<false>) { return fun<T>(_TParsableAdapter<std::is_base_of<Parser, T>::value>()); } template<typename T> T fun(_TParsableAdapter<true>) { return parse_object<T>(); } template<typename T> T fun( _TParsableAdapter<false>) { return fun<T>(_TStringProxyAdapter<std::is_base_of<ParseStringProxy, T>::value>()); // return fun<T>(_TStringProxyAdapter<std::is_base_of<std::vector<typename T::value_type>, T>::value>()); } // template<typename T> T fun(_TStringProxyAdapter<true>) { return parse_primary<std::string>(); } template<typename T> T fun(_TStringProxyAdapter<false>) { // return fun<T>(_TParsableAdapter<std::is_base_of<Parser, T>::value>()); return fun<T>(_TVectorAdapter<std::is_same<std::vector<typename T::value_type>, T>::value>()); } // template<typename T> T fun(_TVectorAdapter<true>) { return parse_vector<T>(); } template<typename T> T fun( _TVectorAdapter<false>) { return parse_primary<std::string>(); throw_error_for_symbol(); //return T(); } public: const char* source() const { return source_; } template<typename T> T parse_primary() { } template <typename T> T parse_vector() { typedef typename T::value_type value_type; std::vector<typename T::value_type> vector; skip_a_mark('['); while(*source_ != '\0') { skip_white_spaces(); if( is_a_mark_next(']')) break; skip_white_spaces(); vector.push_back( value_type(parse<value_type>()) ); skip_white_spaces(); if(!is_a_mark_next(',')) break; skip_a_mark(','); skip_white_spaces(); } skip_white_spaces(); skip_a_mark(']'); return vector; } template <typename T> T parse_object() { skip_a_mark('{'); isFirstIteration_ = true; T object(*this); source_ = object.source(); isFirstIteration_ = false; skip_white_spaces(); skip_a_mark('}'); return object; } private: void skip_white_spaces(); void go_to_key(const char *key_name); std::string parse_number(); void skip_colon() { if (*source_==':') move_to_next_char(); else throw_error_for_symbol(':'); } void skip_coma() { if (*source_==',') move_to_next_char(); else throw_error_for_symbol(','); } void skip_start_new_scope() { if (*source_=='{') move_to_next_char(); else throw_error_for_symbol('{'); } void skip_end_scope() { if (*source_=='}') move_to_next_char(); else throw_error_for_symbol('}'); } void skip_quatation_mark() { if (*source_=='\"') move_to_next_char(); else throw_error_for_symbol('\"'); } inline void skip_a_mark(char mark) { if (*source_==mark) move_to_next_char(); else throw_error_for_symbol(mark); } inline bool is_a_mark_next(char mark) { return (*source_==mark); } bool is_quotation_mark_next() { return (*source_=='\"'); } void move_to_next_char(); void throw_error_for_symbol(char symbol = ' '); void throw_error_unsupported_object(); std::string int_to_string(int a) { return std::to_string(a); } ParsingFlag flag_; const char* source_; bool isFirstIteration_; unsigned int overall_parsed_charts; }; template <> int Parser::parse_primary<int>(); template <> float Parser::parse_primary<float>(); template <> double Parser::parse_primary<double>(); //template <> //unsigned int Parser::parse_primary<unsigned int>(); template <> bool Parser::parse_primary<bool>(); template <> std::string Parser::parse_primary<std::string>(); #endif /* Parser_hpp */
true
34f67bc98450cf1ed059aae7c669dd0d29ade885
C++
dmorse/util
/param/OptionalLabel.h
UTF-8
1,168
2.671875
3
[]
no_license
#ifndef UTIL_OPTIONAL_LABEL_H #define UTIL_OPTIONAL_LABEL_H /* * Util Package - C++ Utilities for Scientific Computation * * Copyright 2010 - 2017, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include <util/param/Label.h> namespace Util { /** * An optional Label string in a file format. * * A subclass of Label that is always optional. * * \ingroup Param_Module */ class OptionalLabel : public Label { public: /** * Default constructor. */ OptionalLabel(); /** * Constructor. * * \param string label string that precedes value in file format */ explicit OptionalLabel(std::string string); /** * Constructor. * * \param string label string that precedes value in file format */ explicit OptionalLabel(const char* string); /** * Copy constructor. * * \param other OptionalLabel being cloned. */ OptionalLabel(const OptionalLabel& other); /** * Destructor. */ virtual ~OptionalLabel(); }; } #endif
true
2e5dd4a87c5317c1e036ab0b505e0e19a30ef5aa
C++
mooniron/learn-cpp
/The cpp program language 4th/ch2/ex2-1-14.cpp
UTF-8
877
3.15625
3
[]
no_license
/************************************************************** * Name : ex2-1-14.cpp * Author : Bronze Lee * Version : 0.1 * Date : 2017年4月7日 **************************************************************/ /* example 2.4.3.1 : exceptions */ #include <iostream> using namespace std; double& Vector::operator[](int i) { if (i < 0 || size() <= i) { throw out_of_range {"Vector::operator[]"}; } // end if return elem[i]; } // end function operator[] void f(Vector& v) { // ... // exceptions here are handled by the hander defined below try { // try to access beyond the end of v v[v.size()] = 7; } // oops : out_of_range error catch(out_of_range) { // ... handle range error } // ... } // end function f
true
b3e6376c371b5c50d10e2bf09140e2afa71981f4
C++
Lukas1584/Accountant
/SRC/GUI/PasswordWidget.cpp
UTF-8
1,701
2.71875
3
[]
no_license
#include "PasswordWidget.h" PasswordWidget::PasswordWidget(){ drawWindow(); QObject::connect(pBtnOK,SIGNAL(clicked()),SLOT(slotClickedOk())); setModal(true); } void PasswordWidget::drawWindow(){ resize(400,150); pBtnOK=new QPushButton(tr("Ок")); pLeName= new QLineEdit; pLePassword=new QLineEdit; pLePassword->setEchoMode(QLineEdit::Password); pLePasswordConfirmation=new QLineEdit; pLePasswordConfirmation->setEchoMode(QLineEdit::Password); QLabel* pLblName=new QLabel(tr("Имя")); QLabel* pLblPassword=new QLabel(tr("Пароль")); QLabel* pLblPasswordConfirmation=new QLabel(tr("Подтверждение пароля")); QGridLayout* pGrdMain=new QGridLayout; pGrdMain->addWidget(pLblName,0,0,Qt::AlignRight); pGrdMain->addWidget(pLblPassword,1,0,Qt::AlignRight); pGrdMain->addWidget(pLblPasswordConfirmation,2,0,Qt::AlignRight); pGrdMain->addWidget(pLeName,0,1); pGrdMain->addWidget(pLePassword,1,1); pGrdMain->addWidget(pLePasswordConfirmation,2,1); pGrdMain->addWidget(pBtnOK,0,2); setLayout(pGrdMain); } void PasswordWidget::slotClickedOk(){ if(pLePassword->text()!=pLePasswordConfirmation->text()){ QMessageBox::information(this,tr("Сообщение"),tr("Пароли не совпадают!")); return; } //Задать рег выражение для логина if(pLeName->text()==""||pLeName->text()==" "){ QMessageBox::information(this,tr("Сообщение"),tr("Вы забыли указать имя!")); return; } emit clickedOk(pLeName->text(),pLePassword->text(),this); }
true
d7a1aa8b11e9bb7842c32dc2f9521f0ef86c6db9
C++
Dragos123321/Chess3D-infoeducatie
/Chess/Chess/src/piece.cpp
UTF-8
1,187
3.265625
3
[]
no_license
#include "piece.h" #include <string> Piece::Piece(int posX, int posY) : m_posX(posX), m_posY(posY) { } void Piece::init(int posX, int posY) { m_posX = posX; m_posY = posY; } Piece::~Piece() { // Empty } bool Piece::canMoveTo(int targetX, int targetY) { for (unsigned int i = 0 ; i < m_availableMovements.size() ; i++) { if (m_availableMovements[i][0] == targetX && m_availableMovements[i][1] == targetY) { return true; } } return false; } void Piece::moveTo(int targetX, int targetY) { m_posX = targetX; m_posY = targetY; } const std::vector<int> Piece::getPosition() { std::vector<int> position; position.resize(2); position[0] = m_posX; position[1] = m_posY; return position; } void Piece::computeAvailableMovements(std::vector<Piece*> own, std::vector<Piece*> opp) { // Empty } std::string Piece::toString() const { std::string s = "Piece at " ; s = std::to_string(m_posX) + " and " + std::to_string(m_posY) ; return s; } void Piece::clearAvailableMovements() { m_availableMovements.clear(); } void Piece::deleteAvailableMovements(std::vector<int>) { // Empty }
true
456760bf5d3aa5e03ce2987f9514a90af3ac622c
C++
AhatLi/AhatConfig
/ahatconfig/src/ahatconfig.cpp
UTF-8
3,232
2.8125
3
[]
no_license
#include "ahatconfig.h" /* bool AhatConfig::readConfig(std::string path) { return readConfig(path.c_str()); } */ bool AhatConfig::readConfig(const char* path) { std::string configPath = ""; if(path == NULL) { #ifdef _WIN32 /* LPSTR tmp; int len = GetModuleFileName(NULL, tmp, MAX_PATH); // std::wstring ws(tmp); std::string buf = tmp; buf = buf.substr(0, buf.find_last_of(".")); */ std::string buf = "./"; #elif __linux__ char buf[256]; int len = readlink("/proc/self/exe", buf, 256); buf[len] = '\0'; #endif configPath += buf; } else { configPath += path; } configPath += ".cfg"; std::string data = ""; int num = 0; char buf[1024+1]; //#ifdef _WIN32 std::ifstream inFile(configPath.c_str()); if (inFile.fail()) { std::cout << "Read Config Fail !! " << configPath.c_str() << "\n"; return false; } while (!inFile.eof()) { inFile.getline(buf, 1024); data += buf; data += "\n"; std::string line = buf; if (line.find("//") != std::string::npos) { line = line.substr(0, line.find("//")); } if (line.find("#") != std::string::npos) { line = line.substr(0, line.find("#")); } if (line.find("=") != std::string::npos) { std::istringstream sss(line); std::string name = ""; std::string value = ""; std::getline(sss, name, '='); std::getline(sss, value, '='); configmap[trim(name)] = trim(value); } } inFile.close(); /* #elif __linux__ int fd = open(configPath.c_str(), O_RDONLY); if (fd == -1) { std::cout << configPath.c_str() << " file not found!\n"; return false; } while ((num = read(fd, buf, 128)) > 0) { buf[num + 1] = '\0'; data += buf; } close(fd); #endif std::istringstream ss(data); std::string line; while(std::getline(ss, line, '\n')) { if(line.find("//") != std::string::npos) { line = line.substr(0, line.find("//")); } if(line.find("#") != std::string::npos) { line = line.substr(0, line.find("#")); } if(line.find("=") != std::string::npos) { std::istringstream sss(line); std::string name = ""; std::string value = ""; std::getline(sss, name, '='); std::getline(sss, value, '='); configmap[trim(name)] = trim(value); } } */ return true; } std::string AhatConfig::trim(std::string str) { int n; n = str.find_first_not_of(" \t"); if ( n != std::string::npos ) { str.replace(0, n,""); } n = str.find_last_not_of(" \t"); if ( n != std::string::npos ) { str.replace(n+1, str.length()-n,""); } return str; } std::string AhatConfig::getConfig(std::string name) { if(configmap[name] == std::string()) { return std::string(); } return configmap[name]; } std::string AhatConfig::getConfig(const char* name) { return getConfig(std::string(name)); } int AhatConfig::getConfigInt(std::string name) { if (configmap[name] == std::string()) { return 0; } return atoi(configmap[name].c_str()); } int AhatConfig::getConfigInt(const char* name) { return getConfigInt(std::string(name)); } bool AhatConfig::setConfig(std::string name, std::string value) { configmap[name] = value; return true; } bool AhatConfig::setConfig(const char* name, const char* value) { return setConfig(std::string(name), std::string(value)); }
true
ca2c919a028f9ff21335b694f0c8afc85556481b
C++
khaledman6122/codeforces-A-B
/A. Triangular numbers.cpp
UTF-8
388
2.609375
3
[]
no_license
// http://codeforces.com/contest/47/problem/A // #include <iostream> #include <algorithm> #include <vector> #define ll long long #define endl "\n" using namespace std ; int main () { std::ios::sync_with_stdio(false); int n,t; cin>>n; for(int i=1;true;i++) { t=(i*(i+1))/2; if(t==n) {cout<<"YES"<<endl; break;} else if(t>n) {cout<<"NO"<<endl; break;} } return 0; }
true
9d583e74235d0a5e40305513faee79c9ef5ac7ca
C++
FinancialEngineerLab/alillevangbech-cpp-xlsx
/CompFinance/Project1/Portfolio.h
UTF-8
365
2.71875
3
[]
no_license
#include <vector> #include "ClosedformOption.h" class portfolio { public: portfolio(size_t dim, std::vector<ClosedformOption* >& OptionValueVector, std::vector<double> weights); ~portfolio(); double getPrice(); private: size_t dim; std::vector<ClosedformOption* > OptionValueVector; std::vector<double> weights; ClosedformOption* theClosedformOptionPtr; };
true
c794900546819d1187b60dfd49dc78322908308b
C++
ruilin/RLMap
/platform/chunks_download_strategy.hpp
UTF-8
2,361
2.8125
3
[ "Apache-2.0" ]
permissive
#pragma once #include "std/string.hpp" #include "std/vector.hpp" #include "std/utility.hpp" #include "std/cstdint.hpp" namespace downloader { /// Single-threaded code class ChunksDownloadStrategy { public: enum ChunkStatusT { CHUNK_FREE = 0, CHUNK_DOWNLOADING = 1, CHUNK_COMPLETE = 2, CHUNK_AUX = -1 }; private: #pragma pack(push, 1) struct ChunkT { /// position of chunk in file int64_t m_pos; /// @see ChunkStatusT int8_t m_status; ChunkT() : m_pos(-1), m_status(-1) { static_assert(sizeof(ChunkT) == 9, "Be sure to avoid overhead in writing to file."); } ChunkT(int64_t pos, int8_t st) : m_pos(pos), m_status(st) {} }; #pragma pack(pop) vector<ChunkT> m_chunks; static const int SERVER_READY = -1; struct ServerT { string m_url; int m_chunkIndex; ServerT(string const & url, int ind) : m_url(url), m_chunkIndex(ind) {} }; vector<ServerT> m_servers; struct LessChunks { bool operator() (ChunkT const & r1, ChunkT const & r2) const { return r1.m_pos < r2.m_pos; } bool operator() (ChunkT const & r1, int64_t const & r2) const { return r1.m_pos < r2; } bool operator() (int64_t const & r1, ChunkT const & r2) const { return r1 < r2.m_pos; } }; typedef pair<int64_t, int64_t> RangeT; /// @return Chunk pointer and it's index for given file offsets range. pair<ChunkT *, int> GetChunk(RangeT const & range); public: ChunksDownloadStrategy(vector<string> const & urls); /// Init chunks vector for fileSize. void InitChunks(int64_t fileSize, int64_t chunkSize, ChunkStatusT status = CHUNK_FREE); /// Used in unit tests only! void AddChunk(RangeT const & range, ChunkStatusT status); void SaveChunks(int64_t fileSize, string const & fName); /// @return Already downloaded size. int64_t LoadOrInitChunks(string const & fName, int64_t fileSize, int64_t chunkSize); /// Should be called for every completed chunk (no matter successful or not). /// @returns url of the chunk string ChunkFinished(bool success, RangeT const & range); size_t ActiveServersCount() const { return m_servers.size(); } enum ResultT { ENextChunk, ENoFreeServers, EDownloadFailed, EDownloadSucceeded }; /// Should be called until returns ENextChunk ResultT NextChunk(string & outUrl, RangeT & range); }; } // namespace downloader
true
1eb7ade4398bfd5db2b20c23d444018468229175
C++
ShinichiArakawa/Leika-STG
/github/Leika/Source/Utility/TaskManager.h
SHIFT_JIS
1,284
3.15625
3
[]
no_license
#pragma once /** * @file TaskManager.h * @brief Task ̍XVƕ` * @author Katsumi Takei * @date 2016 / 06 / 29 * @date ŏIXV 2016 / 11 / 02 */ #include "Task.h" #include "../Function.h" class TaskManager { private: std::list<Task*> tasklist; std::list<Task*> newlist; DrawMode mode_; TaskManager() {} ~TaskManager() {} void CleanUp() { std::list <Task*>(tasklist).swap(tasklist); tasklist.insert(tasklist.end(), newlist.begin(), newlist.end()); newlist.clear(); std::list <Task*>(newlist).swap(newlist); tasklist.sort(compareByA); } public: static TaskManager *Instance() { static TaskManager instance; return &instance; } void Add(Task *task) { newlist.push_back(task); } void Clear() { tasklist.clear(); newlist.clear(); } void SetMode(DrawMode mode) { mode_ = mode; } void Update() { for (std::list<Task*>::iterator it = tasklist.begin(); it != tasklist.end(); ++it) { Task *task = *it; task->update(); if (!task->getIsLiving()) { it = tasklist.erase(it); it--; } } CleanUp(); } void Draw() { for (std::list<Task*>::iterator it = tasklist.begin(); it != tasklist.end(); ++it) { Task *task = *it; if (mode_ == task->drawMode()) { task->draw(); } } } };
true
c311c6964c5b85cc5b7d1cfaf56f632755a52f08
C++
BrillaintCB/Cpp
/cpp2020/06StorageClasses.cpp
UTF-8
598
3.59375
4
[]
no_license
#include <iostream> using namespace std; /* A storage class defines the scope(visibility) and life-time of variables and /or functions whithin a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ program -- auto -- register -- static -- extern -- mutable */ void doSomething() { static int a = 1; // When first declare a static value, it must be initialized(assigned) ++a; // same memory address cout << a << endl; } int main() { doSomething(); doSomething(); doSomething(); doSomething(); }
true
9d91986b2dd4cf2f002450db97a7eeb4915a9646
C++
lugt/cprogram-oj
/test20180423/bankAccount.cpp
UTF-8
1,957
3.15625
3
[ "Apache-2.0" ]
permissive
// // Created by lugt on 2018/4/23. // #include<iostream> #include<string> using std::string; using std::cin; using std::cout; using std::endl; class Account { public: Account(string accno, string name, float banlance) { _accno = accno; _accname = name; _banlance = banlance; } private: static int count; static float m_rate; string _accno, _accname; float _banlance; public: ~Account() { } void depositMoney(float amount) { _banlance += amount; } void retreatMoney(float amount) { _banlance -= amount; } float GetBanlance() { return _banlance; } static int GetCount(int num) { Account::count = num; } static int GetInterestRate(float rate_value) { Account::m_rate = rate_value; } friend void Update(Account &a) { a._banlance *= (m_rate + 1); } void print_first() { cout << _accno << " " << _accname; } void print_second() { cout << " " << _banlance; } }; int Account::count = 0; float Account::m_rate = 0; int main() { int customNums; float iRate, Despo, Outo, Balance, ttemp_, sum_of_balance = 0; string customerId, cusName_; cin >> iRate >> customNums; Account::GetCount(customNums); Account::GetInterestRate(iRate); while (customNums--) { cin >> customerId >> cusName_ >> Balance >> Despo >> Outo; Account Person(customerId, cusName_, Balance); Person.print_first(); Person.depositMoney(Despo); Person.print_second(); Update(Person); Person.print_second(); Person.retreatMoney(Outo); Person.print_second(); ttemp_ = Person.GetBanlance(); sum_of_balance += ttemp_; cout << endl; } cout << sum_of_balance << endl; return 0; }
true
a98c8df0fa7998fccdb63d2ad3aed4e55a6c17ac
C++
wps13/logicaprog
/L2E5.cpp
UTF-8
372
3.296875
3
[]
no_license
#include <iostream> using namespace std; int main(){ float consumo, conta; cout << "Digite o consumo de água(em metros cúbicos): "; cin >> consumo; if(consumo < 20){ conta = consumo * 8.50; cout << "O valor da conta é:R$ " << conta; } else{ conta = consumo*11.0; cout << "O valor da conta é:R$ " << conta; } return 0; }
true
f1b3808bfc972e980e6b53abb14e6aa8807659a2
C++
jasont7/cpp-projects
/linked_list/main_6.cpp
UTF-8
2,699
3.46875
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <memory> #include <iomanip> #include <complex> #include <vector> #include <utility> #include "list.hpp" int main() { link_list<std::string> list; std::string line; // read one string at a time and insert at the end of the list while (getline(std::cin, line)) { list.insert_ordered(line); } std::cout << "Capitals:" << std::endl; list.print(); // now, let us make a list with the first character of each country std::function<char(std::string&)> first_char = [](std::string &st) { if (st.length() > 0) { return st.at(0); } else { return char(0); } }; link_list<char> firstChar = list.map(first_char); firstChar.print(); // map their length std::function<int(std::string&)> f_len = [](std::string &st) { return st.length(); }; auto len = list.map(f_len); len.print(); // let us map empty list too link_list<std::string> empty {}; auto len2 = empty.map(f_len); len2.print(); { // let us create an imaginary number from the capitals // ordinal of first character (starting in A) is the imaginary part, the length is the real part std::cout << "List of Complex numbers" << std::endl; std::function<std::complex<double>(std::string&)> st_to_complex = [](std::string &st) { if (st.length() > 0) { return std::complex<double>(st.length(), int(st.at(0)-'A')); } else { return std::complex<double>(st.length(),0); } }; auto l_complex = list.map(st_to_complex); // we need to do use do to print it l_complex.print(); // let us convert them into polar coordinates, using a pair std::function<std::pair<double,double>(std::complex<double>&)> complex_to_polar = [](std::complex<double> &c) { return std::pair<double,double>(std::abs(c), std::arg(c)); }; auto l_polar = l_complex.map(complex_to_polar); // we need to use a lambda to print it std::cout << "In polar coordinates " << std::endl; int index {0}; std::function<void(std::pair<double,double>)> p_pair = [&index](std::pair<double,double> p) { if (index++ != 0) { std::cout << " -> "; } std::cout << "(" << p.first << "," << p.second << ")"; }; // std::cout << std::fixed << std::setprecision(3); l_polar.apply(p_pair); std::cout << std::endl; } return 0; }
true
3b97c877c35084a23c11f7de81090f90812fa04c
C++
CrossNick/OOPLab3
/OOPLab3/OOPLab2/OOPLab2/StaticArray.cpp
UTF-8
844
3.421875
3
[]
no_license
#include "stdafx.h" #include "StaticArray.h" template<class T> StaticArray<T>::StaticArray(int sz) { _size = sz; arr = new T[_size]; } template<class T> int StaticArray<T>::size() const { return _size; } template<class T> bool StaticArray<T>::isEmpty() const { return _size ==0; } template<class T> std::string StaticArray<T>::toString() const { string result = ""; for (int i = 0; i < _size; i++) { result.append(to_string(arr[i])); result.append(" "); } return result; } template<class T> T StaticArray<T>::get(int index) const { if(index<_size) return arr[index]; throw "The Array is empty!"; } template<class T> bool StaticArray<T>::set(int index, const T& value) { if (index < _size) { arr[index] = value; return true; } return false } template<class T> StaticArray<T>::~StaticArray() { delete[] arr; }
true
cc5cd823c46b56dd316ab4fe331bcec8d0acd0e9
C++
anuanu0-0/a2oj_ladders
/Div_2A/Chat_room.cpp
UTF-8
566
2.921875
3
[ "MIT" ]
permissive
#include <iostream> #include <algorithm> #include <vector> using namespace std; #define test \ int t; \ cin >> t; \ while (t--) #define endl '\n' #define vi vector<int> #define pb push_back int main() { string s, word = "hello"; cin >> s; int idx = 0; string ans = ""; for (int i = 0; i < s.size(); i++) { if (s[i] == word[idx]) { ans += word[idx]; idx++; } } if (ans == "hello") cout << "YES" << endl; else cout << "NO" << endl; return 0; }
true
076a245a7ccc4ce4566fccb1631b8dee02b06bee
C++
Caffrey/CPipeline
/Raytracing/Intrucdtion/Realistic Ray Tracing/Shape.cpp
UTF-8
3,719
2.890625
3
[]
no_license
#include "Shape.h" Triangle::Triangle(const Vector3& _p0, const Vector3& _p1, const Vector3& _p2, const Color& _color) : p0(_p0), p1(_p1), p2(_p2), color(_color) {} bool Triangle::hit(const Ray& r, RFLOAT tmin, RFLOAT tmax, HitRecord& record) const { RFLOAT tval; RFLOAT A = p0.x() - p1.x(); RFLOAT B = p0.y() - p1.y(); RFLOAT C = p0.z() - p1.z(); RFLOAT D = p0.x() - p2.x(); RFLOAT E = p0.y() - p2.y(); RFLOAT F = p0.z() - p2.z(); RFLOAT G = r.Direction().x(); RFLOAT H = r.Direction().y(); RFLOAT I = r.Direction().z(); RFLOAT J = p0.x() - r.Origin().x(); RFLOAT K = p0.y() - r.Origin().y(); RFLOAT L = p0.z() - r.Origin().z(); RFLOAT EIHF = E * I - H * F; RFLOAT GFDI = G * F - D * I; RFLOAT DHEG = D * H - E * G; RFLOAT denom = (A * EIHF + B * GFDI + C * DHEG); RFLOAT beta = (J * EIHF + K * GFDI + L * DHEG) / denom; if (beta < 0.0f || beta >= 1.0f) return false; RFLOAT AKJB = A * K - J * B; RFLOAT JCAL = J * C - A * L; RFLOAT BLKC = B * L - K * C; RFLOAT gamma = (I * AKJB + H * JCAL + G * BLKC) / denom; if (gamma <= 0.0f || beta + gamma >= 1.0f) return false; tval = -(F * AKJB + E * JCAL + D * BLKC) / denom; if (tval >= tmin && tval <= tmax) { record.t = tval; record.normal = normalize(cross((p1 - p0), (p2 - p0))); record.color = color; return true; } return false; } bool Triangle::shadowHit(const Ray& r, RFLOAT tmin, RFLOAT tmax, HitRecord& record) const { RFLOAT tval; RFLOAT A = p0.x() - p1.x(); RFLOAT B = p0.y() - p1.y(); RFLOAT C = p0.z() - p1.z(); RFLOAT D = p0.x() - p2.x(); RFLOAT E = p0.y() - p2.y(); RFLOAT F = p0.z() - p2.z(); RFLOAT G = r.Direction().x(); RFLOAT H = r.Direction().y(); RFLOAT I = r.Direction().z(); RFLOAT J = p0.x() - r.Origin().x(); RFLOAT K = p0.y() - r.Origin().y(); RFLOAT L = p0.z() - r.Origin().z(); RFLOAT EIHF = E * I - H * F; RFLOAT GFDI = G * F - D * I; RFLOAT DHEG = D * H - E * G; RFLOAT denom = (A * EIHF + B * GFDI + C * DHEG); RFLOAT beta = (J * EIHF + K * GFDI + L * DHEG) / denom; if (beta < 0.0f || beta >= 1.0f) return false; RFLOAT AKJB = A * K - J * B; RFLOAT JCAL = J * C - A * L; RFLOAT BLKC = B * L - K * C; RFLOAT gamma = (I * AKJB + H * JCAL + G * BLKC) / denom; if (gamma <= 0.0f || beta + gamma >= 1.0f) return false; tval = -(F * AKJB + E * JCAL + D * BLKC) / denom; return (tval >= tmin && tval <= tmax); } //-----------------Sphere Sphere::Sphere(const Vector3& _center, RFLOAT _radius, const Color& _color): center(_center),radius(_radius),color(_color){} bool Sphere::hit(const Ray& r, RFLOAT tmin, RFLOAT tmax, HitRecord& record) const { Vector3 temp = r.Origin() - center; double a = dot(r.Direction(), r.Direction()); double b = 2 * dot(r.Direction(), temp); double c = dot(temp, temp) - radius * radius; double discriminant = b * b - 4 * a * c; if (discriminant <= 0) { return false; } discriminant = sqrt(discriminant); RFLOAT t = (-b - discriminant) / (2 * a); if (t < tmin) t = (-b + discriminant) / (2 * a); if (t < tmin || t > tmax) return false; record.t = t; record.normal = normalize(r.Origin() + t * r.Direction() - this->center); record.color = this->color; return true; } bool Sphere::shadowHit(const Ray& r, RFLOAT tmin, RFLOAT tmax, HitRecord& record) const { Vector3 temp = r.Origin() - center; double a = dot(r.Direction(), r.Direction()); double b = 2 * dot(r.Direction(), temp); double c = dot(temp, temp) - radius * radius; double discriminant = b * b - 4 * a * c; if (discriminant <= 0) { return false; } discriminant = sqrt(discriminant); RFLOAT t = (-b - discriminant) / (2 * a); if (t < tmin) t = (-b + discriminant) / (2 * a); if (t < tmin || t > tmax) return false; }
true
4ca010b6aa7d2da93308d02b85578882454f86ff
C++
AnneMayor/algorithmstudy
/2071_평균값구하기_D1.cpp
UTF-8
708
2.59375
3
[]
no_license
// // 2071_평균값구하기_D1.cpp // algorithmstudy // codingtest4mycareer // // Created by DHL on 21/04/2019. // Copyright © 2019 DHL. All rights reserved. // #include <iostream> #include <cmath> using namespace std; int main() { int T; cin.tie(0); cin >> T; for(int t = 1; t <= T; t++) { double nums[10]; double total = 0; double ans = 0; for(int i = 0; i < 10; i++) { cin >> nums[i]; total += nums[i]; } ans = total / 10; ans = round(ans); cout << "#" << t << " " << ans << endl; } return 0; }
true
3af77db6facffd84da3d4ac3969511d628b20686
C++
sgajaejung/Utility
/Graphic/collision/boundingbox.h
WINDOWS-1252
456
2.546875
3
[ "MIT" ]
permissive
#pragma once namespace graphic { // OBB 浹ڽ. class cBoundingBox { public: cBoundingBox(); cBoundingBox(const cCube &cube); void SetBoundingBox(const Vector3 &vMin, const Vector3 &vMax ); void SetTransform( const Matrix44 &tm ); bool Collision( cBoundingBox &box ); bool Pick(const Vector3 &orig, const Vector3 &dir); cBoundingBox& operator=(const cCube &cube); Vector3 m_min; Vector3 m_max; Matrix44 m_tm; }; }
true
e9a465c4fe896bbd82ac27d73a075bc6d1ebfade
C++
windgassen/Wreath-FastLED
/Wreath_Fast_LED_REV_A_Final.ino
UTF-8
7,835
2.9375
3
[]
no_license
#include "FastLED.h" FASTLED_USING_NAMESPACE // FastLED "100-lines-of-code" demo reel, showing just a few // of the kinds of animation patterns you can quickly and easily // compose using FastLED. // // This example also shows one easy way to define multiple // animations patterns and have them automatically rotate. // // -Mark Kriegsman, December 2014 #if defined(FASTLED_VERSION) && (FASTLED_VERSION < 3001000) #warning "Requires FastLED 3.1 or later; check github for latest code." #endif #define DATA_PIN 6 //#define CLK_PIN 4 #define LED_TYPE WS2811 #define COLOR_ORDER RGB #define NUM_LEDS 48 CRGB leds[NUM_LEDS]; #define BRIGHTNESS 255 #define FRAMES_PER_SECOND 120 void setup() { delay(3000); // 3 second delay for recovery // tell FastLED about the LED strip configuration FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip); //FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip); // set master brightness control FastLED.setBrightness(BRIGHTNESS); } // List of patterns to cycle through. Each is defined as a separate function below. typedef void (*SimplePatternList[])(); SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, sinelon, juggle, bpm, fire, water, pride}; uint8_t gCurrentPatternNumber = 0; // Index number of which pattern is current uint8_t gHue = 0; // rotating "base color" used by many of the patterns void loop() { // Call the current pattern function once, updating the 'leds' array gPatterns[gCurrentPatternNumber](); // send the 'leds' array out to the actual LED strip FastLED.show(); // insert a delay to keep the framerate modest FastLED.delay(1000/FRAMES_PER_SECOND); // do some periodic updates EVERY_N_MILLISECONDS( 20 ) { gHue++; } // slowly cycle the "base color" through the rainbow EVERY_N_SECONDS( 20 ) { nextPattern(); } // change patterns periodically } #define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0])) void nextPattern() { // add one to the current pattern number, and wrap around at the end gCurrentPatternNumber = (gCurrentPatternNumber + 1) % ARRAY_SIZE( gPatterns); } void rainbow() { // FastLED's built-in rainbow generator fill_rainbow( leds, NUM_LEDS, gHue, 7); } void rainbowWithGlitter() { // built-in FastLED rainbow, plus some random sparkly glitter rainbow(); addGlitter(80); } void addGlitter( fract8 chanceOfGlitter) { if( random8() < chanceOfGlitter) { leds[ random16(NUM_LEDS) ] += CRGB::White; } } void confetti() { // random colored speckles that blink in and fade smoothly fadeToBlackBy( leds, NUM_LEDS, 10); int pos = random16(NUM_LEDS); leds[pos] += CHSV( gHue + random8(64), 200, 255); } void sinelon() { // a colored dot sweeping back and forth, with fading trails fadeToBlackBy( leds, NUM_LEDS, 20); int pos = beatsin16( 13, 0, NUM_LEDS-1 ); leds[pos] += CHSV( gHue, 255, 192); } void bpm() { // colored stripes pulsing at a defined Beats-Per-Minute (BPM) uint8_t BeatsPerMinute = 62; CRGBPalette16 palette = PartyColors_p; uint8_t beat = beatsin8( BeatsPerMinute, 64, 255); for( int i = 0; i < NUM_LEDS; i++) { //9948 leds[i] = ColorFromPalette(palette, gHue+(i*2), beat-gHue+(i*10)); } } void juggle() { // eight colored dots, weaving in and out of sync with each other fadeToBlackBy( leds, NUM_LEDS, 20); byte dothue = 0; for( int i = 0; i < 8; i++) { leds[beatsin16( i+7, 0, NUM_LEDS-1 )] |= CHSV(dothue, 200, 255); dothue += 32; } } //****************************New patterns added in REV A - Jim Windgassen 9 Dec 2017******************************************* void rainbow_solid_glitter(){ //fills with a s fill_solid(leds, NUM_LEDS, CHSV(gHue, 255, 255)); addGlitter(80); //return 8; } void fire() //uint8_t fire() { /* Available Palettes to choose from RainbowColors_p, RainbowStripeColors_p CloudColors_p, OceanColors_p, ForestColors_p, HeatColors_p, LavaColors_p, PartyColors_p, IceColors_p, */ //heatMap(LavaColors_p, true); heatMap(HeatColors_p, true); //return 30; } void water() //uint8_t water() { heatMap(OceanColors_p, false); //return 30; } // Pride2015 by Mark Kriegsman: https://gist.github.com/kriegsman/964de772d64c502760e5 // This function draws rainbows with an ever-changing, // widely-varying set of parameters. void pride() //uint8_t pride() { static uint16_t sPseudotime = 0; static uint16_t sLastMillis = 0; static uint16_t sHue16 = 0; uint8_t sat8 = beatsin88( 87, 220, 250); uint8_t brightdepth = beatsin88( 341, 96, 224); uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256)); uint8_t msmultiplier = beatsin88(147, 23, 60); uint16_t hue16 = sHue16;//gHue * 256; uint16_t hueinc16 = beatsin88(113, 1, 3000); uint16_t ms = millis(); uint16_t deltams = ms - sLastMillis ; sLastMillis = ms; sPseudotime += deltams * msmultiplier; sHue16 += deltams * beatsin88( 400, 5,9); uint16_t brightnesstheta16 = sPseudotime; for( uint16_t i = 0 ; i < NUM_LEDS; i++) { hue16 += hueinc16; uint8_t hue8 = hue16 / 256; brightnesstheta16 += brightnessthetainc16; uint16_t b16 = sin16( brightnesstheta16 ) + 32768; uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536; uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536; bri8 += (255 - brightdepth); CRGB newcolor = CHSV( hue8, sat8, bri8); uint16_t pixelnumber = i; pixelnumber = (NUM_LEDS-1) - pixelnumber; nblend( leds[pixelnumber], newcolor, 64); } //return 15; } //*************************Support Functions used by some of the effects************************************* // based on FastLED example Fire2012WithPalette: https://github.com/FastLED/FastLED/blob/master/examples/Fire2012WithPalette/Fire2012WithPalette.ino void heatMap(CRGBPalette16 palette, bool up) { fill_solid(leds, NUM_LEDS, CRGB::Black); // Add entropy to random number generator; we use a lot of it. random16_add_entropy(random(256)); uint8_t cooling = 55; uint8_t sparking = 120; // Array of temperature readings at each simulation cell static const uint8_t halfLedCount = NUM_LEDS / 2; static byte heat[2][halfLedCount]; byte colorindex; for(uint8_t x = 0; x < 2; x++) { // Step 1. Cool down every cell a little for( int i = 0; i < halfLedCount; i++) { heat[x][i] = qsub8( heat[x][i], random8(0, ((cooling * 10) / halfLedCount) + 2)); } // Step 2. Heat from each cell drifts 'up' and diffuses a little for( int k= halfLedCount - 1; k >= 2; k--) { heat[x][k] = (heat[x][k - 1] + heat[x][k - 2] + heat[x][k - 2] ) / 3; } // Step 3. Randomly ignite new 'sparks' of heat near the bottom if( random8() < sparking ) { int y = random8(7); heat[x][y] = qadd8( heat[x][y], random8(160,255) ); } // Step 4. Map from heat cells to LED colors for( int j = 0; j < halfLedCount; j++) { // Scale the heat value from 0-255 down to 0-240 // for best results with color palettes. colorindex = scale8(heat[x][j], 240); CRGB color = ColorFromPalette(palette, colorindex); if(up) { if(x == 0) { leds[(halfLedCount - 1) - j] = color; } else { leds[halfLedCount + j] = color; } } else { if(x == 0) { leds[j] = color; } else { leds[(NUM_LEDS - 1) - j] = color; } } } } }
true
44e835800a21d71c656329ff768dab5da4915273
C++
fpartl/libpe
/fft.cpp
UTF-8
3,287
2.734375
3
[]
no_license
#include "fft.h" FFT::FFT(int segmentSize, QObject *parent) : QObject(parent) { if (segmentSize <= 0) { emit error("FFT::FFT: Neplatná velikost vstupních segmentů."); return; } // tento výpočet vyplívá z definice algoritmu FFT for (m_maxSegmentSize = 1; m_maxSegmentSize < segmentSize; m_maxSegmentSize *= 2); m_espdSize = (m_maxSegmentSize / 2) + 1; m_fftCfg = kiss_fftr_alloc(m_maxSegmentSize, 0, nullptr, nullptr); m_ifftCft = kiss_fftr_alloc(m_maxSegmentSize, 1, nullptr, nullptr); if (!m_fftCfg || !m_ifftCft) { emit error("FFT::FFT: Nepodařilo se alokovat potřebné zdroje (kissFFT)."); return; } } FFT::~FFT() { free(m_fftCfg); free(m_ifftCft); } int FFT::espdSize() const { return m_espdSize; } QVector<float> FFT::transformEucl(QVector<float> segment) { if (segment.isEmpty()) return QVector<float>(); if (segment.size() > m_maxSegmentSize) { emit error("FFT::transformEucl: Vstupní segment je větší je přednastavená velikost."); return QVector<float>(); } if (segment.size() < m_maxSegmentSize) segment = prepareSegment(segment); QVector<kiss_fft_cpx> cpx = realFFt(segment); if (cpx.isEmpty()) return QVector<float>(); return euclidNorm(cpx); } QVector<kiss_fft_cpx> FFT::realFFt(QVector<float> segment) { if (segment.size() != m_maxSegmentSize) return QVector<kiss_fft_cpx>(); QVector<kiss_fft_cpx> cpx(m_espdSize); kiss_fftr(m_fftCfg, segment.constData(), cpx.data()); return cpx; } QVector<float> FFT::invRealFFT(QVector<kiss_fft_cpx> cpx) { if (cpx.size() != m_espdSize) return QVector<float>(); QVector<float> segment(m_maxSegmentSize); kiss_fftri(m_ifftCft, cpx.constData(), segment.data()); QMutableVectorIterator<float> i(segment); while (i.hasNext()) { float i_val = i.next(); i.setValue(i_val / static_cast<float>(m_espdSize)); } return segment; } void FFT::realFFt(QVector<float> &segment, QVector<kiss_fft_cpx> &cpx) { if (segment.size() != m_maxSegmentSize || cpx.size() != m_espdSize) return; kiss_fftr(m_fftCfg, segment.constData(), cpx.data()); } void FFT::invRealFFT(QVector<kiss_fft_cpx> &cpx, QVector<float> &segment) { if (cpx.size() != m_espdSize || segment.size() != m_maxSegmentSize) return; kiss_fftri(m_ifftCft, cpx.constData(), segment.data()); QMutableVectorIterator<float> i(segment); while (i.hasNext()) { float i_val = i.next(); i.setValue(i_val / static_cast<float>(m_espdSize)); } } QVector<float> FFT::prepareSegment(QVector<float> segment) { if (segment.isEmpty()) return QVector<float>(); QVector<float> fftInput = segment; int toFill = m_maxSegmentSize - fftInput.size(); for (int i = 0; i < toFill; i++) fftInput.append(0); return fftInput; } QVector<float> FFT::euclidNorm(QVector<kiss_fft_cpx> cpx) { if (cpx.isEmpty()) return QVector<float>(); QVector<float> magnitudes; magnitudes.reserve(m_espdSize); for (kiss_fft_cpx val : cpx) { float mag = qSqrt((val.r * val.r) + (val.i * val.i)); magnitudes.append(mag); } return magnitudes; }
true
1390e54139dfa15a11c6559273704217a7f37ea8
C++
maxrchung/TetrisBuddies
/Gameplay/Header and Source for main/GameScreen.cpp
UTF-8
3,708
2.96875
3
[]
no_license
#include "GameScreen.hpp" // To be filled in at the gameplay people's discretion GameScreen::GameScreen() : pressed(false), pressed2(false) { bh = new BlockHandler(GraphicsManager::getInstance()->window.getSize().x, GraphicsManager::getInstance()->window.getSize().y); ch = new CursorHandler(bh->SCREENWIDTH, bh->SCREENHEIGHT, GraphicsManager::getInstance()->window.getSize().x, GraphicsManager::getInstance()->window.getSize().y); //draws a large rectangle around the game screen rec.setSize(sf::Vector2f(bh->SCREENWIDTH, bh->SCREENHEIGHT)); rec.setFillColor(sf::Color::Transparent); rec.setPosition(GraphicsManager::getInstance()->window.getSize().x/2 - bh->SCREENWIDTH/2, GraphicsManager::getInstance()->window.getSize().y/2 - bh->SCREENHEIGHT/2 ); rec.setOutlineThickness(25); rec.setOutlineColor(sf::Color::Black); } void GameScreen::update() { //keyboard movement for cursor if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { if (pressed == false) { ch->Left(sf::Keyboard::Key::Left); pressed = true; // Cannot hold right to move } } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { if (pressed == false) { ch->Right(sf::Keyboard::Key::Right); pressed = true; // Cannot hold right to move } } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { if (pressed == false) { ch->Up(sf::Keyboard::Key::Up); pressed = true; // Cannot hold right to move } } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { if (pressed == false) { ch->Down(sf::Keyboard::Key::Down); pressed = true; // Cannot hold right to move } } else pressed = false; //keypress for block switching if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) //swaps the main block with the left block { if (pressed2 == false) { bh->swapBlocksHorizL(ch->getMainCursor().getPosition().x, ch->getMainCursor().getPosition().y); pressed2 = true; } } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) //swaps the main block with the right block { if (pressed2 == false) { bh->swapBlocksHorizR(ch->getMainCursor().getPosition().x, ch->getMainCursor().getPosition().y); pressed2 = true; } } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) //swaps the main block with the top block { if (pressed2 == false) { bh->swapBlocksVertT(ch->getMainCursor().getPosition().x, ch->getMainCursor().getPosition().y); pressed2 = true; } } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) //swaps the main block with the bottom block { if (pressed2 == false) { bh->swapBlocksVertB(ch->getMainCursor().getPosition().x, ch->getMainCursor().getPosition().y); pressed2 = true; } } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) //swaps the main block with the bottom block { if (pressed2 == false) { bh->raiseBlocks(); pressed2 = true; } } else pressed2 = false; //cannot hold swap button to keep swapping } void GameScreen::draw() { //draws a border around the game GraphicsManager::getInstance()->window.draw(rec); //draws blocks on screen for (int i = 0; i < bh->SCREENHEIGHT / 25; i++) { for (int j = 0; j < bh->SCREENWIDTH / 25; j++) { GraphicsManager::getInstance()->window.draw(bh->getBlocks(j, i)); } } GraphicsManager::getInstance()->window.draw(ch->getMainCursor()); //draws main cursor GraphicsManager::getInstance()->window.draw(ch->getLeftCursor()); //draws left cursor GraphicsManager::getInstance()->window.draw(ch->getRightCursor()); //draws right cursor GraphicsManager::getInstance()->window.draw(ch->getTopCursor()); //draws top cursor GraphicsManager::getInstance()->window.draw(ch->getBottomCursor()); //draws bottom cursor }
true
37596d82222f9487934831962ecb3010b577ab51
C++
gli-27/cpluscode
/chapter1/1.13/main.cpp
UTF-8
321
3.125
3
[]
no_license
// // main.cpp // 1.13 // // Created by LG on 2019/7/18. // Copyright © 2019 LG. All rights reserved. // #include <iostream> int main(){ int sum = 0; for(int val = 1; val <= 10; ++val){ sum += val; } std::cout << "Sum of 1 to 10 inclusive is " << sum <<std::endl; return 0; }
true
20ad3dc50c415f4d12632e545492b8540eec0e17
C++
ererics41/Top-K-Approximation
/src/MaxHeap.cpp
UTF-8
3,561
3.59375
4
[]
no_license
#include "MaxHeap.h" #include <iostream> using namespace std; MaxHeap::MaxHeap(){ MAX_SIZE = 100; this->size = 0; heap = new HeapNode* [MAX_SIZE]; table = new HashTable(10000); } void MaxHeap::insert(string w){ //make word lowercase if(w == ""){ return; } string word = ""; for(string::iterator it = w.begin(); it != w.end(); it++){ word += tolower(*it); } //check if word is in the heap by searching the hash int found = table->search(word); //if word is already in the heap increment if(found > 0){ heap[found]->frequency++; //heapify down from here heapifyUp(found); } //word is not in the heap else{ // heap is not yet full add new element if(size < MAX_SIZE-1){ //create new node to insert HeapNode *node = new HeapNode(word); size++; //insert into heap heap[size] = node; //insert into hash table table->insert(node,size); heapifyUp(size); } } //increase heap size if size is now equal to max size if(size >= MAX_SIZE-1){ if(MAX_SIZE < 1000){ MAX_SIZE *= 3; }else if(MAX_SIZE < 13000){ MAX_SIZE *= 5; }else{ MAX_SIZE += 2000; } HeapNode **temp = new HeapNode* [MAX_SIZE]; for(int i = 1; i <=size; i++){ temp[i] = heap[i]; } heap = temp; } } void MaxHeap::insert(HeapNode *entry){ size++; heap[size] = entry; table->insert(entry,size); heapifyUp(size); } HeapNode* MaxHeap::removeMax(){ HeapNode *rtn = heap[1]; table->remove(heap[size]->word); table->insert(heap[size],1); if(size>1){ heap[1] = heap[size]; size--; heapifyDown(1); } return rtn; } void MaxHeap::print(int num){ if(size == 0){ cout << "File was empty." << endl; return; } cout << "Printing most frequent words." << endl; if(num < size){ num = size; } HeapNode **frequent = new HeapNode* [num]; for(int i = 0; i < num; i++){ frequent[i] = removeMax(); } cout << "removed top nodes " <<endl; for(int i = 0; i < num; i++){ cout << frequent[i]->word << " occurs " << frequent[i]->frequency << " times." << endl; insert(frequent[i]); } } /*void MaxHeap::print(){ for(int i = 1; i <= 15; i++){ cout << heap[i]->word << " occurs " << heap[i]->frequency << " times." << endl; } }*/ void MaxHeap::heapifyUp(int index){ //cout << "Inside heap up" <<endl; if(index <= 1 || heap[index]->frequency <= heap[index/2]->frequency){ return; }else{ HeapNode *temp = heap[index]; table->remove(heap[index]->word); table->remove(heap[index/2]->word); //table->print(); heap[index] = heap[index/2]; heap[index/2] = temp; table->insert(heap[index],index); table->insert(heap[index/2],index/2); //continue checking recursively heapifyUp(index/2); } } void MaxHeap::heapifyDown(int index){ if(index*2 > size){ return; }else{ HeapNode* left = heap[index*2]; HeapNode* right = left; if(index*2+1 <= size){ right = heap[index*2+1]; } int maxIndex; if(left->frequency >= right->frequency){ maxIndex = index*2; }else{ maxIndex = index*2+1; } //swap if min is less than parent if(heap[maxIndex]->frequency > heap[index]->frequency){ //swap table->remove(heap[index]->word); table->remove(heap[maxIndex]->word); HeapNode *temp = heap[index]; heap[index] = heap[maxIndex]; heap[maxIndex] = temp; table->insert(heap[index],index); table->insert(heap[maxIndex],maxIndex); //continue checking recursively heapifyDown(maxIndex); } } }
true
8a2fe19bce8b3a5a4a841d29da14ded61a627aee
C++
MrBean1512/CS273-FinalProject
/Program-Files/Stats.cpp
UTF-8
1,526
3.375
3
[]
no_license
#include "Stats.h" Stats::Stats() { } void Stats::update_report(Citizen * citizen) //updated with new stats every time a patient is done being treated { ++num_patient; num_total_time = num_total_time + (citizen->dismissal_time - citizen->arrival_time); records.insert(std::pair<int, Citizen*>(citizen->it, citizen)); } void Stats::print_report() //prints statistics at the end of the program { std::cout << "Total patients: " << num_patient << std::endl; std::cout << "Average Total Service time: " << (double)num_total_time / num_patient << std::endl; //user may view individual patient reports if they choose to bool search; std::cout << "Would you like to view the records for treated patients?\nEnter 0 if no or 1 if yes" << std::endl; std::cin >> search; if (search) { std::map<int, Citizen*>::iterator it; //used a map here but a loop to print out each patient's info from the population vector would be better for (auto const& pair : records) { std::cout << "{" << pair.first << ": " << pair.second << "}\n"; //could not get this to print the string, would only print pointers, still needs work } int who=0; while (who != -1) { std::cout << "Enter the number of the person who's records you would like to view: "; std::cin >> who; it = records.find(who); std::cout << records.find(who)->second->records[0]; std::cout << "Would you like to search another record?\nEnter -1 to exit and 0 to continue"; std::cin >> who; } } return; }
true
5561ee4162ceac99f5ae28c7f41c3db1e98fdddf
C++
R4x7651/PAT_Answers
/PAT_LevelA/1006_Sign_In_and_Sign_Out.cpp
UTF-8
831
3.03125
3
[ "MIT" ]
permissive
#include "cstdio" struct Stu { char id[16]; int hour; int minute; int second; } in, out, temp; bool earlier(Stu a, Stu b) { int total_a = a.hour * 3600 + a.minute * 60 + a.second; int total_b = b.hour * 3600 + b.minute * 60 + b.second; if (total_a < total_b) return true; else return false; } int main() { int n; in.hour = 23, in.minute = 59, in.second = 59; out.hour = 0, out.minute = 0, out.second = 0; if (scanf("%d", &n) == 1); for (int i = 0; i < n; ++i) { if (scanf("%s %d:%d:%d", temp.id, &temp.hour, &temp.minute, &temp.second) == 1); if (earlier(temp, in)) in = temp; if (scanf("%d:%d:%d", &temp.hour, &temp.minute, &temp.second) == 1); if (!earlier(temp, out)) out = temp; } printf("%s %s", in.id, out.id); return 0; }
true
b1c4c9e11a6fc12515819a8bf9078efdcfac9986
C++
jeroennelis/Ray_Tracer
/Ray_Tracer/src/Ray_Tracer/GeometricObjects/GeometricObject.h
UTF-8
1,671
2.8125
3
[ "Apache-2.0" ]
permissive
#pragma once // this file contains the declaration of the class GeometricObject #include "../Utilities/Constants.h" #include "../Utilities/RGBColor.h" #include "../Utilities/Point3D.h" #include "../Utilities/Normal.h" #include "../Utilities/Ray.h" #include "../Utilities/ShadeRec.h" #include "../Utilities/Constants.h" class GeometricObject { public: GeometricObject(void); // default constructor GeometricObject(const GeometricObject& object); // copy constructor virtual GeometricObject* // virtual copy constructor clone(void) const = 0; virtual // destructor ~GeometricObject (void); virtual bool hit(const Ray& ray, double& t, ShadeRec& s) const = 0; // the following three functions are only required for Chapter 3 void set_color(const RGBColor& c); void set_color(const float r, const float g, const float b); RGBColor get_color(void); protected: RGBColor color; // only used for Bare Bones ray tracing GeometricObject& // assignment operator operator= (const GeometricObject& rhs); }; // -------------------------------------------------------------------- set_colour inline void GeometricObject::set_color(const RGBColor& c) { color = c; } // -------------------------------------------------------------------- set_colour inline void GeometricObject::set_color(const float r, const float g, const float b) { color.r = r; color.b = b; color.g = g; } // -------------------------------------------------------------------- get_colour inline RGBColor GeometricObject::get_color(void) { return (color); }
true
8d1cdff200f838b8495d3a34a0e04f70b3a90649
C++
hirotakaster/iot-workshop
/sketch_pwm/sketch_pwm.ino
UTF-8
331
2.875
3
[]
no_license
void setup() { // PWM PIN : 3,5,6,9,10,11 pinMode(6, OUTPUT); } void loop() { // PWMは0-255まで // ゆっくり明るくなる for (int i = 0; i <= 255; i++) { analogWrite(6, i); delay(20); } // ゆっくり暗くなる for (int i = 255; i >= 0; i--) { analogWrite(6, i); delay(20); } }
true
cd9c48c454ad8ed279f347385f8b981135c694c7
C++
tony-coder/PAT
/C++/Advanced Level/1137 Final Grading (25分).cpp
UTF-8
1,061
2.921875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct node { string id; int Gp, mid_term, final, G; node(): Gp(-1), mid_term(-1), final(-1), G(-1) {} bool operator<(const node& n)const { return G == n.G ? id < n.id : G > n.G; } }; int main(int argc, char const *argv[]) { int P, M, N; cin >> P >> M >> N; unordered_map<string, node> mp; string id; int t; for (int i = 0; i < P; ++i) { cin >> id >> t; mp[id].id = id; mp[id].Gp = t; } for (int i = 0; i < M; ++i) { cin >> id >> t; mp[id].mid_term = t; } for (int i = 0; i < N; ++i) { cin >> id >> t; mp[id].final = t; } vector<node> ans; for (auto& t : mp) { if (t.second.mid_term > t.second.final) t.second.G = round((double)t.second.mid_term * (0.4) + (double)t.second.final * 0.6); else t.second.G = t.second.final; if (t.second.Gp >= 200 && (t.second.G <= 100 && t.second.G >= 60)) ans.push_back(t.second); } sort(ans.begin(), ans.end()); for (auto t : ans) { printf("%s %d %d %d %d\n", t.id.c_str(), t.Gp, t.mid_term, t.final, t.G); } return 0; }
true
0a6bb7f7bc62f3cae00c197c066415dfc1ecf26e
C++
Chickenbumps/BOJ
/#15989/main.cpp
UTF-8
449
2.65625
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; int main(){ int t; cin >> t; int num[3] = {1,2,3}; while(t--){ int sum; cin >> sum; long long dist[sum+1]; memset(dist,0,sizeof(dist)); dist[0] = 1; for (int j = 0; j < 3; j++) { for (int i = 1; i <= sum; i++) { if (i-num[j] >= 0) { dist[i] += dist[i-num[j]]; } } } cout << dist[sum] << '\n'; } return 0; }
true
5761f61dafbf0f82d5304c759fb285f71a1afcbc
C++
thedavekwon/algo-projects
/uva/11450/11450.cpp
UTF-8
1,685
2.71875
3
[]
no_license
#include <iostream> #include <fstream> #include <cstring> using namespace std; int m, c; int choices[21]; int prices[21][21]; int dp[201][21]; void pprint() { for (int i = 0; i < m; ++i) { for (int j = 0; j < c; ++j) { cout << dp[i][j] << " "; } cout << endl; } } int solve_r(int money, int item) { // cout << money << "," << item << endl; int &ret = dp[money][item]; if (ret != -1) return ret; if (item == c) return money; ret = 0; for (int j = 0; j < choices[item]; ++j) { if (money + prices[item][j] <= m) { ret = max(ret, solve_r(money + prices[item][j], item + 1)); } } return ret; } void reconstruct(int money, int item) { if (money < 0 || item == c) return; for (int i = 0; i < choices[item] ; i++) { if (solve_r(money+prices[item][i], item+1) == dp[money][item]) { if (item == c-1) cout << prices[item][i] << endl; else cout << prices[item][i] << " "; reconstruct(money+prices[item][i], item+1); break; } } } int main() { ios::sync_with_stdio(false); ifstream in("./input.txt"); cin.rdbuf(in.rdbuf()); int tc; cin >> tc; while(tc--) { cin >> m >> c; for (int i = 0; i < c; ++i) { cin >> choices[i]; for (int j = 0; j < choices[i]; ++j) { cin >> prices[i][j]; } } memset(dp, -1, sizeof(dp)); int ans = solve_r(0, 0); if (ans == 0) cout << "no solution" << endl; else cout << ans << endl; if (ans != 0) reconstruct(0, 0); // pprint(); } }
true
5388c5bd5cfb675552b98bd208f2bdfa04561441
C++
emiliev/IS_OOP_2017
/Week05/StringProject/String.h
UTF-8
1,017
2.8125
3
[]
no_license
#pragma once #include <cstring> #include <iostream> using namespace std; class String { public: String(); String(char* data, size_t size); String(const String& other); String& operator=(const String&); ~String(); void print(); char getAt(int index); void setAt(int index, char symbol); void concat(const String&); void concat(char* other); const char* GetData()const; String& operator+=(const String& rhs); String& operator-=(const String& rhs); bool operator==(const String& rhs); bool operator!=(const String& rhs); bool operator< (const String& rhs); bool operator> (const String& rhs); bool operator<=(const String& rhs); bool operator>=(const String& rhs); friend std::istream& operator>>(std::istream& is, String& obj); friend std::ostream& operator<<(std::ostream& os, const String& obj); private: void copy(const String&); void destroy(); char* data; size_t size; };
true
72492e223c56c142c080bd42607ccb4053396c72
C++
Kwakcena/algorithm
/baekjoon/1012_유기농배추/1012.cpp
UTF-8
1,051
2.875
3
[]
no_license
#include <cstdio> #include <cstring> using namespace std; const int MAX = 51; int N, M, K; int dy[4] = {-1, +1, 0, 0}; int dx[4] = {0, 0, -1, +1}; int Table[MAX][MAX]; bool check[MAX][MAX]; void DFS(int s_row, int s_col, int value) { check[s_row][s_col] = true; Table[s_row][s_col] = value; for(int idx = 0; idx<4; idx++) { int n_row = s_row + dy[idx]; int n_col = s_col + dx[idx]; if((n_row < N && n_row >= 0) && (n_col < M && n_col >=0)) { if(!check[n_row][n_col] && Table[n_row][n_col] == 1) { DFS(n_row, n_col, value); } } } } int main() { int T=0; scanf("%d", &T); while(T--) { int value = 1; memset(Table, 0, sizeof(int)*(MAX*MAX)); memset(check, false, sizeof(bool)*(MAX*MAX)); scanf("%d %d %d", &M, &N, &K); for(int i=0; i<K; i++) { int row, col; scanf("%d %d", &col, &row); Table[row][col] = 1; } for(int i=0; i<N; i++) { for(int j=0; j<M; j++) { if(Table[i][j] && !check[i][j]) { DFS(i,j,value); value++; } } } printf("%d\n", value-1); } return 0; }
true
47bc5d66224396d885090e9c91608cd0b5d5088d
C++
mmaldacker/FluidRigidCoupling2D
/vector_math.h
UTF-8
839
2.859375
3
[]
no_license
#ifndef VECTOR_MATH_H #define VECTOR_MATH_H #include <vector> #include <algorithm> #include "pcgsolver/blas_wrapper.h" template<class T> T sum(std::vector<T>& data) { T result = 0; for(unsigned int i = 0; i < data.size(); ++i) result += data[i]; return result; } template<class T> void copy(const std::vector<T> & src, std::vector<T>& dest) { std::copy(src.begin(), src.end(), dest.begin()); } template<class T> T dot(const std::vector<T>& a, const std::vector<T>& b) { return BLAS::dot((int)a.size(), &a[0], &b[0]); } template<class T> void scale(T factor, std::vector<T>& data) { BLAS::scale((int)data.size(), factor, &data[0]); } template<class T> void add_scaled(T alpha, const std::vector<T>& x, std::vector<T>& y) { // y = y + alpha*x BLAS::add_scaled((int)x.size(), alpha, &x[0], &y[0]); } #endif
true
64a9f93b39eacdb1acd7f5050f531cf7f16f1c94
C++
jainabhi2001/Data_structure_-_Algo
/7_Evaluate_postfix.cpp
UTF-8
2,768
4.0625
4
[]
no_license
// Program : Implement evaluation of postfix notation using stacks. // ABC*D/+ // 5,6,2,+,*,12,4,/,- // 5 6 2 + * 12 4 / - #include <iostream> #include <process.h> #include <math.h> // For math related functions #include <ctype.h> // For character related operations -isdigit #include <stack> //Stack STL using namespace std; int calc(int fir,int sec,char op) // To check precedence of operators { int res=0; switch(op) { case '^':{res=pow(fir,sec);break;} case '*':{res=fir*sec;break; } case '/':{res=fir/sec;break;} case '+':{res=fir+sec;break;} case '-':{res=fir-sec;break;} default: cout<<"\n Invalid operator used in expression"; exit(1); } cout<<" "<<fir<<" "<<op<<" "<<sec<<" = "<<res<<endl; return res; } int infixToPostfix(string P) { stack <int> ST; P+=')'; cout<<"\n Postfix expression after paranthesis operation : "<<P<<endl; cout<<"\n Operation \t Result"<<endl; for (int i=0;i<P.length();i++) { int operation; if(P[i]==',' || P[i]==' '){} //Do nothing when comma comes else if(P[i]>='0' && P[i]<='9') // 1. Operand { if (P[i+1]>='0' && P[i+1]<='9') { int number = (P[i] - '0') * 10 + (P[i+1] - '0'); // For 2 digit number i=i+1; // For leaving the 2nd digit number in next loop turn ST.push(number); } else ST.push(P[i]-'0'); //Subtracting ascii value of 0 from that of character to get actual number } else if(P[i]==')' ) // 2. Right bracket is present at end of expression { return (ST.top()); } else if(P[i]=='^'|| P[i]=='*'||P[i]=='/' || P[i]=='+'||P[i]=='-') // 3. Operator encountered { int sec_op=ST.top(); ST.pop(); int fir_op=ST.top(); ST.pop(); operation= calc(fir_op,sec_op,P[i]); ST.push(operation); } } cout<<"\n Sorry evaluation failed"; // This will never happen return -1; } int main() { char Postfix[50]; int Evaluation; cout<<"******02216412819******"<<endl; cout<<"*****Abhishek Jain*****"<<endl; cout<<"\n Enter the Postfix expression that is to be evaluated: "; gets(Postfix); Evaluation= infixToPostfix(Postfix); cout<<"\n ----------------------------------------------------------------------"; cout<<"\n The Evaluated Expression/Result is : "<<Evaluation; return 0; }
true
f64f710c022dbee07ce13668cb118199399b8f86
C++
austinholst/Recursion
/Node.h
UTF-8
357
3
3
[]
no_license
//header guards #ifndef NODE_H #define NODE_H //include libraries and h files #include <iostream> #include "Student.h" using namespace std; //node class class Node { public: //function declarations Node(Student*); ~Node(); Node* getNext(); Student* getStudent(); void setNext(Node*); protected: //variables Student* s; Node* n; }; #endif
true
24cf871e4f8d67280118455bc0d70eec572f44b1
C++
Xlgd/learn-cpp
/cpp-primer-answers/Chapter_9/ex9-38.cpp
UTF-8
2,638
3.40625
3
[]
no_license
// 练习9.38 /* 编写程序,探究在你的标准实现中,vector是如何增长的。*/ #include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<int> v; for (int i = 0; i < 100; i++) { cout << "capacity: " << v.capacity() << " size: " << v.size() << endl; v.push_back(i); } return 0; } /* capacity: 0 size: 0 capacity: 1 size: 1 capacity: 2 size: 2 capacity: 3 size: 3 capacity: 4 size: 4 capacity: 6 size: 5 capacity: 6 size: 6 capacity: 9 size: 7 capacity: 9 size: 8 capacity: 9 size: 9 capacity: 13 size: 10 capacity: 13 size: 11 capacity: 13 size: 12 capacity: 13 size: 13 capacity: 19 size: 14 capacity: 19 size: 15 capacity: 19 size: 16 capacity: 19 size: 17 capacity: 19 size: 18 capacity: 19 size: 19 capacity: 28 size: 20 capacity: 28 size: 21 capacity: 28 size: 22 capacity: 28 size: 23 capacity: 28 size: 24 capacity: 28 size: 25 capacity: 28 size: 26 capacity: 28 size: 27 capacity: 28 size: 28 capacity: 42 size: 29 capacity: 42 size: 30 capacity: 42 size: 31 capacity: 42 size: 32 capacity: 42 size: 33 capacity: 42 size: 34 capacity: 42 size: 35 capacity: 42 size: 36 capacity: 42 size: 37 capacity: 42 size: 38 capacity: 42 size: 39 capacity: 42 size: 40 capacity: 42 size: 41 capacity: 42 size: 42 capacity: 63 size: 43 capacity: 63 size: 44 capacity: 63 size: 45 capacity: 63 size: 46 capacity: 63 size: 47 capacity: 63 size: 48 capacity: 63 size: 49 capacity: 63 size: 50 capacity: 63 size: 51 capacity: 63 size: 52 capacity: 63 size: 53 capacity: 63 size: 54 capacity: 63 size: 55 capacity: 63 size: 56 capacity: 63 size: 57 capacity: 63 size: 58 capacity: 63 size: 59 capacity: 63 size: 60 capacity: 63 size: 61 capacity: 63 size: 62 capacity: 63 size: 63 capacity: 94 size: 64 capacity: 94 size: 65 capacity: 94 size: 66 capacity: 94 size: 67 capacity: 94 size: 68 capacity: 94 size: 69 capacity: 94 size: 70 capacity: 94 size: 71 capacity: 94 size: 72 capacity: 94 size: 73 capacity: 94 size: 74 capacity: 94 size: 75 capacity: 94 size: 76 capacity: 94 size: 77 capacity: 94 size: 78 capacity: 94 size: 79 capacity: 94 size: 80 capacity: 94 size: 81 capacity: 94 size: 82 capacity: 94 size: 83 capacity: 94 size: 84 capacity: 94 size: 85 capacity: 94 size: 86 capacity: 94 size: 87 capacity: 94 size: 88 capacity: 94 size: 89 capacity: 94 size: 90 capacity: 94 size: 91 capacity: 94 size: 92 capacity: 94 size: 93 capacity: 94 size: 94 capacity: 141 size: 95 capacity: 141 size: 96 capacity: 141 size: 97 capacity: 141 size: 98 capacity: 141 size: 99 */
true
5ac172eb7b60381c821e44f84f9d1210197ec1b2
C++
joseluis-hd/EstructurasDeDatos
/Tarea04/include/queue.h
UTF-8
3,491
3.546875
4
[]
no_license
#ifndef __QUEUE_H__ #define __QUEUE_H__ #include <iostream> #include <exception> #include <string> using namespace std; class QueueException : public std::exception { private: std::string msg; public: explicit QueueException(const char* message) : msg(message) { } explicit QueueException(const std::string& message) : msg(message) {} virtual ~QueueException() throw () {} virtual const char* what() const throw () { return msg.c_str(); } }; // -------- ------- ------ ----- Definition ----- ------ ------- -------- template <class T, int ARRAYSIZE = 50> class Queue { private: T data[ARRAYSIZE]; int front; int end; bool fullFlag = false; void toggleFull(); void copyAll(const Queue<T, ARRAYSIZE> &); public: Queue(); Queue(const Queue &); bool isEmpty(); bool isFull(); void enqueue(const T &); T dequeue(); T getFront(); Queue<T, ARRAYSIZE> &operator = (const Queue<T, ARRAYSIZE> &); }; // -------- ------- ------ ----- Implementation ----- ------ ------- -------- template<class T, int ARRAYSIZE> void Queue<T, ARRAYSIZE>::copyAll(const Queue<T, ARRAYSIZE> &newQueue) { this->front = newQueue.front; this->end = newQueue.end; this->fullFlag = newQueue.fullFlag; int i = newQueue.front; if ( isEmpty() ) return; while ( (i != newQueue.end + 1) and fullFlag ) { this->data[i] = newQueue.data[i]; i++; if ( ( end == ARRAYSIZE and front != 0 ) or end == ARRAYSIZE + 1 ) i = 0; } } template <class T, int ARRAYSIZE> void Queue<T, ARRAYSIZE>::toggleFull() { fullFlag = !fullFlag; } template <class T, int ARRAYSIZE> Queue<T, ARRAYSIZE>::Queue() { front = 0; end = ARRAYSIZE; } template <class T, int ARRAYSIZE> Queue<T, ARRAYSIZE>::Queue(const Queue &newQueue) { copyAll(newQueue); } template <class T, int ARRAYSIZE> bool Queue<T, ARRAYSIZE>::isEmpty() { if ( isFull() ) return false; return ( front == (end + 1) or ( front == 0 and end == ARRAYSIZE - 1 ) or ( front == 0 and end == ARRAYSIZE ) ); } template <class T, int ARRAYSIZE> bool Queue<T, ARRAYSIZE>::isFull() { return fullFlag; } template <class T, int ARRAYSIZE> void Queue<T, ARRAYSIZE>::enqueue(const T &element) { //-------- ------- ------ ----- Error Desbordamiento de datos ----- ------ ------- -------- if ( isFull() ) { throw QueueException("Desbordamiento de datos, enqueue"); } end++; // when the queue is created, end == ARRAYSIZE + 1 if ( ( end == ARRAYSIZE and front != 0 ) or end == ARRAYSIZE + 1 ) end = 0; data[end] = element; if ( front == end + 1 or ( front == 0 and end == ARRAYSIZE - 1 ) ) { toggleFull(); } } template <class T, int ARRAYSIZE> T Queue<T, ARRAYSIZE>::dequeue() { //-------- ------- ------ ----- Error Insuficiencia de datos ----- ------ ------- -------- if ( isEmpty() ) { throw QueueException("Insuficiencia de datos, dequeue"); } front++; if ( front == ARRAYSIZE) { front = 0; return data[ARRAYSIZE - 1]; } if (fullFlag) toggleFull(); return data[front - 1]; } template <class T, int ARRAYSIZE> T Queue<T, ARRAYSIZE>::getFront() { //-------- ------- ------ ----- Excepcion Insuficiencia de datos ----- ------ ------- -------- if ( isEmpty() ) { throw QueueException("Insuficiencia de datos, getFront"); } return data[front]; } template<class T, int ARRAYSIZE> Queue<T, ARRAYSIZE>& Queue<T, ARRAYSIZE>::operator = (const Queue<T, ARRAYSIZE> &newQueue) { copyAll(newQueue); return *this; } #endif // __QUEUE_H__
true
354d678250b8e7c1d84a192647b7ae4dcd33c82d
C++
kl456123/design_pattern
/decorator.cpp
UTF-8
1,240
3.0625
3
[]
no_license
class VisualComponent{ public: VisualComponent(); virtual void Draw(); virtual void Resize(); }; class Decorator:public VisualComponent{ public: Decorator(VisualComponent*); virtual void Draw(); virtual void Resize(); private: VisualComponent* component_; }; void Decorator::Draw(){ component_->Draw(); } void Decorator::Resize(){ component_->Resize(); } class BorderDecorator:public Decorator{ public: BorderDecorator(VisualComponent*,int borderWidth); virtual void Draw(); virtual void Resize(); private: void DrawBorder(int); private: int width_; }; void BorderDecorator::Draw(){ Decorator::Draw(); DrawBorder(width_); } class ScrollDecorator:public Decorator{ public: ScrollDecorator(VisualComponent*); }; class Window{ public: void SetContents(VisualComponent*); }; class TextView:public VisualComponent{}; void Window::SetContents(VisualComponent* contents){ } int main(){ Window* window = new Window; TextView* textview = new TextView; window->SetContents(textview); window->SetContents(new BorderDecorator(new ScrollDecorator(textview),1)); }
true
5cbc8baa8c05f2c761fae2192a591ca72bdf6ec5
C++
gepizar/CppND-System-Monitor
/src/processor.cpp
UTF-8
414
2.5625
3
[ "MIT" ]
permissive
#include "processor.h" #include "linux_parser.h" #include <iostream> // TODO: Return the aggregate CPU utilization float Processor::Utilization() { long total = LinuxParser::Jiffies(); long idle = LinuxParser::IdleJiffies(); long prevIdle = idle_; long prevTotal = total_; total_ = total; idle_ = idle; return 1.0 - (float)(idle - prevIdle) / (total - prevTotal); }
true